Skip to content

12 个视觉参考图库与浏览器无限画布 AI 创作台(5,700+ 素材、中英提示词、多图对比、ComfyUI & MCP)· Visual reference library & infinite-canvas AI studio in the browser

24.6 KB
Raw Blame
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { chromium } = require('playwright');

const root = path.join(__dirname, '..', 'src');
const mkImg = name => ({ t: name, m: name, i: name, o: name });
const angles = [
  { zh: '正面', en: 'front view', ...mkImg('icon-192.png') },
  { zh: '侧面', en: 'side view', ...mkImg('icon-512.png') },
];

const data = {
  'poses.json': [
    { id: '001', ti: '站姿一', zh: '站姿一', en: 'standing one', no: '1', cat: '站姿', line: '全身', lineEn: 'full body', angles },
    { id: '002', ti: '坐姿二', zh: '坐姿二', en: 'sitting two', no: '2', cat: '坐姿', line: '全身', lineEn: 'full body', angles },
  ],
  'depths.json': [
    { id: '001', pack: 'gia-depth', ti: '站姿一', zh: '站姿一', en: 'standing one', no: '1', cat: '站姿', line: '全身', lineEn: 'full body', angles },
  ],
  'costumes.json': [
    { id: 'c1', ti: '红色连衣裙', zh: '红色连衣裙', en: 'red dress', kw: 'red dress', no: '1', cat: '连衣裙', ...mkImg('swatch-demo.svg') },
    { id: 'c2', ti: '蓝色制服', zh: '蓝色制服', en: 'blue jacket', kw: 'blue jacket', no: '2', cat: '制服', ...mkImg('icon-512.png') },
  ],
  'portraits.json': [
    { id: 'p1', ti: '室内人像一', zh: '室内人像一', en: 'indoor portrait one', no: '1', cat: '室内', sec: '默认', st: '自然', ...mkImg('icon-192.png') },
  ],
};

