Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(chat): 媒体 lightbox 键盘打开后焦点进入弹窗并圈禁 Tab
Kirozeng023bde86ac3a
diff --git a/apps/desktop/src/renderer/__tests__/chatMediaLightboxFocus.test.ts b/apps/desktop/src/renderer/__tests__/chatMediaLightboxFocus.test.tsnew file mode 100644index 0000000000..ae9b567ff2--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/chatMediaLightboxFocus.test.ts@@ -0,0 +1,94 @@+// @vitest-environment jsdom+/**+ * chatMediaLightboxFocus.test.ts — 图片/模型预览的键盘焦点契约。+ *+ * 与 chatVideoView.test.ts 对位,覆盖 review 指出的"image/model 路径同样+ * 没有把焦点移进 lightbox"的一半:不 mock ImageLightbox / ModelLightbox,+ * 用真实组件断言键盘打开后焦点进入弹窗(FocusScope 挂载焦点)、Esc 延迟+ * 关闭后回到预览触发器。图片路径同时保留 gallery 定位标记的既有断言。+ */+import React from 'react';+import { describe, expect, it, vi } from 'vitest';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';++vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string, fallback?: string) => fallback ?? key }),+}));++vi.mock('@/hooks/useRemoteMediaUrl', () => ({+ useRemoteMediaUrl: (url: string) => url,+}));++import { ChatImageView } from '../components/chat/ChatImageView';++describe('ChatImageView 键盘交互(真实 ImageLightbox / ModelLightbox)', () => {+ it('Enter 打开图片预览:焦点进入 lightbox,Esc 延迟关闭后回到触发器', async () => {+ render(+ React.createElement(ChatImageView, {+ src: 'xdt-image://control/focus.png',+ filename: 'focus.png',+ variant: 'tool-output',+ }),+ );+ const trigger = screen.getByRole('button', { name: 'focus.png' });+ trigger.focus();++ fireEvent.keyDown(trigger, { key: 'Enter' });+ // 注:gallery 定位标记(data-gallery-active)是瞬时信号——真实+ // ImageLightbox 挂载后立即清掉(见其 mount effect),这里断不到;它的+ // 设置路径由 chatImageView.test.ts 的 mock 用例覆盖。+ // 真实 ImageLightbox:portal 内出现 alt="" 的大图(触发器缩略图 alt 是+ // 文件名,不会撞)。+ const lightboxImg = document.body.querySelector('img[alt=""]');+ expect(lightboxImg).not.toBeNull();+ expect(lightboxImg?.getAttribute('src')).toBe('xdt-image://control/focus.png');++ // 焦点进入 lightbox(FocusScope 挂载焦点落在 overlay 根),不再留在被+ // 遮罩挡住的预览触发器上。+ expect(document.activeElement?.contains(lightboxImg as Element)).toBe(true);+ expect(document.activeElement).not.toBe(trigger);++ // Esc 延迟关闭:onClose 排在 200ms 渐隐后,此刻焦点仍在 lightbox 内。+ fireEvent.keyDown(document, { key: 'Escape' });+ expect(document.activeElement).not.toBe(trigger);++ await waitFor(() => expect(document.activeElement).toBe(trigger));+ expect(document.body.querySelector('img[alt=""]')).toBeNull();+ expect(screen.getByRole('button', { name: 'focus.png' })).toBeTruthy();+ });++ it('Enter 打开模型预览:焦点进入 lightbox,Esc 延迟关闭后回到触发器', async () => {+ render(+ React.createElement(ChatImageView, {+ src: 'cindy-media://blobs/' + 'e'.repeat(64) + '.png',+ filename: 'model-preview.png',+ variant: 'tool-output',+ modelFile: {+ provider: 'cindy',+ url: 'cindy-media://blobs/' + 'f'.repeat(64) + '.glb',+ format: 'GLB',+ },+ }),+ );+ const trigger = screen.getByRole('button', { name: 'model-preview.png' });+ trigger.focus();++ fireEvent.keyDown(trigger, { key: 'Enter' });+ // 真实 ModelLightbox:portal 内出现 <model-viewer>(jsdom 不升级自定义+ // 元素,但节点在场)。+ const modelViewer = document.body.querySelector('model-viewer');+ expect(modelViewer).not.toBeNull();++ // 焦点进入 lightbox(FocusScope 挂载焦点落在 overlay 根)。+ expect(document.activeElement?.contains(modelViewer as Element)).toBe(true);+ expect(document.activeElement).not.toBe(trigger);++ // Esc 延迟关闭后回到触发器。+ fireEvent.keyDown(document, { key: 'Escape' });+ expect(document.activeElement).not.toBe(trigger);++ await waitFor(() => expect(document.activeElement).toBe(trigger));+ expect(document.body.querySelector('model-viewer')).toBeNull();+ expect(screen.getByRole('button', { name: 'model-preview.png' })).toBeTruthy();+ });+});diff --git a/apps/desktop/src/renderer/__tests__/chatVideoView.test.ts b/apps/desktop/src/renderer/__tests__/chatVideoView.test.tsindex 4af21513b6..af26c4542f 100644--- a/apps/desktop/src/renderer/__tests__/chatVideoView.test.ts+++ b/apps/desktop/src/renderer/__tests__/chatVideoView.test.ts@@ -5,9 +5,9 @@* 与 chatImageView.test.ts 的图片键盘用例对位,但不 mock VideoLightbox:* 真实组件的 onClose 排在 200ms fade-out 的 setTimeout 之后(见* VideoLightbox.handleClose),同步调用 onClose 的 mock 覆盖不到这条时序。- * 断言顺序刻意是「Esc 关闭瞬间焦点还在 lightbox → 200ms 后回到触发器」,- * 锁住"键盘打开 + 延迟关闭 + 关闭后焦点恢复"这条无障碍路径,防止弹窗- * 关闭时序或触发器挂载逻辑调整时静默退化。+ * 用例覆盖:键盘打开、焦点进入 lightbox(FocusScope)并圈禁 Tab、Esc 延迟+ * 关闭后焦点回到预览触发器——锁住整条无障碍路径,防止弹窗关闭时序或触发+ * 器挂载逻辑调整时静默退化。*/import React from 'react';import { afterEach, describe, expect, it, vi } from 'vitest';@@ -31,7 +31,7 @@ describe('ChatVideoView 键盘交互(真实 VideoLightbox)', () => {__resetMediaBusForTests();});- it.each(['Enter', ' '])('键盘 %s 打开视频预览,Esc 延迟关闭后焦点回到触发器', async (key) => {+ it.each(['Enter', ' '])('键盘 %s 打开视频预览:焦点进入 lightbox 并圈禁,Esc 延迟关闭后回到触发器', async (key) => {render(React.createElement(ChatVideoView, {src: 'xdt-video://control/clip.mp4',@@ -49,14 +49,25 @@ describe('ChatVideoView 键盘交互(真实 VideoLightbox)', () => {const backdrop = screen.getByRole('button', { name: 'chat.lightbox.close' });const lightboxVideo = document.body.querySelector('video[controls]');expect(lightboxVideo).not.toBeNull();- expect(lightboxVideo?.getAttribute('src')).toBe('xdt-video://control/clip.mp4');+ const videoEl = lightboxVideo as HTMLVideoElement;+ expect(videoEl.getAttribute('src')).toBe('xdt-video://control/clip.mp4');- // 焦点先挪进 lightbox 再用 Esc 关闭,焦点恢复的断言才有区分度。- backdrop.focus();- fireEvent.keyDown(document, { key: 'Escape' });- // 延迟关闭契约:onClose 排在 200ms fade-out 之后,此刻尚未执行,焦点- // 仍在 lightbox 上——同步 onClose 的 mock 走不到这一步。+ // 焦点进入 lightbox:打开后 FocusScope 把焦点给 <video>(Space 暂停 /+ // 方向键 seek 立即可用),不再留在被遮罩挡住的预览触发器上。+ expect(document.activeElement).toBe(videoEl);+ expect(document.activeElement).not.toBe(trigger);++ // Tab 圈禁:焦点在 lightbox 内首尾循环(overlay DOM 顺序 backdrop 在前、+ // video 在后),不漏到背后的聊天控件。+ fireEvent.keyDown(videoEl, { key: 'Tab' });expect(document.activeElement).toBe(backdrop);+ fireEvent.keyDown(backdrop, { key: 'Tab', shiftKey: true });+ expect(document.activeElement).toBe(videoEl);++ // Esc 关闭(onClose 排在 200ms 渐隐后,此刻焦点仍在 lightbox 内——同步+ // onClose 的 mock 走不到这一步)。+ fireEvent.keyDown(document, { key: 'Escape' });+ expect(document.activeElement).not.toBe(trigger);await waitFor(() => expect(document.activeElement).toBe(trigger));// 关闭完成后 lightbox 卸载,预览触发器仍在原位。diff --git a/apps/desktop/src/renderer/components/chat/ImageLightbox.tsx b/apps/desktop/src/renderer/components/chat/ImageLightbox.tsxindex 1c53ef15c1..4354f4f7ba 100644--- a/apps/desktop/src/renderer/components/chat/ImageLightbox.tsx+++ b/apps/desktop/src/renderer/components/chat/ImageLightbox.tsx@@ -27,6 +27,7 @@* 复用本组件(文件浏览器 / 输入框预览)拿到默认值 undefined,不显示该动作。* - 右键:菜单关闭后的同一次背景点击不能顺带关闭 lightbox,见 `lastMenuCloseAt`。* - 动画:200ms 透明度淡入淡出。+ * - 焦点:FocusScope 打开时把焦点移入 overlay 并圈禁 Tab;卸载时还给打开前的焦点元素。* - 滚动锁定:打开期间给 `[data-scroll-container]` 设置 `overflowY: hidden`。* - 关闭按钮:按设计不显示 X 关闭按钮。* - 会话画廊:`enableGallery` 开启后,可用 ←/→ 或屏幕箭头在会话图片间翻页,并显示@@ -37,6 +38,7 @@import { useCallback, useContext, useEffect, useRef, useState } from 'react';import { createPortal } from 'react-dom';+import { FocusScope } from '@radix-ui/react-focus-scope';import {Check,ChevronLeft,@@ -1070,7 +1072,22 @@ export function ImageLightbox({// 遮罩颜色走统一 token,不再按 Light / Dark 分支判断。const overlay = (- // biome-ignore lint/a11y/noStaticElementInteractions lint/a11y/useKeyWithClickEvents: 全屏 overlay 的键盘关闭由全局 Escape 处理;点击关闭是 lightbox 本身的交互。+ // FocusScope(trapped+loop):键盘打开后焦点进入弹窗并圈禁在内,Tab 不再+ // 穿过被遮挡的聊天控件。挂载焦点给 overlay 根(tabIndex=-1 由 FocusScope+ // 合入,全局 outline:none 保证不闪全屏焦点框):Enter 不触发任何动作,+ // Tab 依次到达工具栏/翻页按钮;卸载时 FocusScope 默认把焦点还给打开前+ // 的元素(ChatImageView 键盘路径 = 预览触发器,与 onClose 里的显式恢复+ // 指向同一元素)。+ <FocusScope+ asChild+ trapped+ loop+ onMountAutoFocus={(event) => {+ event.preventDefault();+ overlayRef.current?.focus();+ }}+ >+ {/* biome-ignore lint/a11y/noStaticElementInteractions lint/a11y/useKeyWithClickEvents: 全屏 overlay 的键盘关闭由全局 Escape 处理;点击关闭是 lightbox 本身的交互。 */}<divref={overlayRef}style={{@@ -1420,6 +1437,7 @@ export function ImageLightbox({</>) : null}</div>+ </FocusScope>);return createPortal(overlay, document.body);diff --git a/apps/desktop/src/renderer/components/chat/ModelLightbox.tsx b/apps/desktop/src/renderer/components/chat/ModelLightbox.tsxindex 4ce92609a2..6a7a277acf 100644--- a/apps/desktop/src/renderer/components/chat/ModelLightbox.tsx+++ b/apps/desktop/src/renderer/components/chat/ModelLightbox.tsx@@ -20,10 +20,13 @@* - Esc closes; click on overlay background closes; click on the model* itself does NOT close (we need rotate/zoom gestures without dismissing)* - Right-click → 打开模型 / 打开模型所在目录+ * - Focus: FocusScope moves focus into the overlay on open, traps Tab+ * inside, and returns focus to the pre-open element on unmount.*/import { useCallback, useEffect, useRef, useState } from 'react';import { createPortal } from 'react-dom';+import { FocusScope } from '@radix-ui/react-focus-scope';import { Box, FolderOpen } from 'lucide-react';import { useTranslation } from 'react-i18next';import { toast } from '@/lib/toast';@@ -76,6 +79,8 @@ export function ModelLightbox({ source, onClose }: ModelLightboxProps) {source.kind === 'local' ? toLocalFileUrl(source.absPath) : source.url,);const modelViewerRef = useRef<HTMLElement | null>(null);+ // FocusScope 挂载焦点的落点:overlay 根(tabIndex=-1 由 FocusScope 合入)。+ const overlayRef = useRef<HTMLDivElement | null>(null);// "open" / "reveal" 正在执行时禁用菜单, 避免重复点击。Mirror ChatImageView。const [modelPending, setModelPending] = useState<'open' | 'reveal' | null>(null);@@ -186,7 +191,23 @@ export function ModelLightbox({ source, onClose }: ModelLightboxProps) {}const overlay = (+ // FocusScope(trapped+loop):键盘打开后焦点进入弹窗并圈禁,Tab 不穿过被+ // 遮挡的聊天控件。挂载焦点给 overlay 根(全局 outline:none 不闪全屏焦+ // 点框),Tab 下一站是 backdrop 关闭按钮;卸载时 FocusScope 默认把焦点+ // 还给打开前的元素(ChatImageView 键盘路径 = 预览触发器)。handleClose+ // 里既有的 blur 仍保留——点进模型后 model-viewer shadow DOM 的焦点框+ // 要在淡出前先灭掉。+ <FocusScope+ asChild+ trapped+ loop+ onMountAutoFocus={(event) => {+ event.preventDefault();+ overlayRef.current?.focus();+ }}+ ><div+ ref={overlayRef}style={{position: 'fixed',inset: 0,@@ -334,6 +355,7 @@ export function ModelLightbox({ source, onClose }: ModelLightboxProps) {</DropdownMenuContent></DropdownMenu></div>+ </FocusScope>);return createPortal(overlay, document.body);diff --git a/apps/desktop/src/renderer/components/chat/VideoLightbox.tsx b/apps/desktop/src/renderer/components/chat/VideoLightbox.tsxindex 2cb01ea9a3..a9c620f598 100644--- a/apps/desktop/src/renderer/components/chat/VideoLightbox.tsx+++ b/apps/desktop/src/renderer/components/chat/VideoLightbox.tsx@@ -5,6 +5,8 @@* but adapted for <video>:** - Overlay: rgba(0,0,0,0.85), 200ms fade, scroll lock on data-scroll-container+ * - Focus: FocusScope moves focus to <video> on open, traps Tab inside the+ * overlay, and returns focus to the pre-open element on unmount.* - Esc key closes (same gesture suppression as ImageLightbox for menu close)* - Background click closes; click ON the <video controls> region does NOT* close (users need to drag the seek bar / hit pause without dismissing).@@ -16,6 +18,7 @@import { useCallback, useEffect, useRef, useState } from 'react';import { createPortal } from 'react-dom';+import { FocusScope } from '@radix-ui/react-focus-scope';import { Copy, FolderOpen } from 'lucide-react';import { useTranslation } from 'react-i18next';import { toast } from '@/lib/toast';@@ -101,6 +104,21 @@ export function VideoLightbox({ src, onClose }: VideoLightboxProps) {}const overlay = (+ // FocusScope(trapped+loop):键盘打开后焦点必须进入弹窗并圈禁在内——+ // 否则焦点留在 z-index 9999 遮罩背后的预览触发器上,Tab 会穿过被遮挡+ // 的聊天控件,视频 controls 也够不着。挂载时焦点直接给 <video>(Space+ // 暂停 / 方向键 seek 立即可用);卸载时 FocusScope 默认把焦点还给打开+ // 前的元素(ChatVideoView 键盘路径 = 预览触发器,与 onClose 里的显式+ // 恢复指向同一元素)。+ <FocusScope+ asChild+ trapped+ loop+ onMountAutoFocus={(event) => {+ event.preventDefault();+ videoRef.current?.focus();+ }}+ ><divstyle={{position: 'fixed',@@ -139,6 +157,9 @@ export function VideoLightbox({ src, onClose }: VideoLightboxProps) {autoPlaylooppreload="auto"+ // controls 视频在 Chromium 本就在 Tab 序里;显式写出是为了 jsdom 单测+ // (jsdom 只认带 tabindex 的元素可聚焦,焦点进入 lightbox 的断言依赖它)。+ tabIndex={0}style={{maxWidth: 'calc(100vw - 80px)',maxHeight: 'calc(100vh - 80px)',@@ -198,6 +219,7 @@ export function VideoLightbox({ src, onClose }: VideoLightboxProps) {</DropdownMenu>) : null}</div>+ </FocusScope>);return createPortal(overlay, document.body);