Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): 修复小窗口下新建任务页模型次级面板悬停展开异常 (#1828)

ZhengyangZhang7e23dc0345a3
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 778e4b7f02..06d6ec4346 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -71,6 +71,7 @@
"@codemirror/state": "^6.6.0",
"@codemirror/view": "^6.41.1",
"@cindy/orca-workflow": "workspace:*",
+ "@floating-ui/react-dom": "^2.1.9",
"@fontsource-variable/inter": "^5.2.8",
"@fontsource-variable/jetbrains-mono": "^5.2.8",
"@google/model-viewer": "^4.0.0",
@@ -97,8 +98,11 @@
"@paralleldrive/cuid2": "^2.3.1",
"@parcel/watcher": "^2.5.6",
"@radix-ui/react-alert-dialog": "^1.1.15",
+ "@radix-ui/react-dismissable-layer": "^1.1.15",
"@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-dropdown-menu": "^2.1.16",
+ "@radix-ui/react-focus-guards": "^1.1.4",
+ "@radix-ui/react-focus-scope": "^1.1.12",
"@radix-ui/react-popover": "^1.1.15",
"@radix-ui/react-select": "^2.3.1",
"@radix-ui/react-slider": "^1.3.6",
diff --git a/apps/desktop/src/renderer/__tests__/modelSelectorProviderGroups.test.tsx b/apps/desktop/src/renderer/__tests__/modelSelectorProviderGroups.test.tsx
index 209a987fda..9bfeb1d599 100644
--- a/apps/desktop/src/renderer/__tests__/modelSelectorProviderGroups.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/modelSelectorProviderGroups.test.tsx
@@ -34,6 +34,38 @@ vi.mock('react-i18next', async (importOriginal) => ({
}),
}));
+const floatingUiMocks = vi.hoisted(() => {
+ const limitShiftResult = { fn: () => ({ x: 0, y: 0 }), options: {} };
+ return {
+ autoUpdate: vi.fn(() => () => {}),
+ flip: vi.fn((options: unknown) => ({ name: 'flip', options })),
+ limitShift: vi.fn(() => limitShiftResult),
+ limitShiftResult,
+ offset: vi.fn((options: unknown) => ({ name: 'offset', options })),
+ shift: vi.fn((options: unknown) => ({ name: 'shift', options })),
+ size: vi.fn((options: unknown) => ({ name: 'size', options })),
+ useFloating: vi.fn(),
+ };
+});
+
+vi.mock('@floating-ui/react-dom', () => ({
+ autoUpdate: floatingUiMocks.autoUpdate,
+ flip: floatingUiMocks.flip,
+ limitShift: floatingUiMocks.limitShift,
+ offset: floatingUiMocks.offset,
+ shift: floatingUiMocks.shift,
+ size: floatingUiMocks.size,
+ useFloating: (options: unknown) => {
+ floatingUiMocks.useFloating(options);
+ return {
+ refs: { setFloating: () => {} },
+ floatingStyles: { position: 'fixed', left: 120, top: 24 },
+ isPositioned: true,
+ placement: 'left',
+ };
+ },
+}));
+
vi.mock('@/components/ui/popover', async () => {
const React = await import('react');
const OpenContext = React.createContext<{
@@ -66,12 +98,37 @@ vi.mock('@/components/ui/popover', async () => {
});
},
PopoverAnchor: ({ children }: { children: React.ReactNode }) => children,
- PopoverContent: ({ children }: { children: React.ReactNode }) => {
+ PopoverContent: React.forwardRef<
+ HTMLDivElement,
+ {
+ children: React.ReactNode;
+ className?: string;
+ collisionPadding?:
+ | number
+ | {
+ top?: number;
+ right?: number;
+ bottom?: number;
+ left?: number;
+ };
+ }
+ >(({ children, className, collisionPadding }, ref) => {
const state = React.useContext(OpenContext);
+ const collisionPaddingTop =
+ typeof collisionPadding === 'number' ? collisionPadding : collisionPadding?.top;
return state.open
- ? React.createElement('div', { 'data-testid': 'model-options-popover' }, children)
+ ? React.createElement(
+ 'div',
+ {
+ ref,
+ 'data-testid': 'model-options-popover',
+ 'data-collision-padding-top': collisionPaddingTop,
+ className,
+ },
+ children,
+ )
: null;
- },
+ }),
};
});
@@ -191,6 +248,13 @@ const requestProviderModelsAutoRefresh = vi.fn(async () => ({ ok: true as const
beforeEach(() => {
requestProviderModelsAutoRefresh.mockClear();
+ floatingUiMocks.autoUpdate.mockClear();
+ floatingUiMocks.flip.mockClear();
+ floatingUiMocks.limitShift.mockClear();
+ floatingUiMocks.offset.mockClear();
+ floatingUiMocks.shift.mockClear();
+ floatingUiMocks.size.mockClear();
+ floatingUiMocks.useFloating.mockClear();
providersRef.providers = providersRef.DEFAULT_PROVIDERS;
(window as unknown as { electronAPI: unknown }).electronAPI = {
maker: { requestProviderModelsAutoRefresh },
@@ -218,6 +282,15 @@ async function openDropdown(): Promise<void> {
});
}
+async function hoverModelRowWithIntent(row: HTMLElement): Promise<void> {
+ await act(async () => {
+ // MorphPopover requires a real pointer delta before revealing row options. Model that
+ // contract explicitly instead of depending on jsdom's synthetic `isTrusted` value.
+ fireEvent.pointerMove(row, { screenX: 0, screenY: 0 });
+ fireEvent.pointerMove(row, { screenX: 8, screenY: 0 });
+ });
+}
+
describe('ModelSelector provider groups', () => {
it('renders a group heading for each provider', async () => {
renderSelector();
@@ -242,6 +315,157 @@ describe('ModelSelector provider groups', () => {
expect(within(dashscopeGroup).queryByText('Opus 4.8')).toBeNull();
});
+ it('keeps the create-agent secondary panel at the original left/center position with layout coordinates', async () => {
+ renderSelector({ visualVariant: 'create-agent', useMorphPopover: true });
+ await openDropdown();
+
+ const modelList = screen.getByRole('listbox', { name: 'Model list' });
+ const row = within(modelList).getByRole('option', { name: /Opus 4\.8/ });
+ await hoverModelRowWithIntent(row);
+
+ const secondaryPanel = await screen.findByTestId('model-options-floating-panel');
+ const positioner = secondaryPanel.closest<HTMLElement>('[data-radix-popper-content-wrapper]');
+ expect(positioner).not.toBeNull();
+ expect(positioner?.parentElement).toBe(document.body);
+ expect(positioner?.style.position).toBe('fixed');
+ expect(positioner?.style.left).toBe('120px');
+ expect(positioner?.style.top).toBe('24px');
+ expect(positioner?.style.transform).toBe('');
+ expect(
+ (positioner?.style as CSSStyleDeclaration & { WebkitAppRegion: string }).WebkitAppRegion,
+ ).toBe('no-drag');
+ expect(secondaryPanel.className).toContain('overflow-hidden');
+ expect(secondaryPanel.className).not.toContain('max-h-[');
+ expect(secondaryPanel.className).not.toContain('overflow-y-auto');
+
+ const floatingOptions = floatingUiMocks.useFloating.mock.calls.at(-1)?.[0] as {
+ strategy: string;
+ placement: string;
+ transform: boolean;
+ open: boolean;
+ elements: { reference: HTMLElement };
+ whileElementsMounted: (
+ reference: HTMLElement,
+ floating: HTMLElement,
+ update: () => void,
+ ) => () => void;
+ };
+ expect(floatingOptions).toMatchObject({
+ strategy: 'fixed',
+ placement: 'left',
+ transform: false,
+ open: true,
+ });
+ expect(floatingOptions.elements.reference).toBe(row);
+ const floatingElement = document.createElement('div');
+ const cleanup = floatingOptions.whileElementsMounted(row, floatingElement, vi.fn());
+ expect(floatingUiMocks.autoUpdate).toHaveBeenCalledWith(
+ row,
+ floatingElement,
+ expect.any(Function),
+ { animationFrame: false },
+ );
+ cleanup();
+
+ expect(floatingUiMocks.offset).toHaveBeenLastCalledWith({
+ mainAxis: 8,
+ alignmentAxis: 0,
+ });
+ expect(floatingUiMocks.shift).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ mainAxis: true,
+ crossAxis: false,
+ limiter: floatingUiMocks.limitShiftResult,
+ padding: 8,
+ boundary: [],
+ altBoundary: false,
+ }),
+ );
+ expect(floatingUiMocks.flip).toHaveBeenLastCalledWith({
+ padding: 8,
+ boundary: [],
+ altBoundary: false,
+ });
+ const sizeOptions = floatingUiMocks.size.mock.calls.at(-1)?.[0] as {
+ apply: (args: { elements: { floating: HTMLElement }; availableHeight: number }) => void;
+ };
+ sizeOptions.apply({ elements: { floating: floatingElement }, availableHeight: 180 });
+ expect(floatingElement.style.getPropertyValue('--radix-popover-content-available-height')).toBe(
+ '180px',
+ );
+
+ const panelOptions = within(secondaryPanel).getAllByRole('option');
+ const firstPanelOption = panelOptions[0];
+ const lastPanelOption = panelOptions.at(-1);
+ expect(lastPanelOption).toBeDefined();
+ lastPanelOption?.focus();
+ fireEvent.keyDown(lastPanelOption as HTMLElement, { key: 'Tab' });
+ expect(document.activeElement).toBe(firstPanelOption);
+ fireEvent.keyDown(firstPanelOption, { key: 'Tab', shiftKey: true });
+ expect(document.activeElement).toBe(lastPanelOption);
+
+ fireEvent.keyDown(row, { key: 'Escape' });
+ expect(screen.queryByTestId('model-options-floating-panel')).toBeNull();
+ expect(screen.getByRole('listbox', { name: 'Model list' })).toBeTruthy();
+ });
+
+ it('refreshes the create-agent floating anchor after search remounts the active model row', async () => {
+ renderSelector({ visualVariant: 'create-agent', useMorphPopover: true });
+ await openDropdown();
+
+ const modelList = screen.getByRole('listbox', { name: 'Model list' });
+ const originalRow = within(modelList).getByRole('option', { name: /Opus 4\.8/ });
+ await hoverModelRowWithIntent(originalRow);
+ await screen.findByTestId('model-options-floating-panel');
+
+ const originalFloatingOptions = floatingUiMocks.useFloating.mock.calls.at(-1)?.[0] as {
+ elements: { reference: HTMLElement };
+ };
+ expect(originalFloatingOptions.elements.reference).toBe(originalRow);
+
+ const searchInput = screen.getByRole('textbox');
+ await act(async () => {
+ fireEvent.change(searchInput, { target: { value: 'qwen' } });
+ });
+ expect(originalRow.isConnected).toBe(false);
+ expect(screen.queryByTestId('model-options-floating-panel')).toBeNull();
+ const floatingCallCountAfterFilter = floatingUiMocks.useFloating.mock.calls.length;
+
+ await act(async () => {
+ fireEvent.change(searchInput, { target: { value: '' } });
+ });
+ const restoredRow = within(modelList).getByRole('option', { name: /Opus 4\.8/ });
+ expect(restoredRow).not.toBe(originalRow);
+ expect(restoredRow.getAttribute('data-model-options-active')).toBeNull();
+ expect(screen.queryByTestId('model-options-floating-panel')).toBeNull();
+ expect(floatingUiMocks.useFloating).toHaveBeenCalledTimes(floatingCallCountAfterFilter);
+
+ await hoverModelRowWithIntent(restoredRow);
+ await screen.findByTestId('model-options-floating-panel');
+
+ const restoredFloatingOptions = floatingUiMocks.useFloating.mock.calls.at(-1)?.[0] as {
+ elements: { reference: HTMLElement };
+ };
+ expect(restoredFloatingOptions.elements.reference).toBe(restoredRow);
+ expect(restoredFloatingOptions.elements.reference.isConnected).toBe(true);
+ });
+
+ it('keeps the existing Radix secondary popover outside the create-agent variant', async () => {
+ renderSelector();
+ await openDropdown();
+
+ const popover = screen.getByTestId('model-options-popover');
+ const row = within(popover).getByRole('option', { name: /Opus 4\.8/ });
+ await act(async () => {
+ fireEvent.pointerEnter(row);
+ });
+
+ const details = screen.getByRole('group', { name: /Opus 4\.8/ });
+ const secondaryPanel = details.closest('[data-testid="model-options-popover"]');
+ expect(secondaryPanel?.getAttribute('data-collision-padding-top')).toBe('8');
+ expect(screen.queryByTestId('model-options-floating-panel')).toBeNull();
+ });
+
it('reselects the connected fallback source when the stored source is disconnected', async () => {
const modelId = 'claude-fable-5';
const model = {
diff --git a/apps/desktop/src/renderer/__tests__/morphPopover.test.tsx b/apps/desktop/src/renderer/__tests__/morphPopover.test.tsx
index 36332038df..4b2f7603ba 100644
--- a/apps/desktop/src/renderer/__tests__/morphPopover.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/morphPopover.test.tsx
@@ -70,6 +70,16 @@ afterEach(() => {
});
describe('MorphPopover interaction contract', () => {
+ it('keeps the portaled panel outside Electron window drag regions', async () => {
+ render(<Harness />);
+ fireEvent.click(screen.getByRole('button', { name: 'Toggle' }));
+ const panel = await screen.findByRole('group', { name: 'Morph panel' });
+
+ expect((panel.style as CSSStyleDeclaration & { WebkitAppRegion: string }).WebkitAppRegion).toBe(
+ 'no-drag',
+ );
+ });
+
it('打开聚焦首个可交互项;Esc 关闭并把焦点归还 trigger', async () => {
render(<Harness />);
const trigger = screen.getByRole('button', { name: 'Toggle' });
@@ -168,9 +178,7 @@ describe('MorphPopover interaction contract', () => {
fireEvent.pointerDown(action);
fireEvent.click(action);
- await waitFor(() =>
- expect(screen.queryByRole('button', { name: 'Select action' })).toBeNull(),
- );
+ await waitFor(() => expect(screen.queryByRole('button', { name: 'Select action' })).toBeNull());
expect(document.activeElement).not.toBe(trigger);
});
@@ -215,9 +223,7 @@ describe('MorphPopover interaction contract', () => {
action.focus();
fireEvent.click(action);
- await waitFor(() =>
- expect(screen.queryByRole('button', { name: 'Open dialog' })).toBeNull(),
- );
+ await waitFor(() => expect(screen.queryByRole('button', { name: 'Open dialog' })).toBeNull());
expect(document.activeElement).toBe(screen.getByRole('button', { name: 'Dialog field' }));
});
diff --git a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx
index adbe36d309..5aa3f1e7ec 100644
--- a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx
@@ -7,7 +7,21 @@ import {
type CSSProperties,
type PointerEvent as ReactPointerEvent,
type ReactNode,
+ type Ref,
} from 'react';
+import { createPortal } from 'react-dom';
+import {
+ autoUpdate,
+ flip,
+ limitShift,
+ offset,
+ shift,
+ size,
+ useFloating,
+} from '@floating-ui/react-dom';
+import { DismissableLayer } from '@radix-ui/react-dismissable-layer';
+import { useFocusGuards } from '@radix-ui/react-focus-guards';
+import { FocusScope } from '@radix-ui/react-focus-scope';
import {
Check,
ChevronDown,
@@ -25,6 +39,7 @@ import { useTranslation } from 'react-i18next';
import { cn } from '@/lib/utils';
import { flashScrollbar } from '@/lib/scrollbarAutoHide';
import { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
+import { WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';
import { MorphPopover } from '@/components/ui/morph-popover';
import { AnthropicMark } from '@/components/icons/AnthropicMark';
import { OpenAIMark } from '@/components/icons/OpenAIMark';
@@ -139,6 +154,8 @@ const PROVIDER_TITLE_KEY: Record<string, string> = {
// 配置面板锚在主菜单内缩 8px 的模型行上;补偿这段内缩,让两块面板贴边但不重叠。
const MODEL_OPTIONS_SIDE_OFFSET = 8;
+const MODEL_OPTIONS_COLLISION_PADDING = 8;
+const MODEL_OPTIONS_COLLISION_BOUNDARY: Element[] = [];
const MODEL_LIST_DEFAULT_MAX_HEIGHT_PX = 300;
// 一级菜单只保留单行模型信息与必要标签:20px 内容 + 16px 纵向 padding。
const MODEL_LIST_ROW_HEIGHT_PX = 36;
@@ -153,6 +170,124 @@ export function modelListMaxHeightForRows(maxVisibleRows?: number): number | und
);
}
+interface ModelOptionsFloatingPanelProps {
+ anchor: HTMLElement;
+ panelRef: Ref<HTMLDivElement>;
+ className?: string;
+ onCancelClose: () => void;
+ onScheduleClose: () => void;
+ onDismiss: () => void;
+ children: ReactNode;
+}
+
+/**
+ * 新建任务页的模型次级面板仍复刻 Radix 的 left/center 几何与 viewport 碰撞规则,
+ * 但定位层改用真实 left/top。Electron 的 app-region 只按布局矩形命中;若沿用
+ * Popper 的 translate 定位,视觉面板与 no-drag 矩形会错位,覆盖标题栏的区域就会吞 pointer。
+ */
+function ModelOptionsFloatingPanel({
+ anchor,
+ panelRef,
+ className,
+ onCancelClose,
+ onScheduleClose,
+ onDismiss,
+ children,
+}: ModelOptionsFloatingPanelProps) {
+ useFocusGuards();
+ const { refs, floatingStyles, isPositioned, placement } = useFloating<HTMLElement>({
+ strategy: 'fixed',
+ placement: 'left',
+ transform: false,
+ open: true,
+ elements: { reference: anchor },
+ whileElementsMounted: (reference, floating, update) =>
+ autoUpdate(reference, floating, update, { animationFrame: false }),
+ middleware: [
+ offset({ mainAxis: MODEL_OPTIONS_SIDE_OFFSET, alignmentAxis: 0 }),
+ shift({
+ mainAxis: true,
+ crossAxis: false,
+ limiter: limitShift(),
+ padding: MODEL_OPTIONS_COLLISION_PADDING,
+ boundary: MODEL_OPTIONS_COLLISION_BOUNDARY,
+ altBoundary: false,
+ }),
+ flip({
+ padding: MODEL_OPTIONS_COLLISION_PADDING,
+ boundary: MODEL_OPTIONS_COLLISION_BOUNDARY,
+ altBoundary: false,
+ }),
+ size({
+ padding: MODEL_OPTIONS_COLLISION_PADDING,
+ boundary: MODEL_OPTIONS_COLLISION_BOUNDARY,
+ altBoundary: false,
+ apply: ({ elements, availableHeight }) => {
+ elements.floating.style.setProperty(
+ '--radix-popover-content-available-height',
+ `${availableHeight}px`,
+ );
+ },
+ }),
+ ],
+ });
+
+ const placedSide = placement.startsWith('left') ? 'left' : 'right';
+
+ return createPortal(
+ <div
+ ref={refs.setFloating}
+ data-radix-popper-content-wrapper=""
+ className="z-50 w-[248px]"
+ style={{
+ ...floatingStyles,
+ visibility: isPositioned ? undefined : 'hidden',
+ pointerEvents: isPositioned ? undefined : 'none',
+ ...WINDOW_NO_DRAG_STYLE,
+ }}
+ >
+ <FocusScope
+ asChild
+ loop
+ trapped={false}
+ onMountAutoFocus={(event) => event.preventDefault()}
+ onUnmountAutoFocus={(event) => event.preventDefault()}
+ >
+ <DismissableLayer
+ asChild
+ disableOutsidePointerEvents={false}
+ deferPointerDownOutside
+ onDismiss={onDismiss}
+ >
+ <div
+ ref={panelRef}
+ role="dialog"
+ data-state="open"
+ data-side={placedSide}
+ data-testid="model-options-floating-panel"
+ onPointerEnter={onCancelClose}
+ onPointerLeave={onScheduleClose}
+ onFocusCapture={onCancelClose}
+ onBlurCapture={(event) => {
+ if (event.currentTarget.contains(event.relatedTarget as Node | null)) return;
+ onScheduleClose();
+ }}
+ className={cn(
+ 'w-full overflow-hidden rounded-[12px] p-2 shadow-[var(--shadow-menu)] outline-none duration-100',
+ 'animate-float-in border border-[var(--model-dropdown-border)] bg-[var(--model-dropdown-bg)]',
+ className,
+ )}
+ style={{ transformOrigin: placedSide === 'left' ? 'right center' : 'left center' }}
+ >
+ {children}
+ </div>
+ </DismissableLayer>
+ </FocusScope>
+ </div>,
+ document.body,
+ );
+}
+
function providerDisplayName(p: ProviderView, t: (key: string) => string): string {
const key = PROVIDER_TITLE_KEY[p.id];
return key ? t(key) : p.name;
@@ -570,6 +705,8 @@ interface ModelSelectorContentProps {
selectedRowClickOpensConfiguration?: boolean;
/** Morph 原位展开时,要求真实 pointer move 后才展示行级配置,避免静止光标误触。 */
pointerRevealRequiresIntent?: boolean;
+ /** 次级面板用真实 left/top 定位,保持原位置并让 Electron no-drag 几何与视觉一致。 */
+ optionsPanelUsesLayoutPositioning?: boolean;
/**
* field 形态:面板宽度绑定 trigger(DESIGN.md §4「Panel width must bind to the
* trigger width」),主菜单列由固定 320 改为撑满外层 PopoverContent。
@@ -689,6 +826,7 @@ function ModelSelectorContentView({
reselectEmitsChange = false,
selectedRowClickOpensConfiguration = false,
pointerRevealRequiresIntent = false,
+ optionsPanelUsesLayoutPositioning = false,
fluidWidth = false,
agentSwitch,
discoveringModels = false,
@@ -804,6 +942,7 @@ function ModelSelectorContentView({
const [editing, setEditing] = useState<{ providerId: string | null; modelId: string } | null>(
null,
);
+ const [optionsAnchor, setOptionsAnchor] = useState<HTMLElement | null>(null);
// 非选中模型的 effort/fast 改动写进全局预设,不反映在 live props —— 用 tick 触发重渲染读新值。
const [editTick, setEditTick] = useState(0);
const bump = () => setEditTick((n) => n + 1);
@@ -821,6 +960,11 @@ function ModelSelectorContentView({
const suppressScrollDismissRef = useRef(false);
const closeOptionsTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const closeOptionsPanel = useCallback(() => {
+ setEditing(null);
+ setOptionsAnchor(null);
+ }, []);
+
// ── pointer-reveal 武装门 ──
// 面板(MorphPopover)在光标正下方原位展开:行滑到**静止**光标底下会触发
// pointerenter,行配置浮层闪现一下(2026-07-22 用户反馈)。静止光标不代表
@@ -857,7 +1001,7 @@ function ModelSelectorContentView({
// 80ms 足够接住浮层,又不会产生「鼠标走了选项还赖着」的视觉残留。
closeOptionsTimerRef.current = setTimeout(() => {
closeOptionsTimerRef.current = null;
- setEditing(null);
+ closeOptionsPanel();
}, 80);
};
@@ -870,11 +1014,11 @@ function ModelSelectorContentView({
const onAnyScroll = (event: Event) => {
if (configPanelRef.current?.contains(event.target as Node)) return;
cancelOptionsClose();
- setEditing(null);
+ closeOptionsPanel();
};
document.addEventListener('scroll', onAnyScroll, true);
return () => document.removeEventListener('scroll', onAnyScroll, true);
- }, [editing]);
+ }, [closeOptionsPanel, editing]);
useEffect(
() => () => {
@@ -889,8 +1033,8 @@ function ModelSelectorContentView({
clearTimeout(closeOptionsTimerRef.current);
closeOptionsTimerRef.current = null;
}
- setEditing(null);
- }, [interactionDisabled]);
+ closeOptionsPanel();
+ }, [closeOptionsPanel, interactionDisabled]);
// 模型清单来源:本机会话从 live providers 派生(builtin + 自定义合集);device-link 远程会话
// 必须列**被控端**模型(cc/codex.capabilities.availableModels,deviceId 作用域),不读控制端本地
@@ -1322,6 +1466,11 @@ function ModelSelectorContentView({
effortOverride?: Effort,
) => {
if (interactionDisabled) return;
+ const dismissAfterSelection = () => {
+ if (!dismiss) return;
+ closeOptionsPanel();
+ onDismiss?.();
+ };
// 浏览目标引擎态:选中模型 = 确认切换引擎(两步式的第二步),走切换事务。
// providerId 一起带上:切换后 sessions.provider_id 直接落用户选的来源,
// trigger 来源 icon / 路由立即正确(null = flat 退化行,交给默认路由)。
@@ -1331,7 +1480,7 @@ function ModelSelectorContentView({
id,
providerId,
);
- if (dismiss) onDismiss?.();
+ dismissAfterSelection();
return;
}
const selectedModel = sections
@@ -1350,23 +1499,15 @@ function ModelSelectorContentView({
!!selectedModel &&
(selectedModel.efforts.length > 0 || fastEditable(providerId, selectedModel));
const opensConfiguration =
- selectedRowClickOpensConfiguration &&
- configurationEnabled &&
- selectedModelHasConfiguration;
+ selectedRowClickOpensConfiguration && configurationEnabled && selectedModelHasConfiguration;
// A selected row can be the effective fallback for a stale explicit
// provider. Repair that route before opening its configuration, but do
// not persist the row's derived/default effort just by opening the card.
if (reselectEmitsChange) {
if (sections && providerId) {
- const needsProviderRepair =
- !!currentProviderId &&
- currentProviderId !== providerId;
+ const needsProviderRepair = !!currentProviderId && currentProviderId !== providerId;
if (!opensConfiguration || needsProviderRepair) {
- onProviderChange?.(
- providerId,
- id,
- opensConfiguration ? undefined : reconciledEffort,
- );
+ onProviderChange?.(providerId, id, opensConfiguration ? undefined : reconciledEffort);
}
} else if (!opensConfiguration) {
onModelChange(id);
@@ -1380,7 +1521,7 @@ function ModelSelectorContentView({
// reselectEmitsChange:调用方的「当前值」可能是**解析出来的继承值**而非已持久化的
// 显式值(IM 工作目录偏好),这时点当前行的语义是「把继承值钉成显式值」,必须照常回调,
// 否则用户点了没反应、之后上游默认一变这条偏好就被静默改掉。
- if (dismiss) onDismiss?.();
+ dismissAfterSelection();
return;
}
if (sections && providerId) {
@@ -1389,7 +1530,7 @@ function ModelSelectorContentView({
} else {
onModelChange(id);
}
- if (dismiss) onDismiss?.();
+ dismissAfterSelection();
};
// ── hover / focus 浮层目标 ───────────────────────────────────────────────
const editingModel: RowModel | null = useMemo(() => {
@@ -1401,6 +1542,18 @@ function ModelSelectorContentView({
return flatModels?.find((m) => m.id === editing.modelId) ?? null;
}, [editing, sections, flatModels]);
+ // 搜索过滤会卸载当前模型行。create-agent 的自定位浮层不能继续保留 detached DOM
+ // 作为锚点;否则清空搜索后 configPanel 恢复时会先在旧锚点上重挂载。
+ useEffect(() => {
+ if (!optionsPanelUsesLayoutPositioning || !editing) return;
+ if (!editingModel || (optionsAnchor !== null && !optionsAnchor.isConnected)) {
+ closeOptionsPanel();
+ }
+ }, [closeOptionsPanel, editing, editingModel, optionsAnchor, optionsPanelUsesLayoutPositioning]);
+
+ // effect 会清理失效状态;渲染门再保证清理提交前也绝不把 detached 锚点交给 Floating UI。
+ const connectedOptionsAnchor = optionsAnchor?.isConnected ? optionsAnchor : null;
+
// 浏览目标引擎态恒非 active(与 isSelectedRow 同口径):目标列表里可能出现与当前
// 会话同 id 同来源的行(网关同一模型双引擎都供),悬浮面板里的改动绝不能写进
// 当前会话的实时 effort / Fast,只能落目标引擎的全局预设。
@@ -1511,7 +1664,6 @@ function ModelSelectorContentView({
// 这样浮层会像 Hermes 的 Radix submenu 一样贴着当前行移动,切行不触发主菜单重排。
const configPanel = editingModel ? (
<div
- ref={configPanelRef}
role="group"
aria-label={`${editingModel.displayName} ${t('newChat.modelSelector.options')}`}
className="flex flex-col gap-0.5"
@@ -1723,9 +1875,18 @@ function ModelSelectorContentView({
const hasOptions = !disabled;
const isEditingThis =
!!editing && editing.modelId === model.id && editing.providerId === providerId;
- const revealOptions = () => {
+ const revealOptions = (anchor: HTMLDivElement) => {
cancelOptionsClose();
- setEditing(hasOptions ? { providerId, modelId: model.id } : null);
+ if (!hasOptions) {
+ closeOptionsPanel();
+ return;
+ }
+ setOptionsAnchor((current) => (current === anchor ? current : anchor));
+ setEditing((current) =>
+ current?.providerId === providerId && current.modelId === model.id
+ ? current
+ : { providerId, modelId: model.id },
+ );
};
// pointerenter 触发的 reveal 必须等光标真实移动过才武装:面板(MorphPopover)在
// 光标正下方原位展开时,行会滑到**静止**光标底下触发 pointerenter,行配置浮层
@@ -1741,15 +1902,14 @@ function ModelSelectorContentView({
event.nativeEvent.isTrusted
)
return;
- if (!isEditingThis) revealOptions();
- else cancelOptionsClose();
+ revealOptions(event.currentTarget);
};
return (
<Popover
key={`${providerId ?? ''}::${model.id}`}
open={isEditingThis}
onOpenChange={(open) => {
- if (!open && isEditingThis) setEditing(null);
+ if (!open && isEditingThis) closeOptionsPanel();
}}
>
<PopoverAnchor asChild>
@@ -1764,7 +1924,7 @@ function ModelSelectorContentView({
onPointerEnter={revealOptionsByPointer}
onPointerMove={revealOptionsByPointer}
onPointerLeave={scheduleOptionsClose}
- onFocus={revealOptions}
+ onFocus={(event) => revealOptions(event.currentTarget)}
onBlur={(event) => {
if (configPanelRef.current?.contains(event.relatedTarget as Node | null)) return;
scheduleOptionsClose();
@@ -1777,7 +1937,7 @@ function ModelSelectorContentView({
if (ev.target !== ev.currentTarget || disabled) return;
if (ev.key === 'ArrowLeft' && hasOptions) {
ev.preventDefault();
- revealOptions();
+ revealOptions(ev.currentTarget);
requestAnimationFrame(() => {
configPanelRef.current
?.querySelector<HTMLElement>('button:not(:disabled)')
@@ -1859,12 +2019,13 @@ function ModelSelectorContentView({
)}
</div>
</PopoverAnchor>
- {isEditingThis && configPanel && (
+ {!optionsPanelUsesLayoutPositioning && isEditingThis && configPanel && (
<PopoverContent
+ ref={configPanelRef}
side="left"
align="center"
sideOffset={MODEL_OPTIONS_SIDE_OFFSET}
- collisionPadding={8}
+ collisionPadding={MODEL_OPTIONS_COLLISION_PADDING}
onOpenAutoFocus={(event) => event.preventDefault()}
onCloseAutoFocus={(event) => event.preventDefault()}
onPointerEnter={cancelOptionsClose}
@@ -2054,7 +2215,7 @@ function ModelSelectorContentView({
return;
}
// 滚动不派发 pointerleave,行级配置浮层会跟着滚出视口的锚点行跑到菜单外 → 一滚动就收起。
- if (editing) setEditing(null);
+ if (editing) closeOptionsPanel();
}}
>
{!hasAnyModel ? (
@@ -2130,6 +2291,19 @@ function ModelSelectorContentView({
</button>
</>
)}
+
+ {optionsPanelUsesLayoutPositioning && connectedOptionsAnchor && configPanel && (
+ <ModelOptionsFloatingPanel
+ anchor={connectedOptionsAnchor}
+ panelRef={configPanelRef}
+ className={overlayContentClassName}
+ onCancelClose={cancelOptionsClose}
+ onScheduleClose={scheduleOptionsClose}
+ onDismiss={closeOptionsPanel}
+ >
+ {configPanel}
+ </ModelOptionsFloatingPanel>
+ )}
</div>
);
@@ -2750,6 +2924,7 @@ export function ModelSelector({
reselectEmitsChange={reselectEmitsChange}
selectedRowClickOpensConfiguration={selectedRowClickOpensConfiguration}
pointerRevealRequiresIntent={morphEnabled}
+ optionsPanelUsesLayoutPositioning={isCreateAgentVariant}
fluidWidth={isFieldTrigger}
agentSwitch={contentAgentSwitch}
discoveringModels={showDiscoveryPending && discovery.pending}
diff --git a/apps/desktop/src/renderer/components/ui/morph-popover.tsx b/apps/desktop/src/renderer/components/ui/morph-popover.tsx
index 72449ee8cd..80be3879fe 100644
--- a/apps/desktop/src/renderer/components/ui/morph-popover.tsx
+++ b/apps/desktop/src/renderer/components/ui/morph-popover.tsx
@@ -8,6 +8,7 @@ import {
} from 'react';
import { createPortal } from 'react-dom';
+import { WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';
import { cn } from '@/lib/utils';
/**
@@ -492,8 +493,10 @@ export function MorphPopover({
// data-[state=closed]:pointer-events-none —— 收合动画期间面板已透明但仍以
// position:fixed 覆盖视口,不加会拦住底下点击(选完项 / Esc 后那 300ms)。
className="group fixed z-50 overflow-hidden border outline-none data-[state=closed]:pointer-events-none"
- // 初始几何由 useLayoutEffect 直写;这里只兜首帧不可见位置
- style={{ left: -9999, bottom: -9999 }}
+ // 初始几何由 useLayoutEffect 直写;这里只兜首帧不可见位置。
+ // Electron 的 app-region 按视口几何命中;矮窗口里面板会顶到标题栏,
+ // 必须显式 no-drag 才能保留搜索框和首行模型的 pointer / focus 交互。
+ style={{ left: -9999, bottom: -9999, ...WINDOW_NO_DRAG_STYLE }}
>
{/* 面板内容: 随生长淡入(50ms 延迟 + 5px 浮入);形变期禁滚(防滚动条
闪现挤压行宽),settle 后由 JS 切回自滚 */}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index e09ea56532..7259dbab2c 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -184,6 +184,9 @@ importers:
'@codemirror/view':
specifier: ^6.41.1
version: 6.43.6
+ '@floating-ui/react-dom':
+ specifier: ^2.1.9
'@fontsource-variable/inter':
specifier: ^5.2.8
version: 5.2.8
@@ -211,9 +214,18 @@ importers:
'@radix-ui/react-dialog':
specifier: ^1.1.15
+ '@radix-ui/react-dismissable-layer':
+ specifier: ^1.1.15
'@radix-ui/react-dropdown-menu':
specifier: ^2.1.16
+ '@radix-ui/react-focus-guards':
+ specifier: ^1.1.4
+ version: 1.1.4(@types/[email protected])([email protected])
+ '@radix-ui/react-focus-scope':
+ specifier: ^1.1.12
'@radix-ui/react-popover':
specifier: ^1.1.15