The best way to control Claude Code, Codex and more from any computer or phone
fix(web): restore palette focus when no composer is mounted (#18850)
Co-authored-by: SAPHID <saphid@users.noreply.github.com> Co-authored-by: GPT-6.1 Sol <noreply@openai.com>
Alex Southwell committed
Oct 19, 2026 at 07:07 UTC
01d2aa87f5dd884bbe83c61842e80219400c33a9
3 files changed
+218
-6
apps/web/src/components/CommandPalette.focus.test.tsx
new
+208
@@ -0,0 +1,208 @@
1
+// @vitest-environment jsdom
2
+
3
+import { act, useImperativeHandle, useRef } from "react";
4
+import { createRoot, type Root } from "react-dom/client";
5
+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
6
+import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";
7
+import { CommandPalette } from "./CommandPalette";
8
+import { useComposerHandleContext } from "../composerHandleContext";
9
+import { openCommandPalette } from "../commandPaletteBus";
10
+import { primaryServerKeybindingsAtom } from "../state/server";
11
+
12
+vi.mock("@tanstack/react-router", () => ({
13
+ useNavigate: () => vi.fn(),
14
+ useParams: () => null,
15
+ useLocation: () => "/settings",
16
+}));
17
+vi.mock("@effect/atom-react", async (importOriginal) => {
18
+ const original = await importOriginal<typeof import("@effect/atom-react")>();
19
+ return {
20
+ ...original,
21
+ useAtomValue: (atom: unknown) =>
22
+ atom === primaryServerKeybindingsAtom ? DEFAULT_RESOLVED_KEYBINDINGS : [],
23
+ };
24
+});
25
+vi.mock("../hooks/useTheme", () => ({
26
+ useTheme: () => ({ theme: "default", resolvedTheme: "light", appearanceMode: "light" }),
27
+}));
28
+vi.mock("../hooks/useCustomThemes", () => ({ useCustomThemes: () => [] }));
29
+vi.mock("../hooks/useEnvironmentTheme", () => ({ useEnvironmentThemeDefinitions: () => [] }));
30
+vi.mock("../hooks/useSettings", async (importOriginal) => ({
31
+ ...(await importOriginal<typeof import("../hooks/useSettings")>()),
32
+ useClientSettings: () => ({}),
33
+}));
34
+vi.mock("../hooks/useScratchProject", () => ({
35
+ useScratchProject: () => ({ scratchEnvironmentId: () => null }),
36
+}));
37
+vi.mock("../hooks/useNewProject", () => ({ useNewProject: () => vi.fn() }));
38
+vi.mock("../hooks/useHandleNewThread", () => ({ useHandleNewThread: () => ({}) }));
39
+vi.mock("../hooks/useOpenPanelPullRequestUrl", () => ({ useOpenPanelPullRequestUrl: () => null }));
40
+vi.mock("../connection/useDesktopLocalBootstraps", () => ({ useDesktopLocalBootstraps: () => [] }));
41
+vi.mock("../state/use-atom-command", () => ({ useAtomCommand: () => vi.fn() }));
42
+vi.mock("../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => vi.fn() }));
43
+vi.mock("../state/environments", async (importOriginal) => ({
44
+ ...(await importOriginal<typeof import("../state/environments")>()),
45
+ useEnvironments: () => ({ environments: [] }),
46
+ usePrimaryEnvironmentId: () => null,
47
+}));
48
+vi.mock("../state/entities", async (importOriginal) => ({
49
+ ...(await importOriginal<typeof import("../state/entities")>()),
50
+ useProjects: () => [],
51
+ useThreadShells: () => [],
52
+ useServerConfigs: () => new Map(),
53
+}));
54
+vi.mock("../state/queries", async (importOriginal) => ({
55
+ ...(await importOriginal<typeof import("../state/queries")>()),
56
+ useThreadSearch: () => ({ matches: [] }),
57
+}));
58
+vi.mock("../state/session", async (importOriginal) => ({
59
+ ...(await importOriginal<typeof import("../state/session")>()),
60
+ useEnvironmentScope: () => false,
61
+}));
62
+vi.mock("../state/query", async (importOriginal) => ({
63
+ ...(await importOriginal<typeof import("../state/query")>()),
64
+ useEnvironmentQuery: () => ({}),
65
+}));
66
+vi.mock("./settings/useAvailableSettingsSearchItems", () => ({
67
+ useAvailableSettingsSearchItems: () => [],
68
+}));
69
+
70
+let root: Root;
71
+let container: HTMLDivElement;
72
+
73
+beforeEach(() => {
74
+ vi.useFakeTimers();
75
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
76
+ vi.stubGlobal(
77
+ "ResizeObserver",
78
+ class {
79
+ observe() {}
80
+ disconnect() {}
81
+ unobserve() {}
82
+ },
83
+ );
84
+ Object.defineProperty(Element.prototype, "getAnimations", {
85
+ configurable: true,
86
+ value: () => [],
87
+ });
88
+ container = document.createElement("div");
89
+ document.body.append(container);
90
+ root = createRoot(container);
91
+});
92
+
93
+afterEach(async () => {
94
+ await act(async () => {
95
+ root.unmount();
96
+ await vi.runOnlyPendingTimersAsync();
97
+ });
98
+ container.remove();
99
+ vi.unstubAllGlobals();
100
+ vi.useRealTimers();
101
+});
102
+
103
+async function flushFocus() {
104
+ await act(() => vi.advanceTimersByTimeAsync(0));
105
+ await act(() => vi.advanceTimersToNextFrame());
106
+}
107
+
108
+async function dismissPalette() {
109
+ await act(() =>
110
+ document.activeElement?.dispatchEvent(
111
+ new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true }),
112
+ ),
113
+ );
114
+ await flushFocus();
115
+ expect(document.querySelector("[data-command-palette]")).toBeNull();
116
+}
117
+
118
+function Composer() {
119
+ const handle = useComposerHandleContext();
120
+ const input = useRef<HTMLTextAreaElement>(null);
121
+ useImperativeHandle(
122
+ handle,
123
+ () =>
124
+ ({
125
+ focusAtEnd: () => {
126
+ input.current?.focus();
127
+ input.current?.setSelectionRange(input.current.value.length, input.current.value.length);
128
+ },
129
+ }) as NonNullable<NonNullable<typeof handle>["current"]>,
130
+ );
131
+ return <textarea ref={input} aria-label="Composer" defaultValue="Draft prompt" />;
132
+}
133
+
134
+describe("command palette focus restoration", () => {
135
+ it("returns to the previously focused Settings field when no composer is mounted", async () => {
136
+ await act(() =>
137
+ root.render(
138
+ <CommandPalette>
139
+ <input aria-label="Settings field" />
140
+ </CommandPalette>,
141
+ ),
142
+ );
143
+ const field = container.querySelector("input")!;
144
+ await act(() => field.focus());
145
+ await act(() => openCommandPalette());
146
+ await flushFocus();
147
+ expect(document.activeElement?.closest("[data-command-palette]")).not.toBeNull();
148
+ await dismissPalette();
149
+ expect(document.activeElement).toBe(field);
150
+ });
151
+
152
+ it("focuses the replacement command input after leaving the file picker", async () => {
153
+ await act(() =>
154
+ root.render(
155
+ <CommandPalette>
156
+ <input aria-label="Settings field" />
157
+ </CommandPalette>,
158
+ ),
159
+ );
160
+ const field = container.querySelector("input")!;
161
+ await act(() => field.focus());
162
+ await act(() =>
163
+ field.dispatchEvent(
164
+ new KeyboardEvent("keydown", {
165
+ key: "p",
166
+ ctrlKey: true,
167
+ bubbles: true,
168
+ cancelable: true,
169
+ }),
170
+ ),
171
+ );
172
+ await flushFocus();
173
+ expect(document.querySelector('[data-palette-mode="files"]')).not.toBeNull();
174
+ await act(() =>
175
+ document.activeElement?.dispatchEvent(
176
+ new KeyboardEvent("keydown", {
177
+ key: "Escape",
178
+ bubbles: true,
179
+ cancelable: true,
180
+ }),
181
+ ),
182
+ );
183
+ await flushFocus();
184
+ expect(document.activeElement?.closest('[data-palette-mode="command"]')).not.toBeNull();
185
+ expect(document.activeElement?.tagName).toBe("INPUT");
186
+ await dismissPalette();
187
+ expect(document.activeElement).toBe(field);
188
+ });
189
+
190
+ it("focuses the mounted composer at the end instead of the previous field", async () => {
191
+ await act(() =>
192
+ root.render(
193
+ <CommandPalette>
194
+ <input aria-label="Previous field" />
195
+ <Composer />
196
+ </CommandPalette>,
197
+ ),
198
+ );
199
+ await act(() => container.querySelector("input")!.focus());
200
+ await act(() => openCommandPalette());
201
+ await flushFocus();
202
+ expect(document.activeElement?.closest("[data-command-palette]")).not.toBeNull();
203
+ await dismissPalette();
204
+ const composer = container.querySelector("textarea")!;
205
+ expect(document.activeElement).toBe(composer);
206
+ expect(composer.selectionStart).toBe(composer.value.length);
207
+ });
208
+});
apps/web/src/components/CommandPalette.tsx
+3
-1
@@ -668,7 +668,9 @@ function CommandPaletteDialog(props: {
668
data-palette-mode={props.mode}
669
data-testid="command-palette"
670
finalFocus={() => {
671
- composerHandleRef?.current?.focusAtEnd();
671
+ const composer = composerHandleRef?.current;
672
+ if (!composer) return true;
673
+ composer.focusAtEnd();
674
return false;
675
}}
676
onBackdropPointerDown={() => {
apps/web/src/components/CommandPaletteContent.tsx
+7
-5
@@ -1,5 +1,5 @@
1
import { ArrowDownIcon, ArrowUpIcon } from "lucide-react";
2
-import { type ComponentProps, type ReactNode, useLayoutEffect, useRef } from "react";
2
+import { type ComponentProps, type ReactNode, useEffect, useRef } from "react";
3
4
import { Command, CommandFooter, CommandInput, CommandPanel } from "./ui/command";
5
import { Kbd, KbdGroup } from "./ui/kbd";
@@ -32,16 +32,18 @@ export function CommandPaletteContent({
32
33
// Direct-open flows replace the initial palette view after the dialog has
34
// already moved focus. Reclaim it when the replacement input mounts so
35
- // typing cannot continue in the composer behind the modal.
36
- useLayoutEffect(() => {
37
- inputRef.current?.focus();
35
+ // typing cannot continue in the composer behind the modal. Defer until the
36
+ // dialog has recorded the previous focus target for restoration on close.
37
+ useEffect(() => {
38
+ const frame = requestAnimationFrame(() => inputRef.current?.focus());
39
+ return () => cancelAnimationFrame(frame);
40
}, []);
41
42
return (
43
<div className="contents" data-testid={testId}>
44
<Command {...commandProps}>
45
<div className="relative">
44
- <CommandInput {...inputProps} ref={inputRef} />
46
+ <CommandInput autoFocus={false} {...inputProps} ref={inputRef} />
47
{inputAccessory}
48
</div>
49
<CommandPanel