Files
pipelines/web/test/artifact-browser-probe.mjs
T

204 lines
16 KiB
JavaScript

// Browser-only regression. Real artifact views/helpers, isolated HTTP fixtures;
// Android intents are inspected, never mistaken for a real OS/browser hand-off.
import assert from "node:assert/strict";
import { createServer } from "node:http";
import { readFile, mkdir } from "node:fs/promises";
import { resolve, extname } from "node:path";
import { launchChrome, eventually } from "./browser.mjs";
const root = resolve(import.meta.dirname, "..");
const out = resolve(process.argv[2] ?? "captures-artifact-browser");
await mkdir(out, { recursive: true });
const artifactPath = "/artifacts/18/1/public/report.html";
const html = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
${["design/tokens/tokens", "base", "shell", "lists", "run-detail", "chat", "dialogs"].map(n => `<link rel="stylesheet" href="/${n}.css">`).join("")}
<div class="app-root"><main id="content" style="padding:16px"><h1>Artifact browser hand-off</h1></main></div>
<script type="module">
import { createModalController } from '/src/modal.js';
import { createRunDetailView } from '/src/views/runDetail.js';
import { createDialogsView } from '/src/views/dialogs.js';
import { createChatView } from '/src/views/chat.js';
import { createSearchView } from '/src/views/search.js';
import { SearchSequencer } from '/src/search.js';
const report={name:'public/report.html',url:'${artifactPath}',content_type:'text/html',size_bytes:70};
const documentFile={name:'public/evidence.md',url:'/artifacts/18/1/public/evidence.md',content_type:'text/markdown',size_bytes:50};
const session={name:'session.html',url:'/artifacts/18/1/session.html',content_type:'text/html',size_bytes:70};
const image={name:'public/pixel.png',url:'/artifacts/18/1/public/pixel.png',content_type:'image/png',size_bytes:68};
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');
host.append(rt.views.runDetail.renderArtifactGallery([step]),rt.views.runDetail.renderSessionExport(step));
const chat=document.createElement('section');chat.id='chatFixture';chat.append(rt.views.chat.renderMarkdown('[Chat report](${artifactPath})\\n\\n[Unsafe](javascript:alert(1))'));host.append(chat);
history.replaceState({selectedRun:18},'', '/runs/18?pipeline=27');
document.addEventListener('click',e=>{const link=e.target.closest('a');if(link?.href.startsWith('intent:')){e.preventDefault();handoffs.push({href:link.href,target:link.target,rel:link.rel});}},true);
Object.defineProperty(navigator,'clipboard',{configurable:true,value:{writeText:async text=>copied.push(text)}});
window.ready=true;
window.showList=()=>{state.artifactView='list';const list=document.createElement('section');list.id='listFixture';list.append(rt.views.runDetail.renderArtifactGallery([step]));host.append(list);};
window.showVisit=()=>{const visit=document.createElement('section');visit.id='visitFixture';visit.append(rt.views.runDetail.renderVisitArtifacts(step));host.append(visit);};
window.showSearch=()=>{const target=document.createElement('div');document.body.append(target);Object.assign(state,{searchQuery:'',searchKind:'',searchSort:'relevance',searchResults:[],searchSequencer:new SearchSequencer(),searchActiveIndex:0});const search=createSearchView({...rt,searchHost:target,renderHeader:()=>{},repo:{search:async()=>({results:[{kind:'artifact',target:documentFile.url,artifact:{...documentFile,run_id:18,sequence:1}}]})}});search.openSearch();};
</script>`;
const server = createServer(async (req, res) => {
try {
const path = new URL(req.url, "http://fixture").pathname;
if (path === "/" || path.startsWith("/runs/")) {
res.setHeader("Content-Type", "text/html"); res.end(html); return;
}
if (path.startsWith("/artifacts/")) {
if (path.endsWith('.png')) {res.setHeader('Content-Type','image/png');res.end(Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=','base64'));return;}
res.setHeader("Content-Type", path.endsWith(".md") ? "text/markdown" : "text/html");
res.setHeader("Content-Security-Policy", "sandbox; default-src 'none'");
res.end(path.endsWith(".md") ? "# Fixture evidence\n\nA document preview remains inside the app." : "<!doctype html><title>Fixture report</title><h1>Fixture report</h1>"); return;
}
const file = resolve(root, `.${path}`);
if (!file.startsWith(root + "/")) throw Error("outside fixture");
res.setHeader("Content-Type", extname(file) === ".css" ? "text/css" : "text/javascript");
res.end(await readFile(file));
} catch { res.writeHead(404); res.end(); }
});
await new Promise(r => server.listen(0, "127.0.0.1", r));
const origin = `http://127.0.0.1:${server.address().port}`;
let browser;
try {
browser = await launchChrome({ width: 390, height: 844 });
const page = await browser.openPage(origin);
await page.waitForSelector(`[data-artifact-name="public/report.html"]`);
const appURL = await page.evaluate("location.href");
const historyLength = await page.evaluate("history.length");
await page.click('[data-artifact-name="public/report.html"]');
await eventually(async () => (await fetch(`http://127.0.0.1:${browser.port}/json/list`).then(r => r.json())).some(target => target.url === origin + artifactPath));
assert.equal(await page.evaluate("location.href"), appURL);
assert.equal(await page.evaluate("history.length"), historyLength);
await page.screenshot(resolve(out, "01-app-preserved-after-browser-open.png"));
const targets=()=>fetch(`http://127.0.0.1:${browser.port}/json/list`).then(r=>r.json());
const targetCount=(await targets()).length;
await page.click('[data-artifact-name="public/pixel.png"]');
await page.waitForSelector('.artifact-viewer');
assert.equal((await targets()).length,targetCount,'image preview must not create a browser tab');
await page.screenshot(resolve(out,'01-image-preview-normal-browser.png'));
await page.pressKey('Escape');
await page.click('[aria-label="Open in browser: public/pixel.png"]');
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);
await android.addInitScript(`(() => {
Object.defineProperty(navigator,'userAgent',{configurable:true,value:'Mozilla/5.0 (Linux; Android 14) Chrome/130 Mobile Safari/537.36'});
const native=window.matchMedia.bind(window);
window.matchMedia=q=>q==='(display-mode: standalone)'?{matches:true}:native(q);
})()`);
await android.goto(origin);
await android.waitForSelector('[data-artifact-name="public/report.html"]');
const original = await android.evaluate("location.href");
await android.click('[data-artifact-name="public/report.html"]');
await android.click('#chatFixture a.md-link');
await android.click('.session-link');
assert.equal(await android.evaluate("handoffs.length"), 3);
assert.equal(await android.evaluate("document.querySelectorAll('a[href^=javascript]').length"), 0);
assert.equal(await android.evaluate("location.href"), original);
await android.click('[data-artifact-name="public/evidence.md"]');
assert.equal(await android.evaluate("handoffs.length"), 4, "Markdown Open must request the browser too");
assert.equal(await android.evaluate("!!document.querySelector('.artifact-viewer')"), false);
await android.click('[data-artifact-name="public/pixel.png"]');
await android.waitForSelector('.artifact-viewer');
assert.equal(await android.evaluate("handoffs.length"), 4, "image clicks preview without external navigation");
await android.screenshot(resolve(out, '03-image-preview-mobile.png'));
await android.pressKey('Escape');
assert.equal(await android.evaluate("document.activeElement.dataset.artifactName"), 'public/pixel.png');
await android.click('[aria-label="Open in browser: public/pixel.png"]');
assert.equal(await android.evaluate("handoffs.length"), 5, "the external icon hands the image to the browser");
assert.equal(await android.evaluate("!!document.querySelector('.artifact-viewer')"), false, "the external action must not also open the viewer");
await android.click('[aria-label="Preview in app: public/evidence.md"]');
await android.waitForSelector('.viewer-markdown');
assert.equal(await android.evaluate("location.href"), original);
const props = await android.evaluate("(() => {const a=document.querySelector('[data-viewer-focus=open]');return {tag:a.tagName,text:a.textContent,href:a.href,target:a.target,rel:a.rel};})()");
assert.equal(props.tag, "A"); assert.equal(props.text, "Open in browser");
assert.match(props.href, /^intent:/); assert.equal(props.target, "_blank"); assert.ok(props.rel.includes("noopener"));
await android.click('[data-viewer-focus=open]');
await android.click('[data-viewer-focus=copy]');
assert.equal(await android.evaluate("handoffs.length"), 6);
assert.equal(await android.evaluate("copied[0]"), origin + "/artifacts/18/1/public/evidence.md");
assert.equal(await android.evaluate("location.href"), original);
for (const width of [390, 420]) {
await android.resize(width,844);
const fits = await android.evaluate("(() => {const p=document.querySelector('.viewer-panel').getBoundingClientRect();return [...document.querySelectorAll('.viewer-action')].every(a=>{const r=a.getBoundingClientRect();return r.left>=p.left && r.right<=p.right;}) && document.documentElement.scrollWidth<=innerWidth;})()");
assert.equal(fits,true,"viewer actions must stay reachable without widening the mobile app");
await android.screenshot(resolve(out, `02-installed-android-browser-action-${width}.png`));
}
await android.pressKey("Escape");
await android.evaluate('showList()');
await android.click('#listFixture .artifact-list-open[aria-label="Open public/evidence.md"]');
assert.equal(await android.evaluate("handoffs.length"), 7);
await android.click('#listFixture .artifact-list-open[aria-label="Open public/pixel.png"]');
await android.waitForSelector('.artifact-viewer');
assert.equal(await android.evaluate("handoffs.length"),7,'image list rows also preview');
await android.screenshot(resolve(out,'04-image-list-preview-mobile.png'));
await android.pressKey('Escape');
await android.click('#listFixture [aria-label="Open in browser: public/pixel.png"]');
assert.equal(await android.evaluate("handoffs.length"),8);
await android.evaluate('showVisit()');
await android.evaluate("document.querySelector('#visitFixture [data-artifact-name=\"public/pixel.png\"]').focus()");
await android.pressKey('Enter');await android.waitForSelector('.artifact-viewer');
assert.equal(await android.evaluate("handoffs.length"),8,'visit image keyboard activation previews without hand-off');
await android.pressKey('Escape');
await android.click('#visitFixture [aria-label="Open in browser: public/pixel.png"]');
assert.equal(await android.evaluate("handoffs.length"),9);
assert.equal(await android.evaluate("!!document.querySelector('[aria-label=\"Preview in app: public/pixel.png\"]')"),false,'images no longer have an eye preview action');
for(const width of [390,420,1100]) {
await android.resize(width,844);
await android.screenshot(resolve(out,`05-image-external-icon-${width}.png`));
assert.equal(await android.evaluate('document.documentElement.scrollWidth<=innerWidth'),true);
}
await android.evaluate('showSearch()');
await android.waitForSelector('#searchInput');await android.fill('#searchInput','evidence');
await android.waitForSelector('.search-row[data-kind=artifact]');await android.click('.search-row[data-kind=artifact]');
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: 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));
}