722 lines
58 KiB
JavaScript
722 lines
58 KiB
JavaScript
// Paired visual QA: the ACTUAL TeamsPeach renderer against the INSTALLED official TeamSpeak 6 UI,
|
||
// both rendering the same canonical synthetic fixture (official-ts6-runtime fixtureData) at the
|
||
// same size, theme, language and display clock, captured in the same run.
|
||
//
|
||
// Not a reconstructed reference: the official side is the unmodified installed bundle driven by
|
||
// scripts/lib/official-ts6-runtime.mjs. The product side is the real app (dev tree or --exe) fed
|
||
// only through its real core-event IPC with read-only fixture answers.
|
||
//
|
||
// Output (<out>): official/<cfg>/<screen>.png, product/<cfg>/<screen>.png, compare/<cfg>/<screen>/
|
||
// <region>.png ([official | product | diff] strips), regions/styles/text JSON per capture,
|
||
// pair-report.json and pair-report.md. A region passes only on pixels: ≤ 0.5 % of its pixels may
|
||
// differ by more than 16/255 in any channel AND its box must match within 1 px. Brand/account-only
|
||
// sidebar regions are excluded from scoring (listed with a reason); they are still captured.
|
||
//
|
||
// Safety: both apps are hidden, unfocused, nonfocusable, offscreen and muted (shared assertOffscreen
|
||
// guard; product via launchApp). Disposable profiles. Network cancelled, permissions denied, media
|
||
// devices never enumerated or opened (getUserMedia/getDisplayMedia/enumerateDevices stubbed and
|
||
// counted), no server, no OS input, no native presentation. Broadcast sources are canvas-drawn
|
||
// fixture thumbnails identical to the official fixture's; nothing is captured.
|
||
//
|
||
// Usage: node scripts/official-pair-capture-offscreen.mjs --out <dir> [--exe <TeamsPeach.exe>]
|
||
// [--themes dark,light] [--locales en,ru] [--sizes 1553x998,1280x800,860x800]
|
||
// [--screens main,main@few,main@empty,menu,broadcast,private,private-info,settings:audio,settings:appearance]
|
||
// [--official-only] [--fixture <fixture-data.json>] [--self-test | --no-self-test] [--official-from <earlier --out dir>]
|
||
// [--hold <screen>:<theme>:<locale>:<WxH>] keep a product window staged with a CDP endpoint
|
||
// until <out>/release exists (hold-ready.json).
|
||
import { launchApp, waitForAsync } from './lib/electron-app.mjs';
|
||
import { launchOfficialRuntime } from './lib/official-ts6-runtime.mjs';
|
||
import { decodePng, encodePng, crop, compare, bestShift, palette, sideBySide, blank } from './lib/png.mjs';
|
||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
||
import { createServer } from 'node:net';
|
||
import { tmpdir } from 'node:os';
|
||
import path from 'node:path';
|
||
import { isDeepStrictEqual } from 'node:util';
|
||
|
||
const argv = process.argv.slice(2);
|
||
const option = (key, fallback) => (argv.includes(`--${key}`) ? argv[argv.indexOf(`--${key}`) + 1] : fallback);
|
||
const list = (value, fallback) => (value ? value.split(',').filter(Boolean) : fallback);
|
||
const out = path.resolve(option('out', 'smoke-out/official-pair'));
|
||
const exe = option('exe');
|
||
const themes = list(option('themes'), ['dark', 'light']);
|
||
const locales = list(option('locales'), ['en', 'ru']);
|
||
const sizes = list(option('sizes'), ['1553x998', '1280x800', '880x800']).map(s => s.split('x').map(Number));
|
||
const screens = list(option('screens'), ['main', 'main@few', 'main@empty', 'menu', 'broadcast', 'private', 'private-info', 'server-info', 'channel-edit', 'server-bans', 'server-clients', 'server-permissions', 'settings:audio', 'settings:appearance']);
|
||
const fixturePath = path.resolve(option('fixture', 'C:/Users/Admin/tmp/teamspeach-exact-design-20261101/expanded-reference/fixture-data.json'));
|
||
const selfTestOnly = argv.includes('--self-test');
|
||
const hold = option('hold');
|
||
const officialFrom = option('official-from') ? path.resolve(option('official-from')) : null;
|
||
const officialRoot = path.join(officialFrom ?? out, 'official');
|
||
const TOLERANCE = 16, MAX_RATIO = 0.005, MAX_BOX_DELTA = 1;
|
||
mkdirSync(out, { recursive: true });
|
||
|
||
const fixture = JSON.parse(readFileSync(fixturePath, 'utf8'));
|
||
// Display clock shared by both sides: fixture day, 2.5 h after T0 (last full-history row is T0+120 min).
|
||
const T0 = Math.min(...Object.values(fixture.chat).flat().map(m => m.timestamp));
|
||
const NOW = T0 + 150 * 60000;
|
||
const report = {
|
||
kind: 'official-pair-visual-qa', startedAt: new Date().toISOString(), exe: exe ?? null, fixture: fixturePath,
|
||
thresholds: { channelTolerance: TOLERANCE, maxDifferingRatio: MAX_RATIO, maxBoxDeltaPx: MAX_BOX_DELTA },
|
||
displayClock: new Date(NOW).toString(), instrument: null, canonicalFixture: null, safety: {}, pairs: [], blocked: [], errors: [],
|
||
};
|
||
const save = () => {
|
||
writeFileSync(path.join(out, 'pair-report.json'), JSON.stringify(report, null, 2));
|
||
writeFileSync(path.join(out, 'pair-report.md'), markdown());
|
||
};
|
||
|
||
// ------------------------------------------------------------------------------------------------
|
||
// Regions: official selector vs product candidates (union of visible matches). `exclude` = captured
|
||
// and shown but not scored, with the reason.
|
||
const R = (name, official, product, exclude = null, extra = {}) => ({ name, official: [].concat(official), product: [].concat(product), exclude, ...extra });
|
||
const SHELL = [
|
||
R('sidebar-brand', '.tsv-sidebar .tsv-title-bar', '.sidebar-title-row', 'independent TeamsPeach brand (mandated); official notification bell is myTeamSpeak account notifications'),
|
||
R('window-caption', '.tsv-window-bar > .tsv-bar-item.tsv-no-padding:last-child', [], 'native caption buttons: product uses the OS titleBarOverlay (app/main/titlebar.js), which offscreen rendering does not paint'),
|
||
R('sidebar-search', '.tsv-sidebar .tsv-search-bar', '.sidebar-search'),
|
||
R('sidebar-servers', '.tsv-sidebar .tsv-body > .tsv-resources-group .tsv-activities', '#connections-panel'),
|
||
R('sidebar-community', '.tsv-sidebar .ts-join-community', '.connections-join', 'official account-bound community action; product exposes account-free New Connection in this slot'),
|
||
R('sidebar-bookmarks', '.tsv-sidebar .tsv-flex-grow > .tsv-flex-vertical > .tsv-resources-group:nth-child(1)', '#servers-panel'),
|
||
R('sidebar-account', ['.tsv-sidebar .tsv-flex-grow > .tsv-flex-vertical > .tsv-resources-group:nth-child(2)', '.tsv-sidebar .tsv-flex-grow > .tsv-flex-vertical > .tsv-resources-group:nth-child(3)'], '#conversations-panel', 'official myTeamSpeak contacts/group chats are account-only'),
|
||
R('sidebar-footer', '.tsv-sidebar .tsv-footer', 'footer.self', 'official footer is myTeamSpeak account presence'),
|
||
R('tree-toolbar', '.tsv-activity-main > .tsv-header', '.server-pane-bar'),
|
||
];
|
||
const SERVER = [
|
||
R('tree', '.tsv-activity-main .ts-tree', '#room-side'),
|
||
R('tree-status', '.tsv-activity-main > .tsv-body .tsv-footer', '.server-status-bar'),
|
||
R('detail-toolbar', '.tsv-activity-detail .tsv-window-bar', '.detail-pane-bar'),
|
||
R('detail-header', '.tsv-activity-detail .tsv-content-header-bar', '#detail-header'),
|
||
R('detail-pane', '.tsv-activity-detail', '.workspace'),
|
||
];
|
||
const CHAT = [
|
||
// The official composer floats over the message list; both sides are scored on the visible part above it.
|
||
R('chat-log', '.ts-chat-container .tsv-virtual-list', '#chat-log', null, { clipAbove: 'composer' }),
|
||
R('composer', '.ts-chat-input-container', '#chat-form'),
|
||
];
|
||
const REGIONS = {
|
||
main: [...SHELL, ...SERVER, ...CHAT],
|
||
menu: [...SHELL, ...SERVER, R('context-menu', '.ts-context-menu', '.client-menu:not(.client-submenu)')],
|
||
broadcast: [...SHELL, R('modal', '.tsv-modal-container', 'dialog.broadcast-dialog[open]')],
|
||
private: [...SHELL, ...SERVER, ...CHAT],
|
||
'private-info': [...SHELL, ...SERVER],
|
||
'server-info': [...SHELL, ...SERVER],
|
||
'channel-edit': [...SHELL, ...SERVER],
|
||
'server-bans': [...SHELL, ...SERVER],
|
||
'server-clients': [...SHELL, ...SERVER],
|
||
'server-permissions': [...SHELL, ...SERVER],
|
||
settings: [...SHELL, R('settings-nav', '.tsv-settings-categories', '#settings-nav'), R('settings-panel', '.tsv-settings-subcategory', '.settings-scroll')],
|
||
};
|
||
const regionsFor = screen => REGIONS[screen.split(':')[0]];
|
||
|
||
// Shared in-page reader (serialized into both renderers).
|
||
function readRegions(specs) {
|
||
const visible = node => node.checkVisibility?.({ visibilityProperty: true, opacityProperty: true }) !== false && node.getBoundingClientRect().width > 0 && node.getBoundingClientRect().height > 0;
|
||
const opaqueBackground = node => { for (let n = node; n; n = n.parentElement) { const c = getComputedStyle(n).backgroundColor; if (c && c !== 'rgba(0, 0, 0, 0)' && c !== 'transparent') return c; } return null; };
|
||
// First PAINTED text (visually-hidden 1×1 accessibility text is skipped).
|
||
const firstText = node => { const walker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT, { acceptNode: t => { const p = t.parentElement; const r = p?.getBoundingClientRect(); return t.textContent.trim() && p && visible(p) && r.width > 2 && r.height > 2 ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT; } }); return walker.nextNode()?.parentElement ?? null; };
|
||
return Object.fromEntries(specs.map(({ name, selectors, clipAbove }) => {
|
||
const nodes = selectors.flatMap(s => [...document.querySelectorAll(s)]).filter(visible);
|
||
if (!nodes.length) return [name, null];
|
||
const boxes = nodes.map(n => n.getBoundingClientRect());
|
||
const x = Math.min(...boxes.map(b => b.left)), y = Math.min(...boxes.map(b => b.top));
|
||
const rect = { x, y, width: Math.max(...boxes.map(b => b.right)) - x, height: Math.max(...boxes.map(b => b.bottom)) - y };
|
||
const text = nodes.map(n => n.innerText ?? '').join('\n').replace(/[ \t]+/g, ' ').trim();
|
||
let paintedText = text;
|
||
if (name === 'chat-log') {
|
||
const overlay = specs.find(s => s.name === clipAbove);
|
||
const overlayTop = overlay ? Math.min(...overlay.selectors.flatMap(s => [...document.querySelectorAll(s)]).filter(visible).map(n => n.getBoundingClientRect().top)) : Infinity;
|
||
const clip = { left: Math.max(0, rect.x), top: Math.max(0, rect.y), right: Math.min(innerWidth, rect.x + rect.width), bottom: Math.min(innerHeight, rect.y + rect.height, overlayTop) };
|
||
const parts = [], range = document.createRange();
|
||
for (const node of nodes) {
|
||
const walker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT);
|
||
for (let textNode = walker.nextNode(); textNode; textNode = walker.nextNode()) {
|
||
if (!textNode.textContent.trim() || !visible(textNode.parentElement)) continue;
|
||
range.selectNodeContents(textNode);
|
||
if ([...range.getClientRects()].some(r => r.right > clip.left && r.left < clip.right && r.bottom > clip.top && r.top < clip.bottom)) parts.push(textNode.textContent.trim());
|
||
}
|
||
}
|
||
paintedText = parts.join('\n');
|
||
}
|
||
const textNode = firstText(nodes[0]);
|
||
const cs = getComputedStyle(nodes[0]), ts = textNode ? getComputedStyle(textNode) : null;
|
||
return [name, {
|
||
rect, count: nodes.length, text, paintedText,
|
||
style: { background: opaqueBackground(nodes[0]), color: ts?.color ?? cs.color, fontFamily: ts?.fontFamily ?? cs.fontFamily, fontSize: ts?.fontSize ?? cs.fontSize, fontWeight: ts?.fontWeight ?? cs.fontWeight, lineHeight: ts?.lineHeight ?? cs.lineHeight, borderRadius: cs.borderRadius },
|
||
}];
|
||
}));
|
||
}
|
||
|
||
// Ticking display clock: Date starts at `now` and advances in real time (waits/timeouts still work).
|
||
function installClock(now) {
|
||
if (!window.__qaRealDate) {
|
||
const Real = Date;
|
||
window.__qaRealDate = Real;
|
||
const current = () => window.__qaClock.base + (Real.now() - window.__qaClock.set);
|
||
class QADate extends Real { constructor(...a) { if (a.length) super(...a); else super(current()); } static now() { return current(); } }
|
||
window.Date = QADate;
|
||
}
|
||
window.__qaClock = { base: now, set: window.__qaRealDate.now() };
|
||
}
|
||
|
||
const cfgName = (theme, locale, [w, h]) => `${theme}-${locale}-${w}x${h}`;
|
||
const fileName = screen => `${screen.replace(/[:/@>]/g, '-')}.png`;
|
||
|
||
// ------------------------------------------------------------------------------------------------
|
||
// Official side.
|
||
async function captureOfficial() {
|
||
const byChat = Map.groupBy(screens, s => s.split('@')[1] ?? 'full');
|
||
for (const theme of themes) for (const locale of locales) for (const size of sizes) {
|
||
const cfg = cfgName(theme, locale, size);
|
||
const dir = path.join(out, 'official', cfg);
|
||
mkdirSync(dir, { recursive: true });
|
||
for (const [chat, group] of byChat) {
|
||
const ref = await launchOfficialRuntime({ theme, locale, width: size[0], height: size[1], chat });
|
||
try {
|
||
if (!report.canonicalFixture) {
|
||
const live = await ref.fixtureData();
|
||
report.canonicalFixture = { file: fixturePath, equalToLiveOfficialFixture: isDeepStrictEqual(live, fixture) };
|
||
if (!report.canonicalFixture.equalToLiveOfficialFixture) throw new Error('Canonical fixture file differs from the live official fixtureData(); refusing to compare different content.');
|
||
}
|
||
await ref.page.evaluate(installClock, NOW);
|
||
// Settings and the broadcast modal change shell state; capture them last, broadcast at the very end.
|
||
const ordered = [...group].sort((a, b) => (a.startsWith('broadcast') - b.startsWith('broadcast')) || (a.startsWith('settings') - b.startsWith('settings')));
|
||
for (const spec of ordered) {
|
||
const screen = spec.split('@')[0];
|
||
const official = { private: 'view:client-Alex.Chat', 'private-info': 'view:client-Alex.Info', 'server-info': 'view:server.Info', 'channel-edit': 'act:cs>universal.edit', 'server-bans': 'view:server.BanList', 'server-clients': 'view:server.ClientList', 'server-permissions': 'view:server.Permissions' }[screen] ?? screen;
|
||
try {
|
||
if (screen === 'broadcast' || screen === 'menu') await ref.open('main');
|
||
let opened;
|
||
try { opened = await ref.open(official); }
|
||
catch (error) {
|
||
// Narrow official layouts render Start Stream icon-only (no text label for the scenario to match):
|
||
// click the same official constructive status-bar button by position, then wait for the official modal.
|
||
if (screen !== 'broadcast' || !/Start Stream button not found/.test(error.message)) throw error;
|
||
opened = await ref.page.evaluate(async () => {
|
||
const buttons = [...document.querySelectorAll('.ts-server-status-constructive-buttons:not(.ts-hidden) .tsv-tool-button')];
|
||
if (buttons.length !== 2) throw new Error(`expected 2 official constructive buttons, found ${buttons.length}`);
|
||
buttons[1].click();
|
||
for (let i = 0; i < 100 && !document.querySelector('.ts-setup-stream.loaded'); i++) await new Promise(r => setTimeout(r, 100));
|
||
if (!document.querySelector('.ts-setup-stream.loaded')) throw new Error('official setup-stream modal did not load from the icon-only button');
|
||
await new Promise(r => setTimeout(r, 400));
|
||
return { screen: 'broadcast', route: location.hash, driven: 'icon-only official Start Stream (2nd constructive status-bar button)' };
|
||
});
|
||
}
|
||
await ref.page.evaluate(() => document.fonts.ready);
|
||
await ref.page.screenshot({ path: path.join(dir, fileName(spec)) });
|
||
const regions = await ref.page.evaluate(readRegions, regionsFor(screen).map(r => ({ name: r.name, selectors: r.official, clipAbove: r.clipAbove })));
|
||
writeFileSync(path.join(dir, fileName(spec).replace('.png', '.json')), JSON.stringify({ opened, viewport: size, regions }, null, 2));
|
||
console.log(`official ${cfg} ${spec}`);
|
||
if (screen === 'menu') await ref.page.evaluate(async () => {
|
||
// Dismiss like a user (Escape, outside click) so later screens are not captured under an open menu.
|
||
document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', code: 'Escape', bubbles: true }));
|
||
document.body.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, clientX: 5, clientY: innerHeight - 8 }));
|
||
document.body.dispatchEvent(new MouseEvent('click', { bubbles: true, clientX: 5, clientY: innerHeight - 8 }));
|
||
for (let i = 0; i < 60 && document.querySelector('.ts-context-menu')?.children.length; i++) await new Promise(r => setTimeout(r, 50));
|
||
if (document.querySelector('.ts-context-menu')?.children.length) throw new Error('official context menu did not close');
|
||
});
|
||
} catch (error) {
|
||
report.blocked.push({ side: 'official', cfg, screen: spec, reason: String(error.message || error).split('\n')[0] });
|
||
console.log(`official ${cfg} ${spec} BLOCKED: ${String(error.message).split('\n')[0]}`);
|
||
}
|
||
}
|
||
const manifest = await ref.manifest();
|
||
writeFileSync(path.join(dir, `manifest-chat-${chat}.json`), JSON.stringify(manifest, null, 2));
|
||
report.safety[`official ${cfg} ${chat}`] = { blockedRequests: manifest.blocked.length, unansweredBridge: manifest.bridge.unanswered.length, pageErrors: manifest.errors.length };
|
||
} finally { await ref.close(); }
|
||
}
|
||
}
|
||
}
|
||
|
||
// ------------------------------------------------------------------------------------------------
|
||
// Product side.
|
||
const freePort = () => new Promise((resolve, reject) => { const s = createServer(); s.once('error', reject); s.listen(0, '127.0.0.1', () => { const { port } = s.address(); s.close(() => resolve(port)); }); });
|
||
const ID = Object.fromEntries(fixture.clients.map(c => [c.id, c]));
|
||
const uidOf = id => ID[id].properties.uniqueIdentifier;
|
||
const nick = id => ID[id].properties.nickname;
|
||
const ownChannel = Number(ID[fixture.ownClientId].channelId);
|
||
|
||
function productSnapshot() {
|
||
const group = (g, i) => ({ id: Number(g.id), name: g.name, icon_id: null, sort_id: g.sortId, name_mode: 'none', type: 'regular', order: i });
|
||
return {
|
||
event: 'snapshot', rev: 1, own_client_id: fixture.ownClientId, own_channel_id: ownChannel,
|
||
server: { name: fixture.server.properties.name, uid: fixture.server.uid, platform: fixture.server.properties.platform, version: fixture.server.properties.version, welcome_message: fixture.server.properties.welcomeMessage, default_server_group: Number(fixture.server.properties.defaultServerGroup), default_channel_group: Number(fixture.server.properties.defaultChannelGroup) },
|
||
server_groups: fixture.groups.server.map(group), channel_groups: fixture.groups.channel.map(group),
|
||
channels: fixture.channels.map(c => ({ id: Number(c.id), parent_id: Number(c.parentId), order: Number(c.properties.order), depth: 0, name: c.properties.name, topic: c.properties.topic,
|
||
has_password: c.properties.flagPassword, is_default: c.properties.flagDefault, max_clients: c.properties.flagMaxclientsUnlimited ? null : c.properties.maxclients, needed_talk_power: c.properties.neededTalkPower, codec: 'opus_voice', codec_quality: c.properties.codecQuality })),
|
||
clients: fixture.clients.map(c => ({ id: c.id, uid: c.properties.uniqueIdentifier, nickname: c.properties.nickname, channel_id: Number(c.channelId), is_self: c.id === fixture.ownClientId, client_type: 'normal',
|
||
input_muted: false, output_muted: false, input_hardware: c.properties.inputHardware, output_hardware: c.properties.outputHardware, away: false, talk_power: c.properties.talkPower,
|
||
server_groups: String(c.properties.serverGroups).split(',').map(Number), channel_group_id: Number(c.properties.channelGroupId), avatar_hash: null, has_myts: false })),
|
||
};
|
||
}
|
||
|
||
// Official history rows → the product's real event paths (text / server_event), same order and time.
|
||
function historyEvents(variant) {
|
||
return fixture.chat[variant].map(m => {
|
||
if (m.message_type === 1) return { at: m.timestamp, event: { event: 'text', target: 'channel', from_client_id: m.senderId, from_uid: uidOf(m.senderId), from_nickname: m.sender_name, message: m.content } };
|
||
const c = JSON.parse(m.content);
|
||
const other = Number(c.associated_channel_id);
|
||
const invoker = c.invoker ? { id: c.invoker.id, uid: c.invoker.uid, name: c.invoker.nickname } : null;
|
||
// Shapes and Reason names/ids exactly as core/src/events.rs emits them (REASONS index = wire reasonid).
|
||
const base = { event: 'server_event', client_id: m.senderId, uid: uidOf(m.senderId), nickname: m.sender_name, is_self: m.senderId === fixture.ownClientId, invoker, message: c.reason || null };
|
||
const why = name => ({ reason: name, reason_id: ['none', 'moved', 'subscription', 'lost_connection', 'kick_channel', 'kick_server', 'ban', 'server_stop', 'disconnect'].indexOf(name) });
|
||
const reason = c.eventType === 2 ? 'moved' : c.eventType === 3 ? 'lost_connection' : 'none';
|
||
if (m.message_type === 3) return { at: m.timestamp, event: other ? { ...base, kind: 'client_move', from_channel_id: other, to_channel_id: ownChannel, ...why(reason) } : { ...base, kind: 'client_enter', to_channel_id: ownChannel, ...why('none') } };
|
||
return { at: m.timestamp, event: other ? { ...base, kind: 'client_move', from_channel_id: ownChannel, to_channel_id: other, ...why(reason) } : { ...base, kind: 'client_leave', from_channel_id: ownChannel, ...why(c.eventType === 3 ? 'lost_connection' : 'disconnect') } };
|
||
});
|
||
}
|
||
|
||
async function launchProduct(variant, { cdpPort } = {}) {
|
||
const profile = mkdtempSync(path.join(tmpdir(), 'teamspeach-pair-qa-'));
|
||
const app = await launchApp({ exe, profile, args: cdpPort ? [`--remote-debugging-port=${cdpPort}`] : [] });
|
||
const safety = await app.evaluate(({ BrowserWindow, session }) => {
|
||
const win = BrowserWindow.getAllWindows()[0];
|
||
win.webContents.setAudioMuted(true);
|
||
session.defaultSession.setPermissionRequestHandler((_w, _p, done) => done(false));
|
||
session.defaultSession.setPermissionCheckHandler(() => false);
|
||
session.defaultSession.setDevicePermissionHandler?.(() => false);
|
||
globalThis.__pairBlocked = [];
|
||
session.defaultSession.webRequest.onBeforeRequest({ urls: ['http://*/*', 'https://*/*', 'ws://*/*', 'wss://*/*'] }, (details, done) => { globalThis.__pairBlocked.push(details.url); done({ cancel: true }); });
|
||
return { visible: win.isVisible(), focused: win.isFocused(), focusable: win.isFocusable(), offscreen: win.webContents.isOffscreen(), muted: win.webContents.isAudioMuted() };
|
||
});
|
||
if (safety.visible || safety.focused || safety.focusable || !safety.offscreen || !safety.muted) throw new Error(`Unsafe product window ${JSON.stringify(safety)}`);
|
||
const errors = [];
|
||
let page;
|
||
try {
|
||
page = await app.firstWindow();
|
||
page.on('pageerror', e => errors.push(String(e.stack || e).slice(0, 800)));
|
||
page.on('console', m => { if (m.type() === 'error') errors.push(`[console] ${m.text().slice(0, 400)}`); });
|
||
await page.waitForSelector('#view-onboarding, #view-app', { state: 'visible', timeout: 30000 }).catch(() => {});
|
||
if (await page.locator('#view-app').isVisible()) throw new Error('Disposable profile unexpectedly skipped onboarding');
|
||
await page.waitForSelector('#view-onboarding', { state: 'visible', timeout: 30000 });
|
||
await page.evaluate(() => {
|
||
window.__forbiddenMedia = [];
|
||
for (const key of ['getUserMedia', 'getDisplayMedia']) navigator.mediaDevices[key] = async () => { window.__forbiddenMedia.push(key); throw new DOMException('Device capture forbidden in pair QA', 'NotAllowedError'); };
|
||
// Same SYNTHETIC device list as the official fixture (official-ts6-runtime/fixture.js); no device is enumerated or opened.
|
||
const device = (deviceId, kind, label) => ({ deviceId, kind, label, groupId: 'reference-fixture-audio', toJSON() { return { deviceId, kind, label, groupId: 'reference-fixture-audio' }; } });
|
||
navigator.mediaDevices.enumerateDevices = async () => [
|
||
device('default', 'audioinput', 'Default - Microphone (Reference Fixture Audio)'),
|
||
device('reference-capture-1', 'audioinput', 'Microphone (Reference Fixture Audio)'),
|
||
device('reference-capture-2', 'audioinput', 'Line In (Reference Fixture Interface)'),
|
||
device('default', 'audiooutput', 'Default - Headphones (Reference Fixture Audio)'),
|
||
device('reference-playback-1', 'audiooutput', 'Headphones (Reference Fixture Audio)'),
|
||
device('reference-playback-2', 'audiooutput', 'Speakers (Reference Fixture Interface)'),
|
||
];
|
||
for (const [proto, method] of [[Element.prototype, 'requestFullscreen'], [HTMLVideoElement.prototype, 'requestPictureInPicture']]) proto[method] = async () => { throw new Error('Native presentation forbidden'); };
|
||
});
|
||
await page.fill('#onboarding-nick', nick(fixture.ownClientId));
|
||
await page.click('#onboarding-submit');
|
||
await page.waitForSelector('#view-app', { state: 'visible' });
|
||
await page.waitForFunction(() => window.teamspeachDiagnostics?.snapshot().core === 'ready', null, { timeout: 30000 });
|
||
// Behaviour before connection: #btn-server-admin is the server title, visible and disabled offline.
|
||
const offline = await page.evaluate(() => { const b = document.querySelector('#btn-server-admin'); return b ? { visible: b.checkVisibility(), disabled: b.disabled } : null; });
|
||
// Same canvas thumbnails as the official fixture (labels/hues), so the source grids carry identical content.
|
||
const thumbs = await page.evaluate(() => {
|
||
const thumbnail = (label, hue) => {
|
||
const c = document.createElement('canvas'); c.width = 320; c.height = 180;
|
||
const g = c.getContext('2d'); const grad = g.createLinearGradient(0, 0, 320, 180);
|
||
grad.addColorStop(0, `hsl(${hue} 45% 32%)`); grad.addColorStop(1, `hsl(${hue + 40} 50% 18%)`);
|
||
g.fillStyle = grad; g.fillRect(0, 0, 320, 180);
|
||
g.fillStyle = 'rgba(255,255,255,.85)'; g.font = '600 18px sans-serif'; g.fillText(label, 16, 96);
|
||
g.font = '12px sans-serif'; g.fillText('REFERENCE FIXTURE — not a capture', 16, 164);
|
||
return c.toDataURL('image/webp');
|
||
};
|
||
return {
|
||
window: ['Browser', 'Editor', 'Game'].map((t, i) => ({ id: `window:reference-window-${i + 1}`, name: `Reference ${t}`, kind: 'window', thumbnail: thumbnail(`Reference ${t}`, 20 + i * 90) })),
|
||
screen: [1, 2].map(n => ({ id: `screen:reference-screen-${n}`, name: `Screen ${n}`, kind: 'screen', thumbnail: thumbnail(`Reference screen ${n}`, 210 + n * 30) })),
|
||
};
|
||
});
|
||
await app.evaluate(({ ipcMain }, { thumbs, serverInfo }) => {
|
||
globalThis.__pairCommands = [];
|
||
const allowed = { allowed: true, reason: 'fixture', source: 'fixture' };
|
||
ipcMain.removeHandler('core:request');
|
||
ipcMain.handle('core:request', (_e, connectionId, cmd, args) => {
|
||
globalThis.__pairCommands.push({ cmd, args });
|
||
if (cmd === 'client_context') return { ok: true, result: { client_id: args.client_id, uid: args.uid, generation: 1, is_self: args.client_id === 1,
|
||
capabilities: Object.fromEntries(['commander', 'avatar', 'poke', 'volume', 'connection_info', 'server_group', 'channel_group', 'client_permissions', 'channel_permissions', 'set_client_permission', 'set_channel_permission', 'kick_channel', 'kick_server', 'ban', 'move_to_own_channel'].map(k => [k, allowed])),
|
||
server_groups: [], channel_groups: [], permissions: [], volume_db: 0, volume_muted: false } };
|
||
if (cmd === 'stream_list') return { ok: true, result: { results: [] } };
|
||
if (cmd === 'set_transmit') return { ok: true, result: args };
|
||
// Read-only admin answers carrying exactly what the official fixture knows (server properties, empty
|
||
// channel description, all-unknown permission hints); everything else stays undispatched.
|
||
if (cmd === 'admin_context') return { ok: true, result: { generation: 1, server_uid: serverInfo.uid, own_client_id: 1, catalog_received: true, permissions: {}, permissions_catalog: [] } };
|
||
if (cmd === 'server_info') return { ok: true, result: { rows: [serverInfo.row] } };
|
||
if (cmd === 'channel_description') return { ok: true, result: { description: '' } };
|
||
return { ok: false, error: { code: 'not_connected', message: 'Read-only pair QA fixture; command not dispatched' } };
|
||
});
|
||
const capabilities = { supported: true, sourceTypes: ['window', 'screen'], nativePicker: false, portal: false, audio: { system: { supported: false, reason: 'Audio blocked in pair QA fixture.' }, excludeSelf: { supported: false } }, requirements: [] };
|
||
for (const channel of ['capture:capabilities', 'capture:sources', 'capture:select', 'capture:cancel', 'appaudio:list']) ipcMain.removeHandler(channel);
|
||
ipcMain.handle('capture:capabilities', () => capabilities);
|
||
ipcMain.handle('capture:sources', (_e, options) => ({ ok: true, capabilities, sources: options.types.flatMap(t => thumbs[t] ?? []) }));
|
||
ipcMain.handle('capture:select', () => ({ ok: false, error: { code: 'fixture_forbidden', message: 'Pair QA never captures.' } }));
|
||
ipcMain.handle('capture:cancel', () => ({ ok: true }));
|
||
ipcMain.handle('appaudio:list', () => ({ ok: true, supported: false, applications: [], reason: 'Audio blocked in pair QA fixture.' }));
|
||
}, { thumbs, serverInfo: { uid: fixture.server.uid, row: { virtualserver_name: fixture.server.properties.name, virtualserver_platform: fixture.server.properties.platform, virtualserver_version: fixture.server.properties.version,
|
||
virtualserver_maxclients: String(fixture.server.properties.maxClients), virtualserver_clientsonline: String(fixture.server.properties.clientsOnline), virtualserver_channelsonline: String(fixture.server.properties.channelsOnline),
|
||
virtualserver_welcomemessage: fixture.server.properties.welcomeMessage, virtualserver_unique_identifier: fixture.server.uid } } });
|
||
const send = event => app.evaluate(({ BrowserWindow }, event) => BrowserWindow.getAllWindows()[0].webContents.send('core:event', { ...event, connectionId: 'c1' }), event);
|
||
await page.evaluate(installClock, T0 - 5 * 60000);
|
||
await send({ event: 'audio_state', input_muted: false, output_muted: false, transmitting: false });
|
||
await send({ event: 'state', state: 'connected', address: 'reference.invalid:9987', reason: null });
|
||
await send(productSnapshot());
|
||
// IPC delivery is asynchronous to CDP evaluation: settle each event before moving the clock on.
|
||
for (const { at, event } of historyEvents(variant)) { await page.evaluate(installClock, at); await send(event); await page.waitForTimeout(40); }
|
||
await page.evaluate(installClock, NOW);
|
||
await page.waitForTimeout(300);
|
||
const online = await page.evaluate(() => { const b = document.querySelector('#btn-server-admin'); return b ? { visible: b.checkVisibility(), disabled: b.disabled, text: b.textContent.trim() } : null; });
|
||
// First frame: body booted, glyphs are painted inline SVG ([data-icon], real geometry, no <use>), fonts loaded.
|
||
const firstFrame = await page.evaluate(async () => {
|
||
await document.fonts.ready;
|
||
const icons = [...document.querySelectorAll('.icon')].filter(n => n.checkVisibility() && n.getBoundingClientRect().width > 0);
|
||
const unpainted = icons.filter(n => { const svg = n.matches('svg') ? n : n.querySelector('svg'); if (!svg) return true; const b = svg.getBBox?.(); return !b || b.width === 0 || b.height === 0; });
|
||
const fonts = [...document.fonts].map(f => ({ family: f.family, weight: f.weight, status: f.status }));
|
||
return { bodyClass: document.body.className, appVisible: Boolean(document.querySelector('#view-app')?.checkVisibility()), icons: icons.length, dataIcon: icons.filter(n => n.closest('[data-icon]') || n.dataset.icon).length,
|
||
useRefs: icons.filter(n => n.querySelector('use')).map(n => n.closest('[data-icon]')?.dataset.icon ?? n.dataset.icon ?? n.getAttribute('class')).slice(0, 20), unpainted: unpainted.slice(0, 10).map(n => n.outerHTML.slice(0, 140)), unpaintedCount: unpainted.length,
|
||
fonts, fontsNotLoaded: fonts.filter(f => f.status !== 'loaded').length, bodyFont: getComputedStyle(document.body).fontFamily };
|
||
});
|
||
return { app, page, profile, errors, behaviour: { serverAdminOffline: offline, serverAdminOnline: online, firstFrame } };
|
||
} catch (error) {
|
||
const boot = await page?.evaluate(() => ({ visibleViews: [...document.querySelectorAll('body > *, #view-app, #boot, [id^="view-"]')].filter(n => n.checkVisibility?.()).map(n => `${n.tagName.toLowerCase()}#${n.id}.${n.className}`),
|
||
bootText: document.querySelector('#boot')?.innerText?.trim(), fatal: document.querySelector('.fatal, #fatal, [role="alert"]')?.innerText?.trim(), bodyText: document.body.innerText.trim().slice(0, 600) })).catch(e => ({ unavailable: String(e) }));
|
||
await page?.screenshot({ path: path.join(out, `product-boot-failure-${variant}.png`) }).catch(() => {});
|
||
await app.close().catch(() => {});
|
||
rmSync(profile, { recursive: true, force: true });
|
||
throw new Error(`Product boot/setup failed (${variant}): ${error.message.split('\n')[0]}\nboot=${JSON.stringify(boot)}\npageErrors=${JSON.stringify(errors.slice(0, 8))}`);
|
||
}
|
||
}
|
||
|
||
async function configureProduct(p, theme, locale, [width, height]) {
|
||
const windows = await p.app.evaluate(({ BrowserWindow }, size) => {
|
||
const all = BrowserWindow.getAllWindows();
|
||
const main = all.find(w => w.webContents.getURL().endsWith('/index.html')) ?? all[0];
|
||
main.setContentSize(...size);
|
||
return all.map(w => ({ url: w.webContents.getURL(), content: w.getContentSize(), min: w.getMinimumSize(), visible: w.isVisible(), main: w === main }));
|
||
}, [width, height]);
|
||
await p.page.waitForFunction(s => innerWidth === s[0] && innerHeight === s[1], [width, height], { timeout: 10000 }).catch(async () => {
|
||
throw new Error(`Viewport did not reach ${width}x${height}: page ${JSON.stringify(await p.page.evaluate(() => [innerWidth, innerHeight]))}, windows ${JSON.stringify(windows)}`);
|
||
});
|
||
await p.page.evaluate(async ({ locale, theme }) => { (await import('./js/i18n.js')).setLanguage(locale); await window.teamspeach.setPrefs({ theme }); }, { locale, theme });
|
||
await p.page.waitForFunction(dark => matchMedia('(prefers-color-scheme: dark)').matches === dark, theme === 'dark');
|
||
}
|
||
|
||
async function resetProduct(page) {
|
||
for (let i = 0; i < 3; i++) await page.keyboard.press('Escape');
|
||
await page.evaluate(() => { document.querySelectorAll('#toasts button').forEach(b => b.click()); document.querySelector('dialog.broadcast-dialog[open]')?.close(); });
|
||
if (await page.locator('#settings-view').isVisible()) {
|
||
if (await page.locator('#settings-back').isVisible()) await page.click('#settings-back');
|
||
else await page.click('#btn-settings');
|
||
}
|
||
}
|
||
|
||
// Drives the product with the same user actions the official screen represents.
|
||
async function stageProduct(page, screen) {
|
||
await resetProduct(page);
|
||
const [name, arg] = screen.split(':');
|
||
const channelRow = page.locator(`.channel-row[data-cid="${ownChannel}"] .row-btn`).first();
|
||
if (name === 'main' || name === 'menu' || name === 'broadcast') {
|
||
// Own channel chat through the product's own route (server card current-chat button).
|
||
if (await page.locator('#server-current-chat').isVisible()) await page.click('#server-current-chat');
|
||
else { await channelRow.click(); if (await page.locator('#btn-channel-chat').isVisible()) await page.click('#btn-channel-chat'); }
|
||
}
|
||
if (name === 'menu') {
|
||
// Same pointer rule as the official scenario: 40 px into the row, vertically centred.
|
||
const row = page.locator('.member-row[data-clid="2"] .row-btn');
|
||
const box = await row.boundingBox();
|
||
await row.click({ button: 'right', position: { x: 40, y: box.height / 2 } });
|
||
await page.waitForSelector('.client-menu:not(.client-submenu):not([aria-busy])');
|
||
}
|
||
if (name === 'broadcast') {
|
||
await page.locator('#broadcast-controls button').first().click();
|
||
await page.waitForSelector('dialog.broadcast-dialog[open] .broadcast-source');
|
||
}
|
||
if (name === 'private' || name === 'private-info') {
|
||
await page.locator('.member-row[data-clid="2"] .row-btn').click();
|
||
if (name === 'private-info') await page.click((await page.locator('#btn-info').isVisible()) ? '#btn-info' : '#chat-client-info');
|
||
}
|
||
if (name === 'server-info') {
|
||
await page.click('#btn-server-admin');
|
||
await page.waitForSelector('#channel-info-view', { state: 'visible' });
|
||
}
|
||
if (name === 'channel-edit') {
|
||
const row = page.locator(`.channel-row[data-cid="${ownChannel}"] .row-btn`).first();
|
||
const box = await row.boundingBox();
|
||
await row.click({ button: 'right', position: { x: 40, y: box.height / 2 } });
|
||
// Own-channel popup order (admin.js openChannelPopup): Info, Files, Edit Channel, Delete, …
|
||
await page.locator('.client-menu [role="menuitem"]').nth(2).click();
|
||
await page.waitForSelector('#channel-info-view .adm-form', { state: 'visible' });
|
||
}
|
||
if (name.startsWith('server-') && name !== 'server-info') {
|
||
// Server admin sub-views through the product's own server pane controls.
|
||
await page.click('#btn-server-admin');
|
||
await page.waitForSelector('#channel-info-view', { state: 'visible' });
|
||
const actionLabel = await page.evaluate(key => import('./js/i18n.js').then(({ t }) => t(`admin.${key}`)), { 'server-permissions': 'permissions', 'server-bans': 'bans', 'server-clients': 'clients' }[name]);
|
||
await page.locator('#channel-info-view .adm-manage').getByRole('button', { name: actionLabel, exact: true }).click();
|
||
await page.waitForTimeout(300);
|
||
}
|
||
if (name === 'settings') {
|
||
await page.click('#btn-settings');
|
||
const panel = { identities: 'identity', keybinds: 'keys', filetransfer: 'transfers' }[arg] ?? arg;
|
||
await page.locator(`#settings-nav [data-panel="${panel}"]`).evaluate(node => node.click());
|
||
await page.evaluate(() => { const s = document.querySelector('.settings-scroll'); if (s) s.scrollTop = 0; });
|
||
}
|
||
// Focus state as the official client presents each screen: opening a chat focuses its composer.
|
||
if (name === 'main' || name === 'private') await page.focus('#chat-input').catch(() => {});
|
||
else await page.evaluate(() => document.activeElement?.blur());
|
||
await page.waitForTimeout(350);
|
||
await page.evaluate(() => document.fonts.ready);
|
||
}
|
||
|
||
async function checkChatResize(p) {
|
||
const settled = () => p.page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
|
||
const position = () => p.page.evaluate(() => {
|
||
const log = document.querySelector('#chat-log');
|
||
return { top: log.scrollTop, height: log.scrollHeight, client: log.clientHeight, gap: log.scrollHeight - log.scrollTop - log.clientHeight };
|
||
});
|
||
await configureProduct(p, themes[0], locales[0], [1553, 998]);
|
||
await stageProduct(p.page, 'main');
|
||
await p.page.evaluate(() => { const log = document.querySelector('#chat-log'); log.scrollTop = log.scrollHeight; });
|
||
await settled();
|
||
const wide = await position();
|
||
await configureProduct(p, themes[0], locales[0], [880, 800]);
|
||
await settled();
|
||
const narrow = await position();
|
||
await p.page.evaluate(() => { document.querySelector('#chat-log').scrollTop = 0; });
|
||
await settled();
|
||
await configureProduct(p, themes[0], locales[0], [1553, 998]);
|
||
await settled();
|
||
const lookback = await position();
|
||
await p.page.evaluate(() => { const log = document.querySelector('#chat-log'); log.scrollTop = log.scrollHeight; });
|
||
await settled();
|
||
return { passed: wide.gap <= 1 && narrow.gap <= 1 && lookback.gap > 80, wide, narrow, lookback };
|
||
}
|
||
|
||
async function captureProduct() {
|
||
const byChat = Map.groupBy(screens, s => s.split('@')[1] ?? 'full');
|
||
for (const [variant, group] of byChat) {
|
||
const p = await launchProduct(variant);
|
||
try {
|
||
report.safety[`product ${variant}`] = { behaviour: p.behaviour };
|
||
if (variant === 'full') {
|
||
report.safety['chat resize'] = await checkChatResize(p);
|
||
if (!report.safety['chat resize'].passed) report.errors.push('Chat resize lost the latest-message anchor or forced a history reader to the bottom.');
|
||
}
|
||
for (const theme of themes) for (const locale of locales) for (const size of sizes) {
|
||
const cfg = cfgName(theme, locale, size);
|
||
const dir = path.join(out, 'product', cfg);
|
||
mkdirSync(dir, { recursive: true });
|
||
try { await configureProduct(p, theme, locale, size); }
|
||
catch (error) {
|
||
// e.g. the product's minimum window size: record every screen of this configuration as blocked.
|
||
for (const spec of group) report.blocked.push({ side: 'product', cfg, screen: spec, reason: String(error.message).split('\n')[0] });
|
||
console.log(`product ${cfg} BLOCKED: ${String(error.message).split('\n')[0]}`);
|
||
continue;
|
||
}
|
||
for (const spec of group) {
|
||
const screen = spec.split('@')[0];
|
||
try {
|
||
await stageProduct(p.page, screen);
|
||
await p.page.screenshot({ path: path.join(dir, fileName(spec)) });
|
||
const regions = await p.page.evaluate(readRegions, regionsFor(screen).map(r => ({ name: r.name, selectors: r.product, clipAbove: r.clipAbove })));
|
||
writeFileSync(path.join(dir, fileName(spec).replace('.png', '.json')), JSON.stringify({ viewport: size, regions }, null, 2));
|
||
console.log(`product ${cfg} ${spec}`);
|
||
} catch (error) {
|
||
report.blocked.push({ side: 'product', cfg, screen: spec, reason: String(error.message || error).split('\n')[0] });
|
||
console.log(`product ${cfg} ${spec} BLOCKED: ${String(error.message).split('\n')[0]}`);
|
||
}
|
||
}
|
||
}
|
||
const media = await p.page.evaluate(() => window.__forbiddenMedia);
|
||
const blocked = await p.app.evaluate(() => globalThis.__pairBlocked);
|
||
const commands = await p.app.evaluate(() => globalThis.__pairCommands.map(c => c.cmd));
|
||
Object.assign(report.safety[`product ${variant}`], { mediaAttempts: media, deviceCaptureOpened: false, blockedRequests: blocked, coreCommands: Object.fromEntries([...new Set(commands)].map(c => [c, commands.filter(x => x === c).length])), pageErrors: p.errors });
|
||
if (p.errors.length) report.errors.push(...p.errors.map(e => `product ${variant}: ${e}`));
|
||
} finally {
|
||
await p.app.close().catch(() => {});
|
||
rmSync(p.profile, { recursive: true, force: true });
|
||
}
|
||
}
|
||
}
|
||
|
||
// ------------------------------------------------------------------------------------------------
|
||
// Comparison.
|
||
const token = s => s.normalize('NFC');
|
||
const timestamps = text => (text?.match(/\b\d{1,2}:\d{2}\b/g) ?? []);
|
||
const sharedContent = () => [fixture.server.properties.name, ...fixture.channels.map(c => c.properties.name), ...fixture.clients.map(c => c.properties.nickname)];
|
||
const messagesOf = variant => fixture.chat[variant].filter(m => m.message_type === 1).map(m => m.content);
|
||
|
||
function comparePair(cfg, spec) {
|
||
const screen = spec.split('@')[0];
|
||
const variant = spec.split('@')[1] ?? 'full';
|
||
const officialPng = path.join(officialRoot, cfg, fileName(spec)), productPng = path.join(out, 'product', cfg, fileName(spec));
|
||
if (!existsSync(officialPng) || !existsSync(productPng)) return { cfg, screen: spec, verdict: 'blocked', reason: `${existsSync(officialPng) ? '' : 'official '}${existsSync(productPng) ? '' : 'product '}capture missing` };
|
||
const A = decodePng(readFileSync(officialPng)), B = decodePng(readFileSync(productPng));
|
||
const oJson = JSON.parse(readFileSync(officialPng.replace('.png', '.json'), 'utf8')), pJson = JSON.parse(readFileSync(productPng.replace('.png', '.json'), 'utf8'));
|
||
const dir = path.join(out, 'compare', cfg, spec.replace(/[:/@>]/g, '-'));
|
||
mkdirSync(dir, { recursive: true });
|
||
const excludedRects = regionsFor(screen).filter(r => r.exclude).flatMap(r => [oJson.regions[r.name]?.rect, pJson.regions[r.name]?.rect]).filter(Boolean);
|
||
const whole = compare(A, B, { tolerance: TOLERANCE, ignore: excludedRects, diff: true });
|
||
writeFileSync(path.join(dir, 'whole.png'), encodePng(sideBySide(A, B, whole.diff)));
|
||
const regions = regionsFor(screen).map(r => {
|
||
const clip = (side, region) => { const limit = r.clipAbove && side.regions[r.clipAbove]?.rect; return region && limit ? { ...region, rect: { ...region.rect, height: Math.min(region.rect.height, limit.y - region.rect.y) } } : region; };
|
||
const o = clip(oJson, oJson.regions[r.name]), p = clip(pJson, pJson.regions[r.name]);
|
||
const entry = { region: r.name, excluded: r.exclude, official: o && { rect: o.rect, style: o.style }, product: p && { rect: p.rect, style: p.style } };
|
||
if (!o && !p) return { ...entry, verdict: r.exclude ? 'excluded' : 'pass', reason: 'absent in both captures' };
|
||
if (!o || !p) return { ...entry, verdict: r.exclude ? 'excluded' : 'fail', reason: `${o ? '' : 'absent in official '}${p ? '' : 'absent in product'}`.trim() };
|
||
const a = crop(A, o.rect), b = crop(B, p.rect);
|
||
const ignore = excludedRects.flatMap(rect => [a, b].map(image => ({ ...rect, x: rect.x - image.rect.x, y: rect.y - image.rect.y })));
|
||
const pixels = compare(a, b, { tolerance: TOLERANCE, ignore, diff: true });
|
||
const shift = a.width * a.height <= 400000 ? bestShift(a, b, { radius: 3, tolerance: TOLERANCE, ignore }) : null;
|
||
writeFileSync(path.join(dir, `${r.name}.png`), encodePng(sideBySide(a, b, pixels.diff)));
|
||
const box = Object.fromEntries(['x', 'y', 'width', 'height'].map(k => [k, Math.round(p.rect[k] - o.rect[k])]));
|
||
const styleDiff = Object.fromEntries(Object.keys(o.style).filter(k => o.style[k] !== p.style[k]).map(k => [k, { official: o.style[k], product: p.style[k] }]));
|
||
const content = sharedContent().map(t => ({ token: t, official: o.text.includes(token(t)), product: p.text.includes(token(t)) })).filter(t => t.official || t.product);
|
||
const passed = !r.exclude && pixels.ratio <= MAX_RATIO && Object.values(box).every(v => Math.abs(v) <= MAX_BOX_DELTA);
|
||
return { ...entry, verdict: r.exclude ? 'excluded' : passed ? 'pass' : 'fail', boxDelta: box,
|
||
pixels: { differing: pixels.differing, counted: pixels.counted, ratio: Number(pixels.ratio.toFixed(5)), meanAbs: pixels.meanAbs && Number(pixels.meanAbs.toFixed(2)), bbox: pixels.bbox, sizeDelta: pixels.sizeDelta },
|
||
bestShift: shift, palette: { official: palette(a), product: palette(b) }, styleDiff,
|
||
contentMismatch: content.filter(t => t.official !== t.product).map(t => `${t.token}: official ${t.official ? 'shows' : 'lacks'}, product ${t.product ? 'shows' : 'lacks'}`),
|
||
crop: path.relative(out, path.join(dir, `${r.name}.png`)) };
|
||
});
|
||
const chatO = oJson.regions['chat-log']?.text, chatP = pJson.regions['chat-log']?.text;
|
||
const paintedO = oJson.regions['chat-log']?.paintedText, paintedP = pJson.regions['chat-log']?.paintedText;
|
||
if (screen === 'main' && (typeof paintedO !== 'string' || typeof paintedP !== 'string')) throw new Error('Chat capture lacks viewport text; regenerate both captures rather than comparing virtualized and retained DOM text.');
|
||
const content = (screen === 'main') ? {
|
||
messages: messagesOf(variant).map(m => ({ message: m, official: Boolean(chatO?.includes(m)), product: Boolean(chatP?.includes(m)) })),
|
||
timestamps: { official: timestamps(paintedO), product: timestamps(paintedP), equal: isDeepStrictEqual(timestamps(paintedO), timestamps(paintedP)) },
|
||
} : null;
|
||
const scored = regions.filter(r => r.verdict !== 'excluded');
|
||
const verdict = whole.ratio <= MAX_RATIO && scored.every(r => r.verdict === 'pass') && (!content || (content.timestamps.equal && content.messages.every(m => m.official === m.product))) ? 'pass' : 'fail';
|
||
return { cfg, screen: spec, verdict,
|
||
whole: { differing: whole.differing, counted: whole.counted, ratio: Number(whole.ratio.toFixed(5)), meanAbs: whole.meanAbs && Number(whole.meanAbs.toFixed(2)), excludedRects, strip: path.relative(out, path.join(dir, 'whole.png')) },
|
||
regions, content };
|
||
}
|
||
|
||
// ------------------------------------------------------------------------------------------------
|
||
// Instrument validation: decoder vs Electron nativeImage, identity, exact sensitivity, shift
|
||
// diagnosis, exclusion handling, and a known-different pair.
|
||
async function selfTest() {
|
||
const results = [];
|
||
const ok = (name, passed, evidence) => results.push({ name, passed: Boolean(passed), evidence });
|
||
const dir = path.join(out, 'instrument');
|
||
mkdirSync(dir, { recursive: true });
|
||
const ref = await launchOfficialRuntime({ theme: 'dark', locale: 'en', width: 1280, height: 800, chat: 'few' });
|
||
let main, settings;
|
||
try {
|
||
await ref.open('main');
|
||
let falsePredicateRejected = false;
|
||
try { await waitForAsync(ref.page, async () => false, undefined, { timeout: 100 }); }
|
||
catch (error) { falsePredicateRejected = /Async condition did not become true/.test(error.message); }
|
||
ok('An asynchronous false predicate is never accepted as a satisfied wait', falsePredicateRejected, {});
|
||
main = path.join(dir, 'official-main.png'); await ref.page.screenshot({ path: main });
|
||
await ref.open('settings:audio');
|
||
settings = path.join(dir, 'official-settings.png'); await ref.page.screenshot({ path: settings });
|
||
const decoded = decodePng(readFileSync(main));
|
||
const native = await ref.app.evaluate(({ nativeImage }, file) => { const img = nativeImage.createFromPath(file); return { size: img.getSize(), bgra: img.toBitmap().toString('base64') }; }, main);
|
||
const bgra = Buffer.from(native.bgra, 'base64');
|
||
let mismatched = 0;
|
||
for (let i = 0; i < decoded.width * decoded.height; i++) if (bgra[i * 4 + 2] !== decoded.data[i * 4] || bgra[i * 4 + 1] !== decoded.data[i * 4 + 1] || bgra[i * 4] !== decoded.data[i * 4 + 2]) mismatched++;
|
||
ok('PNG decoder equals Electron nativeImage on every pixel', native.size.width === decoded.width && native.size.height === decoded.height && mismatched === 0, { size: native.size, mismatched });
|
||
await ref.page.evaluate(() => {
|
||
const host = document.createElement('div'); host.id = 'qa-viewport-text';
|
||
Object.assign(host.style, { position: 'fixed', left: '0', top: '0', width: '100px', height: '20px', overflow: 'hidden', lineHeight: '20px', zIndex: '99999' });
|
||
for (const value of ['00:01', '00:02']) { const row = document.createElement('div'); row.textContent = value; row.style.height = '20px'; host.append(row); }
|
||
document.body.append(host); host.scrollTop = 20;
|
||
});
|
||
const retained = await ref.page.evaluate(readRegions, [{ name: 'chat-log', selectors: ['#qa-viewport-text'] }]);
|
||
await ref.page.evaluate(() => document.querySelector('#qa-viewport-text').firstChild.remove());
|
||
const virtualized = await ref.page.evaluate(readRegions, [{ name: 'chat-log', selectors: ['#qa-viewport-text'] }]);
|
||
ok('Painted chat timestamps ignore clipped retained rows, just like virtualized rows', retained['chat-log'].paintedText === '00:02' && virtualized['chat-log'].paintedText === '00:02', { retained: retained['chat-log'].paintedText, virtualized: virtualized['chat-log'].paintedText });
|
||
await ref.page.evaluate(() => document.querySelector('#qa-viewport-text').remove());
|
||
} finally { await ref.close(); }
|
||
const A = decodePng(readFileSync(main));
|
||
const roundTrip = decodePng(encodePng(A));
|
||
ok('Encode/decode round trip is lossless', isDeepStrictEqual(Buffer.from(roundTrip.data), Buffer.from(A.data)), { width: A.width, height: A.height });
|
||
const identity = compare(A, A, { tolerance: TOLERANCE });
|
||
ok('Identical images: zero differing pixels', identity.differing === 0 && identity.meanAbs === 0, identity);
|
||
const perturbed = { ...A, data: Uint8Array.from(A.data) };
|
||
for (let y = 300; y < 310; y++) for (let x = 500; x < 520; x++) for (let c = 0; c < 3; c++) perturbed.data[(y * A.width + x) * 4 + c] ^= 0x80;
|
||
const sens = compare(A, perturbed, { tolerance: TOLERANCE });
|
||
ok('20×10 perturbation detected exactly (200 px, exact bbox)', sens.differing === 200 && isDeepStrictEqual(sens.bbox, { x: 500, y: 300, width: 20, height: 10 }), { differing: sens.differing, bbox: sens.bbox });
|
||
const below = { ...A, data: Uint8Array.from(A.data) };
|
||
for (let i = 0; i < below.data.length; i += 4) below.data[i] = Math.min(255, below.data[i] + TOLERANCE);
|
||
ok(`Uniform +${TOLERANCE} shift stays within tolerance; +${TOLERANCE + 1} does not`, compare(A, below).differing === 0 && compare(A, { ...A, data: below.data.map((v, i) => (i % 4 === 0 ? Math.min(255, v + 1) : v)) }).differing > 0, {});
|
||
const ignored = compare(A, perturbed, { tolerance: TOLERANCE, ignore: [{ x: 500, y: 300, width: 20, height: 10 }] });
|
||
ok('Excluded rectangle removes exactly its pixels from scoring', ignored.differing === 0 && ignored.counted === A.width * A.height - 200, { counted: ignored.counted });
|
||
const cropRect = { x: 490, y: 290, width: 40, height: 30 };
|
||
const nested = compare(crop(A, cropRect), crop(perturbed, cropRect), { tolerance: TOLERANCE, ignore: [{ x: 10, y: 10, width: 20, height: 10 }] });
|
||
ok('An excluded native rectangle stays excluded inside a scored region crop', nested.differing === 0 && nested.counted === 1000, { differing: nested.differing, counted: nested.counted });
|
||
const region = crop(A, { x: 300, y: 100, width: 300, height: 200 });
|
||
const shifted = crop(A, { x: 302, y: 101, width: 300, height: 200 });
|
||
const strict = compare(region, shifted, { tolerance: TOLERANCE });
|
||
const shift = bestShift(region, shifted, { radius: 3, tolerance: TOLERANCE });
|
||
ok('2,1 px misalignment fails strictly and is diagnosed by bounded shift search', strict.differing > 0 && shift.dx === -2 && shift.dy === -1 && shift.differing <= strict.differing, { strict: strict.differing, shift });
|
||
const sizeMismatch = compare(region, crop(A, { x: 300, y: 100, width: 290, height: 200 }), { tolerance: TOLERANCE });
|
||
ok('Size mismatch counts the uncovered area as differing', sizeMismatch.differing >= 10 * 200, { differing: sizeMismatch.differing, sizeDelta: sizeMismatch.sizeDelta });
|
||
const different = compare(A, decodePng(readFileSync(settings)), { tolerance: TOLERANCE, diff: true });
|
||
writeFileSync(path.join(dir, 'known-different.png'), encodePng(sideBySide(A, decodePng(readFileSync(settings)), different.diff)));
|
||
ok('Known-different official screens (main vs settings) fail', different.ratio > MAX_RATIO, { ratio: different.ratio });
|
||
ok('Blank vs official main fails', compare(A, blank(A.width, A.height)).ratio > 0.5, {});
|
||
return { passed: results.every(r => r.passed), results };
|
||
}
|
||
|
||
// ------------------------------------------------------------------------------------------------
|
||
function markdown() {
|
||
const lines = ['# Official pair visual QA', '', `Started ${report.startedAt}; product ${report.exe ?? 'dev tree'}; fixture ${report.fixture}.`,
|
||
`Thresholds: channel tolerance ${TOLERANCE}/255; region/whole pass ≤ ${MAX_RATIO * 100}% differing pixels; box Δ ≤ ${MAX_BOX_DELTA}px. Display clock ${report.displayClock}.`, '',
|
||
`Instrument self-test: ${report.instrument ? (report.instrument.passed ? 'PASSED' : 'FAILED') : 'not run'}. Canonical fixture equal to live official fixture: ${report.canonicalFixture?.equalToLiveOfficialFixture ?? 'not checked'}.`, '',
|
||
'| cfg | screen | verdict | whole differing | failing regions (ratio, box Δ) |', '|---|---|---|---|---|'];
|
||
for (const p of report.pairs) {
|
||
const failing = (p.regions ?? []).filter(r => r.verdict === 'fail').map(r => `${r.region} ${r.pixels ? `${(r.pixels.ratio * 100).toFixed(1)}% Δ${r.boxDelta.x},${r.boxDelta.y},${r.boxDelta.width},${r.boxDelta.height}` : r.reason}`).join('; ');
|
||
lines.push(`| ${p.cfg} | ${p.screen} | ${p.verdict} | ${p.whole ? `${(p.whole.ratio * 100).toFixed(1)}%` : p.reason} | ${failing} |`);
|
||
}
|
||
if (report.blocked.length) lines.push('', '## Blocked', ...report.blocked.map(b => `- ${b.side} ${b.cfg} ${b.screen}: ${b.reason}`));
|
||
lines.push('', 'Excluded from scoring (captured, visible in strips): ' + [...new Set(Object.values(REGIONS).flat().filter(r => r.exclude).map(r => `${r.name} — ${r.exclude}`))].join('; '));
|
||
return lines.join('\n') + '\n';
|
||
}
|
||
|
||
async function holdStage() {
|
||
const [screenSpec, theme, locale, size] = hold.split(':').length === 5 ? [`${hold.split(':')[0]}:${hold.split(':')[1]}`, ...hold.split(':').slice(2)] : hold.split(':');
|
||
const variant = screenSpec.split('@')[1] ?? 'full';
|
||
const port = await freePort();
|
||
const p = await launchProduct(variant, { cdpPort: port });
|
||
await configureProduct(p, theme, locale, size.split('x').map(Number));
|
||
await stageProduct(p.page, screenSpec.split('@')[0]);
|
||
const targets = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json().catch(() => []);
|
||
const ready = { cdp_url: `http://127.0.0.1:${port}`, stage: hold, targets: targets.map(t => ({ id: t.id, type: t.type, url: t.url, webSocketDebuggerUrl: t.webSocketDebuggerUrl })), release: path.join(out, 'release'),
|
||
note: 'Owned hidden nonfocusable offscreen muted QA window; inspect read-only. Do not show/focus/capture devices. Create the release file to close.' };
|
||
writeFileSync(path.join(out, 'hold-ready.json'), JSON.stringify(ready, null, 2));
|
||
console.log(`HOLD READY ${JSON.stringify(ready)}`);
|
||
rmSync(ready.release, { force: true });
|
||
try { while (!existsSync(ready.release)) await new Promise(r => setTimeout(r, 1000)); }
|
||
finally { await p.app.close().catch(() => {}); rmSync(p.profile, { recursive: true, force: true }); }
|
||
}
|
||
|
||
try {
|
||
report.instrument = argv.includes('--no-self-test') ? { skipped: true, passed: true, note: 'not rerun; validated by a separate --self-test run (decoder==nativeImage, perturbation/shift/exclusion/known-different checks)' } : await selfTest();
|
||
save();
|
||
if (!report.instrument.passed) throw new Error('Instrument self-test failed; comparisons would not be trustworthy.');
|
||
if (!selfTestOnly) {
|
||
if (!hold || argv.includes('--capture')) {
|
||
if (officialFrom) {
|
||
report.officialFrom = officialRoot;
|
||
const prior = JSON.parse(readFileSync(path.join(officialFrom, 'pair-report.json'), 'utf8'));
|
||
report.canonicalFixture = { ...prior.canonicalFixture, verifiedBy: path.join(officialFrom, 'pair-report.json') };
|
||
if (!prior.canonicalFixture?.equalToLiveOfficialFixture || path.resolve(prior.fixture) !== fixturePath) throw new Error('Reused official captures were not verified against this canonical fixture.');
|
||
} else await captureOfficial();
|
||
save();
|
||
if (argv.includes('--official-only')) { report.officialOnly = true; save(); } else {
|
||
await captureProduct(); save();
|
||
for (const theme of themes) for (const locale of locales) for (const size of sizes) for (const spec of screens) report.pairs.push(comparePair(cfgName(theme, locale, size), spec));
|
||
save();
|
||
}
|
||
}
|
||
if (hold) await holdStage();
|
||
}
|
||
} catch (error) {
|
||
report.errors.push(String(error.stack || error));
|
||
process.exitCode = 1;
|
||
} finally {
|
||
report.finishedAt = new Date().toISOString();
|
||
save();
|
||
const counts = report.pairs.reduce((acc, p) => ({ ...acc, [p.verdict]: (acc[p.verdict] ?? 0) + 1 }), {});
|
||
console.log(JSON.stringify({ out, instrument: report.instrument?.passed, canonicalFixture: report.canonicalFixture, pairs: counts, blocked: report.blocked.length, errors: report.errors.slice(0, 5) }, null, 2));
|
||
if (report.pairs.some(p => p.verdict !== 'pass')) process.exitCode = 1;
|
||
}
|