Files
plugins/packages/agent-office/test/browser.mjs
T
Zhaoji Wang 133cd35107 agent-office: Settings pickers read their value, keep open on overscroll, and the page's scrollbars are magpie's thin thumb (#778)
The three Settings pickers' buttons are labelled by the label and their
own value (aria-labelledby="lblScene optScene"), so they read "Scene
Office" again as the <select> did. .picker-list gets
overscroll-behavior: contain, so wheeling past a list's end no longer
scrolls #settings and closes it, and a #settings scroll in the frame a
picker opens repositions the list instead of closing it. The page's
scrollbars take magpie's thin thumb (8px, --faint, --muted on hover,
the same as magpie's Mac rule for pages), with --faint read from the
host's --magpie-faint token. Fixes #773. By frederick-wang.

Run on mote at c7ecc7a6 (Bun 1.4.2, HOME=mktemp -d):
packages/agent-office bun test 183 pass, 0 fail; bun scripts/check.mjs
exit 0; packages/agent-office stamp-page.mjs --check exit 0.
A Playwright script of the reviewer's own against the standalone page
(bin/agent-office.mjs --no-open, 600x520, chromium and webkit, light
and dark), run 4 times: the three accessible names are "Language
Auto", "Scene Office", "Quality Medium"; focus+Enter on #optQuality
keeps its list open; four 600px wheels over #optSceneList keep it open;
setting #settings' scrollTop still closes the picker; the list's
scrollbar is 8px with a #b9b9c2 thumb, #56565f under data-theme=dark;
no page errors.
Broken by hand: the same script at the base 10a61c2e fails the three
names in every engine and theme, and focus+Enter closed the Quality
list in 2 of 4 runs (the #773 race); the thumb is transparent there.
Not tried: test/browser.mjs inside a real magpie host window (needs a
magpie web URL); the wheel check also passes at the base in headless
Chromium and WebKit, so it does not prove the overscroll fix.
2026-11-06 11:08:29 +08:00

151 lines
11 KiB
JavaScript

// Run against magpie web with this plugin installed from the checkout.
// OFFICE_PLAYWRIGHT=/path/to/playwright/index.mjs OFFICE_HOST_URL='http://127.0.0.1:4571/?k=...' bun test/browser.mjs
// Uses real host navigation, bridge, theme and sandbox. Only live.js is
// replaced with synthetic prompts; no user sessions or model calls needed.
import assert from 'node:assert/strict'
import { mkdirSync } from 'node:fs'
const { chromium, webkit } = await import(process.env.OFFICE_PLAYWRIGHT || 'playwright')
const host=process.env.OFFICE_HOST_URL
if(!host) throw new Error('Set OFFICE_HOST_URL to an authenticated magpie web URL')
const output=process.env.OFFICE_QA_OUTPUT || '/tmp/agent-office-browser-qa'
mkdirSync(output,{recursive:true})
const now=Date.now(),marker='SECRET-PROMPT-123'
const snapshot={v:2,written:now,text:true,sessions:Array.from({length:12},(_,i)=>({
key:`qa|${i}`,agent:'claude',session:`qa-${i}`,source:'files',phase:i===0?'error':i===1?'thinking':'done',
title:`${marker} 布局回归测试 ${i}`,query:`${marker} user`,reply:`${marker} reply`,error:i===0?`${marker} error`:'',
project:'fixture',cwd:'/fixture',model:'fixture-model',updated:now-(i===0?2*3600e3:i*100),touched:now-(i===0?2*3600e3:i*100),
turns:1,messages:[{role:'user',text:marker,at:now},{role:'assistant',text:marker,at:now}],
}))}
function overlap(a,b){return Math.min(a.right,b.right)-Math.max(a.left,b.left)>.5 && Math.min(a.bottom,b.bottom)-Math.max(a.top,b.top)>.5}
for(const engine of (process.env.OFFICE_BROWSERS||'chromium,webkit').split(',')) {
const type=engine==='webkit'?webkit:chromium
const browser=await type.launch({headless:true,timeout:30000,...(engine==='chromium'?{executablePath:process.env.OFFICE_CHROME||'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',args:['--use-angle=swiftshader','--enable-unsafe-swiftshader']}: {})})
try {
for(const [width,height] of [[600,620],[820,650],[1440,1000]]) {
console.log(`START ${engine} ${width}x${height}`)
const page=await browser.newPage({viewport:{width,height},deviceScaleFactor:2,colorScheme:'dark'})
const errors=[];page.on('pageerror',e=>errors.push(e.message));page.on('console',m=>{if(m.type()==='error')errors.push(m.text())})
await page.route('**/live.js*',route=>route.fulfill({contentType:'text/javascript',body:`globalThis.AgentOfficeLive=${JSON.stringify(snapshot)};`}))
// magpie 0.1.2305 web emits scheme-less numeric-host CSP sources.
// Observed refusal: Playwright 1.56.1 / WebKit 26.0 build 2215 on
// macOS 15.7.9 arm64. Maintainer could not reproduce on Linux build 2336.
// Explicit opt-in normalization keeps the same host/path and sandbox;
// it is not evidence that every WebKit/Safari release needs this workaround.
if(engine==='webkit' && process.env.OFFICE_NORMALIZE_WEBKIT_CSP==='1') {
await page.route('**/_magpie/plugin/**/index.html',async route=>{
const response=await route.fetch()
const headers=response.headers()
const origin=new URL(route.request().url())
headers['content-security-policy']=(headers['content-security-policy']||'').replaceAll(origin.host+'/_magpie/',origin.origin+'/_magpie/')
await route.fulfill({response,headers})
})
console.log('WebKit test-only CSP URL-scheme normalization enabled')
}
await page.goto(host)
await page.waitForTimeout(1000)
await page.getByText('Agent 办公室',{exact:true}).click()
await page.waitForSelector('iframe')
let frame
for(let attempt=0;attempt<5;attempt++) {
const iframe=await page.waitForSelector('iframe')
frame=await iframe.contentFrame()
try {await frame.waitForFunction(()=>document.querySelector('#nDone')?.textContent==='10',{timeout:30000});break}
catch(e){if(attempt===4||!e.message.includes('detached'))throw e;console.log('reacquire reloaded plugin frame')}
}
await frame.locator('#settingsBtn').click();await frame.locator('#optText').check();await frame.locator('#settingsBtn').click()
const dimensions=await frame.evaluate(()=>({width:innerWidth,height:innerHeight,scroll:document.documentElement.scrollWidth,docHeight:document.documentElement.scrollHeight}))
assert(dimensions.scroll<=dimensions.width+1,JSON.stringify(dimensions))
assert(dimensions.docHeight<=dimensions.height+1,JSON.stringify(dimensions))
for(const id of ['settings','todayMenu']) {
await frame.locator(id==='settings'?'#settingsBtn':'#todayBtn').click()
const bounds=await frame.locator('#'+id).evaluate(e=>{const r=e.getBoundingClientRect();return {left:r.left,right:r.right,top:r.top,bottom:r.bottom,w:innerWidth,h:innerHeight}})
assert(bounds.left>=0&&bounds.right<=bounds.w+1&&bounds.top>=0&&bounds.bottom<=bounds.h+1,`${engine} menu ${JSON.stringify(bounds)}`)
if(id==='settings') {
const sceneA11y=await frame.evaluate(()=>`${document.querySelector('#lblScene').textContent.trim()} ${document.querySelector('#optScene .picker-val').textContent.trim()}`)
assert((await frame.locator('#settings').ariaSnapshot()).includes(`button "${sceneA11y}"`),`${engine} picker accessible name ${sceneA11y}`)
await frame.locator('#optQuality').focus()
await page.keyboard.press('Enter')
assert.equal(await frame.locator('#optQualityList').isVisible(),true,`${engine} same-frame focus+Enter keeps picker open`)
const pb=await frame.locator('#optQualityList').evaluate(e=>{const r=e.getBoundingClientRect();return {left:r.left,right:r.right,top:r.top,bottom:r.bottom,w:innerWidth,h:innerHeight}})
assert(pb.left>=0&&pb.right<=pb.w+1&&pb.top>=0&&pb.bottom<=pb.h+1,`${engine} picker ${JSON.stringify(pb)}`)
await page.keyboard.press('Escape')
assert.equal(await frame.locator('#optQualityList').isVisible(),false)
assert.equal(await frame.locator('#settings').isVisible(),true)
await frame.locator('#optScene').click()
const sceneBar=await frame.locator('#optSceneList').evaluate(e=>({overscroll:getComputedStyle(e).overscrollBehaviorY,width:getComputedStyle(e,'::-webkit-scrollbar').width,thumb:getComputedStyle(e,'::-webkit-scrollbar-thumb').backgroundColor}))
assert.equal(sceneBar.overscroll,'contain')
assert.equal(sceneBar.width,'8px')
assert.notEqual(sceneBar.thumb,'rgba(0, 0, 0, 0)')
const sceneBox=await frame.locator('#optSceneList').boundingBox()
await page.mouse.move(sceneBox.x+sceneBox.width/2,sceneBox.y+sceneBox.height/2)
await page.mouse.wheel(0,600)
await page.mouse.wheel(0,600)
assert.equal(await frame.locator('#optSceneList').isVisible(),true,`${engine} wheel overscroll keeps picker open`)
await page.keyboard.press('Escape')
}
await page.screenshot({path:`${output}/${engine}-${width}-${id}.png`})
await frame.locator(id==='settings'?'#settingsBtn':'#todayBtn').click()
}
// ISO/2D/list/3D plus background/foreground must not reactivate a hidden renderer.
for(const dim of ['iso','2d','3d']) {
await frame.locator(`[data-dim="${dim}"]`).click()
await frame.evaluate(()=>{
Object.defineProperty(document,'hidden',{value:true,configurable:true});document.dispatchEvent(new Event('visibilitychange'))
Object.defineProperty(document,'hidden',{value:false,configurable:true});document.dispatchEvent(new Event('visibilitychange'))
})
await page.waitForTimeout(250)
const boxes=await frame.locator('.tag:visible').evaluateAll(es=>es.map(e=>{const r=e.getBoundingClientRect();return {left:r.left,right:r.right,top:r.top,bottom:r.bottom}}))
for(let i=0;i<boxes.length;i++)for(let j=i+1;j<boxes.length;j++)assert(!overlap(boxes[i],boxes[j]),`${engine} ${width} ${dim} label overlap`)
}
if(width===1440) {
await frame.locator('#settingsBtn').click()
const pick=async(btn,val)=>{await frame.locator(btn).click();await frame.locator(`${btn}List [data-value="${val}"]`).click()}
await pick('#optLang','en')
await frame.locator('#optQuality').focus()
await page.keyboard.press('ArrowDown')
await page.keyboard.press('Home')
await page.keyboard.press('Enter')
assert.equal((await frame.locator('#optQuality .picker-val').textContent())?.trim(),'Low')
await pick('#optLang','auto')
for(const scene of ['office','station','cafe','castle','pirate','graveyard','library','cyberlab','greenhouse','arctic','rainynight']) {
await pick('#optScene',scene)
for(const quality of ['low','medium','high']) {
await pick('#optQuality',quality)
await page.waitForTimeout(80)
}
}
await pick('#optScene','office')
await pick('#optQuality','medium')
await frame.locator('#settingsBtn').click()
}
await frame.locator('[data-mode="list"]').click()
const listBar=await frame.locator('#listview').evaluate(e=>({width:getComputedStyle(e,'::-webkit-scrollbar').width,thumb:getComputedStyle(e,'::-webkit-scrollbar-thumb').backgroundColor}))
assert.equal(listBar.width,'8px')
assert.notEqual(listBar.thumb,'rgba(0, 0, 0, 0)')
const buffer=await frame.locator('#office3d').evaluate(e=>[e.width,e.height])
await frame.evaluate(()=>{for(let i=0;i<5;i++)dispatchEvent(new Event('resize'));document.dispatchEvent(new Event('visibilitychange'))})
assert.deepEqual(await frame.locator('#office3d').evaluate(e=>[e.width,e.height]),buffer)
await frame.locator('[data-mode="office"]').click()
await frame.locator('#settingsBtn').click();await frame.locator('[data-hide="1h"]').click();await frame.locator('[data-hide="6h"]').click();await frame.locator('#settingsBtn').click()
assert.equal(await frame.locator('.toast').count(),0,'filtering must not replay old alerts')
await frame.evaluate(()=>{const real=Date.now;Date.now=()=>real()+11*60e3})
await frame.waitForFunction(()=>document.querySelector('#rows').textContent.includes(AgentOfficeModel.text(document.documentElement.lang).noProgress))
if(!(await frame.locator('#rail').isVisible())) await frame.locator('#sideBtn').click()
await frame.locator('.rail-row').first().click()
assert(await frame.locator('#pop').innerText().then(t=>t.includes(marker)))
await frame.locator('#settingsBtn').click()
await frame.locator('#optText').uncheck()
await frame.locator('#settingsBtn').click()
const leak=await frame.locator('body').evaluate((body,marker)=>({text:body.textContent.includes(marker),attrs:[...body.querySelectorAll('*')].some(n=>[...n.attributes].some(a=>a.value.includes(marker)))}),marker)
assert(!leak.text&&!leak.attrs,`${engine} stale private DOM ${JSON.stringify(leak)}`)
await page.screenshot({path:`${output}/${engine}-${width}-privacy.png`})
await frame.locator('#pop .px').click()
assert(!(await frame.locator('#pop').textContent()).includes(marker),'closed panel retains no private messages')
assert.deepEqual(errors,[],`${engine} page errors`)
console.log(`${engine} ${width}x${height} DPR2 iframe ${dimensions.width}x${dimensions.height}: menus, labels, modes, privacy PASS`)
await page.waitForTimeout(2800)
await page.close()
}
} finally {await browser.close()}
}