Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
167 changes: 167 additions & 0 deletions src/components/AttachmentPreview.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
// Same-origin image thumbnails and an in-app lightbox. Transcript text can
// contain arbitrary strings, so callers pass saved paths and this component
// resolves them through attachmentImageUrl rather than loading them as URLs.
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { Download, ImageOff, Maximize2, X } from "lucide-react";

import { attachmentBasename, attachmentImageUrl } from "@/lib/composer-attachments";
import { cn } from "@/lib/cn";

export interface PreviewImage {
src: string;
name: string;
}

export function previewImage(path: string): PreviewImage | null {
const src = attachmentImageUrl(path);
if (!src) return null;
return { src, name: attachmentBasename(path) };
}

export function AttachmentPreviewDialog({ image, onClose }: { image: PreviewImage; onClose: () => void }) {
const dialogRef = useRef<HTMLDivElement>(null);
const closeRef = useRef(onClose);
const [failed, setFailed] = useState(false);

useLayoutEffect(() => {
closeRef.current = onClose;
}, [onClose]);

useEffect(() => {
const previousFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null;
dialogRef.current?.focus();
const onKey = (event: KeyboardEvent) => {
if (event.key === "Escape") {
event.preventDefault();
closeRef.current();
return;
}
if (event.key !== "Tab") return;
const dialog = dialogRef.current;
if (!dialog) return;
const focusable = [...dialog.querySelectorAll<HTMLElement>(
'button:not([disabled]), [href], [tabindex]:not([tabindex="-1"])',
)];
if (focusable.length === 0) {
event.preventDefault();
dialog.focus();
return;
}
const first = focusable[0];
const last = focusable[focusable.length - 1];
if (event.shiftKey && (document.activeElement === dialog || document.activeElement === first)) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && document.activeElement === last) {
event.preventDefault();
first.focus();
Comment thread
coderabbitai[bot] marked this conversation as resolved.
}
};
window.addEventListener("keydown", onKey);
return () => {
window.removeEventListener("keydown", onKey);
previousFocus?.focus();
};
}, []);

return createPortal(
<div
className="fixed inset-0 z-[70] flex items-center justify-center bg-black/80 p-3 backdrop-blur-sm sm:p-6"
onMouseDown={(event) => event.target === event.currentTarget && onClose()}
>
<div
ref={dialogRef}
role="dialog"
aria-modal="true"
aria-label={`Preview ${image.name}`}
tabIndex={-1}
className="animate-pop-in flex h-full max-h-[900px] w-full max-w-[1200px] flex-col overflow-hidden rounded-2xl border border-white/15 bg-black/70 shadow-2xl outline-none"
>
<header className="flex shrink-0 items-center justify-between gap-4 border-b border-white/10 bg-black/45 px-4 py-3">
<div className="min-w-0">
<div className="truncate text-[13px] font-medium text-white">{image.name}</div>
<div className="text-[10.5px] text-white/50">Saved locally by OpenMausBot</div>
</div>
<div className="flex shrink-0 items-center gap-1">
<a
href={image.src}
download={image.name}
className="flex size-9 items-center justify-center rounded-lg text-white/65 hover:bg-white/10 hover:text-white"
aria-label={`Download ${image.name}`}
title="Download"
>
<Download size={17} />
</a>
<button
onClick={onClose}
className="flex size-9 items-center justify-center rounded-lg text-white/65 hover:bg-white/10 hover:text-white"
aria-label="Close image preview"
>
<X size={19} />
</button>
</div>
</header>
<div className="flex min-h-0 flex-1 items-center justify-center overflow-auto p-4 sm:p-8">
{failed ? (
<div className="flex flex-col items-center gap-3 text-white/60" role="status">
<ImageOff size={34} />
<span className="text-[13px]">This attachment is no longer available.</span>
</div>
) : (
<img
src={image.src}
alt={image.name}
onError={() => setFailed(true)}
className="block max-h-full max-w-full rounded-lg object-contain shadow-2xl"
/>
)}
</div>
</div>
</div>,
document.body,
);
}

function Thumbnail({ image, onPreview }: { image: PreviewImage; onPreview: () => void }) {
const [failed, setFailed] = useState(false);
if (failed) return null;
return (
<button
onClick={onPreview}
className="group/image relative block max-w-[260px] overflow-hidden rounded-lg border border-hairline/40 bg-inset text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/50"
aria-label={`Preview attached image ${image.name}`}
title={`Preview ${image.name}`}
>
<img
src={image.src}
alt={image.name}
loading="lazy"
onError={() => setFailed(true)}
className="block max-h-[220px] w-full object-cover transition-transform duration-200 group-hover/image:scale-[1.015]"
/>
<span className="absolute right-1.5 top-1.5 flex size-7 items-center justify-center rounded-full bg-black/55 text-white opacity-0 backdrop-blur-sm transition-opacity group-hover/image:opacity-100 group-focus-visible/image:opacity-100">
<Maximize2 size={13} />
</span>
</button>
);
}

