okami.mom/strata

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

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

main
82.2 KiB1795 linesraw
1/**
2 * Scripted UI flows for verification screenshots.
3 *
4 *   node scripts/flow.mjs chat|expert|setup|serving|light
5 */
6import { chromium } from 'playwright-core';
7import { existsSync, mkdirSync } from 'node:fs';
8import { join, resolve } from 'node:path';
9import { homedir } from 'node:os';
10import { requireChromium } from './browser.mjs';
11
12const executablePath = requireChromium();
13
14const BASE = process.env.STRATA_URL ?? 'http://localhost:5199';
15const flow = process.argv[2] ?? 'chat';
16const shots = resolve('.shots');
17mkdirSync(shots, { recursive: true });
18
19const browser = await chromium.launch({ executablePath, args: ['--no-sandbox', '--disable-gpu'] });
20const page = await browser.newPage({ viewport: { width: 1512, height: 1110 }, deviceScaleFactor: 1 });
21
22const problems = [];
23
24/**
25 * A flow that deliberately breaks something — aborting a request to exercise a
26 * failure path — would otherwise report its own instrumentation as a problem.
27 * Flows declare the failures they intend; anything else is still a problem.
28 */
29const expectedFailures = [];
30const expectFailure = (pattern) => expectedFailures.push(pattern);
31
32page.on('pageerror', (e) => problems.push(`pageerror: ${e.message}`));
33page.on('console', (m) => {
34  if (m.type() !== 'error') return;
35  const text = m.text();
36  if (expectedFailures.some((re) => re.test(text))) return;
37  problems.push(`console: ${text}`);
38});
39
40const shot = async (name) => {
41  await page.screenshot({ path: join(shots, `${name}.png`) });
42  console.log(join(shots, `${name}.png`));
43};
44
45await page.goto(`${BASE}/#/launch`, { waitUntil: 'domcontentloaded' });
46await page.waitForTimeout(1200);
47
48if (flow === 'chat') {
49  await page.click('text=New conversation');
50  await page.waitForTimeout(500);
51  await page.fill('textarea', 'Explain what a KV cache does, in plain words');
52  await page.waitForTimeout(200);
53  await page.keyboard.press('Enter');
54  await page.waitForTimeout(2600);
55  await shot('20-chat-streaming');
56  await page.waitForTimeout(6000);
57  await shot('21-chat-done');
58  await page.goto(`${BASE}/#/monitor`, { waitUntil: 'domcontentloaded' });
59  await page.waitForTimeout(1600);
60  await shot('22-monitor-after-chat');
61  await page.goto(`${BASE}/#/serving`, { waitUntil: 'domcontentloaded' });
62  await page.waitForTimeout(1400);
63  await shot('23-serving-with-requests');
64}
65
66if (flow === 'expert') {
67  await page.goto(`${BASE}/#/tuning`, { waitUntil: 'domcontentloaded' });
68  await page.waitForTimeout(900);
69  /* The mode control is `.st-tab`, not `.seg__btn` — the flow kept the older
70     class and had been failing on a selector that no longer existed. */
71  await page.click('.st-tab:has-text("Expert")');
72  await page.waitForTimeout(900);
73  await shot('30-tuning-expert');
74  await page.fill('input[placeholder="Search parameters"]', 'cache');
75  await page.waitForTimeout(600);
76  await shot('31-tuning-expert-search');
77  await page.click('.st-tab:has-text("Raw")');
78  await page.waitForTimeout(600);
79  await shot('32-tuning-raw');
80}
81
82if (flow === 'expert-light') {
83  await page.goto(`${BASE}/#/tuning`, { waitUntil: 'domcontentloaded' });
84  await page.waitForTimeout(1200);
85  await page.click('.st-tab:has-text("Expert")');
86  await page.waitForTimeout(800);
87  await shot('98-expert-light');
88}
89
90if (flow === 'setup') {
91  const next = () => page.getByRole('button', { name: 'Continue', exact: true }).first();
92  await page.goto(`${BASE}/#/setup`, { waitUntil: 'domcontentloaded' });
93  await page.waitForTimeout(1800);
94  await shot('40-setup-1-check');
95  /* The wizard only offers "Continue" while it is still being worked through.
96     Once setup is complete the host says so and the screen shows the finished
97     path instead — so this flow reports that rather than timing out on a button
98     that is correctly absent. */
99  const state = await page.evaluate(async () => {
100    const r = await fetch('/api/setup').then((x) => x.json());
101    return { complete: r.complete };
102  });
103  if (state.complete) {
104    console.log('setup is already complete on this host — the wizard shows its finished path.');
105    console.log('The mid-wizard steps are not reachable without resetting it; see plan 09.');
106    await browser.close();
107    process.exit(0);
108  }
109  await next().click();
110  await page.waitForTimeout(900);
111  await shot('41-setup-2-model');
112  await page.getByText('Qwen · Q2_K', { exact: true }).first().click();
113  await page.waitForTimeout(400);
114  await next().click();
115  await page.waitForTimeout(800);
116  await shot('42-setup-3-basics');
117  await page.getByRole('button', { name: /Download & install/ }).click();
118  await page.waitForTimeout(3400);
119  await shot('43-setup-4-install');
120  await page.waitForTimeout(17000);
121  await shot('44-setup-4-done');
122}
123
124if (flow === 'tools') {
125  await page.click('text=New conversation');
126  await page.waitForTimeout(500);
127  await page.fill('textarea', 'Read the README in this workspace and summarise it for me');
128  await page.keyboard.press('Enter');
129  await page.waitForTimeout(3200);
130  await shot('70-tool-approval');
131  await page.keyboard.press('Enter');
132  await page.waitForTimeout(700);
133  await shot('71-tool-approved');
134  await page.waitForTimeout(6000);
135  await shot('72-tool-answered');
136}
137
138if (flow === 'readysummary') {
139  await page.goto(`${BASE}/#/settings`, { waitUntil: 'domcontentloaded' });
140  await page.waitForTimeout(2300);
141  await page.click('text=Run setup again');
142  await page.waitForTimeout(2500);
143  const here = await page.evaluate(() => document.querySelector('.step[aria-current]')?.textContent.replace(/\s+/g, ' ').trim());
144  console.log('wizard opens at:', here);
145
146  const out = await page.evaluate(() => {
147    const grids = [...document.querySelectorAll('.setupmodal__surface .metricgrid')];
148    const grid = grids[grids.length - 1];
149    if (!grid) return null;
150    const cards = [...grid.querySelectorAll('.st-metric')];
151    const tops = cards.map((m) => Math.round(m.closest('.st-card').getBoundingClientRect().top));
152    const perRow = {};
153    tops.forEach((t) => { perRow[t] = (perRow[t] ?? 0) + 1; });
154    return {
155      items: cards.map((m) => ({
156        label: m.querySelector('.st-metric__label')?.textContent.trim(),
157        value: m.querySelector('.st-metric__value')?.textContent.trim(),
158        sub: m.querySelector('.spec__sub')?.textContent.trim(),
159      })),
160      perRow: Object.values(perRow),
161    };
162  });
163  if (!out) { console.log('summary not found'); }
164  else {
165    out.items.forEach((c) => console.log(`  ${String(c.label).padEnd(14)} ${String(c.value).padEnd(22)} ${c.sub ?? ''}`));
166    const ctx = out.items.find((c) => c.label === 'Context');
167    const api = out.items.find((c) => c.label === 'Local API');
168    console.log('context shows a size, not a choice:', /^\d+K$/i.test(ctx?.value ?? ''), '<- it said "Recommended"');
169    console.log('local API leads with plain meaning:', api?.value === 'On this computer', '<- it said "127.0.0.1"');
170    console.log('cards per row                    :', JSON.stringify(out.perRow),
171      out.perRow.every((n) => n === out.perRow[0]) ? '(balanced)' : '(one orphaned)');
172  }
173  await shot('580-ready-summary');
174}
175
176if (flow === 'addskill') {
177  const calls = [];
178  await page.route('**/api/skills/add', (r) => {
179    calls.push(r.request().method());
180    return r.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ cancelled: true }) });
181  });
182  await page.goto(`${BASE}/#/skills`, { waitUntil: 'domcontentloaded' });
183  await page.waitForTimeout(1800);
184
185  await page.fill('input[placeholder="Search skills"]', 'commit');
186  await page.waitForTimeout(400);
187  const typed = await page.inputValue('input[placeholder="Search skills"]');
188  await page.click('text=Add from folder');
189  await page.waitForTimeout(1100);
190  const after = await page.inputValue('input[placeholder="Search skills"]');
191  console.log('search box untouched:', after === typed, '<- the button used to clear it, and do nothing else');
192  console.log('asks the host to add:', calls.length === 1, `(${calls[0] ?? 'no'} request)`);
193
194  const titles = await page.evaluate(() =>
195    [...document.querySelectorAll('.st-tab')].slice(0, 3).map((t) => `${t.textContent} — ${t.title}`));
196  console.log('scope options now say:');
197  titles.forEach((t) => console.log('   ', t));
198  console.log('"Here" names the workspace:', /design-iteration|workspace/.test(titles[1] ?? ''), '<- it said only "Here"');
199  await shot('570-add-from-folder');
200}
201
202if (flow === 'filepreview') {
203  await page.goto(`${BASE}/#/workspace`, { waitUntil: 'domcontentloaded' });
204  await page.waitForTimeout(1800);
205  await page.evaluate(() => {
206    const file = [...document.querySelectorAll('.treerow')].find((r) => r.dataset.kind === 'file');
207    file?.click();
208  });
209  await page.waitForTimeout(1300);
210
211  const read = () => page.evaluate(() => {
212    const el = document.querySelector('.filepreview__body');
213    if (!el) return null;
214    const parse = (c) => { const n = String(c).match(/[\d.]+/g); return n ? { r: +n[0], g: +n[1], b: +n[2], a: n[3] === undefined ? 1 : +n[3] } : null; };
215    const lum = ({ r, g, b }) => { const f = (v) => { v /= 255; return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4; }; return 0.2126 * f(r) + 0.7152 * f(g) + 0.0722 * f(b); };
216    const ratio = (a, b) => { const [hi, lo] = [lum(a), lum(b)].sort((x, y) => y - x); return Number(((hi + 0.05) / (lo + 0.05)).toFixed(2)); };
217    const cs = getComputedStyle(el);
218    let bg = null;
219    let n = el;
220    while (n) { const c = parse(getComputedStyle(n).backgroundColor); if (c && c.a > 0.9) { bg = c; break; } n = n.parentElement; }
221    return {
222      ratio: ratio(parse(cs.color), bg),
223      overflowX: cs.overflowX,
224      clipped: el.scrollWidth - el.clientWidth,
225      scrollable: el.scrollWidth > el.clientWidth && cs.overflowX !== 'hidden',
226      lines: el.textContent.split('\n').length,
227      longest: Math.max(...el.textContent.split('\n').map((l) => l.length)),
228    };
229  });
230
231  const before = await read();
232  console.log('contrast          :', before.ratio, '(needs 4.5) <- it was #303030 on #1b1f23, a ratio of 1.26');
233  console.log('lines / longest   :', before.lines, '/', before.longest, 'chars');
234  console.log('overflows by      :', before.clipped + 'px');
235  console.log('can be reached    :', before.scrollable, '<- overflow was hidden, so the rest of every long line was unreachable');
236
237  await page.evaluate(() => { document.querySelector('.filepreview__body').scrollLeft = 300; });
238  await page.waitForTimeout(300);
239  const scrolled = await page.evaluate(() => document.querySelector('.filepreview__body').scrollLeft);
240  console.log('scrolls           :', scrolled > 0, `(scrollLeft ${scrolled})`);
241  await shot('560-file-preview');
242}
243
244if (flow === 'endpoints') {
245  await page.goto(`${BASE}/#/serving`, { waitUntil: 'domcontentloaded' });
246  await page.waitForTimeout(2000);
247  const read = () => page.evaluate(() => [...document.querySelectorAll('.compatrow')].map((r) => {
248    const url = r.querySelector('.compatrow__url');
249    const lines = (el) => { const rg = document.createRange(); rg.selectNodeContents(el); return rg.getClientRects().length; };
250    return {
251      label: r.querySelector('.compatrow__label').textContent,
252      url: url.textContent,
253      clipped: url.scrollWidth > url.clientWidth + 1,
254      urlLines: lines(url),
255      rowH: Math.round(r.getBoundingClientRect().height),
256    };
257  }));
258
259  const wide = await read();
260  wide.forEach((r) => console.log(`  ${r.label.padEnd(22)} ${r.rowH}px  url ${r.urlLines} line(s)  ${r.clipped ? 'CLIPPED' : 'full'}`));
261  console.log('nothing truncated      :', wide.every((r) => !r.clipped), '<- the longest address used to end in "…/completi…"');
262  console.log('rows equal at this width:', new Set(wide.map((r) => r.rowH)).size === 1);
263
264  const access = await page.evaluate(() => {
265    const card = [...document.querySelectorAll('.grid--2 > .st-card')].find((c) => /^Access/.test(c.textContent.trim()));
266    const r = card.getBoundingClientRect();
267    const rows = [...card.querySelectorAll('.field, .row')];
268    const last = Math.max(...rows.map((x) => x.getBoundingClientRect().bottom));
269    return { cardH: Math.round(r.height), contentH: Math.round(last - r.top) };
270  });
271  console.log('access card           :', access.cardH + 'px card,', access.contentH + 'px content',
272    '<- it was 758px tall holding 260px');
273
274  await page.click('.compatrow .st-btn--icon >> nth=0');
275  await page.waitForTimeout(400);
276  const copied = await page.evaluate(() => navigator.clipboard.readText().catch(() => 'unavailable'));
277  console.log('copy still returns the full url:', copied);
278  await shot('550-endpoints');
279}
280
281if (flow === 'contexthistory') {
282  await page.goto(`${BASE}/#/chat`, { waitUntil: 'domcontentloaded' });
283  await page.waitForTimeout(1500);
284  await page.click('text=New session');
285  await page.waitForTimeout(400);
286  const ctx = () => page.evaluate(async () => {
287    const m = await fetch('/api/monitor').then((r) => r.json());
288    return { used: m.context.usedTokens, msgs: m.context.parts.messages, pct: Number(m.context.pct.toFixed(1)) };
289  });
290  const start = await ctx();
291  console.log('start        :', JSON.stringify(start));
292
293  let prev = start.msgs;
294  let grew = 0;
295  for (const msg of ['write a short paragraph about tides', 'and one about the moon', 'and one about wind']) {
296    await page.fill('textarea', msg);
297    await page.keyboard.press('Enter');
298    await page.waitForTimeout(8000);
299    await page.keyboard.press('Enter').catch(() => {});
300    await page.waitForTimeout(4000);
301    const c = await ctx();
302    const up = c.msgs > prev;
303    if (up) grew += 1;
304    console.log(`turn ${grew + 1}       : used ${c.used}, messages-part ${c.msgs}`, up ? '' : '<- NO GROWTH');
305    prev = c.msgs;
306  }
307  console.log('grows with the conversation:', grew >= 2, '<- it sat at ~350 however long the conversation got');
308  console.log('the model receives prior turns:', grew >= 2, '<- history was never sent, so every message was a first message');
309  const end = await ctx();
310  console.log('used == current occupancy, not a running total:', end.used < 32768, `(${end.pct}%)`);
311  await shot('540-context-history');
312}
313
314if (flow === 'effectpanel') {
315  await page.goto(`${BASE}/#/tuning`, { waitUntil: 'domcontentloaded' });
316  await page.waitForTimeout(2000);
317  const out = await page.evaluate(() => {
318    const rows = [...document.querySelectorAll('.effectrow')].map((r) => {
319      const label = r.querySelector(':first-child');
320      const value = r.querySelector(':last-child');
321      // where does the text actually break?
322      const range = document.createRange();
323      range.selectNodeContents(value);
324      const boxes = [...range.getClientRects()].map((b) => Math.round(b.width));
325      return { label: label.textContent.trim(), value: value.textContent.trim(), lines: boxes.length, widths: boxes };
326    });
327    const notes = [...document.querySelectorAll('.st-card ul li')].map((li) => li.textContent.trim());
328    return { rows, notes, breakdown: notes.filter((n) => /weights/.test(n)).length };
329  });
330  out.rows.forEach((r) => console.log(`  ${r.label.padEnd(16)} ${r.lines} line(s)  ${JSON.stringify(r.widths)}  ${r.value}`));
331  console.log('model breakdown mentioned:', out.breakdown, 'time(s) <- it appeared twice');
332  console.log('notes carry it once      :', out.breakdown === 1);
333  await shot('530-effect-panel');
334}
335
336if (flow === 'loadguard') {
337  await page.goto(`${BASE}/#/models`, { waitUntil: 'domcontentloaded' });
338  await page.waitForTimeout(1900);
339
340  const rows = await page.evaluate(() =>
341    [...document.querySelectorAll('.listrow')]
342      .filter((r) => r.querySelector('.listrow__title'))
343      .map((r) => {
344        const btn = r.querySelector('.listrow__side .st-btn');
345        return {
346          model: r.querySelector('.listrow__title').textContent.trim().slice(0, 20),
347          verdict: [...r.querySelectorAll('.st-pill')].map((x) => x.textContent.trim()).join('/'),
348          button: btn?.textContent.trim(),
349          primary: btn ? btn.className.includes('primary') : null,
350        };
351      }));
352  const oversized = rows.filter((r) => /Too large/.test(r.verdict));
353  console.log('unusable variants :', oversized.length);
354  console.log('their button      :', JSON.stringify(oversized.map((r) => r.button)));
355  console.log('none is a primary action:', oversized.every((r) => r.primary === false),
356    '<- a green one-click Load invited an action the app itself says cannot work');
357
358  // clicking one must ask first, and say what will happen
359  let asked = null;
360  page.on('dialog', async (d) => {
361    asked = d.message();
362    await d.dismiss();
363  });
364  await page.evaluate(() => {
365    const r = [...document.querySelectorAll('.listrow')].find((x) => /Too large/.test(x.textContent));
366    r?.querySelector('.listrow__side .st-btn')?.click();
367  });
368  await page.waitForTimeout(1200);
369  console.log('asks first        :', asked !== null);
370  console.log('names the cost    :', JSON.stringify(asked?.split('\n')[0]));
371  const loaded = await page.evaluate(async () => (await fetch('/api/models').then((x) => x.json())).loaded);
372  console.log('dismissing loads nothing:', loaded === 'qwen2.5-0.5b-q4km', `(loaded: ${loaded})`);
373  await shot('520-load-guard');
374}
375
376if (flow === 'focusmode') {
377  await page.goto(`${BASE}/#/chat`, { waitUntil: 'domcontentloaded' });
378  await page.waitForTimeout(1500);
379  await page.click('text=New session');
380  await page.waitForTimeout(400);
381  await page.fill('textarea', 'say hello in one line');
382  await page.keyboard.press('Enter');
383  await page.waitForTimeout(8000);
384  await page.keyboard.press('Enter').catch(() => {});
385  await page.waitForTimeout(4000);
386  // A second turn, so there is an earlier exchange to recede.
387  await page.fill('textarea', 'and one more line');
388  await page.keyboard.press('Enter');
389  await page.waitForTimeout(8000);
390  await page.keyboard.press('Enter').catch(() => {});
391  await page.waitForTimeout(4000);
392
393  const read = () => page.evaluate(() => {
394    const g = (sel) => {
395      const el = document.querySelector(sel);
396      if (!el) return null;
397      const r = el.getBoundingClientRect();
398      return { l: Math.round(r.left), r: Math.round(r.right), h: Math.round(r.height) };
399    };
400    const bubble = g('.st-msg--assistant .st-bubble');
401    const composer = g('.st-composer');
402    return {
403      composer: composer?.h,
404      reading: Math.round(document.querySelector('.main__body.chat').getBoundingClientRect().height),
405      alignL: bubble && composer ? bubble.l - composer.l : null,
406      alignR: bubble && composer ? composer.r - bubble.r : null,
407      hints: (() => { const e = document.querySelector('.composer__hints'); return e ? getComputedStyle(e).display : 'absent'; })(),
408      icons: [...document.querySelectorAll('.st-composer__bar .st-btn--icon')].filter((x) => getComputedStyle(x).display !== 'none').length,
409      telemetry: (() => { const e = document.querySelector('.telemetry'); return e ? getComputedStyle(e).display : 'absent'; })(),
410      canType: !!document.querySelector('.composer textarea'),
411      barKeys: [...document.querySelectorAll('.focusbar__keys > span')].map((s) => s.textContent.replace(/\s+/g, ' ').trim()),
412      exitLabel: document.querySelector('.focusbar button:last-of-type')?.textContent.trim() ?? '',
413      exitTitle: document.querySelector('.focusbar button:last-of-type')?.getAttribute('title'),
414    };
415  });
416
417  const normal = await read();
418  console.log('normal      : composer', normal.composer + 'px, reading area', normal.reading + 'px, alignment', normal.alignL);
419
420  await page.keyboard.press('Meta+Shift+F');
421  await page.mouse.move(1200, 820);
422  await page.waitForTimeout(1100);
423  const focus = await read();
424  console.log('focus       : composer', focus.composer + 'px, reading area', focus.reading + 'px');
425  console.log('reclaimed   :', focus.reading - normal.reading, 'px for the conversation');
426  console.log('composer aligns with the cards:', focus.alignL === 0 && focus.alignR === 0);
427  console.log('hint line   :', focus.hints, '| icon strip:', focus.icons, 'icons | telemetry:', focus.telemetry);
428  console.log('still usable:', focus.canType, '- the point is removing chrome, not the ability to reply');
429  console.log('keys grouped:', JSON.stringify(focus.barKeys));
430  console.log('exit is quiet:', focus.exitLabel === '', '| labelled', JSON.stringify(focus.exitTitle));
431
432  /* Earlier turns recede — or did not, for as long as this mode has existed.
433     `.st-msg` carried `animation: st-enter ... both`, and an animated value
434     outranks a normal declaration, so the keyframe's closing `opacity: 1` held
435     every turn at full strength. The dimming rule was in the stylesheet,
436     matched the element, and lost the cascade. */
437  const opacities = await page.evaluate(() =>
438    [...document.querySelectorAll('.chat__inner > .st-msg')].map((m) => getComputedStyle(m).opacity));
439  const earlier = opacities.slice(0, -2);
440  const current = opacities.slice(-2);
441  console.log('earlier turns recede :', earlier.length > 0 && earlier.every((o) => Number(o) < 0.9),
442    JSON.stringify(opacities), `(${opacities.length} turns)`);
443  console.log('current stays full   :', current.every((o) => Number(o) > 0.9));
444  await shot('510-focus-mode');
445}
446
447if (flow === 'railgeometry') {
448  await page.click('text=New session');
449  await page.waitForTimeout(400);
450  await page.fill('textarea', 'read the readme');
451  await page.keyboard.press('Enter');
452  await page.waitForTimeout(7000);
453  await page.keyboard.press('Enter').catch(() => {});
454  await page.waitForTimeout(4000);
455  await page.evaluate(() => document.querySelector('.nav__collapse')?.click());
456  await page.mouse.move(900, 700);
457  await page.waitForTimeout(800);
458
459  const out = await page.evaluate(() => {
460    const nav = document.querySelector('.nav');
461    const right = nav.getBoundingClientRect().right;
462    const items = [...nav.querySelectorAll('button, a, .navsession, .ws__name, .nav__brand')]
463      .filter((el) => { const r = el.getBoundingClientRect(); return r.width > 0 && r.height > 0; });
464    // text actually painted, not merely present in the DOM
465    const painted = (el) => [...el.querySelectorAll('*')].some((c) =>
466      !c.children.length && getComputedStyle(c).display !== 'none' &&
467      c.getBoundingClientRect().width > 6 && c.textContent.trim());
468    return {
469      items: items.length,
470      overflowing: items.filter((el) => el.getBoundingClientRect().right > right + 0.5).length,
471      clippedText: items.filter(painted).length,
472      sizes: [...new Set(items.map((el) => {
473        const r = el.getBoundingClientRect();
474        return `${Math.round(r.width)}x${Math.round(r.height)}`;
475      }))],
476      unlabelled: items.filter((el) => el.querySelector('svg') &&
477        !(el.getAttribute('title') || el.getAttribute('aria-label') || el.textContent.trim())).length,
478    };
479  });
480  console.log('items              :', out.items);
481  console.log('clipped text       :', out.clippedText, '<- a conversation used to render as the first 5px of its title');
482  console.log('overflowing the rail:', out.overflowing, '<- the 22px tree indent pushed a session past the edge');
483  console.log('target sizes       :', JSON.stringify(out.sizes));
484  console.log('icons with no label:', out.unlabelled);
485  await shot('500-rail-geometry');
486}
487
488if (flow === 'archive') {
489  for (const m of ['keep me', 'archive me']) {
490    await page.click('text=New session');
491    await page.waitForTimeout(400);
492    await page.fill('textarea', m);
493    await page.keyboard.press('Enter');
494    await page.waitForTimeout(7000);
495    await page.keyboard.press('Enter').catch(() => {});
496    await page.waitForTimeout(3200);
497  }
498  const rows = () => page.evaluate(() =>
499    [...document.querySelectorAll('.navsession__title')].map((t) => t.textContent));
500  console.log('before        :', JSON.stringify(await rows()));
501
502  await page.click('.navsession >> nth=0', { button: 'right' });
503  await page.waitForTimeout(500);
504  console.log('menu          :', JSON.stringify(await page.evaluate(() =>
505    [...document.querySelectorAll('.menu__item')].map((i) => i.textContent.trim()))));
506  await page.click('.menu__item:has-text("Archive")');
507  await page.waitForTimeout(700);
508  console.log('after archive :', JSON.stringify(await rows()), '<- leaves the list, nothing deleted');
509
510  // the search field is behind its own toggle, so open it the way the sidebar does
511  await page.evaluate(() => {
512    const b = [...document.querySelectorAll('button')]
513      .find((x) => /search/i.test(x.getAttribute('title') ?? x.getAttribute('aria-label') ?? ''));
514    b?.click();
515  });
516  await page.waitForTimeout(500);
517  await page.fill('input[placeholder="Search conversations"]', 'archive me');
518  await page.waitForTimeout(700);
519  console.log('found by search:', JSON.stringify(await rows()), '<- archived stays findable');
520  await shot('490-archive');
521}
522
523if (flow === 'aboutengine') {
524  await page.goto(`${BASE}/#/settings`, { waitUntil: 'domcontentloaded' });
525  await page.waitForTimeout(2100);
526  const metrics = await page.evaluate(() =>
527    [...document.querySelectorAll('.settings-body .st-metric')]
528      .map((m) => ({
529        label: m.querySelector('.st-metric__label')?.textContent.trim(),
530        value: m.querySelector('.st-metric__value')?.textContent.trim(),
531        sub: m.querySelector('.spec__sub')?.textContent.trim(),
532      }))
533      .filter((m) => m.label));
534  metrics.forEach((m) => console.log(`  ${String(m.label).padEnd(14)} ${String(m.value).padEnd(10)} ${m.sub ?? ''}`));
535  const engine = metrics.find((m) => m.label === 'Engine');
536  console.log('engine named    :', !!engine, '<- the one thing About was missing');
537  console.log('with its backend:', /metal|vulkan|cuda|cpu/.test(engine?.sub ?? ''));
538  // folder paths belong to Storage, not duplicated here
539  console.log('no duplicated paths:', !metrics.some((m) => /folder/i.test(m.label)));
540  await shot('480-about-engine');
541}
542
543if (flow === 'rowweight') {
544  await page.goto(`${BASE}/#/models`, { waitUntil: 'domcontentloaded' });
545  await page.waitForTimeout(1900);
546  const rows = await page.evaluate(() =>
547    [...document.querySelectorAll('.listrow')]
548      .filter((r) => r.querySelector('.listrow__title'))
549      .map((r) => ({
550        title: r.querySelector('.listrow__title').textContent.trim().slice(0, 22),
551        rec: r.hasAttribute('data-recommended'),
552        size: getComputedStyle(r.querySelector('.listrow__title')).fontSize,
553        edge: getComputedStyle(r, '::after').width,
554        separator: getComputedStyle(r, '::before').height,
555      })));
556  const rec = rows.find((r) => r.rec);
557  const rest = rows.filter((r) => !r.rec);
558  console.log('recommended row  :', JSON.stringify(rec));
559  console.log('one step larger  :', rec && rest.every((r) => parseFloat(rec.size) > parseFloat(r.size)));
560  console.log('accent edge only on it:', rec?.edge === '2px' && rest.every((r) => r.edge === 'auto'));
561  console.log('separator intact  :', rows.every((r) => r.separator === '1px'), '<- the edge uses ::after, so ::before keeps the separator');
562  await shot('470-model-weight');
563}
564
565if (flow === 'dismissal') {
566  // Needs a transcript with room to scroll, or "scroll" tests nothing.
567  const tall = await browser.newPage({ viewport: { width: 1512, height: 560 }, deviceScaleFactor: 1 });
568  await tall.goto(`${BASE}/#/chat`, { waitUntil: 'domcontentloaded' });
569  await tall.waitForTimeout(1500);
570  await tall.click('text=New session');
571  await tall.waitForTimeout(400);
572  for (const m of ['write a paragraph about tides', 'and another about the moon']) {
573    await tall.fill('textarea', m);
574    await tall.keyboard.press('Enter');
575    await tall.waitForTimeout(7500);
576    await tall.keyboard.press('Enter').catch(() => {});
577    await tall.waitForTimeout(3200);
578  }
579  const room = await tall.evaluate(() => {
580    const el = document.querySelector('.main__body.chat');
581    return el.scrollHeight - el.clientHeight;
582  });
583  console.log('scroll room      :', room, 'px (needed, or the scroll test proves nothing)');
584
585  const isOpen = (kind) => tall.evaluate((k) =>
586    k === 'telepop' ? !!document.querySelector('.telepop') : !!document.querySelector('.modal[data-open="true"]'), kind);
587  const blur = () => tall.evaluate(() => document.activeElement?.blur());
588
589  for (const [name, open] of [
590    ['palette', async () => { await blur(); await tall.keyboard.press('Meta+k'); }],
591    ['shortcuts', async () => { await blur(); await tall.keyboard.press('?'); }],
592    ['telepop', async () => { await tall.click('.telemetry__chip >> nth=0'); }],
593  ]) {
594    const out = [];
595    for (const [how, act] of [
596      ['esc', async () => { await blur(); await tall.keyboard.press('Escape'); }],
597      ['outside', async () => { await tall.mouse.click(200, 300); }],
598      ['scroll', async () => {
599        // upward: the transcript starts pinned to the bottom, so adding to
600        // scrollTop clamps to nothing and no scroll event fires
601        await tall.evaluate(() => {
602          const el = document.querySelector('.main__body.chat');
603          el.scrollTop = Math.max(0, el.scrollTop - 150);
604        });
605      }],
606    ]) {
607      await open();
608      await tall.waitForTimeout(550);
609      if (!(await isOpen(name))) { out.push(`${how}: N/A`); continue; }
610      await act();
611      await tall.waitForTimeout(500);
612      out.push(`${how}: ${(await isOpen(name)) ? 'stays' : 'closes'}`);
613    }
614    console.log(`${name.padEnd(10)}: ${out.join(' | ')}`);
615    await tall.keyboard.press('Escape');
616    await tall.waitForTimeout(300);
617  }
618  console.log('rule: anchored overlays leave with their content; unanchored ones ignore scroll');
619  await tall.screenshot({ path: '.shots/460-dismissal.png' });
620  await tall.close();
621}
622
623if (flow === 'railweight') {
624  await page.click('text=New session');
625  await page.waitForTimeout(400);
626  await page.fill('textarea', 'say hello');
627  await page.keyboard.press('Enter');
628  await page.waitForTimeout(7000);
629  await page.keyboard.press('Enter').catch(() => {});
630  await page.waitForTimeout(3500);
631  await page.click('button[title="Conversation context"]');
632  await page.waitForTimeout(800);
633
634  const out = await page.evaluate(() => {
635    const sec = document.querySelector('.railsection');
636    const cs = getComputedStyle(sec);
637    const body = document.querySelector('.contextpanel__body')?.innerText ?? '';
638    return {
639      sectionIsQuiet: cs.backgroundColor === 'rgba(0, 0, 0, 0)' && cs.boxShadow === 'none',
640      panelIsOneSurface: getComputedStyle(document.querySelector('.contextpanel')).backgroundColor !== 'rgba(0, 0, 0, 0)',
641      heads: [...document.querySelectorAll('.railsection .h4')].map((h) => h.textContent.trim()),
642      contextWindowMentions: (body.match(/Context window/g) ?? []).length,
643    };
644  });
645  console.log('sections are quiet   :', out.sectionIsQuiet, '(no fill, no shadow)');
646  console.log('the rail is one object:', out.panelIsOneSurface);
647  console.log('section heads        :', JSON.stringify(out.heads));
648  console.log('no repeated heading  :', out.contextWindowMentions === 1, '<- read "Context window / Context window / 6%" before');
649  await shot('450-rail-weight');
650}
651
652if (flow === 'skillscope') {
653  await page.goto(`${BASE}/#/skills`, { waitUntil: 'domcontentloaded' });
654  await page.waitForTimeout(1900);
655  const read = () => page.evaluate(() =>
656    [...document.querySelectorAll('.listrow')].map((r) => ({
657      name: r.querySelector('.listrow__title')?.textContent.slice(0, 18),
658      where: r.querySelector('.skillScope__where')?.textContent.trim() ?? null,
659    })));
660  console.log('at rest    :', JSON.stringify(await read()));
661
662  // narrow the first skill to this workspace, through the control
663  await page.evaluate(() => {
664    const row = document.querySelector('.listrow');
665    const here = [...row.querySelectorAll('.skillScope button')].find((b) => /Here/.test(b.textContent));
666    here?.click();
667  });
668  await page.waitForTimeout(900);
669  const scoped = await read();
670  console.log('after Here :', JSON.stringify(scoped[0]), '<- narrowed');
671
672  // the host should honour it: fires here, not elsewhere
673  await page.evaluate(async () => {
674    await fetch('/api/chat/stream', {
675      method: 'POST',
676      headers: { 'content-type': 'application/json' },
677      body: JSON.stringify({ message: 'write a commit message for these changes', workspaceId: 'root' }),
678    });
679  });
680  await page.waitForTimeout(2500);
681  const here = await page.evaluate(async () => {
682    const r = await fetch('/api/skills').then((x) => x.json());
683    return r[0].useCount;
684  });
685  await page.evaluate(async () => {
686    await fetch('/api/chat/stream', {
687      method: 'POST',
688      headers: { 'content-type': 'application/json' },
689      body: JSON.stringify({ message: 'write a commit message for these changes', workspaceId: 'elsewhere' }),
690    });
691  });
692  await page.waitForTimeout(2500);
693  const elsewhere = await page.evaluate(async () => {
694    const r = await fetch('/api/skills').then((x) => x.json());
695    return r[0].useCount;
696  });
697  console.log('fires in its workspace   :', here);
698  console.log('silent in another         :', elsewhere === here);
699
700  // widen again so the flow leaves no trace
701  await page.evaluate(() => {
702    const row = document.querySelector('.listrow');
703    const always = [...row.querySelectorAll('.skillScope button')].find((b) => /Always/.test(b.textContent));
704    always?.click();
705  });
706  await page.waitForTimeout(900);
707  console.log('restored   :', JSON.stringify((await read())[0]));
708  await shot('440-skill-scope');
709}
710
711if (flow === 'turnnav') {
712  const tall = await browser.newPage({ viewport: { width: 1512, height: 640 }, deviceScaleFactor: 1 });
713  await tall.goto(`${BASE}/#/chat`, { waitUntil: 'domcontentloaded' });
714  await tall.waitForTimeout(1500);
715  await tall.click('text=New session');
716  await tall.waitForTimeout(400);
717  for (const m of ['first question about tides', 'second question about the moon', 'third question about wind']) {
718    await tall.fill('textarea', m);
719    await tall.keyboard.press('Enter');
720    await tall.waitForTimeout(7500);
721    await tall.keyboard.press('Enter').catch(() => {});
722    await tall.waitForTimeout(3200);
723  }
724  await tall.keyboard.press('Meta+Shift+F');
725  await tall.waitForTimeout(800);
726  console.log('focus bar  :', await tall.evaluate(() => !!document.querySelector('.focusbar')));
727  console.log('keys taught:', await tall.evaluate(() =>
728    document.querySelector('.focusbar__keys')?.textContent.replace(/\s+/g, ' ').trim()));
729
730  const pos = () => tall.evaluate(() => Math.round(document.querySelector('.main__body.chat').scrollTop));
731  await tall.evaluate(() => { document.querySelector('.main__body.chat').scrollTop = 0; });
732  await tall.waitForTimeout(600);
733  const down = [await pos()];
734  for (let i = 0; i < 4; i += 1) {
735    await tall.keyboard.press('Alt+ArrowDown');
736    await tall.waitForTimeout(750);
737    down.push(await pos());
738  }
739  console.log('Alt+Down   :', JSON.stringify(down));
740  console.log('distinct   :', new Set(down).size, 'of', down.length, '<- every press advances, none stick');
741  const up = [];
742  for (let i = 0; i < 2; i += 1) {
743    await tall.keyboard.press('Alt+ArrowUp');
744    await tall.waitForTimeout(750);
745    up.push(await pos());
746  }
747  console.log('Alt+Up     :', JSON.stringify(up), '<- retreats');
748  await tall.keyboard.press('Meta+ArrowDown');
749  await tall.waitForTimeout(1000);
750  console.log('Cmd+Down   : gap', await tall.evaluate(() => {
751    const el = document.querySelector('.main__body.chat');
752    return Math.round(el.scrollHeight - el.scrollTop - el.clientHeight);
753  }), '<- ~0');
754  await tall.screenshot({ path: '.shots/430-focus-turns.png' });
755  await tall.close();
756}
757
758if (flow === 'herorest') {
759  await page.goto(`${BASE}/#/monitor`, { waitUntil: 'domcontentloaded' });
760  await page.waitForTimeout(1900);
761  const idle = await page.evaluate(() => {
762    const rest = document.querySelector('.herorest');
763    return {
764      resting: !!rest,
765      figures: rest
766        ? [...rest.querySelectorAll('.eyebrow')].map((e, i) =>
767            `${e.textContent}: ${rest.querySelectorAll('.h3')[i]?.textContent.replace(/\s+/g, ' ').trim()}`)
768        : [],
769      /* Scoped to the hero. The page has five other progress bars — VRAM, RAM,
770         temperature and two unlabelled — and an unscoped query finds those and
771         reports the hero as unchanged. */
772      bar: (document.querySelector('.stack .st-card')?.querySelectorAll('.st-progress').length ?? 0) > 0,
773    };
774  });
775  console.log('idle — resting block :', idle.resting);
776  console.log('idle — figures       :', JSON.stringify(idle.figures, null, 1));
777  console.log('idle — 0% bar gone   :', !idle.bar);
778
779  await page.evaluate(() => {
780    void fetch('/api/chat/stream', {
781      method: 'POST',
782      headers: { 'content-type': 'application/json' },
783      body: JSON.stringify({ message: 'write a long paragraph about the sea and the moon' }),
784    });
785  });
786  await page.waitForTimeout(2200);
787  const busy = await page.evaluate(() => ({
788    phase: document.querySelector('.stack .st-card .h2')?.textContent,
789    resting: !!document.querySelector('.herorest'),
790    bar: (document.querySelector('.stack .st-card')?.querySelectorAll('.st-progress').length ?? 0) > 0,
791    label: [...document.querySelectorAll('.stack .st-card .muted')].map((e) => e.textContent)[0],
792  }));
793  console.log('busy — phase         :', JSON.stringify(busy.phase));
794  console.log('busy — progress bar  :', busy.bar, '| labelled', JSON.stringify(busy.label), '| resting hidden:', !busy.resting);
795  await shot('420-hero-rest');
796}
797
798if (flow === 'sparkhover') {
799  await page.goto(`${BASE}/#/monitor`, { waitUntil: 'domcontentloaded' });
800  await page.waitForTimeout(1500);
801  // give the series something to show
802  await page.evaluate(() => {
803    void fetch('/api/chat/stream', {
804      method: 'POST',
805      headers: { 'content-type': 'application/json' },
806      body: JSON.stringify({ message: 'write a long paragraph about the sea and the moon and the wind' }),
807    });
808  });
809  await page.waitForTimeout(9000);
810  const box = await page.evaluate(() => {
811    const el = document.querySelector('.spark');
812    const r = el.getBoundingClientRect();
813    return { x: Math.round(r.x), y: Math.round(r.y), w: Math.round(r.width), h: Math.round(r.height) };
814  });
815  for (const frac of [0.75, 0.9, 0.98]) {
816    await page.mouse.move(box.x + box.w * frac, box.y + box.h / 2);
817    await page.waitForTimeout(300);
818    console.log(`at ${String(Math.round(frac * 100)).padStart(2)}% :`, JSON.stringify(await page.evaluate(() =>
819      document.querySelector('.spark__readout')?.textContent ?? 'no readout')));
820  }
821  console.log('marker drawn :', await page.evaluate(() => !!document.querySelector('.spark line')));
822  await page.mouse.move(10, 400);
823  await page.waitForTimeout(300);
824  console.log('clears on leave:', await page.evaluate(() => !document.querySelector('.spark__readout')));
825  await shot('410-spark-hover');
826}
827
828if (flow === 'whythisone') {
829  await page.goto(`${BASE}/#/models`, { waitUntil: 'domcontentloaded' });
830  await page.waitForTimeout(1900);
831  const out = await page.evaluate(() => {
832    const why = document.querySelector('.whyline');
833    return {
834      recommendedPills: [...document.querySelectorAll('.st-pill')].filter((x) => /Recommended/.test(x.textContent)).length,
835      why: why?.textContent.replace(/\s+/g, ' ').trim() ?? null,
836      onRow: why?.closest('.listrow')?.querySelector('.listrow__title')?.textContent.trim().slice(0, 28) ?? null,
837      // exactly one variant is recommended, so exactly one explains itself
838      whyCount: document.querySelectorAll('.whyline').length,
839    };
840  });
841  console.log('recommended pills:', out.recommendedPills, '(want exactly 1)');
842  console.log('explains itself  :', JSON.stringify(out.why));
843  console.log('on which row     :', JSON.stringify(out.onRow));
844  console.log('one reason only  :', out.whyCount === 1);
845  await shot('400-why-this-one');
846}
847
848if (flow === 'paramgroups') {
849  await page.goto(`${BASE}/#/tuning`, { waitUntil: 'domcontentloaded' });
850  await page.waitForTimeout(1700);
851  await page.click('.st-tab:has-text("Expert")');
852  await page.waitForTimeout(900);
853  const out = await page.evaluate(() => ({
854    headings: [...document.querySelectorAll('.paramgroup')].map((r) => r.textContent.replace(/\s+/g, ' ').trim()),
855    params: document.querySelectorAll('.st-table tbody tr:not(.paramgroup)').length,
856    // the group name should appear as a heading, not repeated on every row
857    repeats: [...document.querySelectorAll('td .xs.muted')]
858      .filter((e) => /^(Context & memory|Performance|Sampling|Server|Advanced)$/.test(e.textContent)).length,
859  }));
860  console.log('sections     :', JSON.stringify(out.headings, null, 1));
861  console.log('param rows   :', out.params);
862  console.log('name repeats :', out.repeats, '<- 0 means structure, not a label read 30 times');
863  await page.fill('input[placeholder="Search parameters"]', 'cache');
864  await page.waitForTimeout(600);
865  console.log('after search :', JSON.stringify(await page.evaluate(() =>
866    [...document.querySelectorAll('.paramgroup')].map((r) => r.textContent.replace(/\s+/g, ' ').trim()))));
867  await shot('390-param-groups');
868}
869
870if (flow === 'dlcost') {
871  await page.goto(`${BASE}/#/models`, { waitUntil: 'domcontentloaded' });
872  await page.waitForTimeout(1800);
873  console.log('visible rows:', await page.evaluate(() => document.querySelectorAll('.listrow').length));
874  /* Scoped to the body: the sidebar also has a "More" button, and an unscoped
875     text match clicks that one instead. */
876  await page.click('.main__body button:has-text("Show")');
877  await page.waitForTimeout(900);
878  const cost = await page.evaluate(() =>
879    [...document.querySelectorAll('button')].map((b) => b.textContent.trim()).filter((t) => /Download/.test(t)));
880  console.log('download cost as size and time:', JSON.stringify(cost, null, 1));
881  console.log('every download names a time:', cost.length > 0 && cost.every((c) => /about \d+ min/.test(c)));
882  await shot('380-download-cost');
883}
884
885if (flow === 'servingsort') {
886  await page.goto(`${BASE}/#/serving`, { waitUntil: 'domcontentloaded' });
887  await page.waitForTimeout(1800);
888  const first = () => page.evaluate(() => {
889    const row = document.querySelector('tbody tr');
890    return row ? [...row.querySelectorAll('td')].map((td) => td.textContent.trim())[0] : 'no rows';
891  });
892  const active = () => page.evaluate(() => {
893    const th = document.querySelector('th [aria-sort]:not([aria-sort="none"])');
894    return th ? `${th.textContent.trim()} ${th.getAttribute('aria-sort')}` : 'none';
895  });
896  console.log('rows        :', await page.evaluate(() => document.querySelectorAll('tbody tr').length));
897  console.log('default     :', await active(), '| first row', await first());
898  await page.click('th:has-text("Duration") button');
899  await page.waitForTimeout(450);
900  console.log('by duration :', await active(), '| first row', await first());
901  await page.click('th:has-text("Duration") button');
902  await page.waitForTimeout(450);
903  console.log('reversed    :', await active(), '| first row', await first(), '<- the order really changed');
904  await page.click('th:has-text("Client") button');
905  await page.waitForTimeout(450);
906  console.log('by client   :', await active());
907  console.log('one column sorted at a time:', await page.evaluate(() =>
908    document.querySelectorAll('th [aria-sort]:not([aria-sort="none"])').length) === 1);
909  await shot('370-serving-sort');
910}
911
912if (flow === 'skillgroups') {
913  await page.goto(`${BASE}/#/skills`, { waitUntil: 'domcontentloaded' });
914  await page.waitForTimeout(1900);
915  const read = () => page.evaluate(() => ({
916    groups: [...document.querySelectorAll('.skillgroup__head')].map((h) => h.textContent.replace(/\s+/g, ' ').trim()),
917    rows: document.querySelectorAll('.listrow').length,
918  }));
919  const all = await read();
920  console.log('groups        :', JSON.stringify(all.groups));
921  console.log('rows          :', all.rows);
922  await page.fill('input[type=search], .st-input', 'commit');
923  await page.waitForTimeout(600);
924  const filtered = await read();
925  console.log('filtered      :', JSON.stringify(filtered.groups), '<- empty groups drop out');
926  console.log('matching rows :', JSON.stringify(await page.evaluate(() =>
927    [...document.querySelectorAll('.listrow__title')].map((t) => t.textContent))));
928  await shot('360-skill-groups');
929}
930
931if (flow === 'overlayresize') {
932  const wide = await browser.newPage({ viewport: { width: 1512, height: 1000 }, deviceScaleFactor: 1 });
933  await wide.goto(`${BASE}/#/chat`, { waitUntil: 'domcontentloaded' });
934  await wide.waitForTimeout(1500);
935  await wide.click('text=New session');
936  await wide.waitForTimeout(400);
937  await wide.fill('textarea', 'hello');
938  await wide.keyboard.press('Enter');
939  await wide.waitForTimeout(7000);
940  await wide.keyboard.press('Enter').catch(() => {});
941  await wide.waitForTimeout(3500);
942  await wide.click('.telemetry__chip >> nth=0');
943  await wide.waitForTimeout(500);
944
945  const read = () => wide.evaluate(() => {
946    const el = document.querySelector('.telepop');
947    if (!el) return { present: false };
948    const r = el.getBoundingClientRect();
949    return { present: true, right: Math.round(r.right), vw: window.innerWidth,
950             offscreen: r.right > window.innerWidth + 2 || r.left < -2 };
951  });
952  console.log('at 1512 :', JSON.stringify(await read()));
953  for (const w of [1100, 900]) {
954    await wide.setViewportSize({ width: w, height: 1000 });
955    await wide.waitForTimeout(500);
956    console.log(`at ${w}  :`, JSON.stringify(await read()), '<- follows its chip, stays on screen');
957  }
958  await wide.setViewportSize({ width: 1512, height: 1000 });
959  await wide.close();
960}
961
962if (flow === 'completioncue') {
963  const short = await browser.newPage({ viewport: { width: 1512, height: 520 }, deviceScaleFactor: 1 });
964  await short.goto(`${BASE}/#/chat`, { waitUntil: 'domcontentloaded' });
965  await short.waitForTimeout(1500);
966  await short.click('text=New session');
967  await short.waitForTimeout(400);
968  for (const m of ['write a paragraph about tides', 'and another about the moon']) {
969    await short.fill('textarea', m);
970    await short.keyboard.press('Enter');
971    await short.waitForTimeout(8000);
972    await short.keyboard.press('Enter').catch(() => {});
973    await short.waitForTimeout(3500);
974  }
975  await short.evaluate(() => { document.querySelector('.main__body.chat').scrollTop = 0; });
976  await short.waitForTimeout(700);
977  console.log('pill while scrolled up:', await short.locator('.jumplatest').count());
978
979  await short.fill('textarea', 'one more paragraph please');
980  await short.keyboard.press('Enter');
981  let saw = false;
982  for (let i = 0; i < 90; i += 1) {
983    if (await short.evaluate(() => document.querySelector('.jumplatest')?.hasAttribute('data-finished') ?? false)) {
984      saw = true;
985      break;
986    }
987    await short.waitForTimeout(300);
988  }
989  console.log('completion cue fired  :', saw, '<- a reply finished off screen and said so');
990  console.log('cue animation         :', JSON.stringify(await short.evaluate(() => {
991    const cs = getComputedStyle(document.querySelector('.jumplatest'));
992    return { name: cs.animationName, duration: cs.animationDuration };
993  })));
994  await short.screenshot({ path: '.shots/350-completion-cue.png' });
995  await short.close();
996}
997
998if (flow === 'privacy') {
999  await page.goto(`${BASE}/#/settings`, { waitUntil: 'domcontentloaded' });
1000  await page.waitForTimeout(2200);
1001  const state = () => page.evaluate(() => {
1002    const t = [...document.querySelectorAll('.st-toggle')]
1003      .find((x) => /usage data/i.test(x.getAttribute('aria-label') ?? ''));
1004    return {
1005      checked: t?.getAttribute('aria-checked'),
1006      stored: JSON.parse(localStorage.getItem('strata.prefs.v2') ?? '{}').shareTelemetry,
1007    };
1008  });
1009  console.log('at rest      :', JSON.stringify(await state()), '<- a real false, not an omitted attribute');
1010  await page.click('.st-toggle[aria-label="Share anonymous usage data"]');
1011  await page.waitForTimeout(700);
1012  console.log('after toggling:', JSON.stringify(await state()));
1013  await page.reload({ waitUntil: 'domcontentloaded' });
1014  await page.waitForTimeout(2200);
1015  console.log('after reload :', JSON.stringify(await state()), '<- the choice is recorded');
1016
1017  // a privacy choice is not an appearance setting
1018  await page.fill('.settingsindex__search', 'reset appearance', { timeout: 8000 });
1019  await page.waitForTimeout(600);
1020  const clickIn = (label) => page.evaluate((t) => {
1021    const f = [...document.querySelectorAll('.settings-body .field')].find((x) => !x.hidden);
1022    [...f.querySelectorAll('button')].find((b) => b.textContent.trim() === t).click();
1023  }, label);
1024  await clickIn('Reset');
1025  await page.waitForTimeout(400);
1026  await clickIn('Reset');
1027  await page.waitForTimeout(900);
1028  console.log('after a reset:', JSON.stringify(await state()), '<- untouched by an appearance reset');
1029  await shot('340-privacy');
1030}
1031
1032if (flow === 'railclose') {
1033  await page.click('text=New session');
1034  await page.waitForTimeout(400);
1035  await page.fill('textarea', 'say hello');
1036  await page.keyboard.press('Enter');
1037  await page.waitForTimeout(7000);
1038  await page.keyboard.press('Enter').catch(() => {});
1039  await page.waitForTimeout(3500);
1040  await page.click('button[title="Conversation context"]');
1041  await page.waitForTimeout(700);
1042  console.log('header     :', JSON.stringify(await page.evaluate(() => {
1043    const head = document.querySelector('.contextpanel__head');
1044    const btn = head?.querySelector('button');
1045    return { closeTitle: btn?.getAttribute('title'), buttonText: btn?.textContent.trim() };
1046  })));
1047  console.log('sections   :', await page.evaluate(() =>
1048    document.querySelectorAll('.contextpanel__sections .railsection').length));
1049  await page.click('.contextpanel__head button');
1050  await page.waitForTimeout(800);
1051  console.log('rail dismissed:', await page.evaluate(() =>
1052    getComputedStyle(document.querySelector('.contextpanel')).visibility === 'hidden'));
1053  await shot('330-rail-close');
1054}
1055
1056if (flow === 'treekeys') {
1057  await page.goto(`${BASE}/#/workspace`, { waitUntil: 'domcontentloaded' });
1058  await page.waitForTimeout(1800);
1059  const at = () => page.evaluate(() => {
1060    const el = document.activeElement;
1061    return el?.classList.contains('treerow') ? `${el.dataset.path} (d${el.dataset.depth})` : el?.tagName;
1062  });
1063  console.log('tabbable rows:', await page.evaluate(() =>
1064    document.querySelectorAll('.treerow[tabindex="0"]').length), '(want exactly 1 — roving tabindex)');
1065  console.log('of          :', await page.evaluate(() => document.querySelectorAll('.treerow').length), 'rows');
1066
1067  await page.evaluate(() => document.querySelector('.treerow[tabindex="0"]').focus());
1068  console.log('start       :', await at());
1069  await page.keyboard.press('ArrowDown');
1070  console.log('Down        :', await at());
1071  await page.keyboard.press('ArrowDown');
1072  console.log('Down        :', await at());
1073  await page.keyboard.press('ArrowUp');
1074  console.log('Up          :', await at());
1075  await page.keyboard.press('ArrowRight');
1076  await page.waitForTimeout(350);
1077  console.log('Right       :', await at(), '<- opens or steps in');
1078  await page.keyboard.press('ArrowLeft');
1079  await page.waitForTimeout(350);
1080  console.log('Left        :', await at(), '<- closes or steps out');
1081  await page.keyboard.press('End');
1082  console.log('End         :', await at());
1083  await page.keyboard.press('Home');
1084  console.log('Home        :', await at());
1085  console.log('one tabbable after moving:', await page.evaluate(() =>
1086    document.querySelectorAll('.treerow[tabindex="0"]').length) === 1);
1087  console.log('scope figures:', await page.evaluate(() =>
1088    document.querySelector('.scopes')?.textContent.replace(/\s+/g, ' ').trim()));
1089  await shot('320-tree-keys');
1090}
1091
1092if (flow === 'readmark') {
1093  await page.goto(`${BASE}/#/chat`, { waitUntil: 'domcontentloaded' });
1094  await page.waitForTimeout(1600);
1095  await page.click('text=New session');
1096  await page.waitForTimeout(400);
1097  await page.fill('textarea', 'read the readme file in the repo');
1098  await page.keyboard.press('Enter');
1099  await page.waitForTimeout(9000);
1100  console.log('proposal names a real file:',
1101    await page.evaluate(() => /strata\/README\.md/.test(document.body.innerText)));
1102  await page.click('button:has-text("Approve")');
1103  await page.waitForTimeout(2500);
1104  console.log('persisted  :', await page.evaluate(() => localStorage.getItem('strata.touched.v1')));
1105
1106  await page.reload({ waitUntil: 'domcontentloaded' });
1107  await page.waitForTimeout(1800);
1108  await page.evaluate(() => { window.location.hash = '#/workspace'; });
1109  await page.waitForTimeout(2000);
1110  console.log('marked rows:', JSON.stringify(await page.evaluate(() =>
1111    [...document.querySelectorAll('.treerow[data-touched]')].map((r) => r.textContent.trim().slice(0, 22)))));
1112  console.log('marker title:', await page.evaluate(() =>
1113    document.querySelector('.treerow[data-touched]')?.getAttribute('title')));
1114  console.log('unread files unmarked:', await page.evaluate(() =>
1115    document.querySelectorAll('.treerow:not([data-touched])').length > 50));
1116  await shot('310-read-marker');
1117}
1118
1119if (flow === 'settingsreset') {
1120  await page.goto(`${BASE}/#/settings`, { waitUntil: 'domcontentloaded' });
1121  // seed a deliberately non-default set, then reload so the app applies it
1122  await page.evaluate(() => {
1123    localStorage.setItem('strata.prefs.v2', JSON.stringify({
1124      theme: 'dark', rail: true, focus: false, contentFontSize: 22,
1125      density: 'compact', motion: 'reduced', transparency: 'opaque', uiScale: 1.25,
1126    }));
1127  });
1128  await page.reload({ waitUntil: 'domcontentloaded' });
1129  await page.waitForTimeout(2200);
1130  const read = () => page.evaluate(() => ({
1131    theme: document.documentElement.dataset.theme ?? '(none)',
1132    scale: getComputedStyle(document.documentElement).getPropertyValue('--st-ui-scale').trim(),
1133    rail: JSON.parse(localStorage.getItem('strata.prefs.v2') ?? '{}').rail,
1134  }));
1135  console.log('seeded       :', JSON.stringify(await read()));
1136
1137  await page.fill('.settingsindex__search', 'reset appearance', { timeout: 8000 });
1138  await page.waitForTimeout(600);
1139  console.log('visible fields:', JSON.stringify(await page.evaluate(() =>
1140    [...document.querySelectorAll('.settings-body .field')].filter((f) => !f.hidden)
1141      .map((f) => f.querySelector('.field__label')?.textContent))));
1142
1143  const clickIn = (labelText) => page.evaluate((t) => {
1144    const f = [...document.querySelectorAll('.settings-body .field')].find((x) => !x.hidden);
1145    [...f.querySelectorAll('button')].find((b) => b.textContent.trim() === t).click();
1146  }, labelText);
1147
1148  await clickIn('Reset');
1149  await page.waitForTimeout(400);
1150  console.log('confirmation :', JSON.stringify(await page.evaluate(() => {
1151    const f = [...document.querySelectorAll('.settings-body .field')].find((x) => !x.hidden);
1152    return [...f.querySelectorAll('button')].map((b) => b.textContent.trim());
1153  })));
1154  await clickIn('Keep');
1155  await page.waitForTimeout(400);
1156  console.log('after Keep   :', JSON.stringify(await read()), '<- unchanged');
1157
1158  await clickIn('Reset');
1159  await page.waitForTimeout(400);
1160  await clickIn('Reset');
1161  await page.waitForTimeout(900);
1162  console.log('after Reset  :', JSON.stringify(await read()), '<- theme and scale restored, rail untouched');
1163  await shot('300-settings-reset');
1164}
1165
1166if (flow === 'jumplatest') {
1167  const short = await browser.newPage({ viewport: { width: 1512, height: 520 }, deviceScaleFactor: 1 });
1168  await short.goto(`${BASE}/#/chat`, { waitUntil: 'domcontentloaded' });
1169  await short.waitForTimeout(1500);
1170  await short.click('text=New session');
1171  await short.waitForTimeout(400);
1172  for (const m of ['write a paragraph about tides', 'and another about the moon', 'and one about the wind']) {
1173    await short.fill('textarea', m);
1174    await short.keyboard.press('Enter');
1175    await short.waitForTimeout(8000);
1176    await short.keyboard.press('Enter').catch(() => {});
1177    await short.waitForTimeout(4000);
1178  }
1179  const gap = () => short.evaluate(() => {
1180    const el = document.querySelector('.main__body.chat');
1181    return Math.round(el.scrollHeight - el.scrollTop - el.clientHeight);
1182  });
1183  console.log('turns            :', await short.locator('.st-msg').count());
1184  console.log('content-visibility:', await short.evaluate(() => getComputedStyle(document.querySelector('.st-msg')).contentVisibility));
1185  console.log('pinned at rest   : gap', await gap(), '| pill:', await short.locator('.jumplatest').count(), '<- 0 and hidden');
1186  await short.evaluate(() => { document.querySelector('.main__body.chat').scrollTop = 0; });
1187  await short.waitForTimeout(900);
1188  console.log('scrolled up      : gap', await gap(), '| pill:', await short.locator('.jumplatest').count());
1189  await short.click('.jumplatest');
1190  await short.waitForTimeout(2200);
1191  console.log('after jump       : gap', await gap(), '| pill:', await short.locator('.jumplatest').count(), '<- 0 and hidden');
1192  await short.screenshot({ path: '.shots/290-jumplatest.png' });
1193  await short.close();
1194}
1195
1196if (flow === 'settingssearch') {
1197  await page.goto(`${BASE}/#/settings`, { waitUntil: 'domcontentloaded' });
1198  await page.waitForTimeout(1700);
1199  const vis = () => page.evaluate(() => ({
1200    fields: [...document.querySelectorAll('.settings-body .field')].filter((f) => !f.hidden)
1201      .map((f) => f.querySelector('.field__label')?.textContent),
1202    sections: [...document.querySelectorAll('.settings-body section[id^=settings-]')].filter((s) => !s.hidden).length,
1203  }));
1204  const rest = await vis();
1205  console.log('at rest       :', rest.fields.length, 'fields in', rest.sections, 'sections');
1206
1207  await page.fill('.settingsindex__search', 'dark');
1208  await page.waitForTimeout(450);
1209  console.log('search "dark" :', JSON.stringify((await vis()).fields), '<- matched on the hint, not just the label');
1210
1211  await page.fill('.settingsindex__search', 'cache');
1212  await page.waitForTimeout(450);
1213  console.log('search "cache":', JSON.stringify((await vis()).fields));
1214
1215  await page.fill('.settingsindex__search', 'zzzz');
1216  await page.waitForTimeout(450);
1217  console.log('no match      :', await page.evaluate(() => document.querySelector('.empty__title')?.textContent),
1218    '| action:', await page.evaluate(() => document.querySelector('.empty button')?.textContent.trim()));
1219  await page.click('.empty button');
1220  await page.waitForTimeout(500);
1221  const back = await vis();
1222  console.log('after clear   :', back.fields.length, 'fields in', back.sections, 'sections');
1223  await shot('280-settings-search');
1224}
1225
1226if (flow === 'unread') {
1227  await page.click('text=New session');
1228  await page.waitForTimeout(400);
1229  await page.fill('textarea', 'a thread');
1230  await page.keyboard.press('Enter');
1231  await page.waitForTimeout(7000);
1232  await page.keyboard.press('Enter').catch(() => {});
1233  await page.waitForTimeout(3500);
1234  await page.click('text=New session');
1235  await page.waitForTimeout(600);
1236
1237  // make the older conversation look updated since it was last read
1238  await page.evaluate(async () => {
1239    // The chats are files on the host (owner decision 11-04): read them and save the older one again, as the page would.
1240    const h = { 'x-strata-client': 'ui' };
1241    const list = await (await fetch('/api/chats', { headers: h })).json();
1242    const raw = await Promise.all(list.chats.map(async (c) => (await (await fetch('/api/chats/' + encodeURIComponent(c.id), { headers: h })).json()).session));
1243    const older = raw.filter((s) => s.messages.length > 0).at(-1);
1244    if (older) {
1245      older.updatedAt = new Date(Date.now() + 120000).toISOString();
1246      older.lastReadAt = new Date(Date.now() - 120000).toISOString();
1247      await fetch('/api/chats/' + encodeURIComponent(older.id), { method: 'PUT', headers: h, body: JSON.stringify(older) });
1248    }
1249  });
1250  await page.reload({ waitUntil: 'domcontentloaded' });
1251  await page.waitForTimeout(1800);
1252  const info = await page.evaluate(() => {
1253    const rows = [...document.querySelectorAll('.ws__session')];
1254    const unread = rows.find((r) => r.querySelector('.navsession__unread'));
1255    return {
1256      marked: rows.map((r) => r.querySelector('.navsession__unread') ? r.querySelector('.navsession__title')?.textContent : null).filter(Boolean),
1257      dot: unread ? getComputedStyle(unread.querySelector('.navsession__unread')).width : null,
1258      metaFlex: rows[0] ? getComputedStyle(rows[0].querySelector('.navsession__meta')).flex : null,
1259    };
1260  });
1261  console.log('unread rows   :', JSON.stringify(info.marked));
1262  console.log('dot is a dot  :', info.dot, '(a broad `.navsession span` rule made this 42px)');
1263  console.log('timestamp not stretched:', info.metaFlex);
1264  await shot('270-unread');
1265}
1266
1267if (flow === 'servingfilter') {
1268  await page.goto(`${BASE}/#/serving`, { waitUntil: 'domcontentloaded' });
1269  await page.waitForTimeout(1600);
1270  const rows = () => page.locator('tbody tr').count();
1271  const all = await rows();
1272  console.log('rows total    :', all);
1273  console.log('filter chips  :', JSON.stringify(await page.evaluate(() =>
1274    [...document.querySelectorAll('.servefilter button')].map((x) => x.textContent.trim()))));
1275
1276  await page.click('.servefilter >> text=Errors');
1277  await page.waitForTimeout(500);
1278  console.log('errors filter :', await rows(), 'rows |',
1279    await page.evaluate(() => document.querySelector('.empty__title')?.textContent ?? 'table shown'));
1280
1281  await page.click('.servefilter >> text=All');
1282  await page.waitForTimeout(400);
1283  await page.fill('input[aria-label="Filter requests by client"]', 'zzzz');
1284  await page.waitForTimeout(500);
1285  console.log('no match      :', await page.evaluate(() => document.querySelector('.empty__title')?.textContent ?? 'NO MESSAGE'),
1286    '| action:', await page.evaluate(() => document.querySelector('.empty button')?.textContent.trim()));
1287  await page.click('.empty button');
1288  await page.waitForTimeout(500);
1289  console.log('after clear   :', await rows(), 'rows (was', all + ')');
1290  console.log('state pills carry a glyph:', await page.evaluate(() =>
1291    !!document.querySelector('tbody .st-badge svg use')));
1292  await shot('260-serving-filter');
1293}
1294
1295if (flow === 'empties') {
1296  // Every empty state should state the next move, not only the absence.
1297  const read = () => page.evaluate(() => {
1298    const el = document.querySelector('.empty');
1299    return el
1300      ? { title: el.querySelector('.empty__title')?.textContent,
1301          action: el.querySelector('button')?.textContent.trim() ?? null }
1302      : null;
1303  });
1304
1305  await page.goto(`${BASE}/#/skills`, { waitUntil: 'domcontentloaded' });
1306  await page.waitForTimeout(1500);
1307  await page.fill('input[type=search], .st-input', 'zzzzz');
1308  await page.waitForTimeout(600);
1309  console.log('skills filtered  :', JSON.stringify(await read()));
1310  await page.click('.empty button');
1311  await page.waitForTimeout(600);
1312  console.log('cleared          :', await page.locator('.listrow').count(), 'skills back');
1313
1314  await page.goto(`${BASE}/#/workspace`, { waitUntil: 'domcontentloaded' });
1315  await page.waitForTimeout(1500);
1316  await page.fill('input[placeholder="Filter files"]', 'zzzzz');
1317  await page.waitForTimeout(600);
1318  console.log('workspace filtered:', JSON.stringify(await read()));
1319  await page.click('.empty button');
1320  await page.waitForTimeout(700);
1321  console.log('cleared          :', await page.locator('.treerow').count(), 'rows back');
1322  // the assertion that matters: the pane is not blank, and it offers a way back
1323  const after = await read();
1324  console.log('filtered pane is not blank:', after !== null || (await page.locator('.treerow').count()) > 0);
1325  await shot('250-empty-states');
1326}
1327
1328if (flow === 'branch') {
1329  await page.click('text=New session');
1330  await page.waitForTimeout(400);
1331  await page.fill('textarea', 'say hello');
1332  await page.keyboard.press('Enter');
1333  await page.waitForTimeout(7000);
1334  await page.keyboard.press('Enter');
1335  await page.waitForTimeout(6500);
1336
1337  const view = () => page.evaluate(() => ({
1338    roles: [...document.querySelectorAll('.st-msg')].map((m) =>
1339      m.classList.contains('st-msg--user') ? 'user' : 'assistant'),
1340    url: location.hash.slice(0, 24),
1341  }));
1342  console.log('before    :', JSON.stringify(await view()));
1343
1344  // Continue is only offered on the newest reply, so check it before branching
1345  // away from the state that has one.
1346  const offeredBefore = await page.evaluate(() =>
1347    [...document.querySelectorAll('.st-msg--assistant')].map((m) =>
1348      [...m.querySelectorAll('button')].some((b) => b.title === 'Continue from here')));
1349  console.log('continue on the newest reply only:', JSON.stringify(offeredBefore));
1350  await page.click('.st-msg--assistant .st-msg__actions button[title="Continue from here"]');
1351  await page.waitForTimeout(1200);
1352  console.log('after continue:', JSON.stringify((await view()).roles), '<- a new turn was added');
1353  await page.waitForTimeout(8000);
1354
1355  // remember the original so "untouched" means unchanged by the branch, not a
1356  // hardcoded length
1357  const before = await page.evaluate(() =>
1358    (async () => { const h = { 'x-strata-client': 'ui' }; const l = await (await fetch('/api/chats', { headers: h })).json(); return Promise.all(l.chats.map(async (c) => (await (await fetch('/api/chats/' + encodeURIComponent(c.id), { headers: h })).json()).session)); })()
1359      .map((s) => ({ title: s.title, roles: s.messages.map((m) => m.role) })));
1360  const originalBefore = before.find((s) => !s.title.includes('branch'));
1361
1362  // now branch, from the very first user turn
1363  await page.click('.st-msg--user >> nth=0');
1364  await page.hover('.st-msg--user >> nth=0');
1365  await page.waitForTimeout(300);
1366  await page.click('.st-msg--user >> nth=0 >> xpath=.. >> css=.st-msg__actions button[title="Branch from here"]').catch(async () => {
1367    await page.evaluate(() => {
1368      const u = document.querySelector('.st-msg--user');
1369      [...u.querySelectorAll('button')].find((b) => b.title === 'Branch from here').click();
1370    });
1371  });
1372  await page.waitForTimeout(1100);
1373  console.log('from user :', JSON.stringify(await view()), '<- branch must show only the user turn, and the url must follow');
1374
1375  const sessions = await page.evaluate(() =>
1376    (async () => { const h = { 'x-strata-client': 'ui' }; const l = await (await fetch('/api/chats', { headers: h })).json(); return Promise.all(l.chats.map(async (c) => (await (await fetch('/api/chats/' + encodeURIComponent(c.id), { headers: h })).json()).session)); })()
1377      .map((s) => ({ title: s.title, roles: s.messages.map((m) => m.role) })));
1378  console.log('stored    :', JSON.stringify(sessions));
1379  const originalAfter = sessions.find((s) => !s.title.includes('branch'));
1380  console.log('original untouched by the branch:',
1381    JSON.stringify(originalAfter) === JSON.stringify(originalBefore));
1382
1383  await shot('240-branch-continue');
1384}
1385
1386if (flow === 'loaderror') {
1387  await page.goto(`${BASE}/#/models`, { waitUntil: 'domcontentloaded' });
1388  await page.waitForTimeout(1600);
1389  console.log('at rest:', (await page.locator('.verror').count()) === 0);
1390
1391  expectFailure(/Failed to load resource|ERR_FAILED/);
1392  await page.route('**/api/models/*/load', (r) => r.abort());
1393  /* Every installed variant on this machine is either already loaded or rated
1394     beyond it, so the load action is "Load anyway" and asks first. The flow
1395     accepts the confirmation and exercises the failure path behind it. */
1396  page.on('dialog', (d) => void d.accept());
1397  await page.evaluate(() => {
1398    const btn = [...document.querySelectorAll('button')]
1399      .find((b) => /^load( anyway)?$/i.test(b.textContent.trim()));
1400    btn?.click();
1401  });
1402  await page.waitForTimeout(1400);
1403  console.log('failed load:', await page.evaluate(() => {
1404    const el = document.querySelector('.verror');
1405    return el ? el.textContent.replace(/\s+/g, ' ').trim().slice(0, 60) : 'NOT SHOWN';
1406  }));
1407  await page.waitForTimeout(7000);
1408  console.log('t=8.4s inline:', await page.locator('.verror').count(), '| toasts:', await page.locator('.st-toast').count());
1409  await page.unroute('**/api/models/*/load');
1410  await page.click('.verror button');
1411  await page.waitForTimeout(3000);
1412  console.log('retry when recovered:', (await page.locator('.verror').count()) === 0 ? 'cleared' : 'STILL SHOWING');
1413  await shot('230-load-error');
1414}
1415
1416if (flow === 'actionerror') {
1417  await page.goto(`${BASE}/#/tuning`, { waitUntil: 'domcontentloaded' });
1418  await page.waitForTimeout(1600);
1419  console.log('no error at rest:', (await page.locator('.verror').count()) === 0);
1420
1421  // make the engine action fail — the abort is the point of this flow, so the
1422  // network error it produces is expected rather than a regression
1423  expectFailure(/Failed to load resource|ERR_FAILED/);
1424  await page.route('**/api/engine/restart', (r) => r.abort());
1425  await page.evaluate(() => {
1426    [...document.querySelectorAll('button')].find((b) => /restart engine/i.test(b.textContent))?.click();
1427  });
1428  await page.waitForTimeout(1200);
1429  console.log('t=1.2s  inline:', await page.locator('.verror').count(), '| toasts:', await page.locator('.st-toast').count());
1430  await page.waitForTimeout(7000);
1431  console.log('t=8.2s  inline:', await page.locator('.verror').count(), '| toasts:', await page.locator('.st-toast').count(),
1432    '<- toast expired, failure remains');
1433
1434  // retry while still failing, then with the route restored
1435  await page.click('.verror button');
1436  await page.waitForTimeout(1400);
1437  console.log('retry while failing :', (await page.locator('.verror').count()) > 0 ? 'error returns' : 'SILENTLY CLEARED');
1438  await page.unroute('**/api/engine/restart');
1439  await page.click('.verror button');
1440  await page.waitForTimeout(2000);
1441  console.log('retry when recovered:', (await page.locator('.verror').count()) === 0 ? 'cleared' : 'STILL SHOWING');
1442  await shot('220-action-error');
1443}
1444
1445if (flow === 'skilluse') {
1446  // a prompt that should trigger one skill and nothing else
1447  await page.goto(`${BASE}/#/chat`, { waitUntil: 'domcontentloaded' });
1448  await page.waitForTimeout(1500);
1449  await page.click('text=New session');
1450  await page.waitForTimeout(400);
1451  await page.fill('textarea', 'review this code and check my code for bugs');
1452  await page.keyboard.press('Enter');
1453  await page.waitForTimeout(7000);
1454  await page.keyboard.press('Enter').catch(() => {});
1455  await page.waitForTimeout(4000);
1456
1457  await page.goto(`${BASE}/#/skills`, { waitUntil: 'domcontentloaded' });
1458  await page.waitForTimeout(1500);
1459  const rows = await page.evaluate(() =>
1460    [...document.querySelectorAll('.listrow')].map((r) => ({
1461      name: r.querySelector('.listrow__title')?.textContent,
1462      meta: [...r.querySelectorAll('.xs.muted')].map((e) => e.textContent).find((t) => /Used|Not used/.test(t)),
1463    })));
1464  for (const r of rows) console.log(`  ${String(r.name).padEnd(20)} ${r.meta}`);
1465  console.log('every skill states its usage:', rows.every((r) => r.meta));
1466  await shot('210-skills-usage');
1467}
1468
1469if (flow === 'sessionmenu') {
1470  for (const msg of ['keep this one', 'delete this one']) {
1471    await page.click('text=New session');
1472    await page.waitForTimeout(350);
1473    await page.fill('textarea', msg);
1474    await page.keyboard.press('Enter');
1475    await page.waitForTimeout(3200);
1476  }
1477  const count = () => page.locator('.navsession').count();
1478  console.log('sessions:', await count());
1479
1480  await page.click('.navsession >> nth=0', { button: 'right' });
1481  await page.waitForTimeout(400);
1482  console.log('menu:', JSON.stringify(await page.evaluate(() =>
1483    [...document.querySelectorAll('.menu__item')].map((i) => i.textContent.trim()))));
1484  await page.click('.menu__item--danger');
1485  await page.waitForTimeout(400);
1486  await page.click('.st-btn--danger');
1487  await page.waitForTimeout(600);
1488  console.log('after delete:', await count());
1489
1490  await page.evaluate(() => document.querySelector('.navsession').focus());
1491  await page.keyboard.press('Delete');
1492  await page.waitForTimeout(350);
1493  console.log('Delete key arms confirm:', (await page.locator('.st-btn--danger').count()) > 0);
1494  await page.keyboard.press('Escape');
1495  await shot('200-session-menu');
1496}
1497
1498if (flow === 'rail') {
1499  await page.click('text=New session');
1500  await page.waitForTimeout(400);
1501  await page.fill('textarea', 'read the readme');
1502  await page.keyboard.press('Enter');
1503  await page.waitForTimeout(7000);
1504  await page.keyboard.press('Enter');
1505  await page.waitForTimeout(6000);
1506  await page.click('button[title="Conversation context"]');
1507  await page.waitForTimeout(700);
1508
1509  const state = () => page.evaluate(() => {
1510    const body = document.querySelector('.contextpanel__body');
1511    const secs = [...document.querySelectorAll('.railsection')];
1512    return {
1513      sections: secs.length,
1514      scrolls: body.scrollHeight > body.clientHeight + 2,
1515      firstRows: getComputedStyle(secs[0].querySelector('.railsection__body')).gridTemplateRows,
1516    };
1517  });
1518  console.log('all open    :', JSON.stringify(await state()));
1519  await page.click('.railsection__head >> nth=0');
1520  await page.waitForTimeout(120);
1521  console.log('mid-collapse:', JSON.stringify(await state()), '<- animating, not snapping');
1522  await page.waitForTimeout(450);
1523  console.log('collapsed   :', JSON.stringify(await state()));
1524
1525  const tools = await page.evaluate(() => {
1526    const sec = [...document.querySelectorAll('.railsection')].find((x) => x.textContent.includes('Tools in reach'));
1527    return [...sec.querySelectorAll('.railsection__inner .row')].map((r) => ({
1528      name: r.querySelector('.small.strong')?.textContent,
1529      used: r.hasAttribute('data-used'),
1530    }));
1531  });
1532  console.log('tools used  :', JSON.stringify(tools.filter((t) => t.used).map((t) => t.name)));
1533  await shot('190-context-rail');
1534}
1535
1536if (flow === 'skills') {
1537  await page.goto(`${BASE}/#/skills`, { waitUntil: 'domcontentloaded' });
1538  await page.waitForTimeout(1500);
1539  const rows = await page.locator('.listrow').count();
1540  console.log('skills listed:', rows);
1541  await page.click('text=Read instructions >> nth=0');
1542  await page.waitForTimeout(400);
1543  const detail = await page.evaluate(() => {
1544    const el = document.querySelector('.skilldetail__body');
1545    const tr = document.querySelector('.skilldetail__triggers');
1546    return { chars: el?.textContent.length ?? 0, triggers: tr ? tr.querySelectorAll('.st-pill').length : 0 };
1547  });
1548  console.log('instructions shown:', detail.chars, 'chars ·', detail.triggers, 'triggers');
1549  const all = await page.evaluate(async () => {
1550    const r = await fetch('/api/skills').then((x) => x.json());
1551    return r.filter((s) => !s.body).map((s) => s.name);
1552  });
1553  console.log('skills with no instruction text:', all.length ? all : 'none');
1554  await shot('180-skills-instructions');
1555}
1556
1557if (flow === 'sidebar') {
1558  for (const msg of ['alpha conversation', 'beta conversation']) {
1559    await page.click('text=New session');
1560    await page.waitForTimeout(350);
1561    await page.fill('textarea', msg);
1562    await page.keyboard.press('Enter');
1563    await page.waitForTimeout(3200);
1564  }
1565  const titles = () => page.evaluate(() =>
1566    [...document.querySelectorAll('.navsession__title')].map((e) => e.textContent));
1567  console.log('newest first :', JSON.stringify(await titles()));
1568
1569  await page.evaluate(() => {
1570    const rows = [...document.querySelectorAll('.ws__session')];
1571    rows[rows.length - 1].querySelector('.ws__pin').click();
1572  });
1573  await page.waitForTimeout(450);
1574  console.log('after pinning:', JSON.stringify(await titles()));
1575
1576  await page.evaluate(() => document.querySelector('.nav__collapse').focus());
1577  const walk = [];
1578  for (let i = 0; i < 4; i += 1) {
1579    await page.keyboard.press('ArrowDown');
1580    walk.push(await page.evaluate(() => (document.activeElement?.textContent ?? '').trim().slice(0, 20)));
1581  }
1582  console.log('arrow walk   :', JSON.stringify(walk));
1583  await page.keyboard.press('End');
1584  console.log('End -> ', await page.evaluate(() => (document.activeElement?.textContent ?? '').trim().slice(0, 20)));
1585  await shot('170-sidebar-keys');
1586}
1587
1588if (flow === 'retryedit') {
1589  await page.click('text=New session');
1590  await page.waitForTimeout(400);
1591  await page.fill('textarea', 'read the readme');
1592  await page.keyboard.press('Enter');
1593  await page.waitForTimeout(7000);
1594  await page.keyboard.press('Enter');
1595  await page.waitForTimeout(7000);
1596
1597  const counts = () => page.evaluate(() => ({
1598    user: document.querySelectorAll('.st-msg--user').length,
1599    assistant: document.querySelectorAll('.st-msg--assistant').length,
1600  }));
1601  console.log('after a turn  :', JSON.stringify(await counts()));
1602
1603  await page.hover('.st-msg--assistant');
1604  await page.waitForTimeout(250);
1605  await page.click('button[title="Ask again"]');
1606  await page.waitForTimeout(600);
1607  console.log('mid-retry     :', JSON.stringify(await counts()), '<- reply dropped, not duplicated');
1608  await page.waitForTimeout(8000);
1609  await page.keyboard.press('Enter').catch(() => {});
1610  await page.waitForTimeout(6000);
1611  console.log('after retry   :', JSON.stringify(await counts()));
1612
1613  await page.hover('.st-msg--user');
1614  await page.waitForTimeout(250);
1615  await page.click('button[title="Edit and ask again"]');
1616  await page.waitForTimeout(600);
1617  console.log('after edit    :', JSON.stringify(await counts()),
1618    '| composer:', JSON.stringify(await page.inputValue('textarea')),
1619    '| focus:', await page.evaluate(() => document.activeElement?.tagName));
1620  await shot('160-retry-edit');
1621}
1622
1623if (flow === 'palette') {
1624  await page.keyboard.press('Meta+k');
1625  await page.waitForTimeout(500);
1626
1627  // focus must land inside the surface, and stay there
1628  const inside = () => page.evaluate(() => {
1629    const m = [...document.querySelectorAll('.modal')].find((x) => x.dataset.open === 'true');
1630    return !!(m && document.activeElement && m.contains(document.activeElement));
1631  });
1632  console.log('focus inside on open:', await inside());
1633  for (let i = 0; i < 14; i += 1) await page.keyboard.press('Tab');
1634  console.log('focus inside after 14 Tabs:', await inside());
1635
1636  const top = () => page.evaluate(() =>
1637    [...document.querySelectorAll('.palette__row')].slice(0, 2).map((r) =>
1638      (r.querySelector('.navitem__text')?.textContent ?? '') +
1639      '[' + [...r.querySelectorAll('mark')].map((m) => m.textContent).join('') + ']'));
1640  for (const q of ['mtr', 'tune', 'api', '>unload', '@']) {
1641    await page.fill('.modal input', q);
1642    await page.waitForTimeout(260);
1643    console.log(`  ${q.padEnd(9)} -> ${JSON.stringify(await top())}`);
1644  }
1645  await page.keyboard.press('Escape');
1646  await page.waitForTimeout(400);
1647  console.log('closed:', await page.locator('.modal[data-open="true"]').count() === 0);
1648  await shot('150-palette-fuzzy');
1649}
1650
1651if (flow === 'telemetry') {
1652  await page.click('text=New session');
1653  await page.waitForTimeout(400);
1654  await page.fill('textarea', 'read the readme and summarise it');
1655  await page.keyboard.press('Enter');
1656  await page.waitForTimeout(7000);
1657  await page.keyboard.press('Enter');
1658  await page.waitForTimeout(7000);
1659
1660  const chips = await page.locator('.telemetry__chip').count();
1661  console.log('telemetry chips:', chips);
1662  const titles = ['Session statistics', 'Token usage', 'Context'];
1663  for (let i = 0; i < titles.length; i += 1) {
1664    await page.locator('.telemetry__chip').nth(i).click();
1665    await page.waitForTimeout(450);
1666    const head = await page.textContent('.telepop__head').catch(() => null);
1667    const rows = await page.locator('.telepop__row').count();
1668    console.log(`  ${titles[i]}: head="${head?.trim()}" rows=${rows}`);
1669    await shot(`14${i}-telepop-${titles[i].toLowerCase().replace(/ /g, '-')}`);
1670    await page.keyboard.press('Escape');
1671    await page.waitForTimeout(300);
1672    const gone = await page.locator('.telepop').count();
1673    if (gone !== 0) console.log(`  WARNING: ${titles[i]} did not close on Escape`);
1674  }
1675  await page.click('button[title="Switch to dark"]');
1676  await page.waitForTimeout(500);
1677  await page.locator('.telemetry__chip').nth(2).click();
1678  await page.waitForTimeout(450);
1679  await shot('143-telepop-dark');
1680  await page.keyboard.press('Escape');
1681}
1682
1683if (flow === 'focus') {
1684  await page.click('text=New conversation');
1685  await page.waitForTimeout(400);
1686  await page.fill('textarea', 'Explain what a KV cache does, in plain words');
1687  await page.keyboard.press('Enter');
1688  await page.waitForTimeout(7000);
1689  await shot('130-chat-normal');
1690  await page.keyboard.press('Meta+Shift+F');
1691  await page.waitForTimeout(900);
1692  await shot('131-focus-mode');
1693  // reading size should move only the conversation
1694  await page.keyboard.press('Escape');
1695  await page.waitForTimeout(700);
1696  const exited = await page.evaluate(() => !document.documentElement.dataset.focus);
1697  console.log('Esc left focus mode:', exited);
1698}
1699
1700if (flow === 'overlays') {
1701  await page.goto(`${BASE}/#/launch`, { waitUntil: 'domcontentloaded' });
1702  await page.waitForTimeout(1200);
1703  await page.keyboard.press('Meta+k');
1704  await page.waitForTimeout(700);
1705  await shot('120-palette');
1706  await page.type('.modal input', 'serv');
1707  await page.waitForTimeout(500);
1708  await shot('121-palette-filtered');
1709  await page.keyboard.press('Escape');
1710  await page.waitForTimeout(400);
1711  await page.keyboard.press('Meta+Slash');
1712  await page.waitForTimeout(700);
1713  await shot('122-shortcuts');
1714}
1715
1716if (flow === 'panel') {
1717  await page.click('text=New conversation');
1718  await page.waitForTimeout(500);
1719  await page.fill('textarea', 'Read the README and summarise it');
1720  await page.keyboard.press('Enter');
1721  await page.waitForTimeout(5200);
1722  await page.click('button[title="Conversation context"]');
1723  await page.waitForTimeout(1000);
1724  await shot('100-context-panel');
1725}
1726
1727if (flow === 'sampling') {
1728  await page.click('text=New conversation');
1729  await page.waitForTimeout(500);
1730  await page.click('button[title="Sampling — temperature and friends"]');
1731  await page.waitForTimeout(900);
1732  await shot('95-sampling-drawer');
1733  const slider = page.locator('.st-slider').first();
1734  await slider.focus();
1735  for (let i = 0; i < 6; i += 1) await page.keyboard.press('ArrowRight');
1736  await page.waitForTimeout(900);
1737  await shot('96-sampling-changed');
1738}
1739
1740if (flow === 'commands') {
1741  await page.click('text=New conversation');
1742  await page.waitForTimeout(400);
1743  await page.click('textarea');
1744  await page.type('textarea', '/');
1745  await page.waitForTimeout(600);
1746  await shot('80-slash-menu');
1747  await page.type('textarea', 'mon');
1748  await page.waitForTimeout(500);
1749  await shot('81-slash-filtered');
1750  await page.keyboard.press('Escape');
1751  await page.waitForTimeout(300);
1752  await page.keyboard.press('Meta+Slash');
1753  await page.waitForTimeout(700);
1754  await shot('82-shortcuts');
1755}
1756
1757if (flow.startsWith('tour')) {
1758  const prefix = process.argv[3] ?? 'tour';
1759  // tour-dark flips the theme first so both palettes are captured from one run.
1760  if (flow === 'tour-dark') {
1761    await page.click('button[title="Switch to dark"]');
1762    await page.waitForTimeout(600);
1763  }
1764  const routes = ['launch', 'chat', 'models', 'tuning', 'serving', 'monitor', 'workspace', 'skills', 'settings'];
1765  for (const r of routes) {
1766    await page.goto(`${BASE}/#/${r}`, { waitUntil: 'domcontentloaded' });
1767    await page.waitForTimeout(1600);
1768    await shot(`${prefix}-${r}`);
1769  }
1770  await page.goto(`${BASE}/#/setup`, { waitUntil: 'domcontentloaded' });
1771  await page.waitForTimeout(2000);
1772  await shot(`${prefix}-setup`);
1773}
1774
1775if (flow === 'light') {
1776  /* Sets the theme rather than toggling to it: this flow used to click
1777     "Switch to light", which only exists while the app is dark. Light is the
1778     default now, so the control was correctly absent and the flow failed on a
1779     button that should not have been there. */
1780  await page.evaluate(() => {
1781    const raw = JSON.parse(localStorage.getItem('strata.prefs.v2') ?? '{}');
1782    localStorage.setItem('strata.prefs.v2', JSON.stringify({ ...raw, theme: 'light' }));
1783  });
1784  await page.reload({ waitUntil: 'domcontentloaded' });
1785  await page.waitForTimeout(1200);
1786  await page.goto(`${BASE}/#/models`, { waitUntil: 'domcontentloaded' });
1787  await page.waitForTimeout(1200);
1788  await shot('50-models-light');
1789  await page.goto(`${BASE}/#/monitor`, { waitUntil: 'domcontentloaded' });
1790  await page.waitForTimeout(1400);
1791  await shot('51-monitor-light');
1792}
1793
1794await browser.close();
1795console.log(problems.length ? `problems:\n  ${problems.slice(0, 10).join('\n  ')}` : 'no console errors');