Files
PaperClipAI/ui/src/components/ImageGalleryModal.tsx
T
DottaandPaperclip a0ac81e114 fix(ui): show task image results in compact thumbnail grids (#19626)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Task feeds show agent messages, documents, and files in time order.
> - Each image currently uses a full feed card.
> - A turn with seven screenshots makes the conversation hard to scan.
> - This pull request groups adjacent images from the same run in a
compact grid.
> - Users can scan the results and open each image in the existing
gallery.

## Linked Issues or Issue Description

**What existing behavior does this improve?**

Image results in task history and the live task feed.

**Current behavior**

Each image uses a separate full-width card. Native image upload receipt
messages can also separate related screenshots.

**Proposed behavior**

Adjacent images from one run share a wrapping thumbnail grid. New image
results join the grid. Documents, video, and authored messages keep
their positions. The grid opens the existing gallery.

**Reason and benefit**

Users can see a batch of screenshots without scrolling past one large
card for each file.

**Breaking changes**

The feed layout changes. The stored comments, files, APIs, and
permissions do not change.

Related public work: Refs #17228. Refs #8785. Refs #7667. These changes
supplied the artifact cards and media gallery that this pull request
reuses.

## What Changed

- Add one image grouping function for settled history, turn history, and
live results. Group only images with the same known run. Keep the first
row key and each image key when results arrive.
- Add a token-based grid that reuses the media artifact cards and image
gallery.
- Add an optional typed attachment-preparation marker to file
registration and chat-file reuse. Preserve the marker through comment
normalization. Use it with matching image, author, and run links to hide
generated receipts. Keep the exact historical sentence as a fallback for
old receipts.
- Add nine production component stories with seven sample-account
screenshots. Cover mobile, Classic, mixed results, single images,
missing images, streaming, gallery navigation, and the complete feed
projection.
- Add grouping and production-feed regressions. Add 18 browser cases
across light and dark themes.
- Improve contrast for the shared fallback label and gallery counter
after the accessibility checks found low contrast.
- Match alternate original-image paths when opening the gallery. Keep a
separate Open original link beside Download in the gallery.
- Record the feed layout in DESIGN.md.

## Verification

- Final qualification at `09b12381ce85bee6593050bd8a2fa18cbe2c45a6`:
[required CI
passed](https://github.com/paperclipai/paperclip/actions/runs/42317080212/job/128237094513),
including typecheck, build, all test lanes, E2E, and verify. The
snapshot has 58 successful check runs, three conditional skips, one
neutral advisory job, and a successful legacy Snyk status. No pending or
failed checks remain. Greptile and Paperclip Review both score this
exact head 5/5; all review threads are resolved.

- Current-head local checks: 544 focused UI tests passed across 11
files, with one existing skip. UI/shared typechecks and token gates
pass. All 18 focused Storybook browser cases passed after the CSS merge,
with retries disabled.
- Two database integration cases verify file registration and chat-file
reuse receipt markers. All 52 issue-validator tests and six upstream
default-model tests passed.
- Regressions failed before the fixes for unknown-run grouping, receipt
wording, and authored progress text with an image. The repair uses a
typed receipt marker and requires matching author, attachment, image,
and run links before hiding a generated receipt. All five review
findings are resolved.
- Browser checks cover loaded images, wrapping columns, overflow,
missing-image fallback, streaming stability, keyboard gallery
navigation, original-file links, and downloads. Fixtures use production
renderers. These checks do not prove deployed persistence or provider
behavior and do not compare visual baselines.
- Local limits: the preflight helper could not finish because Cargo was
absent. The earlier low-memory server typecheck and dependency-free
selector did not replace final-head CI. The now-passing final CI
supplies broad typecheck, build, server, Runner, and E2E coverage.
- Prior independent CI failures remain recorded: one Slack timer case
passed a single diagnosed rerun; its exact timer cause was not proved. A
later chat shard lost its self-hosted runner without a test assertion
failure. The current revision passes that shard and all applicable
gates. Master conflict resolution retained both image-grid and patch CSS
rules.

## Risks

- Images without a run ID remain separate. Messages and other resource
types end each batch.
- Receipt suppression requires a matching preparation marker or the
exact legacy sentence, plus matching attachment, image work product,
run, and author. Tests preserve human messages and native progress text
with attachments. The optional marker uses existing JSON metadata and
needs no database migration.
- Shared gallery and fallback text now have stronger contrast.

## Model Used

OpenAI GPT-6, through Codex. The agent used reasoning, repository tools,
code execution, and browser tests. The runtime did not expose a more
specific model ID or context window size.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-06 18:42:22 -06:00

209 lines
7.5 KiB
TypeScript

import { useCallback, useEffect, useRef, useState, type RefObject } from "react";
import { Dialog as DialogPrimitive } from "radix-ui";
import { ChevronLeft, ChevronRight, Download, ExternalLink, X } from "lucide-react";
import { attachmentDownloadPath, attachmentFilename, attachmentOpenPath } from "@/lib/issue-attachments";
import { isVideoLikeOutput } from "@/lib/issue-output";
export interface GalleryMediaItem {
id: string;
contentPath: string;
openPath?: string;
downloadPath?: string;
contentType: string;
originalFilename: string | null;
}
interface ImageGalleryModalProps {
items: GalleryMediaItem[];
initialIndex: number;
open: boolean;
onOpenChange: (open: boolean) => void;
onIndexChange?: (index: number) => void;
returnFocusRef?: RefObject<HTMLElement | null>;
}
export function ImageGalleryModal({
items,
initialIndex,
open,
onOpenChange,
onIndexChange,
returnFocusRef,
}: ImageGalleryModalProps) {
const [currentIndex, setCurrentIndex] = useState(initialIndex);
const mediaRef = useRef<HTMLImageElement | HTMLVideoElement | null>(null);
const setMediaRef = useCallback((node: HTMLImageElement | HTMLVideoElement | null) => {
mediaRef.current = node;
}, []);
useEffect(() => {
if (open) setCurrentIndex(initialIndex);
}, [open, initialIndex]);
const goNext = useCallback(() => {
const next = (currentIndex + 1) % items.length;
setCurrentIndex(next);
onIndexChange?.(next);
}, [currentIndex, items.length, onIndexChange]);
const goPrev = useCallback(() => {
const next = (currentIndex - 1 + items.length) % items.length;
setCurrentIndex(next);
onIndexChange?.(next);
}, [currentIndex, items.length, onIndexChange]);
useEffect(() => {
if (currentIndex < items.length) return;
setCurrentIndex(0);
}, [currentIndex, items.length]);
useEffect(() => {
if (!open || items.length < 2) return;
const handler = (e: KeyboardEvent) => {
if (e.key !== "ArrowRight" && e.key !== "ArrowLeft") return;
e.preventDefault();
if (e.key === "ArrowRight") goNext();
else goPrev();
};
window.addEventListener("keydown", handler);
return () => window.removeEventListener("keydown", handler);
}, [open, goNext, goPrev, items.length]);
/** Close when clicking empty curtain space (not interactive elements or the image) */
const handleBackdropClick = useCallback(
(e: React.MouseEvent) => {
const target = e.target as HTMLElement;
if (
target.closest("button") ||
target.closest("a") ||
target === mediaRef.current
)
return;
onOpenChange(false);
},
[onOpenChange],
);
if (items.length === 0) return null;
const current = items[currentIndex];
if (!current) return null;
const filename = attachmentFilename(current);
const isVideo = isVideoLikeOutput(current.contentType, current.originalFilename);
return (
<DialogPrimitive.Root open={open} onOpenChange={onOpenChange}>
<DialogPrimitive.Portal>
{/* Full-screen curtain */}
<DialogPrimitive.Overlay className="fixed inset-0 z-50 bg-black/90 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 duration-200" />
<DialogPrimitive.Content
className="fixed inset-0 z-50 flex flex-col outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 duration-200"
onClick={handleBackdropClick}
aria-describedby={undefined}
onCloseAutoFocus={returnFocusRef ? (event) => {
event.preventDefault();
returnFocusRef.current?.focus({ preventScroll: true });
} : undefined}
>
<DialogPrimitive.Title className="sr-only">Image gallery</DialogPrimitive.Title>
{/* Top bar */}
<div className="flex items-center justify-between px-5 py-3 text-white/80 text-sm shrink-0">
<span className="truncate max-w-(--pct-50) font-medium" title={filename}>
{filename}
</span>
<div className="flex items-center gap-4">
<span className="tabular-nums text-xs">
{currentIndex + 1} / {items.length}
</span>
<a
href={attachmentOpenPath(current)}
target="_blank"
rel="noopener noreferrer"
className="text-white/50 hover:text-white transition-colors"
title="Open original"
aria-label={`Open original ${filename}`}
onClick={(e) => e.stopPropagation()}
>
<ExternalLink className="h-4.5 w-4.5" />
</a>
<a
href={attachmentDownloadPath(current)}
download={filename}
className="text-white/50 hover:text-white transition-colors"
title="Download"
aria-label={`Download ${filename}`}
onClick={(e) => e.stopPropagation()}
>
<Download className="h-4.5 w-4.5" />
</a>
<button
type="button"
onClick={() => onOpenChange(false)}
className="text-white/50 hover:text-white transition-colors"
title="Close"
>
<X className="h-5 w-5" />
</button>
</div>
</div>
{/* Main area: nav buttons outside image */}
<div className="flex-1 flex items-center min-h-0">
{/* Left nav zone */}
<div className="w-16 md:w-24 shrink-0 flex items-center justify-center h-full">
{items.length > 1 && (
<button
type="button"
onClick={goPrev}
className="rounded-full bg-white/10 p-3 text-white/60 hover:text-white hover:bg-white/20 transition-colors"
title="Previous"
>
<ChevronLeft className="h-7 w-7" />
</button>
)}
</div>
{/* Media */}
<div className="flex-1 flex items-center justify-center min-w-0 min-h-0 h-full px-2">
{isVideo ? (
<video
ref={setMediaRef}
src={current.contentPath}
className="max-w-full max-h-full rounded-lg"
controls
playsInline
/>
) : (
<img
ref={setMediaRef}
src={current.contentPath}
alt={filename}
className="max-w-full max-h-full object-contain select-none rounded-lg"
draggable={false}
/>
)}
</div>
{/* Right nav zone */}
<div className="w-16 md:w-24 shrink-0 flex items-center justify-center h-full">
{items.length > 1 && (
<button
type="button"
onClick={goNext}
className="rounded-full bg-white/10 p-3 text-white/60 hover:text-white hover:bg-white/20 transition-colors"
title="Next"
>
<ChevronRight className="h-7 w-7" />
</button>
)}
</div>
</div>
{/* Bottom padding for balance */}
<div className="h-6 shrink-0" />
</DialogPrimitive.Content>
</DialogPrimitive.Portal>
</DialogPrimitive.Root>
);
}