TypeScript
feat(web): F6 moves between workspace areas, and the sidebar is keyboard navigable (#25877)
Theo Browne2525252c9683
diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.tsindex d0221e9be0e..0fd24803692 100644--- a/apps/desktop/src/preview/Manager.ts+++ b/apps/desktop/src/preview/Manager.ts@@ -1505,7 +1505,16 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function);if (forwarded && host) {event.preventDefault();- if (!input.isAutoRepeat) host.send(MENU_ACTION_CHANNEL, forwarded.command);+ if (!input.isAutoRepeat) {+ if (+ forwarded.command === "workspace.focusNext" ||+ forwarded.command === "workspace.focusPrevious"+ ) {+ // DOM focus in the renderer cannot by itself release the guest's native keyboard focus.+ host.focus();+ }+ host.send(MENU_ACTION_CHANNEL, forwarded.command);+ }return;}if (isPreviewRefreshShortcut(input)) {diff --git a/apps/web/src/appInit.tsx b/apps/web/src/appInit.tsxindex ae7ad7c7df0..b9312858e33 100644--- a/apps/web/src/appInit.tsx+++ b/apps/web/src/appInit.tsx@@ -48,6 +48,7 @@ import { appAtomRegistry } from "./rpc/atomRegistry";import { primaryServerConfigAtom } from "./state/server";import { environmentShell } from "./state/shell";import { installChatRouteCommands } from "./shortcuts/chatRouteCommands";+import { startWorkspaceFocus } from "./lib/workspaceFocus";import { installCommandPaletteCommands } from "./shortcuts/commandPaletteCommands";import { registerOpenFavoriteEditorCommand } from "./components/chat/OpenInPickerShortcut";import { environmentThreadShells } from "./state/threads";@@ -191,6 +192,7 @@ export function startAppServices(): AppRouter {shellStateAtom: environmentShell.stateAtom,});startMainAppLocationTracking(router);+ startWorkspaceFocus(router);startBackgroundThreadAnnouncements(appAtomRegistry, router);startThreadVisitedMigration(appAtomRegistry);startSshPasswordPromptQueue();diff --git a/apps/web/src/commandPaletteStore.ts b/apps/web/src/commandPaletteStore.tsindex b708f3ad6e5..3fdd07383fd 100644--- a/apps/web/src/commandPaletteStore.ts+++ b/apps/web/src/commandPaletteStore.ts@@ -6,6 +6,7 @@ import {type CommandPaletteUiState,reduceCommandPaletteUiState,} from "./components/CommandPalette.logic";+import { getWorkspaceFocusRequestVersion } from "./lib/workspaceFocus";const INITIAL_STATE: CommandPaletteUiState = {open: false,@@ -16,8 +17,35 @@ const INITIAL_STATE: CommandPaletteUiState = {export const useCommandPaletteStore = create<CommandPaletteUiState>(() => INITIAL_STATE);+let returnFocus: { element: HTMLElement | null; href: string; focusRequest: number } | null = null;+export function dispatchCommandPalette(action: CommandPaletteUiAction): void {- useCommandPaletteStore.setState((state) => reduceCommandPaletteUiState(state, action), true);+ const state = useCommandPaletteStore.getState();+ const next = reduceCommandPaletteUiState(state, action);+ if (!state.open && next.open) {+ // The workspace turns inert before the popup mounts, which blurs the opener.+ returnFocus = {+ element: document.activeElement instanceof HTMLElement ? document.activeElement : null,+ href: window.location.href,+ focusRequest: getWorkspaceFocusRequestVersion(),+ };+ }+ useCommandPaletteStore.setState(next, true);+}++/**+ * Where the closing palette should return focus: `false` when a command navigated or asked+ * for workspace focus (the destination owns it), else the opener, or `true` for the default.+ */+export function getCommandPaletteReturnFocus(): HTMLElement | boolean {+ if (+ !returnFocus ||+ window.location.href !== returnFocus.href ||+ getWorkspaceFocusRequestVersion() !== returnFocus.focusRequest+ )+ return false;+ const { element } = returnFocus;+ return element?.isConnected && !element.matches(":disabled") ? element : true;}// The palette is only mounted on app-shell routes (not /pair, sign-in ordiff --git a/apps/web/src/components/AppSidebarLayout.tsx b/apps/web/src/components/AppSidebarLayout.tsxindex befbcf9f871..20abcf1e57a 100644--- a/apps/web/src/components/AppSidebarLayout.tsx+++ b/apps/web/src/components/AppSidebarLayout.tsx@@ -9,6 +9,7 @@ import {} from "react";import { useLocation, useRouter, type AnyRouter } from "@tanstack/react-router";+import { moveWorkspaceFocus, workspaceAreaProps } from "../lib/workspaceFocus";import { isCommandPaletteOpen } from "../commandPaletteBus";import { isElectron } from "../env";import {@@ -170,6 +171,33 @@ export function registerNavigationHistoryCommands(router: AnyRouter): () => void);}+// Capture phase, so F6 also leaves widgets that swallow keys, such as the terminal.+function registerWorkspaceFocusCommands(router: AnyRouter): () => void {+ const move = (direction: 1 | -1) => (event: KeyboardEvent) => {+ if (event.isComposing) return false;+ // Inside a dialog the move is refused, but the key is still consumed.+ event.preventDefault();+ event.stopPropagation();+ moveWorkspaceFocus(direction);+ };+ const disposers = [+ registerCommands(+ { "workspace.focusNext": move(1), "workspace.focusPrevious": move(-1) },+ {+ capture: true,+ when: (event) => !isKeybindingCaptureTarget(event),+ context: () => readRoutePanelsOpen(router),+ },+ ),+ // A focused desktop browser forwards the keys; its renderer focus is stale.+ registerMenuAction("workspace.focusNext", () => moveWorkspaceFocus(1, "panel")),+ registerMenuAction("workspace.focusPrevious", () => moveWorkspaceFocus(-1, "panel")),+ ];+ return () => {+ for (const dispose of disposers) dispose();+ };+}+// Escape leaves the pull requests page when no scope (a selection, a dialog,// a drag) claimed it, so it observes after every other scope.function registerPullRequestsEscapeCommand(router: AnyRouter): () => void {@@ -272,6 +300,7 @@ function registerAppShellCommands(router: AnyRouter, shellElement: Element): ()const disposers = [registerThreadUndoCommands(router, readSidebarVisible),registerNavigationHistoryCommands(router),+ registerWorkspaceFocusCommands(router),registerPullRequestsEscapeCommand(router),registerMenuAction("open-settings", () => {if (!/^\/settings(\/|$)/.test(router.state.location.pathname))@@ -373,6 +402,7 @@ function SidebarControl() {}export function AppSidebarLayout({ children }: { children: ReactNode }) {+ const sidebarArea = workspaceAreaProps("sidebar", 0, "Threads");const legacySidebarEnabled = useLegacySidebarEnabled();const [sidebarRouteReveal] = useState<SidebarRouteReveal>(() => ({observedKey: null,@@ -426,6 +456,7 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {side="left"collapsible="offcanvas"data-app-sidebar=""+ {...sidebarArea}role="navigation"aria-label="Threads"resizable={{diff --git a/apps/web/src/components/BranchToolbar.tsx b/apps/web/src/components/BranchToolbar.tsxindex 6f87daabd27..80edf40d795 100644--- a/apps/web/src/components/BranchToolbar.tsx+++ b/apps/web/src/components/BranchToolbar.tsx@@ -280,7 +280,11 @@ const RunContextSelector = memo(function RunContextSelector({isPanel && THREAD_DETAILS_PANEL_LOCKED_ROW_CLASS,)}onContextMenu={handleContextMenu}- aria-label={isPanel ? "Run context" : undefined}+ aria-label={+ isPanel+ ? `Run context: ${[autoEnvironmentLabel ?? activeEnvironment?.label, workspaceLabel].filter(Boolean).join(", ")}`+ : undefined+ }data-composer-context-control>{triggerContent}@@ -301,7 +305,11 @@ const RunContextSelector = memo(function RunContextSelector({}: undefined}- aria-label={isPanel ? "Run context" : undefined}+ aria-label={+ isPanel+ ? `Run context: ${[autoEnvironmentLabel ?? activeEnvironment?.label, workspaceLabel].filter(Boolean).join(", ")}`+ : undefined+ }data-composer-context-controldata-composer-shortcut={[showEnvironmentPicker && !envLocked ? "composer.host" : "",diff --git a/apps/web/src/components/ChatView.logic.browser.test.ts b/apps/web/src/components/ChatView.logic.browser.test.tsnew file mode 100644index 00000000000..e1c1f04a0c3--- /dev/null+++ b/apps/web/src/components/ChatView.logic.browser.test.ts@@ -0,0 +1,28 @@+import { expect, it } from "vite-plus/test";+import { userEvent } from "vite-plus/test/browser";+import { shouldRefocusComposerOnWindowFocus } from "./ChatView.logic";++it("keeps keyboard focus on a sidebar row on window return, but not a clicked row", async () => {+ const tree = document.createElement("div");+ tree.setAttribute("role", "tree");+ const row = (name: string, tabIndex: number) => {+ const element = document.createElement("div");+ element.setAttribute("role", "treeitem");+ element.tabIndex = tabIndex;+ element.textContent = name;+ tree.append(element);+ return element;+ };+ const clicked = row("Clicked thread", -1);+ const tabbed = row("Tabbed thread", 0);+ document.body.append(tree);+ using _tree = { [Symbol.dispose]: () => tree.remove() };++ await userEvent.click(clicked);+ expect(document.activeElement).toBe(clicked);+ expect(shouldRefocusComposerOnWindowFocus(document.activeElement)).toBe(true);++ await userEvent.tab();+ expect(document.activeElement).toBe(tabbed);+ expect(shouldRefocusComposerOnWindowFocus(document.activeElement)).toBe(false);+});diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.tsindex 24fe3c61451..0febddb13e6 100644--- a/apps/web/src/components/ChatView.logic.ts+++ b/apps/web/src/components/ChatView.logic.ts@@ -1166,6 +1166,10 @@ export function hasServerAcknowledgedLocalDispatch(input: {);}+// Returning to the window should land the caret in the composer, so the reader can type right+// away. The exceptions are places where focus is deliberate: another text field, a terminal in+// the drawer or the right panel, an open dialog, menu, or popup, or a region or sidebar row+// reached from the keyboard. A plain focused button or a clicked row yields to the composer.export function shouldRefocusComposerOnWindowFocus(activeElement:| (Pick<Element, "tagName" | "closest" | "getAttribute"> & { isContentEditable?: boolean })@@ -1185,7 +1189,7 @@ export function shouldRefocusComposerOnWindowFocus(}return (activeElement.closest(- '[role="dialog"], [role="alertdialog"], [role="application"], [data-slot$="-popup"], [data-terminal-owner]',+ '[data-workspace-area]:focus-visible, [role="treeitem"]:focus-visible, [role="dialog"], [role="alertdialog"], [role="application"], [role="menu"], [role="listbox"], [data-slot$="-popup"], [data-terminal-owner]',) === null);}diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex c9ce40121de..7aaa2af1aa1 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -1,3 +1,4 @@+import { workspaceAreaProps } from "../lib/workspaceFocus";import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";import { queuedRunEditBlockedReason } from "@t3tools/client-runtime/queued-run-edit";import { ScrollToEndButton, WorkspaceFileDropOverlay } from "./chat/TimelineOverlays";@@ -707,6 +708,8 @@ export default function ChatView(props: ChatViewProps) {const legendListRef = useRef<LegendListRef | null>(null);const getTimelineScrollableNode = () => legendListRef.current?.getScrollableNode() ?? null;const getTimelineScrollableNodeStable = useStableCallback(getTimelineScrollableNode);+ const conversationArea = workspaceAreaProps("conversation", 1, "Conversation");+ const composerArea = workspaceAreaProps("composer", 2, "Message input");const [composerOverlayElement, setComposerOverlayElement] = useState<HTMLDivElement | null>(null);const [composerTimelineInset, setComposerTimelineInset] = useState(0);const composerTimelineInsetRef = useRef(0);@@ -3173,6 +3176,7 @@ export default function ChatView(props: ChatViewProps) {)}data-chat-column-maximized-away={rightPanelMaximized ? "true" : "false"}data-chat-column+ inert={rightPanelMaximized}><headerref={threadPanelPopoverAnchorRef}@@ -3253,7 +3257,10 @@ export default function ChatView(props: ChatViewProps) {setThreadError={setThreadError}setThreadErrorBannerDismissTick={setThreadErrorBannerDismissTick}/>- <div className="relative flex min-h-0 flex-1 flex-col bg-background">+ <div+ {...conversationArea}+ className="relative flex min-h-0 flex-1 flex-col bg-background"+ ><ThreadTimelinethreadDetailRef={routeThreadDetailRef}entriesInput={timelineEntriesInput}@@ -3360,6 +3367,7 @@ export default function ChatView(props: ChatViewProps) {</div><div+ {...composerArea}ref={(overlay: HTMLDivElement | null) => {setComposerOverlayElement(overlay);attachFollowComposerOverlay(overlay);diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsxindex 378a3e3d058..1adb6bff0da 100644--- a/apps/web/src/components/CommandPalette.tsx+++ b/apps/web/src/components/CommandPalette.tsx@@ -67,6 +67,7 @@ import {PaletteIcon,RotateCcwIcon,SettingsIcon,+ MonitorIcon,SquarePenIcon,TextSearchIcon,UserPlusIcon,@@ -89,6 +90,10 @@ import { useDesktopLocalBootstraps } from "../connection/useDesktopLocalBootstraimport { useHandleNewThread } from "../hooks/useHandleNewThread";import { useOpenPanelPullRequestUrl } from "../hooks/useOpenPanelPullRequestUrl";import { copyThreadReference } from "../lib/copyThreadReference";+import {+ queueWorkspaceFocusFromPalette,+ restoreWorkspaceFocusFromPalette,+} from "../lib/workspaceFocus";import {composerPromptLink,copyPromptLink,@@ -132,6 +137,7 @@ import {} from "../lib/projectPaths";import {dispatchCommandPalette,+ getCommandPaletteReturnFocus,useCommandPaletteMount,useCommandPaletteStore,} from "../commandPaletteStore";@@ -326,8 +332,12 @@ function CommandPaletteDialog(props: {data-palette-mode={props.mode}data-testid="command-palette"finalFocus={() => {+ if (restoreWorkspaceFocusFromPalette()) return false;+ const returnFocus = getCommandPaletteReturnFocus();+ if (returnFocus === false) return false;const composer = composerHandleRef?.current;- if (!composer) return true;+ // Behind the Settings modal the composer is inert and cannot take focus.+ if (!composer || document.querySelector("[data-app-modal]")) return returnFocus;composer.focusAtEnd();return false;}}@@ -1507,6 +1517,21 @@ function OpenCommandPaletteDialog(props: {},});+ for (const direction of [1, -1] as const) {+ const title = direction === 1 ? "Focus Next Workspace Area" : "Focus Previous Workspace Area";+ actionItems.push({+ kind: "action",+ value: `action:workspace-focus:${direction}`,+ title,+ searchTerms: [title, "accessibility", "navigation", "focus", "F6"],+ icon: <MonitorIcon className={ITEM_ICON_CLASS} />,+ shortcutCommand: direction === 1 ? "workspace.focusNext" : "workspace.focusPrevious",+ run: async () => {+ queueWorkspaceFocusFromPalette(direction);+ },+ });+ }+actionItems.push({kind: "action",value: "action:settings",diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsxindex 02275c536c2..0de2d69fff0 100644--- a/apps/web/src/components/DiffPanel.tsx+++ b/apps/web/src/components/DiffPanel.tsx@@ -655,6 +655,7 @@ export default function DiffPanel({render={<Button size="xs" variant="secondary" />}className="max-w-full"aria-label={`Diff scope: ${selectedScopeLabel}`}+ data-workspace-focus-default><span className="truncate">{selectedScopeLabel}</span><ChevronDownIcon className="size-3.5 shrink-0 opacity-70" />diff --git a/apps/web/src/components/LegacySidebar.tsx b/apps/web/src/components/LegacySidebar.tsxindex ea41576fc62..e229e8001ba 100644--- a/apps/web/src/components/LegacySidebar.tsx+++ b/apps/web/src/components/LegacySidebar.tsx@@ -1,3 +1,4 @@+import { attachSidebarTree, SIDEBAR_TREE_PROPS } from "../lib/sidebarTree";import { useSupportsMultiplePullRequests } from "~/hooks/useSupportsMultiplePullRequests";import { resolveThreadCurrentPullRequestLink } from "@t3tools/client-runtime/thread-pull-requests";import { Spinner } from "~/components/ui/spinner";@@ -337,6 +338,7 @@ function buildThreadJumpLabelMap(input: {}interface SidebarThreadRowProps {+ navigationParent?: string | undefined;thread: SidebarThreadSummary;orderedProjectThreadKeys: readonly string[];isActive: boolean;@@ -542,6 +544,16 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowPstartThreadRename(threadKey, thread.title);};const handleRowKeyDown = (event: React.KeyboardEvent) => {+ if (event.target !== event.currentTarget) return;+ if (+ event.key === "F2" &&+ renamingThreadKey !== threadKey &&+ readEnvironmentScope(thread.environmentId, AuthOrchestrationOperateScope)+ ) {+ event.preventDefault();+ startThreadRename(threadKey, thread.title);+ return;+ }if (event.key !== "Enter" && event.key !== " ") return;event.preventDefault();navigateToThread(threadRef);@@ -678,8 +690,11 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP><divref={isActive ? (node) => revealActiveRow(node, threadKey) : undefined}- role="button"- tabIndex={0}+ role="treeitem"+ tabIndex={-1}+ data-sidebar-row={threadKey}+ data-sidebar-parent={props.navigationParent}+ aria-current={isActive ? "page" : undefined}data-active={isActive}data-slot="sidebar-menu-sub-button"data-sidebar="menu-sub-button"@@ -1002,6 +1017,7 @@ const SidebarProjectThreadList = memo(function SidebarProjectThreadList(return (<SidebarMenuSub+ role="presentation"ref={attachThreadListAutoAnimateRef}className="mx-0.5 my-0 w-full translate-x-0 overflow-hidden empty:hidden sm:mx-1">@@ -1022,6 +1038,7 @@ const SidebarProjectThreadList = memo(function SidebarProjectThreadList(<SidebarThreadRowkey={threadKey}thread={thread}+ navigationParent={projectExpanded ? `project:${projectKey}` : undefined}orderedProjectThreadKeys={orderedProjectThreadKeys}isActive={activeRouteThreadKey === threadKey}openPullRequestsInRightPanel={openPullRequestsInRightPanel}@@ -1054,6 +1071,10 @@ const SidebarProjectThreadList = memo(function SidebarProjectThreadList(<SidebarMenuSubItem className="w-full"><SidebarMenuSubButtonrender={showMoreButtonRender}+ role="treeitem"+ tabIndex={-1}+ data-sidebar-row={`project:${projectKey}:more`}+ data-sidebar-parent={`project:${projectKey}`}data-thread-selection-safesize="sm"onClick={() => {@@ -1071,6 +1092,10 @@ const SidebarProjectThreadList = memo(function SidebarProjectThreadList(<SidebarMenuSubItem className="w-full"><SidebarMenuSubButtonrender={showLessButtonRender}+ role="treeitem"+ tabIndex={-1}+ data-sidebar-row={`project:${projectKey}:less`}+ data-sidebar-parent={`project:${projectKey}`}data-thread-selection-safesize="sm"onClick={() => {@@ -1400,9 +1425,12 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjecconst handleProjectButtonClick = (event: React.MouseEvent<HTMLButtonElement>) => {if (suppressProjectClickForContextMenuRef.current) {suppressProjectClickForContextMenuRef.current = false;- event.preventDefault();- event.stopPropagation();- return;+ // A keyboard-made click (detail 0) never follows a context menu.+ if (event.detail !== 0) {+ event.preventDefault();+ event.stopPropagation();+ return;+ }}if (dragInProgressRef.current) {event.preventDefault();@@ -2301,6 +2329,11 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjecclassName={isManualProjectSorting ? "cursor-grab active:cursor-grabbing" : undefined}{...(isManualProjectSorting && dragHandleProps ? dragHandleProps.attributes : {})}{...(isManualProjectSorting && dragHandleProps ? dragHandleProps.listeners : {})}+ role="treeitem"+ tabIndex={-1}+ data-sidebar-row={`project:${project.projectKey}`}+ aria-expanded={projectExpanded}+ aria-label={project.displayName}onPointerDownCapture={handleProjectButtonPointerDownCapture}onClick={handleProjectButtonClick}onKeyDown={handleProjectButtonKeyDown}@@ -2380,6 +2413,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec<buttontype="button"aria-label={`Create new thread in ${project.displayName}`}+ data-sidebar-action-for={`project:${project.projectKey}`}data-testid="new-thread-button"className={SIDEBAR_ICON_ACTION_BUTTON_CLASS}onClick={handleCreateThreadClick}@@ -2878,6 +2912,14 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(projectsLength,} = props;+ const attachTreeRef = (node: HTMLUListElement | null) => {+ attachProjectListAutoAnimateRef(node);+ const dispose = attachSidebarTree(node);+ return () => {+ dispose?.();+ attachProjectListAutoAnimateRef(null);+ };+ };const handleProjectSortOrderChange = (sortOrder: SidebarProjectSortOrder) => {updateClientSettings({ sidebarProjectSortOrder: sortOrder });};@@ -2970,7 +3012,7 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(onDragEnd={handleProjectDragEnd}onDragCancel={handleProjectDragCancel}>- <SidebarMenu>+ <SidebarMenu {...SIDEBAR_TREE_PROPS} ref={attachSidebarTree}><SortableContext items={sortedProjectKeys} strategy={verticalListSortingStrategy}>{sortedProjects.map((project) => (<SortableProjectItem key={project.projectKey} projectId={project.projectKey}>@@ -3006,7 +3048,7 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(</SidebarMenu></DndContext>) : (- <SidebarMenu ref={attachProjectListAutoAnimateRef}>+ <SidebarMenu {...SIDEBAR_TREE_PROPS} ref={attachTreeRef}>{sortedProjects.map((project) => (<SidebarProjectListRowkey={project.projectKey}diff --git a/apps/web/src/components/NoProjectsHero.tsx b/apps/web/src/components/NoProjectsHero.tsxindex fbe96b5f41c..e6ebe6536c5 100644--- a/apps/web/src/components/NoProjectsHero.tsx+++ b/apps/web/src/components/NoProjectsHero.tsx@@ -1,3 +1,4 @@+import { workspaceAreaProps } from "../lib/workspaceFocus";import { MessageSquareDashedIcon, PlusIcon } from "lucide-react";import { openCommandPalette } from "../commandPaletteBus";@@ -10,12 +11,17 @@ import { SidebarInset } from "./ui/sidebar";import { WorkspacePageHeader } from "./WorkspacePageHeader";export function NoProjectsHero() {+ const contentArea = workspaceAreaProps("home", 1, "Home");const primaryEnvironmentId = usePrimaryEnvironmentId();const { scratchEnvironmentId, startScratchThread } = useScratchProject();const scratchTargetEnvironmentId = scratchEnvironmentId(primaryEnvironmentId);return (- <SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none">+ <SidebarInset+ {...contentArea}+ role="main"+ className="h-dvh min-h-0 overflow-hidden overscroll-y-none"+ ><div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-x-hidden bg-background">{/* The desktop window only moves where CSS opts in, so keep a titlebar strip. */}{isElectron ? <WorkspacePageHeader electron /> : null}diff --git a/apps/web/src/components/ReopenClosedViewShortcut.tsx b/apps/web/src/components/ReopenClosedViewShortcut.tsxindex f409ce48bfe..cdccb396a37 100644--- a/apps/web/src/components/ReopenClosedViewShortcut.tsx+++ b/apps/web/src/components/ReopenClosedViewShortcut.tsx@@ -44,6 +44,8 @@ import {import { toastManager } from "./ui/toast";const PREVIEW_FORWARDED_LAYOUT_COMMANDS = [+ "workspace.focusNext",+ "workspace.focusPrevious","sidebar.toggle","rightPanel.toggle","rightPanel.toggleMaximized",diff --git a/apps/web/src/components/RightPanelTabs.tsx b/apps/web/src/components/RightPanelTabs.tsxindex b833eec279d..4d7cfbcbc7d 100644--- a/apps/web/src/components/RightPanelTabs.tsx+++ b/apps/web/src/components/RightPanelTabs.tsx@@ -436,7 +436,7 @@ function RightPanelEmptyState(props: {return (<div- ref={focusOnMount}+ data-workspace-focus-defaulttabIndex={0}onKeyDown={handleKeyDown}aria-label="Open a surface"@@ -748,10 +748,6 @@ function PullRequestSurfaceIcon({return <presentation.Icon className={cn("size-3 shrink-0", presentation.toneClassName)} />;}-function focusOnMount(node: HTMLDivElement | null) {- node?.focus();-}-function SortableTabList(props: {surfaces: readonly RightPanelSurface[];onMove: ((surfaceId: string, toIndex: number) => void) | undefined;@@ -945,6 +941,7 @@ function RightPanelTab(}export function RightPanelTabs(props: RightPanelTabsProps) {+ const focusedSurface = props.surfaces.find((surface) => surface.id === props.activeSurfaceId);const ownsDesktopTitleBar = isElectron && props.mode === "inline";const browserProfiles = useBrowserDefaults().profiles;const { resolvedTheme } = useTheme();@@ -1226,6 +1223,13 @@ export function RightPanelTabs(props: RightPanelTabsProps) {return (<PreviewPanelShell+ workspaceArea+ workspaceFocusKey={`panel:${props.environmentId}:${props.activeSurfaceId ?? "empty"}`}+ workspaceLabel={+ focusedSurface+ ? `Workspace panel: ${surfaceTitle(focusedSurface, props.previewSessions, props.terminalLabelsById)}`+ : "Workspace panel"+ }mode={props.mode}{...(props.maximized !== undefined ? { maximized: props.maximized } : {})}{...(props.open !== undefined ? { open: props.open } : {})}diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsxindex 2677c16f259..72b8b0acbf6 100644--- a/apps/web/src/components/Sidebar.tsx+++ b/apps/web/src/components/Sidebar.tsx@@ -1,3 +1,4 @@+import { attachSidebarTree, SIDEBAR_TREE_PROPS } from "../lib/sidebarTree";import { type EnvironmentId, type ScopedProjectRef } from "@t3tools/contracts";import type { EnvironmentServerConfig } from "@t3tools/client-runtime/connection";import { ThreadContextDragGhost } from "./chat/ThreadContextDragGhost";@@ -1540,6 +1541,15 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve};};+ const attachTreeRef = (node: HTMLUListElement) => {+ const detachMotion = attachListMotionRef(node);+ const detachTree = attachSidebarTree(node);+ return () => {+ detachTree?.();+ detachMotion();+ };+ };+const isContextDrag = dragState?.contextDrag === true || dragState?.activeSection === "working";const dragTargetSection = isContextDrag ? null : (dragState?.targetSection ?? null);const finishThreadDrag = (started: boolean) => {@@ -3034,10 +3044,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve><SortableContext items={sortableIds} strategy={sidebarSortingStrategy}><ul- ref={attachListMotionRef}- // Presentation flattens VoiceOver's list interaction boundary while preserving descendant- // controls.- role="presentation"+ {...SIDEBAR_TREE_PROPS}+ ref={attachTreeRef}className={cn("relative flex flex-col gap-px",sidebarListItems.length > 0 && "flex-1",@@ -3067,6 +3075,13 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve}thread={thread}variant={rowVariant}+ navigationParent={+ section === "working" ||+ section === "snoozed" ||+ section === "settled"+ ? `shelf:${section}`+ : undefined+ }variantAction={section === "snoozed"? "unsnooze"@@ -3295,6 +3310,10 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve<li className="list-none"><buttontype="button"+ role="treeitem"+ tabIndex={-1}+ data-sidebar-row="settled:more"+ data-sidebar-parent="shelf:settled"disabled={olderSettledShelf.loading}onClick={() => {olderSettledShelf.retry();diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsxindex 6bb6dc551c1..7c0a3afa4dd 100644--- a/apps/web/src/components/ThreadTerminalDrawer.tsx+++ b/apps/web/src/components/ThreadTerminalDrawer.tsx@@ -1,3 +1,4 @@+import { workspaceAreaProps } from "../lib/workspaceFocus";import { useAtomMount, useAtomValue } from "@effect/atom-react";import {isAtomCommandInterrupted,@@ -686,6 +687,7 @@ function TerminalSessionViewport({terminal.setTheme(terminalThemeFromApp(mount));setupTerminal = terminal;terminalRef.current = terminal;+ terminal.input.setAttribute("data-workspace-focus-default", "");terminal.input.readOnly = !hasTerminalWriteAccess();// Reapply font settings hydrated during loading, when terminalRef was null.const currentFont = terminalFontRef.current;@@ -1438,6 +1440,7 @@ export default function ThreadTerminalDrawer({terminalLaunchLocationsById,}: ThreadTerminalDrawerProps) {const canOperateTerminal = useEnvironmentScope(threadRef.environmentId, AuthTerminalOperateScope);+ const terminalArea = workspaceAreaProps("terminal", 5, "Terminal");const isPanel = mode === "panel";const [advancedTypography] = useLocalStorage(TYPOGRAPHY_ADVANCED_STORAGE_KEY,@@ -1722,6 +1725,7 @@ export default function ThreadTerminalDrawer({return (<asideref={drawerRef}+ {...(!isPanel && visible ? terminalArea : {})}data-thread-terminal-drawerdata-terminal-owner={isPanel ? "right-panel" : "drawer"}className={cn(@@ -1758,6 +1762,7 @@ export default function ThreadTerminalDrawer({return (<asideref={drawerRef}+ {...(!isPanel && visible ? terminalArea : {})}data-thread-terminal-drawerdata-terminal-owner={isPanel ? "right-panel" : "drawer"}className={cn(diff --git a/apps/web/src/components/chat/QueuedRunsControl.browser.test.tsx b/apps/web/src/components/chat/QueuedRunsControl.browser.test.tsxindex 6a3a5d98131..7e25e84135b 100644--- a/apps/web/src/components/chat/QueuedRunsControl.browser.test.tsx+++ b/apps/web/src/components/chat/QueuedRunsControl.browser.test.tsx@@ -40,6 +40,7 @@ vi.mock(import("../../assets/assetUrls"), async (importOriginal) => ({resources.map((resource) => `https://assets.test/${resource.attachmentId}`)) as never,}));+import "~/index.css";import { render as renderUi } from "../../../test/render";import { QueuedRunsControl } from "./QueuedRunsControl";@@ -172,3 +173,33 @@ it("shows who sent a queued message and folds automation and agent prompts", asyawait expect.element(page.getByText("Sent by T3 Code")).toBeVisible();await expect.element(page.getByText("Continue where you left off.")).toBeVisible();});++it("stays inside the timeline scroller instead of growing the chat column", async () => {+ setup();+ state.projection = { projection: { messages: [] } };+ state.workflow = {+ activeRun: { id: "run:active" },+ canPromoteToSteer: true,+ queuedRuns: [+ {+ run: { id: "run:queued", userMessageId: "message:queued" },+ text: "Later",+ attachments: [],+ },+ ],+ };+ // Mirrors ChatView: a scrollable column, a positioned wrapper, then a non-positioned scroller.+ await using screen = await renderUi(+ <div data-testid="column" style={{ height: 200, overflowY: "auto" }}>+ <div style={{ position: "relative", height: "100%" }}>+ <div style={{ height: "100%", overflowY: "auto" }}>+ <div style={{ height: 1000 }} />+ <QueuedRunsControl {...baseProps} />+ </div>+ </div>+ </div>,+ );+ await expect.element(page.getByText("Later", { exact: true })).toBeInTheDocument();+ const column = screen.getByTestId("column").element();+ expect(column.scrollHeight).toBe(column.clientHeight);+});diff --git a/apps/web/src/components/chat/QueuedRunsControl.tsx b/apps/web/src/components/chat/QueuedRunsControl.tsxindex 850c38df79f..866612bc110 100644--- a/apps/web/src/components/chat/QueuedRunsControl.tsx+++ b/apps/web/src/components/chat/QueuedRunsControl.tsx@@ -229,7 +229,8 @@ export function QueuedRunsControl({<sectionaria-label={`${items.length} queued message${items.length === 1 ? "" : "s"}`}data-thread-queue="true"- className="mx-auto flex w-full max-w-(--chat-content-max-width) flex-col gap-2 pb-4"+ // Anchors the sr-only live region; unanchored, it escapes the timeline scroller and makes the chat column scroll.+ className="relative mx-auto flex w-full max-w-(--chat-content-max-width) flex-col gap-2 pb-4"><span className="sr-only" aria-live="polite">{items.length} queueddiff --git a/apps/web/src/components/chat/ThreadDetailsCard.tsx b/apps/web/src/components/chat/ThreadDetailsCard.tsxindex bd4fde37a13..4add56b80eb 100644--- a/apps/web/src/components/chat/ThreadDetailsCard.tsx+++ b/apps/web/src/components/chat/ThreadDetailsCard.tsx@@ -1,3 +1,4 @@+import { workspaceAreaProps } from "../../lib/workspaceFocus";import { useLayoutEffect, useState, type ReactNode, type RefObject } from "react";import type { ScopedThreadRef } from "@t3tools/contracts";import { ScrollArea } from "../ui/scroll-area";@@ -10,6 +11,7 @@ import {resolveThreadDetailsCardDensity,} from "./threadDetailsCardLayout";import { observeResize } from "../../lib/observeResize";+import { requestWorkspaceFocus } from "../../lib/workspaceFocus";export function ThreadDetailsCard({threadRef,@@ -22,6 +24,7 @@ export function ThreadDetailsCard({handle: ReturnType<typeof PopoverCreateHandle>;children: (density: "full" | "compact" | "essential") => ReactNode;}) {+ const detailsArea = workspaceAreaProps("details", 3, "Thread details");const canvas = useChatCanvas();const preferredPlacement = canvas?.preferredDetailsCard ?? null;const placement = canvas?.detailsCardPlacement ?? null;@@ -133,7 +136,8 @@ export function ThreadDetailsCard({>{placement && inlineOpen ? (<aside- aria-label="Thread details"+ {...detailsArea}+ data-workspace-focus-key={`details:${threadRef.environmentId}:${threadRef.threadId}`}// Skip the return transition to avoid overlapping the rising preview.className={cn("absolute z-20",@@ -155,6 +159,13 @@ export function ThreadDetailsCard({mounted, because its exit animation never finishes. Staying in the treelets it close cleanly when the card switches inline. */}<PopoverPopup+ {...(mode === "popover" ? detailsArea : {})}+ role="dialog"+ data-workspace-focus-key={`details:${threadRef.environmentId}:${threadRef.threadId}`}+ initialFocus={() => {+ requestWorkspaceFocus({ area: "details" });+ return false;+ }}anchor={anchor}align="end"// Account for the find panel's 8px card padding.diff --git a/apps/web/src/components/chat/useRightPanelActions.ts b/apps/web/src/components/chat/useRightPanelActions.tsindex 0e571b3c4a9..ac79b0853bf 100644--- a/apps/web/src/components/chat/useRightPanelActions.ts+++ b/apps/web/src/components/chat/useRightPanelActions.ts@@ -15,9 +15,11 @@ import { useDiffPanelStore } from "../../diffPanelStore";import { type ThreadPanelPresentation } from "../../rightPanelLayout";import {selectActiveRightPanel,+ selectThreadPanelOpen,type RightPanelSurface,useRightPanelStore,} from "../../rightPanelStore";+import { requestWorkspaceContentFocus, requestWorkspaceFocus } from "../../lib/workspaceFocus";import { setActivePreviewTab } from "../../previewStateStore";import { BrowserSettingsReadError } from "../../browser/openFileInPreview";import { addBrowserSurface } from "../preview/addBrowserSurface";@@ -224,11 +226,23 @@ export function useRightPanelActions(input: RightPanelActionsInput) {const toggleRightPanelStable = useStableCallback(toggleRightPanel);const toggleThreadPanel = () => {if (!activeThreadRef) return;- useRightPanelStore.getState().toggleThreadPanel(activeThreadRef, threadPanelPresentation);+ const store = useRightPanelStore.getState();+ if (threadPanelPresentation === "inline") {+ const open = selectThreadPanelOpen(+ store.threadPanelVisibilityByThreadKey,+ activeThreadRef,+ "inline",+ );+ if (!open) requestWorkspaceFocus({ area: "details" });+ else if (document.activeElement?.closest('[data-workspace-area="details"]'))+ requestWorkspaceContentFocus();+ }+ store.toggleThreadPanel(activeThreadRef, threadPanelPresentation);};const toggleThreadPanelStable = useStableCallback(toggleThreadPanel);const toggleRightPanelMaximized = () => {if (!canMaximizeRightPanel || !activeThreadRef) return;+ if (!rightPanelMaximized) requestWorkspaceFocus({ area: "panel" });useRightPanelStore.getState().setMaximized(activeThreadRef, !rightPanelMaximized);};const toggleRightPanelMaximizedStable = useStableCallback(toggleRightPanelMaximized);diff --git a/apps/web/src/components/files/FileBrowserPanel.tsx b/apps/web/src/components/files/FileBrowserPanel.tsxindex 7a6fa3a9405..147ed7614c7 100644--- a/apps/web/src/components/files/FileBrowserPanel.tsx+++ b/apps/web/src/components/files/FileBrowserPanel.tsx@@ -90,6 +90,7 @@ function FileSearchField(props: {value={props.value}aria-label={props.ariaLabel}placeholder="Search files"+ data-workspace-focus-defaultspellCheck={false}onChange={(event) => props.onValueChange(event.target.value)}onKeyDown={(event) => {diff --git a/apps/web/src/components/preview/PreviewChromeRow.tsx b/apps/web/src/components/preview/PreviewChromeRow.tsxindex 1fb95a94f3f..d8202a4064e 100644--- a/apps/web/src/components/preview/PreviewChromeRow.tsx+++ b/apps/web/src/components/preview/PreviewChromeRow.tsx@@ -175,6 +175,8 @@ export function PreviewChromeRow({}}}placeholder="Search or enter URL"+ aria-label="Search or enter URL"+ data-workspace-focus-defaultspellCheck={false}disabled={inputDisabled}data-preview-url-inputdiff --git a/apps/web/src/components/preview/PreviewPanelShell.tsx b/apps/web/src/components/preview/PreviewPanelShell.tsxindex 51e74bd605a..2a3783cab8b 100644--- a/apps/web/src/components/preview/PreviewPanelShell.tsx+++ b/apps/web/src/components/preview/PreviewPanelShell.tsx@@ -4,6 +4,7 @@ import {usePreviewPanelInlineSize,} from "~/hooks/usePreviewPanelInlineSize";import { RESIZABLE_WIDTH_PROPERTY } from "~/hooks/useResizableWidth";+import { workspaceAreaProps } from "../../lib/workspaceFocus";import { cn } from "~/lib/utils";import { RightPanelResizeHandle } from "./RightPanelResizeHandle";@@ -11,6 +12,9 @@ import { RightPanelResizeHandle } from "./RightPanelResizeHandle";export type PreviewPanelMode = "inline" | "sheet" | "sidebar" | "embedded";interface PreviewPanelShellProps {+ workspaceArea?: boolean;+ workspaceFocusKey?: string;+ workspaceLabel?: string;mode: PreviewPanelMode;maximized?: boolean;inlineSize?: PreviewPanelInlineSize;@@ -41,6 +45,7 @@ function ResizablePreviewPanelShell(props: PreviewPanelShellProps) {function PreviewPanelShellFrame(props: PreviewPanelShellProps & { inlineSize: PreviewPanelInlineSize },) {+ const panelArea = workspaceAreaProps("panel", 4, props.workspaceLabel ?? "Workspace panel");const isInline = props.mode === "inline";const collapsible = isInline && props.open !== undefined;const open = props.open ?? true;@@ -112,6 +117,9 @@ function PreviewPanelShellFrame(return (<divref={attachHost}+ {...(props.workspaceArea ? panelArea : {})}+ data-workspace-focus-key={props.workspaceFocusKey}+ data-workspace-unavailable={collapsible && !open ? "true" : undefined}className={cn("relative flex h-full min-h-0 min-w-0 max-w-full flex-col self-stretch bg-background",isInlinediff --git a/apps/web/src/components/pullRequest/PullRequestsColumn.tsx b/apps/web/src/components/pullRequest/PullRequestsColumn.tsxindex 93562d834d2..de66666f928 100644--- a/apps/web/src/components/pullRequest/PullRequestsColumn.tsx+++ b/apps/web/src/components/pullRequest/PullRequestsColumn.tsx@@ -13,6 +13,7 @@ import {} from "../WorkspaceBreadcrumb";import { WorkspacePageContainer } from "../WorkspacePageContainer";import { WorkspacePageHeader } from "../WorkspacePageHeader";+import { workspaceAreaProps } from "../../lib/workspaceFocus";import { PullRequestCompactFilterMenu } from "./PullRequestCompactFilterMenu";import type { PullRequestFilterOption } from "./PullRequestListFilters";import { INVOLVEMENT_TABS, STATE_TABS } from "./pullRequestListOptions";@@ -108,6 +109,7 @@ export function PullRequestsColumn({listBody: ReactNode;scrollRef: RefObject<HTMLDivElement | null>;}) {+ const contentArea = workspaceAreaProps("pull-requests", 1, "Pull requests");const markerRef = useRef<HTMLDivElement | null>(null);const [condensed, setCondensed] = useState(false);// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- IntersectionObserver on the scroll marker condenses the topbar@@ -158,6 +160,8 @@ export function PullRequestsColumn({return (<div+ {...contentArea}+ inert={maximizedAway}className={cn("@container/pr-list flex min-h-0 min-w-0 flex-col overflow-x-hidden bg-background",maximizedAway ? "w-0 flex-none" : "flex-1",diff --git a/apps/web/src/components/settings/KeybindingsSettings.logic.ts b/apps/web/src/components/settings/KeybindingsSettings.logic.tsindex 457fe3fed31..1e75a023438 100644--- a/apps/web/src/components/settings/KeybindingsSettings.logic.ts+++ b/apps/web/src/components/settings/KeybindingsSettings.logic.ts@@ -357,6 +357,8 @@ export function buildKeybindingCommandOptions(}export function commandLabel(command: KeybindingCommand): string {+ if (command === "workspace.focusNext") return "Focus Next Workspace Area";+ if (command === "workspace.focusPrevious") return "Focus Previous Workspace Area";if (command === "composer.sendAlternate") return "Composer: Opposite Queue or Steer Action";if (command === "composer.sendBackground") return "Composer: Start in Background";if (command === "composer.sendAndNewThread") return "Composer: Send and Start New Thread";diff --git a/apps/web/src/components/settings/SettingsSidebarNav.tsx b/apps/web/src/components/settings/SettingsSidebarNav.tsxindex 5ece7c51cea..b58f56a1623 100644--- a/apps/web/src/components/settings/SettingsSidebarNav.tsx+++ b/apps/web/src/components/settings/SettingsSidebarNav.tsx@@ -56,6 +56,8 @@ import {} from "./settingsSearch";import { useAvailableSettingsSearchItems } from "./useAvailableSettingsSearchItems";import { validateSettingsScopeSearch } from "./settingsScope";+import { useSettingsSectionNavigation } from "./useSettingsSectionNavigation";+import { workspaceAreaProps } from "../../lib/workspaceFocus";const SnapShotIcon = createLucideIcon("snap-shot", [[@@ -123,11 +125,18 @@ function SettingsSectionIcon({ to }: { to: SettingsPath }) {}export function SettingsSidebarNav({ pathname }: { pathname: string }) {+ const navArea = workspaceAreaProps("settings-nav", 0, "Settings sections");const navigate = useNavigate();const currentHash = useLocation({ select: (location) => location.hash });const currentSearch = useLocation({ select: (location) => location.search });const scopeSearch = validateSettingsScopeSearch(currentSearch);const activePath = SETTINGS_DETAIL_PAGE_PARENTS[pathname] ?? pathname;+ const navPaths = SETTINGS_NAV_GROUPS.flatMap((group) => group.paths);+ const sectionNavigation = useSettingsSectionNavigation(+ navPaths.find((to) => activePath === to || activePath.startsWith(`${to}/`)) ??+ navPaths[0] ??+ "",+ );const searchInputRef = useRef<HTMLInputElement>(null);const [query, setQuery] = useState("");// Below md the nav is an icon rail; searching expands it over the page.@@ -242,7 +251,8 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) {return (<nav- aria-label="Settings sections"+ {...navArea}+ role="navigation"className={cn("flex w-60 shrink-0 flex-col border-e bg-sidebar text-sidebar-foreground max-md:w-14",compactSearchOpen &&@@ -362,46 +372,60 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) {</SidebarMenuItem></SidebarMenu>)}- {SETTINGS_NAV_GROUPS.map((group, index) => (- <div- key={group.heading ?? index}- role="group"- aria-label={group.heading ?? undefined}- className="flex flex-col gap-1 max-md:border-t max-md:border-sidebar-border max-md:pt-4 max-md:first:border-t-0 max-md:first:pt-0"- >- {group.heading ? (- <h3- className={cn(- "px-2 text-xs font-medium text-sidebar-muted-foreground/80",- !compactSearchOpen && "max-md:hidden",- )}- >- {group.heading}- </h3>- ) : null}- <SidebarMenu>- {group.paths.map((to) => {- const Icon = SETTINGS_SECTION_ICONS[to];- const isActive = activePath === to || activePath.startsWith(`${to}/`);- return (- <SidebarMenuItem key={to}>- <SidebarMenuButton- isActive={isActive}- onClick={() => handleSectionClick(to)}- >- <Icon />- <span- className={cn("truncate", !compactSearchOpen && "max-md:sr-only")}+ <div+ {...sectionNavigation.containerProps}+ role="tree"+ aria-label="Settings sections"+ className="flex flex-col gap-4"+ >+ {SETTINGS_NAV_GROUPS.map((group, index) => (+ <div+ key={group.heading ?? index}+ role="group"+ aria-label={group.heading ?? undefined}+ className="flex flex-col gap-1 max-md:border-t max-md:border-sidebar-border max-md:pt-4 max-md:first:border-t-0 max-md:first:pt-0"+ >+ {group.heading ? (+ // The group carries this label; a heading is not a valid tree child.+ <h3+ aria-hidden="true"+ className={cn(+ "px-2 text-xs font-medium text-sidebar-muted-foreground/80",+ !compactSearchOpen && "max-md:hidden",+ )}+ >+ {group.heading}+ </h3>+ ) : null}+ <SidebarMenu role="presentation">+ {group.paths.map((to) => {+ const Icon = SETTINGS_SECTION_ICONS[to];+ const isActive = activePath === to || activePath.startsWith(`${to}/`);+ return (+ <SidebarMenuItem key={to} role="presentation">+ <SidebarMenuButton+ data-settings-section={to}+ role="treeitem"+ tabIndex={sectionNavigation.tabIndexFor(to)}+ aria-selected={isActive}+ aria-current={isActive ? "page" : undefined}+ isActive={isActive}+ onClick={() => handleSectionClick(to)}>- {SETTINGS_SECTION_LABELS[to]}- </span>- </SidebarMenuButton>- </SidebarMenuItem>- );- })}- </SidebarMenu>- </div>- ))}+ <Icon />+ <span+ className={cn("truncate", !compactSearchOpen && "max-md:sr-only")}+ >+ {SETTINGS_SECTION_LABELS[to]}+ </span>+ </SidebarMenuButton>+ </SidebarMenuItem>+ );+ })}+ </SidebarMenu>+ </div>+ ))}+ </div></div>)}</div>diff --git a/apps/web/src/components/settings/useSettingsSectionNavigation.ts b/apps/web/src/components/settings/useSettingsSectionNavigation.tsnew file mode 100644index 00000000000..bfb4a3570bd--- /dev/null+++ b/apps/web/src/components/settings/useSettingsSectionNavigation.ts@@ -0,0 +1,56 @@+import { useState, type FocusEvent, type KeyboardEvent } from "react";++const SECTION = "[data-settings-section]";++/**+ * Settings sections share one Tab stop, and arrows move focus without opening a section.+ * The Tab stop follows the last focused section until the open section changes.+ */+export function useSettingsSectionNavigation(currentSection: string) {+ const [focused, setFocused] = useState<{ section: string; page: string } | null>(null);+ const tabStop = focused?.page === currentSection ? focused.section : currentSection;+ const remember = (element: HTMLElement) => {+ const section = element.dataset.settingsSection;+ if (section) setFocused({ section, page: currentSection });+ };+ const onFocus = (event: FocusEvent<HTMLElement>) => {+ if (event.target instanceof HTMLElement && event.target.matches(SECTION))+ remember(event.target);+ };+ const onKeyDown = (event: KeyboardEvent<HTMLElement>) => {+ if (+ event.defaultPrevented ||+ event.altKey ||+ event.ctrlKey ||+ event.metaKey ||+ !(event.target instanceof HTMLElement) ||+ !event.target.matches(SECTION)+ )+ return;+ // Every section is a root leaf; Left and Right have no tree action.+ if (event.key === "ArrowLeft" || event.key === "ArrowRight") {+ event.preventDefault();+ return;+ }+ const items = Array.from(event.currentTarget.querySelectorAll<HTMLElement>(SECTION));+ const index = items.indexOf(event.target);+ const next =+ event.key === "ArrowDown"+ ? Math.min(index + 1, items.length - 1)+ : event.key === "ArrowUp"+ ? Math.max(index - 1, 0)+ : event.key === "Home"+ ? 0+ : event.key === "End"+ ? items.length - 1+ : undefined;+ const target = next === undefined ? undefined : items[next];+ if (!target) return;+ event.preventDefault();+ remember(target);+ target.scrollIntoView({ block: "nearest" });+ target.focus({ preventScroll: true });+ };+ const tabIndexFor = (section: string) => (section === tabStop ? 0 : -1);+ return { containerProps: { onFocus, onKeyDown }, tabIndexFor };+}diff --git a/apps/web/src/components/sidebar/SidebarDraftBlock.tsx b/apps/web/src/components/sidebar/SidebarDraftBlock.tsxindex dcb436fc030..a9301f30cb0 100644--- a/apps/web/src/components/sidebar/SidebarDraftBlock.tsx+++ b/apps/web/src/components/sidebar/SidebarDraftBlock.tsx@@ -81,8 +81,9 @@ const SidebarDraftRow = memo(function SidebarDraftRow(props: {return (<li className="list-none py-0.5"><div- role="button"- tabIndex={0}+ role="treeitem"+ tabIndex={-1}+ data-sidebar-row={`draft:${draftId}`}aria-label={accessibility.label}aria-current={accessibility.current}data-testid="sidebar-draft-row"diff --git a/apps/web/src/components/sidebar/SidebarListMarkers.tsx b/apps/web/src/components/sidebar/SidebarListMarkers.tsxindex a8620a9ddf4..30a6776837e 100644--- a/apps/web/src/components/sidebar/SidebarListMarkers.tsx+++ b/apps/web/src/components/sidebar/SidebarListMarkers.tsx@@ -128,6 +128,9 @@ export function SidebarSectionHeader(props: {<SidebarThreadUndoNotice className="absolute inset-x-0 bottom-full bg-sidebar surface-grain" />) : null}<CollapsibleSectionHeader+ role="treeitem"+ tabIndex={-1}+ data-sidebar-row={`shelf:${shelf}`}onClick={props.toggle.onToggle}expanded={props.toggle.expanded}tone={props.isDropTarget ? "accent" : props.dragging ? "emphasized" : "muted"}diff --git a/apps/web/src/components/sidebar/SidebarThreadRow.tsx b/apps/web/src/components/sidebar/SidebarThreadRow.tsxindex b087e3d1e54..e3b1e864629 100644--- a/apps/web/src/components/sidebar/SidebarThreadRow.tsx+++ b/apps/web/src/components/sidebar/SidebarThreadRow.tsx@@ -513,6 +513,7 @@ const dropVerbBadge: Record<SidebarDropVerb, ReactNode> = {type SidebarThreadRowProps = {thread: SidebarThreadSummary;variant: "card" | "slim";+ navigationParent?: string | undefined;variantAction: SidebarSweepAction;settlementSupported: boolean;snoozeSupported: boolean;@@ -810,6 +811,15 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP};const handleKeyDown = (event: ReactKeyboardEvent) => {if (event.target !== event.currentTarget) return;+ if (+ event.key === "F2" &&+ !isRenaming &&+ readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope)+ ) {+ event.preventDefault();+ onStartRename(threadRef, thread.title);+ return;+ }if (event.key !== "Enter" && event.key !== " ") return;event.preventDefault();onThreadActivate(threadRef);@@ -1105,8 +1115,10 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowPrender={<divref={rowRef}- role="button"- tabIndex={0}+ role="treeitem"+ tabIndex={-1}+ data-sidebar-row={threadKey}+ data-sidebar-parent={props.navigationParent}aria-label={accessibility.label}aria-current={accessibility.current}data-testid="sidebar-row-slim"@@ -1274,8 +1286,10 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowPrender={<divref={rowRef}- role="button"- tabIndex={0}+ role="treeitem"+ tabIndex={-1}+ data-sidebar-row={threadKey}+ data-sidebar-parent={props.navigationParent}aria-label={accessibility.label}aria-current={accessibility.current}data-testid="sidebar-row-card"diff --git a/apps/web/src/components/ui/sidebar.tsx b/apps/web/src/components/ui/sidebar.tsxindex f9ab9333105..7d4acf4d392 100644--- a/apps/web/src/components/ui/sidebar.tsx+++ b/apps/web/src/components/ui/sidebar.tsx@@ -21,6 +21,7 @@ import { useMediaQuery } from "~/hooks/useMediaQuery";import { setLocalStorageItem } from "~/hooks/useLocalStorage";import { resolveSidebarState, type ResponsiveSidebarState } from "./sidebarState";import * as Schema from "effect/Schema";+import { announceSidebarVisibility } from "~/lib/accessibilityAnnouncements";const SIDEBAR_COOKIE_NAME = "sidebar_state";const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7;@@ -144,7 +145,10 @@ function createSidebarOpenStore(defaultOpen: boolean) {for (const listener of collapseListeners) listener();moveFocusOutOfCollapsingSidebar();}- if (open !== state.open) publish({ ...state, open });+ if (open !== state.open) {+ if (!isMobileViewport()) announceSidebarVisibility(open);+ publish({ ...state, open });+ }void persistSidebarOpen(open);};const setOpenMobile = (openMobile: boolean) => {@@ -315,7 +319,7 @@ function Sidebar({}><SheetHeader className="sr-only">- <SheetTitle>Sidebar</SheetTitle>+ <SheetTitle>{props["aria-label"] ?? "Sidebar"}</SheetTitle><SheetDescription>Displays the mobile sidebar.</SheetDescription></SheetHeader><divdiff --git a/apps/web/src/contextMenuFallback.keyboard.browser.test.ts b/apps/web/src/contextMenuFallback.keyboard.browser.test.tsnew file mode 100644index 00000000000..bfd74dedfbc--- /dev/null+++ b/apps/web/src/contextMenuFallback.keyboard.browser.test.ts@@ -0,0 +1,106 @@+import { expect, it } from "vite-plus/test";+import {+ dismissContextMenu,+ isContextMenuOpen,+ showContextMenuFallback,+} from "./contextMenuFallback";++const items = [+ { id: "heading", label: "Thread actions", header: true },+ { id: "disabled", label: "Unavailable", disabled: true },+ { id: "rename", label: "Rename" },+ { id: "pin", label: "Pinned", checked: true, separatorBefore: true },+ {+ id: "copy",+ label: "Copy",+ children: [+ { id: "copy-unavailable", label: "Unavailable copy", disabled: true },+ { id: "path", label: "Path" },+ { id: "branch", label: "Branch" },+ ],+ },+];++function setup() {+ const origin = document.createElement("button");+ origin.textContent = "Selected thread";+ document.body.append(origin);+ origin.focus();+ return {+ origin,+ [Symbol.dispose]() {+ dismissContextMenu();+ origin.remove();+ },+ };+}++function press(key: string, shiftKey = false) {+ const event = new KeyboardEvent("keydown", { key, shiftKey, bubbles: true, cancelable: true });+ document.activeElement!.dispatchEvent(event);+ return event;+}++const label = () => document.activeElement?.textContent;++it("starts a keyboard-opened menu on its first action and wraps through enabled actions", () => {+ using _fixture = setup();+ void showContextMenuFallback(items);+ expect(label()).toBe("Rename");+ press("ArrowUp");+ expect(label()).toBe("Copy");+ press("ArrowDown");+ expect(label()).toBe("Rename");+ press("End");+ expect(label()).toBe("Copy");+ press("Home");+ expect(label()).toBe("Rename");+});++it("opens and cancels one submenu level at a time, then returns to the thread", async () => {+ using fixture = setup();+ const result = showContextMenuFallback(items);+ press("End");+ const parent = document.activeElement;+ press("ArrowRight");+ expect(label()).toBe("Path");+ press("ArrowLeft");+ expect(document.activeElement).toBe(parent);+ press("Enter");+ expect(label()).toBe("Path");+ press("Escape");+ expect(document.activeElement).toBe(parent);+ expect(isContextMenuOpen()).toBe(true);+ press("Escape");+ expect(document.activeElement).toBe(fixture.origin);+ await expect(result).resolves.toBeNull();+});++it("activates the focused action with Space or Enter", async () => {+ using _fixture = setup();+ const first = showContextMenuFallback(items);+ press(" ");+ await expect(first).resolves.toBe("rename");+ const second = showContextMenuFallback(items);+ press("Enter");+ await expect(second).resolves.toBe("rename");+});++it("closes on Tab and returns focus to the opener so Tab continues from there", async () => {+ using fixture = setup();+ const result = showContextMenuFallback(items);+ expect(press("Tab").defaultPrevented).toBe(false);+ await expect(result).resolves.toBeNull();+ expect(document.activeElement).toBe(fixture.origin);+});++it("closes without taking focus back when focus moves elsewhere", async () => {+ using _fixture = setup();+ const result = showContextMenuFallback(items);+ const destination = document.createElement("button");+ document.body.append(destination);+ using _destination = { [Symbol.dispose]: () => destination.remove() };+ destination.focus();+ await expect(result).resolves.toBeNull();+ expect(document.activeElement).toBe(destination);+});diff --git a/apps/web/src/contextMenuFallback.test.ts b/apps/web/src/contextMenuFallback.test.tsindex 40016673ba7..3c7e6b742fe 100644--- a/apps/web/src/contextMenuFallback.test.ts+++ b/apps/web/src/contextMenuFallback.test.ts@@ -191,6 +191,8 @@ beforeEach(() => {vi.stubGlobal("window", {innerWidth: 1280,innerHeight: 800,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),});vi.stubGlobal("requestAnimationFrame", (callback: (time: number) => void) => {callback(0);diff --git a/apps/web/src/contextMenuFallback.ts b/apps/web/src/contextMenuFallback.tsindex ecae6bf7c5d..56e85545e6f 100644--- a/apps/web/src/contextMenuFallback.ts+++ b/apps/web/src/contextMenuFallback.ts@@ -155,6 +155,7 @@ function createIconElement(name: string, tone: "neutral" | "destructive"): SVGSVreturn null;}const svg = document.createElementNS(SVG_NS, "svg");+ svg.setAttribute("aria-hidden", "true");svg.setAttribute("xmlns", SVG_NS);svg.setAttribute("viewBox", "0 0 24 24");svg.setAttribute("fill", "none");@@ -210,14 +211,14 @@ function isNodeWithinMenuStack(target: EventTarget | null, menuStack: readonly Hreturn false;}-let activeContextMenuDismiss: (() => void) | null = null;+let activeContextMenuDismiss: ((restoreFocus?: boolean) => void) | null = null;export function isContextMenuOpen(): boolean {return activeContextMenuDismiss !== null;}-export function dismissContextMenu(): void {- activeContextMenuDismiss?.();+export function dismissContextMenu(restoreFocus = true): void {+ activeContextMenuDismiss?.(restoreFocus);activeContextMenuDismiss = null;}@@ -225,6 +226,7 @@ export function showContextMenuFallback<T extends string>(items: readonly ContextMenuItem<T>[],position?: { x: number; y: number },): Promise<T | null> {+ dismissContextMenu();return new Promise<T | null>((resolve) => {const previouslyFocusedElement =document.activeElement instanceof HTMLElement ? document.activeElement : null;@@ -233,9 +235,9 @@ export function showContextMenuFallback<T extends string>(let isDisposed = false;let canDismissFromPointer = false;- const dismiss = () => cleanup(null);+ const dismiss = (restoreFocus = true) => cleanup(null, restoreFocus);- const cleanup = (result: T | null) => {+ const cleanup = (result: T | null, restoreFocus = true) => {if (isDisposed) {return;}@@ -246,7 +248,10 @@ export function showContextMenuFallback<T extends string>(document.removeEventListener("keydown", onKeyDown);document.removeEventListener("pointerdown", onPointerDown, true);document.removeEventListener("contextmenu", onContextMenu, true);- const shouldRestoreFocus = isNodeWithinMenuStack(document.activeElement, menuStack);+ document.removeEventListener("focusin", onFocusIn);+ window.removeEventListener("blur", onWindowBlur);+ const shouldRestoreFocus =+ restoreFocus && isNodeWithinMenuStack(document.activeElement, menuStack);for (const menu of menuStack) {menu.remove();}@@ -257,12 +262,78 @@ export function showContextMenuFallback<T extends string>(};const onKeyDown = (event: KeyboardEvent) => {- if (event.key === "Escape") {- event.preventDefault();- cleanup(null);+ if (+ event.defaultPrevented ||+ event.isComposing ||+ event.altKey ||+ event.ctrlKey ||+ event.metaKey+ )+ return;+ const level = menuStack.findIndex((menu) =>+ isNodeWithinMenuStack(document.activeElement, [menu]),+ );+ if (level < 0) return;+ const menu = menuStack[level]!;+ const buttons = [...menu.querySelectorAll<HTMLButtonElement>("button")].filter(+ (button) => !button.disabled,+ );+ const index = buttons.indexOf(document.activeElement as HTMLButtonElement);+ let target: HTMLButtonElement | undefined;+ switch (event.key) {+ case "ArrowDown":+ target = buttons[(index + 1) % buttons.length];+ break;+ case "ArrowUp":+ target =+ buttons[(index < 0 ? buttons.length - 1 : index - 1 + buttons.length) % buttons.length];+ break;+ case "Home":+ target = buttons[0];+ break;+ case "End":+ target = buttons.at(-1);+ break;+ case "ArrowRight":+ if (buttons[index]?.getAttribute("aria-haspopup") !== "menu") return;+ buttons[index]?.click();+ break;+ case " ":+ case "Enter":+ // Keyboard activation must not depend on the opening pointer gesture's frame.+ canDismissFromPointer = true;+ buttons[index]?.click();+ break;+ case "ArrowLeft":+ if (level === 0) return;+ // Fall through to cancel this submenu only.+ case "Escape": {+ const parent = submenuTriggerStack[level];+ if (parent) {+ parent.focus({ preventScroll: true });+ closeMenusFromLevel(level);+ } else cleanup(null);+ break;+ }+ case "Tab":+ // Tab closes the menu and continues from the element that opened it.+ cleanup(null);+ return;+ default:+ return;}+ event.preventDefault();+ event.stopPropagation();+ if (target && target !== submenuTriggerStack[level + 1]) closeMenusFromLevel(level + 1);+ target?.focus({ preventScroll: true });+ target?.scrollIntoView({ block: "nearest" });};+ const onFocusIn = (event: FocusEvent) => {+ if (!isNodeWithinMenuStack(event.target, menuStack)) cleanup(null, false);+ };+ const onWindowBlur = () => cleanup(null, false);+const onPointerDown = (event: PointerEvent) => {if (!canDismissFromPointer || isNodeWithinMenuStack(event.target, menuStack)) {return;@@ -302,6 +373,10 @@ export function showContextMenuFallback<T extends string>(menu.style.left = `${preferredLeft}px`;menu.style.top = `${preferredTop}px`;menu.dataset.level = String(level);+ menu.dataset.contextMenu = "true";+ menu.setAttribute("role", "menu");+ menu.setAttribute("aria-label", parentTrigger?.textContent ?? "Context menu");+ menu.tabIndex = -1;const inner = document.createElement("div");inner.className =@@ -336,6 +411,9 @@ export function showContextMenuFallback<T extends string>(button.type = "button";const isDisabled = item.disabled === true;button.disabled = isDisabled;+ button.tabIndex = -1;+ button.setAttribute("role", "menuitem");+ button.setAttribute("aria-disabled", String(isDisabled));const rowBase ="flex w-full cursor-default select-none items-center gap-2 rounded-sm px-2 py-1 text-left outline-none transition-colors sm:min-h-7 sm:text-sm min-h-8 text-base";button.className = isDisabled@@ -491,11 +569,17 @@ export function showContextMenuFallback<T extends string>(document.addEventListener("pointerdown", onPointerDown, true);document.addEventListener("contextmenu", onContextMenu, true);openMenu(items, position?.x ?? 0, position?.y ?? 0, 0);- // Dismiss the prior menu before replacing its only cleanup handle, or its DOM and listeners leak.- if (activeContextMenuDismiss) {- activeContextMenuDismiss();- }activeContextMenuDismiss = dismiss;+ // A keyboard-opened menu starts on its first action, a pointer-opened one on the menu itself.+ // Text fields always match :focus-visible, so they say nothing about how the menu opened.+ const firstAction =+ previouslyFocusedElement?.matches(":focus-visible") &&+ !previouslyFocusedElement.matches('input, textarea, select, [contenteditable="true"]')+ ? menuStack[0]?.querySelector<HTMLButtonElement>("button:not(:disabled)")+ : null;+ (firstAction ?? menuStack[0])?.focus({ preventScroll: true });+ document.addEventListener("focusin", onFocusIn);+ window.addEventListener("blur", onWindowBlur);requestAnimationFrame(() => {canDismissFromPointer = true;diff --git a/apps/web/src/index.css b/apps/web/src/index.cssindex 23029609141..71bc4d6b511 100644--- a/apps/web/src/index.css+++ b/apps/web/src/index.css@@ -2577,3 +2577,9 @@ code {}}}++/* A workspace area with no control of its own takes F6 focus itself; keep that visible. */+[data-workspace-area]:focus-visible {+ outline: 2px solid var(--ring);+ outline-offset: -2px;+}diff --git a/apps/web/src/lib/accessibilityAnnouncements.ts b/apps/web/src/lib/accessibilityAnnouncements.tsnew file mode 100644index 00000000000..373795d57a5--- /dev/null+++ b/apps/web/src/lib/accessibilityAnnouncements.ts@@ -0,0 +1,36 @@+let latestOpen = false;+let firstWritePending = false;++/** Alternating atomic live regions allow repeated user actions to be announced, as in VS Code aria.ts. */+export function announceSidebarVisibility(open: boolean) {+ latestOpen = open;+ if (firstWritePending) return;+ let container = document.getElementById("workspace-visibility-alerts");+ const created = !container;+ if (!container) {+ container = document.createElement("div");+ container.id = "workspace-visibility-alerts";+ container.className = "sr-only";+ for (let index = 0; index < 2; index++) {+ const alert = document.createElement("div");+ alert.setAttribute("aria-live", "polite");+ alert.setAttribute("aria-atomic", "true");+ container.append(alert);+ }+ document.body.append(container);+ }+ const [first, second] = Array.from(container.children);+ const write = () => {+ firstWritePending = false;+ const next = first!.textContent ? second! : first!;+ first!.textContent = "";+ second!.textContent = "";+ next.textContent = `Sidebar ${latestOpen ? "shown" : "hidden"}`;+ };+ // Screen readers ignore text written in the same task that inserts its live region.+ // Toggles during that delay only update the state the pending write announces.+ if (created) {+ firstWritePending = true;+ setTimeout(write, 100);+ } else write();+}diff --git a/apps/web/src/lib/sidebarTree.browser.test.ts b/apps/web/src/lib/sidebarTree.browser.test.tsnew file mode 100644index 00000000000..3d57aacb864--- /dev/null+++ b/apps/web/src/lib/sidebarTree.browser.test.ts@@ -0,0 +1,195 @@+import { describe, expect, it, vi } from "vite-plus/test";+import { userEvent } from "vite-plus/test/browser";+import { installSidebarTree } from "./sidebarTree";++function setup() {+ const root = document.createElement("div");+ root.setAttribute("role", "tree");+ document.body.append(root);+ let dispose: (() => void) | undefined;+ const row = (id: string, parent?: string) => {+ const element = document.createElement("button");+ element.dataset.sidebarRow = id;+ if (parent) element.dataset.sidebarParent = parent;+ element.setAttribute("role", "treeitem");+ element.textContent = id;+ root.append(element);+ return element;+ };+ return {+ root,+ row,+ install: () => {+ dispose = installSidebarTree(root);+ },+ [Symbol.dispose]() {+ dispose?.();+ root.remove();+ },+ };+}++function press(target: HTMLElement, key: string, init: KeyboardEventInit = {}) {+ const event = new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true, ...init });+ target.dispatchEvent(event);+ return event;+}++describe("sidebar keyboard navigation", () => {+ it("moves focus without activating rows, clamps at the ends, and keeps one Tab stop", () => {+ using tree = setup();+ const first = tree.row("first");+ const second = tree.row("second");+ const last = tree.row("last");+ const activate = vi.fn();+ tree.root.addEventListener("click", activate);+ tree.install();+ first.focus();+ press(first, "ArrowDown");+ expect(document.activeElement).toBe(second);+ press(second, "End");+ expect(document.activeElement).toBe(last);+ press(last, "ArrowDown");+ expect(document.activeElement).toBe(last);+ press(last, "Home");+ expect(document.activeElement).toBe(first);+ expect(activate).not.toHaveBeenCalled();+ expect(tree.root.querySelectorAll('[tabindex="0"]')).toHaveLength(1);+ });++ it("expands a group before entering its first child and returns to the parent", async () => {+ using tree = setup();+ const group = tree.row("project");+ group.setAttribute("aria-expanded", "false");+ group.addEventListener("click", () => {+ const expanded = group.getAttribute("aria-expanded") === "true";+ group.setAttribute("aria-expanded", String(!expanded));+ if (expanded) tree.root.querySelector('[data-sidebar-row="thread"]')?.remove();+ else tree.row("thread", "project");+ });+ tree.install();+ group.focus();+ press(group, "ArrowRight");+ expect(group.getAttribute("aria-expanded")).toBe("true");+ expect(document.activeElement).toBe(group);+ // The tree picks up the new child from its mutation observer.+ await vi.waitFor(() =>+ expect(+ tree.root.querySelector('[data-sidebar-parent="project"]')?.getAttribute("aria-level"),+ ).toBe("2"),+ );+ press(group, "ArrowRight");+ const child = document.activeElement as HTMLElement;+ expect(child.dataset.sidebarRow).toBe("thread");+ press(child, "ArrowLeft");+ expect(document.activeElement).toBe(group);+ press(group, "ArrowLeft");+ expect(group.getAttribute("aria-expanded")).toBe("false");+ });++ it("opens the row menu on Shift+F10 release without moving focus", () => {+ using tree = setup();+ tree.row("first");+ const selected = tree.row("selected");+ const contextMenu = vi.fn((event: MouseEvent) => event.preventDefault());+ selected.addEventListener("contextmenu", contextMenu);+ tree.install();+ selected.focus();+ expect(press(selected, "F10", { shiftKey: true }).defaultPrevented).toBe(true);+ expect(contextMenu).not.toHaveBeenCalled();+ selected.dispatchEvent(+ new KeyboardEvent("keyup", { key: "F10", shiftKey: true, bubbles: true, cancelable: true }),+ );+ expect(contextMenu).toHaveBeenCalledOnce();+ expect(document.activeElement).toBe(selected);+ });++ it("lets Tab reach only the focused row's buttons", () => {+ using tree = setup();+ const first = tree.row("first");+ const second = tree.row("second");+ const action = (owner: string) => {+ const button = document.createElement("button");+ button.textContent = `Archive ${owner}`;+ button.dataset.sidebarActionFor = owner;+ tree.root.append(button);+ return button;+ };+ const firstAction = action("first");+ const secondAction = action("second");+ tree.install();+ first.focus();+ expect([firstAction.tabIndex, secondAction.tabIndex]).toEqual([0, -1]);+ press(first, "ArrowDown");+ expect(document.activeElement).toBe(second);+ expect([firstAction.tabIndex, secondAction.tabIndex]).toEqual([-1, 0]);+ });++ it("keeps a rendered row under a collapsed group reachable", () => {+ using tree = setup();+ const shelf = tree.row("shelf:settled");+ shelf.setAttribute("aria-expanded", "false");+ // A collapsed shelf still renders the open thread.+ const open = tree.row("thread", "shelf:settled");+ tree.install();+ shelf.focus();+ press(shelf, "ArrowDown");+ expect(document.activeElement).toBe(open);+ });++ it("skips disabled rows and leaves controls outside rows in the Tab order", () => {+ using tree = setup();+ const first = tree.row("first");+ const loading = tree.row("settled:more");+ loading.disabled = true;+ const undo = document.createElement("button");+ undo.textContent = "Undo";+ tree.root.append(undo);+ tree.install();+ first.focus();+ press(first, "ArrowDown");+ expect(document.activeElement).toBe(first);+ expect(undo.tabIndex).toBe(0);+ });++ it("gives row buttons back their own tab order when the tree reinstalls", () => {+ using tree = setup();+ tree.row("first");+ const second = tree.row("second");+ const action = (owner: string) => {+ const button = document.createElement("button");+ button.dataset.sidebarActionFor = owner;+ tree.root.append(button);+ return button;+ };+ const firstAction = action("first");+ const secondAction = action("second");+ const dispose = installSidebarTree(tree.root);+ second.focus();+ dispose();+ expect([firstAction.tabIndex, secondAction.tabIndex]).toEqual([0, 0]);+ tree.install();+ expect([firstAction.tabIndex, secondAction.tabIndex]).toEqual([-1, 0]);+ });++ it("does not pull focus back after a click outside the tree", async () => {+ using tree = setup();+ const first = tree.row("first");+ tree.install();+ const text = document.createElement("p");+ text.textContent = "Chat text";+ document.body.append(text);+ using _text = { [Symbol.dispose]: () => text.remove() };+ first.focus();+ await userEvent.click(text);+ expect(document.activeElement).toBe(document.body);+ // A status change re-renders the tree while the user works elsewhere.+ tree.row("second");+ await vi.waitFor(() =>+ expect(+ tree.root.querySelector('[data-sidebar-row="second"]')?.getAttribute("aria-posinset"),+ ).toBe("2"),+ );+ expect(document.activeElement).toBe(document.body);+ });+});diff --git a/apps/web/src/lib/sidebarTree.ts b/apps/web/src/lib/sidebarTree.tsnew file mode 100644index 00000000000..13dd10340e0--- /dev/null+++ b/apps/web/src/lib/sidebarTree.ts@@ -0,0 +1,263 @@+const ROW = "[data-sidebar-row]";+const CONTROL = 'button, a[href], input, textarea, select, [contenteditable="true"], [tabindex]';+const TEXT_ENTRY = 'input, textarea, select, [contenteditable="true"]';++function setAttribute(element: Element, name: string, value: string) {+ if (element.getAttribute(name) !== value) element.setAttribute(name, value);+}++function setTabIndex(element: HTMLElement, value: number) {+ if (element.tabIndex !== value) element.tabIndex = value;+}++export const SIDEBAR_TREE_PROPS = { role: "tree", "aria-label": "Threads" } as const;++/** Ref callback for a sidebar list; installs the tree and returns its cleanup. */+export function attachSidebarTree(element: HTMLElement | null) {+ return element ? installSidebarTree(element) : undefined;+}++/** A roving DOM focus, separate from thread activation, as in VS Code's list commands. */+export function installSidebarTree(root: HTMLElement) {+ let rows: HTMLElement[] = [];+ let focusedId: string | undefined;+ let ownsFocus = false;+ let tabStop: HTMLElement | undefined;+ let contextMenuRow: HTMLElement | undefined;+ // A control's own tab index, restored while its row holds the Tab stop and on uninstall.+ const ownTabIndex = new Map<HTMLElement, number>();++ const rowControls = (row: HTMLElement) => {+ const id = row.dataset.sidebarRow;+ const linked = id+ ? root.querySelectorAll<HTMLElement>(`[data-sidebar-action-for="${CSS.escape(id)}"]`)+ : [];+ return [...row.querySelectorAll<HTMLElement>(CONTROL), ...linked].filter(+ (control) => !control.matches(ROW) && !control.matches(TEXT_ENTRY),+ );+ };+ // Tab reaches the buttons of the focused row only, so the tree stays one stop for the rest.+ const setRowControlsReachable = (row: HTMLElement, reachable: boolean) => {+ for (const control of rowControls(row)) {+ if (!ownTabIndex.has(control)) ownTabIndex.set(control, control.tabIndex);+ setTabIndex(control, reachable ? ownTabIndex.get(control)! : -1);+ }+ };++ const setTabStop = (row: HTMLElement) => {+ if (tabStop === row) return;+ if (tabStop) {+ setTabIndex(tabStop, -1);+ setRowControlsReachable(tabStop, false);+ }+ setTabIndex(row, 0);+ setRowControlsReachable(row, true);+ tabStop = row;+ focusedId = row.dataset.sidebarRow;+ };++ const focusRow = (row: HTMLElement) => {+ setTabStop(row);+ // Revealing before focusing also materializes content-visibility:auto descendants.+ row.scrollIntoView({ block: "nearest" });+ row.focus({ preventScroll: true });+ };++ const refresh = () => {+ const previousRows = rows;+ const previousIndex = previousRows.findIndex((row) => row.dataset.sidebarRow === focusedId);+ const previous = previousRows[previousIndex];+ rows = Array.from(root.querySelectorAll<HTMLElement>(ROW)).filter((row) => {+ const hidden = row.closest('[hidden], [inert], [aria-hidden="true"]');+ // A dialog can temporarily make the whole workspace inert. Keep the tree's+ // Tab stop ready for its return while still excluding exiting row clones.+ return (!hidden || !root.contains(hidden)) && !row.matches(":disabled");+ });+ let selected =+ rows.find((row) => row.dataset.sidebarRow === focusedId) ??+ rows.find((row) => row === document.activeElement);+ if (!selected) {+ selected =+ rows.find((row) => row.dataset.sidebarRow === previous?.dataset.sidebarParent) ??+ (previousIndex === -1 ? rows.find((row) => row.hasAttribute("aria-current")) : undefined) ??+ rows[Math.min(Math.max(previousIndex, 0), rows.length - 1)];+ }+ focusedId = selected?.dataset.sidebarRow;+ tabStop = selected;+ setTabIndex(root, selected ? -1 : 0);+ const siblings = new Map<string, HTMLElement[]>();+ for (const row of rows) {+ const parent = row.dataset.sidebarParent ?? "";+ const group = siblings.get(parent) ?? [];+ group.push(row);+ siblings.set(parent, group);+ setAttribute(row, "aria-level", parent ? "2" : "1");+ setTabIndex(row, row === selected ? 0 : -1);+ }+ const byId = new Map(rows.map((row) => [row.dataset.sidebarRow, row]));+ for (const control of ownTabIndex.keys()) if (!control.isConnected) ownTabIndex.delete(control);+ for (const control of root.querySelectorAll<HTMLElement>(CONTROL)) {+ if (control.matches(ROW) || control.matches(TEXT_ENTRY)) continue;+ const linked = control.dataset.sidebarActionFor;+ const owner = control.closest<HTMLElement>(ROW) ?? (linked ? byId.get(linked) : undefined);+ if (!owner) continue;+ if (!ownTabIndex.has(control)) ownTabIndex.set(control, control.tabIndex);+ setTabIndex(control, owner === selected ? ownTabIndex.get(control)! : -1);+ }+ for (const group of siblings.values())+ group.forEach((row, index) => {+ setAttribute(row, "aria-posinset", String(index + 1));+ setAttribute(row, "aria-setsize", String(group.length));+ });+ for (const listItem of root.querySelectorAll("li:not([role])"))+ listItem.setAttribute("role", "presentation");+ if (+ ownsFocus &&+ selected &&+ (document.activeElement === document.body ||+ document.activeElement === root ||+ (root.contains(document.activeElement) &&+ !rows.includes(document.activeElement as HTMLElement) &&+ document.activeElement?.matches(ROW)))+ ) {+ focusRow(selected);+ }+ if (ownsFocus && !selected && document.activeElement === document.body) root.focus();+ };++ // Clicking non-focusable content drops focus to the body without a focusin event.+ const onPointerDown = (event: PointerEvent) => {+ if (!root.contains(event.target as Node)) ownsFocus = false;+ };+ const onFocus = (event: FocusEvent) => {+ ownsFocus = root.contains(event.target as Node);+ if (!ownsFocus || !(event.target instanceof HTMLElement) || !event.target.matches(ROW)) return;+ setTabStop(event.target);+ };+ const onKeyDown = (event: KeyboardEvent) => {+ const row = event.target;+ if (+ !event.defaultPrevented &&+ !event.isComposing &&+ !event.altKey &&+ !event.ctrlKey &&+ !event.metaKey &&+ (event.key === "ContextMenu" || (event.shiftKey && event.key === "F10")) &&+ row instanceof HTMLElement &&+ row.matches(ROW)+ ) {+ event.preventDefault();+ event.stopPropagation();+ contextMenuRow = row;+ return;+ }+ if (+ event.defaultPrevented ||+ event.isComposing ||+ event.altKey ||+ event.ctrlKey ||+ event.metaKey ||+ event.shiftKey+ )+ return;+ if (!(row instanceof HTMLElement) || !row.matches(ROW)) return;+ const index = rows.indexOf(row);+ if (index < 0) return;+ let target: HTMLElement | undefined;+ switch (event.key) {+ case "ArrowDown":+ target = rows[Math.min(index + 1, rows.length - 1)];+ break;+ case "ArrowUp":+ target = rows[Math.max(index - 1, 0)];+ break;+ case "Home":+ target = rows[0];+ break;+ case "End":+ target = rows.at(-1);+ break;+ case "ArrowRight":+ if (row.getAttribute("aria-expanded") === "false") row.click();+ else+ target = rows.find(+ (candidate) => candidate.dataset.sidebarParent === row.dataset.sidebarRow,+ );+ break;+ case "ArrowLeft":+ if (row.getAttribute("aria-expanded") === "true") row.click();+ else+ target = rows.find(+ (candidate) => candidate.dataset.sidebarRow === row.dataset.sidebarParent,+ );+ break;+ // Row handlers own Enter, Space, F2 rename, and the context menu.+ default:+ return;+ }+ event.preventDefault();+ event.stopPropagation();+ if (target) focusRow(target);+ };+ const onKeyUp = (event: KeyboardEvent) => {+ if (!contextMenuRow || (event.key !== "ContextMenu" && event.key !== "F10")) return;+ const row = contextMenuRow;+ contextMenuRow = undefined;+ event.preventDefault();+ event.stopPropagation();+ if (document.activeElement !== row || !row.isConnected) return;+ const rect = row.getBoundingClientRect();+ // Like VS Code's list, suppress keydown and open on release. Reuse the row's+ // selection-aware handler, including its Electron native menu route.+ row.dispatchEvent(+ new MouseEvent("contextmenu", {+ bubbles: true,+ cancelable: true,+ clientX: rect.left,+ clientY: rect.bottom,+ }),+ );+ };+ refresh();+ const observer = new MutationObserver((records) => {+ if (+ records.some(+ (record) =>+ record.type === "attributes" ||+ [...record.addedNodes, ...record.removedNodes].some(+ (node) =>+ node instanceof Element &&+ (node.matches(`${ROW}, ${CONTROL}`) || node.querySelector(`${ROW}, ${CONTROL}`)),+ ),+ )+ )+ refresh();+ });+ observer.observe(root, {+ childList: true,+ subtree: true,+ attributes: true,+ attributeFilter: [+ "data-sidebar-row",+ "data-sidebar-parent",+ "aria-expanded",+ "hidden",+ "disabled",+ "inert",+ "aria-hidden",+ ],+ });+ document.addEventListener("focusin", onFocus);+ document.addEventListener("pointerdown", onPointerDown, true);+ root.addEventListener("keydown", onKeyDown, true);+ root.addEventListener("keyup", onKeyUp, true);+ return () => {+ observer.disconnect();+ // A later install reads these as the controls' own tab indexes.+ for (const [control, tabIndex] of ownTabIndex) setTabIndex(control, tabIndex);+ document.removeEventListener("focusin", onFocus);+ document.removeEventListener("pointerdown", onPointerDown, true);+ root.removeEventListener("keydown", onKeyDown, true);+ root.removeEventListener("keyup", onKeyUp, true);+ };+}diff --git a/apps/web/src/lib/workspaceFocus.browser.test.ts b/apps/web/src/lib/workspaceFocus.browser.test.tsnew file mode 100644index 00000000000..f0064630f08--- /dev/null+++ b/apps/web/src/lib/workspaceFocus.browser.test.ts@@ -0,0 +1,260 @@+import { describe, expect, it, vi } from "vite-plus/test";+import { createWorkspaceFocusController } from "./workspaceFocus";++function setup() {+ const root = document.createElement("div");+ document.body.append(root);+ const controller = createWorkspaceFocusController(document);+ const area = (name: string, order: number, parent: HTMLElement = root) => {+ const element = document.createElement("section");+ element.dataset.workspaceArea = name;+ element.dataset.workspaceOrder = String(order);+ element.tabIndex = -1;+ const button = document.createElement("button");+ button.textContent = name;+ element.append(button);+ parent.append(element);+ return { element, button };+ };+ const append = (html: string) => {+ root.insertAdjacentHTML("beforeend", html);+ return root.lastElementChild as HTMLElement;+ };+ return {+ area,+ append,+ controller,+ [Symbol.dispose]() {+ controller.dispose();+ root.remove();+ },+ };+}++describe("workspace area focus", () => {+ it("cycles in workspace order in both directions, independent of DOM order", () => {+ using fixture = setup();+ const panel = fixture.area("panel", 3);+ const sidebar = fixture.area("sidebar", 0);+ const conversation = fixture.area("conversation", 1);+ const composer = fixture.area("composer", 2);+ sidebar.button.focus();+ fixture.controller.move(1);+ // The conversation is a region; it takes focus itself rather than its first button.+ expect(document.activeElement).toBe(conversation.element);+ fixture.controller.move(1);+ expect(document.activeElement).toBe(composer.button);+ fixture.controller.move(1);+ expect(document.activeElement).toBe(panel.button);+ fixture.controller.move(1);+ expect(document.activeElement).toBe(sidebar.button);+ fixture.controller.move(-1);+ expect(document.activeElement).toBe(panel.button);+ });++ it("skips hidden, inert, and maximized-away areas", () => {+ using fixture = setup();+ const sidebar = fixture.area("sidebar", 0);+ const conversation = fixture.area("conversation", 1);+ const composer = fixture.area("composer", 2);+ const panel = fixture.area("panel", 3);+ const terminal = fixture.area("terminal", 4);+ conversation.element.dataset.chatColumnMaximizedAway = "true";+ composer.element.hidden = true;+ panel.element.dataset.workspaceUnavailable = "true";+ terminal.element.inert = true;+ sidebar.button.focus();+ expect(fixture.controller.move(1)).toBe(true);+ expect(document.activeElement).toBe(sidebar.button);+ });++ it("restores the last focused control and falls back when it is removed", () => {+ using fixture = setup();+ fixture.area("sidebar", 0);+ const composer = fixture.area("composer", 2);+ const remembered = document.createElement("button");+ remembered.textContent = "remembered";+ composer.element.append(remembered);+ remembered.focus();+ fixture.controller.move(-1);+ fixture.controller.move(1);+ expect(document.activeElement).toBe(remembered);+ fixture.controller.move(-1);+ remembered.remove();+ fixture.controller.move(1);+ expect(document.activeElement).toBe(composer.button);+ });++ it("keeps focus inside a dialog or an open popup", () => {+ using fixture = setup();+ fixture.area("sidebar", 0);+ fixture.area("panel", 3);+ const dialog = fixture.append('<div role="dialog" tabindex="-1">Confirm</div>');+ dialog.focus();+ expect(fixture.controller.move(1)).toBe(false);+ expect(document.activeElement).toBe(dialog);+ dialog.remove();++ const popup = fixture.append(+ '<div role="listbox" data-slot="select-popup"><button role="option">Choice</button></div>',+ );+ const choice = popup.querySelector("button")!;+ choice.focus();+ expect(fixture.controller.move(1)).toBe(false);+ expect(document.activeElement).toBe(choice);+ });++ it("keeps moving while a non-modal notification is visible", () => {+ using fixture = setup();+ const composer = fixture.area("composer", 2);+ const panel = fixture.area("panel", 4);+ fixture.append(+ '<div data-slot="toast-viewport"><div role="dialog" aria-modal="false" tabindex="0">Update available</div></div>',+ );+ composer.button.focus();+ expect(fixture.controller.move(1)).toBe(true);+ expect(document.activeElement).toBe(panel.button);+ });++ it("moves only between the areas of an open Settings modal", () => {+ using fixture = setup();+ fixture.area("sidebar", 0);+ fixture.area("composer", 2);+ const modal = fixture.append('<div role="dialog" data-app-modal=""></div>');+ const nav = fixture.area("settings-nav", 0, modal);+ const content = fixture.area("settings", 1, modal);+ nav.button.focus();+ expect(fixture.controller.move(1)).toBe(true);+ expect(document.activeElement).toBe(content.button);+ expect(fixture.controller.move(1)).toBe(true);+ expect(document.activeElement).toBe(nav.button);+ });++ it("keeps moving while a shortcut recorder is on the page but not focused", () => {+ using fixture = setup();+ const nav = fixture.area("settings-nav", 0);+ const content = fixture.area("settings", 1);+ fixture.append('<button data-keybinding-capture="">Record shortcut</button>');+ nav.button.focus();+ expect(fixture.controller.move(1)).toBe(true);+ expect(document.activeElement).toBe(content.button);+ });++ it("brings a restored control back into view inside its own list", () => {+ using fixture = setup();+ const sidebar = fixture.area("sidebar", 0);+ const list = document.createElement("div");+ list.style.cssText = "height: 50px; overflow-y: auto";+ const spacer = document.createElement("div");+ spacer.style.height = "400px";+ const row = document.createElement("button");+ row.textContent = "Last thread";+ list.append(spacer, row);+ sidebar.element.append(list);+ const composer = fixture.area("composer", 2);+ row.focus();+ fixture.controller.move(1);+ expect(document.activeElement).toBe(composer.button);+ list.scrollTop = 0;+ fixture.controller.move(-1);+ expect(document.activeElement).toBe(row);+ expect(list.scrollTop).toBeGreaterThan(0);+ });++ it("reveals a restored control through nested scrolling lists", () => {+ using fixture = setup();+ const settings = fixture.area("settings", 1);+ const page = document.createElement("div");+ page.style.cssText = "height: 80px; overflow-y: auto";+ const inner = document.createElement("div");+ inner.style.cssText = "height: 60px; overflow-y: auto";+ const field = document.createElement("button");+ field.textContent = "Provider field";+ inner.append(Object.assign(document.createElement("div"), { style: "height: 200px" }), field);+ page.append(inner, Object.assign(document.createElement("div"), { style: "height: 400px" }));+ settings.element.append(page);+ const nav = fixture.area("settings-nav", 0);+ field.focus();+ fixture.controller.move(-1);+ expect(document.activeElement).toBe(nav.button);+ inner.scrollTop = 0;+ page.scrollTop = 300;+ fixture.controller.move(1);+ expect(document.activeElement).toBe(field);+ const box = page.getBoundingClientRect();+ const rect = field.getBoundingClientRect();+ expect(rect.bottom > box.top && rect.top < box.bottom).toBe(true);+ });++ it("does not scroll the conversation to an old control", () => {+ using fixture = setup();+ const conversation = fixture.area("conversation", 1);+ const timeline = document.createElement("div");+ timeline.style.cssText = "height: 50px; overflow-y: auto";+ const copy = document.createElement("button");+ copy.textContent = "Copy";+ timeline.append(copy, Object.assign(document.createElement("div"), { style: "height: 400px" }));+ conversation.element.append(timeline);+ const composer = fixture.area("composer", 2);+ copy.focus();+ fixture.controller.move(1);+ expect(document.activeElement).toBe(composer.button);+ // Live follow moved the timeline to the newest output.+ timeline.scrollTop = 300;+ fixture.controller.move(-1);+ expect(document.activeElement).toBe(conversation.element);+ expect(timeline.scrollTop).toBe(300);+ });++ it("returns focus to the area when its focused control disappears", async () => {+ using fixture = setup();+ const panel = fixture.area("panel", 3);+ const tab = document.createElement("button");+ tab.textContent = "Files tab";+ panel.element.append(tab);+ tab.focus();+ tab.remove();+ await vi.waitFor(() => expect(document.activeElement).toBe(panel.button));+ });++ it("falls back to the main content when the whole area disappears", async () => {+ using fixture = setup();+ const composer = fixture.area("composer", 2);+ const details = fixture.area("details", 3);+ details.button.focus();+ details.element.hidden = true;+ await vi.waitFor(() => expect(document.activeElement).toBe(composer.button));+ });++ it("waits for a requested area to mount", async () => {+ using fixture = setup();+ fixture.area("composer", 2);+ fixture.controller.request({ area: "pull-requests" });+ const list = fixture.area("pull-requests", 1);+ await vi.waitFor(() => expect(document.activeElement).toBe(list.button));+ });++ it("keeps focus on a control that React remounted elsewhere", async () => {+ using fixture = setup();+ fixture.area("composer", 2);+ const header = fixture.append("<header></header>");+ const toggle = document.createElement("button");+ toggle.setAttribute("aria-label", "Toggle right panel");+ header.append(toggle);+ toggle.focus();+ const moved = toggle.cloneNode() as HTMLButtonElement;+ toggle.remove();+ header.append(moved);+ await vi.waitFor(() => expect(document.activeElement).toBe(moved));+ });++ it("keeps moving while a hover popup without focus is open", () => {+ using fixture = setup();+ const composer = fixture.area("composer", 2);+ const terminal = fixture.area("terminal", 4);+ fixture.append('<div data-slot="popover-popup">New split terminal</div>');+ composer.button.focus();+ expect(fixture.controller.move(1)).toBe(true);+ expect(document.activeElement).toBe(terminal.button);+ });+});diff --git a/apps/web/src/lib/workspaceFocus.ts b/apps/web/src/lib/workspaceFocus.tsnew file mode 100644index 00000000000..e612a8ff549--- /dev/null+++ b/apps/web/src/lib/workspaceFocus.ts@@ -0,0 +1,386 @@+import type { AnyRouter } from "@tanstack/react-router";+import { dismissContextMenu } from "../contextMenuFallback";+import { useRightPanelStore } from "../rightPanelStore";++const AREA_SELECTOR = "[data-workspace-area]";+const FOCUS_BOUNDARY_SELECTOR =+ '[role="dialog"], [role="alertdialog"], [aria-modal="true"], dialog[open], [data-slot$="-popup"]:not([data-slot="tooltip-popup"]):not([role="tooltip"])';+const FOCUSABLE_SELECTOR =+ 'button:not(:disabled), a[href], input:not(:disabled), textarea:not(:disabled), select:not(:disabled), [contenteditable="true"], [tabindex]';++/** Props that make an element one stop in the F6 cycle; `order` sets its place in the cycle. */+export function workspaceAreaProps(name: string, order: number, label: string) {+ return {+ "data-workspace-area": name,+ "data-workspace-order": order,+ "aria-label": label,+ role: "region",+ tabIndex: -1,+ } as const;+}++export interface WorkspaceFocusTarget {+ area: string;+ selector?: string;+ restore?: boolean;+}++function workspaceArea(element: Element): HTMLElement | null {+ const area = element.closest<HTMLElement>(AREA_SELECTOR);+ if (area) return area;+ const root = element.getRootNode();+ return root instanceof ShadowRoot ? workspaceArea(root.host) : null;+}++function isWorkspaceElementVisible(element: HTMLElement): boolean {+ if (+ !element.isConnected ||+ element.closest(+ '[hidden], [inert], [data-closed], [aria-hidden="true"], [data-chat-column-maximized-away="true"], [data-slot="sidebar"][data-state="collapsed"], [data-workspace-unavailable="true"]',+ )+ )+ return false;+ const style = getComputedStyle(element);+ if (style.display === "none" || style.visibility === "hidden") return false;+ const root = element.getRootNode();+ if (+ root instanceof ShadowRoot &&+ root.host instanceof HTMLElement &&+ !isWorkspaceElementVisible(root.host)+ )+ return false;+ return Array.from(element.getClientRects()).some((rect) => rect.width > 0 && rect.height > 0);+}++function scrollingAncestors(target: HTMLElement) {+ const scrollers: HTMLElement[] = [];+ for (let element = target.parentElement; element; element = element.parentElement) {+ const { overflowY } = getComputedStyle(element);+ if (+ (overflowY === "auto" || overflowY === "scroll") &&+ element.scrollHeight > element.clientHeight+ )+ scrollers.push(element);+ }+ return scrollers;+}++function isInScrollView(target: HTMLElement) {+ const rect = target.getBoundingClientRect();+ return scrollingAncestors(target).every((scroller) => {+ const box = scroller.getBoundingClientRect();+ return rect.bottom > box.top && rect.top < box.bottom;+ });+}++/**+ * Brings a restored control into view, innermost scrolling list first.+ * scrollIntoView would also scroll overflow-hidden layout containers out of place.+ */+function revealInScrollers(target: HTMLElement) {+ for (const scroller of scrollingAncestors(target)) {+ const box = scroller.getBoundingClientRect();+ const rect = target.getBoundingClientRect();+ if (rect.top < box.top) scroller.scrollTop -= box.top - rect.top;+ else if (rect.bottom > box.bottom) scroller.scrollTop += rect.bottom - box.bottom;+ }+}++/** Keeps area focus local, like VS Code's layout service focusPart/visible-neighbour actions. */+export function createWorkspaceFocusController(doc: Document) {+ const lastFocused = new Map<string, HTMLElement>();+ let lastArea: string | undefined;+ const remember = (event: FocusEvent) => {+ if (!(event.target instanceof HTMLElement)) return;+ const area = workspaceArea(event.target);+ if (!area?.dataset.workspaceArea) return;+ lastArea = area.dataset.workspaceArea;+ const key = area.dataset.workspaceFocusKey ?? lastArea;+ lastFocused.delete(key);+ // Custom file trees retarget focusin to their nonfocusable shadow host.+ const target = event.composedPath().find((element) => element instanceof HTMLElement);+ lastFocused.set(key, target instanceof HTMLElement ? target : event.target);+ // Surface history must not retain an unbounded number of detached panel trees.+ if (lastFocused.size > 64) lastFocused.delete(lastFocused.keys().next().value!);+ };+ doc.addEventListener("focusin", remember);++ const focusArea = (area: HTMLElement, restore = true) => {+ const key = area.dataset.workspaceFocusKey ?? area.dataset.workspaceArea!;+ const previous = restore ? lastFocused.get(key) : undefined;+ const belongs = (element: HTMLElement) =>+ workspaceArea(element) === area &&+ isWorkspaceElementVisible(element) &&+ !element.matches(":disabled");+ const preferred = Array.from(+ area.querySelectorAll<HTMLElement>(+ '[data-workspace-focus-default], [role="treeitem"][tabindex="0"], [data-settings-section][tabindex="0"], .xterm-helper-textarea, [contenteditable="true"]',+ ),+ ).find(belongs);+ const fallback = Array.from(area.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)).find(+ (element) => element.tabIndex >= 0 && belongs(element),+ );+ // Panel surfaces may unmount when hidden. Recover the same named control when+ // it mounts again, without sharing focus history between different surface tabs.+ const restored =+ previous && !previous.isConnected+ ? Array.from(area.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)).find(+ (element) =>+ belongs(element) &&+ element.tagName === previous.tagName &&+ ((previous.id && element.id === previous.id) ||+ (previous.getAttribute("aria-label") &&+ element.getAttribute("aria-label") === previous.getAttribute("aria-label")) ||+ (previous.matches("button") &&+ previous.textContent?.trim() &&+ element.textContent === previous.textContent)),+ )+ : undefined;+ const surface = area.querySelector<HTMLElement>("[data-right-panel-surface-content]");+ const surfaceControl = surface+ ? Array.from(surface.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)).find(+ (element) => belongs(element) && element.tabIndex >= 0,+ )+ : undefined;+ // Moving the timeline to an old control would also stop it following a running turn,+ // so the conversation reuses a control only while it is still in view.+ const isConversation = area.dataset.workspaceArea === "conversation";+ const targets = new Set([+ previous && belongs(previous) && (!isConversation || isInScrollView(previous))+ ? previous+ : undefined,+ isConversation ? undefined : restored,+ preferred,+ surfaceControl,+ isConversation ? undefined : fallback,+ area,+ ]);+ for (const target of targets) {+ if (!target) continue;+ target.focus({ preventScroll: true });+ const root = target.getRootNode();+ const active = root instanceof ShadowRoot ? root.activeElement : doc.activeElement;+ if (active === target || (active && target.contains(active))) {+ if (target !== area && !isConversation) revealInScrollers(target);+ return true;+ }+ }+ return false;+ };+ const focus = (name: string, restore = true, selector?: string) => {+ const areas = Array.from(doc.querySelectorAll<HTMLElement>(AREA_SELECTOR)).filter(+ isWorkspaceElementVisible,+ );+ const area =+ name === "content"+ ? (areas.find((element) => element.dataset.workspaceArea === "composer") ??+ areas.find(+ (element) =>+ element.dataset.workspaceArea === "pull-requests" || element.matches("main"),+ ) ??+ areas.find((element) => element.dataset.workspaceArea === "conversation") ??+ areas.find((element) => element.dataset.workspaceArea === "panel"))+ : areas.find((element) => element.dataset.workspaceArea === name);+ if (!area) return false;+ const surface = area.querySelector("[data-right-panel-surface-content]");+ // A lazy surface's Suspense fallback is empty. Wait for its content instead+ // of claiming focus on the tab strip before the useful controls mount.+ if (surface && !surface.hasChildNodes()) return false;+ if (selector) {+ const target = area.querySelector<HTMLElement>(selector);+ if (!target || !isWorkspaceElementVisible(target)) return false;+ target.focus({ preventScroll: true });+ return doc.activeElement === target;+ }+ return focusArea(area, restore);+ };+ const move = (direction: 1 | -1, fromArea?: string, closingPalette = false) => {+ // HTML context menus close on blur, unlike modal dialogs and Base UI popups.+ dismissContextMenu(false);+ // A palette closes before running its command. Other popups keep their focus boundary.+ // Inline listboxes (such as Settings search) belong to their workspace area, while+ // portalled listboxes and menus can also supply a boundary without a popup data-slot.+ const activePopup = doc.activeElement?.closest<HTMLElement>('[role="menu"], [role="listbox"]');+ // Settings opens as a route modal with its own areas; navigation stays inside it.+ const appModal = Array.from(doc.querySelectorAll<HTMLElement>("[data-app-modal]")).find(+ isWorkspaceElementVisible,+ );+ const boundaries = Array.from(+ doc.querySelectorAll<HTMLElement>(FOCUS_BOUNDARY_SELECTOR),+ ).filter((boundary) => boundary !== appModal);+ if (activePopup && !activePopup.closest(AREA_SELECTOR)) boundaries.push(activePopup);+ // A modal keeps focus wherever it is; any other popup only while it holds focus,+ // so hover popups and notifications never swallow the key.+ if (+ boundaries.some(+ (boundary) =>+ !(closingPalette && boundary.closest("[data-command-palette]")) &&+ (boundary.matches('[aria-modal="true"]') || boundary.contains(doc.activeElement)) &&+ isWorkspaceElementVisible(boundary),+ )+ )+ return false;+ const areas = Array.from((appModal ?? doc).querySelectorAll<HTMLElement>(AREA_SELECTOR))+ .filter(isWorkspaceElementVisible)+ .sort(+ (left, right) => Number(left.dataset.workspaceOrder) - Number(right.dataset.workspaceOrder),+ );+ if (areas.length === 0) return false;+ const activeArea = doc.activeElement?.closest<HTMLElement>(AREA_SELECTOR);+ const currentId = fromArea ?? activeArea?.dataset.workspaceArea ?? lastArea;+ const current = areas.findIndex((area) => area.dataset.workspaceArea === currentId);+ const index =+ current === -1+ ? direction === 1+ ? 0+ : areas.length - 1+ : (current + direction + areas.length) % areas.length;+ const area = areas[index]!;+ return focusArea(area);+ };++ // Focus that drops to the body because its element was hidden, made inert, or removed+ // returns to the same control when React remounted it, else to its area, else the content.+ const recover = (event: FocusEvent) => {+ const lost = event.target;+ if (!(lost instanceof HTMLElement) || event.relatedTarget) return;+ const areaName = workspaceArea(lost)?.dataset.workspaceArea;+ const label = lost.getAttribute("aria-label");+ requestAnimationFrame(() => {+ if (doc.activeElement !== doc.body || !doc.hasFocus() || isWorkspaceElementVisible(lost))+ return;+ const remounted = Array.from(doc.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)).find(+ (element) =>+ element.tagName === lost.tagName &&+ ((lost.id && element.id === lost.id) ||+ (label && element.getAttribute("aria-label") === label)) &&+ isWorkspaceElementVisible(element),+ );+ if (remounted) remounted.focus({ preventScroll: true });+ else if (!areaName || !focus(areaName)) focus("content");+ });+ };+ doc.addEventListener("focusout", recover);++ // A request names a destination React has not committed yet, so it retries as the+ // DOM changes. User input cancels it, and it gives up after two seconds.+ let pending: WorkspaceFocusTarget | undefined;+ let frame = 0;+ let deadline = 0;+ let cancelOnInput = false;+ const observer = new MutationObserver(() => schedule());+ const cancelRequest = () => {+ pending = undefined;+ cancelOnInput = false;+ observer.disconnect();+ cancelAnimationFrame(frame);+ clearTimeout(deadline);+ };+ const schedule = () => {+ cancelAnimationFrame(frame);+ frame = requestAnimationFrame(() => {+ if (pending && focus(pending.area, pending.restore, pending.selector)) cancelRequest();+ });+ };+ const request = (target: WorkspaceFocusTarget) => {+ cancelRequest();+ pending = target;+ // The key or click that made the request may still be propagating.+ queueMicrotask(() => {+ if (pending === target) cancelOnInput = true;+ });+ observer.observe(doc.body, {+ childList: true,+ subtree: true,+ attributes: true,+ attributeFilter: ["inert", "aria-hidden", "data-workspace-unavailable"],+ });+ deadline = window.setTimeout(cancelRequest, 2000);+ schedule();+ };+ const onUserInput = () => {+ if (cancelOnInput) cancelRequest();+ };+ doc.addEventListener("pointerdown", onUserInput, true);+ doc.addEventListener("keydown", onUserInput, true);++ return {+ move: (direction: 1 | -1, fromArea?: string, closingPalette = false) => {+ cancelRequest();+ return move(direction, fromArea, closingPalette);+ },+ focus,+ request,+ dispose: () => {+ cancelRequest();+ doc.removeEventListener("focusin", remember);+ doc.removeEventListener("focusout", recover);+ doc.removeEventListener("pointerdown", onUserInput, true);+ doc.removeEventListener("keydown", onUserInput, true);+ },+ };+}++let controller: ReturnType<typeof createWorkspaceFocusController> | undefined;+let focusRequestVersion = 0;+export const getWorkspaceFocusRequestVersion = () => focusRequestVersion;++/**+ * Starts workspace focus for the app: F6 area moves, focus requests, focus-loss recovery,+ * focus into a panel the user opens, and focus into the Pull Requests page on entry.+ */+export function startWorkspaceFocus(router: AnyRouter): () => void {+ const active = createWorkspaceFocusController(document);+ controller = active;+ const stopPanels = useRightPanelStore.subscribe((state, previous) => {+ if (state.userActionRevisionByThreadKey === previous.userActionRevisionByThreadKey) return;+ for (const [threadKey, revision] of Object.entries(state.userActionRevisionByThreadKey)) {+ if (previous.userActionRevisionByThreadKey[threadKey] === revision) continue;+ const next = state.byThreadKey[threadKey];+ const before = previous.byThreadKey[threadKey];+ if (next?.isOpen && (!before?.isOpen || next.activeSurfaceId !== before.activeSurfaceId))+ requestWorkspaceFocus({ area: "panel" });+ }+ });+ const stopRoute = router.subscribe("onResolved", ({ fromLocation, toLocation }) => {+ if (toLocation.pathname === "/pull-requests" && fromLocation?.pathname !== "/pull-requests")+ requestWorkspaceFocus({ area: "pull-requests" });+ });+ return () => {+ stopPanels();+ stopRoute();+ active.dispose();+ if (controller === active) controller = undefined;+ };+}++/** Moves to the next or previous visible area. `fromArea` overrides the focused area. */+export function moveWorkspaceFocus(direction: 1 | -1, fromArea?: string): boolean {+ return controller?.move(direction, fromArea) ?? false;+}++/** Explicit user actions request focus after React has committed the destination. */+export function requestWorkspaceFocus(target: WorkspaceFocusTarget) {+ focusRequestVersion++;+ controller?.request(target);+}++export function requestWorkspaceContentFocus() {+ // Resolve after the layout commits: closing a maximized panel makes the+ // composer available again, while hiding a sidebar may leave only the panel.+ requestWorkspaceFocus({ area: "content" });+}++let pendingPaletteDirection: 1 | -1 | undefined;+export function queueWorkspaceFocusFromPalette(direction: 1 | -1) {+ pendingPaletteDirection = direction;+}++/** Runs at the palette's normal focus restoration milestone, after its focus trap closes. */+export function restoreWorkspaceFocusFromPalette(): boolean {+ if (pendingPaletteDirection === undefined) return false;+ const direction = pendingPaletteDirection;+ pendingPaletteDirection = undefined;+ window.requestAnimationFrame(() => controller?.move(direction, undefined, true));+ return true;+}diff --git a/apps/web/src/routes/_chat.index.tsx b/apps/web/src/routes/_chat.index.tsxindex 4b653e5e94f..65315f29364 100644--- a/apps/web/src/routes/_chat.index.tsx+++ b/apps/web/src/routes/_chat.index.tsx@@ -1,3 +1,4 @@+import { workspaceAreaProps } from "../lib/workspaceFocus";import { RefreshIcon } from "~/components/ui/refresh-icon";import { scopeProjectRef } from "@t3tools/client-runtime/environment";import { createFileRoute, useRouter } from "@tanstack/react-router";@@ -86,8 +87,13 @@ function IndexDraftLanding() {}function DraftStartError({ onRetry }: { readonly onRetry: () => void }) {+ const contentArea = workspaceAreaProps("home", 1, "Home");return (- <SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none">+ <SidebarInset+ {...contentArea}+ role="main"+ className="h-dvh min-h-0 overflow-hidden overscroll-y-none"+ >{isElectron ? <WorkspacePageHeader electron /> : null}<Empty className="flex-1"><EmptyHeader className="max-w-md">diff --git a/apps/web/src/routes/_chat.settings.tsx b/apps/web/src/routes/_chat.settings.tsxindex 0dccf0b30c2..fdc350fe81a 100644--- a/apps/web/src/routes/_chat.settings.tsx+++ b/apps/web/src/routes/_chat.settings.tsx@@ -1,3 +1,4 @@+import { workspaceAreaProps } from "../lib/workspaceFocus";import { Outlet, createFileRoute, redirect, useLocation } from "@tanstack/react-router";import { useState, type ReactNode } from "react";import { RotateCcwIcon } from "lucide-react";@@ -106,6 +107,7 @@ function SettingsScopeBoundary({ pathname, children }: { pathname: string; child}function SettingsContentLayout() {+ const contentArea = workspaceAreaProps("settings", 1, "Settings content");const location = useLocation();const { search, environment } = useSettingsScope();const contentScopeKey =@@ -118,7 +120,7 @@ function SettingsContentLayout() {<AppRouteModal label="Settings"><div className="relative flex min-h-0 flex-1"><SettingsSidebarNav pathname={location.pathname} />- <div className="flex min-h-0 min-w-0 flex-1 flex-col">+ <div {...contentArea} className="flex min-h-0 min-w-0 flex-1 flex-col"><header className="flex h-12 shrink-0 items-center gap-3 border-b ps-5 pe-2"><SettingsBreadcrumb pathname={location.pathname} /><div className="ms-auto flex shrink-0 items-center gap-1">diff --git a/docs/user/keyboard-focus.md b/docs/user/keyboard-focus.mdindex 50b9c87c24f..b51262b6d69 100644--- a/docs/user/keyboard-focus.md+++ b/docs/user/keyboard-focus.md@@ -1,9 +1,37 @@# Keyboard focus-The command palette keeps focus while open. Closing it returns focus to the composer.+The command palette keeps focus while open. Closing it returns focus to the composer in chat,+or to the previous control on other pages. Choosing a workspace focus command moves to that+area instead. Opening Pull Requests moves focus into that page.While the palette or model picker is open, number shortcuts select its entries instead ofswitching threads. Model shortcuts work in Settings as well as the composer.See [Keybindings](./keybindings.md) to customize these shortcuts.If you return to typing while a terminal is starting, the composer keeps focus when the terminalbecomes ready. Opening or switching to a terminal explicitly still focuses it.++## Move between workspace areas++On web and desktop, press `F6` or `Shift+F6` to move between the Threads sidebar,+conversation, message input, and visible panels. Navigation wraps around and restores+the last focused control in each area. Pull Requests has a page content area. In Settings,+`F6` moves between the section list and the open section. Hidden areas are skipped. Other+dialogs and form popups retain focus; a thread context menu closes when an area command+moves focus away.++In a browser, plain `F6` may move to the browser's own toolbar. Use `mod+F6` and+`mod+Shift+F6` instead (`mod` is Command on macOS and Ctrl elsewhere). **Focus Next+Workspace Area** and **Focus Previous Workspace Area** are also in the command palette and+can be remapped in Settings > Keybindings.++## Browse threads++Tab enters the sidebar once. Up and Down move between threads without opening them; Enter+opens the focused thread or toggles a group. Right and Left expand and collapse groups.+Tab moves from the focused thread to its buttons. `F2` renames the focused thread.++Press `Shift+F10` or the Context Menu key to open the focused thread's menu. Use the arrow+keys to move through it, Enter to choose, and Escape to close it.++The Settings section list works the same way: Up and Down move between sections, and Enter+opens one.diff --git a/packages/contracts/src/keybindings.ts b/packages/contracts/src/keybindings.tsindex 847ed0746c1..1e7962c04e0 100644--- a/packages/contracts/src/keybindings.ts+++ b/packages/contracts/src/keybindings.ts@@ -57,6 +57,8 @@ const MODEL_PICKER_KEYBINDING_COMMANDS = [export type ModelPickerKeybindingCommand = (typeof MODEL_PICKER_KEYBINDING_COMMANDS)[number];export const STATIC_KEYBINDING_COMMANDS = [+ "workspace.focusNext",+ "workspace.focusPrevious","sidebar.toggle","navigation.back","navigation.forward",diff --git a/packages/shared/src/keybindings.ts b/packages/shared/src/keybindings.tsindex b511f830f69..32292c0f9ef 100644--- a/packages/shared/src/keybindings.ts+++ b/packages/shared/src/keybindings.ts@@ -146,6 +146,11 @@ type WhenToken =export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [{ key: "mod+b", command: "sidebar.toggle" },+ { key: "f6", command: "workspace.focusNext" },+ { key: "shift+f6", command: "workspace.focusPrevious" },+ // Some browsers keep plain F6 for their own toolbars; mod+F6 reaches the page in all of them.+ { key: "mod+f6", command: "workspace.focusNext" },+ { key: "mod+shift+f6", command: "workspace.focusPrevious" },{ key: "mod+[", command: "navigation.back", when: "!terminalFocus" },{ key: "mod+]", command: "navigation.forward", when: "!terminalFocus" },{ key: "mod+j", command: "terminal.toggle" },