Files
client/scripts/smoke-official-parity-offscreen.mjs
T
omar e6464bc4ed feat: checkpoint account-free client workflows and source-matched UI
Preserve accumulated client implementation since v0.1.4, including local identities, multi-server state, chat, administration, audio and streaming controls. Refine official-source layout, original artwork, responsive composer overflow, settings navigation and chat scroll anchoring.

Current verification: Node suite passes; isolated packaged chat and responsive control smokes pass without device capture. Native core is reused, not rebuilt in this pass. Strict whole-screen visual parity remains incomplete; no 1:1 or cross-platform acceptance claim. Local checkpoint only; no release or push.
2026-11-01 19:43:18 +03:00

477 lines
44 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Official TeamSpeak 6 visual parity QA — measurements, not impressions.
//
// Compares the ACTUAL TeamsPeach renderer against a RECONSTRUCTED official reference: the installed
// official client's own CSS layers (read in place, hash-verified, never copied into the repository)
// applied to a template that follows the official render functions (scripts/lib/official-ts6-template.mjs).
// Both sides render the same labelled synthetic data. Every metric is class-matched (region by region)
// and compared numerically: colours, platform fonts, sizes, row heights/pitches, menu and player geometry.
// Optional --official-shots <dir> validates the reconstruction against real official screenshots by sha256
// (pixel probes on regions only; private captures are never copied, cropped into outputs, or committed).
//
// Safety: both windows are hidden, nonfocusable, offscreen and muted (shared launch guard plus the same
// guard on the reference window). Network is cancelled; permissions denied; no OS input, clipboard,
// capture device, native presentation, server, official native bridge, normal profile or audible output.
import { launchApp } from './lib/electron-app.mjs';
import { loadOfficialReference, DEFAULT_OFFICIAL_DIR } from './lib/official-ts6-reference.mjs';
import { FIXTURE, eventSentence, officialLocale, referenceHtml } from './lib/official-ts6-template.mjs';
import { GENERATED_STREAM_COMMANDS, installGeneratedStreams, relayGeneratedStreamCommand, watchGeneratedStream } from './lib/generated-stream.mjs';
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
const args = process.argv.slice(2);
const option = key => args.includes(`--${key}`) ? args[args.indexOf(`--${key}`) + 1] : undefined;
const out = path.resolve(option('out') || 'smoke-out/official-parity');
const officialDir = path.resolve(option('official-dir') || DEFAULT_OFFICIAL_DIR);
const shotsDir = option('official-shots');
const referenceOnly = args.includes('--reference-only');
mkdirSync(out, { recursive: true });
const profile = mkdtempSync(path.join(tmpdir(), 'teamspeach-parity-qa-'));
const scratch = mkdtempSync(path.join(tmpdir(), 'teamspeach-parity-ref-')); // transient reference pages; deleted below
const WIDTH = 1553, HEIGHT = 998;
const configurations = ['dark', 'light'].flatMap(theme => ['en', 'ru'].map(language => ({ theme, language })));
const result = {
scope: 'TeamsPeach actual offscreen renderer vs RECONSTRUCTED official template (installed official CSS + render-function DOM chains, synthetic data). Not the official runtime, its native bridge, or a live server.',
official: null, window: null, referenceWindow: null, configurations: [], metrics: [], screenshotProbes: [], regions: [], checks: [], errors: [],
};
const check = (name, passed, evidence) => result.checks.push({ name, passed: Boolean(passed), evidence });
let app, page, refPage, mainId;
// ---------------------------------------------------------------------------------------------
// Class-matched metric map. teamspeach: candidate selectors (first present wins); official: template selector.
// kind: color (rgba, ±2 per channel), px (±1), num (exact), font (exact), count (exact), text (exact), presence.
const M = (region, metric, kind, teamspeach, read, official, officialRead = read) => ({ region, metric, kind, teamspeach: [].concat(teamspeach), read, official, officialRead });
const MENU = '.client-menu:not(.client-submenu)';
export const METRICS = [
M('shell', 'body font family (first)', 'font', 'body', 'fontFamily0', 'body'),
M('header', 'fill (pixel)', 'color', '.session-head', 'pixelInner', '[data-qa=header-bar]'),
M('header', 'height', 'px', '.session-head', 'height', '[data-qa=header-bar]'),
M('header', 'title font size', 'px', '#channel-title', 'fontSize', '[data-qa=header-title]'),
M('header', 'title font weight', 'num', '#channel-title', 'fontWeight', '[data-qa=header-title]'),
M('header', 'title colour', 'color', '#channel-title', 'color', '[data-qa=header-title]'),
M('header', 'title platform font', 'font', '#channel-title', 'platformFont', '[data-qa=header-title]'),
M('header', 'separator thickness', 'px', '.session-separator', 'height', '[data-qa=header-separator]'),
M('header', 'separator colour', 'color', '.session-separator', 'bg', '[data-qa=header-separator]'),
M('header', 'mode buttons', 'count', '.session-head .detail-modes button', 'count', '[data-qa=header-segments] .tsv-segmented-button'),
M('player', 'tile border width', 'px', '.stream-view', 'borderTopWidth', '[data-qa=stage-tile]'),
M('player', 'tile border colour', 'color', '.stream-view', 'borderTopColor', '[data-qa=stage-tile]'),
M('player', 'tile corner radius', 'px', '.stream-view', 'borderTopLeftRadius', '[data-qa=stage-tile]'),
M('player', 'tile background', 'color', '.stream-view', 'bg', '[data-qa=stage-tile]'),
M('player', 'name label font size', 'px', '.stream-view .stream-title', 'fontSize', '[data-qa=stage-name]'),
M('player', 'name label colour', 'color', '.stream-view .stream-title', 'color', '[data-qa=stage-name]'),
M('player', 'name label left inset', 'px', '.stream-view .stream-title', 'insetLeft', '[data-qa=stage-name]', 'insetLeft'),
M('player', 'name label bottom inset', 'px', '.stream-view .stream-title', 'insetBottom', '[data-qa=stage-name]', 'insetBottom'),
M('events', 'row height', 'px', '#chat-log li.msg-system', 'height', '[data-qa=event-body]'),
M('events', 'row pitch', 'px', '#chat-log li.msg-system', 'pitch', '[data-qa=event-body]'),
M('events', 'row corner radius', 'px', '#chat-log li.msg-system', 'borderTopLeftRadius', '[data-qa=event-body]'),
M('events', 'row left fill (pixel)', 'color', '#chat-log li.msg-system', 'pixelLeft', '[data-qa=event-body]'),
M('events', 'text colour', 'color', ['#chat-log li.msg-system .msg-system-text', '#chat-log li.msg-system'], 'color', '[data-qa=event-text]'),
M('events', 'text font size', 'px', ['#chat-log li.msg-system .msg-system-text', '#chat-log li.msg-system'], 'fontSize', '[data-qa=event-text]'),
M('events', 'names emphasised', 'count', '#chat-log li.msg-system strong', 'count', '[data-qa=event-text] strong'),
M('events', 'time stamps', 'count', ['#chat-log li.msg-system time', '#chat-log li.msg-system .msg-system-time'], 'count', '[data-qa=event-time]'),
M('events', 'time visible colour', 'color', ['#chat-log li.msg-system time', '#chat-log li.msg-system .msg-system-time'], 'visibleColor', '[data-qa=event-time]'),
M('events', 'name colour', 'color', '#chat-log li.msg-system strong', 'color', '[data-qa=event-text] strong'),
M('events', 'platform font', 'font', ['#chat-log li.msg-system .msg-system-text', '#chat-log li.msg-system'], 'platformFont', '[data-qa=event-text]'),
M('composer', 'container background', 'color', '#chat-form', 'bg', '[data-qa=composer]'),
M('composer', 'container border colour', 'color', '#chat-form', 'borderTopColor', '[data-qa=composer]'),
M('composer', 'container corner radius', 'px', '#chat-form', 'borderTopLeftRadius', '[data-qa=composer]'),
M('composer', 'input font size', 'px', '#chat-input', 'fontSize', '[data-qa=composer-input]'),
M('composer', 'toolbar present', 'presence', '#chat-format-bar:not([hidden])', 'count', '[data-qa=toolbar]'),
M('composer', 'toolbar height', 'px', '#chat-format-bar', 'height', '[data-qa=toolbar]'),
M('composer', 'toolbar background', 'color', '#chat-format-bar', 'bg', '[data-qa=toolbar]'),
M('composer', 'toolbar buttons (official order)', 'count', '#chat-format-bar .composer-tool', 'count', '[data-qa=toolbar-button]'),
M('composer', 'action buttons', 'count', '#chat-form > button, #chat-form .composer-actions button', 'count', '[data-qa=composer-action]'),
M('menu', 'corner radius', 'px', MENU, 'borderTopLeftRadius', '[data-qa=menu]'),
M('menu', 'font size', 'px', `${MENU} [role^=menuitem]`, 'fontSize', '[data-qa=menu]'),
M('menu', 'backdrop gradient opacity and blur', 'text', MENU, 'backdropStyle', '[data-qa=menu]'),
M('menu', 'item height', 'px', `${MENU} [role^=menuitem]`, 'height', '[data-qa~=menu-item]'),
M('menu', 'item text colour', 'color', `${MENU} [role^=menuitem]:not(.destructive)`, 'color', '[data-qa=menu-item] [data-qa=menu-label]'),
M('menu', 'item platform font', 'font', `${MENU} [role^=menuitem] .client-menu-label`, 'platformFont', '[data-qa=menu-item] [data-qa=menu-label]'),
M('menu', 'title colour', 'color', `${MENU} .client-menu-title`, 'color', '[data-qa=menu-title] [data-qa=menu-label]'),
M('menu', 'section caption colour', 'color', `${MENU} .client-menu-section`, 'color', '[data-qa=menu-caption]'),
M('menu', 'section caption font size', 'px', `${MENU} .client-menu-section`, 'fontSize', '[data-qa=menu-caption]'),
M('menu', 'section captions', 'count', `${MENU} .client-menu-section`, 'count', '[data-qa=menu-caption]'),
M('menu', 'destructive colour', 'color', `${MENU} .destructive`, 'color', '[data-qa~=menu-destructive]'),
M('menu', 'outer rendered width (same labels)', 'px', MENU, 'width', '[data-qa=menu]'),
M('tree', 'channel row height', 'px', ['#tree .tree-row.channel-row', '#tree .channel-row'], 'height', '[data-qa=tree-channel-row]'),
M('tree', 'client row height', 'px', ['#tree .tree-row.member-row', '#tree .member-row'], 'height', '[data-qa=tree-client-row]'),
M('tree', 'channel name font size', 'px', ['#tree .channel-row .row-label', '#tree .channel-row'], 'fontSize', '[data-qa=tree-channel-name]'),
M('tree', 'channel name colour', 'color', ['#tree .channel-row .row-label', '#tree .channel-row'], 'color', '[data-qa=tree-channel-name]'),
M('tree', 'client name colour', 'color', ['#tree .member-row:not(.self) .row-label', '#tree .member-row:not(.self)'], 'color', '[data-qa=tree-client-name]'),
M('tree', 'pane background (pixel)', 'color', '#tree', 'pixelInner', '[data-qa-region=tree]'),
];
// In-page reader shared by both windows (serialized; no closures).
function readMetrics(specs) {
const rgba = value => { const m = /rgba?\(([^)]+)\)/.exec(value || ''); if (!m) return null; const [r, g, b, a = '1'] = m[1].split(/[ ,/]+/).filter(Boolean); return [Number(r), Number(g), Number(b), Number(a)]; };
const effectiveBg = (node, solidOnly = false) => { for (let n = node; n; n = n.parentElement) { const s = getComputedStyle(n); const c = rgba(s.backgroundColor); if (c && c[3] > 0) return s.backgroundColor; if (s.backgroundImage !== 'none' && !solidOnly) return s.backgroundImage; } return 'rgba(0, 0, 0, 0)'; };
return specs.map(spec => {
const selector = spec.selectors.find(s => { try { return document.querySelector(s); } catch { return false; } });
if (!selector) return { selector: null, value: spec.read === 'count' ? 0 : null };
const nodes = [...document.querySelectorAll(selector)].filter(n => n.getClientRects().length);
const node = nodes[0] ?? document.querySelector(selector);
const style = getComputedStyle(node), rect = node.getBoundingClientRect();
const parentRect = (node.closest('.stream-view, .video-stream') ?? node.parentElement).getBoundingClientRect();
const tops = nodes.map(n => n.getBoundingClientRect().top).sort((a, b) => a - b);
const deltas = tops.slice(1).map((t, i) => t - tops[i]).sort((a, b) => a - b);
const values = {
count: nodes.length, height: rect.height, fontSize: parseFloat(style.fontSize), fontWeight: Number(style.fontWeight), color: style.color,
backdropStyle: [getComputedStyle(node, '::before').backgroundImage, getComputedStyle(node, '::before').opacity, style.backdropFilter].join(' | '),
fontFamily0: style.fontFamily.split(',')[0].trim().replace(/^["']|["']$/g, ''), bg: effectiveBg(node), width: rect.width,
borderTopWidth: parseFloat(style.borderTopWidth), borderTopColor: style.borderTopColor, borderTopLeftRadius: parseFloat(style.borderTopLeftRadius),
visibleColor: (() => { // text colour after element/ancestor opacity over the effective solid background
let alpha = (rgba(style.color)?.[3] ?? 1); for (let n = node; n; n = n.parentElement) alpha *= Number(getComputedStyle(n).opacity);
const fg = rgba(style.color), bg = rgba(effectiveBg(node, true)) ?? [0, 0, 0, 1];
return fg ? `rgb(${fg.slice(0, 3).map((v, i) => Math.round(v * alpha + bg[i] * (1 - alpha))).join(', ')})` : null;
})(),
pitch: deltas.length ? deltas[Math.floor(deltas.length / 2)] : null, insetLeft: rect.left - parentRect.left, insetBottom: parentRect.bottom - rect.bottom,
};
return { selector, value: values[spec.read] ?? null, rect: rect.toJSON(), pixel: spec.read.startsWith('pixel') ? spec.read : null };
});
}
const sha256 = data => createHash('sha256').update(data).digest('hex');
const parseColor = value => { const m = /rgba?\(([^)]+)\)/.exec(value || ''); if (!m) return null; const [r, g, b, a = '1'] = m[1].split(/[ ,/]+/).filter(Boolean); return [Number(r), Number(g), Number(b), Number(a)]; };
const firstGradientColor = value => parseColor((/rgba?\([^)]+\)/.exec(value || '') || [])[0]);
function compare(kind, a, b) {
if (a === null || a === undefined) return { passed: false, reason: 'TeamsPeach counterpart missing' };
if (b === null || b === undefined) return { passed: false, reason: 'official value unavailable' };
if (kind === 'color') {
const x = parseColor(a) ?? firstGradientColor(a), y = parseColor(b) ?? firstGradientColor(b);
if (!x || !y) return { passed: false, reason: 'unparsable colour' };
const delta = Math.max(...x.slice(0, 3).map((v, i) => Math.abs(v - y[i])), Math.round(Math.abs(x[3] - y[3]) * 255));
return { passed: delta <= 2, delta };
}
if (kind === 'px') return { passed: Math.abs(a - b) <= 1, delta: Math.round((a - b) * 100) / 100 };
if (kind === 'presence') return { passed: Boolean(a) === Boolean(b) };
return { passed: a === b };
}
// Pixel work runs in the main process through Electron's nativeImage (no image dependency in the repo).
const imageOps = (source, ops) => app.evaluate(({ nativeImage }, { source, ops }) => {
const image = source.path ? nativeImage.createFromPath(source.path) : nativeImage.createFromBuffer(Buffer.from(source.png, 'base64'));
const { width, height } = image.getSize(); const bitmap = image.toBitmap(); // BGRA
const at = (x, y) => { const i = (Math.round(y) * width + Math.round(x)) * 4; return [bitmap[i + 2], bitmap[i + 1], bitmap[i]]; };
const near = (a, b, tol) => a.every((v, i) => Math.abs(v - b[i]) <= tol);
const hex = c => `#${c.map(v => v.toString(16).padStart(2, '0')).join('')}`;
return { width, height, results: ops.map(op => {
if (op.type === 'pixel') return hex(at(op.x, op.y));
if (op.type === 'leftFill') {
const counts = new Map();
for (let y = op.y + 3; y < op.y + op.height - 3; y++) for (let x = op.x + 1; x <= op.x + 5; x++) {
const color = hex(at(x, y)); counts.set(color, (counts.get(color) ?? 0) + 1);
}
const dominant = [...counts].sort((a, b) => b[1] - a[1])[0]?.[0];
if (!dominant) throw new Error('Empty event-row pixel sample');
return dominant;
}
if (op.type === 'run') { // length of the run of `color` along a column starting at the first match after y0
let y = op.y0; while (y < op.y1 && !near(at(op.x, y), op.color, op.tol ?? 2)) y++;
const start = y; while (y < op.y1 && near(at(op.x, y), op.color, op.tol ?? 2)) y++;
return { start, length: y - start };
}
if (op.type === 'rows') { // non-background runs along a column → heights and pitch
const runs = []; let start = null;
for (let y = op.y0; y < op.y1; y++) { const fg = !near(at(op.x, y), op.background, op.tol ?? 3); if (fg && start === null) start = y; if (!fg && start !== null) { runs.push([start, y - start]); start = null; } }
const full = runs.slice(1); const median = list => list.length ? [...list].sort((a, b) => a - b)[Math.floor(list.length / 2)] : null;
return { runs, height: median(full.map(r => r[1])), pitch: median(full.slice(1).map((r, i) => r[0] - full[i][0])) };
}
if (op.type === 'textColor') { // dominant colour of the most contrasting 3% of pixels in a rectangle
const pixels = []; for (let y = op.y0; y < op.y1; y++) for (let x = op.x0; x < op.x1; x++) pixels.push(at(x, y));
const lum = c => (c[0] + c[1] + c[2]) / 3; const sorted = pixels.map(lum).sort((a, b) => a - b); const median = sorted[Math.floor(sorted.length / 2)];
const distance = pixels.map(c => Math.abs(lum(c) - median)).sort((a, b) => a - b); const cut = distance[Math.floor(distance.length * 0.97)];
const counts = new Map(); for (const c of pixels) if (Math.abs(lum(c) - median) > cut) counts.set(hex(c), (counts.get(hex(c)) ?? 0) + 1);
return [...counts].sort((a, b) => b[1] - a[1])[0]?.[0] ?? null;
}
if (op.type === 'textRunDelta') { // distance between the first two text lines (any pixel brighter than 140) in a window
const starts = []; let inside = false;
for (let y = op.y0; y < op.y1; y++) { let lit = false; for (let x = op.x0; x < op.x1 && !lit; x++) lit = at(x, y).reduce((s, v) => s + v, 0) / 3 > 140; if (lit && !inside) starts.push(y); inside = lit; }
return starts.length >= 2 ? starts[1] - starts[0] : null;
}
if (op.type === 'brightest') { // dominant colour among the 40 brightest pixels (bold light text on dark rows)
const pixels = []; for (let y = op.y0; y < op.y1; y++) for (let x = op.x0; x < op.x1; x++) pixels.push(at(x, y));
const counts = new Map(); for (const c of pixels.sort((a, b) => (b[0] + b[1] + b[2]) - (a[0] + a[1] + a[2])).slice(0, 40)) counts.set(hex(c), (counts.get(hex(c)) ?? 0) + 1);
return [...counts].sort((a, b) => b[1] - a[1])[0]?.[0] ?? null;
}
return null;
}) };
}, { source, ops });
// Real official screenshots (user-provided, private). Probes only; DPR 1 established by exact token matches.
const OFFICIAL_SHOTS = [
{ sha256: '605d553da4d1ca509c6c1ae97ee4b446ad4472a64f6b9eca54e63fda91e34e0f', theme: 'dark', label: 'channel view with stream and chat (857×924)', probes: [
{ name: 'titlebar fill', op: { type: 'pixel', x: 400, y: 15 }, token: '--ts-new-header-bg' },
{ name: 'channel header fill', op: { type: 'pixel', x: 400, y: 70 }, token: '--tsv-shaded-bg' },
{ name: 'channel header height', op: { type: 'run', x: 700, y0: 40, y1: 140, token: '--tsv-shaded-bg' }, field: 'length', template: ['[data-qa=header-bar]', 'height'] },
{ name: 'header separator thickness', op: { type: 'run', x: 700, y0: 100, y1: 140, token: '--tsv-header-bg' }, field: 'length', template: ['[data-qa=header-separator]', 'height'] },
{ name: 'player border colour', op: { type: 'pixel', x: 53, y: 300 }, token: '--tsv-bg' },
{ name: 'player border width', op: { type: 'run', x: 400, y0: 550, y1: 560, token: '--tsv-bg' }, field: 'length', template: ['[data-qa=stage-tile]', 'borderTopWidth'] },
{ name: 'event row height', op: { type: 'rows', x: 300, y0: 566, y1: 836, token: '--tsv-shaded-bg' }, field: 'height', template: ['[data-qa=event-body]', 'height'] },
{ name: 'event row pitch', op: { type: 'rows', x: 300, y0: 566, y1: 836, token: '--tsv-shaded-bg' }, field: 'pitch', template: ['[data-qa=event-body]', 'pitch'] },
{ name: 'event row left fill', op: { type: 'pixel', x: 40, y: 608 }, token: '--ts-chat-system-message-bg' },
{ name: 'event name colour (bold)', op: { type: 'brightest', x0: 60, x1: 150, y0: 600, y1: 618 }, template: ['[data-qa=event-text] strong', 'color'], kind: 'color' },
{ name: 'event sentence colour', op: { type: 'textColor', x0: 145, x1: 265, y0: 600, y1: 618 }, template: ['[data-qa=event-text]', 'color'], kind: 'color' },
{ name: 'event time visible colour', op: { type: 'textColor', x0: 740, x1: 830, y0: 600, y1: 618 }, template: ['[data-qa=event-time]', 'visibleColor'], kind: 'color' },
{ name: 'composer field fill', op: { type: 'pixel', x: 600, y: 892 }, token: '--tsv-bg' },
] },
{ sha256: 'da3542fa69c8c317a2294e310da42a81550f99e0e76af632e253db28510a083d', theme: 'dark', label: 'channel view, player hover controls (827×913)', probes: [
{ name: 'channel header height', op: { type: 'run', x: 700, y0: 29, y1: 130, token: '--tsv-shaded-bg' }, field: 'length', template: ['[data-qa=header-bar]', 'height'] },
{ name: 'header separator thickness', op: { type: 'run', x: 700, y0: 95, y1: 130, token: '--tsv-header-bg' }, field: 'length', template: ['[data-qa=header-separator]', 'height'] },
{ name: 'event row height', op: { type: 'rows', x: 300, y0: 660, y1: 830, token: '--tsv-shaded-bg' }, field: 'height', template: ['[data-qa=event-body]', 'height'] },
] },
{ sha256: 'beb8ea7219e30e7819161fe74b07fac14c956f5004ff82adbb20e751d029aa43', theme: 'dark', label: 'client context menu (262×461 crop)', probes: [
{ name: 'menu item text colour', op: { type: 'textColor', x0: 30, x1: 200, y0: 69, y1: 85 }, token: '--ts-context-menu-font-color' },
{ name: 'section caption colour', op: { type: 'textColor', x0: 30, x1: 200, y0: 125, y1: 145 }, token: '--tsv-font-subtitle-color' },
{ name: 'destructive item colour', op: { type: 'textColor', x0: 30, x1: 200, y0: 365, y1: 381 }, token: '--tsv-context-menu-error-color' },
{ name: 'plain item pitch (kick channel → kick server)', op: { type: 'textRunDelta', x0: 30, x1: 200, y0: 360, y1: 415 }, template: ['[data-qa~=menu-destructive]', 'pitch'] },
{ name: 'submenu item pitch (server groups → channel group)', op: { type: 'textRunDelta', x0: 30, x1: 200, y0: 150, y1: 215 }, template: ['[data-qa=menu-item]:has(.tsv-item-accessory)', 'height'] },
{ name: 'title colour', op: { type: 'brightest', x0: 30, x1: 200, y0: 7, y1: 21 }, template: ['[data-qa=menu-title] [data-qa=menu-label]', 'visibleColor'], kind: 'color' },
] },
];
// ---------------------------------------------------------------------------------------------
const send = event => app.evaluate(({ BrowserWindow }, { id, event }) => BrowserWindow.fromId(id).webContents.send('core:event', { ...event, connectionId: 'c1' }), { id: mainId, event });
const shot = async (target, clip) => (await target.screenshot({ clip, fullPage: true, scale: 'css' })).toString('base64');
// TeamsPeach side: onboarding through the real UI, read-only fixture core answers, synthetic snapshot and one generated stream.
async function setupTeamsPeach() {
await page.waitForSelector('#view-onboarding', { state: 'visible' });
await page.evaluate(() => {
window.__forbiddenCapture = 0; window.__nativeRequests = 0;
for (const key of ['getUserMedia', 'getDisplayMedia']) navigator.mediaDevices[key] = async () => { window.__forbiddenCapture++; throw new DOMException('Capture forbidden in parity fixture', 'NotAllowedError'); };
navigator.mediaDevices.enumerateDevices = async () => [];
for (const [prototype, method] of [[Element.prototype, 'requestFullscreen'], [HTMLVideoElement.prototype, 'requestPictureInPicture']]) prototype[method] = async () => { window.__nativeRequests++; throw new Error('Native presentation forbidden'); };
Object.defineProperty(document, 'pictureInPictureEnabled', { configurable: true, value: false });
});
await page.fill('#onboarding-nick', FIXTURE.self);
await page.locator('#onboarding-submit').click();
await page.waitForSelector('#view-app', { state: 'visible' });
await page.waitForFunction(() => window.teamspeachDiagnostics?.snapshot().core === 'ready');
await app.evaluate(({ ipcMain, BrowserWindow }, { id, commands, relaySource }) => {
const relay = new Function(`return (${relaySource});`)();
globalThis.__parityCommands = [];
ipcMain.removeHandler('core:request');
const allowed = { allowed: true, reason: 'fixture', source: 'fixture' };
ipcMain.handle('core:request', async (_event, connectionId, cmd, args) => {
globalThis.__parityCommands.push({ cmd, args });
if (commands.includes(cmd)) { await BrowserWindow.fromId(id).webContents.executeJavaScript(relay(cmd, args, connectionId)); return { ok: true, result: {} }; }
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'].map(key => [key, 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 };
return { ok: false, error: { code: 'not_connected', message: 'Read-only parity fixture; command not dispatched' } };
});
}, { id: mainId, commands: GENERATED_STREAM_COMMANDS, relaySource: relayGeneratedStreamCommand.toString() });
await send({ event: 'audio_state', input_muted: true, output_muted: true, transmitting: false });
await send({ event: 'state', state: 'connected', address: 'fixture.invalid:9987', reason: null });
await send({ event: 'snapshot', rev: 1, own_client_id: 1, own_channel_id: 10,
server: { name: FIXTURE.server, uid: 'fixture-server=', version: '', welcome_message: '' }, server_groups: [], channel_groups: [],
channels: [{ id: 10, parent_id: 0, order: 0, depth: 0, name: FIXTURE.channel, topic: '', codec: 'opus_voice', max_clients: -1 }, { id: 20, parent_id: 0, order: 10, depth: 0, name: FIXTURE.otherChannel, codec: 'opus_voice', max_clients: -1 }],
clients: [{ id: 1, uid: 'fixture-self', nickname: FIXTURE.self, is_self: true, channel_id: 10, input_muted: true, output_muted: true, input_hardware: true, server_groups: [] },
{ id: 2, uid: 'fixture-mira', nickname: FIXTURE.mira, channel_id: 10, input_hardware: true, server_groups: [] },
{ id: 3, uid: 'fixture-oleg', nickname: FIXTURE.oleg, channel_id: 20, input_hardware: true, server_groups: [] }] });
await installGeneratedStreams(page, [['parity-mira', 2, `${FIXTURE.mira} — generated`, '#25495a']]);
await watchGeneratedStream(page, 'parity-mira');
}
// TeamsPeach side per configuration: the real event paths render the shared fixture; the real menu is opened by the renderer.
async function captureTeamsPeach(config, stem) {
await page.evaluate(async ({ language, theme, sentences, names }) => {
(await import('./js/i18n.js')).setLanguage(language);
await window.teamspeach.setPrefs({ theme });
const chat = await import('./js/chat.js');
document.querySelectorAll('#chat-log li.msg-system').forEach(node => node.remove());
for (const text of sentences) chat.addSystem((await import('./js/state.js')).viewedConnection(), 'channel', () => text, { emphasis: names });
document.querySelectorAll('#toasts button').forEach(button => button.click());
document.activeElement?.blur();
}, { ...config, names: [FIXTURE.self, FIXTURE.mira, FIXTURE.oleg, FIXTURE.channel, FIXTURE.otherChannel], sentences: FIXTURE.events.map(event => eventSentence(officialLocale(officialDir, config.language), event)) });
await page.waitForFunction(dark => matchMedia('(prefers-color-scheme: dark)').matches === dark, config.theme === 'dark');
await page.waitForFunction(() => [...document.querySelectorAll('.stream-view [data-role="stream-overlay"]')].every(node => node.textContent === ''));
await page.locator('.member-row[data-clid="3"] .row-btn, .member-row[data-clid="3"]').first().click({ button: 'right' });
await page.waitForSelector(`${MENU}:not([aria-busy])`);
await page.waitForTimeout(250);
const teamspeach = await page.evaluate(readMetrics, METRICS.map(m => ({ selectors: m.teamspeach, read: m.read })));
const tpShot = await page.screenshot({ path: path.join(out, `teamspeach-${stem}.png`), scale: 'css' });
const widths = await page.evaluate(() => {
const box = selector => document.querySelector(selector)?.getBoundingClientRect();
const tile = box('.stream-view .stream-stage') ?? box('.stream-view');
return { detail: Math.round(box('.workspace')?.width ?? 800), tree: Math.round(box('#tree')?.width ?? 300), tile: Math.round(tile?.width ?? 640), tileHeight: Math.round(tile?.height ?? 360) };
});
const tpRegions = await page.evaluate(menu => Object.fromEntries(Object.entries({ header: '.session-head', stage: '.stream-view', events: '#chat-log', composer: '#chat-form', menu, tree: '#tree' })
.map(([key, selector]) => [key, document.querySelector(selector)?.getBoundingClientRect().toJSON() ?? null])), MENU);
return { teamspeach, tpShot, widths, tpRegions };
}
// --reference-only: measure the reconstructed official template alone (official targets + screenshot validation).
const referenceOnlyCapture = () => ({ teamspeach: METRICS.map(() => ({ selector: null, value: null })), tpShot: null, widths: { detail: 860, tree: 320, tile: 760, tileHeight: 428 }, tpRegions: {} });
try {
const official = loadOfficialReference({ dir: officialDir, platform: 'windows' });
result.official = { dir: official.dir, platform: official.platform, files: official.files, modules: official.modules };
app = await launchApp({ exe: option('exe'), profile });
result.window = 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.webRequest.onBeforeRequest({ urls: ['http://*/*', 'https://*/*', 'ws://*/*', 'wss://*/*'] }, (_details, done) => done({ cancel: true }));
return { id: win.id, visible: win.isVisible(), focusable: win.isFocusable(), offscreen: win.webContents.isOffscreen(), audioMuted: win.webContents.isAudioMuted() };
});
mainId = result.window.id;
assert.deepEqual({ ...result.window, id: 0 }, { id: 0, visible: false, focusable: false, offscreen: true, audioMuted: true });
page = await app.firstWindow();
if (!referenceOnly) page.on('pageerror', error => result.errors.push(`teamspeach: ${error.message}`));
await app.evaluate(({ BrowserWindow }, { id, size }) => BrowserWindow.fromId(id).setContentSize(...size), { id: mainId, size: [WIDTH, HEIGHT] });
if (!referenceOnly) await setupTeamsPeach();
const referenceTime = new Date();
for (const config of configurations) {
const stem = `${config.theme}-${config.language}`;
const { teamspeach, tpShot, widths, tpRegions } = referenceOnly ? referenceOnlyCapture() : await captureTeamsPeach(config, stem);
// --- Reconstructed official reference (fresh hidden window per configuration)
const file = path.join(scratch, `reference-${stem}.html`);
writeFileSync(file, referenceHtml({ stylesheets: official.stylesheetsFor(config.theme), locale: officialLocale(officialDir, config.language), language: config.language, widths, time: referenceTime }));
const windowPromise = app.waitForEvent('window', { predicate: p => p.url().startsWith('file:') });
result.referenceWindow = await app.evaluate(async ({ BrowserWindow, session }, { file, width, height }) => {
globalThis.__qaReferenceWindow?.destroy();
const partition = 'qa-official-reference';
const ses = session.fromPartition(partition);
ses.setPermissionRequestHandler((_w, _p, done) => done(false));
ses.setPermissionCheckHandler(() => false);
ses.webRequest.onBeforeRequest((details, done) => done({ cancel: !/^(file|data|devtools):/.test(details.url) }));
const win = new BrowserWindow({ show: false, focusable: false, skipTaskbar: true, width, height, useContentSize: true,
webPreferences: { offscreen: true, partition, sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: false, paintWhenInitiallyHidden: true } });
for (const method of ['show', 'showInactive', 'focus', 'maximize', 'minimize', 'restore', 'setFullScreen', 'setSimpleFullScreen']) win[method] = () => { throw new Error(`Native window operation forbidden in offscreen QA: ${method}`); };
win.webContents.setAudioMuted(true);
globalThis.__qaReferenceWindow = win;
await win.loadFile(file);
return { visible: win.isVisible(), focusable: win.isFocusable(), offscreen: win.webContents.isOffscreen(), audioMuted: win.webContents.isAudioMuted() };
}, { file, width: WIDTH, height: Math.max(HEIGHT, widths.tileHeight + 1400) });
assert.deepEqual(result.referenceWindow, { visible: false, focusable: false, offscreen: true, audioMuted: true });
refPage = await windowPromise;
refPage.on('pageerror', error => result.errors.push(`reference: ${error.message}`));
await refPage.waitForLoadState('load');
await refPage.evaluate(() => document.fonts.ready);
const officialValues = await refPage.evaluate(readMetrics, METRICS.map(m => ({ selectors: [m.official], read: m.officialRead })));
const refRegions = await refPage.evaluate(() => Object.fromEntries([...document.querySelectorAll('[data-qa-region]')].map(node => {
const inner = { header: '[data-qa-region=header]', stage: '[data-qa=stage-tile]', events: '.qa-events', composer: '[data-qa=composer]', menu: '[data-qa=menu]', tree: '[data-qa-region=tree]' }[node.dataset.qaRegion];
return [node.dataset.qaRegion, document.querySelector(inner).getBoundingClientRect().toJSON()];
})));
const tokens = await refPage.evaluate(names => Object.fromEntries(names.map(name => { const probe = document.createElement('i'); probe.style.color = `var(${name})`; document.body.append(probe); const value = getComputedStyle(probe).color; probe.remove(); return [name, value]; })),
[...new Set(OFFICIAL_SHOTS.flatMap(s => s.probes.flatMap(p => [p.token, p.op.token]).filter(Boolean)))]);
// Platform fonts (actual rendered face) through CDP on both windows.
const platformFonts = async (target, selectors) => {
const cdp = await target.context().newCDPSession(target);
await cdp.send('DOM.enable'); await cdp.send('CSS.enable');
const { root } = await cdp.send('DOM.getDocument', { depth: -1 });
const fonts = [];
for (const selector of selectors) {
const { nodeId } = selector ? await cdp.send('DOM.querySelector', { nodeId: root.nodeId, selector }).catch(() => ({ nodeId: 0 })) : { nodeId: 0 };
fonts.push(nodeId ? (await cdp.send('CSS.getPlatformFontsForNode', { nodeId })).fonts.sort((a, b) => b.glyphCount - a.glyphCount)[0]?.familyName ?? null : null);
}
await cdp.detach();
return fonts;
};
const fontIndexes = METRICS.map((m, i) => m.read === 'platformFont' ? i : -1).filter(i => i >= 0);
const tpFonts = await platformFonts(page, fontIndexes.map(i => teamspeach[i].selector));
const offFonts = await platformFonts(refPage, fontIndexes.map(i => officialValues[i].selector));
fontIndexes.forEach((index, n) => { teamspeach[index].value = tpFonts[n]; officialValues[index].value = offFonts[n]; });
// Pixel metrics from each window's own screenshot.
const refShot = await refPage.screenshot({ path: path.join(out, `official-reconstructed-${stem}.png`), fullPage: true, scale: 'css' });
const pixelPoint = (entry, read) => read === 'pixelLeft' ? { x: entry.rect.left + 3, y: entry.rect.top + entry.rect.height / 2 } : { x: entry.rect.left + entry.rect.width - 6, y: entry.rect.top + 6 };
for (const [values, png] of [[teamspeach, tpShot], [officialValues, refShot]]) {
const pixelIndexes = values.map((v, i) => v.pixel && v.rect ? i : -1).filter(i => i >= 0);
if (!png || !pixelIndexes.length) continue;
const { results } = await imageOps({ png: png.toString('base64') }, pixelIndexes.map(i => values[i].pixel === 'pixelLeft'
? { type: 'leftFill', x: values[i].rect.left, y: values[i].rect.top, height: values[i].rect.height }
: { type: 'pixel', ...pixelPoint(values[i], values[i].pixel) }));
pixelIndexes.forEach((index, n) => { const [r, g, b] = results[n].slice(1).match(/../g).map(h => parseInt(h, 16)); values[index].value = `rgb(${r}, ${g}, ${b})`; });
}
for (const [index, metric] of METRICS.entries()) {
const outcome = referenceOnly ? { passed: null } : compare(metric.kind, teamspeach[index].value, officialValues[index].value);
result.metrics.push({ ...config, region: metric.region, metric: metric.metric, kind: metric.kind, teamspeach: teamspeach[index].value, teamspeachSelector: teamspeach[index].selector, official: officialValues[index].value, officialSelector: officialValues[index].selector, ...outcome });
}
// Region crops (same data, class-matched) and a labelled side-by-side montage rendered in the reference window.
const pairs = [];
for (const region of ['header', 'stage', 'events', 'composer', 'menu', 'tree']) {
const a = tpRegions[region], b = refRegions[region];
if (!b) { pairs.push({ region, missing: 'official' }); continue; }
const clip = r => ({ x: Math.max(0, r.x), y: Math.max(0, r.y), width: Math.max(1, Math.min(r.width, 1200)), height: Math.max(1, Math.min(r.height, 900)) });
const tpFile = `region-${stem}-${region}-teamspeach.png`, offFile = `region-${stem}-${region}-official-reconstructed.png`;
writeFileSync(path.join(out, offFile), Buffer.from(await shot(refPage, clip(b)), 'base64'));
if (!a) { pairs.push({ region, missing: 'teamspeach', official: offFile, officialRect: b }); continue; }
writeFileSync(path.join(out, tpFile), Buffer.from(await shot(page, clip(a)), 'base64'));
pairs.push({ region, teamspeach: tpFile, official: offFile, teamspeachRect: a, officialRect: b, sizeDelta: { width: Math.round(a.width - b.width), height: Math.round(a.height - b.height) } });
}
result.regions.push({ ...config, pairs });
const montage = path.join(scratch, `montage-${stem}.html`);
writeFileSync(montage, `<!doctype html><meta charset="utf-8"><style>body{margin:0;padding:16px;background:#777;font:13px sans-serif;color:#fff}h2{margin:12px 0 4px;font-size:14px}div{display:flex;gap:16px;align-items:flex-start}figure{margin:0}figcaption{margin-bottom:4px}img{display:block;outline:1px solid #000}</style>
<p>${config.theme}/${config.language}. Left: TeamsPeach actual renderer. Right: RECONSTRUCTED official template (installed official CSS, synthetic data) — not the official runtime.</p>
${pairs.map(p => p.missing ? `<h2>${p.region}: ${p.missing} counterpart missing</h2>${p.official ? `<figure><figcaption>Official (reconstructed)</figcaption><img src="${pathToFileURL(path.join(out, p.official)).href}"></figure>` : ''}` : `<h2>${p.region} (Δw ${p.sizeDelta.width}px, Δh ${p.sizeDelta.height}px)</h2><div><figure><figcaption>TeamsPeach</figcaption><img src="${pathToFileURL(path.join(out, p.teamspeach)).href}"></figure><figure><figcaption>Official (reconstructed)</figcaption><img src="${pathToFileURL(path.join(out, p.official)).href}"></figure></div>`).join('')}`);
await refPage.goto(pathToFileURL(montage).href);
await refPage.evaluate(() => Promise.all([...document.images].map(img => img.decode().catch(() => {}))));
await refPage.screenshot({ path: path.join(out, `compare-${stem}.png`), fullPage: true, scale: 'css' });
// Validate the reconstruction against real official screenshots (dark only; captures are dark).
if (shotsDir && config.theme === 'dark' && config.language === 'ru') {
await refPage.goto(pathToFileURL(file).href); await refPage.evaluate(() => document.fonts.ready);
const files = Object.fromEntries(readdirSync(shotsDir).filter(name => name.endsWith('.png')).map(name => [sha256(readFileSync(path.join(shotsDir, name))), path.join(shotsDir, name)]));
for (const shotSpec of OFFICIAL_SHOTS) {
if (!files[shotSpec.sha256]) { result.screenshotProbes.push({ image: shotSpec.sha256, label: shotSpec.label, missing: true }); continue; }
const colour = name => parseColor(tokens[name]).slice(0, 3);
const ops = shotSpec.probes.map(probe => ({ ...probe.op, ...(probe.op.token ? { [probe.op.type === 'rows' ? 'background' : 'color']: colour(probe.op.token) } : {}) }));
const { width, height, results } = await imageOps({ path: files[shotSpec.sha256] }, ops);
const templateValues = await refPage.evaluate(readMetrics, shotSpec.probes.map(p => ({ selectors: [p.template?.[0] ?? 'body'], read: p.template?.[1] ?? 'count' })));
shotSpec.probes.forEach((probe, n) => {
const observed = probe.field ? results[n][probe.field] : results[n];
const expected = probe.template ? templateValues[n].value : tokens[probe.token];
const asRgb = value => typeof value === 'string' && value.startsWith('#') ? `rgb(${value.slice(1).match(/../g).map(h => parseInt(h, 16)).join(', ')})` : value;
const outcome = probe.template && probe.kind !== 'color' ? compare('px', observed, expected) : compare('color', asRgb(observed), expected);
result.screenshotProbes.push({ image: shotSpec.sha256, label: shotSpec.label, size: [width, height], probe: probe.name, observed, expected, against: probe.template ? `template ${probe.template.join(' ')}` : `token ${probe.token}`, ...outcome });
});
}
}
result.configurations.push({ ...config, widths });
if (!referenceOnly) await page.keyboard.press('Escape');
}
await app.evaluate(() => { globalThis.__qaReferenceWindow?.destroy(); globalThis.__qaReferenceWindow = null; });
// ---------------------------------------------------------------------------------------------
if (!referenceOnly) {
for (const config of configurations) {
const rows = result.metrics.filter(m => m.theme === config.theme && m.language === config.language);
check(`${config.theme}/${config.language}: official parity metrics (${rows.filter(m => m.passed).length}/${rows.length})`, rows.every(m => m.passed), rows.filter(m => !m.passed).map(m => `${m.region}/${m.metric}: TeamsPeach ${JSON.stringify(m.teamspeach)} vs official ${JSON.stringify(m.official)}${m.reason ? ` (${m.reason})` : ''}`));
}
result.commands = await app.evaluate(() => globalThis.__parityCommands);
check('No connect, mutation or server command requested', !result.commands.some(({ cmd }) => !['client_context', 'stream_list', 'set_transmit', ...GENERATED_STREAM_COMMANDS].includes(cmd)), result.commands.map(c => c.cmd));
const safety = await page.evaluate(() => ({ capture: window.__forbiddenCapture, native: window.__nativeRequests }));
check('No physical capture or native presentation attempted', safety.capture === 0 && safety.native === 0, safety);
}
if (shotsDir) check('Reconstructed template matches real official screenshots on every probe', result.screenshotProbes.length > 0 && result.screenshotProbes.every(p => p.passed), result.screenshotProbes.filter(p => !p.passed));
check('No renderer errors', result.errors.length === 0, result.errors);
} catch (error) {
result.errors.push(error.stack || String(error));
if (page) await page.screenshot({ path: path.join(out, 'failure.png') }).catch(() => {});
} finally {
if (app) await app.close().catch(() => {});
rmSync(profile, { recursive: true, force: true });
rmSync(scratch, { recursive: true, force: true });
result.ok = result.errors.length === 0 && result.checks.length > 0 && result.checks.every(item => item.passed);
writeFileSync(path.join(out, 'result.json'), JSON.stringify(result, null, 2));
const table = ['| theme/lang | region | metric | TeamsPeach | official (reconstructed) | pass |', '|---|---|---|---|---|---|',
...result.metrics.map(m => `| ${m.theme}/${m.language} | ${m.region} | ${m.metric} | ${JSON.stringify(m.teamspeach)} | ${JSON.stringify(m.official)} | ${m.passed ? 'yes' : `**no**${m.reason ? ` (${m.reason})` : ''}`} |`)];
writeFileSync(path.join(out, 'metrics.md'), `${table.join('\n')}\n`);
}
console.log(JSON.stringify({ ok: result.ok, out, metrics: result.metrics.length, mismatches: result.metrics.filter(m => !m.passed).length, probes: result.screenshotProbes.map(p => `${p.probe ?? 'missing'}: ${p.passed ?? 'missing'}`), failures: result.checks.filter(c => !c.passed).map(c => c.name), errors: result.errors }, null, 2));
process.exitCode = result.ok ? 0 : 1;