Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(desktop-app): portal chat-drawer flyouts so they aren't clipped at 340px

Diego Zacarias7d894ef4d933
diff --git a/desktop-app/test/e2e-playwright/chat-drawer-narrow-flyouts.test.ts b/desktop-app/test/e2e-playwright/chat-drawer-narrow-flyouts.test.ts
new file mode 100644
index 000000000..c16d76e33
--- /dev/null
+++ b/desktop-app/test/e2e-playwright/chat-drawer-narrow-flyouts.test.ts
@@ -0,0 +1,112 @@
+// desktop-app/test/e2e-playwright/chat-drawer-narrow-flyouts.test.ts
+//
+// Real-layout guard for the narrow chat DRAWER (min width 340px): the composer
+// reference submenu (.composer-reference-submenu) and the agent selector menu
+// (.agent-title-selector-menu, incl. its nested submenu) must render fully and be
+// operable, not cropped by the drawer's overflow-clipping ancestors or occluded
+// by the native embed that paints to the drawer's left. The unit suite runs under
+// jsdom (no layout), so this is the only lane that can assert actual on-screen
+// rects. It needs the live external-rest-api + a docked chat drawer, so it runs
+// only via `npm run test:e2e:playwright` against a cluster port-forward — it is
+// NOT part of the vitest unit suite.
+//
+// NOTE (unrun): the "dock a chat into the drawer" step below depends on the
+// packaged app's docked-drawer entry flow, which cannot be validated here without
+// a live cluster. Confirm the dock affordance (the `dock-chat-drawer` testid used
+// below) against the real harness before relying on this spec; the assertions
+// themselves are harness-independent.
+import { expect, test } from './fixtures.js'
+import { enterChatllmChat as enterAgentChat } from './workflowAgentChatTools.js'
+
+const DRAWER = '.chat-drawer'
+const DRAWER_SURFACE = '.chat-drawer__surface'
+const RESIZE_HANDLE = '.chat-drawer__resize-handle'
+
+type Rect = { left: number; right: number; top: number; bottom: number; width: number }
+
+async function rectOf(page: import('@playwright/test').Page, selector: string): Promise<Rect> {
+ return page
+ .locator(selector)
+ .first()
+ .evaluate(el => {
+ const r = el.getBoundingClientRect()
+ return { left: r.left, right: r.right, top: r.top, bottom: r.bottom, width: r.width }
+ })
+}
+
+/**
+ * Shrink the drawer to its 340px minimum via the keyboard-operable resize handle
+ * (ARIA separator pattern, aria-valuemin=340). Left-arrow widens a right-docked
+ * drawer, Right-arrow narrows it; hold Right until it stops moving (pinned to min).
+ */
+async function shrinkDrawerToMinimum(page: import('@playwright/test').Page): Promise<void> {
+ const handle = page.locator(RESIZE_HANDLE)
+ await expect(handle).toBeVisible()
+ await handle.focus()
+ let previous = -1
+ for (let i = 0; i < 60; i += 1) {
+ const width = (await rectOf(page, DRAWER)).width
+ if (width === previous) break
+ previous = width
+ await page.keyboard.press('ArrowRight')
+ await page.waitForTimeout(16)
+ }
+}
+
+test.describe('narrow chat drawer flyouts', () => {
+ test('composer submenu and agent menu render fully inside the 340px drawer', async ({
+ appPage,
+ }) => {
+ await enterAgentChat(appPage)
+ // Dock the active conversation into the right-side chat drawer. Replace with
+ // the harness's real dock affordance if this id differs.
+ const dockButton = appPage.locator('[data-testid="dock-chat-drawer"]')
+ if (await dockButton.count()) {
+ await dockButton.first().click()
+ }
+ await expect(appPage.locator(DRAWER)).toBeVisible()
+
+ await shrinkDrawerToMinimum(appPage)
+ const drawerRect = await rectOf(appPage, DRAWER)
+ expect(Math.round(drawerRect.width)).toBeLessThanOrEqual(360) // ~340 + rounding
+
+ const viewport = appPage.viewportSize()
+ const viewportWidth = viewport?.width ?? (await appPage.evaluate(() => window.innerWidth))
+
+ // The drawer surface never overflows horizontally (the scroll-fix contract).
+ const surfaceOverflow = await appPage.locator(DRAWER_SURFACE).evaluate(el => ({
+ scrollWidth: el.scrollWidth,
+ clientWidth: el.clientWidth,
+ }))
+ expect(surfaceOverflow.scrollWidth).toBeLessThanOrEqual(surfaceOverflow.clientWidth)
+
+ // --- Composer reference submenu ---
+ await appPage.locator('.chat-drawer [aria-label="Add context"]').click()
+ await appPage.getByRole('menuitem', { name: /Plugins/ }).hover()
+ const submenu = appPage.locator('.composer-reference-submenu')
+ await expect(submenu).toBeVisible()
+ const submenuRect = await rectOf(appPage, '.composer-reference-submenu')
+ // Fully on screen: within the viewport and to the right of the drawer's left
+ // edge (so it is off the embed that sits to the drawer's left).
+ expect(submenuRect.left).toBeGreaterThanOrEqual(0)
+ expect(submenuRect.right).toBeLessThanOrEqual(viewportWidth)
+ expect(submenuRect.left).toBeGreaterThanOrEqual(drawerRect.left - 1)
+ await appPage.keyboard.press('Escape')
+
+ // --- Agent selector menu + nested sections submenu ---
+ await appPage.locator('.chat-drawer .agent-title-selector-trigger').first().click()
+ const menu = appPage.locator('.agent-title-selector-menu')
+ await expect(menu).toBeVisible()
+ const menuRect = await rectOf(appPage, '.agent-title-selector-menu')
+ expect(menuRect.left).toBeGreaterThanOrEqual(0)
+ expect(menuRect.right).toBeLessThanOrEqual(viewportWidth)
+
+ // Expand a row's sections submenu; confined, it must stay within the menu.
+ await appPage.locator('.agent-title-selector-row-dots').first().click()
+ const nested = appPage.locator('.agent-title-selector-submenu')
+ await expect(nested).toBeVisible()
+ const nestedRect = await rectOf(appPage, '.agent-title-selector-submenu')
+ expect(nestedRect.left).toBeGreaterThanOrEqual(0)
+ expect(nestedRect.right).toBeLessThanOrEqual(viewportWidth)
+ })
+})
diff --git a/desktop-app/ui/docs/STYLE_STANDARDIZATION.md b/desktop-app/ui/docs/STYLE_STANDARDIZATION.md
index effc9b12c..d9ce322ae 100644
--- a/desktop-app/ui/docs/STYLE_STANDARDIZATION.md
+++ b/desktop-app/ui/docs/STYLE_STANDARDIZATION.md
@@ -265,7 +265,10 @@ position computed from a ref), the warning will fire. Resolve it by:
Currently whitelisted hints: `--da-grid-cols`, `fleetMenuPosition`,
`sessionMenuPosition`, `zIndex: visible.length`, `--seg-width` (data-driven
-stacked-bar segment width in the context-window breakdown popover).
+stacked-bar segment width in the context-window breakdown popover),
+`FlyoutPosition` (portaled flyout `left`/`top` computed from
+`getBoundingClientRect()` via `useFlyoutPosition`; matches the
+`*FlyoutPosition` result variables in `ComposerPanel` and `AgentTitleSelector`).
### Extending coverage
diff --git a/desktop-app/ui/src/__tests__/chatDrawerNoHorizontalOverflow.test.ts b/desktop-app/ui/src/__tests__/chatDrawerNoHorizontalOverflow.test.ts
index 228112d78..43453dc44 100644
--- a/desktop-app/ui/src/__tests__/chatDrawerNoHorizontalOverflow.test.ts
+++ b/desktop-app/ui/src/__tests__/chatDrawerNoHorizontalOverflow.test.ts
@@ -68,4 +68,17 @@ describe('chat drawer — no horizontal overflow', () => {
expect(right).toMatch(/min-width:\s*0/)
expect(right).toMatch(/flex:\s*0 1 auto/)
})
+
+ // The composer reference submenu and the agent selector menu are portaled to
+ // document.body and positioned with a fixed rect confined to the drawer in JS,
+ // so they can no longer be cropped by the drawer's overflow-clipping ancestors
+ // (or occluded by the native embed). Pin `position: fixed` and prove the old
+ // in-flow drawer override is gone so nobody reintroduces the clipped in-flow
+ // layout.
+ it('portals the composer submenu and agent selector menu with a fixed rect', () => {
+ expect(ruleBody('.composer-reference-submenu')).toMatch(/position:\s*fixed/)
+ expect(ruleBody('.agent-title-selector-menu')).toMatch(/position:\s*fixed/)
+ // The dead in-flow confinement override must not come back.
+ expect(styles).not.toContain('.chat-drawer .composer-reference-submenu')
+ })
})
diff --git a/desktop-app/ui/src/components/ChatDrawer/ChatDrawer.test.tsx b/desktop-app/ui/src/components/ChatDrawer/ChatDrawer.test.tsx
index 1f6e44376..03fc80c4c 100644
--- a/desktop-app/ui/src/components/ChatDrawer/ChatDrawer.test.tsx
+++ b/desktop-app/ui/src/components/ChatDrawer/ChatDrawer.test.tsx
@@ -100,14 +100,17 @@ describe('ChatDrawer', () => {
})
it('confines the composer reference submenu to the drawer interior, off the embed rect', () => {
- // Right-docked drawer: the embed is to its LEFT, so the composer submenu must
- // stay anchored rightward (left: 100%+, right: auto) to render over drawer DOM
- // instead of being occluded by the native view. A left flip would cross the
- // embed rect — the confinement guards against that.
- const rule = stylesheet.match(/\.chat-drawer \.composer-reference-submenu\s*\{([^}]*)\}/)?.[1]
+ // Right-docked drawer: the embed is to its LEFT and paints above all DOM, so
+ // a submenu crossing the drawer's left edge would be occluded. The submenu is
+ // now portaled to document.body and positioned with a fixed rect clamped to
+ // the drawer's rect in JS (useFlyoutPosition) — a submenu clamped inside the
+ // drawer is by construction off the embed. Pin `position: fixed` and prove the
+ // old in-flow rightward override was removed so it can't reintroduce the
+ // clipped/occluded in-flow layout.
+ const rule = stylesheet.match(/(?:^|[};/])\s*\.composer-reference-submenu\s*\{([^}]*)\}/)?.[1]
expect(rule).toBeTruthy()
- expect(rule).toMatch(/left:\s*calc\(100% \+ var\(--space-1\)\)/)
- expect(rule).toMatch(/right:\s*auto/)
+ expect(rule).toMatch(/position:\s*fixed/)
+ expect(stylesheet).not.toContain('.chat-drawer .composer-reference-submenu')
})
it('exposes a left-edge resize handle that fires the drag callback on mousedown', () => {
diff --git a/desktop-app/ui/src/components/agents/AgentTitleSelector.tsx b/desktop-app/ui/src/components/agents/AgentTitleSelector.tsx
index c31157fca..3ea4bdfa7 100644
--- a/desktop-app/ui/src/components/agents/AgentTitleSelector.tsx
+++ b/desktop-app/ui/src/components/agents/AgentTitleSelector.tsx
@@ -1,6 +1,9 @@
-import { useEffect, useRef, useState } from 'react'
+import { useCallback, useEffect, useRef, useState } from 'react'
+import type { RefObject } from 'react'
+import { createPortal } from 'react-dom'
import { Button, MenuItem } from '@components/Common'
import { useClickOutside } from '@hooks/useClickOutside'
+import { useFlyoutPosition } from '@hooks/useFlyoutPosition'
import type { AgentWorkspaceRoute } from '../../uiTypes'
import { AGENT_ROUTE_LABELS, AGENT_ROUTE_OPTIONS } from './agentRoutes'
@@ -37,8 +40,54 @@ export function AgentTitleSelector({
// row is expanded; the main dropdown can still be open.
const [openAgent, setOpenAgent] = useState<string | null>(null)
const wrapperRef = useRef<HTMLSpanElement | null>(null)
+ const triggerRef = useRef<HTMLButtonElement | null>(null)
+ // The menu is portaled to document.body so the drawer's overflow-clipping
+ // ancestors and the native embed can't crop it; it is positioned with a fixed
+ // rect confined to the chat drawer (or the viewport in full screen).
+ const menuRef = useRef<HTMLSpanElement | null>(null)
+ // The nested sections sub-menu is ALSO portaled (mirroring GfsResourceMenu):
+ // the menu is a scroll container (max-height + overflow), and an overflow box
+ // cannot host a sub-menu that must escape it. Portaling + fixed positioning
+ // keeps it fully visible and confined to the drawer/viewport. Its anchor is
+ // whichever row's dots button is currently expanded.
+ //
+ // One anchor ref PER ROW (keyed by agent id), not a single shared ref:
+ // useFlyoutPosition keys its recompute + ResizeObserver off the anchor ref's
+ // identity. Jumping straight from one row to another keeps `open` true, so a
+ // shared ref never changes identity and the sub-menu would stay pinned to the
+ // previous row's coordinates. A distinct ref per row flips the identity, which
+ // re-runs the effect and re-observes the current row's button (mirrors the
+ // per-item refs in ComposerPanel).
+ const submenuAnchorRefs = useRef(new Map<string, RefObject<HTMLButtonElement | null>>())
+ const getSubmenuAnchorRef = useCallback((agentId: string) => {
+ const existing = submenuAnchorRefs.current.get(agentId)
+ if (existing) return existing
+ const created: RefObject<HTMLButtonElement | null> = { current: null }
+ submenuAnchorRefs.current.set(agentId, created)
+ return created
+ }, [])
+ // A valid RefObject is required even with no row expanded (hooks are
+ // unconditional); the flyout is closed then, so this ref is never read.
+ const noSubmenuAnchorRef = useRef<HTMLButtonElement | null>(null)
+ const submenuAnchorRef = openAgent !== null ? getSubmenuAnchorRef(openAgent) : noSubmenuAnchorRef
+ const submenuRef = useRef<HTMLSpanElement | null>(null)
+ const menuFlyoutPosition = useFlyoutPosition({
+ anchorRef: triggerRef,
+ flyoutRef: menuRef,
+ open,
+ placement: 'below',
+ })
+ const submenuFlyoutPosition = useFlyoutPosition({
+ anchorRef: submenuAnchorRef,
+ flyoutRef: submenuRef,
+ open: open && openAgent !== null,
+ placement: 'right-of',
+ })
- useClickOutside(wrapperRef, open, () => {
+ // All three refs: the menu and its sub-menu are portaled, so a mousedown
+ // inside either is outside the wrapper and would otherwise close the menu
+ // before the item's click fires.
+ useClickOutside([wrapperRef, menuRef, submenuRef], open, () => {
setOpen(false)
setOpenAgent(null)
})
@@ -52,6 +101,7 @@ export function AgentTitleSelector({
setOpenAgent(null)
} else {
setOpen(false)
+ triggerRef.current?.focus()
}
}
}
@@ -62,6 +112,7 @@ export function AgentTitleSelector({
return (
<span className="agent-title-selector" ref={wrapperRef}>
<Button
+ ref={triggerRef}
color="transparent"
className="agent-title-selector-trigger"
aria-label={ariaLabel}
@@ -79,73 +130,99 @@ export function AgentTitleSelector({
<path d={open ? 'm4.5 10 3.5-3.5L11.5 10' : 'm4.5 6 3.5 3.5L11.5 6'} />
</svg>
</Button>
- {open && (
- <span className="agent-title-selector-menu" role="menu">
- {options.length ? (
- options.map(option => {
- const isExpanded = openAgent === option.id
- const isActive = option.id === selectedId
- return (
- <span
- key={option.id}
- className={`agent-title-selector-row${isActive ? ' agent-title-selector-row--active' : ''}`}
- >
- <button
- type="button"
- className="agent-title-selector-row-name"
- role="menuitem"
- aria-current={isActive ? 'true' : undefined}
- onClick={() => {
- setOpen(false)
- setOpenAgent(null)
- if (option.id !== selectedId) {
- onSelectAgent(option.id)
- }
- }}
+ {open &&
+ createPortal(
+ <span
+ className="agent-title-selector-menu"
+ ref={menuRef}
+ role="menu"
+ style={{
+ left: menuFlyoutPosition?.left ?? 0,
+ top: menuFlyoutPosition?.top ?? 0,
+ // Hidden at the origin until the first layout pass sets a real
+ // rect, so it never flashes in the top-left corner.
+ visibility: menuFlyoutPosition ? undefined : 'hidden',
+ }}
+ >
+ {options.length ? (
+ options.map(option => {
+ const isExpanded = openAgent === option.id
+ const isActive = option.id === selectedId
+ return (
+ <span
+ key={option.id}
+ className={`agent-title-selector-row${isActive ? ' agent-title-selector-row--active' : ''}`}
>
- <span className="agent-title-selector-row-label">{option.label}</span>
- </button>
- <button
- type="button"
- className="agent-title-selector-row-dots"
- role="menuitem"
- aria-label={`Open ${option.label} sections`}
- aria-haspopup="menu"
- aria-expanded={isExpanded}
- onClick={() => setOpenAgent(isExpanded ? null : option.id)}
- >
- <svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
- <circle cx="3.5" cy="8" r="1.2" />
- <circle cx="8" cy="8" r="1.2" />
- <circle cx="12.5" cy="8" r="1.2" />
- </svg>
- </button>
- {isExpanded ? (
- <span className="agent-title-selector-submenu" role="menu">
- {AGENT_ROUTE_OPTIONS.map(route => (
- <MenuItem
- key={route}
- className="agent-title-selector-submenu-item"
- onClick={() => {
- setOpen(false)
- setOpenAgent(null)
- onOpenRoute(option.id, route)
- }}
- role="menuitem"
- >
- {AGENT_ROUTE_LABELS[route]}
- </MenuItem>
- ))}
- </span>
- ) : null}
- </span>
- )
- })
- ) : (
- <span className="agent-title-selector-empty">{emptyLabel}</span>
- )}
- </span>
- )}
+ <button
+ type="button"
+ className="agent-title-selector-row-name"
+ role="menuitem"
+ aria-current={isActive ? 'true' : undefined}
+ onClick={() => {
+ setOpen(false)
+ setOpenAgent(null)
+ if (option.id !== selectedId) {
+ onSelectAgent(option.id)
+ }
+ }}
+ >
+ <span className="agent-title-selector-row-label">{option.label}</span>
+ </button>
+ <button
+ type="button"
+ ref={getSubmenuAnchorRef(option.id)}
+ className="agent-title-selector-row-dots"
+ role="menuitem"
+ aria-label={`Open ${option.label} sections`}
+ aria-haspopup="menu"
+ aria-expanded={isExpanded}
+ onClick={() => setOpenAgent(isExpanded ? null : option.id)}
+ >
+ <svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
+ <circle cx="3.5" cy="8" r="1.2" />
+ <circle cx="8" cy="8" r="1.2" />
+ <circle cx="12.5" cy="8" r="1.2" />
+ </svg>
+ </button>
+ </span>
+ )
+ })
+ ) : (
+ <span className="agent-title-selector-empty">{emptyLabel}</span>
+ )}
+ </span>,
+ document.body
+ )}
+ {open && openAgent !== null
+ ? createPortal(
+ <span
+ className="agent-title-selector-submenu"
+ ref={submenuRef}
+ role="menu"
+ style={{
+ left: submenuFlyoutPosition?.left ?? 0,
+ top: submenuFlyoutPosition?.top ?? 0,
+ visibility: submenuFlyoutPosition ? undefined : 'hidden',
+ }}
+ >
+ {AGENT_ROUTE_OPTIONS.map(route => (
+ <MenuItem
+ key={route}
+ className="agent-title-selector-submenu-item"
+ onClick={() => {
+ setOpen(false)
+ setOpenAgent(null)
+ onOpenRoute(openAgent, route)
+ }}
+ role="menuitem"
+ >
+ {AGENT_ROUTE_LABELS[route]}
+ </MenuItem>
+ ))}
+ </span>,
+ document.body
+ )
+ : null}
</span>
)
}
diff --git a/desktop-app/ui/src/components/agents/ComposerPanel.tsx b/desktop-app/ui/src/components/agents/ComposerPanel.tsx
index c6e3ad1eb..dd17760d7 100644
--- a/desktop-app/ui/src/components/agents/ComposerPanel.tsx
+++ b/desktop-app/ui/src/components/agents/ComposerPanel.tsx
@@ -1,4 +1,5 @@
import React, { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'
+import { createPortal } from 'react-dom'
import { useAgentChatActionsContext } from '@contexts/AgentChatActionsContext'
import { useChatComposerStateContext } from '@contexts/ChatComposerStateContext'
import { useMcpRuntimeContext } from '@contexts/McpRuntimeContext'
@@ -27,6 +28,7 @@ import { useContextsDataController } from '@hooks/domain/useContextsDataControll
import { useMcpServersDataController } from '@hooks/domain/useMcpServersDataController'
import { useClickOutside } from '@hooks/useClickOutside'
import { useComposerDraft } from '@hooks/useComposerDraft'
+import { useFlyoutPosition } from '@hooks/useFlyoutPosition'
import { useHostModels } from '@hooks/useHostModels'
import { readImageHeaderDimensions } from '@lib/imageHeaderDimensions'
import type { WorkflowRecipeListResult } from '../../../../src/types'
@@ -165,6 +167,25 @@ export function ComposerPanel({ inline = false, agentSelector }: ComposerPanelPr
const composerInputWidthRef = useRef<number | null>(null)
const composerFileInputRef = useRef<HTMLInputElement | null>(null)
const composerMenuRef = useRef<HTMLSpanElement | null>(null)
+ // The reference submenu is portaled out of the composer (the drawer's
+ // overflow-clipping ancestors would otherwise crop it), so it needs an anchor
+ // ref per primary item and its own ref for click-outside + positioning.
+ const composerSubmenuRef = useRef<HTMLSpanElement | null>(null)
+ const pluginsItemRef = useRef<HTMLButtonElement | null>(null)
+ const connectorsItemRef = useRef<HTMLButtonElement | null>(null)
+ const agentFilesItemRef = useRef<HTMLButtonElement | null>(null)
+ const composerSubmenuAnchorRef =
+ composerSubmenu === 'connectors'
+ ? connectorsItemRef
+ : composerSubmenu === 'agent-files'
+ ? agentFilesItemRef
+ : pluginsItemRef
+ const submenuFlyoutPosition = useFlyoutPosition({
+ anchorRef: composerSubmenuAnchorRef,
+ flyoutRef: composerSubmenuRef,
+ open: composerMenuOpen && composerSubmenu !== null,
+ placement: 'right-of',
+ })
// Issue #654: image capability comes from the host-projected per-model
// decision shared with the selector and the send path — never from the
@@ -190,7 +211,10 @@ export function ComposerPanel({ inline = false, agentSelector }: ComposerPanelPr
const agentFilesAvailable = Boolean(agentFilesState?.items?.length)
const agentFilesDisabled = agentFilesLoading || !agentFilesAvailable
- useClickOutside(composerMenuRef, composerMenuOpen, () => {
+ // Both refs: the submenu is portaled to document.body, so a mousedown on a
+ // submenu item is outside `composerMenuRef` and would close the menu before
+ // the item's click fires.
+ useClickOutside([composerMenuRef, composerSubmenuRef], composerMenuOpen, () => {
setComposerMenuOpen(false)
setComposerSubmenu(null)
})
@@ -829,6 +853,9 @@ export function ComposerPanel({ inline = false, agentSelector }: ComposerPanelPr
<span className="composer-reference-menu-panel" role="menu">
<span className="composer-reference-menu-primary">
<MenuItem
+ ref={pluginsItemRef}
+ aria-haspopup="menu"
+ aria-expanded={composerSubmenu === 'plugins'}
leadingIcon={<IconWorkflows />}
onMouseEnter={() => setComposerSubmenu('plugins')}
onFocus={() => setComposerSubmenu('plugins')}
@@ -838,6 +865,9 @@ export function ComposerPanel({ inline = false, agentSelector }: ComposerPanelPr
Plugins
</MenuItem>
<MenuItem
+ ref={connectorsItemRef}
+ aria-haspopup="menu"
+ aria-expanded={composerSubmenu === 'connectors'}
leadingIcon={<IconConnectors />}
onMouseEnter={() => setComposerSubmenu('connectors')}
onFocus={() => setComposerSubmenu('connectors')}
@@ -848,7 +878,12 @@ export function ComposerPanel({ inline = false, agentSelector }: ComposerPanelPr
</MenuItem>
{SHOW_AGENT_FILES_UI ? (
<MenuItem
+ ref={agentFilesItemRef}
aria-disabled={agentFilesDisabled}
+ aria-haspopup={agentFilesDisabled ? 'menu' : undefined}
+ aria-expanded={
+ agentFilesDisabled ? composerSubmenu === 'agent-files' : undefined
+ }
className={
agentFilesDisabled ? 'composer-reference-menu-item-disabled' : undefined
}
@@ -885,79 +920,88 @@ export function ComposerPanel({ inline = false, agentSelector }: ComposerPanelPr
Upload Files
</MenuItem>
</span>
- {composerSubmenu === 'plugins' ? (
- <span
- className="composer-reference-submenu composer-reference-submenu--plugins"
- role="menu"
- >
- {pluginsLoading ? (
- <span className="composer-reference-menu-empty">Loading plugins...</span>
- ) : pluginsError ? (
- <span className="composer-reference-menu-empty">{pluginsError}</span>
- ) : pluginOptions.length ? (
- pluginOptions.map(plugin => (
- <MenuItem
- key={plugin.id}
- onClick={() =>
- addComposerReference({
- id: plugin.id,
- type: 'plugin',
- namespace: plugin.namespace,
- name: plugin.name,
- label: plugin.label,
- })
- }
- role="menuitem"
- >
- {plugin.label}
- </MenuItem>
- ))
- ) : (
- <span className="composer-reference-menu-empty">No plugins available</span>
- )}
- </span>
- ) : null}
- {composerSubmenu === 'connectors' ? (
+ </span>
+ ) : null}
+ {/* The submenu is portaled to document.body and positioned with a
+ fixed rect confined to the chat drawer. In-flow it was cropped
+ by the drawer's overflow-clipping ancestors and the native
+ embed painting over it; see useFlyoutPosition. */}
+ {composerMenuOpen && composerSubmenu !== null
+ ? createPortal(
<span
- className="composer-reference-submenu composer-reference-submenu--connectors"
+ className="composer-reference-submenu"
+ ref={composerSubmenuRef}
role="menu"
+ style={{
+ left: submenuFlyoutPosition?.left ?? 0,
+ top: submenuFlyoutPosition?.top ?? 0,
+ // Hidden at the origin until the first layout pass sets a
+ // real rect, so it never flashes in the top-left corner.
+ visibility: submenuFlyoutPosition ? undefined : 'hidden',
+ }}
>
- {connectorOptions.length ? (
- connectorOptions.map(connector => (
- <MenuItem
- key={connector.id}
- onClick={() =>
- addComposerReference({
- id: connector.id,
- type: 'connector',
- name: connector.name,
- label: connector.label,
- })
- }
- role="menuitem"
- >
- {connector.label}
- </MenuItem>
- ))
- ) : (
+ {composerSubmenu === 'plugins' ? (
+ pluginsLoading ? (
+ <span className="composer-reference-menu-empty">Loading plugins...</span>
+ ) : pluginsError ? (
+ <span className="composer-reference-menu-empty">{pluginsError}</span>
+ ) : pluginOptions.length ? (
+ pluginOptions.map(plugin => (
+ <MenuItem
+ key={plugin.id}
+ onClick={() =>
+ addComposerReference({
+ id: plugin.id,
+ type: 'plugin',
+ namespace: plugin.namespace,
+ name: plugin.name,
+ label: plugin.label,
+ })
+ }
+ role="menuitem"
+ >
+ {plugin.label}
+ </MenuItem>
+ ))
+ ) : (
+ <span className="composer-reference-menu-empty">
+ No plugins available
+ </span>
+ )
+ ) : composerSubmenu === 'connectors' ? (
+ connectorOptions.length ? (
+ connectorOptions.map(connector => (
+ <MenuItem
+ key={connector.id}
+ onClick={() =>
+ addComposerReference({
+ id: connector.id,
+ type: 'connector',
+ name: connector.name,
+ label: connector.label,
+ })
+ }
+ role="menuitem"
+ >
+ {connector.label}
+ </MenuItem>
+ ))
+ ) : (
+ <span className="composer-reference-menu-empty">
+ No connectors available
+ </span>
+ )
+ ) : SHOW_AGENT_FILES_UI && composerSubmenu === 'agent-files' ? (
<span className="composer-reference-menu-empty">
- No connectors available
+ {agentFilesLoading
+ ? 'Loading Agent Files...'
+ : 'No Agent Files Available'}
</span>
- )}
- </span>
- ) : null}
- {SHOW_AGENT_FILES_UI && composerSubmenu === 'agent-files' ? (
- <span
- className="composer-reference-submenu composer-reference-submenu--agent-files"
- role="menu"
- >
- <span className="composer-reference-menu-empty">
- {agentFilesLoading ? 'Loading Agent Files...' : 'No Agent Files Available'}
- </span>
- </span>
- ) : null}
- </span>
- ) : null}
+ ) : null}
+ </span>,
+ document.body
+ )
+ : null}
</span>
{hasComposerAttachments ? (
<span className="composer-attachments-list composer-attachments-list--inline">
diff --git a/desktop-app/ui/src/components/agents/__tests__/AgentTitleSelector.test.tsx b/desktop-app/ui/src/components/agents/__tests__/AgentTitleSelector.test.tsx
index 638cc1f6e..54ae7e24e 100644
--- a/desktop-app/ui/src/components/agents/__tests__/AgentTitleSelector.test.tsx
+++ b/desktop-app/ui/src/components/agents/__tests__/AgentTitleSelector.test.tsx
@@ -55,6 +55,29 @@ function findDotsItem(label: string) {
return screen.getByRole('menuitem', { name: `Open ${label} sections` })
}
+// jsdom performs no layout, so every getBoundingClientRect() is 0×0 and the two
+// rows' anchors are indistinguishable. Stub each row's dots button with a
+// distinct rect so the sub-menu's computed coordinates reveal which row it is
+// anchored to.
+function stubRect(el: Element, rect: { top: number; right: number }) {
+ el.getBoundingClientRect = () =>
+ ({
+ top: rect.top,
+ right: rect.right,
+ bottom: rect.top + 16,
+ left: rect.right - 10,
+ width: 10,
+ height: 16,
+ x: rect.right - 10,
+ y: rect.top,
+ toJSON: () => ({}),
+ }) as DOMRect
+}
+
+function submenuEl() {
+ return document.querySelector('.agent-title-selector-submenu') as HTMLElement | null
+}
+
afterEach(() => {
cleanup()
vi.restoreAllMocks()
@@ -146,4 +169,65 @@ describe('AgentTitleSelector', () => {
openMenu()
expect(screen.getByText('No agents')).not.toBeNull()
})
+
+ it('portals the menu out of the selector wrapper', () => {
+ const { container } = renderSelector()
+ openMenu()
+ const menuEl = screen.getByRole('menu')
+ expect(container.querySelector('.agent-title-selector')?.contains(menuEl)).toBe(false)
+ expect(menuEl.parentElement).toBe(document.body)
+ })
+
+ it('portals the nested sections sub-menu out of the (scrollable) menu so it cannot be clipped', () => {
+ renderSelector()
+ openMenu()
+ fireEvent.click(findDotsItem('Beta'))
+
+ const submenu = document.querySelector('.agent-title-selector-submenu')
+ expect(submenu).toBeTruthy()
+ // Not a descendant of the menu (which is a max-height/overflow scroll box):
+ // it hangs off document.body so the overflow can't crop it.
+ const menuEl = screen
+ .getAllByRole('menu')
+ .find(el => el.classList.contains('agent-title-selector-menu'))
+ expect(menuEl?.contains(submenu)).toBe(false)
+ expect(submenu?.parentElement).toBe(document.body)
+ })
+
+ it('re-anchors the sections sub-menu when jumping straight from one row to another', () => {
+ renderSelector()
+ openMenu()
+
+ const betaDots = findDotsItem('Beta')
+ const gammaDots = findDotsItem('Gamma')
+ // Distinct top so the sub-menu's fixed `top` reveals which row it follows.
+ stubRect(betaDots, { top: 100, right: 50 })
+ stubRect(gammaDots, { top: 300, right: 50 })
+
+ // Expand Beta → sub-menu positioned at Beta's anchor (top 100).
+ fireEvent.click(betaDots)
+ expect(submenuEl()?.style.top).toBe('100px')
+
+ // Jump straight to Gamma WITHOUT closing the menu first. The regression:
+ // with a single shared anchor ref, useFlyoutPosition never recomputes and
+ // the sub-menu stays pinned to Beta's coordinates (top 100).
+ fireEvent.click(gammaDots)
+ expect(submenuEl()?.style.top).toBe('300px')
+ })
+
+ it('keeps the menu open when a mousedown lands inside the portaled menu or sub-menu', () => {
+ renderSelector()
+ openMenu()
+ fireEvent.mouseDown(
+ screen.getAllByRole('menu').find(el => el.classList.contains('agent-title-selector-menu'))!
+ )
+ expect(screen.queryByRole('menu')).not.toBeNull()
+
+ // Open the nested sub-menu (portaled) and mousedown inside it: still open.
+ fireEvent.click(findDotsItem('Beta'))
+ fireEvent.mouseDown(document.querySelector('.agent-title-selector-submenu') as HTMLElement)
+ expect(document.querySelector('.agent-title-selector-submenu')).not.toBeNull()
+ // The route item still fires its click (guard kept it mounted through mousedown).
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Connectors' }))
+ })
})
diff --git a/desktop-app/ui/src/components/agents/__tests__/ComposerPanel.test.tsx b/desktop-app/ui/src/components/agents/__tests__/ComposerPanel.test.tsx
index 1909dd7ee..ab454c74e 100644
--- a/desktop-app/ui/src/components/agents/__tests__/ComposerPanel.test.tsx
+++ b/desktop-app/ui/src/components/agents/__tests__/ComposerPanel.test.tsx
@@ -16,6 +16,7 @@ import {
type ImageInputDecision,
imageInputBlockMessage,
} from '../../../../../src/imageInputDecision'
+import type { WorkflowRecipeListResult } from '../../../../../src/types'
import type { ComposerImageAttachment, FailedAgentSend } from '../../../uiTypes'
import { ComposerPanel } from '../ComposerPanel'
@@ -139,7 +140,11 @@ function setScrollHeight(textarea: HTMLTextAreaElement, value: number) {
beforeEach(() => {
Object.defineProperty(window, 'clerum', {
configurable: true,
- value: { workflows: { list: vi.fn(async () => ({ items: [] })) } },
+ value: {
+ workflows: {
+ list: vi.fn(async (): Promise<WorkflowRecipeListResult> => ({ items: [], count: 0 })),
+ },
+ },
})
})
@@ -228,7 +233,9 @@ describe.each([
fireEvent.click(screen.getByRole('button', { name: /Model — Haiku 4.5/ }))
const contextMenu = container.querySelector('.composer-reference-menu-panel')
- const submenu = container.querySelector('.composer-reference-submenu')
+ // The submenu is portaled to document.body, so it lives outside the
+ // component subtree entirely — query the whole document for it.
+ const submenu = document.querySelector('.composer-reference-submenu')
const modelMenu = container.querySelector('.model-selector-popover')
expect(contextMenu).toBeTruthy()
@@ -238,7 +245,9 @@ describe.each([
expect(viewport?.contains(submenu)).toBe(false)
expect(viewport?.contains(modelMenu)).toBe(false)
expect(shell?.contains(contextMenu)).toBe(true)
- expect(shell?.contains(submenu)).toBe(true)
+ // Portaled: no longer a descendant of the composer shell (or the container).
+ expect(shell?.contains(submenu)).toBe(false)
+ expect(container.contains(submenu)).toBe(false)
expect(shell?.contains(modelMenu)).toBe(true)
expect(cssRule('\\.composer-input-shell')).not.toMatch(/overflow\s*:/)
expect(cssRule('\\.composer-textarea-viewport')).toMatch(/overflow\s*:\s*hidden/)
@@ -266,6 +275,61 @@ describe.each([
})
})
+describe('ComposerPanel reference submenu portaling', () => {
+ it('portals the submenu out of the drawer overflow-clipping ancestors', () => {
+ // Reproduce the narrow-drawer DOM: the composer sits inside ancestors that
+ // clip overflow. In-flow, the submenu was cropped by them; portaled, it is
+ // no longer their descendant.
+ const { container } = render(
+ <div className="chat-drawer">
+ <div className="chat-drawer__surface">
+ <div className="agent-workspace-body-slot">
+ <ComposerPanel inline={false} />
+ </div>
+ </div>
+ </div>
+ )
+
+ fireEvent.click(screen.getByRole('button', { name: 'Add context' }))
+ fireEvent.mouseEnter(screen.getByRole('menuitem', { name: /Plugins/ }))
+
+ const submenu = document.querySelector('.composer-reference-submenu')
+ expect(submenu).toBeTruthy()
+ // Not a descendant of the overflow-clipping ancestor, the drawer, or the
+ // rendered component subtree — it hangs off document.body.
+ expect(container.querySelector('.agent-workspace-body-slot')?.contains(submenu)).toBe(false)
+ expect(container.querySelector('.chat-drawer')?.contains(submenu)).toBe(false)
+ expect(container.contains(submenu)).toBe(false)
+ expect(submenu?.parentElement).toBe(document.body)
+ })
+
+ it('keeps the menu mounted through a mousedown on a portaled submenu item so its click fires', async () => {
+ // A clickable plugin so the submenu holds a real menuitem, not an empty state.
+ window.clerum.workflows.list = vi.fn(
+ async (): Promise<WorkflowRecipeListResult> => ({
+ items: [{ metadata: { namespace: 'ns', name: 'plug-a' } }],
+ count: 1,
+ })
+ )
+ render(<ComposerPanel inline={false} />)
+
+ fireEvent.click(screen.getByRole('button', { name: 'Add context' }))
+ fireEvent.mouseEnter(screen.getByRole('menuitem', { name: /Plugins/ }))
+ const item = await screen.findByRole('menuitem', { name: 'plug-a' })
+
+ // The real pointer sequence is mousedown then click. The click-outside guard
+ // listens on mousedown; with a single-ref guard the portaled item would read
+ // as "outside", close the menu, and unmount the item before the click.
+ fireEvent.mouseDown(item)
+ expect(screen.queryByRole('menuitem', { name: 'plug-a' })).not.toBeNull()
+
+ fireEvent.click(item)
+ expect(actionsMock.handleAddComposerReferenceAttachments).toHaveBeenCalledWith([
+ expect.objectContaining({ type: 'plugin', name: 'plug-a', namespace: 'ns' }),
+ ])
+ })
+})
+
// ---------------------------------------------------------------------------
// Issue #654: composer image attachments through real DOM events.
//
diff --git a/desktop-app/ui/src/hooks/__tests__/useClickOutside.test.ts b/desktop-app/ui/src/hooks/__tests__/useClickOutside.test.ts
new file mode 100644
index 000000000..f5dbdd52e
--- /dev/null
+++ b/desktop-app/ui/src/hooks/__tests__/useClickOutside.test.ts
@@ -0,0 +1,57 @@
+// @vitest-environment jsdom
+import { createElement, useRef } from 'react'
+import type { RefObject } from 'react'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { cleanup, fireEvent, render } from '@testing-library/react'
+import { useClickOutside } from '../useClickOutside'
+
+afterEach(cleanup)
+
+// Renders `count` boxes (each carrying a ref) plus an outside box, wires the
+// hook to the requested refs, and hands the boxes back for firing events.
+function renderHarness(refCount: 1 | 2, onOutside: () => void) {
+ function Harness() {
+ const a = useRef<HTMLDivElement | null>(null)
+ const b = useRef<HTMLDivElement | null>(null)
+ const refs: RefObject<HTMLDivElement | null> | Array<RefObject<HTMLDivElement | null>> =
+ refCount === 1 ? a : [a, b]
+ useClickOutside(refs, true, onOutside)
+ return createElement(
+ 'div',
+ null,
+ createElement('div', { ref: a, 'data-testid': 'a' }, 'a'),
+ createElement('div', { ref: b, 'data-testid': 'b' }, 'b'),
+ createElement('div', { 'data-testid': 'outside' }, 'outside')
+ )
+ }
+ return render(createElement(Harness))
+}
+
+describe('useClickOutside', () => {
+ it('single ref: fires only for clicks outside that ref (unchanged behavior)', () => {
+ const onOutside = vi.fn()
+ const { getByTestId } = renderHarness(1, onOutside)
+
+ fireEvent.mouseDown(getByTestId('a'))
+ expect(onOutside).not.toHaveBeenCalled()
+
+ fireEvent.mouseDown(getByTestId('outside'))
+ expect(onOutside).toHaveBeenCalledTimes(1)
+ })
+
+ it('multi ref: a click inside ANY provided ref does not count as outside', () => {
+ const onOutside = vi.fn()
+ const { getByTestId } = renderHarness(2, onOutside)
+
+ // This is the portaled-submenu case: the click lands in the second ref
+ // (outside the first), and must not close the menu.
+ fireEvent.mouseDown(getByTestId('b'))
+ expect(onOutside).not.toHaveBeenCalled()
+
+ fireEvent.mouseDown(getByTestId('a'))
+ expect(onOutside).not.toHaveBeenCalled()
+
+ fireEvent.mouseDown(getByTestId('outside'))
+ expect(onOutside).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/desktop-app/ui/src/hooks/useClickOutside.ts b/desktop-app/ui/src/hooks/useClickOutside.ts
index 97e73c9f5..950318da8 100644
--- a/desktop-app/ui/src/hooks/useClickOutside.ts
+++ b/desktop-app/ui/src/hooks/useClickOutside.ts
@@ -1,21 +1,35 @@
import { useEffect } from 'react'
import type { RefObject } from 'react'
+// Accepts either a single ref or a list of refs. A click counts as "outside"
+// only when it lands outside EVERY provided ref. This matters for portaled
+// menus: the menu panel and its portaled submenu are separate DOM subtrees, so a
+// mousedown on a submenu item would otherwise register as outside the panel ref,
+// close the menu before the click fires, and swallow the action. Passing both
+// refs keeps the menu mounted through the click. The single-ref form is
+// unchanged for the existing consumers.
export function useClickOutside<T extends HTMLElement>(
- ref: RefObject<T | null>,
+ refs: RefObject<T | null> | Array<RefObject<T | null>>,
isActive: boolean,
onOutside: () => void
) {
useEffect(() => {
if (!isActive) return
+ const refList = Array.isArray(refs) ? refs : [refs]
const handleClickOutside = (event: MouseEvent) => {
- if (!ref.current?.contains(event.target as Node)) {
+ const target = event.target as Node
+ const insideAny = refList.some(ref => ref.current?.contains(target))
+ if (!insideAny) {
onOutside()
}
}
window.addEventListener('mousedown', handleClickOutside)
return () => window.removeEventListener('mousedown', handleClickOutside)
- }, [isActive, onOutside, ref])
+ // Depend on each resolved ref (spread) rather than the array literal itself,
+ // which a caller re-creates every render — keeping the dep on stable ref
+ // objects. The deps length is stable because a given call site always passes
+ // the same shape (one ref, or the same-length array).
+ }, [isActive, onOutside, ...(Array.isArray(refs) ? refs : [refs])])
}
diff --git a/desktop-app/ui/src/hooks/useFlyoutPosition.ts b/desktop-app/ui/src/hooks/useFlyoutPosition.ts
new file mode 100644
index 000000000..611b5cd91
--- /dev/null
+++ b/desktop-app/ui/src/hooks/useFlyoutPosition.ts
@@ -0,0 +1,84 @@
+import { useCallback, useLayoutEffect, useState } from 'react'
+import type { RefObject } from 'react'
+import { computeFlyoutPosition } from '@lib/flyoutPosition'
+import type { FlyoutPlacement, FlyoutPosition } from '@lib/flyoutPosition'
+
+type UseFlyoutPositionArgs = {
+ anchorRef: RefObject<HTMLElement | null>
+ flyoutRef: RefObject<HTMLElement | null>
+ open: boolean
+ placement: FlyoutPlacement
+ // The confining ancestor. Its rect bounds the flyout horizontally (for
+ // 'right-of') / horizontally (for 'below'); the other axis uses the viewport.
+ // Defaults to the right-docked chat drawer, whose ancestors clip overflow.
+ boundsSelector?: string
+ gap?: number
+ inset?: number
+}
+
+// Positions a portaled flyout (rendered to document.body) at fixed viewport
+// coordinates computed from its anchor, confined to the rect of `boundsSelector`
+// (or the viewport when that ancestor is absent or has zero width — e.g. jsdom,
+// or a full-screen mount outside the drawer). Recomputes on open, resize,
+// capture-phase scroll, and any size change of the anchor, flyout, or bounds
+// ancestor (which covers dragging the drawer's resize handle). Returns null
+// until the first layout pass; render the flyout hidden at the origin until then
+// so it never flashes in the top-left corner.
+export function useFlyoutPosition({
+ anchorRef,
+ flyoutRef,
+ open,
+ placement,
+ boundsSelector = '.chat-drawer',
+ gap,
+ inset,
+}: UseFlyoutPositionArgs): FlyoutPosition | null {
+ const [position, setPosition] = useState<FlyoutPosition | null>(null)
+
+ const update = useCallback(() => {
+ const anchor = anchorRef.current
+ const flyout = flyoutRef.current
+ if (!anchor || !flyout) return
+
+ const anchorRect = anchor.getBoundingClientRect()
+ const flyoutRect = flyout.getBoundingClientRect()
+ const boundsEl = anchor.closest<HTMLElement>(boundsSelector)
+ const boundsRect = boundsEl?.getBoundingClientRect()
+ const viewportWidth = window.innerWidth
+ const viewportHeight = window.innerHeight
+ // A zero-width bounds rect means the ancestor is absent or unlaid-out
+ // (jsdom reports every rect as 0). Fall back to the full viewport so the
+ // flyout is never clamped to a degenerate box.
+ const bounds =
+ boundsRect && boundsRect.width > 0
+ ? { left: boundsRect.left, right: boundsRect.right, top: 0, bottom: viewportHeight }
+ : { left: 0, right: viewportWidth, top: 0, bottom: viewportHeight }
+
+ setPosition(computeFlyoutPosition({ anchorRect, flyoutRect, bounds, placement, gap, inset }))
+ }, [anchorRef, boundsSelector, flyoutRef, gap, inset, placement])
+
+ useLayoutEffect(() => {
+ if (!open) {
+ setPosition(null)
+ return
+ }
+
+ update()
+ window.addEventListener('resize', update)
+ window.addEventListener('scroll', update, true)
+ const resizeObserver = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(update)
+ const anchor = anchorRef.current
+ const boundsEl = anchor?.closest<HTMLElement>(boundsSelector)
+ if (anchor) resizeObserver?.observe(anchor)
+ if (flyoutRef.current) resizeObserver?.observe(flyoutRef.current)
+ if (boundsEl) resizeObserver?.observe(boundsEl)
+
+ return () => {
+ window.removeEventListener('resize', update)
+ window.removeEventListener('scroll', update, true)
+ resizeObserver?.disconnect()
+ }
+ }, [anchorRef, boundsSelector, flyoutRef, open, update])
+
+ return position
+}
diff --git a/desktop-app/ui/src/lib/__tests__/flyoutPosition.test.ts b/desktop-app/ui/src/lib/__tests__/flyoutPosition.test.ts
new file mode 100644
index 000000000..acd80128d
--- /dev/null
+++ b/desktop-app/ui/src/lib/__tests__/flyoutPosition.test.ts
@@ -0,0 +1,90 @@
+import { describe, expect, it } from 'vitest'
+import { computeFlyoutPosition } from '../flyoutPosition'
+import type { FlyoutBounds } from '../flyoutPosition'
+
+// A tall viewport so vertical clamping never interferes with the horizontal cases.
+const DRAWER: FlyoutBounds = { left: 660, right: 1000, top: 0, bottom: 800 }
+const WIDE: FlyoutBounds = { left: 0, right: 2000, top: 0, bottom: 2000 }
+const INSET = 8
+
+describe('computeFlyoutPosition — right-of (submenu)', () => {
+ it('flips to the anchor left side and clamps inside the bounds when the right side overflows', () => {
+ // Anchor hugs the drawer's right edge, so opening rightward would overflow.
+ const { left, top } = computeFlyoutPosition({
+ anchorRect: { left: 880, right: 900, top: 100, bottom: 120 },
+ flyoutRect: { width: 210, height: 300 },
+ bounds: DRAWER,
+ placement: 'right-of',
+ })
+ // Never crosses the inset drawer edges.
+ expect(left).toBeGreaterThanOrEqual(DRAWER.left)
+ expect(left + 210).toBeLessThanOrEqual(DRAWER.right - INSET)
+ // Vertically aligned to the anchor's top.
+ expect(top).toBe(100)
+ })
+
+ it('opens to the right when there is room', () => {
+ const { left } = computeFlyoutPosition({
+ anchorRect: { left: 80, right: 100, top: 100, bottom: 120 },
+ flyoutRect: { width: 210, height: 300 },
+ bounds: WIDE,
+ placement: 'right-of',
+ gap: 6,
+ })
+ // anchor.right + gap = 106; fits, so no flip.
+ expect(left).toBe(106)
+ })
+
+ it('clamps the top so a low anchor keeps the flyout inside the bounds', () => {
+ const { top } = computeFlyoutPosition({
+ anchorRect: { left: 700, right: 720, top: 780, bottom: 800 },
+ flyoutRect: { width: 210, height: 300 },
+ bounds: DRAWER,
+ placement: 'right-of',
+ })
+ // maxTop = (bottom - inset) - height = 792 - 300 = 492.
+ expect(top).toBe(492)
+ })
+})
+
+describe('computeFlyoutPosition — below (dropdown)', () => {
+ it('drops under the anchor, left-aligned, clamped into the bounds', () => {
+ const { left, top } = computeFlyoutPosition({
+ anchorRect: { left: 100, right: 200, top: 100, bottom: 120 },
+ flyoutRect: { width: 210, height: 150 },
+ bounds: DRAWER,
+ placement: 'below',
+ gap: 6,
+ })
+ // Left anchor (100) is left of the inset drawer edge (668), so it clamps in.
+ expect(left).toBe(DRAWER.left + INSET)
+ expect(left + 210).toBeLessThanOrEqual(DRAWER.right - INSET)
+ // Drops below: anchor.bottom + gap.
+ expect(top).toBe(126)
+ })
+
+ it('keeps the full-screen anchor left when the viewport has room', () => {
+ const { left, top } = computeFlyoutPosition({
+ anchorRect: { left: 300, right: 420, top: 60, bottom: 84 },
+ flyoutRect: { width: 240, height: 200 },
+ bounds: WIDE,
+ placement: 'below',
+ gap: 6,
+ })
+ expect(left).toBe(300)
+ expect(top).toBe(90)
+ })
+
+ it('flips above the anchor only when the drop below overflows and there is room above', () => {
+ const { top } = computeFlyoutPosition({
+ anchorRect: { left: 700, right: 800, top: 500, bottom: 520 },
+ flyoutRect: { width: 210, height: 300 },
+ bounds: { left: 660, right: 1000, top: 0, bottom: 600 },
+ placement: 'below',
+ gap: 6,
+ })
+ // Below (526 + 300 = 826) overflows bottom (600 - 8 = 592); above fits
+ // (500 - 6 - 300 = 194 >= 8), so it opens above.
+ expect(top).toBe(194)
+ })
+})
diff --git a/desktop-app/ui/src/lib/flyoutPosition.ts b/desktop-app/ui/src/lib/flyoutPosition.ts
new file mode 100644
index 000000000..af749a0c3
--- /dev/null
+++ b/desktop-app/ui/src/lib/flyoutPosition.ts
@@ -0,0 +1,91 @@
+// Pure geometry for a portaled flyout (submenu / dropdown). Kept free of the
+// DOM and `window` so it is unit-testable under jsdom, which performs no layout.
+// The runtime wiring (reading rects, listeners, ResizeObserver) lives in
+// `@hooks/useFlyoutPosition`. Semantics mirror GfsResourceMenu's
+// `positionSubmenu`/`positionPanel`: prefer a side, flip to the opposite side
+// when the preferred side would cross the bounds, then clamp inside the bounds.
+
+export type FlyoutPlacement = 'right-of' | 'below'
+
+// Only the fields the geometry reads. A DOMRect satisfies this shape.
+export type FlyoutAnchorRect = {
+ left: number
+ right: number
+ top: number
+ bottom: number
+}
+
+export type FlyoutSize = {
+ width: number
+ height: number
+}
+
+// The rectangle the flyout must stay inside, in viewport coordinates. The
+// caller supplies the confining ancestor's rect (e.g. `.chat-drawer`) for the
+// axis that must be confined and the viewport for the other axis.
+export type FlyoutBounds = {
+ left: number
+ right: number
+ top: number
+ bottom: number
+}
+
+export type ComputeFlyoutPositionArgs = {
+ anchorRect: FlyoutAnchorRect
+ flyoutRect: FlyoutSize
+ bounds: FlyoutBounds
+ placement: FlyoutPlacement
+ gap?: number
+ inset?: number
+}
+
+export type FlyoutPosition = {
+ left: number
+ top: number
+}
+
+const DEFAULT_GAP = 6
+const DEFAULT_INSET = 8
+
+function clamp(value: number, min: number, max: number): number {
+ // `max` can fall below `min` when the flyout is wider/taller than the bounds;
+ // keep the near edge pinned rather than letting the range invert.
+ return Math.min(Math.max(min, value), Math.max(min, max))
+}
+
+export function computeFlyoutPosition({
+ anchorRect,
+ flyoutRect,
+ bounds,
+ placement,
+ gap = DEFAULT_GAP,
+ inset = DEFAULT_INSET,
+}: ComputeFlyoutPositionArgs): FlyoutPosition {
+ // Inset the usable area so the flyout never touches the confining edge.
+ const area = {
+ left: bounds.left + inset,
+ right: bounds.right - inset,
+ top: bounds.top + inset,
+ bottom: bounds.bottom - inset,
+ }
+
+ if (placement === 'right-of') {
+ const preferredLeft = anchorRect.right + gap
+ // Flip to the anchor's left side when opening rightward would overflow.
+ const opensLeft = preferredLeft + flyoutRect.width > area.right
+ const candidateLeft = opensLeft ? anchorRect.left - flyoutRect.width - gap : preferredLeft
+ const left = clamp(candidateLeft, area.left, area.right - flyoutRect.width)
+ const top = clamp(anchorRect.top, area.top, area.bottom - flyoutRect.height)
+ return { left, top }
+ }
+
+ // 'below': drop under the anchor, flip above only when there is room above.
+ const preferredTop = anchorRect.bottom + gap
+ const opensAbove =
+ preferredTop + flyoutRect.height > area.bottom &&
+ anchorRect.top - gap - flyoutRect.height >= area.top
+ const candidateTop = opensAbove ? anchorRect.top - flyoutRect.height - gap : preferredTop
+ const top = clamp(candidateTop, area.top, area.bottom - flyoutRect.height)
+ const left = clamp(anchorRect.left, area.left, area.right - flyoutRect.width)
+ return { left, top }
+}
diff --git a/desktop-app/ui/src/styles.css b/desktop-app/ui/src/styles.css
index 1a07b2d5e..b3fba160a 100644
--- a/desktop-app/ui/src/styles.css
+++ b/desktop-app/ui/src/styles.css
@@ -4993,12 +4993,16 @@ h3 {
stroke-linejoin: round;
}
+/* Portaled to document.body and positioned by useFlyoutPosition with a fixed
+ rect clamped to the chat drawer (or the viewport in full screen). It sits above
+ the persistent sidebar flyout layer (dropdown + 1000), matching the
+ GfsResourceMenu portal. */
.agent-title-selector-menu {
- position: absolute;
- top: calc(100% + var(--space-1));
- left: 0;
- z-index: calc(var(--layer-dropdown) + 60);
+ position: fixed;
+ z-index: calc(var(--layer-dropdown) + 1100);
min-width: 240px;
+ max-height: calc(100vh - (var(--space-4) * 2));
+ overflow-y: auto;
border: 1px solid rgba(var(--edge-rgb), 0.32);
border-radius: var(--radius-md);
background: var(--panel);
@@ -5101,13 +5105,18 @@ h3 {
fill: currentColor;
}
-/* Sections sub-menu opens to the right of its row, vertically aligned. */
+/* Sections sub-menu: portaled to document.body and positioned by
+ useFlyoutPosition (right-of its row's dots button, flipping/clamping inside the
+ drawer or viewport). It must be portaled rather than nested because the menu is
+ a scroll container (max-height + overflow) and an overflow box can't host a
+ sub-menu that escapes it. Sits above the sidebar flyout layer, like the Gfs
+ resource-menu submenu. */
.agent-title-selector-submenu {
- position: absolute;
- left: calc(100% + var(--space-1));
- top: 0;
- z-index: calc(var(--layer-dropdown) + 61);
- min-width: 200px;
+ position: fixed;
+ z-index: calc(var(--layer-dropdown) + 1101);
+ width: min(200px, calc(100vw - (var(--space-4) * 2)));
+ max-height: calc(100vh - (var(--space-4) * 2));
+ overflow-y: auto;
border: 1px solid rgba(var(--edge-rgb), 0.32);
border-radius: var(--radius-md);
background: var(--panel);
@@ -13534,20 +13543,14 @@ pre {
padding-top: var(--space-1);
}
-/* Overlay confinement (spec §6). The native app view paints above ALL DOM, so
- any chat overlay that crosses the embed's rect is hidden behind it. The drawer
- is RIGHT-docked, so the embed sits to its LEFT. The composer reference menu is
- anchored at the composer's left edge and its submenu flies RIGHT
- (`left: calc(100% + …)`) — i.e. INTO the drawer, away from the embed — so it is
- already off the app rect. Pin that rightward direction inside the drawer so a
- future global LEFT flip can't leak the submenu over the embed and be occluded.
- (The spec's suggested LEFT flip is inverted for a right-docked drawer: leftward
- pushes the submenu over the embed, not off it. See report.) */
-.chat-drawer .composer-reference-submenu {
- left: calc(100% + var(--space-1));
- right: auto;
-}
-
+/* Overlay confinement. The native app view paints above ALL DOM, so any chat
+ overlay that crosses the embed's rect is hidden behind it. The drawer is
+ RIGHT-docked, so the embed sits to its LEFT. The composer reference SUBMENU
+ used to be in-flow here and had to pin a rightward direction to stay off the
+ embed; it is now portaled to document.body and confined to the drawer's rect
+ in JS (useFlyoutPosition), so no in-flow override is needed — a submenu clamped
+ inside the drawer is by construction off the embed. The primary panel is still
+ in flow and left-anchored at the composer's left edge. */
.chat-drawer .composer-reference-menu-panel {
left: 0;
right: auto;
@@ -13911,8 +13914,6 @@ pre {
.composer-reference-menu-panel,
.composer-reference-submenu {
- position: absolute;
- bottom: calc(100% + var(--space-1));
z-index: calc(var(--layer-dropdown) + 60);
min-width: 210px;
border: 1px solid rgba(var(--edge-rgb), 0.32);
@@ -13924,14 +13925,23 @@ pre {
gap: var(--space-0-5);
}
+/* The primary panel stays in flow (210px fits the 340px drawer). Only the
+ submenu is portaled. */
.composer-reference-menu-panel {
+ position: absolute;
+ bottom: calc(100% + var(--space-1));
left: 0;
}
+/* Portaled to document.body and positioned by useFlyoutPosition with a fixed
+ rect clamped to the chat drawer (or the viewport in full screen), so it carries
+ no in-flow anchor offsets. It sits above the persistent sidebar flyout layer
+ (dropdown + 1000), matching the GfsResourceMenu portal. */
.composer-reference-submenu {
- left: calc(100% + var(--space-1));
- bottom: calc(var(--space-1) + 34px);
- top: auto;
+ position: fixed;
+ z-index: calc(var(--layer-dropdown) + 1101);
+ width: min(210px, calc(100vw - (var(--space-4) * 2)));
+ min-width: min(210px, calc(100vw - (var(--space-4) * 2)));
max-height: min(420px, 65vh);
overflow-y: auto;
scrollbar-width: thin;
@@ -13950,38 +13960,6 @@ pre {
background: rgba(var(--edge-rgb), 0.6);
}
-.composer-reference-submenu--plugins {
- bottom: calc(var(--space-1) + 68px);
-}
-
-.composer-reference-submenu--connectors {
- bottom: calc(var(--space-1) + 34px);
-}
-
-.composer-reference-submenu--agent-files {
- bottom: var(--space-1);
-}
-
-.composer-inline .composer-reference-submenu {
- bottom: auto;
- top: var(--space-1);
-}
-
-.composer-inline .composer-reference-submenu--plugins {
- top: var(--space-1);
- bottom: auto;
-}
-
-.composer-inline .composer-reference-submenu--connectors {
- top: calc(var(--space-1) + 34px);
- bottom: auto;
-}
-
-.composer-inline .composer-reference-submenu--agent-files {
- top: calc(var(--space-1) + 68px);
- bottom: auto;
-}
-
.composer-inline .composer-reference-menu-panel {
top: calc(100% + var(--space-1));
bottom: auto;
diff --git a/scripts/style-rules/rules.mjs b/scripts/style-rules/rules.mjs
index 06b8c5607..13886cffe 100644
--- a/scripts/style-rules/rules.mjs
+++ b/scripts/style-rules/rules.mjs
@@ -94,6 +94,8 @@ const INLINE_STYLE_DYNAMIC_HINTS = [
'zIndex: visible.length',
// Data-driven stacked-bar segment width (context-window breakdown):
'--seg-width',
+ // Portaled flyout position computed from getBoundingClientRect (useFlyoutPosition).
+ 'FlyoutPosition',
]
function isCssTarget(file) {