Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(outputs): show a deliverable the way a person reads it — a document reader for the Results pane
rubenluetke10-beep52056f0c33b9
diff --git a/jarvis/ui/web/frontend/src/components/outputs/ArtifactViewer.test.tsx b/jarvis/ui/web/frontend/src/components/outputs/ArtifactViewer.test.tsxnew file mode 100644index 0000000000..19fadff8ea--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/outputs/ArtifactViewer.test.tsx@@ -0,0 +1,149 @@+/**+ * ArtifactViewer — a deliverable is SHOWN, not dumped.+ *+ * A Markdown report reads as a typeset document (headings, lists), an image+ * is an image, and the selected file's source stays one click away. The rail+ * lists every file; picking one swaps the pane.+ */+import { afterEach, describe, expect, it, vi } from "vitest";+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";++import { ArtifactViewer, resolveSiblingPath } from "@/components/outputs/ArtifactViewer";+import type { ArtifactSummary } from "@/hooks/useOutputs";++vi.mock("@/lib/openExternal", () => ({+ openExternalUrl: vi.fn(async () => {}),+}));++afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+});++const SLUG = "mission_0199aaaa-bbbb";+const MD_PATH = "tasks/t1/artifacts/files/report.md";+const MD_TEXT = "# Quarterly summary\n\nSome **bold** prose.\n\n- first\n- second\n";+const PNG_PATH = "tasks/t1/artifacts/files/chart.png";++function installFetchMock(texts: Record<string, string>) {+ const fetchMock = vi.fn(async (input: RequestInfo | URL) => {+ const url = String(input);+ if (url.includes("/raw")) {+ const hit = Object.entries(texts).find(([p]) => url.includes(p));+ return {+ ok: true,+ status: 200,+ json: async () => ({+ path: hit?.[0] ?? "",+ size: hit?.[1].length ?? 0,+ text: hit?.[1] ?? "",+ truncated: false,+ }),+ };+ }+ if (url.includes("/openers")) {+ return { ok: true, status: 200, json: async () => ({ openers: [] }) };+ }+ if (url.includes("/preferred-opener")) {+ return { ok: true, status: 200, json: async () => ({ opener: "" }) };+ }+ return { ok: true, status: 200, json: async () => ({}) };+ });+ vi.stubGlobal("fetch", fetchMock);+ return fetchMock;+}++function renderViewer(files: ArtifactSummary[]) {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false, gcTime: 0, staleTime: 0 } },+ });+ return render(+ <QueryClientProvider client={client}>+ <ArtifactViewer slug={SLUG} files={files} nativeActions={false} />+ </QueryClientProvider>,+ );+}++const MD_FILE: ArtifactSummary = {+ path: MD_PATH,+ size: MD_TEXT.length,+ mtime: 1,+ is_text: true,+ preview: MD_TEXT,+};+const PNG_FILE: ArtifactSummary = {+ path: PNG_PATH,+ size: 4096,+ mtime: 2,+ is_text: false,+ preview: null,+};++describe("ArtifactViewer", () => {+ it("renders a Markdown deliverable as a document, with the source behind a toggle", async () => {+ installFetchMock({ [MD_PATH]: MD_TEXT });+ renderViewer([MD_FILE]);++ // Typeset: a real heading and list items, not the raw "# " markup.+ const heading = await screen.findByRole("heading", { name: "Quarterly summary" });+ expect(heading.tagName).toBe("H1");+ expect(screen.getByText("first")).toBeTruthy();+ expect(screen.queryByText(MD_TEXT)).toBeNull();++ fireEvent.click(screen.getByRole("button", { name: "Source" }));+ await waitFor(() =>+ expect(screen.queryByRole("heading", { name: "Quarterly summary" })).toBeNull(),+ );+ expect(screen.getByRole("button", { name: "Rendered" }).getAttribute("aria-pressed")).toBe(+ "false",+ );+ });++ it("lists every file in the rail and swaps the pane on selection", async () => {+ installFetchMock({ [MD_PATH]: MD_TEXT });+ renderViewer([MD_FILE, PNG_FILE]);++ const rail = screen.getAllByTestId("artifact-path");+ expect(rail.map((n) => n.textContent)).toEqual(["report.md", "chart.png"]);+ await screen.findByRole("heading", { name: "Quarterly summary" });++ fireEvent.click(screen.getByText("chart.png"));+ const img = await waitFor(() => {+ const el = document.querySelector("img");+ expect(el).toBeTruthy();+ return el as HTMLImageElement;+ });+ expect(img.getAttribute("src")).toBe(+ `/api/outputs/${SLUG}/files/${PNG_PATH}/download?disposition=inline`,+ );+ expect(screen.queryByRole("heading", { name: "Quarterly summary" })).toBeNull();+ });++ it("opens and closes the full-window reader", async () => {+ installFetchMock({ [MD_PATH]: MD_TEXT });+ renderViewer([MD_FILE]);+ await screen.findByRole("heading", { name: "Quarterly summary" });++ fireEvent.click(screen.getByRole("button", { name: "Open as full-window reader" }));+ expect(screen.getByTestId("artifact-reader-fullscreen")).toBeTruthy();+ fireEvent.keyDown(window, { key: "Escape" });+ await waitFor(() =>+ expect(screen.queryByTestId("artifact-reader-fullscreen")).toBeNull(),+ );+ });+});++describe("resolveSiblingPath", () => {+ it("resolves relative links inside the archive and rejects escapes", () => {+ expect(resolveSiblingPath("tasks/t/artifacts/files/report.md", "chart.png")).toBe(+ "tasks/t/artifacts/files/chart.png",+ );+ expect(resolveSiblingPath("tasks/t/artifacts/files/a/b.md", "../c.md")).toBe(+ "tasks/t/artifacts/files/c.md",+ );+ expect(resolveSiblingPath("x.md", "https://example.com/a.png")).toBeNull();+ expect(resolveSiblingPath("x.md", "#section")).toBeNull();+ expect(resolveSiblingPath("x.md", "../../escape.md")).toBeNull();+ });+});diff --git a/jarvis/ui/web/frontend/src/components/outputs/ArtifactViewer.tsx b/jarvis/ui/web/frontend/src/components/outputs/ArtifactViewer.tsxnew file mode 100644index 0000000000..3308adcf6f--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/outputs/ArtifactViewer.tsx@@ -0,0 +1,842 @@+/**+ * ArtifactViewer — the Outputs "Results" pane, laid out like a document reader.+ *+ * Left: a rail listing every deliverable the mission produced. Right: the+ * SELECTED file, shown the way a person wants to look at it — a Markdown+ * report as a typeset document, an HTML page as the running page, an image+ * as an image, code with syntax colours, a CSV as a table. The source text of+ * a rendered file stays one click away ("Source"), and the whole pane expands+ * to a full-window reader. Opening the file in a real app / the browser keeps+ * the existing opener model (chooser, remembered preference, reveal).+ *+ * Security model for HTML: the page is framed from the `/page` endpoint with+ * `sandbox="allow-scripts"` and WITHOUT `allow-same-origin`. Its own scripts+ * run (a chart draws, tabs switch) while the opaque origin plus the server's+ * CSP keep it away from the app's cookies, storage, API and the network.+ */+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,+ Code2,+ Copy,+ ExternalLink,+ Eye,+ FileCode2,+ FileImage,+ FileQuestion,+ FileText,+ FolderOpen,+ Globe,+ Loader2,+ Maximize2,+ Table2,+ X,+} from "lucide-react";++import { cn } from "@/lib/utils";+import { useT } from "@/i18n";+import { robustCopy } from "@/lib/clipboard";+import { openExternalUrl } from "@/lib/openExternal";+import {+ artifactKind,+ artifactLanguage,+ formatBytes,+ hasRenderedView,+ isTextKind,+ parseCsv,+ type ArtifactKind,+} from "@/lib/artifactKind";+import {+ artifactInlineUrl,+ artifactOpenUrl,+ artifactPageUrl,+ openArtifactWith,+ revealArtifact,+ useArtifactFile,+ useOpeners,+ usePreferredOpener,+ useSetPreferredOpener,+ type ArtifactSummary,+} from "@/hooks/useOutputs";+import { CodeBlock } from "@/components/docs/CodeBlock";+import { OpenWithDialog } from "@/components/OpenWithDialog";++/** Above this many characters the source view skips Shiki — highlighting a+ * megabyte of text would freeze the UI thread for seconds. */+const HIGHLIGHT_MAX_CHARS = 120_000;+/** Rows a CSV table draws before it stops — the rest is in the file. */+const CSV_MAX_ROWS = 500;++const ARCHIVED_DELIVERABLE_PREFIX = /^tasks\/[^/]+\/artifacts\/files\//;++/** Hide archive plumbing from the label while retaining the full path for APIs. */+export function deliverableDisplayPath(path: string): string {+ return path.replace(ARCHIVED_DELIVERABLE_PREFIX, "");+}++type ViewMode = "rendered" | "source";++export interface ArtifactViewerProps {+ slug: string;+ files: ArtifactSummary[];+ nativeActions: boolean;+}++export function ArtifactViewer({ slug, files, nativeActions }: ArtifactViewerProps) {+ const [selectedPath, setSelectedPath] = useState<string | null>(null);+ const [fullscreen, setFullscreen] = useState(false);++ // The selection follows the list: first file by default, and a path that+ // vanished (a re-run replaced the deliverables) falls back to the first.+ const selected = useMemo(+ () => files.find((f) => f.path === selectedPath) ?? files[0] ?? null,+ [files, selectedPath],+ );++ useEffect(() => {+ if (!fullscreen) return;+ const onKey = (e: KeyboardEvent) => {+ if (e.key === "Escape") setFullscreen(false);+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [fullscreen]);++ const pane = (+ <div+ className={cn(+ "flex min-h-0 w-full",+ fullscreen ? "h-full" : "h-[min(72vh,760px)] min-h-[420px]",+ )}+ >+ <FileRail+ files={files}+ selectedPath={selected?.path ?? null}+ onSelect={(p) => setSelectedPath(p)}+ />+ <div className="flex min-w-0 flex-1 flex-col">+ {selected ? (+ <SelectedFile+ key={`${slug}:${selected.path}`}+ slug={slug}+ file={selected}+ files={files}+ nativeActions={nativeActions}+ fullscreen={fullscreen}+ onToggleFullscreen={() => setFullscreen((v) => !v)}+ onSelectSibling={(p) => setSelectedPath(p)}+ />+ ) : null}+ </div>+ </div>+ );++ if (fullscreen) {+ // Portalled to <body>: an ancestor with a transform (the detail pane's+ // scroll area) would otherwise pin a `fixed` overlay to itself.+ return (+ <>+ {/* Placeholder keeps the page layout stable while the reader is open. */}+ <div className="h-[min(72vh,760px)] min-h-[420px] rounded-xl border border-dashed border-border/60" />+ {createPortal(+ <div+ role="dialog"+ aria-modal="true"+ data-testid="artifact-reader-fullscreen"+ className="fixed inset-0 z-50 flex flex-col bg-background"+ >+ {pane}+ </div>,+ document.body,+ )}+ </>+ );+ }++ return (+ <div className="overflow-hidden rounded-xl border border-border bg-background/60">+ {pane}+ </div>+ );+}++// --- File rail -------------------------------------------------------------++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":+ return <FileText className={cls} aria-hidden="true" />;+ case "html":+ return <Globe className={cls} aria-hidden="true" />;+ case "image":+ return <FileImage className={cls} aria-hidden="true" />;+ case "pdf":+ return <FileText className={cls} aria-hidden="true" />;+ case "code":+ return <FileCode2 className={cls} aria-hidden="true" />;+ case "csv":+ return <Table2 className={cls} aria-hidden="true" />;+ default:+ return <FileQuestion className={cls} aria-hidden="true" />;+ }+}++function FileRail({+ files,+ selectedPath,+ onSelect,+}: {+ files: ArtifactSummary[];+ selectedPath: string | null;+ onSelect: (path: string) => void;+}) {+ const t = useT();+ return (+ <nav+ aria-label={t("outputs_view.results")}+ className="flex w-56 shrink-0 flex-col overflow-y-auto border-r border-border/60 bg-card/30 py-2"+ >+ <ul className="flex flex-col gap-px px-1.5">+ {files.map((f) => {+ const display = deliverableDisplayPath(f.path);+ const slash = display.lastIndexOf("/");+ const dir = slash === -1 ? "" : display.slice(0, slash + 1);+ const name = slash === -1 ? display : display.slice(slash + 1);+ const kind = artifactKind(f.path, f.is_text);+ const isSelected = f.path === selectedPath;+ return (+ <li key={f.path}>+ <button+ type="button"+ onClick={() => onSelect(f.path)}+ aria-current={isSelected ? "true" : undefined}+ className={cn(+ "flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-[12px] transition-colors",+ isSelected+ ? "bg-primary/10 text-foreground"+ : "text-muted-foreground hover:bg-secondary/40 hover:text-foreground",+ )}+ >+ <KindIcon+ kind={kind}+ className={isSelected ? "text-primary" : "text-muted-foreground/70"}+ />+ <span+ className="flex min-w-0 flex-1 flex-col font-mono leading-tight"+ data-testid="artifact-path"+ title={f.path}+ >+ {dir && (+ <span className="truncate text-[10px] text-muted-foreground/60">{dir}</span>+ )}+ <span className="truncate">{name}</span>+ </span>+ </button>+ </li>+ );+ })}+ </ul>+ </nav>+ );+}++// --- Selected file: toolbar + body -----------------------------------------++function SelectedFile({+ slug,+ file,+ files,+ nativeActions,+ fullscreen,+ onToggleFullscreen,+ onSelectSibling,+}: {+ slug: string;+ file: ArtifactSummary;+ files: ArtifactSummary[];+ nativeActions: boolean;+ fullscreen: boolean;+ onToggleFullscreen: () => void;+ onSelectSibling: (path: string) => void;+}) {+ const t = useT();+ const kind = artifactKind(file.path, file.is_text);+ const [mode, setMode] = useState<ViewMode>("rendered");+ const [chooserOpen, setChooserOpen] = useState(false);+ const [copied, setCopied] = useState(false);+ const openers = useOpeners();+ const preferred = usePreferredOpener();+ const setPreferred = useSetPreferredOpener();++ // Text is needed for: a rendered Markdown/CSV document, every source view,+ // plain code/text files. A rendered HTML page and media never fetch it.+ const needsText =+ isTextKind(kind) && !(kind === "html" && mode === "rendered");+ const full = useArtifactFile(slug, needsText ? file.path : null);+ const text = full.data?.text ?? null;++ const openUrl = artifactOpenUrl(slug, file.path);+ const absoluteOpenUrl = openUrl+ ? new URL(openUrl, window.location.origin).toString()+ : null;++ // Open the artifact's render url in the user's real default browser. Routes+ // through openExternalUrl (the backend open-external bridge), NOT a bare+ // window.open — the embedded WebView2 desktop shell silently drops+ // window.open / target="_blank".+ const openInBrowser = () => {+ if (absoluteOpenUrl) void openExternalUrl(absoluteOpenUrl);+ };+ const openWithOpener = (opener: string) => {+ if (opener === "browser" && absoluteOpenUrl) {+ openInBrowser();+ return;+ }+ void openArtifactWith(slug, file.path, opener).catch(() => {});+ };+ const pickOpener = (opener: string, remember: boolean) => {+ openWithOpener(opener);+ if (remember) setPreferred.mutate(opener);+ setChooserOpen(false);+ };+ const handleOpen = () => {+ if (!nativeActions) {+ // Headless VPS / web: the UI is already a real browser tab, so the+ // render URL opens in the user's own browser.+ openInBrowser();+ return;+ }+ const pref = preferred.data ?? "";+ if (pref) openWithOpener(pref);+ else setChooserOpen(true); // first time: ask which app+ };++ const handleCopy = () => {+ if (text === null) return;+ void robustCopy(text).then((ok) => {+ if (!ok) return;+ setCopied(true);+ window.setTimeout(() => setCopied(false), 1500);+ });+ };++ const display = deliverableDisplayPath(file.path);+ const canToggle = hasRenderedView(kind);+ const iconBtn =+ "rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-secondary/50 hover:text-foreground disabled:opacity-40";++ return (+ <>+ <header className="flex h-10 shrink-0 items-center gap-2 border-b border-border/60 bg-card/30 px-3">+ <KindIcon kind={kind} className="text-primary" />+ <span+ className="min-w-0 flex-1 truncate font-mono text-[12px] text-foreground"+ title={file.path}+ >+ {`${display} · ${formatBytes(file.size)}`}+ </span>++ {canToggle && (+ <div+ role="group"+ aria-label={t("outputs_view.view_mode")}+ className="ml-2 flex shrink-0 items-center rounded-md border border-border/60 bg-background/60 p-0.5"+ >+ <ModeButton+ active={mode === "rendered"}+ onClick={() => setMode("rendered")}+ icon={<Eye className="h-3 w-3" aria-hidden="true" />}+ label={t("outputs_view.view_rendered")}+ />+ <ModeButton+ active={mode === "source"}+ onClick={() => setMode("source")}+ icon={<Code2 className="h-3 w-3" aria-hidden="true" />}+ label={t("outputs_view.view_source")}+ />+ </div>+ )}++ <div className="ml-1 flex shrink-0 items-center gap-0.5">+ {isTextKind(kind) && (+ <button+ type="button"+ title={t("outputs_view.copy_contents")}+ aria-label={t("outputs_view.copy_contents")}+ disabled={text === null}+ onClick={handleCopy}+ className={iconBtn}+ >+ {copied ? (+ <Check className="h-3.5 w-3.5 text-emerald-400" aria-hidden="true" />+ ) : (+ <Copy className="h-3.5 w-3.5" aria-hidden="true" />+ )}+ </button>+ )}+ {(nativeActions || openUrl) && (+ <button+ type="button"+ title={t("outputs_view.open_action")}+ onClick={handleOpen}+ className={iconBtn}+ >+ <ExternalLink className="h-3.5 w-3.5" aria-hidden="true" />+ </button>+ )}+ {nativeActions && (+ <button+ type="button"+ title={t("outputs_view.open_with_change")}+ onClick={() => setChooserOpen(true)}+ className={iconBtn}+ >+ <ChevronDown className="h-3.5 w-3.5" aria-hidden="true" />+ </button>+ )}+ {nativeActions && (+ <button+ type="button"+ title={t("outputs_view.reveal_in_folder")}+ onClick={() => void revealArtifact(slug, file.path).catch(() => {})}+ className={iconBtn}+ >+ <FolderOpen className="h-3.5 w-3.5" aria-hidden="true" />+ </button>+ )}+ <button+ type="button"+ title={fullscreen ? t("outputs_view.exit_fullscreen") : t("outputs_view.fullscreen")}+ aria-label={fullscreen ? t("outputs_view.exit_fullscreen") : t("outputs_view.fullscreen")}+ onClick={onToggleFullscreen}+ className={iconBtn}+ >+ {fullscreen ? (+ <X className="h-3.5 w-3.5" aria-hidden="true" />+ ) : (+ <Maximize2 className="h-3.5 w-3.5" aria-hidden="true" />+ )}+ </button>+ </div>+ </header>++ {chooserOpen && (+ <OpenWithDialog+ openers={openers.data ?? []}+ loading={openers.isLoading}+ onPick={pickOpener}+ onClose={() => setChooserOpen(false)}+ />+ )}++ <div className="relative min-h-0 flex-1 overflow-auto">+ <ArtifactBody+ slug={slug}+ file={file}+ files={files}+ kind={kind}+ mode={mode}+ text={text}+ loading={needsText && full.isLoading}+ error={needsText && full.isError ? String(full.error) : null}+ truncated={!!full.data?.truncated}+ onSelectSibling={onSelectSibling}+ />+ </div>+ </>+ );+}++function ModeButton({+ active,+ onClick,+ icon,+ label,+}: {+ active: boolean;+ onClick: () => void;+ icon: ReactNode;+ label: string;+}) {+ return (+ <button+ type="button"+ aria-pressed={active}+ onClick={onClick}+ className={cn(+ "flex items-center gap-1 rounded px-2 py-0.5 text-[11px] font-medium transition-colors",+ active+ ? "bg-primary/15 text-foreground"+ : "text-muted-foreground hover:text-foreground",+ )}+ >+ {icon}+ {label}+ </button>+ );+}++// --- Body: one renderer per kind -------------------------------------------++function ArtifactBody({+ slug,+ file,+ files,+ kind,+ mode,+ text,+ loading,+ error,+ truncated,+ onSelectSibling,+}: {+ slug: string;+ file: ArtifactSummary;+ files: ArtifactSummary[];+ kind: ArtifactKind;+ mode: ViewMode;+ text: string | null;+ loading: boolean;+ error: string | null;+ truncated: boolean;+ onSelectSibling: (path: string) => void;+}) {+ const t = useT();++ if (kind === "image") {+ return (+ <div className="flex min-h-full items-center justify-center p-6 [background-image:linear-gradient(45deg,hsl(var(--muted)/0.35)_25%,transparent_25%),linear-gradient(-45deg,hsl(var(--muted)/0.35)_25%,transparent_25%),linear-gradient(45deg,transparent_75%,hsl(var(--muted)/0.35)_75%),linear-gradient(-45deg,transparent_75%,hsl(var(--muted)/0.35)_75%)] [background-size:20px_20px] [background-position:0_0,0_10px,10px_-10px,-10px_0]">+ <img+ src={artifactInlineUrl(slug, file.path)}+ alt={deliverableDisplayPath(file.path)}+ className="max-h-full max-w-full rounded-md shadow-sm"+ />+ </div>+ );+ }++ if (kind === "pdf") {+ // A PDF renders through the browser's own viewer; that viewer is a plugin+ // and plugins never load inside a sandboxed frame, so this one is not+ // sandboxed — the bytes are same-origin and inert.+ return (+ <iframe+ title={deliverableDisplayPath(file.path)}+ src={artifactInlineUrl(slug, file.path)}+ className="h-full w-full border-0 bg-white"+ />+ );+ }++ if (kind === "html" && mode === "rendered") {+ return <HtmlPage slug={slug} path={file.path} />;+ }++ if (kind === "binary") {+ return (+ <div className="flex min-h-full flex-col items-center justify-center gap-2 p-8 text-center">+ <FileQuestion className="h-8 w-8 text-muted-foreground/60" aria-hidden="true" />+ <p className="text-xs text-muted-foreground">{t("outputs_view.binary_file_hint")}</p>+ </div>+ );+ }++ if (loading || (text === null && !error)) {+ return (+ <div className="flex items-center gap-2 p-4 text-[11px] text-muted-foreground">+ <Loader2 className="h-3 w-3 animate-spin" aria-hidden="true" />+ {t("outputs_view.loading_file")}+ </div>+ );+ }+ if (error) {+ return (+ <div className="p-4 text-[11px] text-destructive">+ {t("common.error")}: {error}+ </div>+ );+ }++ const body = text ?? "";+ let content: ReactNode;+ if (kind === "markdown" && mode === "rendered") {+ content = (+ <MarkdownDocument+ slug={slug}+ path={file.path}+ files={files}+ text={body}+ onSelectSibling={onSelectSibling}+ />+ );+ } else if (kind === "csv" && mode === "rendered") {+ content = <CsvTable text={body} tab={file.path.toLowerCase().endsWith(".tsv")} />;+ } else {+ content = <SourceView path={file.path} text={body} />;+ }++ return (+ <>+ {content}+ {truncated && (+ <div className="border-t border-border/60 px-4 py-2 text-[10px] text-muted-foreground">+ {t("outputs_view.file_truncated")}+ </div>+ )}+ </>+ );+}++/**+ * The running HTML page. Framed from `/page` (scripts run, network shut) when+ * 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`.+ */+function HtmlPage({ slug, path }: { slug: string; path: string }) {+ const t = useT();+ const pageUrl = artifactPageUrl(slug, path);+ const probe = useQuery<boolean>({+ queryKey: ["output-artifact-page-available", slug, path],+ queryFn: async () => {+ try {+ const r = await fetch(pageUrl, { method: "HEAD" });+ return r.ok;+ } catch {+ return false;+ }+ },+ staleTime: 60_000,+ retry: false,+ });+ if (probe.isLoading) {+ return (+ <div className="flex items-center gap-2 p-4 text-[11px] text-muted-foreground">+ <Loader2 className="h-3 w-3 animate-spin" aria-hidden="true" />+ {t("outputs_view.loading_file")}+ </div>+ );+ }+ const src = probe.data ? pageUrl : artifactInlineUrl(slug, path);+ return (+ <iframe+ title={deliverableDisplayPath(path)}+ src={src}+ sandbox="allow-scripts"+ referrerPolicy="no-referrer"+ className="h-full w-full border-0 bg-white"+ />+ );+}++function SourceView({ path, text }: { path: string; text: string }) {+ const language = artifactLanguage(path);+ if (text.length > HIGHLIGHT_MAX_CHARS || language === "txt") {+ return (+ <pre className="m-0 whitespace-pre-wrap break-words p-4 font-mono text-[12px] leading-relaxed text-foreground/90">+ {text}+ </pre>+ );+ }+ return (+ <div className="p-3 [&>div]:my-0">+ <CodeBlock language={language} code={text} />+ </div>+ );+}++function CsvTable({ text, tab }: { text: string; tab: boolean }) {+ const t = useT();+ const rows = useMemo(() => parseCsv(text, tab ? "\t" : ","), [text, tab]);+ if (rows.length === 0) {+ return <div className="p-4 text-xs text-muted-foreground">{t("outputs_view.csv_empty")}</div>;+ }+ const [head, ...rest] = rows;+ const shown = rest.slice(0, CSV_MAX_ROWS);+ return (+ <div className="p-4">+ <div className="overflow-x-auto rounded-md border border-border">+ <table className="w-full text-[12px]">+ <thead className="bg-muted/40">+ <tr>+ {head.map((h, i) => (+ <th+ key={i}+ className="whitespace-nowrap px-3 py-1.5 text-left font-semibold text-foreground"+ >+ {h}+ </th>+ ))}+ </tr>+ </thead>+ <tbody>+ {shown.map((r, ri) => (+ <tr key={ri} className="border-t border-border/60 odd:bg-background/40">+ {head.map((_, ci) => (+ <td key={ci} className="whitespace-nowrap px-3 py-1 text-foreground/90">+ {r[ci] ?? ""}+ </td>+ ))}+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ {rest.length > shown.length && (+ <p className="mt-2 text-[10px] text-muted-foreground">+ {t("outputs_view.csv_more_rows").replace("{n}", String(rest.length - shown.length))}+ </p>+ )}+ </div>+ );+}++// --- 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("/");+}++function MarkdownDocument({+ slug,+ path,+ files,+ text,+ onSelectSibling,+}: {+ slug: string;+ path: string;+ files: ArtifactSummary[];+ 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"+ 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",+ "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/hooks/useOutputs.ts b/jarvis/ui/web/frontend/src/hooks/useOutputs.tsindex 9e51f1f4c5..6377b89644 100644--- a/jarvis/ui/web/frontend/src/hooks/useOutputs.ts+++ b/jarvis/ui/web/frontend/src/hooks/useOutputs.ts@@ -306,6 +306,23 @@ export function artifactDownloadUrl(slug: string, path: string): string {)}/download?disposition=attachment`;}+/** The bytes served inline (image, PDF, …) for the in-app viewer. */+export function artifactInlineUrl(slug: string, path: string): string {+ return `/api/outputs/${slug}/files/${encodeArtifactPath(+ path,+ )}/download?disposition=inline`;+}++/**+ * An HTML deliverable as an ARTIFACT PAGE: the server lets the page's own+ * scripts run but shuts every way out (no network, no forms, no navigation);+ * the viewer frames it with `sandbox="allow-scripts"` and no same-origin, so+ * the page lives in an opaque origin that cannot reach the app.+ */+export function artifactPageUrl(slug: string, path: string): string {+ return `/api/outputs/${slug}/files/${encodeArtifactPath(path)}/page`;+}+export type ArtifactOpenKind = "rendered" | "inline" | "opaque";const _INLINE_EXT = [diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 12b7b2b1e4..d5da7a3b68 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -2213,6 +2213,14 @@"open_with_loading": "Apps werden gesucht …","opener_default": "System-Standard-App","opener_browser": "Browser",+ "view_mode": "Ansicht",+ "view_rendered": "Gerendert",+ "view_source": "Quelltext",+ "copy_contents": "Inhalt kopieren",+ "fullscreen": "Als Vollbild-Leser öffnen",+ "exit_fullscreen": "Leser schließen",+ "csv_empty": "Diese Tabelle ist leer.",+ "csv_more_rows": "{n} weitere Zeilen in der Datei.","reveal_in_folder": "Im Ordner anzeigen"},"common": {diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex ec6f9202b1..0b51c2e5fe 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -2213,6 +2213,14 @@"open_with_loading": "Detecting apps…","opener_default": "System default app","opener_browser": "Browser",+ "view_mode": "View",+ "view_rendered": "Rendered",+ "view_source": "Source",+ "copy_contents": "Copy contents",+ "fullscreen": "Open as full-window reader",+ "exit_fullscreen": "Close reader",+ "csv_empty": "This table is empty.",+ "csv_more_rows": "{n} more rows in the file.","reveal_in_folder": "Reveal in folder"},"common": {diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 39ec27223b..36bd152a9c 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -2213,6 +2213,14 @@"open_with_loading": "Detectando apps…","opener_default": "App predeterminada del sistema","opener_browser": "Navegador",+ "view_mode": "Vista",+ "view_rendered": "Renderizado",+ "view_source": "Código fuente",+ "copy_contents": "Copiar contenido",+ "fullscreen": "Abrir como lector a pantalla completa",+ "exit_fullscreen": "Cerrar lector",+ "csv_empty": "Esta tabla está vacía.",+ "csv_more_rows": "{n} filas más en el archivo.","reveal_in_folder": "Mostrar en la carpeta"},"common": {diff --git a/jarvis/ui/web/frontend/src/lib/artifactKind.test.ts b/jarvis/ui/web/frontend/src/lib/artifactKind.test.tsnew file mode 100644index 0000000000..8c1c983173--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/artifactKind.test.ts@@ -0,0 +1,66 @@+import { describe, expect, it } from "vitest";++import {+ artifactKind,+ artifactLanguage,+ formatBytes,+ hasRenderedView,+ parseCsv,+} from "@/lib/artifactKind";++describe("artifactKind", () => {+ it("maps deliverables to their in-app renderer by extension", () => {+ expect(artifactKind("tasks/a/artifacts/files/report.md", true)).toBe("markdown");+ expect(artifactKind("site/index.html", true)).toBe("html");+ expect(artifactKind("chart.PNG", false)).toBe("image");+ expect(artifactKind("paper.pdf", false)).toBe("pdf");+ expect(artifactKind("data.csv", true)).toBe("csv");+ expect(artifactKind("script.py", true)).toBe("code");+ expect(artifactKind("notes.txt", true)).toBe("text");+ });++ it("trusts the server's text verdict for unknown extensions", () => {+ expect(artifactKind("Makefile", true)).toBe("text");+ expect(artifactKind("model.bin", false)).toBe("binary");+ });++ it("only documents and tables own a rendered view distinct from source", () => {+ expect(hasRenderedView("markdown")).toBe(true);+ expect(hasRenderedView("html")).toBe(true);+ expect(hasRenderedView("csv")).toBe(true);+ expect(hasRenderedView("code")).toBe(false);+ expect(hasRenderedView("image")).toBe(false);+ });++ it("resolves the Shiki language from the extension", () => {+ expect(artifactLanguage("a/b/main.py")).toBe("python");+ expect(artifactLanguage("x.yml")).toBe("yaml");+ expect(artifactLanguage("README")).toBe("txt");+ });+});++describe("parseCsv", () => {+ it("handles quoted fields, doubled quotes and CRLF rows", () => {+ const rows = parseCsv('name,note\r\n"Smith, J","said ""hi"""\r\nplain,row\n');+ expect(rows).toEqual([+ ["name", "note"],+ ["Smith, J", 'said "hi"'],+ ["plain", "row"],+ ]);+ });++ it("accepts a tab delimiter", () => {+ expect(parseCsv("a\tb\n1\t2", "\t")).toEqual([+ ["a", "b"],+ ["1", "2"],+ ]);+ });+});++describe("formatBytes", () => {+ it("picks a readable unit", () => {+ expect(formatBytes(12)).toBe("12 B");+ expect(formatBytes(2048)).toBe("2.0 KiB");+ expect(formatBytes(3 * 1024 * 1024)).toBe("3.0 MiB");+ });+});diff --git a/jarvis/ui/web/frontend/src/lib/artifactKind.ts b/jarvis/ui/web/frontend/src/lib/artifactKind.tsnew file mode 100644index 0000000000..bd8fca3917--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/artifactKind.ts@@ -0,0 +1,161 @@+/**+ * How an Outputs deliverable is SHOWN inside the app — pure, by filename.+ *+ * The Outputs view renders every file the way a person wants to look at it,+ * not the way it is stored: a Markdown report reads as a document, an HTML+ * page runs as a page, an image is an image, code is highlighted, a CSV is a+ * table. `classifyArtifact` in `hooks/useOutputs.ts` answers a different+ * question (which URL the *browser* gets); this module answers which in-app+ * renderer draws the file.+ */++export type ArtifactKind =+ | "markdown"+ | "html"+ | "image"+ | "pdf"+ | "code"+ | "csv"+ | "text"+ | "binary";++const IMAGE_EXT = [".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg", ".bmp", ".avif"];+const MARKDOWN_EXT = [".md", ".markdown", ".mdx"];+const HTML_EXT = [".html", ".htm"];+const CSV_EXT = [".csv", ".tsv"];+const TEXT_EXT = [".txt", ".log", ".env", ".cfg", ".ini", ".patch", ".diff"];++/** Extension -> Shiki language for the source / code renderer. */+const CODE_LANG: Record<string, string> = {+ py: "python",+ ts: "typescript",+ tsx: "tsx",+ js: "javascript",+ jsx: "jsx",+ mjs: "javascript",+ cjs: "javascript",+ json: "json",+ jsonl: "json",+ yaml: "yaml",+ yml: "yaml",+ toml: "toml",+ ini: "ini",+ cfg: "ini",+ xml: "xml",+ html: "html",+ htm: "html",+ css: "css",+ sh: "bash",+ bash: "bash",+ zsh: "bash",+ ps1: "powershell",+ rs: "rust",+ go: "go",+ java: "java",+ c: "c",+ h: "c",+ cpp: "cpp",+ hpp: "cpp",+ cs: "csharp",+ kt: "kotlin",+ swift: "swift",+ sql: "sql",+ diff: "diff",+ patch: "diff",+ md: "markdown",+ markdown: "markdown",+ mdx: "markdown",+};++function extOf(path: string): string {+ const name = path.split("/").pop() ?? path;+ const dot = name.lastIndexOf(".");+ return dot === -1 ? "" : name.slice(dot + 1).toLowerCase();+}++function hasExt(path: string, exts: string[]): boolean {+ const lower = path.toLowerCase();+ return exts.some((e) => lower.endsWith(e));+}++/** Decide which in-app renderer draws a deliverable. `isText` is the server's+ * own verdict for the extension-less / unknown case. */+export function artifactKind(path: string, isText: boolean): ArtifactKind {+ if (hasExt(path, MARKDOWN_EXT)) return "markdown";+ if (hasExt(path, HTML_EXT)) return "html";+ if (hasExt(path, IMAGE_EXT)) return "image";+ if (hasExt(path, [".pdf"])) return "pdf";+ if (hasExt(path, CSV_EXT)) return "csv";+ if (CODE_LANG[extOf(path)]) return "code";+ if (hasExt(path, TEXT_EXT)) return "text";+ return isText ? "text" : "binary";+}++/** The Shiki language for a file's source view ("txt" when unknown). */+export function artifactLanguage(path: string): string {+ return CODE_LANG[extOf(path)] ?? "txt";+}++/** Kinds that own a "rendered" presentation distinct from their source text. */+export function hasRenderedView(kind: ArtifactKind): boolean {+ return kind === "markdown" || kind === "html" || kind === "csv";+}++/** Kinds whose bytes are text the viewer fetches through `/raw`. */+export function isTextKind(kind: ArtifactKind): boolean {+ return kind === "markdown" || kind === "html" || kind === "code" || kind === "csv" || kind === "text";+}++/**+ * Minimal RFC-4180-ish CSV parser: quoted fields, doubled quotes, CR/LF rows.+ * Tabs are accepted as the delimiter for `.tsv`. Good enough for a worker's+ * exported table; never used for anything but display.+ */+export function parseCsv(text: string, delimiter: "," | "\t" = ","): string[][] {+ const rows: string[][] = [];+ let row: string[] = [];+ let field = "";+ let quoted = false;+ for (let i = 0; i < text.length; i++) {+ const ch = text[i];+ if (quoted) {+ if (ch === '"') {+ if (text[i + 1] === '"') {+ field += '"';+ i++;+ } else {+ quoted = false;+ }+ } else {+ field += ch;+ }+ continue;+ }+ if (ch === '"') {+ quoted = true;+ } else if (ch === delimiter) {+ row.push(field);+ field = "";+ } else if (ch === "\n" || ch === "\r") {+ if (ch === "\r" && text[i + 1] === "\n") i++;+ row.push(field);+ rows.push(row);+ row = [];+ field = "";+ } else {+ field += ch;+ }+ }+ if (field.length > 0 || row.length > 0) {+ row.push(field);+ rows.push(row);+ }+ return rows.filter((r) => r.length > 1 || (r.length === 1 && r[0] !== ""));+}++/** Human-readable byte count ("1.2 KiB"). */+export function formatBytes(size: number): string {+ if (size < 1024) return `${size} B`;+ if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KiB`;+ return `${(size / (1024 * 1024)).toFixed(1)} MiB`;+}diff --git a/jarvis/ui/web/frontend/src/views/OutputsView.htmlpreview.test.tsx b/jarvis/ui/web/frontend/src/views/OutputsView.htmlpreview.test.tsxnew file mode 100644index 0000000000..ce8906917d--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/OutputsView.htmlpreview.test.tsx@@ -0,0 +1,155 @@+/**+ * Outputs view — a selected HTML artifact shows the RENDERED page, not markup.+ *+ * Regression for "HTML files appear as raw source in the outputs section":+ * `.html` counts as a text file server-side, so the old preview dumped the+ * markup into a <pre>. The viewer frames the file from the `/page` endpoint+ * (scripts run, network shut) with `sandbox="allow-scripts"` and no+ * same-origin; the source stays reachable behind an explicit "Source" toggle.+ */+import { afterEach, describe, expect, it, vi } from "vitest";+import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";++import { OutputsView } from "@/views/OutputsView";+import type { ArtifactSummary, OutputSummary } from "@/hooks/useOutputs";++vi.mock("@/hooks/useWebSocket", () => ({+ getWSClient: () => null,+}));+vi.mock("@/lib/openExternal", () => ({+ openExternalUrl: vi.fn(async () => {}),+}));++afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+ vi.clearAllMocks();+});++const SLUG = "mission_019f0fa6-4ff6";+const HTML_PATH = "tasks/019e3288/artifacts/files/HelloBot.html";+const HTML_SOURCE = "<html><body><h1>Hello</h1></body></html>";++function installFetchMock(artifacts: ArtifactSummary[]) {+ const sessions: OutputSummary[] = [+ {+ slug: SLUG,+ utterance: "Build a page",+ status: "success",+ mission_id: "m-1",+ started_at: 1_750_000_000,+ },+ ];+ const fetchMock = vi.fn(async (input: RequestInfo | URL) => {+ const url = String(input);+ if (url.includes("/raw")) {+ return {+ ok: true,+ status: 200,+ json: async () => ({+ path: HTML_PATH,+ size: HTML_SOURCE.length,+ text: HTML_SOURCE,+ truncated: false,+ }),+ };+ }+ if (url.includes("/artifacts")) {+ return { ok: true, status: 200, json: async () => ({ files: artifacts }) };+ }+ if (url.includes("/plan")) {+ return { ok: true, status: 200, json: async () => ({ plan: null, steps: [] }) };+ }+ if (url.includes("/capabilities")) {+ return {+ ok: true,+ status: 200,+ json: async () => ({ native_file_actions: true, platform: "win32" }),+ };+ }+ if (url.includes("/openers")) {+ return { ok: true, status: 200, json: async () => ({ openers: [] }) };+ }+ if (url.includes("/preferred-opener")) {+ return { ok: true, status: 200, json: async () => ({ opener: "" }) };+ }+ if (url.includes("/api/outputs")) {+ return { ok: true, status: 200, json: async () => ({ sessions }) };+ }+ return { ok: true, status: 200, json: async () => ({}) };+ });+ vi.stubGlobal("fetch", fetchMock);+ return fetchMock;+}++function renderView() {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false, gcTime: 0, staleTime: 0 } },+ });+ return render(+ <QueryClientProvider client={client}>+ <OutputsView />+ </QueryClientProvider>,+ );+}++const HTML_ARTIFACT: ArtifactSummary = {+ path: HTML_PATH,+ size: HTML_SOURCE.length,+ mtime: 1_750_000_100,+ is_text: true,+ preview: HTML_SOURCE,+};++describe("OutputsView — HTML artifacts render as pages", () => {+ it("shows an html artifact in a sandboxed iframe, not a source dump", async () => {+ installFetchMock([HTML_ARTIFACT]);+ renderView();++ await waitFor(() => expect(screen.getByText("HelloBot.html")).toBeTruthy());+ fireEvent.click(screen.getByText("HelloBot.html"));++ const iframe = await waitFor(() => {+ const el = document.querySelector("iframe");+ expect(el).toBeTruthy();+ return el as HTMLIFrameElement;+ });+ // The page endpoint (scripts allowed, every way out shut) inside a frame+ // that runs scripts in an opaque origin — never allow-same-origin.+ expect(iframe.getAttribute("src")).toBe(+ `/api/outputs/${SLUG}/files/${HTML_PATH}/page`,+ );+ expect(iframe.getAttribute("sandbox")).toBe("allow-scripts");+ // The markup is NOT dumped as visible text by default.+ expect(screen.queryByText(HTML_SOURCE)).toBeNull();+ });++ it("keeps the source reachable behind the explicit toggle", async () => {+ const fetchMock = installFetchMock([HTML_ARTIFACT]);+ renderView();++ await waitFor(() => expect(screen.getByText("HelloBot.html")).toBeTruthy());+ fireEvent.click(screen.getByText("HelloBot.html"));+ await waitFor(() => expect(document.querySelector("iframe")).toBeTruthy());++ // Rendered mode never fetches the raw text.+ expect(+ fetchMock.mock.calls.some(([input]) => String(input).includes("/raw")),+ ).toBe(false);++ fireEvent.click(screen.getByRole("button", { name: "Source" }));+ await waitFor(() => expect(screen.getByText(HTML_SOURCE)).toBeTruthy());+ expect(document.querySelector("iframe")).toBeNull();++ // And back to the rendered page.+ fireEvent.click(screen.getByRole("button", { name: "Rendered" }));+ await waitFor(() => expect(document.querySelector("iframe")).toBeTruthy());+ });+});diff --git a/jarvis/ui/web/frontend/src/views/OutputsView.tsx b/jarvis/ui/web/frontend/src/views/OutputsView.tsxindex 752af2e831..73199dc918 100644--- a/jarvis/ui/web/frontend/src/views/OutputsView.tsx+++ b/jarvis/ui/web/frontend/src/views/OutputsView.tsx@@ -7,8 +7,6 @@ import {ListChecks,FileQuestion,FileText,- ChevronRight,- ChevronDown,} from "lucide-react";import { cn } from "@/lib/utils";import { ViewHeader } from "@/views/ChatsView";@@ -21,21 +19,16 @@ import {useOutputsList,usePlanForOutput,useArtifactsForOutput,- useArtifactFile,useCancelMission,useOutputsCapabilities,- useOpeners,- usePreferredOpener,- useSetPreferredOpener,- artifactOpenUrl,- revealArtifact,- openArtifactWith,type OutputSummary,type OutputStatus,type ArtifactSummary,} from "@/hooks/useOutputs";-import { OpenWithDialog } from "@/components/OpenWithDialog";-import { openExternalUrl } from "@/lib/openExternal";+import {+ ArtifactViewer,+ deliverableDisplayPath,+} from "@/components/outputs/ArtifactViewer";import { useT } from "@/i18n";import { applyMissionDragImage } from "@/lib/missionDragImage";import { useMissionDrag } from "@/store/missionDrag";@@ -595,13 +588,6 @@ function isPlumbingArtifact(path: string): boolean {);}-const ARCHIVED_DELIVERABLE_PREFIX = /^tasks\/[^/]+\/artifacts\/files\//;--/** Hide archive plumbing from the label while retaining the full path for APIs. */-function deliverableDisplayPath(path: string): string {- return path.replace(ARCHIVED_DELIVERABLE_PREFIX, "");-}-/** Put primary top-level files first, then group nested assets alphabetically. */function compareDeliverablePaths(a: ArtifactSummary, b: ArtifactSummary): number {const left = deliverableDisplayPath(a.path);@@ -652,197 +638,14 @@ function ArtifactsSection({ slug }: { slug: string }) {{t("outputs_view.no_files")}</div>) : (- <ul className="flex flex-col gap-1">- {files.map((f) => (- <ArtifactRow- key={f.path}- slug={slug}- file={f}- nativeActions={nativeActions}- />- ))}- </ul>- )}- </section>- );-}--function ArtifactRow({- slug,- file,- nativeActions,-}: {- slug: string;- file: ArtifactSummary;- nativeActions: boolean;-}) {- const t = useT();- const [expanded, setExpanded] = useState(false);- const [chooserOpen, setChooserOpen] = useState(false);- const full = useArtifactFile(slug, expanded ? file.path : null);- const openUrl = artifactOpenUrl(slug, file.path);- const openers = useOpeners();- const preferred = usePreferredOpener();- const setPreferred = useSetPreferredOpener();-- // The render endpoint as an ABSOLUTE url. The open-external bridge resolves it- // through `open_url`, which validates an http(s) absolute url — a relative path- // would 400 there and leave only the (WebView2-dropped) window.open fallback.- const absoluteOpenUrl = openUrl- ? new URL(openUrl, window.location.origin).toString()- : null;-- // Open the artifact's render url in the user's real default browser. Routes- // through openExternalUrl (the backend open-external bridge), NOT a bare- // window.open — the embedded WebView2 desktop shell silently drops- // window.open / target="_blank", which is exactly why the "Browser" opener did- // nothing on the desktop. The bridge opens the OS default browser on every OS- // and falls back to a window.open tab on a headless/remote host.- const openInBrowser = () => {- if (absoluteOpenUrl) void openExternalUrl(absoluteOpenUrl);- };-- const openWithOpener = (opener: string) => {- if (opener === "browser" && absoluteOpenUrl) {- openInBrowser();- return;- }- void openArtifactWith(slug, file.path, opener).catch(() => {});- };-- // Open the file with a specific app (desktop). Remembering persists the- // choice so the next "Open" click skips the chooser.- const pickOpener = (opener: string, remember: boolean) => {- openWithOpener(opener);- if (remember) setPreferred.mutate(opener);- setChooserOpen(false);- };-- const handleOpen = () => {- if (!nativeActions) {- // Headless VPS / web: the UI is already a real browser tab. openExternalUrl- // asks the backend first (no display there -> opened:false) and falls back- // to a window.open tab, so the render URL opens in the user's own browser.- openInBrowser();- return;- }- const pref = preferred.data ?? "";- if (pref) {- openWithOpener(pref);- } else {- setChooserOpen(true); // first time: ask which app- }- };-- const sizeLabel =- file.size < 1024- ? `${file.size} B`- : file.size < 1024 * 1024- ? `${(file.size / 1024).toFixed(1)} KiB`- : `${(file.size / (1024 * 1024)).toFixed(1)} MiB`;-- const previewText = expanded- ? full.data?.text ?? file.preview ?? ""- : file.preview;-- return (- <li className="rounded-lg border border-border/60 bg-background/40">- <div className="flex w-full items-center gap-1 px-3 py-2">- <button- type="button"- onClick={() => setExpanded((v) => !v)}- className="flex min-w-0 flex-1 items-center gap-2 text-left hover:bg-secondary/30"- >- {expanded ? (- <ChevronDown className="h-3 w-3 shrink-0 text-muted-foreground" />- ) : (- <ChevronRight className="h-3 w-3 shrink-0 text-muted-foreground" />- )}- <span- className="min-w-0 flex-1 truncate font-mono text-[11px]"- data-testid="artifact-path"- title={file.path}- >- {deliverableDisplayPath(file.path)}- </span>- </button>- <span className="shrink-0 text-[10px] text-muted-foreground">- {sizeLabel}- </span>- <div className="flex shrink-0 items-center gap-0.5">- {(nativeActions || openUrl) && (- <button- type="button"- title={t("outputs_view.open_action")}- onClick={handleOpen}- className="rounded p-1 hover:bg-secondary/40"- >- <ExternalLink className="h-3.5 w-3.5 text-muted-foreground" />- </button>- )}- {nativeActions && (- <button- type="button"- title={t("outputs_view.open_with_change")}- onClick={() => setChooserOpen(true)}- className="rounded p-1 hover:bg-secondary/40"- >- <ChevronDown className="h-3.5 w-3.5 text-muted-foreground" />- </button>- )}- {nativeActions && (- <button- type="button"- title={t("outputs_view.reveal_in_folder")}- onClick={() =>- void revealArtifact(slug, file.path).catch(() => {})- }- className="rounded p-1 hover:bg-secondary/40"- >- <FolderOpen className="h-3.5 w-3.5 text-muted-foreground" />- </button>- )}- </div>- </div>-- {chooserOpen && (- <OpenWithDialog- openers={openers.data ?? []}- onPick={pickOpener}- onClose={() => setChooserOpen(false)}+ <ArtifactViewer+ key={slug}+ slug={slug}+ files={files}+ nativeActions={nativeActions}/>)}-- {expanded && (- <div className="border-t border-border/40 px-3 py-2">- {!file.is_text ? (- <div className="text-[11px] text-muted-foreground">- {t("outputs_view.binary_file_hint")}- </div>- ) : full.isLoading ? (- <div className="flex items-center gap-2 text-[11px] text-muted-foreground">- <Loader2 className="h-3 w-3 animate-spin" />- {t("outputs_view.loading_file")}- </div>- ) : full.isError ? (- <div className="text-[11px] text-destructive">- {t("common.error")}: {String(full.error)}- </div>- ) : (- <>- <pre className="max-h-96 overflow-auto whitespace-pre-wrap break-words text-[11px] font-mono text-foreground/90">- {previewText || ""}- </pre>- {full.data?.truncated && (- <div className="mt-1 text-[10px] text-muted-foreground">- {t("outputs_view.file_truncated")}- </div>- )}- </>- )}- </div>- )}- </li>+ </section>);}