fix(web): open artifacts outside the installed app context

This commit is contained in:
2026-10-20 20:03:41 +01:00
parent 5014c9e61f
commit 06dddb002a
13 changed files with 388 additions and 92 deletions
+45
View File
@@ -0,0 +1,45 @@
// Artifacts are documents, not app destinations. Android can capture even
// _blank links inside an installed PWA's scope; use an explicit VIEW hand-off
// there, retaining ordinary URLs for copy/share and every other environment.
export function artifactBrowserLinkProps(value, environment = globalThis) {
if (typeof value !== "string" || value.trim() === "") return null;
let url;
try {
url = new URL(String(value ?? ""), environment.location?.href);
} catch {
return null;
}
if (!["http:", "https:"].includes(url.protocol) || url.username || url.password) return null;
const standalone = environment.navigator?.standalone === true ||
environment.matchMedia?.("(display-mode: standalone)")?.matches === true ||
environment.matchMedia?.("(display-mode: fullscreen)")?.matches === true;
const userAgent = environment.navigator?.userAgent ?? "";
const android = /Android/i.test(userAgent);
// An implicit HTTPS VIEW intent can resolve straight back to this WebAPK.
// Pin the browser family, never the installed app's link-capturing package.
const browserPackage = /EdgA\//i.test(userAgent) ? "com.microsoft.emmx"
: /SamsungBrowser\//i.test(userAgent) ? "com.sec.android.app.sbrowser"
: /OPR\//i.test(userAgent) ? "com.opera.browser"
: /Firefox\//i.test(userAgent) ? "org.mozilla.firefox"
: "com.android.chrome";
// Intent.parseUri uses the LAST #Intent marker, so an original document
// fragment remains data. Every field after our marker is fixed or encoded;
// untrusted artifact names/fragments cannot inject intent extras or packages.
const href = android && standalone
? `intent:${url.href.slice(url.protocol.length)}#Intent;scheme=${url.protocol.slice(0, -1)};action=android.intent.action.VIEW;category=android.intent.category.BROWSABLE;package=${browserPackage};S.browser_fallback_url=${encodeURIComponent(url.href)};end`
: url.href;
return { href, target: "_blank", rel: "external noopener noreferrer", referrerpolicy: "no-referrer" };
}
/** Recognize same-origin artifacts, including root-relative Markdown links;
* never turn arbitrary SPA paths or javascript/data URLs into navigation. */
export function isLocalArtifactLink(value, base) {
if (!String(value ?? "").startsWith("/artifacts/") && !/^https?:\/\//i.test(String(value ?? ""))) return false;
try {
const url = new URL(value, base);
return url.origin === new URL(base).origin && url.pathname.startsWith("/artifacts/");
} catch {
return false;
}
}
+15
View File
@@ -2,6 +2,9 @@
// node with these functions; server-derived text is always assigned through
// textContent, never innerHTML.
import { artifactBrowserLinkProps } from "./artifactNavigation.js";
export { artifactBrowserLinkProps } from "./artifactNavigation.js";
export function h(tag, props = {}, ...children) {
const node = document.createElement(tag);
for (const [key, value] of Object.entries(props)) {
@@ -19,6 +22,18 @@ export function h(tag, props = {}, ...children) {
return node;
}
/** Run synchronously inside a click/keyboard gesture: Android rejects intents
* launched from timers. Never fall back to replacing the app's own location. */
export function openArtifactInBrowser(resolved) {
const props = artifactBrowserLinkProps(resolved);
if (!props) return false;
const link = h("a", { ...props, hidden: true });
document.body.append(link);
link.click();
link.remove();
return true; // A hand-off was requested; the OS decides which browser handles it.
}
/** One small live-stream badge (LiveBadge.kt): a dot plus the honest word. */
export function renderLiveBadge(info) {
return h(
+9 -4
View File
@@ -3,7 +3,8 @@
// slash commands, notices and the local rename/hide/seen store. Pure models live
// in chat.js and markdown.js; this module owns the DOM and the chat wire wiring.
import { backChevronIcon, h } from "../dom.js";
import { backChevronIcon, h, artifactBrowserLinkProps } from "../dom.js";
import { isLocalArtifactLink } from "../artifactNavigation.js";
import { formFieldVisible, formFieldValue, formAnswerError, visibleFormAnswers, safeFormURL } from "../chatForms.js";
import { readChatStars, writeChatStars } from "../chatStars.js";
import { chatModelLabel, chatModelSelectionNote, supportsChatModels } from "../chatModels.js";
@@ -3795,13 +3796,17 @@ function renderInlineNodes(spans) {
if (span.kind === "strong") return h("strong", {}, ...renderInlineNodes(span.spans));
if (span.kind === "emphasis") return h("em", {}, ...renderInlineNodes(span.spans));
if (span.kind === "link") {
// Only http(s) targets become links: the transcript is untrusted model
// Only HTTP(S) or validated same-origin artifact targets become links:
// the transcript is untrusted model
// output, so a javascript:/data: target is shown as its label, never made
// clickable. Nothing is dropped either way.
if (/^https?:\/\//i.test(span.url)) {
const artifact = isLocalArtifactLink(span.url, globalThis.location?.href);
const linkProps = artifact ? artifactBrowserLinkProps(span.url)
: /^https?:\/\//i.test(span.url) ? { href: span.url, rel: "noreferrer noopener", target: "_blank" } : null;
if (linkProps) {
return h(
"a",
{ class: "md-link", href: span.url, rel: "noreferrer noopener", target: "_blank" },
{ class: "md-link", ...linkProps },
...renderInlineNodes(span.spans),
);
}
+6 -9
View File
@@ -2,7 +2,7 @@
// the rendered/raw diff viewer, the artifact viewer, the human-decision sheet,
// the shared cancel/retry confirm and the shared Action-failed report.
import { backChevronIcon, h, canCopyLink, canShare, copyArtifactLink, copyText, shareArtifact } from "../dom.js";
import { backChevronIcon, h, canCopyLink, canShare, copyArtifactLink, copyText, shareArtifact, artifactBrowserLinkProps } from "../dom.js";
import { changeKindTone, describeError } from "../format.js";
import { definitionDocument } from "./stageDefinition.js";
import {
@@ -663,9 +663,7 @@ function openArtifactViewer(viewable, startIndex, trigger = null) {
error.append(
h("a", {
class: "viewer-external",
href: resolved,
target: "_blank",
rel: "noreferrer",
...artifactBrowserLinkProps(resolved),
text: `Open ${name} externally`,
}),
);
@@ -752,12 +750,11 @@ function openArtifactViewer(viewable, startIndex, trigger = null) {
}
if (resolved) {
actions.append(
h("button", {
class: "viewer-action",
type: "button",
h("a", {
class: "viewer-action browser-button",
...artifactBrowserLinkProps(resolved),
"data-viewer-focus": "open",
text: "Open",
onclick: () => window.open(resolved, "_blank", "noopener,noreferrer"),
text: "Open in browser",
}),
h("button", {
class: "viewer-action",
+25 -49
View File
@@ -3,7 +3,7 @@
// the run's artifact gallery. Pure models live in runDetail.js, changes.js,
// artifacts.js and actions.js; dialogs are delegated to dialogs.js.
import { backChevronIcon, h, kvMono, canCopyLink, canShare, copyArtifactLink, shareArtifact } from "../dom.js";
import { backChevronIcon, h, kvMono, canCopyLink, canShare, copyArtifactLink, shareArtifact, artifactBrowserLinkProps, openArtifactInBrowser } from "../dom.js";
import { isExecuting, changeKindTone, describeError } from "../format.js";
import { resolveArtifactUrl } from "../serverUrl.js";
import { runStateOf, runStatusLabel } from "../runs.js";
@@ -280,9 +280,7 @@ function auditArtifact(step, name, emptyMessage) {
toggle,
h("a", {
class: "audit-doc-open",
href: resolved,
target: "_blank",
rel: "noreferrer",
...artifactBrowserLinkProps(resolved),
text: "Open raw file",
}),
);
@@ -324,9 +322,7 @@ function auditSession(step) {
{ class: "audit-doc-bar" },
h("a", {
class: "audit-doc-open",
href: resolved,
target: "_blank",
rel: "noreferrer",
...artifactBrowserLinkProps(resolved),
text: "Open raw file",
}),
),
@@ -837,16 +833,11 @@ function renderVerdictBlock(step) {
return wrap;
}
/** One inline artifact reference in a verdict reason (viewer files open the viewer). */
/** Open references in the browser; preview is an explicit gallery action. */
function renderVerdictLink(text, artifact, step) {
const resolved = resolvedArtifactUrl(artifact, state.url);
if (!resolved) return h("span", { class: "verdict-link disabled", text });
const link = h("a", { class: "verdict-link", href: resolved, target: "_blank", rel: "noreferrer", text });
link.addEventListener("click", (event) => {
event.preventDefault();
openArtifactFromVerdict(artifact, step, resolved, link);
});
return link;
return h("a", { class: "verdict-link", ...artifactBrowserLinkProps(resolved), text });
}
/** One compact chip naming a referenced artifact. */
@@ -857,24 +848,10 @@ function renderVerdictRef(artifact, step) {
type: "button",
text: artifact.name || "(unnamed artifact)",
});
chip.addEventListener("click", () => openArtifactFromVerdict(artifact, step, resolved, chip));
chip.addEventListener("click", () => openArtifactInBrowser(resolved));
return chip;
}
/** 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);
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. */
function openStagePane(stageKey, visitIndex, { updateRoute = true } = {}) {
state.runStagePane = { stageKey, visitIndex };
@@ -1130,12 +1107,10 @@ function renderArtifactListRow(artifact, viewable, viewerIndexOf) {
open.append(h("span", { class: "artifact-kind", text: artifactKindLabel(kind) }));
open.append(h("span", { class: "artifact-list-name", text: name }));
open.append(h("span", { class: "artifact-size", text: humanBytes(artifact.size_bytes) }));
open.addEventListener("click", () => {
const at = viewerIndexOf.get(artifact.url);
if (opensViewer && at != null) openArtifactViewer(viewable, at, open);
else if (resolved) window.open(resolved, "_blank", "noopener,noreferrer");
});
wrap.append(open, renderTileActions(resolved, media));
open.addEventListener("click", () => openArtifactInBrowser(resolved));
const at = viewerIndexOf.get(artifact.url);
wrap.append(open, renderTileActions(resolved, media, opensViewer && at != null
? (trigger) => openArtifactViewer(viewable, at, trigger) : null, name));
return wrap;
}
@@ -1202,18 +1177,18 @@ function renderArtifactTile(artifact, viewable, viewerIndexOf) {
"data-artifact-url": artifact.url ?? "",
title: name,
});
const openViewer = () => {
const openViewer = (trigger = tile) => {
const at = viewerIndexOf.get(artifact.url);
if (at != null) openArtifactViewer(viewable, at, tile);
if (at != null) openArtifactViewer(viewable, at, trigger);
};
const openTab = () => {
if (resolved) window.open(resolved, "_blank", "noopener,noreferrer");
if (resolved) openArtifactInBrowser(resolved);
};
if (kind === ArtifactKind.Image) {
const img = h("img", { class: "artifact-thumb", alt: name, loading: "lazy" });
if (resolved) img.src = resolved;
tile.append(img);
tile.addEventListener("click", openViewer);
tile.addEventListener("click", openTab);
} else if (kind === ArtifactKind.Video) {
tile.append(
h(
@@ -1223,7 +1198,7 @@ function renderArtifactTile(artifact, viewable, viewerIndexOf) {
),
);
tile.append(h("div", { class: "artifact-name", text: name }));
tile.addEventListener("click", openViewer);
tile.addEventListener("click", openTab);
} else {
if (opensViewer) {
tile.classList.add("artifact-document-tile");
@@ -1234,19 +1209,20 @@ function renderArtifactTile(artifact, viewable, viewerIndexOf) {
h("div", { class: "artifact-name", text: name }),
h("div", { class: "artifact-size", text: humanBytes(artifact.size_bytes) }),
);
tile.addEventListener("click", opensViewer ? openViewer : openTab);
tile.addEventListener("click", openTab);
}
wrap.append(tile, renderTileActions(resolved, media));
wrap.append(tile, renderTileActions(resolved, media, opensViewer ? openViewer : null, name));
return wrap;
}
/** The compact per-tile actions: icon-only link/share, shown on hover or focus. */
function renderTileActions(resolved, media) {
function renderTileActions(resolved, media, preview = null, name = "artifact") {
const actions = h("div", { class: "artifact-actions" });
const stop = (fn) => (event) => {
event.stopPropagation();
fn();
fn(event.currentTarget);
};
if (preview) actions.append(artifactAction("preview", `Preview in app: ${name}`, !resolved, stop(preview)));
if (!media) {
actions.append(
artifactAction("link", "Copy link", !resolved || !canCopyLink(), stop(() => copyArtifactLink(resolved))),
@@ -1275,7 +1251,9 @@ function artifactAction(kind, label, disabled, onclick) {
svg.setAttribute("aria-hidden", "true");
svg.setAttribute("focusable", "false");
const path = document.createElementNS(ARTIFACT_SVG_NS, "path");
path.setAttribute("d", kind === "link"
path.setAttribute("d", kind === "preview"
? "M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12ZM15 12a3 3 0 1 1-6 0a3 3 0 0 1 6 0Z"
: kind === "link"
? "M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"
: "M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8M16 6l-4-4-4 4M12 2v13");
path.setAttribute("fill", "none");
@@ -1302,7 +1280,7 @@ function renderSessionExport(step) {
row.append(h("span", { text: `Repair: ${repair.status || "partial"} · ${repair.messages || 0} messages. ${repair.diagnostic || ""}` }));
const repaired = sessionExportArtifact({ ...step, session_export: repair });
const repairedHref = repaired && resolvedArtifactUrl(repaired, state.url);
if (repairedHref) row.append(h("a", { href: repairedHref, target: "_blank", rel: "noreferrer", text: "Open repaired export" }));
if (repairedHref) row.append(h("a", { ...artifactBrowserLinkProps(repairedHref), text: "Open repaired export" }));
wrap.append(row);
}
const evidence = step?.session_export;
@@ -1319,9 +1297,7 @@ function renderSessionExport(step) {
wrap.append(
h("a", {
class: "session-link",
href,
target: "_blank",
rel: "noreferrer",
...artifactBrowserLinkProps(href),
text: `Open ${file.name || "session.html"}`,
}),
);
+5 -22
View File
@@ -2,10 +2,10 @@
// routing. Debounce/staleness/ordering/empty-state decisions are pure in
// search.js; this module owns the DOM and the route hand-off.
import { h } from "../dom.js";
import { h, openArtifactInBrowser } from "../dom.js";
import { describeError } from "../format.js";
import { resolveArtifactUrl } from "../serverUrl.js";
import { ArtifactKind, artifactKind, isViewerArtifact } from "../artifacts.js";
import { ArtifactKind, artifactKind } from "../artifacts.js";
import {
DEFAULT_SEARCH_KIND,
DEFAULT_SEARCH_SORT,
@@ -623,31 +623,14 @@ function renderSearchResultRow(hit) {
async function routeSearchResult(hit) {
const target = searchTarget(hit);
if (!target) return;
// An artifact hit opens the artifact, not the run/visit that recorded it: media
// in the viewer, anything else in a tab. Nothing to show means no navigation.
// All artifact types open in the browser. In-app preview is an explicit
// gallery action, never an unexpected navigation away from the installed app.
if (hit?.kind === "artifact" && hit.artifact?.url) {
const artifact = hit.artifact;
const resolved = resolveArtifactUrl(state.url, artifact.url);
if (!resolved) return;
closeSearch();
// Media, markdown and text all belong in the viewer, which now renders the
// document and offers the trip back to the run; anything else opens raw.
if (isViewerArtifact(artifact.content_type, artifact.name)) {
rt.views.dialogs.openArtifactViewer(
[
{
url: artifact.url,
name: artifact.name,
content_type: artifact.content_type,
size_bytes: artifact.size_bytes,
run_id: artifact.run_id,
},
],
0,
);
} else {
window.open(resolved, "_blank", "noopener,noreferrer");
}
openArtifactInBrowser(resolved);
return;
}
closeSearch();