okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-0213-guidata (final 1d5096beb) into f-0213-int85269ca15

main
61.6 KiB794 linesraw
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 } = {}) {
55  const context = await browser.newContext({ viewport: { width, height }, colorScheme: scheme, locale, permissions: ['clipboard-read', 'clipboard-write'] });
56  const page = await context.newPage();
57  pages.push(page);
58  const problems = [];
59  page.on('pageerror', e => problems.push(e.message));
60  page.problems = problems;
61  await page.addInitScript(({ sessions, prefs }) => {
62    try {
63      if (sessionStorage.getItem('ui-do-seeded')) return;
64      sessionStorage.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).
66      for (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 })); }
67      if (Object.keys(prefs).length) localStorage.setItem('strata.prefs.v1', JSON.stringify(prefs));
68    } catch { /* storage refused */ }
69  }, { sessions, prefs });
70  if (before) await before(page);
71  await page.goto(`${origin}/${hash}`);
72  await page.waitForTimeout(1800);
73  const skip = page.getByText('Go straight to the app');
74  if (!keepSetup && await skip.count()) { await skip.click(); await page.waitForTimeout(600); }
75  return 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 () => {
88  for (const scheme of ['light', 'dark']) for (const [sizeName, [w, h]] of Object.entries(sizes)) {
89    const tag = `${scheme}-${sizeName}`;
90    const sessions = [chat('s1', 'Long reply', [user('u1', 'Please write notes.txt'), reply('a1', longReply, { tools: [askTool('t1')] })])];
91    const page = await open(scheme, w, h, sessions);
92    const dock = page.locator('.approvaldock');
93    await dock.waitFor({ timeout: 15000 });
94    const view = page.viewportSize();
95    const 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; };
96    check(await page.locator('.askcard').count() === 1, `${tag}: one Approve/Deny card on the page`);
97    check(await page.getByRole('button', { name: 'Approve' }).count() === 1 && await page.getByRole('button', { name: 'Deny' }).count() === 1, `${tag}: one Approve and one Deny`);
98    check(await inView('.approvaldock'), `${tag}: the card is inside the window at the end of the reply`);
99    const scroller = page.locator('.main__body.chat');
100    const atEnd = () => scroller.evaluate(el => el.scrollHeight - el.scrollTop - el.clientHeight);
101    check(await atEnd() < 4, `${tag}: the reply is still scrolled to its end`, String(await atEnd()));
102    check(await page.locator('.approval-wait').count() === 1, `${tag}: the reply says it waits for an answer`);
103    await shot(page, `4725-${tag}-end`);
104    await scroller.evaluate(el => { el.scrollTop = 0; });
105    await page.waitForTimeout(300);
106    check(await inView('.approvaldock'), `${tag}: the card stays in the window when the reader is at the top`);
107    const composerTop = await page.locator('.composer .st-composer').boundingBox();
108    const dockBox = await dock.boundingBox();
109    check(dockBox.y + dockBox.height <= composerTop.y, `${tag}: the card sits above the message box`);
110    check((await page.evaluate(() => document.documentElement.scrollWidth)) <= w, `${tag}: no sideways scroll`);
111    await shot(page, `4725-${tag}-top`);
112    await page.getByRole('button', { name: 'Approve' }).click();
113    await page.waitForTimeout(500);
114    check(await page.locator('.approvaldock').count() === 0, `${tag}: the card goes away after Approve`);
115    check(await page.locator('.approval-wait').count() === 0, `${tag}: and so does the waiting line`);
116    check(page.problems.length === 0, `${tag}: no page error`, page.problems.join('; '));
117    await page.context().close();
118  }
119  // Two waiting at once, one in each card style; Deny works from the dock.
120  const sessions = [chat('s1', 'Two waiting', [user('u1', 'Do two things'), reply('a1', longReply.slice(0, 1500), { tools: [askTool('t1'), plainTool('t2')] })])];
121  const page = await open('light', 1280, 860, sessions);
122  await page.locator('.approvaldock').waitFor({ timeout: 15000 });
123  check(await page.locator('.approvaldock > section').count() === 2, 'two waiting: both cards are in the dock');
124  await shot(page, '4725-two-waiting');
125  await page.getByRole('button', { name: 'Deny' }).first().click();
126  await page.waitForTimeout(400);
127  check(await page.locator('.approvaldock > section').count() === 1, 'two waiting: Deny on the first leaves the second');
128  await 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 () => {
134  for (const scheme of ['light', 'dark']) for (const [sizeName, [w, h]] of Object.entries(sizes)) {
135    const tag = `${scheme}-${sizeName}`;
136    const sessions = [chat('s1', 'Copy', [user('u1', 'Show me a command'), reply('a1', codeReply), user('u2', 'Thanks'), reply('a2', 'You are welcome. Second reply.')])];
137    const page = await open(scheme, w, h, sessions);
138    await page.locator('.st-msg--assistant').last().waitFor({ timeout: 15000 });
139    const flag = async loc => loc.evaluate(el => ({ copied: el.hasAttribute('data-copied'), icon: el.querySelector('use')?.getAttribute('href') ?? '' }));
140    const read = () => page.evaluate(() => navigator.clipboard.readText());
141    // The last reply's copy button (an icon in the action row).
142    const copyResponse = page.getByRole('button', { name: 'Copy response' });
143    await copyResponse.last().click();
144    await page.mouse.move(2, 2);
145    await page.waitForTimeout(250);
146    let f = await flag(copyResponse.last());
147    check(f.copied && f.icon.endsWith('i-check'), `${tag}: Copy response turns into a check mark`, JSON.stringify(f));
148    check((await read()) === 'You are welcome. Second reply.', `${tag}: the reply is on the clipboard`);
149    const row = page.locator('.st-msg--assistant').last().locator('.st-msg__actions');
150    check(await row.evaluate(el => getComputedStyle(el).opacity) === '1', `${tag}: the action row stays visible while it says so, mouse away`);
151    check(/Copied/.test(await page.locator('.st-msg--assistant').last().locator('[role=status]').first().innerText()), `${tag}: a screen reader hears Copied`);
152    await shot(page, `4748-${tag}-reply`);
153    await page.waitForTimeout(2200);
154    f = await flag(copyResponse.last());
155    check(!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.
157    const code = page.locator('.st-code__head').getByRole('button', { name: 'Copy code' });
158    await code.click();
159    await page.waitForTimeout(250);
160    f = await flag(code);
161    check(f.copied && f.icon.endsWith('i-check'), `${tag}: the code block's Copy turns into a check mark`, JSON.stringify(f));
162    check((await read()) === 'npm install left-pad', `${tag}: the code is on the clipboard`);
163    await shot(page, `4748-${tag}-code`);
164    await page.waitForTimeout(2200);
165    // The menu item of an earlier reply: says Copied, then the menu closes.
166    await page.locator('.st-msg--assistant').first().hover();
167    await page.locator('.st-msg--assistant').first().getByRole('button', { name: 'More response actions' }).click();
168    const item = page.getByRole('menuitem', { name: 'Copy response' });
169    await item.click();
170    await page.waitForTimeout(250);
171    check(/Copied/.test(await page.locator('.menu [data-copied]').innerText()), `${tag}: the menu item says Copied`);
172    check((await read()).startsWith('Here is a command'), `${tag}: the earlier reply is on the clipboard`);
173    await shot(page, `4748-${tag}-menu`);
174    await page.waitForTimeout(1300);
175    check(await page.locator('.menu').count() === 0, `${tag}: and the menu closes by itself`);
176    check(page.problems.length === 0, `${tag}: no page error`, page.problems.join('; '));
177    await page.context().close();
178  }
179  // A refused clipboard: nothing says Copied on the button, and the person is told in a toast.
180  {
181    const page = await open('light', 1280, 860, [chat('s1', 'Refused', [user('u1', 'Hi'), reply('a1', 'Hello there.')])]);
182    await page.locator('.st-msg--assistant').last().waitFor({ timeout: 15000 });
183    await page.evaluate(() => { Object.defineProperty(navigator, 'clipboard', { value: { writeText: () => Promise.reject(new Error('denied')) }, configurable: true }); document.execCommand = () => false; });
184    const b = page.getByRole('button', { name: 'Copy response' }).last();
185    await b.click();
186    await page.waitForTimeout(400);
187    check(await b.evaluate(el => !el.hasAttribute('data-copied')), 'refused clipboard: the button does not claim success');
188    check(/Couldn.t copy/.test(await page.locator('.st-toast').first().innerText()), 'refused clipboard: a toast says it did not work');
189    await page.context().close();
190  }
191  // The Serving screen: the address and the request template.
192  for (const scheme of ['light', 'dark']) {
193    const page = await open(scheme, 1280, 860, [chat('s1', 'Serving', [user('u1', 'Hi'), reply('a1', 'Hello there.')])], { hash: '#/serving' });
194    const c = page.getByRole('button', { name: 'Copy API base URL' });
195    await c.waitFor({ timeout: 15000 });
196    await c.click();
197    await page.waitForTimeout(250);
198    check(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`);
199    check(/^http:\/\/127\.0\.0\.1:\d+\/v1$/.test(await page.evaluate(() => navigator.clipboard.readText())), `${scheme}: Serving, the address is on the clipboard`);
200    await shot(page, `4748-serving-${scheme}`);
201    await page.getByRole('button', { name: 'Connection guide' }).click();
202    const t = page.getByRole('button', { name: 'Copy request template' });
203    await t.click();
204    await page.waitForTimeout(250);
205    check(await t.evaluate(el => el.hasAttribute('data-copied')), `${scheme}: Serving, Copy request template turns into a check mark`);
206    check((await page.evaluate(() => navigator.clipboard.readText())).startsWith('curl http'), `${scheme}: Serving, the template is on the clipboard`);
207    await page.context().close();
208  }
209};
210
211/* ------------------------------------------------------------------------------------------------------------------- #4804 */
212let tuneHostInfo = null;
213async function tuneHost() {
214  if (tuneHostInfo) return tuneHostInfo;
215  const tport = await freePort();
216  const 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 });
217  const origin = `http://127.0.0.1:${tport}`;
218  for (let i = 0; i < 100; i++) { try { if ((await fetch(`${origin}/api/native`)).ok) break; } catch { /* starting */ } await sleep(200); }
219  tuneHostInfo = { origin, proc, mode: m => fetch(`${origin}/__fixture/status-mode`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ mode: m }) }) };
220  return tuneHostInfo;
221}
222cases.tune = async () => {
223  const t = await tuneHost();
224  const sessions = [chat('s1', 'Tune', [user('u1', 'Hi'), reply('a1', 'Hello there.')])];
225  const openDialog = async (scheme, w, h, mode, inject = false) => {
226    await t.mode(mode);
227    const page = await open(scheme, w, h, sessions, { hash: '#/models', origin: t.origin });
228    if (inject) await page.route(/\/api\/native(\?.*)?$/, async route => {
229      if (!page.injectJob) return route.continue();
230      const r = await route.fetch(); const j = await r.json();
231      j.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 } }];
232      return route.fulfill({ response: r, json: j });
233    });
234    const tune = page.getByRole('button', { name: 'Tune model' });
235    await tune.waitFor({ timeout: 20000 });
236    for (let i = 0; i < 40 && await tune.isDisabled(); i++) await page.waitForTimeout(250);
237    await tune.click();
238    await page.getByRole('dialog').waitFor({ timeout: 10000 });
239    return page;
240  };
241  const 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).
243  const seen = async (page, w, h) => {
244    const s = await page.locator('.tune-why').boundingBox(), b = await start(page).boundingBox();
245    return !!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  };
247  for (const scheme of ['light', 'dark']) for (const [sizeName, [w, h]] of Object.entries(sizes)) {
248    const tag = `${scheme}-${sizeName}`;
249    // 1. The saved tunings are still being read: greyed out, with the reason, and not "No saved tuning".
250    let page = await openDialog(scheme, w, h, 'slow');
251    await page.waitForTimeout(1200);
252    check(await start(page).isDisabled(), `${tag}: loading: Start tuning is greyed out`);
253    let why = await page.locator('.tune-why').innerText().catch(() => '');
254    check(/still checking this model for saved tunings/.test(why), `${tag}: loading: one sentence says why`, why);
255    check(await page.locator('.tune-why').count() === 1, `${tag}: loading: only one such sentence`);
256    check(!/No saved tuning for these choices yet/.test(await page.getByRole('dialog').innerText()), `${tag}: loading: it does not claim there is no saved tuning`);
257    check(await seen(page, w, h), `${tag}: loading: the sentence is on screen next to the button`);
258    await shot(page, `4804-${tag}-loading`);
259    await page.context().close();
260    // 2. Reading them failed.
261    page = await openDialog(scheme, w, h, 'fail');
262    await page.waitForTimeout(1200);
263    check(await start(page).isDisabled(), `${tag}: unreadable: Start tuning is greyed out`);
264    why = await page.locator('.tune-why').innerText().catch(() => '');
265    check(/could not read the tuning details/.test(why), `${tag}: unreadable: one sentence says why`, why);
266    check(await seen(page, w, h), `${tag}: unreadable: the sentence is on screen next to the button`);
267    check(!/No saved tuning/.test(await page.getByRole('dialog').innerText()), `${tag}: unreadable: it does not claim there is no saved tuning`);
268    await shot(page, `4804-${tag}-unreadable`);
269    await page.context().close();
270    // 3. Another operation is running.
271    page = await openDialog(scheme, w, h, 'ok', true);
272    await page.waitForTimeout(800);
273    check(await start(page).isEnabled() && await page.locator('.tune-why').count() === 0, `${tag}: ready: Start tuning works and shows no sentence`);
274    page.injectJob = true;
275    await page.waitForTimeout(3500);
276    check(await start(page).isDisabled(), `${tag}: another operation: Start tuning is greyed out`);
277    why = await page.locator('.tune-why').innerText().catch(() => '');
278    check(/Finish the current operation first/.test(why), `${tag}: another operation: one sentence says why`, why);
279    check((await page.evaluate(() => document.documentElement.scrollWidth)) <= w, `${tag}: no sideways scroll`);
280    check(await seen(page, w, h), `${tag}: other: the sentence is on screen next to the button`);
281    await shot(page, `4804-${tag}-other`);
282    check(page.problems.length === 0, `${tag}: no page error`, page.problems.join('; '));
283    await page.context().close();
284  }
285};
286
287/* ------------------------------------------------------------------------------------------------------------------- #4721 */
288cases.links = async () => {
289  const 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).`)])];
290  for (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.
292    let page = await open(scheme, 1280, 860, sessions());
293    await page.getByRole('link', { name: 'the docs' }).waitFor({ timeout: 15000 });
294    await page.evaluate(() => { window.__opened = []; window.open = (...a) => { window.__opened.push(a); return null; }; });
295    await page.getByRole('link', { name: 'the docs' }).click();
296    await page.waitForTimeout(300);
297    let opened = await page.evaluate(() => window.__opened);
298    check(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));
299    check(await page.locator('.artifact-panel').count() === 0, `${scheme}: a browser tab: and no side panel opens`);
300    await page.getByRole('link', { name: 'the logo' }).click();
301    await page.locator('.artifact-panel').waitFor({ timeout: 8000 });
302    check((await page.evaluate(() => window.__opened)).length === 1, `${scheme}: a file link keeps the side panel and opens no tab`);
303    await shot(page, `4721-${scheme}-file`);
304    await page.context().close();
305    // The app window: the host hands the address to the default browser; window.open is not used.
306    const posts = [];
307    page = await open(scheme, 1280, 860, sessions(), { before: async p => {
308      await p.route('**/api/app/mode', r => r.fulfill({ json: { mode: 'window', reason: null, canQuit: true, appUpdate: 'unavailable' } }));
309      await p.route('**/api/artifacts/open', r => { posts.push(r.request().postDataJSON()); return r.fulfill({ json: { ok: true } }); });
310    } });
311    await page.getByRole('link', { name: 'the docs' }).waitFor({ timeout: 15000 });
312    await page.evaluate(() => { window.__opened = []; window.open = (...a) => { window.__opened.push(a); return null; }; });
313    await page.getByRole('link', { name: 'the docs' }).click();
314    await page.waitForTimeout(400);
315    check(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));
316    check((await page.evaluate(() => window.__opened)).length === 0 && await page.locator('.artifact-panel').count() === 0, `${scheme}: the app window: nothing else happens`);
317    check(page.problems.length === 0, `${scheme}: no page error`, page.problems.join('; '));
318    await page.context().close();
319  }
320};
321
322/* ------------------------------------------------------------------------------------------------------------------- #4802 */
323cases.progress = async () => {
324  const t = await tuneHost();
325  await t.mode('ok');
326  const sessions = [chat('s1', 'Progress', [user('u1', 'Hi'), reply('a1', 'Hello there.')])];
327  for (const scheme of ['light', 'dark']) for (const [sizeName, [w, h]] of Object.entries(sizes)) {
328    const tag = `${scheme}-${sizeName}`;
329    const page = await open(scheme, w, h, sessions, { hash: '#/models', origin: t.origin });
330    const started = new Date(Date.now() - (3 * 60 + 12) * 1000).toISOString();
331    await page.route(/\/api\/native(\?.*)?$/, async route => {
332      const r = await route.fetch(); const j = await r.json();
333      j.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 }];
334      return route.fulfill({ response: r, json: j });
335    });
336    await page.reload();
337    const card = page.locator('.native-progress');
338    await card.waitFor({ timeout: 20000 });
339    await page.waitForTimeout(1500);
340    check(await card.locator('.spinner').count() === 1, `${tag}: a spinner shows that it is working`);
341    const alive = () => card.locator('.native-progress__alive').innerText();
342    const a1 = await alive();
343    check(/^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);
344    await page.waitForTimeout(2200);
345    const a2 = await alive();
346    check(a1 !== a2, `${tag}: the time keeps counting`, `${a1} -> ${a2}`);
347    check(/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`);
348    const border = await card.evaluate(el => getComputedStyle(el).borderTopColor);
349    const other = await page.locator('.st-card:not(.native-progress)').first().evaluate(el => getComputedStyle(el).borderTopColor);
350    check(border !== other, `${tag}: the card has its own border colour`, `${border} vs ${other}`);
351    check((await page.evaluate(() => document.documentElement.scrollWidth)) <= w, `${tag}: no sideways scroll`);
352    await card.scrollIntoViewIfNeeded();
353    await shot(page, `4802-${tag}`);
354    check(page.problems.length === 0, `${tag}: no page error`, page.problems.join('; '));
355    await page.context().close();
356  }
357};
358
359/* ------------------------------------------------------------------------------------------------------------------- #4798 */
360cases.serving = async () => {
361  const sessions = [chat('s1', 'Serving', [user('u1', 'Hi'), reply('a1', 'Hello there.')])];
362  for (const scheme of ['light', 'dark']) for (const [sizeName, [w, h]] of Object.entries(sizes)) {
363    const 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.
365    for (const sharing of [false, true]) {
366      const page = await open(scheme, w, h, sessions, { hash: '#/serving', before: async p => {
367        if (!sharing) return;
368        await p.route(/\/api\/serving$/, async route => {
369          if (route.request().method() !== 'GET') return route.continue();
370          const r = await route.fetch(); const j = await r.json();
371          return 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      } });
374      await page.getByText('API base URL', { exact: false }).first().waitFor({ timeout: 15000 });
375      await page.waitForTimeout(800);
376      const text = await page.locator('.serving-overview').innerText();
377      if (sharing) {
378        check(/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`);
379        check(/Address for other devices/.test(text) && text.includes('http://100.76.61.73:8080/v1'), `${tag}: sharing on: and the address for other devices`);
380        check(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`);
381        const t = page.getByRole('button', { name: 'Copy local network URL' });
382        await t.click(); await page.waitForTimeout(250);
383        check((await page.evaluate(() => navigator.clipboard.readText())) === 'http://100.76.61.73:8080/v1', `${tag}: sharing on: the copy button gives the network address`);
384        check((await page.evaluate(() => document.documentElement.scrollWidth)) <= w, `${tag}: sharing on: no sideways scroll`);
385        await page.locator('.serving-overview').scrollIntoViewIfNeeded();
386        await shot(page, `4798-${tag}-sharing`);
387      } else {
388        check(!/Address for other devices/.test(text) && await page.locator('.serving-two-addresses').count() === 0, `${tag}: sharing off: one address, no extra line`);
389      }
390      check(page.problems.length === 0, `${tag}: no page error`, page.problems.join('; '));
391      await page.context().close();
392    }
393  }
394};
395
396/* ------------------------------------------------------------------------------------------------------------------- #4722 */
397cases.width = async () => {
398  const 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```';
399  for (const scheme of ['light', 'dark']) for (const [sizeName, [w, h]] of Object.entries(sizes)) {
400    const tag = `${scheme}-${sizeName}`;
401    const page = await open(scheme, w, h, [chat('s1', 'Width', [user('u1', 'Write'), reply('a1', text)])]);
402    await page.locator('.st-bubble ul').first().waitFor({ timeout: 15000 });
403    const m = await page.evaluate(() => {
404      const b = document.querySelector('.st-msg--assistant .st-bubble'), r = el => Math.round(el.getBoundingClientRect().width);
405      return { 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    });
407    const note = JSON.stringify(m);
408    if (w > 700) {
409      check(Math.abs(m.ul - m.p) <= 2 && Math.abs(m.ol - m.p) <= 2, `${tag}: bullets and numbers have the paragraph's width`, note);
410      check(m.table > m.p + 20 && m.code > m.p + 20, `${tag}: the table and the code block keep the full width`, note);
411    } else {
412      check(Math.abs(m.ul - m.p) <= 2 && m.p <= m.bubble, `${tag}: narrow window: everything fits the column`, note);
413    }
414    check((await page.evaluate(() => document.documentElement.scrollWidth)) <= w, `${tag}: no sideways scroll`);
415    await shot(page, `4722-${tag}`);
416    await page.context().close();
417  }
418};
419
420/* ------------------------------------------------------------------------------------------------------------------- #3723 */
421cases.firstrun = async () => {
422  const setupStep = dismissed => fetch(`${base}/api/setup/step`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ step: 1, dismissed, flowVersion: 2 }) });
423  await setupStep(false);
424  // A computer set to a language Strata does not have: English.
425  const page = await open('light', 1280, 860, null, { hash: '#/setup', locale: 'sv-SE', keepSetup: true });
426  await page.locator('.onboard-language').waitFor({ timeout: 20000 });
427  check(/English/.test(await page.locator('.onboard-language').innerText()), 'Swedish computer: English');
428  await 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.
430  for (const scheme of ['light', 'dark']) for (const [sizeName, [w, h]] of Object.entries(sizes)) {
431    const tag = `${scheme}-${sizeName}`;
432    const page = await open(scheme, w, h, null, { hash: '#/setup', locale: 'zh-CN', keepSetup: true });
433    await page.locator('.onboard-language').waitFor({ timeout: 20000 });
434    await page.waitForTimeout(500);
435    const pick = page.locator('.onboard-language [role=combobox], .onboard-language button').first();
436    const shown = await pick.innerText();
437    check(/中文/.test(shown), `${tag}: a computer set to Chinese starts in Chinese`, shown);
438    check(/[\u4e00-\u9fff]/.test(await page.locator('.guided-onboarding h1').first().innerText()), `${tag}: the first screen is in Chinese`);
439    const box = await page.locator('.onboard-language').boundingBox();
440    check(!!box && box.x >= 0 && box.x + box.width <= w && box.y >= 0, `${tag}: the choice is on screen`, JSON.stringify(box));
441    const brand = await page.locator('.guided-onboarding .onboard-header .brand').first().boundingBox();
442    check(!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 }));
443    await shot(page, `3723-${tag}-first-zh`);
444    // Choosing German changes the screen at once, and it is kept.
445    await pick.click();
446    await page.getByRole('option', { name: 'Deutsch' }).click();
447    await page.waitForTimeout(500);
448    check(/[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`);
449    await shot(page, `3723-${tag}-first-de`);
450    await page.reload();
451    await page.locator('.onboard-language').waitFor({ timeout: 20000 });
452    check(/Deutsch/.test(await page.locator('.onboard-language').innerText()), `${tag}: the choice is kept after a restart, whatever the computer says`);
453    check(page.problems.length === 0, `${tag}: no page error`, page.problems.join('; '));
454    await page.context().close();
455  }
456  await setupStep(true);
457};
458
459cases.kv = async () => {
460  const t = await tuneHost();
461  await t.mode('ok');
462  const sessions = [chat('s1', 'KV', [user('u1', 'Hi'), reply('a1', 'Hello there.')])];
463  for (const scheme of ['light', 'dark']) for (const [sizeName, [w, h]] of Object.entries(sizes)) {
464    const tag = `${scheme}-${sizeName}`;
465    const page = await open(scheme, w, h, sessions, { hash: '#/models', origin: t.origin });
466    await page.route(/\/api\/native(\?.*)?$/, async route => {
467      const r = await route.fetch(); const j = await r.json();
468      j.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 }];
469      return route.fulfill({ response: r, json: j });
470    });
471    await page.reload();
472    const expert = page.getByRole('button', { name: 'Expert mode' });
473    await expert.waitFor({ timeout: 20000 });
474    await page.waitForTimeout(1500);
475    await expert.click();
476    const sel = page.getByRole('combobox', { name: 'Native KV format' });
477    if (!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(); }
478    await sel.waitFor({ timeout: 10000 });
479    const hint = page.locator('.native-kv-hint');
480    check(/INT8 is the standard/.test(await hint.innerText()), `${tag}: Context memory: one line says what the chosen format is`);
481    await sel.click();
482    check(await page.getByRole('option').count() === 3, `${tag}: Context memory: three options`);
483    const titles = await page.locator('.select__option-label').evaluateAll(els => els.map(e => e.getAttribute('title')));
484    check(titles.length === 3 && titles.every(x => x && x.length > 20), `${tag}: Context memory: each option carries its line`, JSON.stringify(titles));
485    await page.getByRole('option', { name: 'Q4' }).click();
486    await page.waitForTimeout(300);
487    check(/Q4 uses about half the memory/.test(await hint.innerText()), `${tag}: Context memory: the line follows the choice`);
488    await hint.scrollIntoViewIfNeeded();
489    await shot(page, `3723-${tag}-kv`);
490    const notice = page.locator('.error-notice');
491    await notice.first().waitFor({ timeout: 10000 });
492    const said = await notice.first().innerText();
493    check(/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));
494    await notice.first().scrollIntoViewIfNeeded();
495    await shot(page, `3723-${tag}-vram`);
496    check((await page.evaluate(() => document.documentElement.scrollWidth)) <= w, `${tag}: no sideways scroll`);
497    check(page.problems.length === 0, `${tag}: no page error`, page.problems.join('; '));
498    await page.context().close();
499  }
500};
501
502/* ------------------------------------------------------------------------------------------------------------------- #4749 */
503cases.helper = async () => {
504  const 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  ];
508  for (const scheme of ['light', 'dark']) for (const [sizeName, [w, h]] of Object.entries(sizes)) {
509    const tag = `${scheme}-${sizeName}`;
510    const sessions = [{ ...chat('s1', 'Helpers', [user('u1', 'Do two things'), reply('a1', 'Both helpers are on it.')]), agents }];
511    const posts = []; let refuse = false;
512    const page = await open(scheme, w, h, sessions, { before: async p => {
513      await 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    } });
515    await page.getByRole('button', { name: /Subagents/ }).first().click();
516    const rows = page.locator('.subagent-row');
517    await rows.first().waitFor({ timeout: 15000 });
518    // The finished helper: queue.
519    await rows.nth(0).getByRole('button', { name: 'Message this helper' }).click();
520    const input = rows.nth(0).getByRole('textbox', { name: 'Message to Check the tests' });
521    await input.fill('use ISO dates in the file you just wrote');
522    await shot(page, `4749-${tag}-writing`);
523    await input.press('Enter');
524    await rows.nth(0).getByRole('status').waitFor({ timeout: 5000 });
525    check(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]));
526    check(/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).
528    await rows.nth(1).getByRole('button', { name: 'Message this helper' }).click();
529    await rows.nth(1).getByRole('textbox').fill('also add the date');
530    await rows.nth(1).getByRole('button', { name: 'Send' }).click();
531    await rows.nth(1).getByRole('status').waitFor({ timeout: 5000 });
532    check(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.
534    refuse = true;
535    await rows.nth(0).getByRole('textbox').fill('one more thing');
536    await rows.nth(0).getByRole('button', { name: 'Send' }).click();
537    await rows.nth(0).getByRole('alert').waitFor({ timeout: 5000 });
538    check(/cannot take a message any more/.test(await rows.nth(0).getByRole('alert').innerText()), `${tag}: a refused message says why in plain words`);
539    check((await page.evaluate(() => document.documentElement.scrollWidth)) <= w, `${tag}: no sideways scroll`);
540    await shot(page, `4749-${tag}-sent`);
541    check(page.problems.length === 0, `${tag}: no page error`, page.problems.join('; '));
542    await page.context().close();
543  }
544};
545
546/* ------------------------------------------------------------------------------------------------------------------- #4783 */
547cases.busy = async () => {
548  const fresh = (scheme, w, h, whileBusy) => open(scheme, w, h, [chat('s1', 'Busy', [])], { prefs: whileBusy ? { whileBusy } : {} });
549  const send = async (page, text) => { await page.locator('textarea').first().fill(text); await page.keyboard.press('Enter'); };
550  const lastReply = page => page.locator('.st-msg--assistant .st-bubble').last();
551  for (const scheme of ['light', 'dark']) {
552    const 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.
554    let page = await fresh(scheme, w, h, null);
555    await send(page, 'SCRIPT:slow 80');
556    await page.locator('.st-msg--assistant').first().waitFor({ timeout: 15000 });
557    await page.locator('textarea').first().fill('my second message');
558    await page.keyboard.press('Enter');
559    await page.waitForTimeout(600);
560    check(await page.locator('textarea').first().inputValue() === 'my second message', `${tag}: Wait: the message stays in the box`);
561    check(await page.locator('.parked').count() === 0, `${tag}: Wait: nothing is parked`);
562    await page.getByText('The assistant is still answering').first().waitFor({ timeout: 4000 }).catch(() => {});
563    check(await page.getByText('The assistant is still answering').count() > 0, `${tag}: Wait: a note says the assistant is still answering`);
564    await page.context().close();
565    // Send after: it waits (shown), and goes when the answer is done, after the whole first answer.
566    page = await fresh(scheme, w, h, 'queue');
567    await send(page, 'SCRIPT:slow 80');
568    await page.locator('.st-msg--assistant').first().waitFor({ timeout: 15000 });
569    await page.locator('textarea').first().fill('SCRIPT:echo the second answer');
570    check(/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`);
571    await page.keyboard.press('Enter');
572    await page.locator('.parked').waitFor({ timeout: 3000 });
573    check(/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`);
574    if (scheme === 'light') await shot(page, `4783-${tag}-waiting`);
575    await page.locator('.st-msg--assistant').nth(1).waitFor({ timeout: 30000 });
576    await page.waitForFunction(() => document.querySelectorAll('.parked').length === 0, null, { timeout: 15000 });
577    const firstText = await page.locator('.st-msg--assistant .st-bubble').first().innerText();
578    check(/w79/.test(firstText), `${tag}: Send after: the first answer was written to its end`, firstText.slice(-30));
579    check(/the second answer/.test(await lastReply(page).innerText()), `${tag}: Send after: then the second message was answered`);
580    await page.context().close();
581    // Interrupt: the answer stops where it is, what is written stays, and the message goes at once.
582    page = await fresh(scheme, w, h, 'interject');
583    await send(page, 'SCRIPT:slow 600');
584    await page.locator('.st-msg--assistant').first().waitFor({ timeout: 15000 });
585    await page.waitForTimeout(800);
586    await page.locator('textarea').first().fill('SCRIPT:echo interrupted and answered');
587    check(/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`);
588    await page.keyboard.press('Enter');
589    const t0 = Date.now();
590    await page.locator('.st-msg--assistant').nth(1).waitFor({ timeout: 30000 });
591    check(Date.now() - t0 < 12000, `${tag}: Interrupt: the new message was answered long before the first answer would have ended`, `${Date.now() - t0} ms`);
592    const cut = await page.locator('.st-msg--assistant .st-bubble').first().innerText();
593    check(cut.includes('w0') && !cut.includes('w599'), `${tag}: Interrupt: the first answer stopped where it was and stays`, `${cut.length} characters`);
594    await page.waitForFunction(() => /interrupted and answered/.test([...document.querySelectorAll('.st-msg--assistant .st-bubble')].at(-1)?.innerText ?? ''), null, { timeout: 15000 }).catch(() => {});
595    check(/interrupted and answered/.test(await lastReply(page).innerText()), `${tag}: Interrupt: the second message was answered`);
596    if (scheme === 'light') await shot(page, `4783-${tag}-interrupted`);
597    check(page.problems.length === 0, `${tag}: no page error`, page.problems.join('; '));
598    await page.context().close();
599  }
600};
601
602/* ------------------------------------------------------------------------------------------------------------------- #4785 */
603cases.quote = async () => {
604  const 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.';
605  for (const scheme of ['light', 'dark']) for (const [sizeName, [w, h]] of Object.entries(sizes)) {
606    const tag = `${scheme}-${sizeName}`;
607    const 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.')])]);
608    await page.locator('.st-msg--assistant').first().waitFor({ timeout: 15000 });
609    // A whole turn, from the message menu.
610    await page.locator('.st-msg--assistant').first().hover();
611    await page.locator('.st-msg--assistant').first().getByRole('button', { name: 'More response actions' }).click();
612    await page.getByRole('menuitem', { name: 'Quote' }).click();
613    await page.locator('.quote').first().waitFor({ timeout: 5000 });
614    check(/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.
616    await page.evaluate(() => {
617      const p = document.querySelector('.st-msg--assistant .st-bubble p');
618      const node = p.firstChild; const at = node.textContent.indexOf('Second point'); const end = node.textContent.indexOf('Third point');
619      const r = document.createRange(); r.setStart(node, at); r.setEnd(node, end);
620      const s = window.getSelection(); s.removeAllRanges(); s.addRange(r);
621    });
622    await page.locator('.quote-selection').waitFor({ timeout: 5000 });
623    const sbox = await page.locator('.quote-selection').boundingBox();
624    check(!!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));
625    await page.locator('.quote-selection').click();
626    check(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`);
627    check(await page.locator('.quote-selection').count() === 0, `${tag}: the button goes away`);
628    await shot(page, `4785-${tag}-quotes`);
629    // Remove one, quote it again, jump to the message.
630    await page.locator('.quote').first().getByRole('button', { name: 'Remove this quote' }).click();
631    check(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`);
632    await page.locator('.quote__body').first().click();
633    await page.waitForTimeout(400);
634    // Send an answer: the model gets the fixed form, the transcript shows the quote apart from the reply.
635    await page.locator('textarea').first().fill('SCRIPT:echo thanks for the quote');
636    await page.keyboard.press('Enter');
637    await page.locator('.sent-quote').first().waitFor({ timeout: 15000 });
638    await page.waitForTimeout(300);
639    const sent = await page.locator('.st-msg--user').last().innerText();
640    check(/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));
641    const got = worker.requests.at(-1)?.raw ?? '';
642    check(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));
643    check(await page.locator('.quote').count() === 0, `${tag}: the quotes are cleared after sending`);
644    await page.locator('.sent-quote').first().click();
645    check(await page.locator('.sent-quotes[data-open]').count() === 1, `${tag}: a click opens the rest of a sent quote`);
646    await shot(page, `4785-${tag}-sent`);
647    check((await page.evaluate(() => document.documentElement.scrollWidth)) <= w, `${tag}: no sideways scroll`);
648    check(page.problems.length === 0, `${tag}: no page error`, page.problems.join('; '));
649    await page.context().close();
650  }
651};
652
653/* ------------------------------------------------------------------------------------------------------------------- #4244 */
654cases.ask = async () => {
655  const t = await tuneHost();
656  await t.mode('ok');
657  const asked = () => fetch(`${t.origin}/__fixture/asked`).then(r => r.json());
658  await fetch(`${t.origin}/__fixture/ask`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ on: true }) });
659  for (const scheme of ['light', 'dark']) for (const [sizeName, [w, h]] of Object.entries(sizes)) {
660    const tag = `${scheme}-${sizeName}`;
661    const before = (await asked()).length;
662    const page = await open(scheme, w, h, [chat('s1', 'Ask', [])], { origin: t.origin });
663    await page.locator('textarea').first().fill('Build me a page');
664    await page.keyboard.press('Enter');
665    const card = page.locator('.askq');
666    await card.waitFor({ timeout: 15000 });
667    const text = await card.innerText();
668    check(/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`);
669    check(await page.locator('.askcard').count() === 1 && await page.locator('.approvaldock').count() === 1, `${tag}: it is one card in the dock above the box`);
670    const send = page.getByRole('button', { name: 'Send answer' });
671    check(await send.isDisabled(), `${tag}: Send answer waits until every question has an answer`);
672    await page.getByRole('radio', { name: /Red/ }).click();
673    await page.getByRole('radio', { name: /Blue/ }).click();
674    check(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`);
675    await page.getByRole('checkbox', { name: 'Dark mode' }).click();
676    await page.getByRole('checkbox', { name: 'Animations' }).click();
677    check(await send.isEnabled(), `${tag}: Send answer works once every question has an answer`);
678    await page.waitForTimeout(300);
679    const sb = await send.boundingBox();
680    const 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 });
681    check(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));
682    await shot(page, `4244-${tag}`);
683    check((await page.evaluate(() => document.documentElement.scrollWidth)) <= w, `${tag}: no sideways scroll`);
684    const box = await page.locator('.approvaldock').boundingBox();
685    check(!!box && box.y >= 0 && box.y + box.height <= h + 1, `${tag}: the dock with the card is inside the window`, JSON.stringify(box));
686    await send.click();
687    await page.waitForFunction(() => document.querySelectorAll('.askq').length === 0, null, { timeout: 8000 });
688    const got = (await asked()).slice(before);
689    check(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)));
690    check(await page.locator('.askq').count() === 0, `${tag}: the card goes away, and the turn ends`);
691    // The person's own words, and a skip.
692    await page.locator('textarea').first().fill('Again');
693    await page.keyboard.press('Enter');
694    await card.waitFor({ timeout: 15000 });
695    await page.getByRole('textbox', { name: 'Type your own answer' }).first().fill('Green, like the logo');
696    await page.getByRole('checkbox', { name: 'Animations' }).click();
697    await send.click();
698    await page.waitForFunction(() => document.querySelectorAll('.askq').length === 0, null, { timeout: 8000 });
699    const own = (await asked()).slice(before).at(-1);
700    check(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));
701    await page.locator('textarea').first().fill('Once more');
702    await page.keyboard.press('Enter');
703    await card.waitFor({ timeout: 15000 });
704    await page.getByRole('button', { name: 'Skip' }).click();
705    await page.waitForFunction(() => document.querySelectorAll('.askq').length === 0, null, { timeout: 8000 });
706    check((await asked()).slice(before).at(-1)?.skip === true, `${tag}: Skip is sent as a skip`);
707    check(page.problems.length === 0, `${tag}: no page error`, page.problems.join('; '));
708    await 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  {
712    const before = (await asked()).length;
713    const page = await open('light', 1280, 860, [chat('s1', 'Loop', [])], { origin: t.origin });
714    await page.locator('textarea').first().fill('/loop 10m Build me a page stop after 1 answer');
715    await page.keyboard.press('Enter');
716    await page.waitForFunction(async () => (await (await fetch('/__fixture/asked')).json()).length > 0, null, { timeout: 15000 }).catch(() => {});
717    const got = (await asked()).slice(before).at(-1);
718    check(got?.skip === true && got?.callId === 'call-ask-1', 'a loop: the question is skipped at once', JSON.stringify(got));
719    check(await page.locator('.askq').count() === 0, 'a loop: no question card is shown');
720    await page.context().close();
721  }
722  await 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 () => {
727  const 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');
728  const pick = async (page, fromText, toText) => {
729    const a = await page.getByText(fromText, { exact: false }).first().boundingBox(), b = await page.getByText(toText, { exact: false }).first().boundingBox();
730    await page.mouse.move(a.x + 2, a.y + a.height / 2);
731    await page.mouse.down();
732    await page.mouse.move(b.x + b.width - 4, b.y + b.height / 2, { steps: 12 });
733    await page.mouse.up();
734    return page.evaluate(() => window.getSelection().toString());
735  };
736  const page = await open('light', 1280, 860, [chat('s1', 'Select', [user('u1', 'Write a lot'), reply('a1', paras)])]);
737  await page.locator('.st-bubble p').first().waitFor({ timeout: 15000 });
738  await page.locator('.main__body.chat').evaluate(el => { el.scrollTop = el.scrollHeight; });
739  await page.waitForTimeout(400);
740  // After the reply has finished: a drag across several paragraphs.
741  const 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)));
742  const first = visible[0], last = visible.at(-1);
743  const got = await pick(page, first, last);
744  check(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`);
745  await page.context().close();
746  // While a reply streams: select a passage of the older reply, and see whether the selection and the view stay.
747  const page2 = await open('light', 1280, 860, [chat('s1', 'Select', [user('u1', 'Write a lot'), reply('a1', paras)])]);
748  await page2.locator('.st-bubble p').first().waitFor({ timeout: 15000 });
749  await page2.locator('textarea').first().fill('SCRIPT:slow 400');
750  await page2.keyboard.press('Enter');
751  await page2.waitForTimeout(1500);
752  const 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)));
753  if (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.
755    const sel0 = await page2.evaluate(([a, b]) => {
756      const 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));
757      const r = document.createRange(); r.setStart(from.firstChild, 0); r.setEnd(to.lastChild, to.lastChild.textContent.length);
758      const s = window.getSelection(); s.removeAllRanges(); s.addRange(r); return s.toString();
759    }, [v2[0], v2.at(-1)]);
760    const top0 = await page2.locator('.main__body.chat').evaluate(el => el.scrollTop);
761    await page2.waitForTimeout(3000);
762    const sel1 = await page2.evaluate(() => window.getSelection().toString());
763    const top1 = await page2.locator('.main__body.chat').evaluate(el => el.scrollTop);
764    console.log(`INFO streaming: selection ${sel0.length} -> ${sel1.length} characters, scrollTop ${Math.round(top0)} -> ${Math.round(top1)}`);
765    console.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))}`);
767    check(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}`);
768    check(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');
770  await page2.context().close();
771};
772
773/* ------------------------------------------------------------------------------------------------------------------ run */
774let ran = 0;
775for (const [name, fn] of Object.entries(cases)) {
776  if (ONLY.length && !ONLY.includes(name)) continue;
777  console.log(`--- ${name}`);
778  ran += 1;
779  try { await fn(); } catch (e) {
780    check(false, `${name} threw`, String(e?.stack ?? e).split('\n').slice(0, 4).join(' | '));
781    const last = pages.at(-1);
782    if (last && !last.isClosed()) {
783      await last.screenshot({ path: join(SHOTS, `debug-${name}.png`) }).catch(() => {});
784      console.log('PAGE TEXT:', ((await last.evaluate(() => document.body.innerText).catch(() => '')) || '').slice(0, 600).replace(/\n+/g, ' | '));
785      console.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);