From 60943dde1c491d0136ac9740a3cc7178fbbb1f6e Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Wed, 25 Nov 2026 22:14:42 +0700 Subject: [PATCH] Return focus to the prompt after choosing a New Workspace field (#10632) * fix(app): return focus to the composer after choosing a New Workspace field A closing picker restored focus to whatever had focus when it opened. Opening the project picker by clicking its trigger left focus on the trigger after a keyboard pick, and every later Cmd/Ctrl+N pick captured the trigger again, so the user had to click back into the prompt. The New Workspace form now passes the composer as the restore target for its pickers. The overlay accepts any handle with focus() as a restore target, so the composer's own retrying focus can be used instead of a raw DOM element. * fix(app): keep focus on the field when the terminal profile takes no prompt A terminal profile without a prompt shows a read-only command preview, so there is nothing to type into. Its pickers now fall back to returning focus to the field that opened them instead of losing focus to the preview. --- .../e2e/browser/new-workspace-entry.spec.ts | 28 +++++++++++++++++++ .../new-workspace-launch-terminal.spec.ts | 22 +++++++++++++++ .../app/e2e/support/helpers/new-workspace.ts | 8 ++++++ .../app/src/components/hosts/host-picker.tsx | 3 ++ packages/app/src/components/ui/combobox.tsx | 4 +++ .../src/keyboard/internal/overlay-contract.ts | 4 +++ .../internal/overlay-registration.web.ts | 25 ++++++++++++++--- .../app/src/screens/new-workspace-screen.tsx | 11 ++++++++ .../src/screens/new-workspace/form/index.tsx | 22 ++++++++++++++- 9 files changed, 122 insertions(+), 5 deletions(-) diff --git a/packages/app/e2e/browser/new-workspace-entry.spec.ts b/packages/app/e2e/browser/new-workspace-entry.spec.ts index b61f39e000..497982334c 100644 --- a/packages/app/e2e/browser/new-workspace-entry.spec.ts +++ b/packages/app/e2e/browser/new-workspace-entry.spec.ts @@ -1,6 +1,7 @@ import { expect, test } from "../support/fixtures"; import { gotoAppShell } from "../support/helpers/app"; import { + chooseProjectWithKeyboard, connectNewWorkspaceDaemonClient, expectNewWorkspaceControlsEnabled, expectNewWorkspaceProjectSelected, @@ -176,6 +177,33 @@ test.describe("New workspace entry points", () => { } }); + test("choosing a project returns focus to the composer, even when the picker was opened by clicking it", async ({ + page, + }) => { + const projectA: SeededWorkspace = await seedWorkspace({ repoPrefix: "entry-focus-a-" }); + const projectB: SeededWorkspace = await seedWorkspace({ repoPrefix: "entry-focus-b-" }); + + try { + await gotoAppShell(page); + await waitForSidebarHydration(page); + await openGlobalNewWorkspaceComposer(page); + const composer = page.getByRole("textbox", { name: "Message agent..." }); + + await page.getByTestId("new-workspace-project-picker-trigger").click(); + await chooseProjectWithKeyboard(page, projectB.projectDisplayName); + await expectNewWorkspaceProjectSelected(page, projectB.projectDisplayName); + await expect(composer).toBeFocused(); + + await page.keyboard.press("Control+N"); + await chooseProjectWithKeyboard(page, projectA.projectDisplayName); + await expectNewWorkspaceProjectSelected(page, projectA.projectDisplayName); + await expect(composer).toBeFocused(); + } finally { + await projectA.cleanup(); + await projectB.cleanup(); + } + }); + test("keeps the in-progress form when the remembered workspace is archived elsewhere", async ({ page, }) => { diff --git a/packages/app/e2e/browser/new-workspace-launch-terminal.spec.ts b/packages/app/e2e/browser/new-workspace-launch-terminal.spec.ts index 7268f7146b..e2ce2f942b 100644 --- a/packages/app/e2e/browser/new-workspace-launch-terminal.spec.ts +++ b/packages/app/e2e/browser/new-workspace-launch-terminal.spec.ts @@ -2,6 +2,7 @@ import { expect, test, type Page } from "../support/fixtures"; import { gotoAppShell } from "../support/helpers/app"; import { waitForSidebarHydration } from "../support/helpers/workspace-ui"; import { + chooseProjectWithKeyboard, expectNewWorkspaceDraft, fillNewWorkspaceDraft, openNewWorkspaceComposer, @@ -109,6 +110,27 @@ test.describe("New workspace: launching a terminal", () => { }); }); + test("with a profile that takes no prompt, choosing a project keeps focus on the Project field", async ({ + page, + }) => { + await gotoAppShell(page); + await waitForSidebarHydration(page); + await openNewWorkspaceComposer(page, { + projectKey: workspace.projectKey, + projectDisplayName: workspace.projectDisplayName, + }); + await selectLaunchOption(page, BARE_PROFILE.id); + await expect(terminalPromptInput(page)).toHaveCount(0); + + // The read-only command preview has nothing to type into, so the picker + // hands focus back to the field that opened it. + const projectTrigger = page.getByTestId("new-workspace-project-picker-trigger"); + await projectTrigger.focus(); + await page.keyboard.press("Enter"); + await chooseProjectWithKeyboard(page, workspace.projectDisplayName); + await expect(projectTrigger).toBeFocused(); + }); + test("switching terminal profiles restores the prompt and its fullscreen affordance", async ({ page, }) => { diff --git a/packages/app/e2e/support/helpers/new-workspace.ts b/packages/app/e2e/support/helpers/new-workspace.ts index 6d2833bc8c..74c0a0875a 100644 --- a/packages/app/e2e/support/helpers/new-workspace.ts +++ b/packages/app/e2e/support/helpers/new-workspace.ts @@ -243,6 +243,14 @@ export async function openNewWorkspaceProjectPickerWithShortcut( await expect(searchInput).toBeFocused(); } +export async function chooseProjectWithKeyboard(page: Page, projectName: string): Promise { + const searchInput = page.getByPlaceholder("Search projects"); + await expect(searchInput).toBeFocused({ timeout: 30_000 }); + await page.keyboard.type(projectName); + await page.keyboard.press("Enter"); + await expect(searchInput).toBeHidden({ timeout: 10_000 }); +} + export async function expectNewWorkspaceProjectSelected( page: Page, projectDisplayName: string, diff --git a/packages/app/src/components/hosts/host-picker.tsx b/packages/app/src/components/hosts/host-picker.tsx index 4051896640..019efc42a7 100644 --- a/packages/app/src/components/hosts/host-picker.tsx +++ b/packages/app/src/components/hosts/host-picker.tsx @@ -232,6 +232,7 @@ export interface HostPickerProps { open: boolean; onOpenChange: (open: boolean) => void; anchorRef: React.RefObject; + restoreFocusRef?: ComboboxProps["restoreFocusRef"]; includeAllHost?: boolean; includeAddHost?: boolean; onAddHost?: () => void; @@ -254,6 +255,7 @@ export function HostPicker({ open, onOpenChange, anchorRef, + restoreFocusRef, includeAllHost, includeAddHost, onAddHost, @@ -404,6 +406,7 @@ export function HostPicker({ open={open} onOpenChange={onOpenChange} anchorRef={anchorRef} + restoreFocusRef={restoreFocusRef} desktopPlacement={desktopPlacement} desktopMinWidth={desktopMinWidth} /> diff --git a/packages/app/src/components/ui/combobox.tsx b/packages/app/src/components/ui/combobox.tsx index 339c8b5285..25c2b490f8 100644 --- a/packages/app/src/components/ui/combobox.tsx +++ b/packages/app/src/components/ui/combobox.tsx @@ -146,6 +146,8 @@ export interface ComboboxProps { /** When true, selecting an option does not close the picker (multi-select mode). */ keepOpenOnSelect?: boolean; anchorRef: React.RefObject; + /** Where focus goes when the picker closes. Defaults to whatever had focus when it opened. */ + restoreFocusRef?: React.RefObject; children?: ReactNode; } @@ -1437,6 +1439,7 @@ export function Combobox({ footer, keepOpenOnSelect = false, anchorRef, + restoreFocusRef, children, }: ComboboxProps): ReactElement | null { const { t } = useTranslation(); @@ -1728,6 +1731,7 @@ export function Combobox({ layer: floatingLayer, keys: ["Escape", "Enter", "ArrowUp", "ArrowDown"], onKeyDown: (event) => (isDesktopKey(event.key) ? handleDesktopKey(event.key, event) : false), + restoreFocusRef, }); const effectiveSearchPlaceholder = searchPlaceholder ?? resolvedPlaceholder; diff --git a/packages/app/src/keyboard/internal/overlay-contract.ts b/packages/app/src/keyboard/internal/overlay-contract.ts index d5152e3518..61e851002d 100644 --- a/packages/app/src/keyboard/internal/overlay-contract.ts +++ b/packages/app/src/keyboard/internal/overlay-contract.ts @@ -9,6 +9,10 @@ export interface OverlayRegistration { */ keys: readonly string[]; onKeyDown(event: KeyboardInputEvent): boolean; + /** + * Where focus goes when the overlay closes: an element, or any handle with `focus()`. Defaults + * to whatever had focus when the overlay opened. + */ restoreFocusRef?: RefObject; manageFocus?: boolean; } diff --git a/packages/app/src/keyboard/internal/overlay-registration.web.ts b/packages/app/src/keyboard/internal/overlay-registration.web.ts index 1d579c5e31..564ad3cf07 100644 --- a/packages/app/src/keyboard/internal/overlay-registration.web.ts +++ b/packages/app/src/keyboard/internal/overlay-registration.web.ts @@ -3,12 +3,29 @@ import { overlays, type OverlayEntry, type KeyboardInputEvent } from "./overlays import type { OverlayRegistration } from "./overlay-contract"; type WebOverlayKeyHandler = (event: KeyboardInputEvent) => boolean; +/** A DOM element, or a component handle that knows how to focus itself (such as a text input). */ +interface FocusTarget { + focus(): void; +} + +function isFocusTarget(value: unknown): value is FocusTarget { + return ( + typeof value === "object" && + value !== null && + typeof (value as Partial).focus === "function" + ); +} + +function canRestoreFocusTo(target: FocusTarget): boolean { + return !(target instanceof HTMLElement) || document.contains(target); +} + interface WebOverlayEntry { getLayer: () => number; getKeys: () => readonly string[]; getScope: () => HTMLElement | null; getKeyHandler: () => WebOverlayKeyHandler; - restoreFocus: HTMLElement | null; + restoreFocus: FocusTarget | null; manageFocus: boolean; } @@ -156,7 +173,7 @@ function addWebOverlay(entry: WebOverlayEntry): (options?: RemoveWebOverlayOptio entry.manageFocus && options?.restoreFocus !== false && entry.restoreFocus && - document.contains(entry.restoreFocus) + canRestoreFocusTo(entry.restoreFocus) ) { entry.restoreFocus.focus(); } @@ -181,7 +198,7 @@ export function useOverlayRegistration({ keysRef.current = keys; const layerRef = useRef(layer); const keyHandlerRef = useRef(onKeyDown); - const capturedRestoreFocusRef = useRef(null); + const capturedRestoreFocusRef = useRef(null); const removeEntryRef = useRef<((options?: RemoveWebOverlayOptions) => void) | null>(null); const detachedRemoveEntryRef = useRef<((options?: RemoveWebOverlayOptions) => void) | null>(null); const registeredRef = useRef(false); @@ -193,7 +210,7 @@ export function useOverlayRegistration({ keyHandlerRef.current = onKeyDown; if (active && !wasActiveRef.current && typeof document !== "undefined") { const requestedRestoreTarget = preferredRestoreFocusRef?.current; - if (requestedRestoreTarget instanceof HTMLElement) { + if (isFocusTarget(requestedRestoreTarget)) { capturedRestoreFocusRef.current = requestedRestoreTarget; } else { capturedRestoreFocusRef.current = diff --git a/packages/app/src/screens/new-workspace-screen.tsx b/packages/app/src/screens/new-workspace-screen.tsx index e26fd6eae4..3db430d57a 100644 --- a/packages/app/src/screens/new-workspace-screen.tsx +++ b/packages/app/src/screens/new-workspace-screen.tsx @@ -1578,9 +1578,18 @@ export function NewWorkspaceScreen({ ? t("newWorkspace.refPicker.searching") : t("newWorkspace.refPicker.noMatchingRefs"); + // The prompt is where the user types; when a field's picker closes, focus returns there rather + // than to whatever had focus when the picker opened. A terminal profile that takes no prompt + // shows a read-only command preview, so its pickers keep returning focus to their field. + const composerFocusRef = useRef<{ focus: () => void } | null>(null); + const handleComposerFocusInput = useCallback((focus: () => void) => { + composerFocusRef.current = { focus }; + }, []); + const formStack = useNewWorkspaceForm({ isCompact, isPending, + restoreFocusRef: terminalTakesPrompt ? composerFocusRef : undefined, pluginItems: ( ), @@ -1682,6 +1691,7 @@ export function NewWorkspaceScreen({ clearDraft={noopClearDraft} autoFocus={terminalTakesPrompt} autoFocusKey={launchFocusKey} + onFocusInput={handleComposerFocusInput} error={errorMessage} /> ) : ( @@ -1712,6 +1722,7 @@ export function NewWorkspaceScreen({ clearDraft={handleClearDraft} autoFocus autoFocusKey={launchFocusKey} + onFocusInput={handleComposerFocusInput} commandDraft={composerState?.commandDraft} agentControls={agentControlsWithDisabled} error={errorMessage} diff --git a/packages/app/src/screens/new-workspace/form/index.tsx b/packages/app/src/screens/new-workspace/form/index.tsx index afacce7178..ee70e46165 100644 --- a/packages/app/src/screens/new-workspace/form/index.tsx +++ b/packages/app/src/screens/new-workspace/form/index.tsx @@ -67,6 +67,11 @@ export interface NewWorkspaceFormProps { isPending: boolean; /** Plugin fields, drawn after the base ref. */ pluginItems: ReactNode; + /** + * Where focus goes when a field's picker closes, so the user keeps typing the prompt. Without + * one, focus returns to the field that opened the picker. + */ + restoreFocusRef?: RefObject; project: PickerControl & { options: ComboboxOption[]; projectByOptionId: Map; @@ -373,7 +378,17 @@ function useRefPicker(base: NewWorkspaceFormProps["base"], isPending: boolean) { */ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement { const { t } = useTranslation(); - const { isCompact, isPending, pluginItems, project, host, isolation, base, launch } = props; + const { + isCompact, + isPending, + pluginItems, + restoreFocusRef, + project, + host, + isolation, + base, + launch, + } = props; const variant: FieldTriggerVariant = isCompact ? "field" : "badge"; const projectPicker = useProjectPicker(project, isPending); const isolationPicker = useIsolationPicker({ @@ -432,6 +447,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement open={host.openState} onOpenChange={host.onOpenChange} anchorRef={host.anchorRef} + restoreFocusRef={restoreFocusRef} includeAddHost onAddHost={host.onAddHost} addHostTestID="new-workspace-host-picker-add-host" @@ -525,6 +541,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement desktopPlacement="bottom-start" desktopMinWidth={360} anchorRef={project.anchorRef} + restoreFocusRef={restoreFocusRef} emptyText="No projects available." renderOption={projectPicker.renderOption} footer={projectPicker.footer} @@ -539,6 +556,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement searchable={false} desktopPlacement="bottom-start" anchorRef={isolation.anchorRef} + restoreFocusRef={restoreFocusRef} desktopMinWidth={280} renderOption={isolationPicker.renderOption} /> @@ -555,6 +573,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement desktopPlacement="bottom-start" desktopMinWidth={440} anchorRef={base.anchorRef} + restoreFocusRef={restoreFocusRef} emptyText={base.emptyText} toolbar={refPicker.toolbar} renderOption={refPicker.renderOption} @@ -571,6 +590,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement desktopPlacement="bottom-start" desktopMinWidth={360} anchorRef={worktreePicker.anchorRef} + restoreFocusRef={restoreFocusRef} emptyText={t("newWorkspace.worktreePicker.empty")} renderOption={worktreePicker.renderOption} />