Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(desktop): 完善图片悬浮与文件树预览 (#1182)

codeingforcoffee1144566e37d7
diff --git a/apps/desktop/src/renderer/__tests__/imageLightboxCloseAnywhere.test.ts b/apps/desktop/src/renderer/__tests__/imageLightboxCloseAnywhere.test.ts
index 7c02daa12d..0f2467a8ca 100644
--- a/apps/desktop/src/renderer/__tests__/imageLightboxCloseAnywhere.test.ts
+++ b/apps/desktop/src/renderer/__tests__/imageLightboxCloseAnywhere.test.ts
@@ -49,6 +49,17 @@ describe('ImageLightbox — backdrop click closes, image click does not', () =>
});
describe('ImageLightbox — <img> stays click-transparent', () => {
+ it('gives viewBox-only SVGs an explicit fitted box after load', () => {
+ expect(source).toContain('containImageSize(');
+ expect(source).toContain('width: fittedImageSize?.width');
+ expect(source).toContain('height: fittedImageSize?.height');
+ });
+
+ it('does not reuse the previous gallery image dimensions before the new source loads', () => {
+ expect(source).toContain('naturalSize?.src === currentSrc');
+ expect(source).toMatch(/setNaturalSize\(\{[\s\S]*?src:\s*currentSrc,/);
+ });
+
it('image element does NOT register its own onClick', () => {
// 用 ref={imgRef} 锚定真正的 JSX 标签,避免匹配到行注释里的 "<img>" 字样。
const imageElement =
diff --git a/apps/desktop/src/renderer/__tests__/markdownTargetRendererContract.test.ts b/apps/desktop/src/renderer/__tests__/markdownTargetRendererContract.test.ts
index 2eca95c72b..9bb24c1ea1 100644
--- a/apps/desktop/src/renderer/__tests__/markdownTargetRendererContract.test.ts
+++ b/apps/desktop/src/renderer/__tests__/markdownTargetRendererContract.test.ts
@@ -76,6 +76,19 @@ describe('Markdown target rendering contract', () => {
expect(chipBody).not.toContain('select-none');
});
+ it('shows the composer-equivalent hover preview for resolved image chips', () => {
+ const chipStart = markdownRenderer.indexOf('function FileTargetChip');
+ const chipEnd = markdownRenderer.indexOf('\n/**\n * ResolvedLocalLink', chipStart);
+ const chipBody = markdownRenderer.slice(chipStart, chipEnd);
+
+ expect(chipBody).toContain("localKind !== 'image'");
+ expect(chipBody).toContain('onPointerEnter');
+ expect(chipBody).toContain('onPointerLeave');
+ expect(chipBody).toContain('<ImageHoverPreview');
+ expect(chipBody).toContain('anchorRef={chipRef}');
+ expect(chipBody).toContain('setImagePreviewOpen(false)');
+ });
+
it('resolves targets through the renderer cache so session switches do not re-flash', () => {
// Eager render-time resolution (chip only when unique) re-fires the IPC and
// re-flashes plain-text → chip on every session switch unless results are
diff --git a/apps/desktop/src/renderer/__tests__/thumbnailClickPreview.test.ts b/apps/desktop/src/renderer/__tests__/thumbnailClickPreview.test.ts
index 1f6fd09977..c1a2ec4275 100644
--- a/apps/desktop/src/renderer/__tests__/thumbnailClickPreview.test.ts
+++ b/apps/desktop/src/renderer/__tests__/thumbnailClickPreview.test.ts
@@ -43,6 +43,17 @@ describe('Attachment thumbnail — click opens lightbox (attachment-thumb-click)
);
});
+ it('uses the shared image hover preview so composer and message chips stay identical', () => {
+ expect(chatInput).toContain(
+ "import { ImageHoverPreview } from '@/components/chat/ImageHoverPreview';",
+ );
+ const startIdx = chatInput.indexOf('function ThumbnailItem');
+ const block = chatInput.slice(startIdx);
+ expect(block).toContain('<ImageHoverPreview');
+ expect(block).toContain('open={isHovered}');
+ expect(block).toContain('anchorRef={thumbRef}');
+ });
+
it('ThumbnailItem preview button uses cursor-pointer (hand) and an onClick handler', () => {
// Slice the ThumbnailItem function body so we don't accidentally match
// some other unrelated `cursor-pointer` token elsewhere in the file.
diff --git a/apps/desktop/src/renderer/__tests__/workdirImageExt.test.ts b/apps/desktop/src/renderer/__tests__/workdirImageExt.test.ts
index a68d6b5543..961bf46d43 100644
--- a/apps/desktop/src/renderer/__tests__/workdirImageExt.test.ts
+++ b/apps/desktop/src/renderer/__tests__/workdirImageExt.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
-import { isImagePath } from '../features/cc-agent/workdir-browse/lib/imageExt';
+import { isImagePath, isLightboxImagePath } from '../features/cc-agent/workdir-browse/lib/imageExt';
describe('workdir-browse image extensions', () => {
it('recognizes ordinary bitmap image paths case-insensitively', () => {
@@ -17,4 +17,10 @@ describe('workdir-browse image extensions', () => {
expect(isImagePath('assets/archive.zip')).toBe(false);
expect(isImagePath('README')).toBe(false);
});
+
+ it('includes svg in the full-screen lightbox path', () => {
+ expect(isLightboxImagePath('assets/logo.SVG')).toBe(true);
+ expect(isLightboxImagePath('assets/photo.png')).toBe(true);
+ expect(isLightboxImagePath('assets/archive.zip')).toBe(false);
+ });
});
diff --git a/apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx b/apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx
new file mode 100644
index 0000000000..d13146e743
--- /dev/null
+++ b/apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx
@@ -0,0 +1,125 @@
+import { useEffect, useLayoutEffect, useState, type RefObject } from 'react';
+import { createPortal } from 'react-dom';
+import { containImageSize, type ImageDimensions } from './imageDisplaySize';
+
+const PREVIEW_MAX_WIDTH = 224;
+const PREVIEW_MAX_HEIGHT = 168;
+const PREVIEW_GAP = 12;
+const VIEWPORT_PADDING = 12;
+
+interface PreviewPosition {
+ top: number;
+ left: number;
+ side: 'above' | 'below';
+ maxWidth: number;
+ maxHeight: number;
+}
+
+interface ImageHoverPreviewProps {
+ open: boolean;
+ anchorRef: RefObject<HTMLElement | null>;
+ src: string;
+ alt: string;
+}
+
+/**
+ * 输入附件与消息图片文件 chip 共用的小图预览。
+ *
+ * portal 到 body,避免被消息流 / composer 的 overflow 裁掉;默认位于锚点上方
+ * 12px,空间不足时翻到下方,并始终收在视口内。最大 224×168。
+ */
+export function ImageHoverPreview({ open, anchorRef, src, alt }: ImageHoverPreviewProps) {
+ const [position, setPosition] = useState<PreviewPosition | null>(null);
+ const [naturalSize, setNaturalSize] = useState<ImageDimensions | null>(null);
+
+ useEffect(() => {
+ setNaturalSize(null);
+ }, [src]);
+
+ useLayoutEffect(() => {
+ if (!open || !anchorRef.current) {
+ setPosition(null);
+ return;
+ }
+
+ const updatePosition = () => {
+ const anchor = anchorRef.current;
+ if (!anchor) return;
+
+ const rect = anchor.getBoundingClientRect();
+ const availableAbove = rect.top - PREVIEW_GAP - VIEWPORT_PADDING;
+ const availableBelow = window.innerHeight - rect.bottom - PREVIEW_GAP - VIEWPORT_PADDING;
+ const side =
+ availableAbove >= PREVIEW_MAX_HEIGHT || availableAbove >= availableBelow
+ ? 'above'
+ : 'below';
+ const availableHeight = side === 'above' ? availableAbove : availableBelow;
+ const viewportPreviewWidth = Math.min(
+ PREVIEW_MAX_WIDTH,
+ Math.max(0, window.innerWidth - VIEWPORT_PADDING * 2),
+ );
+ const halfPreviewWidth = viewportPreviewWidth / 2;
+ const minLeft = VIEWPORT_PADDING + halfPreviewWidth;
+ const maxLeft = window.innerWidth - VIEWPORT_PADDING - halfPreviewWidth;
+ const anchorCenter = rect.left + rect.width / 2;
+
+ setPosition({
+ top: side === 'above' ? rect.top - PREVIEW_GAP : rect.bottom + PREVIEW_GAP,
+ left:
+ minLeft <= maxLeft
+ ? Math.min(Math.max(anchorCenter, minLeft), maxLeft)
+ : window.innerWidth / 2,
+ side,
+ maxWidth: viewportPreviewWidth,
+ maxHeight: Math.max(0, Math.min(PREVIEW_MAX_HEIGHT, availableHeight)),
+ });
+ };
+
+ updatePosition();
+ window.addEventListener('resize', updatePosition);
+ const scrollListenerOptions = { capture: true, passive: true } as const;
+ window.addEventListener('scroll', updatePosition, scrollListenerOptions);
+ return () => {
+ window.removeEventListener('resize', updatePosition);
+ window.removeEventListener('scroll', updatePosition, scrollListenerOptions);
+ };
+ }, [anchorRef, open]);
+
+ if (!open || !position) return null;
+
+ const displaySize = naturalSize
+ ? containImageSize(naturalSize, position.maxWidth, position.maxHeight)
+ : null;
+
+ return createPortal(
+ <div
+ className="pointer-events-none fixed z-50 overflow-hidden rounded-xl shadow-[var(--shadow-menu)]"
+ style={{
+ top: position.top,
+ left: position.left,
+ transform: position.side === 'above' ? 'translate(-50%, -100%)' : 'translate(-50%, 0)',
+ maxWidth: position.maxWidth,
+ maxHeight: position.maxHeight,
+ }}
+ >
+ <img
+ src={src}
+ alt={alt}
+ className="max-w-full object-contain"
+ style={{
+ width: displaySize?.width,
+ height: displaySize?.height,
+ maxHeight: position.maxHeight,
+ }}
+ draggable={false}
+ onLoad={(event) => {
+ setNaturalSize({
+ width: event.currentTarget.naturalWidth,
+ height: event.currentTarget.naturalHeight,
+ });
+ }}
+ />
+ </div>,
+ document.body,
+ );
+}
diff --git a/apps/desktop/src/renderer/components/chat/ImageLightbox.tsx b/apps/desktop/src/renderer/components/chat/ImageLightbox.tsx
index 0d77b71090..2de03ea35f 100644
--- a/apps/desktop/src/renderer/components/chat/ImageLightbox.tsx
+++ b/apps/desktop/src/renderer/components/chat/ImageLightbox.tsx
@@ -94,6 +94,7 @@ import {
zoomAtPoint,
} from './lightboxGestures';
import { ImageGalleryContext, type GalleryImage } from './ImageGalleryContext';
+import { containImageSize } from './imageDisplaySize';
/** 图片不允许缩得比"适配窗口"更小,所以下限是 1 而不是共享常量的 0.2。 */
const IMAGE_MIN_SCALE = 1;
@@ -427,7 +428,13 @@ export function ImageLightbox({
const [draftStroke, setDraftStroke] = useState<AnnotationStroke | null>(null);
const [isDrawing, setIsDrawing] = useState(false);
// 图片自然尺寸:SVG viewBox 与烧录 canvas 的坐标基准。onLoad 时设置。
- const [naturalSize, setNaturalSize] = useState<{ w: number; h: number } | null>(null);
+ const [naturalSize, setNaturalSize] = useState<{ src: string; w: number; h: number } | null>(
+ null,
+ );
+ const [viewportSize, setViewportSize] = useState(() => ({
+ width: window.innerWidth,
+ height: window.innerHeight,
+ }));
const imgRef = useRef<HTMLImageElement>(null);
// once-bound keydown handler 需要读到最新标注态,与 viewportRef 同一模式。
const isAnnotatingRef = useRef(false);
@@ -435,6 +442,25 @@ export function ImageLightbox({
isAnnotatingRef.current = isAnnotating;
strokesRef.current = strokes;
+ useEffect(() => {
+ const updateViewportSize = () => {
+ setViewportSize({ width: window.innerWidth, height: window.innerHeight });
+ };
+ window.addEventListener('resize', updateViewportSize);
+ return () => window.removeEventListener('resize', updateViewportSize);
+ }, []);
+
+ // index 变化后的 effect 会在 commit 后清空状态;渲染阶段先按 src 校验,
+ // 避免新图首帧沿用上一张图的宽高比(标注坐标也必须遵守同一约束)。
+ const currentNaturalSize = naturalSize?.src === currentSrc ? naturalSize : null;
+ const fittedImageSize = currentNaturalSize
+ ? containImageSize(
+ { width: currentNaturalSize.w, height: currentNaturalSize.h },
+ viewportSize.width - 80,
+ viewportSize.height - 80,
+ )
+ : null;
+
const undoLastStroke = useCallback(() => {
setStrokes((s) => s.slice(0, -1));
}, []);
@@ -1101,6 +1127,10 @@ export function ImageLightbox({
draggable={false}
style={{
display: 'block',
+ // viewBox-only SVG 在 shrink-to-fit 容器中仅靠 max-* 会塌成 0×0;
+ // onLoad 后写入 contain 结果,同时让标注层与真实图片盒严格同尺寸。
+ width: fittedImageSize?.width,
+ height: fittedImageSize?.height,
maxWidth: 'calc(100vw - 80px)',
maxHeight: 'calc(100vh - 80px)',
objectFit: 'contain',
@@ -1108,6 +1138,7 @@ export function ImageLightbox({
}}
onLoad={(e) => {
setNaturalSize({
+ src: currentSrc,
w: e.currentTarget.naturalWidth,
h: e.currentTarget.naturalHeight,
});
@@ -1130,9 +1161,9 @@ export function ImageLightbox({
/>
{/* 标注层:viewBox = 图片自然尺寸,归一化笔迹 × 自然尺寸 = path 坐标,
与烧录坐标一致(所见即所得)。pointerEvents 关闭,事件由容器接管。 */}
- {naturalSize && (strokes.length > 0 || draftStroke) ? (
+ {currentNaturalSize && (strokes.length > 0 || draftStroke) ? (
<svg
- viewBox={`0 0 ${naturalSize.w} ${naturalSize.h}`}
+ viewBox={`0 0 ${currentNaturalSize.w} ${currentNaturalSize.h}`}
preserveAspectRatio="none"
style={{
position: 'absolute',
@@ -1144,9 +1175,9 @@ export function ImageLightbox({
aria-hidden
>
{[...strokes, ...(draftStroke ? [draftStroke] : [])].map((stroke, i) => {
- const d = strokeToSvgPath(stroke, naturalSize.w, naturalSize.h);
+ const d = strokeToSvgPath(stroke, currentNaturalSize.w, currentNaturalSize.h);
if (!d) return null;
- const w = annotationStrokeWidth(naturalSize.w, naturalSize.h);
+ const w = annotationStrokeWidth(currentNaturalSize.w, currentNaturalSize.h);
return (
// biome-ignore lint/suspicious/noArrayIndexKey: 笔迹列表只增/尾删,index 稳定。
<g key={i}>
diff --git a/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx b/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx
index 004a2e1f84..9bf118598c 100644
--- a/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx
+++ b/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx
@@ -89,6 +89,7 @@ import { SessionHandoffCard } from './SessionHandoffCard';
import { SessionLinkChip } from './SessionLinkChip';
import { ProjectLinkChip } from './ProjectLinkChip';
import { ImageLightbox } from './ImageLightbox';
+import { ImageHoverPreview } from './ImageHoverPreview';
import { ImageMissingPlaceholder } from './ImageMissingPlaceholder';
import { MarkdownDiffBlock } from './MarkdownDiffBlock';
import { MarkdownMermaidBlock } from './MarkdownMermaidBlock';
@@ -893,6 +894,8 @@ function FileTargetChip({
sessionId?: string;
}) {
const { t } = useTranslation();
+ const chipRef = useRef<HTMLElement>(null);
+ const [imagePreviewOpen, setImagePreviewOpen] = useState(false);
// html + 有会话上下文:左键按用户偏好直开(内置侧边栏 / 系统浏览器,见设置 →
// 个性化 → 链接打开方式);右键菜单额外提供「在侧边栏浏览器中打开」和
// 「查看源文件」(TextLightbox 的入口从左键挪到这里)。
@@ -900,6 +903,19 @@ function FileTargetChip({
// remote 会话:file:// / 系统浏览器都读本机 fs,先取回缓存副本再按偏好打开。
const fileCtx = useChatSessionFile();
const chipRemoteOrigin = isRemoteFileOrigin(fileCtx.origin) ? fileCtx.origin : null;
+ const imagePreviewSrc = useMemo(() => {
+ if (localKind !== 'image') return null;
+ const localUrl = toLocalFileUrl(resolvedAbsPath);
+ if (!chipRemoteOrigin) return localUrl;
+
+ // 远程图片只有在现有媒体协议能直接取件时才挂 hover 预览。SSH workdir 外
+ // 的路径需要点击后先下载缓存,不能让 xdt-file:// 误读本机同名路径。
+ const rewritten = rewriteToRemoteMediaOrigin(
+ localUrl,
+ toRemoteMediaOrigin(fileCtx.origin, fileCtx.workingDir),
+ );
+ return rewritten === localUrl ? null : rewritten;
+ }, [chipRemoteOrigin, fileCtx.origin, fileCtx.workingDir, localKind, resolvedAbsPath]);
const htmlWithSession =
localKind !== 'directory' && isHtmlFilePath(resolvedAbsPath) && sessionId ? sessionId : undefined;
const sidebarTargetSessionId = useSidebarTargetSessionId(htmlWithSession);
@@ -912,6 +928,8 @@ function FileTargetChip({
});
const activate = () => {
+ // 与输入附件一致:点击打开 lightbox 前先撤掉 hover 层,避免关闭大图后残留。
+ setImagePreviewOpen(false);
if (htmlWithSession) {
if (chipRemoteOrigin) {
void (async () => {
@@ -933,11 +951,16 @@ function FileTargetChip({
return (
<>
<code
+ ref={chipRef}
role="button"
tabIndex={0}
title={title}
onClick={activate}
onContextMenu={ctxMenu.onContextMenu}
+ onPointerEnter={() => {
+ if (imagePreviewSrc) setImagePreviewOpen(true);
+ }}
+ onPointerLeave={() => setImagePreviewOpen(false)}
onKeyDown={(e) => {
// 换掉原生按钮元素后,键盘激活要自己补回来。
if (e.key !== 'Enter' && e.key !== ' ') return;
@@ -956,6 +979,14 @@ function FileTargetChip({
>
{children}
</code>
+ {imagePreviewSrc ? (
+ <ImageHoverPreview
+ open={imagePreviewOpen}
+ anchorRef={chipRef}
+ src={imagePreviewSrc}
+ alt={basename(resolvedAbsPath)}
+ />
+ ) : null}
{ctxMenu.menu}
</>
);
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/ImageHoverPreview.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/ImageHoverPreview.test.tsx
new file mode 100644
index 0000000000..17f7198b19
--- /dev/null
+++ b/apps/desktop/src/renderer/components/chat/__tests__/ImageHoverPreview.test.tsx
@@ -0,0 +1,139 @@
+// @vitest-environment jsdom
+import React, { type RefObject } from 'react';
+import { fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { ImageHoverPreview } from '../ImageHoverPreview';
+
+const originalInnerWidth = window.innerWidth;
+
+afterEach(() => {
+ Object.defineProperty(window, 'innerWidth', {
+ configurable: true,
+ value: originalInnerWidth,
+ });
+ vi.restoreAllMocks();
+});
+
+describe('ImageHoverPreview', () => {
+ it('flips below the anchor when the shared 224×168 preview would leave the viewport', () => {
+ const addEventListenerSpy = vi.spyOn(window, 'addEventListener');
+ const anchor = document.createElement('span');
+ anchor.getBoundingClientRect = () =>
+ ({
+ top: 120,
+ left: 100,
+ width: 56,
+ height: 24,
+ right: 156,
+ bottom: 144,
+ x: 100,
+ y: 120,
+ toJSON: () => ({}),
+ }) as DOMRect;
+ const anchorRef = { current: anchor } as RefObject<HTMLElement | null>;
+
+ const { rerender } = render(
+ <ImageHoverPreview
+ open
+ anchorRef={anchorRef}
+ src="xdt-file://preview.svg"
+ alt="preview.svg"
+ />,
+ );
+
+ const image = screen.getByRole('img', { name: 'preview.svg' });
+ expect(image.getAttribute('src')).toBe('xdt-file://preview.svg');
+ expect(image.className).toContain('max-w-full');
+ expect(image.parentElement?.className).toContain('rounded-xl');
+ expect(image.style.maxHeight).toBe('168px');
+ expect(addEventListenerSpy).toHaveBeenCalledWith('scroll', expect.any(Function), {
+ capture: true,
+ passive: true,
+ });
+ Object.defineProperties(image, {
+ naturalWidth: { configurable: true, value: 225 },
+ naturalHeight: { configurable: true, value: 150 },
+ });
+ fireEvent.load(image);
+ expect(parseFloat(image.style.width)).toBeCloseTo(224);
+ expect(parseFloat(image.style.height)).toBeCloseTo(149.33);
+ expect(image.parentElement?.style.top).toBe('156px');
+ expect(image.parentElement?.style.left).toBe('128px');
+ expect(image.parentElement?.style.transform).toBe('translate(-50%, 0)');
+
+ rerender(
+ <ImageHoverPreview
+ open={false}
+ anchorRef={anchorRef}
+ src="xdt-file://preview.svg"
+ alt="preview.svg"
+ />,
+ );
+ expect(screen.queryByRole('img', { name: 'preview.svg' })).toBeNull();
+ });
+
+ it('keeps the preview above the anchor when there is enough room', () => {
+ const anchor = document.createElement('span');
+ anchor.getBoundingClientRect = () =>
+ ({
+ top: 400,
+ left: 300,
+ width: 56,
+ height: 24,
+ right: 356,
+ bottom: 424,
+ x: 300,
+ y: 400,
+ toJSON: () => ({}),
+ }) as DOMRect;
+ const anchorRef = { current: anchor } as RefObject<HTMLElement | null>;
+
+ render(
+ <ImageHoverPreview
+ open
+ anchorRef={anchorRef}
+ src="xdt-file://preview.svg"
+ alt="preview-above.svg"
+ />,
+ );
+
+ const image = screen.getByRole('img', { name: 'preview-above.svg' });
+ expect(image.parentElement?.style.top).toBe('388px');
+ expect(image.parentElement?.style.left).toBe('328px');
+ expect(image.parentElement?.style.transform).toBe('translate(-50%, -100%)');
+ });
+
+ it('uses the narrow viewport width for contain sizing instead of clipping at 224px', () => {
+ Object.defineProperty(window, 'innerWidth', { configurable: true, value: 200 });
+ const anchor = document.createElement('span');
+ anchor.getBoundingClientRect = () =>
+ ({
+ top: 400,
+ left: 80,
+ width: 40,
+ height: 24,
+ right: 120,
+ bottom: 424,
+ x: 80,
+ y: 400,
+ toJSON: () => ({}),
+ }) as DOMRect;
+ const anchorRef = { current: anchor } as RefObject<HTMLElement | null>;
+
+ render(
+ <ImageHoverPreview open anchorRef={anchorRef} src="xdt-file://narrow.svg" alt="narrow.svg" />,
+ );
+
+ const image = screen.getByRole('img', { name: 'narrow.svg' });
+ Object.defineProperties(image, {
+ naturalWidth: { configurable: true, value: 225 },
+ naturalHeight: { configurable: true, value: 150 },
+ });
+ fireEvent.load(image);
+
+ expect(image.parentElement?.style.maxWidth).toBe('176px');
+ expect(parseFloat(image.style.width)).toBeCloseTo(176);
+ expect(parseFloat(image.style.height)).toBeCloseTo(117.33);
+ });
+});
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/imageDisplaySize.test.ts b/apps/desktop/src/renderer/components/chat/__tests__/imageDisplaySize.test.ts
new file mode 100644
index 0000000000..e4cc9a4bae
--- /dev/null
+++ b/apps/desktop/src/renderer/components/chat/__tests__/imageDisplaySize.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it } from 'vitest';
+
+import { containImageSize } from '../imageDisplaySize';
+
+describe('containImageSize', () => {
+ it('fits a viewBox-only SVG ratio inside both bounds', () => {
+ const result = containImageSize({ width: 225, height: 150 }, 224, 168);
+
+ expect(result?.width).toBeCloseTo(224);
+ expect(result?.height).toBeCloseTo(149.33);
+ });
+
+ it('does not upscale a smaller image', () => {
+ expect(containImageSize({ width: 120, height: 80 }, 224, 168)).toEqual({
+ width: 120,
+ height: 80,
+ });
+ });
+
+ it('rejects empty dimensions or bounds instead of producing NaN styles', () => {
+ expect(containImageSize({ width: 0, height: 150 }, 224, 168)).toBeNull();
+ expect(containImageSize({ width: 225, height: 150 }, 224, 0)).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/renderer/components/chat/imageDisplaySize.ts b/apps/desktop/src/renderer/components/chat/imageDisplaySize.ts
new file mode 100644
index 0000000000..6b2162edb0
--- /dev/null
+++ b/apps/desktop/src/renderer/components/chat/imageDisplaySize.ts
@@ -0,0 +1,35 @@
+export interface ImageDimensions {
+ width: number;
+ height: number;
+}
+
+/**
+ * 按 contain 语义把图片收进边界,且不放大超过自然尺寸。
+ *
+ * 不能只依赖 CSS max-width / max-height:只有 viewBox、没有 width / height
+ * 的 SVG 在 shrink-to-fit 容器里会形成循环尺寸计算,资源已加载却渲染成 0×0。
+ */
+export function containImageSize(
+ natural: ImageDimensions,
+ maxWidth: number,
+ maxHeight: number,
+): ImageDimensions | null {
+ if (
+ !Number.isFinite(natural.width) ||
+ !Number.isFinite(natural.height) ||
+ !Number.isFinite(maxWidth) ||
+ !Number.isFinite(maxHeight) ||
+ natural.width <= 0 ||
+ natural.height <= 0 ||
+ maxWidth <= 0 ||
+ maxHeight <= 0
+ ) {
+ return null;
+ }
+
+ const scale = Math.min(1, maxWidth / natural.width, maxHeight / natural.height);
+ return {
+ width: natural.width * scale,
+ height: natural.height * scale,
+ };
+}
diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
index 5d776eb669..dbd56d68c8 100644
--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
@@ -17,6 +17,7 @@ import { useTranslation } from 'react-i18next';
import type { AgentInputReference } from '@cindy/maker-shared/agent-input-projection';
import { requiresFullAccessConfirmation } from '@cindy/maker-shared/permission-mode';
import { ImageLightbox } from '@/components/chat/ImageLightbox';
+import { ImageHoverPreview } from '@/components/chat/ImageHoverPreview';
import { formatBytes, TextLightbox } from '@/components/chat/TextLightbox';
import { AttachmentTypeThumb } from './AttachmentTypeThumb';
import { useEditor, EditorContent } from '@tiptap/react';
@@ -5951,18 +5952,18 @@ function ThumbnailItem({
const [lightboxSrc, setLightboxSrc] = useState<string | null>(null);
const [textLightboxOpen, setTextLightboxOpen] = useState(false);
- // Recalculate portal position when hover state changes
+ // 非图片附件仍使用路径 tooltip;图片定位由共享 ImageHoverPreview 自己负责。
useLayoutEffect(() => {
- if (isHovered && thumbRef.current) {
+ if (isHovered && file.category !== 'image' && thumbRef.current) {
const rect = thumbRef.current.getBoundingClientRect();
setPopoverPos({
- top: rect.top, // top edge of the thumbnail
- left: rect.left + rect.width / 2, // horizontal center
+ top: rect.top,
+ left: rect.left + rect.width / 2,
});
} else {
setPopoverPos(null);
}
- }, [isHovered]);
+ }, [file.category, isHovered]);
const handleOpenPreview = useCallback(async () => {
// attachment-thumb-click polish (2026-04-19): clicking opens the lightbox
@@ -6087,30 +6088,14 @@ function ThumbnailItem({
</button>
{/* Hover preview / tooltip (F-FI-4) — rendered via portal to escape overflow clipping */}
- {isHovered &&
- popoverPos &&
- file.category === 'image' &&
- (file.url || file.base64) &&
- createPortal(
- <div
- className="pointer-events-none fixed z-50 overflow-hidden rounded-lg shadow-lg"
- style={{
- top: popoverPos.top - 12, // 12px gap above thumbnail
- left: popoverPos.left,
- transform: 'translate(-50%, -100%)',
- maxWidth: 224,
- maxHeight: 168,
- }}
- >
- <img
- src={file.url ?? `data:${file.mimeType};base64,${file.base64}`}
- alt={file.name}
- className="max-h-[168px] max-w-[224px] object-contain"
- draggable={false}
- />
- </div>,
- document.body,
- )}
+ {file.category === 'image' && (file.url || file.base64) ? (
+ <ImageHoverPreview
+ open={isHovered}
+ anchorRef={thumbRef}
+ src={file.url ?? `data:${file.mimeType};base64,${file.base64}`}
+ alt={file.name}
+ />
+ ) : null}
{isHovered &&
popoverPos &&
file.category !== 'image' &&
diff --git a/apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileTreeView.tsx b/apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileTreeView.tsx
index 423b6aff36..d7bfabb242 100644
--- a/apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileTreeView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileTreeView.tsx
@@ -52,6 +52,7 @@ import {
FolderOpen,
FolderPlus,
FolderTree,
+ Eye,
PanelRight,
Pencil,
Trash2,
@@ -59,6 +60,7 @@ import {
import { cn } from '@/lib/utils';
import { Spinner } from '@/components/ui/spinner';
+import { Tip } from '@/components/ui/tooltip';
import {
DropdownMenu,
DropdownMenuContent,
@@ -71,6 +73,7 @@ import {
} from '@/lib/composerMentionDrag';
import { isBrowserOpenablePath } from '../../../../shared/browserOpenableExts';
import { pickFileIcon, pickFolderIcon } from './lib/fileIcon';
+import { isLightboxImagePath } from './lib/imageExt';
import type { DirEntry, UseFileTreeReturn } from './hooks/useFileTree';
import { useDelayedFlag } from './hooks/useDelayedFlag';
@@ -101,6 +104,8 @@ export interface FileTreeViewProps {
selectedPath: string | null;
/** Click on a file row → caller updates URL search param. */
onSelectFile: (relPath: string) => void;
+ /** 图片文件行的小眼睛操作;仅传入该能力的宿主显示。 */
+ onPreviewImage?: (entry: DirEntry) => void;
/** Right-click 文件夹 → 新建文件。parentRel 是被点中文件夹的 relPath。 */
onNewFile?: (parentRel: string) => void;
/** Right-click 文件夹 → 新建子文件夹。 */
@@ -202,6 +207,7 @@ export const FileTreeView = forwardRef<FileTreeViewHandle, FileTreeViewProps>(fu
tree,
selectedPath,
onSelectFile,
+ onPreviewImage,
onNewFile,
onNewFolder,
onDeleteFile,
@@ -341,6 +347,7 @@ export const FileTreeView = forwardRef<FileTreeViewHandle, FileTreeViewProps>(fu
loading={tree.loadingPaths.has(entry.relPath)}
onToggleFolder={tree.toggleFolder}
onSelectFile={onSelectFile}
+ onPreviewImage={onPreviewImage}
onContextMenu={(e) => {
e.preventDefault();
e.stopPropagation();
@@ -552,6 +559,7 @@ interface FileTreeRowProps {
loading?: boolean;
onToggleFolder: (relPath: string) => void;
onSelectFile: (relPath: string) => void;
+ onPreviewImage?: (entry: DirEntry) => void;
onContextMenu: (e: React.MouseEvent) => void;
}
@@ -563,9 +571,13 @@ function FileTreeRow({
loading = false,
onToggleFolder,
onSelectFile,
+ onPreviewImage,
onContextMenu,
}: FileTreeRowProps) {
+ const { t } = useTranslation();
const isFolder = entry.type === 'directory';
+ const canPreviewImage =
+ !isFolder && Boolean(onPreviewImage) && isLightboxImagePath(entry.relPath);
// 展开慢时 chevron 原位换 spinner(同尺寸,行几何零变化);门控见 useDelayedFlag。
const showLoadingChevron = useDelayedFlag(loading && isFolder);
const Chev = expanded ? ChevronDown : ChevronRight;
@@ -574,7 +586,6 @@ function FileTreeRow({
// Indent: 16 px per depth + 8 px base padding.
const paddingLeft = depth * 16 + 8;
const rowStyle = {
- paddingLeft,
WebkitUserDrag: 'element',
} as CSSProperties & {
WebkitUserDrag: 'element';
@@ -585,13 +596,6 @@ function FileTreeRow({
else onSelectFile(entry.relPath);
};
- const handleKey = (e: React.KeyboardEvent) => {
- if (e.key === 'Enter' || e.key === ' ') {
- e.preventDefault();
- handleClick();
- }
- };
-
const handleDragStart = (e: React.DragEvent<HTMLDivElement>) => {
e.dataTransfer.effectAllowed = 'copy';
e.dataTransfer.setData(
@@ -607,12 +611,10 @@ function FileTreeRow({
};
return (
+ // biome-ignore lint/a11y/noStaticElementInteractions: 行内主按钮承载键盘语义;外层 click 只补回 padding 死区,眼睛按钮会阻止冒泡。
<div
- role="button"
- tabIndex={0}
draggable
onClick={handleClick}
- onKeyDown={handleKey}
onContextMenu={onContextMenu}
onDragStart={handleDragStart}
style={rowStyle}
@@ -621,39 +623,73 @@ function FileTreeRow({
// 未来要"展开到某个文件夹"也能直接复用。
data-relpath={entry.relPath}
className={cn(
- 'flex h-7 w-full shrink-0 items-center gap-1.5 rounded-md pr-2',
+ 'group/file-row flex h-7 w-full shrink-0 items-center rounded-md pr-2',
'cursor-pointer text-[13px] transition-colors',
selected
? 'bg-sidebar-item-active font-medium text-sidebar-item-active-foreground'
: 'text-foreground hover:bg-sidebar-item-hover',
)}
>
- {isFolder ? (
- showLoadingChevron ? (
- <Spinner size={12} strokeWidth={2} className="text-[var(--cmd-palette-item-meta)]" />
+ <button
+ type="button"
+ onClick={(event) => {
+ event.stopPropagation();
+ handleClick();
+ }}
+ style={{ paddingLeft }}
+ className="flex h-full min-w-0 flex-1 items-center gap-1.5 bg-transparent p-0 text-left text-inherit focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-[var(--focus-ring)]"
+ >
+ {isFolder ? (
+ showLoadingChevron ? (
+ <Spinner size={12} strokeWidth={2} className="text-[var(--cmd-palette-item-meta)]" />
+ ) : (
+ <Chev
+ size={12}
+ strokeWidth={2}
+ className="shrink-0 text-[var(--cmd-palette-item-meta)]"
+ />
+ )
) : (
- <Chev
- size={12}
- strokeWidth={2}
- className="shrink-0 text-[var(--cmd-palette-item-meta)]"
- />
- )
- ) : (
- // Phantom 12 px slot so file icons line up with folder icons at the
- // same depth. Same trick as VSCode.
- <span aria-hidden className="inline-block w-3 shrink-0" />
- )}
- <Icon
- size={14}
- strokeWidth={1.75}
- className={cn(
- 'shrink-0',
- selected
- ? 'text-sidebar-item-active-foreground'
- : 'text-[var(--cmd-palette-item-meta)]',
+ // Phantom 12 px slot so file icons line up with folder icons at the
+ // same depth. Same trick as VSCode.
+ <span aria-hidden className="inline-block w-3 shrink-0" />
)}
- />
- <span className="min-w-0 flex-1 truncate">{entry.name}</span>
+ <Icon
+ size={14}
+ strokeWidth={1.75}
+ className={cn(
+ 'shrink-0',
+ selected
+ ? 'text-sidebar-item-active-foreground'
+ : 'text-[var(--cmd-palette-item-meta)]',
+ )}
+ />
+ <span className="min-w-0 flex-1 truncate">{entry.name}</span>
+ </button>
+ {canPreviewImage ? (
+ <Tip text={t('ccAgent.workdirBrowse.imagePreview.viewLarge')} side="left">
+ <button
+ type="button"
+ aria-label={t('ccAgent.workdirBrowse.imagePreview.viewLarge')}
+ onClick={(event) => {
+ event.stopPropagation();
+ onPreviewImage?.(entry);
+ }}
+ className={cn(
+ 'pointer-events-none flex size-5 shrink-0 select-none items-center justify-center rounded-full opacity-0',
+ 'transition-[color,background-color,opacity] duration-[var(--motion-fast)] active:scale-[0.98]',
+ 'group-hover/file-row:pointer-events-auto group-hover/file-row:opacity-100',
+ 'group-focus-within/file-row:pointer-events-auto group-focus-within/file-row:opacity-100',
+ 'focus-visible:pointer-events-auto focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[var(--focus-ring)]',
+ selected
+ ? 'text-sidebar-item-active-foreground'
+ : 'text-sidebar-action-icon hover:bg-sidebar-item-hover hover:text-foreground',
+ )}
+ >
+ <Eye size={14} strokeWidth={1.75} />
+ </button>
+ </Tip>
+ ) : null}
</div>
);
}
diff --git a/apps/desktop/src/renderer/features/cc-agent/workdir-browse/__tests__/FileTreeView.imagePreview.test.tsx b/apps/desktop/src/renderer/features/cc-agent/workdir-browse/__tests__/FileTreeView.imagePreview.test.tsx
new file mode 100644
index 0000000000..ee38040042
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/workdir-browse/__tests__/FileTreeView.imagePreview.test.tsx
@@ -0,0 +1,124 @@
+// @vitest-environment jsdom
+
+import { cleanup, fireEvent, render, screen, within } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+import { FileTreeView } from '../FileTreeView';
+import type { DirEntry, UseFileTreeReturn } from '../hooks/useFileTree';
+
+const entries: DirEntry[] = [
+ { name: 'cat.png', relPath: 'cat.png', type: 'file', size: 10, mtimeMs: 1 },
+ { name: 'logo.svg', relPath: 'logo.svg', type: 'file', size: 20, mtimeMs: 2 },
+ { name: 'README.md', relPath: 'README.md', type: 'file', size: 30, mtimeMs: 3 },
+];
+
+function makeTree(): UseFileTreeReturn {
+ return {
+ entries: new Map([['', entries]]),
+ expanded: new Set(['']),
+ loadingPaths: new Set(),
+ initialLoading: false,
+ loadError: null,
+ toggleFolder: vi.fn(),
+ collapseAll: vi.fn(),
+ refresh: vi.fn(async () => undefined),
+ expandToPath: vi.fn(async () => undefined),
+ };
+}
+
+afterEach(() => cleanup());
+
+describe('FileTreeView image preview action', () => {
+ it('shows the eye action only for lightbox-compatible images', () => {
+ const onPreviewImage = vi.fn();
+ const { container } = render(
+ <FileTreeView
+ tree={makeTree()}
+ selectedPath={null}
+ onSelectFile={vi.fn()}
+ onPreviewImage={onPreviewImage}
+ />,
+ );
+
+ expect(
+ screen.getAllByRole('button', {
+ name: 'ccAgent.workdirBrowse.imagePreview.viewLarge',
+ }),
+ ).toHaveLength(2);
+ const previewButton = screen.getAllByRole('button', {
+ name: 'ccAgent.workdirBrowse.imagePreview.viewLarge',
+ })[0];
+ expect(previewButton.tabIndex).toBe(0);
+ expect(previewButton.className).not.toContain('invisible');
+ expect(previewButton.className).toContain('focus-visible:opacity-100');
+ expect(
+ within(container.querySelector<HTMLElement>('[data-relpath="README.md"]')!).queryByRole(
+ 'button',
+ {
+ name: 'ccAgent.workdirBrowse.imagePreview.viewLarge',
+ },
+ ),
+ ).toBeNull();
+ });
+
+ it('opens the image action without selecting the file row', () => {
+ const onSelectFile = vi.fn();
+ const onPreviewImage = vi.fn();
+ const { container } = render(
+ <FileTreeView
+ tree={makeTree()}
+ selectedPath={null}
+ onSelectFile={onSelectFile}
+ onPreviewImage={onPreviewImage}
+ />,
+ );
+ const row = container.querySelector<HTMLElement>('[data-relpath="cat.png"]')!;
+
+ fireEvent.click(
+ within(row).getByRole('button', {
+ name: 'ccAgent.workdirBrowse.imagePreview.viewLarge',
+ }),
+ );
+
+ expect(onPreviewImage).toHaveBeenCalledWith(entries[0]);
+ expect(onSelectFile).not.toHaveBeenCalled();
+ });
+
+ it('keeps the file name as the row selection action', () => {
+ const onSelectFile = vi.fn();
+ const { container } = render(
+ <FileTreeView
+ tree={makeTree()}
+ selectedPath={null}
+ onSelectFile={onSelectFile}
+ onPreviewImage={vi.fn()}
+ />,
+ );
+ const row = container.querySelector<HTMLElement>('[data-relpath="cat.png"]')!;
+
+ fireEvent.click(within(row).getByRole('button', { name: 'cat.png' }));
+
+ expect(onSelectFile).toHaveBeenCalledWith('cat.png');
+ });
+
+ it('keeps the outer row padding as part of the row selection action', () => {
+ const onSelectFile = vi.fn();
+ const { container } = render(
+ <FileTreeView
+ tree={makeTree()}
+ selectedPath={null}
+ onSelectFile={onSelectFile}
+ onPreviewImage={vi.fn()}
+ />,
+ );
+ const row = container.querySelector<HTMLElement>('[data-relpath="cat.png"]')!;
+
+ fireEvent.click(row);
+
+ expect(onSelectFile).toHaveBeenCalledWith('cat.png');
+ });
+});
diff --git a/apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/imageExt.ts b/apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/imageExt.ts
index d83d3b8d81..9d2923b3a4 100644
--- a/apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/imageExt.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/imageExt.ts
@@ -1,9 +1,18 @@
const IMAGE_EXTS = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp', '.bmp', '.ico']);
+const LIGHTBOX_IMAGE_EXTS = new Set([...IMAGE_EXTS, '.svg']);
-export function isImagePath(filePath: string): boolean {
+function extname(filePath: string): string {
const lastSlash = Math.max(filePath.lastIndexOf('/'), filePath.lastIndexOf('\\'));
const name = filePath.slice(lastSlash + 1);
const dot = name.lastIndexOf('.');
- const ext = dot < 0 ? '' : name.slice(dot).toLowerCase();
- return IMAGE_EXTS.has(ext);
+ return dot < 0 ? '' : name.slice(dot).toLowerCase();
+}
+
+export function isImagePath(filePath: string): boolean {
+ return IMAGE_EXTS.has(extname(filePath));
+}
+
+/** ImageLightbox 能直接渲染的文件类型;SVG 保持文本编辑语义,但可单独预览。 */
+export function isLightboxImagePath(filePath: string): boolean {
+ return LIGHTBOX_IMAGE_EXTS.has(extname(filePath));
}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.tsx
index 1572ee055a..8f73b192cb 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.tsx
@@ -36,6 +36,7 @@ import { cn } from '@/lib/utils';
import { isGlobalDropIntercepted } from '@/lib/globalDropIntercept';
import { toast } from '@/lib/toast';
import { Tip } from '@/components/ui/tooltip';
+import { ImageLightbox } from '@/components/chat/ImageLightbox';
import {
useSessionScopedTreeWidth,
TREE_MIN_WIDTH,
@@ -77,6 +78,7 @@ import {
import type { TabKindHostContext } from '../../types';
import type { FileBrowserState } from './index';
+import { buildFileTreeImagePreviewUrl } from './fileTreeImagePreview';
import {
countFileDragItems,
hasFileDragPayload,
@@ -137,6 +139,7 @@ function FileBrowserBodyWithWorkdir({
const tree = useFileTree({ workdir, hideMetaFiles: true, remoteHostId, deviceId });
const fileContent = useFileContent(workdir, state.selectedFilePath, remoteHostId, deviceId);
const [externalFile, setExternalFile] = useState<ExternalFileSelection | null>(null);
+ const [imageLightboxSrc, setImageLightboxSrc] = useState<string | null>(null);
const externalFileContent = useFileContent(externalFile?.workdir ?? workdir, externalFile?.relPath ?? null);
const fileDragDepthRef = useRef(0);
const [isDraggingFile, setIsDraggingFile] = useState(false);
@@ -330,6 +333,23 @@ function FileBrowserBodyWithWorkdir({
[workdir, t],
);
+ const handlePreviewImage = useCallback(
+ (entry: DirEntry) => {
+ const src = buildFileTreeImagePreviewUrl({
+ workdir,
+ relPath: entry.relPath,
+ remoteHostId,
+ deviceId,
+ });
+ if (!src) {
+ toast.warning(t('ccAgent.workdirBrowse.unrenderable.remoteNotSupported'));
+ return;
+ }
+ setImageLightboxSrc(src);
+ },
+ [deviceId, remoteHostId, t, workdir],
+ );
+
const handleRevealInFolder = useCallback(
async (entry: DirEntry) => {
const abs = toOsAbsolutePath(workdir, entry.relPath);
@@ -644,6 +664,7 @@ function FileBrowserBodyWithWorkdir({
tree={tree}
selectedPath={state.selectedFilePath}
onSelectFile={handleSelectFile}
+ onPreviewImage={handlePreviewImage}
onCopyFilePath={!isRemote ? handleCopyFilePath : undefined}
onRevealInFolder={!isRemote ? handleRevealInFolder : undefined}
onOpenInFileBrowser={ctx.sessionId ? handleOpenInFileBrowser : undefined}
@@ -677,6 +698,13 @@ function FileBrowserBodyWithWorkdir({
aria-hidden="true"
/>
)}
+ {imageLightboxSrc ? (
+ <ImageLightbox
+ src={imageLightboxSrc}
+ sessionId={ctx.sessionId}
+ onClose={() => setImageLightboxSrc(null)}
+ />
+ ) : null}
</div>
);
}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/__tests__/fileTreeImagePreview.test.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/__tests__/fileTreeImagePreview.test.ts
new file mode 100644
index 0000000000..b23417289a
--- /dev/null
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/__tests__/fileTreeImagePreview.test.ts
@@ -0,0 +1,56 @@
+import { describe, expect, it } from 'vitest';
+
+import { parseRemoteMediaUrl } from '../../../../../../shared/remoteMediaUrl';
+import { buildFileTreeImagePreviewUrl } from '../fileTreeImagePreview';
+
+describe('buildFileTreeImagePreviewUrl', () => {
+ it('uses the guarded local-file protocol for local workdirs', () => {
+ const url = buildFileTreeImagePreviewUrl({
+ workdir: '/Users/me/project',
+ relPath: 'art/cat vs kaiju.svg',
+ });
+
+ expect(url).not.toBeNull();
+ expect(new URL(url!).searchParams.get('path')).toBe('/Users/me/project/art/cat vs kaiju.svg');
+ });
+
+ it('routes SSH workdir images through remote media', () => {
+ const url = buildFileTreeImagePreviewUrl({
+ workdir: '/home/me/project',
+ relPath: 'art/cat.png',
+ remoteHostId: 'ssh-host',
+ });
+ const parsed = parseRemoteMediaUrl(url!);
+
+ expect(parsed?.origin).toEqual({
+ kind: 'ssh',
+ remoteHostId: 'ssh-host',
+ workdir: '/home/me/project',
+ });
+ expect(new URL(parsed!.origUrl).searchParams.get('path')).toBe('/home/me/project/art/cat.png');
+ });
+
+ it('routes device-link images through the owning device', () => {
+ const url = buildFileTreeImagePreviewUrl({
+ workdir: 'C:\\Users\\me\\project',
+ relPath: 'art/cat.png',
+ remoteHostId: 'nested-ssh-host',
+ deviceId: 'device-A',
+ });
+
+ expect(parseRemoteMediaUrl(url!)?.origin).toEqual({
+ kind: 'device',
+ deviceId: 'device-A',
+ });
+ });
+
+ it('fails closed when an SSH path cannot be confined to the workdir', () => {
+ expect(
+ buildFileTreeImagePreviewUrl({
+ workdir: '/home/me/project',
+ relPath: '../secret.png',
+ remoteHostId: 'ssh-host',
+ }),
+ ).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/fileTreeImagePreview.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/fileTreeImagePreview.ts
new file mode 100644
index 0000000000..60028fc7d0
--- /dev/null
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/fileTreeImagePreview.ts
@@ -0,0 +1,32 @@
+import { toLocalFileUrl } from '@/lib/localPathResolver';
+import { resolveSessionFileOrigin, toRemoteMediaOrigin } from '@/lib/sessionFileOrigin';
+import { rewriteToRemoteMediaOrigin } from '../../../../../shared/remoteMediaUrl';
+import { joinPath } from '@/features/cc-agent/workdir-browse/lib/fileMeta';
+
+interface FileTreeImagePreviewUrlOptions {
+ workdir: string;
+ relPath: string;
+ remoteHostId?: string | null;
+ deviceId?: string | null;
+}
+
+/**
+ * 把文件树图片定位成 ImageLightbox 可读的 URL。
+ *
+ * 远程来源必须成功改写到 cindy-remote-media://;若路径逃出 SSH workdir 等原因
+ * 导致改写被拒绝,则返回 null,不能误读控制端本机的同名绝对路径。
+ */
+export function buildFileTreeImagePreviewUrl({
+ workdir,
+ relPath,
+ remoteHostId,
+ deviceId,
+}: FileTreeImagePreviewUrlOptions): string | null {
+ const localUrl = toLocalFileUrl(joinPath(workdir, relPath));
+ const remoteOrigin = toRemoteMediaOrigin(
+ resolveSessionFileOrigin(deviceId ?? undefined, remoteHostId),
+ workdir,
+ );
+ const rewritten = rewriteToRemoteMediaOrigin(localUrl, remoteOrigin);
+ return remoteOrigin && rewritten === localUrl ? null : rewritten;
+}