Compare commits

...
Author SHA1 Message Date
Mohamed Boudra 6c22b883ca 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.
2026-11-23 19:17:29 +01:00
Mohamed Boudra f042a6754d 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.
2026-11-23 19:06:16 +01:00
9 changed files with 122 additions and 5 deletions
@@ -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,
}) => {
@@ -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,
}) => {
@@ -243,6 +243,14 @@ export async function openNewWorkspaceProjectPickerWithShortcut(
await expect(searchInput).toBeFocused();
}
export async function chooseProjectWithKeyboard(page: Page, projectName: string): Promise<void> {
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,
@@ -162,6 +162,7 @@ export interface HostPickerProps {
open: boolean;
onOpenChange: (open: boolean) => void;
anchorRef: React.RefObject<View | null>;
restoreFocusRef?: ComboboxProps["restoreFocusRef"];
includeAllHost?: boolean;
includeAddHost?: boolean;
onAddHost?: () => void;
@@ -185,6 +186,7 @@ export function HostPicker({
open,
onOpenChange,
anchorRef,
restoreFocusRef,
includeAllHost,
includeAddHost,
onAddHost,
@@ -306,6 +308,7 @@ export function HostPicker({
open={open}
onOpenChange={onOpenChange}
anchorRef={anchorRef}
restoreFocusRef={restoreFocusRef}
desktopPlacement={desktopPlacement}
desktopMinWidth={desktopMinWidth}
/>
@@ -138,6 +138,8 @@ export interface ComboboxProps {
/** When true, selecting an option does not close the picker (multi-select mode). */
keepOpenOnSelect?: boolean;
anchorRef: React.RefObject<View | null>;
/** Where focus goes when the picker closes. Defaults to whatever had focus when it opened. */
restoreFocusRef?: React.RefObject<unknown>;
children?: ReactNode;
}
@@ -1402,6 +1404,7 @@ export function Combobox({
footer,
keepOpenOnSelect = false,
anchorRef,
restoreFocusRef,
children,
}: ComboboxProps): ReactElement | null {
const { t } = useTranslation();
@@ -1667,6 +1670,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;
@@ -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<unknown>;
manageFocus?: boolean;
}
@@ -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<FocusTarget>).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<HTMLElement | null>(null);
const capturedRestoreFocusRef = useRef<FocusTarget | null>(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 =
@@ -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: (
<PluginNewWorkspaceItems serverId={selectedServerId} screen={pluginScreen} setup={setup} />
),
@@ -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}
@@ -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<unknown>;
project: PickerControl & {
options: ComboboxOption[];
projectByOptionId: Map<string, HostProjectListItem>;
@@ -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}
/>