From 359912f82245d8f1e7589a9617aaceea2ee350c5 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Mon, 19 Oct 2026 21:23:10 +0100 Subject: [PATCH] web: render stage-turn markdown in the artifact viewer The full-screen viewer now opens markdown/text artifacts (text/markdown, text/plain, .md/.markdown/.txt) through the resolved artifact URL and renders them with the page's own DOM markdown renderer, with an honest failure message and an external fallback. ArrowLeft/ArrowRight page the shared media+document list, and a backdrop click closes the viewer while panel clicks do not. The run gallery and per-visit artifacts present input.md, memory.md and output.md as ordinary Document tiles with a drawn glyph and open the viewer. Adds isMarkdownArtifact/isViewerArtifact with unit coverage, deterministic viewer fixtures, and ui-smoke assertions/captures for rendered markdown, keyboard paging, the honest 404 and backdrop dismissal. --- web/PARITY.md | 2 +- web/dialogs.css | 85 +++++++ web/src/artifacts.js | 51 ++++- web/src/views/dialogs.js | 154 +++++++++++-- web/src/views/runDetail.js | 32 ++- web/test/artifacts.test.mjs | 86 ++++++- web/test/fixtures/artifacts/input.md | 7 + web/test/fixtures/artifacts/memory.md | 3 + web/test/fixtures/artifacts/output.md | 6 + web/test/fixtures/artifacts/shot.png | Bin 0 -> 68 bytes web/test/ui-smoke.mjs | 317 +++++++++++++++++++++++++- 11 files changed, 695 insertions(+), 48 deletions(-) create mode 100644 web/test/fixtures/artifacts/input.md create mode 100644 web/test/fixtures/artifacts/memory.md create mode 100644 web/test/fixtures/artifacts/output.md create mode 100644 web/test/fixtures/artifacts/shot.png diff --git a/web/PARITY.md b/web/PARITY.md index 24a23e48..27435e80 100644 --- a/web/PARITY.md +++ b/web/PARITY.md @@ -38,7 +38,7 @@ Status legend: `todo` · `partial` (some of it works) · `done` (working + captu | R5 | Graph tab (per-stage panes, verdicts) | `get_run` | done — the run detail's Graph tab (between Summary and Input) mounts the shared `src/graph.js` renderer in run mode with the app's run note: a visited stage is executed (solid fill + border), an unvisited one hollow with a dashed muted border, a terminal executed only when a visit resolved to it, a route executed only when a visit produced that outcome (solid with an arrowhead; success first, error last, others alphabetical, `error*` for a fallback error route), the Executed / Not executed legend (runs only, never the definition view), and — while executing — the current stage's pulsing halo + elapsed badge (a static ring under `prefers-reduced-motion`; nothing for a finished run). Clicking a stage opens the existing visit pane at that stage's latest visit with its Verdict; Back/Escape close it and restore focus. The empty state is the exact `This server did not include the run graph.` (unit-tested; no live run currently carries a graph-less payload). Captured 2026-10-19: `captures/28-run-438-graph.png` (finished run 438: legend + executed styling + dashed untaken routes), `captures/29-run-438-graph-pane.png` (a graph-opened stage pane showing a Verdict), `captures/30-run-440-graph.png` (failed run 440: hollow/dashed not-executed stages) | | R6 | Input / Output field sections per stage | `get_run` | done — one collapsed section per recorded entry, expanded as a monospace block (primitives verbatim, arrays `, `-joined, objects `k=v` `, `-joined), empty states "No input recorded." / "No output recorded.". Captured 2026-10-19: `captures/21-run-430-input.png`, `captures/22-run-430-output.png`, `captures/27-run-output-empty.png` | | R7 | Timeline | `get_run` | done — one compact row per visit (`{stage} · visit {n}`, stage-outcome chip, paperclip when artifacts recorded, duration, description = first non-blank diagnostic line else `→ {target}`); empty state "No visits recorded.". Captured 2026-10-19: `captures/23-run-430-timeline.png`, `captures/26-run-428-timeline-empty.png` | -| R8 | Artifacts gallery + full-screen viewer (images inline, others download/open) | `GET /artifacts/…` | done (captured 2026-10-19: `captures/04-run-430-artifacts.png`, `captures/05-artifact-viewer.png`) | +| R8 | Artifacts gallery + full-screen viewer (images inline, markdown/text rendered, others download/open) | `GET /artifacts/…` | done — the gallery keeps images (lazy thumbnails) and videos (poster, never autoplay) and now also presents `text/markdown`, `text/plain`, `.md`, `.markdown` and `.txt` artifacts as ordinary **Document** tiles (drawn page glyph + the existing `Document` label; `data-artifact-name` / `data-artifact-kind` metadata), including the stage-turn `input.md`, `memory.md` and `output.md` in both the per-visit section and the run gallery. Clicking one opens the existing full-screen viewer, whose dim backdrop contains one `.viewer-panel`; only a click on the backdrop (never inside the panel) or Escape/Close dismisses it. The document is fetched through the resolved artifact URL (same-origin via `serve.mjs`'s `/artifacts/` proxy) once per viewer session and rendered with the page's own `src/markdown.js` DOM renderer (headings, lists, tables, fenced code, links; never `innerHTML`); a failed fetch/render shows `describeError`'s honest message plus `Open {name} externally` at the resolved URL, while Open/Copy link/Share stay available. Images/videos are unchanged. ArrowLeft/ArrowRight page the same media+markdown list as the buttons (clamped, no wrap, disabled at the ends), and a re-render keeps focus inside the viewer. Pure selection in `src/artifacts.js` (`isMarkdownArtifact`, `isViewerArtifact`, extended `pagedArtifacts`), unit-tested in `test/artifacts.test.mjs`. Captured 2026-10-19 with the deterministic `--viewer` fixture run (ordinary artifacts, no new wire field): `captures/44-viewer-turn-documents.png` (input.md/memory.md/output.md as Documents in both galleries), `captures/45-viewer-markdown-rendered.png` (heading + fenced code fetched from the resolved URL), `captures/46-viewer-markdown-next.png` (ArrowRight advanced to the image artifact), `captures/47-viewer-markdown-failure.png` (honest 404 message + `Open missing.txt externally`) and `captures/48-viewer-markdown-backdrop-closed.png` (a panel click stayed open; the backdrop closed it). The pre-existing image viewer capture `captures/05-artifact-viewer.png` remains the unchanged-behaviour evidence. | | R9 | Session export link (read-only `session.html`) | `GET /artifacts/…` | done (captured 2026-10-19: `captures/06-session-export-link.png`) | | R10 | Live run updates: subscribe/unsubscribe + event fold | `subscribe`, `unsubscribe`, `run_event` | done — one app-wide watch owned by the connection, never by a screen: becoming connected best-effort `unsubscribe`s the previous watch, sends `{type:'subscribe',workspace:''}` send-only (no `run_ids`; `{type:'unsubscribe'}` drops it), then takes one authoritative resync (`list_runs`, plus one `get_run` when a run detail is open); a socket drop clears the watch and no screen change ever unsubscribes. `src/runEvents.js` is the pure fold ported from `ui/RunEvents.kt` (in-place list update preserving order, insert-at-head from the frame's pipeline identity, `needsResync` without identity, detail merge with explicit `resource_wait` set/clear, one step matched by `sequence` and inserted in sequence order, the monotonic run/step ladders and the full-sync decision) and is unit-tested in `test/runEvents.test.mjs`; the send-only path (`src/client.js#sendOnly`), the exact watch frames (`src/repository.js`) and the `run_event`/unsolicited-frame dispatch are unit-tested in `test/client.test.mjs` and `test/repository.test.mjs`. The 1 s run-detail poll is removed — pushed frames drive the detail and a settled/terminal frame triggers one coalesced `get_run` (at most one in flight per kind plus one queued follow-up, retried at 500 ms × attempt at most 3 times before the badge drops to `reconnecting`); the only surviving intervals are render-only clocks. The badge is the explicit stream state (`live` / `reconnecting` / `not live`, LiveBadge.kt words), independent of whether a run is executing, on the Runs list and the run detail. Captured 2026-10-19 against the live server with a **real pushed run** started by the smoke in a throwaway workspace: `captures/75-run-live-list.png` (the new run's row inserted from its own frame, badge `live`), `captures/76-run-live-detail.png` (the open detail folded to `running` from pushes, badge `live`) and `captures/77-run-live-terminal.png` (the pushed terminal fold to `canceled`, no poll), plus the reachable badge states `captures/28-connected-banner.png` (live), `captures/29-disconnected-banner.png` (not live while idle; reconnecting while the socket retries) and `captures/30-reconnect-recovered.png` (live again). `test/ui-smoke.mjs` asserts the reconnect wire order (unsubscribe → subscribe blank-workspace → list_runs) and that at least one genuine `run_event` frame for the started run arrived. The R10 step itself passes on every run; the full smoke can still fail later in unrelated, pre-existing steps on the shared live server (observed after the main merge: a flaky L1 stale page-level error on one run, a C5 chat fold `expected at least one folded agent turn, got 0` on another, and a C8 composer assertion while the operator's live chat session was streaming, so the composer correctly showed Stop; the focused `--notify` run is `UI SMOKE PASS`), which is not an R10 defect. | | R11 | Human decision sheet: prompt, options, feedback | `decide_run` | done — the pure model (`src/actions.js`: `pendingDecision`, `lastWaitingStep`, `waitingPrompt`/`waitingOptions`, `humanOptions`, `decisionTargetLabel`, `DecisionDraft`) and the card + sheet are implemented with the Android copy verbatim: card title `Waiting for your decision`, meta `{stage} · run {id} · {runLabel}`, action `Decide`; sheet title `Decide {stage}`, meta `run {id} · {runLabel}`, the recorded instructions verbatim when non-blank, one selectable row per option in author order showing the option and `→ {target}` only when the declared edge resolves, the `Feedback (optional)` field, and `Cancel` / `Confirm decision` (reading `Sending…` while in flight). Selecting a row sends nothing and Confirm is disabled until a non-blank option is chosen; a refusal keeps the sheet open with the server's exact reason and re-reads the run. The request shape is unit-tested (`decide_run` = `{type, run_id, option, stage?, feedback?}`, stage/feedback omitted when blank, feedback trimmed). **Live, end to end (2026-10-19)**: `test/ui-smoke.mjs` gained an explicit `--decide` mode (the only mode allowed to submit). It reused the entry-stage human-only pipeline submitted create-only as `Web R11 decision 2026-10-19T14-59-18-785Z` (id 30: one `type=human` `gate` stage, `approve -> #success`, `hold -> #success`, `error -> #failure`, so no model stage runs) and started two runs in separate fresh temp workspaces. Run 513 parked in `waiting`; the browser asserted the card (`Waiting for your decision`, `gate · run 513 · Web R11 decision 1 (feedback)`, `Decide`), opened the sheet (`Decide gate`, `run 513 · …`, the recorded instructions `R11 live decision: review the run and choose approve or hold.`, `approve`/`hold` in author order each with `→ SUCCESS`, `Feedback (optional)`, Confirm disabled), selected `approve` (still no `decide_run`, and the run was still `waiting` via `pipelines inspect`), typed feedback, and pressed `Confirm decision`: exactly one frame `{"type":"decide_run","run_id":513,"option":"approve","stage":"gate","feedback":"Approved in the live browser decision sheet."}` was sent, the run left `waiting`, resumed and reached `succeeded`. Run 514 proved the no-feedback shape: selecting `hold` sent nothing, Confirm sent `{"type":"decide_run","run_id":514,"option":"hold","stage":"gate"}` with **no** `feedback` key, the run reached `succeeded`, its recorded feedback is blank and its verdict carries no reason. Captured: `captures/41-run-513-decision-card.png` (waiting card), `captures/42-run-513-decision-sheet.png` (open sheet with the options), `captures/43-run-513-decision-selected.png` (selected + feedback, Confirm enabled), `captures/44-run-513-decision-confirmed.png` (resumed detail, `succeeded`), `captures/45-run-513-decision-verdict.png` (`gate · visit 1` Verdict chip `approve → success` and the exact reason), and the no-feedback path `captures/46-run-514-decision-card.png`, `captures/47-run-514-decision-sheet.png`, `captures/48-run-514-decision-selected.png`, `captures/49-run-514-decision-confirmed.png`, `captures/50-run-514-decision-verdict.png` (`hold → success`, no reason). Command: `cd web && node test/ui-smoke.mjs --decide --out "$PWD/captures"` → `UI SMOKE PASS` (the reused pipeline means no new submit on the capture run); `cd web && node --test test/` stays green. Both runs are terminal, no R11 run remains active and both temp workspaces were removed. The submitted definition is intentionally retained and named here; no operator pipeline, version, run, chat or repository was modified. Re-verified after merging `main` (2026-10-19): the same reused pipeline parked runs 522 and 523, the same `--decide` check ended `UI SMOKE PASS` with `captures/41-run-522-decision-card.png` through `captures/50-run-523-decision-verdict.png`, and the full default live suite also ended `UI SMOKE PASS` (its R11 step still skips only because no operator run was waiting at that moment) | diff --git a/web/dialogs.css b/web/dialogs.css index 8b727828..aa69dd86 100644 --- a/web/dialogs.css +++ b/web/dialogs.css @@ -422,3 +422,88 @@ } .rename-input:focus { outline: none; border-color: var(--accent); } .rename-save { border-color: var(--accent); color: var(--accent); font-weight: 600; } + +/* --------------------------------------------------------------------------- + Artifact viewer (R8): the dim backdrop and its one panel, the rendered + markdown document body and the markdown's document tile. The gallery/viewer + wiring lives in views/runDetail.js and views/dialogs.js; every server string + is still set with textContent. + --------------------------------------------------------------------------- */ + +/* The tile treats a markdown/text file as an ordinary document: a small drawn + page glyph above the existing uppercase "Document" kind label, never a media + poster. The glyph is CSS, so it needs no emoji font; the extra top padding + keeps it clear of the absolutely positioned Copy link / Share actions. */ +.artifact-document-tile { padding-top: 34px; } +.artifact-doc-glyph { + position: relative; + display: block; + width: 18px; + height: 22px; + border: 1.5px solid var(--muted); + border-radius: 2px; +} +.artifact-doc-glyph::before, +.artifact-doc-glyph::after { + content: ""; + position: absolute; + left: 3px; + right: 3px; + height: 1.5px; + background: var(--muted); +} +.artifact-doc-glyph::before { top: 6px; } +.artifact-doc-glyph::after { top: 11px; } + +.artifact-viewer { + z-index: 60; + align-items: center; + justify-content: center; + padding: 24px; + background: rgba(0, 0, 0, 0.78); +} +.viewer-panel { + display: flex; + flex-direction: column; + gap: var(--space-s); + width: min(1100px, 100%); + max-height: 100%; + min-height: 0; + padding: 16px; + background: var(--surface); + border: 1px solid var(--border); + border-radius: 14px; + box-shadow: 0 24px 60px rgba(0, 0, 0, 0.55); + outline: none; +} +.viewer-panel:focus { outline: none; } + +/* Markdown/text needs the full board to scroll: a readable column, not a + centred image. The shared md-* classes keep the app's chat typography. */ +.viewer-board-document { + display: block; + overflow-y: auto; + padding: 18px 20px; + background: var(--surface-2); + border: 1px solid var(--border); + border-radius: 10px; +} +.viewer-markdown { + width: 100%; + max-width: 78ch; + margin: 0 auto; +} +.viewer-markdown .md-code-block { max-width: 100%; } +.viewer-markdown .md-pre { overflow-x: auto; } +.viewer-markdown .md-table { display: block; overflow-x: auto; } + +.viewer-loading { padding: 24px; text-align: center; } +.viewer-error { display: grid; gap: 10px; padding: 12px 4px; } +.viewer-error-message { color: var(--bad); line-height: 1.5; } +.viewer-external { color: var(--accent); justify-self: start; } + +@media (max-width: 760px) { + .artifact-viewer { padding: 10px; } + .viewer-panel { padding: 10px; border-radius: 10px; } + .viewer-board-document { padding: 12px; } +} diff --git a/web/src/artifacts.js b/web/src/artifacts.js index bce21416..0d220add 100644 --- a/web/src/artifacts.js +++ b/web/src/artifacts.js @@ -94,6 +94,9 @@ const DOCUMENT_EXTENSIONS = new Set([ "txt", "md", "markdown", "rst", "doc", "docx", "odt", "rtf", "html", "htm", ]); +/** The text file kinds the browser can render in the artifact viewer. */ +const MARKDOWN_EXTENSIONS = new Set(["md", "markdown", "txt"]); + const DOCUMENT_MIMES = new Set([ "application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", @@ -195,6 +198,31 @@ export function artifactKindLabel(kind) { return KIND_LABELS[kind] ?? "File"; } +/** + * Whether an artifact is text the reader can render as markdown in the viewer: + * `text/markdown` or `text/plain` (parameters ignored), or a `.md`, `.markdown` + * or `.txt` name. The viewer uses the page's existing markdown renderer, so these + * are the text files it is allowed to fetch and draw. Pure and total, mirroring + * the content-type tests above. + */ +export function isMarkdownArtifact(contentType, name) { + const mime = String(contentType ?? "").split(";")[0].trim().toLowerCase(); + if (mime === "text/markdown" || mime === "text/plain") return true; + return MARKDOWN_EXTENSIONS.has(extensionOf(name)); +} + +/** + * Whether an artifact opens inside the full-screen viewer: the two media kinds + * the gallery already previewed, plus the markdown/text documents it now renders + * itself. The kind gate keeps a `text/plain` `.log`, `.py` or `.csv` an external + * file: those are evidence, not prose. This is the one predicate the grid tiles, + * paging and the viewer share, so they cannot disagree about the list. + */ +export function isViewerArtifact(contentType, name) { + if (isImageContentType(contentType) || isVideoContentType(contentType)) return true; + return artifactKind(contentType, name) === ArtifactKind.Document && isMarkdownArtifact(contentType, name); +} + /** * Human-readable byte size, matching Android Format.kt humanBytes (and the TUI): * whole bytes under 1 KiB, otherwise one decimal with a binary unit @@ -320,28 +348,29 @@ export function artifactCaptureNotes(step) { } /** - * The media artifacts `groups` hold, in the exact order the gallery draws them - * (group by group, each group's images and videos in recorded order): the - * neighbours the full-screen viewer pages through, so a swipe visits the same - * list the grid showed. Non-media artifacts open externally and are not part of - * it. Mirrors ArtifactViewer.kt pagedArtifacts. + * The artifacts `groups` hold that the full-screen viewer can page through, in + * the exact order the gallery draws them (group by group, each group's images, + * videos and markdown/text documents in recorded order): the neighbours a + * swipe/keyboard step visits, so the viewer walks the same list the grid showed. + * Other artifacts open externally and are not part of it. Mirrors + * ArtifactViewer.kt pagedArtifacts, extended for markdown-first stage turns. */ export function pagedArtifacts(groups) { const viewable = []; for (const group of groups ?? []) { for (const artifact of group?.artifacts ?? []) { - const kind = artifactKind(artifact?.content_type, artifact?.name); - if (kind === ArtifactKind.Image || kind === ArtifactKind.Video) viewable.push(artifact); + if (isViewerArtifact(artifact?.content_type, artifact?.name)) viewable.push(artifact); } } return viewable; } /** - * Each gallery media artifact's url mapped to its position in `pagedArtifacts`, - * the same ordered list the viewer pages through. The grid's tiles resolve their - * viewer index here, so tile and viewer derive from one source and cannot drift. - * The first occurrence of a url wins. Mirrors ArtifactViewer.kt viewerIndexByUrl. + * Each viewer-selectable artifact's url mapped to its position in + * `pagedArtifacts`, the same ordered list the viewer pages through. The grid's + * tiles resolve their viewer index here, so tile and viewer derive from one + * source and cannot drift. The first occurrence of a url wins. Mirrors + * ArtifactViewer.kt viewerIndexByUrl. */ export function viewerIndexByUrl(groups) { const indices = new Map(); diff --git a/web/src/views/dialogs.js b/web/src/views/dialogs.js index 4d77c4ba..c5fe4b95 100644 --- a/web/src/views/dialogs.js +++ b/web/src/views/dialogs.js @@ -23,6 +23,7 @@ import { ArtifactKind, artifactKind, artifactViewerPositionLabel, + isMarkdownArtifact, pagedIndex, resolvedArtifactUrl, } from "../artifacts.js"; @@ -538,42 +539,167 @@ function dismissActionError() { } let viewerOverlay = null; +let viewerSession = null; /** Close the full-screen viewer; the controller returns focus to its trigger. */ function closeArtifactViewer() { + if (viewerSession) { + viewerSession.closed = true; + viewerSession.abort?.abort(); + viewerSession = null; + } modal.close("artifact-viewer"); viewerOverlay = null; } /** * Open the full-screen viewer at `startIndex` into `viewable`, the same ordered - * media list the grid drew. Previous/Next are disabled at the ends and absent for - * a single artifact; Escape and a backdrop click close it. Nothing autoplays: a - * non-image artifact shows a still poster placeholder instead. + * list the grid drew (images, videos and markdown/text documents). Previous/Next + * are disabled at the ends; ArrowLeft/ArrowRight page the same list; Escape and a + * click on the dimmed backdrop close it, while clicks inside the panel never do. + * Nothing autoplays: a video shows a still poster placeholder instead. + * + * Markdown and text artifacts are fetched once per viewer session from the + * resolved artifact URL and rendered with the page's own markdown renderer, + * building DOM nodes (never innerHTML). A failed fetch or render keeps the + * viewer honest: it shows describeError's message, the resolved-external action + * and the normal Open/Copy/Share actions. */ function openArtifactViewer(viewable, startIndex, trigger = null) { closeArtifactViewer(); if (!viewable?.length) return; let index = pagedIndex(startIndex, 0, viewable.length); + const session = { + closed: false, + generation: 0, + abort: null, + cache: new Map(), + errors: new Map(), + }; const overlay = h("div", { class: "artifact-viewer", role: "dialog", "aria-modal": "true", "aria-label": "Artifact viewer", }); + const panel = h("div", { class: "viewer-panel", "data-viewer-focus": "panel", tabindex: "-1" }); + overlay.append(panel); overlay.addEventListener("click", (event) => { if (event.target === overlay) closeArtifactViewer(); }); - const renderViewer = () => { + /** The focus key of the control inside the panel that currently owns focus. */ + const focusedKey = () => { + const active = document.activeElement; + if (!panel.contains(active)) return null; + return active?.getAttribute?.("data-viewer-focus") ?? null; + }; + + /** Keep focus inside the viewer after the panel is rebuilt. */ + const restoreFocus = (key) => { + if (!key) return; + const target = + key === "panel" ? panel : panel.querySelector(`[data-viewer-focus="${key}"]`); + if (target && !target.disabled) target.focus({ preventScroll: true }); + else panel.focus({ preventScroll: true }); + }; + + const step = (delta) => { + const next = pagedIndex(index, delta, viewable.length); + if (next === index) return; + index = next; + renderViewer({ restore: true }); + }; + + overlay.addEventListener("keydown", (event) => { + if (event.key === "ArrowLeft") { + event.preventDefault(); + step(-1); + } else if (event.key === "ArrowRight") { + event.preventDefault(); + step(1); + } + }); + + const renderViewer = ({ restore = false } = {}) => { + const keepFocus = restore ? focusedKey() : null; + const generation = ++session.generation; const artifact = viewable[index] ?? {}; const resolved = resolvedArtifactUrl(artifact, state.url); const kind = artifactKind(artifact.content_type, artifact.name); + const markdown = isMarkdownArtifact(artifact.content_type, artifact.name); const name = artifact.name || "(unnamed artifact)"; const board = h("div", { class: "viewer-board" }); if (kind === ArtifactKind.Image && resolved) { board.append(h("img", { class: "viewer-image", src: resolved, alt: name })); + } else if (kind === ArtifactKind.Video) { + board.append( + h( + "div", + { class: "viewer-placeholder" }, + h("span", { class: "artifact-play", text: "▶" }), + h("span", { class: "viewer-placeholder-name", text: name }), + ), + ); + } else if (markdown) { + board.classList.add("viewer-board-document"); + const renderMarkdown = rt.views?.chat?.renderMarkdown; + const showFailure = (message) => { + const error = h("div", { class: "viewer-error" }); + error.append(h("div", { class: "viewer-error-message", text: message })); + if (resolved) { + error.append( + h("a", { + class: "viewer-external", + href: resolved, + target: "_blank", + rel: "noreferrer", + text: `Open ${name} externally`, + }), + ); + } + board.append(error); + }; + const draw = (text) => { + try { + const article = h("div", { class: "viewer-markdown" }); + article.append(renderMarkdown(text)); + board.append(article); + return true; + } catch (error) { + showFailure(describeError(error)); + return false; + } + }; + if (!resolved) { + showFailure("Set the server URL in Settings to open this artifact."); + } else if (session.cache.has(resolved)) { + draw(session.cache.get(resolved)); + } else if (session.errors.has(resolved)) { + showFailure(session.errors.get(resolved)); + } else if (typeof renderMarkdown !== "function") { + showFailure("Markdown rendering is unavailable."); + } else { + board.append(h("div", { class: "viewer-loading muted", text: "Loading markdown…" })); + session.abort?.abort(); + const controller = new AbortController(); + session.abort = controller; + (async () => { + try { + const response = await fetch(resolved, { signal: controller.signal }); + if (!response.ok) throw new Error(`The server answered ${response.status}.`); + const text = await response.text(); + if (session.closed || generation !== session.generation) return; + session.cache.set(resolved, text); + renderViewer({ restore: true }); + } catch (error) { + if (error?.name === "AbortError" || session.closed || generation !== session.generation) return; + session.errors.set(resolved, describeError(error)); + renderViewer({ restore: true }); + } + })(); + } } else { board.append( h( @@ -601,12 +727,14 @@ function openArtifactViewer(viewable, startIndex, trigger = null) { h("button", { class: "viewer-action", type: "button", + "data-viewer-focus": "open", text: "Open", onclick: () => window.open(resolved, "_blank", "noopener,noreferrer"), }), h("button", { class: "viewer-action", type: "button", + "data-viewer-focus": "copy", text: "Copy link", disabled: !canCopyLink(), onclick: () => copyArtifactLink(resolved), @@ -614,6 +742,7 @@ function openArtifactViewer(viewable, startIndex, trigger = null) { h("button", { class: "viewer-action", type: "button", + "data-viewer-focus": "share", text: "Share", disabled: !canShare(), onclick: () => shareArtifact(resolved), @@ -624,6 +753,7 @@ function openArtifactViewer(viewable, startIndex, trigger = null) { h("button", { class: "viewer-action viewer-close", type: "button", + "data-viewer-focus": "close", text: "Close viewer", onclick: closeArtifactViewer, }), @@ -638,32 +768,30 @@ function openArtifactViewer(viewable, startIndex, trigger = null) { h("button", { class: "viewer-page", type: "button", + "data-viewer-focus": "prev", text: "Previous artifact", disabled: pagedIndex(index, -1, viewable.length) === index, - onclick: () => { - index = pagedIndex(index, -1, viewable.length); - renderViewer(); - }, + onclick: () => step(-1), }), h("button", { class: "viewer-page", type: "button", + "data-viewer-focus": "next", text: "Next artifact", disabled: pagedIndex(index, 1, viewable.length) === index, - onclick: () => { - index = pagedIndex(index, 1, viewable.length); - renderViewer(); - }, + onclick: () => step(1), }), ), ); } nodes.push(actions); - overlay.replaceChildren(...nodes); + panel.replaceChildren(...nodes); + if (restore) restoreFocus(keepFocus ?? "panel"); }; renderViewer(); viewerOverlay = overlay; + viewerSession = session; modal.open("artifact-viewer", overlay, { onClose: () => closeArtifactViewer(), trigger, diff --git a/web/src/views/runDetail.js b/web/src/views/runDetail.js index e2f08f0b..39ff2674 100644 --- a/web/src/views/runDetail.js +++ b/web/src/views/runDetail.js @@ -43,6 +43,7 @@ import { artifactViewerPositionLabel, displayVisit, humanBytes, + isViewerArtifact, pagedArtifacts, presentedArtifacts, resolvedArtifactUrl, @@ -580,7 +581,7 @@ function renderVerdictBlock(step) { return wrap; } -/** One inline artifact reference in a verdict reason (media opens the viewer). */ +/** One inline artifact reference in a verdict reason (viewer files open the viewer). */ function renderVerdictLink(text, artifact, step) { const resolved = resolvedArtifactUrl(artifact, state.url); if (!resolved) return h("span", { class: "verdict-link disabled", text }); @@ -604,17 +605,18 @@ function renderVerdictRef(artifact, step) { return chip; } -/** Open a referenced artifact: media in the viewer, everything else externally. */ +/** Open a referenced artifact: viewer-selectable files in the viewer, others externally. */ function openArtifactFromVerdict(artifact, step, resolved, trigger = null) { if (!resolved) return; const group = { stageKey: step.stage, visit: displayVisit(step, 0), artifacts: presentedArtifacts(step) }; const viewable = pagedArtifacts([group]); const viewerIndexOf = viewerIndexByUrl([group]); const at = viewerIndexOf.get(artifact.url); - const kind = artifactKind(artifact.content_type, artifact.name); - const media = kind === ArtifactKind.Image || kind === ArtifactKind.Video; - if (media && at != null) openArtifactViewer(viewable, at, trigger); - else window.open(resolved, "_blank", "noopener,noreferrer"); + if (isViewerArtifact(artifact.content_type, artifact.name) && at != null) { + openArtifactViewer(viewable, at, trigger); + } else { + window.open(resolved, "_blank", "noopener,noreferrer"); + } } /** Open the stage pane for one visit of a stage; the controller moves focus in. */ @@ -808,7 +810,8 @@ function renderArtifactGallery(steps) { * The per-visit artifacts section shown inside one step: the summary line, the * capture notes, the no-server-URL hint and a headerless grid of that visit's * tiles (matching the Android ArtifactsSection). Its viewer pages only through - * that visit's media, exactly as the Android section does. + * that visit's viewable artifacts (media and markdown), exactly as the Android + * section does. */ function renderVisitArtifacts(step) { const wrap = h("div", { class: "artifacts" }); @@ -842,13 +845,15 @@ function renderArtifactGrid(artifacts, viewable, viewerIndexOf) { /** * One gallery tile: an image thumbnail, a video poster with a play marker (never - * a