Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 修复视频原生全屏与全屏右键菜单
DavidShen2c8869c2759b
diff --git a/apps/desktop/scripts/fixtures/chat-video/chat-video-fixture.tsx b/apps/desktop/scripts/fixtures/chat-video/chat-video-fixture.tsxnew file mode 100644index 0000000000..3d7b33a89f--- /dev/null+++ b/apps/desktop/scripts/fixtures/chat-video/chat-video-fixture.tsx@@ -0,0 +1,51 @@+import { mountPage } from '../../ui-page/harness';+import { ChatVideoView } from '../../../src/renderer/components/chat/ChatVideoView';+import { VideoLightbox } from '../../../src/renderer/components/chat/VideoLightbox';+import { useLayoutEffect } from 'react';+import '../../../src/renderer/components/chat/rich-answer.css';++// Anonymous 640 x 360 VP8 sample: ffmpeg -f lavfi -i color=c=gray:s=640x360:r=5 -t 1 -c:v libvpx -f webm pipe:1.+// Keep decoding deterministic in hidden Electron windows; no user media or network.+const src =+ 'data:video/webm;base64,GkXfowEAAAAAAAAfQoaBAUL3gQFC8oEEQvOBCEKChHdlYm1Ch4ECQoWBAhhTgGcB/////////xFNm3RALE27i1OrhBVJqWZTrIHlTbuMU6uEFlSua1OsggEjTbuMU6uEElTDZ1OsggFs7AEAAAAAAACqAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmAQAAAAAAADIq17GDD0JATYCNTGF2ZjU4LjI0LjEwMVdBjUxhdmY1OC4yNC4xMDFEiYhAj0AAAAAAABZUrmsBAAAAAAAAPa4BAAAAAAAANNeBA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k5w9k5w9k5w9k5w9k5w9k5w9k5w9k5w9k5w9k5w9k5w9k5w9k5w9k5w9kUAD+aAA=';++function MenuSample({ lightbox }: { lightbox: boolean }) {+ useLayoutEffect(() => {+ // Keep a local-media identity for the production menu, supply anonymous bytes+ // directly because the isolated UI runner has no Cindy protocol handlers.+ document.querySelector('video')!.src = src;+ }, []);+ const localSrc = 'cindy-media://blobs/ui-video.webm';+ return (+ <>+ {lightbox ? (+ <VideoLightbox src={localSrc} onClose={() => { document.body.dataset.videoLightboxClosed = 'true'; }} />+ ) : (+ <ChatVideoView src={localSrc} filename="Menu sample" variant="tool-output" />+ )}+ </>+ );+}++mountPage({+ host: {+ copyMediaToClipboard: async () => {+ document.body.dataset.videoMenuAction = 'copy';+ return { success: true };+ },+ showItemInFolder: async () => {+ document.body.dataset.videoMenuAction = 'reveal';+ return { success: true };+ },+ },+ render: (ctx) =>+ ctx.case.startsWith('menu-') ? (+ <MenuSample lightbox={ctx.case === 'menu-lightbox'} />+ ) : (+ <div className="rich-answer p-6">+ <div className="rich-answer-media">+ <ChatVideoView src={src} filename="Playback sample" variant="tool-output" />+ </div>+ </div>+ ),+});diff --git a/apps/desktop/scripts/fixtures/chat-video/ui-page.mjs b/apps/desktop/scripts/fixtures/chat-video/ui-page.mjsnew file mode 100644index 0000000000..43c5f6378e--- /dev/null+++ b/apps/desktop/scripts/fixtures/chat-video/ui-page.mjs@@ -0,0 +1,93 @@+import assert from 'node:assert/strict';++export default {+ name: 'chat-video',+ entry: './chat-video-fixture.tsx',+ viewport: { width: 800, height: 600 },+ real: 'ChatVideoView, native playback controls, real WebM decoding, retry, light/dark themes and five languages',+ notCovered:+ 'Electron fullscreen permission and OS transitions require the full Desktop sandbox; clipboard/folder APIs are fakes and local protocol bytes are supplied by the fixture.',+ cases: {+ default: {+ about: 'Inline player retains the original native playback and fullscreen controls',+ },+ error: {+ about:+ 'Media errors show an unavailable state and a working Retry action, without claiming the file was deleted',+ },+ 'menu-inline': {+ about: 'Local video context menu stays visible and clickable above native fullscreen',+ },+ 'menu-lightbox': {+ about: 'Lightbox uses the same fullscreen menu and keeps focus inside the player',+ },+ },+ async ready(page) {+ await page.waitForFunction(() => document.querySelector('video')?.readyState >= 2);+ },+ async check(page, ui) {+ if (ui.case.startsWith('menu-')) {+ // Playwright evaluation carries a user gesture; use the real Fullscreen API.+ await page.locator('video').evaluate((video) => video.requestFullscreen());+ await page.waitForFunction(() => document.fullscreenElement?.tagName === 'VIDEO');+ await page.locator('video').click({ button: 'right', position: { x: 250, y: 150 } });+ const menu = page.getByRole('menu');+ await menu.waitFor({ state: 'visible' });+ await ui.capture('fullscreen-menu');+ const hit = await menu.evaluate((el) => {+ const rect = el.getBoundingClientRect();+ const target = document.elementFromPoint(rect.x + rect.width / 2, rect.y + rect.height / 2);+ return { open: el.closest('dialog')?.matches(':modal'), contains: el.contains(target) };+ });+ assert.ok(hit.open && hit.contains, JSON.stringify(hit));+ await page+ .getByRole('menuitem', { name: await ui.t('chat.media.copyVideo'), exact: true })+ .click();+ await page.waitForFunction(+ () => document.body.dataset.videoMenuAction === 'copy' && !document.querySelector('dialog'),+ );+ assert.ok(await page.evaluate(() => document.fullscreenElement?.tagName === 'VIDEO'));+ await page.waitForFunction(() => document.activeElement?.tagName === 'VIDEO');+ await page.locator('video').click({ button: 'right', position: { x: 250, y: 150 } });+ await menu.waitFor({ state: 'visible' });+ await page.keyboard.press('Escape');+ await page.waitForFunction(() => !document.querySelector('dialog'));+ assert.ok(await page.locator('video').evaluate(video => getComputedStyle(video.parentElement).opacity !== '0'));+ assert.ok(await page.evaluate(() => !document.body.dataset.videoLightboxClosed));+ if (!await page.evaluate(() => Boolean(document.fullscreenElement))) {+ await page.locator('video').evaluate(video => video.requestFullscreen());+ }+ await page.locator('video').click({ button: 'right', position: { x: 250, y: 150 } });+ await menu.waitFor({ state: 'visible' });+ await page.mouse.click(40, 40);+ await page.waitForFunction(() => !document.querySelector('dialog'));+ await page.locator('video').click({ button: 'right', position: { x: 250, y: 150 } });+ await menu.waitFor({ state: 'visible' });+ await page.evaluate(() => document.exitFullscreen());+ await page.waitForFunction(+ () => !document.fullscreenElement && !document.querySelector('dialog'),+ );+ await page.locator('video').click({ button: 'right' });+ await page+ .getByRole('menuitem', { name: await ui.t('chat.media.revealVideo'), exact: true })+ .click();+ await page.waitForFunction(() => document.body.dataset.videoMenuAction === 'reveal');+ return;+ }+ if (ui.case === 'error') {+ await page.locator('video').evaluate((video) => video.dispatchEvent(new Event('error')));+ assert.ok(+ await page+ .getByText(await ui.t('chat.media.videoUnavailable'), { exact: true })+ .isVisible(),+ );+ await ui.capture('unavailable');+ await page+ .getByRole('button', { name: await ui.t('chat.errorBanner.retry'), exact: true })+ .click();+ await page.waitForFunction(() => document.querySelector('video')?.readyState >= 2);+ return;+ }+ assert.ok(await page.locator('video').evaluate((video) => video.controls));+ },+};diff --git a/apps/desktop/scripts/ui-page/electron.cjs b/apps/desktop/scripts/ui-page/electron.cjsindex 0375c2069a..ae079cadca 100644--- a/apps/desktop/scripts/ui-page/electron.cjs+++ b/apps/desktop/scripts/ui-page/electron.cjs@@ -9,7 +9,7 @@ if (![profile, bundleDir, evidenceDir].every((dir) => dir && path.isAbsolute(dirthrow new Error('Missing isolated UI profile, bundle or evidence directory');// Same policy the runner sends with the page document in Chromium mode.const csp =- "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'none'; object-src 'none'; frame-src 'none'; base-uri 'none'; form-action 'none'";+ "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; media-src 'self' data: blob:; font-src 'self' data:; connect-src 'none'; object-src 'none'; frame-src 'none'; base-uri 'none'; form-action 'none'";fs.mkdirSync(profile, { recursive: true });app.setPath('userData', profile);app.setPath('sessionData', profile);diff --git a/apps/desktop/scripts/ui-page/run.mjs b/apps/desktop/scripts/ui-page/run.mjsindex 8b9af4d169..1c34e9558f 100644--- a/apps/desktop/scripts/ui-page/run.mjs+++ b/apps/desktop/scripts/ui-page/run.mjs@@ -16,7 +16,7 @@ import { reloadPage } from './registry.mjs';const require = createRequire(import.meta.url);export const origin = 'http://cindy-ui.test';const csp =- "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'none'; object-src 'none'; frame-src 'none'; base-uri 'none'; form-action 'none'";+ "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; media-src 'self' data: blob:; font-src 'self' data:; connect-src 'none'; object-src 'none'; frame-src 'none'; base-uri 'none'; form-action 'none'";const git = (args) =>execFileSync('git', args, {diff --git a/apps/desktop/src/main/remote-desktop/__tests__/captureWindow.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/captureWindow.test.tsindex 51aa3fe84d..c7e4cdf563 100644--- a/apps/desktop/src/main/remote-desktop/__tests__/captureWindow.test.ts+++ b/apps/desktop/src/main/remote-desktop/__tests__/captureWindow.test.ts@@ -185,7 +185,16 @@ it('denies app display/legacy capture while preserving physical microphone and cexpect(reply).toHaveBeenLastCalledWith(true);request(voice, 'media', reply, { ...details, mediaTypes: ['audio'] });expect(reply).toHaveBeenLastCalledWith(true);- for (const permission of ['notifications', 'geolocation', 'midi', 'hid', 'display-capture', 'unknown']) {+ // Regression: the capture filter also denied the native video Fullscreen API.+ // Tier 1: real permission handlers must allow host playback but keep automatic+ // entry, foreign frames, voice windows and desktop capture denied.+ expect(check(owner, 'fullscreen', '', details)).toBe(true);+ request(owner, 'fullscreen', reply, details);+ expect(reply).toHaveBeenLastCalledWith(true);+ expect(check(voice, 'fullscreen', '', details)).toBe(false);+ request(voice, 'fullscreen', reply, details);+ expect(reply).toHaveBeenLastCalledWith(false);+ for (const permission of ['automatic-fullscreen', 'notifications', 'geolocation', 'midi', 'hid', 'display-capture', 'unknown']) {expect(check(owner, permission, '', details)).toBe(false);request(owner, permission, reply, details);expect(reply).toHaveBeenLastCalledWith(false);@@ -200,6 +209,9 @@ it('denies app display/legacy capture while preserving physical microphone and cexpect(check(candidate, 'media', '', { ...requestDetails, mediaType: 'audio' })).toBe(false);request(candidate, 'media', reply, { ...requestDetails, mediaTypes: ['audio'] });expect(reply).toHaveBeenLastCalledWith(false);+ expect(check(candidate, 'fullscreen', '', requestDetails)).toBe(false);+ request(candidate, 'fullscreen', reply, requestDetails);+ expect(reply).toHaveBeenLastCalledWith(false);}expect(check(owner, 'clipboard-sanitized-write', '', details)).toBe(true);request(owner, 'clipboard-sanitized-write', reply, details);diff --git a/apps/desktop/src/main/remote-desktop/capturePermissions.ts b/apps/desktop/src/main/remote-desktop/capturePermissions.tsindex 2f958ad41c..ee29a761e4 100644--- a/apps/desktop/src/main/remote-desktop/capturePermissions.ts+++ b/apps/desktop/src/main/remote-desktop/capturePermissions.ts@@ -8,27 +8,29 @@ export function denyAppDesktopCapture(ses: Session,isVoiceInputOwner: (owner: WebContents) => boolean = () => false,): void {- const trusted = (owner: WebContents | null, details: { isMainFrame: boolean; requestingUrl?: string }) => {+ const trusted = (owner: WebContents | null, details: { isMainFrame: boolean; requestingUrl?: string }, allowVoiceInput: boolean) => {if (!owner || owner.isDestroyed() || !details.isMainFrame || details.requestingUrl !== owner.mainFrame.url)return false;const win = BrowserWindow.fromWebContents(owner);- return isTrustedAppRendererWindow(win) || (isVoiceInputOwner(owner) && isTrustedCindyRendererWindow(win));+ return isTrustedAppRendererWindow(win) || (allowVoiceInput && isVoiceInputOwner(owner) && isTrustedCindyRendererWindow(win));};ses.setDisplayMediaRequestHandler((_request, callback) => callback({}));ses.setPermissionCheckHandler((owner, permission, _origin, details) => {- if (!trusted(owner, details)) return false;+ if (!trusted(owner, details, permission !== 'fullscreen')) return false;if (permission === 'media')return details.mediaType === 'audio' || details.mediaType === 'video';- return permission === 'clipboard-sanitized-write';+ // Native video controls use Fullscreen API permission, not display capture.+ // Keep Chromium's user-gesture requirement (automatic-fullscreen stays denied).+ return permission === 'clipboard-sanitized-write' || permission === 'fullscreen';});ses.setPermissionRequestHandler((owner, permission, callback, details) => {- if (!trusted(owner, details)) return callback(false);+ if (!trusted(owner, details, permission !== 'fullscreen')) return callback(false);if (permission === 'media') {const types = 'mediaTypes' in details ? details.mediaTypes : undefined;return callback(Boolean(types?.length && types.every((type) => type === 'audio' || type === 'video')),);}- callback(permission === 'clipboard-sanitized-write');+ callback(permission === 'clipboard-sanitized-write' || permission === 'fullscreen');});}diff --git a/apps/desktop/src/renderer/components/chat/ChatVideoView.tsx b/apps/desktop/src/renderer/components/chat/ChatVideoView.tsxindex 3634f905be..0e85ce885f 100644--- a/apps/desktop/src/renderer/components/chat/ChatVideoView.tsx+++ b/apps/desktop/src/renderer/components/chat/ChatVideoView.tsx@@ -1,5 +1,5 @@-/** Chat-stream video player. Native controls keep play, pause and seeking in- * the message; fullscreen remains the browser player's optional action. */+/** Chat-stream video player. Keep the browser controls, including native video+ * fullscreen, so its icon, position, keyboard handling and playback stay native. */import { CHAT_FOCUS_CLASS } from './chatChrome';import { useEffect, useRef, useState } from 'react';@@ -14,8 +14,10 @@ import {DropdownMenuTrigger,} from '@/components/ui/dropdown-menu';import { Tooltip } from '@/components/ui/tooltip';+import { Button } from '@/components/ui/button';import { useRemoteMediaUrl } from '@/hooks/useRemoteMediaUrl';import { registerMedia } from '@/lib/mediaPlaybackBus';+import { useVideoContextMenu } from './useVideoContextMenu';export type ChatVideoVariant = 'tool-output';@@ -41,8 +43,7 @@ const VARIANT_STYLES: Record<// (50vw/40vh 相对窗口,列宽约束只有这档提供);maxHeight 收紧到// min(40vh, 420px) 防竖版视频占半屏。与 ChatImageView 保持一致。style: { maxWidth: 'min(100%, 50vw, 480px)', maxHeight: 'min(40vh, 420px)', height: 'auto' },- className:- 'rounded-xl border border-[var(--msg-tool-card-border)] object-contain',+ className: 'rounded-xl border border-[var(--msg-tool-card-border)] object-contain',},};@@ -50,10 +51,15 @@ export function ChatVideoView({ src, filename, variant, sessionId }: ChatVideoViconst { t } = useTranslation();const videoRef = useRef<HTMLVideoElement>(null);const [failedSrc, setFailedSrc] = useState<string | null>(null);- const [menuPos, setMenuPos] = useState<{ x: number; y: number } | null>(null);// 远程会话改写到 cindy-remote-media://(OSS range 流式);本地原样。下游统一用 displaySrc。const displaySrc = useRemoteMediaUrl(src, sessionId);- useEffect(() => { setFailedSrc(null); }, [displaySrc]);+ const { menuPos, setMenuPos, portalContainer, restoreVideoFocus } = useVideoContextMenu(+ videoRef,+ displaySrc,+ );+ useEffect(() => {+ setFailedSrc(null);+ }, [displaySrc]);// Navigation and hidden/recycled rows must not leave an invisible player running.useEffect(() => {@@ -61,12 +67,19 @@ export function ChatVideoView({ src, filename, variant, sessionId }: ChatVideoViif (!video) return;const unregister = registerMedia(video);const observer = new IntersectionObserver(([entry]) => {- if (!entry.isIntersecting) video.pause();+ if (!entry.isIntersecting && document.fullscreenElement !== video) video.pause();});- const onVisibility = () => { if (document.hidden) video.pause(); };+ const onVisibility = () => {+ if (document.hidden) video.pause();+ };observer.observe(video);document.addEventListener('visibilitychange', onVisibility);- return () => { unregister(); observer.disconnect(); document.removeEventListener('visibilitychange', onVisibility); video.pause(); };+ return () => {+ unregister();+ observer.disconnect();+ document.removeEventListener('visibilitychange', onVisibility);+ video.pause();+ };}, [displaySrc, failedSrc]);// A transient failure should recover when the window/network becomes available;@@ -76,11 +89,14 @@ export function ChatVideoView({ src, filename, variant, sessionId }: ChatVideoViconst retry = () => setFailedSrc(null);window.addEventListener('online', retry);window.addEventListener('focus', retry);- return () => { window.removeEventListener('online', retry); window.removeEventListener('focus', retry); };+ return () => {+ window.removeEventListener('online', retry);+ window.removeEventListener('focus', retry);+ };}, [displaySrc, failedSrc]);if (failedSrc === displaySrc) {- return <VideoMissingPlaceholder filename={filename} />;+ return <VideoUnavailablePlaceholder filename={filename} onRetry={() => setFailedSrc(null)} />;}const { style, className } = VARIANT_STYLES[variant];@@ -133,6 +149,7 @@ export function ChatVideoView({ src, filename, variant, sessionId }: ChatVideoVi</div>{canRevealInFolder ? (<DropdownMenu+ modal={!portalContainer}open={menuPos !== null}onOpenChange={(open) => {if (!open) setMenuPos(null);@@ -152,7 +169,13 @@ export function ChatVideoView({ src, filename, variant, sessionId }: ChatVideoVi}}/></DropdownMenuTrigger>- <DropdownMenuContent align="start" sideOffset={2}>+ <DropdownMenuContent+ align="start"+ sideOffset={2}+ portalContainer={portalContainer}+ style={portalContainer ? { pointerEvents: 'auto' } : undefined}+ onCloseAutoFocus={restoreVideoFocus}+ ><DropdownMenuItem onClick={handleCopyVideo}><Copy className="mr-2 h-4 w-4" />{t('chat.media.copyVideo')}@@ -168,11 +191,12 @@ export function ChatVideoView({ src, filename, variant, sessionId }: ChatVideoVi);}-interface VideoMissingPlaceholderProps {+interface VideoUnavailablePlaceholderProps {filename: string;+ onRetry: () => void;}-function VideoMissingPlaceholder({ filename }: VideoMissingPlaceholderProps) {+function VideoUnavailablePlaceholder({ filename, onRetry }: VideoUnavailablePlaceholderProps) {const { t } = useTranslation();return (<div@@ -189,12 +213,13 @@ function VideoMissingPlaceholder({ filename }: VideoMissingPlaceholderProps) {<div className="text-xs font-medium">{t('chat.media.videoUnavailable')}</div><Tooltip.Root><Tooltip.Trigger asChild>- <div className="max-w-full truncate text-11 text-[var(--text-tertiary)]">- {filename}- </div>+ <div className="max-w-full truncate text-11 text-[var(--text-tertiary)]">{filename}</div></Tooltip.Trigger><Tooltip.Content variant="mono">{filename}</Tooltip.Content></Tooltip.Root>+ <Button variant="secondary" size="sm" compact onClick={onRetry}>+ {t('chat.errorBanner.retry')}+ </Button></div>);}diff --git a/apps/desktop/src/renderer/components/chat/VideoLightbox.tsx b/apps/desktop/src/renderer/components/chat/VideoLightbox.tsxindex a9c620f598..4029847015 100644--- a/apps/desktop/src/renderer/components/chat/VideoLightbox.tsx+++ b/apps/desktop/src/renderer/components/chat/VideoLightbox.tsx@@ -29,6 +29,7 @@ import {DropdownMenuTrigger,} from '@/components/ui/dropdown-menu';import { registerMedia } from '@/lib/mediaPlaybackBus';+import { useVideoContextMenu } from './useVideoContextMenu';interface VideoLightboxProps {src: string;@@ -40,7 +41,7 @@ export function VideoLightbox({ src, onClose }: VideoLightboxProps) {const [isVisible, setIsVisible] = useState(false);const isClosingRef = useRef(false);const videoRef = useRef<HTMLVideoElement | null>(null);- const [menuPos, setMenuPos] = useState<{ x: number; y: number } | null>(null);+ const { menuPos, setMenuPos, portalContainer, restoreVideoFocus } = useVideoContextMenu(videoRef, src);const lastMenuCloseAt = useRef(0);const handleClose = useCallback(() => {@@ -179,12 +180,15 @@ export function VideoLightbox({ src, onClose }: VideoLightboxProps) {setMenuPos({ x: e.clientX, y: e.clientY });}}onError={() => {- toast.warning(t('chat.media.videoMissing'));+ // Playback errors also include blocked sources, offline devices and+ // unsupported codecs; they do not prove that a file was deleted.+ toast.warning(t('chat.media.videoUnavailable'));handleClose();}}/>{canRevealInFolder ? (<DropdownMenu+ modal={!portalContainer}open={menuPos !== null}onOpenChange={(open) => {if (!open) {@@ -206,7 +210,12 @@ export function VideoLightbox({ src, onClose }: VideoLightboxProps) {}}/></DropdownMenuTrigger>- <DropdownMenuContent align="start" sideOffset={2} className="z-[10000]">+ <DropdownMenuContent+ align="start" sideOffset={2} className="z-[10000]"+ portalContainer={portalContainer}+ style={portalContainer ? { pointerEvents: 'auto' } : undefined}+ onCloseAutoFocus={restoreVideoFocus}+ ><DropdownMenuItem onClick={handleCopyVideo}><Copy className="mr-2 h-4 w-4" />{t('chat.media.copyVideo')}diff --git a/apps/desktop/src/renderer/components/chat/__tests__/ChatVideoView.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/ChatVideoView.test.tsxindex dffed4685d..3a5d5c1f47 100644--- a/apps/desktop/src/renderer/components/chat/__tests__/ChatVideoView.test.tsx+++ b/apps/desktop/src/renderer/components/chat/__tests__/ChatVideoView.test.tsx@@ -6,20 +6,120 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest';import { cleanup, fireEvent, render } from '@testing-library/react';import { Tooltip } from '@/components/ui/tooltip';import { ChatVideoView } from '../ChatVideoView';+import { VideoLightbox } from '../VideoLightbox';import { registerMedia, __resetMediaBusForTests } from '@/lib/mediaPlaybackBus';vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));vi.mock('@/hooks/useRemoteMediaUrl', () => ({ useRemoteMediaUrl: (url: string) => url }));+vi.mock('@/lib/toast', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));let visibility: IntersectionObserverCallback;let pause: ReturnType<typeof vi.spyOn>;+const showModalDescriptor = Object.getOwnPropertyDescriptor(+ HTMLDialogElement.prototype,+ 'showModal',+);beforeEach(() => {- vi.stubGlobal('IntersectionObserver', class {- constructor(callback: IntersectionObserverCallback) { visibility = callback; }- observe() {} disconnect() {}- });+ vi.stubGlobal(+ 'IntersectionObserver',+ class {+ constructor(callback: IntersectionObserverCallback) {+ visibility = callback;+ }+ observe() {}+ disconnect() {}+ },+ );pause = vi.spyOn(HTMLMediaElement.prototype, 'pause').mockImplementation(() => {});});-afterEach(() => { cleanup(); __resetMediaBusForTests(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });-const props = { filename: 'Clip', variant: 'tool-output' as const, src: 'xdt-file://local/?path=%2Fclip.mp4' };+afterEach(() => {+ cleanup();+ __resetMediaBusForTests();+ vi.restoreAllMocks();+ if (showModalDescriptor)+ Object.defineProperty(HTMLDialogElement.prototype, 'showModal', showModalDescriptor);+ else Reflect.deleteProperty(HTMLDialogElement.prototype, 'showModal');+ Reflect.deleteProperty(document, 'fullscreenElement');+ vi.unstubAllGlobals();+});+const props = {+ filename: 'Clip',+ variant: 'tool-output' as const,+ src: 'xdt-file://local/?path=%2Fclip.mp4',+};+// Tier 1 regression: a local video's body-portal menu was hidden behind native+// fullscreen. Existing inline/retry tests never opened a menu in fullscreen.+// Exercise both real players with one fullscreen video + a right-click, checking+// the menu's top-layer host, usable action, and exit/unmount cleanup.+it.each(['inline', 'lightbox'] as const)(+ '%s keeps its fullscreen context menu above the video',+ async (kind) => {+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ },+ );+ vi.stubGlobal('electronAPI', undefined);+ const copy = vi.fn().mockResolvedValue({ success: true });+ Object.defineProperty(window, 'electronAPI', {+ configurable: true,+ value: { copyMediaToClipboard: copy },+ });+ vi.stubGlobal('requestAnimationFrame', () => 0);+ vi.stubGlobal('cancelAnimationFrame', () => {});+ // jsdom has dialog's hidden style but no native showModal implementation.+ const show = vi.fn(function (this: HTMLDialogElement) {+ this.open = true;+ });+ Object.defineProperty(HTMLDialogElement.prototype, 'showModal', {+ configurable: true,+ value: show,+ });+ const src = 'cindy-media://blobs/test.mp4';+ const view = render(+ kind === 'inline' ? (+ <ChatVideoView {...props} src={src} />+ ) : (+ <VideoLightbox src={src} onClose={vi.fn()} />+ ),+ { wrapper: Tooltip.Provider },+ );+ const video = document.querySelector('video')!;+ Object.defineProperty(document, 'fullscreenElement', {+ configurable: true,+ value: video,+ writable: true,+ });+ fireEvent.contextMenu(video, { clientX: 120, clientY: 100 });+ const menu = view.getByRole('menu');+ const host = document.querySelector('dialog[open]');+ expect(host?.contains(menu)).toBe(true);+ expect(show).toHaveBeenCalled();+ fireEvent.click(view.getByRole('menuitem', { name: 'chat.media.copyVideo' }));+ await vi.waitFor(() => expect(copy).toHaveBeenCalledWith({ url: src }));+ expect(document.querySelector('dialog')).toBeNull();+ expect(document.fullscreenElement).toBe(video);+ fireEvent.contextMenu(video);+ fireEvent(document.querySelector('dialog')!, new Event('cancel', { cancelable: true }));+ expect(document.querySelector('dialog')).toBeNull();+ fireEvent.contextMenu(video);+ Object.defineProperty(document, 'fullscreenElement', { configurable: true, value: null });+ fireEvent(document, new Event('fullscreenchange'));+ expect(view.queryByRole('menu')).toBeNull();+ expect(document.querySelector('dialog')).toBeNull();+ fireEvent.contextMenu(video);+ expect(view.getByRole('menu')).toBeTruthy();+ expect(document.querySelector('dialog')).toBeNull();+ fireEvent.keyDown(view.getByRole('menu'), { key: 'Escape' });+ Object.defineProperty(document, 'fullscreenElement', { configurable: true, value: video });+ fireEvent.contextMenu(video);+ expect(document.querySelector('dialog')).not.toBeNull();+ view.unmount();+ expect(view.queryByRole('menu')).toBeNull();+ expect(document.querySelector('dialog')).toBeNull();+ },+);it('provides inline browser transport controls without a click-to-lightbox wrapper', () => {const view = render(<ChatVideoView {...props} />, { wrapper: Tooltip.Provider });const video = view.container.querySelector('video')!;@@ -43,15 +143,45 @@ it('retries a failed source when the network returns', () => {fireEvent(window, new Event('online'));expect(view.container.querySelector('video')?.src).toBe(props.src);});+// Regression: Windows CSP/transport/decode errors were reported as a lost file.+// Existing source/network retry cases do not exercise the user's recovery action.+// Tier 1, minimum input: one media error followed by Retry on the real player.+it('reports a playback failure without claiming the file is missing and lets the user retry', () => {+ const view = render(<ChatVideoView {...props} />, { wrapper: Tooltip.Provider });+ fireEvent.error(view.container.querySelector('video')!);+ expect(view.getByText('chat.media.videoUnavailable')).toBeTruthy();+ expect(view.queryByText('chat.media.videoMissing')).toBeNull();+ fireEvent.click(view.getByRole('button', { name: 'chat.errorBanner.retry' }));+ expect(view.container.querySelector('video')?.src).toBe(props.src);+});it('pauses video when its message leaves view', () => {- render(<ChatVideoView {...props} />, { wrapper: Tooltip.Provider });- visibility([{ isIntersecting: false }] as IntersectionObserverEntry[], {} as IntersectionObserver);+ const view = render(<ChatVideoView {...props} />, { wrapper: Tooltip.Provider });+ const video = view.container.querySelector('video')!;+ // Native fullscreen can make the original inline bounds leave the viewport.+ // Do not stop playback just because the message's observer reports it hidden.+ Object.defineProperty(document, 'fullscreenElement', { configurable: true, get: () => video });+ visibility(+ [{ isIntersecting: false }] as IntersectionObserverEntry[],+ {} as IntersectionObserver,+ );+ expect(pause).not.toHaveBeenCalled();+ vi.spyOn(document, 'fullscreenElement', 'get').mockReturnValue(null);+ visibility(+ [{ isIntersecting: false }] as IntersectionObserverEntry[],+ {} as IntersectionObserver,+ );expect(pause).toHaveBeenCalledOnce();});// Tier 1: the old lightbox joined the real audio/video bus; inline playback must// preserve that behavior, including the fresh element mounted after retry.it('coordinates inline videos and audio through playback and retry', () => {- const view = render(<><ChatVideoView {...props} /><ChatVideoView {...props} filename="Second" /></>, { wrapper: Tooltip.Provider });+ const view = render(+ <>+ <ChatVideoView {...props} />+ <ChatVideoView {...props} filename="Second" />+ </>,+ { wrapper: Tooltip.Provider },+ );const [first, second] = view.container.querySelectorAll('video');Object.defineProperty(first, 'paused', { configurable: true, value: false });fireEvent.play(second);diff --git a/apps/desktop/src/renderer/components/chat/useVideoContextMenu.ts b/apps/desktop/src/renderer/components/chat/useVideoContextMenu.tsnew file mode 100644index 0000000000..0e3065bc6c--- /dev/null+++ b/apps/desktop/src/renderer/components/chat/useVideoContextMenu.ts@@ -0,0 +1,78 @@+import { useCallback, useEffect, useRef, useState, type RefObject } from 'react';+import './videoContextMenu.css';++type MenuPosition = { x: number; y: number };++/** Keep the entire Radix positioning tree above native fullscreen video.+ * A body portal cannot escape the fullscreen top layer, regardless of z-index.+ */+export function useVideoContextMenu(videoRef: RefObject<HTMLVideoElement | null>, src: string) {+ const [menuPos, setPosition] = useState<MenuPosition | null>(null);+ const [portalContainer, setPortalContainer] = useState<HTMLElement | null>(null);+ const hostRef = useRef<HTMLElement | null>(null);++ const setMenuPos = useCallback(+ (position: MenuPosition | null) => {+ const video = videoRef.current;+ if (position && video && document.fullscreenElement === video) {+ if (!hostRef.current) {+ const host = document.createElement('dialog');+ host.className = 'video-context-menu-layer';+ // The Radix menu supplies semantics; this transparent dialog only lifts+ // its complete positioning tree and makes it interactive above video.+ host.setAttribute('role', 'presentation');+ Object.assign(host.style, {+ position: 'fixed',+ inset: '0',+ width: '100%',+ height: '100%',+ margin: '0',+ padding: '0',+ border: '0',+ background: 'transparent',+ overflow: 'visible',+ pointerEvents: 'auto',+ maxWidth: 'none',+ maxHeight: 'none',+ });+ video.parentElement!.appendChild(host);+ host.addEventListener('cancel', (event) => {+ event.preventDefault();+ setMenuPos(null);+ });+ host.showModal();+ hostRef.current = host;+ }+ setPortalContainer(hostRef.current);+ } else {+ hostRef.current?.remove();+ hostRef.current = null;+ setPortalContainer(null);+ }+ setPosition(position);+ },+ [videoRef],+ );++ useEffect(() => {+ setMenuPos(null);+ const close = () => setMenuPos(null);+ document.addEventListener('fullscreenchange', close);+ return () => {+ document.removeEventListener('fullscreenchange', close);+ hostRef.current?.remove();+ hostRef.current = null;+ };+ }, [src, setMenuPos]);++ const restoreVideoFocus = useCallback(+ (event: Event) => {+ // The zero-size trigger is outside fullscreen; return focus to the player.+ event.preventDefault();+ videoRef.current?.focus();+ },+ [videoRef],+ );++ return { menuPos, setMenuPos, portalContainer, restoreVideoFocus };+}diff --git a/apps/desktop/src/renderer/components/chat/videoContextMenu.css b/apps/desktop/src/renderer/components/chat/videoContextMenu.cssnew file mode 100644index 0000000000..9b8d0b95a0--- /dev/null+++ b/apps/desktop/src/renderer/components/chat/videoContextMenu.css@@ -0,0 +1,3 @@+.video-context-menu-layer::backdrop {+ background: transparent;+}diff --git a/apps/desktop/src/renderer/components/ui/dropdown-menu.tsx b/apps/desktop/src/renderer/components/ui/dropdown-menu.tsxindex b445a81797..bf12134750 100644--- a/apps/desktop/src/renderer/components/ui/dropdown-menu.tsx+++ b/apps/desktop/src/renderer/components/ui/dropdown-menu.tsx@@ -118,9 +118,12 @@ DropdownMenuSubContent.displayName = DropdownMenuPrimitive.SubContent.displayNamconst DropdownMenuContent = React.forwardRef<React.ComponentRef<typeof DropdownMenuPrimitive.Content>,- React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content> & PanelHighlightProps->(({ className, sideOffset = 4, hoverHighlight = true, children, ...props }, ref) => (- <DropdownMenuPrimitive.Portal>+ React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content> & PanelHighlightProps & {+ /** Optional top-layer host, e.g. a menu above native fullscreen media. */+ portalContainer?: HTMLElement | null;+ }+>(({ className, sideOffset = 4, hoverHighlight = true, children, portalContainer, ...props }, ref) => (+ <DropdownMenuPrimitive.Portal container={portalContainer}><DropdownMenuPrimitive.Contentref={useMenuPanel(ref, { highlight: hoverHighlight })}{...{ [MENU_PANEL_ATTR]: '' }}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 3c738a88a3..a0a615c935 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -11918,7 +11918,6 @@"modelLoading": "Loading 3D model…","modelLoadFailed": "Failed to load 3D model","videoCopied": "Video copied",- "videoMissing": "Video missing","copyVideo": "Copy video","revealVideo": "Reveal video in folder","videoUnavailable": "Video unavailable",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 16e46c6a5f..38fc5fa69c 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -11873,7 +11873,6 @@"modelLoading": "3D モデルを読み込み中…","modelLoadFailed": "3D モデルを読み込めませんでした","videoCopied": "動画をコピーしました",- "videoMissing": "動画が失われました","copyVideo": "動画をコピー","revealVideo": "動画のフォルダを開く","videoUnavailable": "動画が利用できません",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 7a3da69507..1ac1141e12 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -11873,7 +11873,6 @@"modelLoading": "3D 모델 로딩 중…","modelLoadFailed": "3D 모델을 불러오지 못했습니다","videoCopied": "동영상을 복사했습니다",- "videoMissing": "동영상이 손실되었습니다","copyVideo": "동영상 복사","revealVideo": "동영상 폴더 열기","videoUnavailable": "동영상을 사용할 수 없음",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex cd9abe6c41..98944de511 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -11873,7 +11873,6 @@"modelLoading": "正在加载 3D 模型…","modelLoadFailed": "加载 3D 模型失败","videoCopied": "视频已复制",- "videoMissing": "视频已丢失","copyVideo": "复制视频","revealVideo": "打开视频所在目录","videoUnavailable": "视频不可用",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 88743b15b0..99e9a825ca 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -11872,7 +11872,6 @@"modelLoading": "正在載入 3D 模型…","modelLoadFailed": "載入 3D 模型失敗","videoCopied": "影片已複製",- "videoMissing": "影片已丟失","copyVideo": "複製影片","revealVideo": "開啟影片所在目錄","videoUnavailable": "影片不可用",diff --git a/docs/rich-answers.md b/docs/rich-answers.mdindex 20ade3649a..208386218d 100644--- a/docs/rich-answers.md+++ b/docs/rich-answers.md@@ -102,6 +102,12 @@ iPhone 原生测试版回放真实结果,已检查任务、伙伴、流式到## 网站视频(2026-10-18)文件视频直接嵌在消息流中,提供播放、暂停和拖动进度;全屏只是可选操作。+Desktop 保留播放器底部的原生全屏按钮,使用 Fullscreen API 将视频铺满屏幕;+退出或按 Esc 返回原位置,保留同一个播放器与播放进度。主进程仅允许 Cindy 自有+顶层页面的全屏请求,嵌入页面、无手势自动全屏与屏幕采集仍按原边界拒绝。+本地视频的右键菜单在全屏时进入独立顶层,保留复制和打开所在目录;关闭菜单、+退出全屏或卸载播放器时清理该层,菜单关闭后焦点回到视频。+媒体加载错误显示「视频不可用」并提供重试;仅凭播放器 error 不判断源文件已经丢失。Desktop 复用受控媒体协议与浏览器播放控件,`xdt-file:` 同时列入 `media-src`,本地文件仍由原协议核验路径与类型。Mobile 在点击播放后通过既有远程媒体取件服务解析源地址,再挂载原生播放器;目录外文件同样只在显式点击后取件,不自动预取。