The best way to control Claude Code, Codex and more from any computer or phone
feat(web): F6 moves between workspace areas, and the sidebar is keyboard navigable (#25877)
Co-authored-by: thienautran <thien.autran75@gmail.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Theo Browne committed
Oct 27, 2026 at 18:55 UTC
2525252c968317a80b2e8b9e774915918196aaeb
45 files changed
+1870
-91
apps/desktop/src/preview/Manager.ts
+10
-1
@@ -1505,7 +1505,16 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
1505
);
1506
if (forwarded && host) {
1507
event.preventDefault();
1508
- if (!input.isAutoRepeat) host.send(MENU_ACTION_CHANNEL, forwarded.command);
1508
+ if (!input.isAutoRepeat) {
1509
+ if (
1510
+ forwarded.command === "workspace.focusNext" ||
1511
+ forwarded.command === "workspace.focusPrevious"
1512
+ ) {
1513
+ // DOM focus in the renderer cannot by itself release the guest's native keyboard focus.
1514
+ host.focus();
1515
+ }
1516
+ host.send(MENU_ACTION_CHANNEL, forwarded.command);
1517
+ }
1518
return;
1519
}
1520
if (isPreviewRefreshShortcut(input)) {
apps/web/src/appInit.tsx
+2
@@ -48,6 +48,7 @@ import { appAtomRegistry } from "./rpc/atomRegistry";
48
import { primaryServerConfigAtom } from "./state/server";
49
import { environmentShell } from "./state/shell";
50
import { installChatRouteCommands } from "./shortcuts/chatRouteCommands";
51
+import { startWorkspaceFocus } from "./lib/workspaceFocus";
52
import { installCommandPaletteCommands } from "./shortcuts/commandPaletteCommands";
53
import { registerOpenFavoriteEditorCommand } from "./components/chat/OpenInPickerShortcut";
54
import { environmentThreadShells } from "./state/threads";
@@ -191,6 +192,7 @@ export function startAppServices(): AppRouter {
192
shellStateAtom: environmentShell.stateAtom,
193
});
194
startMainAppLocationTracking(router);
195
+ startWorkspaceFocus(router);
196
startBackgroundThreadAnnouncements(appAtomRegistry, router);
197
startThreadVisitedMigration(appAtomRegistry);
198
startSshPasswordPromptQueue();
apps/web/src/commandPaletteStore.ts
+29
-1
@@ -6,6 +6,7 @@ import {
6
type CommandPaletteUiState,
7
reduceCommandPaletteUiState,
8
} from "./components/CommandPalette.logic";
9
+import { getWorkspaceFocusRequestVersion } from "./lib/workspaceFocus";
10
11
const INITIAL_STATE: CommandPaletteUiState = {
12
open: false,
@@ -16,8 +17,35 @@ const INITIAL_STATE: CommandPaletteUiState = {
17
18
export const useCommandPaletteStore = create<CommandPaletteUiState>(() => INITIAL_STATE);
19
20
+let returnFocus: { element: HTMLElement | null; href: string; focusRequest: number } | null = null;
21
+
22
export function dispatchCommandPalette(action: CommandPaletteUiAction): void {
20
- useCommandPaletteStore.setState((state) => reduceCommandPaletteUiState(state, action), true);
23
+ const state = useCommandPaletteStore.getState();
24
+ const next = reduceCommandPaletteUiState(state, action);
25
+ if (!state.open && next.open) {
26
+ // The workspace turns inert before the popup mounts, which blurs the opener.
27
+ returnFocus = {
28
+ element: document.activeElement instanceof HTMLElement ? document.activeElement : null,
29
+ href: window.location.href,
30
+ focusRequest: getWorkspaceFocusRequestVersion(),
31
+ };
32
+ }
33
+ useCommandPaletteStore.setState(next, true);
34
+}
35
+
36
+/**
37
+ * Where the closing palette should return focus: `false` when a command navigated or asked
38
+ * for workspace focus (the destination owns it), else the opener, or `true` for the default.
39
+ */
40
+export function getCommandPaletteReturnFocus(): HTMLElement | boolean {
41
+ if (
42
+ !returnFocus ||
43
+ window.location.href !== returnFocus.href ||
44
+ getWorkspaceFocusRequestVersion() !== returnFocus.focusRequest
45
+ )
46
+ return false;
47
+ const { element } = returnFocus;
48
+ return element?.isConnected && !element.matches(":disabled") ? element : true;
49
}
50
51
// The palette is only mounted on app-shell routes (not /pair, sign-in or
apps/web/src/components/AppSidebarLayout.tsx
+31
@@ -9,6 +9,7 @@ import {
9
} from "react";
10
import { useLocation, useRouter, type AnyRouter } from "@tanstack/react-router";
11
12
+import { moveWorkspaceFocus, workspaceAreaProps } from "../lib/workspaceFocus";
13
import { isCommandPaletteOpen } from "../commandPaletteBus";
14
import { isElectron } from "../env";
15
import {
@@ -170,6 +171,33 @@ export function registerNavigationHistoryCommands(router: AnyRouter): () => void
171
);
172
}
173
174
+// Capture phase, so F6 also leaves widgets that swallow keys, such as the terminal.
175
+function registerWorkspaceFocusCommands(router: AnyRouter): () => void {
176
+ const move = (direction: 1 | -1) => (event: KeyboardEvent) => {
177
+ if (event.isComposing) return false;
178
+ // Inside a dialog the move is refused, but the key is still consumed.
179
+ event.preventDefault();
180
+ event.stopPropagation();
181
+ moveWorkspaceFocus(direction);
182
+ };
183
+ const disposers = [
184
+ registerCommands(
185
+ { "workspace.focusNext": move(1), "workspace.focusPrevious": move(-1) },
186
+ {
187
+ capture: true,
188
+ when: (event) => !isKeybindingCaptureTarget(event),
189
+ context: () => readRoutePanelsOpen(router),
190
+ },
191
+ ),
192
+ // A focused desktop browser forwards the keys; its renderer focus is stale.
193
+ registerMenuAction("workspace.focusNext", () => moveWorkspaceFocus(1, "panel")),
194
+ registerMenuAction("workspace.focusPrevious", () => moveWorkspaceFocus(-1, "panel")),
195
+ ];
196
+ return () => {
197
+ for (const dispose of disposers) dispose();
198
+ };
199
+}
200
+
201
// Escape leaves the pull requests page when no scope (a selection, a dialog,
202
// a drag) claimed it, so it observes after every other scope.
203
function registerPullRequestsEscapeCommand(router: AnyRouter): () => void {
@@ -272,6 +300,7 @@ function registerAppShellCommands(router: AnyRouter, shellElement: Element): ()
300
const disposers = [
301
registerThreadUndoCommands(router, readSidebarVisible),
302
registerNavigationHistoryCommands(router),
303
+ registerWorkspaceFocusCommands(router),
304
registerPullRequestsEscapeCommand(router),
305
registerMenuAction("open-settings", () => {
306
if (!/^\/settings(\/|$)/.test(router.state.location.pathname))
@@ -373,6 +402,7 @@ function SidebarControl() {
402
}
403
404
export function AppSidebarLayout({ children }: { children: ReactNode }) {
405
+ const sidebarArea = workspaceAreaProps("sidebar", 0, "Threads");
406
const legacySidebarEnabled = useLegacySidebarEnabled();
407
const [sidebarRouteReveal] = useState<SidebarRouteReveal>(() => ({
408
observedKey: null,
@@ -426,6 +456,7 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
456
side="left"
457
collapsible="offcanvas"
458
data-app-sidebar=""
459
+ {...sidebarArea}
460
role="navigation"
461
aria-label="Threads"
462
resizable={{
apps/web/src/components/BranchToolbar.tsx
+10
-2
@@ -280,7 +280,11 @@ const RunContextSelector = memo(function RunContextSelector({
280
isPanel && THREAD_DETAILS_PANEL_LOCKED_ROW_CLASS,
281
)}
282
onContextMenu={handleContextMenu}
283
- aria-label={isPanel ? "Run context" : undefined}
283
+ aria-label={
284
+ isPanel
285
+ ? `Run context: ${[autoEnvironmentLabel ?? activeEnvironment?.label, workspaceLabel].filter(Boolean).join(", ")}`
286
+ : undefined
287
+ }
288
data-composer-context-control
289
>
290
{triggerContent}
@@ -301,7 +305,11 @@ const RunContextSelector = memo(function RunContextSelector({
305
}
306
: undefined
307
}
304
- aria-label={isPanel ? "Run context" : undefined}
308
+ aria-label={
309
+ isPanel
310
+ ? `Run context: ${[autoEnvironmentLabel ?? activeEnvironment?.label, workspaceLabel].filter(Boolean).join(", ")}`
311
+ : undefined
312
+ }
313
data-composer-context-control
314
data-composer-shortcut={[
315
showEnvironmentPicker && !envLocked ? "composer.host" : "",
apps/web/src/components/ChatView.logic.browser.test.ts
new
+28
@@ -0,0 +1,28 @@
1
+import { expect, it } from "vite-plus/test";
2
+import { userEvent } from "vite-plus/test/browser";
3
+import { shouldRefocusComposerOnWindowFocus } from "./ChatView.logic";
4
+
5
+it("keeps keyboard focus on a sidebar row on window return, but not a clicked row", async () => {
6
+ const tree = document.createElement("div");
7
+ tree.setAttribute("role", "tree");
8
+ const row = (name: string, tabIndex: number) => {
9
+ const element = document.createElement("div");
10
+ element.setAttribute("role", "treeitem");
11
+ element.tabIndex = tabIndex;
12
+ element.textContent = name;
13
+ tree.append(element);
14
+ return element;
15
+ };
16
+ const clicked = row("Clicked thread", -1);
17
+ const tabbed = row("Tabbed thread", 0);
18
+ document.body.append(tree);
19
+ using _tree = { [Symbol.dispose]: () => tree.remove() };
20
+
21
+ await userEvent.click(clicked);
22
+ expect(document.activeElement).toBe(clicked);
23
+ expect(shouldRefocusComposerOnWindowFocus(document.activeElement)).toBe(true);
24
+
25
+ await userEvent.tab();
26
+ expect(document.activeElement).toBe(tabbed);
27
+ expect(shouldRefocusComposerOnWindowFocus(document.activeElement)).toBe(false);
28
+});
apps/web/src/components/ChatView.logic.ts
+5
-1
@@ -1166,6 +1166,10 @@ export function hasServerAcknowledgedLocalDispatch(input: {
1166
);
1167
}
1168
1169
+// Returning to the window should land the caret in the composer, so the reader can type right
1170
+// away. The exceptions are places where focus is deliberate: another text field, a terminal in
1171
+// the drawer or the right panel, an open dialog, menu, or popup, or a region or sidebar row
1172
+// reached from the keyboard. A plain focused button or a clicked row yields to the composer.
1173
export function shouldRefocusComposerOnWindowFocus(
1174
activeElement:
1175
| (Pick<Element, "tagName" | "closest" | "getAttribute"> & { isContentEditable?: boolean })
@@ -1185,7 +1189,7 @@ export function shouldRefocusComposerOnWindowFocus(
1189
}
1190
return (
1191
activeElement.closest(
1188
- '[role="dialog"], [role="alertdialog"], [role="application"], [data-slot$="-popup"], [data-terminal-owner]',
1192
+ '[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]',
1193
) === null
1194
);
1195
}
apps/web/src/components/ChatView.tsx
+9
-1
@@ -1,3 +1,4 @@
1
+import { workspaceAreaProps } from "../lib/workspaceFocus";
2
import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
3
import { queuedRunEditBlockedReason } from "@t3tools/client-runtime/queued-run-edit";
4
import { ScrollToEndButton, WorkspaceFileDropOverlay } from "./chat/TimelineOverlays";
@@ -707,6 +708,8 @@ export default function ChatView(props: ChatViewProps) {
708
const legendListRef = useRef<LegendListRef | null>(null);
709
const getTimelineScrollableNode = () => legendListRef.current?.getScrollableNode() ?? null;
710
const getTimelineScrollableNodeStable = useStableCallback(getTimelineScrollableNode);
711
+ const conversationArea = workspaceAreaProps("conversation", 1, "Conversation");
712
+ const composerArea = workspaceAreaProps("composer", 2, "Message input");
713
const [composerOverlayElement, setComposerOverlayElement] = useState<HTMLDivElement | null>(null);
714
const [composerTimelineInset, setComposerTimelineInset] = useState(0);
715
const composerTimelineInsetRef = useRef(0);
@@ -3173,6 +3176,7 @@ export default function ChatView(props: ChatViewProps) {
3176
)}
3177
data-chat-column-maximized-away={rightPanelMaximized ? "true" : "false"}
3178
data-chat-column
3179
+ inert={rightPanelMaximized}
3180
>
3181
<header
3182
ref={threadPanelPopoverAnchorRef}
@@ -3253,7 +3257,10 @@ export default function ChatView(props: ChatViewProps) {
3257
setThreadError={setThreadError}
3258
setThreadErrorBannerDismissTick={setThreadErrorBannerDismissTick}
3259
/>
3256
- <div className="relative flex min-h-0 flex-1 flex-col bg-background">
3260
+ <div
3261
+ {...conversationArea}
3262
+ className="relative flex min-h-0 flex-1 flex-col bg-background"
3263
+ >
3264
<ThreadTimeline
3265
threadDetailRef={routeThreadDetailRef}
3266
entriesInput={timelineEntriesInput}
@@ -3360,6 +3367,7 @@ export default function ChatView(props: ChatViewProps) {
3367
</div>
3368
3369
<div
3370
+ {...composerArea}
3371
ref={(overlay: HTMLDivElement | null) => {
3372
setComposerOverlayElement(overlay);
3373
attachFollowComposerOverlay(overlay);
apps/web/src/components/CommandPalette.tsx
+26
-1
@@ -67,6 +67,7 @@ import {
67
PaletteIcon,
68
RotateCcwIcon,
69
SettingsIcon,
70
+ MonitorIcon,
71
SquarePenIcon,
72
TextSearchIcon,
73
UserPlusIcon,
@@ -89,6 +90,10 @@ import { useDesktopLocalBootstraps } from "../connection/useDesktopLocalBootstra
90
import { useHandleNewThread } from "../hooks/useHandleNewThread";
91
import { useOpenPanelPullRequestUrl } from "../hooks/useOpenPanelPullRequestUrl";
92
import { copyThreadReference } from "../lib/copyThreadReference";
93
+import {
94
+ queueWorkspaceFocusFromPalette,
95
+ restoreWorkspaceFocusFromPalette,
96
+} from "../lib/workspaceFocus";
97
import {
98
composerPromptLink,
99
copyPromptLink,
@@ -132,6 +137,7 @@ import {
137
} from "../lib/projectPaths";
138
import {
139
dispatchCommandPalette,
140
+ getCommandPaletteReturnFocus,
141
useCommandPaletteMount,
142
useCommandPaletteStore,
143
} from "../commandPaletteStore";
@@ -326,8 +332,12 @@ function CommandPaletteDialog(props: {
332
data-palette-mode={props.mode}
333
data-testid="command-palette"
334
finalFocus={() => {
335
+ if (restoreWorkspaceFocusFromPalette()) return false;
336
+ const returnFocus = getCommandPaletteReturnFocus();
337
+ if (returnFocus === false) return false;
338
const composer = composerHandleRef?.current;
330
- if (!composer) return true;
339
+ // Behind the Settings modal the composer is inert and cannot take focus.
340
+ if (!composer || document.querySelector("[data-app-modal]")) return returnFocus;
341
composer.focusAtEnd();
342
return false;
343
}}
@@ -1507,6 +1517,21 @@ function OpenCommandPaletteDialog(props: {
1517
},
1518
});
1519
1520
+ for (const direction of [1, -1] as const) {
1521
+ const title = direction === 1 ? "Focus Next Workspace Area" : "Focus Previous Workspace Area";
1522
+ actionItems.push({
1523
+ kind: "action",
1524
+ value: `action:workspace-focus:${direction}`,
1525
+ title,
1526
+ searchTerms: [title, "accessibility", "navigation", "focus", "F6"],
1527
+ icon: <MonitorIcon className={ITEM_ICON_CLASS} />,
1528
+ shortcutCommand: direction === 1 ? "workspace.focusNext" : "workspace.focusPrevious",
1529
+ run: async () => {
1530
+ queueWorkspaceFocusFromPalette(direction);
1531
+ },
1532
+ });
1533
+ }
1534
+
1535
actionItems.push({
1536
kind: "action",
1537
value: "action:settings",
apps/web/src/components/DiffPanel.tsx
+1
@@ -655,6 +655,7 @@ export default function DiffPanel({
655
render={<Button size="xs" variant="secondary" />}
656
className="max-w-full"
657
aria-label={`Diff scope: ${selectedScopeLabel}`}
658
+ data-workspace-focus-default
659
>
660
<span className="truncate">{selectedScopeLabel}</span>
661
<ChevronDownIcon className="size-3.5 shrink-0 opacity-70" />
apps/web/src/components/LegacySidebar.tsx
+49
-7
@@ -1,3 +1,4 @@
1
+import { attachSidebarTree, SIDEBAR_TREE_PROPS } from "../lib/sidebarTree";
2
import { useSupportsMultiplePullRequests } from "~/hooks/useSupportsMultiplePullRequests";
3
import { resolveThreadCurrentPullRequestLink } from "@t3tools/client-runtime/thread-pull-requests";
4
import { Spinner } from "~/components/ui/spinner";
@@ -337,6 +338,7 @@ function buildThreadJumpLabelMap(input: {
338
}
339
340
interface SidebarThreadRowProps {
341
+ navigationParent?: string | undefined;
342
thread: SidebarThreadSummary;
343
orderedProjectThreadKeys: readonly string[];
344
isActive: boolean;
@@ -542,6 +544,16 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
544
startThreadRename(threadKey, thread.title);
545
};
546
const handleRowKeyDown = (event: React.KeyboardEvent) => {
547
+ if (event.target !== event.currentTarget) return;
548
+ if (
549
+ event.key === "F2" &&
550
+ renamingThreadKey !== threadKey &&
551
+ readEnvironmentScope(thread.environmentId, AuthOrchestrationOperateScope)
552
+ ) {
553
+ event.preventDefault();
554
+ startThreadRename(threadKey, thread.title);
555
+ return;
556
+ }
557
if (event.key !== "Enter" && event.key !== " ") return;
558
event.preventDefault();
559
navigateToThread(threadRef);
@@ -678,8 +690,11 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
690
>
691
<div
692
ref={isActive ? (node) => revealActiveRow(node, threadKey) : undefined}
681
- role="button"
682
- tabIndex={0}
693
+ role="treeitem"
694
+ tabIndex={-1}
695
+ data-sidebar-row={threadKey}
696
+ data-sidebar-parent={props.navigationParent}
697
+ aria-current={isActive ? "page" : undefined}
698
data-active={isActive}
699
data-slot="sidebar-menu-sub-button"
700
data-sidebar="menu-sub-button"
@@ -1002,6 +1017,7 @@ const SidebarProjectThreadList = memo(function SidebarProjectThreadList(
1017
1018
return (
1019
<SidebarMenuSub
1020
+ role="presentation"
1021
ref={attachThreadListAutoAnimateRef}
1022
className="mx-0.5 my-0 w-full translate-x-0 overflow-hidden empty:hidden sm:mx-1"
1023
>
@@ -1022,6 +1038,7 @@ const SidebarProjectThreadList = memo(function SidebarProjectThreadList(
1038
<SidebarThreadRow
1039
key={threadKey}
1040
thread={thread}
1041
+ navigationParent={projectExpanded ? `project:${projectKey}` : undefined}
1042
orderedProjectThreadKeys={orderedProjectThreadKeys}
1043
isActive={activeRouteThreadKey === threadKey}
1044
openPullRequestsInRightPanel={openPullRequestsInRightPanel}
@@ -1054,6 +1071,10 @@ const SidebarProjectThreadList = memo(function SidebarProjectThreadList(
1071
<SidebarMenuSubItem className="w-full">
1072
<SidebarMenuSubButton
1073
render={showMoreButtonRender}
1074
+ role="treeitem"
1075
+ tabIndex={-1}
1076
+ data-sidebar-row={`project:${projectKey}:more`}
1077
+ data-sidebar-parent={`project:${projectKey}`}
1078
data-thread-selection-safe
1079
size="sm"
1080
onClick={() => {
@@ -1071,6 +1092,10 @@ const SidebarProjectThreadList = memo(function SidebarProjectThreadList(
1092
<SidebarMenuSubItem className="w-full">
1093
<SidebarMenuSubButton
1094
render={showLessButtonRender}
1095
+ role="treeitem"
1096
+ tabIndex={-1}
1097
+ data-sidebar-row={`project:${projectKey}:less`}
1098
+ data-sidebar-parent={`project:${projectKey}`}
1099
data-thread-selection-safe
1100
size="sm"
1101
onClick={() => {
@@ -1400,9 +1425,12 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
1425
const handleProjectButtonClick = (event: React.MouseEvent<HTMLButtonElement>) => {
1426
if (suppressProjectClickForContextMenuRef.current) {
1427
suppressProjectClickForContextMenuRef.current = false;
1403
- event.preventDefault();
1404
- event.stopPropagation();
1405
- return;
1428
+ // A keyboard-made click (detail 0) never follows a context menu.
1429
+ if (event.detail !== 0) {
1430
+ event.preventDefault();
1431
+ event.stopPropagation();
1432
+ return;
1433
+ }
1434
}
1435
if (dragInProgressRef.current) {
1436
event.preventDefault();
@@ -2301,6 +2329,11 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
2329
className={isManualProjectSorting ? "cursor-grab active:cursor-grabbing" : undefined}
2330
{...(isManualProjectSorting && dragHandleProps ? dragHandleProps.attributes : {})}
2331
{...(isManualProjectSorting && dragHandleProps ? dragHandleProps.listeners : {})}
2332
+ role="treeitem"
2333
+ tabIndex={-1}
2334
+ data-sidebar-row={`project:${project.projectKey}`}
2335
+ aria-expanded={projectExpanded}
2336
+ aria-label={project.displayName}
2337
onPointerDownCapture={handleProjectButtonPointerDownCapture}
2338
onClick={handleProjectButtonClick}
2339
onKeyDown={handleProjectButtonKeyDown}
@@ -2380,6 +2413,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
2413
<button
2414
type="button"
2415
aria-label={`Create new thread in ${project.displayName}`}
2416
+ data-sidebar-action-for={`project:${project.projectKey}`}
2417
data-testid="new-thread-button"
2418
className={SIDEBAR_ICON_ACTION_BUTTON_CLASS}
2419
onClick={handleCreateThreadClick}
@@ -2878,6 +2912,14 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
2912
projectsLength,
2913
} = props;
2914
2915
+ const attachTreeRef = (node: HTMLUListElement | null) => {
2916
+ attachProjectListAutoAnimateRef(node);
2917
+ const dispose = attachSidebarTree(node);
2918
+ return () => {
2919
+ dispose?.();
2920
+ attachProjectListAutoAnimateRef(null);
2921
+ };
2922
+ };
2923
const handleProjectSortOrderChange = (sortOrder: SidebarProjectSortOrder) => {
2924
updateClientSettings({ sidebarProjectSortOrder: sortOrder });
2925
};
@@ -2970,7 +3012,7 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
3012
onDragEnd={handleProjectDragEnd}
3013
onDragCancel={handleProjectDragCancel}
3014
>
2973
- <SidebarMenu>
3015
+ <SidebarMenu {...SIDEBAR_TREE_PROPS} ref={attachSidebarTree}>
3016
<SortableContext items={sortedProjectKeys} strategy={verticalListSortingStrategy}>
3017
{sortedProjects.map((project) => (
3018
<SortableProjectItem key={project.projectKey} projectId={project.projectKey}>
@@ -3006,7 +3048,7 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
3048
</SidebarMenu>
3049
</DndContext>
3050
) : (
3009
- <SidebarMenu ref={attachProjectListAutoAnimateRef}>
3051
+ <SidebarMenu {...SIDEBAR_TREE_PROPS} ref={attachTreeRef}>
3052
{sortedProjects.map((project) => (
3053
<SidebarProjectListRow
3054
key={project.projectKey}
apps/web/src/components/NoProjectsHero.tsx
+7
-1
@@ -1,3 +1,4 @@
1
+import { workspaceAreaProps } from "../lib/workspaceFocus";
2
import { MessageSquareDashedIcon, PlusIcon } from "lucide-react";
3
4
import { openCommandPalette } from "../commandPaletteBus";
@@ -10,12 +11,17 @@ import { SidebarInset } from "./ui/sidebar";
11
import { WorkspacePageHeader } from "./WorkspacePageHeader";
12
13
export function NoProjectsHero() {
14
+ const contentArea = workspaceAreaProps("home", 1, "Home");
15
const primaryEnvironmentId = usePrimaryEnvironmentId();
16
const { scratchEnvironmentId, startScratchThread } = useScratchProject();
17
const scratchTargetEnvironmentId = scratchEnvironmentId(primaryEnvironmentId);
18
19
return (
18
- <SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none">
20
+ <SidebarInset
21
+ {...contentArea}
22
+ role="main"
23
+ className="h-dvh min-h-0 overflow-hidden overscroll-y-none"
24
+ >
25
<div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-x-hidden bg-background">
26
{/* The desktop window only moves where CSS opts in, so keep a titlebar strip. */}
27
{isElectron ? <WorkspacePageHeader electron /> : null}
apps/web/src/components/ReopenClosedViewShortcut.tsx
+2
@@ -44,6 +44,8 @@ import {
44
import { toastManager } from "./ui/toast";
45
46
const PREVIEW_FORWARDED_LAYOUT_COMMANDS = [
47
+ "workspace.focusNext",
48
+ "workspace.focusPrevious",
49
"sidebar.toggle",
50
"rightPanel.toggle",
51
"rightPanel.toggleMaximized",
apps/web/src/components/RightPanelTabs.tsx
+9
-5
@@ -436,7 +436,7 @@ function RightPanelEmptyState(props: {
436
437
return (
438
<div
439
- ref={focusOnMount}
439
+ data-workspace-focus-default
440
tabIndex={0}
441
onKeyDown={handleKeyDown}
442
aria-label="Open a surface"
@@ -748,10 +748,6 @@ function PullRequestSurfaceIcon({
748
return <presentation.Icon className={cn("size-3 shrink-0", presentation.toneClassName)} />;
749
}
750
751
-function focusOnMount(node: HTMLDivElement | null) {
752
- node?.focus();
753
-}
754
-
751
function SortableTabList(props: {
752
surfaces: readonly RightPanelSurface[];
753
onMove: ((surfaceId: string, toIndex: number) => void) | undefined;
@@ -945,6 +941,7 @@ function RightPanelTab(
941
}
942
943
export function RightPanelTabs(props: RightPanelTabsProps) {
944
+ const focusedSurface = props.surfaces.find((surface) => surface.id === props.activeSurfaceId);
945
const ownsDesktopTitleBar = isElectron && props.mode === "inline";
946
const browserProfiles = useBrowserDefaults().profiles;
947
const { resolvedTheme } = useTheme();
@@ -1226,6 +1223,13 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
1223
1224
return (
1225
<PreviewPanelShell
1226
+ workspaceArea
1227
+ workspaceFocusKey={`panel:${props.environmentId}:${props.activeSurfaceId ?? "empty"}`}
1228
+ workspaceLabel={
1229
+ focusedSurface
1230
+ ? `Workspace panel: ${surfaceTitle(focusedSurface, props.previewSessions, props.terminalLabelsById)}`
1231
+ : "Workspace panel"
1232
+ }
1233
mode={props.mode}
1234
{...(props.maximized !== undefined ? { maximized: props.maximized } : {})}
1235
{...(props.open !== undefined ? { open: props.open } : {})}
apps/web/src/components/Sidebar.tsx
+23
-4
@@ -1,3 +1,4 @@
1
+import { attachSidebarTree, SIDEBAR_TREE_PROPS } from "../lib/sidebarTree";
2
import { type EnvironmentId, type ScopedProjectRef } from "@t3tools/contracts";
3
import type { EnvironmentServerConfig } from "@t3tools/client-runtime/connection";
4
import { ThreadContextDragGhost } from "./chat/ThreadContextDragGhost";
@@ -1540,6 +1541,15 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
1541
};
1542
};
1543
1544
+ const attachTreeRef = (node: HTMLUListElement) => {
1545
+ const detachMotion = attachListMotionRef(node);
1546
+ const detachTree = attachSidebarTree(node);
1547
+ return () => {
1548
+ detachTree?.();
1549
+ detachMotion();
1550
+ };
1551
+ };
1552
+
1553
const isContextDrag = dragState?.contextDrag === true || dragState?.activeSection === "working";
1554
const dragTargetSection = isContextDrag ? null : (dragState?.targetSection ?? null);
1555
const finishThreadDrag = (started: boolean) => {
@@ -3034,10 +3044,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
3044
>
3045
<SortableContext items={sortableIds} strategy={sidebarSortingStrategy}>
3046
<ul
3037
- ref={attachListMotionRef}
3038
- // Presentation flattens VoiceOver's list interaction boundary while preserving descendant
3039
- // controls.
3040
- role="presentation"
3047
+ {...SIDEBAR_TREE_PROPS}
3048
+ ref={attachTreeRef}
3049
className={cn(
3050
"relative flex flex-col gap-px",
3051
sidebarListItems.length > 0 && "flex-1",
@@ -3067,6 +3075,13 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
3075
}
3076
thread={thread}
3077
variant={rowVariant}
3078
+ navigationParent={
3079
+ section === "working" ||
3080
+ section === "snoozed" ||
3081
+ section === "settled"
3082
+ ? `shelf:${section}`
3083
+ : undefined
3084
+ }
3085
variantAction={
3086
section === "snoozed"
3087
? "unsnooze"
@@ -3295,6 +3310,10 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
3310
<li className="list-none">
3311
<button
3312
type="button"
3313
+ role="treeitem"
3314
+ tabIndex={-1}
3315
+ data-sidebar-row="settled:more"
3316
+ data-sidebar-parent="shelf:settled"
3317
disabled={olderSettledShelf.loading}
3318
onClick={() => {
3319
olderSettledShelf.retry();
apps/web/src/components/ThreadTerminalDrawer.tsx
+5
@@ -1,3 +1,4 @@
1
+import { workspaceAreaProps } from "../lib/workspaceFocus";
2
import { useAtomMount, useAtomValue } from "@effect/atom-react";
3
import {
4
isAtomCommandInterrupted,
@@ -686,6 +687,7 @@ function TerminalSessionViewport({
687
terminal.setTheme(terminalThemeFromApp(mount));
688
setupTerminal = terminal;
689
terminalRef.current = terminal;
690
+ terminal.input.setAttribute("data-workspace-focus-default", "");
691
terminal.input.readOnly = !hasTerminalWriteAccess();
692
// Reapply font settings hydrated during loading, when terminalRef was null.
693
const currentFont = terminalFontRef.current;
@@ -1438,6 +1440,7 @@ export default function ThreadTerminalDrawer({
1440
terminalLaunchLocationsById,
1441
}: ThreadTerminalDrawerProps) {
1442
const canOperateTerminal = useEnvironmentScope(threadRef.environmentId, AuthTerminalOperateScope);
1443
+ const terminalArea = workspaceAreaProps("terminal", 5, "Terminal");
1444
const isPanel = mode === "panel";
1445
const [advancedTypography] = useLocalStorage(
1446
TYPOGRAPHY_ADVANCED_STORAGE_KEY,
@@ -1722,6 +1725,7 @@ export default function ThreadTerminalDrawer({
1725
return (
1726
<aside
1727
ref={drawerRef}
1728
+ {...(!isPanel && visible ? terminalArea : {})}
1729
data-thread-terminal-drawer
1730
data-terminal-owner={isPanel ? "right-panel" : "drawer"}
1731
className={cn(
@@ -1758,6 +1762,7 @@ export default function ThreadTerminalDrawer({
1762
return (
1763
<aside
1764
ref={drawerRef}
1765
+ {...(!isPanel && visible ? terminalArea : {})}
1766
data-thread-terminal-drawer
1767
data-terminal-owner={isPanel ? "right-panel" : "drawer"}
1768
className={cn(
apps/web/src/components/chat/QueuedRunsControl.browser.test.tsx
+31
@@ -40,6 +40,7 @@ vi.mock(import("../../assets/assetUrls"), async (importOriginal) => ({
40
resources.map((resource) => `https://assets.test/${resource.attachmentId}`)) as never,
41
}));
42
43
+import "~/index.css";
44
import { render as renderUi } from "../../../test/render";
45
import { QueuedRunsControl } from "./QueuedRunsControl";
46
@@ -172,3 +173,33 @@ it("shows who sent a queued message and folds automation and agent prompts", asy
173
await expect.element(page.getByText("Sent by T3 Code")).toBeVisible();
174
await expect.element(page.getByText("Continue where you left off.")).toBeVisible();
175
});
176
+
177
+it("stays inside the timeline scroller instead of growing the chat column", async () => {
178
+ setup();
179
+ state.projection = { projection: { messages: [] } };
180
+ state.workflow = {
181
+ activeRun: { id: "run:active" },
182
+ canPromoteToSteer: true,
183
+ queuedRuns: [
184
+ {
185
+ run: { id: "run:queued", userMessageId: "message:queued" },
186
+ text: "Later",
187
+ attachments: [],
188
+ },
189
+ ],
190
+ };
191
+ // Mirrors ChatView: a scrollable column, a positioned wrapper, then a non-positioned scroller.
192
+ await using screen = await renderUi(
193
+ <div data-testid="column" style={{ height: 200, overflowY: "auto" }}>
194
+ <div style={{ position: "relative", height: "100%" }}>
195
+ <div style={{ height: "100%", overflowY: "auto" }}>
196
+ <div style={{ height: 1000 }} />
197
+ <QueuedRunsControl {...baseProps} />
198
+ </div>
199
+ </div>
200
+ </div>,
201
+ );
202
+ await expect.element(page.getByText("Later", { exact: true })).toBeInTheDocument();
203
+ const column = screen.getByTestId("column").element();
204
+ expect(column.scrollHeight).toBe(column.clientHeight);
205
+});
apps/web/src/components/chat/QueuedRunsControl.tsx
+2
-1
@@ -229,7 +229,8 @@ export function QueuedRunsControl({
229
<section
230
aria-label={`${items.length} queued message${items.length === 1 ? "" : "s"}`}
231
data-thread-queue="true"
232
- className="mx-auto flex w-full max-w-(--chat-content-max-width) flex-col gap-2 pb-4"
232
+ // Anchors the sr-only live region; unanchored, it escapes the timeline scroller and makes the chat column scroll.
233
+ className="relative mx-auto flex w-full max-w-(--chat-content-max-width) flex-col gap-2 pb-4"
234
>
235
<span className="sr-only" aria-live="polite">
236
{items.length} queued
apps/web/src/components/chat/ThreadDetailsCard.tsx
+12
-1
@@ -1,3 +1,4 @@
1
+import { workspaceAreaProps } from "../../lib/workspaceFocus";
2
import { useLayoutEffect, useState, type ReactNode, type RefObject } from "react";
3
import type { ScopedThreadRef } from "@t3tools/contracts";
4
import { ScrollArea } from "../ui/scroll-area";
@@ -10,6 +11,7 @@ import {
11
resolveThreadDetailsCardDensity,
12
} from "./threadDetailsCardLayout";
13
import { observeResize } from "../../lib/observeResize";
14
+import { requestWorkspaceFocus } from "../../lib/workspaceFocus";
15
16
export function ThreadDetailsCard({
17
threadRef,
@@ -22,6 +24,7 @@ export function ThreadDetailsCard({
24
handle: ReturnType<typeof PopoverCreateHandle>;
25
children: (density: "full" | "compact" | "essential") => ReactNode;
26
}) {
27
+ const detailsArea = workspaceAreaProps("details", 3, "Thread details");
28
const canvas = useChatCanvas();
29
const preferredPlacement = canvas?.preferredDetailsCard ?? null;
30
const placement = canvas?.detailsCardPlacement ?? null;
@@ -133,7 +136,8 @@ export function ThreadDetailsCard({
136
>
137
{placement && inlineOpen ? (
138
<aside
136
- aria-label="Thread details"
139
+ {...detailsArea}
140
+ data-workspace-focus-key={`details:${threadRef.environmentId}:${threadRef.threadId}`}
141
// Skip the return transition to avoid overlapping the rising preview.
142
className={cn(
143
"absolute z-20",
@@ -155,6 +159,13 @@ export function ThreadDetailsCard({
159
mounted, because its exit animation never finishes. Staying in the tree
160
lets it close cleanly when the card switches inline. */}
161
<PopoverPopup
162
+ {...(mode === "popover" ? detailsArea : {})}
163
+ role="dialog"
164
+ data-workspace-focus-key={`details:${threadRef.environmentId}:${threadRef.threadId}`}
165
+ initialFocus={() => {
166
+ requestWorkspaceFocus({ area: "details" });
167
+ return false;
168
+ }}
169
anchor={anchor}
170
align="end"
171
// Account for the find panel's 8px card padding.
apps/web/src/components/chat/useRightPanelActions.ts
+15
-1
@@ -15,9 +15,11 @@ import { useDiffPanelStore } from "../../diffPanelStore";
15
import { type ThreadPanelPresentation } from "../../rightPanelLayout";
16
import {
17
selectActiveRightPanel,
18
+ selectThreadPanelOpen,
19
type RightPanelSurface,
20
useRightPanelStore,
21
} from "../../rightPanelStore";
22
+import { requestWorkspaceContentFocus, requestWorkspaceFocus } from "../../lib/workspaceFocus";
23
import { setActivePreviewTab } from "../../previewStateStore";
24
import { BrowserSettingsReadError } from "../../browser/openFileInPreview";
25
import { addBrowserSurface } from "../preview/addBrowserSurface";
@@ -224,11 +226,23 @@ export function useRightPanelActions(input: RightPanelActionsInput) {
226
const toggleRightPanelStable = useStableCallback(toggleRightPanel);
227
const toggleThreadPanel = () => {
228
if (!activeThreadRef) return;
227
- useRightPanelStore.getState().toggleThreadPanel(activeThreadRef, threadPanelPresentation);
229
+ const store = useRightPanelStore.getState();
230
+ if (threadPanelPresentation === "inline") {
231
+ const open = selectThreadPanelOpen(
232
+ store.threadPanelVisibilityByThreadKey,
233
+ activeThreadRef,
234
+ "inline",
235
+ );
236
+ if (!open) requestWorkspaceFocus({ area: "details" });
237
+ else if (document.activeElement?.closest('[data-workspace-area="details"]'))
238
+ requestWorkspaceContentFocus();
239
+ }
240
+ store.toggleThreadPanel(activeThreadRef, threadPanelPresentation);
241
};
242
const toggleThreadPanelStable = useStableCallback(toggleThreadPanel);
243
const toggleRightPanelMaximized = () => {
244
if (!canMaximizeRightPanel || !activeThreadRef) return;
245
+ if (!rightPanelMaximized) requestWorkspaceFocus({ area: "panel" });
246
useRightPanelStore.getState().setMaximized(activeThreadRef, !rightPanelMaximized);
247
};
248
const toggleRightPanelMaximizedStable = useStableCallback(toggleRightPanelMaximized);
apps/web/src/components/files/FileBrowserPanel.tsx
+1
@@ -90,6 +90,7 @@ function FileSearchField(props: {
90
value={props.value}
91
aria-label={props.ariaLabel}
92
placeholder="Search files"
93
+ data-workspace-focus-default
94
spellCheck={false}
95
onChange={(event) => props.onValueChange(event.target.value)}
96
onKeyDown={(event) => {
apps/web/src/components/preview/PreviewChromeRow.tsx
+2
@@ -175,6 +175,8 @@ export function PreviewChromeRow({
175
}
176
}}
177
placeholder="Search or enter URL"
178
+ aria-label="Search or enter URL"
179
+ data-workspace-focus-default
180
spellCheck={false}
181
disabled={inputDisabled}
182
data-preview-url-input
apps/web/src/components/preview/PreviewPanelShell.tsx
+8
@@ -4,6 +4,7 @@ import {
4
usePreviewPanelInlineSize,
5
} from "~/hooks/usePreviewPanelInlineSize";
6
import { RESIZABLE_WIDTH_PROPERTY } from "~/hooks/useResizableWidth";
7
+import { workspaceAreaProps } from "../../lib/workspaceFocus";
8
import { cn } from "~/lib/utils";
9
10
import { RightPanelResizeHandle } from "./RightPanelResizeHandle";
@@ -11,6 +12,9 @@ import { RightPanelResizeHandle } from "./RightPanelResizeHandle";
12
export type PreviewPanelMode = "inline" | "sheet" | "sidebar" | "embedded";
13
14
interface PreviewPanelShellProps {
15
+ workspaceArea?: boolean;
16
+ workspaceFocusKey?: string;
17
+ workspaceLabel?: string;
18
mode: PreviewPanelMode;
19
maximized?: boolean;
20
inlineSize?: PreviewPanelInlineSize;
@@ -41,6 +45,7 @@ function ResizablePreviewPanelShell(props: PreviewPanelShellProps) {
45
function PreviewPanelShellFrame(
46
props: PreviewPanelShellProps & { inlineSize: PreviewPanelInlineSize },
47
) {
48
+ const panelArea = workspaceAreaProps("panel", 4, props.workspaceLabel ?? "Workspace panel");
49
const isInline = props.mode === "inline";
50
const collapsible = isInline && props.open !== undefined;
51
const open = props.open ?? true;
@@ -112,6 +117,9 @@ function PreviewPanelShellFrame(
117
return (
118
<div
119
ref={attachHost}
120
+ {...(props.workspaceArea ? panelArea : {})}
121
+ data-workspace-focus-key={props.workspaceFocusKey}
122
+ data-workspace-unavailable={collapsible && !open ? "true" : undefined}
123
className={cn(
124
"relative flex h-full min-h-0 min-w-0 max-w-full flex-col self-stretch bg-background",
125
isInline
apps/web/src/components/pullRequest/PullRequestsColumn.tsx
+4
@@ -13,6 +13,7 @@ import {
13
} from "../WorkspaceBreadcrumb";
14
import { WorkspacePageContainer } from "../WorkspacePageContainer";
15
import { WorkspacePageHeader } from "../WorkspacePageHeader";
16
+import { workspaceAreaProps } from "../../lib/workspaceFocus";
17
import { PullRequestCompactFilterMenu } from "./PullRequestCompactFilterMenu";
18
import type { PullRequestFilterOption } from "./PullRequestListFilters";
19
import { INVOLVEMENT_TABS, STATE_TABS } from "./pullRequestListOptions";
@@ -108,6 +109,7 @@ export function PullRequestsColumn({
109
listBody: ReactNode;
110
scrollRef: RefObject<HTMLDivElement | null>;
111
}) {
112
+ const contentArea = workspaceAreaProps("pull-requests", 1, "Pull requests");
113
const markerRef = useRef<HTMLDivElement | null>(null);
114
const [condensed, setCondensed] = useState(false);
115
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- IntersectionObserver on the scroll marker condenses the topbar
@@ -158,6 +160,8 @@ export function PullRequestsColumn({
160
161
return (
162
<div
163
+ {...contentArea}
164
+ inert={maximizedAway}
165
className={cn(
166
"@container/pr-list flex min-h-0 min-w-0 flex-col overflow-x-hidden bg-background",
167
maximizedAway ? "w-0 flex-none" : "flex-1",
apps/web/src/components/settings/KeybindingsSettings.logic.ts
+2
@@ -357,6 +357,8 @@ export function buildKeybindingCommandOptions(
357
}
358
359
export function commandLabel(command: KeybindingCommand): string {
360
+ if (command === "workspace.focusNext") return "Focus Next Workspace Area";
361
+ if (command === "workspace.focusPrevious") return "Focus Previous Workspace Area";
362
if (command === "composer.sendAlternate") return "Composer: Opposite Queue or Steer Action";
363
if (command === "composer.sendBackground") return "Composer: Start in Background";
364
if (command === "composer.sendAndNewThread") return "Composer: Send and Start New Thread";
apps/web/src/components/settings/SettingsSidebarNav.tsx
+64
-40
@@ -56,6 +56,8 @@ import {
56
} from "./settingsSearch";
57
import { useAvailableSettingsSearchItems } from "./useAvailableSettingsSearchItems";
58
import { validateSettingsScopeSearch } from "./settingsScope";
59
+import { useSettingsSectionNavigation } from "./useSettingsSectionNavigation";
60
+import { workspaceAreaProps } from "../../lib/workspaceFocus";
61
62
const SnapShotIcon = createLucideIcon("snap-shot", [
63
[
@@ -123,11 +125,18 @@ function SettingsSectionIcon({ to }: { to: SettingsPath }) {
125
}
126
127
export function SettingsSidebarNav({ pathname }: { pathname: string }) {
128
+ const navArea = workspaceAreaProps("settings-nav", 0, "Settings sections");
129
const navigate = useNavigate();
130
const currentHash = useLocation({ select: (location) => location.hash });
131
const currentSearch = useLocation({ select: (location) => location.search });
132
const scopeSearch = validateSettingsScopeSearch(currentSearch);
133
const activePath = SETTINGS_DETAIL_PAGE_PARENTS[pathname] ?? pathname;
134
+ const navPaths = SETTINGS_NAV_GROUPS.flatMap((group) => group.paths);
135
+ const sectionNavigation = useSettingsSectionNavigation(
136
+ navPaths.find((to) => activePath === to || activePath.startsWith(`${to}/`)) ??
137
+ navPaths[0] ??
138
+ "",
139
+ );
140
const searchInputRef = useRef<HTMLInputElement>(null);
141
const [query, setQuery] = useState("");
142
// Below md the nav is an icon rail; searching expands it over the page.
@@ -242,7 +251,8 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) {
251
252
return (
253
<nav
245
- aria-label="Settings sections"
254
+ {...navArea}
255
+ role="navigation"
256
className={cn(
257
"flex w-60 shrink-0 flex-col border-e bg-sidebar text-sidebar-foreground max-md:w-14",
258
compactSearchOpen &&
@@ -362,46 +372,60 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) {
372
</SidebarMenuItem>
373
</SidebarMenu>
374
)}
365
- {SETTINGS_NAV_GROUPS.map((group, index) => (
366
- <div
367
- key={group.heading ?? index}
368
- role="group"
369
- aria-label={group.heading ?? undefined}
370
- 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"
371
- >
372
- {group.heading ? (
373
- <h3
374
- className={cn(
375
- "px-2 text-xs font-medium text-sidebar-muted-foreground/80",
376
- !compactSearchOpen && "max-md:hidden",
377
- )}
378
- >
379
- {group.heading}
380
- </h3>
381
- ) : null}
382
- <SidebarMenu>
383
- {group.paths.map((to) => {
384
- const Icon = SETTINGS_SECTION_ICONS[to];
385
- const isActive = activePath === to || activePath.startsWith(`${to}/`);
386
- return (
387
- <SidebarMenuItem key={to}>
388
- <SidebarMenuButton
389
- isActive={isActive}
390
- onClick={() => handleSectionClick(to)}
391
- >
392
- <Icon />
393
- <span
394
- className={cn("truncate", !compactSearchOpen && "max-md:sr-only")}
375
+ <div
376
+ {...sectionNavigation.containerProps}
377
+ role="tree"
378
+ aria-label="Settings sections"
379
+ className="flex flex-col gap-4"
380
+ >
381
+ {SETTINGS_NAV_GROUPS.map((group, index) => (
382
+ <div
383
+ key={group.heading ?? index}
384
+ role="group"
385
+ aria-label={group.heading ?? undefined}
386
+ 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"
387
+ >
388
+ {group.heading ? (
389
+ // The group carries this label; a heading is not a valid tree child.
390
+ <h3
391
+ aria-hidden="true"
392
+ className={cn(
393
+ "px-2 text-xs font-medium text-sidebar-muted-foreground/80",
394
+ !compactSearchOpen && "max-md:hidden",
395
+ )}
396
+ >
397
+ {group.heading}
398
+ </h3>
399
+ ) : null}
400
+ <SidebarMenu role="presentation">
401
+ {group.paths.map((to) => {
402
+ const Icon = SETTINGS_SECTION_ICONS[to];
403
+ const isActive = activePath === to || activePath.startsWith(`${to}/`);
404
+ return (
405
+ <SidebarMenuItem key={to} role="presentation">
406
+ <SidebarMenuButton
407
+ data-settings-section={to}
408
+ role="treeitem"
409
+ tabIndex={sectionNavigation.tabIndexFor(to)}
410
+ aria-selected={isActive}
411
+ aria-current={isActive ? "page" : undefined}
412
+ isActive={isActive}
413
+ onClick={() => handleSectionClick(to)}
414
>
396
- {SETTINGS_SECTION_LABELS[to]}
397
- </span>
398
- </SidebarMenuButton>
399
- </SidebarMenuItem>
400
- );
401
- })}
402
- </SidebarMenu>
403
- </div>
404
- ))}
415
+ <Icon />
416
+ <span
417
+ className={cn("truncate", !compactSearchOpen && "max-md:sr-only")}
418
+ >
419
+ {SETTINGS_SECTION_LABELS[to]}
420
+ </span>
421
+ </SidebarMenuButton>
422
+ </SidebarMenuItem>
423
+ );
424
+ })}
425
+ </SidebarMenu>
426
+ </div>
427
+ ))}
428
+ </div>
429
</div>
430
)}
431
</div>
apps/web/src/components/settings/useSettingsSectionNavigation.ts
new
+56
@@ -0,0 +1,56 @@
1
+import { useState, type FocusEvent, type KeyboardEvent } from "react";
2
+
3
+const SECTION = "[data-settings-section]";
4
+
5
+/**
6
+ * Settings sections share one Tab stop, and arrows move focus without opening a section.
7
+ * The Tab stop follows the last focused section until the open section changes.
8
+ */
9
+export function useSettingsSectionNavigation(currentSection: string) {
10
+ const [focused, setFocused] = useState<{ section: string; page: string } | null>(null);
11
+ const tabStop = focused?.page === currentSection ? focused.section : currentSection;
12
+ const remember = (element: HTMLElement) => {
13
+ const section = element.dataset.settingsSection;
14
+ if (section) setFocused({ section, page: currentSection });
15
+ };
16
+ const onFocus = (event: FocusEvent<HTMLElement>) => {
17
+ if (event.target instanceof HTMLElement && event.target.matches(SECTION))
18
+ remember(event.target);
19
+ };
20
+ const onKeyDown = (event: KeyboardEvent<HTMLElement>) => {
21
+ if (
22
+ event.defaultPrevented ||
23
+ event.altKey ||
24
+ event.ctrlKey ||
25
+ event.metaKey ||
26
+ !(event.target instanceof HTMLElement) ||
27
+ !event.target.matches(SECTION)
28
+ )
29
+ return;
30
+ // Every section is a root leaf; Left and Right have no tree action.
31
+ if (event.key === "ArrowLeft" || event.key === "ArrowRight") {
32
+ event.preventDefault();
33
+ return;
34
+ }
35
+ const items = Array.from(event.currentTarget.querySelectorAll<HTMLElement>(SECTION));
36
+ const index = items.indexOf(event.target);
37
+ const next =
38
+ event.key === "ArrowDown"
39
+ ? Math.min(index + 1, items.length - 1)
40
+ : event.key === "ArrowUp"
41
+ ? Math.max(index - 1, 0)
42
+ : event.key === "Home"
43
+ ? 0
44
+ : event.key === "End"
45
+ ? items.length - 1
46
+ : undefined;
47
+ const target = next === undefined ? undefined : items[next];
48
+ if (!target) return;
49
+ event.preventDefault();
50
+ remember(target);
51
+ target.scrollIntoView({ block: "nearest" });
52
+ target.focus({ preventScroll: true });
53
+ };
54
+ const tabIndexFor = (section: string) => (section === tabStop ? 0 : -1);
55
+ return { containerProps: { onFocus, onKeyDown }, tabIndexFor };
56
+}
apps/web/src/components/sidebar/SidebarDraftBlock.tsx
+3
-2
@@ -81,8 +81,9 @@ const SidebarDraftRow = memo(function SidebarDraftRow(props: {
81
return (
82
<li className="list-none py-0.5">
83
<div
84
- role="button"
85
- tabIndex={0}
84
+ role="treeitem"
85
+ tabIndex={-1}
86
+ data-sidebar-row={`draft:${draftId}`}
87
aria-label={accessibility.label}
88
aria-current={accessibility.current}
89
data-testid="sidebar-draft-row"
apps/web/src/components/sidebar/SidebarListMarkers.tsx
+3
@@ -128,6 +128,9 @@ export function SidebarSectionHeader(props: {
128
<SidebarThreadUndoNotice className="absolute inset-x-0 bottom-full bg-sidebar surface-grain" />
129
) : null}
130
<CollapsibleSectionHeader
131
+ role="treeitem"
132
+ tabIndex={-1}
133
+ data-sidebar-row={`shelf:${shelf}`}
134
onClick={props.toggle.onToggle}
135
expanded={props.toggle.expanded}
136
tone={props.isDropTarget ? "accent" : props.dragging ? "emphasized" : "muted"}
apps/web/src/components/sidebar/SidebarThreadRow.tsx
+18
-4
@@ -513,6 +513,7 @@ const dropVerbBadge: Record<SidebarDropVerb, ReactNode> = {
513
type SidebarThreadRowProps = {
514
thread: SidebarThreadSummary;
515
variant: "card" | "slim";
516
+ navigationParent?: string | undefined;
517
variantAction: SidebarSweepAction;
518
settlementSupported: boolean;
519
snoozeSupported: boolean;
@@ -810,6 +811,15 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
811
};
812
const handleKeyDown = (event: ReactKeyboardEvent) => {
813
if (event.target !== event.currentTarget) return;
814
+ if (
815
+ event.key === "F2" &&
816
+ !isRenaming &&
817
+ readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope)
818
+ ) {
819
+ event.preventDefault();
820
+ onStartRename(threadRef, thread.title);
821
+ return;
822
+ }
823
if (event.key !== "Enter" && event.key !== " ") return;
824
event.preventDefault();
825
onThreadActivate(threadRef);
@@ -1105,8 +1115,10 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
1115
render={
1116
<div
1117
ref={rowRef}
1108
- role="button"
1109
- tabIndex={0}
1118
+ role="treeitem"
1119
+ tabIndex={-1}
1120
+ data-sidebar-row={threadKey}
1121
+ data-sidebar-parent={props.navigationParent}
1122
aria-label={accessibility.label}
1123
aria-current={accessibility.current}
1124
data-testid="sidebar-row-slim"
@@ -1274,8 +1286,10 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
1286
render={
1287
<div
1288
ref={rowRef}
1277
- role="button"
1278
- tabIndex={0}
1289
+ role="treeitem"
1290
+ tabIndex={-1}
1291
+ data-sidebar-row={threadKey}
1292
+ data-sidebar-parent={props.navigationParent}
1293
aria-label={accessibility.label}
1294
aria-current={accessibility.current}
1295
data-testid="sidebar-row-card"
apps/web/src/components/ui/sidebar.tsx
+6
-2
@@ -21,6 +21,7 @@ import { useMediaQuery } from "~/hooks/useMediaQuery";
21
import { setLocalStorageItem } from "~/hooks/useLocalStorage";
22
import { resolveSidebarState, type ResponsiveSidebarState } from "./sidebarState";
23
import * as Schema from "effect/Schema";
24
+import { announceSidebarVisibility } from "~/lib/accessibilityAnnouncements";
25
26
const SIDEBAR_COOKIE_NAME = "sidebar_state";
27
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7;
@@ -144,7 +145,10 @@ function createSidebarOpenStore(defaultOpen: boolean) {
145
for (const listener of collapseListeners) listener();
146
moveFocusOutOfCollapsingSidebar();
147
}
147
- if (open !== state.open) publish({ ...state, open });
148
+ if (open !== state.open) {
149
+ if (!isMobileViewport()) announceSidebarVisibility(open);
150
+ publish({ ...state, open });
151
+ }
152
void persistSidebarOpen(open);
153
};
154
const setOpenMobile = (openMobile: boolean) => {
@@ -315,7 +319,7 @@ function Sidebar({
319
}
320
>
321
<SheetHeader className="sr-only">
318
- <SheetTitle>Sidebar</SheetTitle>
322
+ <SheetTitle>{props["aria-label"] ?? "Sidebar"}</SheetTitle>
323
<SheetDescription>Displays the mobile sidebar.</SheetDescription>
324
</SheetHeader>
325
<div
apps/web/src/contextMenuFallback.keyboard.browser.test.ts
new
+106
@@ -0,0 +1,106 @@
1
+import { expect, it } from "vite-plus/test";
2
+import {
3
+ dismissContextMenu,
4
+ isContextMenuOpen,
5
+ showContextMenuFallback,
6
+} from "./contextMenuFallback";
7
+
8
+const items = [
9
+ { id: "heading", label: "Thread actions", header: true },
10
+ { id: "disabled", label: "Unavailable", disabled: true },
11
+ { id: "rename", label: "Rename" },
12
+ { id: "pin", label: "Pinned", checked: true, separatorBefore: true },
13
+ {
14
+ id: "copy",
15
+ label: "Copy",
16
+ children: [
17
+ { id: "copy-unavailable", label: "Unavailable copy", disabled: true },
18
+ { id: "path", label: "Path" },
19
+ { id: "branch", label: "Branch" },
20
+ ],
21
+ },
22
+];
23
+
24
+function setup() {
25
+ const origin = document.createElement("button");
26
+ origin.textContent = "Selected thread";
27
+ document.body.append(origin);
28
+ origin.focus();
29
+ return {
30
+ origin,
31
+ [Symbol.dispose]() {
32
+ dismissContextMenu();
33
+ origin.remove();
34
+ },
35
+ };
36
+}
37
+
38
+function press(key: string, shiftKey = false) {
39
+ const event = new KeyboardEvent("keydown", { key, shiftKey, bubbles: true, cancelable: true });
40
+ document.activeElement!.dispatchEvent(event);
41
+ return event;
42
+}
43
+
44
+const label = () => document.activeElement?.textContent;
45
+
46
+it("starts a keyboard-opened menu on its first action and wraps through enabled actions", () => {
47
+ using _fixture = setup();
48
+ void showContextMenuFallback(items);
49
+ expect(label()).toBe("Rename");
50
+ press("ArrowUp");
51
+ expect(label()).toBe("Copy");
52
+ press("ArrowDown");
53
+ expect(label()).toBe("Rename");
54
+ press("End");
55
+ expect(label()).toBe("Copy");
56
+ press("Home");
57
+ expect(label()).toBe("Rename");
58
+});
59
+
60
+it("opens and cancels one submenu level at a time, then returns to the thread", async () => {
61
+ using fixture = setup();
62
+ const result = showContextMenuFallback(items);
63
+ press("End");
64
+ const parent = document.activeElement;
65
+ press("ArrowRight");
66
+ expect(label()).toBe("Path");
67
+ press("ArrowLeft");
68
+ expect(document.activeElement).toBe(parent);
69
+ press("Enter");
70
+ expect(label()).toBe("Path");
71
+ press("Escape");
72
+ expect(document.activeElement).toBe(parent);
73
+ expect(isContextMenuOpen()).toBe(true);
74
+ press("Escape");
75
+ expect(document.activeElement).toBe(fixture.origin);
76
+ await expect(result).resolves.toBeNull();
77
+});
78
+
79
+it("activates the focused action with Space or Enter", async () => {
80
+ using _fixture = setup();
81
+ const first = showContextMenuFallback(items);
82
+ press(" ");
83
+ await expect(first).resolves.toBe("rename");
84
+ const second = showContextMenuFallback(items);
85
+ press("Enter");
86
+ await expect(second).resolves.toBe("rename");
87
+});
88
+
89
+it("closes on Tab and returns focus to the opener so Tab continues from there", async () => {
90
+ using fixture = setup();
91
+ const result = showContextMenuFallback(items);
92
+ expect(press("Tab").defaultPrevented).toBe(false);
93
+ await expect(result).resolves.toBeNull();
94
+ expect(document.activeElement).toBe(fixture.origin);
95
+});
96
+
97
+it("closes without taking focus back when focus moves elsewhere", async () => {
98
+ using _fixture = setup();
99
+ const result = showContextMenuFallback(items);
100
+ const destination = document.createElement("button");
101
+ document.body.append(destination);
102
+ using _destination = { [Symbol.dispose]: () => destination.remove() };
103
+ destination.focus();
104
+ await expect(result).resolves.toBeNull();
105
+ expect(document.activeElement).toBe(destination);
106
+});
apps/web/src/contextMenuFallback.test.ts
+2
@@ -191,6 +191,8 @@ beforeEach(() => {
191
vi.stubGlobal("window", {
192
innerWidth: 1280,
193
innerHeight: 800,
194
+ addEventListener: vi.fn(),
195
+ removeEventListener: vi.fn(),
196
});
197
vi.stubGlobal("requestAnimationFrame", (callback: (time: number) => void) => {
198
callback(0);
apps/web/src/contextMenuFallback.ts
+97
-13
@@ -155,6 +155,7 @@ function createIconElement(name: string, tone: "neutral" | "destructive"): SVGSV
155
return null;
156
}
157
const svg = document.createElementNS(SVG_NS, "svg");
158
+ svg.setAttribute("aria-hidden", "true");
159
svg.setAttribute("xmlns", SVG_NS);
160
svg.setAttribute("viewBox", "0 0 24 24");
161
svg.setAttribute("fill", "none");
@@ -210,14 +211,14 @@ function isNodeWithinMenuStack(target: EventTarget | null, menuStack: readonly H
211
return false;
212
}
213
213
-let activeContextMenuDismiss: (() => void) | null = null;
214
+let activeContextMenuDismiss: ((restoreFocus?: boolean) => void) | null = null;
215
216
export function isContextMenuOpen(): boolean {
217
return activeContextMenuDismiss !== null;
218
}
219
219
-export function dismissContextMenu(): void {
220
- activeContextMenuDismiss?.();
220
+export function dismissContextMenu(restoreFocus = true): void {
221
+ activeContextMenuDismiss?.(restoreFocus);
222
activeContextMenuDismiss = null;
223
}
224
@@ -225,6 +226,7 @@ export function showContextMenuFallback<T extends string>(
226
items: readonly ContextMenuItem<T>[],
227
position?: { x: number; y: number },
228
): Promise<T | null> {
229
+ dismissContextMenu();
230
return new Promise<T | null>((resolve) => {
231
const previouslyFocusedElement =
232
document.activeElement instanceof HTMLElement ? document.activeElement : null;
@@ -233,9 +235,9 @@ export function showContextMenuFallback<T extends string>(
235
let isDisposed = false;
236
let canDismissFromPointer = false;
237
236
- const dismiss = () => cleanup(null);
238
+ const dismiss = (restoreFocus = true) => cleanup(null, restoreFocus);
239
238
- const cleanup = (result: T | null) => {
240
+ const cleanup = (result: T | null, restoreFocus = true) => {
241
if (isDisposed) {
242
return;
243
}
@@ -246,7 +248,10 @@ export function showContextMenuFallback<T extends string>(
248
document.removeEventListener("keydown", onKeyDown);
249
document.removeEventListener("pointerdown", onPointerDown, true);
250
document.removeEventListener("contextmenu", onContextMenu, true);
249
- const shouldRestoreFocus = isNodeWithinMenuStack(document.activeElement, menuStack);
251
+ document.removeEventListener("focusin", onFocusIn);
252
+ window.removeEventListener("blur", onWindowBlur);
253
+ const shouldRestoreFocus =
254
+ restoreFocus && isNodeWithinMenuStack(document.activeElement, menuStack);
255
for (const menu of menuStack) {
256
menu.remove();
257
}
@@ -257,12 +262,78 @@ export function showContextMenuFallback<T extends string>(
262
};
263
264
const onKeyDown = (event: KeyboardEvent) => {
260
- if (event.key === "Escape") {
261
- event.preventDefault();
262
- cleanup(null);
265
+ if (
266
+ event.defaultPrevented ||
267
+ event.isComposing ||
268
+ event.altKey ||
269
+ event.ctrlKey ||
270
+ event.metaKey
271
+ )
272
+ return;
273
+ const level = menuStack.findIndex((menu) =>
274
+ isNodeWithinMenuStack(document.activeElement, [menu]),
275
+ );
276
+ if (level < 0) return;
277
+ const menu = menuStack[level]!;
278
+ const buttons = [...menu.querySelectorAll<HTMLButtonElement>("button")].filter(
279
+ (button) => !button.disabled,
280
+ );
281
+ const index = buttons.indexOf(document.activeElement as HTMLButtonElement);
282
+ let target: HTMLButtonElement | undefined;
283
+ switch (event.key) {
284
+ case "ArrowDown":
285
+ target = buttons[(index + 1) % buttons.length];
286
+ break;
287
+ case "ArrowUp":
288
+ target =
289
+ buttons[(index < 0 ? buttons.length - 1 : index - 1 + buttons.length) % buttons.length];
290
+ break;
291
+ case "Home":
292
+ target = buttons[0];
293
+ break;
294
+ case "End":
295
+ target = buttons.at(-1);
296
+ break;
297
+ case "ArrowRight":
298
+ if (buttons[index]?.getAttribute("aria-haspopup") !== "menu") return;
299
+ buttons[index]?.click();
300
+ break;
301
+ case " ":
302
+ case "Enter":
303
+ // Keyboard activation must not depend on the opening pointer gesture's frame.
304
+ canDismissFromPointer = true;
305
+ buttons[index]?.click();
306
+ break;
307
+ case "ArrowLeft":
308
+ if (level === 0) return;
309
+ // Fall through to cancel this submenu only.
310
+ case "Escape": {
311
+ const parent = submenuTriggerStack[level];
312
+ if (parent) {
313
+ parent.focus({ preventScroll: true });
314
+ closeMenusFromLevel(level);
315
+ } else cleanup(null);
316
+ break;
317
+ }
318
+ case "Tab":
319
+ // Tab closes the menu and continues from the element that opened it.
320
+ cleanup(null);
321
+ return;
322
+ default:
323
+ return;
324
}
325
+ event.preventDefault();
326
+ event.stopPropagation();
327
+ if (target && target !== submenuTriggerStack[level + 1]) closeMenusFromLevel(level + 1);
328
+ target?.focus({ preventScroll: true });
329
+ target?.scrollIntoView({ block: "nearest" });
330
};
331
332
+ const onFocusIn = (event: FocusEvent) => {
333
+ if (!isNodeWithinMenuStack(event.target, menuStack)) cleanup(null, false);
334
+ };
335
+ const onWindowBlur = () => cleanup(null, false);
336
+
337
const onPointerDown = (event: PointerEvent) => {
338
if (!canDismissFromPointer || isNodeWithinMenuStack(event.target, menuStack)) {
339
return;
@@ -302,6 +373,10 @@ export function showContextMenuFallback<T extends string>(
373
menu.style.left = `${preferredLeft}px`;
374
menu.style.top = `${preferredTop}px`;
375
menu.dataset.level = String(level);
376
+ menu.dataset.contextMenu = "true";
377
+ menu.setAttribute("role", "menu");
378
+ menu.setAttribute("aria-label", parentTrigger?.textContent ?? "Context menu");
379
+ menu.tabIndex = -1;
380
381
const inner = document.createElement("div");
382
inner.className =
@@ -336,6 +411,9 @@ export function showContextMenuFallback<T extends string>(
411
button.type = "button";
412
const isDisabled = item.disabled === true;
413
button.disabled = isDisabled;
414
+ button.tabIndex = -1;
415
+ button.setAttribute("role", "menuitem");
416
+ button.setAttribute("aria-disabled", String(isDisabled));
417
const rowBase =
418
"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";
419
button.className = isDisabled
@@ -491,11 +569,17 @@ export function showContextMenuFallback<T extends string>(
569
document.addEventListener("pointerdown", onPointerDown, true);
570
document.addEventListener("contextmenu", onContextMenu, true);
571
openMenu(items, position?.x ?? 0, position?.y ?? 0, 0);
494
- // Dismiss the prior menu before replacing its only cleanup handle, or its DOM and listeners leak.
495
- if (activeContextMenuDismiss) {
496
- activeContextMenuDismiss();
497
- }
572
activeContextMenuDismiss = dismiss;
573
+ // A keyboard-opened menu starts on its first action, a pointer-opened one on the menu itself.
574
+ // Text fields always match :focus-visible, so they say nothing about how the menu opened.
575
+ const firstAction =
576
+ previouslyFocusedElement?.matches(":focus-visible") &&
577
+ !previouslyFocusedElement.matches('input, textarea, select, [contenteditable="true"]')
578
+ ? menuStack[0]?.querySelector<HTMLButtonElement>("button:not(:disabled)")
579
+ : null;
580
+ (firstAction ?? menuStack[0])?.focus({ preventScroll: true });
581
+ document.addEventListener("focusin", onFocusIn);
582
+ window.addEventListener("blur", onWindowBlur);
583
584
requestAnimationFrame(() => {
585
canDismissFromPointer = true;
apps/web/src/index.css
+6
@@ -2577,3 +2577,9 @@ code {
2577
}
2578
}
2579
}
2580
+
2581
+/* A workspace area with no control of its own takes F6 focus itself; keep that visible. */
2582
+[data-workspace-area]:focus-visible {
2583
+ outline: 2px solid var(--ring);
2584
+ outline-offset: -2px;
2585
+}
apps/web/src/lib/accessibilityAnnouncements.ts
new
+36
@@ -0,0 +1,36 @@
1
+let latestOpen = false;
2
+let firstWritePending = false;
3
+
4
+/** Alternating atomic live regions allow repeated user actions to be announced, as in VS Code aria.ts. */
5
+export function announceSidebarVisibility(open: boolean) {
6
+ latestOpen = open;
7
+ if (firstWritePending) return;
8
+ let container = document.getElementById("workspace-visibility-alerts");
9
+ const created = !container;
10
+ if (!container) {
11
+ container = document.createElement("div");
12
+ container.id = "workspace-visibility-alerts";
13
+ container.className = "sr-only";
14
+ for (let index = 0; index < 2; index++) {
15
+ const alert = document.createElement("div");
16
+ alert.setAttribute("aria-live", "polite");
17
+ alert.setAttribute("aria-atomic", "true");
18
+ container.append(alert);
19
+ }
20
+ document.body.append(container);
21
+ }
22
+ const [first, second] = Array.from(container.children);
23
+ const write = () => {
24
+ firstWritePending = false;
25
+ const next = first!.textContent ? second! : first!;
26
+ first!.textContent = "";
27
+ second!.textContent = "";
28
+ next.textContent = `Sidebar ${latestOpen ? "shown" : "hidden"}`;
29
+ };
30
+ // Screen readers ignore text written in the same task that inserts its live region.
31
+ // Toggles during that delay only update the state the pending write announces.
32
+ if (created) {
33
+ firstWritePending = true;
34
+ setTimeout(write, 100);
35
+ } else write();
36
+}
apps/web/src/lib/sidebarTree.browser.test.ts
new
+195
@@ -0,0 +1,195 @@
1
+import { describe, expect, it, vi } from "vite-plus/test";
2
+import { userEvent } from "vite-plus/test/browser";
3
+import { installSidebarTree } from "./sidebarTree";
4
+
5
+function setup() {
6
+ const root = document.createElement("div");
7
+ root.setAttribute("role", "tree");
8
+ document.body.append(root);
9
+ let dispose: (() => void) | undefined;
10
+ const row = (id: string, parent?: string) => {
11
+ const element = document.createElement("button");
12
+ element.dataset.sidebarRow = id;
13
+ if (parent) element.dataset.sidebarParent = parent;
14
+ element.setAttribute("role", "treeitem");
15
+ element.textContent = id;
16
+ root.append(element);
17
+ return element;
18
+ };
19
+ return {
20
+ root,
21
+ row,
22
+ install: () => {
23
+ dispose = installSidebarTree(root);
24
+ },
25
+ [Symbol.dispose]() {
26
+ dispose?.();
27
+ root.remove();
28
+ },
29
+ };
30
+}
31
+
32
+function press(target: HTMLElement, key: string, init: KeyboardEventInit = {}) {
33
+ const event = new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true, ...init });
34
+ target.dispatchEvent(event);
35
+ return event;
36
+}
37
+
38
+describe("sidebar keyboard navigation", () => {
39
+ it("moves focus without activating rows, clamps at the ends, and keeps one Tab stop", () => {
40
+ using tree = setup();
41
+ const first = tree.row("first");
42
+ const second = tree.row("second");
43
+ const last = tree.row("last");
44
+ const activate = vi.fn();
45
+ tree.root.addEventListener("click", activate);
46
+ tree.install();
47
+ first.focus();
48
+ press(first, "ArrowDown");
49
+ expect(document.activeElement).toBe(second);
50
+ press(second, "End");
51
+ expect(document.activeElement).toBe(last);
52
+ press(last, "ArrowDown");
53
+ expect(document.activeElement).toBe(last);
54
+ press(last, "Home");
55
+ expect(document.activeElement).toBe(first);
56
+ expect(activate).not.toHaveBeenCalled();
57
+ expect(tree.root.querySelectorAll('[tabindex="0"]')).toHaveLength(1);
58
+ });
59
+
60
+ it("expands a group before entering its first child and returns to the parent", async () => {
61
+ using tree = setup();
62
+ const group = tree.row("project");
63
+ group.setAttribute("aria-expanded", "false");
64
+ group.addEventListener("click", () => {
65
+ const expanded = group.getAttribute("aria-expanded") === "true";
66
+ group.setAttribute("aria-expanded", String(!expanded));
67
+ if (expanded) tree.root.querySelector('[data-sidebar-row="thread"]')?.remove();
68
+ else tree.row("thread", "project");
69
+ });
70
+ tree.install();
71
+ group.focus();
72
+ press(group, "ArrowRight");
73
+ expect(group.getAttribute("aria-expanded")).toBe("true");
74
+ expect(document.activeElement).toBe(group);
75
+ // The tree picks up the new child from its mutation observer.
76
+ await vi.waitFor(() =>
77
+ expect(
78
+ tree.root.querySelector('[data-sidebar-parent="project"]')?.getAttribute("aria-level"),
79
+ ).toBe("2"),
80
+ );
81
+ press(group, "ArrowRight");
82
+ const child = document.activeElement as HTMLElement;
83
+ expect(child.dataset.sidebarRow).toBe("thread");
84
+ press(child, "ArrowLeft");
85
+ expect(document.activeElement).toBe(group);
86
+ press(group, "ArrowLeft");
87
+ expect(group.getAttribute("aria-expanded")).toBe("false");
88
+ });
89
+
90
+ it("opens the row menu on Shift+F10 release without moving focus", () => {
91
+ using tree = setup();
92
+ tree.row("first");
93
+ const selected = tree.row("selected");
94
+ const contextMenu = vi.fn((event: MouseEvent) => event.preventDefault());
95
+ selected.addEventListener("contextmenu", contextMenu);
96
+ tree.install();
97
+ selected.focus();
98
+ expect(press(selected, "F10", { shiftKey: true }).defaultPrevented).toBe(true);
99
+ expect(contextMenu).not.toHaveBeenCalled();
100
+ selected.dispatchEvent(
101
+ new KeyboardEvent("keyup", { key: "F10", shiftKey: true, bubbles: true, cancelable: true }),
102
+ );
103
+ expect(contextMenu).toHaveBeenCalledOnce();
104
+ expect(document.activeElement).toBe(selected);
105
+ });
106
+
107
+ it("lets Tab reach only the focused row's buttons", () => {
108
+ using tree = setup();
109
+ const first = tree.row("first");
110
+ const second = tree.row("second");
111
+ const action = (owner: string) => {
112
+ const button = document.createElement("button");
113
+ button.textContent = `Archive ${owner}`;
114
+ button.dataset.sidebarActionFor = owner;
115
+ tree.root.append(button);
116
+ return button;
117
+ };
118
+ const firstAction = action("first");
119
+ const secondAction = action("second");
120
+ tree.install();
121
+ first.focus();
122
+ expect([firstAction.tabIndex, secondAction.tabIndex]).toEqual([0, -1]);
123
+ press(first, "ArrowDown");
124
+ expect(document.activeElement).toBe(second);
125
+ expect([firstAction.tabIndex, secondAction.tabIndex]).toEqual([-1, 0]);
126
+ });
127
+
128
+ it("keeps a rendered row under a collapsed group reachable", () => {
129
+ using tree = setup();
130
+ const shelf = tree.row("shelf:settled");
131
+ shelf.setAttribute("aria-expanded", "false");
132
+ // A collapsed shelf still renders the open thread.
133
+ const open = tree.row("thread", "shelf:settled");
134
+ tree.install();
135
+ shelf.focus();
136
+ press(shelf, "ArrowDown");
137
+ expect(document.activeElement).toBe(open);
138
+ });
139
+
140
+ it("skips disabled rows and leaves controls outside rows in the Tab order", () => {
141
+ using tree = setup();
142
+ const first = tree.row("first");
143
+ const loading = tree.row("settled:more");
144
+ loading.disabled = true;
145
+ const undo = document.createElement("button");
146
+ undo.textContent = "Undo";
147
+ tree.root.append(undo);
148
+ tree.install();
149
+ first.focus();
150
+ press(first, "ArrowDown");
151
+ expect(document.activeElement).toBe(first);
152
+ expect(undo.tabIndex).toBe(0);
153
+ });
154
+
155
+ it("gives row buttons back their own tab order when the tree reinstalls", () => {
156
+ using tree = setup();
157
+ tree.row("first");
158
+ const second = tree.row("second");
159
+ const action = (owner: string) => {
160
+ const button = document.createElement("button");
161
+ button.dataset.sidebarActionFor = owner;
162
+ tree.root.append(button);
163
+ return button;
164
+ };
165
+ const firstAction = action("first");
166
+ const secondAction = action("second");
167
+ const dispose = installSidebarTree(tree.root);
168
+ second.focus();
169
+ dispose();
170
+ expect([firstAction.tabIndex, secondAction.tabIndex]).toEqual([0, 0]);
171
+ tree.install();
172
+ expect([firstAction.tabIndex, secondAction.tabIndex]).toEqual([-1, 0]);
173
+ });
174
+
175
+ it("does not pull focus back after a click outside the tree", async () => {
176
+ using tree = setup();
177
+ const first = tree.row("first");
178
+ tree.install();
179
+ const text = document.createElement("p");
180
+ text.textContent = "Chat text";
181
+ document.body.append(text);
182
+ using _text = { [Symbol.dispose]: () => text.remove() };
183
+ first.focus();
184
+ await userEvent.click(text);
185
+ expect(document.activeElement).toBe(document.body);
186
+ // A status change re-renders the tree while the user works elsewhere.
187
+ tree.row("second");
188
+ await vi.waitFor(() =>
189
+ expect(
190
+ tree.root.querySelector('[data-sidebar-row="second"]')?.getAttribute("aria-posinset"),
191
+ ).toBe("2"),
192
+ );
193
+ expect(document.activeElement).toBe(document.body);
194
+ });
195
+});
apps/web/src/lib/sidebarTree.ts
new
+263
@@ -0,0 +1,263 @@
1
+const ROW = "[data-sidebar-row]";
2
+const CONTROL = 'button, a[href], input, textarea, select, [contenteditable="true"], [tabindex]';
3
+const TEXT_ENTRY = 'input, textarea, select, [contenteditable="true"]';
4
+
5
+function setAttribute(element: Element, name: string, value: string) {
6
+ if (element.getAttribute(name) !== value) element.setAttribute(name, value);
7
+}
8
+
9
+function setTabIndex(element: HTMLElement, value: number) {
10
+ if (element.tabIndex !== value) element.tabIndex = value;
11
+}
12
+
13
+export const SIDEBAR_TREE_PROPS = { role: "tree", "aria-label": "Threads" } as const;
14
+
15
+/** Ref callback for a sidebar list; installs the tree and returns its cleanup. */
16
+export function attachSidebarTree(element: HTMLElement | null) {
17
+ return element ? installSidebarTree(element) : undefined;
18
+}
19
+
20
+/** A roving DOM focus, separate from thread activation, as in VS Code's list commands. */
21
+export function installSidebarTree(root: HTMLElement) {
22
+ let rows: HTMLElement[] = [];
23
+ let focusedId: string | undefined;
24
+ let ownsFocus = false;
25
+ let tabStop: HTMLElement | undefined;
26
+ let contextMenuRow: HTMLElement | undefined;
27
+ // A control's own tab index, restored while its row holds the Tab stop and on uninstall.
28
+ const ownTabIndex = new Map<HTMLElement, number>();
29
+
30
+ const rowControls = (row: HTMLElement) => {
31
+ const id = row.dataset.sidebarRow;
32
+ const linked = id
33
+ ? root.querySelectorAll<HTMLElement>(`[data-sidebar-action-for="${CSS.escape(id)}"]`)
34
+ : [];
35
+ return [...row.querySelectorAll<HTMLElement>(CONTROL), ...linked].filter(
36
+ (control) => !control.matches(ROW) && !control.matches(TEXT_ENTRY),
37
+ );
38
+ };
39
+ // Tab reaches the buttons of the focused row only, so the tree stays one stop for the rest.
40
+ const setRowControlsReachable = (row: HTMLElement, reachable: boolean) => {
41
+ for (const control of rowControls(row)) {
42
+ if (!ownTabIndex.has(control)) ownTabIndex.set(control, control.tabIndex);
43
+ setTabIndex(control, reachable ? ownTabIndex.get(control)! : -1);
44
+ }
45
+ };
46
+
47
+ const setTabStop = (row: HTMLElement) => {
48
+ if (tabStop === row) return;
49
+ if (tabStop) {
50
+ setTabIndex(tabStop, -1);
51
+ setRowControlsReachable(tabStop, false);
52
+ }
53
+ setTabIndex(row, 0);
54
+ setRowControlsReachable(row, true);
55
+ tabStop = row;
56
+ focusedId = row.dataset.sidebarRow;
57
+ };
58
+
59
+ const focusRow = (row: HTMLElement) => {
60
+ setTabStop(row);
61
+ // Revealing before focusing also materializes content-visibility:auto descendants.
62
+ row.scrollIntoView({ block: "nearest" });
63
+ row.focus({ preventScroll: true });
64
+ };
65
+
66
+ const refresh = () => {
67
+ const previousRows = rows;
68
+ const previousIndex = previousRows.findIndex((row) => row.dataset.sidebarRow === focusedId);
69
+ const previous = previousRows[previousIndex];
70
+ rows = Array.from(root.querySelectorAll<HTMLElement>(ROW)).filter((row) => {
71
+ const hidden = row.closest('[hidden], [inert], [aria-hidden="true"]');
72
+ // A dialog can temporarily make the whole workspace inert. Keep the tree's
73
+ // Tab stop ready for its return while still excluding exiting row clones.
74
+ return (!hidden || !root.contains(hidden)) && !row.matches(":disabled");
75
+ });
76
+ let selected =
77
+ rows.find((row) => row.dataset.sidebarRow === focusedId) ??
78
+ rows.find((row) => row === document.activeElement);
79
+ if (!selected) {
80
+ selected =
81
+ rows.find((row) => row.dataset.sidebarRow === previous?.dataset.sidebarParent) ??
82
+ (previousIndex === -1 ? rows.find((row) => row.hasAttribute("aria-current")) : undefined) ??
83
+ rows[Math.min(Math.max(previousIndex, 0), rows.length - 1)];
84
+ }
85
+ focusedId = selected?.dataset.sidebarRow;
86
+ tabStop = selected;
87
+ setTabIndex(root, selected ? -1 : 0);
88
+ const siblings = new Map<string, HTMLElement[]>();
89
+ for (const row of rows) {
90
+ const parent = row.dataset.sidebarParent ?? "";
91
+ const group = siblings.get(parent) ?? [];
92
+ group.push(row);
93
+ siblings.set(parent, group);
94
+ setAttribute(row, "aria-level", parent ? "2" : "1");
95
+ setTabIndex(row, row === selected ? 0 : -1);
96
+ }
97
+ const byId = new Map(rows.map((row) => [row.dataset.sidebarRow, row]));
98
+ for (const control of ownTabIndex.keys()) if (!control.isConnected) ownTabIndex.delete(control);
99
+ for (const control of root.querySelectorAll<HTMLElement>(CONTROL)) {
100
+ if (control.matches(ROW) || control.matches(TEXT_ENTRY)) continue;
101
+ const linked = control.dataset.sidebarActionFor;
102
+ const owner = control.closest<HTMLElement>(ROW) ?? (linked ? byId.get(linked) : undefined);
103
+ if (!owner) continue;
104
+ if (!ownTabIndex.has(control)) ownTabIndex.set(control, control.tabIndex);
105
+ setTabIndex(control, owner === selected ? ownTabIndex.get(control)! : -1);
106
+ }
107
+ for (const group of siblings.values())
108
+ group.forEach((row, index) => {
109
+ setAttribute(row, "aria-posinset", String(index + 1));
110
+ setAttribute(row, "aria-setsize", String(group.length));
111
+ });
112
+ for (const listItem of root.querySelectorAll("li:not([role])"))
113
+ listItem.setAttribute("role", "presentation");
114
+ if (
115
+ ownsFocus &&
116
+ selected &&
117
+ (document.activeElement === document.body ||
118
+ document.activeElement === root ||
119
+ (root.contains(document.activeElement) &&
120
+ !rows.includes(document.activeElement as HTMLElement) &&
121
+ document.activeElement?.matches(ROW)))
122
+ ) {
123
+ focusRow(selected);
124
+ }
125
+ if (ownsFocus && !selected && document.activeElement === document.body) root.focus();
126
+ };
127
+
128
+ // Clicking non-focusable content drops focus to the body without a focusin event.
129
+ const onPointerDown = (event: PointerEvent) => {
130
+ if (!root.contains(event.target as Node)) ownsFocus = false;
131
+ };
132
+ const onFocus = (event: FocusEvent) => {
133
+ ownsFocus = root.contains(event.target as Node);
134
+ if (!ownsFocus || !(event.target instanceof HTMLElement) || !event.target.matches(ROW)) return;
135
+ setTabStop(event.target);
136
+ };
137
+ const onKeyDown = (event: KeyboardEvent) => {
138
+ const row = event.target;
139
+ if (
140
+ !event.defaultPrevented &&
141
+ !event.isComposing &&
142
+ !event.altKey &&
143
+ !event.ctrlKey &&
144
+ !event.metaKey &&
145
+ (event.key === "ContextMenu" || (event.shiftKey && event.key === "F10")) &&
146
+ row instanceof HTMLElement &&
147
+ row.matches(ROW)
148
+ ) {
149
+ event.preventDefault();
150
+ event.stopPropagation();
151
+ contextMenuRow = row;
152
+ return;
153
+ }
154
+ if (
155
+ event.defaultPrevented ||
156
+ event.isComposing ||
157
+ event.altKey ||
158
+ event.ctrlKey ||
159
+ event.metaKey ||
160
+ event.shiftKey
161
+ )
162
+ return;
163
+ if (!(row instanceof HTMLElement) || !row.matches(ROW)) return;
164
+ const index = rows.indexOf(row);
165
+ if (index < 0) return;
166
+ let target: HTMLElement | undefined;
167
+ switch (event.key) {
168
+ case "ArrowDown":
169
+ target = rows[Math.min(index + 1, rows.length - 1)];
170
+ break;
171
+ case "ArrowUp":
172
+ target = rows[Math.max(index - 1, 0)];
173
+ break;
174
+ case "Home":
175
+ target = rows[0];
176
+ break;
177
+ case "End":
178
+ target = rows.at(-1);
179
+ break;
180
+ case "ArrowRight":
181
+ if (row.getAttribute("aria-expanded") === "false") row.click();
182
+ else
183
+ target = rows.find(
184
+ (candidate) => candidate.dataset.sidebarParent === row.dataset.sidebarRow,
185
+ );
186
+ break;
187
+ case "ArrowLeft":
188
+ if (row.getAttribute("aria-expanded") === "true") row.click();
189
+ else
190
+ target = rows.find(
191
+ (candidate) => candidate.dataset.sidebarRow === row.dataset.sidebarParent,
192
+ );
193
+ break;
194
+ // Row handlers own Enter, Space, F2 rename, and the context menu.
195
+ default:
196
+ return;
197
+ }
198
+ event.preventDefault();
199
+ event.stopPropagation();
200
+ if (target) focusRow(target);
201
+ };
202
+ const onKeyUp = (event: KeyboardEvent) => {
203
+ if (!contextMenuRow || (event.key !== "ContextMenu" && event.key !== "F10")) return;
204
+ const row = contextMenuRow;
205
+ contextMenuRow = undefined;
206
+ event.preventDefault();
207
+ event.stopPropagation();
208
+ if (document.activeElement !== row || !row.isConnected) return;
209
+ const rect = row.getBoundingClientRect();
210
+ // Like VS Code's list, suppress keydown and open on release. Reuse the row's
211
+ // selection-aware handler, including its Electron native menu route.
212
+ row.dispatchEvent(
213
+ new MouseEvent("contextmenu", {
214
+ bubbles: true,
215
+ cancelable: true,
216
+ clientX: rect.left,
217
+ clientY: rect.bottom,
218
+ }),
219
+ );
220
+ };
221
+ refresh();
222
+ const observer = new MutationObserver((records) => {
223
+ if (
224
+ records.some(
225
+ (record) =>
226
+ record.type === "attributes" ||
227
+ [...record.addedNodes, ...record.removedNodes].some(
228
+ (node) =>
229
+ node instanceof Element &&
230
+ (node.matches(`${ROW}, ${CONTROL}`) || node.querySelector(`${ROW}, ${CONTROL}`)),
231
+ ),
232
+ )
233
+ )
234
+ refresh();
235
+ });
236
+ observer.observe(root, {
237
+ childList: true,
238
+ subtree: true,
239
+ attributes: true,
240
+ attributeFilter: [
241
+ "data-sidebar-row",
242
+ "data-sidebar-parent",
243
+ "aria-expanded",
244
+ "hidden",
245
+ "disabled",
246
+ "inert",
247
+ "aria-hidden",
248
+ ],
249
+ });
250
+ document.addEventListener("focusin", onFocus);
251
+ document.addEventListener("pointerdown", onPointerDown, true);
252
+ root.addEventListener("keydown", onKeyDown, true);
253
+ root.addEventListener("keyup", onKeyUp, true);
254
+ return () => {
255
+ observer.disconnect();
256
+ // A later install reads these as the controls' own tab indexes.
257
+ for (const [control, tabIndex] of ownTabIndex) setTabIndex(control, tabIndex);
258
+ document.removeEventListener("focusin", onFocus);
259
+ document.removeEventListener("pointerdown", onPointerDown, true);
260
+ root.removeEventListener("keydown", onKeyDown, true);
261
+ root.removeEventListener("keyup", onKeyUp, true);
262
+ };
263
+}
apps/web/src/lib/workspaceFocus.browser.test.ts
new
+260
@@ -0,0 +1,260 @@
1
+import { describe, expect, it, vi } from "vite-plus/test";
2
+import { createWorkspaceFocusController } from "./workspaceFocus";
3
+
4
+function setup() {
5
+ const root = document.createElement("div");
6
+ document.body.append(root);
7
+ const controller = createWorkspaceFocusController(document);
8
+ const area = (name: string, order: number, parent: HTMLElement = root) => {
9
+ const element = document.createElement("section");
10
+ element.dataset.workspaceArea = name;
11
+ element.dataset.workspaceOrder = String(order);
12
+ element.tabIndex = -1;
13
+ const button = document.createElement("button");
14
+ button.textContent = name;
15
+ element.append(button);
16
+ parent.append(element);
17
+ return { element, button };
18
+ };
19
+ const append = (html: string) => {
20
+ root.insertAdjacentHTML("beforeend", html);
21
+ return root.lastElementChild as HTMLElement;
22
+ };
23
+ return {
24
+ area,
25
+ append,
26
+ controller,
27
+ [Symbol.dispose]() {
28
+ controller.dispose();
29
+ root.remove();
30
+ },
31
+ };
32
+}
33
+
34
+describe("workspace area focus", () => {
35
+ it("cycles in workspace order in both directions, independent of DOM order", () => {
36
+ using fixture = setup();
37
+ const panel = fixture.area("panel", 3);
38
+ const sidebar = fixture.area("sidebar", 0);
39
+ const conversation = fixture.area("conversation", 1);
40
+ const composer = fixture.area("composer", 2);
41
+ sidebar.button.focus();
42
+ fixture.controller.move(1);
43
+ // The conversation is a region; it takes focus itself rather than its first button.
44
+ expect(document.activeElement).toBe(conversation.element);
45
+ fixture.controller.move(1);
46
+ expect(document.activeElement).toBe(composer.button);
47
+ fixture.controller.move(1);
48
+ expect(document.activeElement).toBe(panel.button);
49
+ fixture.controller.move(1);
50
+ expect(document.activeElement).toBe(sidebar.button);
51
+ fixture.controller.move(-1);
52
+ expect(document.activeElement).toBe(panel.button);
53
+ });
54
+
55
+ it("skips hidden, inert, and maximized-away areas", () => {
56
+ using fixture = setup();
57
+ const sidebar = fixture.area("sidebar", 0);
58
+ const conversation = fixture.area("conversation", 1);
59
+ const composer = fixture.area("composer", 2);
60
+ const panel = fixture.area("panel", 3);
61
+ const terminal = fixture.area("terminal", 4);
62
+ conversation.element.dataset.chatColumnMaximizedAway = "true";
63
+ composer.element.hidden = true;
64
+ panel.element.dataset.workspaceUnavailable = "true";
65
+ terminal.element.inert = true;
66
+ sidebar.button.focus();
67
+ expect(fixture.controller.move(1)).toBe(true);
68
+ expect(document.activeElement).toBe(sidebar.button);
69
+ });
70
+
71
+ it("restores the last focused control and falls back when it is removed", () => {
72
+ using fixture = setup();
73
+ fixture.area("sidebar", 0);
74
+ const composer = fixture.area("composer", 2);
75
+ const remembered = document.createElement("button");
76
+ remembered.textContent = "remembered";
77
+ composer.element.append(remembered);
78
+ remembered.focus();
79
+ fixture.controller.move(-1);
80
+ fixture.controller.move(1);
81
+ expect(document.activeElement).toBe(remembered);
82
+ fixture.controller.move(-1);
83
+ remembered.remove();
84
+ fixture.controller.move(1);
85
+ expect(document.activeElement).toBe(composer.button);
86
+ });
87
+
88
+ it("keeps focus inside a dialog or an open popup", () => {
89
+ using fixture = setup();
90
+ fixture.area("sidebar", 0);
91
+ fixture.area("panel", 3);
92
+ const dialog = fixture.append('<div role="dialog" tabindex="-1">Confirm</div>');
93
+ dialog.focus();
94
+ expect(fixture.controller.move(1)).toBe(false);
95
+ expect(document.activeElement).toBe(dialog);
96
+ dialog.remove();
97
+
98
+ const popup = fixture.append(
99
+ '<div role="listbox" data-slot="select-popup"><button role="option">Choice</button></div>',
100
+ );
101
+ const choice = popup.querySelector("button")!;
102
+ choice.focus();
103
+ expect(fixture.controller.move(1)).toBe(false);
104
+ expect(document.activeElement).toBe(choice);
105
+ });
106
+
107
+ it("keeps moving while a non-modal notification is visible", () => {
108
+ using fixture = setup();
109
+ const composer = fixture.area("composer", 2);
110
+ const panel = fixture.area("panel", 4);
111
+ fixture.append(
112
+ '<div data-slot="toast-viewport"><div role="dialog" aria-modal="false" tabindex="0">Update available</div></div>',
113
+ );
114
+ composer.button.focus();
115
+ expect(fixture.controller.move(1)).toBe(true);
116
+ expect(document.activeElement).toBe(panel.button);
117
+ });
118
+
119
+ it("moves only between the areas of an open Settings modal", () => {
120
+ using fixture = setup();
121
+ fixture.area("sidebar", 0);
122
+ fixture.area("composer", 2);
123
+ const modal = fixture.append('<div role="dialog" data-app-modal=""></div>');
124
+ const nav = fixture.area("settings-nav", 0, modal);
125
+ const content = fixture.area("settings", 1, modal);
126
+ nav.button.focus();
127
+ expect(fixture.controller.move(1)).toBe(true);
128
+ expect(document.activeElement).toBe(content.button);
129
+ expect(fixture.controller.move(1)).toBe(true);
130
+ expect(document.activeElement).toBe(nav.button);
131
+ });
132
+
133
+ it("keeps moving while a shortcut recorder is on the page but not focused", () => {
134
+ using fixture = setup();
135
+ const nav = fixture.area("settings-nav", 0);
136
+ const content = fixture.area("settings", 1);
137
+ fixture.append('<button data-keybinding-capture="">Record shortcut</button>');
138
+ nav.button.focus();
139
+ expect(fixture.controller.move(1)).toBe(true);
140
+ expect(document.activeElement).toBe(content.button);
141
+ });
142
+
143
+ it("brings a restored control back into view inside its own list", () => {
144
+ using fixture = setup();
145
+ const sidebar = fixture.area("sidebar", 0);
146
+ const list = document.createElement("div");
147
+ list.style.cssText = "height: 50px; overflow-y: auto";
148
+ const spacer = document.createElement("div");
149
+ spacer.style.height = "400px";
150
+ const row = document.createElement("button");
151
+ row.textContent = "Last thread";
152
+ list.append(spacer, row);
153
+ sidebar.element.append(list);
154
+ const composer = fixture.area("composer", 2);
155
+ row.focus();
156
+ fixture.controller.move(1);
157
+ expect(document.activeElement).toBe(composer.button);
158
+ list.scrollTop = 0;
159
+ fixture.controller.move(-1);
160
+ expect(document.activeElement).toBe(row);
161
+ expect(list.scrollTop).toBeGreaterThan(0);
162
+ });
163
+
164
+ it("reveals a restored control through nested scrolling lists", () => {
165
+ using fixture = setup();
166
+ const settings = fixture.area("settings", 1);
167
+ const page = document.createElement("div");
168
+ page.style.cssText = "height: 80px; overflow-y: auto";
169
+ const inner = document.createElement("div");
170
+ inner.style.cssText = "height: 60px; overflow-y: auto";
171
+ const field = document.createElement("button");
172
+ field.textContent = "Provider field";
173
+ inner.append(Object.assign(document.createElement("div"), { style: "height: 200px" }), field);
174
+ page.append(inner, Object.assign(document.createElement("div"), { style: "height: 400px" }));
175
+ settings.element.append(page);
176
+ const nav = fixture.area("settings-nav", 0);
177
+ field.focus();
178
+ fixture.controller.move(-1);
179
+ expect(document.activeElement).toBe(nav.button);
180
+ inner.scrollTop = 0;
181
+ page.scrollTop = 300;
182
+ fixture.controller.move(1);
183
+ expect(document.activeElement).toBe(field);
184
+ const box = page.getBoundingClientRect();
185
+ const rect = field.getBoundingClientRect();
186
+ expect(rect.bottom > box.top && rect.top < box.bottom).toBe(true);
187
+ });
188
+
189
+ it("does not scroll the conversation to an old control", () => {
190
+ using fixture = setup();
191
+ const conversation = fixture.area("conversation", 1);
192
+ const timeline = document.createElement("div");
193
+ timeline.style.cssText = "height: 50px; overflow-y: auto";
194
+ const copy = document.createElement("button");
195
+ copy.textContent = "Copy";
196
+ timeline.append(copy, Object.assign(document.createElement("div"), { style: "height: 400px" }));
197
+ conversation.element.append(timeline);
198
+ const composer = fixture.area("composer", 2);
199
+ copy.focus();
200
+ fixture.controller.move(1);
201
+ expect(document.activeElement).toBe(composer.button);
202
+ // Live follow moved the timeline to the newest output.
203
+ timeline.scrollTop = 300;
204
+ fixture.controller.move(-1);
205
+ expect(document.activeElement).toBe(conversation.element);
206
+ expect(timeline.scrollTop).toBe(300);
207
+ });
208
+
209
+ it("returns focus to the area when its focused control disappears", async () => {
210
+ using fixture = setup();
211
+ const panel = fixture.area("panel", 3);
212
+ const tab = document.createElement("button");
213
+ tab.textContent = "Files tab";
214
+ panel.element.append(tab);
215
+ tab.focus();
216
+ tab.remove();
217
+ await vi.waitFor(() => expect(document.activeElement).toBe(panel.button));
218
+ });
219
+
220
+ it("falls back to the main content when the whole area disappears", async () => {
221
+ using fixture = setup();
222
+ const composer = fixture.area("composer", 2);
223
+ const details = fixture.area("details", 3);
224
+ details.button.focus();
225
+ details.element.hidden = true;
226
+ await vi.waitFor(() => expect(document.activeElement).toBe(composer.button));
227
+ });
228
+
229
+ it("waits for a requested area to mount", async () => {
230
+ using fixture = setup();
231
+ fixture.area("composer", 2);
232
+ fixture.controller.request({ area: "pull-requests" });
233
+ const list = fixture.area("pull-requests", 1);
234
+ await vi.waitFor(() => expect(document.activeElement).toBe(list.button));
235
+ });
236
+
237
+ it("keeps focus on a control that React remounted elsewhere", async () => {
238
+ using fixture = setup();
239
+ fixture.area("composer", 2);
240
+ const header = fixture.append("<header></header>");
241
+ const toggle = document.createElement("button");
242
+ toggle.setAttribute("aria-label", "Toggle right panel");
243
+ header.append(toggle);
244
+ toggle.focus();
245
+ const moved = toggle.cloneNode() as HTMLButtonElement;
246
+ toggle.remove();
247
+ header.append(moved);
248
+ await vi.waitFor(() => expect(document.activeElement).toBe(moved));
249
+ });
250
+
251
+ it("keeps moving while a hover popup without focus is open", () => {
252
+ using fixture = setup();
253
+ const composer = fixture.area("composer", 2);
254
+ const terminal = fixture.area("terminal", 4);
255
+ fixture.append('<div data-slot="popover-popup">New split terminal</div>');
256
+ composer.button.focus();
257
+ expect(fixture.controller.move(1)).toBe(true);
258
+ expect(document.activeElement).toBe(terminal.button);
259
+ });
260
+});
apps/web/src/lib/workspaceFocus.ts
new
+386
@@ -0,0 +1,386 @@
1
+import type { AnyRouter } from "@tanstack/react-router";
2
+import { dismissContextMenu } from "../contextMenuFallback";
3
+import { useRightPanelStore } from "../rightPanelStore";
4
+
5
+const AREA_SELECTOR = "[data-workspace-area]";
6
+const FOCUS_BOUNDARY_SELECTOR =
7
+ '[role="dialog"], [role="alertdialog"], [aria-modal="true"], dialog[open], [data-slot$="-popup"]:not([data-slot="tooltip-popup"]):not([role="tooltip"])';
8
+const FOCUSABLE_SELECTOR =
9
+ 'button:not(:disabled), a[href], input:not(:disabled), textarea:not(:disabled), select:not(:disabled), [contenteditable="true"], [tabindex]';
10
+
11
+/** Props that make an element one stop in the F6 cycle; `order` sets its place in the cycle. */
12
+export function workspaceAreaProps(name: string, order: number, label: string) {
13
+ return {
14
+ "data-workspace-area": name,
15
+ "data-workspace-order": order,
16
+ "aria-label": label,
17
+ role: "region",
18
+ tabIndex: -1,
19
+ } as const;
20
+}
21
+
22
+export interface WorkspaceFocusTarget {
23
+ area: string;
24
+ selector?: string;
25
+ restore?: boolean;
26
+}
27
+
28
+function workspaceArea(element: Element): HTMLElement | null {
29
+ const area = element.closest<HTMLElement>(AREA_SELECTOR);
30
+ if (area) return area;
31
+ const root = element.getRootNode();
32
+ return root instanceof ShadowRoot ? workspaceArea(root.host) : null;
33
+}
34
+
35
+function isWorkspaceElementVisible(element: HTMLElement): boolean {
36
+ if (
37
+ !element.isConnected ||
38
+ element.closest(
39
+ '[hidden], [inert], [data-closed], [aria-hidden="true"], [data-chat-column-maximized-away="true"], [data-slot="sidebar"][data-state="collapsed"], [data-workspace-unavailable="true"]',
40
+ )
41
+ )
42
+ return false;
43
+ const style = getComputedStyle(element);
44
+ if (style.display === "none" || style.visibility === "hidden") return false;
45
+ const root = element.getRootNode();
46
+ if (
47
+ root instanceof ShadowRoot &&
48
+ root.host instanceof HTMLElement &&
49
+ !isWorkspaceElementVisible(root.host)
50
+ )
51
+ return false;
52
+ return Array.from(element.getClientRects()).some((rect) => rect.width > 0 && rect.height > 0);
53
+}
54
+
55
+function scrollingAncestors(target: HTMLElement) {
56
+ const scrollers: HTMLElement[] = [];
57
+ for (let element = target.parentElement; element; element = element.parentElement) {
58
+ const { overflowY } = getComputedStyle(element);
59
+ if (
60
+ (overflowY === "auto" || overflowY === "scroll") &&
61
+ element.scrollHeight > element.clientHeight
62
+ )
63
+ scrollers.push(element);
64
+ }
65
+ return scrollers;
66
+}
67
+
68
+function isInScrollView(target: HTMLElement) {
69
+ const rect = target.getBoundingClientRect();
70
+ return scrollingAncestors(target).every((scroller) => {
71
+ const box = scroller.getBoundingClientRect();
72
+ return rect.bottom > box.top && rect.top < box.bottom;
73
+ });
74
+}
75
+
76
+/**
77
+ * Brings a restored control into view, innermost scrolling list first.
78
+ * scrollIntoView would also scroll overflow-hidden layout containers out of place.
79
+ */
80
+function revealInScrollers(target: HTMLElement) {
81
+ for (const scroller of scrollingAncestors(target)) {
82
+ const box = scroller.getBoundingClientRect();
83
+ const rect = target.getBoundingClientRect();
84
+ if (rect.top < box.top) scroller.scrollTop -= box.top - rect.top;
85
+ else if (rect.bottom > box.bottom) scroller.scrollTop += rect.bottom - box.bottom;
86
+ }
87
+}
88
+
89
+/** Keeps area focus local, like VS Code's layout service focusPart/visible-neighbour actions. */
90
+export function createWorkspaceFocusController(doc: Document) {
91
+ const lastFocused = new Map<string, HTMLElement>();
92
+ let lastArea: string | undefined;
93
+ const remember = (event: FocusEvent) => {
94
+ if (!(event.target instanceof HTMLElement)) return;
95
+ const area = workspaceArea(event.target);
96
+ if (!area?.dataset.workspaceArea) return;
97
+ lastArea = area.dataset.workspaceArea;
98
+ const key = area.dataset.workspaceFocusKey ?? lastArea;
99
+ lastFocused.delete(key);
100
+ // Custom file trees retarget focusin to their nonfocusable shadow host.
101
+ const target = event.composedPath().find((element) => element instanceof HTMLElement);
102
+ lastFocused.set(key, target instanceof HTMLElement ? target : event.target);
103
+ // Surface history must not retain an unbounded number of detached panel trees.
104
+ if (lastFocused.size > 64) lastFocused.delete(lastFocused.keys().next().value!);
105
+ };
106
+ doc.addEventListener("focusin", remember);
107
+
108
+ const focusArea = (area: HTMLElement, restore = true) => {
109
+ const key = area.dataset.workspaceFocusKey ?? area.dataset.workspaceArea!;
110
+ const previous = restore ? lastFocused.get(key) : undefined;
111
+ const belongs = (element: HTMLElement) =>
112
+ workspaceArea(element) === area &&
113
+ isWorkspaceElementVisible(element) &&
114
+ !element.matches(":disabled");
115
+ const preferred = Array.from(
116
+ area.querySelectorAll<HTMLElement>(
117
+ '[data-workspace-focus-default], [role="treeitem"][tabindex="0"], [data-settings-section][tabindex="0"], .xterm-helper-textarea, [contenteditable="true"]',
118
+ ),
119
+ ).find(belongs);
120
+ const fallback = Array.from(area.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)).find(
121
+ (element) => element.tabIndex >= 0 && belongs(element),
122
+ );
123
+ // Panel surfaces may unmount when hidden. Recover the same named control when
124
+ // it mounts again, without sharing focus history between different surface tabs.
125
+ const restored =
126
+ previous && !previous.isConnected
127
+ ? Array.from(area.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)).find(
128
+ (element) =>
129
+ belongs(element) &&
130
+ element.tagName === previous.tagName &&
131
+ ((previous.id && element.id === previous.id) ||
132
+ (previous.getAttribute("aria-label") &&
133
+ element.getAttribute("aria-label") === previous.getAttribute("aria-label")) ||
134
+ (previous.matches("button") &&
135
+ previous.textContent?.trim() &&
136
+ element.textContent === previous.textContent)),
137
+ )
138
+ : undefined;
139
+ const surface = area.querySelector<HTMLElement>("[data-right-panel-surface-content]");
140
+ const surfaceControl = surface
141
+ ? Array.from(surface.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)).find(
142
+ (element) => belongs(element) && element.tabIndex >= 0,
143
+ )
144
+ : undefined;
145
+ // Moving the timeline to an old control would also stop it following a running turn,
146
+ // so the conversation reuses a control only while it is still in view.
147
+ const isConversation = area.dataset.workspaceArea === "conversation";
148
+ const targets = new Set([
149
+ previous && belongs(previous) && (!isConversation || isInScrollView(previous))
150
+ ? previous
151
+ : undefined,
152
+ isConversation ? undefined : restored,
153
+ preferred,
154
+ surfaceControl,
155
+ isConversation ? undefined : fallback,
156
+ area,
157
+ ]);
158
+ for (const target of targets) {
159
+ if (!target) continue;
160
+ target.focus({ preventScroll: true });
161
+ const root = target.getRootNode();
162
+ const active = root instanceof ShadowRoot ? root.activeElement : doc.activeElement;
163
+ if (active === target || (active && target.contains(active))) {
164
+ if (target !== area && !isConversation) revealInScrollers(target);
165
+ return true;
166
+ }
167
+ }
168
+ return false;
169
+ };
170
+ const focus = (name: string, restore = true, selector?: string) => {
171
+ const areas = Array.from(doc.querySelectorAll<HTMLElement>(AREA_SELECTOR)).filter(
172
+ isWorkspaceElementVisible,
173
+ );
174
+ const area =
175
+ name === "content"
176
+ ? (areas.find((element) => element.dataset.workspaceArea === "composer") ??
177
+ areas.find(
178
+ (element) =>
179
+ element.dataset.workspaceArea === "pull-requests" || element.matches("main"),
180
+ ) ??
181
+ areas.find((element) => element.dataset.workspaceArea === "conversation") ??
182
+ areas.find((element) => element.dataset.workspaceArea === "panel"))
183
+ : areas.find((element) => element.dataset.workspaceArea === name);
184
+ if (!area) return false;
185
+ const surface = area.querySelector("[data-right-panel-surface-content]");
186
+ // A lazy surface's Suspense fallback is empty. Wait for its content instead
187
+ // of claiming focus on the tab strip before the useful controls mount.
188
+ if (surface && !surface.hasChildNodes()) return false;
189
+ if (selector) {
190
+ const target = area.querySelector<HTMLElement>(selector);
191
+ if (!target || !isWorkspaceElementVisible(target)) return false;
192
+ target.focus({ preventScroll: true });
193
+ return doc.activeElement === target;
194
+ }
195
+ return focusArea(area, restore);
196
+ };
197
+ const move = (direction: 1 | -1, fromArea?: string, closingPalette = false) => {
198
+ // HTML context menus close on blur, unlike modal dialogs and Base UI popups.
199
+ dismissContextMenu(false);
200
+ // A palette closes before running its command. Other popups keep their focus boundary.
201
+ // Inline listboxes (such as Settings search) belong to their workspace area, while
202
+ // portalled listboxes and menus can also supply a boundary without a popup data-slot.
203
+ const activePopup = doc.activeElement?.closest<HTMLElement>('[role="menu"], [role="listbox"]');
204
+ // Settings opens as a route modal with its own areas; navigation stays inside it.
205
+ const appModal = Array.from(doc.querySelectorAll<HTMLElement>("[data-app-modal]")).find(
206
+ isWorkspaceElementVisible,
207
+ );
208
+ const boundaries = Array.from(
209
+ doc.querySelectorAll<HTMLElement>(FOCUS_BOUNDARY_SELECTOR),
210
+ ).filter((boundary) => boundary !== appModal);
211
+ if (activePopup && !activePopup.closest(AREA_SELECTOR)) boundaries.push(activePopup);
212
+ // A modal keeps focus wherever it is; any other popup only while it holds focus,
213
+ // so hover popups and notifications never swallow the key.
214
+ if (
215
+ boundaries.some(
216
+ (boundary) =>
217
+ !(closingPalette && boundary.closest("[data-command-palette]")) &&
218
+ (boundary.matches('[aria-modal="true"]') || boundary.contains(doc.activeElement)) &&
219
+ isWorkspaceElementVisible(boundary),
220
+ )
221
+ )
222
+ return false;
223
+ const areas = Array.from((appModal ?? doc).querySelectorAll<HTMLElement>(AREA_SELECTOR))
224
+ .filter(isWorkspaceElementVisible)
225
+ .sort(
226
+ (left, right) => Number(left.dataset.workspaceOrder) - Number(right.dataset.workspaceOrder),
227
+ );
228
+ if (areas.length === 0) return false;
229
+ const activeArea = doc.activeElement?.closest<HTMLElement>(AREA_SELECTOR);
230
+ const currentId = fromArea ?? activeArea?.dataset.workspaceArea ?? lastArea;
231
+ const current = areas.findIndex((area) => area.dataset.workspaceArea === currentId);
232
+ const index =
233
+ current === -1
234
+ ? direction === 1
235
+ ? 0
236
+ : areas.length - 1
237
+ : (current + direction + areas.length) % areas.length;
238
+ const area = areas[index]!;
239
+ return focusArea(area);
240
+ };
241
+
242
+ // Focus that drops to the body because its element was hidden, made inert, or removed
243
+ // returns to the same control when React remounted it, else to its area, else the content.
244
+ const recover = (event: FocusEvent) => {
245
+ const lost = event.target;
246
+ if (!(lost instanceof HTMLElement) || event.relatedTarget) return;
247
+ const areaName = workspaceArea(lost)?.dataset.workspaceArea;
248
+ const label = lost.getAttribute("aria-label");
249
+ requestAnimationFrame(() => {
250
+ if (doc.activeElement !== doc.body || !doc.hasFocus() || isWorkspaceElementVisible(lost))
251
+ return;
252
+ const remounted = Array.from(doc.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)).find(
253
+ (element) =>
254
+ element.tagName === lost.tagName &&
255
+ ((lost.id && element.id === lost.id) ||
256
+ (label && element.getAttribute("aria-label") === label)) &&
257
+ isWorkspaceElementVisible(element),
258
+ );
259
+ if (remounted) remounted.focus({ preventScroll: true });
260
+ else if (!areaName || !focus(areaName)) focus("content");
261
+ });
262
+ };
263
+ doc.addEventListener("focusout", recover);
264
+
265
+ // A request names a destination React has not committed yet, so it retries as the
266
+ // DOM changes. User input cancels it, and it gives up after two seconds.
267
+ let pending: WorkspaceFocusTarget | undefined;
268
+ let frame = 0;
269
+ let deadline = 0;
270
+ let cancelOnInput = false;
271
+ const observer = new MutationObserver(() => schedule());
272
+ const cancelRequest = () => {
273
+ pending = undefined;
274
+ cancelOnInput = false;
275
+ observer.disconnect();
276
+ cancelAnimationFrame(frame);
277
+ clearTimeout(deadline);
278
+ };
279
+ const schedule = () => {
280
+ cancelAnimationFrame(frame);
281
+ frame = requestAnimationFrame(() => {
282
+ if (pending && focus(pending.area, pending.restore, pending.selector)) cancelRequest();
283
+ });
284
+ };
285
+ const request = (target: WorkspaceFocusTarget) => {
286
+ cancelRequest();
287
+ pending = target;
288
+ // The key or click that made the request may still be propagating.
289
+ queueMicrotask(() => {
290
+ if (pending === target) cancelOnInput = true;
291
+ });
292
+ observer.observe(doc.body, {
293
+ childList: true,
294
+ subtree: true,
295
+ attributes: true,
296
+ attributeFilter: ["inert", "aria-hidden", "data-workspace-unavailable"],
297
+ });
298
+ deadline = window.setTimeout(cancelRequest, 2000);
299
+ schedule();
300
+ };
301
+ const onUserInput = () => {
302
+ if (cancelOnInput) cancelRequest();
303
+ };
304
+ doc.addEventListener("pointerdown", onUserInput, true);
305
+ doc.addEventListener("keydown", onUserInput, true);
306
+
307
+ return {
308
+ move: (direction: 1 | -1, fromArea?: string, closingPalette = false) => {
309
+ cancelRequest();
310
+ return move(direction, fromArea, closingPalette);
311
+ },
312
+ focus,
313
+ request,
314
+ dispose: () => {
315
+ cancelRequest();
316
+ doc.removeEventListener("focusin", remember);
317
+ doc.removeEventListener("focusout", recover);
318
+ doc.removeEventListener("pointerdown", onUserInput, true);
319
+ doc.removeEventListener("keydown", onUserInput, true);
320
+ },
321
+ };
322
+}
323
+
324
+let controller: ReturnType<typeof createWorkspaceFocusController> | undefined;
325
+let focusRequestVersion = 0;
326
+export const getWorkspaceFocusRequestVersion = () => focusRequestVersion;
327
+
328
+/**
329
+ * Starts workspace focus for the app: F6 area moves, focus requests, focus-loss recovery,
330
+ * focus into a panel the user opens, and focus into the Pull Requests page on entry.
331
+ */
332
+export function startWorkspaceFocus(router: AnyRouter): () => void {
333
+ const active = createWorkspaceFocusController(document);
334
+ controller = active;
335
+ const stopPanels = useRightPanelStore.subscribe((state, previous) => {
336
+ if (state.userActionRevisionByThreadKey === previous.userActionRevisionByThreadKey) return;
337
+ for (const [threadKey, revision] of Object.entries(state.userActionRevisionByThreadKey)) {
338
+ if (previous.userActionRevisionByThreadKey[threadKey] === revision) continue;
339
+ const next = state.byThreadKey[threadKey];
340
+ const before = previous.byThreadKey[threadKey];
341
+ if (next?.isOpen && (!before?.isOpen || next.activeSurfaceId !== before.activeSurfaceId))
342
+ requestWorkspaceFocus({ area: "panel" });
343
+ }
344
+ });
345
+ const stopRoute = router.subscribe("onResolved", ({ fromLocation, toLocation }) => {
346
+ if (toLocation.pathname === "/pull-requests" && fromLocation?.pathname !== "/pull-requests")
347
+ requestWorkspaceFocus({ area: "pull-requests" });
348
+ });
349
+ return () => {
350
+ stopPanels();
351
+ stopRoute();
352
+ active.dispose();
353
+ if (controller === active) controller = undefined;
354
+ };
355
+}
356
+
357
+/** Moves to the next or previous visible area. `fromArea` overrides the focused area. */
358
+export function moveWorkspaceFocus(direction: 1 | -1, fromArea?: string): boolean {
359
+ return controller?.move(direction, fromArea) ?? false;
360
+}
361
+
362
+/** Explicit user actions request focus after React has committed the destination. */
363
+export function requestWorkspaceFocus(target: WorkspaceFocusTarget) {
364
+ focusRequestVersion++;
365
+ controller?.request(target);
366
+}
367
+
368
+export function requestWorkspaceContentFocus() {
369
+ // Resolve after the layout commits: closing a maximized panel makes the
370
+ // composer available again, while hiding a sidebar may leave only the panel.
371
+ requestWorkspaceFocus({ area: "content" });
372
+}
373
+
374
+let pendingPaletteDirection: 1 | -1 | undefined;
375
+export function queueWorkspaceFocusFromPalette(direction: 1 | -1) {
376
+ pendingPaletteDirection = direction;
377
+}
378
+
379
+/** Runs at the palette's normal focus restoration milestone, after its focus trap closes. */
380
+export function restoreWorkspaceFocusFromPalette(): boolean {
381
+ if (pendingPaletteDirection === undefined) return false;
382
+ const direction = pendingPaletteDirection;
383
+ pendingPaletteDirection = undefined;
384
+ window.requestAnimationFrame(() => controller?.move(direction, undefined, true));
385
+ return true;
386
+}
apps/web/src/routes/_chat.index.tsx
+7
-1
@@ -1,3 +1,4 @@
1
+import { workspaceAreaProps } from "../lib/workspaceFocus";
2
import { RefreshIcon } from "~/components/ui/refresh-icon";
3
import { scopeProjectRef } from "@t3tools/client-runtime/environment";
4
import { createFileRoute, useRouter } from "@tanstack/react-router";
@@ -86,8 +87,13 @@ function IndexDraftLanding() {
87
}
88
89
function DraftStartError({ onRetry }: { readonly onRetry: () => void }) {
90
+ const contentArea = workspaceAreaProps("home", 1, "Home");
91
return (
90
- <SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none">
92
+ <SidebarInset
93
+ {...contentArea}
94
+ role="main"
95
+ className="h-dvh min-h-0 overflow-hidden overscroll-y-none"
96
+ >
97
{isElectron ? <WorkspacePageHeader electron /> : null}
98
<Empty className="flex-1">
99
<EmptyHeader className="max-w-md">
apps/web/src/routes/_chat.settings.tsx
+3
-1
@@ -1,3 +1,4 @@
1
+import { workspaceAreaProps } from "../lib/workspaceFocus";
2
import { Outlet, createFileRoute, redirect, useLocation } from "@tanstack/react-router";
3
import { useState, type ReactNode } from "react";
4
import { RotateCcwIcon } from "lucide-react";
@@ -106,6 +107,7 @@ function SettingsScopeBoundary({ pathname, children }: { pathname: string; child
107
}
108
109
function SettingsContentLayout() {
110
+ const contentArea = workspaceAreaProps("settings", 1, "Settings content");
111
const location = useLocation();
112
const { search, environment } = useSettingsScope();
113
const contentScopeKey =
@@ -118,7 +120,7 @@ function SettingsContentLayout() {
120
<AppRouteModal label="Settings">
121
<div className="relative flex min-h-0 flex-1">
122
<SettingsSidebarNav pathname={location.pathname} />
121
- <div className="flex min-h-0 min-w-0 flex-1 flex-col">
123
+ <div {...contentArea} className="flex min-h-0 min-w-0 flex-1 flex-col">
124
<header className="flex h-12 shrink-0 items-center gap-3 border-b ps-5 pe-2">
125
<SettingsBreadcrumb pathname={location.pathname} />
126
<div className="ms-auto flex shrink-0 items-center gap-1">
docs/user/keyboard-focus.md
+29
-1
@@ -1,9 +1,37 @@
1
# Keyboard focus
2
3
-The command palette keeps focus while open. Closing it returns focus to the composer.
3
+The command palette keeps focus while open. Closing it returns focus to the composer in chat,
4
+or to the previous control on other pages. Choosing a workspace focus command moves to that
5
+area instead. Opening Pull Requests moves focus into that page.
6
While the palette or model picker is open, number shortcuts select its entries instead of
7
switching threads. Model shortcuts work in Settings as well as the composer.
8
See [Keybindings](./keybindings.md) to customize these shortcuts.
9
10
If you return to typing while a terminal is starting, the composer keeps focus when the terminal
11
becomes ready. Opening or switching to a terminal explicitly still focuses it.
12
+
13
+## Move between workspace areas
14
+
15
+On web and desktop, press `F6` or `Shift+F6` to move between the Threads sidebar,
16
+conversation, message input, and visible panels. Navigation wraps around and restores
17
+the last focused control in each area. Pull Requests has a page content area. In Settings,
18
+`F6` moves between the section list and the open section. Hidden areas are skipped. Other
19
+dialogs and form popups retain focus; a thread context menu closes when an area command
20
+moves focus away.
21
+
22
+In a browser, plain `F6` may move to the browser's own toolbar. Use `mod+F6` and
23
+`mod+Shift+F6` instead (`mod` is Command on macOS and Ctrl elsewhere). **Focus Next
24
+Workspace Area** and **Focus Previous Workspace Area** are also in the command palette and
25
+can be remapped in Settings > Keybindings.
26
+
27
+## Browse threads
28
+
29
+Tab enters the sidebar once. Up and Down move between threads without opening them; Enter
30
+opens the focused thread or toggles a group. Right and Left expand and collapse groups.
31
+Tab moves from the focused thread to its buttons. `F2` renames the focused thread.
32
+
33
+Press `Shift+F10` or the Context Menu key to open the focused thread's menu. Use the arrow
34
+keys to move through it, Enter to choose, and Escape to close it.
35
+
36
+The Settings section list works the same way: Up and Down move between sections, and Enter
37
+opens one.
packages/contracts/src/keybindings.ts
+2
@@ -57,6 +57,8 @@ const MODEL_PICKER_KEYBINDING_COMMANDS = [
57
export type ModelPickerKeybindingCommand = (typeof MODEL_PICKER_KEYBINDING_COMMANDS)[number];
58
59
export const STATIC_KEYBINDING_COMMANDS = [
60
+ "workspace.focusNext",
61
+ "workspace.focusPrevious",
62
"sidebar.toggle",
63
"navigation.back",
64
"navigation.forward",
packages/shared/src/keybindings.ts
+5
@@ -146,6 +146,11 @@ type WhenToken =
146
147
export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
148
{ key: "mod+b", command: "sidebar.toggle" },
149
+ { key: "f6", command: "workspace.focusNext" },
150
+ { key: "shift+f6", command: "workspace.focusPrevious" },
151
+ // Some browsers keep plain F6 for their own toolbars; mod+F6 reaches the page in all of them.
152
+ { key: "mod+f6", command: "workspace.focusNext" },
153
+ { key: "mod+shift+f6", command: "workspace.focusPrevious" },
154
{ key: "mod+[", command: "navigation.back", when: "!terminalFocus" },
155
{ key: "mod+]", command: "navigation.forward", when: "!terminalFocus" },
156
{ key: "mod+j", command: "terminal.toggle" },