okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
85269ca15
main
1#!/usr/bin/env node 2/** 3* Drives the built app in a headless Chrome against a real host with a clean temporary profile (no engine, no model), for the 0.2.10 4* interface changes (branch f-0291-ui). Each case seeds the chat history it needs into the page's local storage, so the real screens 5* draw real data without a model. 6* 7* npx vite build && node scripts/ui-do-drive.mjs <shots-dir> [case ...] 8* 9* Never point it at a real install: the host it starts uses a fresh STRATA_HOME in the temp folder and a random port. 10* Light and dark, at a normal and a narrow window. Prints "ok" / "FAIL" lines and exits 1 on a failure. 11*/ 12import { spawn , spawnSync } from 'node:child_process' ; 13import { existsSync , mkdirSync , mkdtempSync , rmSync } from 'node:fs' ; 14import { createServer } from 'node:net' ; 15import { tmpdir } from 'node:os' ; 16import { join , resolve } from 'node:path' ; 17import { pathToFileURL } from 'node:url' ; 18import { startScriptedWorker } from '../tests/helpers/scripted-worker.mjs' ; 19 20const HOST_DIR = resolve ( import . meta. dirname , '..' ); 21const SHOTS = resolve ( process . argv [ 2 ] ?? 'ui-shots' ); 22const ONLY = process . argv . slice ( 3 ); 23mkdirSync ( SHOTS , { recursive :true }); 24const { chromium} = await import ( pathToFileURL ( join ( HOST_DIR , 'node_modules/playwright-core/index.mjs' )). href ); 25const CHROME = process . env . CHROME ?? [ 'C:/Program Files/Google/Chrome/Application/chrome.exe' , '/usr/bin/google-chrome' ]. find ( existsSync ); 26const freePort = () => new Promise ( r => { const s = createServer (); s . listen ( 0 , '127.0.0.1' , () => { const p = s . address (). port ; s . close (() => r ( p )); }); }); 27const sleep = ms => new Promise ( r => setTimeout ( r , ms )); 28let failed = false ; 29export const check = ( ok , label , extra = '' ) => { console . log ( ` ${ ok ? 'ok ' : 'FAIL' } ${ label } ${ extra ? ' ' + extra : '' } ` ); if ( ! ok ) failed = true ; }; 30 31const home = mkdtempSync ( join ( tmpdir (), 'strata-ui-do-' )); 32const ws = join ( home , 'workspace' ); mkdirSync ( ws , { recursive :true }); 33const port = await freePort (); 34const env = { ...process . env , STRATA_HOME :home , STRATA_PORT :String ( port ), STRATA_WORKSPACE :ws , STRATA_REAL_ENGINE :'0' , STRATA_COMPONENTS_DIR :join ( home , 'components' ), STRATA_SETTINGS_FILE :join ( home , 'app-settings.json' ), LOCALAPPDATA :join ( home , 'Local' ), APPDATA :join ( home , 'Roaming' ), XDG_DATA_HOME :join ( home , 'xdg-data' ), XDG_CONFIG_HOME :join ( home , 'xdg-config' ), XDG_STATE_HOME :join ( home , 'xdg-state' ) }; 35delete env . STRATA_HARNESS_DIR ; 36const child = spawn ( process . execPath , [ join ( HOST_DIR , 'server' , 'index.mjs' )], { cwd :HOST_DIR , env, stdio :'ignore' , windowsHide :true }); 37export const base = `http://127.0.0.1: ${ port } ` ; 38for ( let i = 0 ; i < 100 ; i ++ ) { try { if (( await fetch ( ` ${ base } /api/health` )). ok ) break ; } catch { /* starting */ } await sleep ( 200 ); } 39// A saved API connection to a scripted model gives the app a model to talk to, so it stays on the chat screen (no model loaded would send it to Models). 40const worker = await startScriptedWorker ({ model :'cloud-model' }); 41const saved = await ( await fetch ( ` ${ base } /api/model-providers` , { method :'POST' , headers :{ 'content-type' :'application/json' }, body :JSON . stringify ({ kind :'custom' , name :'Scripted API' , baseUrl :worker . url , protocol :'openai-chat' , apiKey :'sk-ui-do-test-0123456789' , models :[{ id :'cloud-model' , name :'Cloud model' , contextMax :64000 }] }) })). json (); 42const remoteModel = { connectionId :saved . connections ?.[ 0 ]?. id , modelId :'cloud-model' }; 43check ( !! remoteModel . connectionId , 'a scripted API model is connected' ); 44// "Go straight to the app": the first-run screens are not what these cases look at. 45await fetch ( ` ${ base } /api/setup/step` , { method :'POST' , headers :{ 'content-type' :'application/json' }, body :JSON . stringify ({ step :1 , dismissed :true , flowVersion :2 }) }); 46const browser = await chromium . launch ({ executablePath :CHROME , headless :true , args :[ '--no-sandbox' ] }); 47 48const iso = ( n = 0 ) => new Date ( Date . UTC ( 2026 , 9 , 31 , 9 , 0 , n )). toISOString (); 49export const user = ( id , content , n = 0 ) => ({ id, role :'user' , content, at :iso ( n ) }); 50export const reply = ( id , content , extra = {}) => ({ id, role :'assistant' , content, at :iso ( 5 ), tokens :120 , tps :40 , durationMs :3000 , ...extra }); 51export const chat = ( id , title , messages ) => ({ id, title, defaultTitle :false , updatedAt :iso ( 9 ), createdAt :iso ( 0 ), messages, workspace :ws , tokensIn :0 , tokensOut :0 , preferences :{ useTools :true , mode :'manual' , remoteModel} }); 52 53/** A page with the given chats already in local storage. `prefs` are merged into the saved preferences. */ 54export async function open ( scheme , width , height , sessions , { hash= '#/chat' , prefs= {}, origin= base , before= null , locale= 'en-US' , keepSetup= false } = {}) { 55const context = await browser . newContext ({ viewport :{ width, height}, colorScheme :scheme , locale, permissions :[ 'clipboard-read' , 'clipboard-write' ] }); 56const page = await context . newPage (); 57pages . push ( page ); 58const problems = []; 59page . on ( 'pageerror' , e => problems . push ( e . message )); 60page . problems = problems ; 61await page . addInitScript (({ sessions, prefs}) => { 62try { 63if ( sessionStorage . getItem ( 'ui-do-seeded' )) return ; 64sessionStorage . setItem ( 'ui-do-seeded' , '1' ); 65// The chats are files on the host: put the seed there (a synchronous request, so it is in place before the page starts). 66for ( const chat of sessions ?? []) { const request = new XMLHttpRequest (); request . open ( 'PUT' , '/api/chats/' + encodeURIComponent ( chat . id ), false ); request . setRequestHeader ( 'x-strata-client' , 'ui' ); request . send ( JSON . stringify ({ messages :[], ...chat })); } 67if ( Object . keys ( prefs ). length ) localStorage . setItem ( 'strata.prefs.v1' , JSON . stringify ( prefs )); 68} catch { /* storage refused */ } 69}, { sessions, prefs}); 70if ( before ) await before ( page ); 71await page . goto ( ` ${ origin } / ${ hash } ` ); 72await page . waitForTimeout ( 1800 ); 73const skip = page . getByText ( 'Go straight to the app' ); 74if ( ! keepSetup && await skip . count ()) { await skip . click (); await page . waitForTimeout ( 600 ); } 75return page ; 76} 77export const shot = ( page , name ) => page . screenshot ({ path :join ( SHOTS , ` ${ name } .png` ) }); 78export const sizes = { wide :[ 1280 , 860 ], narrow :[ 390 , 800 ] }; 79 80export const cases = {}; 81const pages = []; 82 83/* ------------------------------------------------------------------------------------------------------------------- #4725 */ 84const longReply = Array . from ({ length :70 }, ( _ , i ) => `Paragraph ${ i + 1 } . This is part of a long answer from the assistant that goes on for many screens before it asks to change a file in the project.` ). join ( '\n\n' ); 85const askTool = ( id , state = 'proposed' , file = 'notes.txt' ) => ({ id, name :'write' , args :{ file_path :file }, preview :`write ${ file } \n\na\nb\nc` , effect :'Creates a file.' , scope :'write' , verb :'Create a file' , target :file , state, ask :{ id :'create-file' , params :[ file ], why :'replaces-if-exists' }, live :false }); 86const plainTool = ( id , state = 'proposed' ) => ({ id, name :'bash' , args :{}, preview :'npm install left-pad' , effect :'Runs a command on your computer.' , scope :'shell' , verb :'Run a command' , target :'npm install left-pad' , state}); 87cases . approval = async () => { 88for ( const scheme of [ 'light' , 'dark' ]) for ( const [ sizeName , [ w , h ]] of Object . entries ( sizes )) { 89const tag = ` ${ scheme } - ${ sizeName } ` ; 90const sessions = [ chat ( 's1' , 'Long reply' , [ user ( 'u1' , 'Please write notes.txt' ), reply ( 'a1' , longReply , { tools :[ askTool ( 't1' )] })])]; 91const page = await open ( scheme , w , h , sessions ); 92const dock = page . locator ( '.approvaldock' ); 93await dock . waitFor ({ timeout :15000 }); 94const view = page . viewportSize (); 95const inView = async sel => { const b = await page . locator ( sel ). first (). boundingBox (); return !! b && b . y >= 0 && b . y + b . height <= view . height + 1 && b . x >= 0 && b . x + b . width <= view . width + 1 ; }; 96check ( await page . locator ( '.askcard' ). count () === 1 , ` ${ tag } : one Approve/Deny card on the page` ); 97check ( await page . getByRole ( 'button' , { name :'Approve' }). count () === 1 && await page . getByRole ( 'button' , { name :'Deny' }). count () === 1 , ` ${ tag } : one Approve and one Deny` ); 98check ( await inView ( '.approvaldock' ), ` ${ tag } : the card is inside the window at the end of the reply` ); 99const scroller = page . locator ( '.main__body.chat' ); 100const atEnd = () => scroller . evaluate ( el => el . scrollHeight - el . scrollTop - el . clientHeight ); 101check ( await atEnd () < 4 , ` ${ tag } : the reply is still scrolled to its end` , String ( await atEnd ())); 102check ( await page . locator ( '.approval-wait' ). count () === 1 , ` ${ tag } : the reply says it waits for an answer` ); 103await shot ( page , `4725- ${ tag } -end` ); 104await scroller . evaluate ( el => { el . scrollTop = 0 ; }); 105await page . waitForTimeout ( 300 ); 106check ( await inView ( '.approvaldock' ), ` ${ tag } : the card stays in the window when the reader is at the top` ); 107const composerTop = await page . locator ( '.composer .st-composer' ). boundingBox (); 108const dockBox = await dock . boundingBox (); 109check ( dockBox . y + dockBox . height <= composerTop . y , ` ${ tag } : the card sits above the message box` ); 110check (( await page . evaluate (() => document . documentElement . scrollWidth )) <= w , ` ${ tag } : no sideways scroll` ); 111await shot ( page , `4725- ${ tag } -top` ); 112await page . getByRole ( 'button' , { name :'Approve' }). click (); 113await page . waitForTimeout ( 500 ); 114check ( await page . locator ( '.approvaldock' ). count () === 0 , ` ${ tag } : the card goes away after Approve` ); 115check ( await page . locator ( '.approval-wait' ). count () === 0 , ` ${ tag } : and so does the waiting line` ); 116check ( page . problems . length === 0 , ` ${ tag } : no page error` , page . problems . join ( '; ' )); 117await page . context (). close (); 118} 119// Two waiting at once, one in each card style; Deny works from the dock. 120const sessions = [ chat ( 's1' , 'Two waiting' , [ user ( 'u1' , 'Do two things' ), reply ( 'a1' , longReply . slice ( 0 , 1500 ), { tools :[ askTool ( 't1' ), plainTool ( 't2' )] })])]; 121const page = await open ( 'light' , 1280 , 860 , sessions ); 122await page . locator ( '.approvaldock' ). waitFor ({ timeout :15000 }); 123check ( await page . locator ( '.approvaldock > section' ). count () === 2 , 'two waiting: both cards are in the dock' ); 124await shot ( page , '4725-two-waiting' ); 125await page . getByRole ( 'button' , { name :'Deny' }). first (). click (); 126await page . waitForTimeout ( 400 ); 127check ( await page . locator ( '.approvaldock > section' ). count () === 1 , 'two waiting: Deny on the first leaves the second' ); 128await page . context (). close (); 129}; 130 131/* ------------------------------------------------------------------------------------------------------------------- #4748 */ 132const codeReply = 'Here is a command.\n\n```bash\nnpm install left-pad\n```\n\nThat is all.' ; 133cases . copy = async () => { 134for ( const scheme of [ 'light' , 'dark' ]) for ( const [ sizeName , [ w , h ]] of Object . entries ( sizes )) { 135const tag = ` ${ scheme } - ${ sizeName } ` ; 136const sessions = [ chat ( 's1' , 'Copy' , [ user ( 'u1' , 'Show me a command' ), reply ( 'a1' , codeReply ), user ( 'u2' , 'Thanks' ), reply ( 'a2' , 'You are welcome. Second reply.' )])]; 137const page = await open ( scheme , w , h , sessions ); 138await page . locator ( '.st-msg--assistant' ). last (). waitFor ({ timeout :15000 }); 139const flag = async loc => loc . evaluate ( el => ({ copied :el . hasAttribute ( 'data-copied' ), icon :el . querySelector ( 'use' )?. getAttribute ( 'href' ) ?? '' })); 140const read = () => page . evaluate (() => navigator . clipboard . readText ()); 141// The last reply's copy button (an icon in the action row). 142const copyResponse = page . getByRole ( 'button' , { name :'Copy response' }); 143await copyResponse . last (). click (); 144await page . mouse . move ( 2 , 2 ); 145await page . waitForTimeout ( 250 ); 146let f = await flag ( copyResponse . last ()); 147check ( f . copied && f . icon . endsWith ( 'i-check' ), ` ${ tag } : Copy response turns into a check mark` , JSON . stringify ( f )); 148check (( await read ()) === 'You are welcome. Second reply.' , ` ${ tag } : the reply is on the clipboard` ); 149const row = page . locator ( '.st-msg--assistant' ). last (). locator ( '.st-msg__actions' ); 150check ( await row . evaluate ( el => getComputedStyle ( el ). opacity ) === '1' , ` ${ tag } : the action row stays visible while it says so, mouse away` ); 151check ( / Copied / . test ( await page . locator ( '.st-msg--assistant' ). last (). locator ( '[role=status]' ). first (). innerText ()), ` ${ tag } : a screen reader hears Copied` ); 152await shot ( page , `4748- ${ tag } -reply` ); 153await page . waitForTimeout ( 2200 ); 154f = await flag ( copyResponse . last ()); 155check ( ! f . copied && f . icon . endsWith ( 'i-copy' ), ` ${ tag } : after about two seconds it is a Copy button again` , JSON . stringify ( f )); 156// The code block. 157const code = page . locator ( '.st-code__head' ). getByRole ( 'button' , { name :'Copy code' }); 158await code . click (); 159await page . waitForTimeout ( 250 ); 160f = await flag ( code ); 161check ( f . copied && f . icon . endsWith ( 'i-check' ), ` ${ tag } : the code block's Copy turns into a check mark` , JSON . stringify ( f )); 162check (( await read ()) === 'npm install left-pad' , ` ${ tag } : the code is on the clipboard` ); 163await shot ( page , `4748- ${ tag } -code` ); 164await page . waitForTimeout ( 2200 ); 165// The menu item of an earlier reply: says Copied, then the menu closes. 166await page . locator ( '.st-msg--assistant' ). first (). hover (); 167await page . locator ( '.st-msg--assistant' ). first (). getByRole ( 'button' , { name :'More response actions' }). click (); 168const item = page . getByRole ( 'menuitem' , { name :'Copy response' }); 169await item . click (); 170await page . waitForTimeout ( 250 ); 171check ( / Copied / . test ( await page . locator ( '.menu [data-copied]' ). innerText ()), ` ${ tag } : the menu item says Copied` ); 172check (( await read ()). startsWith ( 'Here is a command' ), ` ${ tag } : the earlier reply is on the clipboard` ); 173await shot ( page , `4748- ${ tag } -menu` ); 174await page . waitForTimeout ( 1300 ); 175check ( await page . locator ( '.menu' ). count () === 0 , ` ${ tag } : and the menu closes by itself` ); 176check ( page . problems . length === 0 , ` ${ tag } : no page error` , page . problems . join ( '; ' )); 177await page . context (). close (); 178} 179// A refused clipboard: nothing says Copied on the button, and the person is told in a toast. 180{ 181const page = await open ( 'light' , 1280 , 860 , [ chat ( 's1' , 'Refused' , [ user ( 'u1' , 'Hi' ), reply ( 'a1' , 'Hello there.' )])]); 182await page . locator ( '.st-msg--assistant' ). last (). waitFor ({ timeout :15000 }); 183await page . evaluate (() => { Object . defineProperty ( navigator , 'clipboard' , { value :{ writeText :() => Promise . reject ( new Error ( 'denied' )) }, configurable :true }); document . execCommand = () => false ; }); 184const b = page . getByRole ( 'button' , { name :'Copy response' }). last (); 185await b . click (); 186await page . waitForTimeout ( 400 ); 187check ( await b . evaluate ( el => ! el . hasAttribute ( 'data-copied' )), 'refused clipboard: the button does not claim success' ); 188check ( / Couldn.t copy / . test ( await page . locator ( '.st-toast' ). first (). innerText ()), 'refused clipboard: a toast says it did not work' ); 189await page . context (). close (); 190} 191// The Serving screen: the address and the request template. 192for ( const scheme of [ 'light' , 'dark' ]) { 193const page = await open ( scheme , 1280 , 860 , [ chat ( 's1' , 'Serving' , [ user ( 'u1' , 'Hi' ), reply ( 'a1' , 'Hello there.' )])], { hash :'#/serving' }); 194const c = page . getByRole ( 'button' , { name :'Copy API base URL' }); 195await c . waitFor ({ timeout :15000 }); 196await c . click (); 197await page . waitForTimeout ( 250 ); 198check ( await c . evaluate ( el => el . hasAttribute ( 'data-copied' ) && ( el . querySelector ( 'use' )?. getAttribute ( 'href' ) ?? '' ). endsWith ( 'i-check' )), ` ${ scheme } : Serving, Copy API base URL turns into a check mark` ); 199check ( / ^http:\/\/127\.0\.0\.1:\d + \/v1$ / . test ( await page . evaluate (() => navigator . clipboard . readText ())), ` ${ scheme } : Serving, the address is on the clipboard` ); 200await shot ( page , `4748-serving- ${ scheme } ` ); 201await page . getByRole ( 'button' , { name :'Connection guide' }). click (); 202const t = page . getByRole ( 'button' , { name :'Copy request template' }); 203await t . click (); 204await page . waitForTimeout ( 250 ); 205check ( await t . evaluate ( el => el . hasAttribute ( 'data-copied' )), ` ${ scheme } : Serving, Copy request template turns into a check mark` ); 206check (( await page . evaluate (() => navigator . clipboard . readText ())). startsWith ( 'curl http' ), ` ${ scheme } : Serving, the template is on the clipboard` ); 207await page . context (). close (); 208} 209}; 210 211/* ------------------------------------------------------------------------------------------------------------------- #4804 */ 212let tuneHostInfo = null ; 213async function tuneHost () { 214if ( tuneHostInfo ) return tuneHostInfo ; 215const tport = await freePort (); 216const proc = spawn ( process . execPath , [ join ( HOST_DIR , 'tests/fixtures/tune-ui-host.mjs' )], { cwd :HOST_DIR , env :{ ...process . env , TUNE_UI_PORT :String ( tport ), TUNE_UPSTREAM :base , TUNE_SHOT_DIR :SHOTS }, stdio :'ignore' , windowsHide :true }); 217const origin = `http://127.0.0.1: ${ tport } ` ; 218for ( let i = 0 ; i < 100 ; i ++ ) { try { if (( await fetch ( ` ${ origin } /api/native` )). ok ) break ; } catch { /* starting */ } await sleep ( 200 ); } 219tuneHostInfo = { origin, proc, mode :m => fetch ( ` ${ origin } /__fixture/status-mode` , { method :'POST' , headers :{ 'content-type' :'application/json' }, body :JSON . stringify ({ mode :m }) }) }; 220return tuneHostInfo ; 221} 222cases . tune = async () => { 223const t = await tuneHost (); 224const sessions = [ chat ( 's1' , 'Tune' , [ user ( 'u1' , 'Hi' ), reply ( 'a1' , 'Hello there.' )])]; 225const openDialog = async ( scheme , w , h , mode , inject = false ) => { 226await t . mode ( mode ); 227const page = await open ( scheme , w , h , sessions , { hash :'#/models' , origin :t . origin }); 228if ( inject ) await page . route ( / \/api\/native ( \?. * ) ? $ / , async route => { 229if ( ! page . injectJob ) return route . continue (); 230const r = await route . fetch (); const j = await r . json (); 231j . jobs = [ ...( j . jobs ?? []), { id :'job-x' , kind :'download' , state :'running' , startedAt :new Date (). toISOString (), summary :'Downloading the model' , error :null , result :null , progress :{ text :'Downloading' , percent :12 } }]; 232return route . fulfill ({ response :r , json :j }); 233}); 234const tune = page . getByRole ( 'button' , { name :'Tune model' }); 235await tune . waitFor ({ timeout :20000 }); 236for ( let i = 0 ; i < 40 && await tune . isDisabled (); i ++ ) await page . waitForTimeout ( 250 ); 237await tune . click (); 238await page . getByRole ( 'dialog' ). waitFor ({ timeout :10000 }); 239return page ; 240}; 241const start = page => page . getByRole ( 'button' , { name :'Start tuning' }); 242// The sentence must be on screen without scrolling the dialog, beside the button (above it when the window is narrow). 243const seen = async ( page , w , h ) => { 244const s = await page . locator ( '.tune-why' ). boundingBox (), b = await start ( page ). boundingBox (); 245return !! s && !! b && s . y >= 0 && s . y + s . height <= h && s . x >= 0 && s . x + s . width <= w && Math . abs (( s . y + s . height / 2 ) - ( b . y + b . height / 2 )) < 110 ; 246}; 247for ( const scheme of [ 'light' , 'dark' ]) for ( const [ sizeName , [ w , h ]] of Object . entries ( sizes )) { 248const tag = ` ${ scheme } - ${ sizeName } ` ; 249// 1. The saved tunings are still being read: greyed out, with the reason, and not "No saved tuning". 250let page = await openDialog ( scheme , w , h , 'slow' ); 251await page . waitForTimeout ( 1200 ); 252check ( await start ( page ). isDisabled (), ` ${ tag } : loading: Start tuning is greyed out` ); 253let why = await page . locator ( '.tune-why' ). innerText (). catch (() => '' ); 254check ( / still checking this model for saved tunings / . test ( why ), ` ${ tag } : loading: one sentence says why` , why ); 255check ( await page . locator ( '.tune-why' ). count () === 1 , ` ${ tag } : loading: only one such sentence` ); 256check ( ! /No saved tuning for these choices yet / . test ( await page . getByRole ( 'dialog' ). innerText ()), ` ${ tag } : loading: it does not claim there is no saved tuning` ); 257check ( await seen ( page , w , h ), ` ${ tag } : loading: the sentence is on screen next to the button` ); 258await shot ( page , `4804- ${ tag } -loading` ); 259await page . context (). close (); 260// 2. Reading them failed. 261page = await openDialog ( scheme , w , h , 'fail' ); 262await page . waitForTimeout ( 1200 ); 263check ( await start ( page ). isDisabled (), ` ${ tag } : unreadable: Start tuning is greyed out` ); 264why = await page . locator ( '.tune-why' ). innerText (). catch (() => '' ); 265check ( / could not read the tuning details / . test ( why ), ` ${ tag } : unreadable: one sentence says why` , why ); 266check ( await seen ( page , w , h ), ` ${ tag } : unreadable: the sentence is on screen next to the button` ); 267check ( ! /No saved tuning / . test ( await page . getByRole ( 'dialog' ). innerText ()), ` ${ tag } : unreadable: it does not claim there is no saved tuning` ); 268await shot ( page , `4804- ${ tag } -unreadable` ); 269await page . context (). close (); 270// 3. Another operation is running. 271page = await openDialog ( scheme , w , h , 'ok' , true ); 272await page . waitForTimeout ( 800 ); 273check ( await start ( page ). isEnabled () && await page . locator ( '.tune-why' ). count () === 0 , ` ${ tag } : ready: Start tuning works and shows no sentence` ); 274page . injectJob = true ; 275await page . waitForTimeout ( 3500 ); 276check ( await start ( page ). isDisabled (), ` ${ tag } : another operation: Start tuning is greyed out` ); 277why = await page . locator ( '.tune-why' ). innerText (). catch (() => '' ); 278check ( / Finish the current operation first / . test ( why ), ` ${ tag } : another operation: one sentence says why` , why ); 279check (( await page . evaluate (() => document . documentElement . scrollWidth )) <= w , ` ${ tag } : no sideways scroll` ); 280check ( await seen ( page , w , h ), ` ${ tag } : other: the sentence is on screen next to the button` ); 281await shot ( page , `4804- ${ tag } -other` ); 282check ( page . problems . length === 0 , ` ${ tag } : no page error` , page . problems . join ( '; ' )); 283await page . context (). close (); 284} 285}; 286 287/* ------------------------------------------------------------------------------------------------------------------- #4721 */ 288cases . links = async () => { 289const sessions = () => [ chat ( 's1' , 'Links' , [ user ( 'u1' , 'Show links' ), reply ( 'a1' , `Read [the docs](https://example.com/docs) or open [the logo]( ${ base } /icons/sprite.svg).` )])]; 290for ( const scheme of [ 'light' , 'dark' ]) { 291// A browser tab: the browser opens the address in a new tab; a file stays in the side panel. 292let page = await open ( scheme , 1280 , 860 , sessions ()); 293await page . getByRole ( 'link' , { name :'the docs' }). waitFor ({ timeout :15000 }); 294await page . evaluate (() => { window . __opened = []; window . open = ( ...a ) => { window . __opened . push ( a ); return null ; }; }); 295await page . getByRole ( 'link' , { name :'the docs' }). click (); 296await page . waitForTimeout ( 300 ); 297let opened = await page . evaluate (() => window . __opened ); 298check ( JSON . stringify ( opened ) === JSON . stringify ([[ 'https://example.com/docs' , '_blank' , 'noopener,noreferrer' ]]), ` ${ scheme } : a browser tab: a plain click on a web address opens it in a new tab` , JSON . stringify ( opened )); 299check ( await page . locator ( '.artifact-panel' ). count () === 0 , ` ${ scheme } : a browser tab: and no side panel opens` ); 300await page . getByRole ( 'link' , { name :'the logo' }). click (); 301await page . locator ( '.artifact-panel' ). waitFor ({ timeout :8000 }); 302check (( await page . evaluate (() => window . __opened )). length === 1 , ` ${ scheme } : a file link keeps the side panel and opens no tab` ); 303await shot ( page , `4721- ${ scheme } -file` ); 304await page . context (). close (); 305// The app window: the host hands the address to the default browser; window.open is not used. 306const posts = []; 307page = await open ( scheme , 1280 , 860 , sessions (), { before :async p => { 308await p . route ( '**/api/app/mode' , r => r . fulfill ({ json :{ mode :'window' , reason :null , canQuit :true , appUpdate :'unavailable' } })); 309await p . route ( '**/api/artifacts/open' , r => { posts . push ( r . request (). postDataJSON ()); return r . fulfill ({ json :{ ok :true } }); }); 310} }); 311await page . getByRole ( 'link' , { name :'the docs' }). waitFor ({ timeout :15000 }); 312await page . evaluate (() => { window . __opened = []; window . open = ( ...a ) => { window . __opened . push ( a ); return null ; }; }); 313await page . getByRole ( 'link' , { name :'the docs' }). click (); 314await page . waitForTimeout ( 400 ); 315check ( JSON . stringify ( posts ) === JSON . stringify ([{ action :'open' , url :'https://example.com/docs' }]), ` ${ scheme } : the app window: the host is asked to open it in the default browser` , JSON . stringify ( posts )); 316check (( await page . evaluate (() => window . __opened )). length === 0 && await page . locator ( '.artifact-panel' ). count () === 0 , ` ${ scheme } : the app window: nothing else happens` ); 317check ( page . problems . length === 0 , ` ${ scheme } : no page error` , page . problems . join ( '; ' )); 318await page . context (). close (); 319} 320}; 321 322/* ------------------------------------------------------------------------------------------------------------------- #4802 */ 323cases . progress = async () => { 324const t = await tuneHost (); 325await t . mode ( 'ok' ); 326const sessions = [ chat ( 's1' , 'Progress' , [ user ( 'u1' , 'Hi' ), reply ( 'a1' , 'Hello there.' )])]; 327for ( const scheme of [ 'light' , 'dark' ]) for ( const [ sizeName , [ w , h ]] of Object . entries ( sizes )) { 328const tag = ` ${ scheme } - ${ sizeName } ` ; 329const page = await open ( scheme , w , h , sessions , { hash :'#/models' , origin :t . origin }); 330const started = new Date ( Date . now () - ( 3 * 60 + 12 ) * 1000 ). toISOString (); 331await page . route ( / \/api\/native ( \?. * ) ? $ / , async route => { 332const r = await route . fetch (); const j = await r . json (); 333j . jobs = [ ...( j . jobs ?? []), { id :'job-x' , kind :'install' , model :'iq2_xs' , state :'running' , startedAt :started , summary :'Preparing' , error :null , result :{ install :{ step :'6/7' , label :'Preparing the model data for the engine (one time)' , parts :[{ label :'Model files' , done_gb :0.6 , total_gb :0.6 , state :'done' }], download :{ file :'model files' , done_gb :0.6 , total_gb :0.6 , remaining_gb :0 , percent :99 } } }, progress :null }]; 334return route . fulfill ({ response :r , json :j }); 335}); 336await page . reload (); 337const card = page . locator ( '.native-progress' ); 338await card . waitFor ({ timeout :20000 }); 339await page . waitForTimeout ( 1500 ); 340check ( await card . locator ( '.spinner' ). count () === 1 , ` ${ tag } : a spinner shows that it is working` ); 341const alive = () => card . locator ( '.native-progress__alive' ). innerText (); 342const a1 = await alive (); 343check ( / ^Still working for 3m \d + s\. You don't need to do anything\.$ / . test ( a1 ), ` ${ tag } : it says how long and that nothing is needed` , a1 ); 344await page . waitForTimeout ( 2200 ); 345const a2 = await alive (); 346check ( a1 !== a2 , ` ${ tag } : the time keeps counting` , ` ${ a1 } -> ${ a2 } ` ); 347check ( / The buttons below wait until this finishes / . test ( await page . locator ( '.native-wait-note' ). innerText ()), ` ${ tag } : a sentence says why the buttons are greyed out` ); 348const border = await card . evaluate ( el => getComputedStyle ( el ). borderTopColor ); 349const other = await page . locator ( '.st-card:not(.native-progress)' ). first (). evaluate ( el => getComputedStyle ( el ). borderTopColor ); 350check ( border !== other , ` ${ tag } : the card has its own border colour` , ` ${ border } vs ${ other } ` ); 351check (( await page . evaluate (() => document . documentElement . scrollWidth )) <= w , ` ${ tag } : no sideways scroll` ); 352await card . scrollIntoViewIfNeeded (); 353await shot ( page , `4802- ${ tag } ` ); 354check ( page . problems . length === 0 , ` ${ tag } : no page error` , page . problems . join ( '; ' )); 355await page . context (). close (); 356} 357}; 358 359/* ------------------------------------------------------------------------------------------------------------------- #4798 */ 360cases . serving = async () => { 361const sessions = [ chat ( 's1' , 'Serving' , [ user ( 'u1' , 'Hi' ), reply ( 'a1' , 'Hello there.' )])]; 362for ( const scheme of [ 'light' , 'dark' ]) for ( const [ sizeName , [ w , h ]] of Object . entries ( sizes )) { 363const tag = ` ${ scheme } - ${ sizeName } ` ; 364// Sharing off: one address, no extra line. Sharing on: the app's own address and the one for other devices, with one sentence. 365for ( const sharing of [ false , true ]) { 366const page = await open ( scheme , w , h , sessions , { hash :'#/serving' , before :async p => { 367if ( ! sharing ) return ; 368await p . route ( / \/api\/serving$ / , async route => { 369if ( route . request (). method () !== 'GET' ) return route . continue (); 370const r = await route . fetch (); const j = await r . json (); 371return route . fulfill ({ response :r , json :{ ...j , localUrl :'http://127.0.0.1:8079/v1' , baseUrl :'http://100.76.61.73:8080/v1' , sharing :{ active :true , url :'http://100.76.61.73:8080/v1' } } }); 372}); 373} }); 374await page . getByText ( 'API base URL' , { exact :false }). first (). waitFor ({ timeout :15000 }); 375await page . waitForTimeout ( 800 ); 376const text = await page . locator ( '.serving-overview' ). innerText (); 377if ( sharing ) { 378check ( / API base URL on this computer / . test ( text ) && text . includes ( 'http://127.0.0.1:8079/v1' ), ` ${ tag } : sharing on: the app's own address is shown` ); 379check ( / Address for other devices / . test ( text ) && text . includes ( 'http://100.76.61.73:8080/v1' ), ` ${ tag } : sharing on: and the address for other devices` ); 380check ( await page . locator ( '.serving-two-addresses' ). count () === 1 && / its own port / . test ( await page . locator ( '.serving-two-addresses' ). innerText ()), ` ${ tag } : sharing on: one sentence says why they differ` ); 381const t = page . getByRole ( 'button' , { name :'Copy local network URL' }); 382await t . click (); await page . waitForTimeout ( 250 ); 383check (( await page . evaluate (() => navigator . clipboard . readText ())) === 'http://100.76.61.73:8080/v1' , ` ${ tag } : sharing on: the copy button gives the network address` ); 384check (( await page . evaluate (() => document . documentElement . scrollWidth )) <= w , ` ${ tag } : sharing on: no sideways scroll` ); 385await page . locator ( '.serving-overview' ). scrollIntoViewIfNeeded (); 386await shot ( page , `4798- ${ tag } -sharing` ); 387} else { 388check ( ! /Address for other devices / . test ( text ) && await page . locator ( '.serving-two-addresses' ). count () === 0 , ` ${ tag } : sharing off: one address, no extra line` ); 389} 390check ( page . problems . length === 0 , ` ${ tag } : no page error` , page . problems . join ( '; ' )); 391await page . context (). close (); 392} 393} 394}; 395 396/* ------------------------------------------------------------------------------------------------------------------- #4722 */ 397cases . width = async () => { 398const text = '用中文写一段九十字左右的段落,说明本地模型为什么适合处理私人文件,并且不需要把任何内容上传到网络上去,这样可以让人放心。\n\n- 第一条要点同样写得比较长,用来观察列表项在气泡里到底会排到多宽才换行,看看它是否与上面的段落一样。\n- 第二条要点也一样长,看看两条要点是不是排得整齐,不会比段落更宽也不会更窄。\n\nAnd an English paragraph that is long enough to wrap onto at least two lines so that the measure of the prose can be read off it by the test.\n\n1. A numbered point in English that is also long enough to wrap onto a second line in the same bubble as the paragraph above it.\n2. Another numbered point.\n\n| Name | Value |\n| --- | --- |\n| a long cell that is wide | another long cell that is wide too |\n\n```bash\nnpm install a-very-long-package-name another-very-long-package-name yet-another-long-package-name --save-dev --legacy-peer-deps\n```' ; 399for ( const scheme of [ 'light' , 'dark' ]) for ( const [ sizeName , [ w , h ]] of Object . entries ( sizes )) { 400const tag = ` ${ scheme } - ${ sizeName } ` ; 401const page = await open ( scheme , w , h , [ chat ( 's1' , 'Width' , [ user ( 'u1' , 'Write' ), reply ( 'a1' , text )])]); 402await page . locator ( '.st-bubble ul' ). first (). waitFor ({ timeout :15000 }); 403const m = await page . evaluate (() => { 404const b = document . querySelector ( '.st-msg--assistant .st-bubble' ), r = el => Math . round ( el . getBoundingClientRect (). width ); 405return { bubble :r ( b ), p :r ( b . querySelector ( 'p' )), ul :r ( b . querySelector ( 'ul' )), ol :r ( b . querySelector ( 'ol' )), table :r ( b . querySelector ( '.md-table-wrap' )), code :r ( b . querySelector ( '.st-code' )) }; 406}); 407const note = JSON . stringify ( m ); 408if ( w > 700 ) { 409check ( Math . abs ( m . ul - m . p ) <= 2 && Math . abs ( m . ol - m . p ) <= 2 , ` ${ tag } : bullets and numbers have the paragraph's width` , note ); 410check ( m . table > m . p + 20 && m . code > m . p + 20 , ` ${ tag } : the table and the code block keep the full width` , note ); 411} else { 412check ( Math . abs ( m . ul - m . p ) <= 2 && m . p <= m . bubble , ` ${ tag } : narrow window: everything fits the column` , note ); 413} 414check (( await page . evaluate (() => document . documentElement . scrollWidth )) <= w , ` ${ tag } : no sideways scroll` ); 415await shot ( page , `4722- ${ tag } ` ); 416await page . context (). close (); 417} 418}; 419 420/* ------------------------------------------------------------------------------------------------------------------- #3723 */ 421cases . firstrun = async () => { 422const setupStep = dismissed => fetch ( ` ${ base } /api/setup/step` , { method :'POST' , headers :{ 'content-type' :'application/json' }, body :JSON . stringify ({ step :1 , dismissed, flowVersion :2 }) }); 423await setupStep ( false ); 424// A computer set to a language Strata does not have: English. 425const page = await open ( 'light' , 1280 , 860 , null , { hash :'#/setup' , locale :'sv-SE' , keepSetup :true }); 426await page . locator ( '.onboard-language' ). waitFor ({ timeout :20000 }); 427check ( / English / . test ( await page . locator ( '.onboard-language' ). innerText ()), 'Swedish computer: English' ); 428await page . context (). close (); 429// A first start (nothing saved) on a computer set to Chinese opens in Chinese, with a language choice on the first screen. 430for ( const scheme of [ 'light' , 'dark' ]) for ( const [ sizeName , [ w , h ]] of Object . entries ( sizes )) { 431const tag = ` ${ scheme } - ${ sizeName } ` ; 432const page = await open ( scheme , w , h , null , { hash :'#/setup' , locale :'zh-CN' , keepSetup :true }); 433await page . locator ( '.onboard-language' ). waitFor ({ timeout :20000 }); 434await page . waitForTimeout ( 500 ); 435const pick = page . locator ( '.onboard-language [role=combobox], .onboard-language button' ). first (); 436const shown = await pick . innerText (); 437check ( / 中文 / . test ( shown ), ` ${ tag } : a computer set to Chinese starts in Chinese` , shown ); 438check ( / [ \u4e00 - \u9fff ] / . test ( await page . locator ( '.guided-onboarding h1' ). first (). innerText ()), ` ${ tag } : the first screen is in Chinese` ); 439const box = await page . locator ( '.onboard-language' ). boundingBox (); 440check ( !! box && box . x >= 0 && box . x + box . width <= w && box . y >= 0 , ` ${ tag } : the choice is on screen` , JSON . stringify ( box )); 441const brand = await page . locator ( '.guided-onboarding .onboard-header .brand' ). first (). boundingBox (); 442check ( ! brand || box . x >= brand . x + brand . width - 1 || box . x + box . width <= brand . x + 1 || box . y >= brand . y + brand . height || box . y + box . height <= brand . y , ` ${ tag } : the choice does not cover the logo` , JSON . stringify ({ brand, box})); 443await shot ( page , `3723- ${ tag } -first-zh` ); 444// Choosing German changes the screen at once, and it is kept. 445await pick . click (); 446await page . getByRole ( 'option' , { name :'Deutsch' }). click (); 447await page . waitForTimeout ( 500 ); 448check ( / [ A - Za - zäöü ] / . test ( await page . locator ( '.guided-onboarding h1' ). first (). innerText ()) && ! / [ \u4e00 - \u9fff ] / . test ( await page . locator ( '.guided-onboarding h1' ). first (). innerText ()), ` ${ tag } : choosing Deutsch changes the first screen` ); 449await shot ( page , `3723- ${ tag } -first-de` ); 450await page . reload (); 451await page . locator ( '.onboard-language' ). waitFor ({ timeout :20000 }); 452check ( / Deutsch / . test ( await page . locator ( '.onboard-language' ). innerText ()), ` ${ tag } : the choice is kept after a restart, whatever the computer says` ); 453check ( page . problems . length === 0 , ` ${ tag } : no page error` , page . problems . join ( '; ' )); 454await page . context (). close (); 455} 456await setupStep ( true ); 457}; 458 459cases . kv = async () => { 460const t = await tuneHost (); 461await t . mode ( 'ok' ); 462const sessions = [ chat ( 's1' , 'KV' , [ user ( 'u1' , 'Hi' ), reply ( 'a1' , 'Hello there.' )])]; 463for ( const scheme of [ 'light' , 'dark' ]) for ( const [ sizeName , [ w , h ]] of Object . entries ( sizes )) { 464const tag = ` ${ scheme } - ${ sizeName } ` ; 465const page = await open ( scheme , w , h , sessions , { hash :'#/models' , origin :t . origin }); 466await page . route ( / \/api\/native ( \?. * ) ? $ / , async route => { 467const r = await route . fetch (); const j = await r . json (); 468j . jobs = [ ...( j . jobs ?? []), { id :'job-f' , kind :'load' , model :'iq2_xs' , state :'error' , startedAt :new Date (). toISOString (), summary :'Load failed' , error :"server_exited (exit code 1): EngineDied: the engine exited before it was ready | the engine process ended: exit code 1: \nthe engine log's last lines:\n strata generate: expert cache auto: 1.92 GiB free, 2048 MiB reserved -> 0 slots\n strata generate: no VRAM is left for the expert cache: it needs at least 332 slots (737 MiB), about 1000 MiB more than this card has free." , result :null , progress :null }]; 469return route . fulfill ({ response :r , json :j }); 470}); 471await page . reload (); 472const expert = page . getByRole ( 'button' , { name :'Expert mode' }); 473await expert . waitFor ({ timeout :20000 }); 474await page . waitForTimeout ( 1500 ); 475await expert . click (); 476const sel = page . getByRole ( 'combobox' , { name :'Native KV format' }); 477if ( ! await sel . isVisible (). catch (() => false )) { await page . waitForTimeout ( 800 ); if ( ! await sel . isVisible (). catch (() => false )) await page . getByRole ( 'button' , { name :/ expert mode / i }). first (). click (); } 478await sel . waitFor ({ timeout :10000 }); 479const hint = page . locator ( '.native-kv-hint' ); 480check ( / INT8 is the standard / . test ( await hint . innerText ()), ` ${ tag } : Context memory: one line says what the chosen format is` ); 481await sel . click (); 482check ( await page . getByRole ( 'option' ). count () === 3 , ` ${ tag } : Context memory: three options` ); 483const titles = await page . locator ( '.select__option-label' ). evaluateAll ( els => els . map ( e => e . getAttribute ( 'title' ))); 484check ( titles . length === 3 && titles . every ( x => x && x . length > 20 ), ` ${ tag } : Context memory: each option carries its line` , JSON . stringify ( titles )); 485await page . getByRole ( 'option' , { name :'Q4' }). click (); 486await page . waitForTimeout ( 300 ); 487check ( / Q4 uses about half the memory / . test ( await hint . innerText ()), ` ${ tag } : Context memory: the line follows the choice` ); 488await hint . scrollIntoViewIfNeeded (); 489await shot ( page , `3723- ${ tag } -kv` ); 490const notice = page . locator ( '.error-notice' ); 491await notice . first (). waitFor ({ timeout :10000 }); 492const said = await notice . first (). innerText (); 493check ( / did not fit in your graphics card.s memory / . test ( said ) && / Context memory to Q4 / . test ( said ), ` ${ tag } : a start that ran out of graphics memory says so in plain words` , said . replace ( / \n +/ g , ' | ' ). slice ( 0 , 200 )); 494await notice . first (). scrollIntoViewIfNeeded (); 495await shot ( page , `3723- ${ tag } -vram` ); 496check (( await page . evaluate (() => document . documentElement . scrollWidth )) <= w , ` ${ tag } : no sideways scroll` ); 497check ( page . problems . length === 0 , ` ${ tag } : no page error` , page . problems . join ( '; ' )); 498await page . context (). close (); 499} 500}; 501 502/* ------------------------------------------------------------------------------------------------------------------- #4749 */ 503cases . helper = async () => { 504const agents = [ 505{ id :'child-1' , name :'Check the tests' , description :'All 12 tests pass.' , status :'completed' , durationMs :42000 , tokens :1800 , updatedAt :Date . now () }, 506{ id :'child-2' , name :'Write the notes' , description :'Could not write notes.txt' , status :'failed' , durationMs :9000 , tokens :400 , updatedAt :Date . now () }, 507]; 508for ( const scheme of [ 'light' , 'dark' ]) for ( const [ sizeName , [ w , h ]] of Object . entries ( sizes )) { 509const tag = ` ${ scheme } - ${ sizeName } ` ; 510const sessions = [{ ...chat ( 's1' , 'Helpers' , [ user ( 'u1' , 'Do two things' ), reply ( 'a1' , 'Both helpers are on it.' )]), agents}]; 511const posts = []; let refuse = false ; 512const page = await open ( scheme , w , h , sessions , { before :async p => { 513await p . route ( '**/api/chat/helper' , async r => { posts . push ( r . request (). postDataJSON ()); if ( refuse ) return r . fulfill ({ status :409 , json :{ error :'This helper cannot take a message any more. Ask the assistant in the chat to start a new one.' } }); return r . fulfill ({ json :{ ok :true , messageId :'m1' } }); }); 514} }); 515await page . getByRole ( 'button' , { name :/ Subagents / }). first (). click (); 516const rows = page . locator ( '.subagent-row' ); 517await rows . first (). waitFor ({ timeout :15000 }); 518// The finished helper: queue. 519await rows . nth ( 0 ). getByRole ( 'button' , { name :'Message this helper' }). click (); 520const input = rows . nth ( 0 ). getByRole ( 'textbox' , { name :'Message to Check the tests' }); 521await input . fill ( 'use ISO dates in the file you just wrote' ); 522await shot ( page , `4749- ${ tag } -writing` ); 523await input . press ( 'Enter' ); 524await rows . nth ( 0 ). getByRole ( 'status' ). waitFor ({ timeout :5000 }); 525check ( JSON . stringify ( posts [ 0 ]) === JSON . stringify ({ sessionId :'s1' , helperId :'child-1' , message :'use ISO dates in the file you just wrote' , delivery :'queue' }), ` ${ tag } : a finished helper gets the message as a new turn (queue)` , JSON . stringify ( posts [ 0 ])); 526check ( / Sent to Check the tests\. / . test ( await rows . nth ( 0 ). innerText ()) && await input . inputValue () === '' , ` ${ tag } : the row says it was sent and the box is empty again` ); 527// A second helper (a failed one is listed too). 528await rows . nth ( 1 ). getByRole ( 'button' , { name :'Message this helper' }). click (); 529await rows . nth ( 1 ). getByRole ( 'textbox' ). fill ( 'also add the date' ); 530await rows . nth ( 1 ). getByRole ( 'button' , { name :'Send' }). click (); 531await rows . nth ( 1 ). getByRole ( 'status' ). waitFor ({ timeout :5000 }); 532check ( posts [ 1 ]?. delivery === 'queue' && posts [ 1 ]?. helperId === 'child-2' , ` ${ tag } : the message goes to the helper that was chosen` , JSON . stringify ( posts [ 1 ])); 533// A refusal says so in plain words. 534refuse = true ; 535await rows . nth ( 0 ). getByRole ( 'textbox' ). fill ( 'one more thing' ); 536await rows . nth ( 0 ). getByRole ( 'button' , { name :'Send' }). click (); 537await rows . nth ( 0 ). getByRole ( 'alert' ). waitFor ({ timeout :5000 }); 538check ( / cannot take a message any more / . test ( await rows . nth ( 0 ). getByRole ( 'alert' ). innerText ()), ` ${ tag } : a refused message says why in plain words` ); 539check (( await page . evaluate (() => document . documentElement . scrollWidth )) <= w , ` ${ tag } : no sideways scroll` ); 540await shot ( page , `4749- ${ tag } -sent` ); 541check ( page . problems . length === 0 , ` ${ tag } : no page error` , page . problems . join ( '; ' )); 542await page . context (). close (); 543} 544}; 545 546/* ------------------------------------------------------------------------------------------------------------------- #4783 */ 547cases . busy = async () => { 548const fresh = ( scheme , w , h , whileBusy ) => open ( scheme , w , h , [ chat ( 's1' , 'Busy' , [])], { prefs :whileBusy ?{ whileBusy} :{} }); 549const send = async ( page , text ) => { await page . locator ( 'textarea' ). first (). fill ( text ); await page . keyboard . press ( 'Enter' ); }; 550const lastReply = page => page . locator ( '.st-msg--assistant .st-bubble' ). last (); 551for ( const scheme of [ 'light' , 'dark' ]) { 552const w = 1280 , h = 860 , tag = scheme ; 553// Wait (the default): Enter while it answers sends nothing, the message stays in the box, and a note says why. 554let page = await fresh ( scheme , w , h , null ); 555await send ( page , 'SCRIPT:slow 80' ); 556await page . locator ( '.st-msg--assistant' ). first (). waitFor ({ timeout :15000 }); 557await page . locator ( 'textarea' ). first (). fill ( 'my second message' ); 558await page . keyboard . press ( 'Enter' ); 559await page . waitForTimeout ( 600 ); 560check ( await page . locator ( 'textarea' ). first (). inputValue () === 'my second message' , ` ${ tag } : Wait: the message stays in the box` ); 561check ( await page . locator ( '.parked' ). count () === 0 , ` ${ tag } : Wait: nothing is parked` ); 562await page . getByText ( 'The assistant is still answering' ). first (). waitFor ({ timeout :4000 }). catch (() => {}); 563check ( await page . getByText ( 'The assistant is still answering' ). count () > 0 , ` ${ tag } : Wait: a note says the assistant is still answering` ); 564await page . context (). close (); 565// Send after: it waits (shown), and goes when the answer is done, after the whole first answer. 566page = await fresh ( scheme , w , h , 'queue' ); 567await send ( page , 'SCRIPT:slow 80' ); 568await page . locator ( '.st-msg--assistant' ). first (). waitFor ({ timeout :15000 }); 569await page . locator ( 'textarea' ). first (). fill ( 'SCRIPT:echo the second answer' ); 570check ( / Enter sends it when the answer is done / . test ( await page . locator ( '.composer__busy-hint' ). innerText ()), ` ${ tag } : Send after: the hint says what Enter will do` ); 571await page . keyboard . press ( 'Enter' ); 572await page . locator ( '.parked' ). waitFor ({ timeout :3000 }); 573check ( / Waiting to send / . test ( await page . locator ( '.parked' ). innerText ()) && / second answer / . test ( await page . locator ( '.parked' ). innerText ()), ` ${ tag } : Send after: the waiting message is shown` ); 574if ( scheme === 'light' ) await shot ( page , `4783- ${ tag } -waiting` ); 575await page . locator ( '.st-msg--assistant' ). nth ( 1 ). waitFor ({ timeout :30000 }); 576await page . waitForFunction (() => document . querySelectorAll ( '.parked' ). length === 0 , null , { timeout :15000 }); 577const firstText = await page . locator ( '.st-msg--assistant .st-bubble' ). first (). innerText (); 578check ( / w79 / . test ( firstText ), ` ${ tag } : Send after: the first answer was written to its end` , firstText . slice ( - 30 )); 579check ( / the second answer / . test ( await lastReply ( page ). innerText ()), ` ${ tag } : Send after: then the second message was answered` ); 580await page . context (). close (); 581// Interrupt: the answer stops where it is, what is written stays, and the message goes at once. 582page = await fresh ( scheme , w , h , 'interject' ); 583await send ( page , 'SCRIPT:slow 600' ); 584await page . locator ( '.st-msg--assistant' ). first (). waitFor ({ timeout :15000 }); 585await page . waitForTimeout ( 800 ); 586await page . locator ( 'textarea' ). first (). fill ( 'SCRIPT:echo interrupted and answered' ); 587check ( / Enter stops the answer here and sends it now / . test ( await page . locator ( '.composer__busy-hint' ). innerText ()), ` ${ tag } : Interrupt: the hint says what Enter will do` ); 588await page . keyboard . press ( 'Enter' ); 589const t0 = Date . now (); 590await page . locator ( '.st-msg--assistant' ). nth ( 1 ). waitFor ({ timeout :30000 }); 591check ( Date . now () - t0 < 12000 , ` ${ tag } : Interrupt: the new message was answered long before the first answer would have ended` , ` ${ Date . now () - t0 } ms` ); 592const cut = await page . locator ( '.st-msg--assistant .st-bubble' ). first (). innerText (); 593check ( cut . includes ( 'w0' ) && ! cut . includes ( 'w599' ), ` ${ tag } : Interrupt: the first answer stopped where it was and stays` , ` ${ cut . length } characters` ); 594await page . waitForFunction (() => / interrupted and answered / . test ([ ...document . querySelectorAll ( '.st-msg--assistant .st-bubble' )]. at ( - 1 )?. innerText ?? '' ), null , { timeout :15000 }). catch (() => {}); 595check ( / interrupted and answered / . test ( await lastReply ( page ). innerText ()), ` ${ tag } : Interrupt: the second message was answered` ); 596if ( scheme === 'light' ) await shot ( page , `4783- ${ tag } -interrupted` ); 597check ( page . problems . length === 0 , ` ${ tag } : no page error` , page . problems . join ( '; ' )); 598await page . context (). close (); 599} 600}; 601 602/* ------------------------------------------------------------------------------------------------------------------- #4785 */ 603cases . quote = async () => { 604const long = 'First point: local models keep your files on your own computer. Second point: nothing has to be uploaded to a service. Third point: you can work without a network connection.' ; 605for ( const scheme of [ 'light' , 'dark' ]) for ( const [ sizeName , [ w , h ]] of Object . entries ( sizes )) { 606const tag = ` ${ scheme } - ${ sizeName } ` ; 607const page = await open ( scheme , w , h , [ chat ( 's1' , 'Quote' , [ user ( 'u1' , 'Why run a model locally?' ), reply ( 'a1' , long ), user ( 'u2' , 'Thanks, one more question' ), reply ( 'a2' , 'Ask away.' )])]); 608await page . locator ( '.st-msg--assistant' ). first (). waitFor ({ timeout :15000 }); 609// A whole turn, from the message menu. 610await page . locator ( '.st-msg--assistant' ). first (). hover (); 611await page . locator ( '.st-msg--assistant' ). first (). getByRole ( 'button' , { name :'More response actions' }). click (); 612await page . getByRole ( 'menuitem' , { name :'Quote' }). click (); 613await page . locator ( '.quote' ). first (). waitFor ({ timeout :5000 }); 614check ( / Quoting the assistant / . test ( await page . locator ( '.quote' ). first (). innerText ()) && / First point / . test ( await page . locator ( '.quote' ). first (). innerText ()), ` ${ tag } : Quote in the message menu puts the turn above the box` ); 615// Just a passage: select the second sentence and quote it. 616await page . evaluate (() => { 617const p = document . querySelector ( '.st-msg--assistant .st-bubble p' ); 618const node = p . firstChild ; const at = node . textContent . indexOf ( 'Second point' ); const end = node . textContent . indexOf ( 'Third point' ); 619const r = document . createRange (); r . setStart ( node , at ); r . setEnd ( node , end ); 620const s = window . getSelection (); s . removeAllRanges (); s . addRange ( r ); 621}); 622await page . locator ( '.quote-selection' ). waitFor ({ timeout :5000 }); 623const sbox = await page . locator ( '.quote-selection' ). boundingBox (); 624check ( !! sbox && sbox . x >= 0 && sbox . y >= 0 && sbox . x + sbox . width <= w , ` ${ tag } : a Quote button appears by the selected words, on screen` , JSON . stringify ( sbox )); 625await page . locator ( '.quote-selection' ). click (); 626check ( await page . locator ( '.quote' ). count () === 2 && / ^Second point: nothing has to be uploaded to a service\.$ / . test (( await page . locator ( '.quote .quote__text' ). nth ( 1 ). innerText ()). trim ()), ` ${ tag } : the second quote is just the selected passage, listed after the first` ); 627check ( await page . locator ( '.quote-selection' ). count () === 0 , ` ${ tag } : the button goes away` ); 628await shot ( page , `4785- ${ tag } -quotes` ); 629// Remove one, quote it again, jump to the message. 630await page . locator ( '.quote' ). first (). getByRole ( 'button' , { name :'Remove this quote' }). click (); 631check ( await page . locator ( '.quote' ). count () === 1 && / Second point / . test ( await page . locator ( '.quote' ). first (). innerText ()), ` ${ tag } : one quote can be removed without touching the others` ); 632await page . locator ( '.quote__body' ). first (). click (); 633await page . waitForTimeout ( 400 ); 634// Send an answer: the model gets the fixed form, the transcript shows the quote apart from the reply. 635await page . locator ( 'textarea' ). first (). fill ( 'SCRIPT:echo thanks for the quote' ); 636await page . keyboard . press ( 'Enter' ); 637await page . locator ( '.sent-quote' ). first (). waitFor ({ timeout :15000 }); 638await page . waitForTimeout ( 300 ); 639const sent = await page . locator ( '.st-msg--user' ). last (). innerText (); 640check ( / Second point: nothing has to be uploaded / . test ( sent ) && / SCRIPT:echo thanks for the quote / . test ( sent ) && ! /Quoting: / . test ( sent ) && ! /「 / . test ( sent ), ` ${ tag } : the sent message shows the quote apart from the reply, without the markup` , sent . replace ( / \n +/ g , ' | ' ). slice ( 0 , 160 )); 641const got = worker . requests . at ( - 1 )?. raw ?? '' ; 642check ( got . includes ( 'Quoting:\\n「Second point: nothing has to be uploaded to a service.」\\n→ Reply: SCRIPT:echo thanks for the quote' ), ` ${ tag } : the model receives the quote in its fixed form` , got . slice ( - 220 )); 643check ( await page . locator ( '.quote' ). count () === 0 , ` ${ tag } : the quotes are cleared after sending` ); 644await page . locator ( '.sent-quote' ). first (). click (); 645check ( await page . locator ( '.sent-quotes[data-open]' ). count () === 1 , ` ${ tag } : a click opens the rest of a sent quote` ); 646await shot ( page , `4785- ${ tag } -sent` ); 647check (( await page . evaluate (() => document . documentElement . scrollWidth )) <= w , ` ${ tag } : no sideways scroll` ); 648check ( page . problems . length === 0 , ` ${ tag } : no page error` , page . problems . join ( '; ' )); 649await page . context (). close (); 650} 651}; 652 653/* ------------------------------------------------------------------------------------------------------------------- #4244 */ 654cases . ask = async () => { 655const t = await tuneHost (); 656await t . mode ( 'ok' ); 657const asked = () => fetch ( ` ${ t . origin } /__fixture/asked` ). then ( r => r . json ()); 658await fetch ( ` ${ t . origin } /__fixture/ask` , { method :'POST' , headers :{ 'content-type' :'application/json' }, body :JSON . stringify ({ on :true }) }); 659for ( const scheme of [ 'light' , 'dark' ]) for ( const [ sizeName , [ w , h ]] of Object . entries ( sizes )) { 660const tag = ` ${ scheme } - ${ sizeName } ` ; 661const before = ( await asked ()). length ; 662const page = await open ( scheme , w , h , [ chat ( 's1' , 'Ask' , [])], { origin :t . origin }); 663await page . locator ( 'textarea' ). first (). fill ( 'Build me a page' ); 664await page . keyboard . press ( 'Enter' ); 665const card = page . locator ( '.askq' ); 666await card . waitFor ({ timeout :15000 }); 667const text = await card . innerText (); 668check ( / Which colour should the page be\? / . test ( text ) && / Which extras do you want\? / . test ( text ) && / Warm and strong / . test ( text ) && / It sets the whole theme / . test ( text ), ` ${ tag } : the question, its detail and the option descriptions are shown` ); 669check ( await page . locator ( '.askcard' ). count () === 1 && await page . locator ( '.approvaldock' ). count () === 1 , ` ${ tag } : it is one card in the dock above the box` ); 670const send = page . getByRole ( 'button' , { name :'Send answer' }); 671check ( await send . isDisabled (), ` ${ tag } : Send answer waits until every question has an answer` ); 672await page . getByRole ( 'radio' , { name :/ Red / }). click (); 673await page . getByRole ( 'radio' , { name :/ Blue / }). click (); 674check ( await page . getByRole ( 'radio' , { name :/ Red / }). getAttribute ( 'aria-checked' ) === 'false' && await page . getByRole ( 'radio' , { name :/ Blue / }). getAttribute ( 'aria-checked' ) === 'true' , ` ${ tag } : a single-select question takes one choice` ); 675await page . getByRole ( 'checkbox' , { name :'Dark mode' }). click (); 676await page . getByRole ( 'checkbox' , { name :'Animations' }). click (); 677check ( await send . isEnabled (), ` ${ tag } : Send answer works once every question has an answer` ); 678await page . waitForTimeout ( 300 ); 679const sb = await send . boundingBox (); 680const top = await page . evaluate (({ x, y}) => { const e = document . elementFromPoint ( x , y ); return e ?. closest ( 'button' )?. textContent ?? '' ; }, { x :sb . x + sb . width / 2 , y :sb . y + sb . height / 2 }); 681check ( sb . y >= 0 && sb . y + sb . height <= h && / Send answer / . test ( top ), ` ${ tag } : the answer buttons are in view and reachable without scrolling the card` , JSON . stringify ( sb )); 682await shot ( page , `4244- ${ tag } ` ); 683check (( await page . evaluate (() => document . documentElement . scrollWidth )) <= w , ` ${ tag } : no sideways scroll` ); 684const box = await page . locator ( '.approvaldock' ). boundingBox (); 685check ( !! box && box . y >= 0 && box . y + box . height <= h + 1 , ` ${ tag } : the dock with the card is inside the window` , JSON . stringify ( box )); 686await send . click (); 687await page . waitForFunction (() => document . querySelectorAll ( '.askq' ). length === 0 , null , { timeout :8000 }); 688const got = ( await asked ()). slice ( before ); 689check ( JSON . stringify ( got . at ( - 1 )) === JSON . stringify ({ sessionId :'s1' , callId :'call-ask-1' , answers :[{ id :'q1' , selected :[ 'Blue' ] }, { id :'q2' , selected :[ 'Dark mode' , 'Animations' ] }] }), ` ${ tag } : the answer goes to the host as chosen` , JSON . stringify ( got . at ( - 1 ))); 690check ( await page . locator ( '.askq' ). count () === 0 , ` ${ tag } : the card goes away, and the turn ends` ); 691// The person's own words, and a skip. 692await page . locator ( 'textarea' ). first (). fill ( 'Again' ); 693await page . keyboard . press ( 'Enter' ); 694await card . waitFor ({ timeout :15000 }); 695await page . getByRole ( 'textbox' , { name :'Type your own answer' }). first (). fill ( 'Green, like the logo' ); 696await page . getByRole ( 'checkbox' , { name :'Animations' }). click (); 697await send . click (); 698await page . waitForFunction (() => document . querySelectorAll ( '.askq' ). length === 0 , null , { timeout :8000 }); 699const own = ( await asked ()). slice ( before ). at ( - 1 ); 700check ( JSON . stringify ( own ?. answers ) === JSON . stringify ([{ id :'q1' , selected :[], custom :'Green, like the logo' }, { id :'q2' , selected :[ 'Animations' ] }]), ` ${ tag } : the person's own words are sent as such` , JSON . stringify ( own )); 701await page . locator ( 'textarea' ). first (). fill ( 'Once more' ); 702await page . keyboard . press ( 'Enter' ); 703await card . waitFor ({ timeout :15000 }); 704await page . getByRole ( 'button' , { name :'Skip' }). click (); 705await page . waitForFunction (() => document . querySelectorAll ( '.askq' ). length === 0 , null , { timeout :8000 }); 706check (( await asked ()). slice ( before ). at ( - 1 )?. skip === true , ` ${ tag } : Skip is sent as a skip` ); 707check ( page . problems . length === 0 , ` ${ tag } : no page error` , page . problems . join ( '; ' )); 708await page . context (). close (); 709} 710// A /loop runs without anyone there: the question is skipped at once, no card, and the loop is not left waiting. 711{ 712const before = ( await asked ()). length ; 713const page = await open ( 'light' , 1280 , 860 , [ chat ( 's1' , 'Loop' , [])], { origin :t . origin }); 714await page . locator ( 'textarea' ). first (). fill ( '/loop 10m Build me a page stop after 1 answer' ); 715await page . keyboard . press ( 'Enter' ); 716await page . waitForFunction ( async () => ( await ( await fetch ( '/__fixture/asked' )). json ()). length > 0 , null , { timeout :15000 }). catch (() => {}); 717const got = ( await asked ()). slice ( before ). at ( - 1 ); 718check ( got ?. skip === true && got ?. callId === 'call-ask-1' , 'a loop: the question is skipped at once' , JSON . stringify ( got )); 719check ( await page . locator ( '.askq' ). count () === 0 , 'a loop: no question card is shown' ); 720await page . context (). close (); 721} 722await fetch ( ` ${ t . origin } /__fixture/ask` , { method :'POST' , headers :{ 'content-type' :'application/json' }, body :JSON . stringify ({ on :false }) }); 723}; 724 725/* ------------------------------------------------------------------------------------------------------------------- #3818 (a probe, no fix) */ 726cases . select = async () => { 727const paras = Array . from ({ length :40 }, ( _ , i ) => `Paragraph ${ i + 1 } . This is a sentence of a long answer that goes on for a while so that the reply overflows the window.` ). join ( '\n\n' ); 728const pick = async ( page , fromText , toText ) => { 729const a = await page . getByText ( fromText , { exact :false }). first (). boundingBox (), b = await page . getByText ( toText , { exact :false }). first (). boundingBox (); 730await page . mouse . move ( a . x + 2 , a . y + a . height / 2 ); 731await page . mouse . down (); 732await page . mouse . move ( b . x + b . width - 4 , b . y + b . height / 2 , { steps :12 }); 733await page . mouse . up (); 734return page . evaluate (() => window . getSelection (). toString ()); 735}; 736const page = await open ( 'light' , 1280 , 860 , [ chat ( 's1' , 'Select' , [ user ( 'u1' , 'Write a lot' ), reply ( 'a1' , paras )])]); 737await page . locator ( '.st-bubble p' ). first (). waitFor ({ timeout :15000 }); 738await page . locator ( '.main__body.chat' ). evaluate ( el => { el . scrollTop = el . scrollHeight ; }); 739await page . waitForTimeout ( 400 ); 740// After the reply has finished: a drag across several paragraphs. 741const visible = await page . evaluate (() => [ ...document . querySelectorAll ( '.st-bubble p' )]. filter ( p => { const r = p . getBoundingClientRect (); return r . top > 100 && r . bottom < innerHeight - 220 ; }). map ( p => p . textContent . slice ( 0 , 12 ))); 742const first = visible [ 0 ], last = visible . at ( - 1 ); 743const got = await pick ( page , first , last ); 744check ( got . includes ( first ) && got . includes ( last ) && got . split ( '\n' ). filter ( Boolean ). length >= visible . length , `finished reply: a drag across ${ visible . length } paragraphs selects all of them` , ` ${ got . length } characters` ); 745await page . context (). close (); 746// While a reply streams: select a passage of the older reply, and see whether the selection and the view stay. 747const page2 = await open ( 'light' , 1280 , 860 , [ chat ( 's1' , 'Select' , [ user ( 'u1' , 'Write a lot' ), reply ( 'a1' , paras )])]); 748await page2 . locator ( '.st-bubble p' ). first (). waitFor ({ timeout :15000 }); 749await page2 . locator ( 'textarea' ). first (). fill ( 'SCRIPT:slow 400' ); 750await page2 . keyboard . press ( 'Enter' ); 751await page2 . waitForTimeout ( 1500 ); 752const v2 = await page2 . evaluate (() => [ ...document . querySelector ( '.st-msg--assistant' ). querySelectorAll ( '.st-bubble p' )]. filter ( p => { const r = p . getBoundingClientRect (); return r . top > 100 && r . bottom < innerHeight - 220 ; }). map ( p => p . textContent . slice ( 0 , 12 ))); 753if ( v2 . length >= 2 ) { 754// The selection is made in code here (a drag moves with the layout and made this probe flaky): words of the older reply, as a drag would select them. 755const sel0 = await page2 . evaluate (([ a , b ]) => { 756const ps = [ ...document . querySelector ( '.st-msg--assistant' ). querySelectorAll ( '.st-bubble p' )], from = ps . find ( p => p . textContent . startsWith ( a )), to = ps . find ( p => p . textContent . startsWith ( b )); 757const r = document . createRange (); r . setStart ( from . firstChild , 0 ); r . setEnd ( to . lastChild , to . lastChild . textContent . length ); 758const s = window . getSelection (); s . removeAllRanges (); s . addRange ( r ); return s . toString (); 759}, [ v2 [ 0 ], v2 . at ( - 1 )]); 760const top0 = await page2 . locator ( '.main__body.chat' ). evaluate ( el => el . scrollTop ); 761await page2 . waitForTimeout ( 3000 ); 762const sel1 = await page2 . evaluate (() => window . getSelection (). toString ()); 763const top1 = await page2 . locator ( '.main__body.chat' ). evaluate ( el => el . scrollTop ); 764console . log ( `INFO streaming: selection ${ sel0 . length } -> ${ sel1 . length } characters, scrollTop ${ Math . round ( top0 )} -> ${ Math . round ( top1 )} ` ); 765console . log ( `INFO before: ${ JSON . stringify ( sel0 . slice ( 0 , 40 ))} ... ${ JSON . stringify ( sel0 . slice ( - 40 ))} 766INFO after: ${ JSON . stringify ( sel1 . slice ( 0 , 40 ))} ... ${ JSON . stringify ( sel1 . slice ( - 40 ))} ` ); 767check ( sel1 === sel0 , 'streaming: a selection in the older reply stays as it was while the new reply is written (a selection inside the paragraph that is being written does not: React replaces its text node on every token)' , ` ${ sel0 . length } -> ${ sel1 . length } ` ); 768check ( Math . abs ( top1 - top0 ) < 40 , 'streaming: the view is not pulled away from the selection' , ` ${ Math . round ( top0 )} -> ${ Math . round ( top1 )} ` ); 769} else console . log ( 'INFO streaming: the older reply was not on screen, nothing to select' ); 770await page2 . context (). close (); 771}; 772 773/* ------------------------------------------------------------------------------------------------------------------ run */ 774let ran = 0 ; 775for ( const [ name , fn ] of Object . entries ( cases )) { 776if ( ONLY . length && ! ONLY . includes ( name )) continue ; 777console . log ( `--- ${ name } ` ); 778ran += 1 ; 779try { await fn (); } catch ( e ) { 780check ( false , ` ${ name } threw` , String ( e ?. stack ?? e ). split ( '\n' ). slice ( 0 , 4 ). join ( ' | ' )); 781const last = pages . at ( - 1 ); 782if ( last && ! last . isClosed ()) { 783await last . screenshot ({ path :join ( SHOTS , `debug- ${ name } .png` ) }). catch (() => {}); 784console . log ( 'PAGE TEXT:' , (( await last . evaluate (() => document . body . innerText ). catch (() => '' )) || '' ). slice ( 0 , 600 ). replace ( / \n +/ g , ' | ' )); 785console . log ( 'PAGE ERRORS:' , last . problems ?. join ( '; ' )); 786} 787} 788} 789check ( ran > 0 , 'at least one case ran' ); 790await browser . close (); 791await worker . close (); 792for ( const proc of [ child , tuneHostInfo ?. proc ]) if ( proc ) { if ( process . platform === 'win32' ) spawnSync ( 'taskkill' , [ '/PID' , String ( proc . pid ), '/T' , '/F' ], { windowsHide :true }); else proc . kill ( 'SIGTERM' ); } 793try { rmSync ( home , { recursive :true , force :true , maxRetries :3 }); } catch { /* best effort */ } 794process . exit ( failed ?1 :0 );