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): open the section on a gallery with live previews
rubenluetke10-beep8e68a54e845f
diff --git a/jarvis/ui/web/frontend/src/components/visualization/ArtifactGallery.tsx b/jarvis/ui/web/frontend/src/components/visualization/ArtifactGallery.tsxnew file mode 100644index 0000000000..69d3981056--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/visualization/ArtifactGallery.tsx@@ -0,0 +1,533 @@+import { useEffect, useRef, useState, type DragEvent, type ReactNode, type RefObject } from "react";+import {+ FileImage,+ FileText,+ Files,+ Globe,+ LayoutGrid,+ Loader2,+ PenTool,+ Search,+ Workflow,+} 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";+import { endMissionDrag, startMissionDrag } from "@/lib/missionDnd";+import type { OutputStatus } from "@/hooks/useOutputs";+import { artifactPageUrl, type VisualArtifact, type VisualKind } from "@/hooks/useVisualArtifacts";+import {+ RAIL_FILTERS,+ relativeWhen,+ rowRequest,+ rowTitle,+ rowWhen,+ type GalleryGroup,+ type GallerySort,+ type RailFilter,+ type RailRow,+} from "@/components/visualization/galleryModel";++/**+ * The Artifacts library — every artifact as a card with the artifact itself+ * drawn on it, the way a gallery of finished work should look.+ *+ * 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).+ */++/** What a card's status dot means — the run vocabulary, one language. */+const STATUS_DOT: Record<OutputStatus, string> = {+ success: "bg-success",+ error: "bg-destructive",+ running: "bg-success animate-pulse",+ cancelled: "bg-warning",+ unknown: "bg-muted-foreground",+};++const KIND_ICON: Record<VisualKind, typeof Globe> = {+ page: Globe,+ image: FileImage,+ vector: PenTool,+ document: FileText,+};++const FILTER_ICON: Record<RailFilter, typeof Globe> = {+ all: LayoutGrid,+ pages: Globe,+ images: FileImage,+ documents: FileText,+ outputs: Workflow,+};++/** 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;++/* ------------------------------------------------------------------------- */++/** The library's left rail: the categories, each with its count. */+export function GalleryCategoryRail({+ filter,+ counts,+ loading,+ onChange,+}: {+ filter: RailFilter;+ counts: Record<RailFilter, number>;+ /** No answer yet — counts are left out rather than shown as zeros. */+ loading: boolean;+ onChange: (next: RailFilter) => void;+}) {+ const t = useT();+ return (+ <nav+ aria-label={t("visualization.rail_filter")}+ className="flex w-56 shrink-0 flex-col gap-0.5 border-r border-border bg-sidebar p-3"+ 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+ key={id}+ type="button"+ aria-pressed={active}+ 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",+ "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",+ )}+ >+ <Icon className="h-4 w-4 shrink-0" aria-hidden />+ <span className="min-w-0 flex-1 truncate">{t(`visualization.filter_${id}`)}</span>+ {!loading && (+ <span className="text-sm tabular-nums text-foreground-faint">{counts[id]}</span>+ )}+ </button>+ );+ })}+ </nav>+ );+}++/** 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. */+export function ArtifactGallery({+ groups,+ loading,+ searching,+ footer,+ onOpen,+}: {+ groups: GalleryGroup[];+ loading: boolean;+ /** A search is narrowing the library — an empty result is "no match", not "nothing". */+ searching: boolean;+ footer?: ReactNode;+ onOpen: (row: RailRow) => void;+}) {+ const t = useT();+ const empty = groups.every((group) => group.rows.length === 0);++ 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="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",+ )}+ />+ </div>+ ) : (+ 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} />+ ))}+ </CardGrid>+ </section>+ ))+ )}+ {footer}+ </div>+ </ScrollArea>+ );+}++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 }: { row: RailRow; onOpen: (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;+ // 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),+ onDragEnd: endMissionDrag,+ }+ : {};++ return (+ <button+ type="button"+ onClick={() => onOpen(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>+ );+}++/* ------------------------------------------------------------------------- */++/** 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+ />+ );+}++/**+ * 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;+}++/** 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,+}: {+ src: string;+ title: string;+ virtualWidth: number;+ sandbox: string;+ white?: boolean;+}) {+ 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;++ 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>+ );+}++function ImageCover({ visual }: { visual: VisualArtifact }) {+ const [failed, setFailed] = useState(false);+ if (failed) return <IconCover icon={<FileImage className="h-8 w-8" aria-hidden />} />;+ 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",+ )}+ />+ );+}++function IconCover({ icon }: { icon: ReactNode }) {+ return (+ <div className="absolute inset-0 flex items-center justify-center text-foreground-faint">{icon}</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 }) {+ 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>+ );+}++/** A page being written: a page-shaped placeholder that says so. */+function BuildingCover() {+ const t = useT();+ 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>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/visualization/galleryModel.test.ts b/jarvis/ui/web/frontend/src/components/visualization/galleryModel.test.tsnew file mode 100644index 0000000000..2d3d7ca520--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/visualization/galleryModel.test.ts@@ -0,0 +1,91 @@+/**+ * The gallery's ordering rules — categories, search, sort and date headings —+ * pinned without rendering a single card.+ */+import { describe, expect, it } from "vitest";++import type { OutputSummary } from "@/hooks/useOutputs";+import type { VisualArtifact, VisualKind } from "@/hooks/useVisualArtifacts";+import {+ buildRailRows,+ countByFilter,+ dateGroupOf,+ filterRailRows,+ groupRailRows,+ searchRailRows,+ sortRailRows,+} from "@/components/visualization/galleryModel";++const NOW = new Date(2026, 9, 1, 15, 0, 0).getTime();+const HOUR = 3600;+const nowS = NOW / 1000;++function visual(slug: string, title: string, kind: VisualKind, mtime: number): VisualArtifact {+ return {+ slug,+ path: `files/${title}`,+ name: title,+ title,+ kind,+ size: 1,+ mtime,+ url: `/x/${slug}`,+ status: "success",+ utterance: `Make ${title}`,+ };+}++function run(slug: string, over: Partial<OutputSummary> = {}): OutputSummary {+ return { slug, utterance: `Task ${slug}`, status: "success", completed_at: nowS - HOUR, ...over };+}++const VISUALS = [+ visual("a", "Sales map", "page", nowS - 2 * HOUR),+ visual("b", "Logo", "vector", nowS - 30 * HOUR),+ visual("c", "Report", "document", nowS - 40 * 24 * HOUR),+];+const RUNS = [run("a"), run("b"), run("c"), run("d", { summary: "Refactored the parser" })];++describe("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(filterRailRows(rows, "images").map((r) => r.key)).toEqual(["b::files/Logo"]);+ });++ it("searches titles, requests and summaries with every word", () => {+ const rows = buildRailRows(RUNS, VISUALS, []);+ expect(searchRailRows(rows, "sales MAP")).toHaveLength(1);+ expect(searchRailRows(rows, "parser")).toHaveLength(1);+ expect(searchRailRows(rows, "sales parser")).toHaveLength(0);+ });++ it("sorts by name and keeps work in progress first", () => {+ const building = run("e", { status: "running", utterance: "Artifact: Zebra board\nDraw it" });+ const rows = buildRailRows([...RUNS, building], VISUALS, [building]);+ const titles = sortRailRows(rows, "name").map((r) =>+ r.kind === "visual" ? r.visual.title : r.run.slug,+ );+ expect(titles[0]).toBe("e");+ expect(titles.slice(1, 4)).toEqual(["Logo", "Report", "Sales map"]);+ });++ it("groups by day, newest first, with work in progress on top", () => {+ const building = run("e", { status: "running", utterance: "Artifact: Board\nDraw it" });+ const rows = sortRailRows(buildRailRows([...RUNS, building], VISUALS, [building]), "newest");+ const groups = groupRailRows(rows, "newest", NOW);+ expect(groups.map((g) => g.id)).toEqual(["active", "today", "yesterday", "earlier"]);+ expect(groupRailRows(sortRailRows(rows, "name"), "name", NOW).map((g) => g.id)).toEqual([+ "active",+ "all",+ ]);+ });++ it("places moments under the right heading", () => {+ expect(dateGroupOf(nowS - 60, NOW)).toBe("today");+ expect(dateGroupOf(nowS - 24 * HOUR, NOW)).toBe("yesterday");+ expect(dateGroupOf(nowS - 4 * 24 * HOUR, NOW)).toBe("week");+ expect(dateGroupOf(nowS - 20 * 24 * HOUR, NOW)).toBe("month");+ expect(dateGroupOf(nowS - 90 * 24 * HOUR, NOW)).toBe("earlier");+ });+});diff --git a/jarvis/ui/web/frontend/src/components/visualization/galleryModel.ts b/jarvis/ui/web/frontend/src/components/visualization/galleryModel.tsnew file mode 100644index 0000000000..92a6bd3993--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/visualization/galleryModel.ts@@ -0,0 +1,255 @@+/**+ * The pure model behind the Artifacts gallery — which cards exist, which a+ * category or a search lets through, in what order, under which date heading.+ *+ * No React and no fetching: the view hands in the runs and visuals it read,+ * this module turns them into cards. Kept separate so the ordering rules are+ * testable without rendering a single iframe.+ */+import type { OutputSummary } from "@/hooks/useOutputs";+import { cleanRequest, requestHeadline } from "@/lib/runRequest";+import { visualId, type VisualArtifact } from "@/hooks/useVisualArtifacts";++/** One card — a build in progress, an artifact, or a run without one. */+export type RailRow =+ | { kind: "build"; run: OutputSummary; key: string }+ | { 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";++export const RAIL_FILTERS: readonly RailFilter[] = [+ "all",+ "pages",+ "images",+ "documents",+ "outputs",+];++/** How the gallery orders its cards. */+export type GallerySort = "newest" | "oldest" | "name";++/** The date headings the gallery groups by when it sorts by time. */+export type GalleryGroupId = "active" | "today" | "yesterday" | "week" | "month" | "earlier" | "all";++export interface GalleryGroup {+ id: GalleryGroupId;+ rows: RailRow[];+}++/**+ * A `create_artifact` mission's prompt leads with `Artifact: <title>` and the+ * user's request right after (jarvis/artifacts/brief.py). The run list+ * already strips the quality lead, so the run's `utterance` starts with that+ * line — which is how a running build is recognised and labelled here.+ */+export function parseArtifactUtterance(+ utterance: string | undefined,+): { title: string; request: string } | null {+ const text = (utterance ?? "").trim();+ const match = /^Artifact:[ \t]*([^\n]+)/.exec(text);+ if (!match) return null;+ const rest = text.slice(match[0].length).trim();+ const request = rest.split(/\n\s*\n/)[0]?.trim() ?? "";+ return { title: match[1].trim(), request };+}++/** What a run is called when it has no page title of its own. */+export function runTitle(run: OutputSummary): string {+ return (+ parseArtifactUtterance(run.utterance)?.title || requestHeadline(run.utterance ?? "") || run.slug+ );+}++/** The run's moment for ordering — when it ended, else when it began. */+export function runWhen(run: OutputSummary): number {+ return run.completed_at ?? run.started_at ?? 0;+}++/** A card's moment, in epoch seconds. */+export function rowWhen(row: RailRow): number {+ return row.kind === "visual" ? row.visual.mtime : runWhen(row.run);+}++/** A card's title — the page's own `<title>`, the brief's title, or the request. */+export function rowTitle(row: RailRow): string {+ if (row.kind === "visual") return row.visual.title;+ return runTitle(row.run);+}++/** The user's words behind a card, cleaned of the brief's scaffolding. */+export function rowRequest(row: RailRow): string {+ const utterance = row.kind === "visual" ? row.visual.utterance : row.run.utterance;+ return parseArtifactUtterance(utterance)?.request || cleanRequest(utterance) || "";+}++/** Still being made — a build, or a run (or a run's page) that is running. */+export function isActiveRow(row: RailRow): boolean {+ if (row.kind === "build") return true;+ if (row.kind === "visual") return row.visual.status === "running";+ return row.run.status === "running";+}++/** The category a card belongs to (besides "all"). */+export function rowCategory(row: RailRow): Exclude<RailFilter, "all"> {+ if (row.kind === "build") return "pages";+ if (row.kind === "run") return "outputs";+ switch (row.visual.kind) {+ case "page":+ return "pages";+ case "document":+ return "documents";+ default:+ return "images";+ }+}++/**+ * The cards, in their natural order: builds in progress, then running runs,+ * then every artifact and every artifact-less run newest first. A run with at+ * least one artifact is reached through its artifact cards (its other files+ * sit behind the stage's Files tab), so it gets no card of its own.+ */+export function buildRailRows(+ runs: OutputSummary[],+ visuals: VisualArtifact[],+ building: OutputSummary[],+): RailRow[] {+ const bySlug = new Map(runs.map((run) => [run.slug, run]));+ const visualSlugs = new Set(visuals.map((v) => v.slug));+ const buildSlugs = new Set(building.map((r) => r.slug));++ const rest: Array<{ row: RailRow; running: boolean; when: number }> = [];+ for (const visual of visuals) {+ rest.push({+ row: { kind: "visual", run: bySlug.get(visual.slug) ?? null, visual, key: visualId(visual) },+ running: visual.status === "running",+ when: visual.mtime,+ });+ }+ for (const run of runs) {+ if (visualSlugs.has(run.slug) || buildSlugs.has(run.slug)) continue;+ rest.push({+ row: { kind: "run", run, key: `run:${run.slug}` },+ running: run.status === "running",+ when: runWhen(run),+ });+ }+ rest.sort((a, b) => Number(b.running) - Number(a.running) || b.when - a.when);++ return [+ ...building.map((run): RailRow => ({ kind: "build", run, key: `build:${run.slug}` })),+ ...rest.map((entry) => entry.row),+ ];+}++/** The cards a category lets through. */+export function filterRailRows(rows: RailRow[], filter: RailFilter): RailRow[] {+ if (filter === "all") return rows;+ return rows.filter((row) => rowCategory(row) === filter);+}++/** How many cards each category holds. */+export function countByFilter(rows: RailRow[]): Record<RailFilter, number> {+ const counts: Record<RailFilter, number> = {+ all: rows.length,+ pages: 0,+ images: 0,+ documents: 0,+ outputs: 0,+ };+ for (const row of rows) counts[rowCategory(row)] += 1;+ return counts;+}++/** 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);+ if (words.length === 0) return rows;+ return rows.filter((row) => {+ const haystack = [+ rowTitle(row),+ rowRequest(row),+ row.kind === "visual" ? row.visual.name : "",+ row.run?.summary ?? "",+ row.run?.slug ?? "",+ ]+ .join(" ")+ .toLowerCase();+ return words.every((word) => haystack.includes(word));+ });+}++/** The cards in the chosen order; work in progress always leads. */+export function sortRailRows(rows: RailRow[], sort: GallerySort): RailRow[] {+ const sorted = [...rows];+ sorted.sort((a, b) => {+ const active = Number(isActiveRow(b)) - Number(isActiveRow(a));+ if (active !== 0) return active;+ if (sort === "name") return rowTitle(a).localeCompare(rowTitle(b), undefined, { sensitivity: "base" });+ return sort === "oldest" ? rowWhen(a) - rowWhen(b) : rowWhen(b) - rowWhen(a);+ });+ return sorted;+}++function startOfDay(ms: number): number {+ const day = new Date(ms);+ day.setHours(0, 0, 0, 0);+ return day.getTime();+}++/** Which date heading a moment falls under, seen from `now`. */+export function dateGroupOf(seconds: number, now: number): GalleryGroupId {+ const ms = seconds * 1000;+ const today = startOfDay(now);+ const DAY = 86_400_000;+ if (ms >= today) return "today";+ if (ms >= today - DAY) return "yesterday";+ if (ms >= today - 6 * DAY) return "week";+ if (ms >= today - 29 * DAY) return "month";+ return "earlier";+}++/**+ * Sorted cards cut into headed groups: work in progress on top, then by date+ * when the order is by time. Sorting by name is one flat group — a date+ * heading over an alphabetical list would split it in random places.+ */+export function groupRailRows(rows: RailRow[], sort: GallerySort, now: number): GalleryGroup[] {+ const active = rows.filter(isActiveRow);+ const rest = rows.filter((row) => !isActiveRow(row));+ const groups: GalleryGroup[] = [];+ if (active.length > 0) groups.push({ id: "active", rows: active });+ if (sort === "name") {+ if (rest.length > 0) groups.push({ id: "all", rows: rest });+ return groups;+ }+ const byId = new Map<GalleryGroupId, RailRow[]>();+ for (const row of rest) {+ const id = dateGroupOf(rowWhen(row), now);+ const list = byId.get(id);+ if (list) list.push(row);+ else byId.set(id, [row]);+ }+ // Rows arrive sorted, so the groups appear in the same direction.+ for (const [id, list] of byId) groups.push({ id, rows: list });+ return groups;+}++/** "12 min ago" in the UI language — what tells two same-named cards apart. */+export function relativeWhen(seconds: number, now: number, language: string): string {+ if (!seconds) return "";+ const diff = Math.round(seconds - now / 1000);+ const abs = Math.abs(diff);+ const rtf = new Intl.RelativeTimeFormat(language, { numeric: "auto" });+ if (abs < 60) return rtf.format(0, "second");+ if (abs < 3600) return rtf.format(Math.round(diff / 60), "minute");+ if (abs < 86_400) return rtf.format(Math.round(diff / 3600), "hour");+ if (abs < 7 * 86_400) return rtf.format(Math.round(diff / 86_400), "day");+ return new Date(seconds * 1000).toLocaleDateString(language, {+ month: "short",+ day: "numeric",+ year: abs > 300 * 86_400 ? "numeric" : undefined,+ });+}diff --git a/jarvis/ui/web/frontend/src/hooks/useVisualArtifacts.ts b/jarvis/ui/web/frontend/src/hooks/useVisualArtifacts.tsindex f4064787d0..86a5b55710 100644--- a/jarvis/ui/web/frontend/src/hooks/useVisualArtifacts.ts+++ b/jarvis/ui/web/frontend/src/hooks/useVisualArtifacts.ts@@ -83,13 +83,13 @@ export interface VisualArtifact {}/**- * Newest runs scanned for visuals. See the module docstring for the why. Twenty- * because that is how many runs the Outputs section listed before it folded- * into Artifacts (2026-08-23): the rail shows every run the list returns, but- * only these many are looked inside for pages and pictures up front — an older- * run still shows as a run row and is read when picked.+ * Newest runs scanned for visuals. See the module docstring for the why.+ * Sixty since the section opened on a gallery (2026-10-01): with twenty, a+ * machine with a couple dozen runs showed its one dashboard as a text card+ * because it sat just outside the window. One listing per run is cheap; an+ * older run still shows as a run card and is read when opened.*/-export const DEFAULT_RUN_SCAN_LIMIT = 20;+export const DEFAULT_RUN_SCAN_LIMIT = 60;/*** Encode an artifact path segment by segment.diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 3762ccfe76..4b6c2aed63 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -4528,7 +4528,7 @@},"visualization": {"title": "Artefakte",- "subtitle": "Alles, was deine Durchläufe erzeugt haben, jedes als Seite — Artefakte in voller Größe, jeder andere Output genauso aufbereitet; Quelltext, Dateien und Durchlauf einen Tab entfernt",+ "subtitle": "Alles, was deine Durchläufe erzeugt haben, so gezeigt, wie es aussieht — öffne eins für volle Größe, mit Quelltext, Dateien und Durchlauf einen Tab entfernt","refresh": "Aktualisieren","rail": "Artefakte & Durchläufe","building": "Wird gebaut …",@@ -4543,6 +4543,36 @@"filter_all": "Alle","filter_artifacts": "Artefakte","filter_outputs": "Outputs",+ "nav_library": "Bibliothek",+ "filter_pages": "Seiten",+ "filter_images": "Bilder",+ "filter_documents": "Dokumente",+ "search_placeholder": "Artefakte durchsuchen",+ "sort_label": "Sortieren",+ "sort_newest": "Neueste zuerst",+ "sort_oldest": "Älteste zuerst",+ "sort_name": "Name A–Z",+ "group_active": "In Arbeit",+ "group_today": "Heute",+ "group_yesterday": "Gestern",+ "group_week": "Diese Woche",+ "group_month": "Diesen Monat",+ "group_earlier": "Älter",+ "group_all": "Alle Artefakte",+ "kind_page": "Seite",+ "kind_image": "Bild",+ "kind_vector": "Vektorgrafik",+ "kind_document": "PDF",+ "back": "Alle Artefakte",+ "previous": "Vorheriges",+ "next": "Nächstes",+ "position": "{0} von {1}",+ "no_matches_title": "Nichts gefunden",+ "no_matches_body": "Versuche ein anderes Wort oder schau in eine andere Kategorie.",+ "category_empty_title": "In dieser Kategorie ist noch nichts",+ "category_empty_body": "Bitte um ein Dashboard, ein Diagramm oder einen Bericht – es erscheint dann hier.",+ "files_count": "{0} Dateien",+ "file_one": "1 Datei","output_kind": "Output","preview_answer": "Antwort","preview_deliverables": "Dateien",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex cb2b217208..a6be6f353f 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -4561,7 +4561,7 @@},"visualization": {"title": "Artifacts",- "subtitle": "Everything your runs produced, every one as a page — artifacts full-size, every other output composed the same way; source, files and the run one tab away",+ "subtitle": "Everything your runs produced, drawn as it looks — open one to see it full-size, with its source, files and run one tab away","refresh": "Refresh","rail": "Artifacts & runs","building": "Building…",@@ -4576,6 +4576,36 @@"filter_all": "All","filter_artifacts": "Artifacts","filter_outputs": "Outputs",+ "nav_library": "Library",+ "filter_pages": "Pages",+ "filter_images": "Images",+ "filter_documents": "Documents",+ "search_placeholder": "Search artifacts",+ "sort_label": "Sort",+ "sort_newest": "Newest first",+ "sort_oldest": "Oldest first",+ "sort_name": "Name A–Z",+ "group_active": "In progress",+ "group_today": "Today",+ "group_yesterday": "Yesterday",+ "group_week": "Earlier this week",+ "group_month": "Earlier this month",+ "group_earlier": "Older",+ "group_all": "All artifacts",+ "kind_page": "Page",+ "kind_image": "Image",+ "kind_vector": "Vector graphic",+ "kind_document": "PDF",+ "back": "All artifacts",+ "previous": "Previous",+ "next": "Next",+ "position": "{0} of {1}",+ "no_matches_title": "Nothing matches",+ "no_matches_body": "Try another word, or look in a different category.",+ "category_empty_title": "Nothing in this category yet",+ "category_empty_body": "Ask for a dashboard, a diagram or a report and it appears here.",+ "files_count": "{0} files",+ "file_one": "1 file","output_kind": "Output","preview_answer": "Answer","preview_deliverables": "Files",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 93529f1d13..a3200c57a2 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -4528,7 +4528,7 @@},"visualization": {"title": "Artefactos",- "subtitle": "Todo lo que produjeron tus ejecuciones, cada una como página — artefactos a tamaño completo, cualquier otro resultado compuesto igual; código, archivos y ejecución a una pestaña",+ "subtitle": "Todo lo que produjeron tus ejecuciones, mostrado tal como se ve — abre uno a tamaño completo, con código, archivos y ejecución a una pestaña","refresh": "Actualizar","rail": "Artefactos y ejecuciones","building": "Creando…",@@ -4543,6 +4543,36 @@"filter_all": "Todo","filter_artifacts": "Artefactos","filter_outputs": "Resultados",+ "nav_library": "Biblioteca",+ "filter_pages": "Páginas",+ "filter_images": "Imágenes",+ "filter_documents": "Documentos",+ "search_placeholder": "Buscar artefactos",+ "sort_label": "Ordenar",+ "sort_newest": "Más recientes",+ "sort_oldest": "Más antiguos",+ "sort_name": "Nombre A–Z",+ "group_active": "En curso",+ "group_today": "Hoy",+ "group_yesterday": "Ayer",+ "group_week": "Esta semana",+ "group_month": "Este mes",+ "group_earlier": "Anteriores",+ "group_all": "Todos los artefactos",+ "kind_page": "Página",+ "kind_image": "Imagen",+ "kind_vector": "Gráfico vectorial",+ "kind_document": "PDF",+ "back": "Todos los artefactos",+ "previous": "Anterior",+ "next": "Siguiente",+ "position": "{0} de {1}",+ "no_matches_title": "Sin resultados",+ "no_matches_body": "Prueba con otra palabra o mira en otra categoría.",+ "category_empty_title": "Todavía no hay nada en esta categoría",+ "category_empty_body": "Pide un panel, un diagrama o un informe y aparecerá aquí.",+ "files_count": "{0} archivos",+ "file_one": "1 archivo","output_kind": "Resultado","preview_answer": "Respuesta","preview_deliverables": "Archivos",diff --git a/jarvis/ui/web/frontend/src/views/VisualizationView.runs.test.tsx b/jarvis/ui/web/frontend/src/views/VisualizationView.runs.test.tsxindex 7c7e40dada..9dae22b064 100644--- a/jarvis/ui/web/frontend/src/views/VisualizationView.runs.test.tsx+++ b/jarvis/ui/web/frontend/src/views/VisualizationView.runs.test.tsx@@ -125,6 +125,19 @@ function renderView() {);}+/** The section opens on the library; a click on the first card opens its stage. */+async function renderStaged() {+ const view = renderView();+ // A run's card turns into its artifact's card when the listing lands; a+ // click on the card being replaced is retried on the one that replaced it.+ await waitFor(() => {+ const first = screen.queryAllByTestId(/^visualization-(artifact|run|building)-row$/)[0];+ if (first) fireEvent.click(first);+ expect(screen.getByTestId("visualization-stage")).toBeTruthy();+ });+ return view;+}+function run(over: Partial<OutputSummary>): OutputSummary {return {slug: "20260615T120000__task__abcdef123456",@@ -173,6 +186,8 @@ describe("VisualizationView — runs without an artifact", () => {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.+ fireEvent.click(rows[0]);// The stage opens on Preview — the same four tabs every run gets …const previewTab = await screen.findByTestId("visualization-tab-preview");expect(previewTab.getAttribute("aria-selected")).toBe("true");@@ -194,7 +209,7 @@ describe("VisualizationView — runs without an artifact", () => {expect(screen.getByTestId("run-status-badge").textContent).toContain("success");});- it("narrows the rail to artifacts or outputs and remembers the pick", async () => {+ it("narrows the library by category, searches it, and remembers the category", async () => {window.localStorage.removeItem("jarvis.artifacts.rail-filter");installFetchMock([@@ -218,22 +233,35 @@ describe("VisualizationView — runs without an artifact", () => {const filter = screen.getByTestId("visualization-filter");expect(within(filter).getByTestId("visualization-filter-all").textContent).toContain("2");- fireEvent.click(within(filter).getByTestId("visualization-filter-artifacts"));+ expect(within(filter).getByTestId("visualization-filter-pages").textContent).toContain("1");+ expect(within(filter).getByTestId("visualization-filter-images").textContent).toContain("0");++ fireEvent.click(within(filter).getByTestId("visualization-filter-pages"));await waitFor(() => expect(screen.queryAllByTestId("visualization-run-row")).toHaveLength(0));expect(screen.getAllByTestId("visualization-artifact-row")).toHaveLength(1);- expect(window.localStorage.getItem("jarvis.artifacts.rail-filter")).toBe("artifacts");+ expect(window.localStorage.getItem("jarvis.artifacts.rail-filter")).toBe("pages");fireEvent.click(within(filter).getByTestId("visualization-filter-outputs"));await waitFor(() =>expect(screen.queryAllByTestId("visualization-artifact-row")).toHaveLength(0),);expect(screen.getAllByTestId("visualization-run-row")).toHaveLength(1);- // The stage followed the filter: the output is on stage, not the page.- await screen.findByTestId("output-preview");+ // A category with nothing in it says so instead of showing a blank grid.+ fireEvent.click(within(filter).getByTestId("visualization-filter-images"));+ await screen.findByTestId("visualization-no-matches");fireEvent.click(within(filter).getByTestId("visualization-filter-all"));await waitFor(() => expect(screen.getAllByTestId("visualization-run-row")).toHaveLength(1));expect(screen.getAllByTestId("visualization-artifact-row")).toHaveLength(1);++ // Search narrows across titles and requests.+ fireEvent.change(screen.getByTestId("visualization-search"), { target: { value: "notes" } });+ await waitFor(() =>+ expect(screen.queryAllByTestId("visualization-artifact-row")).toHaveLength(0),+ );+ expect(screen.getAllByTestId("visualization-run-row")).toHaveLength(1);+ fireEvent.change(screen.getByTestId("visualization-search"), { target: { value: "zebra" } });+ await screen.findByTestId("visualization-no-matches");window.localStorage.removeItem("jarvis.artifacts.rail-filter");});@@ -246,7 +274,7 @@ describe("VisualizationView — runs without an artifact", () => {it("shows Continue (and no Restart) for a cancelled run", async () => {installFetchMock([run({ slug: "cancelled-slug", status: "cancelled", mission_id: "m-c" })]);- renderView();+ await renderStaged();await waitFor(() =>expect(screen.getAllByRole("button", { name: "Continue" }).length).toBeGreaterThan(0),);@@ -255,7 +283,7 @@ describe("VisualizationView — runs without an artifact", () => {it("shows Restart (and no Continue) for a failed run", async () => {installFetchMock([run({ slug: "error-slug", status: "error", mission_id: "m-e" })]);- renderView();+ await renderStaged();await waitFor(() =>expect(screen.getAllByRole("button", { name: "Restart" }).length).toBeGreaterThan(0),);@@ -276,7 +304,7 @@ describe("VisualizationView — runs without an artifact", () => {}),]);- renderView();+ await renderStaged();// The output page leads with why the run ended …const outcome = await screen.findByTestId("output-preview-outcome");@@ -304,7 +332,7 @@ describe("VisualizationView — runs without an artifact", () => {}),]);- renderView();+ await renderStaged();const outcome = await screen.findByTestId("output-preview-outcome");expect(within(outcome).getByText("task_error")).toBeDefined();@@ -360,7 +388,7 @@ describe("VisualizationView — runs without an artifact", () => {run({ slug: "run-slug", status: "running", mission_id: "m-r" }),run({ slug: "ok-slug", status: "success", mission_id: "m-ok" }),]);- renderView();+ await renderStaged();await waitFor(() =>expect(screen.getAllByRole("button", { name: "Hold to abort" }).length).toBeGreaterThan(0),);@@ -403,7 +431,7 @@ describe("VisualizationView — the Files tab", () => {},);- renderView();+ await renderStaged();await openFiles();await waitFor(() => expect(screen.getAllByTestId("artifact-path")).toHaveLength(3));@@ -419,7 +447,7 @@ describe("VisualizationView — the Files tab", () => {"artifact-slug": [REPORT],});- renderView();+ await renderStaged();await openFiles();await waitFor(() => expect(screen.getByTestId("artifact-path").textContent).toBe("report.md"));@@ -448,7 +476,7 @@ describe("VisualizationView — the Files tab", () => {);const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);- renderView();+ await renderStaged();await openFiles();await waitFor(() => expect(screen.getByTestId("artifact-path").textContent).toBe("report.md"));@@ -484,7 +512,7 @@ describe("VisualizationView — the Files tab", () => {);const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);- renderView();+ await renderStaged();await openFiles();await waitFor(() => expect(screen.getByTestId("artifact-path").textContent).toBe("report.md"));@@ -523,7 +551,7 @@ describe("VisualizationView — the Files tab", () => {{ rawBySlug: { "html-slug": HTML_SOURCE } },);- renderView();+ await renderStaged();// The page is an artifact: it opens on Preview, the stage's own frame.await screen.findByTestId("visualization-frame");diff --git a/jarvis/ui/web/frontend/src/views/VisualizationView.test.tsx b/jarvis/ui/web/frontend/src/views/VisualizationView.test.tsxindex dfe08c5508..9e56450800 100644--- a/jarvis/ui/web/frontend/src/views/VisualizationView.test.tsx+++ b/jarvis/ui/web/frontend/src/views/VisualizationView.test.tsx@@ -2,8 +2,9 @@* The Artifacts section — every page and picture a run produced, full-size.** Contracts worth pinning:- * - the newest artifact is on stage when the section opens; the rail lists- * every artifact newest-first and labels a page by its own <title>,+ * - 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+ * returns, previous / next walk the library,* - 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,@@ -11,7 +12,7 @@* 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* stage, recognised by the brief's "Artifact:" lead line,- * - `?run=<slug>` pre-selects that run's artifact; a click wins over newest,+ * - `?run=<slug>` opens that run's artifact straight away,* - only files the WebView can draw are offered (`classifyVisual`).*/import { afterEach, describe, expect, it, vi } from "vitest";@@ -184,11 +185,19 @@ describe("parseArtifactUtterance", () => {});describe("VisualizationView", () => {- it("stages the newest artifact full-size, labelled by its page title", async () => {+ it("opens a card full-size on the stage, labelled by its page title", async () => {installFetchMock([DASH_RUN], { mission_dash: [DASH_FILE] });renderView();+ // 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].textContent).toContain("Umsatz-Dashboard");+ expect(rows[0].textContent).toContain("Umsatz pro Monat 2026 als Balken.");+ expect(screen.queryByTestId("visualization-frame")).toBeNull();+ fireEvent.click(rows[0]);+const frame = await screen.findByTestId("visualization-frame");// The artifact-page route: scripts allowed server-side …expect(frame.getAttribute("src")).toContain("/files/tasks/t1/artifacts/files/umsatz-dashboard.html/page");@@ -196,16 +205,15 @@ describe("VisualizationView", () => {// same-origin never.expect(frame.getAttribute("sandbox")).toBe("allow-scripts");expect(screen.getByTestId("visualization-title").textContent).toBe("Umsatz-Dashboard");- // The rail row carries the same title, not the filename.- 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.");// The run graph is a tab away, not on stage.expect(screen.queryByTestId("graph-node-start")).toBeNull();+ // Back returns to the library.+ fireEvent.click(screen.getByTestId("visualization-back"));+ await screen.findAllByTestId("visualization-artifact-row");+ expect(screen.queryByTestId("visualization-frame")).toBeNull();});- it("lists every artifact newest-first and switches on click", async () => {+ it("lists every artifact newest-first and walks them with next / previous", async () => {installFetchMock([{ slug: "run-a", utterance: "Draw the architecture", status: "success" },@@ -224,17 +232,28 @@ describe("VisualizationView", () => {expect.stringContaining("diagram.svg"),expect.stringContaining("old-chart.png"),]);- // Newest on stage first …+ fireEvent.click(rows[0]);expect((await screen.findByTestId("visualization-image")).getAttribute("src")).toContain("diagram.svg",);- // … a click moves to the older one.- fireEvent.click(rows[1]);+ expect(screen.getByTestId("visualization-previous")).toHaveProperty("disabled", true);+ // Next moves to the older one …+ fireEvent.click(screen.getByTestId("visualization-next"));await waitFor(() =>expect(screen.getByTestId("visualization-image").getAttribute("src")).toContain("old-chart.png",),);+ // … and the arrow key walks back.+ fireEvent.keyDown(window, { key: "ArrowLeft" });+ await waitFor(() =>+ expect(screen.getByTestId("visualization-image").getAttribute("src")).toContain(+ "diagram.svg",+ ),+ );+ // Escape returns to the library.+ fireEvent.keyDown(window, { key: "Escape" });+ await screen.findAllByTestId("visualization-artifact-row");});it("shows the source under Code and the run graph under Run", async () => {@@ -254,6 +273,7 @@ describe("VisualizationView", () => {);renderView();+ fireEvent.click(await screen.findByTestId("visualization-artifact-row"));await screen.findByTestId("visualization-frame");fireEvent.click(screen.getByTestId("visualization-tab-code"));@@ -284,13 +304,16 @@ describe("VisualizationView", () => {renderView();+ const cards = await screen.findAllByTestId("visualization-artifact-row");+ expect(cards).toHaveLength(2);+ fireEvent.click(cards[0]);const frame = await screen.findByTestId("visualization-frame");expect(frame.getAttribute("sandbox")).toBe("");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();- fireEvent.click(screen.getAllByTestId("visualization-artifact-row")[1]);+ fireEvent.click(screen.getByTestId("visualization-next"));const image = await screen.findByTestId("visualization-image");expect(image.getAttribute("src")).toContain("cover.png");});@@ -312,10 +335,12 @@ describe("VisualizationView", () => {const building = await screen.findAllByTestId("visualization-building-row");expect(building).toHaveLength(1);expect(building[0].textContent).toContain("Umsatz-Dashboard");- // With nothing picked, the newest build is what the stage shows.+ // Opening the build shows its stage …+ fireEvent.click(building[0]);await screen.findByTestId("visualization-building");- // The finished artifact is still in the rail, one click away.- fireEvent.click(screen.getByTestId("visualization-artifact-row"));+ // … and the finished artifact is back in the library, one click away.+ fireEvent.click(screen.getByTestId("visualization-back"));+ fireEvent.click(await screen.findByTestId("visualization-artifact-row"));await screen.findByTestId("visualization-frame");});diff --git a/jarvis/ui/web/frontend/src/views/VisualizationView.tsx b/jarvis/ui/web/frontend/src/views/VisualizationView.tsxindex 915c7d2326..f96ed39f57 100644--- a/jarvis/ui/web/frontend/src/views/VisualizationView.tsx+++ b/jarvis/ui/web/frontend/src/views/VisualizationView.tsx@@ -1,14 +1,14 @@-import { useCallback, useEffect, useMemo, useState, type DragEvent } from "react";+import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react";import {+ ArrowLeft,+ ChevronLeft,+ ChevronRight,Code2,Download,ExternalLink,Eye,- FileImage,- FileText,Files,FolderOpen,- Globe,Loader2,RefreshCw,Shapes,@@ -18,7 +18,6 @@ import {import { Button } from "@/components/ui/button";import { EmptyState } from "@/components/ui/empty-state";-import { ScrollArea } from "@/components/ui/scroll-area";import { OutputPreview } from "@/components/visualization/OutputPreview";import { RunGraphPanel } from "@/components/visualization/RunGraphPanel";import {@@ -27,15 +26,33 @@ import {RunStatusBadge,deliverableFiles,} from "@/components/visualization/RunPanels";+import {+ ArtifactGallery,+ GalleryCategoryRail,+ GalleryControls,+} from "@/components/visualization/ArtifactGallery";+import {+ buildRailRows,+ countByFilter,+ filterRailRows,+ groupRailRows,+ parseArtifactUtterance,+ runTitle,+ runWhen,+ searchRailRows,+ sortRailRows,+ type GallerySort,+ type RailFilter,+ type RailRow,+} from "@/components/visualization/galleryModel";import { ViewHeader } from "@/views/ChatsView";import { useT } from "@/i18n";import { useThemeValue } from "@/hooks/useTheme";import { cn } from "@/lib/utils";import { artifactKind, isTextKind } from "@/lib/artifactKind";-import { cleanRequest, requestHeadline } from "@/lib/runRequest";+import { cleanRequest } from "@/lib/runRequest";import { useEventStore } from "@/store/events";import { openExternalUrl } from "@/lib/openExternal";-import { endMissionDrag, startMissionDrag } from "@/lib/missionDnd";import {artifactDownloadUrl,artifactOpenUrl,@@ -45,7 +62,6 @@ import {useOutputsCapabilities,useOutputsList,type ArtifactSummary,- type OutputStatus,type OutputSummary,} from "@/hooks/useOutputs";import {@@ -55,76 +71,49 @@ import {useVisualArtifacts,visualId,type VisualArtifact,- type VisualKind,} from "@/hooks/useVisualArtifacts";+export { buildRailRows, filterRailRows, parseArtifactUtterance };+export type { RailFilter };+/**- * The Artifacts section — everything a run produced, with the artifact itself- * on stage.+ * The Artifacts section — everything a run produced, as a library first and+ * a stage second.** 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. It is- * shown the way Claude shows an artifact: the page fills the stage, its own- * scripts run inside a sandbox, the source is one tab away, every file of- * the run is behind "Files", and "how did this come to be" — the n8n-style- * run graph — behind "Run".- *- * Since 2026-08-23 this section is ALSO where every other run lands. The- * Outputs section that used to list them is gone: a run that produced no- * page or picture — a research answer, a refactor, a failed build — shows as- * a run row in the same rail, with its status, its summary or the reason it- * ended, its files, and the controls it always had (hold-to-abort, Continue,- * Restart, the GitHub link). One place for what Jarvis and its agents made,- * not two.+ * 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.*- * Since 2026-08-25 the artifact treatment IS the standard for every run:- * the stage always offers Preview / Code / Files / Run, and a run without a- * page gets its Preview composed from what it left behind (`OutputPreview`- * — the answer and every file rendered in place, in the artifact design- * standard) instead of a bare file list. The rail can be narrowed to- * artifacts (pages and pictures a worker drew) or outputs (every other- * run); "all" is the default.+ * 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+ * its own answer as the cover, and its stage composes a page from what it+ * left behind (`OutputPreview`).** It owns no data: runs come from `/api/outputs`, files from the artifact* listing (`useVisualArtifacts`, `useArtifactsForOutput`), a page's source* from `/raw`. A run that is still building its artifact shows as a- * "building…" row the rail follows until the page lands — the listings of- * running runs poll, nothing else does.+ * "building…" card the gallery follows until the page lands — the listings+ * of running runs poll, nothing else does.** Detachable (`DETACHABLE_VIEWS` in jarvis/ui/desktop_app.py): an artifact is* the thing people put on a second monitor.*/-/** What a row's status dot means — the run vocabulary, one language. */-const RUN_DOT: Record<OutputStatus, string> = {- success: "bg-success",- error: "bg-destructive",- running: "bg-success animate-pulse",- cancelled: "bg-warning",- unknown: "bg-muted-foreground",-};--const KIND_ICON: Record<VisualKind, typeof Globe> = {- page: Globe,- image: FileImage,- vector: FileImage,- document: FileText,-};-type StageMode = "preview" | "code" | "files" | "run";-/** The rail's pick: an artifact (`path`) or a whole run (`null`). */-interface Selection {- slug: string;- path: string | null;-}--/** One rail row — a build in progress, an artifact, or a run without one. */-type RailRow =- | { kind: "build"; run: OutputSummary; key: string }- | { kind: "visual"; run: OutputSummary | null; visual: VisualArtifact; key: string }- | { kind: "run"; run: OutputSummary; key: string };+/**+ * What is open: an artifact (`path`) or a whole run (`null`), "latest" for+ * whatever leads the library (another surface asked for the newest), or+ * nothing — the gallery.+ */+type Selection = { slug: string; path: string | null } | "latest" | null;/** What the stage shows: a run (always), and its artifact when it has one. */interface StageTarget {@@ -134,65 +123,31 @@ interface StageTarget {building: boolean;}-/**- * A `create_artifact` mission's prompt leads with `Artifact: <title>` and the- * user's request right after (jarvis/artifacts/brief.py). The run list- * already strips the quality lead, so the run's `utterance` starts with that- * line — which is how a running build is recognised and labelled here.- */-export function parseArtifactUtterance(- utterance: string | undefined,-): { title: string; request: string } | null {- const text = (utterance ?? "").trim();- const match = /^Artifact:[ \t]*([^\n]+)/.exec(text);- if (!match) return null;- const rest = text.slice(match[0].length).trim();- const request = rest.split(/\n\s*\n/)[0]?.trim() ?? "";- return { title: match[1].trim(), request };-}--/** What a run is called when it has no page title of its own. */-function runTitle(run: OutputSummary): string {- return (- parseArtifactUtterance(run.utterance)?.title || requestHeadline(run.utterance ?? "") || run.slug- );-}--/** The rail's narrowing: everything, the pages and pictures, or the rest. */-export type RailFilter = "all" | "artifacts" | "outputs";--const RAIL_FILTER_KEY = "jarvis.artifacts.rail-filter";+const FILTER_KEY = "jarvis.artifacts.rail-filter";+const SORT_KEY = "jarvis.artifacts.sort";-function readRailFilter(): RailFilter {+function readStored<T extends string>(key: string, allowed: readonly T[], fallback: T): T {try {- const stored = window.localStorage.getItem(RAIL_FILTER_KEY);- if (stored === "artifacts" || stored === "outputs") return stored;+ const stored = window.localStorage.getItem(key);+ if (stored !== null && (allowed as readonly string[]).includes(stored)) return stored as T;} catch {- // Storage can be unavailable (private window, blocked site data) — "all" then.+ // Storage can be unavailable (private window, blocked site data) — the default then.}- return "all";+ return fallback;}-function storeRailFilter(filter: RailFilter): void {+function store(key: string, value: string): void {try {- window.localStorage.setItem(RAIL_FILTER_KEY, filter);+ window.localStorage.setItem(key, value);} catch {- // A remembered filter is a convenience, never a requirement.+ // A remembered category or order is a convenience, never a requirement.}}-/** An artifact row is a page or picture (or one being built); the rest are outputs. */-function isArtifactRow(row: RailRow): boolean {- return row.kind === "visual" || row.kind === "build";-}--/** The rows the filter lets through. */-export function filterRailRows(rows: RailRow[], filter: RailFilter): RailRow[] {- if (filter === "all") return rows;- return rows.filter((row) => (filter === "artifacts" ? isArtifactRow(row) : !isArtifactRow(row)));-}+const FILTERS: readonly RailFilter[] = ["all", "pages", "images", "documents", "outputs"];+const SORTS: readonly GallerySort[] = ["newest", "oldest", "name"];-/** The rail row's timestamp — what tells two same-named artifacts apart. */+/** The stage's timestamp — what tells two same-named artifacts apart. */function formatWhen(seconds: number): string {if (!seconds) return "";return new Date(seconds * 1000).toLocaleString(undefined, {@@ -209,48 +164,29 @@ function formatSize(bytes: number): string {return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;}-/** The run's moment for ordering — when it ended, else when it began. */-function runWhen(run: OutputSummary): number {- return run.completed_at ?? run.started_at ?? 0;+/** The card's key for what the stage shows. */+function stageKey(target: StageTarget): string | null {+ if (target.building && target.run) return `build:${target.run.slug}`;+ if (target.visual) return visualId(target.visual);+ if (target.run) return `run:${target.run.slug}`;+ return null;}-/**- * The rail, in order: builds in progress, then running runs, then every- * artifact and every artifact-less run newest first. A run with at least one- * artifact is reached through its artifact rows (its other files sit behind- * the stage's Files tab), so it gets no row of its own.- */-export function buildRailRows(- runs: OutputSummary[],- visuals: VisualArtifact[],- building: OutputSummary[],-): RailRow[] {- const bySlug = new Map(runs.map((run) => [run.slug, run]));- const visualSlugs = new Set(visuals.map((v) => v.slug));- const buildSlugs = new Set(building.map((r) => r.slug));-- const rest: Array<{ row: RailRow; running: boolean; when: number }> = [];- for (const visual of visuals) {- rest.push({- row: { kind: "visual", run: bySlug.get(visual.slug) ?? null, visual, key: visualId(visual) },- running: visual.status === "running",- when: visual.mtime,- });- }- for (const run of runs) {- if (visualSlugs.has(run.slug) || buildSlugs.has(run.slug)) continue;- rest.push({- row: { kind: "run", run, key: `run:${run.slug}` },- running: run.status === "running",- when: runWhen(run),- });- }- rest.sort((a, b) => Number(b.running) - Number(a.running) || b.when - a.when);+function selectionOf(row: RailRow): { slug: string; path: string | null } {+ return row.kind === "visual"+ ? { slug: row.visual.slug, path: row.visual.path }+ : { slug: row.run.slug, path: null };+}- return [- ...building.map((run): RailRow => ({ kind: "build", run, key: `build:${run.slug}` })),- ...rest.map((entry) => entry.row),- ];+/** 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;+ return (+ target.isContentEditable ||+ target.tagName === "INPUT" ||+ target.tagName === "TEXTAREA" ||+ target.tagName === "SELECT"+ );}export function VisualizationView() {@@ -271,33 +207,38 @@ export function VisualizationView() {);const allRows = useMemo(() => buildRailRows(runs, visuals, building), [runs, visuals, building]);- const [filter, setFilterState] = useState<RailFilter>(readRailFilter);+ const counts = useMemo(() => countByFilter(allRows), [allRows]);++ const [filter, setFilterState] = useState<RailFilter>(() => readStored(FILTER_KEY, FILTERS, "all"));const setFilter = useCallback((next: RailFilter) => {setFilterState(next);- storeRailFilter(next);+ store(FILTER_KEY, next);}, []);- const rows = useMemo(() => filterRailRows(allRows, filter), [allRows, filter]);- const counts = useMemo(- () => ({- all: allRows.length,- artifacts: allRows.filter(isArtifactRow).length,- outputs: allRows.filter((row) => !isArtifactRow(row)).length,- }),- [allRows],- );+ const [sort, setSortState] = useState<GallerySort>(() => readStored(SORT_KEY, SORTS, "newest"));+ const setSort = useCallback((next: GallerySort) => {+ setSortState(next);+ store(SORT_KEY, next);+ }, []);+ const [query, setQuery] = useState("");- /* A `?run=<slug>` in the URL pre-selects that run's newest artifact — what- * makes a detached window or a pasted link open on the page it talks about.- * Read once at mount; clicks own it after. */- const [selection, setSelection] = useState<Selection | null>(() => {+ /* The library as shown: category, 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],+ );+ const groups = useMemo(() => groupRailRows(rows, sort, Date.now()), [rows, sort]);+ /* The order the cards appear in on screen — groups pull work in progress+ * to the top, so this is not always `rows`. */+ const ordered = useMemo(() => groups.flatMap((group) => group.rows), [groups]);++ /* A `?run=<slug>` in the URL opens that run's newest artifact — what makes a+ * detached window or a pasted link open on the page it talks about. Read+ * once at mount; clicks own it after. */+ const [selection, setSelection] = useState<Selection>(() => {const slug = new URLSearchParams(window.location.search).get("run");return slug ? { slug, path: null } : null;});- /* Once the user picked a row, the newest artifact landing must not steal the- * stage — an explicit choice is never fought (the selection stays until the- * next click). A pick of a BUILDING run is the exception it resolves itself:- * its page replaces the spinner when it lands. */- const pick = useCallback((next: Selection) => setSelection(next), []);/** Another surface asked for something to be staged ("show visuals" on the@@ -308,7 +249,7 @@ export function VisualizationView() {useEffect(() => {if (visualStage === null) return;if (visualStage.target === "latest") {- setSelection(null);+ setSelection("latest");return;}const separator = visualStage.target.indexOf("::");@@ -321,65 +262,116 @@ export function VisualizationView() {}, [visualStage]);/*- * What the stage shows. The row the user picked — an artifact, or a run- * (its newest artifact once it has one, the run itself otherwise). While- * nothing was picked, the first rail row: the newest build in progress,- * else the newest thing there is.+ * What the stage shows. The card the user opened — an artifact, or a run+ * (its newest artifact once it has one, the run itself otherwise). For+ * "latest", whatever leads the whole library: the newest build in+ * progress, else the newest thing there is.*/- const target: StageTarget = useMemo(() => {+ const target: StageTarget | null = useMemo(() => {+ if (selection === null) return null;const bySlug = (slug: string) => runs.find((r) => r.slug === slug) ?? null;- const resolveRun = (slug: string): StageTarget | null => {- const run = bySlug(slug);- const visual = visuals.find((v) => v.slug === slug) ?? null;- if (run === null && visual === null) return null;- const isBuilding = run !== null && building.includes(run) && visual === null;- return { run, visual, building: isBuilding };- };- if (selection !== null) {- if (selection.path !== null) {- const visual = visuals.find(- (v) => v.slug === selection.slug && v.path === selection.path,- );- if (visual) return { run: bySlug(visual.slug), visual, building: false };- }- const resolved = resolveRun(selection.slug);- if (resolved) return resolved;+ if (selection === "latest") {+ const first = allRows[0];+ if (!first) return { run: null, visual: null, building: false };+ if (first.kind === "build") return { run: first.run, visual: null, building: true };+ if (first.kind === "visual") return { run: first.run, visual: first.visual, building: false };+ return { run: first.run, visual: null, building: false };}- const first = rows[0];- if (!first) return { run: null, visual: null, building: false };- if (first.kind === "build") return { run: first.run, visual: null, building: true };- if (first.kind === "visual") return { run: first.run, visual: first.visual, building: false };- return { run: first.run, visual: null, building: false };- }, [selection, runs, visuals, building, rows]);+ if (selection.path !== null) {+ const visual = visuals.find((v) => v.slug === selection.slug && v.path === selection.path);+ if (visual) return { run: bySlug(visual.slug), visual, building: false };+ }+ const run = bySlug(selection.slug);+ const visual = visuals.find((v) => v.slug === selection.slug) ?? null;+ if (run === null && visual === null) return { run: null, visual: null, building: false };+ const isBuilding = run !== null && building.includes(run) && visual === null;+ return { run, visual, building: isBuilding };+ }, [selection, runs, visuals, building, allRows]);const refetch = useCallback(() => {void outputs.refetch();gallery.refetch();}, [outputs, gallery]);- /* Narrowing the rail to a group the picked row is not in would leave the- * stage on something the rail no longer lists; the pick is dropped and the- * first visible row takes the stage. Nothing happens while the rail is- * still filling (a pick may simply not have loaded yet). */+ const open = useCallback((row: RailRow) => setSelection(selectionOf(row)), []);+ const back = useCallback(() => setSelection(null), []);++ /* Previous / next: the stage's place in the library as currently shown.+ * Opened from elsewhere (a link, "latest") and not in the current view,+ * the stage simply has no neighbours. */+ const activeKey = target ? stageKey(target) : null;+ const position = activeKey ? ordered.findIndex((row) => row.key === activeKey) : -1;+ const step = useCallback(+ (delta: number) => {+ if (position < 0) return;+ const next = ordered[position + delta];+ if (next) setSelection(selectionOf(next));+ },+ [ordered, position],+ );++ /* Escape goes back to the library, ←/→ walk it — unless a text field has+ * the keys. A framed page keeps its own keys (its events never reach us). */+ const staged = target !== null;useEffect(() => {- if (selection === null || filter === "all" || allRows.length === 0) return;- const visible = rows.some(- (row) =>- (row.kind === "visual" && row.visual.slug === selection.slug) ||- (row.kind !== "visual" && row.run.slug === selection.slug),- );- if (!visible) setSelection(null);- }, [filter, rows, allRows.length, selection]);+ if (!staged) return;+ const onKey = (event: KeyboardEvent) => {+ if (event.defaultPrevented || isTypingTarget(event.target)) return;+ if (event.altKey || event.ctrlKey || event.metaKey) return;+ if (event.key === "Escape") back();+ else if (event.key === "ArrowLeft") step(-1);+ else if (event.key === "ArrowRight") step(1);+ else return;+ event.preventDefault();+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [staged, back, step]);const loading = outputs.isLoading || gallery.isLoading;- const activeKey =- target.building && target.run- ? `build:${target.run.slug}`- : target.visual- ? visualId(target.visual)- : target.run- ? `run:${target.run.slug}`- : null;+ const error = outputs.isError || gallery.isError;++ if (target !== null) {+ return (+ <div className="flex h-full min-h-0 flex-col">+ <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}+ />+ <BuildingStage run={target.run} />+ </>+ ) : target.run === null && target.visual === null ? (+ <>+ <StageNav onBack={back} position={-1} total={0} onStep={step} />+ <EmptyStage loading={loading} error={error} />+ </>+ ) : (+ <Stage+ key={target.run?.slug ?? target.visual?.slug}+ run={target.run}+ visual={target.visual}+ onJumpToRun={(slug) => setSelection({ slug, path: null })}+ nav={+ <StageNav+ onBack={back}+ position={position}+ total={ordered.length}+ onStep={step}+ />+ }+ />+ )}+ </section>+ </div>+ );+ }++ const nothingAtAll = !loading && allRows.length === 0;return (<div className="flex h-full min-h-0 flex-col">@@ -388,63 +380,54 @@ export function VisualizationView() {title={t("visualization.title")}subtitle={t("visualization.subtitle")}right={- <Button- variant="outline"- onClick={refetch}- disabled={loading}- data-testid="visualization-refresh"- >- {loading ? (- <Loader2 className="animate-spin" aria-hidden />- ) : (- <RefreshCw aria-hidden />+ <div className="flex items-center gap-2">+ {!nothingAtAll && (+ <GalleryControls query={query} onQuery={setQuery} sort={sort} onSort={setSort} />)}- {t("visualization.refresh")}- </Button>+ <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>}/><div className="flex min-h-0 flex-1">- {/* Rail — builds in progress first, then every artifact and run, newest first. */}- <aside className="flex w-80 shrink-0 flex-col border-r border-border bg-sidebar">- <div className="flex flex-col gap-2 px-3 pt-1">- <RailFilterControl filter={filter} counts={counts} onChange={setFilter} />- </div>- <ScrollArea className="min-h-0 flex-1">- <ul className="space-y-0.5 p-2" data-testid="visualization-artifacts">- {rows.map((row) => (- <li key={row.key}>- <RailRowButton- row={row}- active={activeKey === row.key}- onPick={pick}- />- </li>- ))}- </ul>- {gallery.skippedRuns > 0 && (- <p className="px-3 pb-3 text-sm text-foreground-faint">- {t("visualization.older_not_scanned").replace(- "{0}",- String(gallery.scannedRuns),- )}- </p>- )}- </ScrollArea>- </aside>-- {/* Stage — the artifact itself, full-size; the run around it. */}+ <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">- {target.building && target.run !== null ? (- <BuildingStage run={target.run} />- ) : target.run === null && target.visual === null ? (- <EmptyStage loading={loading} error={outputs.isError || gallery.isError} />+ {nothingAtAll ? (+ <EmptyStage loading={false} error={error} />) : (- <Stage- key={target.run?.slug ?? target.visual?.slug}- run={target.run}- visual={target.visual}- onJumpToRun={(slug) => pick({ slug, path: null })}+ <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>@@ -455,181 +438,58 @@ export function VisualizationView() {/* ------------------------------------------------------------------------- */-/**- * All · Artifacts · Outputs — one segmented control, the count beside each- * word so an empty group reads as "none" rather than "broken".- */-function RailFilterControl({- filter,- counts,- onChange,+/** Back to the library, and the stage's place in it with previous / next. */+function StageNav({+ onBack,+ position,+ total,+ onStep,}: {- filter: RailFilter;- counts: Record<RailFilter, number>;- onChange: (next: RailFilter) => void;+ 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 t = useT();- const options: Array<{ id: RailFilter; label: string }> = [- { id: "all", label: t("visualization.filter_all") },- { id: "artifacts", label: t("visualization.filter_artifacts") },- { id: "outputs", label: t("visualization.filter_outputs") },- ];return (- // Underline tabs (v4), never pill segments.- <div- role="radiogroup"- aria-label={t("visualization.rail_filter")}- className="flex items-center gap-5 border-b border-border"- data-testid="visualization-filter"- >- {options.map(({ id, label }) => (- <button- key={id}- type="button"- role="radio"- aria-checked={filter === id}- onClick={() => onChange(id)}- data-testid={`visualization-filter-${id}`}- className={cn(- "relative -mb-px inline-flex h-10 items-center gap-1.5 border-b-2 text-base font-medium transition-colors",- "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",- filter === id- ? "border-accent text-foreground-strong"- : "border-transparent text-muted-foreground hover:text-foreground",- )}- >- {label}- <span className="text-sm tabular-nums text-foreground-faint">{counts[id]}</span>- </button>- ))}- </div>- );-}--function RailRowButton({- row,- active,- onPick,-}: {- row: RailRow;- active: boolean;- onPick: (next: Selection) => void;-}) {- const t = useT();- const base = cn(- "flex w-full items-start gap-2.5 rounded-md px-3 py-3 text-left text-sm transition-colors",- "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",- active- ? "bg-secondary text-foreground"- : "text-muted-foreground hover:bg-secondary hover:text-foreground",- );- // Every row can be dragged onto the Jarvis dock — the run is what the dock- // takes, whichever of its artifacts the row happens to show.- const dragRun = row.run;- const dragProps = dragRun- ? {- draggable: true,- onDragStart: (e: DragEvent) => startMissionDrag(e, dragRun),- onDragEnd: endMissionDrag,- }- : {};-- if (row.kind === "build") {- const parsed = parseArtifactUtterance(row.run.utterance);- return (- <button- type="button"- onClick={() => onPick({ slug: row.run.slug, path: null })}- aria-current={active}- data-testid="visualization-building-row"- className={base}- {...dragProps}- >- <Loader2 className="mt-0.5 h-3.5 w-3.5 shrink-0 animate-spin text-primary" aria-hidden />- <span className="min-w-0 flex-1">- <span className="block truncate text-base font-medium text-foreground">- {parsed?.title || t("visualization.building")}+ <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>+ {position >= 0 && total > 1 && (+ <div className="ml-auto flex items-center gap-1">+ <span className="px-2 text-sm tabular-nums text-foreground-faint">+ {t("visualization.position")+ .replace("{0}", String(position + 1))+ .replace("{1}", String(total))}</span>- <span className="block truncate">{t("visualization.building")}</span>- </span>- </button>- );- }-- if (row.kind === "visual") {- const { visual } = row;- const Icon = KIND_ICON[visual.kind];- const parsed = parseArtifactUtterance(visual.utterance);- return (- <button- type="button"- onClick={() => onPick({ slug: visual.slug, path: visual.path })}- aria-current={active}- data-testid="visualization-artifact-row"- data-kind={visual.kind}- className={base}- {...dragProps}- >- <span className="relative mt-0.5 shrink-0">- <Icon className="h-3.5 w-3.5" aria-hidden />- <span- className={cn(- "absolute -right-0.5 -top-0.5 h-1.5 w-1.5 rounded-full",- RUN_DOT[visual.status ?? "unknown"],- )}- aria-hidden- />- </span>- <span className="min-w-0 flex-1">- <span className="block truncate text-base font-medium text-foreground">{visual.title}</span>- <span className="block truncate">- {[- formatWhen(visual.mtime),- parsed?.request || cleanRequest(visual.utterance) || visual.name,- ]- .filter(Boolean)- .join(" · ")}- </span>- </span>- </button>- );- }-- // A run without a page or picture: the answer, the refactor, the failure.- const { run } = row;- const status = run.status ?? "unknown";- const Icon = status === "running" ? Loader2 : (run.artifact_count ?? 0) > 0 ? FileText : Workflow;- return (- <button- type="button"- onClick={() => onPick({ slug: run.slug, path: null })}- aria-current={active}- data-testid="visualization-run-row"- data-status={status}- className={base}- {...dragProps}- >- <span className="relative mt-0.5 shrink-0">- <Icon- className={cn("h-3.5 w-3.5", status === "running" && "animate-spin text-primary")}- aria-hidden- />- {status !== "running" && (- <span- className={cn("absolute -right-0.5 -top-0.5 h-1.5 w-1.5 rounded-full", RUN_DOT[status])}- aria-hidden- />- )}- </span>- <span className="min-w-0 flex-1">- <span className="block truncate text-base font-medium text-foreground">{runTitle(run)}</span>- <span className="block truncate">- {[formatWhen(runWhen(run)), run.summary?.trim() || run.terminal_reason || status]- .filter(Boolean)- .join(" · ")}- </span>- </span>- </button>+ <Button+ variant="ghost"+ size="sm"+ onClick={() => onStep(-1)}+ disabled={position === 0}+ title={t("visualization.previous")}+ aria-label={t("visualization.previous")}+ data-testid="visualization-previous"+ >+ <ChevronLeft className="h-4 w-4" aria-hidden />+ </Button>+ <Button+ variant="ghost"+ size="sm"+ onClick={() => onStep(1)}+ disabled={position >= total - 1}+ title={t("visualization.next")}+ aria-label={t("visualization.next")}+ data-testid="visualization-next"+ >+ <ChevronRight className="h-4 w-4" aria-hidden />+ </Button>+ </div>+ )}+ </div>);}@@ -650,10 +510,13 @@ function Stage({run,visual: pickedVisual,onJumpToRun,+ nav,}: {run: OutputSummary | null;visual: VisualArtifact | null;onJumpToRun: (slug: string) => void;+ /** Back to the library and previous / next, above the toolbar. */+ nav: ReactNode;}) {const slug = run?.slug ?? pickedVisual?.slug ?? null;const listing = useArtifactsForOutput(run !== null ? slug : null);@@ -687,6 +550,7 @@ function Stage({return (<>+ {nav}<ArtifactToolbarrun={run}visual={visual}@@ -802,7 +666,7 @@ function ArtifactToolbar({];return (- <div className="flex shrink-0 items-end gap-4 border-b border-border px-6 pt-4">+ <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"><div className="flex min-w-0 items-center gap-3"><p