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): every run is a page — outputs composed in the artifact standard, a rail filter for artifacts vs outputs

rubenluetke10-beepdeb0ea90b9a0
diff --git a/jarvis/ui/web/artifact_view.py b/jarvis/ui/web/artifact_view.py
index cd2483fd2c..fae7deabc5 100644
--- a/jarvis/ui/web/artifact_view.py
+++ b/jarvis/ui/web/artifact_view.py
@@ -15,6 +15,8 @@ from __future__ import annotations
import html
import logging
+from jarvis.artifacts.design_guide import THEME_CSS
+
log = logging.getLogger(__name__)
_MARKDOWN_EXT = (".md", ".markdown")
@@ -46,55 +48,61 @@ ARTIFACT_PAGE_CSP = (
"base-uri 'none';"
)
-# Brand theme (matte black + signal yellow), kept in lockstep with the desktop
-# app's dark tokens (frontend/src/index.css) and video/src/intro/theme.ts. The
-# app is dark-first and this page opens from inside it, so it commits to the
-# brand look instead of following the OS light/dark preference.
+# The artifact design standard (jarvis/artifacts/design_guide.py): the app's
+# own tokens in both palettes, so a Markdown output opened in the browser
+# looks like the page it sits next to in the Artifacts section — and follows
+# the app's theme through the same `?theme=light|dark` query the artifact
+# stage appends, stamped on <html> by the SERVER (the page stays script-free
+# under VIEW_CSP; the guide's bootstrap script is for worker-written pages).
+# The tokens are the guide's verbatim; only the document rules below are this
+# page's own.
_PAGE_CSS = (
- "*{box-sizing:border-box}"
- "body{max-width:52rem;margin:0 auto;padding:2.5rem 1.5rem 4rem;"
- "font:15px/1.65 -apple-system,'Segoe UI',Roboto,'Helvetica Neue',Arial,sans-serif;"
- "color:#FAFAFA;background:#0A0A0A}"
- "h1,h2,h3,h4{line-height:1.3;margin:1.6em 0 .6em;font-weight:600}"
- "h1:first-child,h2:first-child{margin-top:0}"
- "h1{font-size:1.5rem;padding-bottom:.4em;border-bottom:1px solid rgba(255,255,255,0.10)}"
- "h2{font-size:1.2rem}h3{font-size:1.05rem}"
- "a{color:#FFD60A}a:hover{color:#E6BE00}"
- "p,ul,ol{margin:.7em 0}li{margin:.25em 0}"
- "pre{background:#141414;border:1px solid rgba(255,255,255,0.10);"
- "padding:1rem;overflow:auto;border-radius:10px}"
- "code{background:#181818;border:1px solid rgba(255,255,255,0.10);"
- "padding:.1em .35em;border-radius:5px;font-size:.92em}"
- "pre code{background:none;border:none;padding:0}"
- "table{border-collapse:collapse;margin:1em 0;display:block;overflow-x:auto}"
- "th,td{border:1px solid rgba(255,255,255,0.14);padding:.45rem .7rem}"
- "th{background:#141414;text-align:left}"
- "blockquote{border-left:3px solid #FFD60A;margin:1em 0;"
- "padding:.1em 0 .1em 1rem;color:#9A9A9A}"
- "img{max-width:100%;border-radius:8px}"
- "hr{border:none;border-top:1px solid rgba(255,255,255,0.10);margin:2em 0}"
- ".artifact-name{font-size:11px;letter-spacing:.14em;text-transform:uppercase;"
- "color:#9A9A9A;margin:0 0 1.6rem;display:flex;align-items:center;gap:.6em}"
- ".artifact-name::before{content:'';width:9px;height:9px;border-radius:50%;"
- "background:#FFD60A;box-shadow:0 0 10px rgba(255,214,10,0.35)}"
+ THEME_CSS + "\n"
+ "body{padding:40px 24px 64px}"
+ "main{max-width:72ch;margin:0 auto}"
+ "h1,h2,h3,h4{margin:1.6em 0 .5em}"
+ "main>h1:first-of-type{margin-top:0}"
+ "h4{font-size:14px;font-weight:600}"
+ "p,ul,ol{margin:.7em 0;max-width:none}li{margin:.25em 0}"
+ "pre{background:var(--bg-2);border:1px solid var(--line);padding:14px 16px;"
+ "overflow:auto;border-radius:var(--radius-sm);font-size:13px;line-height:1.5}"
+ "code{background:var(--bg-3);border:1px solid var(--line);padding:.1em .35em;"
+ "border-radius:4px}"
+ "pre code{background:none;border:none;padding:0;font-size:inherit}"
+ "table{border-collapse:collapse;margin:1em 0;display:block;overflow-x:auto;"
+ "font-size:14px}"
+ "th,td{border:1px solid var(--line);padding:.45rem .7rem;text-align:left}"
+ "th{background:var(--bg-2);font-weight:600}"
+ "blockquote{border-left:2px solid var(--accent);margin:1em 0;"
+ "padding:.1em 0 .1em 1rem;color:var(--ink-2)}"
+ "img{max-width:100%;border-radius:var(--radius-sm)}"
+ "hr{border:none;border-top:1px solid var(--line);margin:2em 0}"
+ ".artifact-name{margin:0 0 24px;padding-bottom:12px;border-bottom:1px solid var(--line)}"
)
-def _shell(title: str, body_html: str) -> str:
+_THEMES = frozenset({"light", "dark"})
+
+
+def _shell(title: str, body_html: str, theme: str | None) -> str:
+ stamp = f" data-theme='{theme}'" if theme in _THEMES else ""
return (
- "<!doctype html><html lang='en'><head><meta charset='utf-8'>"
+ f"<!doctype html><html lang='en'{stamp}><head><meta charset='utf-8'>"
f'<meta http-equiv="Content-Security-Policy" content="{VIEW_CSP}">'
"<meta name='viewport' content='width=device-width,initial-scale=1'>"
f"<title>{html.escape(title)}</title><style>{_PAGE_CSS}</style></head>"
- f"<body><p class='artifact-name'>{html.escape(title)}</p>{body_html}</body></html>"
+ f"<body><main><p class='artifact-name eyebrow'>{html.escape(title)}</p>"
+ f"{body_html}</main></body></html>"
)
-def render_artifact_html(filename: str, text: str) -> str:
+def render_artifact_html(filename: str, text: str, *, theme: str | None = None) -> str:
"""Return a complete HTML document rendering *text*.
Markdown filenames are rendered to HTML via the `markdown` library; everything
- else (and the no-markdown-lib fallback) is shown escaped in <pre>. Never raises.
+ else (and the no-markdown-lib fallback) is shown escaped in <pre>. *theme*
+ (``light`` / ``dark``, anything else ignored) pins the palette the way the
+ app's Artifacts stage pins it; without it the page follows the OS. Never raises.
"""
if filename.lower().endswith(_MARKDOWN_EXT):
try:
@@ -104,10 +112,10 @@ def render_artifact_html(filename: str, text: str) -> str:
text,
extensions=["extra", "sane_lists", "tables", "fenced_code"],
)
- return _shell(filename, body)
+ return _shell(filename, body, theme)
except Exception as exc: # noqa: BLE001 — a view must never 500
log.info("markdown render unavailable (%s) — serving raw <pre>", exc)
- return _shell(filename, f"<pre>{html.escape(text)}</pre>")
+ return _shell(filename, f"<pre>{html.escape(text)}</pre>", theme)
__all__ = ["ARTIFACT_PAGE_CSP", "VIEW_CSP", "render_artifact_html"]
diff --git a/jarvis/ui/web/frontend/src/components/outputs/ArtifactViewer.tsx b/jarvis/ui/web/frontend/src/components/outputs/ArtifactViewer.tsx
index 681893c207..e09ec14fee 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,
@@ -65,6 +63,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 +88,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
@@ -640,7 +645,8 @@ function HtmlPage({ slug, path }: { slug: string; path: string }) {
);
}
-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 +662,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 +711,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 +729,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..676155c3a0
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/outputs/MarkdownProse.tsx
@@ -0,0 +1,186 @@
+/**
+ * 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`; 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";
+
+/**
+ * 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>
+ );
+ }
+ 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) && 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/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..b3892c18c5
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/visualization/OutputPreview.tsx
@@ -0,0 +1,428 @@
+/**
+ * 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, code highlighted, a table as a table, a picture as a
+ * picture; 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, type ReactNode } from "react";
+import {
+ AlertTriangle,
+ ArrowUpRight,
+ FileCode2,
+ FileImage,
+ FileQuestion,
+ FileText,
+ Globe,
+ Loader2,
+ Table2,
+} from "lucide-react";
+
+import { cn } from "@/lib/utils";
+import { useT } from "@/i18n";
+import { artifactKind, formatBytes, isTextKind, type ArtifactKind } from "@/lib/artifactKind";
+import { cleanRequest, requestHeadline } from "@/lib/runRequest";
+import {
+ artifactInlineUrl,
+ useArtifactFile,
+ useArtifactsForOutput,
+ usePlanForOutput,
+ type ArtifactSummary,
+ type OutputStatus,
+ type OutputSummary,
+} from "@/hooks/useOutputs";
+import { CsvTable, 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) and a binary are named and left to Files, where the reader has the
+ * sandbox and the openers for them.
+ */
+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 (!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 = <SourceView 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>
+ );
+}
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 e4c7bd941c..ef7bbce45f 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -5002,7 +5002,7 @@
},
"visualization": {
"title": "Artefakte",
- "subtitle": "Alles, was deine Durchläufe erzeugt haben — Seiten und Bilder in voller Größe, jeder andere Durchlauf mit Dateien, Status und Steuerung; Quelltext und Durchlauf einen Tab entfernt",
+ "subtitle": "Alles, was deine Durchläufe erzeugt haben, jedes als Seite — Artefakte in voller Größe, jeder andere Output genauso aufbereitet; Quelltext, Dateien und Durchlauf einen Tab entfernt",
"refresh": "Aktualisieren",
"rail": "Artefakte & Durchläufe",
"building": "Wird gebaut …",
@@ -5013,6 +5013,23 @@
"tab_code": "Code",
"tab_files": "Dateien",
"tab_run": "Durchlauf",
+ "rail_filter": "Anzeigen",
+ "filter_all": "Alle",
+ "filter_artifacts": "Artefakte",
+ "filter_outputs": "Outputs",
+ "output_kind": "Output",
+ "preview_answer": "Antwort",
+ "preview_deliverables": "Dateien",
+ "preview_nothing": "Dieser Durchlauf hat weder eine Antwort noch Dateien hinterlassen.",
+ "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_more_files": "{0} weitere Dateien unter Dateien.",
+ "status_word_success": "Erfolgreich",
+ "status_word_error": "Fehlgeschlagen",
+ "status_word_running": "Läuft",
+ "status_word_cancelled": "Abgebrochen",
+ "status_word_unknown": "Unbekannt",
"stage_tabs": "Ansicht dieses Artefakts",
"open_external_hint": "Öffnet dieses Artefakt im Browser — ganzes Fenster, teilbar, druckbar.",
"page_sandbox_note": "Läuft in einer Sandbox: die Skripte der Seite funktionieren, das Netzwerk ist aus.",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 9542c9fac1..862a25fad9 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -5002,7 +5002,7 @@
},
"visualization": {
"title": "Artifacts",
- "subtitle": "Everything your runs produced — pages and pictures full-size, every other run with its files, status and controls; source and run one tab away",
+ "subtitle": "Everything your runs produced, every one as a page — artifacts full-size, every other output composed the same way; source, files and the run one tab away",
"refresh": "Refresh",
"rail": "Artifacts & runs",
"building": "Building…",
@@ -5013,6 +5013,23 @@
"tab_code": "Code",
"tab_files": "Files",
"tab_run": "Run",
+ "rail_filter": "Show",
+ "filter_all": "All",
+ "filter_artifacts": "Artifacts",
+ "filter_outputs": "Outputs",
+ "output_kind": "Output",
+ "preview_answer": "Answer",
+ "preview_deliverables": "Files",
+ "preview_nothing": "This run left no answer and no files behind.",
+ "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_more_files": "{0} more files under Files.",
+ "status_word_success": "Succeeded",
+ "status_word_error": "Failed",
+ "status_word_running": "Running",
+ "status_word_cancelled": "Cancelled",
+ "status_word_unknown": "Unknown",
"stage_tabs": "How to view this artifact",
"open_external_hint": "Open this artifact in your browser — full window, shareable, printable.",
"page_sandbox_note": "Runs in a sandbox: the page's own scripts work, the network is off.",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 52b4fbe51b..b237b1f93a 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -5002,7 +5002,7 @@
},
"visualization": {
"title": "Artefactos",
- "subtitle": "Todo lo que produjeron tus ejecuciones — páginas e imágenes a tamaño completo, cada otra ejecución con sus archivos, estado y controles; código y ejecución a una pestaña de distancia",
+ "subtitle": "Todo lo que produjeron tus ejecuciones, cada una como página — artefactos a tamaño completo, cualquier otro resultado compuesto igual; código, archivos y ejecución a una pestaña",
"refresh": "Actualizar",
"rail": "Artefactos y ejecuciones",
"building": "Creando…",
@@ -5013,6 +5013,23 @@
"tab_code": "Código",
"tab_files": "Archivos",
"tab_run": "Ejecución",
+ "rail_filter": "Mostrar",
+ "filter_all": "Todo",
+ "filter_artifacts": "Artefactos",
+ "filter_outputs": "Resultados",
+ "output_kind": "Resultado",
+ "preview_answer": "Respuesta",
+ "preview_deliverables": "Archivos",
+ "preview_nothing": "Esta ejecución no dejó ni respuesta ni archivos.",
+ "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_more_files": "{0} archivos más en Archivos.",
+ "status_word_success": "Completada",
+ "status_word_error": "Fallida",
+ "status_word_running": "En curso",
+ "status_word_cancelled": "Cancelada",
+ "status_word_unknown": "Desconocido",
"stage_tabs": "Cómo ver este artefacto",
"open_external_hint": "Abre este artefacto en el navegador — ventana completa, se puede compartir e imprimir.",
"page_sandbox_note": "Se ejecuta en un entorno aislado: los scripts de la página funcionan, la red está desactivada.",
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..5b6ec085fe 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(() =>
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"
diff --git a/jarvis/ui/web/outputs_routes.py b/jarvis/ui/web/outputs_routes.py
index 743e11243b..92db9c3dc9 100644
--- a/jarvis/ui/web/outputs_routes.py
+++ b/jarvis/ui/web/outputs_routes.py
@@ -366,9 +366,7 @@ async def _terminal_outcome_details(
"terminal_event": event_type,
"terminal_reason": None,
"terminal_summary": (
- preferred_summary
- or payload.get("summary_en")
- or payload.get("summary_de")
+ preferred_summary or payload.get("summary_en") or payload.get("summary_de")
),
}
if event_type in ("MissionFailed", "MissionCancelled"):
@@ -618,9 +616,11 @@ async def list_outputs(request: Request) -> OutputsResponse:
# card and graph node would show that boilerplate instead of the
# user's actual ask. `clean_request_body` exists precisely for
# UI previews — see its docstring in stream_evidence.py.
- summary["utterance"] = summary["utterance"] or clean_request_body(
- str(mission_row.get("prompt") or "")
- ) or None
+ summary["utterance"] = (
+ summary["utterance"]
+ or clean_request_body(str(mission_row.get("prompt") or ""))
+ or None
+ )
summary["summary"] = mission_row.get("terminal_summary")
summary["terminal_reason"] = mission_row.get("terminal_reason")
summary["terminal_event"] = mission_row.get("terminal_event")
@@ -645,8 +645,9 @@ async def list_outputs(request: Request) -> OutputsResponse:
)
artifact_count = artifact_counts.get(entry, 0)
summary["artifact_count"] = artifact_count
- summary["has_partial_output"] = (
- artifact_count > 0 and summary["status"] in ("error", "cancelled")
+ summary["has_partial_output"] = artifact_count > 0 and summary["status"] in (
+ "error",
+ "cancelled",
)
terminal_reason = str(summary.get("terminal_reason") or "")
reason_key = terminal_reason.split(":", 1)[0]
@@ -1128,7 +1129,9 @@ async def view_output_artifact(slug: str, path: str, request: Request) -> HTMLRe
except OSError as exc:
raise HTTPException(status_code=500, detail=f"read failed: {exc}") from exc
return HTMLResponse(
- render_artifact_html(target.name, text),
+ # `?theme=` is what the Artifacts stage appends so the page follows
+ # the app's theme rather than the OS's; absent = OS preference.
+ render_artifact_html(target.name, text, theme=request.query_params.get("theme")),
headers={
"Content-Security-Policy": VIEW_CSP,
"X-Content-Type-Options": "nosniff",
diff --git a/tests/unit/ui/web/test_artifact_view.py b/tests/unit/ui/web/test_artifact_view.py
index 133844cfbe..01c44103c1 100644
--- a/tests/unit/ui/web/test_artifact_view.py
+++ b/tests/unit/ui/web/test_artifact_view.py
@@ -1,4 +1,5 @@
"""Unit tests for server-side artifact HTML rendering (markdown + escape + CSP)."""
+
from __future__ import annotations
import builtins
@@ -43,3 +44,19 @@ def test_markdown_missing_lib_falls_back_to_pre(monkeypatch):
def test_csp_blocks_scripts():
assert "default-src 'none'" in VIEW_CSP
assert "script-src" not in VIEW_CSP
+
+
+def test_page_wears_the_artifact_tokens_and_no_script():
+ out = render_artifact_html("report.md", "# Title")
+ # The design guide's token block, both palettes, is the page's stylesheet.
+ assert "--accent:#FFD60A" in out
+ assert ':root[data-theme="light"]' in out
+ assert "<script" not in out
+
+
+def test_theme_query_is_stamped_on_html_and_junk_is_ignored():
+ assert "<html lang='en' data-theme='light'>" in render_artifact_html("r.md", "x", theme="light")
+ assert "<html lang='en' data-theme='dark'>" in render_artifact_html("r.txt", "x", theme="dark")
+ # (the stylesheet mentions data-theme selectors; the attribute is what matters)
+ assert "data-theme='" not in render_artifact_html("r.md", "x", theme="<b>x</b>")
+ assert "data-theme='" not in render_artifact_html("r.md", "x")