fix(web): share artifact files instead of URLs
This commit is contained in:
@@ -8,6 +8,25 @@ test, or a code change without a capture, is `partial` at best.
|
||||
|
||||
Status legend: `todo` · `partial` (some of it works) · `done` (working + captured).
|
||||
|
||||
### Share artifact files, not links (2026-10-21)
|
||||
|
||||
Gallery/list/visit and viewer Share actions now fetch the artifact and pass a
|
||||
named, MIME-typed `File` to `navigator.share({files})`. No URL is substituted.
|
||||
Copy link remains separate. Browsers without file-sharing APIs disable Share;
|
||||
unsupported types, failed fetches, cancellation and blocked sharing have truthful
|
||||
feedback. A slow download that outlasts user activation asks for a fresh Share
|
||||
tap using the prepared file, rather than silently failing or sharing a URL.
|
||||
Preparation is deduplicated per button and canceled if its view goes away.
|
||||
|
||||
`test/artifactSharing.test.mjs` checks exact binary bytes, filename/MIME, file-only
|
||||
payloads, HTTP/network failures, unsupported types/APIs, cancellation/denial,
|
||||
expired activation, navigation away and concurrent clicks. The real Chrome
|
||||
`test/artifact-browser-probe.mjs` drives gallery/list/viewer Share and feedback
|
||||
states with a stubbed native Share API; captures at 390/420/1100px are in approved
|
||||
OpenCode temporary `artifact-file-share-captures/`. Native OS chooser/recipient
|
||||
delivery is **not tested**. Shell cache is v16. This supersedes earlier URL-share
|
||||
behavior without changing the artifact's external-open action or authentication.
|
||||
|
||||
### Image artifact primary preview (2026-10-21)
|
||||
|
||||
Image thumbnails and image list rows now open the existing in-app viewer. The
|
||||
|
||||
@@ -291,6 +291,7 @@ button, [role="tab"] { -webkit-user-select: none; user-select: none; touch-actio
|
||||
.viewer-nav { display: flex; gap: var(--space-xs); justify-content: center; }
|
||||
.viewer-page:disabled { opacity: 0.4; cursor: not-allowed; }
|
||||
.viewer-actions { display: flex; flex-wrap: wrap; min-width: 0; gap: var(--space-xs); justify-content: flex-end; }
|
||||
.artifact-share-status { padding: 6px 8px; font-size: 12px; line-height: 1.5; overflow-wrap: anywhere; }
|
||||
.viewer-action { white-space: nowrap; }
|
||||
|
||||
@media (any-pointer: coarse) {
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
// File sharing never falls back to sending a private artifact URL. Keep prepared
|
||||
// files local to the owning button so a slow fetch can be shared on a fresh tap.
|
||||
const prepared = new WeakMap();
|
||||
const pending = new WeakSet();
|
||||
|
||||
export function canShareFiles(environment = globalThis) {
|
||||
return typeof environment.navigator?.share === "function" &&
|
||||
typeof environment.navigator?.canShare === "function" &&
|
||||
typeof environment.File === "function";
|
||||
}
|
||||
|
||||
export async function shareArtifactFile(resolved, artifact, owner, environment = globalThis) {
|
||||
if (!resolved || !canShareFiles(environment)) return { state: "error", message: "File sharing is not supported in this browser. Use Open in browser to save the file." };
|
||||
if (pending.has(owner)) return { state: "busy", message: "Preparing file…" };
|
||||
pending.add(owner);
|
||||
try {
|
||||
let entry = prepared.get(owner);
|
||||
if (!entry || entry.url !== resolved) {
|
||||
const response = await environment.fetch(resolved, { credentials: "same-origin", redirect: "error" });
|
||||
if (!response.ok) throw new Error(`Could not fetch the artifact (HTTP ${response.status}).`);
|
||||
const blob = await response.blob();
|
||||
const name = String(artifact?.name || new URL(resolved).pathname.split("/").pop() || "artifact")
|
||||
.split(/[\\/]/).pop().replace(/[\x00-\x1f\x7f]/g, "_") || "artifact";
|
||||
const file = new environment.File([blob], name, { type: blob.type || artifact?.content_type || "application/octet-stream" });
|
||||
entry = { url: resolved, file };
|
||||
if (!environment.navigator.canShare({ files: [file] })) {
|
||||
return { state: "error", message: "This browser cannot share this file type. Use Open in browser to save the file." };
|
||||
}
|
||||
prepared.set(owner, entry);
|
||||
}
|
||||
if (owner.isConnected === false) {
|
||||
prepared.delete(owner);
|
||||
return { state: "canceled", message: "Sharing canceled." };
|
||||
}
|
||||
// Fetching may outlast the browser's transient activation. Do not attempt a
|
||||
// doomed share or substitute a URL: the next tap uses the prepared file.
|
||||
if (environment.navigator.userActivation?.isActive === false) {
|
||||
return { state: "ready", message: "File ready. Tap Share again to choose where to send it." };
|
||||
}
|
||||
await environment.navigator.share({ files: [entry.file] });
|
||||
prepared.delete(owner);
|
||||
return { state: "shared", message: "File shared." };
|
||||
} catch (error) {
|
||||
if (error?.name === "AbortError") return { state: "canceled", message: "Sharing canceled." };
|
||||
if (error?.name === "NotAllowedError" && prepared.has(owner)) {
|
||||
return { state: "ready", message: "Sharing was blocked. Tap Share again, or use Open in browser to save the file." };
|
||||
}
|
||||
return { state: "error", message: "Could not share the file. Use Open in browser to save it, or try Share again." };
|
||||
} finally {
|
||||
pending.delete(owner);
|
||||
}
|
||||
}
|
||||
+17
-7
@@ -3,6 +3,7 @@
|
||||
// textContent, never innerHTML.
|
||||
|
||||
import { artifactBrowserLinkProps } from "./artifactNavigation.js";
|
||||
import { canShareFiles, shareArtifactFile } from "./artifactSharing.js";
|
||||
export { artifactBrowserLinkProps } from "./artifactNavigation.js";
|
||||
|
||||
export function h(tag, props = {}, ...children) {
|
||||
@@ -49,9 +50,9 @@ export function canCopyLink() {
|
||||
return typeof navigator !== "undefined" && Boolean(navigator.clipboard?.writeText);
|
||||
}
|
||||
|
||||
/** Whether the Web Share API can be used for a share control. */
|
||||
/** Whether the browser exposes file sharing (not just URL sharing). */
|
||||
export function canShare() {
|
||||
return typeof navigator !== "undefined" && typeof navigator.share === "function";
|
||||
return canShareFiles();
|
||||
}
|
||||
|
||||
export async function copyText(text) {
|
||||
@@ -72,12 +73,21 @@ export async function copyArtifactLink(resolved) {
|
||||
}
|
||||
}
|
||||
|
||||
export async function shareArtifact(resolved) {
|
||||
if (!resolved || !canShare()) return;
|
||||
export async function shareArtifact(resolved, artifact, trigger) {
|
||||
if (!trigger || trigger.getAttribute("aria-busy") === "true") return;
|
||||
const host = trigger.closest(".artifact-tile-wrap, .artifact-list-row, .viewer-panel");
|
||||
let status = host?.querySelector(".artifact-share-status");
|
||||
if (!status && host) {
|
||||
status = h("div", { class: "artifact-share-status muted", role: "status", "aria-live": "polite" });
|
||||
host.append(status);
|
||||
}
|
||||
if (status) status.textContent = "Preparing file…";
|
||||
trigger.setAttribute("aria-busy", "true");
|
||||
try {
|
||||
await navigator.share({ url: resolved });
|
||||
} catch {
|
||||
// The share chooser may be dismissed.
|
||||
const result = await shareArtifactFile(resolved, artifact, trigger);
|
||||
if (status && trigger.isConnected) status.textContent = result.message;
|
||||
} finally {
|
||||
trigger.removeAttribute("aria-busy");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -773,7 +773,8 @@ function openArtifactViewer(viewable, startIndex, trigger = null) {
|
||||
"data-viewer-focus": "share",
|
||||
text: "Share",
|
||||
disabled: !canShare(),
|
||||
onclick: () => shareArtifact(resolved),
|
||||
title: canShare() ? "Share file" : "File sharing is not supported in this browser",
|
||||
onclick: (event) => shareArtifact(resolved, artifact, event.currentTarget),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1240,7 +1240,7 @@ function renderArtifactListRow(artifact, viewable, viewerIndexOf) {
|
||||
open.addEventListener("click", () => previewImage
|
||||
? openArtifactViewer(viewable, at, open) : openArtifactInBrowser(resolved));
|
||||
wrap.append(open, renderTileActions(resolved, media, opensViewer && at != null
|
||||
? (trigger) => openArtifactViewer(viewable, at, trigger) : null, name, previewImage));
|
||||
? (trigger) => openArtifactViewer(viewable, at, trigger) : null, name, previewImage, artifact));
|
||||
return wrap;
|
||||
}
|
||||
|
||||
@@ -1341,12 +1341,12 @@ function renderArtifactTile(artifact, viewable, viewerIndexOf) {
|
||||
);
|
||||
tile.addEventListener("click", openTab);
|
||||
}
|
||||
wrap.append(tile, renderTileActions(resolved, media, opensViewer ? openViewer : null, name, kind === ArtifactKind.Image));
|
||||
wrap.append(tile, renderTileActions(resolved, media, opensViewer ? openViewer : null, name, kind === ArtifactKind.Image, artifact));
|
||||
return wrap;
|
||||
}
|
||||
|
||||
/** The compact per-tile actions: icon-only link/share, shown on hover or focus. */
|
||||
function renderTileActions(resolved, media, preview = null, name = "artifact", previewImage = false) {
|
||||
function renderTileActions(resolved, media, preview = null, name = "artifact", previewImage = false, artifact = null) {
|
||||
const actions = h("div", { class: "artifact-actions" });
|
||||
const stop = (fn) => (event) => {
|
||||
event.stopPropagation();
|
||||
@@ -1363,8 +1363,9 @@ function renderTileActions(resolved, media, preview = null, name = "artifact", p
|
||||
);
|
||||
}
|
||||
actions.append(
|
||||
artifactAction("share", "Share", !resolved || !canShare(), stop(() => shareArtifact(resolved))),
|
||||
artifactAction("share", "Share", !resolved || !canShare(), stop((trigger) => shareArtifact(resolved, artifact, trigger))),
|
||||
);
|
||||
if (!canShare()) actions.lastElementChild.title = "File sharing is not supported in this browser";
|
||||
return actions;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// A shell cache for an installed Pipelines app. The API (the WebSocket proxy and
|
||||
// artifact files) is never cached; static files prefer the network and fall back
|
||||
// to the last good copy so an installed app still opens when the server is away.
|
||||
const CACHE = "pipelines-shell-v15";
|
||||
const CACHE = "pipelines-shell-v16";
|
||||
const SHELL = ["/", "/index.html", "/manifest.webmanifest", "/favicon.svg"];
|
||||
|
||||
self.addEventListener("install", (event) => {
|
||||
|
||||
@@ -27,6 +27,14 @@ const image={name:'public/pixel.png',url:'/artifacts/18/1/public/pixel.png',cont
|
||||
const step={stage:'research',sequence:1,status:'completed',outcome:'success',artifacts:[report,documentFile,image,session],session_id:'ses_fixture',session_export:{html:'session.html',messages:2,status:'complete'}};
|
||||
const state={url:'ws://'+location.host+'/connect',selectedRunId:18,artifactView:'gallery',runDetail:{id:18,steps:[step]}};
|
||||
window.routes=[];window.handoffs=[];window.copied=[];
|
||||
window.shared=[];window.shareMode='success';window.fileReadyActivation=true;
|
||||
Object.defineProperty(navigator,'userActivation',{configurable:true,value:{get isActive(){return fileReadyActivation;}}});
|
||||
Object.defineProperty(navigator,'canShare',{configurable:true,value:({files})=>files?.length===1&&files[0] instanceof File});
|
||||
Object.defineProperty(navigator,'share',{configurable:true,value:async data=>{
|
||||
if(shareMode==='cancel')throw new DOMException('Canceled','AbortError');
|
||||
if(shareMode==='deny')throw new DOMException('Denied','NotAllowedError');
|
||||
const f=data.files[0];shared.push({keys:Object.keys(data),name:f.name,type:f.type,bytes:[...new Uint8Array(await f.arrayBuffer())]});
|
||||
}});
|
||||
const rt={state,modal:createModalController(),repo:{},views:{},renderContent:()=>{},selectRun:id=>routes.push(id)};
|
||||
rt.views.chat=createChatView(rt);rt.views.dialogs=createDialogsView(rt);rt.views.runDetail=createRunDetailView(rt);
|
||||
const host=document.querySelector('#content');
|
||||
@@ -84,6 +92,34 @@ try {
|
||||
await eventually(async()=>(await targets()).some(t=>t.url===origin+'/artifacts/18/1/public/pixel.png'));
|
||||
assert.equal(await page.evaluate('location.href'),appURL);
|
||||
assert.equal(await page.evaluate("!!document.querySelector('.artifact-viewer')"),false);
|
||||
const imageShare='[data-artifact-name="public/pixel.png"] + .artifact-actions [aria-label="Share"]';
|
||||
await page.click(imageShare);
|
||||
await eventually(()=>page.evaluate('shared.length===1'));
|
||||
const file=await page.evaluate('shared[0]');
|
||||
assert.deepEqual(file.keys,['files']);assert.equal(file.name,'pixel.png');assert.equal(file.type,'image/png');
|
||||
assert.deepEqual(file.bytes,[...Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=','base64')]);
|
||||
await page.evaluate("shareMode='cancel'");await page.click(imageShare);await page.waitForText('Sharing canceled.');
|
||||
await page.evaluate("shareMode='deny'");await page.click(imageShare);await page.waitForText('Sharing was blocked.');
|
||||
await page.screenshot(resolve(out,'06-file-share-blocked-mobile.png'));
|
||||
await page.evaluate("shareMode='success';fileReadyActivation=false");await page.click(imageShare);await page.waitForText('File ready.');
|
||||
await page.screenshot(resolve(out,'06-file-ready-retap-mobile.png'));
|
||||
await page.evaluate('fileReadyActivation=true');await page.click(imageShare);await eventually(()=>page.evaluate('shared.length===2'));
|
||||
await page.click('[data-artifact-name="public/pixel.png"]');await page.waitForSelector('.artifact-viewer');
|
||||
await page.click('[data-viewer-focus=share]');await eventually(()=>page.evaluate('shared.length===3'));
|
||||
assert.deepEqual(await page.evaluate('shared[2]'),file,'viewer shares the same file bytes and metadata');
|
||||
await page.screenshot(resolve(out,'06-viewer-file-share-mobile.png'));
|
||||
for (const width of [420,1100]) {
|
||||
await page.resize(width,844);
|
||||
assert.equal(await page.evaluate('document.documentElement.scrollWidth<=innerWidth'),true);
|
||||
await page.screenshot(resolve(out,`06-viewer-file-share-${width}.png`));
|
||||
}
|
||||
await page.pressKey('Escape');
|
||||
await page.evaluate('showList()');await page.click('#listFixture .artifact-list-row:last-child [aria-label=Share]');
|
||||
await eventually(()=>page.evaluate('shared.length===4'));assert.deepEqual(await page.evaluate('shared[3]'),file);
|
||||
await page.resize(390,844);
|
||||
await page.evaluate("Object.defineProperty(navigator,'canShare',{configurable:true,value:undefined});showVisit()");
|
||||
assert.equal(await page.evaluate("document.querySelector('#visitFixture [aria-label=Share]').disabled"),true);
|
||||
await page.screenshot(resolve(out,'06-file-sharing-unsupported-mobile.png'));
|
||||
|
||||
const android = await browser.openPage("about:blank");
|
||||
await android.emulateTouch(true);
|
||||
@@ -160,7 +196,7 @@ try {
|
||||
assert.equal(await android.evaluate("handoffs.length"), 10, "search results must use the same browser hand-off");
|
||||
assert.equal(await android.evaluate("location.href"), original);
|
||||
assert.deepEqual(await android.evaluate("routes"), []);
|
||||
console.log("PASS: images preview on primary gallery/list/visit activation; external icons hand off without opening the viewer; keyboard/focus and mobile fit pass. Other artifact, chat, session, search and viewer browser actions retain safe hand-off. Android OS launch is not tested.");
|
||||
console.log("PASS: primary image previews, external hand-off, and exact named/typed file-byte sharing from gallery/list/viewer; cancellation, blocked/unsupported sharing and fresh-tap preparation are truthful. Real Chrome uses a stubbed Share API; native OS chooser/delivery and Android OS launch are not tested.");
|
||||
} finally {
|
||||
await browser?.close();
|
||||
await new Promise(r => server.close(r));
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { canShareFiles, shareArtifactFile } from "../src/artifactSharing.js";
|
||||
|
||||
function fixture() {
|
||||
const calls = [], shares = [];
|
||||
const env = { File, navigator: { userActivation: { isActive: true }, canShare: () => true,
|
||||
share: async data => shares.push(data) },
|
||||
fetch: async (...args) => { calls.push(args); return new Response(new Uint8Array([0, 1, 255, 42]), { headers: { "Content-Type": "image/png" } }); } };
|
||||
return { env, calls, shares, owner: {} };
|
||||
}
|
||||
const url = "https://app.example/artifacts/20/1/public/capture.png";
|
||||
|
||||
test("shares exact downloaded bytes as a named typed File, never a URL", async () => {
|
||||
const { env, calls, shares, owner } = fixture();
|
||||
assert.equal((await shareArtifactFile(url, { name: "public/capture.png" }, owner, env)).state, "shared");
|
||||
assert.equal(calls[0][0], url);
|
||||
assert.deepEqual(calls[0][1], { credentials: "same-origin", redirect: "error" });
|
||||
assert.deepEqual(Object.keys(shares[0]), ["files"]);
|
||||
const file = shares[0].files[0];
|
||||
assert.ok(file instanceof File); assert.equal(file.name, "capture.png"); assert.equal(file.type, "image/png");
|
||||
assert.deepEqual([...new Uint8Array(await file.arrayBuffer())], [0, 1, 255, 42]);
|
||||
});
|
||||
|
||||
test("unsupported browsers and file types never share links", async () => {
|
||||
const { env, calls, shares, owner } = fixture();
|
||||
env.navigator.canShare = undefined; assert.equal(canShareFiles(env), false);
|
||||
assert.equal((await shareArtifactFile(url, {}, owner, env)).state, "error"); assert.equal(calls.length, 0);
|
||||
env.navigator.canShare = () => false;
|
||||
assert.equal((await shareArtifactFile(url, {}, owner, env)).state, "error"); assert.equal(shares.length, 0);
|
||||
});
|
||||
|
||||
test("a slow fetch prepares for a fresh Share tap without another download", async () => {
|
||||
const { env, calls, shares, owner } = fixture(); env.navigator.userActivation.isActive = false;
|
||||
assert.equal((await shareArtifactFile(url, {}, owner, env)).state, "ready"); assert.equal(shares.length, 0);
|
||||
env.navigator.userActivation.isActive = true;
|
||||
assert.equal((await shareArtifactFile(url, {}, owner, env)).state, "shared");
|
||||
assert.equal(shares.length, 1); assert.equal(calls.length, 1);
|
||||
});
|
||||
|
||||
test("cancel and permission denial are truthful and allow a retry", async () => {
|
||||
const { env, calls, shares, owner } = fixture();
|
||||
env.navigator.share = async () => { throw new DOMException("Canceled", "AbortError"); };
|
||||
assert.equal((await shareArtifactFile(url, {}, owner, env)).state, "canceled");
|
||||
env.navigator.share = async () => { throw new DOMException("Denied", "NotAllowedError"); };
|
||||
assert.equal((await shareArtifactFile(url, {}, owner, env)).state, "ready");
|
||||
env.navigator.share = async data => shares.push(data);
|
||||
assert.equal((await shareArtifactFile(url, {}, owner, env)).state, "shared"); assert.equal(calls.length, 1);
|
||||
});
|
||||
|
||||
test("fetch/auth errors never invoke Share; navigation away cancels preparation", async () => {
|
||||
const { env, shares, owner } = fixture();
|
||||
env.fetch = async () => new Response("Unauthorized", { status: 401 });
|
||||
assert.equal((await shareArtifactFile(url, {}, owner, env)).state, "error");
|
||||
env.fetch = async () => { throw new TypeError("Failed to fetch"); };
|
||||
assert.equal((await shareArtifactFile(url, {}, owner, env)).state, "error");
|
||||
env.fetch = async () => new Response("file"); owner.isConnected = false;
|
||||
assert.equal((await shareArtifactFile(url, {}, owner, env)).state, "canceled"); assert.equal(shares.length, 0);
|
||||
});
|
||||
|
||||
test("concurrent clicks do not duplicate a fetch or share", async () => {
|
||||
const { env, calls, shares, owner } = fixture(); let release;
|
||||
const fetch = env.fetch;
|
||||
env.fetch = async (...args) => { await new Promise(resolve => { release = resolve; }); return fetch(...args); };
|
||||
const first = shareArtifactFile(url, {}, owner, env);
|
||||
assert.equal((await shareArtifactFile(url, {}, owner, env)).state, "busy");
|
||||
release(); assert.equal((await first).state, "shared"); assert.equal(calls.length, 1); assert.equal(shares.length, 1);
|
||||
});
|
||||
@@ -9,9 +9,9 @@ test("shell updates retain unrelated caches and the current app cache", async ()
|
||||
let activation;
|
||||
vm.runInNewContext(await readFile(new URL("../sw.js", import.meta.url), "utf8"), {
|
||||
self: { addEventListener: (type, handler) => handlers.set(type, handler), clients: { claim: async () => {} } },
|
||||
caches: { keys: async () => ["pipelines-shell-v14", "pipelines-shell-v15", "unrelated-user-cache"], delete: async (key) => deleted.push(key) },
|
||||
caches: { keys: async () => ["pipelines-shell-v15", "pipelines-shell-v16", "unrelated-user-cache"], delete: async (key) => deleted.push(key) },
|
||||
});
|
||||
handlers.get("activate")({ waitUntil: (promise) => { activation = promise; } });
|
||||
await activation;
|
||||
assert.deepEqual(deleted, ["pipelines-shell-v14"]);
|
||||
assert.deepEqual(deleted, ["pipelines-shell-v15"]);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user