async function run() {
  const browser = await chromium.launch({ executablePath: process.env.CHROME_PATH });
  try {
    const ctx = await browser.newContext({
      viewport: { width: 1366, height: 860 },
      reducedMotion: 'reduce',
      serviceWorkers: 'block',
      locale: 'zh-CN',
    });
    const page = await ctx.newPage();
    const errors = [];
    page.on('pageerror', err => errors.push(err.message));

    await page.addInitScript(() => {
      // Capture clipboard text & PNG image blobs deterministically in headless tests.
      window.__clipTexts = [];
      window.__clipBlobs = [];
      class MockClipboardItem {
        constructor(items) { this.items = items; }
      }
      window.ClipboardItem = MockClipboardItem;
      Object.defineProperty(navigator, 'clipboard', {
        configurable: true,
        value: {
          writeText: async text => { window.__clipTexts.push(text); },
          write: async items => {
            for (const item of items) {
              const map = item.items || {};
              for (const [type, blob] of Object.entries(map)) {
                const head = [...new Uint8Array(await blob.slice(0, 4).arrayBuffer())];
                window.__clipBlobs.push({ type, size: blob.size, head });
              }
            }
          },
        },
      });
    });

    await page.route('**/*', route => {
      const url = new URL(route.request().url());
      if (url.hostname !== 'posewear.test') return route.abort();
      const file = url.pathname.slice(1) || 'index.html';
      if (file === 'swatch-demo.svg') {
        const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="90" height="120"><rect width="90" height="40" fill="#C8233C"/><rect y="40" width="90" height="40" fill="#2B5B84"/><rect y="80" width="90" height="40" fill="#2E8B57"/></svg>';
        return route.fulfill({ contentType: 'image/svg+xml', body: svg });
      }
      if (file.endsWith('.json')) return route.fulfill({ json: data[file] || [] });
      const source = path.join(root, file);
      if (fs.existsSync(source)) return route.fulfill({ path: source });
      return route.fulfill({ status: 404, body: '' });
    });

    // 1. Notan 3-tone & Silhouette inspection in Lightbox and Gesture Studio
    await page.goto('http://posewear.test/#costume');
    await page.locator('#grid .card').first().waitFor();
    await page.locator('#grid .card').first().locator('.phk').click();
    await page.locator('#lbTools [data-lt=gray]').waitFor({ state: 'visible' });
    await page.locator('#lbTools [data-lt=sil]').waitFor({ state: 'visible' });

    await page.keyboard.press('b');
    assert.deepEqual(
      await page.evaluate(() => ({
        gray: document.querySelector('#lbStage').classList.contains('gray'),
        notan: document.querySelector('#lbStage').classList.contains('notan'),
        label: document.querySelector('#lbTools [data-lt=gray] span').textContent,
      })),
      { gray: true, notan: false, label: '灰度' }
    );
    await page.keyboard.press('b');
    assert.deepEqual(
      await page.evaluate(() => ({
        gray: document.querySelector('#lbStage').classList.contains('gray'),
        notan: document.querySelector('#lbStage').classList.contains('notan'),
        label: document.querySelector('#lbTools [data-lt=gray] span').textContent,
      })),
      { gray: true, notan: true, label: '明度块面' }
    );
    await page.keyboard.press('u');
    assert.deepEqual(
      await page.evaluate(() => ({
        gray: document.querySelector('#lbStage').classList.contains('gray'),
        notan: document.querySelector('#lbStage').classList.contains('notan'),
        sil: document.querySelector('#lbStage').classList.contains('sil'),
      })),
      { gray: false, notan: false, sil: true },
      'Silhouette mode (U) should activate .sil and clear grayscale/notan'
    );
    await page.keyboard.press('Escape');
    assert.ok(!(await page.locator('#lbStage').evaluate(el => el.classList.contains('sil'))));

    // Gesture Studio Notan & Silhouette
    await page.locator('#sketchBtn').click();
    await page.locator('#sketch').waitFor({ state: 'visible' });
    await page.keyboard.press('b');
    assert.ok(await page.locator('#skFrame').evaluate(el => el.classList.contains('gray') && !el.classList.contains('notan')));
    await page.keyboard.press('b');
    assert.ok(await page.locator('#skFrame').evaluate(el => el.classList.contains('gray') && el.classList.contains('notan')));
    assert.equal(await page.locator('#sketch [data-skt=gray]').textContent(), '明度块面');
    await page.keyboard.press('u');
    assert.ok(await page.locator('#skFrame').evaluate(el => el.classList.contains('sil') && !el.classList.contains('gray')));
    await page.keyboard.press('Escape');
    assert.ok(await page.locator('#sketch').isHidden());
    console.log('PASS 3-tone Notan & Silhouette inspection in Lightbox and Gesture Studio');

    // 2. Side-by-Side Reference Compare Studio from Batch Bar & Floating Tray
    await page.locator('#libraryMenu summary').click();
    await page.locator('.tabs [data-tab=pose]').click();
    await page.locator('#grid .card').first().waitFor();
    await page.locator('#batchBtn').click();
    await page.locator('#grid .card').nth(0).click();
    await page.locator('#grid .card').nth(1).click();

    await page.locator('#bbar [data-b=cmp]').waitFor({ state: 'visible' });
    await page.locator('#bbar [data-b=cmp]').click();
    await page.locator('#cmpModal').waitFor({ state: 'visible' });
    assert.equal(await page.locator('#cmpGrid .cmp-card').count(), 2);
    assert.equal(await page.locator('#cmpGrid').getAttribute('data-n'), '2');
    assert.equal(await page.locator('#cmpCount').textContent(), '2 / 4');

    // Synced tools: flip (H), grid (G), gray/notan (B), silhouette (U), pose/depth pair (V)
    await page.keyboard.press('h');
    assert.equal(await page.locator('#cmpGrid .cmp-stage.flipped').count(), 2);
    await page.keyboard.press('g');
    assert.equal(await page.locator('#cmpGrid .lb-grid[data-mode=thirds]').count(), 2);
    await page.keyboard.press('b');
    assert.equal(await page.locator('#cmpGrid .cmp-stage.gray').count(), 2);
    await page.keyboard.press('b');
    assert.equal(await page.locator('#cmpGrid .cmp-stage.notan').count(), 2);
    assert.equal(await page.locator('#cmpModal [data-ct=gray] span').textContent(), '明度块面');
    await page.keyboard.press('u');
    assert.equal(await page.locator('#cmpGrid .cmp-stage.sil').count(), 2);
    assert.equal(await page.locator('#cmpGrid .cmp-stage.gray').count(), 0);
    await page.locator('#cmpModal [data-ct=pair]').waitFor({ state: 'visible' });
    await page.keyboard.press('v');
    assert.equal(await page.locator('#cmpGrid .cmp-card[data-type=depth]').count(), 1, 'V should switch pairable pose card to depth');
    await page.keyboard.press('v');
    assert.equal(await page.locator('#cmpGrid .cmp-card[data-type=pose]').count(), 2);

    // Inline angle switch inside compare card
    await page.locator('#cmpGrid .cmp-card').first().locator('[data-cai="1"]').click();
    assert.ok((await page.locator('#cmpGrid .cmp-card').first().locator('img').getAttribute('src')).includes('icon-512.png'));

    // Removing one card when 2 remain closes compare modal cleanly
    await page.locator('#cmpGrid .cmp-card').first().locator('[data-ca=rm]').click();
    await page.locator('#cmpModal').waitFor({ state: 'hidden' });

    // Exit batch mode, add 2 items to selection, and open Compare Studio from Floating Workspace Dock (#trayCmp)
    await page.locator('#bbar [data-b=x]').click();
    await page.locator('#grid .card').nth(0).locator('[data-a=sel]').click();
    await page.locator('#grid .card').nth(1).locator('[data-a=sel]').click();
    await page.locator('#trayFab').click();
    await page.locator('#trayCmp').waitFor({ state: 'visible' });
    await page.locator('#trayCmp').click();
    await page.locator('#cmpModal').waitFor({ state: 'visible' });
    await page.keyboard.press('Escape');
    await page.locator('#cmpModal').waitFor({ state: 'hidden' });
    await page.locator('#trayMin').click();
    console.log('PASS Side-by-Side Reference Compare Studio (batch bar, tray, synced tools, pair & angle switch)');

    // 3. Studio Creative Suite: 12 styles, camera shot, negative prompt, multi-ecosystem export, clipboard PNG, relay presets
    await page.locator('.tabs [data-tab=studio]').click();
    await page.waitForFunction(() => window.WB && APP.st.tab === 'studio');
    assert.ok(await page.locator('#wbCopyBoard').isHidden(), 'Copy PNG should stay hidden on sample board');
    assert.equal(await page.locator('#wbStyles .chip').count(), 12, 'Studio should offer 12 style presets');

    await page.locator('#wbExample').click();
    await page.waitForFunction(() => document.querySelectorAll('#wbBoardCards .board-idx').length >= 2);
    assert.ok(await page.locator('#wbCopyBoard').isVisible());

    // Copy Board PNG to clipboard
    await page.locator('#wbCopyBoard').click();
    await page.waitForFunction(() => window.__clipBlobs.length >= 1);
    const copiedPng = await page.evaluate(() => window.__clipBlobs[0]);
    assert.equal(copiedPng.type, 'image/png');
    assert.ok(copiedPng.size > 4000);
    assert.deepEqual(copiedPng.head, [137, 80, 78, 71]);

    // Style (Turnaround sheet) + Camera Shot (85mm) + Negative prompt fill
    await page.locator('#wbStyles [data-style=sheet]').click();
    assert.match(await page.locator('#wbPrompt').inputValue(), /turnaround sheet/i);
    await page.selectOption('#wbShot', 'lens85');
    assert.match(await page.locator('#wbPrompt').inputValue(), /85mm portrait lens perspective/i);
    await page.locator('details.adv > summary').click();
    await page.locator('#wbNegFill').click();
    assert.match(await page.locator('#wbNeg').inputValue(), /malformed hands/i);
    assert.match(await page.locator('#wbPrompt').inputValue(), /Avoid: malformed hands/i);

    // Multi-ecosystem prompt formats (Midjourney / SD-NovelAI / JSON)
    await page.selectOption('#wbAR', '2:3');
    const formatted = await page.evaluate(() => ({
      mj: WB.formatPrompt('mj'),
      sd: WB.formatPrompt('sd'),
      json: JSON.parse(WB.formatPrompt('json')),
    }));
    assert.match(formatted.mj, /--no malformed hands/i);
    assert.match(formatted.mj, /--ar 2:3/);
    assert.match(formatted.sd, /Negative prompt:\s*malformed hands/i);
    assert.equal(formatted.json.style, 'sheet');
    assert.equal(formatted.json.shot, 'lens85');
    assert.equal(formatted.json.aspectRatio, '2:3');
    assert.match(formatted.json.negativePrompt, /malformed hands/i);
    assert.ok(Array.isArray(formatted.json.references) && formatted.json.references.length >= 2);

    await page.locator('#wbFmtMenu summary').click();
    await page.locator('#wbFmtMenu [data-fmt=mj]').click();
    assert.ok(await page.evaluate(() => window.__clipTexts.some(t => t.includes('--ar 2:3'))));

    // Custom Relay Presets
    await page.locator('#wbCfg').click();
    await page.locator('[name=prov][value=custom]').check();
    await page.locator('#cfPresetsW').waitFor({ state: 'visible' });
    assert.equal(await page.locator('#cfPresets [data-preset]').count(), 5);
    await page.locator('#cfPresets [data-preset=xai]').click();
    assert.equal(await page.locator('#cfBase').inputValue(), 'https://api.x.ai');
    assert.equal(await page.locator('#cfProto').inputValue(), 'xai');
    assert.equal(await page.locator('#cfModel').inputValue(), 'grok-imagine-image-2.0');
    assert.equal(await page.locator('#cfProxy').isChecked(), true);
    await page.locator('#cfPresets [data-preset=flux]').click();
    assert.equal(await page.locator('#cfProto').inputValue(), 'json');
    assert.equal(await page.locator('#cfModel').inputValue(), 'flux-2-pro');
    await page.locator('#cfgX').click();
    console.log('PASS Studio 12 styles, camera shot, negative prompt, multi-ecosystem export, board clipboard PNG & relay presets');

    // 3b. Infinite Spatial Canvas Studio: spatial layout, wires, output hub, zoom/tidy, drag card, prompt-linked sticky note, Zen Focus
    assert.equal(await page.locator('#wbPh0').getAttribute('data-layout'), 'spatial');
    await page.locator('#wbCanvasOutputs .cv-hub').waitFor({ state: 'visible' });
    await page.waitForFunction(() => document.querySelectorAll('#wbCanvasWires path.cv-wire').length >= 2);

    // Zoom & Reset
    await page.locator('#wbCanvasZoom [data-cv-act=zin]').click();
    const zoomedPct = await page.locator('#wbZoomPct').textContent();
    await page.locator('#wbCanvasZoom [data-cv-act=zreset]').click();
    assert.equal(await page.locator('#wbZoomPct').textContent(), '100%');
    assert.notEqual(zoomedPct, '100%');

    // Toggle semantic wires off/on
    await page.locator('#wbCanvasTools [data-cv-act=wires]').click();
    assert.equal(await page.locator('#wbCanvasWires path').count(), 0);
    await page.locator('#wbCanvasTools [data-cv-act=wires]').click();
    await page.waitForFunction(() => document.querySelectorAll('#wbCanvasWires path.cv-wire').length >= 2);

    // Drag a reference card smoothly without falsely opening the picker
    const firstCard = page.locator('#wbBoardCards .board-card').first();
    const beforePos = await firstCard.evaluate(el => ({ l: parseFloat(el.style.left), t: parseFloat(el.style.top) }));
    const box = await firstCard.boundingBox();
    await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
    await page.mouse.down();
    await page.mouse.move(box.x + box.width / 2 + 64, box.y + box.height / 2 + 32, { steps: 6 });
    await page.mouse.up();
    const afterPos = await firstCard.evaluate(el => ({ l: parseFloat(el.style.left), t: parseFloat(el.style.top) }));
    assert.ok(Math.abs(afterPos.l - beforePos.l) >= 32, 'Dragging card should move its spatial world position');
    assert.ok(await page.locator('#pk').isHidden(), 'Dragging card must not accidentally open picker');

    // Sticky Note with live prompt injection + toggle + delete
    await page.locator('#wbCanvasTools [data-cv-act=note]').click();
    const noteTa = page.locator('#wbCanvasNotes .cv-note textarea').first();
    await noteTa.waitFor({ state: 'visible' });
    await noteTa.fill('rim light dramatic haze');
    assert.match(await page.locator('#wbPrompt').inputValue(), /rim light dramatic haze/);
    await page.waitForFunction(() => document.querySelectorAll('#wbCanvasWires path.note-wire').length === 1);
    await page.locator('#wbCanvasNotes .cv-note [data-note-act=link]').first().click();
    assert.doesNotMatch(await page.locator('#wbPrompt').inputValue(), /rim light dramatic haze/);
    await page.locator('#wbCanvasNotes .cv-note [data-note-act=rm]').first().click();
    assert.equal(await page.locator('#wbCanvasNotes .cv-note').count(), 0);

    // Tidy & Zen Focus Canvas + Escape exit
    await page.locator('#wbCanvasTools [data-cv-act=tidy]').click();
    await page.locator('#wbCanvasZoom [data-cv-act=zen]').click();
    assert.ok(await page.locator('#studio').evaluate(el => el.classList.contains('zen')));
    assert.ok(await page.locator('#wbZenBar').isVisible());
    await page.keyboard.press('Escape');
    assert.ok(!(await page.locator('#studio').evaluate(el => el.classList.contains('zen'))));
    assert.ok(await page.locator('#wbZenBar').isHidden());
    console.log('PASS Infinite Spatial Canvas (drag, zoom, wires, output hub, prompt-linked sticky notes, Zen Focus)');

    // 4. Named Character & Scene Recipes (Save, Persist, Keep-Current-Pose Swap, Full Load, Delete+Undo, JSON Import)
    const savedPoseKey = await page.evaluate(() => WB._W.poses[0]?.k);
    assert.ok(savedPoseKey, 'Studio should have a pose selected from example');
    await page.locator('#wbRecipesBtn').click();
    await page.locator('#recipeBox').waitFor({ state: 'visible' });
    await page.fill('#rcpName', '银发机能风');
    await page.locator('#rcpSave').click();
    assert.equal(await page.locator('#wbRecipeN').textContent(), '1');
    assert.equal(await page.locator('#rcpList .recipe-name').first().textContent(), '银发机能风');
    await page.keyboard.press('Escape');
    await page.locator('#recipeBox').waitFor({ state: 'hidden' });

    // Reload and verify recipe persistence
    await page.reload();
    await page.waitForFunction(() => window.WB && APP.st.tab === 'studio');
    assert.equal(await page.locator('#wbRecipeN').textContent(), '1');

    // Switch studio to a different pose and different style, then Keep-Current-Pose swap!
    const otherPoseKey = savedPoseKey === 'p:001' ? 'p:002' : 'p:001';
    await page.evaluate(async key => {
      await WB.setSel({ pose: [APP.ITEMS[key]] });
    }, otherPoseKey);
    await page.locator('#wbStyles [data-style=ecom]').click();
    assert.equal(await page.evaluate(() => WB._W.poses[0]?.k), otherPoseKey);

    await page.locator('#wbRecipesBtn').click();
    await page.locator('#rcpList [data-rcp-keep]').first().waitFor({ state: 'visible' });
    await page.locator('#rcpList [data-rcp-keep]').first().click();
    await page.locator('#recipeBox').waitFor({ state: 'hidden' });
    await page.waitForFunction(k => WB._W.poses[0]?.k === k && WB._W.style === 'sheet' && WB._W.garments.length >= 1, otherPoseKey);

    // Full load restores original saved pose
    await page.locator('#wbRecipesBtn').click();
    await page.locator('#rcpList [data-rcp-load]').first().click();
    await page.waitForFunction(k => WB._W.poses[0]?.k === k, savedPoseKey);

    // Delete + Undo
    await page.locator('#wbRecipesBtn').click();
    await page.locator('#rcpList [data-rcp-del]').first().click();
    assert.ok(await page.locator('#rcpEmpty').isVisible());
    assert.ok(await page.locator('#wbRecipeN').isHidden());
    await page.locator('#toast button').click();
    assert.equal(await page.locator('#wbRecipeN').textContent(), '1');

    // JSON Import
    const importPayload = JSON.stringify({
      recipes: [{
        id: 'imported_1',
        name: 'Cyber Lookbook',
        t: Date.now(),
        mode: 'gen',
        style: 'cyber',
        shot: 'low',
        ar: '9:16',
        pl: 'en',
        extra: 'neon reflections',
        neg: 'blurry',
        refs: { r: ['r:p1'], g: ['c:c2'], p: [['p:002', 0]], e: [], x: [] },
      }],
    });
    await page.setInputFiles('#rcpImpF', {
      name: 'recipes.json',
      mimeType: 'application/json',
      buffer: Buffer.from(importPayload, 'utf8'),
    });
    await page.waitForFunction(() => document.querySelectorAll('#rcpList .rcp-item').length === 2);
    assert.equal(await page.locator('#wbRecipeN').textContent(), '2');

    // Empty / invalid recipe import should be rejected cleanly without corrupting store
    await page.setInputFiles('#rcpImpF', {
      name: 'empty.json',
      mimeType: 'application/json',
      buffer: Buffer.from('{"recipes":[{"bad":1}]}', 'utf8'),
    });
    await page.waitForFunction(() => document.querySelector('#toast')?.textContent.includes('没有有效'));
    assert.equal(await page.locator('#wbRecipeN').textContent(), '2');
    await page.keyboard.press('Escape');
    console.log('PASS Named Studio Recipes (save, persistence, keep-pose swap, full load, delete+undo, JSON import)');

    // 5. 5-Language Parity Check (en / ja / vi / tr) on new UI controls + preserved user recipe names
    const checks = [
      ['en', 'Recipes', 'Copy PNG', 'Formats', 'Studio recipes'],
      ['ja', 'レシピ', 'PNG コピー', '形式別', 'スタイルレシピ'],
      ['vi', 'Công thức', 'Chép PNG', 'Định dạng', 'Công thức phối đồ'],
      ['tr', 'Tarifler', 'PNG kopyala', 'Biçimler', 'Stüdyo tarifleri'],
    ];
    for (const [loc, rcpBtn, copyPng, formatsLbl, rcpTitle] of checks) {
      await page.locator('#languageMenu summary').click();
      await page.selectOption('#uiLocale', loc);
      await page.waitForFunction(l => document.documentElement.lang === l, loc);
      await page.locator('#languageMenu summary').click();
      assert.equal(await page.locator('#wbRecipesBtn').evaluate(el => el.firstChild.textContent.trim()), rcpBtn);
      assert.equal(await page.locator('#wbCopyBoard').textContent(), copyPng);
      assert.equal(await page.locator('#wbFmtMenu summary').textContent(), formatsLbl);
      await page.locator('#wbRecipesBtn').click();
      assert.equal(await page.locator('#rcpT').textContent(), rcpTitle);
      // User-authored recipe name must stay untranslated!
      const names = await page.locator('#rcpList .recipe-name').allTextContents();
      assert.ok(names.includes('银发机能风'), 'User recipe name should be preserved in ' + loc);
      if (loc !== 'ja') {
        const uiTexts = await page.evaluate(() => [
          document.querySelector('#rcpT').textContent,
          document.querySelector('#rcpSave').textContent,
          document.querySelector('#rcpExp').textContent,
          document.querySelector('#wbCopyBoard').textContent,
          document.querySelector('#wbFmtMenu summary').textContent,
        ]);
        for (const text of uiTexts) {
          assert.ok(!/[\u4e00-\u9fff]/.test(text), `Leaked CJK in ${loc}: ${text}`);
        }
      }
      await page.keyboard.press('Escape');
    }
    console.log('PASS 5-language UI parity (en/ja/vi/tr) and preserved user recipe names');

    // 6. Narrow mobile (320x568) + Dark theme overflow & compact HUD pruning check
    await page.setViewportSize({ width: 320, height: 568 });
    await page.evaluate(() => window.PoseWearTheme.select('dark'));
    await page.waitForFunction(() => document.documentElement.dataset.theme === 'dark');
    await page.waitForFunction(() => document.querySelector('#wbPh0')?.dataset.layout === 'compact');
    const studioOverflow = await page.evaluate(() => ({
      scrollW: document.documentElement.scrollWidth,
      innerW: window.innerWidth,
      rcpRect: document.querySelector('#wbRecipesBtn').getBoundingClientRect().toJSON(),
      hiddenSpatialTools: [...document.querySelectorAll('#wbCanvasTools [data-cv-act="tidy"], #wbCanvasTools [data-cv-act="fit"], #wbCanvasTools [data-cv-act="wires"]')].every(b => b.hidden),
    }));
    assert.ok(studioOverflow.scrollW <= studioOverflow.innerW + 1, 'Studio should not overflow horizontally at 320px: ' + JSON.stringify(studioOverflow));
    assert.ok(studioOverflow.rcpRect.right <= 321 && studioOverflow.rcpRect.left >= 0, '#wbRecipesBtn should stay within 320px viewport');
    assert.ok(studioOverflow.hiddenSpatialTools, 'Desktop-only tidy/fit/wires canvas tools should be hidden in compact mobile layout');

    await page.locator('#wbRecipesBtn').click();
    await page.locator('#recipeBox').waitFor({ state: 'visible' });
    const rcpBoxRect = await page.locator('.rcp-box').boundingBox();
    assert.ok(rcpBoxRect && rcpBoxRect.x >= 0 && rcpBoxRect.x + rcpBoxRect.width <= 321, 'Recipe modal should fit 320px viewport');
    await page.keyboard.press('Escape');

    await page.evaluate(() => APP.compareOpen(['p:001', 'p:002']));
    await page.locator('#cmpModal').waitFor({ state: 'visible' });
    const cmpBoxRect = await page.locator('.cmp-box').boundingBox();
    assert.ok(cmpBoxRect && cmpBoxRect.x >= 0 && cmpBoxRect.x + cmpBoxRect.width <= 321, 'Compare modal should fit 320px viewport');
    await page.keyboard.press('Escape');
    console.log('PASS 320px mobile dark-mode layout & viewport fit for new dialogs');

    assert.deepEqual(errors, []);
    console.log('creative-update-regressions PASS');
  } finally {
    await browser.close();
  }
}

run().catch(err => {
  console.error(err);
  process.exitCode = 1;
});