Skip to content

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.

feat(artifacts): the output page draws what a run made — HTML runs in its sandbox, html/svg fences render, a script is a card with its source folded

rubenluetke10-beepe89f3a437548
diff --git a/jarvis/ui/web/frontend/src/components/docs/CodeBlock.tsx b/jarvis/ui/web/frontend/src/components/docs/CodeBlock.tsx
index ac0d87428e..752e5e5e72 100644
--- a/jarvis/ui/web/frontend/src/components/docs/CodeBlock.tsx
+++ b/jarvis/ui/web/frontend/src/components/docs/CodeBlock.tsx
@@ -78,9 +78,15 @@ async function loadHighlighter(language: string): Promise<ShikiHighlighterApi> {
interface CodeBlockProps {
language: string;
code: string;
+ /**
+ * Draw the block's own frame — border, language tag, copy button. Off when
+ * the caller frames the code itself (a rendered fence's Source view), so two
+ * header bars never stack.
+ */
+ chrome?: boolean;
}
-export function CodeBlock({ language, code }: CodeBlockProps) {
+export function CodeBlock({ language, code, chrome = true }: CodeBlockProps) {
const t = useT();
const [html, setHtml] = useState<string | null>(null);
const [copied, setCopied] = useState(false);
@@ -136,8 +142,14 @@ export function CodeBlock({ language, code }: CodeBlockProps) {
};
return (
- <div className="not-prose group relative my-4 overflow-hidden rounded-md border border-border bg-muted/40">
+ <div
+ className={cn(
+ "not-prose group relative overflow-hidden",
+ chrome && "my-4 rounded-md border border-border bg-muted/40",
+ )}
+ >
{/* Header-Bar */}
+ {chrome && (
<div className="flex items-center justify-between border-b border-border/40 bg-muted/20 px-3 py-1">
<span className="text-[10px] uppercase tracking-wider text-muted-foreground">
{language || "text"}
@@ -165,6 +177,7 @@ export function CodeBlock({ language, code }: CodeBlockProps) {
</span>
</button>
</div>
+ )}
{/* Body — either Shiki HTML or plain text */}
{html ? (
<div
diff --git a/jarvis/ui/web/frontend/src/components/outputs/ArtifactViewer.tsx b/jarvis/ui/web/frontend/src/components/outputs/ArtifactViewer.tsx
index 681893c207..f70bd18604 100644
--- a/jarvis/ui/web/frontend/src/components/outputs/ArtifactViewer.tsx
+++ b/jarvis/ui/web/frontend/src/components/outputs/ArtifactViewer.tsx
@@ -17,8 +17,6 @@
import { useEffect, useMemo, useState, type ReactNode } from "react";
import { createPortal } from "react-dom";
import { useQuery } from "@tanstack/react-query";
-import ReactMarkdown, { type Components } from "react-markdown";
-import remarkGfm from "remark-gfm";
import {
Check,
ChevronDown,
@@ -42,6 +40,7 @@ import { cn } from "@/lib/utils";
import { useT } from "@/i18n";
import { robustCopy } from "@/lib/clipboard";
import { openExternalUrl } from "@/lib/openExternal";
+import { useThemeValue } from "@/hooks/useTheme";
import {
artifactKind,
artifactLanguage,
@@ -65,6 +64,11 @@ import {
} from "@/hooks/useOutputs";
import { CodeBlock } from "@/components/docs/CodeBlock";
import { OpenWithDialog } from "@/components/OpenWithDialog";
+import { MarkdownProse, resolveSiblingPath } from "@/components/outputs/MarkdownProse";
+
+// Re-exported: the resolver moved to MarkdownProse when the output page
+// started sharing the renderer; callers and tests keep importing it here.
+export { resolveSiblingPath };
/** Above this many characters the source view skips Shiki — highlighting a
* megabyte of text would freeze the UI thread for seconds. */
@@ -85,10 +89,12 @@ export interface ArtifactViewerProps {
slug: string;
files: ArtifactSummary[];
nativeActions: boolean;
+ /** The file to open on first — how "Open in Files" on the output page lands on it. */
+ initialPath?: string | null;
}
-export function ArtifactViewer({ slug, files, nativeActions }: ArtifactViewerProps) {
- const [selectedPath, setSelectedPath] = useState<string | null>(null);
+export function ArtifactViewer({ slug, files, nativeActions, initialPath }: ArtifactViewerProps) {
+ const [selectedPath, setSelectedPath] = useState<string | null>(initialPath ?? null);
const [fullscreen, setFullscreen] = useState(false);
// The selection follows the list: first file by default, and a path that
@@ -599,10 +605,21 @@ function ArtifactBody({
* the backend serves it; an older backend without that route still shows the
* page through the inline download (styles and data-URL images render, scripts
* do not) instead of a blank 404 frame. Either way the frame never gets
- * `allow-same-origin`.
+ * `allow-same-origin`. The page follows the APP's theme, not the OS's, through
+ * the same `?theme=` query the Artifacts stage appends. Drawn full-height in
+ * the Files reader and, through `className`, as a block on the output page.
*/
-function HtmlPage({ slug, path }: { slug: string; path: string }) {
+export function HtmlPage({
+ slug,
+ path,
+ className = "h-full w-full",
+}: {
+ slug: string;
+ path: string;
+ className?: string;
+}) {
const t = useT();
+ const theme = useThemeValue();
const pageUrl = artifactPageUrl(slug, path);
const probe = useQuery<boolean>({
queryKey: ["output-artifact-page-available", slug, path],
@@ -628,19 +645,22 @@ function HtmlPage({ slug, path }: { slug: string; path: string }) {
</div>
);
}
- const src = probe.data ? pageUrl : artifactInlineUrl(slug, path);
+ const src = probe.data ? `${pageUrl}?theme=${theme}` : artifactInlineUrl(slug, path);
return (
<iframe
+ key={`${src}`}
title={deliverableDisplayPath(path)}
src={src}
sandbox="allow-scripts"
referrerPolicy="no-referrer"
- className="h-full w-full border-0 bg-white"
+ data-testid="artifact-html-page"
+ className={cn("border-0 bg-white", className)}
/>
);
}
-function SourceView({ path, text }: { path: string; text: string }) {
+/** Highlighted source for code, plain `<pre>` for text or anything huge. */
+export function SourceView({ path, text }: { path: string; text: string }) {
const language = artifactLanguage(path);
if (text.length > HIGHLIGHT_MAX_CHARS || language === "txt") {
return (
@@ -656,7 +676,8 @@ function SourceView({ path, text }: { path: string; text: string }) {
);
}
-function CsvTable({ text, tab }: { text: string; tab: boolean }) {
+/** A CSV/TSV as a table, capped at `CSV_MAX_ROWS` rows. */
+export function CsvTable({ text, tab }: { text: string; tab: boolean }) {
const t = useT();
const rows = useMemo(() => parseCsv(text, tab ? "\t" : ","), [text, tab]);
if (rows.length === 0) {
@@ -704,25 +725,11 @@ function CsvTable({ text, tab }: { text: string; tab: boolean }) {
// --- Markdown document -----------------------------------------------------
-/** Resolve `href` relative to the directory of `fromPath` inside the archive. */
-export function resolveSiblingPath(fromPath: string, href: string): string | null {
- if (!href || /^[a-z][a-z0-9+.-]*:/i.test(href) || href.startsWith("#") || href.startsWith("/")) {
- return null;
- }
- const clean = href.split(/[?#]/)[0];
- const base = fromPath.split("/").slice(0, -1);
- for (const seg of clean.split("/")) {
- if (seg === "" || seg === ".") continue;
- if (seg === "..") {
- if (base.length === 0) return null;
- base.pop();
- } else {
- base.push(seg);
- }
- }
- return base.join("/");
-}
-
+/**
+ * The reader's document: the shared renderer in a serif reading face with a
+ * measure — a report reads as a report, while everything else in the app
+ * stays in the UI sans.
+ */
function MarkdownDocument({
slug,
path,
@@ -736,110 +743,18 @@ function MarkdownDocument({
text: string;
onSelectSibling: (path: string) => void;
}) {
- const known = useMemo(() => new Set(files.map((f) => f.path)), [files]);
- const components = useMemo<Components>(
- () => ({
- // Fenced blocks render their own complete container; unwrapping the
- // Markdown ``pre`` avoids invalid ``pre > div`` nesting around CodeBlock.
- pre({ children }) {
- return <>{children}</>;
- },
- code({ className, children, ...rest }) {
- const match = /language-(\w+)/.exec(className || "");
- if (!match) {
- return (
- <code className={className} {...rest}>
- {children}
- </code>
- );
- }
- return (
- <CodeBlock language={match[1]} code={String(children).replace(/\n$/, "")} />
- );
- },
- a({ href, children, ...rest }) {
- const sibling = href ? resolveSiblingPath(path, href) : null;
- if (sibling && known.has(sibling)) {
- return (
- <a
- href={`#${sibling}`}
- onClick={(e) => {
- e.preventDefault();
- onSelectSibling(sibling);
- }}
- {...rest}
- >
- {children}
- </a>
- );
- }
- if (href && /^https?:\/\//i.test(href)) {
- return (
- <a
- href={href}
- rel="noopener noreferrer"
- onClick={(e) => {
- e.preventDefault();
- void openExternalUrl(href);
- }}
- {...rest}
- >
- {children}
- </a>
- );
- }
- return (
- <a href={href} {...rest}>
- {children}
- </a>
- );
- },
- img({ src, alt, ...rest }) {
- const sibling = typeof src === "string" ? resolveSiblingPath(path, src) : null;
- const resolved =
- sibling && known.has(sibling) ? artifactInlineUrl(slug, sibling) : src;
- return <img src={resolved} alt={alt ?? ""} loading="lazy" {...rest} />;
- },
- table({ children }) {
- return (
- <div className="not-prose my-5 overflow-x-auto rounded-md border border-border">
- <table className="w-full text-sm [&_td]:px-3 [&_td]:py-1.5 [&_th]:px-3 [&_th]:py-2 [&_th]:text-left [&_th]:font-semibold [&_thead]:bg-muted/40 [&_tr]:border-t [&_tr]:border-border/60 [&_thead_tr]:border-t-0">
- {children}
- </table>
- </div>
- );
- },
- blockquote({ children }) {
- return (
- <blockquote className="border-l-2 border-primary/50 pl-4 not-italic text-muted-foreground">
- {children}
- </blockquote>
- );
- },
- }),
- [known, onSelectSibling, path, slug],
- );
-
return (
- <article
- data-testid="artifact-markdown"
+ <MarkdownProse
+ slug={slug}
+ path={path}
+ files={files}
+ text={text}
+ onSelectSibling={onSelectSibling}
className={cn(
- "prose prose-neutral dark:prose-invert mx-auto max-w-3xl px-8 py-8 [overflow-wrap:anywhere] lg:px-12",
- // A document reads as a document: a serif text face, generous leading,
- // headings that are clearly headings. Everything else in the app stays
- // in the UI sans.
- "font-serif text-[15.5px] leading-7",
- "prose-headings:font-serif prose-headings:font-semibold prose-headings:tracking-tight prose-headings:text-pretty",
+ "mx-auto max-w-3xl px-8 py-8 lg:px-12",
+ "font-serif text-[15.5px] leading-7 prose-headings:font-serif",
"prose-h1:text-3xl prose-h1:leading-tight prose-h2:mt-10 prose-h2:text-2xl prose-h3:text-xl",
- "prose-p:text-pretty prose-li:my-1",
- "prose-a:text-primary prose-a:no-underline hover:prose-a:underline",
- "prose-code:rounded prose-code:bg-muted/60 prose-code:px-1 prose-code:py-0.5 prose-code:font-mono prose-code:text-[0.85em] prose-code:font-normal prose-code:before:hidden prose-code:after:hidden",
- "prose-hr:border-border prose-img:rounded-md",
)}
- >
- <ReactMarkdown remarkPlugins={[remarkGfm]} components={components}>
- {text}
- </ReactMarkdown>
- </article>
+ />
);
}
diff --git a/jarvis/ui/web/frontend/src/components/outputs/MarkdownProse.tsx b/jarvis/ui/web/frontend/src/components/outputs/MarkdownProse.tsx
new file mode 100644
index 0000000000..e1127f2c74
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/outputs/MarkdownProse.tsx
@@ -0,0 +1,193 @@
+/**
+ * A Markdown deliverable rendered as a document — the one renderer both the
+ * Files reader (`ArtifactViewer`) and the output page (`OutputPreview`) draw
+ * with, so a report reads the same wherever it is opened.
+ *
+ * What it adds over plain `react-markdown`: fenced code goes through the
+ * Shiki `CodeBlock`, except an `html` or `svg` fence, which is DRAWN
+ * (`RenderedFence`: a chart the worker wrote as inline SVG is a chart, a
+ * snippet of HTML runs in a sandbox, the markup one click away behind its
+ * Source switch); a link to a sibling file in the same run selects that
+ * file instead of navigating; an external link opens in the user's real
+ * browser through the open-external bridge (the desktop WebView drops a bare
+ * `target="_blank"`); an image next to the document is served from the run
+ * archive. The typography is the caller's — the reader passes its own
+ * classes, the output page the artifact standard's.
+ */
+import { useMemo } from "react";
+import ReactMarkdown, { type Components } from "react-markdown";
+import remarkGfm from "remark-gfm";
+
+import { cn } from "@/lib/utils";
+import { openExternalUrl } from "@/lib/openExternal";
+import { artifactInlineUrl, type ArtifactSummary } from "@/hooks/useOutputs";
+import { CodeBlock } from "@/components/docs/CodeBlock";
+import { RenderedFence } from "@/components/outputs/RenderedFence";
+
+/**
+ * Split a leading YAML front matter block (`---` … `---`) off a document.
+ * A SKILL.md or a note with metadata would otherwise render the block as one
+ * run-on paragraph ("schema_version: "1" name: … description: …"), which
+ * reads as a broken page. The metadata is kept and drawn as a small YAML
+ * block above the body — it is part of the file, just not prose.
+ */
+export function splitFrontMatter(text: string): { meta: string | null; body: string } {
+ const match = /^?---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/.exec(text);
+ if (!match) return { meta: null, body: text };
+ const meta = match[1].trim();
+ return { meta: meta.length > 0 ? meta : null, body: text.slice(match[0].length) };
+}
+
+/** Resolve `href` relative to the directory of `fromPath` inside the archive. */
+export function resolveSiblingPath(fromPath: string, href: string): string | null {
+ if (!href || /^[a-z][a-z0-9+.-]*:/i.test(href) || href.startsWith("#") || href.startsWith("/")) {
+ return null;
+ }
+ const clean = href.split(/[?#]/)[0];
+ const base = fromPath.split("/").slice(0, -1);
+ for (const seg of clean.split("/")) {
+ if (seg === "" || seg === ".") continue;
+ if (seg === "..") {
+ if (base.length === 0) return null;
+ base.pop();
+ } else {
+ base.push(seg);
+ }
+ }
+ return base.join("/");
+}
+
+/**
+ * The typographic base every Markdown document shares: Tailwind's prose in
+ * both themes, links in the accent, inline code on a quiet chip, tables and
+ * images with the app's radius. Callers add the face and the measure.
+ */
+export const PROSE_BASE =
+ "prose prose-neutral dark:prose-invert [overflow-wrap:anywhere] " +
+ "prose-headings:font-semibold prose-headings:tracking-tight prose-headings:text-pretty " +
+ "prose-p:text-pretty prose-li:my-1 " +
+ "prose-a:text-primary prose-a:no-underline hover:prose-a:underline " +
+ "prose-code:rounded prose-code:bg-muted/60 prose-code:px-1 prose-code:py-0.5 prose-code:font-mono prose-code:text-[0.85em] prose-code:font-normal prose-code:before:hidden prose-code:after:hidden " +
+ "prose-hr:border-border prose-img:rounded-md";
+
+export function MarkdownProse({
+ slug,
+ path,
+ files,
+ text,
+ onSelectSibling,
+ className,
+ testId = "artifact-markdown",
+}: {
+ slug: string;
+ /** The document's own archive path — what relative links resolve against. */
+ path: string;
+ /** Every file of the run, so a relative link can be recognised as a sibling. */
+ files: ArtifactSummary[];
+ text: string;
+ /** Called with a sibling's path when the reader clicks a link to it. */
+ onSelectSibling?: (path: string) => void;
+ className?: string;
+ testId?: string;
+}) {
+ const known = useMemo(() => new Set(files.map((f) => f.path)), [files]);
+ const { meta, body } = useMemo(() => splitFrontMatter(text), [text]);
+ const components = useMemo<Components>(
+ () => ({
+ // Fenced blocks render their own complete container; unwrapping the
+ // Markdown ``pre`` avoids invalid ``pre > div`` nesting around CodeBlock.
+ pre({ children }) {
+ return <>{children}</>;
+ },
+ code({ className: codeClass, children, ...rest }) {
+ const match = /language-(\w+)/.exec(codeClass || "");
+ if (!match) {
+ return (
+ <code className={codeClass} {...rest}>
+ {children}
+ </code>
+ );
+ }
+ const language = match[1].toLowerCase();
+ const code = String(children).replace(/\n$/, "");
+ if (language === "html" || language === "svg") {
+ return <RenderedFence language={language} code={code} />;
+ }
+ return <CodeBlock language={language} code={code} />;
+ },
+ a({ href, children, ...rest }) {
+ const sibling = href ? resolveSiblingPath(path, href) : null;
+ if (sibling && known.has(sibling) && onSelectSibling) {
+ return (
+ <a
+ href={`#${sibling}`}
+ onClick={(e) => {
+ e.preventDefault();
+ onSelectSibling(sibling);
+ }}
+ {...rest}
+ >
+ {children}
+ </a>
+ );
+ }
+ if (href && /^https?:\/\//i.test(href)) {
+ return (
+ <a
+ href={href}
+ rel="noopener noreferrer"
+ onClick={(e) => {
+ e.preventDefault();
+ void openExternalUrl(href);
+ }}
+ {...rest}
+ >
+ {children}
+ </a>
+ );
+ }
+ return (
+ <a href={href} {...rest}>
+ {children}
+ </a>
+ );
+ },
+ img({ src, alt, ...rest }) {
+ const sibling = typeof src === "string" ? resolveSiblingPath(path, src) : null;
+ const resolved =
+ sibling && known.has(sibling) ? artifactInlineUrl(slug, sibling) : src;
+ return <img src={resolved} alt={alt ?? ""} loading="lazy" {...rest} />;
+ },
+ table({ children }) {
+ return (
+ <div className="not-prose my-5 overflow-x-auto rounded-md border border-border">
+ <table className="w-full text-sm [&_td]:px-3 [&_td]:py-1.5 [&_th]:px-3 [&_th]:py-2 [&_th]:text-left [&_th]:font-semibold [&_thead]:bg-muted/40 [&_tr]:border-t [&_tr]:border-border/60 [&_thead_tr]:border-t-0">
+ {children}
+ </table>
+ </div>
+ );
+ },
+ blockquote({ children }) {
+ return (
+ <blockquote className="border-l-2 border-primary/50 pl-4 not-italic text-muted-foreground">
+ {children}
+ </blockquote>
+ );
+ },
+ }),
+ [known, onSelectSibling, path, slug],
+ );
+
+ return (
+ <article data-testid={testId} className={cn(PROSE_BASE, className)}>
+ {meta !== null && (
+ <div data-testid="markdown-front-matter">
+ <CodeBlock language="yaml" code={meta} />
+ </div>
+ )}
+ <ReactMarkdown remarkPlugins={[remarkGfm]} components={components}>
+ {body}
+ </ReactMarkdown>
+ </article>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/outputs/RenderedFence.test.tsx b/jarvis/ui/web/frontend/src/components/outputs/RenderedFence.test.tsx
new file mode 100644
index 0000000000..e88c2d2a32
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/outputs/RenderedFence.test.tsx
@@ -0,0 +1,92 @@
+/**
+ * An `html` or `svg` fence in a Markdown deliverable is DRAWN, with its
+ * markup one click away — and the HTML runs in the artifact page's sandbox
+ * model, never in the app's origin.
+ */
+import { afterEach, describe, expect, it } from "vitest";
+import { cleanup, fireEvent, render, screen, within } from "@testing-library/react";
+
+import { MarkdownProse } from "@/components/outputs/MarkdownProse";
+import {
+ INLINE_HTML_CSP,
+ INLINE_HTML_SIZE_MESSAGE,
+ wrapInlineHtml,
+} from "@/components/outputs/RenderedFence";
+
+afterEach(() => cleanup());
+
+const SVG = '<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><rect width="10" height="10"/></svg>';
+
+describe("wrapInlineHtml", () => {
+ it("wraps a fragment in a themed page with the artifact CSP and the size reporter", () => {
+ const doc = wrapInlineHtml("<div>hi</div>", "dark", ":r1:");
+ expect(doc.startsWith("<!doctype html>")).toBe(true);
+ expect(doc).toContain('data-theme="dark"');
+ expect(doc).toContain(`content="${INLINE_HTML_CSP}"`);
+ expect(doc).toContain("<div>hi</div>");
+ expect(doc).toContain(INLINE_HTML_SIZE_MESSAGE);
+ expect(doc).toContain('token:":r1:"');
+ });
+
+ it("stamps a whole page instead of wrapping it", () => {
+ const page = "<html><head><title>t</title></head><body><p>x</p></body></html>";
+ const doc = wrapInlineHtml(page, "light", "a");
+ expect(doc.match(/<html/g)).toHaveLength(1);
+ expect(doc).toContain('<html data-theme="light">');
+ expect(doc).toContain(`<head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy"`);
+ expect(doc).toContain("</script></body>");
+ });
+
+ it("keeps a page's own theme stamp and adds a head when it has none", () => {
+ const doc = wrapInlineHtml('<html data-theme="dark"><body>x</body></html>', "light", "a");
+ expect(doc).toContain('<html data-theme="dark"><head><meta charset="utf-8">');
+ expect(doc).not.toContain('data-theme="light"');
+ });
+});
+
+describe("MarkdownProse fences", () => {
+ it("draws an svg fence as a picture and an html fence in a sandboxed frame", () => {
+ render(
+ <MarkdownProse
+ slug="run-1"
+ path="report.md"
+ files={[]}
+ text={"# Chart\n\n```svg\n" + SVG + "\n```\n\n```html\n<div id=\"card\">hi</div>\n```\n"}
+ />,
+ );
+ const fences = screen.getAllByTestId("rendered-fence");
+ expect(fences.map((f) => f.getAttribute("data-language"))).toEqual(["svg", "html"]);
+
+ const picture = within(fences[0]).getByTestId("inline-svg") as HTMLImageElement;
+ expect(picture.getAttribute("src")).toBe(
+ `data:image/svg+xml;charset=utf-8,${encodeURIComponent(SVG)}`,
+ );
+
+ const frame = within(fences[1]).getByTestId("inline-html-frame") as HTMLIFrameElement;
+ expect(frame.getAttribute("sandbox")).toBe("allow-scripts");
+ expect(frame.getAttribute("srcdoc")).toContain('<div id="card">hi</div>');
+ expect(frame.getAttribute("srcdoc")).toContain("Content-Security-Policy");
+ });
+
+ it("shows the markup behind the Source switch and comes back to Rendered", () => {
+ render(
+ <MarkdownProse slug="run-1" path="r.md" files={[]} text={"```html\n<b>bold</b>\n```\n"} />,
+ );
+ const fence = screen.getByTestId("rendered-fence");
+ expect(fence.getAttribute("data-mode")).toBe("rendered");
+
+ fireEvent.click(within(fence).getByRole("button", { name: "Source" }));
+ expect(fence.getAttribute("data-mode")).toBe("source");
+ expect(within(fence).queryByTestId("inline-html-frame")).toBeNull();
+ expect(within(fence).getByText("<b>bold</b>")).toBeDefined();
+
+ fireEvent.click(within(fence).getByRole("button", { name: "Rendered" }));
+ expect(within(fence).getByTestId("inline-html-frame")).toBeDefined();
+ });
+
+ it("leaves every other fence to the code block", () => {
+ render(<MarkdownProse slug="r" path="r.md" files={[]} text={"```python\nprint(1)\n```\n"} />);
+ expect(screen.queryByTestId("rendered-fence")).toBeNull();
+ expect(screen.getByText("print(1)")).toBeDefined();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/outputs/RenderedFence.tsx b/jarvis/ui/web/frontend/src/components/outputs/RenderedFence.tsx
new file mode 100644
index 0000000000..d065eca791
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/outputs/RenderedFence.tsx
@@ -0,0 +1,224 @@
+/**
+ * A fenced `html` / `svg` block DRAWN, the way the reader expects a picture
+ * to appear, with its source one click away.
+ *
+ * A worker that answers with a chart or a diagram writes it as inline SVG or
+ * a self-contained HTML snippet (the artifact brief tells it to); shown as a
+ * code block, the "picture" is a wall of angle brackets. Here the block
+ * renders by default and a Rendered / Source switch in its header shows the
+ * markup for whoever wants it.
+ *
+ * Safety is the artifact page's model, mirrored for inline markup:
+ * - SVG is drawn through an `<img>` from a data: URL — a browser never runs
+ * script or fetches anything for an SVG-as-image.
+ * - HTML runs in an `<iframe srcdoc>` with `sandbox="allow-scripts"` and NO
+ * `allow-same-origin`, so it lives in an opaque origin that cannot reach the
+ * app's cookies, storage or API; a Content-Security-Policy stamped into the
+ * document (`INLINE_HTML_CSP`, the verbatim twin of `ARTIFACT_PAGE_CSP` in
+ * `jarvis/ui/web/artifact_view.py`) shuts every way out — no network, no
+ * forms, no navigation. The frame grows to its content through a
+ * `postMessage` the injected reporter sends; the parent trusts a message
+ * only from that frame's own window, and only up to a ceiling.
+ */
+import { useEffect, useId, useMemo, useRef, useState } from "react";
+import { Check, Copy } from "lucide-react";
+
+import { cn } from "@/lib/utils";
+import { robustCopy } from "@/lib/clipboard";
+import { useT } from "@/i18n";
+import { useThemeValue, type Theme } from "@/hooks/useTheme";
+import { CodeBlock } from "@/components/docs/CodeBlock";
+
+export type FenceLanguage = "html" | "svg";
+
+/** Twin of `ARTIFACT_PAGE_CSP` (jarvis/ui/web/artifact_view.py) — keep in step. */
+export const INLINE_HTML_CSP =
+ "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; " +
+ "img-src data: blob:; font-src data:; media-src data: blob:; connect-src 'none'; " +
+ "form-action 'none'; frame-src 'none'; base-uri 'none';";
+
+/** The message type the injected reporter posts with the document's height. */
+export const INLINE_HTML_SIZE_MESSAGE = "jarvis-inline-html-size";
+
+const MIN_FRAME_PX = 96;
+const MAX_FRAME_PX = 720;
+
+/** The app's card surface in each palette, for a fragment that brings no page of its own. */
+const FRAGMENT_SKIN: Record<Theme, { bg: string; ink: string }> = {
+ light: { bg: "#ffffff", ink: "#141413" },
+ dark: { bg: "#30302e", ink: "#f5f4ef" },
+};
+
+function headBits(): string {
+ return (
+ '<meta charset="utf-8">' +
+ `<meta http-equiv="Content-Security-Policy" content="${INLINE_HTML_CSP}">`
+ );
+}
+
+function reporterScript(token: string): string {
+ const safe = token.replace(/[^\w:-]/g, "");
+ return (
+ "<script>(function(){var h=document.documentElement;function r(){try{" +
+ `parent.postMessage({type:"${INLINE_HTML_SIZE_MESSAGE}",token:"${safe}",` +
+ 'height:h.scrollHeight},"*")}catch(e){}}' +
+ "try{new ResizeObserver(r).observe(h)}catch(e){}" +
+ 'addEventListener("load",r);r()})();</script>'
+ );
+}
+
+/**
+ * The document the frame loads: the snippet as-is when it is a whole page
+ * (CSP and theme stamp added to its head), otherwise wrapped in a minimal
+ * page on the app's card surface so a bare `<div>` or `<svg>` reads in both
+ * palettes. Exported for the tests.
+ */
+export function wrapInlineHtml(html: string, theme: Theme, token: string): string {
+ const script = reporterScript(token);
+ if (/<html[\s>]/i.test(html)) {
+ let doc = html;
+ if (!/<html[^>]*\sdata-theme=/i.test(doc)) {
+ doc = doc.replace(/<html(\s[^>]*)?>/i, (_m, attrs: string | undefined) =>
+ `<html${attrs ?? ""} data-theme="${theme}">`,
+ );
+ }
+ if (/<head[^>]*>/i.test(doc)) {
+ doc = doc.replace(/<head[^>]*>/i, (m) => `${m}${headBits()}`);
+ } else {
+ doc = doc.replace(/<html[^>]*>/i, (m) => `${m}<head>${headBits()}</head>`);
+ }
+ return /<\/body>/i.test(doc)
+ ? doc.replace(/<\/body>/i, `${script}</body>`)
+ : `${doc}${script}`;
+ }
+ const skin = FRAGMENT_SKIN[theme];
+ return (
+ `<!doctype html><html lang="en" data-theme="${theme}"><head>${headBits()}` +
+ `<style>:root{color-scheme:${theme}}html,body{margin:0}` +
+ `body{padding:12px;background:${skin.bg};color:${skin.ink};` +
+ 'font:14px/1.5 system-ui,-apple-system,"Segoe UI",sans-serif}' +
+ "svg,img,canvas,video{max-width:100%}</style></head>" +
+ `<body>${html}${script}</body></html>`
+ );
+}
+
+/** An SVG snippet as an inert picture. */
+export function svgDataUrl(svg: string): string {
+ return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
+}
+
+/** The sandboxed frame an inline HTML snippet runs in, sized to its content. */
+export function InlineHtmlFrame({ html, title }: { html: string; title: string }) {
+ const theme = useThemeValue();
+ const token = useId();
+ const ref = useRef<HTMLIFrameElement>(null);
+ const [height, setHeight] = useState(MIN_FRAME_PX * 2);
+
+ useEffect(() => {
+ const onMessage = (event: MessageEvent) => {
+ const frame = ref.current;
+ if (!frame || event.source !== frame.contentWindow) return;
+ const data: unknown = event.data;
+ if (
+ typeof data !== "object" ||
+ data === null ||
+ (data as { type?: unknown }).type !== INLINE_HTML_SIZE_MESSAGE ||
+ (data as { token?: unknown }).token !== token.replace(/[^\w:-]/g, "")
+ ) {
+ return;
+ }
+ const reported = Number((data as { height?: unknown }).height);
+ if (!Number.isFinite(reported)) return;
+ setHeight(Math.min(MAX_FRAME_PX, Math.max(MIN_FRAME_PX, Math.ceil(reported) + 2)));
+ };
+ window.addEventListener("message", onMessage);
+ return () => window.removeEventListener("message", onMessage);
+ }, [token]);
+
+ const doc = useMemo(() => wrapInlineHtml(html, theme, token), [html, theme, token]);
+
+ return (
+ <iframe
+ ref={ref}
+ key={theme}
+ title={title}
+ srcDoc={doc}
+ sandbox="allow-scripts"
+ referrerPolicy="no-referrer"
+ style={{ height }}
+ className="block w-full border-0 bg-transparent"
+ data-testid="inline-html-frame"
+ />
+ );
+}
+
+export function RenderedFence({ language, code }: { language: FenceLanguage; code: string }) {
+ const t = useT();
+ const [mode, setMode] = useState<"rendered" | "source">("rendered");
+ const [copied, setCopied] = useState(false);
+
+ const copy = () => {
+ void robustCopy(code).then((ok) => {
+ if (!ok) return;
+ setCopied(true);
+ window.setTimeout(() => setCopied(false), 1500);
+ });
+ };
+
+ const segment = (value: "rendered" | "source", label: string) => (
+ <button
+ type="button"
+ aria-pressed={mode === value}
+ onClick={() => setMode(value)}
+ className={cn(
+ "rounded-sm px-2 py-0.5 text-[10px] font-medium transition-colors",
+ mode === value
+ ? "bg-background text-foreground shadow-sm"
+ : "text-muted-foreground hover:text-foreground",
+ )}
+ >
+ {label}
+ </button>
+ );
+
+ return (
+ <div
+ className="not-prose my-4 overflow-hidden rounded-md border border-border bg-muted/40"
+ data-testid="rendered-fence"
+ data-language={language}
+ data-mode={mode}
+ >
+ <div className="flex items-center justify-between gap-2 border-b border-border/40 bg-muted/20 px-3 py-1">
+ <span className="text-[10px] uppercase tracking-wider text-muted-foreground">{language}</span>
+ <div className="flex items-center gap-1.5">
+ <div role="group" className="inline-flex rounded border border-border/60 bg-muted/40 p-0.5">
+ {segment("rendered", t("outputs_view.fence_rendered"))}
+ {segment("source", t("outputs_view.fence_source"))}
+ </div>
+ <button
+ type="button"
+ onClick={copy}
+ className="rounded p-1 text-muted-foreground transition hover:bg-muted hover:text-foreground"
+ title={t("docs_content.copy_code")}
+ aria-label={copied ? t("docs_content.code_copied") : t("docs_content.copy_code")}
+ >
+ {copied ? (
+ <Check className="h-3 w-3 text-emerald-400" aria-hidden="true" />
+ ) : (
+ <Copy className="h-3 w-3" aria-hidden="true" />
+ )}
+ </button>
+ </div>
+ </div>
+ {mode === "source" ? (
+ <CodeBlock language={language} code={code} chrome={false} />
+ ) : language === "svg" ? (
+ <div className="flex justify-center bg-card p-4">
+ <img src={svgDataUrl(code)} alt="SVG" className="max-w-full" data-testid="inline-svg" />
+ </div>
+ ) : (
+ <InlineHtmlFrame html={code} title="HTML" />
+ )}
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/visualization/OutputPreview.test.tsx b/jarvis/ui/web/frontend/src/components/visualization/OutputPreview.test.tsx
new file mode 100644
index 0000000000..4bfbba4551
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/visualization/OutputPreview.test.tsx
@@ -0,0 +1,206 @@
+/**
+ * The output page — a run without a page composed the way an artifact is
+ * shown. Pins: the headline comes from the report's own title when there is
+ * one, the request is the lead, the final answer is the answer (the run's
+ * "Done." summary is not repeated), every file is drawn in place by kind,
+ * and "Open in Files" hands the file's path back.
+ */
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+
+import { OutputPreview, markdownTitle } from "@/components/visualization/OutputPreview";
+import type { ArtifactSummary, OutputSummary } from "@/hooks/useOutputs";
+
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+});
+
+function installFetchMock(
+ files: ArtifactSummary[],
+ rawByPath: Record<string, string>,
+ finalAnswer: string | null,
+) {
+ const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
+ const url = String(input);
+ const raw = /\/files\/(.+)\/raw$/.exec(url);
+ if (raw) {
+ const path = decodeURIComponent(raw[1]);
+ const text = rawByPath[path];
+ if (text === undefined) return { ok: false, status: 404, json: async () => ({}) };
+ return {
+ ok: true,
+ status: 200,
+ json: async () => ({ path, size: text.length, text, truncated: false }),
+ };
+ }
+ if (url.endsWith("/artifacts")) {
+ return { ok: true, status: 200, json: async () => ({ files }) };
+ }
+ if (url.endsWith("/plan")) {
+ return {
+ ok: true,
+ status: 200,
+ json: async () => ({
+ plan: finalAnswer ? { plan_id: "p", vision: "", status: "complete" } : null,
+ steps: [],
+ final_answer: finalAnswer,
+ }),
+ };
+ }
+ return { ok: false, status: 404, json: async () => ({}) };
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ return fetchMock;
+}
+
+function renderPreview(run: OutputSummary, onOpenFile = vi.fn()) {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ render(
+ <QueryClientProvider client={client}>
+ <OutputPreview run={run} onOpenFile={onOpenFile} />
+ </QueryClientProvider>,
+ );
+ return onOpenFile;
+}
+
+function file(path: string, over: Partial<ArtifactSummary> = {}): ArtifactSummary {
+ return { path, size: 120, mtime: 1_750_000_000, is_text: true, preview: null, ...over };
+}
+
+const RUN: OutputSummary = {
+ slug: "run-1",
+ utterance:
+ "Do a deep dive on Reddit.\n\nSupporting context from the recent conversation " +
+ "(use only to resolve references; the underlying request remains authoritative):\n- x",
+ status: "success",
+ summary: "Done. File reddit.md is in the folder Jarvis-Outputs.",
+ duration_s: 153.2,
+ completed_at: 1_755_000_000,
+};
+
+describe("markdownTitle", () => {
+ it("reads the first heading and ignores inline marks", () => {
+ expect(markdownTitle("intro\n\n# Reddit **Open Source** AI\n\ntext")).toBe(
+ "Reddit Open Source AI",
+ );
+ expect(markdownTitle("no heading here")).toBeNull();
+ expect(markdownTitle("")).toBeNull();
+ });
+});
+
+describe("OutputPreview", () => {
+ it("composes the page: report title, clean request, final answer, files in place", async () => {
+ installFetchMock(
+ [
+ file("tasks/t/artifacts/files/reddit.md"),
+ file("tasks/t/artifacts/files/scripts/tool.py"),
+ file("tasks/t/artifacts/files/data.csv"),
+ ],
+ {
+ "tasks/t/artifacts/files/reddit.md": "# Reddit Open Source AI Landscape\n\nA **report**.",
+ "tasks/t/artifacts/files/scripts/tool.py": "print('hi')\n",
+ "tasks/t/artifacts/files/data.csv": "a,b\n1,2\n",
+ },
+ "Done — the report is in reddit.md.",
+ );
+ const onOpenFile = renderPreview(RUN);
+
+ const page = await screen.findByTestId("output-preview");
+ await waitFor(() =>
+ expect(within(page).getByTestId("output-preview-title").textContent).toBe(
+ "Reddit Open Source AI Landscape",
+ ),
+ );
+ // The request, without the builder's supporting-context tail.
+ expect(within(page).getByTestId("output-preview-request").textContent).toBe(
+ "Do a deep dive on Reddit.",
+ );
+ // Eyebrow facts: kind, when, duration, status word.
+ expect(within(page).getByTestId("output-preview-status").textContent).toContain("Succeeded");
+ expect(page.textContent).toContain("2 min 33 s");
+ // The answer is the worker's final reply; the "Done." summary is not repeated.
+ const answer = await within(page).findByTestId("output-preview-answer");
+ expect(answer.textContent).toContain("Done — the report is in reddit.md.");
+ expect(answer.textContent).not.toContain("Done. File reddit.md");
+ // Every file drawn in place, by kind.
+ await waitFor(() =>
+ expect(within(page).getAllByTestId("output-preview-file")).toHaveLength(3),
+ );
+ const sections = within(page).getAllByTestId("output-preview-file");
+ expect(sections.map((s) => s.getAttribute("data-kind"))).toEqual(["markdown", "csv", "code"]);
+ await within(sections[0]).findByTestId("output-preview-markdown");
+ expect(within(sections[0]).getByText("report").tagName).toBe("STRONG");
+ await waitFor(() => expect(within(sections[1]).getByText("b")).toBeDefined());
+ await waitFor(() => expect(sections[2].textContent).toContain("print"));
+ // "Open in Files" hands the archive path back.
+ fireEvent.click(within(sections[2]).getByTitle("Open in Files"));
+ expect(onOpenFile).toHaveBeenCalledWith("tasks/t/artifacts/files/scripts/tool.py");
+ });
+
+ it("draws a document's front matter as a metadata block, not as prose", async () => {
+ installFetchMock(
+ [file("tasks/t/artifacts/files/SKILL.md")],
+ {
+ "tasks/t/artifacts/files/SKILL.md":
+ '---\nname: gmail-deep-clean\ndescription: "Cleans the inbox"\n---\n# Gmail Deep Clean\n\nBody.',
+ },
+ null,
+ );
+ renderPreview({ slug: "run-skill", utterance: "Write a skill", status: "success" });
+ const page = await screen.findByTestId("output-preview");
+ await waitFor(() =>
+ expect(within(page).getByTestId("output-preview-title").textContent).toBe(
+ "Gmail Deep Clean",
+ ),
+ );
+ const doc = await within(page).findByTestId("output-preview-markdown");
+ const meta = within(doc).getByTestId("markdown-front-matter");
+ expect(meta.textContent).toContain("name: gmail-deep-clean");
+ // The body no longer starts with the run-on metadata paragraph.
+ expect(within(doc).getByRole("heading", { level: 1 }).textContent).toBe("Gmail Deep Clean");
+ expect(within(doc).queryByText(/^name: gmail-deep-clean/)).toBeNull();
+ });
+
+ it("falls back to the request as headline and the summary as answer", async () => {
+ installFetchMock([], {}, null);
+ renderPreview({
+ slug: "run-2",
+ utterance: "What is the capital of Australia?",
+ status: "success",
+ summary: "Canberra — not Sydney.",
+ });
+ const page = await screen.findByTestId("output-preview");
+ expect(within(page).getByTestId("output-preview-title").textContent).toBe(
+ "What is the capital of Australia?",
+ );
+ // The headline IS the request: it is not repeated as a lead.
+ expect(within(page).queryByTestId("output-preview-request")).toBeNull();
+ const answer = await within(page).findByTestId("output-preview-answer");
+ expect(answer.textContent).toContain("Canberra — not Sydney.");
+ expect(within(page).queryByTestId("output-preview-files")).toBeNull();
+ });
+
+ it("leads with why a run ended early, and says when nothing is left behind", async () => {
+ installFetchMock([], {}, null);
+ renderPreview({
+ slug: "run-3",
+ utterance: "Build it",
+ status: "cancelled",
+ terminal_reason: "ui_cancel",
+ });
+ const page = await screen.findByTestId("output-preview");
+ const outcome = await within(page).findByTestId("output-preview-outcome");
+ expect(outcome.textContent).toContain("ui_cancel");
+ expect(within(page).getByTestId("output-preview-status").textContent).toContain("Cancelled");
+ expect(within(page).queryByTestId("output-preview-nothing")).toBeNull();
+ });
+
+ it("says so when a finished run left neither an answer nor a file", async () => {
+ installFetchMock([], {}, null);
+ renderPreview({ slug: "run-4", utterance: "Nothing", status: "success" });
+ const page = await screen.findByTestId("output-preview");
+ await within(page).findByTestId("output-preview-nothing");
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/visualization/OutputPreview.tsx b/jarvis/ui/web/frontend/src/components/visualization/OutputPreview.tsx
new file mode 100644
index 0000000000..845d169571
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/visualization/OutputPreview.tsx
@@ -0,0 +1,593 @@
+/**
+ * The output page — a run that produced no page or picture, shown the way an
+ * artifact is shown: one composed page on the stage, not a file list.
+ *
+ * Every run gets the same treatment (2026-08-25): the artifacts a worker
+ * wrote as HTML fill the stage as pages; everything else — a research answer,
+ * a memo, a set of scripts, a failed build — is composed HERE from what the
+ * run left behind, in the same design standard the artifact brief hands the
+ * worker (`jarvis/artifacts/design_guide.py`: the app's tokens, an eyebrow
+ * that says something true, a headline, the body in reading order, a
+ * hairline where a section ends; no hero, no gradient, no decoration).
+ *
+ * Reading order, top to bottom:
+ * 1. eyebrow (kind · when · duration · status), the headline, the request;
+ * 2. why the run ended, when it ended early (failure, cancellation, review);
+ * 3. the answer — the worker's final reply, or the run's summary;
+ * 4. the deliverables — every file rendered in place: a Markdown report as
+ * a document, an HTML page running in its sandbox, a table as a table, a
+ * picture as a picture; a script, a patch or a data file as a card that
+ * says what it is (its own description, what it defines, which files a
+ * patch touches) with the source folded under it — the reader scrolling
+ * through sees what was made, and the code is one click away here and
+ * under Code / Files. Anything the page cannot draw is one click from
+ * Files.
+ *
+ * Data: the run itself (`OutputSummary`), the reconstructed plan for the
+ * final answer (`/plan`, same cache the run graph reads), the file listing
+ * (`/artifacts`, same cache the rail's scan fills) and each text file's
+ * bytes (`/raw`). Nothing is fetched twice.
+ */
+import { useMemo, useState, type ReactNode } from "react";
+import {
+ AlertTriangle,
+ ArrowUpRight,
+ ChevronRight,
+ FileCode2,
+ FileImage,
+ FileQuestion,
+ FileText,
+ Globe,
+ Loader2,
+ ShieldCheck,
+ Table2,
+} from "lucide-react";
+
+import { cn } from "@/lib/utils";
+import { useT } from "@/i18n";
+import { artifactKind, formatBytes, isTextKind, type ArtifactKind } from "@/lib/artifactKind";
+import { codeDigest, type CodeDigest } from "@/lib/codeDigest";
+import { cleanRequest, requestHeadline } from "@/lib/runRequest";
+import {
+ artifactInlineUrl,
+ useArtifactFile,
+ useArtifactsForOutput,
+ usePlanForOutput,
+ type ArtifactSummary,
+ type OutputStatus,
+ type OutputSummary,
+} from "@/hooks/useOutputs";
+import {
+ CsvTable,
+ HtmlPage,
+ SourceView,
+ deliverableDisplayPath,
+} from "@/components/outputs/ArtifactViewer";
+import { MarkdownProse, splitFrontMatter } from "@/components/outputs/MarkdownProse";
+import { deliverableFiles, runNeedsReview } from "@/components/visualization/RunPanels";
+
+/** Files drawn in place; the rest are listed and one click from Files. */
+const MAX_INLINE_FILES = 12;
+/** Above this a text file is not fetched for the page — Files still shows it. */
+const MAX_INLINE_BYTES = 400_000;
+
+/** The document's first `# Heading` — the title the worker gave its report. */
+export function markdownTitle(text: string | null | undefined): string | null {
+ if (!text) return null;
+ const match = /^\s*#\s+(.+?)\s*#*\s*$/m.exec(splitFrontMatter(text).body.slice(0, 4000));
+ if (!match) return null;
+ const title = match[1].replace(/[*_`]/g, "").trim();
+ return title.length > 0 ? title : null;
+}
+
+/** Status as a word plus a dot — the one place colour carries meaning here. */
+const STATUS_DOT: Record<OutputStatus, string> = {
+ success: "bg-emerald-400",
+ error: "bg-destructive",
+ running: "bg-primary animate-pulse",
+ cancelled: "bg-amber-400",
+ unknown: "bg-muted-foreground/50",
+};
+
+function formatWhen(seconds: number | undefined): string {
+ if (!seconds) return "";
+ return new Date(seconds * 1000).toLocaleString(undefined, {
+ year: "numeric",
+ month: "short",
+ day: "numeric",
+ hour: "2-digit",
+ minute: "2-digit",
+ });
+}
+
+function formatDuration(seconds: number | undefined): string {
+ if (typeof seconds !== "number") return "";
+ if (seconds < 90) return `${seconds.toFixed(seconds < 10 ? 1 : 0)} s`;
+ const minutes = Math.floor(seconds / 60);
+ const rest = Math.round(seconds - minutes * 60);
+ return `${minutes} min ${rest} s`;
+}
+
+/** The first file the page would draw as a document — its title names the run. */
+function primaryMarkdown(files: ArtifactSummary[]): ArtifactSummary | null {
+ return files.find((f) => artifactKind(f.path, f.is_text) === "markdown") ?? null;
+}
+
+export function OutputPreview({
+ run,
+ onOpenFile,
+}: {
+ run: OutputSummary;
+ /** Switch the stage to Files with this file selected. */
+ onOpenFile?: (path: string) => void;
+}) {
+ const t = useT();
+ const listing = useArtifactsForOutput(run.slug);
+ const plan = usePlanForOutput(run.slug);
+ const lead = useMemo(
+ () => primaryMarkdown(deliverableFiles(listing.data?.files ?? [])),
+ [listing.data],
+ );
+ // The report leads the page; scripts, data and assets follow in the
+ // reader's order (primary files first, then nested assets).
+ const files = useMemo(() => {
+ const ordered = deliverableFiles(listing.data?.files ?? []);
+ return lead ? [lead, ...ordered.filter((f) => f.path !== lead.path)] : ordered;
+ }, [listing.data, lead]);
+ const leadText = useArtifactFile(run.slug, lead && lead.size <= MAX_INLINE_BYTES ? lead.path : null);
+
+ const request = cleanRequest(run.utterance);
+ const title = markdownTitle(leadText.data?.text) ?? requestHeadline(request);
+ // The request repeats the headline when the headline IS the request.
+ const showRequest = request.length > 0 && request !== title;
+
+ // The answer is the worker's final reply. The run's summary is what the
+ // voice read back — the reply itself (often cut short) or the stock "Done.
+ // File X is in the folder…" — so it stands in only when no reply survived.
+ const answer = plan.data?.final_answer?.trim() || run.summary?.trim() || "";
+
+ const status = run.status ?? "unknown";
+ const needsReview = runNeedsReview(run);
+ const endedEarly = !!run.terminal_reason || needsReview || (!!run.error && status === "error");
+ const loading = listing.isLoading || plan.isLoading;
+ const inline = files.slice(0, MAX_INLINE_FILES);
+ const rest = files.slice(MAX_INLINE_FILES);
+ const nothing = !loading && files.length === 0 && answer.length === 0 && !endedEarly;
+
+ return (
+ <div className="h-full overflow-auto" data-testid="output-preview">
+ <article className="mx-auto flex max-w-[1080px] flex-col gap-10 px-8 py-10 lg:px-12">
+ <header className="flex flex-col gap-3">
+ <p className="flex flex-wrap items-center gap-x-2 gap-y-1 text-[11px] font-semibold uppercase tracking-[0.08em] text-muted-foreground">
+ <span>{t("visualization.output_kind")}</span>
+ {run.started_at || run.completed_at ? (
+ <>
+ <span aria-hidden>·</span>
+ <span className="normal-case tracking-normal">
+ {formatWhen(run.completed_at ?? run.started_at)}
+ </span>
+ </>
+ ) : null}
+ {typeof run.duration_s === "number" && (
+ <>
+ <span aria-hidden>·</span>
+ <span className="normal-case tracking-normal tabular-nums">
+ {formatDuration(run.duration_s)}
+ </span>
+ </>
+ )}
+ <span aria-hidden>·</span>
+ <span className="inline-flex items-center gap-1.5" data-testid="output-preview-status">
+ <span className={cn("h-1.5 w-1.5 rounded-full", STATUS_DOT[status])} aria-hidden />
+ {needsReview ? t("outputs_view.needs_review") : t(`visualization.status_word_${status}`)}
+ </span>
+ </p>
+ <h1
+ className="text-balance text-[clamp(26px,3.2vw,34px)] font-semibold leading-tight tracking-tight text-foreground"
+ data-testid="output-preview-title"
+ >
+ {title || run.slug}
+ </h1>
+ {showRequest && (
+ <p
+ className="max-w-[68ch] text-[15px] leading-relaxed text-muted-foreground"
+ data-testid="output-preview-request"
+ >
+ {request}
+ </p>
+ )}
+ </header>
+
+ {endedEarly && (
+ <section
+ data-testid="output-preview-outcome"
+ className={cn(
+ "flex gap-3 rounded-xl border p-4",
+ needsReview || status === "cancelled"
+ ? "border-amber-400/30 bg-amber-400/5"
+ : "border-destructive/30 bg-destructive/5",
+ )}
+ >
+ <AlertTriangle
+ className={cn(
+ "mt-0.5 h-4 w-4 shrink-0",
+ needsReview || status === "cancelled" ? "text-amber-400" : "text-destructive",
+ )}
+ aria-hidden
+ />
+ <div className="flex min-w-0 flex-col gap-1">
+ <p className="text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">
+ {needsReview
+ ? t("outputs_view.needs_review")
+ : status === "cancelled"
+ ? t("outputs_view.cancellation_reason")
+ : t("outputs_view.failure_reason")}
+ </p>
+ {needsReview && (
+ <p className="text-sm leading-relaxed text-foreground/90">
+ {t("outputs_view.needs_review_hint")}
+ </p>
+ )}
+ {!needsReview && status === "error" && run.has_partial_output && (
+ <p className="text-sm leading-relaxed text-foreground/90">
+ {t("outputs_view.partial_output_hint")}
+ </p>
+ )}
+ {run.terminal_reason && (
+ <p className="font-mono text-[12px] text-muted-foreground">{run.terminal_reason}</p>
+ )}
+ {run.error && !run.terminal_reason && (
+ <pre className="whitespace-pre-wrap font-mono text-[12px] text-destructive/90">
+ {run.error}
+ </pre>
+ )}
+ </div>
+ </section>
+ )}
+
+ {loading && answer.length === 0 && files.length === 0 && (
+ <p className="flex items-center gap-2 text-xs text-muted-foreground">
+ <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />
+ {t("outputs_view.loading_artifacts")}
+ </p>
+ )}
+
+ {nothing && (
+ <p className="text-sm text-muted-foreground" data-testid="output-preview-nothing">
+ {t("visualization.preview_nothing")}
+ </p>
+ )}
+
+ {answer.length > 0 && (
+ <section className="flex flex-col gap-3" data-testid="output-preview-answer">
+ <SectionEyebrow>{t("visualization.preview_answer")}</SectionEyebrow>
+ <MarkdownProse
+ slug={run.slug}
+ path=""
+ files={files}
+ text={answer}
+ onSelectSibling={onOpenFile}
+ className="max-w-none text-[15px] leading-7 prose-h1:text-2xl prose-h2:text-xl prose-h3:text-lg"
+ testId="output-preview-answer-body"
+ />
+ </section>
+ )}
+
+ {files.length > 0 && (
+ <section className="flex flex-col gap-4" data-testid="output-preview-files">
+ <SectionEyebrow>
+ {t("visualization.preview_deliverables")}
+ <span className="ml-2 font-normal normal-case tracking-normal text-muted-foreground/70">
+ {files.length} {files.length === 1 ? t("outputs_view.file") : t("outputs_view.files")}
+ </span>
+ </SectionEyebrow>
+ {inline.map((file) => (
+ <FileSection
+ key={file.path}
+ slug={run.slug}
+ file={file}
+ files={files}
+ onOpenFile={onOpenFile}
+ />
+ ))}
+ {rest.length > 0 && (
+ <p className="text-xs text-muted-foreground">
+ {t("visualization.preview_more_files").replace("{0}", String(rest.length))}
+ </p>
+ )}
+ </section>
+ )}
+ </article>
+ </div>
+ );
+}
+
+/** A section's label — small caps, a hairline above, the way the standard marks a section. */
+function SectionEyebrow({ children }: { children: ReactNode }) {
+ return (
+ <h2 className="border-t border-border pt-4 text-[11px] font-semibold uppercase tracking-[0.08em] text-muted-foreground">
+ {children}
+ </h2>
+ );
+}
+
+function KindIcon({ kind, className }: { kind: ArtifactKind; className?: string }) {
+ const cls = cn("h-3.5 w-3.5 shrink-0", className);
+ switch (kind) {
+ case "markdown":
+ case "text":
+ case "pdf":
+ return <FileText className={cls} aria-hidden />;
+ case "html":
+ return <Globe className={cls} aria-hidden />;
+ case "image":
+ return <FileImage className={cls} aria-hidden />;
+ case "code":
+ return <FileCode2 className={cls} aria-hidden />;
+ case "csv":
+ return <Table2 className={cls} aria-hidden />;
+ default:
+ return <FileQuestion className={cls} aria-hidden />;
+ }
+}
+
+/**
+ * One deliverable in place: a labelled block with the file's own rendering
+ * inside. Text is fetched only for kinds the page draws from text; a page
+ * (HTML) runs in its sandbox from the server's `/page` route; a binary is
+ * named and left to Files, where the reader has the openers for it.
+ */
+function FileSection({
+ slug,
+ file,
+ files,
+ onOpenFile,
+}: {
+ slug: string;
+ file: ArtifactSummary;
+ files: ArtifactSummary[];
+ onOpenFile?: (path: string) => void;
+}) {
+ const t = useT();
+ const kind = artifactKind(file.path, file.is_text);
+ const drawsFromText = isTextKind(kind) && kind !== "html";
+ const tooLarge = file.size > MAX_INLINE_BYTES;
+ const full = useArtifactFile(slug, drawsFromText && !tooLarge ? file.path : null);
+ const display = deliverableDisplayPath(file.path);
+
+ let body: ReactNode;
+ if (kind === "image") {
+ body = (
+ <div className="flex justify-center p-4">
+ <img
+ src={artifactInlineUrl(slug, file.path)}
+ alt={display}
+ loading="lazy"
+ className="max-h-[70vh] max-w-full rounded-md"
+ />
+ </div>
+ );
+ } else if (kind === "html") {
+ body = (
+ <div className="flex flex-col" data-testid="output-preview-page">
+ <HtmlPage slug={slug} path={file.path} className="h-[min(70vh,720px)] w-full" />
+ <p className="flex items-center gap-1.5 border-t border-border/60 px-4 py-1.5 text-[11px] text-muted-foreground">
+ <ShieldCheck className="h-3 w-3 shrink-0" aria-hidden />
+ {t("visualization.page_sandbox_note")}
+ </p>
+ </div>
+ );
+ } else if (!drawsFromText || tooLarge) {
+ body = (
+ <p className="px-4 py-3 text-xs text-muted-foreground">
+ {t(tooLarge ? "visualization.preview_too_large" : "visualization.preview_open_in_files_hint")}
+ </p>
+ );
+ } else if (full.isLoading || (!full.data && !full.isError)) {
+ body = (
+ <p className="flex items-center gap-2 px-4 py-3 text-xs text-muted-foreground">
+ <Loader2 className="h-3 w-3 animate-spin" aria-hidden />
+ {t("outputs_view.loading_file")}
+ </p>
+ );
+ } else if (full.isError || !full.data) {
+ body = (
+ <p className="px-4 py-3 text-xs text-destructive">
+ {t("common.error")}: {String(full.error ?? "")}
+ </p>
+ );
+ } else if (kind === "markdown") {
+ body = (
+ <MarkdownProse
+ slug={slug}
+ path={file.path}
+ files={files}
+ text={full.data.text}
+ onSelectSibling={onOpenFile}
+ className="max-w-none px-6 py-5 text-[15px] leading-7 prose-h1:text-2xl prose-h2:text-xl prose-h3:text-lg"
+ testId="output-preview-markdown"
+ />
+ );
+ } else if (kind === "csv") {
+ body = <CsvTable text={full.data.text} tab={file.path.toLowerCase().endsWith(".tsv")} />;
+ } else {
+ body = <CodeCard path={file.path} text={full.data.text} />;
+ }
+
+ return (
+ <section
+ className="overflow-hidden rounded-xl border border-border bg-card/40"
+ data-testid="output-preview-file"
+ data-kind={kind}
+ >
+ <header className="flex h-10 items-center gap-2 border-b border-border/60 bg-card/60 px-4">
+ <KindIcon kind={kind} className="text-primary" />
+ <span className="min-w-0 flex-1 truncate font-mono text-[12px] text-foreground" title={file.path}>
+ {display}
+ </span>
+ <span className="shrink-0 font-mono text-[11px] text-muted-foreground">
+ {formatBytes(file.size)}
+ </span>
+ {onOpenFile && (
+ <button
+ type="button"
+ onClick={() => onOpenFile(file.path)}
+ className="inline-flex shrink-0 items-center gap-1 rounded px-1.5 py-0.5 text-[11px] text-muted-foreground transition-colors hover:bg-secondary/50 hover:text-foreground"
+ title={t("visualization.preview_open_in_files")}
+ >
+ {t("visualization.preview_open_in_files")}
+ <ArrowUpRight className="h-3 w-3" aria-hidden />
+ </button>
+ )}
+ </header>
+ {full.data?.truncated && (
+ <p className="border-b border-border/60 px-4 py-1.5 text-[10px] text-muted-foreground">
+ {t("outputs_view.file_truncated")}
+ </p>
+ )}
+ {body}
+ </section>
+ );
+}
+
+/** A file this short is shown whole — folding twelve lines away would be theatre. */
+const SHORT_FILE_LINES = 30;
+/** Definitions, keys or touched files named on the card before "+N more". */
+const MAX_NAMED = 12;
+
+/**
+ * A script, a patch or a data file as a card: what the file says about
+ * itself first (`codeDigest`), the source folded beneath it — open by
+ * default only when the file is short. The reader who wants every line has
+ * the fold, and the Code and Files tabs.
+ */
+function CodeCard({ path, text }: { path: string; text: string }) {
+ const t = useT();
+ const digest = useMemo(() => codeDigest(path, text), [path, text]);
+ const [open, setOpen] = useState(digest.lines <= SHORT_FILE_LINES);
+ return (
+ <div data-testid="output-preview-code-card" data-open={open ? "true" : "false"}>
+ <div className="flex flex-col gap-2 px-4 py-3">
+ {digest.description && (
+ <p
+ className="max-w-[72ch] text-[14px] leading-relaxed text-foreground/90"
+ data-testid="output-preview-code-description"
+ >
+ {digest.description}
+ </p>
+ )}
+ <DigestFacts digest={digest} />
+ </div>
+ <button
+ type="button"
+ aria-expanded={open}
+ onClick={() => setOpen((v) => !v)}
+ className="flex w-full items-center gap-1.5 border-t border-border/60 px-4 py-2 text-left text-[11px] text-muted-foreground transition-colors hover:bg-secondary/40 hover:text-foreground"
+ >
+ <ChevronRight
+ className={cn("h-3 w-3 shrink-0 transition-transform", open && "rotate-90")}
+ aria-hidden
+ />
+ {open ? t("visualization.preview_hide_source") : t("visualization.preview_show_source")}
+ </button>
+ {open && (
+ <div className="border-t border-border/60" data-testid="output-preview-code-source">
+ <SourceView path={path} text={text} />
+ </div>
+ )}
+ </div>
+ );
+}
+
+/** The card's facts line(s): language · lines, then what the file defines or touches. */
+function DigestFacts({ digest }: { digest: CodeDigest }) {
+ const t = useT();
+ const lines =
+ digest.lines === 1
+ ? t("visualization.preview_line_one")
+ : t("visualization.preview_lines").replace("{0}", String(digest.lines));
+ const named = <T,>(items: T[], draw: (item: T) => ReactNode) => (
+ <>
+ {items.slice(0, MAX_NAMED).map((item, i) => (
+ <span key={i}>
+ {i > 0 && <span className="text-muted-foreground/60">, </span>}
+ {draw(item)}
+ </span>
+ ))}
+ {items.length > MAX_NAMED && (
+ <span className="text-muted-foreground"> +{items.length - MAX_NAMED}</span>
+ )}
+ </>
+ );
+ const added = digest.diff?.reduce((n, f) => n + f.added, 0) ?? 0;
+ const removed = digest.diff?.reduce((n, f) => n + f.removed, 0) ?? 0;
+
+ return (
+ <div className="flex flex-col gap-1.5" data-testid="output-preview-code-facts">
+ <p className="flex flex-wrap items-center gap-x-2 text-[11px] font-semibold uppercase tracking-[0.08em] text-muted-foreground">
+ <span>{digest.language}</span>
+ <span aria-hidden>·</span>
+ <span className="normal-case tracking-normal tabular-nums">{lines}</span>
+ {digest.diff && digest.diff.length > 0 && (
+ <>
+ <span aria-hidden>·</span>
+ <span className="normal-case tracking-normal tabular-nums">
+ {digest.diff.length === 1
+ ? t("visualization.preview_file_changed_one")
+ : t("visualization.preview_files_changed").replace("{0}", String(digest.diff.length))}
+ <span className="ml-2 text-emerald-500">+{added}</span>
+ <span className="ml-1.5 text-destructive">−{removed}</span>
+ </span>
+ </>
+ )}
+ {digest.json && (
+ <>
+ <span aria-hidden>·</span>
+ <span className="normal-case tracking-normal tabular-nums">
+ {digest.json.kind === "object"
+ ? t("visualization.preview_json_object").replace("{0}", String(digest.json.count))
+ : t("visualization.preview_json_array").replace("{0}", String(digest.json.count))}
+ </span>
+ </>
+ )}
+ </p>
+ {digest.symbols.length > 0 && (
+ <p className="text-[12px] leading-relaxed text-muted-foreground">
+ <span className="mr-2 text-[11px] font-semibold uppercase tracking-[0.08em]">
+ {t("visualization.preview_defines")}
+ </span>
+ {named(digest.symbols, (s) => (
+ <code className="font-mono text-[12px] text-foreground/80">
+ {s.kind === "function" ? `${s.name}()` : s.name}
+ </code>
+ ))}
+ </p>
+ )}
+ {digest.json?.kind === "object" && digest.json.keys.length > 0 && (
+ <p className="text-[12px] leading-relaxed text-muted-foreground">
+ {named(digest.json.keys, (k) => (
+ <code className="font-mono text-[12px] text-foreground/80">{k}</code>
+ ))}
+ </p>
+ )}
+ {digest.diff && digest.diff.length > 0 && (
+ <ul className="mt-1 flex flex-col gap-0.5 text-[12px]" data-testid="output-preview-diff-files">
+ {digest.diff.slice(0, MAX_NAMED).map((f) => (
+ <li key={f.path} className="flex items-baseline gap-3">
+ <code className="min-w-0 flex-1 truncate font-mono text-[12px] text-foreground/80">
+ {f.path}
+ </code>
+ <span className="shrink-0 font-mono text-[11px] tabular-nums">
+ <span className="text-emerald-500">+{f.added}</span>
+ <span className="ml-1.5 text-destructive">−{f.removed}</span>
+ </span>
+ </li>
+ ))}
+ {digest.diff.length > MAX_NAMED && (
+ <li className="text-[11px] text-muted-foreground">+{digest.diff.length - MAX_NAMED}</li>
+ )}
+ </ul>
+ )}
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/visualization/OutputPreviewCards.test.tsx b/jarvis/ui/web/frontend/src/components/visualization/OutputPreviewCards.test.tsx
new file mode 100644
index 0000000000..cdbfe5315d
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/visualization/OutputPreviewCards.test.tsx
@@ -0,0 +1,180 @@
+/**
+ * The output page draws what a run made, not its source: an HTML deliverable
+ * runs in its sandbox, a script is a card that says what it does with the
+ * source folded away, a patch lists the files it touches.
+ */
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+
+import { OutputPreview } from "@/components/visualization/OutputPreview";
+import type { ArtifactSummary, OutputSummary } from "@/hooks/useOutputs";
+
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+});
+
+function installFetchMock(files: ArtifactSummary[], rawByPath: Record<string, string>) {
+ const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input);
+ const raw = /\/files\/(.+)\/raw$/.exec(url);
+ if (raw) {
+ const path = decodeURIComponent(raw[1]);
+ const text = rawByPath[path];
+ if (text === undefined) return { ok: false, status: 404, json: async () => ({}) };
+ return {
+ ok: true,
+ status: 200,
+ json: async () => ({ path, size: text.length, text, truncated: false }),
+ };
+ }
+ if (url.endsWith("/page") && init?.method === "HEAD") {
+ return { ok: true, status: 200, json: async () => ({}) };
+ }
+ if (url.endsWith("/artifacts")) {
+ return { ok: true, status: 200, json: async () => ({ files }) };
+ }
+ if (url.endsWith("/plan")) {
+ return {
+ ok: true,
+ status: 200,
+ json: async () => ({ plan: null, steps: [], final_answer: null }),
+ };
+ }
+ return { ok: false, status: 404, json: async () => ({}) };
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ return fetchMock;
+}
+
+function renderPreview(run: OutputSummary) {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ render(
+ <QueryClientProvider client={client}>
+ <OutputPreview run={run} onOpenFile={vi.fn()} />
+ </QueryClientProvider>,
+ );
+}
+
+function file(path: string, over: Partial<ArtifactSummary> = {}): ArtifactSummary {
+ return { path, size: 120, mtime: 1_750_000_000, is_text: true, preview: null, ...over };
+}
+
+const RUN: OutputSummary = {
+ slug: "run-2",
+ utterance: "Build me the thing.",
+ status: "success",
+ summary: "Done.",
+ duration_s: 12,
+ completed_at: 1_755_000_000,
+};
+
+const LONG_SCRIPT = [
+ "#!/usr/bin/env python3",
+ '"""Gmail Deep Clean CLI utility.',
+ "",
+ "Scans the inbox and proposes deletions.",
+ '"""',
+ "import sys",
+ "",
+ "class Cleaner:",
+ " pass",
+ "",
+ "def main() -> int:",
+ " return 0",
+ ...Array.from({ length: 30 }, (_, i) => `x${i} = ${i}`),
+ "",
+].join("\n");
+
+describe("OutputPreview cards", () => {
+ it("runs an HTML deliverable in its sandbox on the page instead of pointing at Files", async () => {
+ installFetchMock([file("dashboard.html")], {});
+ renderPreview(RUN);
+ const frame = (await screen.findByTestId("artifact-html-page")) as HTMLIFrameElement;
+ expect(frame.getAttribute("sandbox")).toBe("allow-scripts");
+ expect(frame.getAttribute("src")).toMatch(/\/files\/dashboard\.html\/page\?theme=(light|dark)$/);
+ expect(screen.queryByText(/not drawn on the page/)).toBeNull();
+ expect(screen.getByText(/Runs in a sandbox/)).toBeDefined();
+ });
+
+ it("draws a long script as a card — description, definitions, source folded", async () => {
+ installFetchMock([file("scripts/clean.py", { size: LONG_SCRIPT.length })], {
+ "scripts/clean.py": LONG_SCRIPT,
+ });
+ renderPreview(RUN);
+ const card = await screen.findByTestId("output-preview-code-card");
+ expect(card.getAttribute("data-open")).toBe("false");
+ expect(within(card).getByTestId("output-preview-code-description").textContent).toBe(
+ "Gmail Deep Clean CLI utility.",
+ );
+ const facts = within(card).getByTestId("output-preview-code-facts");
+ expect(facts.textContent).toContain("python");
+ expect(facts.textContent).toContain("42 lines");
+ expect(facts.textContent).toContain("Cleaner");
+ expect(facts.textContent).toContain("main()");
+ expect(within(card).queryByTestId("output-preview-code-source")).toBeNull();
+
+ fireEvent.click(within(card).getByRole("button", { name: "Show source" }));
+ await waitFor(() =>
+ expect(within(card).getByTestId("output-preview-code-source").textContent).toContain(
+ "def main()",
+ ),
+ );
+ expect(card.getAttribute("data-open")).toBe("true");
+ expect(within(card).getByRole("button", { name: "Hide source" })).toBeDefined();
+ });
+
+ it("shows a short file whole", async () => {
+ installFetchMock([file("run.sh")], { "run.sh": "#!/bin/sh\n# Start it.\nnpm start\n" });
+ renderPreview(RUN);
+ const card = await screen.findByTestId("output-preview-code-card");
+ expect(card.getAttribute("data-open")).toBe("true");
+ expect(within(card).getByTestId("output-preview-code-source").textContent).toContain(
+ "npm start",
+ );
+ expect(within(card).getByTestId("output-preview-code-facts").textContent).toContain(
+ "3 lines",
+ );
+ });
+
+ it("lists the files a patch touches with their added and removed lines", async () => {
+ const patch = [
+ "Subject: [PATCH] fix(rail): keep the newest run on top",
+ "",
+ "diff --git a/src/rail.ts b/src/rail.ts",
+ "--- a/src/rail.ts",
+ "+++ b/src/rail.ts",
+ "@@ -1,2 +1,3 @@",
+ "-old",
+ "+new",
+ "+newer",
+ "",
+ ].join("\n");
+ installFetchMock([file("0001-fix.patch")], { "0001-fix.patch": patch });
+ renderPreview(RUN);
+ const card = await screen.findByTestId("output-preview-code-card");
+ expect(within(card).getByTestId("output-preview-code-description").textContent).toBe(
+ "fix(rail): keep the newest run on top",
+ );
+ const facts = within(card).getByTestId("output-preview-code-facts");
+ expect(facts.textContent).toContain("1 file changed");
+ const rows = within(card).getAllByRole("listitem");
+ expect(rows).toHaveLength(1);
+ expect(rows[0].textContent).toContain("src/rail.ts");
+ expect(rows[0].textContent).toContain("+2");
+ expect(rows[0].textContent).toContain("−1");
+ });
+
+ it("describes a JSON deliverable by its shape", async () => {
+ installFetchMock([file("result.json")], {
+ "result.json": JSON.stringify({ alpha: 1, beta: [2], gamma: null }, null, 2),
+ });
+ renderPreview(RUN);
+ const card = await screen.findByTestId("output-preview-code-card");
+ const facts = within(card).getByTestId("output-preview-code-facts");
+ expect(facts.textContent).toContain("Object · 3 keys");
+ expect(facts.textContent).toContain("alpha");
+ expect(facts.textContent).toContain("gamma");
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/visualization/RunPanels.tsx b/jarvis/ui/web/frontend/src/components/visualization/RunPanels.tsx
index e75ccac33a..950e74ac79 100644
--- a/jarvis/ui/web/frontend/src/components/visualization/RunPanels.tsx
+++ b/jarvis/ui/web/frontend/src/components/visualization/RunPanels.tsx
@@ -353,7 +353,14 @@ export function deliverableFiles(files: ArtifactSummary[]): ArtifactSummary[] {
* (summary, why it ended) sit above the files: for a run that produced no
* page — a research answer, a failed build — they ARE the result.
*/
-export function RunFiles({ run }: { run: OutputSummary }) {
+export function RunFiles({
+ run,
+ initialPath,
+}: {
+ run: OutputSummary;
+ /** The file the reader opens on — set when the user came from the output page. */
+ initialPath?: string | null;
+}) {
const t = useT();
const q = useArtifactsForOutput(run.slug);
const caps = useOutputsCapabilities();
@@ -389,10 +396,11 @@ export function RunFiles({ run }: { run: OutputSummary }) {
<div className="text-xs text-muted-foreground">{t("outputs_view.no_files")}</div>
) : (
<ArtifactViewer
- key={run.slug}
+ key={`${run.slug}:${initialPath ?? ""}`}
slug={run.slug}
files={files}
nativeActions={nativeActions}
+ initialPath={initialPath}
/>
)}
</section>
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index cb64ddb5e5..c7c3b59b01 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -2659,6 +2659,8 @@
"binary_file_hint": "Binärdatei — öffne den Ordner auf dem Desktop, um sie anzuzeigen.",
"loading_file": "Lade Datei…",
"file_truncated": "Datei gekürzt auf 1 MiB — Rest im Datei-Manager anzeigen.",
+ "fence_rendered": "Gerendert",
+ "fence_source": "Quelltext",
"open_action": "Öffnen",
"open_with_title": "Öffnen mit…",
"open_with_remember": "Als Standard merken",
@@ -5088,6 +5090,15 @@
"preview_open_in_files": "Unter Dateien öffnen",
"preview_open_in_files_hint": "Diese Datei wird nicht auf der Seite gezeichnet — öffne sie unter Dateien.",
"preview_too_large": "Zu groß für die Seite — öffne sie unter Dateien.",
+ "preview_show_source": "Quelltext anzeigen",
+ "preview_hide_source": "Quelltext ausblenden",
+ "preview_lines": "{0} Zeilen",
+ "preview_line_one": "1 Zeile",
+ "preview_defines": "Definiert",
+ "preview_files_changed": "{0} Dateien geändert",
+ "preview_file_changed_one": "1 Datei geändert",
+ "preview_json_object": "Objekt · {0} Schlüssel",
+ "preview_json_array": "Liste · {0} Einträge",
"preview_more_files": "{0} weitere Dateien unter Dateien.",
"status_word_success": "Erfolgreich",
"status_word_error": "Fehlgeschlagen",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 0100b28f2e..97ca748b55 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -2659,6 +2659,8 @@
"binary_file_hint": "Binary file — open the folder on the desktop to view it.",
"loading_file": "Loading file…",
"file_truncated": "File truncated to 1 MiB — view the rest in the file manager.",
+ "fence_rendered": "Rendered",
+ "fence_source": "Source",
"open_action": "Open",
"open_with_title": "Open with…",
"open_with_remember": "Remember as default",
@@ -5088,6 +5090,15 @@
"preview_open_in_files": "Open in Files",
"preview_open_in_files_hint": "This file is not drawn on the page — open it under Files.",
"preview_too_large": "Too large to draw on the page — open it under Files.",
+ "preview_show_source": "Show source",
+ "preview_hide_source": "Hide source",
+ "preview_lines": "{0} lines",
+ "preview_line_one": "1 line",
+ "preview_defines": "Defines",
+ "preview_files_changed": "{0} files changed",
+ "preview_file_changed_one": "1 file changed",
+ "preview_json_object": "Object · {0} keys",
+ "preview_json_array": "List · {0} entries",
"preview_more_files": "{0} more files under Files.",
"status_word_success": "Succeeded",
"status_word_error": "Failed",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 0656636315..a3410ec0d3 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -2659,6 +2659,8 @@
"binary_file_hint": "Archivo binario: abre la carpeta en el escritorio para verlo.",
"loading_file": "Cargando el archivo…",
"file_truncated": "Archivo truncado a 1 MiB: ver el resto en el gestor de archivos.",
+ "fence_rendered": "Renderizado",
+ "fence_source": "Código",
"open_action": "Abrir",
"open_with_title": "Abrir con…",
"open_with_remember": "Recordar como predeterminado",
@@ -5088,6 +5090,15 @@
"preview_open_in_files": "Abrir en Archivos",
"preview_open_in_files_hint": "Este archivo no se dibuja en la página — ábrelo en Archivos.",
"preview_too_large": "Demasiado grande para la página — ábrelo en Archivos.",
+ "preview_show_source": "Mostrar código",
+ "preview_hide_source": "Ocultar código",
+ "preview_lines": "{0} líneas",
+ "preview_line_one": "1 línea",
+ "preview_defines": "Define",
+ "preview_files_changed": "{0} archivos cambiados",
+ "preview_file_changed_one": "1 archivo cambiado",
+ "preview_json_object": "Objeto · {0} claves",
+ "preview_json_array": "Lista · {0} entradas",
"preview_more_files": "{0} archivos más en Archivos.",
"status_word_success": "Completada",
"status_word_error": "Fallida",
diff --git a/jarvis/ui/web/frontend/src/lib/codeDigest.test.ts b/jarvis/ui/web/frontend/src/lib/codeDigest.test.ts
new file mode 100644
index 0000000000..7f9ac2b8e3
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/codeDigest.test.ts
@@ -0,0 +1,155 @@
+import { describe, expect, it } from "vitest";
+
+import { codeDigest } from "@/lib/codeDigest";
+
+describe("codeDigest", () => {
+ it("reads a Python module's docstring and its top-level definitions", () => {
+ const text = [
+ "#!/usr/bin/env python3",
+ '"""Gmail Deep Clean CLI utility.',
+ "",
+ "Scans the connected Gmail account and proposes deletions.",
+ '"""',
+ "from __future__ import annotations",
+ "",
+ "import argparse",
+ "",
+ "class Cleaner:",
+ " def run(self) -> None:",
+ " pass",
+ "",
+ "async def async_main(args: argparse.Namespace) -> int:",
+ " return 0",
+ "",
+ "def _private() -> None:",
+ " pass",
+ "",
+ "def main() -> int:",
+ " return 0",
+ "",
+ ].join("\n");
+ const digest = codeDigest("scripts/gmail_deep_clean.py", text);
+ expect(digest.language).toBe("python");
+ expect(digest.lines).toBe(21);
+ expect(digest.description).toBe("Gmail Deep Clean CLI utility.");
+ expect(digest.symbols).toEqual([
+ { kind: "class", name: "Cleaner" },
+ { kind: "function", name: "async_main" },
+ { kind: "function", name: "main" },
+ ]);
+ expect(digest.json).toBeNull();
+ expect(digest.diff).toBeNull();
+ });
+
+ it("reads a docstring that opens after leading comments and closes on one line", () => {
+ const text = '# -*- coding: utf-8 -*-\n"""One-liner."""\n\ndef go():\n pass\n';
+ expect(codeDigest("x.py", text).description).toBe("One-liner.");
+ });
+
+ it("reads a TypeScript module's leading block comment and exported definitions", () => {
+ const text = [
+ "/**",
+ " * The rail — every run, newest first.",
+ " *",
+ " * Second paragraph, not part of the summary.",
+ " */",
+ 'import { x } from "y";',
+ "",
+ "export const LIMIT = 12;",
+ "export function toRows(a: string): string[] { return [a]; }",
+ "const helper = async (a: number): Promise<void> => {};",
+ "export default class Rail {}",
+ "",
+ ].join("\n");
+ const digest = codeDigest("src/rail.ts", text);
+ expect(digest.description).toBe("The rail — every run, newest first.");
+ expect(digest.symbols).toEqual([
+ { kind: "const", name: "LIMIT" },
+ { kind: "function", name: "toRows" },
+ { kind: "function", name: "helper" },
+ { kind: "class", name: "Rail" },
+ ]);
+ });
+
+ it("reads a shell script's comment header and its functions", () => {
+ const text = "#!/usr/bin/env bash\n# Rebuild the bundle.\n# Then restart.\n\nset -e\nbuild() {\n npm run build\n}\nfunction restart {\n :\n}\n";
+ const digest = codeDigest("rebuild.sh", text);
+ expect(digest.description).toBe("Rebuild the bundle. Then restart.");
+ expect(digest.symbols.map((s) => s.name)).toEqual(["build", "restart"]);
+ });
+
+ it("reads a PowerShell help block's synopsis", () => {
+ const text = "<#\n.SYNOPSIS\nInstalls the thing.\n.DESCRIPTION\nLong text.\n#>\nfunction Install-Thing {\n}\n";
+ const digest = codeDigest("install.ps1", text);
+ expect(digest.description).toBe("Installs the thing.");
+ expect(digest.symbols).toEqual([{ kind: "function", name: "Install-Thing" }]);
+ });
+
+ it("describes a JSON document by its shape", () => {
+ expect(codeDigest("out.json", '{"a": 1, "b": [1, 2], "c": null}').json).toEqual({
+ kind: "object",
+ keys: ["a", "b", "c"],
+ count: 3,
+ });
+ expect(codeDigest("rows.json", "[1, 2, 3]").json).toEqual({ kind: "array", count: 3 });
+ expect(codeDigest("events.jsonl", '{"a":1}\n{"a":2}\n\n').json).toEqual({
+ kind: "array",
+ count: 2,
+ });
+ expect(codeDigest("broken.json", "{not json").json).toBeNull();
+ });
+
+ it("lists a patch's files with their added and removed lines", () => {
+ const text = [
+ "From abc Mon Sep 17 00:00:00 2001",
+ "Subject: [PATCH 1/2] fix(rail): keep the newest run on top",
+ "",
+ "diff --git a/src/rail.ts b/src/rail.ts",
+ "--- a/src/rail.ts",
+ "+++ b/src/rail.ts",
+ "@@ -1,3 +1,4 @@",
+ " keep",
+ "-old",
+ "+new",
+ "+newer",
+ "diff --git a/README.md b/README.md",
+ "--- a/README.md",
+ "+++ b/README.md",
+ "@@ -1 +1 @@",
+ "-a",
+ "+b",
+ "",
+ ].join("\n");
+ const digest = codeDigest("0001-fix.patch", text);
+ expect(digest.description).toBe("fix(rail): keep the newest run on top");
+ expect(digest.diff).toEqual([
+ { path: "src/rail.ts", added: 2, removed: 1 },
+ { path: "README.md", added: 1, removed: 1 },
+ ]);
+ });
+
+ it("reads a plain unified diff without git headers", () => {
+ const text = "--- a/x.py\n+++ b/x.py\n@@ -1 +1 @@\n-a\n+b\n";
+ expect(codeDigest("change.diff", text).diff).toEqual([{ path: "x.py", added: 1, removed: 1 }]);
+ });
+
+ it("yields the line count alone for an unknown language", () => {
+ const digest = codeDigest("notes.txt", "a\nb\nc");
+ expect(digest).toEqual({
+ language: "txt",
+ lines: 3,
+ description: null,
+ symbols: [],
+ json: null,
+ diff: null,
+ });
+ expect(codeDigest("empty.txt", "").lines).toBe(0);
+ });
+
+ it("caps a long description with an ellipsis", () => {
+ const long = "x".repeat(600);
+ const description = codeDigest("a.py", `"""${long}"""`).description ?? "";
+ expect(description.length).toBeLessThanOrEqual(320);
+ expect(description.endsWith("…")).toBe(true);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/lib/codeDigest.ts b/jarvis/ui/web/frontend/src/lib/codeDigest.ts
new file mode 100644
index 0000000000..d3f5a11ddf
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/codeDigest.ts
@@ -0,0 +1,343 @@
+/**
+ * What a code deliverable IS, read from its text — pure, by filename and
+ * content, no highlighter involved.
+ *
+ * The output page (`OutputPreview`) draws a script, a patch or a data file as
+ * a card that says what the file does BEFORE it shows a line of it: the
+ * module's own description (a Python docstring, a leading `/** … *\/` or `#`
+ * comment block), the definitions it holds, a patch's file list with its
+ * `+`/`−` counts, a JSON document's shape. The reader scrolling through a run
+ * sees what was made; the source itself stays one click away, on the same
+ * card and under Code / Files. Everything here degrades to "nothing found"
+ * rather than guessing — an unknown language yields the line count alone.
+ */
+import { artifactLanguage } from "@/lib/artifactKind";
+
+export interface CodeSymbol {
+ kind: "function" | "class" | "const";
+ name: string;
+}
+
+export interface DiffFile {
+ path: string;
+ added: number;
+ removed: number;
+}
+
+export type JsonShape =
+ | { kind: "object"; keys: string[]; count: number }
+ | { kind: "array"; count: number };
+
+export interface CodeDigest {
+ /** The Shiki language of the file ("txt" when unknown). */
+ language: string;
+ lines: number;
+ /** The file's own description — the first paragraph of its leading doc comment. */
+ description: string | null;
+ /** Top-level definitions in file order (functions, classes, exported constants). */
+ symbols: CodeSymbol[];
+ /** A JSON / JSONL document's shape, when the file is one. */
+ json: JsonShape | null;
+ /** A patch's touched files, when the file is one. */
+ diff: DiffFile[] | null;
+}
+
+const MAX_DESCRIPTION = 320;
+const MAX_SYMBOLS = 40;
+const MAX_JSON_KEYS = 24;
+
+function countLines(text: string): number {
+ if (text.length === 0) return 0;
+ const trimmed = text.endsWith("\n") ? text.slice(0, -1) : text;
+ return trimmed.split("\n").length;
+}
+
+/** First paragraph of a comment body, joined to one line and capped. */
+function firstParagraph(lines: string[]): string | null {
+ const out: string[] = [];
+ for (const raw of lines) {
+ const line = raw.trim();
+ if (line.length === 0) {
+ if (out.length > 0) break;
+ continue;
+ }
+ out.push(line);
+ }
+ if (out.length === 0) return null;
+ const text = out.join(" ").replace(/\s+/g, " ").trim();
+ if (text.length <= MAX_DESCRIPTION) return text;
+ return `${text.slice(0, MAX_DESCRIPTION - 1).trimEnd()}…`;
+}
+
+// --- Python -----------------------------------------------------------------
+
+const PY_PREAMBLE = /^(#.*|\s*|from __future__ import .*|import __future__.*)$/;
+
+function pythonDescription(lines: string[]): string | null {
+ let i = 0;
+ while (i < lines.length && PY_PREAMBLE.test(lines[i])) i++;
+ if (i >= lines.length) return null;
+ const open = /^\s*[rRuUbB]{0,2}("""|''')/.exec(lines[i]);
+ if (!open) return null;
+ const quote = open[1];
+ const first = lines[i].slice(open[0].length);
+ const body: string[] = [];
+ const endOnFirst = first.indexOf(quote);
+ if (endOnFirst !== -1) return firstParagraph([first.slice(0, endOnFirst)]);
+ body.push(first);
+ for (let j = i + 1; j < lines.length; j++) {
+ const end = lines[j].indexOf(quote);
+ if (end !== -1) {
+ body.push(lines[j].slice(0, end));
+ break;
+ }
+ body.push(lines[j]);
+ }
+ return firstParagraph(body);
+}
+
+const PY_DEF = /^(?:async\s+)?def\s+([A-Za-z_]\w*)/;
+const PY_CLASS = /^class\s+([A-Za-z_]\w*)/;
+
+function pythonSymbols(lines: string[]): CodeSymbol[] {
+ const out: CodeSymbol[] = [];
+ for (const line of lines) {
+ let m = PY_CLASS.exec(line);
+ if (m) {
+ out.push({ kind: "class", name: m[1] });
+ continue;
+ }
+ m = PY_DEF.exec(line);
+ if (m && !m[1].startsWith("_")) out.push({ kind: "function", name: m[1] });
+ }
+ return out;
+}
+
+// --- JavaScript / TypeScript ---------------------------------------------------
+
+function blockCommentDescription(lines: string[]): string | null {
+ let i = 0;
+ while (i < lines.length && (/^\s*$/.test(lines[i]) || lines[i].startsWith("#!"))) i++;
+ if (i >= lines.length) return null;
+ const head = lines[i].trim();
+ if (head.startsWith("/*")) {
+ const body: string[] = [];
+ const first = head.replace(/^\/\*+/, "");
+ const closeOnFirst = first.indexOf("*/");
+ if (closeOnFirst !== -1) return firstParagraph([first.slice(0, closeOnFirst)]);
+ body.push(first);
+ for (let j = i + 1; j < lines.length; j++) {
+ const raw = lines[j].trim();
+ const close = raw.indexOf("*/");
+ body.push((close === -1 ? raw : raw.slice(0, close)).replace(/^\*\s?/, ""));
+ if (close !== -1) break;
+ }
+ return firstParagraph(body);
+ }
+ if (head.startsWith("//")) {
+ const body: string[] = [];
+ for (let j = i; j < lines.length; j++) {
+ const line = lines[j].trim();
+ if (!line.startsWith("//")) break;
+ body.push(line.replace(/^\/\/\s?/, ""));
+ }
+ return firstParagraph(body);
+ }
+ return null;
+}
+
+const JS_FUNCTION = /^(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)/;
+const JS_CLASS = /^(?:export\s+)?(?:default\s+)?(?:abstract\s+)?class\s+([A-Za-z_$][\w$]*)/;
+const JS_ARROW =
+ /^(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=]+)?=\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*(?::\s*[^=]+)?=>/;
+const JS_EXPORT_CONST = /^export\s+(?:const|let|var)\s+([A-Za-z_$][\w$]*)/;
+
+function jsSymbols(lines: string[]): CodeSymbol[] {
+ const out: CodeSymbol[] = [];
+ for (const line of lines) {
+ let m = JS_CLASS.exec(line);
+ if (m) {
+ out.push({ kind: "class", name: m[1] });
+ continue;
+ }
+ m = JS_FUNCTION.exec(line);
+ if (m) {
+ out.push({ kind: "function", name: m[1] });
+ continue;
+ }
+ m = JS_ARROW.exec(line);
+ if (m) {
+ out.push({ kind: "function", name: m[1] });
+ continue;
+ }
+ m = JS_EXPORT_CONST.exec(line);
+ if (m) out.push({ kind: "const", name: m[1] });
+ }
+ return out;
+}
+
+// --- Shell / PowerShell -------------------------------------------------------
+
+function hashCommentDescription(lines: string[]): string | null {
+ let i = 0;
+ while (i < lines.length && (/^\s*$/.test(lines[i]) || lines[i].startsWith("#!"))) i++;
+ if (i < lines.length && lines[i].trim().startsWith("<#")) {
+ const body: string[] = [];
+ for (let j = i; j < lines.length; j++) {
+ const line = lines[j].replace(/^\s*<#/, "");
+ const close = line.indexOf("#>");
+ if (close !== -1) {
+ body.push(line.slice(0, close));
+ break;
+ }
+ body.push(line);
+ }
+ // A PowerShell help block leads with `.SYNOPSIS`; the text under it, up to
+ // the next `.KEYWORD`, is the description.
+ const keyword = (l: string) => /^\s*\.\w+/.test(l);
+ const synopsis = body.findIndex((l) => /^\s*\.SYNOPSIS/i.test(l));
+ if (synopsis === -1) return firstParagraph(body.filter((l) => !keyword(l)));
+ const under = body.slice(synopsis + 1);
+ const next = under.findIndex(keyword);
+ return firstParagraph(next === -1 ? under : under.slice(0, next));
+ }
+ const body: string[] = [];
+ for (let j = i; j < lines.length; j++) {
+ const line = lines[j].trim();
+ if (!line.startsWith("#")) break;
+ if (/^#\s*-\*-/.test(line) || /^#\s*(?:shellcheck|noqa)/i.test(line)) continue;
+ body.push(line.replace(/^#+\s?/, ""));
+ }
+ return firstParagraph(body);
+}
+
+const SH_FUNCTION = /^(?:function\s+)?([A-Za-z_][\w-]*)\s*\(\)\s*\{?/;
+const SH_FUNCTION_KW = /^function\s+([A-Za-z_][\w-]*)/;
+
+function shellSymbols(lines: string[]): CodeSymbol[] {
+ const out: CodeSymbol[] = [];
+ for (const line of lines) {
+ const m = SH_FUNCTION.exec(line) ?? SH_FUNCTION_KW.exec(line);
+ if (m) out.push({ kind: "function", name: m[1] });
+ }
+ return out;
+}
+
+// --- JSON -----------------------------------------------------------------------
+
+function jsonShape(text: string, jsonl: boolean): JsonShape | null {
+ if (jsonl) {
+ const records = text.split("\n").filter((l) => l.trim().length > 0).length;
+ return { kind: "array", count: records };
+ }
+ try {
+ const value: unknown = JSON.parse(text);
+ if (Array.isArray(value)) return { kind: "array", count: value.length };
+ if (value !== null && typeof value === "object") {
+ const keys = Object.keys(value as Record<string, unknown>);
+ return { kind: "object", keys: keys.slice(0, MAX_JSON_KEYS), count: keys.length };
+ }
+ } catch {
+ // Not a JSON document after all (a fragment, a comment-laden config):
+ // the card falls back to the line count, which is always true.
+ }
+ return null;
+}
+
+// --- Patches --------------------------------------------------------------------
+
+const DIFF_GIT = /^diff --git a\/(.+?) b\/(.+)$/;
+const DIFF_NEW = /^\+\+\+ (?:b\/)?(.+)$/;
+
+function diffFiles(lines: string[]): DiffFile[] {
+ const out: DiffFile[] = [];
+ let current: DiffFile | null = null;
+ let sawGitHeader = false;
+ for (const line of lines) {
+ let m = DIFF_GIT.exec(line);
+ if (m) {
+ current = { path: m[2], added: 0, removed: 0 };
+ out.push(current);
+ sawGitHeader = true;
+ continue;
+ }
+ m = DIFF_NEW.exec(line);
+ if (m) {
+ // A plain unified diff has no `diff --git` line; `+++` names the file.
+ if (!sawGitHeader || current === null) {
+ current = { path: m[1].trim(), added: 0, removed: 0 };
+ out.push(current);
+ }
+ continue;
+ }
+ if (line.startsWith("--- ")) continue;
+ if (current === null) continue;
+ if (line.startsWith("+")) current.added++;
+ else if (line.startsWith("-")) current.removed++;
+ }
+ return out;
+}
+
+/** A `git format-patch` subject, without the `[PATCH n/m]` tag. */
+function patchDescription(lines: string[]): string | null {
+ for (const line of lines) {
+ if (DIFF_GIT.test(line) || line.startsWith("--- ")) break;
+ const m = /^Subject:\s*(?:\[PATCH[^\]]*\]\s*)?(.+)$/.exec(line);
+ if (m) return m[1].trim();
+ }
+ return null;
+}
+
+// --- The digest -------------------------------------------------------------------
+
+export function codeDigest(path: string, text: string): CodeDigest {
+ const language = artifactLanguage(path);
+ const lines = text.split("\n");
+ const digest: CodeDigest = {
+ language,
+ lines: countLines(text),
+ description: null,
+ symbols: [],
+ json: null,
+ diff: null,
+ };
+ switch (language) {
+ case "python":
+ digest.description = pythonDescription(lines);
+ digest.symbols = pythonSymbols(lines);
+ break;
+ case "typescript":
+ case "tsx":
+ case "javascript":
+ case "jsx":
+ digest.description = blockCommentDescription(lines);
+ digest.symbols = jsSymbols(lines);
+ break;
+ case "bash":
+ case "powershell":
+ digest.description = hashCommentDescription(lines);
+ digest.symbols = shellSymbols(lines);
+ break;
+ case "json":
+ digest.json = jsonShape(text, path.toLowerCase().endsWith(".jsonl"));
+ break;
+ case "diff":
+ digest.description = patchDescription(lines);
+ digest.diff = diffFiles(lines);
+ break;
+ case "rust":
+ case "go":
+ case "java":
+ case "c":
+ case "cpp":
+ case "csharp":
+ case "kotlin":
+ case "swift":
+ digest.description = blockCommentDescription(lines);
+ break;
+ default:
+ break;
+ }
+ digest.symbols = digest.symbols.slice(0, MAX_SYMBOLS);
+ return digest;
+}
diff --git a/jarvis/ui/web/frontend/src/lib/runRequest.test.ts b/jarvis/ui/web/frontend/src/lib/runRequest.test.ts
new file mode 100644
index 0000000000..5cfbf8fbca
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/runRequest.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it } from "vitest";
+
+import { cleanRequest, requestHeadline } from "@/lib/runRequest";
+
+describe("cleanRequest", () => {
+ it("drops the builder's supporting-context tail and collapses whitespace", () => {
+ const utterance =
+ "No, just spawn them.\n\nSupporting context from the recent conversation " +
+ "(use only to resolve references; the underlying request remains authoritative):\n" +
+ "- Conversation context (recent turns, newest last): …";
+ expect(cleanRequest(utterance)).toBe("No, just spawn them.");
+ });
+
+ it("returns a plain request whole", () => {
+ expect(cleanRequest(" Write notes ")).toBe("Write notes");
+ expect(cleanRequest(undefined)).toBe("");
+ });
+});
+
+describe("requestHeadline", () => {
+ it("keeps a short request as it is", () => {
+ expect(requestHeadline("Write notes")).toBe("Write notes");
+ });
+
+ it("takes the first sentence when it is short enough", () => {
+ expect(
+ requestHeadline(
+ "Please start five new cloud coding instances. They should all do the same thing and " +
+ "then report back in great detail on what happened.",
+ ),
+ ).toBe("Please start five new cloud coding instances.");
+ });
+
+ it("cuts a long single sentence at a word boundary with an ellipsis", () => {
+ const text =
+ "a quick deep dive that analyses all my e-mails through the Gmail plugin and then " +
+ "tells me which ones matter and which ones I can delete";
+ const headline = requestHeadline(text, 60);
+ expect(headline.endsWith("…")).toBe(true);
+ expect(headline.length).toBeLessThanOrEqual(61);
+ expect(headline).toBe("a quick deep dive that analyses all my e-mails through the…");
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/lib/runRequest.ts b/jarvis/ui/web/frontend/src/lib/runRequest.ts
new file mode 100644
index 0000000000..4878812c47
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/runRequest.ts
@@ -0,0 +1,42 @@
+/**
+ * The user's real ask out of a run's recorded request — what a rail row, a
+ * stage title and an output page call the run.
+ *
+ * The run list (`/api/outputs`) already strips the standing quality
+ * directive the mission builder prepends (`clean_request_body`). What it
+ * leaves in place is the TAIL the builder appends on a no-interpretation
+ * spawn: "Supporting context from the recent conversation (use only to
+ * resolve references; …):" followed by the transcript hints. That tail is
+ * plumbing for the worker, not part of the request, and it made half the
+ * rail read "…Supporting context from the recent conversation (use only to
+ * resolve references; the underlying request remains authoritative): - …"
+ * (2026-08-25). Pure text; no I/O.
+ */
+
+/** The builder's supporting-context tail — everything from its lead on. */
+const SUPPORTING_CONTEXT_RE =
+ /\s*Supporting context from the recent conversation\b[\s\S]*$/i;
+
+/** The user's request without the worker-facing tail, whitespace collapsed. */
+export function cleanRequest(utterance: string | null | undefined): string {
+ const text = (utterance ?? "").replace(SUPPORTING_CONTEXT_RE, "");
+ return text.replace(/\s+/g, " ").trim();
+}
+
+/** Default headline length — one comfortable line at the stage's h1 size. */
+export const HEADLINE_MAX_CHARS = 96;
+
+/**
+ * A headline out of a request: its first sentence when that is short enough,
+ * otherwise the first `max` characters cut at a word boundary with an
+ * ellipsis. A request that is already short comes back whole.
+ */
+export function requestHeadline(text: string, max: number = HEADLINE_MAX_CHARS): string {
+ const clean = cleanRequest(text);
+ if (clean.length <= max) return clean;
+ const sentence = /^(.{12,}?[.!?])\s/.exec(clean)?.[1];
+ if (sentence && sentence.length <= max) return sentence;
+ const cut = clean.slice(0, max);
+ const space = cut.lastIndexOf(" ");
+ return `${(space > max / 2 ? cut.slice(0, space) : cut).replace(/[\s,;:\-–—(]+$/, "")}…`;
+}
diff --git a/jarvis/ui/web/frontend/src/views/VisualizationView.runs.test.tsx b/jarvis/ui/web/frontend/src/views/VisualizationView.runs.test.tsx
index ada1cab296..7c7e40dada 100644
--- a/jarvis/ui/web/frontend/src/views/VisualizationView.runs.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/VisualizationView.runs.test.tsx
@@ -5,8 +5,10 @@
*
* Contracts:
* - a run without a page or picture shows as a run row; its stage opens on
- * Files, with the summary / reason it ended above the files; the empty
- * state appears only when there are no runs at all,
+ * Preview as a composed output page (the answer, the reason it ended, its
+ * files in place), with Files one tab away carrying the notes above the
+ * reader; the empty state appears only when there are no runs at all,
+ * - the rail narrows to artifacts or outputs and back, remembering the pick,
* - Continue / Restart gating per status, the needs-review card, the live
* continuation chip that jumps to the child, hold-to-abort while running,
* - Files: clean paths with primary files first, no direct download, the
@@ -143,8 +145,13 @@ const REPORT = file("tasks/019edf/artifacts/files/report.md", {
preview: "# Report",
});
+/** The stage opens on Preview; the Files reader is one click away. */
+async function openFiles() {
+ fireEvent.click(await screen.findByTestId("visualization-tab-files"));
+}
+
describe("VisualizationView — runs without an artifact", () => {
- it("lists a page-less run as a run row and opens it on Files with its notes", async () => {
+ it("lists a page-less run as a run row and opens it on Preview as a page, Files one tab away", async () => {
installFetchMock(
[
run({
@@ -166,18 +173,70 @@ 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 stage opens on Files (there is no page to preview) …
- const filesTab = await screen.findByTestId("visualization-tab-files");
- expect(filesTab.getAttribute("aria-selected")).toBe("true");
- expect(screen.queryByTestId("visualization-tab-preview")).toBeNull();
- // … with the summary above the files, and the file itself in the reader.
+ // 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");
+ expect(screen.getByTestId("visualization-tab-files")).toBeDefined();
+ expect(screen.getByTestId("visualization-tab-run")).toBeDefined();
+ // … and the page composed from the run: headline, the answer, the file in place.
+ const page = await screen.findByTestId("output-preview");
+ expect(within(page).getByTestId("output-preview-title").textContent).toBe("Write notes");
+ await within(page).findByTestId("output-preview-answer");
+ expect(within(page).getAllByText("Three notes, saved.").length).toBeGreaterThan(0);
+ await waitFor(() =>
+ expect(within(page).getAllByTestId("output-preview-file")).toHaveLength(1),
+ );
+ // Files: the notes above the reader, the file itself in it.
+ await openFiles();
await screen.findByTestId("run-notes");
- expect(screen.getAllByText("Three notes, saved.").length).toBeGreaterThan(0);
await waitFor(() => expect(screen.getByTestId("artifact-path").textContent).toBe("notes.md"));
// The run status sits in the toolbar, one badge.
expect(screen.getByTestId("run-status-badge").textContent).toContain("success");
});
+ it("narrows the rail to artifacts or outputs and remembers the pick", async () => {
+ window.localStorage.removeItem("jarvis.artifacts.rail-filter");
+ installFetchMock(
+ [
+ run({ slug: "page-run", utterance: "Draw a dashboard", status: "success" }),
+ run({ slug: "notes-run", utterance: "Write notes", status: "success" }),
+ ],
+ {
+ "page-run": [
+ file("tasks/t1/artifacts/files/dashboard.html", {
+ preview: "<title>Sales</title>",
+ }),
+ ],
+ "notes-run": [file("tasks/t2/artifacts/files/notes.md")],
+ },
+ );
+
+ renderView();
+
+ await screen.findAllByTestId("visualization-artifact-row");
+ await screen.findAllByTestId("visualization-run-row");
+ const filter = screen.getByTestId("visualization-filter");
+ expect(within(filter).getByTestId("visualization-filter-all").textContent).toContain("2");
+
+ fireEvent.click(within(filter).getByTestId("visualization-filter-artifacts"));
+ 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");
+
+ 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");
+
+ 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);
+ window.localStorage.removeItem("jarvis.artifacts.rail-filter");
+ });
+
it("says so only when there are no runs at all", async () => {
installFetchMock([], {});
renderView();
@@ -219,6 +278,12 @@ describe("VisualizationView — runs without an artifact", () => {
renderView();
+ // The output page leads with why the run ended …
+ const outcome = await screen.findByTestId("output-preview-outcome");
+ expect(within(outcome).getAllByText("Needs review").length).toBeGreaterThan(0);
+ expect(within(outcome).getByText("critic_loop_exhausted")).toBeDefined();
+ // … and Files carries the same verdict above the reader.
+ await openFiles();
await waitFor(() => expect(screen.getByTestId("output-needs-review")).toBeDefined());
expect(screen.getAllByText("Needs review").length).toBeGreaterThan(0);
expect(screen.getAllByText("critic_loop_exhausted").length).toBeGreaterThan(0);
@@ -241,6 +306,10 @@ describe("VisualizationView — runs without an artifact", () => {
renderView();
+ const outcome = await screen.findByTestId("output-preview-outcome");
+ expect(within(outcome).getByText("task_error")).toBeDefined();
+ expect(within(outcome).queryByText("Needs review")).toBeNull();
+ await openFiles();
await waitFor(() => expect(screen.getByTestId("output-terminal-reason")).toBeDefined());
expect(screen.queryByTestId("output-needs-review")).toBeNull();
expect(screen.getByTestId("run-status-badge").textContent).toContain("error");
@@ -335,6 +404,7 @@ describe("VisualizationView — the Files tab", () => {
);
renderView();
+ await openFiles();
await waitFor(() => expect(screen.getAllByTestId("artifact-path")).toHaveLength(3));
expect(screen.getAllByTestId("artifact-path").map((node) => node.textContent)).toEqual([
@@ -350,8 +420,9 @@ describe("VisualizationView — the Files tab", () => {
});
renderView();
+ await openFiles();
- await waitFor(() => expect(screen.getByText("report.md")).toBeDefined());
+ await waitFor(() => expect(screen.getByTestId("artifact-path").textContent).toBe("report.md"));
expect(screen.queryByText("tasks/019edf/artifacts/files/report.md")).toBeNull();
expect(screen.queryByTitle("Download")).toBeNull();
@@ -378,8 +449,9 @@ describe("VisualizationView — the Files tab", () => {
const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);
renderView();
+ await openFiles();
- await waitFor(() => expect(screen.getByText("report.md")).toBeDefined());
+ await waitFor(() => expect(screen.getByTestId("artifact-path").textContent).toBe("report.md"));
fireEvent.click(screen.getByTitle("Change how this opens"));
fireEvent.click(await screen.findByText("Browser"));
@@ -413,8 +485,9 @@ describe("VisualizationView — the Files tab", () => {
const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);
renderView();
+ await openFiles();
- await waitFor(() => expect(screen.getByText("report.md")).toBeDefined());
+ await waitFor(() => expect(screen.getByTestId("artifact-path").textContent).toBe("report.md"));
// The remembered preference is a query of its own; "Open" asks the chooser
// until it has resolved, so wait for it before clicking.
await waitFor(() =>
@@ -463,7 +536,11 @@ describe("VisualizationView — the Files tab", () => {
expect(el).toBeTruthy();
return el as HTMLIFrameElement;
});
- expect(iframe.getAttribute("src")).toBe(`/api/outputs/html-slug/files/${HTML_PATH}/page`);
+ // The reader's frame follows the app's theme through the same `?theme=`
+ // query the stage appends.
+ expect(iframe.getAttribute("src")).toMatch(
+ new RegExp(`^/api/outputs/html-slug/files/${HTML_PATH.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/page\\?theme=(light|dark)$`),
+ );
expect(iframe.getAttribute("sandbox")).toBe("allow-scripts");
expect(screen.queryByText(HTML_SOURCE)).toBeNull();
// Rendered mode never fetches the raw text.
diff --git a/jarvis/ui/web/frontend/src/views/VisualizationView.tsx b/jarvis/ui/web/frontend/src/views/VisualizationView.tsx
index 9b28959a00..918589df0c 100644
--- a/jarvis/ui/web/frontend/src/views/VisualizationView.tsx
+++ b/jarvis/ui/web/frontend/src/views/VisualizationView.tsx
@@ -18,26 +18,32 @@ import {
import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";
+import { OutputPreview } from "@/components/visualization/OutputPreview";
import { RunGraphPanel } from "@/components/visualization/RunGraphPanel";
import {
RunActions,
RunFiles,
RunStatusBadge,
+ deliverableFiles,
} from "@/components/visualization/RunPanels";
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 { useEventStore } from "@/store/events";
import { openExternalUrl } from "@/lib/openExternal";
import { endMissionDrag, startMissionDrag } from "@/lib/missionDnd";
import {
artifactDownloadUrl,
+ artifactOpenUrl,
revealArtifact,
useArtifactFile,
useArtifactsForOutput,
useOutputsCapabilities,
useOutputsList,
+ type ArtifactSummary,
type OutputStatus,
type OutputSummary,
} from "@/hooks/useOutputs";
@@ -71,6 +77,14 @@ import {
* Restart, the GitHub link). One place for what Jarvis and its agents made,
* not two.
*
+ * 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.
+ *
* 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
@@ -138,7 +152,43 @@ export function parseArtifactUtterance(
/** What a run is called when it has no page title of its own. */
function runTitle(run: OutputSummary): string {
- return parseArtifactUtterance(run.utterance)?.title || run.utterance?.trim() || run.slug;
+ 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";
+
+function readRailFilter(): RailFilter {
+ try {
+ const stored = window.localStorage.getItem(RAIL_FILTER_KEY);
+ if (stored === "artifacts" || stored === "outputs") return stored;
+ } catch {
+ // Storage can be unavailable (private window, blocked site data) — "all" then.
+ }
+ return "all";
+}
+
+function storeRailFilter(filter: RailFilter): void {
+ try {
+ window.localStorage.setItem(RAIL_FILTER_KEY, filter);
+ } catch {
+ // A remembered filter 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)));
}
/** The rail row's timestamp — what tells two same-named artifacts apart. */
@@ -219,7 +269,21 @@ export function VisualizationView() {
[runs],
);
- const rows = useMemo(() => buildRailRows(runs, visuals, building), [runs, visuals, building]);
+ const allRows = useMemo(() => buildRailRows(runs, visuals, building), [runs, visuals, building]);
+ const [filter, setFilterState] = useState<RailFilter>(readRailFilter);
+ const setFilter = useCallback((next: RailFilter) => {
+ setFilterState(next);
+ storeRailFilter(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],
+ );
/* 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.
@@ -292,6 +356,20 @@ export function VisualizationView() {
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). */
+ 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]);
+
const loading = outputs.isLoading || gallery.isLoading;
const activeKey =
target.building && target.run
@@ -329,14 +407,17 @@ export function VisualizationView() {
<div className="flex min-h-0 flex-1">
{/* Rail — builds in progress first, then every artifact and run, newest first. */}
<aside className="flex w-72 shrink-0 flex-col border-r border-border">
- <p className="border-b border-border px-3 py-2 text-[11px] font-medium uppercase tracking-wide text-muted-foreground">
- {t("visualization.rail")}
- {rows.length > 0 && (
- <span className="ml-1.5 normal-case tracking-normal text-muted-foreground/70">
- · {rows.length}
- </span>
- )}
- </p>
+ <div className="flex flex-col gap-2 border-b border-border px-3 py-2">
+ <p className="text-[11px] font-medium uppercase tracking-wide text-muted-foreground">
+ {t("visualization.rail")}
+ {rows.length > 0 && (
+ <span className="ml-1.5 normal-case tracking-normal text-muted-foreground/70">
+ · {rows.length}
+ </span>
+ )}
+ </p>
+ <RailFilterControl filter={filter} counts={counts} onChange={setFilter} />
+ </div>
<ScrollArea className="min-h-0 flex-1">
<ul className="space-y-1 p-2" data-testid="visualization-artifacts">
{rows.map((row) => (
@@ -382,6 +463,55 @@ 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,
+}: {
+ filter: RailFilter;
+ counts: Record<RailFilter, number>;
+ onChange: (next: RailFilter) => 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 (
+ <div
+ role="radiogroup"
+ aria-label={t("visualization.rail_filter")}
+ className="flex items-center rounded-md border border-border bg-secondary/40 p-0.5"
+ 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(
+ "inline-flex flex-1 items-center justify-center gap-1 rounded px-1.5 py-1 text-[11px] font-medium transition-colors",
+ filter === id
+ ? "bg-background text-foreground shadow-sm"
+ : "text-muted-foreground hover:text-foreground",
+ )}
+ >
+ {label}
+ <span className="tabular-nums text-muted-foreground/70">{counts[id]}</span>
+ </button>
+ ))}
+ </div>
+ );
+}
+
function RailRowButton({
row,
active,
@@ -460,7 +590,7 @@ function RailRowButton({
<span className="block truncate">
{[
formatWhen(visual.mtime),
- parsed?.request || visual.utterance?.trim() || visual.name,
+ parsed?.request || cleanRequest(visual.utterance) || visual.name,
]
.filter(Boolean)
.join(" · ")}
@@ -511,9 +641,10 @@ function RailRowButton({
/* ------------------------------------------------------------------------- */
/**
- * The stage for one run: its artifact (when it has one) under Preview / Code,
- * every file under Files, the graph under Run. Keyed by run in the caller, so
- * a new run opens on its own default tab.
+ * The stage for one run: its artifact under Preview / Code when it drew one,
+ * the composed output page under Preview and the primary file's source under
+ * Code when it did not; every file under Files, the graph under Run. Keyed
+ * by run in the caller, so a new run opens on Preview.
*
* A run outside the rail's scan window arrives without artifacts in hand; its
* listing is read here (same cache entry the rail's scan fills) and the newest
@@ -530,7 +661,7 @@ function Stage({
onJumpToRun: (slug: string) => void;
}) {
const slug = run?.slug ?? pickedVisual?.slug ?? null;
- const listing = useArtifactsForOutput(run !== null && pickedVisual === null ? slug : null);
+ const listing = useArtifactsForOutput(run !== null ? slug : null);
const visual: VisualArtifact | null = useMemo(() => {
if (pickedVisual) return pickedVisual;
if (run === null) return null;
@@ -538,43 +669,78 @@ function Stage({
found.sort((a, b) => b.mtime - a.mtime);
return found[0] ?? null;
}, [pickedVisual, run, listing.data]);
+ // The output's primary file — what Code shows and the toolbar's file
+ // actions act on when the run drew no page: the first text deliverable.
+ const primary: ArtifactSummary | null = useMemo(() => {
+ if (visual !== null) return null;
+ return primaryTextFile(listing.data?.files ?? []);
+ }, [visual, listing.data]);
- const [mode, setMode] = useState<StageMode>(visual ? "preview" : "files");
+ const [mode, setMode] = useState<StageMode>("preview");
+ // "Open in Files" on the output page lands the reader on that file.
+ const [filesPath, setFilesPath] = useState<string | null>(null);
const currentId = visual ? visualId(visual) : null;
// A new artifact opens on its page, whatever tab the previous one was on; a
// run that turns out to have one (its listing just arrived) moves to it too.
useEffect(() => {
- setMode(currentId ? "preview" : "files");
+ setMode("preview");
}, [currentId]);
+ const openFile = useCallback((path: string) => {
+ setFilesPath(path);
+ setMode("files");
+ }, []);
return (
<>
<ArtifactToolbar
run={run}
visual={visual}
+ primary={primary}
mode={mode}
onMode={setMode}
onJumpToRun={onJumpToRun}
/>
<div className="min-h-0 flex-1" data-testid="visualization-stage">
{mode === "preview" && visual && <ArtifactStage visual={visual} />}
+ {mode === "preview" && !visual && run && (
+ <OutputPreview key={run.slug} run={run} onOpenFile={openFile} />
+ )}
{mode === "code" && visual && <ArtifactSource slug={visual.slug} path={visual.path} />}
- {mode === "files" && run && <RunFiles run={run} />}
+ {mode === "code" && !visual && run && primary && (
+ <ArtifactSource slug={run.slug} path={primary.path} />
+ )}
+ {mode === "files" && run && <RunFiles run={run} initialPath={filesPath} />}
{mode === "run" && run && <RunGraphPanel key={run.slug} run={run} />}
</div>
</>
);
}
+/** The `/view` page follows the app's theme like an artifact page does. */
+function withTheme(url: string | null, theme: string): string | null {
+ if (url === null) return null;
+ return url.includes("?") ? url : `${url}?theme=${theme}`;
+}
+
+/** The first deliverable whose bytes are text — the output's "source". */
+function primaryTextFile(files: ArtifactSummary[]): ArtifactSummary | null {
+ return (
+ deliverableFiles(files).find((f) => isTextKind(artifactKind(f.path, f.is_text))) ?? null
+ );
+}
+
function ArtifactToolbar({
run,
visual,
+ primary,
mode,
onMode,
onJumpToRun,
}: {
run: OutputSummary | null;
visual: VisualArtifact | null;
+ /** The output's primary text file when the run drew no page. */
+ primary: ArtifactSummary | null;
mode: StageMode;
onMode: (mode: StageMode) => void;
onJumpToRun: (slug: string) => void;
@@ -584,40 +750,57 @@ function ArtifactToolbar({
const capabilities = useOutputsCapabilities();
const parsed = parseArtifactUtterance(visual?.utterance ?? run?.utterance);
const slug = visual?.slug ?? run?.slug ?? "";
+ // The file the toolbar's Download / Reveal / Open act on: the artifact, or
+ // the output's primary file.
+ const file: { slug: string; path: string } | null = visual
+ ? { slug: visual.slug, path: visual.path }
+ : run && primary
+ ? { slug: run.slug, path: primary.path }
+ : null;
const onReveal = useCallback(async () => {
- if (!visual) return;
+ if (!file) return;
try {
- await revealArtifact(visual.slug, visual.path);
+ await revealArtifact(file.slug, file.path);
} catch {
pushToast("error", t("visualization.reveal_failed"));
}
- }, [visual, pushToast, t]);
+ }, [file, pushToast, t]);
const theme = useThemeValue();
const externalUrl = visual
? visual.kind === "page"
? `${artifactPageUrl(visual.slug, visual.path)}?theme=${theme}`
: visual.url
- : null;
+ : file
+ ? withTheme(artifactOpenUrl(file.slug, file.path), theme)
+ : null;
const title = visual?.title ?? (run ? runTitle(run) : "");
const caption = [
visual ? formatWhen(visual.mtime) : run ? formatWhen(runWhen(run)) : "",
visual ? formatSize(visual.size) : "",
run && typeof run.duration_s === "number" ? `${run.duration_s.toFixed(1)} s` : "",
- parsed?.request || (visual ? visual.utterance?.trim() || visual.name : ""),
+ parsed?.request ||
+ (visual ? cleanRequest(visual.utterance) || visual.name : run ? cleanRequest(run.utterance) : ""),
]
.filter(Boolean)
.join(" · ");
+ // Every run gets the same four tabs; Code is absent only when there is no
+ // source to show (a picture, a run that left no text file).
const tabs: Array<{ id: StageMode; label: string; Icon: typeof Eye; show: boolean }> = [
- { id: "preview", label: t("visualization.tab_preview"), Icon: Eye, show: visual !== null },
+ {
+ id: "preview",
+ label: t("visualization.tab_preview"),
+ Icon: Eye,
+ show: visual !== null || run !== null,
+ },
{
id: "code",
label: t("visualization.tab_code"),
Icon: Code2,
- show: visual !== null && (visual.kind === "page" || visual.kind === "vector"),
+ show: visual !== null ? visual.kind === "page" || visual.kind === "vector" : primary !== null,
},
{ id: "files", label: t("visualization.tab_files"), Icon: Files, show: run !== null },
{ id: "run", label: t("visualization.tab_run"), Icon: Workflow, show: run !== null },
@@ -677,7 +860,7 @@ function ArtifactToolbar({
{t("visualization.open_map_page")}
</Button>
)}
- {visual && externalUrl && (
+ {externalUrl && (
<Button
variant="ghost"
size="sm"
@@ -689,10 +872,10 @@ function ArtifactToolbar({
{t("visualization.open_external")}
</Button>
)}
- {visual && (
+ {file && (
<Button variant="ghost" size="sm" asChild>
<a
- href={artifactDownloadUrl(visual.slug, visual.path)}
+ href={artifactDownloadUrl(file.slug, file.path)}
download
title={t("visualization.download")}
aria-label={t("visualization.download")}
@@ -703,7 +886,7 @@ function ArtifactToolbar({
)}
{/* Desktop only: a headless host has no file manager to open, so the
button is absent rather than dead. */}
- {visual && capabilities.data?.native_file_actions && (
+ {file && capabilities.data?.native_file_actions && (
<Button
variant="ghost"
size="sm"