diff --git a/src/renderer/src/components/agent/AgentLaunchPickerMenu.keyboard.test.tsx b/src/renderer/src/components/agent/AgentLaunchPickerMenu.keyboard.test.tsx new file mode 100644 index 000000000000..87f1142f9b62 --- /dev/null +++ b/src/renderer/src/components/agent/AgentLaunchPickerMenu.keyboard.test.tsx @@ -0,0 +1,249 @@ +// @vitest-environment happy-dom +import { useState } from 'react' +import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { afterEach, expect, it, vi } from 'vitest' +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuTrigger +} from '@/components/ui/dropdown-menu' +import { TooltipProvider } from '@/components/ui/tooltip' +import { AgentLaunchPickerMenu } from './AgentLaunchPickerMenu' +import type { AgentPickerEntry } from '../../../../shared/agent-launch-picker' + +vi.mock('@/hooks/useShortcutLabel', () => ({ useOptionalShortcutLabel: () => null })) +afterEach(cleanup) +afterEach(() => vi.restoreAllMocks()) + +const entries: AgentPickerEntry[] = (['codex', 'claude'] as const).map((agent) => ({ + agent: agent, + label: agent === 'codex' ? 'Codex' : 'Claude', + rows: [{ agent: agent, kind: 'chat' }], + surfaces: ['chat'], + defaultSurface: 'chat', + terminal: {}, + structured: {}, + catalog: { + origin: 'probe', + fetchedAt: 1, + models: [{ id: 'default', label: 'Default', isDefault: true, efforts: [] }] + } +})) + +function show(controlled = false) { + const launched = vi.fn() + const changed = vi.fn() + function Menu() { + const [open, setOpen] = useState(true) + return ( + + { + changed(next) + setOpen(next) + }} + > + New tab + + + + + + ) + } + render() + return { launched, changed } +} + +it('moves one agent per Up/Down press, including after returning from its submenu', async () => { + const { launched } = show() + const user = userEvent.setup() + const codex = screen.getByRole('menuitem', { name: /^Codex/ }) + const claude = screen.getByRole('menuitem', { name: /^Claude/ }) + codex.focus() + await user.keyboard('{ArrowDown}') + await waitFor(() => expect(document.activeElement).toBe(claude)) + await user.keyboard('{ArrowUp}') + await waitFor(() => expect(document.activeElement).toBe(codex)) + await user.keyboard('{ArrowRight}') + expect(screen.getByRole('menu', { name: 'Configure Codex' })).toBeTruthy() + await waitFor(() => + expect(document.activeElement).toBe(screen.getByPlaceholderText('Search Codex models…')) + ) + await user.keyboard('{Escape}') + await waitFor(() => + expect(document.activeElement).toBe(screen.getByRole('button', { name: 'Configure Codex' })) + ) + await user.keyboard('{ArrowRight}') + expect(document.activeElement).toBe(screen.getByPlaceholderText('Search Codex models…')) + await user.keyboard('{Escape}') + await user.keyboard('{ArrowDown}') + await waitFor(() => expect(document.activeElement).toBe(claude)) + expect(launched).not.toHaveBeenCalled() +}) + +it.each(['hover', 'click'] as const)( + 'focuses model search when the chevron opens by %s', + async (method) => { + const { launched } = show() + const user = userEvent.setup({ skipHover: method === 'click' }) + const segment = screen.getByRole('button', { name: 'Configure Codex' }) + await user[method](segment) + const search = screen.getByPlaceholderText('Search Codex models…') + await waitFor(() => expect(document.activeElement).toBe(search)) + fireEvent.pointerMove(segment, { pointerType: 'mouse' }) + expect(document.activeElement).toBe(search) + await user.keyboard('missing') + expect(search.value).toBe('missing') + expect(screen.getByText('No models match your search.')).toBeTruthy() + expect(launched).not.toHaveBeenCalled() + } +) + +it('returns from empty search with Left Arrow, then reopens and navigates the main menu', async () => { + const { launched, changed } = show() + const user = userEvent.setup() + const codex = screen.getByRole('menuitem', { name: /^Codex/ }) + codex.focus() + await user.keyboard('{ArrowRight}') + expect(document.activeElement).toBe(screen.getByPlaceholderText('Search Codex models…')) + await user.keyboard('{ArrowLeft}') + expect(screen.queryByRole('menu', { name: 'Configure Codex' })).toBeNull() + expect(document.activeElement).toBe(codex) + expect(screen.getByRole('menu', { name: 'New tab' })).toBeTruthy() + await user.keyboard('{ArrowRight}') + expect(document.activeElement).toBe(screen.getByPlaceholderText('Search Codex models…')) + await user.keyboard('{ArrowLeft}{ArrowDown}') + await waitFor(() => + expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: /^Claude/ })) + ) + expect(changed).not.toHaveBeenCalled() + expect(launched).not.toHaveBeenCalled() +}) + +it('keeps Left Arrow editing a typed search and returns after the search is cleared', async () => { + show() + const user = userEvent.setup() + await user.click(screen.getByRole('button', { name: 'Configure Codex' })) + const search = screen.getByPlaceholderText('Search Codex models…') + await user.keyboard('query{ArrowLeft}') + expect(search.selectionStart).toBe(4) + expect(document.activeElement).toBe(search) + expect(screen.getByRole('menu', { name: 'Configure Codex' })).toBeTruthy() + await user.clear(search) + fireEvent.keyDown(search, { key: 'ArrowLeft', isComposing: true }) + expect(screen.getByRole('menu', { name: 'Configure Codex' })).toBeTruthy() + await user.keyboard('{ArrowLeft}') + expect(screen.queryByRole('menu', { name: 'Configure Codex' })).toBeNull() + expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: /^Codex/ })) +}) + +it.each([false, true])( + 'closes a controlled=%s menu once after default launch', + async (controlled) => { + const { launched, changed } = show(controlled) + await userEvent.setup().click(screen.getByRole('menuitem', { name: /^Codex/ })) + expect(launched).toHaveBeenCalledExactlyOnceWith(entries[0].rows[0], undefined) + await waitFor(() => expect(screen.queryByRole('menu')).toBeNull()) + expect(changed).toHaveBeenCalledExactlyOnceWith(false) + } +) + +it('only opens setup from the chevron segment, never from hovering the agent name or icon', async () => { + const { launched } = show() + const codex = screen.getByRole('menuitem', { name: /^Codex/ }) + const claude = screen.getByRole('menuitem', { name: /^Claude/ }) + vi.useFakeTimers() + try { + for (const target of [codex, screen.getByText('Codex'), codex.querySelector('svg')!]) { + fireEvent.pointerMove(target, { pointerType: 'mouse' }) + await act(() => vi.advanceTimersByTimeAsync(200)) + expect(screen.queryByRole('menu', { name: 'Configure Codex' })).toBeNull() + expect(document.activeElement).toBe(codex) + } + + fireEvent.pointerOver(screen.getByRole('button', { name: 'Configure Codex' }), { + pointerType: 'mouse' + }) + expect(screen.getByRole('menu', { name: 'Configure Codex' })).toBeTruthy() + + fireEvent.pointerMove(screen.getByText('Claude'), { pointerType: 'mouse' }) + await act(() => vi.advanceTimersByTimeAsync(200)) + expect(document.activeElement).toBe(claude) + expect(screen.queryByRole('menu', { name: 'Configure Claude' })).toBeNull() + expect(screen.queryByRole('menu', { name: 'Configure Codex' })).toBeNull() + expect(launched).not.toHaveBeenCalled() + } finally { + vi.useRealTimers() + } +}) + +it('keeps wheel highlighting on the agent under the resting pointer without opening setup', () => { + const { launched } = show() + const codex = screen.getByRole('menuitem', { name: /^Codex/ }) + const claude = screen.getByRole('menuitem', { name: /^Claude/ }) + const menu = screen.getByRole('menu', { name: 'New tab' }) + const frames: FrameRequestCallback[] = [] + vi.spyOn(window, 'requestAnimationFrame').mockImplementation((callback) => frames.push(callback)) + vi.spyOn(document, 'elementFromPoint').mockReturnValue(claude) + codex.focus() + const wheel = new WheelEvent('wheel', { bubbles: true }) + Object.defineProperties(wheel, { clientX: { value: 10 }, clientY: { value: 40 } }) + fireEvent(menu, wheel) + fireEvent.pointerMove(screen.getByText('Codex'), { + pointerType: 'mouse', + clientX: 10, + clientY: 40 + }) + fireEvent.scroll(menu) + act(() => frames.splice(0).forEach((callback) => callback(0))) + expect(document.activeElement).toBe(claude) + expect(screen.queryByRole('menu', { name: /^Configure/ })).toBeNull() + expect(launched).not.toHaveBeenCalled() +}) + +it('does not launch when a row press is released over the submenu trigger', async () => { + const { launched } = show() + const configure = screen.getByRole('button', { name: 'Configure Codex' }) + const row = screen.getByRole('menuitem', { name: /^Codex/ }) + const user = userEvent.setup() + await user.pointer([ + { target: screen.getByText('Codex'), keys: '[MouseLeft>]' }, + { target: configure, keys: '[/MouseLeft]' } + ]) + expect(launched).not.toHaveBeenCalled() + await user.click(row.querySelector('span')!) + expect(launched).toHaveBeenCalledOnce() +}) + +it('preserves search focus while crossing another row toward a left-opening submenu', async () => { + const { launched } = show() + await userEvent.setup().hover(screen.getByRole('button', { name: 'Configure Codex' })) + const panel = screen.getByRole('menu', { name: 'Configure Codex' }) + const search = screen.getByPlaceholderText('Search Codex models…') + const codex = screen.getByRole('menuitem', { name: /^Codex/ }) + const claude = screen.getByRole('menuitem', { name: /^Claude/ }) + const menu = screen.getByRole('menu', { name: 'New tab' }) + panel.dataset.side = 'left' + vi.spyOn(panel, 'getBoundingClientRect').mockReturnValue(new DOMRect(100, 20, 300, 180)) + for (const clientX of [500, 460]) { + fireEvent.pointerMove(menu, { pointerType: 'mouse', clientX, clientY: 45 }) + } + fireEvent.pointerOut(codex, { + pointerType: 'mouse', + clientX: 450, + clientY: 50, + relatedTarget: claude + }) + fireEvent.pointerMove(claude, { pointerType: 'mouse', clientX: 440, clientY: 60 }) + expect(document.activeElement).toBe(search) + expect(panel.dataset.state).toBe('open') + fireEvent.pointerMove(claude, { pointerType: 'mouse', clientX: 460, clientY: 230 }) + expect(document.activeElement).toBe(claude) + expect(screen.queryByRole('menu', { name: /^Configure/ })).toBeNull() + expect(launched).not.toHaveBeenCalled() +}) diff --git a/src/renderer/src/components/agent/AgentLaunchPickerMenu.search.test.tsx b/src/renderer/src/components/agent/AgentLaunchPickerMenu.search.test.tsx index ba3cd12d5405..dd6ed105bb54 100644 --- a/src/renderer/src/components/agent/AgentLaunchPickerMenu.search.test.tsx +++ b/src/renderer/src/components/agent/AgentLaunchPickerMenu.search.test.tsx @@ -7,15 +7,21 @@ import { AgentLaunchPickerMenu } from './AgentLaunchPickerMenu' import { DropdownMenu, DropdownMenuContent, - DropdownMenuTrigger + DropdownMenuTrigger, + DropdownMenuSub, + DropdownMenuSubTrigger } from '@/components/ui/dropdown-menu' import type { AgentPickerEntry } from '../../../../shared/agent-launch-picker' vi.mock('@/hooks/useShortcutLabel', () => ({ useOptionalShortcutLabel: () => null })) vi.mock('./AgentLaunchSetupButton', () => ({ - AgentLaunchSetupButton: vi.fn((props: ComponentProps) => - props.renderAnchor?.() - ) + AgentLaunchSetupButton: vi.fn((props: ComponentProps) => ( + + + {props.renderAnchor?.()} + + + )) })) afterEach(() => { cleanup() diff --git a/src/renderer/src/components/agent/AgentLaunchPickerMenu.test.tsx b/src/renderer/src/components/agent/AgentLaunchPickerMenu.test.tsx index 2f93dea87d07..3c70c36f3564 100644 --- a/src/renderer/src/components/agent/AgentLaunchPickerMenu.test.tsx +++ b/src/renderer/src/components/agent/AgentLaunchPickerMenu.test.tsx @@ -8,6 +8,7 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest' import { DropdownMenu, DropdownMenuContent, + DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu' import { TooltipProvider } from '@/components/ui/tooltip' @@ -166,7 +167,24 @@ it.each([ terminal: { model: 'astra', permissionMode: 'ask' }, structured: { model: 'astra', permissionMode: 'ask' } } - show(hydrated) + const showPopover = (value: AgentPickerEntry) => + act(() => + root.render( + + + New tab + + {trigger}} + /> + + + + ) + ) + showPopover(hydrated) let viewportWidth = viewport let placementReads = 0 const observers = new Set() @@ -339,7 +357,7 @@ it.each([ expect(content.querySelector('button[aria-label="Codex permissions"]')?.textContent).toContain( 'Full access' ) - show({ ...hydrated }) + showPopover({ ...hydrated }) expect(document.querySelector('[role="menuitem"]')?.isConnected).toBe(true) await waitFor(() => { expect(content.parentElement!.style.transform).toBe(originalTransform) @@ -418,14 +436,16 @@ it.each([ it('opens setup with a clicked chevron without launching, then dispatches its selected surface once', () => { const configure = getByRole(document.body, 'button', { name: 'Configure Codex' }) - expect(configure?.dataset.variant).toBe('ghost') - expect(configure?.previousElementSibling?.getAttribute('data-orientation')).toBe('vertical') + expect(configure?.closest('[data-agent-launch-row]')?.getAttribute('data-slot')).toBe( + 'dropdown-menu-sub-trigger' + ) + expect(configure?.previousElementSibling?.getAttribute('data-orientation')).not.toBe('vertical') act(() => configure?.click()) expect(launch).not.toHaveBeenCalled() expect(document.body.textContent).toContain('Arguments') - expect(getByRole(document.body, 'dialog', { name: 'Configure Codex' })).not.toBeNull() + expect(getByRole(document.body, 'menu', { name: 'Configure Codex' })).not.toBeNull() const terminal = [...document.querySelectorAll('button')].find( - (button) => button.textContent === 'Launch terminal' + (button) => button.getAttribute('aria-label') === 'Launch terminal' ) act(() => terminal?.click()) expect(launch).toHaveBeenCalledTimes(1) @@ -439,8 +459,10 @@ it('opens the setup panel on the menu layer so it stacks above the new tab menu' act(() => getByRole(document.body, 'button', { name: 'Configure Codex' }).click()) // happy-dom computes no stacking, so compare the z-index utilities the layers come from. const layer = (element: HTMLElement) => element.className.match(/\bz-\[\d+\]/)?.[0] - const panel = layer(getByRole(document.body, 'dialog', { name: 'Configure Codex' })) - expect(panel).toBe(layer(getByRole(document.body, 'menu'))) + const panel = layer(getByRole(document.body, 'menu', { name: 'Configure Codex' })) + expect(panel).toBe( + layer(document.querySelector('[data-slot="dropdown-menu-content"]')!) + ) expect(panel).not.toBe('z-[60]') }) it('keeps setup open while the pointer expands and collapses Arguments', async () => { @@ -448,75 +470,55 @@ it('keeps setup open while the pointer expands and collapses Arguments', async ( await user.click( document.querySelector('button[aria-label="Configure Codex"]')! ) - const panel = document.querySelector('[role="dialog"]')! + const panel = document.querySelector('[data-slot="dropdown-menu-sub-content"]')! expect(panel).not.toBeNull() expect(panel.querySelector('textarea[aria-label="Arguments"]')).toBeNull() const toggle = panel.querySelector('button[aria-label="Toggle Arguments"]')! await user.hover(toggle) - expect(document.querySelector('[role="dialog"]')).toBe(panel) + expect(document.querySelector('[data-slot="dropdown-menu-sub-content"]')).toBe(panel) await user.click(toggle) - expect(document.querySelector('[role="dialog"]')).toBe(panel) + expect(document.querySelector('[data-slot="dropdown-menu-sub-content"]')).toBe(panel) expect(panel.querySelector('textarea[aria-label="Arguments"]')).not.toBeNull() await user.click(toggle) - expect(document.querySelector('[role="dialog"]')).toBe(panel) + expect(document.querySelector('[data-slot="dropdown-menu-sub-content"]')).toBe(panel) expect(panel.querySelector('textarea[aria-label="Arguments"]')).toBeNull() expect(launch).not.toHaveBeenCalled() }) -it.each(['{Enter}', ' '])( - 'keeps setup on hover, replaces it on keyboard %s, and dismisses without launching', - async (key) => { - show(entry, [ - { - ...entry, - agent: 'claude', - label: 'Claude', - rows: [{ agent: 'claude', kind: 'chat' }] - } - ]) - const user = userEvent.setup() - await user.click( - document.querySelector('button[aria-label="Configure Codex"]')! - ) - const panel = document.querySelector('[role="dialog"]')! - expect(panel).not.toBeNull() - const closeAutoFocus = vi.fn() - panel.addEventListener('focusScope.autoFocusOnUnmount', closeAutoFocus, { once: true }) - const otherRow = [...document.querySelectorAll('[role="menuitem"]')].find( - (row) => row.textContent === 'Claude' - )! - fireEvent.pointerMove(otherRow, { pointerType: 'mouse' }) - await waitFor(() => expect(document.activeElement).toBe(otherRow)) - expect(document.querySelector('[role="dialog"]')).toBe(panel) - await user.keyboard('{ArrowRight}') - const otherTrigger = document.querySelector( - 'button[aria-label="Configure Claude"]' - )! - expect(document.activeElement).toBe(otherTrigger) - await user.keyboard(key) - await waitFor(() => expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(1)) - const replacement = document.querySelector('[role="dialog"]')! - const search = replacement.querySelector( - 'input[placeholder="Search Claude models…"]' - )! - expect(search).not.toBeNull() - expect(replacement).not.toBe(panel) - await waitFor(() => expect(panel.isConnected).toBe(false)) - await waitFor(() => expect(closeAutoFocus).toHaveBeenCalledOnce()) - expect(document.activeElement).toBe(search) - await user.keyboard('astra') - expect(search.value).toBe('astra') - expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(1) - await user.keyboard('{Escape}') - await waitFor(() => expect(document.querySelector('[role="dialog"]')).toBeNull()) - await waitFor(() => expect(document.activeElement).toBe(otherTrigger)) - await user.click(otherTrigger) - expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(1) - fireEvent.pointerDown(document.body, { pointerType: 'mouse', button: 0 }) - await waitFor(() => expect(document.querySelector('[role="dialog"]')).toBeNull()) - expect(launch).not.toHaveBeenCalled() - } -) +it('opens on chevron hover, crosses into setup, and switches agents without launching', async () => { + show(entry, [ + { ...entry, agent: 'claude', label: 'Claude', rows: [{ agent: 'claude', kind: 'chat' }] } + ]) + const user = userEvent.setup() + const codex = getByRole(document.body, 'button', { name: 'Configure Codex' }) + await user.hover(codex) + const panel = await waitFor(() => getByRole(document.body, 'menu', { name: 'Configure Codex' })) + await user.hover(panel) + expect(panel.isConnected).toBe(true) + const claude = getByRole(document.body, 'button', { name: 'Configure Claude' }) + await user.hover(claude) + await waitFor(() => + expect(document.querySelectorAll('[data-slot="dropdown-menu-sub-content"]')).toHaveLength(1) + ) + await waitFor(() => + expect(getByRole(document.body, 'menu', { name: 'Configure Claude' })).toBeTruthy() + ) + expect(panel.isConnected).toBe(false) + expect(launch).not.toHaveBeenCalled() +}) + +it('opens with ArrowRight and returns to the trigger with ArrowLeft', async () => { + const user = userEvent.setup() + const row = document.querySelector('[data-agent-launch-row]')! + act(() => row.focus()) + await user.keyboard('{ArrowRight}') + const panel = getByRole(document.body, 'menu', { name: 'Configure Codex' }) + act(() => getByRole(panel, 'button', { name: 'Toggle Arguments' }).focus()) + await user.keyboard('{ArrowLeft}') + expect(document.querySelector('[data-slot="dropdown-menu-sub-content"]')).toBeNull() + expect(document.activeElement).toBe(row) + expect(launch).not.toHaveBeenCalled() +}) it('keeps model, permission and Fast badge pointer interactions inside setup, but dismisses outside', async () => { show({ @@ -541,11 +543,11 @@ it('keeps model, permission and Fast badge pointer interactions inside setup, bu await user.click( document.querySelector('button[aria-label="Configure Claude"]')! ) - const panel = document.querySelector('[role="dialog"]')! + const panel = document.querySelector('[data-slot="dropdown-menu-sub-content"]')! const model = panel.querySelector('[cmdk-item]')! await user.hover(model) await user.click(model) - expect(document.querySelector('[role="dialog"]')).toBe(panel) + expect(document.querySelector('[data-slot="dropdown-menu-sub-content"]')).toBe(panel) await user.click( panel.querySelector('button[aria-label="Claude permissions"]')! ) @@ -554,16 +556,16 @@ it('keeps model, permission and Fast badge pointer interactions inside setup, bu item.textContent?.startsWith('Full access') )! ) - expect(document.querySelector('[role="dialog"]')).toBe(panel) + expect(document.querySelector('[data-slot="dropdown-menu-sub-content"]')).toBe(panel) await user.click(panel.querySelector('button[aria-label="Toggle Arguments"]')!) const chip = panel.querySelector('button[aria-label*="Remove --settings"]')! expect(chip).not.toBeNull() await user.click(chip) - expect(document.querySelector('[role="dialog"]')).toBe(panel) + expect(document.querySelector('[data-slot="dropdown-menu-sub-content"]')).toBe(panel) expect(panel.querySelector('button[aria-label*="Remove --settings"]')).toBeNull() expect(panel.querySelector('textarea')?.value).toContain('"theme":"light"') await user.click(document.body) - expect(document.querySelector('[role="dialog"]')).toBeNull() + expect(document.querySelector('[data-slot="dropdown-menu-sub-content"]')).toBeNull() expect(launch).not.toHaveBeenCalled() }) @@ -582,7 +584,7 @@ it('opens a searched setup only from its chevron and launches the alternate way act(() => row.querySelector('button')?.click()) expect(launch).not.toHaveBeenCalled() const alternate = [...document.querySelectorAll('button')].find( - (button) => button.textContent === 'Launch terminal' + (button) => button.getAttribute('aria-label') === 'Launch terminal' ) act(() => alternate?.click()) expect(launch).toHaveBeenCalledTimes(1) @@ -624,9 +626,7 @@ it('still launches today’s default when the row is clicked while its setup is }) it('lets the chevron return keyboard focus to its row without opening or launching', () => { - const configure = document.querySelector( - 'button[aria-label="Configure Codex"]' - ) + const configure = getByRole(document.body, 'button', { name: 'Configure Codex' }) act(() => { configure?.focus() configure?.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowLeft', bubbles: true })) @@ -658,9 +658,7 @@ it('launches the searched default once from Enter', () => { }) it('closes Configure with Escape without dispatch and returns focus to its trigger', async () => { - const configure = document.querySelector( - 'button[aria-label="Configure Codex"]' - )! + const configure = getByRole(document.body, 'button', { name: 'Configure Codex' })! act(() => configure.click()) const search = document.querySelector('input[aria-label="Search models"]')! act(() => { @@ -706,7 +704,9 @@ it('retains authored Arguments on close/reopen and rebinds their acquisition aut show({ ...own, ownerKey: 'pair8/runtime2', arguments: '--add-dir new-owner' }) expect(document.querySelector('textarea')?.value).toBe('--add-dir old-owner') fireEvent.click( - [...document.querySelectorAll('button')].find((b) => b.textContent === 'Launch terminal')! + [...document.querySelectorAll('button')].find( + (b) => b.getAttribute('aria-label') === 'Launch terminal' + )! ) expect(launch).toHaveBeenCalledExactlyOnceWith( expect.objectContaining({ diff --git a/src/renderer/src/components/agent/AgentLaunchPickerMenu.tsx b/src/renderer/src/components/agent/AgentLaunchPickerMenu.tsx index 133d92aa6b19..44370cff8ce6 100644 --- a/src/renderer/src/components/agent/AgentLaunchPickerMenu.tsx +++ b/src/renderer/src/components/agent/AgentLaunchPickerMenu.tsx @@ -1,6 +1,11 @@ -import { memo, useId, useRef, useState, type ComponentProps, type PointerEvent } from 'react' +import { memo, useId, useRef, useState, type ComponentProps } from 'react' import { Input } from '@/components/ui/input' -import { DropdownMenuItem, DropdownMenuShortcut } from '@/components/ui/dropdown-menu' +import { Button } from '@/components/ui/button' +import { + DropdownMenuItem, + DropdownMenuShortcut, + useDropdownMenuClose +} from '@/components/ui/dropdown-menu' import { AgentIcon } from '@/lib/agent-catalog' import { translate } from '@/i18n/i18n' import { useUiLanguageRevision } from '@/i18n/use-ui-language-revision' @@ -35,13 +40,6 @@ type Launch = ( entry?: AgentPickerEntry ) => boolean | void | Promise -function keepSetupFocus(event: PointerEvent) { - // Radix row hover must not steal focus from the row's portaled setup or its nested controls. - if (event.currentTarget.querySelector('[data-slot="popover-trigger"][aria-expanded="true"]')) { - event.preventDefault() - } -} - export function AgentLaunchPickerMenu({ disabled, runLaunch, @@ -179,18 +177,20 @@ const AgentPickerMenuRow = memo(function AgentPickerMenuRow({ } : undefined const setupId = useId() - const item = useRef(null) - const dismissing = useRef(false) + const closeMenu = useDropdownMenuClose() const unavailable = entry.rows.find((row) => row.kind === 'chat-unavailable') return ( { - onSetupOpenChange(next ? setupId : null) + if (next || openSetup === setupId) { + onSetupOpenChange(next ? setupId : null) + } if (next) { onSelectAgent?.(entry.agent) } @@ -198,20 +198,16 @@ const AgentPickerMenuRow = memo(function AgentPickerMenuRow({ onUse={(draft) => { const result = runLaunch(pickerLaunchRow(entry, draft.surface), draft, entry) if (result !== false) { - // The row click dismisses Radix only; the operation above owns acceptance. - dismissing.current = true - item.current?.click() + closeMenu() } return result }} renderAnchor={(trigger) => ( - { - if (dismissing.current) { - dismissing.current = false +
{ + event.preventDefault() + if (disabled || !entry.surfaces.length) { return } const draft = initial @@ -224,29 +220,34 @@ const AgentPickerMenuRow = memo(function AgentPickerMenuRow({ : row.kind === 'terminal' || row.kind === 'cli' ) ?? pickerLaunchRow(entry, surface)) const result = draft ? runLaunch(row, draft, entry) : runLaunch(row, undefined) - if (result === false) { - event.preventDefault() + if (result !== false) { + closeMenu() } }} onKeyDown={(event) => { - if (event.key === 'ArrowRight') { + if ( + event.target === event.currentTarget && + (event.key === 'Enter' || event.key === ' ') + ) { event.preventDefault() - item.current?.querySelector('button')?.focus() + event.currentTarget.click() } }} - onPointerMove={keepSetupFocus} - onPointerLeave={keepSetupFocus} > - - {label} - {shortcut ? {shortcut} : null} - {unavailable?.kind === 'chat-unavailable' && !entry.surfaces.includes('chat') ? ( - - {chatUnavailableLabel(unavailable.reason)} + {trigger} - +
)} /> ) diff --git a/src/renderer/src/components/agent/AgentLaunchSetupButton.tsx b/src/renderer/src/components/agent/AgentLaunchSetupButton.tsx index c377353f9ec4..396f654722a6 100644 --- a/src/renderer/src/components/agent/AgentLaunchSetupButton.tsx +++ b/src/renderer/src/components/agent/AgentLaunchSetupButton.tsx @@ -11,6 +11,7 @@ import { flushSync } from 'react-dom' import { ChevronRight } from 'lucide-react' import { Button } from '@/components/ui/button' import { Separator } from '@/components/ui/separator' +import { AgentLaunchSetupSubmenu } from './AgentLaunchSetupSubmenu' import { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from '@/components/ui/popover' import { translate } from '@/i18n/i18n' import { AgentLaunchSetupPanel } from './AgentLaunchSetupPanel' @@ -50,6 +51,7 @@ export function AgentLaunchSetupButton({ initial, renderAnchor, disabled, + submenu = false, open: controlledOpen, replacedByAnotherSetup = false, onOpenChange, @@ -59,6 +61,7 @@ export function AgentLaunchSetupButton({ initial?: AgentPickerDraft renderAnchor?: (trigger: ReactElement) => ReactElement disabled?: boolean + submenu?: boolean open?: boolean replacedByAnotherSetup?: boolean onOpenChange?: (open: boolean) => void @@ -93,7 +96,7 @@ export function AgentLaunchSetupButton({ const content = useRef(null) const anchor = useRef(null) useLayoutEffect(() => { - if (!open) { + if (!open || submenu) { return } let frame = 0 @@ -126,7 +129,7 @@ export function AgentLaunchSetupButton({ observer.disconnect() cancelAnimationFrame(frame) } - }, [open]) + }, [open, submenu]) const changeOpen = (next: boolean) => { if (next) { setPlacement('right') @@ -136,6 +139,39 @@ export function AgentLaunchSetupButton({ } onOpenChange?.(next) } + const panel = ( +
+ writeLaunchSetupOptions(draftKey, draft, slot)} + onUse={(draft) => { + const accepted = onUse(draft) + if (accepted !== false) { + changeOpen(false) + } + return accepted + }} + /> +
+ ) + const label = translate('agentPicker.configure', 'Configure {{agent}}', { agent: entry.label }) + if (submenu && renderAnchor) { + return ( + + {panel} + + ) + } + const trigger = (
@@ -191,22 +227,7 @@ export function AgentLaunchSetupButton({ } }} > -
- writeLaunchSetupOptions(draftKey, draft, slot)} - onUse={(draft) => { - const accepted = onUse(draft) - if (accepted !== false) { - changeOpen(false) - } - return accepted - }} - /> -
+ {panel} ) diff --git a/src/renderer/src/components/agent/AgentLaunchSetupFooter.tsx b/src/renderer/src/components/agent/AgentLaunchSetupFooter.tsx index bcd9e3b42c3b..a7539178645a 100644 --- a/src/renderer/src/components/agent/AgentLaunchSetupFooter.tsx +++ b/src/renderer/src/components/agent/AgentLaunchSetupFooter.tsx @@ -1,7 +1,8 @@ import { useImperativeHandle, useRef, type Ref } from 'react' -import { CornerDownLeft } from 'lucide-react' import { Button } from '@/components/ui/button' +import { ShortcutKeyCombo } from '@/components/ShortcutKeyCombo' import { translate } from '@/i18n/i18n' +import { getShortcutPlatform } from '@/lib/shortcut-platform' import type { NativeChatComposerHandle } from '../native-chat/NativeChatComposer' import { AgentLaunchPromptComposer } from './AgentLaunchPromptComposer' import { @@ -9,6 +10,7 @@ import { type AgentPickerEntry, type AgentPickerSurface } from '../../../../shared/agent-launch-picker' +import { formatKeybinding } from '../../../../shared/keybindings' export type AgentLaunchSetupFooterHandle = { launch: (surface: AgentPickerSurface) => void } @@ -25,6 +27,7 @@ export function AgentLaunchSetupFooter({ onLaunch: (surface: AgentPickerSurface, prompt?: string) => boolean | void | Promise }): React.JSX.Element { const composer = useRef(null) + const platform = getShortcutPlatform() // Enter launches the default way; a Launch button names its own before it submits the prompt. const surface = useRef(entry.defaultSurface) const launch = (next: AgentPickerSurface): void => { @@ -51,23 +54,40 @@ export function AgentLaunchSetupFooter({ />
- {agentPickerButtonOrder(entry).map((next) => ( - - ))} +
+ {agentPickerButtonOrder(entry).map((next) => { + const primary = next === entry.defaultSurface + const label = + next === 'chat' + ? translate('agentPicker.launchChat', 'Launch chat') + : translate('agentPicker.launchTerminal', 'Launch terminal') + return ( + + ) + })} +
) diff --git a/src/renderer/src/components/agent/AgentLaunchSetupPanel.authority.test.tsx b/src/renderer/src/components/agent/AgentLaunchSetupPanel.authority.test.tsx index 5e2c7d9a33cd..2976b94848aa 100644 --- a/src/renderer/src/components/agent/AgentLaunchSetupPanel.authority.test.tsx +++ b/src/renderer/src/components/agent/AgentLaunchSetupPanel.authority.test.tsx @@ -97,7 +97,9 @@ it.each(['missing-default', 'pending', 'known-default', 'explicit'] as const)( for (const way of ['Launch chat', 'Launch terminal']) { onUse.mockClear() fireEvent.click( - [...host.querySelectorAll('button')].find((button) => button.textContent === way)! + [...host.querySelectorAll('button')].find( + (button) => button.getAttribute('aria-label') === way + )! ) expect(agentPickerLaunchInputs(onUse.mock.calls[0][0], own)).toEqual({}) } @@ -127,7 +129,9 @@ it('edits the QA inline settings carrier after verbose and compiles the same eff expect(fast?.disabled).toBe(false) fireEvent.click(fast!) fireEvent.click( - [...host.querySelectorAll('button')].find((button) => button.textContent === 'Launch terminal')! + [...host.querySelectorAll('button')].find( + (button) => button.getAttribute('aria-label') === 'Launch terminal' + )! ) const launch = agentPickerLaunchInputs(onUse.mock.calls[0][0], own) const compiled = resolveAgentLaunchCommand({ @@ -176,7 +180,9 @@ it('keeps the QA unclosed permission literal once after Ask and preserves actual ) expect(host.querySelector('button[aria-label^="Remove --permission"]')).toBeNull() fireEvent.click( - [...host.querySelectorAll('button')].find((button) => button.textContent === 'Launch terminal')! + [...host.querySelectorAll('button')].find( + (button) => button.getAttribute('aria-label') === 'Launch terminal' + )! ) const launch = agentPickerLaunchInputs(onUse.mock.calls[0][0], own) expect(launch.agentArgs).toBe(raw) diff --git a/src/renderer/src/components/agent/AgentLaunchSetupPanel.perf.test.tsx b/src/renderer/src/components/agent/AgentLaunchSetupPanel.perf.test.tsx index fe5c7d63d116..a2701a21e9e3 100644 --- a/src/renderer/src/components/agent/AgentLaunchSetupPanel.perf.test.tsx +++ b/src/renderer/src/components/agent/AgentLaunchSetupPanel.perf.test.tsx @@ -169,7 +169,9 @@ it('bounds effective-settings work for direct analysis, collapsed Chat render an ) } fireEvent.click( - [...host.querySelectorAll('button')].find((b) => b.textContent === 'Launch terminal')! + [...host.querySelectorAll('button')].find( + (b) => b.getAttribute('aria-label') === 'Launch terminal' + )! ) const launch = agentPickerLaunchInputs(onUse.mock.calls.at(-1)![0], own) expect(tokenizeStartupCommand(launch.agentArgs ?? '', 'posix')).toMatchObject({ @@ -259,7 +261,9 @@ it('bounds catalog projection independently of raw model operands and retains Co host.querySelector(`button[aria-label="Remove -c service_tier=${tier}"]`) ).not.toBeNull() fireEvent.click( - [...host.querySelectorAll('button')].find((b) => b.textContent === 'Launch terminal')! + [...host.querySelectorAll('button')].find( + (b) => b.getAttribute('aria-label') === 'Launch terminal' + )! ) const launch = agentPickerLaunchInputs(onUse.mock.calls.at(-1)![0], own) expect(launch.agentArgs).toContain(`service_tier=${tier}`) @@ -288,7 +292,9 @@ it('bounds catalog projection independently of raw model operands and retains Co target: { value: '--model claude-opus-4-8 --verbose' } }) fireEvent.click( - [...host.querySelectorAll('button')].find((b) => b.textContent === 'Launch terminal')! + [...host.querySelectorAll('button')].find( + (b) => b.getAttribute('aria-label') === 'Launch terminal' + )! ) const launch = agentPickerLaunchInputs(onUse.mock.calls.at(-1)![0], own) expect(launch.agentArgs).toContain('--model claude-opus-4-8') diff --git a/src/renderer/src/components/agent/AgentLaunchSetupPanel.prompt.test.tsx b/src/renderer/src/components/agent/AgentLaunchSetupPanel.prompt.test.tsx index f106d37f7f7b..ec34833d07c4 100644 --- a/src/renderer/src/components/agent/AgentLaunchSetupPanel.prompt.test.tsx +++ b/src/renderer/src/components/agent/AgentLaunchSetupPanel.prompt.test.tsx @@ -32,7 +32,9 @@ function prompt(): HTMLElement { } function launchButton(label: string): HTMLButtonElement { - return [...host.querySelectorAll('button')].find((button) => button.textContent === label)! + return [...host.querySelectorAll('button')].find( + (button) => button.getAttribute('aria-label') === label + )! } it('launches with the typed first prompt from Enter or either Launch button, and without one as before', async () => { @@ -308,7 +310,10 @@ it.each(['claude', 'codex'] as const)( const configure = () => document.querySelector(`button[aria-label="Configure ${agent}"]`)! fireEvent.click(configure()) - const panel = () => document.querySelector('[data-slot="popover-content"]')! + const panel = () => + document.querySelector( + '[data-slot="dropdown-menu-sub-content"], [data-slot="popover-content"]' + )! fireEvent.click(panel().querySelector('[cmdk-item]')!) fireEvent.click(getByRole(document.body, 'radio', { name: 'High' })) fireEvent.change(panel().querySelector('textarea')!, { diff --git a/src/renderer/src/components/agent/AgentLaunchSetupPanel.shortcuts.test.tsx b/src/renderer/src/components/agent/AgentLaunchSetupPanel.shortcuts.test.tsx new file mode 100644 index 000000000000..662182e2f8a9 --- /dev/null +++ b/src/renderer/src/components/agent/AgentLaunchSetupPanel.shortcuts.test.tsx @@ -0,0 +1,133 @@ +// @vitest-environment happy-dom +import { act } from 'react' +import { fireEvent, getByRole, waitFor } from '@testing-library/react' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { TooltipProvider } from '@/components/ui/tooltip' +import { entry, host, root, onUse } from './agent-launch-setup-panel-test-fixture' +import { AgentLaunchSetupPanel } from './AgentLaunchSetupPanel' +import { changePrompt } from '../native-chat/native-chat-prompt-editor.test-support' +import { clearNativeChatComposerDraftsForTests } from '../native-chat/native-chat-composer-draft-store' +import type { AgentPickerSurface } from '../../../../shared/agent-launch-picker' + +beforeEach(() => clearNativeChatComposerDraftsForTests()) +afterEach(() => vi.restoreAllMocks()) + +function renderPanel({ + defaultSurface = 'terminal', + surfaces = ['chat', 'terminal'], + disabled = false +}: { + defaultSurface?: AgentPickerSurface + surfaces?: AgentPickerSurface[] + disabled?: boolean +} = {}) { + act(() => + root.render( + + + + ) + ) +} + +function prompt(): HTMLElement { + return host.querySelector('[contenteditable][aria-multiline="true"]')! +} + +const cases = ['Macintosh', 'Windows NT 10.0', 'X11; Linux x86_64'].flatMap((userAgent) => + (['terminal', 'chat'] as const).flatMap((defaultSurface) => + (['prompt', 'model', 'arguments'] as const).map((target) => ({ + userAgent, + defaultSurface, + target + })) + ) +) + +it.each(cases)( + 'launches the alternative to $defaultSurface from $target on $userAgent', + async ({ userAgent, defaultSurface, target }) => { + vi.spyOn(navigator, 'userAgent', 'get').mockReturnValue(userAgent) + renderPanel({ defaultSurface }) + changePrompt(prompt(), 'inspect the selected workspace') + if (target === 'arguments' && !host.querySelector('textarea')) { + fireEvent.click(getByRole(host, 'button', { name: 'Toggle Arguments' })) + } + const input = + target === 'prompt' + ? prompt() + : target === 'model' + ? host.querySelector('[cmdk-input]')! + : host.querySelector('textarea')! + const mac = userAgent.includes('Mac') + fireEvent.keyDown(input, { key: 'Enter', keyCode: 13, metaKey: mac, ctrlKey: !mac }) + const alternate = defaultSurface === 'terminal' ? 'chat' : 'terminal' + await waitFor(() => + expect(onUse).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + surface: alternate, + prompt: 'inspect the selected workspace' + }) + ) + ) + const button = getByRole(host, 'button', { name: `Launch ${alternate}` }) + expect(button.getAttribute('aria-keyshortcuts')).toBe(mac ? 'Meta+Enter' : 'Control+Enter') + expect(button.textContent).toContain(mac ? '⌘' : 'Ctrl') + expect( + getByRole(host, 'button', { name: `Launch ${defaultSurface}` }).getAttribute( + 'aria-keyshortcuts' + ) + ).toBe('Enter') + } +) + +it.each(['Macintosh', 'Windows NT 10.0'])( + 'launches the alternative with an empty prompt on %s', + async (userAgent) => { + vi.spyOn(navigator, 'userAgent', 'get').mockReturnValue(userAgent) + renderPanel() + const mac = userAgent.includes('Mac') + fireEvent.keyDown(prompt(), { key: 'Enter', keyCode: 13, metaKey: mac, ctrlKey: !mac }) + await waitFor(() => + expect(onUse).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ surface: 'chat' })) + ) + expect(onUse.mock.calls[0][0].prompt).toBeUndefined() + } +) + +it.each(['disabled', 'single-surface', 'repeat', 'composition', 'shift'] as const)( + 'does not launch through the alternative shortcut during %s', + (state) => { + vi.spyOn(navigator, 'userAgent', 'get').mockReturnValue('Macintosh') + renderPanel({ + disabled: state === 'disabled', + surfaces: state === 'single-surface' ? ['terminal'] : ['chat', 'terminal'] + }) + fireEvent.keyDown(state === 'composition' ? host.querySelector('textarea')! : prompt(), { + key: 'Enter', + keyCode: 13, + metaKey: true, + isComposing: state === 'composition', + repeat: state === 'repeat', + shiftKey: state === 'shift' + }) + expect(onUse).not.toHaveBeenCalled() + } +) diff --git a/src/renderer/src/components/agent/AgentLaunchSetupPanel.test.tsx b/src/renderer/src/components/agent/AgentLaunchSetupPanel.test.tsx index c7cf2fae5585..f67e4f71069c 100644 --- a/src/renderer/src/components/agent/AgentLaunchSetupPanel.test.tsx +++ b/src/renderer/src/components/agent/AgentLaunchSetupPanel.test.tsx @@ -1,7 +1,7 @@ // @vitest-environment happy-dom import { entry, host, root, onUse } from './agent-launch-setup-panel-test-fixture' import { act } from 'react' -import { fireEvent, getByText, isInaccessible, waitFor } from '@testing-library/react' +import { fireEvent, getByRole, getByText, isInaccessible, waitFor } from '@testing-library/react' import { expect, it, vi } from 'vitest' import { TooltipProvider } from '@/components/ui/tooltip' import { AgentLaunchSetupPanel } from './AgentLaunchSetupPanel' @@ -66,11 +66,7 @@ it('shows a raw Arguments value in the shared Permissions menu; removing its chi expect(host.querySelector('textarea[aria-label="Arguments"]')?.value).toBe( '--add-dir docs' ) - act(() => - [...host.querySelectorAll('button')] - .find((button) => button.textContent === 'Launch terminal') - ?.click() - ) + act(() => getByRole(host, 'button', { name: 'Launch terminal' })?.click()) expect(onUse).toHaveBeenCalledExactlyOnceWith( expect.objectContaining({ surface: 'terminal', arguments: '--add-dir docs' }) ) @@ -125,11 +121,7 @@ it('shows remembered chat defaults without turning displayed values into launch ) expect(host.textContent).not.toMatch(/Agents? defaults?|Reset to default/) expect(host.querySelector('[cmdk-item][data-current="true"]')?.textContent).toBe('Astra') - act(() => - [...host.querySelectorAll('button')] - .find((button) => button.textContent === 'Launch chat') - ?.click() - ) + act(() => getByRole(host, 'button', { name: 'Launch chat' })?.click()) expect(onUse).toHaveBeenCalledExactlyOnceWith({ agent: 'codex', surface: 'chat', @@ -158,10 +150,7 @@ it('keeps pending defaults disabled, selects resolved values without overrides, ) render(pending) fireEvent.click(host.querySelector('button[aria-label="Toggle Arguments"]')!) - expect( - [...host.querySelectorAll('button')].find((button) => button.textContent === 'Launch chat') - ?.disabled - ).toBe(false) + expect(getByRole(host, 'button', { name: 'Launch chat' }).disabled).toBe(false) expect(host.querySelector('input[aria-label="Search models"]')?.disabled).toBe( true ) @@ -220,11 +209,7 @@ it('keeps pending defaults disabled, selects resolved values without overrides, 'Ask for approval' ) expect(host.textContent).not.toMatch(/Agents? defaults?|Reset to default/) - act(() => - [...host.querySelectorAll('button')] - .find((button) => button.textContent === 'Launch chat') - ?.click() - ) + act(() => getByRole(host, 'button', { name: 'Launch chat' })?.click()) expect(onUse).toHaveBeenCalledExactlyOnceWith( expect.objectContaining({ choices: {}, arguments: undefined }) ) @@ -234,10 +219,7 @@ it('keeps pending defaults disabled, selects resolved values without overrides, false ) expect(host.querySelector('[cmdk-item][data-current="true"]')).toBeNull() - expect( - [...host.querySelectorAll('button')].find((button) => button.textContent === 'Launch chat') - ?.disabled - ).toBe(false) + expect(getByRole(host, 'button', { name: 'Launch chat' }).disabled).toBe(false) }) it('launches explicit model and effort picks when settled defaults have neither selected', () => { @@ -280,9 +262,7 @@ it('launches explicit model and effort picks when settled defaults have neither [...host.querySelectorAll('[role="radio"]')].find((radio) => radio.textContent === 'High')! ) expect(host.querySelector('[role="radio"][data-state="on"]')?.textContent).toBe('High') - fireEvent.click( - [...host.querySelectorAll('button')].find((button) => button.textContent === 'Launch chat')! - ) + fireEvent.click(getByRole(host, 'button', { name: 'Launch chat' })) expect(onUse).toHaveBeenCalledExactlyOnceWith( expect.objectContaining({ surface: 'chat', @@ -293,10 +273,12 @@ it('launches explicit model and effort picks when settled defaults have neither model: 'host-model', effort: 'high' }) - const footer = [...host.querySelectorAll('button')].find( - (button) => button.textContent === 'Launch chat' - )!.parentElement! - expect(footer.textContent).toBe('Launch terminalLaunch chat') + const footer = getByRole(host, 'button', { + name: 'Launch chat' + }).parentElement! + expect( + [...footer.querySelectorAll('button')].map((button) => button.getAttribute('aria-label')) + ).toEqual(['Launch terminal', 'Launch chat']) }) it('returns to concrete default model, effort and permission values by selecting them directly', () => { @@ -370,11 +352,7 @@ it('returns to concrete default model, effort and permission values by selecting ) select('Permissions', 'Full access') select('Permissions', 'Ask') - act(() => - [...host.querySelectorAll('button')] - .find((button) => button.textContent === 'Launch chat') - ?.click() - ) + act(() => getByRole(host, 'button', { name: 'Launch chat' })?.click()) expect(onUse).toHaveBeenCalledExactlyOnceWith( expect.objectContaining({ choices: { model: 'astra', options: { effort: 'low' }, permissionMode: 'ask' } @@ -423,11 +401,7 @@ it('searches current and supplied legacy models, keeps unknown explicit choices, .find((row) => row.textContent === 'Retired model') ?.click() ) - act(() => - [...host.querySelectorAll('button')] - .find((button) => button.textContent === 'Launch chat') - ?.click() - ) + act(() => getByRole(host, 'button', { name: 'Launch chat' })?.click()) expect(onUse).toHaveBeenCalledExactlyOnceWith( expect.objectContaining({ choices: { model: 'retired' } }) ) @@ -461,7 +435,9 @@ it.each(['chat', 'terminal'] as const)( act(() => [...host.querySelectorAll('button')] .find( - (button) => button.textContent === (way === 'chat' ? 'Launch chat' : 'Launch terminal') + (button) => + button.getAttribute('aria-label') === + (way === 'chat' ? 'Launch chat' : 'Launch terminal') ) ?.click() ) @@ -530,11 +506,7 @@ it('keeps uncertain permission text literal instead of offering a badge that rem raw ) expect(host.querySelector('button[aria-label^="Remove --unknown-option"]')).toBeNull() - act(() => - [...host.querySelectorAll('button')] - .find((button) => button.textContent === 'Launch terminal') - ?.click() - ) + act(() => getByRole(host, 'button', { name: 'Launch terminal' })?.click()) expect(onUse).toHaveBeenCalledExactlyOnceWith( expect.objectContaining({ arguments: undefined, choices: {} }) ) @@ -568,9 +540,7 @@ it('uses the shared permission menu without its inheritance row and couples raw, expect(input.value).toBe('--add-dir "keep spaces"') for (const way of ['Launch chat', 'Launch terminal']) { onUse.mockClear() - fireEvent.click( - [...host.querySelectorAll('button')].find((button) => button.textContent === way)! - ) + fireEvent.click(getByRole(host, 'button', { name: way })) expect(onUse).toHaveBeenCalledOnce() const launch = agentPickerLaunchInputs(onUse.mock.calls[0][0], entry) expect(launch.sessionOptions?.permissionMode).toBe('accept-edits') @@ -622,9 +592,7 @@ it.each(['chat', 'terminal'] as const)( expect(input.value).toContain('"theme":"dark"') for (const way of ['Launch chat', 'Launch terminal']) { onUse.mockClear() - fireEvent.click( - [...host.querySelectorAll('button')].find((button) => button.textContent === way)! - ) + fireEvent.click(getByRole(host, 'button', { name: way })) const launch = agentPickerLaunchInputs(onUse.mock.calls[0][0], own) expect(launch.sessionOptions?.fastMode).toBe('true') if (way === 'Launch terminal') { @@ -684,18 +652,14 @@ it.each([ expect(input.value).toContain('--add-dir docs') for (const way of ['Launch chat', 'Launch terminal']) { onUse.mockClear() - fireEvent.click( - [...host.querySelectorAll('button')].find((button) => button.textContent === way)! - ) + fireEvent.click(getByRole(host, 'button', { name: way })) expect(agentPickerLaunchInputs(onUse.mock.calls[0][0], own)).not.toHaveProperty('agentArgs') } fireEvent.click(chip!) expect(host.querySelector('button[aria-label*="Remove --settings"]')).toBeNull() for (const way of ['Launch chat', 'Launch terminal']) { onUse.mockClear() - fireEvent.click( - [...host.querySelectorAll('button')].find((button) => button.textContent === way)! - ) + fireEvent.click(getByRole(host, 'button', { name: way })) const launch = agentPickerLaunchInputs(onUse.mock.calls[0][0], own) expect(launch.sessionOptions?.fastMode).toBe('false') if (way === 'Launch terminal') { @@ -754,9 +718,7 @@ it('enables recorded Codex tier choices after defaults become known without inve expect(standard().getAttribute('aria-checked')).toBe('false') const launch = (way: string) => { onUse.mockClear() - fireEvent.click( - [...host.querySelectorAll('button')].find((button) => button.textContent === way)! - ) + fireEvent.click(getByRole(host, 'button', { name: way })) return agentPickerLaunchInputs(onUse.mock.calls[0][0], own) } for (const way of ['Launch chat', 'Launch terminal']) { @@ -807,9 +769,7 @@ it.each([`--settings '{"fastMode":true}' --settings ./team.json`, `--settings '{ ) for (const way of ['Launch chat', 'Launch terminal']) { onUse.mockClear() - fireEvent.click( - [...host.querySelectorAll('button')].find((button) => button.textContent === way)! - ) + fireEvent.click(getByRole(host, 'button', { name: way })) const input = agentPickerLaunchInputs(onUse.mock.calls[0][0], own) expect(input.sessionOptions?.fastMode).toBeUndefined() expect(input).not.toHaveProperty('agentArgs') diff --git a/src/renderer/src/components/agent/AgentLaunchSetupPanel.tsx b/src/renderer/src/components/agent/AgentLaunchSetupPanel.tsx index c067c2d1969e..c2067c8ac5cc 100644 --- a/src/renderer/src/components/agent/AgentLaunchSetupPanel.tsx +++ b/src/renderer/src/components/agent/AgentLaunchSetupPanel.tsx @@ -10,6 +10,8 @@ import { CommandItem } from '@/components/ui/command' import { translate } from '@/i18n/i18n' +import { isScreenSubmitShortcut } from '@/lib/screen-submit-shortcut' +import { isImeOwnedKeyboardEvent } from '@/lib/ime-composition-keyboard-event' import { AgentDefaultArgsInput } from '../settings/AgentLaunchDefaultsEditor' import { NativeChatSessionOptionRows } from '../native-chat/NativeChatSessionOptionRows' import { Collapsible, CollapsibleTrigger, CollapsibleContent } from '@/components/ui/collapsible' @@ -172,10 +174,21 @@ export function AgentLaunchSetupPanel({ return (
{ + if (isScreenSubmitShortcut(event)) { + event.preventDefault() + event.stopPropagation() + const alternate = entry.surfaces.find((surface) => surface !== entry.defaultSurface) + if (alternate && !disabled && !event.repeat) { + use(alternate) + } + } + }} onKeyDown={(event) => { event.stopPropagation() if ( !disabled && + !isImeOwnedKeyboardEvent(event) && event.key === 'Enter' && (event.target instanceof HTMLInputElement || event.target instanceof HTMLTextAreaElement) ) { @@ -190,6 +203,7 @@ export function AgentLaunchSetupPanel({ onKeyDownCapture={(event) => { if ( !disabled && + !isImeOwnedKeyboardEvent(event) && event.key === 'Enter' && event.currentTarget.querySelector( '[cmdk-item][data-selected="true"][data-current="true"]' @@ -207,6 +221,7 @@ export function AgentLaunchSetupPanel({ }} > void + renderAnchor: (trigger: ReactElement) => ReactElement + disabled?: boolean + label: string + children: ReactNode +}) { + const trigger = useRef(null) + const content = useRef(null) + const segmentRelease = useRef(false) + const focusSearch = () => + content.current?.querySelector('[cmdk-input]:not(:disabled)')?.focus({ + preventScroll: true + }) + const close = (returnFocus: 'row' | 'segment') => { + onOpenChange(false) + const target = + returnFocus === 'row' + ? trigger.current + : trigger.current?.querySelector('button') + target?.focus() + } + return ( + { + // Opening is explicit; Radix still owns pointer grace, focus, and dismissal. + if (!next) { + onOpenChange(false) + } + }} + > + { + const segment = event.currentTarget.querySelector('button') + if (event.target instanceof Node && segment?.contains(event.target)) { + event.preventDefault() + } + }} + onPointerDownCapture={() => { + segmentRelease.current = false + }} + onPointerUpCapture={(event) => { + segmentRelease.current = + event.target instanceof Node && + !!event.currentTarget.querySelector('button')?.contains(event.target) + }} + onClickCapture={(event) => { + if (segmentRelease.current && event.target === event.currentTarget) { + event.preventDefault() + event.stopPropagation() + } + segmentRelease.current = false + }} + onKeyDownCapture={() => { + segmentRelease.current = false + }} + onKeyDown={(event) => { + if (!disabled && event.target === event.currentTarget && event.key === 'ArrowRight') { + event.preventDefault() + onOpenChange(true) + focusSearch() + } + }} + > + {renderAnchor( + + )} + + { + if (event.target === event.currentTarget) { + focusSearch() + } + }} + onClick={(event) => event.stopPropagation()} + onFocusOutside={(event) => { + const row = trigger.current?.closest('[data-agent-launch-row]') + const menu = trigger.current?.closest('[data-slot="dropdown-menu-content"]') + // Nested option menus and pointer grace may move focus outside this portal. + if ( + !( + event.target instanceof Element && + event.target.closest('[role="menuitem"]') && + menu?.contains(event.target) && + !row?.contains(event.target) + ) + ) { + event.preventDefault() + } + }} + onKeyDownCapture={(event) => { + const target = event.target + const emptySearch = + target instanceof HTMLInputElement && target.matches('[cmdk-input]') && !target.value + const editing = + target instanceof HTMLInputElement || + target instanceof HTMLTextAreaElement || + (target instanceof HTMLElement && target.isContentEditable) + if ( + event.key === 'ArrowLeft' && + !event.nativeEvent.isComposing && + !event.altKey && + !event.ctrlKey && + !event.metaKey && + !event.shiftKey && + target instanceof Element && + target.closest('[role="menu"]') === event.currentTarget && + (emptySearch || !editing) + ) { + event.preventDefault() + event.stopPropagation() + close('row') + } + }} + onEscapeKeyDown={(event) => { + event.preventDefault() + if (!content.current?.querySelector('[contenteditable][aria-expanded="true"]')) { + close('segment') + } + }} + > + {children} + + + ) +} diff --git a/src/renderer/src/components/agent/agent-launch-picker-freshness-test-fixture.tsx b/src/renderer/src/components/agent/agent-launch-picker-freshness-test-fixture.tsx index 65186c01aefe..9c5716e5badf 100644 --- a/src/renderer/src/components/agent/agent-launch-picker-freshness-test-fixture.tsx +++ b/src/renderer/src/components/agent/agent-launch-picker-freshness-test-fixture.tsx @@ -81,7 +81,9 @@ export async function exerciseAgentPickerFreshness({ view.container.querySelector('[data-option-id="effort"] [data-state="on"]')?.textContent const launch = () => { fireEvent.click( - [...view.container.querySelectorAll('button')].find((b) => b.textContent === 'Launch chat')! + [...view.container.querySelectorAll('button')].find( + (b) => b.getAttribute('aria-label') === 'Launch chat' + )! ) expect(launches.mock.lastCall).toEqual([{}]) } diff --git a/src/renderer/src/components/agent/use-agent-launch-picker-inventory.test.tsx b/src/renderer/src/components/agent/use-agent-launch-picker-inventory.test.tsx index e308d5c7bedc..a9af01671b40 100644 --- a/src/renderer/src/components/agent/use-agent-launch-picker-inventory.test.tsx +++ b/src/renderer/src/components/agent/use-agent-launch-picker-inventory.test.tsx @@ -648,7 +648,7 @@ it('updates a mounted setup from current host rows without making ordinary actio expect(document.querySelector('textarea')).toHaveProperty('disabled', true) expect( [...document.querySelectorAll('button')].find( - (button) => button.textContent === 'Launch terminal' + (button) => button.getAttribute('aria-label') === 'Launch terminal' ) ).toHaveProperty('disabled', false) } diff --git a/src/renderer/src/components/tab-bar/TabBarCreateEntry.search.test.tsx b/src/renderer/src/components/tab-bar/TabBarCreateEntry.search.test.tsx index 5db51f5edd15..cc568e0961e0 100644 --- a/src/renderer/src/components/tab-bar/TabBarCreateEntry.search.test.tsx +++ b/src/renderer/src/components/tab-bar/TabBarCreateEntry.search.test.tsx @@ -595,7 +595,7 @@ it('launches searched defaults on Enter and reaches the alternate only through C expect(launched).not.toHaveBeenCalled() act(() => [...document.querySelectorAll('button')] - .find((button) => button.textContent === 'Launch terminal') + .find((button) => button.getAttribute('aria-label') === 'Launch terminal') ?.click() ) expect(launched).toHaveBeenCalledOnce() diff --git a/src/renderer/src/components/ui/button.tsx b/src/renderer/src/components/ui/button.tsx index bfcd65aa90e7..c1684ca7fc31 100644 --- a/src/renderer/src/components/ui/button.tsx +++ b/src/renderer/src/components/ui/button.tsx @@ -17,6 +17,10 @@ const buttonVariants = cva( secondary: 'bg-secondary text-secondary-foreground hover:bg-secondary/80', ghost: 'hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50', link: 'text-primary underline-offset-4 hover:underline', + 'menu-launch': + 'min-w-0 flex-1 justify-start rounded-l-[7px] rounded-r-none text-foreground', + 'menu-segment': + 'rounded-l-none border-l border-border bg-muted/40 text-muted-foreground hover:bg-primary hover:text-primary-foreground focus-visible:bg-primary focus-visible:text-primary-foreground aria-expanded:bg-primary aria-expanded:text-primary-foreground', 'pane-title': 'pane-title-split-trigger', 'pane-title-close': 'pane-title-close', // The worktree card's "rename failed" chip, for a failure the user can open. @@ -27,6 +31,7 @@ const buttonVariants = cva( default: 'h-9 px-4 py-2 has-[>svg]:px-3', xs: "h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3", sm: 'h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5', + menu: 'h-8 gap-2 px-2 py-1.5 text-xs leading-5', lg: 'h-10 rounded-md px-6 has-[>svg]:px-4', icon: 'size-9', 'icon-xs': "size-6 rounded-md [&_svg:not([class*='size-'])]:size-3", diff --git a/src/renderer/src/components/ui/dropdown-menu.tsx b/src/renderer/src/components/ui/dropdown-menu.tsx index 2db04acabcd0..0c2bd5111bca 100644 --- a/src/renderer/src/components/ui/dropdown-menu.tsx +++ b/src/renderer/src/components/ui/dropdown-menu.tsx @@ -1,6 +1,8 @@ import * as React from 'react' +import { cva } from 'class-variance-authority' import { CheckIcon, ChevronRightIcon, CircleIcon } from 'lucide-react' import * as DropdownMenuPrimitive from 'radix-ui/dropdown-menu' +import { useControllableState } from 'radix-ui/internal' import { cn } from '@/lib/utils' import { handleOverlayCloseAutoFocus } from '@/lib/overlay-focus-ownership' @@ -9,8 +11,35 @@ import { handleImeOverlayEscape } from '@/lib/ime-overlay-escape' import { keepFocusWhileMenuCloses } from './menu-item-closing-focus' import { useMenuPointerHighlight } from './menu-pointer-highlight' -function DropdownMenu({ ...props }: React.ComponentProps) { - return +const DropdownMenuCloseContext = React.createContext<() => void>(() => {}) + +function useDropdownMenuClose() { + return React.useContext(DropdownMenuCloseContext) +} + +function DropdownMenu({ + open: controlledOpen, + defaultOpen, + onOpenChange, + ...props +}: React.ComponentProps) { + const [open, setOpen] = useControllableState({ + prop: controlledOpen, + defaultProp: defaultOpen ?? false, + onChange: onOpenChange, + caller: 'DropdownMenu' + }) + const close = React.useCallback(() => setOpen(false), [setOpen]) + return ( + + + + ) } function DropdownMenuPortal({ @@ -190,42 +219,70 @@ function DropdownMenuSub({ ...props }: React.ComponentProps } +const dropdownMenuSubTriggerVariants = cva( + "flex cursor-default items-center gap-2 rounded-md px-2.5 py-1 text-[13px] leading-4 font-normal outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5 [&_svg:not([class*='text-'])]:text-muted-foreground", + { + variants: { + variant: { + default: + 'focus:bg-black/8 dark:focus:bg-white/14 focus:text-accent-foreground data-[state=open]:bg-black/8 dark:data-[state=open]:bg-white/14 data-[state=open]:text-accent-foreground', + 'launch-row': + 'gap-0 rounded-[7px] p-0 text-xs leading-5 font-medium hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus-within:bg-accent focus-within:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-40' + } + }, + defaultVariants: { variant: 'default' } + } +) + function DropdownMenuSubTrigger({ className, inset, children, hideChevron, + variant = 'default', ...props }: React.ComponentProps & { inset?: boolean // Why: collision-flipped submenus open leftward, where a right-pointing chevron misleads. hideChevron?: boolean + variant?: 'default' | 'launch-row' }) { return ( - {children} - {hideChevron ? null : ( - + {hideChevron ? ( + children + ) : ( + <> + {children} + + )} ) } +const dropdownMenuSubContentVariants = cva('', { + variants: { variant: { default: '', picker: 'p-0' } }, + defaultVariants: { variant: 'default' } +}) + function DropdownMenuSubContent({ className, style, alignOffset = -5, scrollable = false, + variant = 'default', ...props -}: React.ComponentProps & { scrollable?: boolean }) { +}: React.ComponentProps & { + scrollable?: boolean + variant?: 'default' | 'picker' +}) { const pointerHighlight = useMenuPointerHighlight(props) const { ref: focusScopeRef, scope } = useOverlayFocusScope(pointerHighlight.ref) return ( @@ -233,10 +290,12 @@ function DropdownMenuSubContent({ ('[contenteditable][aria-multiline="true"]')! } function button(name: string): HTMLButtonElement { - return [...document.querySelectorAll('button')].find((button) => button.textContent === name)! + return screen.getByRole('button', { name }) } it.each(