Implement Knowledge City platform, organizer and DAV integration

Capture accumulated application, UI, CLI, regression tests and design documentation changes, including task project mapping and default CalDAV list naming.

Keep deployment data, backups, local credentials and build artifacts out of Git. Move the Compose enrollment token to an ignored local environment file.
This commit is contained in:
Anya Tokugawa committed 2026-09-27 14:44:43 +09:00
1 parent 288e6e94ac
commit c1175d389f
699 files changed
+110197 -4117

No files matched your search

+65
View File
@@ -0,0 +1,65 @@
window.addEventListener('load',async()=>{
const wait=async(test,step)=>{for(let i=0;i<150;i++){if(test())return;await new Promise(r=>setTimeout(r,30));}throw new Error(step+': '+document.querySelector('[data-governance-result]')?.textContent);};
try{
document.querySelector('[data-governance-open]').click();
const dialog=document.querySelector('[data-governance-dialog]'),form=dialog.querySelector('[data-publication-form]'),fields=form.querySelector('fieldset');
await wait(()=>!fields.disabled,'open');
form.querySelector('[data-publication-preview]').click();
await wait(()=>!fields.disabled&&form.querySelector('[data-publication-impact] li'),'impact');
if(!form.querySelector('[data-publication-impact]').textContent.includes('/public/page'))throw new Error('Missing approved Path');
form.elements.confirm.checked=true;form.requestSubmit();
await wait(()=>!fields.disabled&&form.querySelector('[data-publication-status]').textContent===form.dataset.enabled,'approve');
const frame=document.createElement('iframe');frame.src='/public/page';document.body.append(frame);
await new Promise((resolve,reject)=>{frame.onload=resolve;frame.onerror=reject;});
if(!frame.contentDocument.querySelector('h1')?.textContent.includes('Public browser sentinel')||frame.contentWindow.authoredRan||frame.contentDocument.querySelector('.auth-menu'))throw new Error('Unsafe/broken public projection');
await wait(()=>frame.contentDocument.querySelector('[data-public-children-body] a[href="/public/page/child"]'),'async children');
const viewButtons=[...frame.contentDocument.querySelectorAll('.public-children-views button')];
if(viewButtons.map(button=>button.textContent).join('')!=='▦☷≡'||viewButtons.some(button=>!button.title||button.getAttribute('aria-label')!==button.title))throw new Error('Public view icons / accessible labels');
if(frame.contentDocument.querySelector('a[download]')||!frame.contentDocument.querySelector('.public-topbar a[href="/v/tree"]'))throw new Error('Public navigation chrome');
frame.style.width='100%';frame.style.height='600px';
const navigate=async url=>{await new Promise((resolve,reject)=>{frame.onload=resolve;frame.onerror=reject;frame.src=url;});};
const doc=()=>frame.contentDocument;
await navigate('/v/tree');
await wait(()=>doc().querySelector('[data-public-tree-tools]:not([hidden])'),'tree enhancement');
const row=path=>[...doc().querySelectorAll('[data-public-tree-path]')].find(r=>r.dataset.publicTreePath===path);
doc().querySelector('[data-public-collapse]').click();
if(!row('/public/page/child').hidden||row('/public').hidden)throw new Error('Tree collapse');
const link=row('/public').querySelector('.public-tree-name');link.focus();
link.dispatchEvent(new frame.contentWindow.KeyboardEvent('keydown',{key:'ArrowRight',bubbles:true}));
if(row('/public/page').hidden||!row('/public/page/child').hidden)throw new Error('Tree keyboard expand');
doc().querySelector('[data-public-expand]').click();
row('/public/page').querySelector('[data-public-tree-toggle]').click();
if(!row('/public/page/child').hidden||row('/public/page-other').hidden)throw new Error('Tree prefix collision');
const filter=doc().querySelector('[data-public-tree-filter]');filter.value='grandchild';filter.dispatchEvent(new frame.contentWindow.Event('input'));
if(row('/public/page/child/grandchild').hidden||row('/public').hidden||!row('/public/page-other').hidden)throw new Error('Tree filter ancestry');
await navigate('/v/browser/public/page');
await wait(()=>doc().querySelector('[data-public-children-body] a[href="/public/page/child"]'),'folder listing');
if(!doc().querySelector('a[href="/public/page"]')||!doc().querySelector('.public-child-folder[href="/v/browser/public/page/child"]'))throw new Error('Page / folder navigation');
const original=frame.contentWindow.fetch.bind(frame.contentWindow);let fail=true;
frame.contentWindow.fetch=(...args)=>fail?Promise.resolve(new frame.contentWindow.Response('temporary failure',{status:503})):original(...args);
doc().querySelector('[data-view="detail"]').click();
await wait(()=>doc().querySelector('[data-public-children-body] button'),'children retry');
fail=false;doc().querySelector('[data-public-children-body] button').click();
await wait(()=>doc().querySelector('.public-children-details'),'children retry success');
doc().querySelector('[data-view="list"]').click();doc().querySelector('[data-view="icon"]').click();
await wait(()=>doc().querySelector('.public-children-icons'),'latest view wins');
if(doc().querySelector('.public-children-list')||doc().querySelector('[data-view="icon"]').getAttribute('aria-pressed')!=='true')throw new Error('Stale children response');
await navigate('/public/page');
await wait(()=>doc().querySelector('.public-children-icons'),'view preference retained');
if(doc().documentElement.scrollWidth>frame.clientWidth+5)throw new Error('Public navigation horizontal overflow');
await navigate('/');
await wait(()=>doc().querySelector('[data-public-children-body] a[href="/v/tree/public"]'),'public home directory');
const tree=await fetch('/v/tree');if(!tree.ok||!(await tree.text()).includes('/public/page/child'))throw new Error('Public tree');
const map=await fetch('/_/api/v1/city/map');if(!map.ok||(await map.json()).quartiers.length!==1)throw new Error('Public City');
await navigate('/v/tree');
await wait(()=>doc().querySelector('[data-public-tree-tools]:not([hidden])'),'final tree');
form.querySelector('[data-publication-revoke]').click();
await wait(()=>!fields.disabled&&form.querySelector('[data-publication-status]').textContent===form.dataset.disabled,'revoke');
const response=await fetch('/public/page',{redirect:'manual'});if(response.status===200)throw new Error('Revocation failed');
const children=await fetch('/v/children?path=/public/page');if((await children.text()).includes('/public/page/child'))throw new Error('Stale children cache');
dialog.close();
[...document.body.children].forEach(element=>{if(element!==frame)element.style.display='none';});
document.body.style.margin='0';document.body.style.padding='0';frame.style.border='0';frame.style.height='100vh';
document.body.dataset.vimReady='true';
}catch(error){const box=document.createElement('div');box.id='error';box.textContent=error.message;document.body.append(box);}
});
+36
View File
@@ -0,0 +1,36 @@
;(async () => {
const assert = (value, message) => { if (!value) throw new Error(message) }
const phase = sessionStorage.getItem('auth-flow-phase') || 'login'
if (phase === 'login') {
const form = document.querySelector('form[action="/_/auth/login"]')
assert(form, 'Login form missing')
form.elements.username.value = 'admin'
form.elements.password.value = 'a long test password'
sessionStorage.setItem('auth-flow-phase', 'authenticated')
form.requestSubmit()
return
}
if (phase === 'authenticated') {
assert(location.pathname === '/-/sys/config', 'Cookie login did not return to configuration')
assert(document.querySelector('.auth-user-name')?.textContent.includes('Test Admin'), 'Authenticated account missing')
assert(!document.cookie.includes('pageswiki_session'), 'Session cookie is not HttpOnly')
const confirmation = await fetch('/_/auth/logout')
assert(confirmation.ok && (await confirmation.text()).includes('action="/_/auth/logout"'), 'Logout GET is not confirmation')
const api = await fetch('/_/api/v1/queue')
assert(api.ok, 'Logout GET revoked the browser session')
const form = document.querySelector('.auth-menu-popover form[action="/_/auth/logout"]')
assert(form?.method === 'post', 'Account menu logout is not POST')
sessionStorage.setItem('auth-flow-phase', 'logged-out')
form.requestSubmit()
return
}
assert(location.pathname === '/_/auth/login', 'Logout did not return to login')
const denied = await fetch('/_/api/v1/queue')
assert(denied.status === 401, 'Logged-out cookie still authenticated')
document.body.dataset.vimReady = 'true'
})().catch(error => {
const element = document.createElement('pre')
element.id = 'error'
element.textContent = error.stack || String(error)
document.body.append(element)
})
+22
View File
@@ -0,0 +1,22 @@
window.addEventListener('load',async()=>{
const wait=async(test,label)=>{for(let i=0;i<150;i++){if(test())return;await new Promise(r=>setTimeout(r,30));}throw new Error(label);};
try {
document.querySelector('[data-governance-open]').click();
const dialog=document.querySelector('[data-governance-dialog]');
await wait(()=>!dialog.querySelector('fieldset').disabled,'load');
const form=dialog.querySelector('[data-auto-publication-form]'),save=form.querySelector('[data-auto-save]');
const preview=async()=>{form.querySelector('[data-auto-preview]').click();await wait(()=>!save.disabled,'automatic preview');};
await preview();if(form.elements.mode.value!=='automatic')throw new Error('current mode');
if(!form.querySelector('[data-auto-impact]').textContent.includes('/auto/empty/new'))throw new Error('impact list');
form.elements.mode.value='required';form.requestSubmit();
await wait(()=>!form.querySelector('[data-auto-impact]').textContent,'manual save');
await preview();if(form.elements.mode.value!=='required')throw new Error('manual persisted');
if(form.elements.mode.querySelector('[value=automatic]').disabled)throw new Error('automatic eligibility');
form.elements.mode.value='automatic';form.elements.confirm.checked=true;form.requestSubmit();
await wait(()=>!form.querySelector('[data-auto-impact]').textContent,'automatic save');
await preview();if(form.elements.mode.value!=='automatic')throw new Error('automatic persisted');
form.scrollIntoView({block:'center'});
if(dialog.scrollWidth>dialog.clientWidth+2)throw new Error('horizontal overflow');
document.body.dataset.vimReady='true';
}catch(error){const node=document.createElement('div');node.id='error';node.textContent=error.message;document.body.append(node);}
});
+176
View File
@@ -0,0 +1,176 @@
import {spawn} from 'node:child_process';
import {setTimeout as delay} from 'node:timers/promises';
import {once} from 'node:events';
const [url,profile]=process.argv.slice(2);
const browser=spawn('chromium',['--headless','--no-sandbox','--disable-gpu','--disable-background-networking','--no-proxy-server','--remote-debugging-port=0','--user-data-dir='+profile,'about:blank']);
let socket;
process.on('SIGTERM',()=>{browser.kill();process.exit(1);});
try {
const endpoint=await new Promise((resolve,reject)=>{let log='';browser.stderr.on('data',chunk=>{log+=chunk;const m=log.match(/DevTools listening on (ws:\/\/[^\s]+)/);if(m)resolve(m[1]);});browser.on('error',reject);browser.on('exit',code=>reject(new Error('Browser exited '+code)));});
socket=new WebSocket(endpoint);await new Promise((resolve,reject)=>{socket.onopen=resolve;socket.onerror=reject;});
let seq=0,gets=0,reports=0;const pending=new Map(),errors=[];
socket.onmessage=event=>{const m=JSON.parse(event.data),p=pending.get(m.id);if(p){pending.delete(m.id);m.error?p.reject(new Error(JSON.stringify(m.error))):p.resolve(m.result);}if(m.method==='Network.requestWillBeSent'){if(m.params.request.method==='REPORT')reports++;if(m.params.request.url.includes('/events?uid=')||m.params.request.url.includes('/events?resource='))gets++;}if(m.method==='Runtime.exceptionThrown')errors.push(JSON.stringify(m.params));};
const send=(method,params={},sessionId)=>new Promise((resolve,reject)=>{pending.set(++seq,{resolve,reject});socket.send(JSON.stringify({id:seq,method,params,sessionId}));});
const {targetId}=await send('Target.createTarget',{url:'about:blank'}),{sessionId}=await send('Target.attachToTarget',{targetId,flatten:true});const call=(method,params={})=>send(method,params,sessionId);
await call('Runtime.enable');await call('Network.enable');await call('Page.enable');await call('Page.navigate',{url});
const evaluate=async expression=>{const r=await call('Runtime.evaluate',{expression,returnByValue:true,awaitPromise:true});if(r.exceptionDetails)throw new Error(JSON.stringify(r.exceptionDetails));return r.result.value;};
const wait=async expression=>{for(let i=0;i<150;i++){if(await evaluate(expression))return;await delay(50);}throw new Error('Timed out: '+expression+' '+await evaluate('document.body.innerText'));};
await wait("document.querySelector('.calendar-event')?.textContent.includes('Browser meeting') && !document.querySelector('#calendar-status').textContent");
await wait("document.querySelector('#tasks-dav-open')");
await evaluate("document.querySelector('#tasks-dav-open').click()");
await wait("document.querySelector('#tasks-dav-dialog').open && document.querySelector('#tasks-dav-dialog thead')");
if(!await evaluate("(()=>{const d=document.querySelector('#tasks-dav-dialog'),r=d.getBoundingClientRect();return getComputedStyle(d).backgroundColor!=='rgba(0, 0, 0, 0)'&&r.width<=innerWidth&&d.scrollWidth<=d.clientWidth+1&&d.querySelector('form select').value==='calendar'&&d.querySelector(':scope>input').value.endsWith('/_/api/v1/caldav/')})()"))throw Error('Common DAV dialog style/default scope invalid');
await evaluate("(()=>{const f=document.querySelector('#tasks-dav-dialog form'),c=document.querySelector('#tasks-dav-compat');if(c.checked)throw Error('Compatibility must be opt-in');c.checked=true;f.querySelector('input').value='Calendar browser fixture';f.querySelector('select').value='all';f.requestSubmit()})()");
await wait("!document.querySelector('#tasks-dav-dialog section').hidden && document.querySelector('#tasks-dav-dialog tbody tr')");
if(!await evaluate("document.querySelector('#tasks-dav-dialog tbody').textContent.includes('OneTask')"))throw Error('Compatibility mode was not saved');
await evaluate("window.confirm=()=>true;document.querySelector('#tasks-dav-dialog tbody button').click()");
await wait("!document.querySelector('#tasks-dav-dialog tbody tr')");
await evaluate("document.querySelector('#tasks-dav-dialog header button').click()");
if(!await evaluate("document.querySelector('#tasks-dav-dialog section').hidden&&!document.querySelector('#tasks-dav-dialog section input')"))throw Error('Common DAV secret remained after close');
if(!await evaluate("getComputedStyle(document.querySelector('#calendar-content')).backdropFilter.includes('blur')"))throw Error('Calendar view glass background was not applied');
await evaluate("Array.from({length:localStorage.length},(_,i)=>localStorage.key(i)).filter(k=>k?.startsWith('pageswiki.calendar.view.v1:')).forEach(k=>localStorage.removeItem(k))");
await call('Page.navigate',{url:new URL('/v/plan?calendar='+new URL(url).searchParams.get('calendar'),url).href});
await wait("document.querySelectorAll('.calendar-time-column').length===7 && !document.querySelector('#calendar-status').textContent");
await call('Page.navigate',{url});
await wait("document.querySelector('.calendar-event')?.textContent.includes('Browser meeting') && !document.querySelector('#calendar-status').textContent");
await call('Page.navigate',{url:new URL('/v/plan?calendar='+new URL(url).searchParams.get('calendar'),url).href});
await wait("document.querySelector('.calendar-month') && !document.querySelector('#calendar-status').textContent");
await call('Page.navigate',{url});
await wait("document.querySelector('.calendar-event')?.textContent.includes('Browser meeting') && !document.querySelector('#calendar-status').textContent");
const before=gets,reportBefore=reports;
await evaluate("document.querySelector('#calendar-refresh').click()");
await wait("document.querySelector('#calendar-status').textContent === ''");
await delay(200);
if(gets!==before||reports<=reportBefore)throw new Error('ETag refresh fetched unchanged event data');
await evaluate("document.querySelector('#calendar-new').click()");
await wait("document.querySelector('#calendar-dialog').open");
if(!await evaluate("(()=>{const d=document.querySelector('#calendar-dialog'),f=document.querySelector('#calendar-form'),fields=document.querySelector('#calendar-fields'),s=getComputedStyle(d);return s.position==='fixed'&&s.backdropFilter.includes('blur')&&getComputedStyle(f).display==='grid'&&getComputedStyle(fields).overflowY==='auto'})()"))throw Error('Calendar editor modal styles were not applied');
await evaluate("document.querySelector('[name=summary]').value='Created in browser';document.querySelector('#calendar-form').requestSubmit()");
await wait("location.pathname==='/v/plan/cal/2026/09' && Array.from(document.querySelectorAll('.calendar-event')).some(e=>e.textContent.includes('Created in browser')) && !document.querySelector('#calendar-dialog').open");
await evaluate("Array.from(document.querySelectorAll('.calendar-event')).find(e=>e.textContent.includes('Created in browser')).click()");
await wait("document.querySelector('.calendar-detail h2')?.textContent==='Created in browser'");
await evaluate("document.querySelector('a[href*=\"/edit?\"]').click()");
await wait("document.querySelector('#calendar-dialog').open");
await evaluate("document.querySelector('[name=summary]').value='Edited in browser';document.querySelector('#calendar-form').requestSubmit()");
await wait("document.querySelector('.calendar-detail h2')?.textContent==='Edited in browser' && !document.querySelector('#calendar-dialog').open");
await evaluate("document.querySelector('#calendar-settings').click()");
await wait("document.querySelector('#calendar-dialog').open");
await evaluate("document.querySelector('[name=name]').value='Renamed Calendar';document.querySelector('[name=pretty_name]').value='work';document.querySelector('#calendar-form').requestSubmit()");
await wait("document.querySelector('#calendar-heading').textContent.includes('Renamed Calendar') && !document.querySelector('#calendar-dialog').open");
await evaluate("window.confirm=()=>true;document.querySelector('.calendar-detail nav button').click()");
await wait("location.pathname.includes('/v/plan/cal/') && !document.querySelector('#calendar-status').textContent");
if(await evaluate("document.querySelector('#calendar-content').textContent.includes('Edited in browser')"))throw new Error('Deleted event remained visible');
await evaluate("(async()=>{const base='/_/api/v1/extension/organizer.calendar/';const r=await fetch(base+'calendars',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({name:'Personal',pretty_name:'personal'})});if(!r.ok)throw Error(await r.text());const c=await r.json();const event=await fetch(base+'calendars/'+c.id+'/events',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({summary:'Personal meeting',start:'2026-09-22T11:00:00Z',end:'2026-09-22T12:00:00Z'})});if(!event.ok)throw Error(await event.text());})()");
await call('Page.navigate',{url:new URL('/v/plan/cal/2026/09?calendar=work,personal',url).href});
await wait("document.querySelector('#calendar-content')?.textContent.includes('Personal meeting') && document.querySelector('#calendar-content')?.textContent.includes('Browser meeting') && !document.querySelector('#calendar-status').textContent");
if(!await evaluate("Array.from(document.querySelectorAll('.calendar-event')).some(a=>a.href.includes('calendar=work'))&&Array.from(document.querySelectorAll('.calendar-event')).some(a=>a.href.includes('calendar=personal'))"))throw Error('Event links lost source calendar');
await evaluate("document.querySelector('#calendar-display-settings').click()");
await wait("document.querySelector('#calendar-dialog').open");
await evaluate("document.querySelector('[name=save-defaults]').checked=true;document.querySelector('#calendar-form').requestSubmit()");
await wait("location.search==='' && !document.querySelector('#calendar-dialog').open && document.querySelector('#calendar-content').textContent.includes('Personal meeting')");
await call('Page.reload');
await wait("document.querySelector('#calendar-content')?.textContent.includes('Personal meeting') && document.querySelector('#calendar-content')?.textContent.includes('Browser meeting') && !document.querySelector('#calendar-status').textContent");
if(await evaluate("location.search!==''"))throw Error('Defaults added a calendar query');
await call('Page.navigate',{url:new URL('/v/plan/cal/2026/09/22?calendar=work',url).href});
await wait("document.querySelector('.calendar-time-event .calendar-move-handle') && !document.querySelector('#calendar-status').textContent");
if(!await evaluate("document.querySelector('#calendar-app').dataset.timezone==='Asia/Tokyo'&&parseFloat(document.querySelector('.calendar-time-event').style.top)===1080"))throw Error('Configured calendar timezone was not used by the time grid');
if(!await evaluate("(()=>{const s=getComputedStyle(document.querySelector('.calendar-time-scroll'));return s.scrollbarWidth==='thin'&&s.scrollbarColor!=='auto'})()"))throw Error('Global theme-aware scrollbar styles were not applied');
let viewportMetrics=await evaluate("(()=>{const r=document.querySelector('.calendar-time-scroll').getBoundingClientRect(),v=document.querySelector('.calendar-time-view').getBoundingClientRect(),c=document.querySelector('#calendar-content').getBoundingClientRect();return {bottom:r.bottom,height:r.height,viewport:innerHeight,page:document.documentElement.scrollHeight,ratio:v.height/c.height,body:getComputedStyle(document.body).display,app:getComputedStyle(document.querySelector('#calendar-app')).display}})()");
if(viewportMetrics.bottom>viewportMetrics.viewport+2||viewportMetrics.height<100||viewportMetrics.page>viewportMetrics.viewport+1||Math.abs(viewportMetrics.ratio-.95)>.02)throw Error('Day time grid did not use 95% of the remaining viewport: '+JSON.stringify(viewportMetrics));
const moveGets=gets,moveReports=reports;
await evaluate("document.querySelector('.calendar-move-handle').dispatchEvent(new KeyboardEvent('keydown',{key:'ArrowDown',bubbles:true}))");
await wait("document.querySelector('.calendar-time-event')?.dataset.start==='2026-09-22T09:15:00Z' && !document.querySelector('#calendar-status').textContent");
await delay(100);
await evaluate("document.querySelector('.calendar-move-handle').scrollIntoView({block:'center',inline:'center'})");
await delay(50);
let point=await evaluate("(()=>{const r=document.querySelector('.calendar-move-handle').getBoundingClientRect();return {x:r.x+r.width/2,y:r.y+r.height/2}})()");
await call('Input.dispatchMouseEvent',{type:'mousePressed',button:'left',clickCount:1,...point});
await call('Input.dispatchMouseEvent',{type:'mouseMoved',button:'left',buttons:1,x:point.x,y:point.y+15});
await call('Input.dispatchMouseEvent',{type:'mouseReleased',button:'left',clickCount:1,x:point.x,y:point.y+15});
await wait("document.querySelector('.calendar-time-event')?.dataset.start==='2026-09-22T09:30:00Z' && !document.querySelector('#calendar-status').textContent");
const height=await evaluate("document.querySelector('.calendar-time-column').offsetHeight");
await evaluate("document.querySelector('[data-calendar-zoom=in]').click()");
if(await evaluate("document.querySelector('.calendar-time-column').offsetHeight")<=height)throw Error('Zoom did not change scale');
await evaluate("(()=>{for(let i=0;i<10;i++){const b=document.querySelector('[data-calendar-zoom=in]');if(!b||b.disabled)break;b.click();}})()");
if(!await evaluate("document.querySelector('.calendar-time-controls span')?.textContent==='400%'&&document.querySelector('.calendar-time-grid')?.dataset.snapMinutes==='5'&&document.querySelector('[data-calendar-zoom=in]').disabled"))throw Error('Maximum zoom or five-minute scale missing');
await evaluate("(()=>{const s=document.querySelector('.calendar-time-scroll');s.scrollTop=16*240-s.clientHeight/2+30})()");
point=await evaluate("(()=>{const c=document.querySelector('.calendar-time-column'),r=c.getBoundingClientRect(),x=r.x+r.width/2,y=r.top+16*240,h=document.elementFromPoint(x,y);return {x,y,hit:h?.className||h?.tagName,top:r.top,scroll:c.closest('.calendar-time-scroll').scrollTop}})()");
if(point.hit!=='calendar-time-column')throw Error('Empty-range test target is not visible: '+JSON.stringify(point));
await call('Input.dispatchMouseEvent',{type:'mousePressed',button:'left',clickCount:1,...point});
await call('Input.dispatchMouseEvent',{type:'mouseMoved',button:'left',buttons:1,x:point.x,y:point.y+120});
await call('Input.dispatchMouseEvent',{type:'mouseReleased',button:'left',clickCount:1,x:point.x,y:point.y+120});
await wait("document.querySelector('#calendar-dialog').open");
if(!await evaluate("document.querySelector('[name=start]').value==='2026-09-22T16:00'&&document.querySelector('[name=end]').value==='2026-09-22T16:30'"))throw Error('Empty-range drag did not prefill configured-timezone event range');
await evaluate("document.querySelector('#calendar-cancel').click()");
await evaluate("document.querySelector('.calendar-resize-end').dispatchEvent(new KeyboardEvent('keydown',{key:'ArrowDown',bubbles:true}))");
await wait("document.querySelector('.calendar-time-event')?.dataset.end==='2026-09-22T10:35:00Z' && !document.querySelector('#calendar-status').textContent");
await evaluate("document.querySelector('.calendar-resize-end').scrollIntoView({block:'center',inline:'center'})");
await delay(50);
point=await evaluate("(()=>{const r=document.querySelector('.calendar-resize-end').getBoundingClientRect();return {x:r.x+r.width/2,y:r.y+r.height/2}})()");
await call('Input.dispatchMouseEvent',{type:'mousePressed',button:'left',clickCount:1,...point});
await call('Input.dispatchMouseEvent',{type:'mouseMoved',button:'left',buttons:1,x:point.x,y:point.y+20});
await call('Input.dispatchMouseEvent',{type:'mouseReleased',button:'left',clickCount:1,x:point.x,y:point.y+20});
await wait("document.querySelector('.calendar-time-event')?.dataset.end==='2026-09-22T10:40:00Z' && !document.querySelector('#calendar-status').textContent");
await evaluate("document.querySelector('.calendar-resize-end').dispatchEvent(new KeyboardEvent('keydown',{key:'ArrowUp',bubbles:true}))");
await wait("document.querySelector('.calendar-time-event')?.dataset.end==='2026-09-22T10:35:00Z' && !document.querySelector('#calendar-status').textContent");
await evaluate("document.querySelector('.calendar-resize-start').scrollIntoView({block:'center',inline:'center'})");
await delay(50);
point=await evaluate("(()=>{const r=document.querySelector('.calendar-resize-start').getBoundingClientRect();return {x:r.x+r.width/2,y:r.y+r.height/2}})()");
await call('Input.dispatchMouseEvent',{type:'mousePressed',button:'left',clickCount:1,...point});
await call('Input.dispatchMouseEvent',{type:'mouseMoved',button:'left',buttons:1,x:point.x,y:point.y+20});
await call('Input.dispatchMouseEvent',{type:'mouseReleased',button:'left',clickCount:1,x:point.x,y:point.y+20});
await wait("document.querySelector('.calendar-time-event')?.dataset.start==='2026-09-22T09:35:00Z' && !document.querySelector('#calendar-status').textContent");
await evaluate("document.querySelector('.calendar-resize-start').dispatchEvent(new KeyboardEvent('keydown',{key:'ArrowUp',bubbles:true}))");
await wait("document.querySelector('.calendar-time-event')?.dataset.start==='2026-09-22T09:30:00Z' && !document.querySelector('#calendar-status').textContent");
if(gets!==moveGets||reports!==moveReports)throw Error('Time changes reloaded the calendar instead of updating locally');
await evaluate("(async()=>{const base='/_/api/v1/extension/organizer.calendar/',id=document.querySelector('#calendar-select').value;const r=await fetch(base+'calendars/'+id+'/events',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({summary:'Overlapping meeting',start:'2026-09-22T09:45:00Z',end:'2026-09-22T10:15:00Z'})});if(!r.ok)throw Error(await r.text());document.querySelector('#calendar-refresh').click()})()");
await wait("Array.from(document.querySelectorAll('.calendar-time-event')).some(e=>e.textContent.includes('Overlapping meeting'))&&!document.querySelector('#calendar-status').textContent");
if(!await evaluate("(()=>{const cards=Array.from(document.querySelectorAll('.calendar-time-event')).filter(e=>/Browser meeting|Overlapping meeting/.test(e.textContent));return cards.length===2&&cards.every(e=>e.style.width==='50%')})()"))throw Error('Overlapping events did not receive equal lanes');
await call('Page.navigate',{url:new URL('/v/plan/cal/2026/09/22/week?calendar=work',url).href});
await wait("document.querySelectorAll('.calendar-time-column').length===7 && !document.querySelector('#calendar-status').textContent");
viewportMetrics=await evaluate("(()=>{const r=document.querySelector('.calendar-time-scroll').getBoundingClientRect(),v=document.querySelector('.calendar-time-view').getBoundingClientRect(),c=document.querySelector('#calendar-content').getBoundingClientRect();return {bottom:r.bottom,height:r.height,viewport:innerHeight,page:document.documentElement.scrollHeight,ratio:v.height/c.height}})()");
if(viewportMetrics.bottom>viewportMetrics.viewport+2||viewportMetrics.height<100||viewportMetrics.page>viewportMetrics.viewport+1||Math.abs(viewportMetrics.ratio-.95)>.02)throw Error('Week time grid did not use 95% of the remaining viewport: '+JSON.stringify(viewportMetrics));
await call('Page.navigate',{url:new URL('/v/plan/cal/2026/09/22/timeline?calendar=work',url).href});
await wait("Array.from(document.querySelectorAll('.calendar-track[data-start]')).some(e=>e.textContent.includes('Browser meeting')&&e.querySelector('.calendar-timeline-handle')) && !document.querySelector('#calendar-status').textContent");
await evaluate("Array.from(document.querySelectorAll('.calendar-track[data-start]')).find(e=>e.textContent.includes('Browser meeting')).querySelector('.calendar-timeline-handle').dispatchEvent(new KeyboardEvent('keydown',{key:'ArrowRight',bubbles:true}))");
await wait("Array.from(document.querySelectorAll('.calendar-track[data-start]')).find(e=>e.textContent.includes('Browser meeting'))?.dataset.start==='2026-09-22T09:45:00Z' && !document.querySelector('#calendar-status').textContent");
await evaluate("Array.from(document.querySelectorAll('.calendar-track[data-start]')).find(e=>e.textContent.includes('Browser meeting')).querySelector('.calendar-timeline-handle').scrollIntoView({block:'center',inline:'center'})");
await delay(50);
point=await evaluate("(()=>{const h=Array.from(document.querySelectorAll('.calendar-track[data-start]')).find(e=>e.textContent.includes('Browser meeting')).querySelector('.calendar-timeline-handle'),r=h.getBoundingClientRect();return {x:r.x+r.width/2,y:r.y+r.height/2,step:h.parentNode.getBoundingClientRect().width/24}})()");
await call('Input.dispatchMouseEvent',{type:'mousePressed',button:'left',clickCount:1,x:point.x,y:point.y});
await call('Input.dispatchMouseEvent',{type:'mouseMoved',button:'left',buttons:1,x:point.x+point.step,y:point.y});
await call('Input.dispatchMouseEvent',{type:'mouseReleased',button:'left',clickCount:1,x:point.x+point.step,y:point.y});
await wait("Array.from(document.querySelectorAll('.calendar-track[data-start]')).find(e=>e.textContent.includes('Browser meeting'))?.dataset.start==='2026-09-22T10:45:00Z' && !document.querySelector('#calendar-status').textContent");
await call('Page.navigate',{url:new URL('/v/plan/cal/2026/09/22/week/list?calendar=work',url).href});
await wait("document.querySelectorAll('.calendar-week-heading').length===7 && document.querySelector('#calendar-content').textContent.includes('Browser meeting')");
await evaluate("document.querySelector('#calendar-new').click()");
await wait("document.querySelector('#calendar-dialog').open");
await evaluate("document.querySelector('[name=summary]').value='Inclusive all day';const a=document.querySelector('[name=all_day]');a.checked=true;a.dispatchEvent(new Event('change'));document.querySelector('[name=start]').value='2026-09-22';document.querySelector('[name=end]').value='2026-09-22';document.querySelector('#calendar-form').requestSubmit()");
await wait("location.pathname.endsWith('/week/list') && Array.from(document.querySelectorAll('.calendar-event')).some(e=>e.textContent.includes('Inclusive all day')) && !document.querySelector('#calendar-dialog').open");
await evaluate("Array.from(document.querySelectorAll('.calendar-event')).find(e=>e.textContent.includes('Inclusive all day')).click()");
await wait("document.querySelector('.calendar-detail h2')?.textContent==='Inclusive all day'");
if(!await evaluate("Array.from(document.querySelectorAll('.calendar-detail dd')).slice(0,2).every(e=>e.textContent==='2026-09-22')"))throw Error('All-day display is not inclusive');
await evaluate("document.querySelector('a[href*=\"/edit?\"]').click()");
await wait("document.querySelector('#calendar-dialog').open");
if(!await evaluate("document.querySelector('[name=end]').value==='2026-09-22'"))throw Error('All-day edit extended date');
await evaluate("document.querySelector('#calendar-cancel').click();document.querySelector('[data-calendar-upcoming-launch]').click()");
await wait("document.querySelector('[data-calendar-upcoming-dialog]').matches(':modal') && !document.querySelector('[data-calendar-upcoming-status]').textContent.includes('Loading') && !document.querySelector('[data-calendar-upcoming-status]').textContent.includes('読み込み')");
if(!await evaluate("getComputedStyle(document.documentElement).overflow==='hidden' && document.querySelector('[data-calendar-upcoming-launch]').nextElementSibling.matches('[data-notification-launch]')"))throw Error('Modal scroll lock or icon order');
if(!await evaluate("(()=>{const d=document.querySelector('[data-calendar-upcoming-dialog]'),i=d.querySelector('.calendar-upcoming-item'),s=getComputedStyle(d),r=d.getBoundingClientRect();return s.position==='fixed'&&Math.abs(r.height/innerHeight-.95)<.02&&d.querySelector('.calendar-upcoming-list')&&!d.textContent.includes('今日から31日間')&&(!i||(getComputedStyle(i).display==='grid'&&i.children.length===3&&i.children[0].tagName==='TIME'&&i.children[1].tagName==='TIME'))})()"))throw Error('Upcoming modal layout, 95% height, or compact event row is missing');
await call('Input.dispatchKeyEvent',{type:'keyDown',key:'Escape',code:'Escape',windowsVirtualKeyCode:27});
await call('Input.dispatchKeyEvent',{type:'keyUp',key:'Escape',code:'Escape',windowsVirtualKeyCode:27});
await wait("!document.querySelector('[data-calendar-upcoming-dialog]').open");
await evaluate("document.querySelector('[data-notification-launch]').click()");
await wait("document.querySelector('[data-notification-dialog]').matches(':modal')");
await evaluate("document.querySelector('[data-notification-close]').click()");
const disposable=await evaluate("(async()=>{const r=await fetch('/_/api/v1/extension/organizer.calendar/calendars',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({name:'Disposable Calendar',pretty_name:'disposable'})});if(!r.ok)throw Error(await r.text());return (await r.json()).pretty_name})()");
await call('Page.navigate',{url:new URL('/v/plan?calendar='+encodeURIComponent(disposable),url).href});
await wait("document.querySelector('#calendar-heading').textContent.includes('Disposable Calendar')&&!document.querySelector('#calendar-status').textContent");
await evaluate("document.querySelector('#calendar-settings').click()");
await wait("document.querySelector('#calendar-dialog').open&&document.querySelector('.calendar-delete-button')");
await evaluate("window.confirm=()=>true;document.querySelector('.calendar-delete-button').click()");
await wait("location.pathname==='/v/plan'&&!document.querySelector('#calendar-dialog').open&&!document.querySelector('#calendar-heading').textContent.includes('Disposable Calendar')&&!document.querySelector('#calendar-status').textContent");
if(!await evaluate("fetch('/_/api/v1/extension/organizer.calendar/calendars').then(r=>r.json()).then(v=>!v.calendars.some(c=>c.pretty_name==='disposable'))"))throw Error('Deleted calendar remained in API');
if(errors.length)throw new Error(errors.join('\n'));
console.log('Calendar browser CRUD, deletion, settings, navigation and ETag cache passed');
} finally {socket?.close();const closed=once(browser,'exit');browser.kill();await Promise.race([closed,delay(3000)]);}
+25
View File
@@ -0,0 +1,25 @@
// Chromium touch/small-viewport regression, not a claim of running iOS Safari.
import {spawn} from 'node:child_process';
import {writeFile} from 'node:fs/promises';
import {setTimeout as delay} from 'node:timers/promises';
const [origin,profile]=process.argv.slice(2);
const browser=spawn('chromium',['--headless','--no-sandbox','--disable-gpu','--disable-background-networking','--no-proxy-server','--remote-debugging-port=0','--user-data-dir='+profile,'about:blank']);
process.on('SIGTERM',()=>{browser.kill();process.exit(1);});let socket;
try{
const endpoint=await new Promise((resolve,reject)=>{let log='';browser.stderr.on('data',c=>{log+=c;const m=log.match(/DevTools listening on (ws:\/\/[^\s]+)/);if(m)resolve(m[1]);});browser.on('error',reject);});socket=new WebSocket(endpoint);await new Promise(resolve=>socket.onopen=resolve);let seq=0;const pending=new Map(),errors=[];socket.onmessage=e=>{const m=JSON.parse(e.data),p=pending.get(m.id);if(p){pending.delete(m.id);m.error?p.reject(Error(JSON.stringify(m.error))):p.resolve(m.result);}if(m.method==='Runtime.exceptionThrown')errors.push(JSON.stringify(m.params));};const send=(method,params={},sessionId)=>new Promise((resolve,reject)=>{pending.set(++seq,{resolve,reject});socket.send(JSON.stringify({id:seq,method,params,sessionId}));});const {targetId}=await send('Target.createTarget',{url:'about:blank'}),{sessionId}=await send('Target.attachToTarget',{targetId,flatten:true}),call=(method,params={})=>send(method,params,sessionId);await call('Runtime.enable');await call('Page.enable');await call('Emulation.setTouchEmulationEnabled',{enabled:true,maxTouchPoints:1});
const evaluate=async expression=>{const r=await call('Runtime.evaluate',{expression,returnByValue:true,awaitPromise:true});if(r.exceptionDetails)throw Error(JSON.stringify(r.exceptionDetails));return r.result.value;};const wait=async expr=>{for(let i=0;i<100;i++){if(await evaluate(expr))return;await delay(50);}throw Error('Timed out: '+expr);};
for(const [width,height] of [[320,568],[375,667],[667,375]]){
await call('Emulation.setDeviceMetricsOverride',{width,height,deviceScaleFactor:1,mobile:true});await call('Page.navigate',{url:origin+'/v/plan/cal/2026/09/22/week?calendar=mobile'});await wait("document.querySelectorAll('.calendar-time-column').length===7&&!document.querySelector('#calendar-status').textContent");await delay(100);
const metrics=await evaluate("(()=>{const scroll=document.querySelector('.calendar-time-scroll'),column=document.querySelector('.calendar-time-column'),card=document.querySelector('.calendar-time-event'),select=document.querySelector('.calendar-mobile-view'),r=scroll.getBoundingClientRect();return {width:document.documentElement.scrollWidth,viewport:innerWidth,height:r.height,bottom:r.bottom,screen:innerHeight,column:column.clientWidth,touch:getComputedStyle(card).touchAction,view:getComputedStyle(select).display,day:document.querySelector('.calendar-mobile-days [aria-pressed=true]')?.getAttribute('aria-label')}})()");
if(metrics.width>width+1||metrics.bottom>height+1||metrics.height<80||metrics.column<240||metrics.touch==='none'||metrics.view==='none'||metrics.day!=='2026-09-22')throw Error('Mobile layout '+width+': '+JSON.stringify(metrics));
await evaluate("document.querySelector('.calendar-mobile-days button:last-child').click()");await wait("document.querySelector('.calendar-mobile-days [aria-pressed=true]')?.getAttribute('aria-label')==='2026-09-27'");
await evaluate("document.querySelector('.calendar-mobile-days button:nth-child(2)').click()");
await evaluate("(()=>{const c=document.querySelector('.calendar-time-event');c.dispatchEvent(new PointerEvent('pointerdown',{bubbles:true,pointerId:7,pointerType:'touch',button:0,clientX:150,clientY:200}));if(c.hasPointerCapture(7))throw Error('Touch scroll captured by drag');})()");
await evaluate("document.querySelector('.calendar-touch-edit').click()");if(!await evaluate("getComputedStyle(document.querySelector('.calendar-time-event')).touchAction==='none'"))throw Error('Explicit gesture mode missing');await evaluate("document.querySelector('.calendar-touch-edit').click()");
if(width!==667){await evaluate("document.querySelector('.calendar-time-scroll').scrollTop=16*60");await delay(80);const screenshot=await call('Page.captureScreenshot',{format:'png'});await writeFile('/tmp/pageswiki-calendar-'+width+'.png',Buffer.from(screenshot.data,'base64'));}
await evaluate("document.querySelector('#calendar-new').click()");await wait("document.querySelector('#calendar-dialog').open");const editor=await evaluate("(()=>{const d=document.querySelector('#calendar-dialog'),i=d.querySelector('[name=summary]'),r=d.getBoundingClientRect();return {width:d.scrollWidth,client:d.clientWidth,bottom:r.bottom,top:r.top,font:parseFloat(getComputedStyle(i).fontSize)}})()");if(editor.width>editor.client+1||editor.bottom>height+1||editor.top<0||editor.font<16)throw Error('Editor small screen '+JSON.stringify(editor));
await evaluate("document.querySelector('#calendar-cancel').click();const s=document.querySelector('.calendar-mobile-view');s.value='month';s.dispatchEvent(new Event('change'))");await wait("document.querySelector('.calendar-month')&&!document.querySelector('#calendar-status').textContent");if(!await evaluate("document.documentElement.scrollWidth<=innerWidth+1&&getComputedStyle(document.querySelector('.calendar-mobile-count')).display!=='none'"))throw Error('Compact month counts missing');
await evaluate("document.querySelector('.calendar-mobile-actions').open=true");await delay(50);await evaluate("document.querySelector('.calendar-mobile-actions [data-source=calendar-settings]').click()");await wait("document.querySelector('#calendar-dialog').open&&document.querySelector('[name=pretty_name]')");await evaluate("document.querySelector('#calendar-cancel').click()");
}
if(errors.length)throw Error(errors.join('\n'));console.log('320/375 portrait and 667 landscape calendar UI passed');
}finally{socket?.close();browser.kill();}
+37
View File
@@ -0,0 +1,37 @@
window.addEventListener('load', async () => {
const wait = async (test,step) => { for (let i=0;i<150;i++) { if (test()) return; await new Promise(r=>setTimeout(r,30)); } throw new Error('Governance UI timeout: '+step+' '+document.querySelector('[data-governance-result]')?.textContent); };
try {
const domain = location.pathname === '/v/city';
if (domain) document.querySelector('[data-city-menu-open]').click();
document.querySelector('[data-governance-open]').click();
const dialog = document.querySelector('[data-governance-dialog]'), form = dialog.querySelector('form'), fields = form.querySelector('fieldset');
await wait(()=>!fields.disabled,'initial load');
if (!dialog.open) throw new Error('Settings dialog did not open');
if (!domain) {
if (!form.elements.policy.querySelector('[value=public]').disabled) throw new Error('Public option ignores superior cap');
const search = dialog.querySelector('[data-governance-search]'); search.value='delegate'; search.dispatchEvent(new Event('input'));
const select = dialog.querySelector('[data-governance-members]'); await wait(()=>select.options.length===1 && select.options[0].textContent.includes('delegate'),'member search');
dialog.querySelector('[data-governance-add]').click();
if (dialog.querySelectorAll('[data-governance-owners] li').length!==1) throw new Error('Owner picker failed');
}
form.elements.policy.value = domain ? 'public' : 'authenticated_acl';
if (domain) form.elements.confirm_relaxation.checked=true;
form.requestSubmit();
await wait(()=>dialog.querySelector('[data-governance-result]').textContent===dialog.dataset.saved,'save');
if (!domain) {
const acl=dialog.querySelector('[data-access-form]'); acl.elements.mode.value='restricted';
dialog.querySelector('[data-access-add]').click();
const row=dialog.querySelector('.city-access-row'); const name=row.querySelector('input'); name.value='delegate';name.dispatchEvent(new Event('input'));
const permission=row.querySelectorAll('select')[1];permission.value='read_write';permission.dispatchEvent(new Event('input'));
acl.elements.confirm.checked=true; acl.requestSubmit();
await wait(()=>dialog.querySelector('[data-governance-result]').textContent===acl.dataset.saved,'ACL save');
}
dialog.querySelector('[data-governance-close]').click();
document.querySelector('[data-governance-open]').click(); await wait(()=>!fields.disabled,'reopen');
if (form.elements.policy.value !== (domain?'public':'authenticated_acl')) throw new Error('Persisted policy lost');
if (!domain && dialog.querySelectorAll('[data-governance-owners] li').length!==1) throw new Error('Persisted owners lost');
if (!domain && (dialog.querySelector('[data-access-form]').elements.mode.value!=='restricted' || dialog.querySelector('.city-access-row input').value!=='delegate')) throw new Error('Persisted ACL lost');
const rect=dialog.getBoundingClientRect(); if (rect.width<200 || rect.width>window.innerWidth || rect.height>window.innerHeight) throw new Error('Dialog layout overflow');
dialog.close(); document.body.dataset.vimReady='true';
} catch(error) { const box=document.createElement('div'); box.id='error'; box.textContent=error.message; document.body.append(box); }
});
+114
View File
@@ -0,0 +1,114 @@
window.addEventListener('load', async () => {
const wait = async check => {
for (let i = 0; i < 200; i++) {
if (check()) return;
await new Promise(resolve => setTimeout(resolve, 25));
}
throw new Error('Immersive City did not finish rendering');
};
const assert = (value, message) => { if (!value) throw new Error(message); };
const click = (element, ctrlKey = false) => {
assert(element, 'Missing click target');
element.dispatchEvent(new MouseEvent('click', {bubbles:true, cancelable:true, ctrlKey}));
};
const boxesOverlap = (a, b) => a[0] < b[0]+b[2] && b[0] < a[0]+a[2] && a[1] < b[1]+b[3] && b[1] < a[1]+a[3];
const inspectStreet = () => {
const plots = [...document.querySelectorAll('[data-estate-box]')];
assert(plots.length <= 6, 'Street exceeded bounded Spot projection');
plots.forEach((plot, i) => {
const bounds = plot.dataset.estateBox.split(',').map(Number);
for (const other of plots.slice(i+1)) assert(!boxesOverlap(bounds, other.dataset.estateBox.split(',').map(Number)), 'Spot courtyards overlap');
assert(plot.querySelectorAll('.city-map-page-link').length <= 6, 'Street renders unbounded Page buildings');
const more = plot.querySelector('.city-estate-more');
if (more) {
const m = more.getBBox();
for (const page of plot.querySelectorAll('.city-map-page-link')) {
const p = page.getBBox();
assert(!boxesOverlap([m.x,m.y,m.width,m.height], [p.x,p.y,p.width,p.height]), 'More Pages badge covers a Page');
}
}
});
return plots.map(plot => plot.dataset.cityUuid);
};
try {
const fixture = new URLSearchParams(location.search).get('fixture');
if (fixture === 'mobile-light') {
await new Promise((resolve, reject) => {
const style = document.createElement('link'); style.rel = 'stylesheet'; style.href = '/static/css/theme/index-white.css';
style.onload = resolve; style.onerror = reject; document.head.append(style);
});
}
const originalURL = location.href, originalHistory = history.length;
const data = await (await fetch('/_/api/v1/city/map')).json();
const quartier = data.quartiers[0], street = quartier.streets.find(s => s.name === 'home');
const alpha = street.spots.find(s => s.title === 'alpha');
await wait(() => document.querySelector('.city-quartier-tile'));
assert(document.querySelector('#city-map').getBoundingClientRect().height > innerHeight * .8, 'Utilities occupy the map');
assert(document.documentElement.scrollHeight <= innerHeight+1, 'Map has document scrolling');
assert(!document.querySelector('[data-city-command-menu]').open, 'Utility menu is open on entry');
click(document.querySelector('.city-quartier-tile'));
await wait(() => document.querySelector('.city-street-tile'));
click(document.querySelector(`[data-city-type="Street"][data-city-uuid="${street.uuid}"]`));
await wait(() => document.querySelector('[data-estate-box]'));
const seenSpots = new Set(inspectStreet());
assert(!document.querySelector('[data-city-scene-pager]').hidden, 'Large Street has no pagination');
click(document.querySelector('[data-city-scene-next]'));
await wait(() => document.querySelector('[data-city-scene-next]').disabled && document.querySelector('[data-estate-box]'));
inspectStreet().forEach(id => seenSpots.add(id));
const nonempty = street.spots.filter(s => !window.PagesWikiCityEstates.undefinedSpot(s) || s.pages.length);
assert(seenSpots.size === nonempty.length, 'Pagination makes some Spots unreachable');
click(document.querySelector('[data-city-scene-prev]'));
await wait(() => document.querySelector(`[data-city-uuid="${alpha.uuid}"] .city-spot-entry`));
click(document.querySelector(`[data-city-uuid="${alpha.uuid}"] .city-spot-entry`));
await wait(() => document.querySelector('.city-estate-detail .city-map-page-link'));
assert(location.href === originalURL && history.length === originalHistory, 'Opening a Spot navigated to a document');
assert(document.querySelector('[aria-current="location"]').textContent === alpha.title, 'Breadcrumb omits focused Spot');
assert(document.querySelector('.city-portal-link').getAttribute('href') === '/life/home/alpha', 'Spot portal URL changed');
const pageLinks = [...document.querySelectorAll('.city-map-page-link')];
assert(pageLinks.length === 24, 'Focused Spot must bound Page rendering');
const seenPages = new Map(pageLinks.map(a => [a.dataset.pageUuid,a.getAttribute('href')]));
click(pageLinks[0], true);
assert(pageLinks[0].classList.contains('city-is-selected') && location.href === originalURL, 'Page building cannot be Ctrl-selected');
click(pageLinks[0], true);
click(document.querySelector('[data-city-scene-next]'));
await wait(() => document.querySelector('[data-city-scene-next]').disabled && document.querySelectorAll('.city-map-page-link').length < 24);
for (const a of document.querySelectorAll('.city-map-page-link')) seenPages.set(a.dataset.pageUuid,a.getAttribute('href'));
click(document.querySelector('.city-estate-focused > .city-courtyard'));
assert(document.querySelector('[data-city-scene-next]').disabled, 'Empty focused courtyard resets pagination');
const expected = window.PagesWikiCityEstates.surroundingPages(alpha);
assert(!seenPages.has(alpha.portal_page_uuid), 'Portal duplicates itself as a child Page');
assert(seenPages.size === expected.length, 'Focused Spot hides Pages permanently');
expected.forEach(p => assert(seenPages.get(p.page_uuid) === p.path, 'Page building points to the wrong URL'));
click(document.querySelector('[data-city-menu-open]'));
const menu = document.querySelector('[data-city-command-menu]');
assert(menu.open && menu.contains(document.activeElement), 'Menu did not acquire focus');
assert(menu.getBoundingClientRect().right <= innerWidth && menu.getBoundingClientRect().bottom <= innerHeight, 'Menu is outside viewport');
for (const tab of ['directory','planning','settings','guide']) {
click(menu.querySelector(`[data-city-menu-tab="${tab}"]`));
assert([...menu.querySelectorAll('[data-city-menu-panel]')].filter(p => !p.hidden).length === 1, 'Utility panels overlap');
assert(!menu.querySelector(`[data-city-menu-panel="${tab}"]`).hidden, 'Wrong utility panel');
}
click(menu.querySelector('[data-city-menu-tab="planning"]'));
const kind = menu.querySelector('[data-city-create-kind]');
kind.value = 'spot'; kind.dispatchEvent(new Event('change', {bubbles:true}));
assert([...menu.querySelectorAll('[data-city-create]')].filter(f => !f.hidden).length === 1 && !menu.querySelector('[data-city-create="spot"]').hidden, 'Creation forms are not compact');
click(menu.querySelector('[data-city-menu-close]'));
assert(!menu.open, 'Menu cannot close');
// Click outside the courtyard ascends without adding browser history.
click(document.querySelector('#city-map'));
await wait(() => document.querySelector('[data-estate-box]'));
assert(!document.querySelector('.city-estate-detail'), 'Background click does not ascend to Street');
assert(location.href === originalURL && history.length === originalHistory, 'Map exploration changed URL/history');
// The menu directory is also a map navigator, including locations whose
// assigned generated-road hit target is too small to pick visually.
click(document.querySelector('[data-city-menu-open]'));
click(menu.querySelector('[data-city-menu-tab="directory"]'));
click(menu.querySelector(`[data-city-jump="spot"][data-city-id="${alpha.uuid}"]`));
await wait(() => document.querySelectorAll('.city-estate-detail .city-map-page-link').length === 24);
assert(!menu.open && location.href === originalURL, 'Directory jump did not return to the map');
if (fixture === 'menu' || fixture === 'mobile-light') window.PagesWikiCityMenu.open('planning');
document.body.dataset.vimReady = 'true';
} catch (error) {
const box = document.createElement('div'); box.id = 'error'; box.textContent = error.stack || error.message; document.body.append(box);
}
});
+58
View File
@@ -0,0 +1,58 @@
window.addEventListener('load', async () => {
const assert = (condition, message) => { if (!condition) throw new Error(message); };
const wait = async condition => { for (let i=0;i<200;i++) { if(condition())return;await new Promise(r=>setTimeout(r,25)); } throw new Error('Keyboard scene did not render'); };
const key = (target, value, options={}) => { const event=new KeyboardEvent('keydown',{key:value,bubbles:true,cancelable:true,...options});target.dispatchEvent(event);return event; };
const click = (target, options={}) => target.dispatchEvent(new MouseEvent('click',{bubbles:true,cancelable:true,...options}));
const center = element => { const r=element.getBoundingClientRect();return {x:r.left+r.width/2,y:r.top+r.height/2}; };
try {
const url=location.href, historyLength=history.length;
const data=await(await fetch('/_/api/v1/city/map')).json();
const quartier=data.quartiers.find(q=>q.name==='life'), street=quartier.streets.find(s=>s.name==='home'), spot=street.spots.find(s=>s.title==='alpha');
await wait(()=>document.querySelectorAll('.city-quartier-tile').length===2);
const q=document.querySelector(`[data-city-uuid="${quartier.uuid}"]`);
q.focus();key(q,'Enter');
await wait(()=>document.querySelector(`[data-city-type="Street"][data-city-uuid="${street.uuid}"]`));
const s=document.querySelector(`[data-city-type="Street"][data-city-uuid="${street.uuid}"]`);
s.focus();key(s,'Enter');
await wait(()=>document.querySelector(`[data-city-uuid="${spot.uuid}"] .city-spot-entry`));
let entry=document.querySelector(`[data-city-uuid="${spot.uuid}"] .city-spot-entry`);
for(const [keys,axis,direction] of [[['ArrowLeft','a','h'],'x',-1],[['ArrowRight','d','l'],'x',1],[['ArrowUp','w','k'],'y',-1],[['ArrowDown','s','j'],'y',1]]){
for(const name of keys){
entry.focus();const origin=center(entry);const event=key(entry,name);
assert(event.defaultPrevented&&document.activeElement!==entry,`${name} did not move focus`);
assert((center(document.activeElement)[axis]-origin[axis])*direction>0,`${name} moved in the wrong direction`);
}
}
for(const options of [{ctrlKey:true},{metaKey:true},{altKey:true},{isComposing:true},{keyCode:229}]){
entry.focus();const event=key(entry,'h',options);assert(!event.defaultPrevented&&document.activeElement===entry,'Map consumed a modifier/composition shortcut');
}
entry.focus();key(entry,'Enter',{ctrlKey:true});
assert(!document.querySelector('.city-estate-detail'),'Ctrl+Enter activated a Spot');
for(const tag of ['input','textarea','div']){
const input=document.createElement(tag);if(tag==='div')input.contentEditable='true';document.body.append(input);input.focus();
const event=key(input,'w');assert(!event.defaultPrevented&&document.activeElement===input,`${tag} typing was hijacked`);input.remove();
}
window.PagesWikiCityMenu.open('settings');
const dialog=document.querySelector('[data-city-command-menu]'), before=document.activeElement;
const modalKey=key(document.body,'h');assert(!modalKey.defaultPrevented&&document.activeElement===before,'Modal key moved map focus');
assert(dialog.open,'Keyboard closed the utility modal');window.PagesWikiCityMenu.close();
click(entry,{ctrlKey:true});assert(entry.closest('.city-node').classList.contains('city-is-selected'),'Ctrl multi-selection stopped working');click(entry,{ctrlKey:true});
// Intercept before the popup's top-window navigation listener. Verify the
// exact activated href without leaving the browser regression fixture.
let captured='';const capture=event=>{const link=event.target.closest?.('.city-map-page-link');if(link){captured=link.getAttribute('href');event.preventDefault();event.stopImmediatePropagation();}};
window.addEventListener('click',capture,true);
const page=entry.closest('.city-node').querySelector('.city-map-page-link');page.focus();key(page,'Enter');
assert(captured.startsWith('/life/home/alpha/'),'Keyboard Page activation lost the semantic URL');window.removeEventListener('click',capture,true);
entry.focus();key(entry,'Enter');await wait(()=>document.querySelector('.city-estate-detail .city-map-page-link'));
assert(location.href===url&&history.length===historyLength,'Spot drill-down added browser history');
key(document.activeElement,'Backspace');await wait(()=>document.querySelector('.city-spot-entry'));
assert(document.activeElement.closest('[data-city-uuid]')?.dataset.cityUuid===spot.uuid,'Parent navigation did not restore Spot focus');
key(document.activeElement,'Backspace');await wait(()=>document.querySelector('.city-street-tile'));
assert(document.activeElement.dataset.cityUuid===street.uuid,'Parent navigation did not restore Street focus');
key(document.activeElement,'Backspace');await wait(()=>document.querySelector('.city-quartier-tile'));
assert(document.activeElement.dataset.cityUuid===quartier.uuid,'Parent navigation did not restore Quartier focus');
assert(key(document.activeElement,'Backspace').defaultPrevented,'Root Backspace was allowed to navigate browser history');
assert(location.href===url&&history.length===historyLength,'Map keyboard navigation changed browser history');
document.body.dataset.vimReady='true';
}catch(error){const box=document.createElement('div');box.id='error';box.textContent=error.stack||error.message;document.body.append(box);}
});
+65
View File
@@ -0,0 +1,65 @@
window.addEventListener('load', async () => {
const wait = async check => {
for (let i = 0; i < 150; i++) {
if (check()) return;
await new Promise(resolve => setTimeout(resolve, 30));
}
throw new Error('City label fixture did not finish rendering');
};
const checkLabels = selector => {
const labels = [...document.querySelectorAll(selector)];
if (!labels.length) throw new Error('Missing labels: ' + selector);
for (const label of labels) {
const style = getComputedStyle(label), matrix = label.getScreenCTM();
if (style.display === 'none' || Number(style.opacity) < .99 || !label.textContent.trim())
throw new Error('Label hidden without hover: ' + label.textContent);
if (label.querySelector('textPath') || !matrix || Math.abs(matrix.b) > .001 || Math.abs(matrix.c) > .001)
throw new Error('Rotated label: ' + label.textContent);
}
};
const activate = element => element.dispatchEvent(new MouseEvent('click', {bubbles:true}));
const toggleLabels = checked => {
const input = document.querySelector('[data-city-labels]');
input.checked = checked;
input.dispatchEvent(new Event('change', {bubbles:true}));
};
try {
await wait(() => document.querySelector('.city-quartier-tile'));
checkLabels('.city-scene-title');
activate(document.querySelector('.city-quartier-tile'));
await wait(() => document.querySelectorAll('.city-generated-street-label').length === 2);
if (document.querySelector('.city-node:hover')) throw new Error('Fixture must begin without hover');
checkLabels('.city-generated-street-label');
// Keyboard focus still highlights a road without hiding its neighbors.
const street = document.querySelector('.city-street-tile');
const restingStroke = getComputedStyle(street.querySelector('.city-generated-street-hit')).stroke;
street.focus();
await wait(() => getComputedStyle(street.querySelector('.city-generated-street-hit')).stroke !== restingStroke);
checkLabels('.city-generated-street-label');
street.blur();
toggleLabels(false);
if ([...document.querySelectorAll('.city-generated-street-label')].some(label => getComputedStyle(label).display !== 'none'))
throw new Error('Labels toggle does not hide Streets');
toggleLabels(true);
checkLabels('.city-generated-street-label');
activate(document.querySelector('.city-street-tile'));
await wait(() => document.querySelector('.city-undefined-page-label'));
checkLabels('.city-generated-street-label,.city-undefined-page-label');
toggleLabels(false);
if (getComputedStyle(document.querySelector('.city-undefined-page-label')).display !== 'none')
throw new Error('Labels toggle does not hide undefined Pages');
toggleLabels(true);
activate(document.querySelector('[data-city-level="quartier"]'));
await wait(() => document.querySelectorAll('.city-generated-street-label').length === 2);
activate(document.querySelectorAll('.city-street-tile')[1]);
await wait(() => document.querySelector('.city-spot-point-label'));
checkLabels('.city-generated-street-label,.city-spot-point-label');
activate(document.querySelector('[data-city-level="quartier"]'));
await wait(() => document.querySelectorAll('.city-generated-street-label').length === 2);
checkLabels('.city-generated-street-label');
document.body.dataset.vimReady = 'true';
} catch (error) {
const box = document.createElement('div');
box.id = 'error'; box.textContent = error.message; document.body.append(box);
}
});
+46
View File
@@ -0,0 +1,46 @@
window.addEventListener('load', async () => {
const assert=(ok,message)=>{if(!ok)throw new Error(message);};
const wait=async check=>{for(let i=0;i<180;i++){if(check())return;await new Promise(r=>setTimeout(r,25));}throw new Error('City link fixture timed out');};
const click=element=>element.dispatchEvent(new MouseEvent('click',{bubbles:true,cancelable:true}));
try {
const start=location.href, historyLength=history.length;
const data=await(await fetch('/_/api/v1/city/map')).json();
const q=data.quartiers.find(q=>q.name==='life'),s=q.streets.find(s=>s.name==='home'),p=s.spots.find(p=>p.name==='alpha');
const params=new URLSearchParams(location.search),level=['spot','street','quartier'].find(k=>params.has(k));
await wait(()=>document.querySelector('[data-city-locality-search]').elements.locality.value===(level||'domain'));
const form=document.querySelector('[data-city-locality-search]');
if(level){
const target={quartier:q,street:s,spot:p}[level];
await wait(()=>document.querySelector('[data-city-inspector]').dataset.cityUuid===target.uuid);
assert(form.elements.locality_id.value==='uuid:'+target.uuid,'Initial locality must be an explicit UUID');
assert(document.querySelector('.city-detail-link').getAttribute('href')===target.detail_href,'Deep link inspector opened wrong node');
}
const jump=(type,id)=>click(document.querySelector(`[data-city-jump="${type}"][data-city-id="${id}"]`));
jump('quartier',q.uuid);
await wait(()=>document.querySelector('.city-street-tile'));
const road=document.querySelector(`.city-street-tile[data-city-uuid="${s.uuid}"]`);
road.dispatchEvent(new MouseEvent('contextmenu',{bubbles:true,cancelable:true,clientX:100,clientY:100}));
assert(document.querySelector('.city-context-menu a').getAttribute('href')==='/v/city/s/life/home','Context menu lost parent qualifier');
jump('street',s.uuid);
assert(document.querySelector('.city-detail-link').getAttribute('href')==='/v/city/s/life/home','Inspector lost parent qualifier');
assert(form.elements.locality_id.value==='uuid:'+s.uuid,'Search selector is not an explicit UUID');
const search=await fetch('/v/search?q=page&'+new URLSearchParams(new FormData(form)));
assert(search.ok,'Locality search failed');
for(const quartier of data.quartiers){
const street=quartier.streets[0];
assert(street.detail_href===`/v/city/s/${quartier.name}/home`,'Repeated Street not parent qualified');
const response=await fetch(street.detail_href),body=await response.text();
assert(response.ok&&body.includes(street.uuid),'Detail resolved a different Street');
}
assert((await fetch('/v/city/s/home')).status===404,'Ambiguous legacy name selected an arbitrary Street');
jump('spot',p.uuid);
await wait(()=>document.querySelector('.city-estate-detail .city-map-page-link'));
for(const a of document.querySelectorAll('.city-map-page-link,[data-city-inspector] li a')){
const href=new URL(a.getAttribute('href'),location.href);
assert(!href.hash&&!href.search,'Literal Page path interpreted as query/fragment');
assert(decodeURIComponent(href.pathname)==='/life/home/alpha/page?#%','Page path bytes were lost');
}
assert(location.href===start&&history.length===historyLength,'Map navigation changed browser history');
document.body.dataset.vimReady='true';
}catch(error){const box=document.createElement('div');box.id='error';box.textContent=error.stack||error.message;document.body.append(box);}
});
+42
View File
@@ -0,0 +1,42 @@
window.addEventListener('load',async()=>{
const wait=async check=>{for(let i=0;i<200;i++){if(check())return;const error=document.querySelector('[data-city-organize-error]')?.textContent;if(error&&!error.includes('保存中'))throw new Error(error);await new Promise(r=>setTimeout(r,25));}throw new Error('City organizer timed out');};
const click=(el,ctrl=false)=>{if(!el)throw new Error('Missing click target');el.dispatchEvent(new MouseEvent('click',{bubbles:true,ctrlKey:ctrl,cancelable:true}));};
const map=async()=>await(await fetch('/_/api/v1/city/map')).json();
const spot=(data,title)=>data.quartiers.flatMap(q=>q.streets.flatMap(s=>s.spots)).find(p=>p.title===title);
const enterStreet=async id=>{click(document.querySelector(`[data-city-type="Street"][data-city-uuid="${id}"]`));await wait(()=>document.querySelector('.city-spot-tile'));};
const submit=()=>document.querySelector('.city-organize-dialog form').requestSubmit();
try{
let data=await map();const home=data.quartiers[0].streets.find(s=>s.name==='home'),work=data.quartiers[0].streets.find(s=>s.name==='work');
await wait(()=>document.querySelector('.city-quartier-tile'));click(document.querySelector('.city-quartier-tile'));
await wait(()=>document.querySelectorAll('.city-generated-street-label').length===2);await enterStreet(home.uuid);
await wait(()=>document.querySelectorAll('.city-undefined-page-link').length===2);
const url=location.href,points=[...document.querySelectorAll('.city-undefined-page-link')];
click(points[0],true);click(points[1],true);
if(document.querySelectorAll('.city-undefined-page-link.city-is-selected').length!==2||location.href!==url)throw new Error('Ctrl selection navigated or failed');
click(points[0],true);if(document.querySelectorAll('.city-undefined-page-link.city-is-selected').length!==1)throw new Error('Ctrl toggle failed');click(points[0],true);
click(document.querySelector('.city-selection-bar [data-city-create-selection]'));
const form=document.querySelector('.city-organize-dialog form');form.elements.title.value='まとめたSpot';form.elements.name.value='bundle';form.elements.name.dispatchEvent(new Event('input'));submit();
await wait(()=>!document.querySelector('.city-organize-dialog'));
data=await map();const bundle=spot(data,'まとめたSpot');if(!bundle||bundle.pages.length!==2||!bundle.pages.every(p=>p.path.startsWith('/life/home/')))throw new Error('Grouping changed URLs or lost Pages');
await wait(()=>document.querySelector(`[data-city-uuid="${bundle.uuid}"]`));
// Right-click title edit, preserving identifier and Page URLs.
document.querySelector(`[data-city-uuid="${bundle.uuid}"]`).dispatchEvent(new MouseEvent('contextmenu',{bubbles:true,cancelable:true}));
click(document.querySelector('.city-context-menu [data-city-rename]'));
document.querySelector('.city-organize-dialog input[name="title"]').value='新しい表示名';submit();await wait(()=>!document.querySelector('.city-organize-dialog'));
data=await map();if(spot(data,'新しい表示名')?.uuid!==bundle.uuid||spot(data,'新しい表示名')?.name!=='bundle')throw new Error('Rename changed identity');
// Whole-Spot merge, using the floating toolbar rather than portal clicks.
for(const title of ['alpha','beta']){const p=spot(data,title);await wait(()=>document.querySelector(`[data-city-uuid="${p.uuid}"]`));click(document.querySelector(`[data-city-uuid="${p.uuid}"]`),true);}
click(document.querySelector('.city-selection-bar [data-city-merge]'));
document.querySelector('.city-organize-dialog select[name="target"]').value=bundle.uuid;submit();await wait(()=>!document.querySelector('.city-organize-dialog'));
data=await map();if(spot(data,'新しい表示名').pages.length!==4||spot(data,'alpha')||spot(data,'beta'))throw new Error('Whole Spot merge failed');
await wait(()=>document.querySelector(`[data-city-uuid="${bundle.uuid}"]`));click(document.querySelector(`[data-city-uuid="${bundle.uuid}"]`),true);
click(document.querySelector('.city-selection-bar [data-city-move-selection]'));
const move=document.querySelector('.city-organize-dialog form');move.elements.street.value=work.uuid;move.elements.street.dispatchEvent(new Event('change'));submit();await wait(()=>!document.querySelector('.city-organize-dialog'));
data=await map();const moved=data.quartiers[0].streets.find(s=>s.uuid===work.uuid).spots.find(p=>p.uuid===bundle.uuid);
if(!moved||moved.path_prefix!=='/life/work/bundle'||moved.pages.length!==4||!moved.pages.every(p=>p.path.startsWith('/life/home/')))throw new Error('Move lost identity or moved URLs');
const paths=await(await fetch('/_/api/v1/city/autoplan')).json();
if(paths.items.some(p=>p.path.startsWith('/life/home/')))throw new Error('Autoplan will undo manual organization');
click(document.querySelector('[data-city-level="quartier"]'));await wait(()=>document.querySelectorAll('.city-generated-street-label').length===2);await enterStreet(work.uuid);
document.body.dataset.vimReady='true';
}catch(error){const el=document.createElement('div');el.id='error';el.textContent=error.stack||error.message;document.body.append(el);}
});
+63
View File
@@ -0,0 +1,63 @@
window.addEventListener('load', async () => {
const assert=(condition,message)=>{if(!condition)throw new Error(message);};
const wait=async condition=>{for(let i=0;i<240;i++){if(condition())return;await new Promise(r=>setTimeout(r,25));}throw new Error('City worker fixture timed out');};
const rejectName=async(promise,name)=>{let rejected=false;try{await promise;}catch(error){rejected=true;if(name)assert(error.name===name,`Expected ${name}, got ${error.name}`);}assert(rejected,'Operation unexpectedly resolved');};
const fabric={generator:'test',version:'test',width:180,height:100,roads:[[10,10,20,20]],buildings:[[[1,1],[1,2],[2,2]]]};
const WorkerClient=window.PagesWikiCityFabricClient;
class FakeWorker {
constructor(){this.terminated=false;this.message=null;}
postMessage(message){this.message=message;}
terminate(){this.terminated=true;}
result(value=fabric){this.onmessage({data:{id:this.message.id,fabric:value}});}
}
class MemoryStorage {
constructor(){this.values=new Map();}
get length(){return this.values.size;}
key(index){return [...this.values.keys()][index];}
getItem(key){return this.values.get(key)||null;}
setItem(key,value){this.values.set(key,String(value));}
removeItem(key){this.values.delete(key);}
}
try{
await wait(()=>document.querySelector('.city-quartier-tile'));
assert(window.PagesWikiGenCity instanceof WorkerClient,'Main thread loaded the synchronous generator');
assert(!document.querySelector('script[src*="gen-city.bundle"]'),'Generator bundle executes in the page');
const real=new WorkerClient({storage:null});
const first=await real.generateFabric('deterministic-domain',240,160);
assert(first.generator==='gen-city'&&first.roads.length>0&&first.buildings.length>0,'Real Worker generated no city');
const second=await new WorkerClient({storage:null}).generateFabric('deterministic-domain',240,160);
assert(JSON.stringify(first)===JSON.stringify(second),'Domain seed is nondeterministic');
// Force expensive synchronous work inside an actual Worker and ensure that
// main-thread timers continue to run throughout it.
const blob=URL.createObjectURL(new Blob([`onmessage=e=>{const until=performance.now()+180;while(performance.now()<until){};postMessage({id:e.data.id,fabric:${JSON.stringify(fabric)}});};`],{type:'text/javascript'}));
let ticks=0;const timer=setInterval(()=>ticks++,10);
try{await new WorkerClient({storage:null,workerFactory:()=>new Worker(blob)}).generateFabric('busy');}finally{clearInterval(timer);URL.revokeObjectURL(blob);}
assert(ticks>=5,'Worker computation starved main-thread timers');
const workers=[], storage=new MemoryStorage();
const client=new WorkerClient({storage,workerFactory:()=>{const w=new FakeWorker();workers.push(w);return w;}});
const a=client.generateFabric('a');const aRejected=rejectName(a,'AbortError');
const b=client.generateFabric('b');await aRejected;
assert(workers[0].terminated,'Superseded Worker stayed alive');
workers[0].result();assert(client.pending?.key.includes('"b"'),'Stale Worker replaced the active job');
workers[1].result();await b;assert(workers[1].terminated&&!client.pending,'Completed Worker was not released');
const count=workers.length;await client.generateFabric('b');assert(workers.length===count,'Memory cache regenerated a stable Domain');
const warm=new WorkerClient({storage,workerFactory:()=>{throw new Error('Cache miss');}});
await warm.generateFabric('b');
const abort=new AbortController(), pending=client.generateFabric('cancel',180,100,{signal:abort.signal});
const cancelled=rejectName(pending,'AbortError');abort.abort();await cancelled;assert(workers.at(-1).terminated,'Abort did not terminate Worker');
const timed=new FakeWorker();await rejectName(new WorkerClient({storage:null,timeout:30,workerFactory:()=>timed}).generateFabric('timeout'));
assert(timed.terminated,'Timed-out Worker stayed alive');
await rejectName(new WorkerClient({storage:null,workerFactory:()=>{throw new Error('Blocked');}}).generateFabric('unsupported'));
const invalid=client.generateFabric('invalid');const invalidRejected=rejectName(invalid);workers.at(-1).result({...fabric,roads:[[Infinity,0,0,0]]});await invalidRejected;
await rejectName(client.generateFabric('too-large',100000,100),'RangeError');
for(const name of ['c','d','e','f']){const task=client.generateFabric(name);workers.at(-1).result();await task;}
assert(client.memory.size<=3&&storage.length<=3,'Geometry cache grew without a bound');
const global=window.PagesWikiGenCity, factory=global.workerFactory, lifecycle=new FakeWorker();global.workerFactory=()=>lifecycle;
const task=global.generateFabric('lifecycle-cancelled'), stopped=rejectName(task,'AbortError');
window.dispatchEvent(new PageTransitionEvent('pagehide',{persisted:true}));await stopped;
assert(lifecycle.terminated&&!global.pending,'Page suspension retained CPU work');
global.workerFactory=factory;const previous=document.querySelector('.city-quartier-tile');window.dispatchEvent(new PageTransitionEvent('pageshow',{persisted:true}));
await wait(()=>document.querySelector('.city-quartier-tile')&&document.querySelector('.city-quartier-tile')!==previous);
document.body.dataset.vimReady='true';
}catch(error){const box=document.createElement('div');box.id='error';box.textContent=error.stack||error.message;document.body.append(box);}
});
+26
View File
@@ -0,0 +1,26 @@
window.addEventListener('load', async () => {
const wait=async check=>{for(let i=0;i<150;i++){if(check())return;await new Promise(resolve=>setTimeout(resolve,30));}throw new Error('Table did not load');};
try {
for(const name of ['campuses','domains','nav-home','nav-system','auth','auth-sessions','events','assets','adapters','extensions']){
showConfigPanel(name);
const panel=document.getElementById('panel-'+name);
await wait(()=>!panel.querySelector('.recent-table tbody')?.textContent.includes(configMessages.loading));
for(const table of panel.querySelectorAll('.recent-table')){
if(!table.closest('.table-scroll'))throw new Error(name+': missing scroll container');
for(const row of table.querySelectorAll('tbody tr')){
if(row.getBoundingClientRect().height>42)throw new Error(name+': tall row '+row.getBoundingClientRect().height+' '+row.textContent.slice(0,60));
for(const cell of row.cells)if(getComputedStyle(cell).whiteSpace!=='nowrap')throw new Error(name+': wrapping cell');
for(const form of row.querySelectorAll('form'))if(parseFloat(getComputedStyle(form).marginBottom)!==0)throw new Error(name+': form adds row margin');
}
}
if(['campuses','domains'].includes(name))for(const input of panel.querySelectorAll('input[form]'))if(!input.form)throw new Error('Detached form association');
}
showConfigPanel('assets');
await wait(()=>document.querySelector('#asset-list .cell-clip[title$=".txt"]'));
const asset=document.querySelector('#asset-list .cell-clip[title$=".txt"]');
if(!asset || asset.scrollWidth<=asset.clientWidth || asset.title!==asset.textContent)throw new Error('Long asset name not available through tooltip');
if(!document.querySelector('#event-definitions .cell-clip[title]')?.title.includes('"'))throw new Error('Quoted title lost');
showConfigPanel(new URLSearchParams(location.search).get('capture') || 'auth');
document.body.dataset.vimReady='true';
}catch(error){const box=document.createElement('div');box.id='error';box.textContent=error.message;document.body.append(box);}
});
+29
View File
@@ -0,0 +1,29 @@
addEventListener('load',()=>{
try {
const button=document.querySelector('[data-domain-entry-open]');button.click();
const dialog=document.getElementById(button.dataset.domainEntryOpen);
if(!dialog.open||dialog.closest('table,.config-panel'))throw new Error('dialog not isolated');
const bounds=dialog.getBoundingClientRect();
if(bounds.width<200||bounds.left<0||bounds.right>innerWidth+1||bounds.top<0||bounds.bottom>innerHeight+1)throw new Error('dialog viewport bounds');
if(dialog.scrollWidth>dialog.clientWidth+1)throw new Error('horizontal overflow');
for(const form of dialog.querySelectorAll('form')){
if(getComputedStyle(form).display!=='block')throw new Error('table form CSS leaked');
}
for(const p of dialog.querySelectorAll('p'))if(getComputedStyle(p).display!=='block')throw new Error('inline help text');
const controls=[...dialog.querySelectorAll('input:not([type=hidden]),select')];
for(let i=0;i<controls.length;i++){
const r=controls[i].getBoundingClientRect();
if(r.width<24||r.left<bounds.left||r.right>bounds.right+1)throw new Error('control overflow');
for(let j=i+1;j<controls.length;j++){
const b=controls[j].getBoundingClientRect();
if(Math.min(r.right,b.right)>Math.max(r.left,b.left)+1&&Math.min(r.bottom,b.bottom)>Math.max(r.top,b.top)+1)throw new Error('overlapping inputs');
}
}
dialog.scrollTop=dialog.scrollHeight;
const close=dialog.querySelector('[data-domain-entry-close]'),c=close.getBoundingClientRect();
if(c.top<bounds.top||c.bottom>bounds.bottom)throw new Error('close button not sticky');
close.click();if(dialog.open)throw new Error('close failed');
button.click();dialog.scrollTop=0;
document.body.dataset.vimReady='true';
}catch(error){const p=document.createElement('p');p.id='error';p.textContent=error.message;document.body.append(p);}
});
+42
View File
@@ -0,0 +1,42 @@
(async()=>{
const assert=(ok,message)=>{if(!ok)throw new Error(message)};
const wait=async check=>{for(let i=0;i<150;i++){if(check())return;await new Promise(r=>setTimeout(r,25))}throw new Error('Projection did not initialize')};
try{
const state=await(await fetch('/fixture-state')).json();
for(const route of state.routes){
const frame=document.createElement('iframe');frame.width=1000;frame.height=600;document.body.append(frame);
await new Promise((resolve,reject)=>{frame.onload=resolve;frame.onerror=reject;frame.src=route});
const w=frame.contentWindow,d=frame.contentDocument;
assert(d.body&&!d.body.textContent.startsWith('forbidden'),route+' denied fixture');
if(route.startsWith('/e/')){
await wait(()=>d.querySelector('#preview h1'));
assert(w.PagesWikiCodeMirror,'CodeMirror failed under CSP');
assert(d.querySelector('#preview strong')?.textContent==='Formatting','Editor formatting missing');
if(route.includes('edittype=html')){
assert(d.querySelector('#editor').value===state.body,'HTML authoring source changed');
assert(await w.PagesEditor.getCanonicalHTML()===state.body,'Saving would write sanitized content');
}
const button=d.querySelector('[data-editor-action=preview]');
button.click();assert(d.querySelector('#preview').hidden,'Preview toggle stopped working under CSP');
button.click();assert(!d.querySelector('#preview').hidden,'Preview toggle did not restore');
let saves=0;w.PagesEditor.saveNow=()=>saves++;d.querySelector('[data-editor-action=save]').click();assert(saves===1,'Save button blocked by CSP');
const expected=d.querySelector('#preview').innerHTML;
// Force an API failure. The only fallback is text, never innerHTML.
const originalFetch=w.fetch;w.fetch=async()=>{throw new Error('fixture unavailable')};
await w.PagesEditor.renderPreview();assert(!d.querySelector('#preview script,#preview iframe'),'Unsafe failure fallback');w.fetch=originalFetch;
await w.PagesEditor.renderPreview();assert(d.querySelector('#preview h1'),'Preview did not recover');
assert(expected.includes('Formatting'),'No safe result before failure');
}
await new Promise(r=>setTimeout(r,80));
assert(!d.documentElement.dataset.attack,route+' executed authored code');
assert(!d.querySelector('.page-html script,.page-html iframe,.page-html form,#preview script,#preview iframe'),route+' kept active author nodes');
const source=d.querySelector('.page-html,#preview,.preview-content');assert(source?.textContent.includes('Readable heading'),route+' lost safe content');
assert(!d.querySelector('[data-children-src="/sentinel"]'),route+' accepted forged UI hooks');
for(const a of source.querySelectorAll('a')){if(a.textContent==='bad URL')a.click()}
assert(!d.documentElement.dataset.cspAttack,route+' CSP did not block parser-inserted probes');
frame.remove();
}
assert((await(await fetch('/fixture-state')).json()).hits===0,'Reader-authorized side effect');
document.body.dataset.vimReady='true';
}catch(error){const box=document.createElement('div');box.id='error';box.textContent=error.stack||error.message;document.body.append(box)}
})();
+75
View File
@@ -0,0 +1,75 @@
window.addEventListener('load', async () => {
const wait = async check => { for(let i=0;i<200;i++){if(check())return;await new Promise(resolve=>setTimeout(resolve,30));}throw new Error('Timed out waiting for monitor UI'); };
try {
await wait(() => document.querySelector('#scheduler-jobs [data-job-row]'));
if (document.querySelectorAll('#scheduler-jobs [data-job-row]').length !== 1 || !document.querySelector('#scheduler-jobs [data-job-row="monitor-000"]')) throw new Error('Non-running jobs in monitor');
const dialog = document.getElementById('monitor-settings-dialog');
const open = document.getElementById('monitor-settings-open');
const restored = new URLSearchParams(location.search).has('monitor_dialog');
const period = document.getElementById('resource-history-hours');
if(period.value !== (restored ? '24' : '1'))throw new Error('History period default/restore failed');
if(document.getElementById('resource-stat-interval').value !== '1' || document.getElementById('resource-graph-interval').value !== '5')throw new Error('Unexpected polling defaults');
if(restored && document.getElementById('resource-live').checked)throw new Error('Auto refresh status not restored');
if(document.querySelector('[data-chart-range], #resource-sample-window, .monitor-header [data-config-panel="logs"]'))throw new Error('Old chart labels or history link remain');
if(!document.querySelector('#monitor-refresh svg') || !document.querySelector('.monitor-header #resource-time-range'))throw new Error('Missing reload icon or shared time range');
if (!restored) {
const fetchBefore=window.fetch;let updates=0;
window.fetch=(...args)=>{if(String(args[0])==='/_/api/v1/queue/resources')updates++;return fetchBefore(...args);};
const range=document.getElementById('resource-time-range').textContent;
await wait(()=>updates>=2);
await wait(()=>document.getElementById('resource-time-range').textContent!==range);
if(!document.querySelector('[data-resource-chart="io"] .io-read') || !document.querySelector('[data-resource-chart="io"] .io-write'))throw new Error('I/O series missing');
for(const line of document.querySelectorAll('.resource-charts polyline'))if(line.getAttribute('points').split(' ').length>361)throw new Error('Unbounded chart points');
}
if (dialog.open || dialog.getBoundingClientRect().height) throw new Error('Monitor settings initially visible');
for (const id of ['resource-monitor-form','resource-history-hours','resource-live']) {
if (!dialog.contains(document.getElementById(id))) throw new Error('Settings outside dialog: ' + id);
}
open.click();
if (!dialog.open || !dialog.matches(':modal')) throw new Error('Monitor settings did not open modally');
period.value='24';period.dispatchEvent(new Event('change',{bubbles:true}));
const form = document.getElementById('resource-monitor-form');
form.elements.interval.value = '120'; form.dispatchEvent(new Event('input',{bubbles:true}));
form.requestSubmit();
await wait(() => document.getElementById('resource-monitor-result').textContent === '✓');
const live=document.getElementById('resource-live');live.checked=false;live.dispatchEvent(new Event('change',{bubbles:true}));
document.getElementById('monitor-settings-close').click();
await wait(() => !dialog.open && document.activeElement === open);
const panel = document.getElementById('panel-scheduler');
const figures = [...panel.querySelectorAll('.resource-charts figure')];
const checkRow = () => {
const rects=figures.map(figure=>figure.getBoundingClientRect());
if(rects.length!==4 || rects.some(rect=>Math.abs(rect.top-rects[0].top)>1))throw new Error('Resource charts are not one row of four');
};
checkRow(); panel.style.width='360px'; checkRow();
const scroll = panel.querySelector('.resource-chart-scroll');
if(scroll.scrollWidth<=scroll.clientWidth)throw new Error('Narrow charts not horizontally scrollable');
panel.style.removeProperty('width');
open.click();
showConfigPanel('logs');
if(dialog.open)throw new Error('Settings dialog left open after navigation');
await wait(() => document.querySelector('#job-history [data-job-row="monitor-064"]'));
if (document.querySelectorAll('#job-history [data-job-row]').length !== 50) throw new Error('Unbounded history');
document.querySelector('[data-job-logs="monitor-064"]').click();
await wait(() => document.querySelector('.job-log-detail pre')?.textContent.includes('entry-104 <unsafe>'));
if (document.querySelector('.job-log-detail unsafe')) throw new Error('Unescaped log content');
document.querySelector('[data-older-logs]').click();
await wait(() => document.querySelector('.job-log-detail pre').textContent.includes('entry-000'));
if(document.querySelector('.job-log-detail pre').textContent.includes('entry-104'))throw new Error('Log page accumulated');
document.getElementById('job-history-more').click();
await wait(() => document.querySelectorAll('#job-history [data-job-row]').length === 13);
showConfigPanel('resources');
await wait(() => activeConfigPanel === 'scheduler');
const cancel = document.querySelector('#scheduler-jobs [data-queue-action="cancel"]');cancel.click();
await wait(() => document.querySelector('#scheduler-jobs').textContent.includes(configMessages.cancelRequested));
const realFetch = window.fetch; let requests=0;
window.fetch=(...args)=>{requests++;return realFetch(...args);};
showConfigPanel('home');
await new Promise(resolve=>setTimeout(resolve,5200));
if(requests)throw new Error('Monitor polled after leaving panel');
showConfigPanel('scheduler');
await wait(() => document.querySelector('[data-resource-chart="cpu"] .chart-line'));
if(new URLSearchParams(location.search).has('monitor_dialog'))open.click();
document.body.dataset.vimReady='true';
} catch(error) {const box=document.createElement('div');box.id='error';box.textContent=error.message;document.body.append(box);}
});
+85
View File
@@ -0,0 +1,85 @@
window.addEventListener('load',async()=>{
const wait=async(test,label)=>{for(let i=0;i<180;i++){if(test())return;await new Promise(r=>setTimeout(r,30));}throw new Error(label);};
try{
const entryButton=document.querySelector('[data-domain-entry-open]');entryButton.click();
const entryDialog=document.getElementById(entryButton.dataset.domainEntryOpen);
if(!entryDialog.open)throw new Error('domain entry dialog');
const entryLayout=entryDialog.querySelector('[name=entry_layout]');entryLayout.value='diary';entryLayout.dispatchEvent(new Event('change'));
if(!entryLayout.form.elements.diary_enabled.checked)throw new Error('entry enables selected plugin');
entryDialog.querySelector('[data-domain-entry-close]').click();
const panel=document.querySelector('[data-periodical-settings="diary"]'),settings=panel.querySelector('form');
await wait(()=>!settings.querySelector('fieldset').disabled,'settings load');
settings.elements.enabled.checked=true;settings.elements.prefix.value='/journal';settings.requestSubmit();
await wait(()=>!settings.querySelector('fieldset').disabled&&settings.querySelector('[role=status]').textContent,'enable');
const frame=document.createElement('iframe');frame.style.width='100%';frame.style.height='800px';document.body.append(frame);
await new Promise(resolve=>{frame.onload=resolve;frame.src='/v/diary?month=2026-09';});
const doc=()=>frame.contentDocument;
await wait(()=>doc().querySelector('[data-periodical-add]'),'diary enabled');
if(frame.contentWindow.location.pathname!=='/v/diary/2026/09'||frame.contentWindow.location.search)throw new Error('legacy month redirect');
const filters=doc().querySelector('[data-periodical-filters]');filters.elements.own.checked=true;filters.requestSubmit();
await wait(()=>doc().readyState==='complete'&&frame.contentWindow.location.search==='?own','own flag navigation');
const dayLink=[...doc().querySelectorAll('.periodical-days a')].find(a=>a.getAttribute('href')==='/v/diary/2026/09/18?own');
if(!dayLink)throw new Error('canonical day URL');dayLink.click();
await wait(()=>doc().readyState==='complete'&&frame.contentWindow.location.pathname==='/v/diary/2026/09/18','day navigation');
await new Promise(resolve=>{frame.onload=resolve;frame.src='/v/diary/2026/09';});
doc().querySelector('[data-periodical-new]').click();
const planner=doc().querySelector('[data-periodical-planner]'),plan=planner.querySelector('form');
if(!planner.open)throw new Error('planner dialog');
plan.elements.date.value='2026-09-17';plan.elements.keyword.value='walk';plan.requestSubmit();
await wait(()=>!plan.querySelector('[data-planner-result]').hidden,'plan article URL');
if(plan.querySelector('[data-planner-editor]').getAttribute('href')!=='/e/journal/2026/09/17/walk')throw new Error('planned editor URL');
plan.querySelector('[data-planner-register]').click();
if(doc().querySelector('[data-periodical-entry-form]').elements.path.value!=='/journal/2026/09/17/walk')throw new Error('registration path');
doc().querySelector('[data-periodical-close]').click();
async function submit(form){const old=doc();form.requestSubmit();await wait(()=>doc()!==old&&doc().readyState==='complete','entry save');}
doc().querySelector('[data-periodical-add]').click();
let form=doc().querySelector('[data-periodical-entry-form]');
if(!doc().querySelector('[data-periodical-dialog]').open)throw new Error('register dialog');
form.elements.path.value='/journal/browser';form.elements.title.value='Calendar entry';form.elements.date.value='2026-09-16';form.elements.category.value='Work';
await submit(form);
if(!doc().querySelector('.periodical-entries a[href="/journal/browser"]')||!doc().querySelector('.periodical-days .has-entries'))throw new Error('entry/calendar');
doc().querySelector('[data-periodical-edit]').click();form=doc().querySelector('[data-periodical-entry-form]');
if(!form.elements.path.readOnly||form.elements.version.value!=='1')throw new Error('metadata identity');
form.elements.title.value='Edited diary entry';await submit(form);
if(!doc().querySelector('.periodical-entries h2').textContent.includes('Edited diary entry'))throw new Error('metadata edit');
frame.contentWindow.confirm=()=>true;const old=doc();doc().querySelector('[data-periodical-remove]').click();
await wait(()=>doc()!==old&&doc().readyState==='complete','unregister');
if(doc().querySelector('[data-periodical-entry]'))throw new Error('unregister failed');
doc().querySelector('[data-periodical-compose]').click();
const compose=doc().querySelector('[data-periodical-composer]'),postForm=compose.querySelector('form');
if(!compose.open)throw new Error('composer dialog');
postForm.elements.title.value='Atomic diary';postForm.elements.date.value='2026-09-18';postForm.elements.keyword.value='posted';postForm.elements.body.value='# One step\n\nA **new** entry.';
const beforePost=doc();postForm.requestSubmit();
await wait(()=>doc().querySelector('[data-periodical-posted]'),'post sharing actions');
if(!doc().querySelector('[data-share-x]')||!new URL(doc().querySelector('[data-share-x]').href).searchParams.get('url').endsWith('/journal/2026/09/18/posted'))throw new Error('post share URL');
doc().querySelector('[data-post-continue]').click();
await wait(()=>doc()!==beforePost&&doc().readyState==='complete'&&doc().querySelector('[data-periodical-entry]'),'atomic post');
if(frame.contentWindow.location.pathname!=='/v/diary/2026/09/18'||!doc().querySelector('a[href="/journal/2026/09/18/posted"]'))throw new Error('posted article path');
const response=await fetch('/_/api/v1/extension/content.blog/settings',{method:'POST',headers:{'Content-Type':'application/json'},body:'{"enabled":true}'});if(!response.ok)throw new Error('blog enable');
const post=await fetch('/_/api/v1/extension/content.blog/entries',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({path:'/journal/browser',title:'A first blog article',date:'2026-09-16',category:'Work',version:0})});if(!post.ok)throw new Error('blog register');
await new Promise(resolve=>{frame.onload=resolve;frame.src='/v/blog?category=Work&month=2026-09';});
await wait(()=>doc().querySelector('[data-periodical-entry]'),'blog category');
if(frame.contentWindow.location.pathname!=='/v/blog/2026/09'||frame.contentWindow.location.search!=='?category=Work')throw new Error('blog canonical URL');
if(!doc().querySelector('.periodical-entries h2').textContent.includes('A first blog article'))throw new Error('blog article');
const calendarPanel=doc().querySelector('.periodical-calendar-panel');
if(!calendarPanel.querySelector('[data-periodical-filters]')||calendarPanel.querySelector('[data-periodical-filters]').getBoundingClientRect().bottom>calendarPanel.querySelector('.periodical-calendar').getBoundingClientRect().top+1)throw new Error('month selector above calendar');
const compactRow=doc().querySelector('.periodical-index tbody tr');
if(!compactRow||compactRow.getBoundingClientRect().height>55)throw new Error('compact date/title row');
const monthControls=doc().querySelector('.periodical-month-controls');
if(!monthControls||monthControls.getBoundingClientRect().height>36)throw new Error('single-line month controls');
for(const control of monthControls.querySelectorAll('input,button,a'))if(!control.getAttribute('aria-label'))throw new Error('month control accessible label');
if(doc().documentElement.scrollWidth>frame.clientWidth+5)throw new Error('responsive overflow');
await new Promise(resolve=>{frame.onload=resolve;frame.src='/v/blog/-/new';});
const newForm=doc().querySelector('.periodical-compose-page form');
if(!newForm)throw new Error('standalone new article page');
if(doc().documentElement.scrollWidth>frame.clientWidth+5)throw new Error('new article responsive overflow');
newForm.elements.title.value='Standalone article';newForm.elements.date.value='2026-09-19';newForm.elements.keyword.value='new-page';newForm.elements.body.value='# Standalone\n\nNew page body.';
const beforeNew=doc();newForm.requestSubmit();
await wait(()=>doc().querySelector('[data-periodical-posted]'),'standalone sharing actions');
if(!doc().querySelector('[data-share-x]')||!doc().querySelector('[data-periodical-posted]').textContent.includes('承認'))throw new Error('publication warning/share');
doc().querySelector('[data-post-continue]').click();
await wait(()=>doc()!==beforeNew&&doc().readyState==='complete'&&doc().querySelector('a[href="/blog/2026/09/19/new-page"]'),'standalone article submit');
[...document.body.children].forEach(element=>{if(element!==frame)element.style.display='none';});document.body.style.margin='0';document.body.style.padding='0';frame.style.border='0';frame.style.height='100vh';
document.body.dataset.vimReady='true';
}catch(error){const box=document.createElement('div');box.id='error';box.textContent=error.message;document.body.append(box);}
});
+58
View File
@@ -0,0 +1,58 @@
(() => {
let sawPending = false
const originalFetch = window.fetch
window.fetch = async (...args) => {
const response = await originalFetch(...args)
if (String(args[0]).includes("metadata=1") && response.status === 202) sawPending = true
return response
}
const wait = async predicate => {
for (let i = 0; i < 600; i++) {
if (predicate()) return
await new Promise(resolve => setTimeout(resolve, 25))
}
throw Error("metadata UI timed out")
}
const assert = (condition, message) => { if (!condition) throw Error(message) }
window.addEventListener("load", async () => {
try {
const mode = new URLSearchParams(location.search).get("fixture")
if (mode === "failed") {
await wait(() => [...document.querySelectorAll("[data-projection-retry]")].some(button => !button.hidden))
assert(document.querySelector("[data-projection-status]").textContent.trim(), "failed metadata became an empty final state")
} else if (mode === "pdf") {
const viewer = document.querySelector("[data-pdf-viewer]")
await wait(() => viewer.dataset.pages === "3")
const next = document.querySelector("[data-pdf-next]")
next.click(); next.click(); next.click()
assert(document.querySelector("[data-pdf-status]").textContent === "3 / 3", "PDF count did not update navigation bounds")
assert(viewer.querySelector("img").src.includes("page=3"), "PDF did not retain the requested page")
} else {
const viewer = document.querySelector("[data-archive-metadata]")
await wait(() => viewer.dataset.metadataStatus === "ready")
if (mode === "comic") {
const comic = viewer.querySelector("[data-comic-viewer]")
const pages = [...comic.querySelectorAll("[data-comic-page]")]
assert(pages.length === 3 && pages.filter(page => !page.hidden).length === 1, "pending comic images did not initialize safely")
const before = history.length
comic.querySelector("[data-comic-next]").click()
comic.querySelector("[data-comic-layout]").click()
assert(pages.filter(page => !page.hidden).length === 2, "async comic spread is broken")
assert(history.length === before, "comic navigation polluted browser history")
} else {
const rows = [...viewer.querySelectorAll("[data-archive-entries] tr")]
assert(rows.length === 3, "asynchronous archive table is incomplete")
assert(rows[2].textContent.includes("<img onerror=alert(1)>.png"), "archive filename was not shown as text")
assert(!rows[2].querySelector("img"), "archive filename was interpreted as markup")
assert(rows.every(row => new URL(row.querySelector("a").href).searchParams.has("rev")), "archive links lost immutable revision binding")
}
}
assert(sawPending, "browser did not exercise the asynchronous pending transition")
document.body.dataset.vimReady = "true"
} catch (error) {
const message = document.createElement("pre")
message.id = "error"; message.textContent = error.stack || String(error)
document.body.append(message)
}
})
})()
+23
View File
@@ -0,0 +1,23 @@
(async () => {
try {
await new Promise(resolve => setTimeout(resolve, 100));
const check = (ok, message) => { if (!ok) throw new Error(message); };
check(document.querySelector('.periodical-site-title').textContent === 'Public Blog', 'Domain branding');
check(document.querySelector('.periodical-full-article h1').textContent === 'Public registered title & notes', 'Registered title');
check(document.querySelector('.periodical-body').textContent.includes('Article body'), 'Body rendering');
check(document.querySelector('a[rel=next]').getAttribute('href') === '/2026/09/18/keyword', 'Next article');
check(document.querySelector('a[rel=prev]').getAttribute('href') === '/2026/09/16', 'Previous article');
check(document.querySelector('.periodical-calendar').getBoundingClientRect().width > 100, 'Calendar visibility');
const monthControls = document.querySelector('.periodical-month-controls');
check(monthControls && monthControls.getBoundingClientRect().height <= 36, 'Single-line month controls');
check(monthControls.getBoundingClientRect().bottom <= document.querySelector('.periodical-calendar').getBoundingClientRect().top, 'Month controls above calendar');
check(document.documentElement.scrollWidth <= innerWidth + 2, 'Horizontal overflow');
check(!document.querySelector('.periodical-body script'), 'Inert content');
const feed = await fetch('/rss.xml', {cache: 'no-store'});
const xml = new DOMParser().parseFromString(await feed.text(), 'application/xml');
check(feed.ok && !xml.querySelector('parsererror') && xml.querySelectorAll('item').length === 3, 'RSS');
document.body.dataset.vimReady = 'true';
} catch (error) {
const element = document.createElement('pre'); element.id = 'error'; element.textContent = error.stack; document.body.append(element);
}
})();
+67
View File
@@ -0,0 +1,67 @@
window.addEventListener('load', async () => {
try {
const assert = (condition, message) => { if (!condition) throw new Error(message); };
const results = document.querySelector('[data-search-view]');
assert(results, 'Search results missing');
const form = document.querySelector('#search-form');
assert(form, 'Shared search form missing');
const initial = new FormData(form);
assert(initial.get('q')?.includes('nebula'), 'Search query not preserved');
for (const name of ['q', 'scope', 'file_type', 'ext', 'date_field', 'from', 'to']) {
assert(initial.getAll(name).length === 1, 'Search parameter missing or duplicated: ' + name);
}
const options = document.querySelector('.search-options');
assert(options?.querySelector('summary'), 'Accessible search options disclosure missing');
const saved = {};
for (const [name, value] of Object.entries({file_type:'pdf', ext:'pdf', date_field:'created', from:'2026-01-01', to:'2026-01-31'})) {
const control = form.elements.namedItem(name);
assert(control?.form === form, 'Filter does not belong to the search form: ' + name);
saved[name] = control.value;
control.value = value;
}
const filtered = new FormData(form);
assert(filtered.get('file_type') === 'pdf' && filtered.get('ext') === 'pdf', 'File filter was not submitted');
assert(filtered.get('date_field') === 'created' && filtered.get('from') === '2026-01-01' && filtered.get('to') === '2026-01-31', 'Date filter was not submitted');
assert(filtered.get('q') === initial.get('q') && filtered.get('scope') === initial.get('scope'), 'Filters lost the query or folder scope');
for (const [name, value] of Object.entries(saved)) form.elements.namedItem(name).value = value;
const city = document.querySelector('[data-city-search-results]');
if (city) {
assert(city.compareDocumentPosition(results) & Node.DOCUMENT_POSITION_FOLLOWING, 'City results must precede pages');
assert(!city.querySelector('.children-entry,[data-child-path]'), 'City result is exposed to file operations');
assert(city.querySelector('[data-city-search-kind] .search-result-name mark'), 'City name highlight missing');
assert(city.querySelector('.search-result-path')?.getAttribute('href')?.startsWith('/'), 'City boundary Path link missing');
assert(city.querySelector('.search-result-name')?.getAttribute('href')?.startsWith('/v/city/'), 'City details link missing');
assert(!city.querySelector('script,[onload],[onerror]'), 'City source HTML became executable markup');
}
for (const mode of ['list', 'detail', 'icon']) {
const button = document.querySelector(`[data-children-view="${mode}"]`);
button.click();
assert(results.dataset.searchView === mode, 'View switch failed: ' + mode);
const panel = results.querySelector('.search-view-' + mode);
assert(getComputedStyle(panel).display !== 'none', 'Selected mode is hidden: ' + mode);
assert(panel.querySelector('.search-result-name')?.textContent.includes('nebula'), 'Page name missing');
assert(panel.querySelector('.search-result-path')?.textContent.includes('/docs/nebula guide?#%'), 'Full Path missing');
assert(panel.querySelector('.search-result-excerpt mark')?.textContent === 'NEBULA', 'Context highlight missing');
assert(panel.querySelector('[data-match-source="body"]'), 'Match source missing');
assert(panel.querySelector('.search-result-name').closest('a').getAttribute('href').includes('%3F%23%25'), 'Path URL was not encoded');
if (city) assert(getComputedStyle(city).display !== 'none', 'View switching hid City results: ' + mode);
}
assert(!results.querySelector('script,[onload],[onerror]'), 'Source HTML became executable markup');
assert(!results.textContent.includes('SECRET_EXCERPT'), 'Unreadable snippet leaked');
document.querySelector('[data-children-view="list"]').click();
const row = results.querySelector('.search-view-list .children-entry');
row.dispatchEvent(new MouseEvent('click', {bubbles:true, cancelable:true, ctrlKey:true}));
assert(row.classList.contains('children-selected'), 'Ctrl selection stopped working');
if (city) {
const cityRow = city.querySelector('[data-city-search-kind]');
cityRow.dispatchEvent(new MouseEvent('click', {bubbles:true, cancelable:true, ctrlKey:true}));
assert(!cityRow.classList.contains('children-selected'), 'City result became a selectable file');
}
options.open = true;
assert(document.documentElement.scrollWidth <= innerWidth, 'Search introduces horizontal page scrolling');
document.body.dataset.vimReady = '1';
console.log('Vim initialized');
} catch (error) {
const box = document.createElement('div'); box.id = 'error'; box.textContent = error.stack || error.message; document.body.append(box);
}
});
+91
View File
@@ -0,0 +1,91 @@
window.addEventListener('load', async () => {
const pause = () => new Promise(resolve=>setTimeout(resolve,30));
const set = (input,value) => {input.value=value;input.dispatchEvent(new Event('input',{bubbles:true}));};
try {
if (location.pathname === '/') {
const account=document.querySelector('.home-account');
if(account&&getComputedStyle(account).position!=='absolute')throw new Error('Home navigation lost its anchored position');
const wikiTitle=document.querySelector('.home-wiki-title'),titleRect=wikiTitle?.getBoundingClientRect();
if(!wikiTitle||document.querySelector('.home-search h1')||parseFloat(getComputedStyle(wikiTitle).fontSize)>17||titleRect.left>48)throw new Error('Home title was not moved to the upper-left navigation');
const shortcuts={browser:'/v/browser',tree:'/v/tree',city:'/v/city',calendar:'/v/plan',blog:'/v/blog',diary:'/v/diary'};
for(const [name,href] of Object.entries(shortcuts)){
const link=document.querySelector(`[data-home-shortcut="${name}"]`);
if(!link||link.getAttribute('href')!==href||!link.querySelector('svg')||link.textContent.trim()||!link.getAttribute('aria-label')||link.hasAttribute('target'))throw new Error('Home direct icon shortcut failed: '+name);
}
const shortcutStyle=getComputedStyle(document.querySelector('.home-shortcuts'));
if(shortcutStyle.backdropFilter!=='none'||parseFloat(shortcutStyle.borderTopWidth)!==0||shortcutStyle.backgroundColor!=='rgba(0, 0, 0, 0)')throw new Error('Home shortcut icons retained a glass enclosure');
const pager=document.querySelector('[data-home-pager]');
if(!pager||pager.dataset.homePage!=='search')throw new Error('Home search page was not the initial page');
const searchInput=document.getElementById('home-search-input');
set(searchInput,'Browser Guide');
for(let i=0;i<100&&!document.querySelector('.home-search-suggestion[href="/docs/browser-guide"]');i++)await pause();
const directSuggestion=document.querySelector('.home-search-suggestion[href="/docs/browser-guide"]');
if(!directSuggestion||directSuggestion.querySelector('strong')?.textContent!=='Browser Guide'||searchInput.getAttribute('aria-expanded')!=='true')throw new Error('Top-page direct search suggestion missing');
const suggestionPanel=document.getElementById('home-search-suggestions'),suggestionRect=suggestionPanel.getBoundingClientRect();
if(!getComputedStyle(suggestionPanel).backdropFilter.includes('blur')||suggestionRect.bottom>innerHeight+1||suggestionRect.right>innerWidth+1)throw new Error('Top-page suggestion panel style or viewport fit failed');
set(searchInput,'');
const appearanceOpen=document.querySelector('[data-home-appearance-open]'),appearanceDialog=document.querySelector('[data-home-appearance-dialog]');
appearanceOpen.click();
if(!appearanceDialog.open||!getComputedStyle(appearanceDialog).backdropFilter.includes('blur'))throw new Error('Home appearance dialog did not open');
const glassInput=appearanceDialog.querySelector('[name=home_glass_transparency]');set(glassInput,'57');
if(getComputedStyle(document.body).getPropertyValue('--home-glass-opacity').trim()!=='43%')throw new Error('Home glass live preview failed');
appearanceDialog.querySelector('form').requestSubmit();
for(let i=0;i<100&&appearanceDialog.open;i++)await pause();
if(appearanceDialog.open||getComputedStyle(document.body).getPropertyValue('--home-glass-opacity').trim()!=='43%')throw new Error('Home glass setting was not saved');
pager.dispatchEvent(new WheelEvent('wheel',{deltaY:80,bubbles:true,cancelable:true}));
for(let i=0;i<20&&pager.dataset.homePage!=='bookmarks';i++)await pause();
if(pager.dataset.homePage!=='bookmarks'||document.querySelector('[data-home-pager-page="bookmarks"]').inert)throw new Error('Home bookmark page transition failed');
const dialog=document.querySelector('[data-bookmark-dialog]');
if(dialog.open)throw new Error('Bookmark dialog initially open');
document.querySelector('[data-bookmark-open]').click();
if(!dialog.open)throw new Error('Settings button failed');
if(!getComputedStyle(dialog).backdropFilter.includes('blur'))throw new Error('Top-page modal glass style missing');
if(!sessionStorage.getItem('bookmarkSaved')) {
document.querySelector('.bookmark-editor-toolbar button').click();
let card=document.querySelector('.bookmark-editor-card');
set(card.querySelector('.bookmark-card-head input'),'Guides');
card.lastElementChild.click();
let fields=card.querySelectorAll('.bookmark-link-row input');
// Rendering replaces the card after adding a link.
card=document.querySelector('.bookmark-editor-card');fields=card.querySelectorAll('.bookmark-link-row input');
set(fields[0],'Reference');set(fields[1],'/docs/child');
const toggle=card.querySelector('[type=checkbox]');toggle.checked=true;toggle.dispatchEvent(new Event('change',{bubbles:true}));
card=document.querySelector('.bookmark-editor-card');set(card.querySelector('.bookmark-section-options input:not([type=checkbox])'),'/docs');
sessionStorage.setItem('bookmarkSaved','1');document.getElementById('bookmark-form').requestSubmit();return;
}
if(document.querySelector('.bookmark-card-head input').value!=='Guides')throw new Error('Bookmark save not reflected');
const bookmarkCard=document.querySelector('.bookmark-section');
if(!bookmarkCard||!getComputedStyle(bookmarkCard).backdropFilter.includes('blur'))throw new Error('Top-page bookmark glass style missing');
const searchBar=document.querySelector('.home-search form,.topbar-search');
if(!searchBar||!getComputedStyle(searchBar).backdropFilter.includes('blur'))throw new Error('Top-page search glass style missing');
dialog.querySelector('[data-bookmark-close]').click();if(dialog.open)throw new Error('Close button failed');
document.querySelector('[data-bookmark-open]').click();document.body.dataset.vimReady='true';
} else if (new URLSearchParams(location.search).has('picker_test')) {
const open=document.querySelector('[data-picker-target="home-wallpaper-path"]');
const dialog=document.querySelector('[data-path-picker-dialog]');
open.click();
for(let i=0;i<100&&!dialog.querySelector('[data-path="/wallpapers"]');i++)await pause();
const folder=dialog.querySelector('[data-path="/wallpapers"]');
if(!dialog.open||!folder||getComputedStyle(dialog).display!=='grid')throw new Error('Path picker did not open with themed layout');
folder.click();
for(let i=0;i<100&&!dialog.querySelector('[data-path="/wallpapers/browser.jpg"]');i++)await pause();
const image=dialog.querySelector('[data-path="/wallpapers/browser.jpg"]');
if(!image)throw new Error('Image picker did not list the wallpaper');
image.click();dialog.querySelector('[data-path-picker-select]').click();
if(document.getElementById('home-wallpaper-path').value!=='/wallpapers/browser.jpg'||dialog.open)throw new Error('Path picker selection was not applied');
document.body.dataset.vimReady='true';
} else {
const form=document.getElementById('vim-settings-form');
for(const [kind,name,text] of [['vimrc','.vimrc','set tabstop=3\n'],['colorscheme','uploaded.vim','hi Normal guifg=#abcdef\n']]){
const dt=new DataTransfer();dt.items.add(new File([text],name,{type:'text/plain'}));
const input=form.querySelector(`[data-vim-upload="${kind}"]`);input.files=dt.files;input.dispatchEvent(new Event('change',{bubbles:true}));
for(let i=0;i<100&&form.elements[kind].value!==text;i++)await pause();
if(form.elements[kind].value!==text)throw new Error('Upload failed: '+kind);
}
form.requestSubmit();
for(let i=0;i<100&&document.getElementById('vim-settings-status').textContent!==form.dataset.saved;i++)await pause();
if(document.getElementById('vim-settings-status').textContent!==form.dataset.saved)throw new Error('Vim settings save failed');
document.body.dataset.vimReady='true';
}
}catch(error){const box=document.createElement('div');box.id='error';box.textContent=error.message;document.body.append(box);}
});
+175
View File
@@ -0,0 +1,175 @@
window.addEventListener('load', async () => {
const $=id=>document.getElementById('tasks-'+id);
const wait=async fn=>{for(let i=0;i<100;i++){if(fn())return;await new Promise(r=>setTimeout(r,50));}throw Error('Timed out: '+fn);};
const value=(name,text)=>{const n=document.querySelector('#tasks-form [name="'+name+'"]');if(!n)throw Error('Missing field '+name);n.value=text;n.dispatchEvent(new Event('input',{bubbles:true}));};
try {
if (!sessionStorage.getItem('focus-reload')) {
$('dav-open').click(); await wait(()=>$('dav-dialog').open&&$('dav-dialog').querySelector('thead'));
const dav=$('dav-dialog'),form=dav.querySelector('form');if($('dav-compat').checked)throw Error('Compatibility must be opt-in');$('dav-compat').checked=true;form.querySelector('input').value='Browser CLI fixture';form.querySelectorAll('select')[0].value='all';form.querySelectorAll('select')[1].value='write';form.requestSubmit();
await wait(()=>!dav.querySelector('section').hidden&&dav.querySelector('tbody tr'));
if(!dav.querySelector('section input:last-child')||!dav.querySelector('section').textContent.includes('パスワード'))throw Error('DAV credential issue failed');
if(!dav.querySelector('tbody').textContent.includes('OneTask'))throw Error('Compatibility setting not persisted');
const r=dav.getBoundingClientRect();if(r.width>innerWidth+1||r.height>innerHeight+1||dav.scrollWidth>dav.clientWidth+1)throw Error('DAV dialog overflow');
window.confirm=()=>true;await wait(()=>!form.querySelector('button').disabled);dav.querySelector('tbody button').click();await wait(()=>!dav.querySelector('tbody tr'));
dav.querySelector('header button').click();if(!dav.querySelector('section').hidden||dav.querySelector('section input'))throw Error('DAV password retained after close');
}
if(sessionStorage.getItem('focus-reload')){
await wait(()=>$('focus').dataset.state==='paused');
const f=await fetch('/_/api/v1/extension/organizer.tasks/focus').then(r=>r.json());
if(f.item.uuid!==sessionStorage.getItem('focus-reload')||f.item.version!==2)throw Error('Timer failed to restore');
await wait(()=>$('day').querySelector('strong').textContent==='25分'&&$('day-blocks').textContent.includes('Changed elsewhere'));
$('day').querySelector('details').open=true;
// Inline edits preserve notes and support independently dated children.
await wait(()=>$('list').querySelector('[data-action=add-child]'));
const row=$('list').querySelector('.task-inline-row');
const editInline=async(name,text)=>{const input=row.querySelector('[name="'+name+'"]');input.value=text;input.dispatchEvent(new Event('input',{bubbles:true}));input.dispatchEvent(new Event('change',{bubbles:true}));await wait(()=>!window.PagesWikiTaskRows.hasDirty()&&!row.hasAttribute('aria-busy'));};
await editInline('start_on','2026-09-25');await editInline('end_on','2026-09-28');
row.querySelector('[data-action=add-child]').click();const capture=row.querySelector('.task-child-capture');capture.querySelector('input').value='Independent child';capture.querySelector('input').dispatchEvent(new Event('input',{bubbles:true}));capture.requestSubmit();await wait(()=>row.querySelector('.task-inline-children .task-inline-row'));
const child=row.querySelector('.task-inline-children .task-inline-row');if(child.querySelector('[data-action=add-child]'))throw Error('Nested subtasks should be bounded');
// Dense desktop rows keep editable fields on a single baseline, including children.
const fields=['title','status','planned_on','due_on','review_on','start_on','end_on'];
const controls=fields.map(name=>row.querySelector('[name="'+name+'"]'));
if(innerWidth>=1024){
const first=controls[0].getBoundingClientRect();
for(const control of controls){
const r=control.getBoundingClientRect();
if(Math.abs(r.top-first.top)>1||r.height>36)throw Error('Desktop task fields must fit one compact line');
const nested=child.querySelector('[name="'+control.name+'"]').getBoundingClientRect();
if(Math.abs(nested.left-r.left)>1||Math.abs(nested.width-r.width)>1)throw Error('Subtask columns are misaligned');
}
const action=row.querySelector('[data-action=detail]').getBoundingClientRect();
if(Math.abs((action.top+action.height/2)-(first.top+first.height/2))>1)throw Error('Desktop actions wrapped');
if(getComputedStyle(document.querySelector('.task-inline-header')).display==='none')throw Error('Desktop column headings missing');
if(row.querySelector('.task-inline-status').getBoundingClientRect().height>1)throw Error('Successful save added another row');
}else{
for(const control of [...controls,...row.querySelectorAll(':scope > .tasks-actions button,:scope > .tasks-actions a,:scope > .task-inline-main button')]){
const r=control.getBoundingClientRect();
if(r.height<44||r.width<44)throw Error('Mobile task touch target is too small');
if(parseFloat(getComputedStyle(control).fontSize)<16)throw Error('Mobile input may trigger Safari zoom');
}
if(getComputedStyle(document.querySelector('.task-inline-header')).display!=='none')throw Error('Mobile should use local field labels');
if(child.scrollWidth>child.clientWidth+1)throw Error('Subtask mobile overflow');
}
if(row.querySelector('[data-action=children]').getAttribute('aria-expanded')!=='true')throw Error('Subtask expansion state missing');
// A failed inline save remains visible and keeps the typed value.
const latest=await fetch('/_/api/v1/extension/organizer.tasks/items/'+row.dataset.taskId).then(r=>r.json());
const concurrent=await fetch('/_/api/v1/extension/organizer.tasks/items/'+row.dataset.taskId,{method:'PUT',headers:{'Content-Type':'application/json','If-Match':'"'+latest.item.version+'"'},body:JSON.stringify({...latest.item,notes:'Concurrent notes kept'})});
if(!concurrent.ok)throw Error('Concurrent fixture update failed');
const title=row.querySelector('[name=title]');title.value='Keep my inline draft';title.dispatchEvent(new Event('input',{bubbles:true}));title.dispatchEvent(new Event('change',{bubbles:true}));
const rowStatus=row.querySelector(':scope > .task-inline-status');
await wait(()=>rowStatus.dataset.state==='error'&&!row.hasAttribute('aria-busy'));
if(title.value!=='Keep my inline draft'||rowStatus.getBoundingClientRect().height<16||!window.PagesWikiTaskRows.hasDirty())throw Error('Inline conflict hidden or discarded');
window.confirm=()=>true;row.querySelector('[data-action=reload]').click();await wait(()=>!window.PagesWikiTaskRows.hasDirty());
const schedule=await fetch('/_/api/v1/extension/organizer.tasks/schedule?month=2026-09').then(r=>r.json());if(schedule.items.length!==1||schedule.items[0].start_on!=='2026-09-25')throw Error('Schedule failed');
document.querySelector('[data-tasks-today-launch]').click();await wait(()=>document.querySelector('[data-tasks-today-list]').textContent.includes('Changed elsewhere'));document.querySelector('[data-tasks-today-close]').click();
// No OS permission prompt is triggered automatically. Test in-page notification paths.
Object.defineProperty(document,'hasFocus',{configurable:true,value:()=>true});
await fetch('/__notification-fixture',{method:'POST'});window.dispatchEvent(new Event('focus'));
await wait(()=>document.querySelector('.notification-toast')?.textContent.includes('Browser notification fixture'));
document.querySelector('[data-notification-launch]').click();await wait(()=>document.querySelector('[data-notification-dialog] .notification-item'));
const auto=document.querySelectorAll('.notification-settings input[type=checkbox]')[1];auto.checked=true;auto.dispatchEvent(new Event('change'));document.querySelector('[data-notification-close]').click();
await new Promise(resolve=>setTimeout(resolve,50));await fetch('/__notification-fixture',{method:'POST'});document.activeElement?.blur();document.dispatchEvent(new Event('visibilitychange'));await wait(()=>document.querySelector('[data-notification-dialog]').open);await wait(()=>document.querySelector('[data-notification-dialog] .notification-item'));
const modal=document.querySelector('[data-notification-dialog]');if(modal.scrollWidth>modal.clientWidth+1)throw Error('Notification settings overflow');modal.close();
// Leave a clean, expanded hierarchy for visual review.
await wait(()=>$('list').querySelector('[data-action=children]'));
const current=$('list').querySelector('.task-inline-row'),expand=current.querySelector('[data-action=children]');
if(expand.getAttribute('aria-expanded')!=='true')expand.click();
await wait(()=>current.querySelector('.task-inline-children .task-inline-row'));
document.querySelectorAll('.notification-toast button').forEach(button=>button.click());
if(innerWidth<1024)current.scrollIntoView({block:'start'});
if(document.documentElement.scrollWidth>innerWidth+1)throw Error('Focus toolbar horizontal overflow');
// A real daily page groups filtered children beneath their parent and
// opens a newly-created Wiki document through the row's memo actions.
const taskAPI='/_/api/v1/extension/organizer.tasks/items';
const today=$('app').dataset.today,date=new Date(today+'T12:00:00Z');date.setUTCDate(date.getUTCDate()+1);const tomorrow=date.toISOString().slice(0,10);
const make=async(title,extra={})=>{const response=await fetch(taskAPI,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({uuid:crypto.randomUUID(),kind:'task',title,notes:'Private short notes',status:'todo',bucket:'inbox',priority:1,project_uuid:'__TASK_PROJECT_UUID__',...extra})});if(!response.ok)throw Error('Task fixture create failed');return (await response.json()).item;};
const plannedParent=await make('Tomorrow parent',{planned_on:tomorrow});
const plannedChild=await make('Tomorrow child',{parent_uuid:plannedParent.uuid});
const frame=document.createElement('iframe');frame.style.cssText='position:fixed;inset:0;width:100%;height:100%;z-index:10000;background:var(--bg)';frame.src='/v/plan/tasks/tomorrow';document.body.append(frame);
const inFrame=selector=>frame.contentDocument?.querySelector(selector);
await wait(()=>inFrame('[data-task-id="'+plannedParent.uuid+'"]'));
let parentRow=inFrame('[data-task-id="'+plannedParent.uuid+'"]');
parentRow.querySelector('[data-action=children]').click();
await wait(()=>inFrame('[data-task-id="'+plannedChild.uuid+'"]'));
if(!parentRow.contains(inFrame('[data-task-id="'+plannedChild.uuid+'"]')))throw Error('Planned parent cannot expand unscheduled children');
// Giving a child its own plan must not duplicate it as a top-level row.
const childDate=inFrame('[data-task-id="'+plannedChild.uuid+'"] [name=planned_on]');childDate.value=tomorrow;childDate.dispatchEvent(new frame.contentWindow.Event('input',{bubbles:true}));childDate.dispatchEvent(new frame.contentWindow.Event('change',{bubbles:true}));
await wait(()=>!frame.contentWindow.PagesWikiTaskRows.hasDirty());
frame.contentDocument.getElementById('tasks-refresh').click();
await wait(()=>inFrame('[data-task-id="'+plannedChild.uuid+'"]'));
if(frame.contentDocument.querySelectorAll('[data-task-id="'+plannedChild.uuid+'"]').length!==1||!inFrame('[data-task-id="'+plannedParent.uuid+'"]').contains(inFrame('[data-task-id="'+plannedChild.uuid+'"]')))throw Error('Child grouping duplicated or detached');
inFrame('[data-task-id="'+plannedChild.uuid+'"] [data-action=plan]').click();
await wait(()=>inFrame('#tasks-plan-dialog')?.open&&inFrame('#tasks-plan-dialog [name=start]')?.value.startsWith(tomorrow)&&!inFrame('#tasks-plan-dialog button[type=submit]').disabled);
inFrame('#tasks-plan-dialog header button').click();
// New tasks created on a selected day get that day, not today.
frame.contentDocument.getElementById('tasks-quick-title').value='Created on tomorrow';
frame.contentDocument.getElementById('tasks-capture').requestSubmit();
await wait(()=>Array.from(frame.contentDocument.querySelectorAll('input[name=title]')).some(n=>n.value==='Created on tomorrow'));
const dayData=await fetch(taskAPI+'?view=day&date='+tomorrow).then(r=>r.json());
if(!dayData.items.some(i=>i.title==='Created on tomorrow'&&i.planned_on===tomorrow))throw Error('Daily quick capture used the wrong date');
frame.contentWindow.confirm=()=>true;
inFrame('[data-task-id="'+plannedChild.uuid+'"] [data-action=note-edit]').click();
await wait(()=>frame.contentWindow.location.pathname.startsWith('/e/-/projects/browser/notes/'));
const note=await fetch(taskAPI+'/'+plannedChild.uuid+'/note').then(r=>r.json());
if(!note.linked||note.path!=='/projects/browser/notes/Tomorrow child')throw Error('Memo edit did not create/link the Wiki page');
frame.src='/v/plan/tasks/tomorrow';
await wait(()=>inFrame('[data-task-id="'+plannedChild.uuid+'"] [data-action=note-view]'));
inFrame('[data-task-id="'+plannedChild.uuid+'"] [data-action=note-view]').click();
await wait(()=>decodeURIComponent(frame.contentWindow.location.pathname)==='/projects/browser/notes/Tomorrow child');
await wait(()=>frame.contentDocument.body.textContent.includes('Tomorrow child'));
const yesterday=new Date(today+'T12:00:00Z');yesterday.setUTCDate(yesterday.getUTCDate()-1);
const carried=await make('Carry to tomorrow',{planned_on:yesterday.toISOString().slice(0,10)});
frame.src='/v/plan/tasks/carryover';
await wait(()=>inFrame('[data-task-id="'+carried.uuid+'"]'));
const targetDate=inFrame('.task-date-nav input');targetDate.value=tomorrow;targetDate.dispatchEvent(new frame.contentWindow.Event('change',{bubbles:true}));
inFrame('[data-task-id="'+carried.uuid+'"] [data-action=schedule-day]').click();
await wait(()=>!inFrame('[data-task-id="'+carried.uuid+'"]'));
const rescheduled=await fetch(taskAPI+'/'+carried.uuid).then(r=>r.json());
if(rescheduled.item.planned_on!==tomorrow||rescheduled.item.due_on)throw Error('Carryover action changed deadline or used wrong day');
frame.remove();
document.body.dataset.vimReady='true';return;
}
await wait(()=>$('status').textContent.includes('ありません'));
$('quick-title').value='Write the first task';$('capture').requestSubmit();
await wait(()=>$('list').querySelector('[data-action=detail]'));
$('list').querySelector('[data-action=detail]').click();
await wait(()=>document.querySelector('[name="page_path"]'));
value('notes','Preserve these private notes');value('status','doing');value('estimate_minutes','25');
const notify=document.querySelector('[name="notify_planned"]');if(!notify||notify.checked)throw Error('Reminder must default off');notify.click();value('reminder_time','10:30');$('form').requestSubmit();
await wait(()=>!$('dialog').open);await wait(()=>$('list').textContent.includes('25 min'));
const delivered=await fetch('/__task-reminder-fixture',{method:'POST'});if(!delivered.ok)throw Error('Fixture delivery failed');
document.dispatchEvent(new Event('visibilitychange'));
await wait(()=>!document.querySelector('[data-notification-badge]').hidden);
document.querySelector('[data-notification-launch]').click();
await wait(()=>document.querySelector('[data-notification-dialog] [data-notifications-list]').textContent.includes('Write the first task'));
if(!document.querySelector('[data-notification-badge]').hidden)throw Error('Badge remained after opening Inbox');
document.querySelector('[data-notification-close]').click();
$('list').querySelector('button').click();
await wait(()=>!$('list').children.length);
const res=await fetch('/_/api/v1/extension/organizer.tasks/items?view=done');const done=await res.json();if(done.items.length!==1)throw Error('Completion missing');
const detail=await fetch('/_/api/v1/extension/organizer.tasks/items/'+done.items[0].uuid).then(r=>r.json());if(detail.item.notes!=='Preserve these private notes')throw Error('Notes lost on quick completion');if(!detail.item.notify_planned||detail.item.reminder_time!=='10:30'||!detail.item.reminder_timezone)throw Error('Reminder settings lost');
const undo=await fetch('/_/api/v1/extension/organizer.tasks/items/'+detail.item.uuid,{method:'PUT',headers:{'Content-Type':'application/json','If-Match':'"'+detail.item.version+'"'},body:JSON.stringify({...detail.item,status:'todo'})});if(!undo.ok)throw Error('Reopen failed');
$('refresh').click();await wait(()=>$('list').querySelector('[data-action=detail]'));$('list').querySelector('[data-action=detail]').click();await wait(()=>document.querySelector('[name="page_path"]'));
// A background edit must not silently overwrite an already-open form.
const fresh=await fetch('/_/api/v1/extension/organizer.tasks/items/'+detail.item.uuid).then(r=>r.json());
await fetch('/_/api/v1/extension/organizer.tasks/items/'+detail.item.uuid,{method:'PUT',headers:{'Content-Type':'application/json','If-Match':'"'+fresh.item.version+'"'},body:JSON.stringify({...fresh.item,title:'Changed elsewhere'})});
value('title','Unsaved local title');$('form').requestSubmit();await wait(()=>$('error').textContent.includes('別の画面'));
if(document.querySelector('#tasks-form [name="title"]').value!=='Unsaved local title')throw Error('Conflict lost input');
window.confirm=()=>true;$('close').click();$('refresh').click();await wait(()=>$('list').querySelector('input[name=title]')?.value==='Changed elsewhere');
if(document.documentElement.scrollWidth>innerWidth+1)throw Error('Horizontal page overflow');
// Validate responsive modal dimensions and save an inspectable screenshot.
$('list').querySelector('[data-action=detail]').click();await wait(()=>document.querySelector('[name="page_path"]'));
const rect=$('dialog').getBoundingClientRect();if(rect.width>innerWidth+1||rect.height>innerHeight+1)throw Error('Modal overflow');
$('plan-open').click();await wait(()=>$('plan-dialog').open&&$('plan-dialog').querySelector('select').options.length&&!$('plan-dialog').querySelector('button[type=submit]').disabled);
const pf=$('plan-dialog').querySelector('form'),date=$('app').dataset.today;pf.querySelector('[name=start]').value=date+'T10:00';pf.querySelector('[name=end]').value=date+'T11:00';pf.requestSubmit();
await wait(()=>$('plan-list').querySelector('a'));
if(!$('plan-list').querySelector('a').href.includes('/v/plan/event/'))throw Error('Calendar event link missing');
if($('plan-dialog').scrollWidth>$('plan-dialog').clientWidth+1)throw Error('Planning dialog overflow');
const planningRect=$('plan-dialog').getBoundingClientRect();if(planningRect.width>innerWidth+1||planningRect.height>innerHeight+1)throw Error('Planning modal outside viewport');
$('plan-dialog').querySelector('header button').click();$('close').click();
await wait(()=>!$('focus').querySelector('[data-action=start]').disabled);
$('focus').querySelector('[data-action=start]').click();await wait(()=>$('focus').dataset.state==='running'&&!$('focus').querySelector('[data-action=pause]').disabled);
$('focus').querySelector('[data-action=pause]').click();await wait(()=>$('focus').dataset.state==='paused');
const f=await fetch('/_/api/v1/extension/organizer.tasks/focus').then(r=>r.json());sessionStorage.setItem('focus-reload',f.item.uuid);location.reload();
} catch(e) {const out=document.createElement('pre');out.id='error';out.textContent=e.stack||e.message;document.body.append(out);}
});
+53
View File
@@ -0,0 +1,53 @@
// Real-time CDP smoke test: virtual-time screenshots finish before Wasm
// compilation on a worker. No credentials or production workspace are used.
import {spawn} from 'node:child_process';
import {writeFile} from 'node:fs/promises';
import {setTimeout as delay} from 'node:timers/promises';
const [url, profile, screenshot, width = '1440', height = '1000'] = process.argv.slice(2);
const browser = spawn('chromium', ['--headless', '--no-sandbox', '--disable-gpu', '--disable-background-networking', '--no-proxy-server', '--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank']);
process.on('SIGTERM', () => { browser.kill(); process.exit(1); });
let socket;
try {
const endpoint = await new Promise((resolve, reject) => {
let log = '';
browser.stderr.on('data', chunk => {
log += chunk;
const match = log.match(/DevTools listening on (ws:\/\/[^\s]+)/);
if (match) resolve(match[1]);
});
browser.on('error', reject);
browser.on('exit', code => reject(new Error(`Browser exited ${code}: ${log}`)));
});
socket = new WebSocket(endpoint);
await new Promise((resolve, reject) => { socket.onopen = resolve; socket.onerror = reject; });
let id = 0;
const pending = new Map();
socket.onmessage = event => {
const message = JSON.parse(event.data), pair = pending.get(message.id);
if (pair) { pending.delete(message.id); message.error ? pair.reject(new Error(JSON.stringify(message.error))) : pair.resolve(message.result); }
};
const send = (method, params = {}, sessionId) => new Promise((resolve, reject) => {
pending.set(++id, {resolve, reject}); socket.send(JSON.stringify({id, method, params, sessionId}));
});
const {targetId} = await send('Target.createTarget', {url: 'about:blank'});
const {sessionId} = await send('Target.attachToTarget', {targetId, flatten: true});
const call = (method, params) => send(method, params, sessionId);
await call('Page.enable');
await call('Emulation.setDeviceMetricsOverride', {width: Number(width), height: Number(height), deviceScaleFactor: 1, mobile: false});
await call('Page.navigate', {url});
let ready = false;
for (let attempt = 0; attempt < 150; attempt++) {
const {result} = await call('Runtime.evaluate', {expression: `JSON.stringify({ready: document.body?.dataset.vimReady, error: document.querySelector('#error:not([hidden])')?.textContent})`, returnByValue: true});
const state = JSON.parse(result.value || '{}');
if (state.error) throw new Error(state.error);
if (state.ready) { ready = true; break; }
await delay(200);
}
if (screenshot) {
const {data} = await call('Page.captureScreenshot', {format: 'png'});
await writeFile(screenshot, Buffer.from(data, 'base64'));
}
if (!ready) throw new Error('Vim startup timed out');
console.log('Vim initialized and exported startup report');
} finally { socket?.close(); browser.kill(); }