export function AttachedImageGallery({ paths, className }: { paths: string[]; className?: string }) {
const images = useMemo(() => paths.flatMap((path) => {
const image = previewImage(path);
return image ? [image] : [];
}), [paths]);
const [selected, setSelected] = useState<PreviewImage | null>(null);
if (images.length === 0) return null;
return (
<>
<div className={cn("mb-2 flex flex-wrap justify-end gap-2", className)}>
{images.map((image, index) => (
<Thumbnail key={`${image.src}:${index}`} image={image} onPreview={() => setSelected(image)} />
))}
</div>
{selected && <AttachmentPreviewDialog image={selected} onClose={() => setSelected(null)} />}
</>
);
}
23 changes: 3 additions & 20 deletions src/components/ChatView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ import { ApprovalCard } from "./ApprovalCard";
import { Composer } from "./Composer";
import { ConnectorCard } from "./ConnectorCard";
import { SecretRequestCard } from "./SecretRequestCard";
import { AttachedImageGallery } from "./AttachmentPreview";
import { ModelPicker } from "./ModelPicker";
import { RenameTitle } from "./RenameTitle";
import { TaskPicker } from "./TaskPicker";
Expand All @@ -54,7 +55,7 @@ import { cn } from "@/lib/cn";
import { COMPACT_BUBBLE, COMPACT_SQUARE } from "@/lib/compact-chip";
import { useFocusMessage } from "@/lib/focus-message";
import { webhookMessageView } from "@/lib/webhook-message";
import { attachmentBasename, splitAttachedImages } from "@/lib/composer-attachments";
import { splitAttachedImages } from "@/lib/composer-attachments";
import { BOTTOM_FOLLOW_THRESHOLD, shouldResumeBottomFollow } from "@/lib/bottom-follow";
import {
TRANSCRIPT_WINDOW_SIZE,
Expand Down Expand Up @@ -421,25 +422,7 @@ function Bubble({
) : user ? (
<>
{attachedImages && attachedImages.images.length > 0 && (
<div className="mb-2 flex flex-wrap justify-end gap-2">
{attachedImages.images.map((path) => (
<a
key={path}
href={`/api/attachments/${encodeURIComponent(attachmentBasename(path))}`}
target="_blank"
rel="noreferrer"
className="block max-w-[260px] overflow-hidden rounded-lg border border-hairline/40"
title={path}
>
<img
src={`/api/attachments/${encodeURIComponent(attachmentBasename(path))}`}
alt="Attached image"
loading="lazy"
className="block max-h-[220px] w-full object-cover"
/>
</a>
))}
</div>
<AttachedImageGallery paths={attachedImages.images} />
)}
<div
className={cn(collapsible && "max-h-40 overflow-hidden [mask-image:linear-gradient(to_bottom,black_60%,transparent)]")}
Expand Down
18 changes: 13 additions & 5 deletions src/components/ComposerAttachments.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,14 @@ import { useEffect, useRef, useState } from "react";
import { ClipboardPaste, File as FileIcon, Image as ImageIcon, X } from "lucide-react";
import { cn } from "@/lib/cn";
import {
attachmentBasename,
attachmentImageUrl,
intakeFiles,
formatSize,
imageAttachmentFromFile,
pasteSummary,
type Attachment,
} from "@/lib/composer-attachments";
import { AttachmentPreviewDialog, previewImage, type PreviewImage } from "./AttachmentPreview";

/** Electron 32 removed File.path — only the preload can name a file. */
export function pathForFile(file: File): string {
Expand All @@ -35,6 +36,7 @@ export function ComposerAttachments({
onNotice: (notice: string | null) => void;
}) {
const [dragging, setDragging] = useState(false);
const [preview, setPreview] = useState<PreviewImage | null>(null);
// dragenter/dragleave fire once per element crossed, so the overlay
// tracks depth rather than the last event it happened to see
const depth = useRef(0);
Expand Down Expand Up @@ -133,15 +135,20 @@ export function ComposerAttachments({
<div className="mt-1 text-[10.5px] text-ink-secondary/70">{pasteSummary(a)}</div>
</Chip>
) : a.kind === "image" ? (
<Chip key={a.id} label="IMAGE" title={a.path} onRemove={() => onRemove(a.id)}>
<div className="flex h-[76px] items-center justify-center overflow-hidden rounded-lg bg-inset">
<Chip key={a.id} label="IMAGE" title={a.name} onRemove={() => onRemove(a.id)}>
<button
type="button"
onClick={() => setPreview(previewImage(a.path))}
className="flex h-[76px] w-full items-center justify-center overflow-hidden rounded-lg bg-inset focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/50"
aria-label={`Preview ${a.name}`}
>
<img
src={`/api/attachments/${encodeURIComponent(attachmentBasename(a.path))}`}
src={attachmentImageUrl(a.path) ?? undefined}
alt={a.name}
loading="lazy"
className="max-h-[76px] max-w-full object-contain"
/>
</div>
</button>
<div className="mt-1 truncate text-[10.5px] text-ink-secondary/70">{formatSize(a.size)}</div>
</Chip>
) : (
Expand All @@ -158,6 +165,7 @@ export function ComposerAttachments({
)}
</div>
)}
{preview && <AttachmentPreviewDialog image={preview} onClose={() => setPreview(null)} />}
</>
);
}
Expand Down
12 changes: 11 additions & 1 deletion src/components/GroupView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { ChatMarkdown } from "./ChatMarkdown";
import { Composer } from "./Composer";
import { ConnectorCard } from "./ConnectorCard";
import { SecretRequestCard } from "./SecretRequestCard";
import { AttachedImageGallery } from "./AttachmentPreview";
import { GroupCallButton, GroupCallOverlay } from "./GroupCallView";
import { ReactionBar, ReactionChips } from "./Reactions";
import { ApprovalCard } from "./ApprovalCard";
Expand All @@ -31,6 +32,7 @@ import { useFocusMessage } from "@/lib/focus-message";
import { shortPath } from "@/lib/short-path";
import { BOTTOM_FOLLOW_THRESHOLD, shouldResumeBottomFollow } from "@/lib/bottom-follow";
import { showWorkingDots } from "@/lib/turn-tail";
import { splitAttachedImages } from "@/lib/composer-attachments";
import {
TRANSCRIPT_WINDOW_SIZE,
expandWindowStart,
Expand Down Expand Up @@ -106,6 +108,7 @@ const Transcript = memo(function Transcript({
const prev = textMessages[i - 1];
const newDay = !prev || new Date(prev.at).toDateString() !== new Date(m.at).toDateString();
const user = m.role === "user";
const attachedImages = user && m.text ? splitAttachedImages(m.text) : null;
const newCluster = !prev || prev.role !== m.role || prev.from?.botId !== m.from?.botId || newDay;
const row =
// a member can hit a permission ask mid-turn; without this the
Expand Down Expand Up @@ -144,7 +147,14 @@ const Transcript = memo(function Transcript({
)}
title={new Date(m.at).toLocaleString()}
>
{user ? m.text : <ChatMarkdown text={m.text} />}
{user ? (
<>
{attachedImages && attachedImages.images.length > 0 && (
<AttachedImageGallery paths={attachedImages.images} />
)}
{attachedImages?.display ?? m.text}
</>
) : <ChatMarkdown text={m.text} />}
</div>
{!user && <ReactionBar threadId={group.threadId} message={m} />}
<span className="self-end pb-1 text-[11px] tabular-nums text-ink-secondary/70 opacity-0 transition-opacity group-hover:opacity-100">
Expand Down
12 changes: 11 additions & 1 deletion src/lib/composer-attachments.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { describe, expect, it } from "vitest";

import {
attachmentBasename,
attachmentImageUrl,
composeMessage,
isImageFile,
splitAttachedImages,
Expand Down Expand Up @@ -64,6 +65,16 @@ describe("attachmentBasename", () => {
expect(attachmentBasename("/a/b/c.png")).toBe("c.png");
expect(attachmentBasename("C:\\a\\b\\c.png")).toBe("c.png");
});

it("turns only generated image names into same-origin preview URLs", () => {
expect(attachmentImageUrl("/a/b/123e4567-e89b-12d3-a456-426614174000.png")).toBe(
"/api/attachments/123e4567-e89b-12d3-a456-426614174000.png",
);
expect(attachmentImageUrl("C:\\a\\b\\photo.webp")).toBe("/api/attachments/photo.webp");
expect(attachmentImageUrl("https://attacker.example/tracker.png?cookie=1")).toBeNull();
expect(attachmentImageUrl("/a/b/payload.svg")).toBeNull();
expect(attachmentImageUrl("/a/b/not%2Fan-image.png")).toBeNull();
});
});

describe("isImageFile", () => {
Expand All @@ -75,4 +86,3 @@ describe("isImageFile", () => {
expect(isImageFile({ type: "text/plain", size: 10 })).toBe(false);
});
});

10 changes: 10 additions & 0 deletions src/lib/composer-attachments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,16 @@ export function attachmentBasename(path: string): string {
return parts[parts.length - 1] ?? "";
}

/** The renderer never loads a transcript-provided URL directly. Only names
* the attachment server itself can have generated become same-origin image
* URLs; malformed and executable-image paths render nothing, while a string
* that looks remote can at most resolve to a local generated filename. */
export function attachmentImageUrl(path: string): string | null {
const name = attachmentBasename(path);
if (!/^[A-Za-z0-9-]+\.(png|jpg|gif|webp)$/.test(name)) return null;
return `/api/attachments/${encodeURIComponent(name)}`;
}

/** One intake path for files arriving by drop OR by the composer's attach
* button, so a picked file and a dropped one can never behave differently.
* The image uploader is injected: the caller owns the network, this owns
Expand Down
Loading