| 1 | |
| 2 | |
| 3 | |
| 4 | import assert from "node:assert/strict"; |
| 5 | import {once} from "node:events"; |
| 6 | import {mkdtemp, readFile, rm} from "node:fs/promises"; |
| 7 | import http from "node:http"; |
| 8 | import net from "node:net"; |
| 9 | import {tmpdir} from "node:os"; |
| 10 | import {join} from "node:path"; |
| 11 | import {setTimeout as delay} from "node:timers/promises"; |
| 12 | import {fileURLToPath} from "node:url"; |
| 13 | import {PhoneBrowser} from "../../internal/cage/browser-phone.mjs"; |
| 14 | |
| 15 | const playwright = await import(process.env.CAGE_PLAYWRIGHT_MODULE || "playwright"); |
| 16 | const binary = process.env.CAGE_TEST_CHROMIUM || playwright.chromium.executablePath(); |
| 17 | const engine = process.env.CAGE_TEST_MOBILE_BROWSER || "webkit"; |
| 18 | const current = fileURLToPath(new URL("../../mobile/.build/resources/mobile-ui/",import.meta.url)); |
| 19 | const site = http.createServer((req,res) => { |
| 20 | res.setHeader("Content-Type","text/html; charset=utf-8"); |
| 21 | res.end('<meta name="viewport" content="width=device-width, initial-scale=1"><title>Scroll test</title>' + |
| 22 | '<style>*{box-sizing:border-box}body{margin:0;font:18px sans-serif;scrollbar-width:none}::-webkit-scrollbar{display:none}button{display:block;width:100%;height:80px;touch-action:manipulation}p{padding:24px;margin:0;border-bottom:1px solid silver}</style>' + |
| 23 | '<button onclick="document.body.style.backgroundColor=\'wheat\'">Change page colour</button>' + |
| 24 | Array.from({length:100},(_,i)=>"<p>Row "+(i+1)+"</p>").join("")); |
| 25 | }).listen(0,"127.0.0.1"); |
| 26 | await once(site,"listening"); |
| 27 | |
| 28 | async function measure(directory, baseline) { |
| 29 | const profile = await mkdtemp(join(tmpdir(),"cage-phone-latency-")); |
| 30 | const guest = new PhoneBrowser({directory:profile,binary,connect:async (host,port) => { |
| 31 | if (host !== "scroll.example" || port !== site.address().port) throw Error("Unexpected test destination"); |
| 32 | const socket = net.connect({host:"127.0.0.1",port}); await once(socket,"connect"); return socket; |
| 33 | }}); |
| 34 | const events = []; |
| 35 | let pageReady = false; |
| 36 | const host = http.createServer(async (req,res) => { |
| 37 | const url = new URL(req.url,"http://localhost"); |
| 38 | const send = value => {res.setHeader("Content-Type","application/json"); res.end(JSON.stringify(value));}; |
| 39 | try { |
| 40 | if (url.pathname === "/api/mobile/cli/projects") return send({ready:true,host:"Test",projects:[]}); |
| 41 | if (url.pathname === "/api/mobile/cli/sessions") return send({sessions:[]}); |
| 42 | if (!url.pathname.startsWith("/api/mobile/browser/")) { |
| 43 | const asset = url.pathname.slice(1) || "mobile.html"; |
| 44 | if (asset !== "mobile.html" && !/^assets\/[\w.-]+$/.test(asset)) throw Error("Missing asset"); |
| 45 | res.setHeader("Content-Type",asset.endsWith(".js") ? "text/javascript" : asset.endsWith(".css") ? "text/css" : asset.endsWith(".png") ? "image/png" : "text/html"); |
| 46 | res.end(await readFile(join(directory,asset))); return; |
| 47 | } |
| 48 | const parts = url.pathname.split("/"), op = parts.at(-1); |
| 49 | const chunks = []; for await (const b of req) chunks.push(b); |
| 50 | const input = chunks.length ? JSON.parse(Buffer.concat(chunks)) : {}; |
| 51 | if (op === "open") input.profile = "a".repeat(64); |
| 52 | else input.id = parts.at(-2); |
| 53 | if (url.searchParams.has("after")) input.after = url.searchParams.get("after"); |
| 54 | const log = {op,type:input.type,at:Date.now(),after:!!input.after,delta:input.dy||0}; |
| 55 | events.push(log); |
| 56 | await delay(80); |
| 57 | const output = await guest.run(op,input); |
| 58 | if (op === "open" || output.image) output.action_frame = true; |
| 59 | if (output.title === "Scroll test") pageReady = true; |
| 60 | log.bytes = Buffer.byteLength(JSON.stringify(output)); |
| 61 | log.image = !!output.image; |
| 62 | await delay(80); |
| 63 | send(output); |
| 64 | } catch (error) { if (!res.headersSent) res.writeHead(error.status || 500); res.end(error.message); } |
| 65 | }).listen(0,"127.0.0.1"); |
| 66 | await once(host,"listening"); |
| 67 | const browser = await playwright[engine].launch(); |
| 68 | try { |
| 69 | const page = await browser.newPage({viewport:{width:390,height:844},deviceScaleFactor:1,isMobile:true,hasTouch:true,userAgent:"CageMobile/1"}); |
| 70 | await page.goto("http://127.0.0.1:"+host.address().port); |
| 71 | await page.getByRole("button",{name:"浏览器",exact:true}).click(); |
| 72 | const address = page.getByRole("textbox",{name:"远程网页地址"}); |
| 73 | await address.fill("http://scroll.example:"+site.address().port); |
| 74 | await address.press("Enter"); |
| 75 | for(let i=0; i<80 && !pageReady; i++) await delay(100); |
| 76 | assert.ok(pageReady,"remote Chromium did not load the local page"); |
| 77 | await delay(550); |
| 78 | const stage = page.getByRole("img",{name:"远程浏览器画面"}); |
| 79 | const rect = await stage.boundingBox(); |
| 80 | const start = async type => { |
| 81 | await page.evaluate(type => { |
| 82 | const stage = document.querySelector(".remote-stage"); |
| 83 | const img = stage.querySelector("img"), original = img.src; |
| 84 | window.result = null; |
| 85 | stage.addEventListener(type, () => { |
| 86 | const start = performance.now(); |
| 87 | const observer = new MutationObserver(() => { |
| 88 | if (img.src === original) return; |
| 89 | requestAnimationFrame(() => requestAnimationFrame(() => {window.result = {ms:Math.round(performance.now()-start),wall:Date.now()};})); |
| 90 | observer.disconnect(); |
| 91 | }); |
| 92 | observer.observe(img,{attributes:true,attributeFilter:["src"]}); |
| 93 | },{once:true}); |
| 94 | },type); |
| 95 | }; |
| 96 | const finish = async (logStart,timeout=5000) => { |
| 97 | await page.waitForFunction(() => window.result !== null,null,{timeout}); |
| 98 | const result = await page.evaluate(() => window.result); |
| 99 | const log = events.slice(logStart).filter(event => event.at <= result.wall); |
| 100 | const first = log.findIndex(e => e.op === "action"); |
| 101 | assert.notEqual(first,-1); |
| 102 | return {ms:result.ms, requests:log.slice(first).length}; |
| 103 | }; |
| 104 | const tapStart = events.length; |
| 105 | await start("pointerup"); |
| 106 | await page.touchscreen.tap(rect.x+rect.width/2,rect.y+40); |
| 107 | const tap = await finish(tapStart); |
| 108 | const x = rect.x + rect.width/2, y = rect.y + rect.height*.75; |
| 109 | await page.mouse.move(x,y); await page.mouse.down(); |
| 110 | await start("pointermove"); |
| 111 | const dragStart = events.length; |
| 112 | for (let i=1; i<=12; i++) {await page.mouse.move(x,y-i*12); await delay(32);} |
| 113 | const beforeRelease = await page.evaluate(() => window.result !== null); |
| 114 | await page.mouse.up(); |
| 115 | const scroll = await finish(dragStart); |
| 116 | assert.equal(beforeRelease,!baseline,"scroll feedback while the finger is down"); |
| 117 | |
| 118 | await delay(2000); |
| 119 | const sent = events.slice(dragStart).filter(e => e.type === "scroll"); |
| 120 | assert.equal(sent.reduce((sum,e)=>sum+e.delta,0),144,"only unsent motion may be coalesced"); |
| 121 | if (!baseline) assert.ok(sent.length > 1 && sent.length < 12); |
| 122 | const idleStart = events.length; |
| 123 | await delay(5200); |
| 124 | const idle = events.slice(idleStart).filter(e=>e.op === "frame" && e.bytes); |
| 125 | if (!baseline) assert.ok(idle.length && idle.every(e=>e.after && !e.image),"the idle page must not keep downloading JPEGs"); |
| 126 | return {tap,scroll:{...scroll,paintedWhileDragging:beforeRelease,writes:sent.length},idle:{reads:idle.length,bodyBytes:idle.reduce((sum,e)=>sum+e.bytes,0)}}; |
| 127 | } finally { |
| 128 | await browser.close(); await guest.dispose(); host.closeAllConnections(); await new Promise(resolve => host.close(resolve)); |
| 129 | await rm(profile,{recursive:true,force:true}); |
| 130 | } |
| 131 | } |
| 132 | try { |
| 133 | const before = process.env.CAGE_MOBILE_BASELINE ? await measure(process.env.CAGE_MOBILE_BASELINE,true) : null; |
| 134 | const after = await measure(current,false); |
| 135 | if (before) { |
| 136 | assert.ok(after.tap.ms < before.tap.ms,"combined action feedback must remove one round trip"); |
| 137 | assert.ok(after.scroll.ms < before.scroll.ms,"continuous drag must paint sooner"); |
| 138 | } |
| 139 | console.log(JSON.stringify({engine,roundTripMs:160,before,after},null,2)); |
| 140 | } finally {site.closeAllConnections(); site.close();} |