From b555164a17e80652fd7c981fdd6f280eaadd0d25 Mon Sep 17 00:00:00 2001 From: Xubin Ren <52506698+Re-bin@users.noreply.github.com> Date: Thu, 24 Sep 2026 01:44:23 +0800 Subject: [PATCH] feat(webui): polish tabbed previews and image presentation --- webui/bun.lock | 1 + webui/package.json | 1 + webui/src/components/AttachmentTile.tsx | 44 ++-- webui/src/components/FileActions.tsx | 117 ++++----- webui/src/components/FilePreviewPanel.tsx | 223 +++--------------- webui/src/components/FileReferenceChip.tsx | 60 ++++- webui/src/components/ImageGallery.tsx | 71 ++++++ webui/src/components/ImageLightbox.tsx | 33 +-- webui/src/components/InlineImageContext.tsx | 32 +++ webui/src/components/MessageBubble.tsx | 152 +----------- webui/src/components/PreviewPane.tsx | 121 ++++++++++ .../components/SidebarSelectionHighlight.tsx | 5 +- webui/src/components/WebPreviewPanel.tsx | 40 ++-- webui/src/components/ZoomableImage.tsx | 119 ++++++++++ webui/src/components/thread/ThreadHeader.tsx | 3 + webui/src/components/thread/ThreadShell.tsx | 129 +++++----- .../components/workbench/PaneWorkbench.tsx | 4 +- webui/src/globals.css | 29 ++- webui/src/hooks/useFilePreviewState.ts | 63 ++++- webui/src/i18n/locales/en/common.json | 11 + webui/src/i18n/locales/es/common.json | 11 + webui/src/i18n/locales/fr/common.json | 11 + webui/src/i18n/locales/id/common.json | 11 + webui/src/i18n/locales/ja/common.json | 11 + webui/src/i18n/locales/ko/common.json | 11 + webui/src/i18n/locales/pt-BR/common.json | 11 + webui/src/i18n/locales/vi/common.json | 11 + webui/src/i18n/locales/zh-CN/common.json | 11 + webui/src/i18n/locales/zh-TW/common.json | 11 + webui/src/lib/file-preview-resource.ts | 53 +++++ webui/src/tests/file-actions.test.tsx | 44 ++-- webui/src/tests/file-preview-panel.test.tsx | 66 ++++-- webui/src/tests/file-preview-resource.test.ts | 71 ++++++ webui/src/tests/image-gallery.test.tsx | 165 +++++++++++++ webui/src/tests/image-lightbox.test.tsx | 88 +++++++ .../src/tests/markdown-text-renderer.test.tsx | 10 +- webui/src/tests/message-bubble.test.tsx | 2 +- webui/src/tests/pane-workbench.test.tsx | 12 + webui/src/tests/preview-pane.test.tsx | 108 +++++++++ .../tests/temporary-chat-navigation.test.tsx | 69 ++++-- webui/src/tests/web-preview.test.tsx | 35 +-- 41 files changed, 1459 insertions(+), 621 deletions(-) create mode 100644 webui/src/components/ImageGallery.tsx create mode 100644 webui/src/components/InlineImageContext.tsx create mode 100644 webui/src/components/PreviewPane.tsx create mode 100644 webui/src/components/ZoomableImage.tsx create mode 100644 webui/src/lib/file-preview-resource.ts create mode 100644 webui/src/tests/file-preview-resource.test.ts create mode 100644 webui/src/tests/image-gallery.test.tsx create mode 100644 webui/src/tests/image-lightbox.test.tsx create mode 100644 webui/src/tests/preview-pane.test.tsx diff --git a/webui/bun.lock b/webui/bun.lock index 3308ca9b0..f3cf4b9f1 100644 --- a/webui/bun.lock +++ b/webui/bun.lock @@ -8,6 +8,7 @@ "@radix-ui/react-alert-dialog": "^1.1.4", "@radix-ui/react-dialog": "^1.1.4", "@radix-ui/react-dropdown-menu": "^2.1.4", + "@radix-ui/react-menu": "2.1.16", "@radix-ui/react-popover": "1.1.15", "@radix-ui/react-select": "2.2.6", "@radix-ui/react-slot": "^1.1.1", diff --git a/webui/package.json b/webui/package.json index 0ad328f2e..f8574c648 100644 --- a/webui/package.json +++ b/webui/package.json @@ -16,6 +16,7 @@ "@radix-ui/react-alert-dialog": "^1.1.4", "@radix-ui/react-dialog": "^1.1.4", "@radix-ui/react-dropdown-menu": "^2.1.4", + "@radix-ui/react-menu": "2.1.16", "@radix-ui/react-popover": "1.1.15", "@radix-ui/react-select": "2.2.6", "@radix-ui/react-slot": "^1.1.1", diff --git a/webui/src/components/AttachmentTile.tsx b/webui/src/components/AttachmentTile.tsx index 914cb393f..0f1b39ab6 100644 --- a/webui/src/components/AttachmentTile.tsx +++ b/webui/src/components/AttachmentTile.tsx @@ -4,6 +4,9 @@ import { useTranslation } from "react-i18next"; import { cn } from "@/lib/utils"; import type { UIMediaAttachment } from "@/lib/types"; +import { ImageThumbnail } from "@/components/ImageGallery"; +import { ImageLightbox } from "@/components/ImageLightbox"; +import { useRegisterInlineImage } from "@/components/InlineImageContext"; interface AttachmentTileProps { attachment: UIMediaAttachment; @@ -14,41 +17,22 @@ interface AttachmentTileProps { export function AttachmentTile({ attachment, className, inline = false, variant = "default" }: AttachmentTileProps) { const { t } = useTranslation(); - const [failed, setFailed] = useState(false); + const [failedUrl, setFailedUrl] = useState(undefined); + const failed = !!attachment.url && failedUrl === attachment.url; + const [imageOpen, setImageOpen] = useState(false); const hasUrl = typeof attachment.url === "string" && attachment.url.length > 0; const label = attachmentLabel(attachment, t); + useRegisterInlineImage(inline && attachment.kind === "image" && hasUrl && !failed ? attachment.url : undefined); if (attachment.kind === "image" && hasUrl && !failed) { return ( - - - {attachment.name setFailed(true)} - className={cn( - "block h-auto max-w-full bg-background object-contain", - variant === "compact" ? "max-h-40" : "max-h-[34rem]", - )} - /> - - + + setImageOpen(true)} onError={() => setFailedUrl(attachment.url)} /> + {}} onOpenChange={setImageOpen} /> + ); } diff --git a/webui/src/components/FileActions.tsx b/webui/src/components/FileActions.tsx index 2432597f3..a62d02505 100644 --- a/webui/src/components/FileActions.tsx +++ b/webui/src/components/FileActions.tsx @@ -1,31 +1,36 @@ -import { createContext, useContext, useEffect, useState, type ReactNode } from "react"; -import { Copy, Ellipsis, PanelRight } from "lucide-react"; +import { createContext, useContext, useEffect, useRef, useState, type ReactNode } from "react"; +import * as Menu from "@radix-ui/react-menu"; import { useTranslation } from "react-i18next"; -import { - DropdownMenu, DropdownMenuContent, DropdownMenuItem, - DropdownMenuSeparator, DropdownMenuTrigger, -} from "@/components/ui/dropdown-menu"; +import { floatingItemClassName, floatingItemFocusClassName, floatingSurfaceClassName, floatingSurfaceMotionClassName } from "@/components/ui/floating-surface"; +import { useFloatingPortal } from "@/components/ui/floating-portal"; import { copyTextToClipboard } from "@/lib/clipboard"; -import type { FileReferenceMetadata } from "@/lib/types"; +import type { FileReferenceMetadata, FilePreviewPayload } from "@/lib/types"; +import { cn } from "@/lib/utils"; interface FileActionsContextValue { resolveMetadata: (path: string) => Promise; - openPreview: (path: string) => void; + loadPreview?: (path: string) => Promise; } const FileActionsContext = createContext(undefined); export const FileActionsProvider = FileActionsContext.Provider; -/** Shared by reply references, activity rows, and the preview header. */ +export function useFilePreviewLoader() { + return useContext(FileActionsContext)?.loadPreview; +} + +const itemClassName = `${floatingItemClassName} ${floatingItemFocusClassName} cursor-default data-[disabled]:pointer-events-none data-[disabled]:opacity-50`; + +/** Copy-only context menu, shared by file references and preview tabs. */ export function FileActions({ - path, children, onPreview, metadata, + path, children, metadata, className, }: { path: string; - children?: ReactNode; - onPreview?: (path: string) => void; + children: ReactNode; metadata?: FileReferenceMetadata; + className?: string; }) { const context = useContext(FileActionsContext); const { t } = useTranslation(); @@ -34,6 +39,11 @@ export function FileActions({ const [loadFailed, setLoadFailed] = useState(false); const [copyStatus, setCopyStatus] = useState<"copied" | "failed" | null>(null); const resolveMetadata = context?.resolveMetadata; + const portal = useFloatingPortal(); + const point = useRef({ x: 0, y: 0 }); + const anchor = useRef({ getBoundingClientRect: () => new DOMRect(point.current.x, point.current.y, 0, 0) }); + const opener = useRef(null); + const interactedOutside = useRef(false); useEffect(() => { let cancelled = false; @@ -51,79 +61,72 @@ export function FileActions({ return () => { cancelled = true; }; }, [open, path, metadata, resolveMetadata]); - const enabled = Boolean(context || onPreview || metadata); - const copy = async (value: string) => { const success = await copyTextToClipboard(value); setCopyStatus(success ? "copied" : "failed"); + if (success) setOpen(false); }; - const preview = onPreview ? context?.openPreview ?? onPreview : undefined; + const openMenu = (target: EventTarget, x: number, y: number) => { + point.current = { x, y }; + opener.current = target instanceof Element ? target.closest("button, a, [tabindex]") : null; + interactedOutside.current = false; + setOpen(true); + }; + const status = copyStatus ?? (loadFailed ? "unavailable" : !resolved && resolveMetadata ? "loading" : null); return ( - + + { - if (!enabled) return; event.preventDefault(); event.stopPropagation(); - setOpen(true); + openMenu(event.target, event.clientX, event.clientY); }} onKeyDown={(event) => { - if (!enabled) return; if (event.key === "ContextMenu" || (event.key === "F10" && event.shiftKey)) { event.preventDefault(); event.stopPropagation(); - setOpen(true); + const bounds = event.currentTarget.getBoundingClientRect(); + openMenu(event.target, bounds.left, bounds.bottom); } }} > {children} - {enabled ? - - : null} - {enabled ? event.stopPropagation()}> - {preview ? <> - preview(path)}> - - {t("fileActions.preview")} - - - : null} - { + + + event.stopPropagation()} + onContextMenu={(event) => { event.preventDefault(); event.stopPropagation(); }} + onInteractOutside={() => { interactedOutside.current = true; }} + onCloseAutoFocus={(event) => { + event.preventDefault(); + if (!interactedOutside.current) opener.current?.focus(); + }}> + { event.preventDefault(); if (resolved) void copy(resolved.path); }}> - {t("fileActions.copyAbsolute")} - - { + + { event.preventDefault(); if (resolved?.relative_path) void copy(resolved.relative_path); }}> - {t("fileActions.copyRelative")} - - {!resolved ? { + + {!resolved ? { event.preventDefault(); void copy(path); - }}>{t("fileActions.copyReference")} : null} -
- {copyStatus ? t(`fileActions.${copyStatus}`) - : loadFailed ? t("fileActions.unavailable") - : !resolved && resolveMetadata ? t("fileActions.loading") - : t("fileActions.gatewayPath")} -
- : null} - -
+ }}>{t("fileActions.copyReference")} : null} + {status ?
+ {t(`fileActions.${status}`)} +
: null} + + + ); } diff --git a/webui/src/components/FilePreviewPanel.tsx b/webui/src/components/FilePreviewPanel.tsx index 412403327..16d2d3022 100644 --- a/webui/src/components/FilePreviewPanel.tsx +++ b/webui/src/components/FilePreviewPanel.tsx @@ -1,24 +1,19 @@ -import { useEffect, useMemo, useRef, useState } from "react"; -import type { CSSProperties, PointerEvent as ReactPointerEvent } from "react"; -import { AlertCircle, ChevronRight, Loader2, X } from "lucide-react"; +import { useEffect, useRef, useState } from "react"; +import { AlertCircle } from "lucide-react"; import { useTranslation } from "react-i18next"; import { CodeBlock } from "@/components/CodeBlock"; -import { FileActions } from "@/components/FileActions"; -import { splitFilePath } from "@/components/FileReferenceChip"; +import { ImageLightbox } from "@/components/ImageLightbox"; +import { fileKindForPath, splitFilePath } from "@/components/FileReferenceChip"; import { ApiError, fetchFilePreview } from "@/lib/api"; -import type { FilePreviewPayload, FileReferenceMetadata } from "@/lib/types"; -import { cn } from "@/lib/utils"; +import type { FilePreviewPayload } from "@/lib/types"; interface FilePreviewPanelProps { sessionKey: string; path: string; token: string; loadPreview?: (path: string) => Promise; - desktopWidth?: number; - isClosing?: boolean; - onResizeStart?: (event: ReactPointerEvent) => void; - onClose: () => void; + initialPreview?: FilePreviewPayload; } type PreviewState = @@ -31,28 +26,22 @@ export function FilePreviewPanel({ path, token, loadPreview, - desktopWidth = 544, - isClosing = false, - onResizeStart, - onClose, + initialPreview, }: FilePreviewPanelProps) { const { t } = useTranslation(); - const [state, setState] = useState({ status: "loading" }); - const [entered, setEntered] = useState(false); - const tokenRef = useRef(token); - tokenRef.current = token; - const loadPreviewRef = useRef(loadPreview); - loadPreviewRef.current = loadPreview; - - useEffect(() => { - const frame = window.requestAnimationFrame(() => setEntered(true)); - return () => window.cancelAnimationFrame(frame); - }, []); + const [state, setState] = useState(() => initialPreview + ? { status: "ready", payload: initialPreview } : { status: "loading" }); + const [imageOpen, setImageOpen] = useState(false); + // Cache aging must not restart an already open preview on unrelated rerenders. + const initialPreviewRef = useRef(initialPreview); + initialPreviewRef.current = initialPreview; useEffect(() => { let cancelled = false; - setState({ status: "loading" }); - (loadPreviewRef.current?.(path) ?? fetchFilePreview(tokenRef.current, sessionKey, path)) + setImageOpen(false); + const cached = initialPreviewRef.current; + setState(cached ? { status: "ready", payload: cached } : { status: "loading" }); + (loadPreview?.(path) ?? fetchFilePreview(token, sessionKey, path)) .then((payload) => { if (!cancelled) setState({ status: "ready", payload }); }) @@ -62,45 +51,11 @@ export function FilePreviewPanel({ return () => { cancelled = true; }; - }, [path, sessionKey]); + }, [path, sessionKey, token, loadPreview]); const displayPath = state.status === "ready" ? state.payload.display_path : path; - const metadata = useMemo(() => { - if (state.status !== "ready") return undefined; - const { path: absolute, project_path: root, display_path: relative } = state.payload; - // display_path is absolute for files outside the session project (e.g. media). - const normalizedRoot = root?.replace(/\\/g, "/").replace(/\/+$/, ""); - return { - path: absolute, - relative_path: normalizedRoot != null && absolute.replace(/\\/g, "/").startsWith(`${normalizedRoot}/`) ? relative : null, - }; - }, [state]); - const previewPath = state.status === "ready" ? state.payload.path : displayPath; - const normalizedPreviewPath = previewPath.replace(/\\/g, "/"); - const hasRootPrefix = normalizedPreviewPath.startsWith("/"); const { name } = splitFilePath(displayPath); const fileName = name || displayPath; - const pathParts = useMemo( - () => normalizedPreviewPath.split("/").filter(Boolean), - [normalizedPreviewPath], - ); - const directoryParts = useMemo( - () => (pathParts.length > 1 ? pathParts.slice(0, -1) : []), - [pathParts], - ); - const breadcrumbParts = useMemo( - () => (directoryParts.length > 0 ? [...directoryParts, fileName] : [fileName]), - [directoryParts, fileName], - ); - const compactBreadcrumbParts = useMemo( - () => (breadcrumbParts.length > 3 ? breadcrumbParts.slice(-3) : breadcrumbParts), - [breadcrumbParts], - ); - const hasCompactPrefix = breadcrumbParts.length > compactBreadcrumbParts.length; - const breadcrumbTitle = `${hasRootPrefix ? "/" : ""}${[ - ...directoryParts, - fileName, - ].join("/")}`; const errorMessage = state.status === "error" ? (state.error instanceof ApiError ? (state.error.status === 404 && /API route not found/i.test(state.error.message) @@ -112,128 +67,17 @@ export function FilePreviewPanel({ : null; return ( - + ); } diff --git a/webui/src/components/FileReferenceChip.tsx b/webui/src/components/FileReferenceChip.tsx index 99b7ba9a7..5a1c9c6bb 100644 --- a/webui/src/components/FileReferenceChip.tsx +++ b/webui/src/components/FileReferenceChip.tsx @@ -1,5 +1,8 @@ -import type { KeyboardEvent, MouseEvent } from "react"; -import { FileActions } from "@/components/FileActions"; +import { useEffect, useState, type KeyboardEvent, type MouseEvent } from "react"; +import { ImageIcon } from "lucide-react"; +import { useTranslation } from "react-i18next"; +import { FileActions, useFilePreviewLoader } from "@/components/FileActions"; +import { inferMediaKind } from "@/lib/media"; import { Tooltip, @@ -13,6 +16,7 @@ export type FileReferenceKind = | "default" | "css" | "html" + | "image" | "javascript" | "json" | "markdown" @@ -44,16 +48,20 @@ export function FileReferenceChip({ onOpen, testId = "inline-file-path", }: FileReferenceChipProps) { + const { t } = useTranslation(); + const [tooltipOpen, setTooltipOpen] = useState(false); const { directory, name } = splitFilePath(path); - const kind = fileKindForPath(path); const displayText = display === "path" ? path.replace(/\\/g, "/") : name; const fullPath = tooltipPath || path; const targetPath = previewPath || tooltipPath || path; + const kind = fileKindForPath(targetPath); const interactive = Boolean(onOpen); + const imageQuickLook = kind === "image" && interactive; const openPreview = (event: MouseEvent | KeyboardEvent) => { if (!onOpen) return; event.preventDefault(); event.stopPropagation(); + setTooltipOpen(false); onOpen(targetPath); }; const onKeyDown = (event: KeyboardEvent) => { @@ -61,11 +69,12 @@ export function FileReferenceChip({ openPreview(event); }; return ( - + - + setTooltipOpen(false)} className={cn("not-prose inline-flex max-w-full align-baseline leading-[inherit]", className)} > - {fullPath} + {imageQuickLook + ? tooltipOpen ? : null + : fullPath} @@ -126,6 +139,29 @@ export function FileReferenceChip({ ); } +/** Only loads after the normal hover/focus delay, through the session's guarded preview API. */ +function FileImageQuickLook({ path }: { path: string }) { + const { t } = useTranslation(); + const load = useFilePreviewLoader(); + const [result, setResult] = useState<{ load: typeof load; source: string | null }>(); + const source = result?.load === load ? result?.source : undefined; + useEffect(() => { + let cancelled = false; + void load?.(path).then((payload) => { + if (!cancelled) setResult({ load, source: payload.kind === "image" ? payload.data_url : null }); + }).catch(() => { if (!cancelled) setResult({ load, source: null }); }); + return () => { cancelled = true; }; + }, [path, load]); + if (!load || source === null) return + {t("filePreview.failed", { defaultValue: "Could not preview this file." })} + ; + return + {source ? setResult({ load, source: null })} /> + : } + ; +} + export function isLikelyFilePath(value: string): boolean { const raw = value.trim(); if (!raw || raw.includes("\n")) return false; @@ -155,7 +191,8 @@ export function splitFilePath(path: string): { directory: string; name: string } }; } -function fileKindForPath(path: string): FileReferenceKind { +export function fileKindForPath(path: string): FileReferenceKind { + if (inferMediaKind({ url: path }) === "image") return "image"; const normalized = path.toLowerCase(); const name = normalized.split(/[\\/]/).pop() ?? normalized; const ext = name.includes(".") ? name.split(".").pop() ?? "" : ""; @@ -197,7 +234,8 @@ function fileKindForPath(path: string): FileReferenceKind { } } -function FileReferenceIcon({ kind, interactive }: { kind: FileReferenceKind; interactive: boolean }) { +export function FileReferenceIcon({ kind, interactive }: { kind: FileReferenceKind; interactive: boolean }) { + if (kind === "image") return ; if (kind === "python") { return ( (null); + const viewable = images.filter((image) => image.url); + const multiple = images.length > 1; + const visible = images.slice(0, 4); + return <> + + {visible.map((image, position) => { + const remaining = images.length - visible.length; + const overflow = position === visible.length - 1 && remaining > 0; + return setIndex(Math.max(0, viewable.indexOf(image))) : undefined} + overlay={overflow ? `+${remaining}` : undefined} />; + })} + + { if (!open) setIndex(null); }} /> + ; +} + +export function ImageThumbnail({ image, size = "large", onOpen, label, overlay, onError }: { + image: UIImage; + size?: "compact" | "large" | "grid"; + onOpen?: () => void; + label?: string; + overlay?: string; + onError?: () => void; +}) { + const { t } = useTranslation(); + const [failed, setFailed] = useState(false); + const classes = cn( + "relative block max-w-full overflow-hidden rounded-control border border-border/60 bg-muted/25", + size === "large" ? "w-[min(100%,28rem)]" : size === "grid" ? "aspect-[8/5] w-full" : "h-24 w-24", + ); + const content = image.url && !failed ? {image.name { setFailed(true); onError?.(); }} + className={cn("block w-full object-contain", size === "large" ? "h-auto max-h-[22rem]" : "h-full")} /> + : + + {image.name || t("message.imageAttachment")} + ; + if (!onOpen || ((!image.url || failed) && !overlay)) return {content}; + return ; +} diff --git a/webui/src/components/ImageLightbox.tsx b/webui/src/components/ImageLightbox.tsx index c3faae8fe..7e497501a 100644 --- a/webui/src/components/ImageLightbox.tsx +++ b/webui/src/components/ImageLightbox.tsx @@ -1,10 +1,11 @@ -import { useCallback, useEffect, useMemo } from "react"; +import { useCallback, useEffect, useMemo, useRef } from "react"; import * as DialogPrimitive from "@radix-ui/react-dialog"; import { ChevronLeft, ChevronRight, X } from "lucide-react"; import { useTranslation } from "react-i18next"; import { cn } from "@/lib/utils"; import type { UIImage } from "@/lib/types"; +import { ZoomableImage } from "@/components/ZoomableImage"; interface ImageLightboxProps { images: UIImage[]; @@ -19,8 +20,7 @@ interface ImageLightboxProps { * which is much too small for a photo preview). * * Implementation notes: - * - `translate3d` + `will-change: transform` promote the image to a GPU - * compositing layer so open/swap stays at 60 FPS on long threads. + * - Image-local pinch/pan uses transforms; switching images resets the view. * - Adjacent images are rendered in hidden `` tags so the browser * decodes them eagerly; pressing left/right feels instant. * - Radix handles `Escape` + focus trapping; we only wire up ←/→ + Home/End. @@ -37,6 +37,7 @@ export function ImageLightbox({ const open = index !== null; const total = images.length; const current = index !== null ? images[index] : null; + const opener = useRef(null); const go = useCallback( (delta: number) => { @@ -94,8 +95,13 @@ export function ImageLightbox({ /> { opener.current = document.activeElement instanceof HTMLElement ? document.activeElement : null; }} + onCloseAutoFocus={(event) => { + if (opener.current?.isConnected) { event.preventDefault(); opener.current.focus(); } + }} className={cn( - "fixed inset-0 z-50 flex items-center justify-center", + "fixed inset-0 z-50 flex items-center justify-center overflow-hidden", "focus:outline-none", "data-[state=open]:animate-in data-[state=closed]:animate-out", "data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0", @@ -107,22 +113,7 @@ export function ImageLightbox({ {current.name ?? t("lightbox.title")} -
- {current.name -
+ {hasMany ? ( <> @@ -142,7 +133,7 @@ export function ImageLightbox({ go(1); }} /> -
+
{counter}
diff --git a/webui/src/components/InlineImageContext.tsx b/webui/src/components/InlineImageContext.tsx new file mode 100644 index 000000000..6edd53554 --- /dev/null +++ b/webui/src/components/InlineImageContext.tsx @@ -0,0 +1,32 @@ +import { createContext, useCallback, useContext, useLayoutEffect, useState, type ReactNode } from "react"; + +const InlineImages = createContext>(new Map()); +const RegisterImage = createContext<((url: string) => () => void) | undefined>(undefined); + +/** Deduplicate only images actually rendered in this answer, not links or code examples. */ +export function InlineImageProvider({ children }: { children: ReactNode }) { + const [urls, setUrls] = useState>(new Map()); + const register = useCallback((url: string) => { + const update = (delta: number) => setUrls((previous) => { + const next = new Map(previous); + const count = (next.get(url) ?? 0) + delta; + if (count > 0) next.set(url, count); + else next.delete(url); + return next; + }); + update(1); + return () => update(-1); + }, []); + return + {children} + ; +} + +export function useRegisterInlineImage(url?: string) { + const register = useContext(RegisterImage); + useLayoutEffect(() => url ? register?.(url) : undefined, [register, url]); +} + +export function useInlineImages() { + return useContext(InlineImages); +} diff --git a/webui/src/components/MessageBubble.tsx b/webui/src/components/MessageBubble.tsx index 180e170e4..0697cf464 100644 --- a/webui/src/components/MessageBubble.tsx +++ b/webui/src/components/MessageBubble.tsx @@ -14,7 +14,6 @@ import { CircleAlert, Clock3, Copy, - ImageIcon, Quote, Wrench, } from "lucide-react"; @@ -24,7 +23,8 @@ import { DisclosureContent } from "@/components/ui/disclosure"; import { AttachmentTile } from "@/components/AttachmentTile"; import { SessionHandleLabel } from "@/components/SessionHandleLabel"; import { FallbackResponseSources } from "@/components/ResponseSourceBadge"; -import { ImageLightbox } from "@/components/ImageLightbox"; +import { ImageGallery } from "@/components/ImageGallery"; +import { InlineImageProvider, useInlineImages } from "@/components/InlineImageContext"; import { MarkdownText } from "@/components/MarkdownText"; import { SlashCommandText } from "@/components/SlashCommandText"; import { ReasoningRow } from "@/components/thread/activity/ReasoningRow"; @@ -511,7 +511,7 @@ export function MessageBubble({ className="group relative ml-auto flex w-fit max-w-[min(85%,36rem)] flex-col items-end gap-1.5" > {contextMenu} - {hasImages ? : null} + {hasImages ? : null} {!hasImages && hasMedia ? ( ) : null} @@ -576,7 +576,7 @@ export function MessageBubble({ {empty && message.isStreaming && !hasReasoning ? ( ) : empty && message.isStreaming ? null : ( - <> +
{/* A mode switch rebuilds Streamdown's subtree and moves the scroll anchor. */}
{media.length > 0 ? : null} - +
)}
); @@ -681,17 +681,22 @@ function MessageMedia({ media: UIMediaAttachment[]; align: "left" | "right"; }) { + const inlineImages = useInlineImages(); if (media.length === 0) return null; const images: UIImage[] = []; + const seen = new Set(); const nonImages: UIMediaAttachment[] = []; for (const item of media) { const normalized = toMediaAttachment(item); if (normalized.kind === "image") { + if (normalized.url && (inlineImages.has(normalized.url) || seen.has(normalized.url))) continue; + if (normalized.url) seen.add(normalized.url); images.push({ url: normalized.url, name: normalized.name }); } else { nonImages.push(normalized); } } + if (images.length === 0 && nonImages.length === 0) return null; return (
{images.length > 0 ? ( - + ) : null} {nonImages.map((item, i) => ( @@ -710,141 +715,6 @@ function MessageMedia({ ); } -/** - * Right-aligned preview row for images attached to a user turn. - * - * The URL is expected to be a self-contained ``data:`` URL (the Composer - * hands the normalized base64 payload to the optimistic bubble so that the - * preview survives React StrictMode double-mount — blob URLs would be - * revoked by the Composer's cleanup before remount). Historical replays - * have no URL (the backend strips data URLs before persisting), so we - * render a labelled placeholder tile instead of a broken ````. - */ -function UserImages({ - images, - align = "right", - size = "compact", -}: { - images: UIImage[]; - align?: "left" | "right"; - size?: "compact" | "large"; -}) { - const { t } = useTranslation(); - // Only real-URL images can open in the lightbox; historical-replay - // placeholders (no URL) have nothing to zoom into. - const viewableImages: UIImage[] = []; - const originalToViewable = new Map(); - for (let i = 0; i < images.length; i += 1) { - const img = images[i]; - if (typeof img.url !== "string" || img.url.length === 0) continue; - originalToViewable.set(i, viewableImages.length); - viewableImages.push(img); - } - - const [lightboxIndex, setLightboxIndex] = useState(null); - - return ( - <> -
- {images.map((img, i) => ( - setLightboxIndex(originalToViewable.get(i)!) - : undefined - } - /> - ))} -
- { - if (!open) setLightboxIndex(null); - }} - /> - - ); -} - -function UserImageCell({ - image, - size, - placeholderLabel, - openLabel, - onOpen, -}: { - image: UIImage; - size: "compact" | "large"; - placeholderLabel: string; - openLabel: string; - onOpen?: () => void; -}) { - const hasUrl = typeof image.url === "string" && image.url.length > 0; - const tileClasses = cn( - "relative overflow-hidden border border-border/60 bg-muted/40", - size === "large" - ? "w-[min(100%,34rem)] rounded-panel bg-transparent" - : "h-24 w-24 rounded-control", - "shadow-[0_6px_18px_-14px_rgba(0,0,0,0.45)]", - ); - - if (hasUrl && onOpen) { - return ( - - ); - } - - return ( -
-
- - - {image.name ?? placeholderLabel} - -
-
- ); -} - /** Quiet pre-token state that occupies a stable line in the answer column. */ function ThinkingState() { const { t } = useTranslation(); diff --git a/webui/src/components/PreviewPane.tsx b/webui/src/components/PreviewPane.tsx new file mode 100644 index 000000000..08f3bd230 --- /dev/null +++ b/webui/src/components/PreviewPane.tsx @@ -0,0 +1,121 @@ +import { useEffect, useId, useRef, useState, type CSSProperties, type PointerEvent, type ReactNode } from "react"; +import { Globe2, Image, PanelRightClose, X } from "lucide-react"; +import { useTranslation } from "react-i18next"; +import { FileReferenceIcon, fileKindForPath, splitFilePath } from "@/components/FileReferenceChip"; +import { FileActions } from "@/components/FileActions"; +import { SidebarSelectionHighlight, SIDEBAR_SELECTION_ITEM_CLASS } from "@/components/SidebarSelectionHighlight"; +import type { PreviewTab } from "@/hooks/useFilePreviewState"; +import { cn } from "@/lib/utils"; + +function tabName(tab: PreviewTab) { + return tab.kind === "web" ? new URL(tab.value).host : splitFilePath(tab.value).name; +} + +/** One stable sidebar shell: switching targets never replays its opening animation. */ +export function PreviewPane({ tabs, activeId, width, isClosing, onSelect, onCloseTab, onClose, onResizeStart, children }: { + tabs: PreviewTab[]; + activeId: string; + width: number; + isClosing: boolean; + onSelect: (id: string) => void; + onCloseTab: (id: string) => void; + onClose: () => void; + onResizeStart: (event: PointerEvent) => void; + children: ReactNode; +}) { + const { t } = useTranslation(); + const id = useId(); + const [entered, setEntered] = useState(false); + const buttons = useRef(new Map()); + const tabList = useRef(null); + const pendingFocus = useRef(null); + useEffect(() => { + const frame = requestAnimationFrame(() => setEntered(true)); + return () => cancelAnimationFrame(frame); + }, []); + useEffect(() => { + const revealActiveTab = () => buttons.current.get(activeId)?.parentElement?.scrollIntoView?.({ block: "nearest", inline: "nearest" }); + revealActiveTab(); + if (pendingFocus.current) { + buttons.current.get(pendingFocus.current)?.focus(); + pendingFocus.current = null; + } + if (!tabList.current || typeof ResizeObserver === "undefined") return; + const observer = new ResizeObserver(revealActiveTab); + observer.observe(tabList.current); + return () => observer.disconnect(); + }, [activeId, tabs]); + const closeTab = (tab: PreviewTab, index: number) => { + const remaining = tabs.filter((item) => item.id !== tab.id); + pendingFocus.current = tab.id === activeId + ? remaining[Math.min(index, remaining.length - 1)]?.id ?? null : activeId; + onCloseTab(tab.id); + }; + const iconButton = "inline-flex size-8 shrink-0 items-center justify-center rounded-control text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"; + return ; +} diff --git a/webui/src/components/SidebarSelectionHighlight.tsx b/webui/src/components/SidebarSelectionHighlight.tsx index aa740c431..c97fd15dd 100644 --- a/webui/src/components/SidebarSelectionHighlight.tsx +++ b/webui/src/components/SidebarSelectionHighlight.tsx @@ -4,12 +4,14 @@ import { useLayoutEffect, useRef, } from "react"; +import { cn } from "@/lib/utils"; interface SidebarSelectionHighlightProps extends HTMLAttributes { targetRef?: RefObject; targetSelector?: string; activeId: string | null; scope: string; + highlightClassName?: string; } export const SIDEBAR_SELECTION_ITEM_CLASS = @@ -24,6 +26,7 @@ export function SidebarSelectionHighlight({ targetSelector, activeId, scope, + highlightClassName, children, ...containerProps }: SidebarSelectionHighlightProps) { @@ -114,7 +117,7 @@ export function SidebarSelectionHighlight({ data-testid={`${scope}-selection-highlight`} data-active-id={activeId ?? undefined} aria-hidden="true" - className="pointer-events-none absolute left-0 top-0 z-0 !mt-0 rounded-xl bg-sidebar-foreground/[0.055] opacity-0 transition-[transform,width,height] duration-300 ease-out will-change-transform motion-reduce:transition-none dark:bg-white/[0.07]" + className={cn("pointer-events-none absolute left-0 top-0 z-0 !mt-0 rounded-xl bg-sidebar-foreground/[0.055] opacity-0 transition-[transform,width,height] duration-300 ease-out will-change-transform motion-reduce:transition-none dark:bg-white/[0.07]", highlightClassName)} />
); diff --git a/webui/src/components/WebPreviewPanel.tsx b/webui/src/components/WebPreviewPanel.tsx index 32ffe5264..c4d344317 100644 --- a/webui/src/components/WebPreviewPanel.tsx +++ b/webui/src/components/WebPreviewPanel.tsx @@ -1,19 +1,17 @@ -import { useState, type CSSProperties, type PointerEvent } from "react"; -import { ExternalLink, RotateCw, X } from "lucide-react"; +import { useState } from "react"; +import { ExternalLink, Info, RotateCw } from "lucide-react"; import { useTranslation } from "react-i18next"; +import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"; import { isLoopbackHost } from "@/lib/network"; import { isNativeRuntime } from "@/lib/runtime"; import { parseWebLink, webPreviewRestriction } from "@/lib/web-preview"; interface WebPreviewPanelProps { url: string; - desktopWidth?: number; - onResizeStart?: (event: PointerEvent) => void; - onClose: () => void; } -export function WebPreviewPanel({ url: value, desktopWidth = 544, onResizeStart, onClose }: WebPreviewPanelProps) { +export function WebPreviewPanel({ url: value }: WebPreviewPanelProps) { const { t } = useTranslation(); const [revision, setRevision] = useState(0); const url = parseWebLink(value); @@ -21,29 +19,23 @@ export function WebPreviewPanel({ url: value, desktopWidth = 544, onResizeStart, "credentialless" in HTMLIFrameElement.prototype) : "invalid"; const buttonClass = "inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"; return ( - + ); } diff --git a/webui/src/components/ZoomableImage.tsx b/webui/src/components/ZoomableImage.tsx new file mode 100644 index 000000000..e6589e10a --- /dev/null +++ b/webui/src/components/ZoomableImage.tsx @@ -0,0 +1,119 @@ +import { useCallback, useEffect, useRef, useState, type PointerEvent } from "react"; +import { Minus, Plus } from "lucide-react"; +import { useTranslation } from "react-i18next"; + +import { cn } from "@/lib/utils"; + +type Point = { x: number; y: number }; +type View = Point & { scale: number }; +const FIT: View = { x: 0, y: 0, scale: 1 }; +const MAX_SCALE = 8; +const clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value)); +const midpoint = (a: Point, b: Point): Point => ({ x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }); +const distance = (a: Point, b: Point) => Math.hypot(a.x - b.x, a.y - b.y); + +/** Image-local gestures; the surrounding page retains normal browser zoom. Remount per image. */ +export function ZoomableImage({ src, alt }: { src: string; alt: string }) { + const { t } = useTranslation(); + const viewport = useRef(null); + const image = useRef(null); + const pointers = useRef(new Map()); + const viewRef = useRef(FIT); + const [view, setView] = useState(FIT); + const [dragging, setDragging] = useState(false); + + const apply = useCallback((next: View) => { + const scale = clamp(next.scale, 1, MAX_SCALE); + const maxX = Math.max(0, ((image.current?.offsetWidth ?? 0) * scale - (viewport.current?.clientWidth ?? 0)) / 2); + const maxY = Math.max(0, ((image.current?.offsetHeight ?? 0) * scale - (viewport.current?.clientHeight ?? 0)) / 2); + const bounded = { scale, x: clamp(next.x, -maxX, maxX), y: clamp(next.y, -maxY, maxY) }; + viewRef.current = bounded; + setView(bounded); + }, []); + + const zoom = useCallback((scale: number, from?: Point, to = from) => { + const rect = viewport.current?.getBoundingClientRect(); + const current = viewRef.current; + const next = clamp(scale, 1, MAX_SCALE); + const center = rect ? { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 } : { x: 0, y: 0 }; + const origin = from ?? center; + const target = to ?? origin; + apply({ + scale: next, + x: target.x - center.x - (origin.x - center.x - current.x) * next / current.scale, + y: target.y - center.y - (origin.y - center.y - current.y) * next / current.scale, + }); + }, [apply]); + + useEffect(() => { + const element = viewport.current; + if (!element) return; + // React's wheel listener is passive; cancel browser zoom only over this image viewport. + const onWheel = (event: WheelEvent) => { + if (event.ctrlKey) { + event.preventDefault(); + zoom(viewRef.current.scale * Math.exp(-clamp(event.deltaY, -50, 50) * 0.01), { x: event.clientX, y: event.clientY }); + } else if (viewRef.current.scale > 1) { + event.preventDefault(); + const unit = event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? element.clientHeight : 1; + apply({ ...viewRef.current, x: viewRef.current.x - event.deltaX * unit, y: viewRef.current.y - event.deltaY * unit }); + } + }; + element.addEventListener("wheel", onWheel, { passive: false }); + const resize = new ResizeObserver(() => apply(viewRef.current)); + resize.observe(element); + return () => { element.removeEventListener("wheel", onWheel); resize.disconnect(); }; + }, [apply, zoom]); + + const onPointerDown = (event: PointerEvent) => { + if (event.button !== 0 || pointers.current.size >= 2) return; + pointers.current.set(event.pointerId, { x: event.clientX, y: event.clientY }); + event.currentTarget.setPointerCapture(event.pointerId); + setDragging(true); + }; + const onPointerMove = (event: PointerEvent) => { + if (!pointers.current.has(event.pointerId)) return; + const before = [...pointers.current.values()]; + pointers.current.set(event.pointerId, { x: event.clientX, y: event.clientY }); + const after = [...pointers.current.values()]; + if (before.length === 2) { + const previousDistance = distance(before[0], before[1]); + if (previousDistance > 0) zoom(viewRef.current.scale * distance(after[0], after[1]) / previousDistance, + midpoint(before[0], before[1]), midpoint(after[0], after[1])); + } else if (viewRef.current.scale > 1) { + apply({ ...viewRef.current, x: viewRef.current.x + after[0].x - before[0].x, y: viewRef.current.y + after[0].y - before[0].y }); + } + }; + const endPointer = (event: PointerEvent) => { + pointers.current.delete(event.pointerId); + if (event.currentTarget.hasPointerCapture(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId); + setDragging(pointers.current.size > 0); + }; + const buttonClass = "grid size-9 shrink-0 place-items-center rounded-full text-white/90 transition-colors hover:bg-white/10 hover:text-white disabled:opacity-30 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white/70"; + + return <> +
1 ? dragging ? "cursor-grabbing" : "cursor-grab" : "cursor-zoom-in")} + onPointerDown={onPointerDown} onPointerMove={onPointerMove} onPointerUp={endPointer} onPointerCancel={endPointer} onLostPointerCapture={endPointer} + onDoubleClick={(event) => zoom(view.scale > 1 ? 1 : 2, { x: event.clientX, y: event.clientY })} + onKeyDown={(event) => { + if (event.key === "+" || event.key === "=") zoom(view.scale * 1.5); + else if (event.key === "-") zoom(view.scale / 1.5); + else if (event.key === "0") apply(FIT); + else return; + event.preventDefault(); + }}> + {alt} apply(viewRef.current)} + className="max-h-full max-w-full select-none rounded-compact object-contain shadow-2xl will-change-transform" + style={{ transform: `translate3d(${view.x}px, ${view.y}px, 0) scale(${view.scale})` }} /> +
+
+ + + +
+ ; +} diff --git a/webui/src/components/thread/ThreadHeader.tsx b/webui/src/components/thread/ThreadHeader.tsx index 18f13f565..e7a4d3aaa 100644 --- a/webui/src/components/thread/ThreadHeader.tsx +++ b/webui/src/components/thread/ThreadHeader.tsx @@ -20,6 +20,7 @@ const controlsClassName = cn( ); interface ThreadHeaderProps { + className?: string; title: string; handle?: SessionHandle | null; onToggleSidebar: () => void; @@ -39,6 +40,7 @@ interface ThreadHeaderProps { } export function ThreadHeader({ + className, title, handle = null, onToggleSidebar, @@ -65,6 +67,7 @@ export function ThreadHeader({ "pointer-events-none inset-x-0 top-0 z-30 flex shrink-0 items-center justify-between gap-3 px-3 py-1", "[position:var(--thread-header-position,absolute)]", minimal && "h-11", + className, )} >
(null); const [heroGreetingKey, setHeroGreetingKey] = useState(randomHeroGreetingKey); const [submittedViewportTurnId, setSubmittedViewportTurnId] = useState(null); - const { state: previewState, setPath: setFilePreviewPath, setWidth: setFilePreviewWidth, setWebUrl } = + const { state: previewState, openFile, openWeb, selectTab, closeTab, close: closePreview, setWidth: setFilePreviewWidth } = useFilePreviewState(previewSessionKey, filePreviewStore); - const [closingPreview, setClosingPreview] = useState<{ key: string; path: string } | null>(null); + const [closingPreview, setClosingPreview] = useState<{ key: string; state: FilePreviewState } | null>(null); const filePreviewClosing = closingPreview?.key === previewSessionKey; - const filePreviewPath = previewState.path - ?? (filePreviewClosing ? closingPreview?.path ?? null : null); + const visiblePreview = filePreviewClosing ? closingPreview.state : previewState; + const activePreview = visiblePreview.tabs.find((tab) => tab.id === visiblePreview.activeId); + const previewOpen = Boolean(activePreview); const [filePreviewMaxWidth, setFilePreviewMaxWidth] = useState(FILE_PREVIEW_MAX_WIDTH); const filePreviewWidth = clampFilePreviewWidth(previewState.width, filePreviewMaxWidth); const [quotedContext, setQuotedContext] = useState(null); @@ -1502,29 +1506,38 @@ export function ThreadShell({ }), [client, chatId]); const handleCloseFilePreview = useCallback(() => { - if (!previewSessionKey || !filePreviewPath || filePreviewClosing) return; + if (!previewSessionKey || !previewState.activeId || filePreviewClosing) return; filePreviewResizeCleanupRef.current?.(); - setClosingPreview({ key: previewSessionKey, path: filePreviewPath }); + setClosingPreview({ key: previewSessionKey, state: previewState }); // Record the closed state immediately, even if navigation interrupts the animation. - setFilePreviewPath(null); + closePreview(); filePreviewCloseTimerRef.current = window.setTimeout(() => { filePreviewCloseTimerRef.current = null; setClosingPreview(null); }, FILE_PREVIEW_CLOSE_ANIMATION_MS); - }, [previewSessionKey, filePreviewClosing, filePreviewPath, setFilePreviewPath]); + }, [previewSessionKey, filePreviewClosing, previewState, closePreview]); - const handleOpenFilePreview = useCallback((path: string) => { - if (path === filePreviewPath && !filePreviewClosing) { - handleCloseFilePreview(); - return; - } + const cancelPreviewClose = useCallback(() => { + filePreviewResizeCleanupRef.current?.(); if (filePreviewCloseTimerRef.current !== null) { window.clearTimeout(filePreviewCloseTimerRef.current); filePreviewCloseTimerRef.current = null; } setClosingPreview(null); - setFilePreviewPath(path); - }, [filePreviewPath, filePreviewClosing, handleCloseFilePreview, setFilePreviewPath]); + }, []); + + const handleOpenFilePreview = useCallback((path: string) => { + cancelPreviewClose(); + openFile(path); + }, [cancelPreviewClose, openFile]); + + const handleClosePreviewTab = useCallback((id: string) => { + if (previewState.tabs.length === 1) handleCloseFilePreview(); + else { + filePreviewResizeCleanupRef.current?.(); + closeTab(id); + } + }, [previewState.tabs.length, handleCloseFilePreview, closeTab]); // Markdown blocks can retain rendered links while their text is unchanged. // Keep their callback stable, but always act on the current pane/session state. @@ -1539,44 +1552,35 @@ export function ThreadShell({ }) : fetchFileReferenceMetadata(getToken(), previewSessionKey, path); }, [chatId, client, getToken, previewSessionKey, temporary]); + const loadFilePreview = useCallback((path: string) => { + if (!previewSessionKey) return Promise.reject(new Error("No active session")); + return temporary ? loadTemporaryFilePreview(path) : fetchFilePreview(getToken(), previewSessionKey, path); + }, [previewSessionKey, temporary, loadTemporaryFilePreview, getToken]); + const filePreviews = useMemo(() => createFilePreviewResource(loadFilePreview), [loadFilePreview, token]); const fileActions = useMemo(() => ({ resolveMetadata: resolveFileMetadata, - // A menu's explicit Preview action should not toggle an already-open file closed. - openPreview: (path: string) => { - if (path !== filePreviewPath || filePreviewClosing) openFilePreview(path); - }, - }), [filePreviewClosing, filePreviewPath, openFilePreview, resolveFileMetadata]); + loadPreview: filePreviews.load, + }), [resolveFileMetadata, filePreviews]); const openWebPreview = useCallback((url: string) => { const parsed = parseWebLink(url); if (!parsed) return; - filePreviewResizeCleanupRef.current?.(); - if (filePreviewCloseTimerRef.current !== null) { - window.clearTimeout(filePreviewCloseTimerRef.current); - filePreviewCloseTimerRef.current = null; - } - setClosingPreview(null); - setWebUrl(parsed.href); - }, [setWebUrl]); - - const closeWebPreview = useCallback(() => { - filePreviewResizeCleanupRef.current?.(); - setWebUrl(null); - }, [setWebUrl]); + cancelPreviewClose(); + openWeb(parsed.href); + }, [cancelPreviewClose, openWeb]); useEffect(() => { - if ((!filePreviewPath && !previewState.webUrl) || !headerActive) return; + if (!previewOpen || !headerActive) return; const onKeyDown = (event: KeyboardEvent) => { if (event.key !== "Escape" || event.defaultPrevented || event.isComposing) return; // Let a dialog/menu above the pane consume Escape without closing this preview. if (document.querySelector('[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"], [data-radix-popper-content-wrapper]')) return; event.preventDefault(); - if (previewState.webUrl) closeWebPreview(); - else handleCloseFilePreview(); + handleCloseFilePreview(); }; window.addEventListener("keydown", onKeyDown); return () => window.removeEventListener("keydown", onKeyDown); - }, [filePreviewPath, previewState.webUrl, headerActive, handleCloseFilePreview, closeWebPreview]); + }, [previewOpen, headerActive, handleCloseFilePreview]); const handleFilePreviewResizeStart = useCallback((event: ReactPointerEvent) => { filePreviewResizeCleanupRef.current?.(); @@ -1640,7 +1644,7 @@ export function ThreadShell({ }, [setFilePreviewWidth]); useEffect(() => { - if (!filePreviewPath && !previewState.webUrl) return; + if (!previewOpen) return; const clampToShell = () => { const shellWidth = shellRef.current?.getBoundingClientRect().width ?? window.innerWidth; const maxWidth = maxFilePreviewWidth(shellWidth); @@ -1654,7 +1658,7 @@ export function ThreadShell({ observer?.disconnect(); window.removeEventListener("resize", clampToShell); }; - }, [filePreviewPath, previewState.webUrl]); + }, [previewOpen]); const handleForkFromMessage = useCallback( async (beforeUserIndex: number) => { @@ -1813,6 +1817,7 @@ export function ThreadShell({ const threadHeader = !hideHeader ? ( +
{hideHeaderTitle && inlineHandle && !temporary && session?.handle ? ( @@ -1904,27 +1909,31 @@ export function ThreadShell({
, composerPortalTarget, ) : null} - {filePreviewPath && previewSessionKey ? ( - + - ) : null} - {previewState.webUrl && previewSessionKey ? ( - + > + {activePreview.kind === "file" ? ( + + ) : } + + ) : null}
); diff --git a/webui/src/components/workbench/PaneWorkbench.tsx b/webui/src/components/workbench/PaneWorkbench.tsx index d976b8893..6fea15564 100644 --- a/webui/src/components/workbench/PaneWorkbench.tsx +++ b/webui/src/components/workbench/PaneWorkbench.tsx @@ -732,7 +732,9 @@ export function PaneWorkbench({ > {renderPane(pane, { active, - headerPortalTarget: chrome ? headerPortalTarget : undefined, + // A single conversation owns its header, alongside its preview tabs. + // Multiple conversation panes still share the workbench toolbar. + headerPortalTarget: chrome && displayedPanes.length > 1 ? headerPortalTarget : undefined, composerPortalTarget: chrome ? composerPortalTarget : undefined, headerActions, })} diff --git a/webui/src/globals.css b/webui/src/globals.css index 880298368..642cf4fde 100644 --- a/webui/src/globals.css +++ b/webui/src/globals.css @@ -607,7 +607,34 @@ .thread-workspace { container: thread-workspace / inline-size; } - /* The full-width toolbar must not cover the preview breadcrumb or close button. */ + .thread-preview-layout { + container: thread-preview-layout / inline-size; + } + /* A split needs 420px for the conversation plus 360px for the preview. + Narrow workbench panes use the same contained overlay as a phone. */ + @container thread-preview-layout (min-width: 780px) { + .file-preview-pane { + position: relative; + z-index: auto; + width: var(--file-preview-slot-width); + min-width: 0; + flex-shrink: 0; + } + .file-preview-content { + width: var(--file-preview-width); + padding-bottom: 0; + } + .file-preview-resize { + display: flex; + } + } + @container thread-preview-layout (width < 780px) { + /* Covered conversation controls must not remain in the keyboard/AT order. */ + .thread-preview-layout[data-preview-open] > .thread-conversation { + visibility: hidden; + } + } + /* Split content leaves no margin for floating conversation controls. */ .thread-workspace:has([data-file-preview-panel]) > * { --thread-header-position: relative; --thread-prompt-inset: 1rem; diff --git a/webui/src/hooks/useFilePreviewState.ts b/webui/src/hooks/useFilePreviewState.ts index 90e173cbd..9a36102e6 100644 --- a/webui/src/hooks/useFilePreviewState.ts +++ b/webui/src/hooks/useFilePreviewState.ts @@ -1,12 +1,18 @@ import { useCallback, useState, useSyncExternalStore } from "react"; -interface FilePreviewState { - path: string | null; - webUrl?: string | null; +export interface PreviewTab { + id: string; + kind: "file" | "web"; + value: string; +} + +export interface FilePreviewState { + tabs: PreviewTab[]; + activeId: string | null; width: number; } -const EMPTY_PREVIEW: FilePreviewState = { path: null, width: 544 }; +const EMPTY_PREVIEW: FilePreviewState = { tabs: [], activeId: null, width: 544 }; /** App-lifetime view state only. Never stores file contents or writes to browser storage. */ export class FilePreviewStore { @@ -25,13 +31,37 @@ export class FilePreviewStore { update(key: string, patch: Partial) { const previous = this.get(key); const next = { ...previous, ...patch }; - if (patch.path) next.webUrl = null; - if (patch.webUrl) next.path = null; - if (previous.path === next.path && previous.width === next.width && previous.webUrl === next.webUrl) return; + if (previous.tabs === next.tabs && previous.width === next.width && previous.activeId === next.activeId) return; this.states.set(key, next); this.listeners.forEach((listener) => listener()); } + open(key: string, kind: PreviewTab["kind"], value: string) { + const previous = this.get(key); + const id = `${kind}:${value}`; + const tabs = previous.tabs.some((tab) => tab.id === id) + ? previous.tabs : [...previous.tabs, { id, kind, value }]; + this.update(key, { tabs, activeId: id }); + } + + select(key: string, id: string) { + if (this.get(key).tabs.some((tab) => tab.id === id)) this.update(key, { activeId: id }); + } + + closeTab(key: string, id: string) { + const previous = this.get(key); + const index = previous.tabs.findIndex((tab) => tab.id === id); + if (index < 0) return; + const tabs = previous.tabs.filter((tab) => tab.id !== id); + const activeId = previous.activeId === id + ? (tabs[Math.min(index, tabs.length - 1)]?.id ?? null) : previous.activeId; + this.update(key, { tabs, activeId }); + } + + close(key: string) { + this.update(key, { tabs: [], activeId: null }); + } + delete(key: string) { if (this.states.delete(key)) this.listeners.forEach((listener) => listener()); } @@ -47,14 +77,23 @@ export function useFilePreviewState(key: string | null, sharedStore?: FilePrevie const store = sharedStore ?? localStore; const snapshot = useCallback(() => store.get(key), [key, store]); const state = useSyncExternalStore(store.subscribe, snapshot, snapshot); - const setPath = useCallback((path: string | null) => { - if (key) store.update(key, { path }); + const openFile = useCallback((path: string) => { + if (key) store.open(key, "file", path); }, [key, store]); const setWidth = useCallback((width: number) => { if (key) store.update(key, { width }); }, [key, store]); - const setWebUrl = useCallback((webUrl: string | null) => { - if (key) store.update(key, { webUrl }); + const openWeb = useCallback((url: string) => { + if (key) store.open(key, "web", url); }, [key, store]); - return { state, setPath, setWidth, setWebUrl }; + const selectTab = useCallback((id: string) => { + if (key) store.select(key, id); + }, [key, store]); + const closeTab = useCallback((id: string) => { + if (key) store.closeTab(key, id); + }, [key, store]); + const close = useCallback(() => { + if (key) store.close(key); + }, [key, store]); + return { state, openFile, openWeb, selectTab, closeTab, close, setWidth }; } diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.json index d45831774..5c44f982d 100644 --- a/webui/src/i18n/locales/en/common.json +++ b/webui/src/i18n/locales/en/common.json @@ -1,4 +1,10 @@ { + "previewTabs": { + "title": "Preview", + "closeTab": "Close {{name}}", + "closeAll": "Close preview pane", + "websiteInfo": "About website previews" + }, "webPreview": { "original": "Original link", "actions": "Link actions", @@ -1897,6 +1903,11 @@ "continue": "Continue" }, "lightbox": { + "viewAll": "View all {{count}} images", + "zoomIn": "Zoom in", + "zoomOut": "Zoom out", + "resetZoom": "Fit image", + "gestures": "Pinch or double-click to zoom. Drag to move when zoomed. Use +, − or 0 to zoom or reset.", "title": "Image preview", "open": "View image", "prev": "Previous image", diff --git a/webui/src/i18n/locales/es/common.json b/webui/src/i18n/locales/es/common.json index 64c3dc38d..1bcfa9c91 100644 --- a/webui/src/i18n/locales/es/common.json +++ b/webui/src/i18n/locales/es/common.json @@ -1,4 +1,10 @@ { + "previewTabs": { + "title": "Vista previa", + "closeTab": "Cerrar {{name}}", + "closeAll": "Cerrar panel de vista previa", + "websiteInfo": "Acerca de las vistas previas web" + }, "webPreview": { "original": "Enlace original", "actions": "Acciones del enlace", @@ -1698,6 +1704,11 @@ "continue": "Continuar" }, "lightbox": { + "viewAll": "Ver las {{count}} imágenes", + "zoomIn": "Acercar", + "zoomOut": "Alejar", + "resetZoom": "Ajustar imagen", + "gestures": "Pellizca o haz doble clic para ampliar. Arrastra para mover. Usa +, − o 0 para ampliar o restablecer.", "title": "Vista previa de imagen", "open": "Ver imagen", "prev": "Imagen anterior", diff --git a/webui/src/i18n/locales/fr/common.json b/webui/src/i18n/locales/fr/common.json index 04ea96f3b..3f51d97ab 100644 --- a/webui/src/i18n/locales/fr/common.json +++ b/webui/src/i18n/locales/fr/common.json @@ -1,4 +1,10 @@ { + "previewTabs": { + "title": "Aperçu", + "closeTab": "Fermer {{name}}", + "closeAll": "Fermer le panneau d’aperçu", + "websiteInfo": "À propos des aperçus web" + }, "webPreview": { "original": "Lien d’origine", "actions": "Actions du lien", @@ -1697,6 +1703,11 @@ "continue": "Continuer" }, "lightbox": { + "viewAll": "Voir les {{count}} images", + "zoomIn": "Agrandir", + "zoomOut": "Réduire", + "resetZoom": "Ajuster l’image", + "gestures": "Pincez ou double-cliquez pour zoomer. Faites glisser pour déplacer. Utilisez +, − ou 0 pour zoomer ou réinitialiser.", "title": "Aperçu de l’image", "open": "Voir l’image", "prev": "Image précédente", diff --git a/webui/src/i18n/locales/id/common.json b/webui/src/i18n/locales/id/common.json index 59e7e5831..7586146d8 100644 --- a/webui/src/i18n/locales/id/common.json +++ b/webui/src/i18n/locales/id/common.json @@ -1,4 +1,10 @@ { + "previewTabs": { + "title": "Pratinjau", + "closeTab": "Tutup {{name}}", + "closeAll": "Tutup panel pratinjau", + "websiteInfo": "Tentang pratinjau situs" + }, "webPreview": { "original": "Tautan asli", "actions": "Tindakan tautan", @@ -1697,6 +1703,11 @@ "continue": "Lanjutkan" }, "lightbox": { + "viewAll": "Lihat semua {{count}} gambar", + "zoomIn": "Perbesar", + "zoomOut": "Perkecil", + "resetZoom": "Sesuaikan gambar", + "gestures": "Cubit atau klik dua kali untuk memperbesar. Seret untuk menggeser. Gunakan +, − atau 0 untuk memperbesar atau mereset.", "title": "Pratinjau gambar", "open": "Lihat gambar", "prev": "Gambar sebelumnya", diff --git a/webui/src/i18n/locales/ja/common.json b/webui/src/i18n/locales/ja/common.json index d84d53c00..4ba456930 100644 --- a/webui/src/i18n/locales/ja/common.json +++ b/webui/src/i18n/locales/ja/common.json @@ -1,4 +1,10 @@ { + "previewTabs": { + "title": "プレビュー", + "closeTab": "{{name}} を閉じる", + "closeAll": "プレビューパネルを閉じる", + "websiteInfo": "ウェブプレビューについて" + }, "webPreview": { "original": "元のリンク", "actions": "リンク操作", @@ -1697,6 +1703,11 @@ "continue": "続行" }, "lightbox": { + "viewAll": "すべての画像({{count}} 枚)を表示", + "zoomIn": "拡大", + "zoomOut": "縮小", + "resetZoom": "画面に合わせる", + "gestures": "ピンチまたはダブルクリックで拡大し、ドラッグで移動できます。+、−、0 キーで拡大・縮小・リセットできます。", "title": "画像プレビュー", "open": "画像を表示", "prev": "前の画像", diff --git a/webui/src/i18n/locales/ko/common.json b/webui/src/i18n/locales/ko/common.json index caf535a25..1d07cc393 100644 --- a/webui/src/i18n/locales/ko/common.json +++ b/webui/src/i18n/locales/ko/common.json @@ -1,4 +1,10 @@ { + "previewTabs": { + "title": "미리보기", + "closeTab": "{{name}} 닫기", + "closeAll": "미리보기 패널 닫기", + "websiteInfo": "웹 미리보기 정보" + }, "webPreview": { "original": "원래 링크", "actions": "링크 작업", @@ -1697,6 +1703,11 @@ "continue": "계속" }, "lightbox": { + "viewAll": "이미지 {{count}}개 모두 보기", + "zoomIn": "확대", + "zoomOut": "축소", + "resetZoom": "화면에 맞추기", + "gestures": "두 손가락이나 두 번 클릭으로 확대하고 드래그로 이동하세요. +, −, 0 키로 확대, 축소 또는 초기화할 수 있습니다.", "title": "이미지 미리보기", "open": "이미지 보기", "prev": "이전 이미지", diff --git a/webui/src/i18n/locales/pt-BR/common.json b/webui/src/i18n/locales/pt-BR/common.json index 142e95b7a..f4b09ff15 100644 --- a/webui/src/i18n/locales/pt-BR/common.json +++ b/webui/src/i18n/locales/pt-BR/common.json @@ -1,4 +1,10 @@ { + "previewTabs": { + "title": "Prévia", + "closeTab": "Fechar {{name}}", + "closeAll": "Fechar painel de prévia", + "websiteInfo": "Sobre as prévias de sites" + }, "webPreview": { "original": "Link original", "actions": "Ações do link", @@ -1711,6 +1717,11 @@ "continue": "Continuar" }, "lightbox": { + "viewAll": "Ver todas as {{count}} imagens", + "zoomIn": "Ampliar", + "zoomOut": "Reduzir", + "resetZoom": "Ajustar imagem", + "gestures": "Faça o gesto de pinça ou clique duas vezes para ampliar. Arraste para mover. Use +, − ou 0 para ampliar ou redefinir.", "title": "Pré-visualização de imagem", "open": "Ver imagem", "prev": "Imagem anterior", diff --git a/webui/src/i18n/locales/vi/common.json b/webui/src/i18n/locales/vi/common.json index ecfe3010e..e388fabd8 100644 --- a/webui/src/i18n/locales/vi/common.json +++ b/webui/src/i18n/locales/vi/common.json @@ -1,4 +1,10 @@ { + "previewTabs": { + "title": "Xem trước", + "closeTab": "Đóng {{name}}", + "closeAll": "Đóng khung xem trước", + "websiteInfo": "Giới thiệu về xem trước trang web" + }, "webPreview": { "original": "Liên kết gốc", "actions": "Thao tác liên kết", @@ -1697,6 +1703,11 @@ "continue": "Tiếp tục" }, "lightbox": { + "viewAll": "Xem tất cả {{count}} ảnh", + "zoomIn": "Phóng to", + "zoomOut": "Thu nhỏ", + "resetZoom": "Vừa khung hình", + "gestures": "Chụm ngón tay hoặc nhấp đúp để thu phóng. Kéo để di chuyển. Dùng +, − hoặc 0 để thu phóng hoặc đặt lại.", "title": "Xem trước ảnh", "open": "Xem ảnh", "prev": "Ảnh trước", diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.json index 52d20b750..b2601ec5d 100644 --- a/webui/src/i18n/locales/zh-CN/common.json +++ b/webui/src/i18n/locales/zh-CN/common.json @@ -1,4 +1,10 @@ { + "previewTabs": { + "title": "预览", + "closeTab": "关闭 {{name}}", + "closeAll": "关闭预览栏", + "websiteInfo": "关于网页预览" + }, "webPreview": { "original": "原始链接", "actions": "链接操作", @@ -1897,6 +1903,11 @@ "continue": "继续" }, "lightbox": { + "viewAll": "查看全部 {{count}} 张图片", + "zoomIn": "放大", + "zoomOut": "缩小", + "resetZoom": "适应窗口", + "gestures": "双指捏合或双击缩放,放大后拖动查看。也可按 +、− 或 0 缩放或复位。", "title": "图片预览", "open": "查看图片", "prev": "上一张", diff --git a/webui/src/i18n/locales/zh-TW/common.json b/webui/src/i18n/locales/zh-TW/common.json index 721933fb1..db1121ea1 100644 --- a/webui/src/i18n/locales/zh-TW/common.json +++ b/webui/src/i18n/locales/zh-TW/common.json @@ -1,4 +1,10 @@ { + "previewTabs": { + "title": "預覽", + "closeTab": "關閉 {{name}}", + "closeAll": "關閉預覽欄", + "websiteInfo": "關於網頁預覽" + }, "webPreview": { "original": "原始連結", "actions": "連結操作", @@ -1697,6 +1703,11 @@ "continue": "繼續" }, "lightbox": { + "viewAll": "查看全部 {{count}} 張圖片", + "zoomIn": "放大", + "zoomOut": "縮小", + "resetZoom": "符合視窗", + "gestures": "雙指捏合或按兩下縮放,放大後拖曳查看。也可按 +、− 或 0 縮放或重設。", "title": "圖片預覽", "open": "檢視圖片", "prev": "上一張", diff --git a/webui/src/lib/file-preview-resource.ts b/webui/src/lib/file-preview-resource.ts new file mode 100644 index 000000000..16e9c5d1c --- /dev/null +++ b/webui/src/lib/file-preview-resource.ts @@ -0,0 +1,53 @@ +import type { FilePreviewPayload } from "@/lib/types"; + +const FRESH_MS = 5_000; +const RETAIN_MS = 60_000; +const MAX_ENTRIES = 4; +const MAX_BYTES = 8 * 1024 * 1024; + +/** Short-lived, in-memory only. The caller owns one resource per session/loader. */ +export function createFilePreviewResource(fetchPreview: (path: string) => Promise) { + const entries = new Map; + loadedAt: number; + bytes: number; + }>(); + const peek = (path: string) => { + const entry = entries.get(path); + return entry?.payload && Date.now() - entry.loadedAt < RETAIN_MS ? entry.payload : undefined; + }; + const load = (path: string): Promise => { + const existing = entries.get(path); + if (existing?.pending) return existing.pending; + if (existing?.payload && Date.now() - existing.loadedAt < FRESH_MS) { + return Promise.resolve(existing.payload); + } + const entry = { payload: peek(path), loadedAt: existing?.loadedAt ?? 0, bytes: existing?.bytes ?? 0, + pending: undefined as Promise | undefined }; + entries.delete(path); + entries.set(path, entry); + while (entries.size > MAX_ENTRIES) entries.delete(entries.keys().next().value!); + entry.pending = Promise.resolve().then(() => fetchPreview(path)).then((payload) => { + // An evicted request may finish, but must not put its data back into the cache. + if (entries.get(path) === entry) { + entry.payload = payload; + entry.pending = undefined; + entry.loadedAt = Date.now(); + entry.bytes = 2 * (payload.kind === "image" ? payload.data_url.length : payload.content.length); + let total = [...entries.values()].reduce((sum, item) => sum + item.bytes, 0); + for (const [key, item] of entries) { + if (total <= MAX_BYTES) break; + total -= item.bytes; + entries.delete(key); + } + } + return payload; + }, (error: unknown) => { + if (entries.get(path) === entry) entries.delete(path); + throw error; + }); + return entry.pending; + }; + return { peek, load }; +} diff --git a/webui/src/tests/file-actions.test.tsx b/webui/src/tests/file-actions.test.tsx index a9eb185d0..f663c0365 100644 --- a/webui/src/tests/file-actions.test.tsx +++ b/webui/src/tests/file-actions.test.tsx @@ -16,22 +16,28 @@ describe("File actions", () => { it("resolves paths only when opened and uses the same menu for both copies", async () => { const user = userEvent.setup(); const resolveMetadata = vi.fn().mockResolvedValue(details); - const openPreview = vi.fn(); - render( + render( ); expect(resolveMetadata).not.toHaveBeenCalled(); - await user.click(screen.getByRole("button", { name: "File actions for notes.md:12" })); + expect(screen.queryByRole("button", { name: /File actions/ })).not.toBeInTheDocument(); + fireEvent.contextMenu(screen.getByRole("button", { name: "notes.md:12" }), { clientX: 100, clientY: 200 }); await waitFor(() => expect(screen.getByRole("menuitem", { name: "Copy absolute path" })).not.toHaveAttribute("data-disabled")); expect(resolveMetadata).toHaveBeenCalledWith("notes.md:12"); + expect(screen.queryByRole("menuitem", { name: "Preview" })).not.toBeInTheDocument(); + expect(screen.queryByText("Paths refer to the gateway machine.")).not.toBeInTheDocument(); + expect(screen.getAllByRole("menuitem")).toHaveLength(2); await user.click(screen.getByRole("menuitem", { name: "Copy absolute path" })); expect(copyTextToClipboard).toHaveBeenLastCalledWith(details.path); - expect(await screen.findByText("Copied")).toBeVisible(); + await waitFor(() => expect(screen.queryByRole("menu")).not.toBeInTheDocument()); + expect(screen.getByRole("button", { name: "notes.md:12" })).toHaveFocus(); + fireEvent.contextMenu(screen.getByRole("button", { name: "notes.md:12" })); + await waitFor(() => expect(screen.getByRole("menuitem", { name: "Copy relative path" })).not.toHaveAttribute("data-disabled")); await user.click(screen.getByRole("menuitem", { name: "Copy relative path" })); expect(copyTextToClipboard).toHaveBeenLastCalledWith("notes.md"); - await user.click(screen.getByRole("menuitem", { name: "Preview" })); - expect(openPreview).toHaveBeenCalledWith("notes.md:12"); - expect(screen.queryByRole("menu")).not.toBeInTheDocument(); + await user.keyboard("{Escape}"); + await waitFor(() => expect(screen.queryByRole("menu")).not.toBeInTheDocument()); + expect(screen.getByRole("button", { name: "notes.md:12" })).toHaveFocus(); }); it("keeps primary click working and supports context menu and Shift+F10", async () => { @@ -43,17 +49,21 @@ describe("File actions", () => { expect(onOpen).toHaveBeenCalledTimes(1); expect(onOpen).toHaveBeenCalledWith("src/app.ts"); fireEvent.contextMenu(reference); - expect(await screen.findByRole("menuitem", { name: "Preview" })).toBeVisible(); + expect(await screen.findByRole("menuitem", { name: "Copy reference" })).toBeVisible(); await user.keyboard("{Escape}"); fireEvent.keyDown(reference, { key: "F10", shiftKey: true }); expect(await screen.findByRole("menuitem", { name: "Copy reference" })).toBeVisible(); expect(onOpen).toHaveBeenCalledTimes(1); + await user.keyboard("{Escape}"); + fireEvent.keyDown(reference, { key: "ContextMenu" }); + expect(await screen.findByRole("menuitem", { name: "Copy reference" })).toBeVisible(); + expect(onOpen).toHaveBeenCalledTimes(1); }); it("does not invent a relative path for files outside the project", async () => { const user = userEvent.setup(); - render(); - await user.click(screen.getByRole("button", { name: "File actions for image.png" })); + render(); + fireEvent.contextMenu(screen.getByRole("button", { name: "image.png" })); expect(screen.getByRole("menuitem", { name: "Copy relative path" })).toHaveAttribute("data-disabled"); expect(screen.queryByRole("menuitem", { name: "Preview" })).not.toBeInTheDocument(); await user.click(screen.getByRole("menuitem", { name: "Copy absolute path" })); @@ -63,10 +73,10 @@ describe("File actions", () => { it("retains the original reference if resolution fails and reports clipboard errors", async () => { const user = userEvent.setup(); vi.mocked(copyTextToClipboard).mockResolvedValue(false); - render( + render( ); - await user.click(screen.getByRole("button", { name: "File actions for missing.txt" })); + fireEvent.contextMenu(screen.getByRole("button", { name: "missing.txt" })); expect(await screen.findByText(/Could not resolve this file/)).toBeVisible(); expect(screen.getByRole("menuitem", { name: "Copy absolute path" })).toHaveAttribute("data-disabled"); await user.click(screen.getByRole("menuitem", { name: "Copy reference" })); @@ -77,11 +87,11 @@ describe("File actions", () => { it("ignores late metadata from a previous session", async () => { const user = userEvent.setup(); let resolveOld!: (value: FileReferenceMetadata) => void; - const previous = { resolveMetadata: () => new Promise((resolve) => { resolveOld = resolve; }), openPreview: vi.fn() }; - const current = { resolveMetadata: vi.fn().mockResolvedValue({ path: "/new/notes.md", relative_path: "notes.md" }), openPreview: vi.fn() }; + const previous = { resolveMetadata: () => new Promise((resolve) => { resolveOld = resolve; }) }; + const current = { resolveMetadata: vi.fn().mockResolvedValue({ path: "/new/notes.md", relative_path: "notes.md" }) }; const view = (value: typeof current | typeof previous) => ; const { rerender } = render(view(previous)); - await user.click(screen.getByRole("button", { name: "File actions for notes.md" })); + fireEvent.contextMenu(screen.getByRole("button", { name: "notes.md" })); rerender(view(current)); await waitFor(() => expect(current.resolveMetadata).toHaveBeenCalled()); await act(async () => resolveOld(details)); @@ -91,10 +101,10 @@ describe("File actions", () => { it("degrades to the original reference on an older gateway response", async () => { const user = userEvent.setup(); - render( + render( ); - await user.click(screen.getByRole("button", { name: "File actions for notes.md" })); + fireEvent.contextMenu(screen.getByRole("button", { name: "notes.md" })); expect(await screen.findByText(/Could not resolve this file/)).toBeVisible(); expect(screen.getByRole("menuitem", { name: "Copy absolute path" })).toHaveAttribute("data-disabled"); await user.click(screen.getByRole("menuitem", { name: "Copy reference" })); diff --git a/webui/src/tests/file-preview-panel.test.tsx b/webui/src/tests/file-preview-panel.test.tsx index f5c5131da..78f5660fd 100644 --- a/webui/src/tests/file-preview-panel.test.tsx +++ b/webui/src/tests/file-preview-panel.test.tsx @@ -1,5 +1,4 @@ -import { act, fireEvent, render, screen } from "@testing-library/react"; -import userEvent from "@testing-library/user-event"; +import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { FilePreviewPanel } from "@/components/FilePreviewPanel"; @@ -46,7 +45,7 @@ describe("FilePreviewPanel", () => { kind: "image", path: "/workspace/chart.png", display_path: "chart.png", project_path: "/workspace", size: 42, mime_type: "image/png", data_url: dataUrl, }); - render( {}} />); + render(); const img = await screen.findByRole("img", { name: "chart.png" }); expect(img).toHaveAttribute("src", dataUrl); expect(screen.queryByTestId("mock-code-block")).not.toBeInTheDocument(); @@ -62,7 +61,7 @@ describe("FilePreviewPanel", () => { language: "text", content: "session B", truncated: false, size: 9, }; vi.mocked(fetchFilePreview).mockResolvedValueOnce(payload); - const view = (key: string) => {}} />; + const view = (key: string) => ; const { rerender } = render(view("a")); rerender(view("b")); await screen.findByText("session B"); @@ -70,9 +69,27 @@ describe("FilePreviewPanel", () => { expect(screen.queryByText("session A")).not.toBeInTheDocument(); }); - it("shows a compact breadcrumb with one file name and a visible close action", async () => { - const user = userEvent.setup(); - const onClose = vi.fn(); + it("opens the sidebar image in the shared zoomable viewer and returns to the preview", async () => { + vi.mocked(fetchFilePreview).mockResolvedValue({ + kind: "image", path: "/workspace/chart.png", display_path: "chart.png", + size: 42, mime_type: "image/png", data_url: "data:image/png;base64,example", + }); + render(); + const trigger = await screen.findByRole("button", { name: "View image: chart.png" }); + trigger.focus(); + fireEvent.click(trigger); + const dialog = screen.getByRole("dialog"); + expect(within(dialog).getByRole("img", { name: "chart.png" })).toBeInTheDocument(); + fireEvent.click(within(dialog).getByRole("button", { name: "Zoom in" })); + expect(within(dialog).getByRole("button", { name: "Fit image" })).toHaveTextContent("150%"); + fireEvent.keyDown(dialog, { key: "Escape" }); + await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument()); + await waitFor(() => expect(trigger).toHaveFocus()); + expect(screen.getByTestId("file-preview-panel")).toBeInTheDocument(); + expect(fetchFilePreview).toHaveBeenCalledTimes(1); + }); + + it("renders file content without a second filename or breadcrumb below the tabs", async () => { vi.mocked(fetchFilePreview).mockResolvedValue({ path: "/Users/hr/workspace/quicksort.py", display_path: "quicksort.py", @@ -86,7 +103,6 @@ describe("FilePreviewPanel", () => { sessionKey="websocket:chat-1" path="quicksort.py" token="tok" - onClose={onClose} />, ); @@ -94,16 +110,33 @@ describe("FilePreviewPanel", () => { expect(codeBlock).toHaveTextContent("print('ok')"); expect(codeBlock).toHaveAttribute("data-language", "python"); expect(codeBlock).toHaveAttribute("data-highlight", "true"); - expect(screen.getByTestId("file-preview-breadcrumb")).toHaveTextContent("..."); - expect(screen.getByTestId("file-preview-breadcrumb")).toHaveTextContent("workspace"); - expect(screen.getByTestId("file-preview-title")).toHaveTextContent("quicksort.py"); - expect(screen.getAllByText("quicksort.py")).toHaveLength(1); + expect(screen.queryByTestId("file-preview-breadcrumb")).not.toBeInTheDocument(); + expect(screen.queryByText("quicksort.py")).not.toBeInTheDocument(); - const closeButton = screen.getByRole("button", { name: "Close file preview" }); - expect(closeButton).toBeVisible(); + }); - await user.click(closeButton); - expect(onClose).toHaveBeenCalledTimes(1); + it("paints cached content immediately, revalidates it, and does not restart when the cache ages", async () => { + const cached = { path: "notes.txt", display_path: "notes.txt", language: "text", content: "Cached", truncated: false }; + let resolve!: (payload: typeof cached) => void; + const loadPreview = vi.fn(() => new Promise(r => { resolve = r; })); + const view = (initialPreview?: typeof cached) => ; + const { rerender } = render(view(cached)); + expect(screen.getByTestId("mock-code-block")).toHaveTextContent("Cached"); + expect(screen.queryByRole("status")).not.toBeInTheDocument(); + await act(async () => resolve({ ...cached, content: "Updated" })); + expect(screen.getByTestId("mock-code-block")).toHaveTextContent("Updated"); + rerender(view()); + expect(screen.getByTestId("mock-code-block")).toHaveTextContent("Updated"); + expect(loadPreview).toHaveBeenCalledTimes(1); + }); + + it("reports a failed revalidation rather than leaving stale cached content looking current", async () => { + const cached = { path: "notes.txt", display_path: "notes.txt", language: "text", content: "Cached", truncated: false }; + render(); + await screen.findByText("Could not preview this file."); + expect(screen.queryByText("Cached")).not.toBeInTheDocument(); }); it("updates translated chrome without refetching the open file", async () => { @@ -120,7 +153,6 @@ describe("FilePreviewPanel", () => { sessionKey="websocket:chat-1" path="notes.md" token="tok" - onClose={() => {}} />, ); diff --git a/webui/src/tests/file-preview-resource.test.ts b/webui/src/tests/file-preview-resource.test.ts new file mode 100644 index 000000000..e61d6acfa --- /dev/null +++ b/webui/src/tests/file-preview-resource.test.ts @@ -0,0 +1,71 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { createFilePreviewResource } from "@/lib/file-preview-resource"; +import type { FilePreviewPayload } from "@/lib/types"; + +const payload: FilePreviewPayload = { path: "notes.txt", display_path: "notes.txt", content: "One", language: "text", truncated: false }; + +afterEach(() => vi.useRealTimers()); + +describe("session-scoped file previews", () => { + it("shares hover and click requests, then immediately reuses a recently viewed file", async () => { + const fetchPreview = vi.fn().mockResolvedValue(payload); + const resource = createFilePreviewResource(fetchPreview); + const hover = resource.load("notes.txt"); + expect(resource.load("notes.txt")).toBe(hover); + await hover; + expect(resource.peek("notes.txt")).toBe(payload); + expect(await resource.load("notes.txt")).toBe(payload); + expect(fetchPreview).toHaveBeenCalledTimes(1); + }); + + it("revalidates older content without losing the snapshot, but does not retain it forever", async () => { + vi.useFakeTimers(); + const updated = { ...payload, content: "Two" }; + const fetchPreview = vi.fn().mockResolvedValueOnce(payload).mockResolvedValueOnce(updated); + const resource = createFilePreviewResource(fetchPreview); + await resource.load("notes.txt"); + vi.advanceTimersByTime(5_001); + expect(resource.peek("notes.txt")).toBe(payload); + expect(await resource.load("notes.txt")).toBe(updated); + expect(fetchPreview).toHaveBeenCalledTimes(2); + vi.advanceTimersByTime(60_001); + expect(resource.peek("notes.txt")).toBeUndefined(); + }); + + it("does not hide authorization failures behind cached data and allows a retry", async () => { + vi.useFakeTimers(); + const fetchPreview = vi.fn().mockResolvedValueOnce(payload).mockRejectedValueOnce(new Error("401")).mockResolvedValueOnce(payload); + const resource = createFilePreviewResource(fetchPreview); + await resource.load("notes.txt"); + vi.advanceTimersByTime(5_001); + await expect(resource.load("notes.txt")).rejects.toThrow("401"); + expect(resource.peek("notes.txt")).toBeUndefined(); + expect(await resource.load("notes.txt")).toBe(payload); + }); + + it("bounds entries and payload bytes; late evicted requests cannot refill the cache", async () => { + let resolve!: (value: FilePreviewPayload) => void; + const fetchPreview = vi.fn().mockImplementationOnce(() => new Promise(r => { resolve = r; })).mockResolvedValue(payload); + const resource = createFilePreviewResource(fetchPreview); + const late = resource.load("old.txt"); + for (let index = 0; index < 4; index++) await resource.load(`${index}.txt`); + resolve(payload); + await late; + expect(resource.peek("old.txt")).toBeUndefined(); + fetchPreview.mockResolvedValueOnce({ ...payload, content: "x".repeat(4 * 1024 * 1024 + 1) }); + await resource.load("huge.txt"); + expect(resource.peek("huge.txt")).toBeUndefined(); + }); + + it("never shares data between session resources or writes browser storage", async () => { + const writes = vi.spyOn(Storage.prototype, "setItem"); + const first = createFilePreviewResource(vi.fn().mockResolvedValue(payload)); + const second = createFilePreviewResource(vi.fn().mockResolvedValue({ ...payload, content: "Second session" })); + await first.load("notes.txt"); + expect(second.peek("notes.txt")).toBeUndefined(); + expect((await second.load("notes.txt"))).toMatchObject({ content: "Second session" }); + expect(first.peek("notes.txt")).toBe(payload); + expect(writes).not.toHaveBeenCalled(); + writes.mockRestore(); + }); +}); diff --git a/webui/src/tests/image-gallery.test.tsx b/webui/src/tests/image-gallery.test.tsx new file mode 100644 index 000000000..871fa96a7 --- /dev/null +++ b/webui/src/tests/image-gallery.test.tsx @@ -0,0 +1,165 @@ +import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { describe, expect, it, vi } from "vitest"; + +import { ImageGallery } from "@/components/ImageGallery"; +import { MessageBubble } from "@/components/MessageBubble"; +import { FileActionsProvider } from "@/components/FileActions"; +import { FileReferenceChip } from "@/components/FileReferenceChip"; +import type { FilePreviewPayload, UIMessage } from "@/lib/types"; + +const images = Array.from({ length: 8 }, (_, index) => ({ url: `/api/media/sign/image-${index}`, name: `${index}.png` })); +const message: UIMessage = { id: "images", role: "assistant", content: "", createdAt: 1, + media: [{ kind: "image", url: "/api/media/sign/chart", name: "chart.png" }] }; + +describe("image presentation", () => { + it("bounds a large collection to four thumbnails and keeps every image in the viewer", async () => { + const user = userEvent.setup(); + const { container } = render(); + expect(container.querySelectorAll("img")).toHaveLength(4); + expect(screen.getByText("+4")).toBeVisible(); + await user.click(screen.getByRole("button", { name: "View all 8 images" })); + expect(screen.getByText("4 / 8")).toBeVisible(); + await user.keyboard("{End}"); + expect(screen.getByText("8 / 8")).toBeVisible(); + expect(within(screen.getByRole("dialog")).getByRole("img", { name: "7.png" })).toBeVisible(); + await user.keyboard("{Escape}"); + expect(screen.queryByRole("dialog")).not.toBeInTheDocument(); + expect(screen.getByRole("button", { name: "View all 8 images" })).toHaveFocus(); + }); + + it("preserves an inline image's position, deduplicates its attachment, and opens the shared viewer", async () => { + const user = userEvent.setup(); + const { container, rerender } = render(); + await screen.findByRole("img", { name: "Trend" }); + await waitFor(() => expect(container.querySelectorAll("img")).toHaveLength(1)); + expect(container.textContent).toMatch(/Before.*After/s); + await user.click(screen.getByRole("button", { name: "View image: Trend" })); + expect(await screen.findByRole("button", { name: "Zoom in" })).toBeVisible(); + await user.keyboard("{Escape}"); + // Removing inline content must restore the attachment; no global remembered suppression. + rerender(); + expect(await screen.findByRole("button", { name: "View image: chart.png" })).toBeVisible(); + }); + + it("does not suppress files referenced in code or links, or different images sharing a name", async () => { + const { container } = render(); + await waitFor(() => expect(container.querySelector("pre")).toBeInTheDocument()); + expect(container.querySelectorAll("img")).toHaveLength(2); + }); + + it("keeps the attachment if an image reference is not actually rendered by the streaming renderer", async () => { + const { container } = render(); + await screen.findByText("![Trend][chart]"); + expect(screen.getByRole("button", { name: "View image: chart.png" })).toBeVisible(); + await waitFor(() => expect(container.querySelectorAll("img")).toHaveLength(1)); + }); + + it("keeps unavailable images readable, and never hides a valid image behind missing placeholders", async () => { + const user = userEvent.setup(); + render( ({ name: "old.png" })), images[0]]} />); + await user.click(screen.getByRole("button", { name: "View all 5 images" })); + expect(within(screen.getByRole("dialog")).getByRole("img", { name: "0.png" })).toBeVisible(); + }); + + it("replaces a broken thumbnail with a quiet named placeholder", () => { + render(); + fireEvent.error(screen.getByRole("img")); + expect(screen.queryByRole("img")).not.toBeInTheDocument(); + expect(screen.getByText("0.png")).toBeVisible(); + expect(screen.queryByRole("button")).not.toBeInTheDocument(); + }); +}); + +describe("file quick look", () => { + const preview: FilePreviewPayload = { kind: "image", path: "chart.png", display_path: "chart.png", + project_path: "/workspace", size: 100, mime_type: "image/png", data_url: "data:image/png;base64,dGVzdA==" }; + it("loads only on deliberate hover/focus, keeps click as preview, and releases content on dismissal", async () => { + const user = userEvent.setup(); + const loadPreview = vi.fn().mockResolvedValue(preview); + const onOpen = vi.fn(); + const { container } = render( + + ); + expect(loadPreview).not.toHaveBeenCalled(); + await user.hover(screen.getByRole("button", { name: "chart.png" })); + expect(loadPreview).not.toHaveBeenCalled(); + await screen.findByRole("tooltip"); + await waitFor(() => expect(loadPreview).toHaveBeenCalledWith("chart.png")); + const quickLook = screen.getByTestId("file-image-quick-look"); + expect(quickLook.textContent).toBe(""); + expect(quickLook).toHaveClass("w-max"); + expect(quickLook).not.toHaveClass("h-36", "w-full"); + expect(quickLook.querySelector("img")).toHaveClass("rounded-mark", "object-contain"); + expect(quickLook.querySelector("img")).toHaveClass("h-auto", "w-auto", "max-h-36"); + expect(screen.getByRole("tooltip")).toHaveTextContent("File preview"); + await user.click(screen.getByRole("button", { name: "chart.png" })); + expect(onOpen).toHaveBeenCalledWith("chart.png"); + await waitFor(() => expect(screen.queryByRole("tooltip")).not.toBeInTheDocument()); + expect(container.querySelector("img")).not.toBeInTheDocument(); + }); + + it("does not show a late image from a previous session, and shows a quiet failure instead of an empty popup", async () => { + let resolveOld!: (payload: FilePreviewPayload) => void; + const oldLoader = vi.fn(() => new Promise((resolve) => { resolveOld = resolve; })); + const newLoader = vi.fn().mockRejectedValue(new Error("404")); + const view = (loadPreview: typeof oldLoader) => + + ; + const { rerender } = render(view(oldLoader)); + fireEvent.focus(screen.getByRole("button", { name: "chart.png" })); + await waitFor(() => expect(oldLoader).toHaveBeenCalled()); + rerender(view(newLoader)); + await act(async () => resolveOld(preview)); + expect(document.querySelector('img[src^="data:image"]')).not.toBeInTheDocument(); + expect(screen.getByText("Could not preview this file.")).toBeVisible(); + expect(screen.getByRole("button", { name: "chart.png" })).toBeVisible(); + }); + + it("keeps long image paths out of the quick look while preserving the real preview target", async () => { + const user = userEvent.setup(); + const filename = "a-long-descriptive-filename-for-a-generated-project-overview.png"; + const path = `/workspace/projects/weekly-reports/exported-charts/${filename}`; + const loadPreview = vi.fn().mockResolvedValue(preview); + const onOpen = vi.fn(); + render( + + ); + fireEvent.focus(screen.getByRole("button", { name: path })); + const tooltip = await screen.findByRole("tooltip"); + expect(tooltip).not.toHaveTextContent(filename); + expect(tooltip).not.toHaveTextContent("/workspace/"); + await waitFor(() => expect(loadPreview).toHaveBeenCalledWith(path)); + expect(screen.getByTestId("file-image-quick-look").textContent).toBe(""); + await user.click(screen.getByRole("button", { name: path })); + expect(onOpen).toHaveBeenCalledWith(path); + }); + + it("replaces a broken preview image with a readable failure without repeating the filename", async () => { + const loadPreview = vi.fn().mockResolvedValue(preview); + render( + + ); + fireEvent.focus(screen.getByRole("button", { name: "chart.png" })); + await waitFor(() => expect(document.querySelector('img[src^="data:image"]')).toBeInTheDocument()); + fireEvent.error(screen.getByTestId("file-image-quick-look").querySelector("img")!); + expect(screen.queryByTestId("file-image-quick-look")).not.toBeInTheDocument(); + expect(screen.getByText("Could not preview this file.")).toBeVisible(); + expect(screen.getAllByText("chart.png")).toHaveLength(1); + }); + + it("retains the full path tooltip for non-image file references without fetching an image", async () => { + const path = "/workspace/projects/reports/data.json"; + const loadPreview = vi.fn(); + render( + + ); + fireEvent.focus(screen.getByRole("button", { name: path })); + expect(await screen.findByRole("tooltip")).toHaveTextContent(path); + expect(loadPreview).not.toHaveBeenCalled(); + }); +}); diff --git a/webui/src/tests/image-lightbox.test.tsx b/webui/src/tests/image-lightbox.test.tsx new file mode 100644 index 000000000..21ff4ba70 --- /dev/null +++ b/webui/src/tests/image-lightbox.test.tsx @@ -0,0 +1,88 @@ +import { fireEvent, render, screen, within } from "@testing-library/react"; +import { describe, expect, it } from "vitest"; + +import { ImageLightbox } from "@/components/ImageLightbox"; +import { ZoomableImage } from "@/components/ZoomableImage"; + +function renderImage() { + const result = render(); + const viewport = screen.getByTestId("image-zoom-viewport"); + const image = screen.getByRole("img", { name: "Test chart" }); + Object.defineProperties(viewport, { clientWidth: { value: 800 }, clientHeight: { value: 600 } }); + Object.defineProperties(image, { offsetWidth: { value: 800 }, offsetHeight: { value: 600 } }); + viewport.getBoundingClientRect = () => new DOMRect(0, 0, 800, 600); + return { ...result, viewport, image }; +} + +function wheel(target: Element, deltaY: number, ctrlKey = true) { + const event = new WheelEvent("wheel", { deltaY, bubbles: true, cancelable: true }); + // happy-dom 16's WheelEvent extends UIEvent instead of MouseEvent and drops these fields. + Object.defineProperties(event, { ctrlKey: { value: ctrlKey }, clientX: { value: 400 }, clientY: { value: 300 } }); + return fireEvent(target, event); +} + +describe("image zoom", () => { + it("pinches around the two-finger midpoint, then drags with the remaining finger", () => { + const { viewport, image } = renderImage(); + fireEvent.pointerDown(viewport, { pointerId: 1, pointerType: "touch", button: 0, clientX: 300, clientY: 300 }); + fireEvent.pointerDown(viewport, { pointerId: 2, pointerType: "touch", button: 0, clientX: 500, clientY: 300 }); + fireEvent.pointerMove(viewport, { pointerId: 2, pointerType: "touch", clientX: 700, clientY: 300 }); + expect(image.style.transform).toBe("translate3d(100px, 0px, 0) scale(2)"); + fireEvent.pointerUp(viewport, { pointerId: 2, pointerType: "touch" }); + fireEvent.pointerMove(viewport, { pointerId: 1, pointerType: "touch", clientX: 400, clientY: 300 }); + expect(image.style.transform).toBe("translate3d(200px, 0px, 0) scale(2)"); + fireEvent.pointerMove(viewport, { pointerId: 1, pointerType: "touch", clientX: 9000, clientY: 9000 }); + expect(image.style.transform).toBe("translate3d(400px, 300px, 0) scale(2)"); + fireEvent.pointerCancel(viewport, { pointerId: 1 }); + fireEvent.pointerMove(viewport, { pointerId: 1, clientX: 300, clientY: 300 }); + expect(image.style.transform).toBe("translate3d(400px, 300px, 0) scale(2)"); + expect(viewport.className).not.toContain("cursor-grabbing"); + fireEvent.click(screen.getByRole("button", { name: "Fit image" })); + expect(image.style.transform).toBe("translate3d(0px, 0px, 0) scale(1)"); + }); + + it("supports trackpad pinch without hijacking browser zoom outside the image", () => { + const { viewport, image } = renderImage(); + expect(wheel(viewport, 20, false)).toBe(true); + expect(wheel(viewport, -50)).toBe(false); + expect(image.style.transform).toContain(`scale(${Math.exp(0.5)})`); + expect(wheel(document.body, -50)).toBe(true); + expect(wheel(viewport, 20, false)).toBe(false); + expect(image.style.transform).toContain("-20px"); + for (let i = 0; i < 10; i++) wheel(viewport, -50); + expect(image.style.transform).toContain("scale(8)"); + expect(screen.getByRole("button", { name: "Zoom in" })).toBeDisabled(); + for (let i = 0; i < 10; i++) wheel(viewport, 50); + expect(image.style.transform).toBe("translate3d(0px, 0px, 0) scale(1)"); + expect(screen.getByRole("button", { name: "Zoom out" })).toBeDisabled(); + }); + + it("supports double-click, keyboard and visible controls", () => { + const { viewport, image } = renderImage(); + fireEvent.doubleClick(viewport, { clientX: 400, clientY: 300 }); + expect(image.style.transform).toContain("scale(2)"); + fireEvent.doubleClick(viewport, { clientX: 400, clientY: 300 }); + expect(image.style.transform).toContain("scale(1)"); + fireEvent.keyDown(viewport, { key: "+" }); + expect(screen.getByRole("button", { name: "Fit image" })).toHaveTextContent("150%"); + fireEvent.keyDown(viewport, { key: "0" }); + fireEvent.click(screen.getByRole("button", { name: "Zoom in" })); + fireEvent.click(screen.getByRole("button", { name: "Zoom out" })); + expect(image.style.transform).toContain("scale(1)"); + }); + + it("resets zoom when switching images and reopening the lightbox", () => { + const images = [{ url: "data:image/png;base64,a", name: "A" }, { url: "data:image/png;base64,b", name: "B" }]; + const view = (index: number | null) => {}} onOpenChange={() => {}} />; + const { rerender } = render(view(0)); + fireEvent.click(screen.getByRole("button", { name: "Zoom in" })); + expect(screen.getByRole("button", { name: "Fit image" })).toHaveTextContent("150%"); + rerender(view(1)); + expect(within(screen.getByRole("dialog")).getByRole("img", { name: "B" }).style.transform).toContain("scale(1)"); + fireEvent.click(screen.getByRole("button", { name: "Zoom in" })); + rerender(view(null)); + expect(screen.queryByRole("dialog")).not.toBeInTheDocument(); + rerender(view(1)); + expect(screen.getByRole("button", { name: "Fit image" })).toHaveTextContent("100%"); + }); +}); diff --git a/webui/src/tests/markdown-text-renderer.test.tsx b/webui/src/tests/markdown-text-renderer.test.tsx index a17cd9c61..66904d516 100644 --- a/webui/src/tests/markdown-text-renderer.test.tsx +++ b/webui/src/tests/markdown-text-renderer.test.tsx @@ -265,10 +265,7 @@ describe("MarkdownTextRenderer", () => { const image = screen.getByRole("img", { name: "Diagram" }); expect(image).toHaveAttribute("src", "/api/media/sig/payload"); - expect(screen.getByRole("link", { name: "Open Diagram" })).toHaveAttribute( - "href", - "/api/media/sig/payload", - ); + expect(screen.getByRole("button", { name: "View image: Diagram" })).toBeInTheDocument(); }); it("renders markdown videos as inline players", () => { @@ -378,10 +375,7 @@ describe("MarkdownTextRenderer", () => { "src", "/api/media/sig/payload", ); - expect(screen.getByRole("link", { name: "Open Diagram" })).toHaveAttribute( - "href", - "/api/media/sig/payload", - ); + expect(screen.getByRole("button", { name: "View image: Diagram" })).toBeInTheDocument(); expect(screen.queryByRole("button", { name: "Code" })).not.toBeInTheDocument(); }); diff --git a/webui/src/tests/message-bubble.test.tsx b/webui/src/tests/message-bubble.test.tsx index 335ab4007..60b907c91 100644 --- a/webui/src/tests/message-bubble.test.tsx +++ b/webui/src/tests/message-bubble.test.tsx @@ -1158,7 +1158,7 @@ describe("MessageBubble", () => { const { container } = render(); const imageButton = screen.getByRole("button", { name: /view image/i }); - expect(imageButton).toHaveClass("w-[min(100%,34rem)]", "rounded-panel"); + expect(imageButton).toHaveClass("w-[min(100%,28rem)]", "rounded-control"); expect(imageButton).toHaveClass( "border", "border-border/60", diff --git a/webui/src/tests/pane-workbench.test.tsx b/webui/src/tests/pane-workbench.test.tsx index 22c0bbe5c..6ce8c2a13 100644 --- a/webui/src/tests/pane-workbench.test.tsx +++ b/webui/src/tests/pane-workbench.test.tsx @@ -108,6 +108,18 @@ function BspWorkbenchHarness() { } describe("PaneWorkbench", () => { + it("keeps a single conversation's header inside that pane instead of above its previews", () => { + render( { + expect(context.headerPortalTarget).toBeUndefined(); + return
{context.headerActions}
; + }} />); + expect(screen.getByTestId("workbench-header-host")).toBeEmptyDOMElement(); + expect(within(screen.getByTestId("local-toolbar")).getByRole("button", { name: "Add pane" })).toBeVisible(); + }); + const originalGetBoundingClientRect = HTMLElement.prototype.getBoundingClientRect; const originalAnimate = HTMLElement.prototype.animate; const animate = vi.fn(() => ({ diff --git a/webui/src/tests/preview-pane.test.tsx b/webui/src/tests/preview-pane.test.tsx new file mode 100644 index 000000000..ee8054972 --- /dev/null +++ b/webui/src/tests/preview-pane.test.tsx @@ -0,0 +1,108 @@ +import { act, fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { describe, expect, it, vi } from "vitest"; +import { PreviewPane } from "@/components/PreviewPane"; +import { FilePreviewStore, useFilePreviewState } from "@/hooks/useFilePreviewState"; + +describe("preview tabs", () => { + it("deduplicates targets, keeps selection and width per session, and closes neighboring tabs", () => { + const store = new FilePreviewStore(); + const storage = vi.spyOn(Storage.prototype, "setItem"); + store.open("a", "file", "chart.png"); + store.open("a", "file", "index.html"); + store.open("a", "file", "data.json"); + store.update("a", { width: 620 }); + store.open("a", "file", "index.html"); + expect(store.get("a").tabs).toHaveLength(3); + expect(store.get("a").activeId).toBe("file:index.html"); + store.closeTab("a", "file:chart.png"); + expect(store.get("a").activeId).toBe("file:index.html"); + store.closeTab("a", "file:index.html"); + expect(store.get("a").activeId).toBe("file:data.json"); + store.select("a", "missing"); + store.closeTab("a", "missing"); + expect(store.get("a").activeId).toBe("file:data.json"); + store.open("b", "web", "https://example.com"); + expect(store.get("a").width).toBe(620); + store.closeTab("a", "file:data.json"); + expect(store.get("a")).toMatchObject({ tabs: [], activeId: null, width: 620 }); + expect(store.get("b").tabs).toHaveLength(1); + store.open("a", "file", "chart.png"); + store.close("a"); + expect(store.get("a")).toMatchObject({ tabs: [], activeId: null, width: 620 }); + store.delete("b"); + store.clear(); + expect(store.get("a").tabs).toEqual([]); + expect(store.get("b").tabs).toEqual([]); + expect(storage).not.toHaveBeenCalled(); + storage.mockRestore(); + }); + + it("keeps one shell, supports keyboard tabs and close buttons, and never reloads the same tab", async () => { + const store = new FilePreviewStore(); + store.open("a", "file", "chart.png"); + store.open("a", "file", "index.html"); + store.open("a", "file", "data.json"); + function View() { + const { state, selectTab, closeTab, close } = useFilePreviewState("a", store); + return state.activeId ? {}}> +

{state.activeId}

+
: null; + } + render(); + const shell = screen.getByTestId("preview-pane"); + const highlight = screen.getByTestId("preview-tabs-selection-highlight"); + expect(highlight).toHaveAttribute("data-active-id", "file:data.json"); + expect(highlight.className).toContain("bg-sidebar-foreground/[0.055]"); + expect(highlight.className).toContain("motion-reduce:transition-none"); + await waitFor(() => expect(shell.style.getPropertyValue("--file-preview-slot-width")).toBe("544px")); + fireEvent.click(screen.getByRole("tab", { name: "chart.png" })); + expect(screen.getByTestId("preview-pane")).toBe(shell); + expect(screen.getByTestId("preview-tabs-selection-highlight")).toBe(highlight); + expect(highlight).toHaveAttribute("data-active-id", "file:chart.png"); + expect(shell.style.getPropertyValue("--file-preview-slot-width")).toBe("544px"); + expect(screen.getByRole("tabpanel")).toHaveTextContent("file:chart.png"); + fireEvent.keyDown(screen.getByRole("tab", { name: "chart.png" }), { key: "ArrowRight" }); + expect(screen.getByRole("tab", { name: "index.html" })).toHaveFocus(); + expect(screen.getByRole("tab", { name: "index.html" })).toHaveAttribute("aria-selected", "true"); + act(() => store.open("a", "file", "index.html")); + expect(screen.getAllByRole("tab")).toHaveLength(3); + fireEvent.keyDown(screen.getByRole("tab", { name: "index.html" }), { key: "Delete" }); + expect(screen.queryByRole("tab", { name: "index.html" })).not.toBeInTheDocument(); + expect(screen.getByRole("tab", { name: "data.json" })).toHaveFocus(); + fireEvent.click(screen.getByRole("button", { name: "Close chart.png" })); + expect(screen.getByRole("tab", { name: "data.json" })).toHaveAttribute("aria-selected", "true"); + expect(screen.queryByRole("button", { name: "Close preview pane" })).not.toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: "Close data.json" })); + expect(screen.queryByTestId("preview-pane")).not.toBeInTheDocument(); + }); + + it("reveals the whole active tab including its close button after the tab strip resizes", () => { + let resize: (() => void) | undefined; + const observe = vi.fn(); + const disconnect = vi.fn(); + vi.stubGlobal("ResizeObserver", class { + constructor(callback: () => void) { resize = callback; } + observe = observe; + disconnect = disconnect; + }); + try { + const tab = { id: "file:chart.png", kind: "file" as const, value: "chart.png" }; + const view = render( {}} onCloseTab={() => {}} onClose={() => {}} onResizeStart={() => {}}> +

Preview

+
); + const wholeTab = screen.getByRole("tab", { name: "chart.png" }).parentElement!; + const reveal = vi.fn(); + wholeTab.scrollIntoView = reveal; + expect(wholeTab).toContainElement(screen.getByRole("button", { name: "Close chart.png" })); + expect(observe).toHaveBeenCalledWith(screen.getByRole("tablist")); + act(() => resize?.()); + expect(reveal).toHaveBeenCalledWith({ block: "nearest", inline: "nearest" }); + view.unmount(); + expect(disconnect).toHaveBeenCalled(); + } finally { + vi.unstubAllGlobals(); + } + }); +}); diff --git a/webui/src/tests/temporary-chat-navigation.test.tsx b/webui/src/tests/temporary-chat-navigation.test.tsx index 5c6c3a578..b472dff9c 100644 --- a/webui/src/tests/temporary-chat-navigation.test.tsx +++ b/webui/src/tests/temporary-chat-navigation.test.tsx @@ -174,18 +174,50 @@ describe("temporary chat navigation", () => { } else { expect(vi.mocked(fetch).mock.calls.some(([url]) => String(url).includes("path=notes.txt&metadata=1"))).toBe(true); } - fireEvent.click(screen.getByRole("menuitem", { name: "Preview" })); + fireEvent.keyDown(screen.getByRole("menu"), { key: "Escape" }); + await waitFor(() => expect(screen.queryByRole("menu")).not.toBeInTheDocument()); + fireEvent.click(screen.getByRole("button", { name: "notes.txt" })); await screen.findByText("Preview of notes.txt"); + fireEvent.click(screen.getByRole("button", { name: "second.txt" })); + await screen.findByText("Preview of second.txt"); + const pane = screen.getByTestId("preview-pane"); + expect(within(pane).getAllByText("second.txt")).toHaveLength(1); + expect(within(pane).queryByRole("navigation", { name: "File path" })).not.toBeInTheDocument(); + expect(within(pane).queryByRole("button", { name: /File actions/ })).not.toBeInTheDocument(); + fireEvent.contextMenu(within(pane).getByRole("tab", { name: "second.txt" })); + await waitFor(() => expect(screen.getByRole("menuitem", { name: "Copy absolute path" })).not.toHaveAttribute("data-disabled")); + if (temporary) { + expect(TestSocket.current.sent).toContainEqual(expect.objectContaining({ + type: "webui_request", action: "temporary_chat.file_preview", + payload: expect.objectContaining({ path: "second.txt", metadata: true }), + })); + } else { + expect(vi.mocked(fetch).mock.calls.some(([url]) => String(url).includes("path=second.txt&metadata=1"))).toBe(true); + } + fireEvent.keyDown(screen.getByRole("menu"), { key: "Escape" }); + await waitFor(() => expect(screen.queryByRole("menu")).not.toBeInTheDocument()); + expect(screen.getByTestId("preview-pane")).toBe(pane); + const previewRequestCount = () => temporary + ? TestSocket.current.sent.filter((frame) => frame.type === "webui_request" && frame.action === "temporary_chat.file_preview" + && frame.payload?.path === "notes.txt" && !frame.payload?.metadata && !frame.payload?.probe).length + : vi.mocked(fetch).mock.calls.filter(([url]) => String(url).includes("/file-preview?path=notes.txt") + && !String(url).includes("metadata=") && !String(url).includes("probe=")).length; + const beforeReturn = previewRequestCount(); + fireEvent.click(screen.getByRole("tab", { name: "notes.txt" })); + expect(screen.getByText("Preview of notes.txt")).toBeInTheDocument(); + expect(previewRequestCount()).toBe(beforeReturn); await selectTopic("Second pane"); expect(screen.queryByTestId("file-preview-panel")).not.toBeInTheDocument(); fireEvent.click(await screen.findByRole("button", { name: "second.txt" })); await screen.findByText("Preview of second.txt"); await selectTopic(temporary ? "Show example files" : "Regular topic"); await screen.findByText("Preview of notes.txt"); + expect(screen.getAllByRole("tab")).toHaveLength(2); + expect(screen.getByRole("tab", { name: "notes.txt" })).toHaveAttribute("aria-selected", "true"); expect(screen.queryByText("Preview of second.txt")).not.toBeInTheDocument(); // Explicit close must stick even if switching interrupts the close animation. - fireEvent.click(screen.getByRole("button", { name: "Close file preview" })); + fireEvent.click(screen.getByRole("button", { name: "Close preview pane" })); await selectTopic("Second pane"); await selectTopic(temporary ? "Show example files" : "Regular topic"); expect(screen.queryByTestId("file-preview-panel")).not.toBeInTheDocument(); @@ -212,7 +244,7 @@ describe("temporary chat navigation", () => { fireEvent.click(await screen.findByRole("menuitem", { name: "Preview website" })); await screen.findByTestId("web-preview-panel"); await selectTopic("Synthetic separate session"); - expect(screen.queryByTestId("web-preview-panel")).not.toBeInTheDocument(); + await waitFor(() => expect(screen.queryByTestId("web-preview-panel")).not.toBeInTheDocument()); await selectTopic("Regular topic"); await screen.findByTestId("web-preview-panel"); fireEvent.contextMenu(screen.getByRole("link", { name: "Website" })); @@ -221,24 +253,24 @@ describe("temporary chat navigation", () => { expect(screen.getByTestId("web-preview-panel")).toBeInTheDocument(); await waitFor(() => expect(screen.queryByRole("menu")).not.toBeInTheDocument()); fireEvent.keyDown(window, { key: "Escape" }); - expect(screen.queryByTestId("web-preview-panel")).not.toBeInTheDocument(); + await waitFor(() => expect(screen.queryByTestId("web-preview-panel")).not.toBeInTheDocument()); fireEvent.contextMenu(screen.getByRole("link", { name: "Website" })); fireEvent.click(await screen.findByRole("menuitem", { name: "Preview website" })); fireEvent.click(screen.getByRole("button", { name: "notes.txt" })); - expect(screen.queryByTestId("web-preview-panel")).not.toBeInTheDocument(); + await waitFor(() => expect(screen.queryByTestId("web-preview-panel")).not.toBeInTheDocument()); await screen.findByText("Preview of notes.txt"); fireEvent.contextMenu(screen.getByRole("link", { name: "Website" })); fireEvent.click(await screen.findByRole("menuitem", { name: "Preview website" })); expect(screen.queryByTestId("file-preview-panel")).not.toBeInTheDocument(); - fireEvent.click(screen.getByRole("button", { name: "Close website preview" })); - expect(screen.queryByTestId("web-preview-panel")).not.toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: "Close preview pane" })); + await waitFor(() => expect(screen.queryByTestId("web-preview-panel")).not.toBeInTheDocument()); for (const storage of [localStorage, sessionStorage]) { const values = Array.from({ length: storage.length }, (_, i) => storage.getItem(storage.key(i)!)); expect(JSON.stringify(values)).not.toContain("https://example.com/demo"); } }); - it("toggles the current file, switches files, and only handles Escape below dialogs", async () => { + it("keeps the sidebar mounted across tabs, deduplicates repeated opens, and handles Escape below dialogs", async () => { withFiles = true; render(); await screen.findByRole("button", { name: "Temporary chat" }); @@ -248,8 +280,15 @@ describe("temporary chat navigation", () => { await screen.findByText("Preview of notes.txt"); fireEvent.click(screen.getByRole("button", { name: "second.txt" })); await screen.findByText("Preview of second.txt"); + const pane = screen.getByTestId("preview-pane"); fireEvent.click(screen.getByRole("button", { name: "second.txt" })); - await waitFor(() => expect(screen.queryByTestId("file-preview-panel")).not.toBeInTheDocument()); + expect(screen.getByTestId("preview-pane")).toBe(pane); + expect(screen.getAllByRole("tab")).toHaveLength(2); + expect(screen.getByRole("tab", { name: "second.txt" })).toHaveAttribute("aria-selected", "true"); + fireEvent.click(screen.getByRole("button", { name: "Close second.txt" })); + await screen.findByText("Preview of notes.txt"); + expect(screen.getByTestId("preview-pane")).toBe(pane); + expect(screen.getAllByRole("tab")).toHaveLength(1); fireEvent.click(screen.getByRole("button", { name: "notes.txt" })); await screen.findByText("Preview of notes.txt"); const dialog = document.createElement("div"); @@ -263,7 +302,7 @@ describe("temporary chat navigation", () => { }); it("forgets preview paths on temporary close and disconnect", async () => { - const update = vi.spyOn(FilePreviewStore.prototype, "update"); + const update = vi.spyOn(FilePreviewStore.prototype, "open"); render(); await screen.findByRole("button", { name: "Temporary chat" }); act(() => TestSocket.current.open()); @@ -273,14 +312,14 @@ describe("temporary chat navigation", () => { })); fireEvent.click(await screen.findByRole("button", { name: "notes.txt" })); await screen.findByText("Preview of notes.txt"); - const store = update.mock.contexts.find((value) => value.get(`websocket:${chatId}`).path)!; - expect(store.get(`websocket:${chatId}`).path).toBe("notes.txt"); + const store = update.mock.contexts.find((value) => value.get(`websocket:${chatId}`).tabs.length)!; + expect(store.get(`websocket:${chatId}`).activeId).toBe("file:notes.txt"); await selectTopic("Close temporary chat: Show example files"); - expect(store.get(`websocket:${chatId}`).path).toBeNull(); - act(() => store.update("websocket:regular", { path: "notes.txt" })); + expect(store.get(`websocket:${chatId}`).tabs).toEqual([]); + act(() => store.open("websocket:regular", "file", "notes.txt")); vi.useFakeTimers(); act(() => TestSocket.current.close()); - expect(store.get("websocket:regular").path).toBeNull(); + expect(store.get("websocket:regular").tabs).toEqual([]); }); it("keeps messages when navigating to a regular workbench and back", async () => { diff --git a/webui/src/tests/web-preview.test.tsx b/webui/src/tests/web-preview.test.tsx index b9e55d43e..47033f92d 100644 --- a/webui/src/tests/web-preview.test.tsx +++ b/webui/src/tests/web-preview.test.tsx @@ -40,8 +40,7 @@ describe("web preview boundaries", () => { expect(webPreviewRestriction(external, page, false, true)).toBeNull(); }); it("embeds only on mount, without credentials/referrer/host permissions, and refreshes with a new frame", async () => { - const close = vi.fn(); - const { container } = render(); + const { container } = render(); const frame = container.querySelector("iframe")!; expect(frame).toHaveAttribute("src", "https://example.com/demo"); expect(frame).toHaveAttribute("sandbox", "allow-scripts"); @@ -50,27 +49,29 @@ describe("web preview boundaries", () => { expect(frame.getAttribute("allow")).toContain("clipboard-read 'none'"); // A frame load event is not evidence that CSP/X-Frame-Options allowed embedding. fireEvent.load(frame); - expect(screen.getByText(/Some sites block embedding/)).toBeInTheDocument(); + expect(screen.queryByText(/Some sites block embedding/)).not.toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: "About website previews" })); + expect(await screen.findByText(/Some sites block embedding/)).toBeInTheDocument(); + await userEvent.setup().keyboard("{Escape}"); fireEvent.click(screen.getByRole("button", { name: "Refresh website" })); expect(container.querySelector("iframe")).not.toBe(frame); expect(screen.getByRole("link", { name: "Open in browser" })).toHaveAttribute("rel", "noreferrer noopener"); - fireEvent.click(screen.getByRole("button", { name: "Close website preview" })); - expect(close).toHaveBeenCalledOnce(); }); it("does not load an iframe in native or unsupported browsers", () => { vi.mocked(isNativeRuntime).mockReturnValue(true); - const { container, rerender } = render( {}} />); + const { container, rerender } = render(); expect(container.querySelector("iframe")).toBeNull(); expect(screen.getByRole("status")).toHaveTextContent(/native host/); vi.mocked(isNativeRuntime).mockReturnValue(false); Reflect.deleteProperty(HTMLIFrameElement.prototype, "credentialless"); - rerender( {}} />); + rerender(); expect(container.querySelector("iframe")).toBeNull(); expect(screen.getByRole("status")).toHaveTextContent(/does not support/); }); - it("explains that loopback belongs to the browsing device", () => { - render( {}} />); - expect(screen.getByText(/not a remote gateway/)).toBeInTheDocument(); + it("explains that loopback belongs to the browsing device on request", async () => { + render(); + fireEvent.click(screen.getByRole("button", { name: "About website previews" })); + expect(await screen.findByText(/not a remote gateway/)).toBeInTheDocument(); }); }); @@ -105,12 +106,12 @@ describe("web link actions", () => { }); }); -it("keeps mutually exclusive preview targets per session, clears them on deletion, and never persists URLs", () => { +it("keeps file and website tabs per session, clears them on deletion, and never persists URLs", () => { const store = new FilePreviewStore(); const local = vi.spyOn(Storage.prototype, "setItem"); function View({ session }: { session: string }) { - const { state, setWebUrl, setPath } = useFilePreviewState(session, store); - return <>{state.webUrl ?? state.path ?? "closed"}; + const { state, openWeb, openFile } = useFilePreviewState(session, store); + return <>{state.tabs.find((tab) => tab.id === state.activeId)?.value ?? "closed"}; } const { rerender } = render(); fireEvent.click(screen.getByText("Web")); @@ -120,12 +121,14 @@ it("keeps mutually exclusive preview targets per session, clears them on deletio rerender(); expect(screen.getByRole("status")).toHaveTextContent("https://example.com/preview"); fireEvent.click(screen.getByText("File")); - expect(store.get("a")).toMatchObject({ path: "notes.txt", webUrl: null }); + expect(store.get("a").activeId).toBe("file:notes.txt"); + expect(store.get("a").tabs).toHaveLength(2); fireEvent.click(screen.getByText("Web")); - expect(store.get("a").path).toBeNull(); + expect(store.get("a").activeId).toBe("web:https://example.com/preview"); + expect(store.get("a").tabs).toHaveLength(2); act(() => store.delete("a")); expect(screen.getByRole("status")).toHaveTextContent("closed"); act(() => store.clear()); - expect(store.get("b").path).toBeNull(); + expect(store.get("b").tabs).toEqual([]); expect(local).not.toHaveBeenCalled(); });