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。

refactor(desktop): 将五个手写模态弹窗迁移至 Radix (#5491)

Kirozeng53ee2f7d3903
diff --git a/apps/desktop/src/renderer/__tests__/addProviderWizardOpenAiAuth.test.tsx b/apps/desktop/src/renderer/__tests__/addProviderWizardOpenAiAuth.test.tsx
index f82b0ab598..9f05c920b3 100644
--- a/apps/desktop/src/renderer/__tests__/addProviderWizardOpenAiAuth.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/addProviderWizardOpenAiAuth.test.tsx
@@ -9,7 +9,9 @@
*/
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
-import React from 'react';
+import React, { useState } from 'react';
+import userEvent from '@testing-library/user-event';
+import * as Dialog from '@radix-ui/react-dialog';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { ProviderView } from '@cindy/model-providers';
@@ -283,7 +285,8 @@ describe('AddProviderWizard — OpenAI 授权边界', () => {
fireEvent.click(screen.getByText('settings.providers.openai.addIndependentAccount'));
await waitFor(() => expect(providerOAuthLogin).toHaveBeenCalledTimes(1));
const oldId = providerOAuthLogin.mock.calls[0][0];
- fireEvent.click(screen.getByText('settings.providers.wizard.cancel'));
+ fireEvent.click(screen.getByText('settings.providers.wizard.back'));
+ fireEvent.click(screen.getByText('OpenAI'));
fireEvent.click(screen.getByText('settings.providers.openai.addIndependentAccount'));
await waitFor(() => expect(providerOAuthLogin).toHaveBeenCalledTimes(2));
const [newId, { ownerId }] = providerOAuthLogin.mock.calls[1];
@@ -295,7 +298,7 @@ describe('AddProviderWizard — OpenAI 授权边界', () => {
expect(screen.getByText('settings.providers.wizard.cancel')).toBeTruthy();
expect(onDone).not.toHaveBeenCalled();
await act(async () => { finishNew({ ok: true }); });
- expect(onDone).toHaveBeenCalledWith(newId);
+ await waitFor(() => expect(onDone).toHaveBeenCalledWith(newId));
expect(onDone).toHaveBeenCalledTimes(1);
});
it.each(['xai'])('cancels only the pending independent %s authorization', async id => {
@@ -523,7 +526,7 @@ describe('AddProviderWizard — OpenAI 授权边界', () => {
});
describe('AddProviderWizard — 关闭途径(取消 / Esc)', () => {
- it('按 Esc 关闭向导', () => {
+ it('按 Esc 关闭向导', async () => {
const onClose = vi.fn();
render(
<AddProviderWizard
@@ -533,11 +536,11 @@ describe('AddProviderWizard — 关闭途径(取消 / Esc)', () => {
onDone={vi.fn()}
/>,
);
- fireEvent.keyDown(window, { key: 'Escape' });
- expect(onClose).toHaveBeenCalledTimes(1);
+ fireEvent.keyDown(document.activeElement!, { key: 'Escape' });
+ await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1));
});
- it('输入法组合期间按 Esc 不关闭向导(取消候选词,不是关闭命令)', () => {
+ it('输入法组合期间按 Esc 不关闭向导(取消候选词,不是关闭命令)', async () => {
const onClose = vi.fn();
render(
<AddProviderWizard
@@ -547,17 +550,17 @@ describe('AddProviderWizard — 关闭途径(取消 / Esc)', () => {
onDone={vi.fn()}
/>,
);
- fireEvent.keyDown(window, { key: 'Escape', isComposing: true });
+ fireEvent.keyDown(document.activeElement!, { key: 'Escape', isComposing: true });
expect(onClose).not.toHaveBeenCalled();
- fireEvent.keyDown(window, { key: 'Escape', keyCode: 229 });
+ fireEvent.keyDown(document.activeElement!, { key: 'Escape', keyCode: 229 });
expect(onClose).not.toHaveBeenCalled();
- fireEvent.keyDown(window, { key: 'Escape' });
- expect(onClose).toHaveBeenCalledTimes(1);
+ fireEvent.keyDown(document.activeElement!, { key: 'Escape' });
+ await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1));
});
- it('点击遮罩或弹窗内部不关闭;点击取消关闭', () => {
+ it('点击遮罩或弹窗内部不关闭;点击取消关闭', async () => {
const onClose = vi.fn();
- const { container } = render(
+ render(
<AddProviderWizard
providers={[OPENAI_PROVIDER]}
onOpenCustomForm={vi.fn()}
@@ -567,7 +570,7 @@ describe('AddProviderWizard — 关闭途径(取消 / Esc)', () => {
);
fireEvent.click(screen.getByText('settings.providers.wizard.title'));
expect(onClose).not.toHaveBeenCalled();
- const overlay = container.firstElementChild as HTMLElement;
+ const overlay = document.querySelector('.modal-scrim')!;
fireEvent.mouseDown(screen.getByText('settings.providers.wizard.title'));
fireEvent.click(overlay);
expect(onClose).not.toHaveBeenCalled();
@@ -575,6 +578,40 @@ describe('AddProviderWizard — 关闭途径(取消 / Esc)', () => {
fireEvent.click(overlay);
expect(onClose).not.toHaveBeenCalled();
fireEvent.click(screen.getByText('settings.providers.wizard.cancel'));
- expect(onClose).toHaveBeenCalledTimes(1);
+ await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1));
});
});
+
+it('wizard focuses search, contains Tab, restores its opener and lets a top dialog own Esc', async () => {
+ function Harness() {
+ const [open, setOpen] = useState(false);
+ const [child, setChild] = useState(false);
+ return <>
+ <button onClick={() => setOpen(true)}>Add provider</button>
+ {open && <AddProviderWizard providers={[]} onOpenCustomForm={vi.fn()} onClose={() => setOpen(false)} onDone={() => setOpen(false)} />}
+ <Dialog.Root open={child} onOpenChange={setChild}>
+ <Dialog.Portal><Dialog.Content aria-describedby={undefined}><Dialog.Title>Top layer</Dialog.Title><button>Child action</button></Dialog.Content></Dialog.Portal>
+ </Dialog.Root>
+ <button onClick={() => setChild(true)}>Open child</button>
+ </>;
+ }
+ const user = userEvent.setup();
+ render(<Harness />);
+ const opener = screen.getByRole('button', { name: 'Add provider' });
+ await user.click(opener);
+ const search = screen.getByPlaceholderText('settings.providers.wizard.searchPlaceholder');
+ const cancel = screen.getByRole('button', { name: 'settings.providers.wizard.cancel' });
+ expect(document.activeElement).toBe(search);
+ await user.tab({ shift: true });
+ expect(document.activeElement).toBe(cancel);
+ await user.tab();
+ expect(document.activeElement).toBe(search);
+ // Open a second Radix layer without moving focus outside the first modal.
+ fireEvent.click(screen.getByRole('button', { name: 'Open child', hidden: true }));
+ await user.keyboard('{Escape}');
+ expect(screen.getByRole('dialog')).toBeTruthy();
+ expect(screen.queryByText('Top layer')).toBeNull();
+ await user.keyboard('{Escape}');
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ await waitFor(() => expect(document.activeElement).toBe(opener));
+});
diff --git a/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsx b/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsx
index b0df3b9aeb..22f61e4a41 100644
--- a/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsx
@@ -1149,15 +1149,15 @@ it.each(['audioModels', 'embeddingModels'] as const)('opens key setup for a disc
const store = vi.fn(async () => undefined);
window.electronAPI.builtinApiKeyStore = store;
const onDone = vi.fn();
- const view = render(<AddProviderWizard providers={[mediaProvider]} onOpenCustomForm={vi.fn()} onClose={vi.fn()} onDone={onDone} />);
+ render(<AddProviderWizard providers={[mediaProvider]} onOpenCustomForm={vi.fn()} onClose={vi.fn()} onDone={onDone} />);
fireEvent.click(await screen.findByText('Media Only'));
expect(await screen.findByText('settings.providers.wizard.builtinApiKey.subtitle')).toBeTruthy();
- const keyInput = view.container.querySelector('input[type="password"]');
+ const keyInput = screen.getByRole('dialog').querySelector('input[type="password"]');
expect(keyInput).not.toBeNull();
fireEvent.change(keyInput!, { target: { value: 'test-media-key' } });
fireEvent.click(screen.getByRole('button', { name: 'settings.providers.wizard.finish' }));
await waitFor(() => expect(store).toHaveBeenCalledWith('gemini', 'test-media-key'));
- expect(onDone).toHaveBeenCalledWith('gemini');
+ await waitFor(() => expect(onDone).toHaveBeenCalledWith('gemini'));
});
@@ -1361,7 +1361,7 @@ it('does not discard the OAuth connection if the wizard closes while finish is s
await screen.findByText('Test model');
fireEvent.click(screen.getByRole('button', { name: 'settings.providers.wizard.finish' }));
await waitFor(() => expect(updateCustomProvider).toHaveBeenCalledOnce());
- fireEvent.keyDown(window, { key: 'Escape' });
+ fireEvent.keyDown(document.activeElement!, { key: 'Escape' });
fireEvent.click(screen.getByRole('button', { name: 'settings.providers.wizard.cancel' }));
expect(onClose).not.toHaveBeenCalled();
expect(deleteCustomProvider).not.toHaveBeenCalled();
diff --git a/apps/desktop/src/renderer/__tests__/customProviderDialogPresetLocale.test.tsx b/apps/desktop/src/renderer/__tests__/customProviderDialogPresetLocale.test.tsx
index 3619421c3c..1d45cf9b4d 100644
--- a/apps/desktop/src/renderer/__tests__/customProviderDialogPresetLocale.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/customProviderDialogPresetLocale.test.tsx
@@ -252,18 +252,18 @@ describe('ProviderConnectionDialog preset locale ownership', () => {
expect(onClose).not.toHaveBeenCalled();
fireEvent.keyDown(document, { key: 'Escape' });
- expect(onClose).toHaveBeenCalledTimes(1);
+ await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1));
});
it('does not close the provider form on a scrim gesture', async () => {
i18nState.language = 'zh-TW';
- const { container, onClose } = renderDialog();
+ const { onClose } = renderDialog();
const trigger = await findReadyPresetTrigger();
fireEvent.click(trigger);
expect(await screen.findByRole('option', { name: '繁體供應商' })).not.toBeNull();
- const scrim = container.firstElementChild as Element;
+ const scrim = document.querySelector('[data-custom-provider-dialog-scrim]')!;
fireEvent.pointerDown(scrim);
expect(screen.getByRole('option', { name: '繁體供應商' })).not.toBeNull();
expect(onClose).not.toHaveBeenCalled();
@@ -271,7 +271,7 @@ describe('ProviderConnectionDialog preset locale ownership', () => {
fireEvent.pointerDown(scrim);
expect(onClose).not.toHaveBeenCalled();
fireEvent.click(screen.getByText('settings.providers.custom.cancel'));
- expect(onClose).toHaveBeenCalledTimes(1);
+ await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1));
});
it('does not consume runtime tab or input pointerdowns while a child layer is open', async () => {
@@ -314,7 +314,7 @@ describe('ProviderConnectionDialog preset locale ownership', () => {
await findReadyPresetTrigger();
fireEvent.click(screen.getByRole('button', { name: 'settings.providers.custom.cancel' }));
- expect(onClose).toHaveBeenCalledTimes(1);
+ await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1));
});
@@ -444,7 +444,7 @@ describe('ProviderConnectionDialog preset locale ownership', () => {
expect(onClose).not.toHaveBeenCalled();
fireEvent.keyDown(document, { key: 'Escape' });
- expect(onClose).toHaveBeenCalledTimes(1);
+ await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1));
} finally {
document.removeEventListener('keydown', staleLayerListener, true);
}
diff --git a/apps/desktop/src/renderer/__tests__/modalSurfaceContract.test.ts b/apps/desktop/src/renderer/__tests__/modalSurfaceContract.test.ts
index 3ebbfbea70..c427f2c8c4 100644
--- a/apps/desktop/src/renderer/__tests__/modalSurfaceContract.test.ts
+++ b/apps/desktop/src/renderer/__tests__/modalSurfaceContract.test.ts
@@ -26,11 +26,7 @@ const SIDE_DRAWERS = new Set([
// 不经过 Radix、自己写遮罩和面板的弹窗:每个都必须同时挂着 modal-scrim 与 modal-panel,
// 删掉其中一个(改回独立底色 / 圆角)就会报出来。新增手写弹窗时登记到这里。
const HAND_BUILT_DIALOGS = new Set([
- 'components/chat/GhostCardHostPrompts.tsx',
- 'components/markdown/MermaidSourceEditor.tsx',
- 'components/settings/AddProviderWizard.tsx',
- 'components/settings/ProviderConnectionDialog.tsx',
- 'features/cc-agent/CreateWorkerPopover.tsx',
+ // A tab-local recovery banner: must not trap focus or lock scrolling across the window.
'features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx',
]);
diff --git a/apps/desktop/src/renderer/components/chat/GhostCardHostPrompts.tsx b/apps/desktop/src/renderer/components/chat/GhostCardHostPrompts.tsx
index 6c91dc4a2a..9b20719d88 100644
--- a/apps/desktop/src/renderer/components/chat/GhostCardHostPrompts.tsx
+++ b/apps/desktop/src/renderer/components/chat/GhostCardHostPrompts.tsx
@@ -1,3 +1,7 @@
+import * as AlertDialog from '@radix-ui/react-alert-dialog';
+import { useCallback } from 'react';
+import { useDialogExit } from '@/hooks/useDialogExit';
+import { WINDOW_DRAG_STYLE, WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';
/**
* 插件卡片(GhostToolCard)的两个宿主交互面:
* - GhostCardPromptPanel:data-ghost-prompt 动作的提示词输入面板(与老基座
@@ -118,8 +122,8 @@ export function GhostCardPromptPanel({
export function GhostCardLinkConfirm({
url,
host,
- onConfirm,
- onCancel,
+ onConfirm: notifyConfirmed,
+ onCancel: notifyCanceled,
}: {
url: string;
/** 醒目域名;解析失败传空串,正文仍展示全串。 */
@@ -128,23 +132,30 @@ export function GhostCardLinkConfirm({
onCancel: () => void;
}) {
const { t } = useTranslation();
+ const dialog = useDialogExit();
+ const onCancel = useCallback(() => dialog.close(notifyCanceled), [dialog.close, notifyCanceled]);
+ const onConfirm = useCallback(() => dialog.close(notifyConfirmed), [dialog.close, notifyConfirmed]);
return (
- <>
- <BlockingScrim modal />
- <div
- className="modal-panel fixed left-1/2 top-1/2 z-50 w-80 -translate-x-1/2 -translate-y-1/2 p-3.5"
- role="alertdialog"
- aria-label={t('chat.ghostCall.linkConfirmTitle')}
- onKeyDown={(e) => {
- if (e.key === 'Escape') onCancel();
- }}
+ <AlertDialog.Root open={dialog.open} onOpenChange={(open) => { if (!open) onCancel(); }}>
+ <AlertDialog.Portal>
+ <AlertDialog.Overlay
+ className="modal-scrim fixed inset-0 z-40"
+ style={WINDOW_DRAG_STYLE}
+ data-testid="ghost-card-scrim"
+ onMouseDown={(event) => event.preventDefault()}
+ />
+ <AlertDialog.Content
+ className="modal-panel fixed inset-0 z-50 m-auto h-fit w-80 p-3.5 outline-none"
+ style={WINDOW_NO_DRAG_STYLE}
+ onOpenAutoFocus={dialog.onOpenAutoFocus}
+ onCloseAutoFocus={dialog.onCloseAutoFocus}
>
- <div className="text-13 font-semibold" style={{ color: 'var(--text-primary)' }}>
+ <AlertDialog.Title asChild><div className="text-13 font-semibold" style={{ color: 'var(--text-primary)' }}>
{t('chat.ghostCall.linkConfirmTitle')}
- </div>
- <div className="mt-1.5 text-xs" style={{ color: 'var(--text-secondary)' }}>
+ </div></AlertDialog.Title>
+ <AlertDialog.Description asChild><div className="mt-1.5 text-xs" style={{ color: 'var(--text-secondary)' }}>
{t('chat.ghostCall.linkConfirmHint')}
- </div>
+ </div></AlertDialog.Description>
{host ? (
<div
className="mt-1.5 break-all text-13 font-semibold"
@@ -160,22 +171,21 @@ export function GhostCardLinkConfirm({
{url}
</div>
<div className="mt-2.5 flex items-center justify-end gap-1.5">
- <Button
+ <AlertDialog.Cancel asChild><Button
variant="secondary"
tone="quiet"
size="xs"
compact
type="button"
- autoFocus
- onClick={onCancel}
>
{t('chat.ghostCall.linkConfirmCancel')}
- </Button>
+ </Button></AlertDialog.Cancel>
<Button variant="secondary" size="xs" compact type="button" onClick={onConfirm}>
{t('chat.ghostCall.linkConfirmOpen')}
</Button>
</div>
- </div>
- </>
+ </AlertDialog.Content>
+ </AlertDialog.Portal>
+ </AlertDialog.Root>
);
}
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/GhostCardHostPrompts.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/GhostCardHostPrompts.test.tsx
index 6f54e09fba..3e4596d297 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/GhostCardHostPrompts.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/GhostCardHostPrompts.test.tsx
@@ -1,5 +1,7 @@
// @vitest-environment jsdom
-import { cleanup, createEvent, fireEvent, render, screen } from '@testing-library/react';
+import { cleanup, createEvent, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { useState } from 'react';
import { afterEach, expect, it, vi } from 'vitest';
import { GhostCardLinkConfirm, GhostCardPromptPanel } from '../GhostCardHostPrompts';
@@ -46,25 +48,37 @@ it('prompt panel keeps typed text when the scrim is clicked and closes only via
expect(onSubmit).toHaveBeenCalledTimes(1);
});
-it('link confirmation ignores scrim clicks and closes only via Cancel or Escape', () => {
+it.each(['Escape', 'Cancel', 'Open'])('link confirmation ignores scrim clicks and handles %s once', async (action) => {
const onCancel = vi.fn();
const onConfirm = vi.fn();
- render(
- <GhostCardLinkConfirm
- url="https://example.com/path"
- host="example.com"
- onConfirm={onConfirm}
- onCancel={onCancel}
- />,
- );
+ render(<GhostCardLinkConfirm url="https://example.com/path" host="example.com" onConfirm={onConfirm} onCancel={onCancel} />);
expect(pressScrim()).toBe(true);
expect(onCancel).not.toHaveBeenCalled();
expect(onConfirm).not.toHaveBeenCalled();
+ if (action === 'Escape') fireEvent.keyDown(document.activeElement!, { key: 'Escape' });
+ else fireEvent.click(screen.getByRole('button', { name: action === 'Cancel' ? 'chat.ghostCall.linkConfirmCancel' : 'chat.ghostCall.linkConfirmOpen' }));
+ await waitFor(() => expect(action === 'Open' ? onConfirm : onCancel).toHaveBeenCalledOnce());
+ expect(action === 'Open' ? onCancel : onConfirm).not.toHaveBeenCalled();
+ expect(screen.queryByRole('alertdialog')).toBeNull();
+});
- fireEvent.keyDown(screen.getByRole('alertdialog'), { key: 'Escape' });
- expect(onCancel).toHaveBeenCalledTimes(1);
- fireEvent.click(screen.getByRole('button', { name: 'chat.ghostCall.linkConfirmCancel' }));
- expect(onCancel).toHaveBeenCalledTimes(2);
- fireEvent.click(screen.getByRole('button', { name: 'chat.ghostCall.linkConfirmOpen' }));
- expect(onConfirm).toHaveBeenCalledTimes(1);
+it('focuses Cancel, traps Tab in both directions, and restores the link opener', async () => {
+ function Harness() {
+ const [open, setOpen] = useState(false);
+ return <><button onClick={() => setOpen(true)}>Open link</button>{open && <GhostCardLinkConfirm url="https://example.com" host="example.com" onConfirm={() => setOpen(false)} onCancel={() => setOpen(false)} />}</>;
+ }
+ const user = userEvent.setup();
+ render(<Harness />);
+ const opener = screen.getByRole('button', { name: 'Open link' });
+ await user.click(opener);
+ const cancel = screen.getByRole('button', { name: 'chat.ghostCall.linkConfirmCancel' });
+ const confirm = screen.getByRole('button', { name: 'chat.ghostCall.linkConfirmOpen' });
+ expect(document.activeElement).toBe(cancel);
+ await user.tab({ shift: true });
+ expect(document.activeElement).toBe(confirm);
+ await user.tab();
+ expect(document.activeElement).toBe(cancel);
+ await user.keyboard('{Escape}');
+ await waitFor(() => expect(screen.queryByRole('alertdialog')).toBeNull());
+ await waitFor(() => expect(document.activeElement).toBe(opener));
});
diff --git a/apps/desktop/src/renderer/components/markdown/MermaidSourceEditor.tsx b/apps/desktop/src/renderer/components/markdown/MermaidSourceEditor.tsx
index 60f6bcdef0..164ac8cd51 100644
--- a/apps/desktop/src/renderer/components/markdown/MermaidSourceEditor.tsx
+++ b/apps/desktop/src/renderer/components/markdown/MermaidSourceEditor.tsx
@@ -23,7 +23,9 @@ import { Button } from '@/components/ui/button';
*/
import { useCallback, useEffect, useRef, useState } from 'react';
-import { createPortal } from 'react-dom';
+import * as Dialog from '@radix-ui/react-dialog';
+import { useDialogExit } from '@/hooks/useDialogExit';
+import { WINDOW_DRAG_STYLE, WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';
import { useTranslation } from 'react-i18next';
import { cn } from '@/lib/utils';
@@ -87,15 +89,9 @@ function MermaidSourceEditor({
}: MermaidSourceEditorProps) {
const { t } = useTranslation();
const [draft, setDraft] = useState(initialSource);
- const [isVisible, setIsVisible] = useState(false);
- const isClosingRef = useRef(false);
+ const dialog = useDialogExit();
const textareaRef = useRef<HTMLTextAreaElement>(null);
- useEffect(() => {
- const raf = requestAnimationFrame(() => setIsVisible(true));
- return () => cancelAnimationFrame(raf);
- }, []);
-
// Tell window-capture shortcut handlers (e.g. FileBodyView's Cmd+F /
// Cmd+S) to bail while this modal is open. Capture-phase listeners on
// window fire in registration order; FileBodyView mounted first so any
@@ -111,35 +107,16 @@ function MermaidSourceEditor({
};
}, []);
- // Autofocus textarea so the user can start editing without clicking.
- useEffect(() => {
- textareaRef.current?.focus();
- textareaRef.current?.setSelectionRange(0, 0);
- }, []);
-
- const close = useCallback(
- (commit: boolean) => {
- if (isClosingRef.current) return;
- isClosingRef.current = true;
- setIsVisible(false);
- // Match the lightbox's 200ms fade-out so the two modals feel related.
- setTimeout(() => {
- if (commit) onSave(draft);
- else onCancel();
- }, 200);
- },
- [draft, onSave, onCancel],
- );
+ const close = useCallback((commit: boolean) => {
+ dialog.close(() => {
+ if (commit) onSave(draft);
+ else onCancel();
+ });
+ }, [dialog.close, draft, onSave, onCancel]);
const dirty = draft !== initialSource;
- useEffect(() => {
- const onKey = (ev: KeyboardEvent) => {
- if (ev.key === 'Escape') {
- ev.preventDefault();
- close(false);
- return;
- }
+ const onKeyDown = (ev: React.KeyboardEvent) => {
// Cmd/Ctrl+Enter saves — quick exit for users who edited and want out.
// Gate on `dirty` so a stale shortcut press on an unchanged diagram
// doesn't fire a no-op `view.dispatch`. The dispatch would still
@@ -163,28 +140,28 @@ function MermaidSourceEditor({
// modal is open, it writes the SAME bytes already on disk (the
// modal draft hasn't been dispatched), so there's no real data
// loss — only a no-op write.
- };
- window.addEventListener('keydown', onKey);
- return () => window.removeEventListener('keydown', onKey);
- }, [close, dirty]);
+ };
- const overlay = (
- <div
- className={cn(
- 'fixed inset-0 z-[60] flex items-center justify-center',
- 'transition-opacity duration-200',
- isVisible ? 'opacity-100' : 'opacity-0',
- )}
- >
+ return (
+ <Dialog.Root open={dialog.open} onOpenChange={(open) => { if (!open) close(false); }}>
+ <Dialog.Portal>
+ <Dialog.Overlay className="modal-scrim fixed inset-0 z-[60]" style={WINDOW_DRAG_STYLE} />
{/* The scrim does not dismiss: a stray click outside must not discard the
draft. Cancel and Escape remain the ways out (DESIGN §4 Dialog). */}
- <div className="modal-scrim absolute inset-0" />
- <div
- role="dialog"
- aria-modal="true"
- aria-label={t('ccAgent.workdirBrowse.mermaidEditor.title', '编辑 mermaid 源码')}
+ <Dialog.Content
+ aria-describedby={undefined}
+ onPointerDownOutside={(event) => event.preventDefault()}
+ onOpenAutoFocus={(event) => {
+ dialog.onOpenAutoFocus();
+ event.preventDefault();
+ textareaRef.current?.focus();
+ textareaRef.current?.setSelectionRange(0, 0);
+ }}
+ onCloseAutoFocus={dialog.onCloseAutoFocus}
+ onKeyDown={onKeyDown}
+ style={WINDOW_NO_DRAG_STYLE}
className={cn(
- 'modal-panel relative z-[61] flex flex-col',
+ 'modal-panel fixed inset-0 z-[61] m-auto flex flex-col outline-none',
'w-[min(880px,90vw)] h-[min(640px,80vh)]',
'overflow-hidden',
)}
@@ -195,9 +172,9 @@ function MermaidSourceEditor({
'px-5 py-3 border-b border-[var(--border-default)]',
)}
>
- <div className="text-14 font-medium text-[var(--text-primary)]">
+ <Dialog.Title asChild><div className="text-14 font-medium text-[var(--text-primary)]">
{t('ccAgent.workdirBrowse.mermaidEditor.title')}
- </div>
+ </div></Dialog.Title>
<div className="text-11 text-[var(--text-tertiary)]">
{t('ccAgent.workdirBrowse.mermaidEditor.shortcuts')}
</div>
@@ -240,9 +217,8 @@ function MermaidSourceEditor({
{t('ccAgent.workdirBrowse.mermaidEditor.save')}
</Button>
</div>
- </div>
- </div>
+ </Dialog.Content>
+ </Dialog.Portal>
+ </Dialog.Root>
);
-
- return createPortal(overlay, document.body);
}
diff --git a/apps/desktop/src/renderer/components/markdown/__tests__/MermaidSourceEditor.test.tsx b/apps/desktop/src/renderer/components/markdown/__tests__/MermaidSourceEditor.test.tsx
new file mode 100644
index 0000000000..a61b23acc0
--- /dev/null
+++ b/apps/desktop/src/renderer/components/markdown/__tests__/MermaidSourceEditor.test.tsx
@@ -0,0 +1,90 @@
+// @vitest-environment jsdom
+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 { MermaidSourceEditorHost } from '../MermaidSourceEditor';
+import { MERMAID_EDIT_EVENT } from '../markdownMermaidLivePreview';
+
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+afterEach(() => { cleanup(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
+
+function openEditor(applyEdit = vi.fn(() => 'applied' as const)) {
+ render(<>
+ <button onClick={() => window.dispatchEvent(new CustomEvent(MERMAID_EDIT_EVENT, {
+ detail: { source: 'graph TD', applyEdit },
+ }))}>Edit diagram</button>
+ <MermaidSourceEditorHost />
+ </>);
+ return { applyEdit, opener: screen.getByRole('button', { name: 'Edit diagram' }) };
+}
+
+it('focuses the source at offset zero, traps Tab, keeps the draft on scrim click and returns focus', async () => {
+ const user = userEvent.setup();
+ const { opener, applyEdit } = openEditor();
+ await user.click(opener);
+ const source = screen.getByRole('textbox') as HTMLTextAreaElement;
+ expect(document.activeElement).toBe(source);
+ expect(source.selectionStart).toBe(0);
+ expect(document.body.dataset.mermaidEditorOpen).toBe('1');
+ const save = screen.getByRole('button', { name: 'ccAgent.workdirBrowse.mermaidEditor.save' }) as HTMLButtonElement;
+ expect(save.disabled).toBe(true);
+ fireEvent.change(source, { target: { value: 'graph LR' } });
+ await user.tab({ shift: true });
+ expect(document.activeElement).toBe(save);
+ await user.tab();
+ expect(document.activeElement).toBe(source);
+ fireEvent.pointerDown(document.querySelector('.modal-scrim')!);
+ fireEvent.click(document.querySelector('.modal-scrim')!);
+ expect(source.value).toBe('graph LR');
+ expect(document.activeElement).toBe(source);
+ await user.keyboard('{Escape}');
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ await waitFor(() => expect(document.activeElement).toBe(opener));
+ expect(document.body.dataset.mermaidEditorOpen).toBeUndefined();
+ expect(applyEdit).not.toHaveBeenCalled();
+});
+
+it.each([true, false])('Cmd+Enter commits only a dirty draft (dirty=%s)', async (dirty) => {
+ const user = userEvent.setup();
+ const { opener, applyEdit } = openEditor();
+ await user.click(opener);
+ if (dirty) fireEvent.change(screen.getByRole('textbox'), { target: { value: 'graph LR' } });
+ fireEvent.keyDown(screen.getByRole('textbox'), { key: 'Enter', metaKey: true });
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ await waitFor(() => expect(document.activeElement).toBe(opener));
+ if (dirty) expect(applyEdit).toHaveBeenCalledExactlyOnceWith('graph LR');
+ else expect(applyEdit).not.toHaveBeenCalled();
+});
+
+it('lets Presence finish the closing animation before committing and unmounting', async () => {
+ vi.stubGlobal('CSS', { escape: (value: string) => value });
+ const getStyle = window.getComputedStyle.bind(window);
+ vi.spyOn(window, 'getComputedStyle').mockImplementation((element) => {
+ const style = getStyle(element);
+ if (element.classList.contains('modal-panel') || element.classList.contains('modal-scrim')) {
+ // JSDOM has no CSS animations. Supply the real data-state contract and
+ // dispatch its completion rather than mocking Radix or advancing a timer.
+ Object.defineProperty(style, 'animationName', { configurable: true, get: () =>
+ element.getAttribute('data-state') === 'closed' ? 'modal-fade-out' : 'modal-panel-in' });
+ }
+ return style;
+ });
+ const user = userEvent.setup();
+ const { opener, applyEdit } = openEditor();
+ await user.click(opener);
+ const panel = screen.getByRole('dialog');
+ const source = screen.getByRole('textbox');
+ fireEvent.change(source, { target: { value: 'graph LR' } });
+ fireEvent.animationStart(panel, { animationName: 'modal-panel-in' });
+ await user.click(screen.getByRole('button', { name: 'ccAgent.workdirBrowse.mermaidEditor.save' }));
+ expect(panel.getAttribute('data-state')).toBe('closed');
+ expect(panel.isConnected).toBe(true);
+ expect(applyEdit).not.toHaveBeenCalled();
+ const end = new Event('animationend', { bubbles: true });
+ Object.defineProperty(end, 'animationName', { value: 'modal-fade-out' });
+ act(() => { panel.dispatchEvent(end); });
+ await waitFor(() => expect(applyEdit).toHaveBeenCalledExactlyOnceWith('graph LR'));
+ expect(screen.queryByRole('dialog')).toBeNull();
+ await waitFor(() => expect(document.activeElement).toBe(opener));
+});
diff --git a/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx b/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx
index 84a0820981..a29c732dba 100644
--- a/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx
+++ b/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx
@@ -18,6 +18,9 @@ import { bindProviderPresetRuntime, providerEndpointBindings, bindProviderEndpoi
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import * as Dialog from '@radix-ui/react-dialog';
+import { useDialogExit } from '@/hooks/useDialogExit';
+import { WINDOW_DRAG_STYLE, WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';
import { Check, Info, Plus, Search } from 'lucide-react';
import { Button } from '@/components/ui/button';
@@ -355,11 +358,16 @@ function hasRetainedBuiltinConnection(provider: ProviderView): boolean {
export function AddProviderWizard({
providers,
entry,
- onOpenCustomForm,
- onClose,
- onDone,
+ onOpenCustomForm: openCustomForm,
+ onClose: notifyClosed,
+ onDone: notifyDone,
}: AddProviderWizardProps) {
const { t, i18n } = useTranslation();
+ const dialog = useDialogExit();
+ const panelRef = useRef<HTMLDivElement>(null);
+ const onClose = useCallback(() => dialog.close(notifyClosed), [dialog.close, notifyClosed]);
+ const onDone = useCallback((id?: string) => dialog.close(() => notifyDone(id)), [dialog.close, notifyDone]);
+ const onOpenCustomForm = useCallback(() => dialog.close(openCustomForm), [dialog.close, openCustomForm]);
// Native credentials alone do not mean this Cindy account has added the local
// connection. Keep the slot occupied when suspended or awaiting reconnection.
@@ -942,18 +950,6 @@ export function AddProviderWizard({
onClose();
}, [loggingIn, cancelAuthorize, onClose]);
- // Esc 关闭(本弹窗未用 Radix,需自行监听)。
- // CJK 输入法组合期间的 Esc 是「取消候选词」,不是关闭命令(isComposing / 遗留
- // keyCode 229),与仓库其他 CJK 输入场景同口径(PR #1102 review 第六轮)。
- useEffect(() => {
- const onKeyDown = (e: KeyboardEvent) => {
- if (e.key === 'Escape' && !e.isComposing && e.keyCode !== 229) handleClose();
- };
- window.addEventListener('keydown', onKeyDown);
- return () => window.removeEventListener('keydown', onKeyDown);
- }, [handleClose]);
-
-
// ── 预设:进入 Step 3 时自动拉取模型 ─────────────────────────────────────
const startFetch = useCallback(async () => {
if (!sel || sel.kind !== 'preset') return;
@@ -1454,15 +1450,29 @@ export function AddProviderWizard({
(!presetNeedsApiKey || apiKey.trim().length > 0);
return (
- <div
- className="modal-scrim fixed inset-0 z-[10000] flex items-center justify-center"
- >
- <div
- className="modal-panel flex max-h-[min(640px,85vh)] w-[min(600px,calc(100vw-32px))] flex-col overflow-hidden"
+ <Dialog.Root open={dialog.open} onOpenChange={(open) => { if (!open) handleClose(); }}>
+ <Dialog.Portal>
+ <Dialog.Overlay className="modal-scrim fixed inset-0 z-[10000]" style={WINDOW_DRAG_STYLE} />
+ <Dialog.Content
+ ref={panelRef}
+ aria-describedby={undefined}
+ onPointerDownOutside={(event) => event.preventDefault()}
+ onOpenAutoFocus={(event) => {
+ dialog.onOpenAutoFocus();
+ event.preventDefault();
+ const input = panelRef.current?.querySelector<HTMLElement>('input:not([disabled]), textarea:not([disabled])');
+ (input ?? panelRef.current?.querySelector<HTMLElement>('button:not([disabled])'))?.focus();
+ }}
+ onCloseAutoFocus={dialog.onCloseAutoFocus}
+ onEscapeKeyDown={(event) => {
+ if (savingRef.current || event.isComposing || event.keyCode === 229) event.preventDefault();
+ }}
+ style={WINDOW_NO_DRAG_STYLE}
+ className="modal-panel fixed inset-0 z-[10000] m-auto flex h-fit max-h-[min(640px,85vh)] w-[min(600px,calc(100vw-32px))] flex-col overflow-hidden outline-none"
>
{/* 头部:标题居左 + 步骤指示居右,同一行(2026-07 定稿原型形态)。 */}
<div className="flex items-center justify-between gap-4 px-4 pb-3 pt-4">
- <h3
+ <Dialog.Title asChild><h3
className="min-w-0 truncate text-16 font-medium"
style={{ color: 'var(--settings-section-title)' }}
>
@@ -1476,7 +1486,7 @@ export function AddProviderWizard({
: sel.provider.name,
})
: t('settings.providers.wizard.title')}
- </h3>
+ </h3></Dialog.Title>
<div className="flex shrink-0 items-center gap-4">
{stepLabels.map((label, i) => {
const n = i + 1;
@@ -2243,7 +2253,8 @@ export function AddProviderWizard({
)}
</div>
</div>
- </div>
- </div>
+ </Dialog.Content>
+ </Dialog.Portal>
+ </Dialog.Root>
);
}
diff --git a/apps/desktop/src/renderer/components/settings/ProviderConnectionDialog.tsx b/apps/desktop/src/renderer/components/settings/ProviderConnectionDialog.tsx
index a8a607029c..644b5dda43 100644
--- a/apps/desktop/src/renderer/components/settings/ProviderConnectionDialog.tsx
+++ b/apps/desktop/src/renderer/components/settings/ProviderConnectionDialog.tsx
@@ -1,3 +1,5 @@
+import { useDialogExit } from '@/hooks/useDialogExit';
+import { WINDOW_DRAG_STYLE, WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';
import { providerEndpointBindings, canonicalProviderEndpoint, BUNDLED_CATALOG, classifyModel, isChatEligible, isAgentSelectableModel, mergeModelMetadata } from '@cindy/model-providers';
/**
* Connection credentials and advanced routing only. Model capabilities are imported into the
@@ -118,15 +120,6 @@ const AGENTS: DialogAgentKind[] = ['claude-code', 'codex', 'pi'];
const VISIBLE_AGENTS: DialogAgentKind[] = AGENTS;
-const DIALOG_FOCUSABLE_SELECTOR = [
- 'button:not([disabled])',
- 'input:not([disabled])',
- 'select:not([disabled])',
- 'textarea:not([disabled])',
- '[href]',
- '[tabindex]:not([tabindex="-1"])',
-].join(',');
-
const TAB_META: Record<
DialogAgentKind,
{ Mark: typeof ClaudeMark; labelKey: string; helpKey: string }
@@ -407,10 +400,13 @@ export function ProviderConnectionDialog({
existingIds,
returnFocusRef,
focusAgent,
- onSaved,
- onClose,
+ onSaved: notifySaved,
+ onClose: notifyClosed,
}: ProviderConnectionDialogProps) {
const { t, i18n } = useTranslation();
+ const dialog = useDialogExit(returnFocusRef);
+ const onClose = useCallback(() => dialog.close(notifyClosed), [dialog.close, notifyClosed]);
+ const onSaved = useCallback(() => dialog.close(notifySaved), [dialog.close, notifySaved]);
const editing = !!initial;
const initialOAuth = initial?.auth?.method === 'oauth' ? initial.auth.oauth : undefined;
@@ -668,24 +664,6 @@ export function ProviderConnectionDialog({
return () => window.removeEventListener('keydown', onKeyDown, true);
}, [dismissImageGenerationHelp, dismissTopmostLayer, showImageGenerationHelp]);
- useEffect(() => {
- const returnFocusElement =
- document.activeElement instanceof HTMLElement && document.activeElement !== document.body
- ? document.activeElement
- : null;
- const frame = requestAnimationFrame(() => {
- (
- dialogPanelRef.current?.querySelector<HTMLInputElement>('input')
- )?.focus();
- });
- return () => {
- cancelAnimationFrame(frame);
- const focusTarget = returnFocusElement?.isConnected
- ? returnFocusElement
- : returnFocusRef?.current;
- if (focusTarget?.isConnected) focusTarget.focus();
- };
- }, [returnFocusRef]);
// 最新 runtime 表单状态镜像:拉取响应到达时据此构建弹层行/预勾选,而不是用请求发出时的
// 闭包快照——在途期间被用户删除的行不得复活。镜像在每个 setRt updater 内**同步**更新
// (见 setRtSynced),不用被动 useEffect——effect 在 commit 后才跑,IPC 响应若落在
@@ -1991,37 +1969,29 @@ export function ProviderConnectionDialog({
};
return (
- <div
- data-custom-provider-dialog-scrim="true"
- className="modal-scrim fixed inset-0 z-[10000] flex items-center justify-center"
- onKeyDown={(event) => {
- if (childLayer || runtimeFill || imageGenerationReloadConfirmation) return;
- if (event.key !== 'Tab') return;
- const focusable = Array.from(
- dialogPanelRef.current?.querySelectorAll<HTMLElement>(DIALOG_FOCUSABLE_SELECTOR) ?? [],
- );
- if (focusable.length === 0) {
- event.preventDefault();
- dialogPanelRef.current?.focus();
- return;
- }
- const first = focusable[0];
- const last = focusable[focusable.length - 1];
- if (event.shiftKey && document.activeElement === first) {
- event.preventDefault();
- last.focus();
- } else if (!event.shiftKey && document.activeElement === last) {
- event.preventDefault();
- first.focus();
- }
- }}
- >
- <div
+ <Dialog.Root open={dialog.open} onOpenChange={(open) => { if (!open) dismissTopmostLayer(); }}>
+ <Dialog.Portal>
+ <Dialog.Overlay
+ data-custom-provider-dialog-scrim="true"
+ className="modal-scrim fixed inset-0 z-[10000]"
+ style={WINDOW_DRAG_STYLE}
+ />
+ <Dialog.Content
ref={dialogPanelRef}
- role="dialog"
- aria-modal="true"
+ aria-describedby={undefined}
aria-labelledby="custom-provider-dialog-title"
- tabIndex={-1}
+ onPointerDownOutside={(event) => event.preventDefault()}
+ onOpenAutoFocus={(event) => {
+ dialog.onOpenAutoFocus();
+ event.preventDefault();
+ dialogPanelRef.current?.querySelector<HTMLInputElement>('input')?.focus();
+ }}
+ onCloseAutoFocus={dialog.onCloseAutoFocus}
+ onEscapeKeyDown={(event) => {
+ // The existing window-capture owner handles child layers and IME first.
+ event.preventDefault();
+ }}
+ style={WINDOW_NO_DRAG_STYLE}
onChangeCapture={(event) => {
// 错误清除粒度(review P2/P1 双向约束):
// - 报错字段自身被编辑时清除——改其它字段(名称/密钥/别的 runtime 行)
@@ -2046,7 +2016,7 @@ export function ProviderConnectionDialog({
}
}}
className={cn(
- 'modal-panel flex max-h-[88vh] w-[min(600px,calc(100vw-32px))] flex-col outline-none',
+ 'modal-panel fixed inset-0 z-[10000] m-auto flex h-fit max-h-[88vh] w-[min(600px,calc(100vw-32px))] flex-col outline-none',
'[&_button:focus-visible]:outline-none [&_button:focus-visible]:ring-2 [&_button:focus-visible]:ring-[var(--focus-ring)]',
)}
>
@@ -2054,14 +2024,14 @@ export function ProviderConnectionDialog({
<div className="flex items-center px-3 py-3">
<div className="flex items-center gap-2.5 pl-2">
<Sparkles size={20} className="text-[var(--settings-section-title)]" />
- <h2
+ <Dialog.Title asChild><h2
id="custom-provider-dialog-title"
className="text-18 font-semibold text-[var(--settings-section-title)]"
>
{editing
? t('settings.providers.custom.dialog.editTitle')
: t('settings.providers.custom.dialog.createTitle')}
- </h2>
+ </h2></Dialog.Title>
</div>
</div>
@@ -2778,7 +2748,8 @@ export function ProviderConnectionDialog({
{t('settings.providers.custom.save')}
</Button>
</div>
- </div>
+ </Dialog.Content>
+ </Dialog.Portal>
{/* 「获取模型列表」勾选弹层:可搜索多选,确认后替换该 runtime 的模型行。 */}
{picker && (
@@ -2893,7 +2864,7 @@ export function ProviderConnectionDialog({
</Dialog.Portal>
</Dialog.Root>
)}
- </div>
+ </Dialog.Root>
);
}
diff --git a/apps/desktop/src/renderer/components/settings/__tests__/CustomProviderDialogAccessibility.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/CustomProviderDialogAccessibility.test.tsx
index c0376b4335..c0a9fcee87 100644
--- a/apps/desktop/src/renderer/components/settings/__tests__/CustomProviderDialogAccessibility.test.tsx
+++ b/apps/desktop/src/renderer/components/settings/__tests__/CustomProviderDialogAccessibility.test.tsx
@@ -1242,11 +1242,10 @@ describe('ProviderConnectionDialog accessibility', () => {
expect(document.querySelectorAll('#custom-provider-image-generation-help-card')).toHaveLength(
1,
);
- await user.unhover(help);
await user.hover(screen.getByRole('tooltip'));
await act(() => new Promise((resolve) => window.setTimeout(resolve, 150)));
expectCompleteImageGenerationHelp(screen.getByRole('tooltip'));
- await user.unhover(screen.getByRole('tooltip'));
+ await user.hover(advanced);
await waitFor(() => expect(screen.queryByRole('tooltip')).toBeNull());
await user.hover(help);
@@ -1260,7 +1259,7 @@ describe('ProviderConnectionDialog accessibility', () => {
expect(onClose).not.toHaveBeenCalled();
await act(() => new Promise((resolve) => window.setTimeout(resolve, 0)));
expect(screen.queryByRole('tooltip')).toBeNull();
- await user.unhover(help);
+ await user.hover(advanced);
await act(async () => help.focus());
expect(screen.queryByRole('tooltip')).toBeNull();
@@ -1293,14 +1292,14 @@ describe('ProviderConnectionDialog accessibility', () => {
expect(onClose).not.toHaveBeenCalled();
await act(() => new Promise((resolve) => window.setTimeout(resolve, 0)));
expect(screen.queryByRole('tooltip')).toBeNull();
- await user.unhover(help);
+ await user.hover(advanced);
await user.click(help);
helpPopover = await screen.findByRole('dialog', {
name: 'settings.providers.custom.fields.runtimeSupportsImageGenerationHelpLabel',
});
expectCompleteImageGenerationHelp(helpPopover);
- await user.unhover(help);
+ await user.hover(advanced);
await act(() => new Promise((resolve) => window.setTimeout(resolve, 150)));
expect(
screen.getByRole('dialog', {
@@ -1365,9 +1364,6 @@ describe('ProviderConnectionDialog accessibility', () => {
expect(document.activeElement).toBe(help);
expect(onClose).not.toHaveBeenCalled();
await act(async () => capability.focus());
- await user.keyboard('{Escape}');
- expect(onClose).toHaveBeenCalledOnce();
-
await act(async () => help.focus());
expectCompleteImageGenerationHelp(await screen.findByRole('tooltip'));
await user.keyboard(' ');
@@ -1383,6 +1379,11 @@ describe('ProviderConnectionDialog accessibility', () => {
).toBeNull(),
);
+ await act(async () => capability.focus());
+ await user.keyboard('{Escape}');
+ await waitFor(() => expect(onClose).toHaveBeenCalledOnce());
+ expect(screen.queryByRole('dialog')).toBeNull();
+
expect(consoleError.mock.calls.flat().join('\n')).not.toMatch(
/changing an (uncontrolled|controlled).*component/i,
);
@@ -1816,3 +1817,34 @@ it('saves OpenRouter OAuth connections that leave scopes empty for provider defa
method: 'oauth', oauth: { scopes: '' },
});
});
+
+it('main provider form contains Tab and blocks dismissal only during the actual save', async () => {
+ let finish!: () => void;
+ customProviderMocks.readCustomProviderKey.mockResolvedValue(null);
+ customProviderMocks.updateCustomProvider.mockImplementation(() => new Promise<void>((resolve) => { finish = resolve; }));
+ const onSaved = vi.fn();
+ const onClose = vi.fn();
+ const user = userEvent.setup();
+ render(<ProviderConnectionDialog initial={modelRoutedCodexProvider()} onSaved={onSaved} onClose={onClose} />);
+ await waitForInitialDialogFocus();
+ const name = screen.getByPlaceholderText('settings.providers.custom.fields.namePlaceholder');
+ const save = screen.getByRole('button', { name: 'settings.providers.custom.save' });
+ const cancel = screen.getByRole('button', { name: 'settings.providers.custom.cancel' }) as HTMLButtonElement;
+ await user.tab({ shift: true });
+ expect(document.activeElement).toBe(save);
+ await user.tab();
+ expect(document.activeElement).toBe(name);
+ await user.type(name, ' renamed');
+ await user.click(save);
+ await waitFor(() => expect(customProviderMocks.updateCustomProvider).toHaveBeenCalledOnce());
+ expect(cancel.disabled).toBe(true);
+ await user.keyboard('{Escape}');
+ fireEvent.click(cancel);
+ fireEvent.pointerDown(document.querySelector('[data-custom-provider-dialog-scrim]')!);
+ expect(onClose).not.toHaveBeenCalled();
+ expect(onSaved).not.toHaveBeenCalled();
+ expect(screen.getByRole('dialog')).toBeTruthy();
+ await act(async () => finish());
+ await waitFor(() => expect(onSaved).toHaveBeenCalledOnce());
+ expect(screen.queryByRole('dialog')).toBeNull();
+});
diff --git a/apps/desktop/src/renderer/features/cc-agent/CreateWorkerPopover.tsx b/apps/desktop/src/renderer/features/cc-agent/CreateWorkerPopover.tsx
index f71ecf30b0..e60b5cc130 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CreateWorkerPopover.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CreateWorkerPopover.tsx
@@ -1,3 +1,5 @@
+import * as Dialog from '@radix-ui/react-dialog';
+import { WINDOW_DRAG_STYLE, WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';
import { Button } from '@/components/ui/button';
import { useModelPickerAgents } from '@/hooks/useAvailableAgents';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
@@ -640,21 +642,45 @@ export function CreateWorkerPopover({
supportsWorkerPermissionModeSelection,
]);
- if (!open) return null;
+ const roleInputRef = useRef<HTMLInputElement>(null);
+ const openerRef = useRef<HTMLElement | null>(null);
+ const handleClose = useCallback(() => {
+ if (!submittingRef.current) onClose();
+ }, [onClose]);
return (
- <div className={cn('fixed inset-0 z-50 flex items-center justify-center', className)}>
- <div className="modal-scrim absolute inset-0" />
- <div
- className="modal-panel relative z-10 w-[500px] p-6"
+ <Dialog.Root open={open} onOpenChange={(next) => { if (!next) handleClose(); }}>
+ <Dialog.Portal>
+ <Dialog.Overlay
+ className={cn('modal-scrim fixed inset-0 z-50 flex items-center justify-center', className)}
+ style={WINDOW_DRAG_STYLE}
+ >
+ <Dialog.Content
+ className="modal-panel relative z-10 w-[500px] p-6 outline-none"
+ aria-describedby={undefined}
+ onPointerDownOutside={(event) => event.preventDefault()}
+ onOpenAutoFocus={(event) => {
+ event.preventDefault();
+ openerRef.current = document.activeElement instanceof HTMLElement ? document.activeElement : null;
+ roleInputRef.current?.focus();
+ }}
+ onCloseAutoFocus={(event) => {
+ event.preventDefault();
+ if (openerRef.current?.isConnected) openerRef.current.focus({ preventScroll: true });
+ }}
+ onEscapeKeyDown={(event) => {
+ if (submittingRef.current || event.isComposing || event.keyCode === 229) event.preventDefault();
+ }}
+ style={WINDOW_NO_DRAG_STYLE}
>
<div className="mb-5 flex items-center justify-between">
- <span className="text-16 font-medium text-[var(--text-primary)]">{resolvedTitle}</span>
+ <Dialog.Title asChild><span className="text-16 font-medium text-[var(--text-primary)]">{resolvedTitle}</span></Dialog.Title>
<button
type="button"
aria-label={t('orca.createWorker.closeAria')}
className="inline-flex h-6 w-6 items-center justify-center rounded text-[var(--text-tertiary)] hover:text-[var(--text-primary)]"
- onClick={onClose}
+ disabled={isSubmitting}
+ onClick={handleClose}
>
<X size={15} />
</button>
@@ -705,6 +731,7 @@ export function CreateWorkerPopover({
))}
</div>
<input
+ ref={roleInputRef}
type="text"
className="mt-2 w-full rounded-full border border-[var(--border-default)] bg-transparent px-3 py-1.5 text-13 leading-none text-[var(--text-primary)] placeholder:text-[var(--text-tertiary)] outline-none focus:border-[var(--text-secondary)]"
placeholder={t('orca.createWorker.customRolePlaceholder')}
@@ -872,7 +899,9 @@ export function CreateWorkerPopover({
>
{resolvedSubmitLabel}
</Button>
- </div>
- </div>
+ </Dialog.Content>
+ </Dialog.Overlay>
+ </Dialog.Portal>
+ </Dialog.Root>
);
}
diff --git a/apps/desktop/src/renderer/features/cc-agent/__tests__/CreateWorkerPopover.test.tsx b/apps/desktop/src/renderer/features/cc-agent/__tests__/CreateWorkerPopover.test.tsx
index 0994786a14..a8d737afbc 100644
--- a/apps/desktop/src/renderer/features/cc-agent/__tests__/CreateWorkerPopover.test.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/__tests__/CreateWorkerPopover.test.tsx
@@ -1,6 +1,8 @@
// @vitest-environment jsdom
-import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { useState } from 'react';
+import userEvent from '@testing-library/user-event';
import { renderToString } from 'react-dom/server';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -282,7 +284,7 @@ describe('CreateWorkerPopover', () => {
) as HTMLTextAreaElement;
fireEvent.change(initialTask, { target: { value: 'Draft a plan' } });
const panel = screen.getByText('orca.createWorker.title').closest('.relative.z-10');
- fireEvent.click(panel!.previousElementSibling!);
+ fireEvent.click(panel!.closest('.modal-scrim')!);
expect(onClose).not.toHaveBeenCalled();
expect(initialTask.value).toBe('Draft a plan');
@@ -291,6 +293,72 @@ describe('CreateWorkerPopover', () => {
expect(onClose).toHaveBeenCalledOnce();
});
+ it('focuses the role input, traps Tab, closes with Esc, and returns focus on reopen', async () => {
+ function Harness() {
+ const [open, setOpen] = useState(false);
+ return <><button onClick={() => setOpen(true)}>Add worker</button><CreateWorkerPopover open={open} onClose={() => setOpen(false)} onCreate={vi.fn()} /></>;
+ }
+ const user = userEvent.setup();
+ render(<Harness />);
+ const opener = screen.getByRole('button', { name: 'Add worker' });
+ for (let attempt = 0; attempt < 2; attempt++) {
+ await user.click(opener);
+ expect(document.activeElement).toBe(screen.getByPlaceholderText('orca.createWorker.customRolePlaceholder'));
+ const close = screen.getByRole('button', { name: 'orca.createWorker.closeAria' });
+ const submit = screen.getByRole('button', { name: 'orca.createWorker.submit' });
+ close.focus();
+ await user.tab({ shift: true });
+ expect(document.activeElement).toBe(submit);
+ await user.tab();
+ expect(document.activeElement).toBe(close);
+ await user.keyboard('{Escape}');
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ await waitFor(() => expect(document.activeElement).toBe(opener));
+ }
+ });
+
+ it.each([
+ ['role', 'orca.createWorker.customRolePlaceholder', { isComposing: true }],
+ ['role', 'orca.createWorker.customRolePlaceholder', { keyCode: 229 }],
+ ['task', 'orca.createWorker.initialTaskPlaceholder', { isComposing: true }],
+ ['task', 'orca.createWorker.initialTaskPlaceholder', { keyCode: 229 }],
+ ] as const)('preserves the %s draft in %s on IME Esc (%j)', (_field, placeholder, ime) => {
+ const onClose = vi.fn();
+ render(<CreateWorkerPopover open onClose={onClose} onCreate={vi.fn()} />);
+ const input = screen.getByPlaceholderText(placeholder) as HTMLInputElement | HTMLTextAreaElement;
+ fireEvent.change(input, { target: { value: 'Worker draft' } });
+ input.focus();
+
+ fireEvent.keyDown(input, { key: 'Escape', ...ime });
+ expect(onClose).not.toHaveBeenCalled();
+ expect(screen.getByRole('dialog')).toBeTruthy();
+ expect(input.value).toBe('Worker draft');
+ expect(document.activeElement).toBe(input);
+
+ fireEvent.keyDown(input, { key: 'Escape' });
+ expect(onClose).toHaveBeenCalledOnce();
+ });
+
+ it('blocks both Esc and the close button until creation settles', async () => {
+ let finish!: () => void;
+ const onCreate = vi.fn(() => new Promise<void>((resolve) => { finish = resolve; }));
+ const onClose = vi.fn();
+ const user = userEvent.setup();
+ render(<CreateWorkerPopover open onClose={onClose} onCreate={onCreate} />);
+ await user.click(screen.getByRole('button', { name: 'orca.createWorker.submit' }));
+ expect(onCreate).toHaveBeenCalledOnce();
+ const close = screen.getByRole('button', { name: 'orca.createWorker.closeAria' }) as HTMLButtonElement;
+ expect(close.disabled).toBe(true);
+ await user.keyboard('{Escape}');
+ fireEvent.click(close);
+ expect(onClose).not.toHaveBeenCalled();
+ expect(screen.getByRole('dialog')).toBeTruthy();
+ await act(async () => finish());
+ expect(close.disabled).toBe(false);
+ await user.keyboard('{Escape}');
+ expect(onClose).toHaveBeenCalledOnce();
+ });
+
it('labels the worker role as a name and exposes an explanation', () => {
render(<CreateWorkerPopover open onClose={vi.fn()} onCreate={vi.fn()} />);
diff --git a/apps/desktop/src/renderer/hooks/useDialogExit.ts b/apps/desktop/src/renderer/hooks/useDialogExit.ts
new file mode 100644
index 0000000000..dd5886ce03
--- /dev/null
+++ b/apps/desktop/src/renderer/hooks/useDialogExit.ts
@@ -0,0 +1,42 @@
+import { useCallback, useEffect, useRef, useState, type RefObject } from 'react';
+
+/**
+ * For dialogs whose caller unmounts them in a completion/cancel callback. Let
+ * Radix Presence finish the CSS exit before handing control back to that caller.
+ * No timers: reduced motion and animation completion remain owned by Radix.
+ */
+export function useDialogExit(returnFocusRef?: RefObject<HTMLElement | null>) {
+ const [open, setOpen] = useState(true);
+ const openerRef = useRef<HTMLElement | null>(null);
+ const completionRef = useRef<(() => void) | null>(null);
+ const mountedRef = useRef(true);
+ useEffect(() => {
+ mountedRef.current = true;
+ return () => { mountedRef.current = false; };
+ }, []);
+
+ const close = useCallback((completion: () => void) => {
+ // An in-flight save can settle after the caller externally unmounted us.
+ if (!mountedRef.current) { completion(); return; }
+ if (completionRef.current) return;
+ completionRef.current = completion;
+ setOpen(false);
+ }, []);
+
+ const onOpenAutoFocus = useCallback(() => {
+ openerRef.current = document.activeElement instanceof HTMLElement
+ && document.activeElement !== document.body ? document.activeElement : null;
+ }, []);
+
+ const onCloseAutoFocus = useCallback((event: Event) => {
+ // These dialogs have no Radix Trigger. Its default would focus a null ref.
+ event.preventDefault();
+ const target = openerRef.current?.isConnected ? openerRef.current : returnFocusRef?.current;
+ if (target?.isConnected) target.focus({ preventScroll: true });
+ const completion = completionRef.current;
+ completionRef.current = null;
+ completion?.();
+ }, [returnFocusRef]);
+
+ return { open, close, onOpenAutoFocus, onCloseAutoFocus };
+}
diff --git a/docs/design-evidence/2026-10-05/handwritten-dialogs-radix.md b/docs/design-evidence/2026-10-05/handwritten-dialogs-radix.md
new file mode 100644
index 0000000000..0e3286a65f
--- /dev/null
+++ b/docs/design-evidence/2026-10-05/handwritten-dialogs-radix.md
@@ -0,0 +1,63 @@
+# Desktop 手写弹窗 Radix 迁移证据
+
+日期:2026-10-05。平台:macOS arm64 / 真实 Electron Desktop,1280 × 800 CSS px,DPR 2。
+基线:`24551276ff345b980533ba1c89274c6bb890b28d`(开工时最新 origin/main)。候选:`fix/desktop-handwritten-dialogs-radix` 上的补丁;最终提交 SHA 记录于草稿 PR 正文。
+
+## 逐项评估与行为对照
+
+| 对象 / 决定 | 迁移前:焦点、Tab、Esc、关闭与保存 | 迁移后与保留方式 |
+| --- | --- | --- |
+| AddProviderWizard / Dialog | 无统一初始焦点、Tab 限制或回焦;window Esc(保护 IME / keyCode 229)关闭整个向导;遮罩不关闭;实际保存用 savingRef 阻止取消和 Esc,授权取消走原 cancelAuthorize | 用户批准补齐:目录聚焦搜索,直达表单首个 input,无输入时首按钮;Radix 限制 Tab、最上层 Esc,IME / 保存门保留;退场后再 onClose / onDone / onOpenCustomForm,并回到原打开控件。 |
+| ProviderConnectionDialog 主表单 / Dialog | 首个 input,手写 Tab 循环,卸载回到 opener 或 returnFocusRef;window capture 唯一 Esc owner:图片中断确认 → 帮助 → runtimeFill / childLayer → 主表单;保护 IME / 已消费事件 / saving;遮罩不关闭,实际保存期间取消不能关;独立模型获取不锁表单 | 保留首个 input 与 returnFocusRef,Radix 接管 Tab / Presence / 回焦;保留原 window capture owner,主 Content 阻止 Radix 二次消费 Esc;子弹层、图片确认、测试连接和模型获取原样。实际保存成功待退场后再 onSaved,失败恢复原表单。 |
+| MermaidSourceEditor / Dialog | textarea 获焦、光标 0;无 Tab 限制 / 回焦;window Esc 和取消直接放弃草稿;dirty 控制保存 / Cmd+Enter,未修改时快捷键取消;遮罩不关闭;isVisible / RAF / 200ms timer 手写退场 | 保留 textarea / 光标、dirty / Cmd+Enter、body.dataset.mermaidEditorOpen 和取消语义;用户批准 Tab / 回焦与最上层 Esc;Presence 取代手写动画与计时,退场后保存 / 取消。原源码没有放弃修改二次确认,本次也不添加。保存退场后同步交给 applyEdit,无独立异步保存态。 |
+| CreateWorkerPopover / Dialog | 无初始焦点 / Tab 限制 / 回焦 / Esc owner;遮罩不关闭;× 在 onCreate promise 未完成时仍可关闭 | 用户批准角色 input 初始焦点、Tab / 最上层 Esc / 回焦,以及创建时禁止 × / Esc;失败后恢复。3 个生产调用点:OrcaWorkerPanel / CCAgentSessionView / NewMakerDraftRoute,均不传 className;入参留在 Overlay 原 shell。从 + 菜单打开时,菜单本来先回焦到编辑框,弹窗记录并归还该焦点;直接按钮入口归还按钮。 |
+| BrowserTabBody 崩溃提示 / 保留手写 | 标签页 slot 内 absolute 覆盖;无自动获焦 / Tab trap / Esc / 关闭回焦;重新加载或强制终止是恢复动作,无保存态 | 不是整窗模态。Radix 会错误锁定整个窗口焦点和滚动,所以不迁移;源码不变,HAND_BUILT_DIALOGS 仅保留该项并说明原因。 |
+| GhostCardLinkConfirm / AlertDialog | 取消 autoFocus;仅面板内 Esc 取消;BlockingScrim 阻止外部点击、不关闭;无 Tab trap / 回焦;打开与取消是同步结算,无保存态 | 保留取消初始焦点、按钮顺序和业务语义;用户批准 Tab / 最上层 Esc / 回焦;Cancel asChild + Presence,退出后结算一次。GhostCardPromptPanel / BlockingScrim 输入浮层保持原样。 |
+
+上述焦点补齐、最上层 Esc,以及 Worker 创建中关闭保护已在实现前得到用户确认。未调整外观、文案、业务提交参数或其他弹窗。
+
+## 规范与结构
+
+- DESIGN.md §4 Dialog & Modal:Overlay / Container 只复用 `.modal-scrim` / `.modal-panel`;保留宽度、层级、内边距与布局。Focus on open 保持原首输入 / Cancel;Closing affordance:每个 Dialog.Content 无条件 preventDefault onPointerDownOutside,AlertDialog 保留内建外部点击保护。
+- DESIGN.md §14.2 / §14.4 heavy overlay:共享关闭状态与 Radix Presence,不添加独立动效或计时器;开场 250ms、退场 150ms。减弱动效由既有 CSS / Presence 决定。
+- design-governance.md §6:真实客户端 Light / Dark 截图与 computed;§10 D5:只在真正保存期间禁止关闭,不锁连接测试 / 获取模型。
+- windowDrag.tsx:Overlay 在前、WINDOW_DRAG_STYLE,Content 在后、WINDOW_NO_DRAG_STYLE;中心定位使用 inset-0 + margin auto,避免 transform 居中导致 Electron no-drag 打孔偏位。Worker Content 在 Overlay 内,保留 className 的 shell 语义。
+- useDialogExit 只协调父级会立即卸载的弹窗:以 onCloseAutoFocus 的 Presence 生命周期回焦并结算 callback,不另造 timer / CSS / 弹窗 primitive。
+
+## 实机对照
+
+采用用户指定 `--region=cn --isolated=@worktree`;启动日志 `DESKTOP_DEV_VERDICT=ready`,desktop:whoami 确认独立 profile。未修改主仓未提交内容,未保存供应商、创建 Worker 或发送外链。
+基线截图是在同一 worktree 暂时装载 base 原版 5 个生产组件补采,之后恢复全部候选源码;全局样式与依赖相同。这是实际 Electron 生产组件渲染。
+
+Light / Dark 各 5 个弹窗、共 10 组 before / after:panel / scrim 的 x、y、width、height、background、border、borderRadius、shadow、padding、color 逐值一致。未宣称逐像素完全相同:新增焦点保障按批准落点呈现焦点态,背景内容可能动态变化。
+
+| 面板 | x, y(CSS px) | width × height(CSS px) | padding |
+| --- | --- | --- | --- |
+| wizard | 340, 80 | 600 × 640 | 0px |
+| provider | 340, 48 | 600 × 704 | 0px |
+| worker | 390, 131.5 | 500 × 537 | 24px |
+| ghost | 480, 323.5625 | 320 × 152.875 | 14px |
+| mermaid | 200, 80 | 880 × 640 | 0px |
+
+所有面板圆角 12px。Light:背景 `rgb(253, 253, 248)`,边框 `1px solid rgb(228, 228, 223)`,阴影 `rgba(0, 0, 0, 0.15) 0px 4px 16px 0px`,遮罩 `rgba(0, 0, 0, 0.5)`。Dark:背景 `rgb(31, 31, 31)`,边框 `1px solid rgb(49, 49, 49)`,阴影 `rgba(0, 0, 0, 0.5) 0px 4px 16px 0px`,遮罩 `rgba(0, 0, 0, 0.7)`。遮罩均 1280 × 800、无圆角与阴影。这些是实测值,不是新增 token。
+
+5 个弹窗两主题均实际读到 open 的 modal-scrim-in / modal-panel-in(0.25s),closed 的 modal-fade-out(0.15s),Presence 留到退场完成再卸载。窗口后台 Chromium 暂停动画时,采集计算值并推进实际 CSS Animation.finish(),切到前台复核完成,不派发伪造动画事件。Ghost 原 modal-panel-in-centered 转为共享 modal-panel-in,静止中心位置不变。
+
+执行者已目检上述 10 张候选截图,尺寸、布局、浅深主题与初始焦点正常。另以 CDP 鼠标 / Tab / Escape 复核 5 个弹窗的初始焦点、连续 Tab 不离开面板及关闭回焦;Worker 角色说明 Tip 是最上层,Esc 先关闭它,Tip 退场后 Esc 才关闭主面板。
+
+## 自动验证与缺口
+
+- `pnpm --filter desktop run --if-present typecheck`:通过。
+- `pnpm test:unit:related`:通过;新增 / 更新焦点、双向 Tab、Esc 层级、实际保存 / 创建期间关闭门、回焦、Mermaid 草稿与真实 Radix Presence 生命周期测试;cardShortcutYield 回归通过;dialogScrimDismissal 单独运行,6 项通过。
+- `pnpm check:design-colors --worktree` / `pnpm check:design-inventory` / `pnpm check:dev-docs` / `git diff --check`:通过。未改守卫门槛。
+- Windows 实机未验证:本机 macOS;no-drag 几何、系统窗口行为与无 blur 回退等待 Windows 复核。
+- 向导 / 供应商 / Worker 来自真实业务入口;Ghost / Mermaid 是真实 Electron 中临时挂载生产组件的测试入口,未跑完整插件 iframe 外链与 CodeMirror 文件编辑端到端路径。保存 / 创建成功失败门由可控 promise 单测覆盖,未做真实账号 mutation。
+- 截图 / JSON 本地目录 `artifacts/handwritten-dialogs`(Git 忽略),文件名 `{wizard,provider,worker,ghost,mermaid}-{light,dark}-{before,after}.{png,json}`;动画审计 `animation-audit.json`,键盘 / 回焦 `focus-real.json`。未提交截图、运行日志或测试替身。
+- 20 张公开图片已上传为 [cindy-fork Release 证据附件](https://github.com/kirozeng/cindy-fork/releases/tag/pr-5491-ui-evidence),并嵌入 [PR #5491 描述](https://github.com/makecindy/cindy/pull/5491):每个弹窗均有 Light / Dark × before / after。PNG 不进入代码提交历史;这是截图证据存储页,不是客户端版本发布。使用既有 GitHub CLI 登录上传 Release assets,无需网页登录。
+
+## 提交后复检(2026-10-05)
+
+- 简洁度检查删除 Ghost Cancel 上重复的手动 onClick,统一经 Radix Cancel → Root onOpenChange → useDialogExit 结算;取消 / Esc / 打开仍各只结算一次。清理测试的无用变量和无用 async suite 声明,不更改测试断言。
+- 重新运行 design-colors(包含实际 worktree)、design-inventory(52 surface)、dev-docs(10 项):通过。颜色 unexpected=0,报告项是既有表单采用提示与本证据实测 RGB 记录。
+- 清理后 Desktop typecheck 与 test:unit:related(40.1s)通过,git diff --check 通过。
+- 截图仍对应 `0ff0d015767491884ed2c2759233ed5c7c639e72`;本次清理只去掉重复处理,无外观变化。