Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(artifacts): rebuild the library as a wall of full-bleed tiles (#538)
Ruben Lütkee4c00ad33c22
diff --git a/jarvis/ui/web/frontend/src/components/visualization/ArtifactCardMenu.tsx b/jarvis/ui/web/frontend/src/components/visualization/ArtifactCardMenu.tsxindex 4fa084367b..30f4edc6f5 100644--- a/jarvis/ui/web/frontend/src/components/visualization/ArtifactCardMenu.tsx+++ b/jarvis/ui/web/frontend/src/components/visualization/ArtifactCardMenu.tsx@@ -6,7 +6,7 @@ import {type ReactNode,} from "react";import { createPortal } from "react-dom";-import { Download, Eye, ExternalLink, FolderOpen, Trash2 } from "lucide-react";+import { Download, Eye, ExternalLink, FolderOpen, Star, StarOff, Trash2 } from "lucide-react";import { fill, useT } from "@/i18n";import { cn } from "@/lib/utils";@@ -19,9 +19,9 @@ import { rowTitle, type RailRow } from "@/components/visualization/galleryModel"* The desktop WebView has no native context menu, and the app-wide* Cut/Copy/Paste menu lives on `document`, so the card stops its own* right-click and opens this one instead. What it offers follows the card:- * an artifact can be opened, opened in the browser, saved and shown in its- * folder; a run without one can be opened and shown in its folder; anything- * finished can be deleted. A card whose run is still working cannot be+ * an artifact can be opened, starred, opened in the browser, saved and shown+ * in its folder; a run without one can be opened, starred and shown in its+ * folder; anything finished can be deleted. A card whose run is still working cannot be* deleted — its worker may be writing into that very folder — so the item is* there but disabled, with the reason on hover.*/@@ -46,8 +46,10 @@ export function ArtifactCardMenu({x,y,canReveal,+ favorite = false,onDismiss,onOpen,+ onToggleFavorite,onOpenExternal,onDownload,onReveal,@@ -58,8 +60,12 @@ export function ArtifactCardMenu({y: number;/** Desktop only — a headless host has no file manager to open. */canReveal: boolean;+ /** The card carries a star. */+ favorite?: boolean;onDismiss: () => void;onOpen: () => void;+ /** Star or unstar the card; the item is left out where stars are not offered. */+ onToggleFavorite?: () => void;onOpenExternal: () => void;onDownload: () => void;onReveal: () => void;@@ -132,6 +138,15 @@ export function ArtifactCardMenu({<MenuItem icon={<Eye />} testId="artifact-menu-open" onClick={onOpen}>{t("visualization.menu_open")}</MenuItem>+ {onToggleFavorite && row.kind !== "build" && (+ <MenuItem+ icon={favorite ? <StarOff /> : <Star />}+ testId="artifact-menu-favorite"+ onClick={onToggleFavorite}+ >+ {t(favorite ? "visualization.favorite_remove" : "visualization.favorite_add")}+ </MenuItem>+ )}{isVisual && (<MenuItem icon={<ExternalLink />} testId="artifact-menu-open-external" onClick={onOpenExternal}>{t("visualization.open_external")}diff --git a/jarvis/ui/web/frontend/src/components/visualization/ArtifactCovers.tsx b/jarvis/ui/web/frontend/src/components/visualization/ArtifactCovers.tsxnew file mode 100644index 0000000000..062e5a608e--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/visualization/ArtifactCovers.tsx@@ -0,0 +1,497 @@+import {+ useEffect,+ useLayoutEffect,+ useRef,+ useState,+ useSyncExternalStore,+ type RefObject,+} from "react";+import { Ban, CircleAlert, FileImage, FileText, Files, Globe, Loader2, PenTool, StickyNote } from "lucide-react";++import { useT, useUiLanguage } from "@/i18n";+import { useThemeValue } from "@/hooks/useTheme";+import { cn } from "@/lib/utils";+import type { OutputStatus } from "@/hooks/useOutputs";+import { artifactPageUrl, type VisualArtifact, type VisualKind } from "@/hooks/useVisualArtifacts";+import {+ relativeWhen,+ rowTitle,+ rowWhen,+ type RailRow,+} from "@/components/visualization/galleryModel";++/**+ * What a tile on the Artifacts wall shows — the artifact itself, edge to edge.+ *+ * A page is the live page: laid out narrow enough that its headline is still+ * readable at tile size, scripts running, network shut (the same sandbox as+ * the stage). Rest the pointer on it and it scrolls itself, so the reader sees+ * what is further down without opening it. A picture fills its tile, a vector+ * sits on a white mat, a PDF shows its first sheet, and a run that drew+ * nothing is a note: its title, a mark for how it ended, and when.+ *+ * Live covers mount only while their tile is near the viewport, so a library+ * of a hundred dashboards costs what a screenful costs — and a WebGL map+ * scrolled out of view gives its context back (AP-32).+ */++export const KIND_ICON: Record<VisualKind, typeof Globe> = {+ page: Globe,+ image: FileImage,+ vector: PenTool,+ document: FileText,+};++/** The share of a tile's width one CSS pixel of a framed page is drawn at. */+const PAGE_TARGET_SCALE = 0.36;+/** A page is never laid out narrower or wider than this, whatever the tile. */+const PAGE_MIN_WIDTH = 680;+const PAGE_MAX_WIDTH = 1200;+/** Layout widths move in steps, so dragging the window does not re-flow every page per pixel. */+const PAGE_WIDTH_STEP = 40;+const DOCUMENT_VIRTUAL_WIDTH = 820;+/** CSS px a framed page may spend on its own vertical scrollbar. */+const SCROLLBAR_ALLOWANCE = 24;+/** How far a resting pointer scrolls a page, in tile heights, and how fast (screen px/s). */+const PEEK_TRAVEL = 1.6;+const PEEK_SPEED = 64;+const PEEK_RETURN_MS = 520;++/** The width a page is laid out at for a tile this wide. */+export function pageVirtualWidth(tileWidth: number): number {+ const wanted = tileWidth / PAGE_TARGET_SCALE;+ const stepped = Math.round(wanted / PAGE_WIDTH_STEP) * PAGE_WIDTH_STEP;+ return Math.min(PAGE_MAX_WIDTH, Math.max(PAGE_MIN_WIDTH, stepped));+}++/* ------------------------------------------------------------------------- */++/**+ * True while the element is on, or about to scroll onto, the screen. Without+ * an IntersectionObserver (a test DOM) nothing is ever mounted — a cover then+ * stays its quiet placeholder, never a dozen live frames.+ */+export function useNearViewport(ref: RefObject<HTMLElement | null>): boolean {+ const [near, setNear] = useState(false);+ useEffect(() => {+ const node = ref.current;+ if (!node || typeof IntersectionObserver === "undefined") return;+ const observer = new IntersectionObserver(+ (entries) => setNear(entries.some((entry) => entry.isIntersecting)),+ { rootMargin: "400px 0px" },+ );+ observer.observe(node);+ return () => observer.disconnect();+ }, [ref]);+ return near;+}++/** The element's size, known before the first paint and kept current. */+export function useBoxSize(ref: RefObject<HTMLElement | null>): { width: number; height: number } {+ const [size, setSize] = useState({ width: 0, height: 0 });+ useLayoutEffect(() => {+ const node = ref.current;+ if (!node) return;+ const update = (width: number, height: number) =>+ setSize((prev) => (prev.width === width && prev.height === height ? prev : { width, height }));+ update(node.clientWidth, node.clientHeight);+ if (typeof ResizeObserver === "undefined") return;+ const observer = new ResizeObserver(([entry]) => {+ update(entry.contentRect.width, entry.contentRect.height);+ });+ observer.observe(node);+ return () => observer.disconnect();+ }, [ref]);+ return size;+}++function usePrefersReducedMotion(): boolean {+ const [reduced, setReduced] = useState(false);+ useEffect(() => {+ if (typeof window.matchMedia !== "function") return;+ const query = window.matchMedia("(prefers-reduced-motion: reduce)");+ const update = () => setReduced(query.matches);+ update();+ query.addEventListener("change", update);+ return () => query.removeEventListener("change", update);+ }, []);+ return reduced;+}++/* ------------------------------------------------------------------------- */++/*+ * The proportions of the pictures seen so far. A picture's tile takes its+ * shape from them, so the wall has to hear when one becomes known — and keeps+ * them for the session, so a second visit lays out right at once.+ */+const ratios = new Map<string, number>();+const ratioListeners = new Set<() => void>();+let ratioVersion = 0;++function reportRatio(key: string, ratio: number): void {+ if (!Number.isFinite(ratio) || ratio <= 0) return;+ const known = ratios.get(key);+ if (known !== undefined && Math.abs(known - ratio) < 0.01) return;+ ratios.set(key, ratio);+ ratioVersion += 1;+ for (const listener of ratioListeners) listener();+}++function subscribeRatios(listener: () => void): () => void {+ ratioListeners.add(listener);+ return () => ratioListeners.delete(listener);+}++/** Width / height of every picture measured so far, by card key. */+export function useImageRatios(): ReadonlyMap<string, number> {+ useSyncExternalStore(+ subscribeRatios,+ () => ratioVersion,+ () => 0,+ );+ return ratios;+}++/* ------------------------------------------------------------------------- */++/** What fills a tile: the artifact itself, or a composed note. */+export function TileCover({ row, peek }: { row: RailRow; peek: boolean }) {+ const theme = useThemeValue();+ if (row.kind === "build") return <BuildingCover title={rowTitle(row)} />;+ if (row.kind === "run") {+ return (+ <NoteCover+ title={rowTitle(row)}+ status={row.run.status ?? "unknown"}+ when={rowWhen(row)}+ files={row.run.artifact_count ?? 0}+ />+ );+ }+ const { visual } = row;+ if (visual.kind === "image" || visual.kind === "vector") {+ return <ImageCover visual={visual} cardKey={row.key} />;+ }+ if (visual.kind === "page") {+ return (+ <PageCover+ src={`${artifactPageUrl(visual.slug, visual.path)}?theme=${theme}`}+ title={visual.title}+ peek={peek}+ />+ );+ }+ return <DocumentCover src={`${visual.url}#toolbar=0&navpanes=0&scrollbar=0&view=FitH`} title={visual.title} />;+}++/**+ * The live page, scaled onto its tile. Inert: no pointer, no focus, hidden+ * from assistive tech (the tile's button carries the name).+ *+ * While `peek` holds, the frame grows downwards and glides up, so the page+ * scrolls past at reading-glance speed; it is only made taller for that+ * moment — a page that sizes its hero to the viewport keeps its real+ * proportions on the resting tile.+ */+function PageCover({ src, title, peek }: { src: string; title: string; peek: boolean }) {+ const box = useRef<HTMLDivElement>(null);+ const near = useNearViewport(box);+ const { width, height } = useBoxSize(box);+ const reduced = usePrefersReducedMotion();+ const [loaded, setLoaded] = useState(false);+ useEffect(() => setLoaded(false), [src]);++ const scrolling = peek && loaded && !reduced;+ // Taller while scrolling and until the page has glided back to its top.+ const [grown, setGrown] = useState(false);+ useEffect(() => {+ if (scrolling) {+ setGrown(true);+ return;+ }+ const timer = window.setTimeout(() => setGrown(false), PEEK_RETURN_MS + 80);+ return () => window.clearTimeout(timer);+ }, [scrolling]);++ const virtualWidth = pageVirtualWidth(width);+ const scale = width > 0 ? width / virtualWidth : 0;+ const visible = scale > 0 ? height / scale : 0;+ const travel = visible * PEEK_TRAVEL;++ return (+ <div ref={box} className="absolute inset-0 bg-background" aria-hidden>+ {!loaded && <div className="absolute inset-0 animate-pulse bg-foreground/5" />}+ {near && scale > 0 && (+ <iframe+ key={src}+ src={src}+ title={title}+ tabIndex={-1}+ // allow-scripts WITHOUT allow-same-origin, exactly as on the stage.+ sandbox="allow-scripts"+ loading="lazy"+ onLoad={() => setLoaded(true)}+ data-testid="artifact-card-frame"+ className={cn(+ "pointer-events-none absolute left-0 top-0 origin-top-left border-0 bg-background",+ loaded ? "opacity-100" : "opacity-0",+ )}+ style={{+ // A little wider than the box shows: the page's own scrollbar+ // falls outside the tile instead of striping its edge.+ width: virtualWidth + SCROLLBAR_ALLOWANCE,+ height: grown ? visible + travel : visible,+ transform: `scale(${scale}) translateY(${scrolling ? -travel : 0}px)`,+ transition: scrolling+ ? `transform ${Math.round(((travel * scale) / PEEK_SPEED) * 1000)}ms linear, opacity 300ms`+ : `transform ${PEEK_RETURN_MS}ms cubic-bezier(0.22, 1, 0.36, 1), opacity 300ms`,+ }}+ />+ )}+ </div>+ );+}++/**+ * A PDF's first sheet, drawn by the browser's own viewer on white. That+ * viewer is a plugin, and plugins never load inside a sandboxed frame, so+ * this one is not sandboxed — the bytes are same-origin and inert.+ */+function DocumentCover({ src, title }: { src: string; title: string }) {+ const box = useRef<HTMLDivElement>(null);+ const near = useNearViewport(box);+ const { width, height } = useBoxSize(box);+ const [loaded, setLoaded] = useState(false);+ useEffect(() => setLoaded(false), [src]);+ const scale = width > 0 ? width / DOCUMENT_VIRTUAL_WIDTH : 0;++ return (+ <div ref={box} className="absolute inset-0 bg-white" aria-hidden>+ {!loaded && <div className="absolute inset-0 animate-pulse bg-black/5" />}+ {near && scale > 0 && (+ <iframe+ key={src}+ src={src}+ title={title}+ tabIndex={-1}+ loading="lazy"+ onLoad={() => setLoaded(true)}+ data-testid="artifact-card-frame"+ className={cn(+ "pointer-events-none absolute left-0 top-0 origin-top-left border-0 bg-white transition-opacity duration-300",+ loaded ? "opacity-100" : "opacity-0",+ )}+ style={{+ // Both of the viewer's scrollbars fall outside the tile.+ width: DOCUMENT_VIRTUAL_WIDTH + SCROLLBAR_ALLOWANCE,+ height: height / scale + SCROLLBAR_ALLOWANCE,+ transform: `scale(${scale})`,+ }}+ />+ )}+ </div>+ );+}++/**+ * How a picture sits in its tile. A photograph fills it, cropped. A drawing+ * with a plain ground — a logo, a diagram, a banner — is shown whole, on a mat+ * of exactly that ground, so the tile reads as more of the same picture. One+ * with a transparent ground gets a white mat and some air: a drawing made+ * with dark strokes on nothing would vanish into a dark tile.+ */+interface PictureFit {+ whole: boolean;+ mat: string;+ air: boolean;+}++const FILLED: PictureFit = { whole: false, mat: "#ffffff", air: false };+const ON_WHITE: PictureFit = { whole: true, mat: "#ffffff", air: true };+/** The fits worked out so far, by card key — a second visit does not re-measure. */+const fits = new Map<string, PictureFit>();++const SAMPLE = 24;+/** How far an edge pixel may stray from the edge's average and still count as ground. */+const GROUND_TOLERANCE = 22;++/** Reads the picture's edge: a transparent ground, a plain one, or neither. */+export function measurePictureFit(image: HTMLImageElement): PictureFit | null {+ try {+ const canvas = document.createElement("canvas");+ canvas.width = SAMPLE;+ canvas.height = SAMPLE;+ const context = canvas.getContext("2d", { willReadFrequently: true });+ if (!context) return null;+ context.drawImage(image, 0, 0, SAMPLE, SAMPLE);+ const { data } = context.getImageData(0, 0, SAMPLE, SAMPLE);+ const edge: number[][] = [];+ for (let y = 0; y < SAMPLE; y += 1) {+ for (let x = 0; x < SAMPLE; x += 1) {+ if (x !== 0 && y !== 0 && x !== SAMPLE - 1 && y !== SAMPLE - 1) continue;+ const at = (y * SAMPLE + x) * 4;+ edge.push([data[at], data[at + 1], data[at + 2], data[at + 3]]);+ }+ }+ const mean = [0, 1, 2, 3].map(+ (channel) => edge.reduce((sum, pixel) => sum + pixel[channel], 0) / edge.length,+ );+ if (mean[3] < 24) return ON_WHITE;+ if (mean[3] < 250) return null;+ const ground = edge.filter((pixel) =>+ [0, 1, 2].every((channel) => Math.abs(pixel[channel] - mean[channel]) <= GROUND_TOLERANCE),+ );+ if (ground.length < edge.length * 0.9) return null;+ const [r, g, b] = mean.map(Math.round);+ return { whole: true, mat: `rgb(${r}, ${g}, ${b})`, air: false };+ } catch {+ // A canvas that cannot be read (a tainted source, no 2D context) just+ // leaves the picture as it was going to be shown anyway.+ return null;+ }+}++/**+ * A picture on its tile. The tile learns the picture's proportions here and+ * takes its shape from them; how the picture then sits in that shape is+ * `PictureFit`.+ */+function ImageCover({ visual, cardKey }: { visual: VisualArtifact; cardKey: string }) {+ const vector = visual.kind === "vector";+ const [failed, setFailed] = useState(false);+ const [fit, setFit] = useState<PictureFit>(() => fits.get(cardKey) ?? (vector ? ON_WHITE : FILLED));+ if (failed) {+ return (+ <div className="absolute inset-0 flex items-center justify-center text-foreground-faint">+ <FileImage className="h-8 w-8" aria-hidden />+ </div>+ );+ }+ return (+ <div className="absolute inset-0" style={{ backgroundColor: fit.mat }}>+ <img+ src={visual.url}+ alt=""+ loading="lazy"+ decoding="async"+ draggable={false}+ onLoad={(event) => {+ const image = event.currentTarget;+ if (image.naturalHeight > 0) reportRatio(cardKey, image.naturalWidth / image.naturalHeight);+ const measured = measurePictureFit(image) ?? (vector ? ON_WHITE : FILLED);+ fits.set(cardKey, measured);+ setFit(measured);+ }}+ onError={() => setFailed(true)}+ className={cn(+ "absolute inset-0 h-full w-full transition-transform duration-500 ease-out",+ "group-hover/tile:scale-[1.03] motion-reduce:transition-none motion-reduce:group-hover/tile:scale-100",+ fit.whole ? "object-contain" : "object-cover",+ fit.air && "p-[9%]",+ )}+ />+ </div>+ );+}++/** How a note marks the way its run ended. */+function NoteMark({ status }: { status: OutputStatus }) {+ if (status === "running") return <Loader2 className="h-7 w-7 animate-spin text-accent" aria-hidden />;+ if (status === "error") return <CircleAlert className="h-7 w-7 text-destructive" aria-hidden />;+ if (status === "cancelled") return <Ban className="h-7 w-7 text-warning" aria-hidden />;+ return <StickyNote className="h-7 w-7 text-accent" aria-hidden />;+}++/** A run that drew nothing: a note with its title, its mark, and when. */+function NoteCover({+ title,+ status,+ when,+ files,+}: {+ title: string;+ status: OutputStatus;+ when: number;+ files: number;+}) {+ const t = useT();+ const language = useUiLanguage();+ const date = relativeWhen(when, Date.now(), language);+ return (+ <div className="absolute inset-0 flex flex-col p-5">+ <p className="line-clamp-3 shrink-0 text-lg font-semibold leading-snug text-foreground-strong [overflow-wrap:anywhere]">+ {title}+ </p>+ <div className="flex min-h-0 flex-1 items-center justify-center">+ <NoteMark status={status} />+ </div>+ <p className="flex shrink-0 items-center gap-3 truncate text-sm text-muted-foreground">+ {date && <span className="truncate">{date}</span>}+ {files > 0 && (+ <span className="inline-flex shrink-0 items-center gap-1.5 text-foreground-faint">+ <Files className="h-3.5 w-3.5" aria-hidden />+ {files === 1+ ? t("visualization.file_one")+ : t("visualization.files_count").replace("{0}", String(files))}+ </span>+ )}+ </p>+ </div>+ );+}++/** A page being written: its name on a sheet that is still filling in. */+function BuildingCover({ title }: { title: string }) {+ const t = useT();+ return (+ <div className="absolute inset-0 flex flex-col p-5">+ <p className="line-clamp-3 shrink-0 text-lg font-semibold leading-snug text-foreground-strong [overflow-wrap:anywhere]">+ {title}+ </p>+ <div className="flex min-h-0 flex-1 flex-col justify-center gap-2.5 py-3">+ <div className="h-2.5 w-4/5 animate-pulse rounded-full bg-foreground/10" />+ <div className="h-2.5 w-3/5 animate-pulse rounded-full bg-foreground/10 [animation-delay:150ms]" />+ <div className="h-2.5 w-2/3 animate-pulse rounded-full bg-foreground/10 [animation-delay:300ms]" />+ </div>+ <p className="inline-flex shrink-0 items-center gap-2 text-sm text-muted-foreground">+ <Loader2 className="h-3.5 w-3.5 animate-spin text-accent" aria-hidden />+ {t("visualization.building")}+ </p>+ </div>+ );+}++/* ------------------------------------------------------------------------- */++/** The small square a list row leads with — the picture, or the kind's mark. */+export function RowThumb({ row }: { row: RailRow }) {+ const [failed, setFailed] = useState(false);+ const picture =+ row.kind === "visual" && (row.visual.kind === "image" || row.visual.kind === "vector") && !failed;+ if (picture && row.kind === "visual") {+ return (+ <span className="relative h-11 w-11 shrink-0 overflow-hidden rounded-lg border border-border bg-white">+ <img+ src={row.visual.url}+ alt=""+ loading="lazy"+ decoding="async"+ draggable={false}+ onError={() => setFailed(true)}+ className={cn(+ "absolute inset-0 h-full w-full",+ row.visual.kind === "vector" ? "object-contain p-1.5" : "object-cover",+ )}+ />+ </span>+ );+ }+ const Icon =+ row.kind === "visual" ? KIND_ICON[row.visual.kind] : row.kind === "build" ? Loader2 : StickyNote;+ return (+ <span className="flex h-11 w-11 shrink-0 items-center justify-center rounded-lg bg-secondary text-muted-foreground">+ <Icon className={cn("h-5 w-5", row.kind === "build" && "animate-spin")} aria-hidden />+ </span>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/visualization/ArtifactGallery.tsx b/jarvis/ui/web/frontend/src/components/visualization/ArtifactGallery.tsxindex 31aa42e096..7efd1efb98 100644--- a/jarvis/ui/web/frontend/src/components/visualization/ArtifactGallery.tsx+++ b/jarvis/ui/web/frontend/src/components/visualization/ArtifactGallery.tsx@@ -1,30 +1,30 @@import {useCallback,useEffect,+ useMemo,useRef,useState,type DragEvent,+ type KeyboardEvent as ReactKeyboardEvent,type MouseEvent as ReactMouseEvent,type ReactNode,- type RefObject,} from "react";import { useQueryClient } from "@tanstack/react-query";import {- FileImage,- FileText,- Files,- Globe,+ ArrowDownUp,+ Check,+ Ellipsis,LayoutGrid,+ List,Loader2,- PenTool,+ RefreshCw,Search,- Workflow,+ SlidersHorizontal,+ Star,} from "lucide-react";import { EmptyState } from "@/components/ui/empty-state";-import { Input } from "@/components/ui/input";import { ScrollArea } from "@/components/ui/scroll-area";-import { BrandedSelect } from "@/components/ui/select";import { useT, useUiLanguage } from "@/i18n";import { useThemeValue } from "@/hooks/useTheme";import { cn } from "@/lib/utils";@@ -40,17 +40,22 @@ import {useOutputsCapabilities,type OutputStatus,} from "@/hooks/useOutputs";-import { artifactPageUrl, type VisualArtifact, type VisualKind } from "@/hooks/useVisualArtifacts";+import { artifactPageUrl } from "@/hooks/useVisualArtifacts";import {RAIL_FILTERS,+ featureIndex,+ layoutWall,relativeWhen,rowRequest,rowTitle,rowWhen,+ tileShape,+ wallColumns,type GalleryGroup,type GallerySort,type RailFilter,type RailRow,+ type TileShape,} from "@/components/visualization/galleryModel";import {ArtifactCardMenu,@@ -58,21 +63,46 @@ import {rowIsWorking,type ArtifactMenuState,} from "@/components/visualization/ArtifactCardMenu";+import {+ RowThumb,+ TileCover,+ useBoxSize,+ useImageRatios,+} from "@/components/visualization/ArtifactCovers";/**- * The Artifacts library — every artifact as a card with the artifact itself- * drawn on it, the way a gallery of finished work should look.+ * The Artifacts library: a title, a row of tabs, and a wall.+ *+ * The wall is the point. Every artifact is a tile with the artifact itself+ * drawn on it, edge to edge, and nothing underneath — no caption strip, no+ * icon chip, no date heading. A tile's name, kind and age rise over its lower+ * edge when the pointer or the keyboard reaches it (or always, when the reader+ * asks for that), next to a star and a menu. Tiles come in three shapes on one+ * half-tile lattice, so pictures keep their proportions and the wall still+ * reads as one surface; they are placed by hand (`layoutWall`) rather than by+ * CSS columns, which keeps the DOM in reading order and lets a tile glide to+ * its new place when a tab or a search narrows the wall.*- * A page's card frames the live page (scaled down, scripts running, network- * shut — the same sandbox as the stage), a picture shows the picture, a PDF- * its first page, and a run that drew nothing gets a composed text cover- * from its own answer. Previews mount only while their card is near the- * viewport, so a library of a hundred dashboards costs what a screenful- * costs — and a WebGL map scrolled out of view gives its context back- * (AP-32).+ * The same cards as a list are one toggle away, for when the reader is+ * looking for a name rather than a picture.*/-/** What a card's status dot means — the run vocabulary, one language. */+/** How the library is drawn, how big its tiles are, and when they are named. */+export type GalleryView = "wall" | "list";+export type TileSize = "s" | "m" | "l";+export type TileLabels = "hover" | "always";++export const GALLERY_VIEWS: readonly GalleryView[] = ["wall", "list"];+export const TILE_SIZES: readonly TileSize[] = ["s", "m", "l"];+export const TILE_LABELS: readonly TileLabels[] = ["hover", "always"];++/** The narrowest a tile of each size may get before the wall drops a column. */+const TILE_MINIMUM: Record<TileSize, number> = { s: 168, m: 228, l: 320 };+const WALL_GAP = 16;+/** How long the pointer rests on a tile before its page starts to scroll. */+const PEEK_DELAY_MS = 420;++/** What a status chip's dot means — the run vocabulary, one language. */const STATUS_DOT: Record<OutputStatus, string> = {success: "bg-success",error: "bg-destructive",@@ -81,31 +111,342 @@ const STATUS_DOT: Record<OutputStatus, string> = {unknown: "bg-muted-foreground",};-const KIND_ICON: Record<VisualKind, typeof Globe> = {- page: Globe,- image: FileImage,- vector: PenTool,- document: FileText,+const ROW_TESTID: Record<RailRow["kind"], string> = {+ build: "visualization-building-row",+ visual: "visualization-artifact-row",+ run: "visualization-run-row",};-const FILTER_ICON: Record<RailFilter, typeof Globe> = {- all: LayoutGrid,- pages: Globe,- images: FileImage,- documents: FileText,- outputs: Workflow,-};+function rowStatus(row: RailRow): OutputStatus {+ return row.kind === "visual" ? (row.visual.status ?? "unknown") : (row.run.status ?? "unknown");+}++/** The kind word in a tile's caption and a list row's column. */+function kindLabel(row: RailRow, t: (key: string) => string): string {+ if (row.kind === "build") return t("visualization.building");+ if (row.kind === "run") return t("visualization.output_kind");+ return t(`visualization.kind_${row.visual.kind}`);+}-/** The width a page is laid out at before it is scaled onto its card. */-const PAGE_VIRTUAL_WIDTH = 1280;-const DOCUMENT_VIRTUAL_WIDTH = 900;-/** CSS px a framed page may spend on its own vertical scrollbar. */-const SCROLLBAR_ALLOWANCE = 24;+function formatSize(bytes: number): string {+ if (bytes < 1024) return `${bytes} B`;+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`;+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;+}/* ------------------------------------------------------------------------- */-/** The library's left rail: the categories, each with its count. */-export function GalleryCategoryRail({+const ICON_BUTTON =+ "inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors " ++ "hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring " ++ "disabled:pointer-events-none disabled:opacity-50 [&_svg]:h-[18px] [&_svg]:w-[18px]";++/**+ * A button that opens a small panel under itself. Closes on a click outside,+ * on Escape, and when focus leaves it.+ */+function HeaderPopover({+ label,+ icon,+ testId,+ children,+}: {+ label: string;+ icon: ReactNode;+ testId: string;+ children: (close: () => void) => ReactNode;+}) {+ const [open, setOpen] = useState(false);+ const root = useRef<HTMLDivElement>(null);+ const close = useCallback(() => setOpen(false), []);++ useEffect(() => {+ if (!open) return;+ const onPointerDown = (event: PointerEvent) => {+ if (!root.current?.contains(event.target as Node)) setOpen(false);+ };+ const onKeyDown = (event: KeyboardEvent) => {+ if (event.key !== "Escape") return;+ event.stopPropagation();+ setOpen(false);+ root.current?.querySelector<HTMLButtonElement>("button")?.focus();+ };+ window.addEventListener("pointerdown", onPointerDown, true);+ window.addEventListener("keydown", onKeyDown, true);+ return () => {+ window.removeEventListener("pointerdown", onPointerDown, true);+ window.removeEventListener("keydown", onKeyDown, true);+ };+ }, [open]);++ return (+ <div ref={root} className="relative">+ <button+ type="button"+ aria-haspopup="true"+ aria-expanded={open}+ aria-label={label}+ title={label}+ onClick={() => setOpen((value) => !value)}+ data-testid={testId}+ className={cn(ICON_BUTTON, open && "bg-secondary text-foreground")}+ >+ {icon}+ </button>+ {open && (+ <div+ className={cn(+ "absolute right-0 top-full z-50 mt-2 min-w-56 rounded-xl border border-border bg-popover p-1.5 shadow-float",+ "animate-in fade-in-0 zoom-in-95 duration-150",+ )}+ >+ {children(close)}+ </div>+ )}+ </div>+ );+}++/** One choice in a header panel; the chosen one carries a check. */+function PanelChoice({+ chosen,+ onChoose,+ testId,+ children,+}: {+ chosen: boolean;+ onChoose: () => void;+ testId?: string;+ children: ReactNode;+}) {+ return (+ <button+ type="button"+ role="menuitemradio"+ aria-checked={chosen}+ onClick={onChoose}+ data-testid={testId}+ className={cn(+ "flex h-9 w-full items-center gap-2.5 rounded-lg px-2.5 text-left text-base transition-colors",+ "hover:bg-secondary focus-visible:bg-secondary focus-visible:outline-none",+ chosen ? "font-medium text-foreground-strong" : "text-foreground",+ )}+ >+ <span className="min-w-0 flex-1 truncate">{children}</span>+ {chosen && <Check className="h-4 w-4 shrink-0 text-accent" aria-hidden />}+ </button>+ );+}++function PanelHeading({ children }: { children: ReactNode }) {+ return <p className="px-2.5 pb-1 pt-2 text-sm font-medium text-foreground-faint">{children}</p>;+}++/** A row of mutually exclusive words — the tile sizes. */+function Segmented<T extends string>({+ value,+ options,+ onChange,+ label,+ testId,+}: {+ value: T;+ options: ReadonlyArray<{ id: T; label: string }>;+ onChange: (next: T) => void;+ label: string;+ testId: string;+}) {+ return (+ <div role="radiogroup" aria-label={label} className="mx-1 flex rounded-full bg-secondary p-1">+ {options.map((option) => (+ <button+ key={option.id}+ type="button"+ role="radio"+ aria-checked={value === option.id}+ onClick={() => onChange(option.id)}+ data-testid={`${testId}-${option.id}`}+ className={cn(+ "h-7 flex-1 whitespace-nowrap rounded-full px-3 text-sm font-medium transition-colors",+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ value === option.id+ ? "bg-background text-foreground-strong shadow-sm"+ : "text-muted-foreground hover:text-foreground",+ )}+ >+ {option.label}+ </button>+ ))}+ </div>+ );+}++/**+ * The library's head: its name on the left; order, wall-or-list, search,+ * display options and refresh on the right. With `bare` (nothing in the+ * library at all) only the name and refresh remain.+ */+export function LibraryHeader({+ query,+ onQuery,+ sort,+ onSort,+ view,+ onView,+ size,+ onSize,+ labels,+ onLabels,+ loading,+ onRefresh,+ bare,+}: {+ query: string;+ onQuery: (next: string) => void;+ sort: GallerySort;+ onSort: (next: GallerySort) => void;+ view: GalleryView;+ onView: (next: GalleryView) => void;+ size: TileSize;+ onSize: (next: TileSize) => void;+ labels: TileLabels;+ onLabels: (next: TileLabels) => void;+ loading: boolean;+ onRefresh: () => void;+ bare: boolean;+}) {+ const t = useT();+ const sorts: GallerySort[] = ["newest", "oldest", "name"];+ return (+ <header className="relative z-20 flex shrink-0 flex-wrap items-center gap-x-2 gap-y-3 px-8 pt-8">+ <h1 className="mr-auto pr-4 text-3xl font-semibold tracking-tight text-foreground-strong">+ {t("visualization.title")}+ </h1>+ {!bare && (+ <>+ <HeaderPopover+ label={t("visualization.sort_label")}+ icon={<ArrowDownUp aria-hidden />}+ testId="visualization-sort"+ >+ {(close) => (+ <div role="menu" aria-label={t("visualization.sort_label")}>+ {sorts.map((id) => (+ <PanelChoice+ key={id}+ chosen={sort === id}+ testId={`visualization-sort-${id}`}+ onChoose={() => {+ onSort(id);+ close();+ }}+ >+ {t(`visualization.sort_${id}`)}+ </PanelChoice>+ ))}+ </div>+ )}+ </HeaderPopover>++ <div+ role="group"+ aria-label={t("visualization.view_label")}+ className="flex items-center rounded-full"+ >+ {(+ [+ { id: "wall", Icon: LayoutGrid },+ { id: "list", Icon: List },+ ] as const+ ).map(({ id, Icon }) => (+ <button+ key={id}+ type="button"+ aria-pressed={view === id}+ aria-label={t(`visualization.view_${id}`)}+ title={t(`visualization.view_${id}`)}+ onClick={() => onView(id)}+ data-testid={`visualization-view-${id}`}+ className={cn(ICON_BUTTON, view === id && "bg-secondary text-foreground-strong")}+ >+ <Icon aria-hidden />+ </button>+ ))}+ </div>++ <div className="relative mx-1 w-72 max-w-full">+ <Search+ className="pointer-events-none absolute left-3.5 top-1/2 h-4 w-4 -translate-y-1/2 text-foreground-faint"+ aria-hidden+ />+ <input+ type="search"+ value={query}+ onChange={(event) => onQuery(event.target.value)}+ placeholder={t("visualization.search_placeholder")}+ aria-label={t("visualization.search_placeholder")}+ data-testid="visualization-search"+ className={cn(+ "h-9 w-full rounded-full border border-border bg-secondary/60 pl-10 pr-4 text-base text-foreground",+ "placeholder:text-foreground-faint transition-colors",+ "hover:border-border-strong focus-visible:border-accent focus-visible:bg-background focus-visible:outline-none",+ "focus-visible:ring-2 focus-visible:ring-ring",+ )}+ />+ </div>++ <HeaderPopover+ label={t("visualization.display_options")}+ icon={<SlidersHorizontal aria-hidden />}+ testId="visualization-display"+ >+ {() => (+ <div className="w-72 pb-1">+ <PanelHeading>{t("visualization.tile_size")}</PanelHeading>+ <Segmented+ value={size}+ onChange={onSize}+ label={t("visualization.tile_size")}+ testId="visualization-size"+ options={[+ { id: "s", label: t("visualization.size_s") },+ { id: "m", label: t("visualization.size_m") },+ { id: "l", label: t("visualization.size_l") },+ ]}+ />+ <PanelHeading>{t("visualization.labels_title")}</PanelHeading>+ <Segmented+ value={labels}+ onChange={onLabels}+ label={t("visualization.labels_title")}+ testId="visualization-labels"+ options={[+ { id: "hover", label: t("visualization.labels_hover") },+ { id: "always", label: t("visualization.labels_always") },+ ]}+ />+ </div>+ )}+ </HeaderPopover>+ </>+ )}+ <button+ type="button"+ onClick={onRefresh}+ disabled={loading}+ title={t("visualization.refresh")}+ aria-label={t("visualization.refresh")}+ data-testid="visualization-refresh"+ className={ICON_BUTTON}+ >+ {loading ? <Loader2 className="animate-spin" aria-hidden /> : <RefreshCw aria-hidden />}+ </button>+ </header>+ );+}++/** The library's tabs: two picks, four kinds, and everything. */+export function LibraryTabs({filter,counts,loading,@@ -121,14 +462,10 @@ export function GalleryCategoryRail({return (<navaria-label={t("visualization.rail_filter")}- className="flex w-56 shrink-0 flex-col gap-0.5 border-r border-border bg-sidebar p-3"+ className="flex shrink-0 flex-wrap items-center gap-1 px-8 pb-2 pt-5"data-testid="visualization-filter">- <p className="px-2 pb-2 pt-1 text-sm font-medium text-foreground-faint">- {t("visualization.nav_library")}- </p>{RAIL_FILTERS.map((id) => {- const Icon = FILTER_ICON[id];const active = filter === id;return (<button@@ -138,17 +475,23 @@ export function GalleryCategoryRail({onClick={() => onChange(id)}data-testid={`visualization-filter-${id}`}className={cn(- "flex h-9 items-center gap-2.5 rounded-md px-2 text-left text-base transition-colors",+ "inline-flex h-9 items-center gap-2 rounded-full px-4 text-base font-medium transition-colors","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",active- ? "jarvis-nav-active bg-secondary font-medium text-foreground-strong"- : "text-muted-foreground hover:bg-secondary hover:text-foreground",+ ? "bg-secondary text-foreground-strong"+ : "text-muted-foreground hover:bg-secondary/60 hover:text-foreground",)}>- <Icon className="h-4 w-4 shrink-0" aria-hidden />- <span className="min-w-0 flex-1 truncate">{t(`visualization.filter_${id}`)}</span>+ {t(`visualization.filter_${id}`)}{!loading && (- <span className="text-sm tabular-nums text-foreground-faint">{counts[id]}</span>+ <span+ className={cn(+ "text-sm tabular-nums",+ active ? "text-muted-foreground" : "text-foreground-faint",+ )}+ >+ {counts[id]}+ </span>)}</button>);@@ -157,111 +500,81 @@ export function GalleryCategoryRail({);}-/** Search box and sort order — the library's own toolbar. */-export function GalleryControls({- query,- onQuery,- sort,- onSort,-}: {- query: string;- onQuery: (next: string) => void;- sort: GallerySort;- onSort: (next: GallerySort) => void;-}) {- const t = useT();- return (- <div className="flex items-center gap-2">- <div className="relative w-64">- <Search- className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-foreground-faint"- aria-hidden- />- <Input- type="search"- value={query}- onChange={(event) => onQuery(event.target.value)}- placeholder={t("visualization.search_placeholder")}- aria-label={t("visualization.search_placeholder")}- data-testid="visualization-search"- className="pl-9"- />- </div>- <BrandedSelect- value={sort}- onValueChange={(value) => onSort(value as GallerySort)}- ariaLabel={t("visualization.sort_label")}- testId="visualization-sort"- className="w-44"- options={[- { value: "newest", label: t("visualization.sort_newest") },- { value: "oldest", label: t("visualization.sort_oldest") },- { value: "name", label: t("visualization.sort_name") },- ]}- />- </div>- );-}-/* ------------------------------------------------------------------------- */-/** The grid of cards, under its date headings. */+interface CardHandlers {+ onOpen: (row: RailRow) => void;+ onMenu: (row: RailRow, x: number, y: number) => void;+ onDeleteKey: (row: RailRow) => void;+ onToggleFavorite: (key: string) => void;+}++/** The library itself — the wall, or the same cards as a list. */export function ArtifactGallery({+ rows,groups,+ view,+ size,+ labels,+ feature,+ favorites,+ onToggleFavorite,loading,- searching,+ empty: emptyReason,footer,onOpen,}: {+ /** Every card, in the order it appears on screen. */+ rows: RailRow[];+ /** The same cards under their date headings — what the list is cut by. */groups: GalleryGroup[];+ view: GalleryView;+ size: TileSize;+ labels: TileLabels;+ /** Give the wall's first artifact a tile of four. */+ feature: boolean;+ favorites: ReadonlySet<string>;+ onToggleFavorite: (key: string) => void;loading: boolean;- /** A search is narrowing the library — an empty result is "no match", not "nothing". */- searching: boolean;+ /** Why the wall would be empty: a search, the favourites tab, or a kind. */+ empty: "search" | "favorites" | "category";footer?: ReactNode;onOpen: (row: RailRow) => void;}) {const t = useT();- const empty = groups.every((group) => group.rows.length === 0);const actions = useCardActions();+ const nothing = rows.length === 0;+ const handlers: CardHandlers = {+ onOpen,+ onMenu: actions.openMenu,+ onDeleteKey: actions.askDelete,+ onToggleFavorite,+ };return (<ScrollArea className="min-h-0 flex-1">- <div className="w-full px-8 pb-10 pt-2" data-testid="visualization-artifacts">- {loading && empty ? (- <CardGrid>- {Array.from({ length: 6 }, (_, index) => (- <SkeletonCard key={index} />- ))}- </CardGrid>- ) : empty ? (+ <div className="w-full px-8 pb-12 pt-3" data-testid="visualization-artifacts">+ {loading && nothing ? (+ <SkeletonWall />+ ) : nothing ? (<div className="flex min-h-80 items-center justify-center" data-testid="visualization-no-matches"><EmptyState- icon={<Search aria-hidden />}- title={t(searching ? "visualization.no_matches_title" : "visualization.category_empty_title")}- description={t(- searching ? "visualization.no_matches_body" : "visualization.category_empty_body",- )}+ icon={emptyReason === "favorites" ? <Star aria-hidden /> : <Search aria-hidden />}+ title={t(`visualization.${EMPTY_KEYS[emptyReason]}_title`)}+ description={t(`visualization.${EMPTY_KEYS[emptyReason]}_body`)}/></div>+ ) : view === "list" ? (+ <ArtifactList groups={groups} favorites={favorites} handlers={handlers} />) : (- groups.map((group) => (- <section key={group.id} className="pt-6" aria-label={t(`visualization.group_${group.id}`)}>- <h2 className="pb-3 text-lg font-semibold text-foreground-strong">- {t(`visualization.group_${group.id}`)}- </h2>- <CardGrid>- {group.rows.map((row) => (- <ArtifactCard- key={row.key}- row={row}- onOpen={onOpen}- onMenu={actions.openMenu}- onDeleteKey={actions.askDelete}- />- ))}- </CardGrid>- </section>- ))+ <ArtifactWall+ rows={rows}+ size={size}+ labels={labels}+ feature={feature}+ favorites={favorites}+ handlers={handlers}+ />)}{footer}</div>@@ -271,8 +584,10 @@ export function ArtifactGallery({x={actions.menu.x}y={actions.menu.y}canReveal={actions.canReveal}+ favorite={favorites.has(actions.menu.row.key)}onDismiss={actions.closeMenu}onOpen={() => actions.run(onOpen)}+ onToggleFavorite={() => actions.run((row) => onToggleFavorite(row.key))}onOpenExternal={() => actions.run(actions.openExternal)}onDownload={() => actions.run(actions.download)}onReveal={() => actions.run(actions.reveal)}@@ -291,9 +606,15 @@ export function ArtifactGallery({);}+const EMPTY_KEYS = {+ search: "no_matches",+ favorites: "favorites_empty",+ category: "category_empty",+} as const;+/**- * What a card's right-click menu does. One menu and one pending delete for- * the whole gallery — the card only reports where it was clicked.+ * What a card's menu does. One menu and one pending delete for the whole+ * library — the card only reports where it was clicked.*/function useCardActions() {const t = useT();@@ -393,73 +714,20 @@ function useCardActions() {};}-function CardGrid({ children }: { children: ReactNode }) {- return (- <div className="grid grid-cols-[repeat(auto-fill,minmax(20rem,1fr))] gap-5">{children}</div>- );-}--function SkeletonCard() {- return (- <div className="overflow-hidden rounded-xl border border-border bg-card" aria-hidden>- <div className="aspect-[16/10] animate-pulse bg-foreground/10" />- <div className="flex items-center gap-3 p-3">- <div className="h-9 w-9 shrink-0 animate-pulse rounded-lg bg-foreground/10" />- <div className="flex-1 space-y-2">- <div className="h-3.5 w-2/3 animate-pulse rounded bg-foreground/15" />- <div className="h-3 w-1/3 animate-pulse rounded bg-foreground/10" />- </div>- </div>- </div>- );-}--/* ------------------------------------------------------------------------- */--/** The kind word under a card's title. */-function kindLabel(row: RailRow, t: (key: string) => string): string {- if (row.kind === "build") return t("visualization.building");- if (row.kind === "run") return t("visualization.output_kind");- return t(`visualization.kind_${row.visual.kind}`);-}--const ROW_TESTID: Record<RailRow["kind"], string> = {- build: "visualization-building-row",- visual: "visualization-artifact-row",- run: "visualization-run-row",-};--function ArtifactCard({- row,- onOpen,- onMenu,- onDeleteKey,-}: {- row: RailRow;- onOpen: (row: RailRow) => void;- onMenu: (row: RailRow, x: number, y: number) => void;- onDeleteKey: (row: RailRow) => void;-}) {- const t = useT();- const language = useUiLanguage();- const title = rowTitle(row);- const request = rowRequest(row);- const status: OutputStatus =- row.kind === "visual" ? (row.visual.status ?? "unknown") : (row.run.status ?? "unknown");- const KindIcon =- row.kind === "visual" ? KIND_ICON[row.visual.kind] : row.kind === "build" ? Loader2 : Workflow;+/** What a card shares between the wall and the list: its keys and its drag. */+function useCardInteractions(row: RailRow, handlers: CardHandlers) {// Every card can be dragged onto the Jarvis dock — the run is what the dock// takes, whichever of its artifacts the card happens to show.const dragRun = row.run;const dragProps = dragRun? {draggable: true,- onDragStart: (e: DragEvent) => startMissionDrag(e, dragRun),+ onDragStart: (event: DragEvent) => startMissionDrag(event, dragRun),onDragEnd: endMissionDrag,}: {};- const onContextMenu = (event: ReactMouseEvent<HTMLButtonElement>) => {+ const onContextMenu = (event: ReactMouseEvent<HTMLElement>) => {// The app-wide Cut/Copy/Paste menu lives on document; a card offers its// own actions instead. The menu key reports no pointer, so the menu then// opens at the card's corner.@@ -467,255 +735,379 @@ function ArtifactCard({event.stopPropagation();if (event.clientX === 0 && event.clientY === 0) {const box = event.currentTarget.getBoundingClientRect();- onMenu(row, box.left + 16, box.top + 16);+ handlers.onMenu(row, box.left + 16, box.top + 16);} else {- onMenu(row, event.clientX, event.clientY);+ handlers.onMenu(row, event.clientX, event.clientY);}};- return (- <button- type="button"- onClick={() => onOpen(row)}- onContextMenu={onContextMenu}- onKeyDown={(event) => {- if (event.key === "Delete" && !event.altKey && !event.ctrlKey && !event.metaKey) {- event.preventDefault();- onDeleteKey(row);- }- }}- data-testid={ROW_TESTID[row.kind]}- data-kind={row.kind === "visual" ? row.visual.kind : undefined}- data-status={row.kind === "run" ? status : undefined}- className={cn(- "group flex min-w-0 flex-col overflow-hidden rounded-xl border border-border bg-card text-left",- "transition-[border-color,box-shadow] duration-150 hover:border-border-strong hover:shadow-lg",- "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",- )}- {...dragProps}- >- <div className="relative aspect-[16/10] w-full overflow-hidden border-b border-border bg-background">- <CardCover row={row} />- {status !== "success" && status !== "unknown" && row.kind !== "build" && (- <span className="absolute bottom-2 right-2 inline-flex items-center gap-1.5 rounded-md border border-border bg-popover/90 px-2 py-0.5 text-sm text-foreground backdrop-blur">- <span className={cn("h-1.5 w-1.5 rounded-full", STATUS_DOT[status])} aria-hidden />- {t(`visualization.status_word_${status}`)}- </span>- )}- </div>- <div className="flex min-w-0 items-center gap-3 p-3">- <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-secondary text-muted-foreground">- <KindIcon className={cn("h-4 w-4", row.kind === "build" && "animate-spin")} aria-hidden />- </span>- <span className="min-w-0 flex-1">- <span className="block truncate text-base font-semibold text-foreground-strong">{title}</span>- <span className="block truncate text-sm text-muted-foreground">- {[kindLabel(row, t), relativeWhen(rowWhen(row), Date.now(), language)]- .filter(Boolean)- .join(" · ")}- </span>- {row.kind !== "run" && request && request !== title && (- <span className="mt-0.5 block truncate text-sm text-foreground-faint">{request}</span>- )}- </span>- </div>- </button>- );-}--/* ------------------------------------------------------------------------- */+ const onKeyDown = (event: ReactKeyboardEvent<HTMLElement>) => {+ if (event.altKey || event.ctrlKey || event.metaKey) return;+ if (event.key === "Delete") {+ event.preventDefault();+ handlers.onDeleteKey(row);+ } else if (event.key === "f" || event.key === "F") {+ event.preventDefault();+ handlers.onToggleFavorite(row.key);+ }+ };-/** What fills the top of a card: the artifact itself, or a composed cover. */-function CardCover({ row }: { row: RailRow }) {- const theme = useThemeValue();- if (row.kind === "build") return <BuildingCover />;- if (row.kind === "run") {- return (- <TextCover- title={rowTitle(row)}- body={row.run.summary?.trim() || row.run.terminal_reason || row.run.error || ""}- files={row.run.artifact_count ?? 0}- />- );- }- const { visual } = row;- if (visual.kind === "image" || visual.kind === "vector") return <ImageCover visual={visual} />;- if (visual.kind === "page") {- return (- <ScaledFrame- src={`${artifactPageUrl(visual.slug, visual.path)}?theme=${theme}`}- title={visual.title}- virtualWidth={PAGE_VIRTUAL_WIDTH}- // allow-scripts WITHOUT allow-same-origin, exactly as on the stage.- sandbox="allow-scripts"- />- );- }- return (- <ScaledFrame- src={`${visual.url}#toolbar=0&navpanes=0&scrollbar=0&view=FitH`}- title={visual.title}- virtualWidth={DOCUMENT_VIRTUAL_WIDTH}- // Empty sandbox: the browser's own PDF viewer still draws the file.- sandbox=""- white- />- );-}+ /** The "…" button: the same menu, opened under the button. */+ const onMore = (event: ReactMouseEvent<HTMLElement>) => {+ event.stopPropagation();+ const box = event.currentTarget.getBoundingClientRect();+ handlers.onMenu(row, box.left, box.bottom + 6);+ };-/**- * True while the element is on, or about to scroll onto, the screen. Without- * an IntersectionObserver (a test DOM) nothing is ever mounted — a cover then- * stays its quiet placeholder, never a dozen live frames.- */-function useNearViewport(ref: RefObject<HTMLElement | null>): boolean {- const [near, setNear] = useState(false);- useEffect(() => {- const node = ref.current;- if (!node || typeof IntersectionObserver === "undefined") return;- const observer = new IntersectionObserver(- (entries) => setNear(entries.some((entry) => entry.isIntersecting)),- { rootMargin: "400px 0px" },- );- observer.observe(node);- return () => observer.disconnect();- }, [ref]);- return near;+ return { dragProps, onContextMenu, onKeyDown, onMore };}-/** The element's size, kept current. */-function useBoxSize(ref: RefObject<HTMLElement | null>): { width: number; height: number } {- const [size, setSize] = useState({ width: 0, height: 0 });- useEffect(() => {- const node = ref.current;- if (!node || typeof ResizeObserver === "undefined") return;- const observer = new ResizeObserver(([entry]) => {- const { width, height } = entry.contentRect;- setSize((prev) => (prev.width === width && prev.height === height ? prev : { width, height }));- });- observer.observe(node);- return () => observer.disconnect();- }, [ref]);- return size;-}+/* ------------------------------------------------------------------------- */-/**- * A page laid out at desktop width and scaled onto the card — the dashboard- * looks like the dashboard, not like its mobile layout. Inert: no pointer,- * no focus, hidden from assistive tech (the card button carries the name).- */-function ScaledFrame({- src,- title,- virtualWidth,- sandbox,- white = false,+/** The wall: tiles of three shapes, each in the column that is shortest. */+function ArtifactWall({+ rows,+ size,+ labels,+ feature,+ favorites,+ handlers,}: {- src: string;- title: string;- virtualWidth: number;- sandbox: string;- white?: boolean;+ rows: RailRow[];+ size: TileSize;+ labels: TileLabels;+ feature: boolean;+ favorites: ReadonlySet<string>;+ handlers: CardHandlers;}) {const box = useRef<HTMLDivElement>(null);- const near = useNearViewport(box);- const { width, height } = useBoxSize(box);- const [loaded, setLoaded] = useState(false);- useEffect(() => setLoaded(false), [src]);- const scale = width > 0 ? width / virtualWidth : 0;+ const { width } = useBoxSize(box);+ const ratios = useImageRatios();+ const columns = wallColumns(width, TILE_MINIMUM[size], WALL_GAP);+ // The newest page or picture leads as a tile of four — when there is room+ // for it to lead something.+ const lead = feature && columns >= 3 && rows.length >= 4 ? featureIndex(rows) : -1;+ const shapes = rows.map(+ (row, index): TileShape => (index === lead ? "feature" : tileShape(row, ratios.get(row.key))),+ );+ const shapeKey = shapes.join(",");+ const layout = useMemo(+ () => (width > 0 ? layoutWall(shapes, width, columns, WALL_GAP) : null),+ // `shapes` is rebuilt every render; its joined form is what changes.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ [shapeKey, width, columns],+ );++ // One container either way, so what measures it keeps measuring it. Before+ // the wall knows its width (and in a DOM without layout) the tiles are a+ // plain grid of squares — every card is there from the first paint.return (- <div ref={box} className="absolute inset-0" aria-hidden>- {!loaded && <div className="absolute inset-0 animate-pulse bg-foreground/5" />}- {near && scale > 0 && (- <iframe- key={src}- src={src}- title={title}- tabIndex={-1}- sandbox={sandbox}- loading="lazy"- onLoad={() => setLoaded(true)}- data-testid="artifact-card-frame"- className={cn(- "pointer-events-none absolute left-0 top-0 origin-top-left border-0 transition-opacity duration-300",- white ? "bg-white" : "bg-background",- loaded ? "opacity-100" : "opacity-0",- )}- style={{- // A little wider than the box shows: the page's own scrollbar- // falls outside the card instead of striping its edge.- width: virtualWidth + SCROLLBAR_ALLOWANCE,- height: height / scale,- transform: `scale(${scale})`,- }}- />- )}+ <div+ ref={box}+ className={+ layout ? "relative w-full" : "grid grid-cols-[repeat(auto-fill,minmax(14rem,1fr))] gap-4"+ }+ style={layout ? { height: layout.height } : undefined}+ >+ {rows.map((row, index) => {+ const place = layout?.boxes[index];+ return (+ <div+ key={row.key}+ className={+ place+ ? "absolute left-0 top-0 transition-[transform,width,height] duration-500 ease-out motion-reduce:transition-none"+ : "relative aspect-square"+ }+ style={+ place && {+ width: place.width,+ height: place.height,+ transform: `translate3d(${place.x}px, ${place.y}px, 0)`,+ }+ }+ >+ <div+ className="h-full w-full animate-in fade-in-0 zoom-in-95 fill-mode-both duration-500 motion-reduce:animate-none"+ style={{ animationDelay: `${Math.min(index, 14) * 28}ms` }}+ >+ <WallTile+ row={row}+ labels={labels}+ short={place !== undefined && shapes[index] === "wide"}+ favorite={favorites.has(row.key)}+ handlers={handlers}+ />+ </div>+ </div>+ );+ })}</div>);}-function ImageCover({ visual }: { visual: VisualArtifact }) {- const [failed, setFailed] = useState(false);- if (failed) return <IconCover icon={<FileImage className="h-8 w-8" aria-hidden />} />;+function SkeletonWall() {return (- <img- src={visual.url}- alt=""- loading="lazy"- decoding="async"- onError={() => setFailed(true)}- className={cn(- "absolute inset-0 h-full w-full",- visual.kind === "vector" ? "object-contain p-6" : "object-cover object-top",- )}- />+ <div className="grid grid-cols-[repeat(auto-fill,minmax(14rem,1fr))] gap-4" aria-hidden>+ {Array.from({ length: 10 }, (_, index) => (+ <div+ key={index}+ className="aspect-square animate-pulse rounded-2xl bg-foreground/[0.06]"+ style={{ animationDelay: `${index * 90}ms` }}+ />+ ))}+ </div>);}-function IconCover({ icon }: { icon: ReactNode }) {+/** The round buttons that sit on a tile's corner. */+const TILE_BUTTON =+ "inline-flex h-8 w-8 items-center justify-center rounded-full transition-[background-color,color,transform] " ++ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring active:scale-95 [&_svg]:h-4 [&_svg]:w-4";++/** One tile: the cover, and over it a caption, a star, a menu and a status. */+function WallTile({+ row,+ labels,+ short,+ favorite,+ handlers,+}: {+ row: RailRow;+ labels: TileLabels;+ /** A half-height tile: its caption is one line, so the picture keeps the rest. */+ short: boolean;+ favorite: boolean;+ handlers: CardHandlers;+}) {+ const t = useT();+ const language = useUiLanguage();+ const title = rowTitle(row);+ const status = rowStatus(row);+ const { dragProps, onContextMenu, onKeyDown, onMore } = useCardInteractions(row, handlers);+ // A cover drawn by the artifact (a page, a picture) is imagery: what sits on+ // it is light on a dark veil in both themes. A note is app surface.+ const imagery = row.kind === "visual";+ const meta = [kindLabel(row, t), relativeWhen(rowWhen(row), Date.now(), language)]+ .filter(Boolean)+ .join(" · ");++ // The pointer has to rest before a page starts to scroll — passing over the+ // wall must not set a dozen pages moving.+ const [peek, setPeek] = useState(false);+ const peekTimer = useRef<number | null>(null);+ const stopPeek = useCallback(() => {+ if (peekTimer.current !== null) window.clearTimeout(peekTimer.current);+ peekTimer.current = null;+ setPeek(false);+ }, []);+ useEffect(() => stopPeek, [stopPeek]);++ const overTile = imagery+ ? "bg-black/55 text-white backdrop-blur-md hover:bg-black/75"+ : "bg-secondary text-muted-foreground hover:bg-border hover:text-foreground";+ const revealed =+ "opacity-0 transition-opacity duration-200 group-hover/tile:opacity-100 group-focus-within/tile:opacity-100";+return (- <div className="absolute inset-0 flex items-center justify-center text-foreground-faint">{icon}</div>+ <div+ className="group/tile relative h-full w-full"+ onPointerEnter={(event) => {+ if (event.pointerType === "touch") return;+ peekTimer.current = window.setTimeout(() => setPeek(true), PEEK_DELAY_MS);+ }}+ onPointerLeave={stopPeek}+ >+ <button+ type="button"+ onClick={() => handlers.onOpen(row)}+ onContextMenu={onContextMenu}+ onKeyDown={onKeyDown}+ aria-label={title}+ data-testid={ROW_TESTID[row.kind]}+ data-kind={row.kind === "visual" ? row.visual.kind : undefined}+ data-status={row.kind === "run" ? status : undefined}+ className={cn(+ "absolute inset-0 overflow-hidden rounded-2xl border border-border bg-card text-left",+ "transition-[border-color,box-shadow] duration-200",+ "hover:border-border-strong hover:shadow-float",+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",+ )}+ {...dragProps}+ >+ <TileCover row={row} peek={peek} />+ {imagery && (+ <span+ className={cn(+ // A pane of dark glass, so the name reads on any page or picture.+ "pointer-events-none absolute inset-x-2 bottom-2 flex flex-col gap-0.5 rounded-xl px-3",+ "bg-black/70 backdrop-blur-md",+ short ? "py-1.5" : "py-2.5",+ labels === "hover" &&+ "translate-y-1 opacity-0 transition-[opacity,transform] duration-200 group-hover/tile:translate-y-0 group-hover/tile:opacity-100 group-focus-within/tile:translate-y-0 group-focus-within/tile:opacity-100",+ )}+ data-testid="artifact-tile-caption"+ >+ <span+ className={cn(+ "text-base font-semibold leading-snug text-white [overflow-wrap:anywhere]",+ short ? "line-clamp-1" : "line-clamp-2",+ )}+ >+ {title}+ </span>+ {!short && <span className="truncate text-sm text-white/70">{meta}</span>}+ </span>+ )}+ </button>++ {status !== "success" && status !== "unknown" && row.kind === "visual" && (+ <span className="pointer-events-none absolute left-3 top-3 inline-flex items-center gap-1.5 rounded-full bg-black/60 px-2.5 py-1 text-sm text-white backdrop-blur-md">+ <span className={cn("h-1.5 w-1.5 rounded-full", STATUS_DOT[status])} aria-hidden />+ {t(`visualization.status_word_${status}`)}+ </span>+ )}++ <div className="absolute right-2.5 top-2.5 flex items-center gap-1.5">+ <button+ type="button"+ aria-pressed={favorite}+ aria-label={t(favorite ? "visualization.favorite_remove" : "visualization.favorite_add")}+ title={t(favorite ? "visualization.favorite_remove" : "visualization.favorite_add")}+ onClick={() => handlers.onToggleFavorite(row.key)}+ data-testid="artifact-favorite"+ className={cn(TILE_BUTTON, overTile, !favorite && revealed)}+ >+ <Star className={cn(favorite && "fill-current text-warning")} aria-hidden />+ </button>+ <button+ type="button"+ aria-haspopup="menu"+ aria-label={t("visualization.menu_aria")}+ title={t("visualization.menu_aria")}+ onClick={onMore}+ data-testid="artifact-more"+ className={cn(TILE_BUTTON, overTile, revealed)}+ >+ <Ellipsis aria-hidden />+ </button>+ </div>+ </div>);}-/** A run that drew nothing: its own answer, set like the first page of a document. */-function TextCover({ title, body, files }: { title: string; body: string; files: number }) {+/* ------------------------------------------------------------------------- */++/** The same cards as rows, under their date headings. */+function ArtifactList({+ groups,+ favorites,+ handlers,+}: {+ groups: GalleryGroup[];+ favorites: ReadonlySet<string>;+ handlers: CardHandlers;+}) {const t = useT();return (- <div className="absolute inset-0 flex flex-col gap-2 bg-sidebar px-5 pb-4 pt-5">- <p className="line-clamp-2 shrink-0 text-base font-semibold leading-snug text-foreground-strong">{title}</p>- {body && (- <p className="min-h-0 flex-1 overflow-hidden text-sm leading-relaxed text-muted-foreground [mask-image:linear-gradient(to_bottom,black_60%,transparent)]">- {body}- </p>- )}- {files > 0 && (- <p className="mt-auto inline-flex shrink-0 items-center gap-1.5 text-sm text-foreground-faint">- <Files className="h-3.5 w-3.5" aria-hidden />- {files === 1 ? t("visualization.file_one") : t("visualization.files_count").replace("{0}", String(files))}- </p>- )}+ <div className="-mx-3 w-full max-w-6xl">+ {groups.map((group) => (+ <section key={group.id} aria-label={t(`visualization.group_${group.id}`)} className="pt-4">+ <h2 className="px-3 pb-1.5 text-sm font-medium text-foreground-faint">+ {t(`visualization.group_${group.id}`)}+ </h2>+ {group.rows.map((row) => (+ <ListRow key={row.key} row={row} favorite={favorites.has(row.key)} handlers={handlers} />+ ))}+ </section>+ ))}</div>);}-/** A page being written: a page-shaped placeholder that says so. */-function BuildingCover() {+function ListRow({+ row,+ favorite,+ handlers,+}: {+ row: RailRow;+ favorite: boolean;+ handlers: CardHandlers;+}) {const t = useT();+ const language = useUiLanguage();+ const title = rowTitle(row);+ const request = rowRequest(row);+ const status = rowStatus(row);+ const { dragProps, onContextMenu, onKeyDown, onMore } = useCardInteractions(row, handlers);+ const quiet =+ "opacity-0 transition-opacity group-hover/row:opacity-100 group-focus-within/row:opacity-100";+return (- <div className="absolute inset-0 flex flex-col gap-3 bg-sidebar p-5">- <div className="h-4 w-1/2 animate-pulse rounded bg-foreground/15" />- <div className="h-3 w-3/4 animate-pulse rounded bg-foreground/10" />- <div className="grid flex-1 grid-cols-3 gap-2 pt-1">- <div className="animate-pulse rounded-md bg-foreground/10" />- <div className="animate-pulse rounded-md bg-foreground/10" />- <div className="animate-pulse rounded-md bg-foreground/10" />- </div>- <p className="inline-flex items-center gap-1.5 text-sm text-muted-foreground">- <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />- {t("visualization.building")}- </p>+ <div className="group/row flex items-center gap-1 rounded-xl pr-2 transition-colors hover:bg-secondary/70 focus-within:bg-secondary/70">+ <button+ type="button"+ onClick={() => handlers.onOpen(row)}+ onContextMenu={onContextMenu}+ onKeyDown={onKeyDown}+ data-testid={ROW_TESTID[row.kind]}+ data-kind={row.kind === "visual" ? row.visual.kind : undefined}+ data-status={row.kind === "run" ? status : undefined}+ className="flex min-w-0 flex-1 items-center gap-4 rounded-xl px-3 py-2 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ {...dragProps}+ >+ <RowThumb row={row} />+ <span className="min-w-0 flex-1">+ <span className="flex min-w-0 items-center gap-2">+ <span className="truncate text-base font-medium text-foreground-strong">{title}</span>+ {status !== "success" && status !== "unknown" && row.kind !== "build" && (+ <span className="inline-flex shrink-0 items-center gap-1.5 text-sm text-muted-foreground">+ <span className={cn("h-1.5 w-1.5 rounded-full", STATUS_DOT[status])} aria-hidden />+ {t(`visualization.status_word_${status}`)}+ </span>+ )}+ </span>+ {request && request !== title && (+ <span className="block truncate text-sm text-foreground-faint">{request}</span>+ )}+ </span>+ <span className="hidden w-32 shrink-0 truncate text-sm text-muted-foreground md:block">+ {kindLabel(row, t)}+ </span>+ <span className="hidden w-28 shrink-0 truncate text-sm text-muted-foreground sm:block">+ {relativeWhen(rowWhen(row), Date.now(), language)}+ </span>+ <span className="hidden w-20 shrink-0 text-right text-sm tabular-nums text-foreground-faint lg:block">+ {row.kind === "visual" ? formatSize(row.visual.size) : ""}+ </span>+ </button>+ <button+ type="button"+ aria-pressed={favorite}+ aria-label={t(favorite ? "visualization.favorite_remove" : "visualization.favorite_add")}+ title={t(favorite ? "visualization.favorite_remove" : "visualization.favorite_add")}+ onClick={() => handlers.onToggleFavorite(row.key)}+ data-testid="artifact-favorite"+ className={cn(+ TILE_BUTTON,+ "text-muted-foreground hover:bg-border hover:text-foreground",+ !favorite && quiet,+ )}+ >+ <Star className={cn(favorite && "fill-current text-warning")} aria-hidden />+ </button>+ <button+ type="button"+ aria-haspopup="menu"+ aria-label={t("visualization.menu_aria")}+ title={t("visualization.menu_aria")}+ onClick={onMore}+ data-testid="artifact-more"+ className={cn(TILE_BUTTON, "text-muted-foreground hover:bg-border hover:text-foreground", quiet)}+ >+ <Ellipsis aria-hidden />+ </button></div>);}diff --git a/jarvis/ui/web/frontend/src/components/visualization/galleryModel.test.ts b/jarvis/ui/web/frontend/src/components/visualization/galleryModel.test.tsindex 2d3d7ca520..e188caf510 100644--- a/jarvis/ui/web/frontend/src/components/visualization/galleryModel.test.ts+++ b/jarvis/ui/web/frontend/src/components/visualization/galleryModel.test.ts@@ -1,6 +1,6 @@/**- * The gallery's ordering rules — categories, search, sort and date headings —- * pinned without rendering a single card.+ * The gallery's rules — tabs, search, sort, date headings and where each tile+ * goes on the wall — pinned without rendering a single card.*/import { describe, expect, it } from "vitest";@@ -10,10 +10,16 @@ import {buildRailRows,countByFilter,dateGroupOf,+ featureIndex,filterRailRows,groupRailRows,+ layoutWall,searchRailRows,+ shapeForRatio,sortRailRows,+ suggestRows,+ tileShape,+ wallColumns,} from "@/components/visualization/galleryModel";const NOW = new Date(2026, 9, 1, 15, 0, 0).getTime();@@ -49,10 +55,115 @@ const RUNS = [run("a"), run("b"), run("c"), run("d", { summary: "Refactored thedescribe("gallery model", () => {it("counts and filters by category", () => {const rows = buildRailRows(RUNS, VISUALS, []);- expect(countByFilter(rows)).toEqual({ all: 4, pages: 1, images: 1, documents: 1, outputs: 1 });+ expect(countByFilter(rows)).toEqual({+ suggested: 4,+ favorites: 0,+ pages: 1,+ images: 1,+ documents: 1,+ outputs: 1,+ all: 4,+ });expect(filterRailRows(rows, "images").map((r) => r.key)).toEqual(["b::files/Logo"]);});+ it("keeps the starred cards under Favorites and counts them", () => {+ const rows = buildRailRows(RUNS, VISUALS, []);+ const picks = { favorites: new Set(["c::files/Report", "run:d"]), now: NOW };+ expect(filterRailRows(rows, "favorites", picks).map((r) => r.key)).toEqual([+ "run:d",+ "c::files/Report",+ ]);+ expect(countByFilter(rows, picks).favorites).toBe(2);+ // A star on something that is gone counts for nothing.+ expect(countByFilter(rows, { favorites: new Set(["gone::x"]), now: NOW }).favorites).toBe(0);+ });++ it("suggests what is in progress, starred or new, and tops a quiet library up", () => {+ const old = (index: number) =>+ visual(`old${index}`, `Old ${index}`, "page", nowS - (30 + index) * 24 * HOUR);+ const many = Array.from({ length: 20 }, (_, index) => old(index));+ const fresh = visual("new", "Fresh", "page", nowS - HOUR);+ const building = run("wip", { status: "running", utterance: "Artifact: Board\nDraw it" });+ const rows = buildRailRows([building], [fresh, ...many], [building]);++ // Twelve at least: the build, the fresh page, then the newest of the old.+ const quiet = suggestRows(rows, { favorites: new Set(), now: NOW });+ expect(quiet).toHaveLength(12);+ expect(quiet.slice(0, 2).map((r) => r.key)).toEqual(["build:wip", "new::files/Fresh"]);+ expect(quiet.some((r) => r.key === "old19::files/Old 19")).toBe(false);++ // A star pulls an old card in, wherever it sits.+ const starred = suggestRows(rows, { favorites: new Set(["old19::files/Old 19"]), now: NOW });+ expect(starred.some((r) => r.key === "old19::files/Old 19")).toBe(true);+ expect(starred).toHaveLength(12);+ });++ it("shapes a tile by what it shows", () => {+ const [page, vector, document] = buildRailRows([], VISUALS, []);+ expect(tileShape(page)).toBe("square");+ expect(tileShape(document)).toBe("tall");+ // A picture follows its own proportions once they are known.+ expect(tileShape(vector)).toBe("square");+ expect(tileShape(vector, 2.4)).toBe("wide");+ expect(tileShape(vector, 0.6)).toBe("tall");+ expect(shapeForRatio(1)).toBe("square");+ // A page stays a square whatever a stale measurement says.+ expect(tileShape(page, 3)).toBe("square");+ });++ it("leads the wall with its first page, picture or drawing, never a note or a PDF", () => {+ const building = run("wip", { status: "running", utterance: "Artifact: Board\nDraw it" });+ const rows = buildRailRows([...RUNS, building], VISUALS, [building]);+ // rows: the build, the note (run d), then the page.+ expect(rows.map((r) => r.kind)).toEqual(["build", "run", "visual", "visual", "visual"]);+ expect(featureIndex(rows)).toBe(2);+ expect(featureIndex(rows.filter((r) => r.kind !== "visual"))).toBe(-1);+ // A drawing leads; a PDF in front of it is passed over.+ const sheets = buildRailRows(+ [],+ [visual("p", "Deck", "document", nowS - HOUR), visual("v", "Mark", "vector", nowS - 2 * HOUR)],+ [],+ );+ expect(featureIndex(sheets)).toBe(1);+ expect(featureIndex(sheets.slice(0, 1))).toBe(-1);+ // Too far down to lead anything.+ const notes = Array.from({ length: 6 }, (_, index) => run(`n${index}`));+ const buried = buildRailRows(notes, [visual("late", "Late", "page", nowS - 9 * HOUR)], []);+ expect(buried[6].kind).toBe("visual");+ expect(featureIndex(buried)).toBe(-1);+ });++ it("fits as many columns as the tile size allows, one at least", () => {+ expect(wallColumns(1000, 228, 16)).toBe(4);+ expect(wallColumns(1204, 228, 16)).toBe(5);+ expect(wallColumns(120, 228, 16)).toBe(1);+ });++ it("puts each tile into the shortest column on one half-tile lattice", () => {+ // Three columns of 100 with a gap of 10.+ const { boxes, height } = layoutWall(["square", "wide", "tall", "wide", "square"], 320, 3, 10);+ expect(boxes[0]).toEqual({ x: 0, y: 0, width: 100, height: 100 });+ expect(boxes[1]).toEqual({ x: 110, y: 0, width: 100, height: 45 });+ expect(boxes[2]).toEqual({ x: 220, y: 0, width: 100, height: 155 });+ // The second wide tile goes under the first: two of them make one square.+ expect(boxes[3]).toEqual({ x: 110, y: 55, width: 100, height: 45 });+ expect(boxes[3].y + boxes[3].height).toBe(boxes[0].height);+ // Columns one and two are level again; the leftmost takes the next tile.+ expect(boxes[4]).toEqual({ x: 0, y: 110, width: 100, height: 100 });+ expect(height).toBe(210);+ });++ it("gives a lead tile two columns and two rows, and falls back when there is one column", () => {+ const { boxes } = layoutWall(["square", "feature", "square"], 320, 3, 10);+ expect(boxes[1]).toEqual({ x: 110, y: 0, width: 210, height: 210 });+ // The next tile goes under the first, beside the lead.+ expect(boxes[2]).toEqual({ x: 0, y: 110, width: 100, height: 100 });+ const narrow = layoutWall(["feature", "square"], 100, 1, 10);+ expect(narrow.boxes[0]).toEqual({ x: 0, y: 0, width: 100, height: 100 });+ expect(narrow.boxes[1].y).toBe(110);+ });+it("searches titles, requests and summaries with every word", () => {const rows = buildRailRows(RUNS, VISUALS, []);expect(searchRailRows(rows, "sales MAP")).toHaveLength(1);diff --git a/jarvis/ui/web/frontend/src/components/visualization/galleryModel.ts b/jarvis/ui/web/frontend/src/components/visualization/galleryModel.tsindex 92a6bd3993..51d739c973 100644--- a/jarvis/ui/web/frontend/src/components/visualization/galleryModel.ts+++ b/jarvis/ui/web/frontend/src/components/visualization/galleryModel.ts@@ -16,17 +16,42 @@ export type RailRow =| { kind: "visual"; run: OutputSummary | null; visual: VisualArtifact; key: string }| { kind: "run"; run: OutputSummary; key: string };-/** The library's categories — what the gallery's side rail offers. */-export type RailFilter = "all" | "pages" | "images" | "documents" | "outputs";+/**+ * The library's tabs. Two are picks ("suggested": what is in progress, what is+ * starred and what is new; "favorites": what the reader starred), four are+ * kinds, and "all" is everything.+ */+export type RailFilter =+ | "suggested"+ | "favorites"+ | "pages"+ | "images"+ | "documents"+ | "outputs"+ | "all";export const RAIL_FILTERS: readonly RailFilter[] = [- "all",+ "suggested",+ "favorites","pages","images","documents","outputs",+ "all",];+/** The kind a card belongs to — every tab that is not a pick or "all". */+export type RailCategory = "pages" | "images" | "documents" | "outputs";++/** What the two pick tabs need to know: the starred cards and the time. */+export interface PickContext {+ favorites: ReadonlySet<string>;+ /** Epoch milliseconds. */+ now: number;+}++const NO_PICKS: PickContext = { favorites: new Set(), now: 0 };+/** How the gallery orders its cards. */export type GallerySort = "newest" | "oldest" | "name";@@ -92,7 +117,7 @@ export function isActiveRow(row: RailRow): boolean {}/** The category a card belongs to (besides "all"). */-export function rowCategory(row: RailRow): Exclude<RailFilter, "all"> {+export function rowCategory(row: RailRow): RailCategory {if (row.kind === "build") return "pages";if (row.kind === "run") return "outputs";switch (row.visual.kind) {@@ -144,25 +169,173 @@ export function buildRailRows(];}-/** The cards a category lets through. */-export function filterRailRows(rows: RailRow[], filter: RailFilter): RailRow[] {+/** A week of work counts as new; a quiet library still suggests this many. */+const SUGGEST_WINDOW_S = 7 * 86_400;+const SUGGEST_MINIMUM = 12;++/**+ * The "Suggested" pick: everything in progress, everything starred and+ * everything from the last week — topped up with the newest older cards so a+ * library nobody touched this week still opens on a full wall. The order of+ * `rows` is kept.+ */+export function suggestRows(rows: RailRow[], picks: PickContext): RailRow[] {+ const since = picks.now / 1000 - SUGGEST_WINDOW_S;+ const chosen = new Set<string>();+ for (const row of rows) {+ if (isActiveRow(row) || picks.favorites.has(row.key) || rowWhen(row) >= since) {+ chosen.add(row.key);+ }+ }+ if (chosen.size < SUGGEST_MINIMUM) {+ const newest = [...rows].sort((a, b) => rowWhen(b) - rowWhen(a));+ for (const row of newest) {+ if (chosen.size >= SUGGEST_MINIMUM) break;+ chosen.add(row.key);+ }+ }+ return rows.filter((row) => chosen.has(row.key));+}++/** The cards a tab lets through. */+export function filterRailRows(+ rows: RailRow[],+ filter: RailFilter,+ picks: PickContext = NO_PICKS,+): RailRow[] {if (filter === "all") return rows;+ if (filter === "suggested") return suggestRows(rows, picks);+ if (filter === "favorites") return rows.filter((row) => picks.favorites.has(row.key));return rows.filter((row) => rowCategory(row) === filter);}-/** How many cards each category holds. */-export function countByFilter(rows: RailRow[]): Record<RailFilter, number> {+/** How many cards each tab holds. */+export function countByFilter(+ rows: RailRow[],+ picks: PickContext = NO_PICKS,+): Record<RailFilter, number> {const counts: Record<RailFilter, number> = {- all: rows.length,+ suggested: suggestRows(rows, picks).length,+ favorites: 0,pages: 0,images: 0,documents: 0,outputs: 0,+ all: rows.length,};- for (const row of rows) counts[rowCategory(row)] += 1;+ for (const row of rows) {+ counts[rowCategory(row)] += 1;+ if (picks.favorites.has(row.key)) counts.favorites += 1;+ }return counts;}+/* ------------------------------------------------------------------------- */++/**+ * The shapes a tile on the wall can take. All of them sit on one half-tile+ * lattice — a wide tile is half a square, a tall one a square and a half — so+ * columns of mixed tiles keep falling back into line.+ */+export type TileShape = "wide" | "square" | "tall" | "feature";++/** The shape a picture of this width/height ratio is shown in. */+export function shapeForRatio(ratio: number): Exclude<TileShape, "feature"> {+ if (ratio >= 1.4) return "wide";+ if (ratio <= 0.8) return "tall";+ return "square";+}++/**+ * A card's shape on the wall. A picture follows its own proportions once they+ * are known (`ratio`), a PDF stands like the sheet it is, everything else is a+ * square.+ */+export function tileShape(row: RailRow, ratio?: number): Exclude<TileShape, "feature"> {+ if (row.kind !== "visual") return "square";+ if (row.visual.kind === "document") return "tall";+ const picture = row.visual.kind === "image" || row.visual.kind === "vector";+ if (picture && ratio !== undefined && ratio > 0) return shapeForRatio(ratio);+ return "square";+}++/**+ * How far into the wall the lead tile may sit — behind work in progress and a+ * few notes, not behind a whole row of other pictures.+ */+const FEATURE_WITHIN = 6;++/**+ * Which card leads the wall as a tile of four: the first page, picture or+ * drawing near the top. A note has nothing to fill four tiles with and a PDF+ * is a sheet, not a square, so neither leads. -1 when nothing does.+ */+export function featureIndex(rows: RailRow[]): number {+ const limit = Math.min(rows.length, FEATURE_WITHIN);+ for (let index = 0; index < limit; index += 1) {+ const row = rows[index];+ if (row.kind === "visual" && row.visual.kind !== "document") return index;+ }+ return -1;+}++export interface TileBox {+ x: number;+ y: number;+ width: number;+ height: number;+}++/** How many columns of at least `minimum` px fit into `width`. */+export function wallColumns(width: number, minimum: number, gap: number): number {+ return Math.max(1, Math.floor((width + gap) / (minimum + gap)));+}++/**+ * Where every tile goes: each one into the column that is shortest so far,+ * leftmost on a tie — reading order stays roughly left to right, top to+ * bottom, and no column runs away from the others. A "feature" tile takes two+ * columns side by side and is two squares high.+ */+export function layoutWall(+ shapes: TileShape[],+ width: number,+ columns: number,+ gap: number,+): { boxes: TileBox[]; height: number } {+ const count = Math.max(1, columns);+ const column = (width - gap * (count - 1)) / count;+ const heights = new Array<number>(count).fill(0);+ const boxes: TileBox[] = [];+ for (const wanted of shapes) {+ const shape = wanted === "feature" && count < 2 ? "square" : wanted;+ if (shape === "feature") {+ let at = 0;+ let top = Number.POSITIVE_INFINITY;+ for (let index = 0; index < count - 1; index += 1) {+ const candidate = Math.max(heights[index], heights[index + 1]);+ if (candidate < top) {+ top = candidate;+ at = index;+ }+ }+ const size = column * 2 + gap;+ boxes.push({ x: at * (column + gap), y: top, width: size, height: size });+ heights[at] = heights[at + 1] = top + size + gap;+ continue;+ }+ let at = 0;+ for (let index = 1; index < count; index += 1) {+ if (heights[index] < heights[at] - 0.5) at = index;+ }+ const height =+ shape === "wide" ? (column - gap) / 2 : shape === "tall" ? column * 1.5 + gap / 2 : column;+ boxes.push({ x: at * (column + gap), y: heights[at], width: column, height });+ heights[at] += height + gap;+ }+ return { boxes, height: Math.max(0, Math.max(...heights) - gap) };+}+/** Cards whose title, request, summary or filename contain every search word. */export function searchRailRows(rows: RailRow[], query: string): RailRow[] {const words = query.toLowerCase().split(/\s+/).filter(Boolean);diff --git a/jarvis/ui/web/frontend/src/hooks/useArtifactFavorites.ts b/jarvis/ui/web/frontend/src/hooks/useArtifactFavorites.tsnew file mode 100644index 0000000000..847931caa6--- /dev/null+++ b/jarvis/ui/web/frontend/src/hooks/useArtifactFavorites.ts@@ -0,0 +1,86 @@+/**+ * The artifacts the reader starred.+ *+ * A star is a per-reader mark on a card, kept in this browser profile's+ * storage: it survives restarts of the desktop app and is shared by every+ * window of it (a detached Artifacts window stars and the main one follows,+ * through the `storage` event). Nothing about it reaches the run archive — a+ * starred run is the same folder on disk as any other.+ *+ * The key is the card's key (`<slug>::<path>` for an artifact, `run:<slug>`+ * for a run without one), so a star stays with exactly the thing it was put on.+ */+import { useCallback, useSyncExternalStore } from "react";++const STORAGE_KEY = "jarvis.artifacts.favorites";+/** A star on something long deleted is harmless; a list without end is not. */+const MAX_FAVORITES = 500;++const EMPTY: ReadonlySet<string> = new Set();++let cachedRaw: string | null | undefined;+let cachedSet: ReadonlySet<string> = EMPTY;+const listeners = new Set<() => void>();++function read(): ReadonlySet<string> {+ let raw: string | null = null;+ try {+ raw = window.localStorage.getItem(STORAGE_KEY);+ } catch {+ // Storage can be unavailable (private window, blocked site data) — no stars then.+ }+ if (raw === cachedRaw) return cachedSet;+ cachedRaw = raw;+ cachedSet = EMPTY;+ if (raw) {+ try {+ const parsed: unknown = JSON.parse(raw);+ if (Array.isArray(parsed)) {+ cachedSet = new Set(parsed.filter((key): key is string => typeof key === "string"));+ }+ } catch {+ // A value something else wrote under this key is not a list of stars.+ }+ }+ return cachedSet;+}++function write(next: ReadonlySet<string>): void {+ const keys = [...next].slice(-MAX_FAVORITES);+ cachedSet = new Set(keys);+ cachedRaw = JSON.stringify(keys);+ try {+ window.localStorage.setItem(STORAGE_KEY, cachedRaw);+ } catch {+ // The star still holds for this window; it just will not outlive it.+ }+ for (const listener of listeners) listener();+}++function subscribe(listener: () => void): () => void {+ listeners.add(listener);+ const onStorage = (event: StorageEvent) => {+ if (event.key === null || event.key === STORAGE_KEY) listener();+ };+ window.addEventListener("storage", onStorage);+ return () => {+ listeners.delete(listener);+ window.removeEventListener("storage", onStorage);+ };+}++export interface ArtifactFavorites {+ favorites: ReadonlySet<string>;+ /** Star the card, or take its star away. */+ toggle: (key: string) => void;+}++export function useArtifactFavorites(): ArtifactFavorites {+ const favorites = useSyncExternalStore(subscribe, read, () => EMPTY);+ const toggle = useCallback((key: string) => {+ const next = new Set(read());+ if (!next.delete(key)) next.add(key);+ write(next);+ }, []);+ return { favorites, toggle };+}diff --git a/jarvis/ui/web/frontend/src/hooks/useOutputs.ts b/jarvis/ui/web/frontend/src/hooks/useOutputs.tsindex c1b26b2273..9966e618cf 100644--- a/jarvis/ui/web/frontend/src/hooks/useOutputs.ts+++ b/jarvis/ui/web/frontend/src/hooks/useOutputs.ts@@ -227,6 +227,8 @@ export interface ArtifactSummary {mtime: number;is_text: boolean;preview: string | null;+ /** A page's own `<title>`, read by the listing (absent on older backends). */+ title?: string | null;}export interface ArtifactsResponse {diff --git a/jarvis/ui/web/frontend/src/hooks/useVisualArtifacts.ts b/jarvis/ui/web/frontend/src/hooks/useVisualArtifacts.tsindex 86a5b55710..936ca34f10 100644--- a/jarvis/ui/web/frontend/src/hooks/useVisualArtifacts.ts+++ b/jarvis/ui/web/frontend/src/hooks/useVisualArtifacts.ts@@ -70,9 +70,9 @@ export interface VisualArtifact {/** Last path segment — the fallback label. */name: string;/**- * What the rail calls it: a page's own `<title>` when the listing's preview- * carries one, otherwise the filename. The title is what the user asked for- * in their words ("Umsatz-Dashboard"), the filename is its slug.+ * What the library calls it: a page's own `<title>`, else the title its+ * brief asked for, otherwise the filename. The title is what the user asked+ * for in their words ("Umsatz-Dashboard"), the filename is its slug.*/title: string;kind: VisualKind;@@ -154,20 +154,32 @@ function decodeEntities(text: string): string {.replace(/&/g, "&");}+/** The title a `create_artifact` brief leads with (`Artifact: <title>`), or null. */+function briefTitle(utterance: string | undefined): string | null {+ const match = /^Artifact:[ \t]*([^\n]+)/.exec((utterance ?? "").trim());+ return match ? match[1].trim() || null : null;+}+/** The visuals among a run's files, carrying the run they belong to. */export function toVisuals(run: OutputSummary, files: ArtifactSummary[]): VisualArtifact[] {const visuals: VisualArtifact[] = [];+ // A run that built exactly one page was asked for that page by name — the+ // brief's title is the page's name when the file itself does not say.+ const pages = files.filter((file) => classifyVisual(file.path) === "page").length;+ const asked = pages === 1 ? briefTitle(run.utterance) : null;for (const file of files) {const kind = classifyVisual(file.path);if (kind === null) continue;const name = file.path.split("/").pop() ?? file.path;+ const ownTitle =+ kind === "page" ? file.title?.trim() || pageTitleFromPreview(file.preview) || asked : null;visuals.push({slug: run.slug,utterance: run.utterance,status: run.status,path: file.path,name,- title: (kind === "page" ? pageTitleFromPreview(file.preview) : null) ?? name,+ title: ownTitle ?? name,kind,size: file.size,mtime: file.mtime,diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 632d9f656a..251a553ea0 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -5100,6 +5100,23 @@"filter_pages": "Seiten","filter_images": "Bilder","filter_documents": "Dokumente",+ "filter_suggested": "Vorschläge",+ "filter_favorites": "Favoriten",+ "view_label": "Darstellung",+ "view_wall": "Wand",+ "view_list": "Liste",+ "display_options": "Anzeigeoptionen",+ "tile_size": "Kachelgröße",+ "size_s": "Klein",+ "size_m": "Mittel",+ "size_l": "Groß",+ "labels_title": "Titel",+ "labels_hover": "Beim Überfahren",+ "labels_always": "Immer",+ "favorite_add": "Zu Favoriten hinzufügen",+ "favorite_remove": "Aus Favoriten entfernen",+ "favorites_empty_title": "Noch keine Favoriten",+ "favorites_empty_body": "Markiere ein Artefakt mit dem Stern, dann bleibt es hier, egal was danach kommt.","search_placeholder": "Artefakte durchsuchen","sort_label": "Sortieren","sort_newest": "Neueste zuerst",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 1e3f3df386..39e76b3eba 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -5100,6 +5100,23 @@"filter_pages": "Pages","filter_images": "Images","filter_documents": "Documents",+ "filter_suggested": "Suggested",+ "filter_favorites": "Favorites",+ "view_label": "Layout",+ "view_wall": "Wall",+ "view_list": "List",+ "display_options": "Display options",+ "tile_size": "Tile size",+ "size_s": "Small",+ "size_m": "Medium",+ "size_l": "Large",+ "labels_title": "Titles",+ "labels_hover": "On hover",+ "labels_always": "Always",+ "favorite_add": "Add to favorites",+ "favorite_remove": "Remove from favorites",+ "favorites_empty_title": "No favorites yet",+ "favorites_empty_body": "Star an artifact and it stays here, whatever comes after it.","search_placeholder": "Search artifacts","sort_label": "Sort","sort_newest": "Newest first",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 7de678813c..6e7510bf35 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -5100,6 +5100,23 @@"filter_pages": "Páginas","filter_images": "Imágenes","filter_documents": "Documentos",+ "filter_suggested": "Sugeridos",+ "filter_favorites": "Favoritos",+ "view_label": "Diseño",+ "view_wall": "Mural",+ "view_list": "Lista",+ "display_options": "Opciones de visualización",+ "tile_size": "Tamaño de las fichas",+ "size_s": "Pequeño",+ "size_m": "Mediano",+ "size_l": "Grande",+ "labels_title": "Títulos",+ "labels_hover": "Al pasar el cursor",+ "labels_always": "Siempre",+ "favorite_add": "Añadir a favoritos",+ "favorite_remove": "Quitar de favoritos",+ "favorites_empty_title": "Aún no hay favoritos",+ "favorites_empty_body": "Marca un artefacto con la estrella y se queda aquí, venga lo que venga después.","search_placeholder": "Buscar artefactos","sort_label": "Ordenar","sort_newest": "Más recientes",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/zh.json b/jarvis/ui/web/frontend/src/i18n/locales/zh.jsonindex 04190257e9..ef12d78505 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/zh.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/zh.json@@ -5106,6 +5106,23 @@"filter_pages": "页面","filter_images": "图片","filter_documents": "文档",+ "filter_suggested": "推荐",+ "filter_favorites": "收藏",+ "view_label": "布局",+ "view_wall": "墙面",+ "view_list": "列表",+ "display_options": "显示选项",+ "tile_size": "卡片大小",+ "size_s": "小",+ "size_m": "中",+ "size_l": "大",+ "labels_title": "标题",+ "labels_hover": "悬停时",+ "labels_always": "始终",+ "favorite_add": "加入收藏",+ "favorite_remove": "取消收藏",+ "favorites_empty_title": "还没有收藏",+ "favorites_empty_body": "给作品加上星标,它就会一直留在这里。","search_placeholder": "搜索成果","sort_label": "排序","sort_newest": "最新优先",diff --git a/jarvis/ui/web/frontend/src/views/VisualizationView.runs.test.tsx b/jarvis/ui/web/frontend/src/views/VisualizationView.runs.test.tsxindex 42baee5c39..36e97e4a68 100644--- a/jarvis/ui/web/frontend/src/views/VisualizationView.runs.test.tsx+++ b/jarvis/ui/web/frontend/src/views/VisualizationView.runs.test.tsx@@ -182,11 +182,10 @@ describe("VisualizationView — runs without an artifact", () => {const rows = await screen.findAllByTestId("visualization-run-row");expect(rows).toHaveLength(1);expect(rows[0].textContent).toContain("Write notes");- expect(rows[0].textContent).toContain("Three notes, saved.");expect(screen.queryAllByTestId("visualization-artifact-row")).toHaveLength(0);// No empty state: the run IS the content.expect(screen.queryByTestId("visualization-empty")).toBeNull();- // The library shows the run's own answer as its cover; a click opens it.+ // The library shows the run as a note under its own name; a click opens it.fireEvent.click(rows[0]);// The stage opens on Preview — the same four tabs every run gets …const previewTab = await screen.findByTestId("visualization-tab-preview");diff --git a/jarvis/ui/web/frontend/src/views/VisualizationView.test.tsx b/jarvis/ui/web/frontend/src/views/VisualizationView.test.tsxindex 9e56450800..f103236df9 100644--- a/jarvis/ui/web/frontend/src/views/VisualizationView.test.tsx+++ b/jarvis/ui/web/frontend/src/views/VisualizationView.test.tsx@@ -2,12 +2,15 @@* The Artifacts section — every page and picture a run produced, full-size.** Contracts worth pinning:- * - the section opens on the library: every artifact a card, newest first,- * a page labelled by its own <title>; a click opens it on the stage, back+ * - the section opens on the library: every artifact a tile, newest first,+ * a page named by its own <title>; a click opens it on the stage, back* returns, previous / next walk the library,+ * - a tile can be starred, and the starred ones are what Favorites shows,+ * - the same cards are a list one toggle away, with the request on each row,* - a PAGE is framed from `/page` with `sandbox="allow-scripts"` and no* same-origin (its scripts run, the app stays out of reach); an image goes- * through <img>; a PDF through an empty sandbox,+ * through <img>; a PDF through a frame without a sandbox, because the+ * browser's PDF viewer is a plugin and never loads inside one,* - "Code" shows the page's source, "Run" the node graph of the run that made* it — the graph is one tab away, never in front of the page,* - a `create_artifact` mission still running shows as a "building…" row and@@ -193,8 +196,9 @@ describe("VisualizationView", () => {// The library card carries the page's title, not the filename.const rows = await screen.findAllByTestId("visualization-artifact-row");expect(rows).toHaveLength(1);+ expect(rows[0].getAttribute("aria-label")).toBe("Umsatz-Dashboard");expect(rows[0].textContent).toContain("Umsatz-Dashboard");- expect(rows[0].textContent).toContain("Umsatz pro Monat 2026 als Balken.");+ expect(rows[0].textContent).toContain("Page");expect(screen.queryByTestId("visualization-frame")).toBeNull();fireEvent.click(rows[0]);@@ -291,7 +295,7 @@ describe("VisualizationView", () => {await screen.findByTestId("visualization-frame");});- it("frames a PDF in an empty sandbox and draws an image through <img>", async () => {+ it("frames a PDF without a sandbox and draws an image through <img>", async () => {installFetchMock([{ slug: "run-1", utterance: "Export", status: "success" }],{@@ -308,7 +312,8 @@ describe("VisualizationView", () => {expect(cards).toHaveLength(2);fireEvent.click(cards[0]);const frame = await screen.findByTestId("visualization-frame");- expect(frame.getAttribute("sandbox")).toBe("");+ // The browser's PDF viewer is a plugin; a sandboxed frame would stay blank.+ expect(frame.hasAttribute("sandbox")).toBe(false);expect(frame.getAttribute("src")).toContain("deck.pdf");// No Code tab for a PDF — there is no source to show.expect(screen.queryByTestId("visualization-tab-code")).toBeNull();@@ -386,6 +391,60 @@ describe("VisualizationView", () => {expect(screen.queryAllByTestId("visualization-artifact-row")).toHaveLength(0);});+ it("stars a tile and shows the starred ones under Favorites", async () => {+ window.localStorage.removeItem("jarvis.artifacts.favorites");+ window.localStorage.removeItem("jarvis.artifacts.rail-filter");+ installFetchMock(+ [{ slug: "run-1", utterance: "Export", status: "success" }],+ {+ "run-1": [+ file("tasks/t1/artifacts/files/deck.pdf", { mtime: 1_700_000_200 }),+ file("tasks/t1/artifacts/files/cover.png", { mtime: 1_700_000_100 }),+ ],+ },+ );++ renderView();++ await waitFor(() => expect(screen.getAllByTestId("visualization-artifact-row")).toHaveLength(2));+ expect(screen.getByTestId("visualization-filter-favorites").textContent).toContain("0");+ const stars = screen.getAllByTestId("artifact-favorite");+ expect(stars[1].getAttribute("aria-pressed")).toBe("false");+ fireEvent.click(stars[1]);+ expect(screen.getAllByTestId("artifact-favorite")[1].getAttribute("aria-pressed")).toBe("true");+ expect(screen.getByTestId("visualization-filter-favorites").textContent).toContain("1");++ fireEvent.click(screen.getByTestId("visualization-filter-favorites"));+ const kept = screen.getAllByTestId("visualization-artifact-row");+ expect(kept).toHaveLength(1);+ expect(kept[0].getAttribute("aria-label")).toBe("cover.png");++ // Taking the star away empties the tab, and it says what the tab is for.+ fireEvent.click(screen.getByTestId("artifact-favorite"));+ expect(screen.queryAllByTestId("visualization-artifact-row")).toHaveLength(0);+ expect(screen.getByTestId("visualization-no-matches")).toBeTruthy();+ window.localStorage.removeItem("jarvis.artifacts.rail-filter");+ });++ it("draws the same cards as a list, with the request on each row", async () => {+ window.localStorage.removeItem("jarvis.artifacts.view");+ installFetchMock([DASH_RUN], { mission_dash: [DASH_FILE] });++ renderView();++ const tiles = await screen.findAllByTestId("visualization-artifact-row");+ expect(tiles[0].textContent).not.toContain("Umsatz pro Monat 2026 als Balken.");+ fireEvent.click(screen.getByTestId("visualization-view-list"));+ const rows = screen.getAllByTestId("visualization-artifact-row");+ expect(rows).toHaveLength(1);+ expect(rows[0].textContent).toContain("Umsatz-Dashboard");+ expect(rows[0].textContent).toContain("Umsatz pro Monat 2026 als Balken.");+ expect(window.localStorage.getItem("jarvis.artifacts.view")).toBe("list");+ fireEvent.click(rows[0]);+ await screen.findByTestId("visualization-stage");+ window.localStorage.removeItem("jarvis.artifacts.view");+ });+it("says so when there are no runs at all", async () => {installFetchMock([], {});diff --git a/jarvis/ui/web/frontend/src/views/VisualizationView.tsx b/jarvis/ui/web/frontend/src/views/VisualizationView.tsxindex dc58824880..26ef781ce1 100644--- a/jarvis/ui/web/frontend/src/views/VisualizationView.tsx+++ b/jarvis/ui/web/frontend/src/views/VisualizationView.tsx@@ -10,13 +10,12 @@ import {Files,FolderOpen,Loader2,- RefreshCw,Shapes,ShieldCheck,+ Star,Workflow,} from "lucide-react";-import { Button } from "@/components/ui/button";import { EmptyState } from "@/components/ui/empty-state";import { OutputPreview } from "@/components/visualization/OutputPreview";import { RunGraphPanel } from "@/components/visualization/RunGraphPanel";@@ -28,10 +27,17 @@ import {} from "@/components/visualization/RunPanels";import {ArtifactGallery,- GalleryCategoryRail,- GalleryControls,+ GALLERY_VIEWS,+ LibraryHeader,+ LibraryTabs,+ TILE_LABELS,+ TILE_SIZES,+ type GalleryView,+ type TileLabels,+ type TileSize,} from "@/components/visualization/ArtifactGallery";import {+ RAIL_FILTERS,buildRailRows,countByFilter,filterRailRows,@@ -45,8 +51,8 @@ import {type RailFilter,type RailRow,} from "@/components/visualization/galleryModel";-import { ViewHeader } from "@/views/ChatsView";import { useT } from "@/i18n";+import { useArtifactFavorites } from "@/hooks/useArtifactFavorites";import { useThemeValue } from "@/hooks/useTheme";import { cn } from "@/lib/utils";import { artifactKind, isTextKind } from "@/lib/artifactKind";@@ -83,14 +89,16 @@ export type { RailFilter };** An artifact is the thing the user asked to LOOK AT: the dashboard, the* report, the diagram a background agent wrote as one self-contained HTML- * file (`create_artifact`), or any image/PDF a worker left behind. Since- * 2026-10-01 the section opens on a GALLERY: every artifact as a card with- * the artifact itself drawn on it (a live, scaled page; the picture; a PDF's- * first page), grouped by day, narrowed by category (pages, images,- * documents, outputs) and by search, sorted newest, oldest or by name. A- * click opens the STAGE: the page full-size in its sandbox, the source one- * tab away, every file of the run behind "Files", and the n8n-style run- * graph behind "Run"; back, previous and next walk the same list.+ * file (`create_artifact`), or any image/PDF a worker left behind. The+ * section opens on a WALL: every artifact as a tile with the artifact itself+ * drawn on it edge to edge (a live, scaled page that scrolls itself under a+ * resting pointer; the picture; a PDF's first sheet), narrowed by a row of+ * tabs — Suggested, Favorites, the four kinds, All — and by search, sorted+ * newest, oldest or by name, and drawn as a list instead when the reader+ * wants names rather than pictures. A click opens the STAGE: the page+ * full-size in its sandbox, the source one tab away, every file of the run+ * behind "Files", and the run graph behind "Run"; back, previous and next+ * walk the same list.** Every other run lands here too (the Outputs section folded in on* 2026-08-23): a run that drew no page or picture is an "Output" card with@@ -126,6 +134,9 @@ interface StageTarget {const FILTER_KEY = "jarvis.artifacts.rail-filter";const SORT_KEY = "jarvis.artifacts.sort";+const VIEW_KEY = "jarvis.artifacts.view";+const SIZE_KEY = "jarvis.artifacts.tile-size";+const LABELS_KEY = "jarvis.artifacts.tile-labels";function readStored<T extends string>(key: string, allowed: readonly T[], fallback: T): T {try {@@ -145,7 +156,6 @@ function store(key: string, value: string): void {}}-const FILTERS: readonly RailFilter[] = ["all", "pages", "images", "documents", "outputs"];const SORTS: readonly GallerySort[] = ["newest", "oldest", "name"];/** The stage's timestamp — what tells two same-named artifacts apart. */@@ -179,6 +189,23 @@ function selectionOf(row: RailRow): { slug: string; path: string | null } {: { slug: row.run.slug, path: null };}+/** A choice the reader made once and expects to find again. */+function useStoredChoice<T extends string>(+ key: string,+ allowed: readonly T[],+ fallback: T,+): [T, (next: T) => void] {+ const [value, setValue] = useState<T>(() => readStored(key, allowed, fallback));+ const choose = useCallback(+ (next: T) => {+ setValue(next);+ store(key, next);+ },+ [key],+ );+ return [value, choose];+}+/** A key press that belongs to a text field, not to the gallery's navigation. */function isTypingTarget(target: EventTarget | null): boolean {if (!(target instanceof HTMLElement)) return false;@@ -208,25 +235,25 @@ export function VisualizationView() {);const allRows = useMemo(() => buildRailRows(runs, visuals, building), [runs, visuals, building]);- const counts = useMemo(() => countByFilter(allRows), [allRows]);-- const [filter, setFilterState] = useState<RailFilter>(() => readStored(FILTER_KEY, FILTERS, "all"));- const setFilter = useCallback((next: RailFilter) => {- setFilterState(next);- store(FILTER_KEY, next);- }, []);- const [sort, setSortState] = useState<GallerySort>(() => readStored(SORT_KEY, SORTS, "newest"));- const setSort = useCallback((next: GallerySort) => {- setSortState(next);- store(SORT_KEY, next);- }, []);+ const { favorites, toggle: toggleFavorite } = useArtifactFavorites();+ /* What the two pick tabs go by. The clock is read when the library or the+ * stars change — "new this week" does not need to tick. */+ // eslint-disable-next-line react-hooks/exhaustive-deps+ const picks = useMemo(() => ({ favorites, now: Date.now() }), [favorites, allRows]);+ const counts = useMemo(() => countByFilter(allRows, picks), [allRows, picks]);++ const [filter, setFilter] = useStoredChoice<RailFilter>(FILTER_KEY, RAIL_FILTERS, "suggested");+ const [sort, setSort] = useStoredChoice<GallerySort>(SORT_KEY, SORTS, "newest");+ const [view, setView] = useStoredChoice<GalleryView>(VIEW_KEY, GALLERY_VIEWS, "wall");+ const [size, setSize] = useStoredChoice<TileSize>(SIZE_KEY, TILE_SIZES, "m");+ const [labels, setLabels] = useStoredChoice<TileLabels>(LABELS_KEY, TILE_LABELS, "hover");const [query, setQuery] = useState("");- /* The library as shown: category, then search, then order. The stage's+ /* The library as shown: tab, then search, then order. The stage's* previous / next walk exactly this list. */const rows = useMemo(- () => sortRailRows(searchRailRows(filterRailRows(allRows, filter), query), sort),- [allRows, filter, query, sort],+ () => sortRailRows(searchRailRows(filterRailRows(allRows, filter, picks), query), sort),+ [allRows, filter, picks, query, sort],);const groups = useMemo(() => groupRailRows(rows, sort, Date.now()), [rows, sort]);/* The order the cards appear in on screen — groups pull work in progress@@ -338,18 +365,13 @@ export function VisualizationView() {<section className="flex min-h-0 min-w-0 flex-1 flex-col">{target.building && target.run !== null ? (<>- <StageNav- onBack={back}- position={position}- total={ordered.length}- onStep={step}- />+ <StageBar onBack={back} position={position} total={ordered.length} onStep={step} /><RunCapacityDecision run={target.run} /><BuildingStage run={target.run} /></>) : target.run === null && target.visual === null ? (<>- <StageNav onBack={back} position={-1} total={0} onStep={step} />+ <StageBar onBack={back} position={-1} total={0} onStep={step} /><EmptyStage loading={loading} error={error} /></>) : (@@ -358,14 +380,7 @@ export function VisualizationView() {run={target.run}visual={target.visual}onJumpToRun={(slug) => setSelection({ slug, path: null })}- nav={- <StageNav- onBack={back}- position={position}- total={ordered.length}- onStep={step}- />- }+ nav={{ onBack: back, position, total: ordered.length, onStep: step }}/>)}</section>@@ -374,121 +389,134 @@ export function VisualizationView() {}const nothingAtAll = !loading && allRows.length === 0;+ const searching = query.trim().length > 0;return (<div className="flex h-full min-h-0 flex-col">- <ViewHeader- icon={<Shapes aria-hidden />}- title={t("visualization.title")}- subtitle={t("visualization.subtitle")}- right={- <div className="flex items-center gap-2">- {!nothingAtAll && (- <GalleryControls query={query} onQuery={setQuery} sort={sort} onSort={setSort} />- )}- <Button- variant="outline"- onClick={refetch}- disabled={loading}- title={t("visualization.refresh")}- aria-label={t("visualization.refresh")}- data-testid="visualization-refresh"- >- {loading ? (- <Loader2 className="animate-spin" aria-hidden />- ) : (- <RefreshCw aria-hidden />- )}- </Button>- </div>- }+ <LibraryHeader+ query={query}+ onQuery={setQuery}+ sort={sort}+ onSort={setSort}+ view={view}+ onView={setView}+ size={size}+ onSize={setSize}+ labels={labels}+ onLabels={setLabels}+ loading={loading}+ onRefresh={refetch}+ bare={nothingAtAll}/>-- <div className="flex min-h-0 flex-1">- <GalleryCategoryRail- filter={filter}- counts={counts}- loading={loading && allRows.length === 0}- onChange={setFilter}- />- <section className="flex min-h-0 min-w-0 flex-1 flex-col">- {nothingAtAll ? (- <EmptyStage loading={false} error={error} />- ) : (- <ArtifactGallery- groups={groups}- loading={loading}- searching={query.trim().length > 0}- onOpen={open}- footer={- gallery.skippedRuns > 0 ? (- <p className="pt-8 text-sm text-foreground-faint">- {t("visualization.older_not_scanned").replace(- "{0}",- String(gallery.scannedRuns),- )}- </p>- ) : null- }- />- )}- </section>- </div>+ {nothingAtAll ? (+ <EmptyStage loading={false} error={error} />+ ) : (+ <>+ <LibraryTabs+ filter={filter}+ counts={counts}+ loading={loading && allRows.length === 0}+ onChange={setFilter}+ />+ <ArtifactGallery+ rows={ordered}+ groups={groups}+ view={view}+ size={size}+ labels={labels}+ // The newest artifact leads the pick — not a search result, not+ // an alphabetical list, where "first" means nothing.+ feature={filter === "suggested" && !searching && sort === "newest"}+ favorites={favorites}+ onToggleFavorite={toggleFavorite}+ loading={loading}+ empty={searching ? "search" : filter === "favorites" ? "favorites" : "category"}+ onOpen={open}+ footer={+ gallery.skippedRuns > 0 ? (+ <p className="pt-8 text-sm text-foreground-faint">+ {t("visualization.older_not_scanned").replace("{0}", String(gallery.scannedRuns))}+ </p>+ ) : null+ }+ />+ </>+ )}</div>);}/* ------------------------------------------------------------------------- */-/** Back to the library, and the stage's place in it with previous / next. */-function StageNav({- onBack,- position,- total,- onStep,-}: {+/** What the stage needs to know about its place in the library. */+interface StageNavigation {onBack: () => void;/** Index in the library as shown, or -1 when the open item is not in it. */position: number;total: number;onStep: (delta: number) => void;-}) {+}++const BAR_BUTTON =+ "inline-flex h-9 min-w-9 shrink-0 items-center justify-center gap-1.5 rounded-full px-2.5 text-base text-muted-foreground " ++ "transition-colors hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 " ++ "focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40 [&_svg]:h-[18px] [&_svg]:w-[18px] [&_svg]:shrink-0";++/**+ * The stage's one bar: back to the library on the left, the stage's place in+ * it with previous / next on the right, and whatever the open item brings+ * (its name, its tabs, its actions) in between.+ */+function StageBar({+ onBack,+ position,+ total,+ onStep,+ children,+}: StageNavigation & { children?: ReactNode }) {const t = useT();return (- <div className="flex shrink-0 items-center gap-1 px-4 pt-3">- <Button variant="ghost" size="sm" onClick={onBack} data-testid="visualization-back">- <ArrowLeft className="mr-1.5 h-4 w-4" aria-hidden />- {t("visualization.back")}- </Button>+ <div className="flex shrink-0 flex-wrap items-center gap-x-3 gap-y-2 border-b border-border px-4 py-2.5">+ <button+ type="button"+ onClick={onBack}+ title={t("visualization.back")}+ aria-label={t("visualization.back")}+ data-testid="visualization-back"+ className={BAR_BUTTON}+ >+ <ArrowLeft aria-hidden />+ </button>+ {children ?? <span className="flex-1" />}{position >= 0 && total > 1 && (- <div className="ml-auto flex items-center gap-1">+ <div className="flex shrink-0 items-center"><span className="px-2 text-sm tabular-nums text-foreground-faint">{t("visualization.position").replace("{0}", String(position + 1)).replace("{1}", String(total))}</span>- <Button- variant="ghost"- size="sm"+ <button+ type="button"onClick={() => onStep(-1)}disabled={position === 0}title={t("visualization.previous")}aria-label={t("visualization.previous")}data-testid="visualization-previous"+ className={BAR_BUTTON}>- <ChevronLeft className="h-4 w-4" aria-hidden />- </Button>- <Button- variant="ghost"- size="sm"+ <ChevronLeft aria-hidden />+ </button>+ <button+ type="button"onClick={() => onStep(1)}disabled={position >= total - 1}title={t("visualization.next")}aria-label={t("visualization.next")}data-testid="visualization-next"+ className={BAR_BUTTON}>- <ChevronRight className="h-4 w-4" aria-hidden />- </Button>+ <ChevronRight aria-hidden />+ </button></div>)}</div>@@ -517,8 +545,8 @@ function Stage({run: OutputSummary | null;visual: VisualArtifact | null;onJumpToRun: (slug: string) => void;- /** Back to the library and previous / next, above the toolbar. */- nav: ReactNode;+ /** Back to the library and previous / next — the ends of the stage's bar. */+ nav: StageNavigation;}) {const slug = run?.slug ?? pickedVisual?.slug ?? null;const listing = useArtifactsForOutput(run !== null ? slug : null);@@ -552,8 +580,6 @@ function Stage({return (<>- {nav}- {run && <RunCapacityDecision run={run} />}<ArtifactToolbarrun={run}visual={visual}@@ -561,7 +587,9 @@ function Stage({mode={mode}onMode={setMode}onJumpToRun={onJumpToRun}+ nav={nav}/>+ {run && <RunCapacityDecision run={run} />}<div className="min-h-0 flex-1" data-testid="visualization-stage">{mode === "preview" && visual && <ArtifactStage visual={visual} />}{mode === "preview" && !visual && run && (@@ -598,6 +626,7 @@ function ArtifactToolbar({mode,onMode,onJumpToRun,+ nav,}: {run: OutputSummary | null;visual: VisualArtifact | null;@@ -606,8 +635,13 @@ function ArtifactToolbar({mode: StageMode;onMode: (mode: StageMode) => void;onJumpToRun: (slug: string) => void;+ nav: StageNavigation;}) {const t = useT();+ const { favorites, toggle: toggleFavorite } = useArtifactFavorites();+ // The same key the library's card carries, so a star set here shows there.+ const favoriteKey = visual ? visualId(visual) : run ? `run:${run.slug}` : null;+ const favorite = favoriteKey !== null && favorites.has(favoriteKey);const pushToast = useEventStore((s) => s.pushToast);const capabilities = useOutputsCapabilities();const parsed = parseArtifactUtterance(visual?.utterance ?? run?.utterance);@@ -669,8 +703,8 @@ function ArtifactToolbar({];return (- <div className="flex shrink-0 items-end gap-4 border-b border-border px-6 pt-1">- <div className="min-w-0 flex-1 pb-3">+ <StageBar {...nav}>+ <div className="min-w-0 flex-1 basis-64"><div className="flex min-w-0 items-center gap-3"><pclassName="truncate text-xl font-semibold text-foreground-strong"@@ -681,13 +715,13 @@ function ArtifactToolbar({{run && <RunStatusBadge run={run} />}{run && <RunActions run={run} onJumpToRun={onJumpToRun} />}</div>- <p className="mt-0.5 truncate text-sm text-muted-foreground">{caption}</p>+ <p className="truncate text-sm text-muted-foreground">{caption}</p></div><divrole="tablist"aria-label={t("visualization.stage_tabs")}- className="-mb-px flex shrink-0 items-center gap-5"+ className="flex shrink-0 items-center gap-0.5 rounded-full bg-secondary p-1">{tabs.filter((tab) => tab.show)@@ -700,11 +734,11 @@ function ArtifactToolbar({onClick={() => onMode(id)}data-testid={`visualization-tab-${id}`}className={cn(- "relative inline-flex h-10 items-center gap-1.5 border-b-2 text-base font-medium transition-colors",+ "inline-flex h-8 items-center gap-1.5 rounded-full px-3.5 text-base font-medium transition-colors","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",mode === id- ? "border-accent text-foreground-strong"- : "border-transparent text-muted-foreground hover:text-foreground",+ ? "bg-background text-foreground-strong shadow-sm"+ : "text-muted-foreground hover:text-foreground",)}><Icon className="h-4 w-4" aria-hidden />@@ -713,58 +747,70 @@ function ArtifactToolbar({))}</div>- <div className="flex shrink-0 items-center gap-1 pb-3">+ <div className="flex shrink-0 items-center">+ {favoriteKey !== null && (+ <button+ type="button"+ aria-pressed={favorite}+ onClick={() => toggleFavorite(favoriteKey)}+ title={t(favorite ? "visualization.favorite_remove" : "visualization.favorite_add")}+ aria-label={t(favorite ? "visualization.favorite_remove" : "visualization.favorite_add")}+ data-testid="visualization-favorite"+ className={BAR_BUTTON}+ >+ <Star className={cn(favorite && "fill-current text-warning")} aria-hidden />+ </button>+ )}{mode === "run" && slug && (- <Button- variant="ghost"- size="sm"+ <button+ type="button"onClick={() => void openExternalUrl(`${window.location.origin}${missionMapUrl(slug)}`)}title={t("visualization.open_map_page_hint")}data-testid="visualization-open-map"+ className={BAR_BUTTON}>- <Workflow className="mr-1.5 h-3.5 w-3.5" aria-hidden />+ <Workflow aria-hidden />{t("visualization.open_map_page")}- </Button>+ </button>)}{externalUrl && (- <Button- variant="ghost"- size="sm"+ <button+ type="button"onClick={() => void openExternalUrl(`${window.location.origin}${externalUrl}`)}title={t("visualization.open_external_hint")}+ aria-label={t("visualization.open_external")}data-testid="visualization-open-external"+ className={BAR_BUTTON}>- <ExternalLink className="mr-1.5 h-3.5 w-3.5" aria-hidden />- {t("visualization.open_external")}- </Button>+ <ExternalLink aria-hidden />+ </button>)}{file && (- <Button variant="ghost" size="sm" asChild>- <a- href={artifactDownloadUrl(file.slug, file.path)}- download- title={t("visualization.download")}- aria-label={t("visualization.download")}- >- <Download className="h-3.5 w-3.5" aria-hidden />- </a>- </Button>+ <a+ href={artifactDownloadUrl(file.slug, file.path)}+ download+ title={t("visualization.download")}+ aria-label={t("visualization.download")}+ className={BAR_BUTTON}+ >+ <Download aria-hidden />+ </a>)}{/* Desktop only: a headless host has no file manager to open, so thebutton is absent rather than dead. */}{file && capabilities.data?.native_file_actions && (- <Button- variant="ghost"- size="sm"+ <button+ type="button"onClick={() => void onReveal()}title={t("visualization.reveal")}aria-label={t("visualization.reveal")}+ className={BAR_BUTTON}>- <FolderOpen className="h-3.5 w-3.5" aria-hidden />- </Button>+ <FolderOpen aria-hidden />+ </button>)}</div>- </div>+ </StageBar>);}@@ -776,9 +822,10 @@ function ArtifactToolbar({* A PAGE is framed from `/page` — served with scripts allowed and every* network path shut — inside `sandbox="allow-scripts"` WITHOUT* `allow-same-origin`: its JavaScript runs in an opaque origin that cannot- * reach the app's cookies, storage or API (the Claude-artifact model). Raster- * and vector go through `<img>`, which executes nothing. A PDF renders in the- * browser's own viewer inside an empty sandbox.+ * reach the app's cookies, storage or API. Raster and vector go through+ * `<img>`, which executes nothing. A PDF renders in the browser's own viewer;+ * that viewer is a plugin and plugins never load inside a sandboxed frame, so+ * its frame is not sandboxed — the bytes are same-origin and inert.*/function ArtifactStage({ visual }: { visual: VisualArtifact }) {const t = useT();@@ -803,13 +850,15 @@ function ArtifactStage({ visual }: { visual: VisualArtifact }) {if (visual.kind === "image" || visual.kind === "vector") {return (- <div className="flex h-full items-center justify-center overflow-auto p-6">+ <div className="flex h-full items-center justify-center overflow-auto bg-sidebar p-8"><imgsrc={visual.url}alt={visual.title}data-testid="visualization-image"onError={() => setFailed(true)}- className="max-h-full max-w-full rounded-md border border-border bg-background/40 object-contain"+ // White behind the picture in both themes: a drawing made with dark+ // strokes on a transparent ground would vanish into a dark stage.+ className="max-h-full max-w-full rounded-xl border border-border bg-white object-contain shadow-float"/></div>);@@ -838,23 +887,14 @@ function ArtifactStage({ visual }: { visual: VisualArtifact }) {}return (- <div className="flex h-full flex-col">- <iframe- key={id}- src={visual.url}- title={visual.title}- data-testid="visualization-frame"- onError={() => setFailed(true)}- // Empty sandbox: the browser's own PDF viewer is not the document's- // script context, so the file still renders.- sandbox=""- className="min-h-0 w-full flex-1 border-0 bg-white"- />- <p className="flex shrink-0 items-center gap-1.5 border-t border-border px-4 py-1.5 text-sm text-muted-foreground">- <ShieldCheck className="h-3 w-3 shrink-0" aria-hidden />- {t("visualization.sandbox_note")}- </p>- </div>+ <iframe+ key={id}+ src={visual.url}+ title={visual.title}+ data-testid="visualization-frame"+ onError={() => setFailed(true)}+ className="h-full w-full border-0 bg-white"+ />);}diff --git a/jarvis/ui/web/outputs_routes.py b/jarvis/ui/web/outputs_routes.pyindex 2bf2ffa629..bc5fca8862 100644--- a/jarvis/ui/web/outputs_routes.py+++ b/jarvis/ui/web/outputs_routes.py@@ -15,6 +15,7 @@ even when the mission row is gone (DB pruned, recovery cleanup).from __future__ import annotationsimport asyncio+import htmlimport jsonimport loggingimport mimetypes@@ -831,6 +832,11 @@ async def get_output_graph(slug: str, request: Request) -> HTMLResponse:# short preview so the UI sidebar doesn't have to fetch each file._ARTIFACT_PREVIEW_BYTES: int = 4096_ARTIFACT_MAX_LISTING: int = 200+# A page states its ``<title>`` in its head; this much of the file is read to+# find it, whatever the page weighs.+_HTML_TITLE_HEAD_BYTES: int = 16 * 1024+_HTML_TITLE_RE: Final = re.compile(r"<title[^>]*>(.*?)</title>", re.IGNORECASE | re.DOTALL)+_HTML_TITLE_MAX_CHARS: int = 200# Cap the /view render path so a huge artifact can't block the event loop on the# synchronous read or spike memory while rendering. Larger files use /download.@@ -898,6 +904,26 @@ def _resolve_artifact_target(request: Request, slug: str, path: str) -> Path:return target+def _html_title(path: Path) -> str | None:+ """Return an HTML deliverable's own ``<title>``, or None.++ The Artifacts library names a page by its title. The listing's text+ preview only covers small files, and a real report or dashboard is far+ larger than that, so the head of the file is read here regardless of its+ size. Entities are unescaped; an empty or missing title is None.+ """+ try:+ with path.open("rb") as handle:+ head = handle.read(_HTML_TITLE_HEAD_BYTES)+ except OSError: # an unreadable page is simply listed under its filename+ return None+ match = _HTML_TITLE_RE.search(head.decode("utf-8", errors="replace"))+ if match is None:+ return None+ title = " ".join(html.unescape(match.group(1)).split())+ return title[:_HTML_TITLE_MAX_CHARS] or None++def _is_text_filename(name: str) -> bool:"""Heuristic — file extensions whose contents are safe to inline-preview."""lower = name.lower()@@ -957,10 +983,14 @@ async def list_output_artifacts(slug: str, request: Request) -> dict[str, Any]:"files": [{"path": "tasks/019e3288/artifacts/files/HelloBot.html","size": 1237, "mtime": 1778963665.0, "is_text": true,- "preview": "<html>...\\n..."},+ "preview": "<html>...\\n...",+ "title": "Hello Bot"},...]}++ ``title`` is an HTML file's own ``<title>`` (None for every other file, and+ for a page that states none)."""target = _resolve_output_dir(request, slug)@@ -991,6 +1021,9 @@ async def list_output_artifacts(slug: str, request: Request) -> dict[str, Any]:"mtime": stat.st_mtime,"is_text": _is_text_filename(child.name),"preview": None,+ "title": (+ _html_title(child) if child.suffix.lower() in (".html", ".htm") else None+ ),}if entry["is_text"] and stat.st_size <= _ARTIFACT_PREVIEW_BYTES * 4:try:diff --git a/tests/unit/ui/web/test_outputs_routes.py b/tests/unit/ui/web/test_outputs_routes.pyindex a1e7ad4fb6..0402901970 100644--- a/tests/unit/ui/web/test_outputs_routes.py+++ b/tests/unit/ui/web/test_outputs_routes.py@@ -1168,6 +1168,34 @@ async def test_list_artifacts_lists_nested_deliverables(app: FastAPI, tmp_path:assert "tasks/019e0000/artifacts/files/assets/logo.svg" in paths+async def test_list_artifacts_names_a_page_by_its_title(app: FastAPI, tmp_path: Path) -> None:+ """An HTML deliverable carries its own ``<title>`` in the listing, however+ large the page is — the text preview stops at small files, and a real+ report is not one."""+ d = _make_mission_dir(tmp_path, "019e3288abcd")+ files = d / "tasks" / "019e0000" / "artifacts" / "files"+ padding = "<p>" + "x" * 40_000 + "</p>"+ _seed(+ files / "report.html",+ "<!doctype html><html><head><title>\n Sales & Returns\n 2026 </title></head>"+ f"<body>{padding}</body></html>",+ )+ _seed(files / "untitled.html", "<html><body>no title here</body></html>")+ _seed(files / "blank.html", "<html><head><title> </title></head></html>")+ _seed(files / "notes.md", "<title>Not a page</title>")+ with TestClient(app) as client:+ r = client.get(f"/api/outputs/{d.name}/artifacts")+ assert r.status_code == 200+ by_name = {f["path"].rsplit("/", 1)[-1]: f for f in r.json()["files"]}+ assert by_name["report.html"]["title"] == "Sales & Returns 2026"+ # Too large for a preview, and still named.+ assert by_name["report.html"]["preview"] is None+ assert by_name["untitled.html"]["title"] is None+ assert by_name["blank.html"]["title"] is None+ assert by_name["notes.md"]["title"] is None++@pytest.mark.asyncioasync def test_raw_serves_deliverable(app: FastAPI, tmp_path: Path) -> None:"""The raw-file endpoint returns the contents of a genuine deliverable."""