import test from 'node:test'; import assert from 'node:assert/strict'; import { fixture } from './fixture.mjs'; import { browser } from './browser.mjs'; import { P, T, stub } from './helpers/projects-review-fixture.mjs'; const history = stub + `;for(let i=0;i<42;i++){const n=String(i+10).padStart(12,'0'),body='History '+i+' '+('message text '.repeat(8)),at='2026-11-06T10:26:00Z',id='50000000-0000-4000-8000-'+n;fixtureRoom.push({id,ids:[id],from_role:'human',to:['assistant'],body,at})}`; // Exercise a valid ordering in which repaint and its native scroll event happen // before the log's resize callback. Other observers retain normal delivery. const delayLogResize = `(() => { const Native = window.ResizeObserver; window.ResizeObserver = class extends Native { constructor(callback) { super((entries, observer) => { if (!entries.some(e => e.target.matches?.('.project-chat .chat-log'))) return callback(entries, observer); const deliver = n => n ? requestAnimationFrame(() => deliver(n-1)) : callback(entries, observer); deliver(4); }); } }; })();`; for (const width of [700, 1440]) test(`S14 room ${width}x700 follows the tail when resize delivery follows repaint`, async t => { const f = await fixture(), b = await browser({ machine: false }); t.after(async () => { await b.close(); await f.close(); }); await b.call('Fetch.enable', { patterns: [{ urlPattern: '*' }] }); b.on('Fetch.requestPaused', p => void b.call(p.request.url.startsWith(f.base+'/') ? 'Fetch.continueRequest' : 'Fetch.failRequest', p.request.url.startsWith(f.base+'/') ? { requestId:p.requestId } : { requestId:p.requestId, errorReason:'BlockedByClient' }).catch(() => {})); await b.call('Page.addScriptToEvaluateOnNewDocument', { source: delayLogResize + history }); await b.viewport(width, 700); await b.navigate(f.base+'/#/projects/'+P); const wait = expr => b.evaluate(`(async()=>{for(let i=0;i<200;i++){if(${expr})return;await new Promise(r=>setTimeout(r,30))}throw Error('Timeout')})()`); await wait("document.querySelector('[data-project-content] [data-project-room-status]')"); await b.evaluate(`location.hash=${JSON.stringify('#/projects/rooms/'+P)}`); await wait("document.querySelectorAll('.project-chat .chat-log > li').length >= 45"); await b.evaluate('(async()=>{for(let i=0;i<20;i++)await new Promise(requestAnimationFrame)})()'); const m = await b.evaluate(`(()=>{const l=document.querySelector('.project-chat .chat-log'),last=l.lastElementChild.getBoundingClientRect(),box=l.getBoundingClientRect();return {top:l.scrollTop,scrollHeight:l.scrollHeight,clientHeight:l.clientHeight,lastBottom:last.bottom,logBottom:box.bottom}})()`); console.log('S14',width,JSON.stringify(m)); if (process.env.S14_CAPTURE) await b.screenshot(`${process.env.S14_CAPTURE}/${process.env.S14_PHASE}-room-${width}x700.png`); assert.ok(m.lastBottom <= m.logBottom + 0.5, `newest message is clipped: ${JSON.stringify(m)}`); // The delayed resize must not override a reader who leaves the tail. const point = await b.evaluate(`(()=>{const r=document.querySelector('.project-chat .chat-log').getBoundingClientRect();return {x:r.left+r.width/2,y:r.top+r.height/2}})()`); await b.call('Input.dispatchMouseEvent',{type:'mouseWheel',...point,deltaX:0,deltaY:-300}); await b.evaluate('(async()=>{for(let i=0;i<8;i++)await new Promise(requestAnimationFrame)})()'); const up = await b.evaluate("document.querySelector('.chat-log').scrollTop"); assert.ok(up < m.top - 100, `wheel did not scroll up: ${up}`); await b.evaluate("document.querySelector('.chat-log li:last-child .chat-body').append(' more '.repeat(100))"); await b.evaluate('(async()=>{for(let i=0;i<12;i++)await new Promise(requestAnimationFrame)})()'); const held = await b.evaluate("document.querySelector('.chat-log').scrollTop"); assert.ok(Math.abs(held-up)<=1, `reader pulled back to tail: ${JSON.stringify({up,held})}`); // Find-style reveals and focus return must also remain away from the tail. await b.evaluate("document.querySelectorAll('.chat-log > li')[4].scrollIntoView({block:'center'})"); await b.evaluate('(async()=>{for(let i=0;i<8;i++)await new Promise(requestAnimationFrame)})()'); const revealed = await b.evaluate("document.querySelector('.chat-log').scrollTop"); await b.evaluate(`(()=>{const id='50000000-0000-4000-8000-000000000099';fixtureRoom.push({id,ids:[id],from_role:'human',to:['assistant'],body:'New while reading',at:'2026-11-06T10:27:00Z'});document.querySelector('#refresh').click()})()`); await wait("document.querySelector('[data-message$=\"000000000099\"]')"); await b.evaluate('(async()=>{for(let i=0;i<12;i++)await new Promise(requestAnimationFrame)})()'); const afterRefresh = await b.evaluate("document.querySelector('.chat-log').scrollTop"); assert.ok(Math.abs(afterRefresh-revealed)<=1, `revealed message moved: ${JSON.stringify({revealed,afterRefresh})}`); await b.evaluate("document.querySelector('[data-project-dialog=room]').focus()"); await b.key('Enter'); assert.ok(await b.evaluate("!!document.querySelector('dialog[open]')"), 'room details opened'); await b.key('Escape'); await b.evaluate('(async()=>{for(let i=0;i<8;i++)await new Promise(requestAnimationFrame)})()'); const focus = await b.evaluate(`(()=>{const e=document.activeElement,r=e.getBoundingClientRect();return {details:e.matches('[data-project-dialog=room]'),visible:r.top0,top:document.querySelector('.chat-log').scrollTop}})()`); assert.ok(focus.details && focus.visible && Math.abs(focus.top-revealed)<=1, `dialog focus or reader position lost: ${JSON.stringify(focus)}`); await b.evaluate("document.querySelector('.chat-log').focus({preventScroll:true})"); await b.key('Tab'); await b.evaluate('(async()=>{for(let i=0;i<8;i++)await new Promise(requestAnimationFrame)})()'); const tab = await b.evaluate(`(()=>{const r=document.activeElement.getBoundingClientRect();return {visible:r.top0,top:document.querySelector('.chat-log').scrollTop}})()`); assert.ok(tab.visible && tab.top < m.top-100, `Tab focus or reader position lost: ${JSON.stringify(tab)}`); }); // A Tab outside the log while a stale matching scroll is still being classified // moves no transcript, so no later scroll event decides it. The reader stays put. for (const name of ['room', 'conversation']) test(`S14 ${name} 700x700 Tab during pending classification keeps the reader's place`, async t => { const f = await fixture(), b = await browser({ machine: false }); t.after(async () => { await b.close(); await f.close(); }); await b.call('Fetch.enable', { patterns: [{ urlPattern: '*' }] }); b.on('Fetch.requestPaused', p => void b.call(p.request.url.startsWith(f.base+'/') ? 'Fetch.continueRequest' : 'Fetch.failRequest', p.request.url.startsWith(f.base+'/') ? { requestId:p.requestId } : { requestId:p.requestId, errorReason:'BlockedByClient' }).catch(() => {})); const threadHistory = `;for(let i=0;i<42;i++){const n=String(i+10).padStart(12,'0');fixtureMessages.push({id:'40000000-0000-4000-8000-'+n,from_role:'human',body:'History '+i+' '+('message text '.repeat(8)),at:'2026-11-06T10:26:00Z'})}`; await b.call('Page.addScriptToEvaluateOnNewDocument', { source: history + threadHistory }); await b.viewport(700, 700); await b.navigate(f.base+'/#/projects/'+P); const wait = expr => b.evaluate(`(async()=>{for(let i=0;i<200;i++){if(${expr})return;await new Promise(r=>setTimeout(r,30))}throw Error('Timeout')})()`); const frames = n => b.evaluate(`(async()=>{for(let i=0;i<${n};i++)await new Promise(requestAnimationFrame)})()`); await wait("document.querySelector('[data-project-content] [data-project-room-status]')"); await b.evaluate(`location.hash=${JSON.stringify('#/projects/'+(name==='room'?'rooms/'+P:'threads/'+T))}`); await wait("document.querySelectorAll('.project-chat .chat-log > li').length >= 43"); await frames(20); const gap = "(()=>{const l=document.querySelector('.chat-log');return l.scrollHeight-l.clientHeight-l.scrollTop})()"; assert.ok(await b.evaluate(gap) <= 1, 'opens at the tail'); await b.evaluate("document.querySelector('h1').focus({preventScroll:true})"); // The S11 stale-pin collision: a pin, growth the observer has not settled, a coalesced matching scroll. const before = await b.evaluate(`(async()=>{const l=document.querySelector('.chat-log'),last=l.lastElementChild.querySelector('.chat-body');const scrolled=new Promise(r=>l.addEventListener('scroll',()=>r(),{once:true}));last.append(' pin '.repeat(150));await Promise.resolve();const pin=l.scrollTop;last.style.minHeight=(last.getBoundingClientRect().height+250)+'px';l.scrollTop=pin+100;l.scrollTop=pin;await scrolled;return {pin,gap:l.scrollHeight-l.clientHeight-l.scrollTop}})()`); await b.key('Tab'); await frames(8); const tab = await b.evaluate(`(()=>{const e=document.activeElement,r=e.getBoundingClientRect();return {top:document.querySelector('.chat-log').scrollTop,inLog:!!e.closest('.chat-log'),visible:e!==document.body&&r.top0}})()`); assert.ok(before.gap >= 249 && tab.visible && !tab.inLog && Math.abs(tab.top-before.pin) <= 2, `setup: ${JSON.stringify({before,tab})}`); await b.evaluate("document.querySelector('.chat-log li:last-child .chat-body').append(' next '.repeat(150))"); await frames(12); const after = await b.evaluate("document.querySelector('.chat-log').scrollTop"); assert.ok(Math.abs(after-before.pin) <= 2, `reader pulled to the tail after Tab: ${JSON.stringify({before,tab,after})}`); });