// Local TS6 theme extensions in the real app, through the mandatory hidden/non-focusable/offscreen/muted // harness and a disposable profile with GENERATED extensions (never the user's profile or real themes): // selected variant CSS really applies (custom property + a rule + a font + an image from the extension root), // the selection persists as "//" and is re-applied on restart before Settings opens, // refresh picks up a newly installed extension, a variant whose CSS is refused (remote url()) leaves the stock // theme, a removed extension falls back to stock and clears the selection, and the page cannot fetch tsext:. // node scripts/smoke-user-styles.mjs --out docs/evidence/runtime/ [--exe packaged.exe] import { launchApp } from './lib/electron-app.mjs'; import { mkdirSync, writeFileSync, mkdtempSync, rmSync, readFileSync, copyFileSync, existsSync } from 'node:fs'; import { tmpdir } from 'node:os'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { createRequire } from 'node:module'; const require = createRequire(import.meta.url); const { writeExtension, png } = require('../test/fixtures/themes-fixture.cjs'); const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); const argv = process.argv.slice(2); const opt = (n, d) => (argv.indexOf(`--${n}`) >= 0 ? argv[argv.indexOf(`--${n}`) + 1] : d); const out = path.resolve(root, opt('out', 'smoke-out')); const exe = opt('exe'); mkdirSync(out, { recursive: true }); const result = { steps: [], limits: [] }; const step = (name, data = {}) => { result.steps.push({ name, ...data }); console.log(`[user-styles] ${name}`, JSON.stringify(data)); }; const check = (cond, message) => { if (!cond) throw new Error(message); }; const ID = 'org.teamspeach.fixture'; const BROKEN = 'org.teamspeach.broken'; const LATE = 'org.teamspeach.late'; const MAGENTA = `${ID}//Magenta Variant`; const LIME = `${ID}//Lime Variant`; // A real TrueType font copied from the OS into the disposable profile at run time (never committed). const FONT_CANDIDATES = [ 'C:/Windows/Fonts/arial.ttf', 'C:/Windows/Fonts/segoeui.ttf', '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', '/usr/share/fonts/TTF/DejaVuSans.ttf', '/System/Library/Fonts/Supplemental/Arial.ttf', ]; function variantCss(color, outline) { return [ ':root { --tsv-bg: ' + color + '; --tsv-tint: ' + color + '; }', '@font-face { font-family: "TPFixtureFont"; src: url(fonts/fixture.ttf) format("truetype"); }', `body { outline: 3px solid ${outline}; }`, 'body::after { content: ""; background-image: url(img/bg.png); }', ].join('\n'); } function seed(profile) { const ext = path.join(profile, 'extensions'); const font = FONT_CANDIDATES.find((f) => existsSync(f)); const files = { 'img/bg.png': png([1, 2, 3]) }; writeExtension(ext, ID, { themes: [ { name: 'Magenta Variant', source: 'magenta.css', css: variantCss('#ff00ff', 'rgb(1, 2, 3)') }, { name: 'Lime Variant', source: 'lime.css', css: variantCss('#00ff00', 'rgb(4, 5, 6)') }, ], files, }); if (font) { mkdirSync(path.join(ext, ID, 'fonts'), { recursive: true }); copyFileSync(font, path.join(ext, ID, 'fonts', 'fixture.ttf')); } else { result.limits.push('no system TrueType font found: the @font-face load is not exercised on this host'); } writeExtension(ext, BROKEN, { themes: [{ name: 'Remote Variant', source: 'remote.css', css: 'body { outline: 3px solid rgb(7, 8, 9); background: url(https://example.org/x.png); }' }], files: { 'img/bg.png': png() }, }); return { ext, font: Boolean(font) }; } async function launch(profile) { const app = await launchApp({ exe, profile }); const page = await app.firstWindow(); page.on('requestfailed', (request) => { if (request.url().startsWith('tsext:')) step('theme resource request failed', { url: request.url(), error: request.failure()?.errorText }); }); page.on('response', (response) => { if (response.url().startsWith('tsext:')) step('theme resource response', { url: response.url(), status: response.status() }); }); await page.setViewportSize({ width: 1280, height: 800 }).catch(() => {}); return { app, page }; } const state = (page) => page.evaluate(() => ({ state: document.documentElement.dataset.userStyleState ?? null, link: document.getElementById('userStyle')?.getAttribute('href') ?? null, links: document.querySelectorAll('link[data-user-style]').length, lastInHead: document.head.lastElementChild?.id === 'userStyle', tsvBg: getComputedStyle(document.documentElement).getPropertyValue('--tsv-bg').trim(), outline: getComputedStyle(document.body).outlineColor, })); const waitState = (page, want) => page.waitForFunction((w) => document.documentElement.dataset.userStyleState === w, want, { timeout: 15000 }); const storedSelection = (profile) => JSON.parse(readFileSync(path.join(profile, 'prefs.json'), 'utf8')).userStyle ?? null; async function openAppearance(page) { await page.click('#btn-settings'); await page.click('button[data-panel="appearance"]'); await page.waitForSelector('#user-style-settings', { state: 'visible' }); } const profiles = []; let app; let failed = null; try { const profile = mkdtempSync(path.join(tmpdir(), 'teamspeach-user-styles-')); profiles.push(profile); const { ext, font } = seed(profile); let page; // 1) First run: stock theme, onboarding, picker lists the generated extensions. ({ app, page } = await launch(profile)); await page.waitForSelector('#view-onboarding', { state: 'visible', timeout: 20000 }); await waitState(page, 'stock'); const stock = await state(page); step('first run uses the stock theme', stock); await page.fill('#onboarding-nick', 'ThemeSmoke'); await page.click('#onboarding-submit'); await page.waitForSelector('#view-app', { state: 'visible', timeout: 20000 }); await openAppearance(page); await page.click('#user-style-toggle'); // the picker re-renders, so no post-click state check on the old node await page.waitForSelector(`#extension_${ID.replaceAll('.', '\\.')}`); const cards = await page.$$eval('.ts-user-style-cards:not(.ts-user-style-expanded) .ts-user-style-card', (els) => els.map((e) => e.id)); const preview = await page.$eval(`#extension_${ID.replaceAll('.', '\\.')} img`, async (img) => { let decodeError = null; try { await img.decode(); } catch (error) { decodeError = `${error.name}: ${error.message}`; } return { naturalWidth: img.naturalWidth, complete: img.complete, connected: img.isConnected, src: img.getAttribute('src'), decodeError }; }); step('picker lists generated extensions with decoded previews', { cards, preview }); check(cards.includes(`extension_${ID}`) && cards.includes(`extension_${BROKEN}`), 'extensions missing from picker'); check(preview.naturalWidth === 1 && preview.src.startsWith(`tsext://${ID}/preview.png`), 'preview not decoded from tsext:'); // 2) Select a variant: the CSS really applies, last in , with its font and image. await page.click(`#extension_${ID.replaceAll('.', '\\.')}`); await page.click(`#${ID.replaceAll('.', '\\.')}_magenta_variant`); await waitState(page, 'applied'); const applied = await state(page); const assets = await page.evaluate(async ([id, broken, wantFont]) => { const load = (src) => new Promise((resolve) => { const img = new Image(); img.onload = () => resolve(img.naturalWidth); img.onerror = () => resolve('error'); img.src = src; }); let fetchBlocked = false; try { await fetch(`tsext://${id}/magenta.css`); } catch { fetchBlocked = true; } const faces = wantFont ? (await document.fonts.load('16px "TPFixtureFont"')).length : null; return { activeImage: await load(`tsext://${id}/img/bg.png`), otherExtensionImage: await load(`tsext://${broken}/img/bg.png`), otherExtensionPreview: await load(`tsext://${broken}/preview.png`), remoteImage: await load('https://example.org/x.png'), fontFaces: faces, fetchBlocked, }; }, [ID, BROKEN, font]); step('selected variant applied', { ...applied, ...assets, stored: storedSelection(profile) }); check(applied.tsvBg === '#ff00ff' && applied.outline === 'rgb(1, 2, 3)' && applied.lastInHead && applied.links === 1, 'variant CSS not applied'); check(assets.activeImage === 1 && assets.otherExtensionImage === 'error' && assets.otherExtensionPreview === 1 && assets.remoteImage === 'error', 'image confinement wrong'); check(!font || assets.fontFaces >= 1, 'extension font did not load'); check(assets.fetchBlocked, 'page could fetch tsext:'); check(storedSelection(profile) === MAGENTA, 'selection not persisted'); await page.screenshot({ path: path.join(out, 'user-style-applied.png') }); // 3) Switch variant without a stock flash: still exactly one sheet afterwards. await page.click(`#${ID.replaceAll('.', '\\.')}_lime_variant`); await page.waitForFunction(() => getComputedStyle(document.documentElement).getPropertyValue('--tsv-bg').trim() === '#00ff00', null, { timeout: 15000 }); const lime = await state(page); step('variant switch', { ...lime, stored: storedSelection(profile) }); check(lime.links === 1 && lime.outline === 'rgb(4, 5, 6)' && storedSelection(profile) === LIME, 'variant switch failed'); // 4) Refresh picks up an extension installed while running. writeExtension(ext, LATE, { themes: [{ name: 'Late Variant', source: 'late.css', css: ':root{--tsv-bg:#123456}' }] }); await page.click('#user-style-settings [data-action="refresh"]'); await page.waitForSelector(`#extension_${LATE.replaceAll('.', '\\.')}`, { timeout: 15000 }); step('refresh lists a newly installed extension', { identifier: LATE }); // 5) Resource failure: CSS refused by the loader (remote url()) → stock theme, selection kept for a later fix. await page.click(`#extension_${BROKEN.replaceAll('.', '\\.')}`); await page.click(`#${BROKEN.replaceAll('.', '\\.')}_remote_variant`); await waitState(page, 'error'); const broken = await state(page); step('refused CSS leaves the stock theme', { ...broken, stock, stored: storedSelection(profile) }); check(broken.links === 0 && broken.link === null && broken.tsvBg === stock.tsvBg && broken.outline === stock.outline, 'stock not restored after failure'); check(storedSelection(profile) === `${BROKEN}//Remote Variant`, 'selection should persist after a load failure'); // 6) Restart: the saved variant is applied at startup, before Settings is opened. await page.click(`#extension_${ID.replaceAll('.', '\\.')}`); await page.click(`#${ID.replaceAll('.', '\\.')}_magenta_variant`); await waitState(page, 'applied'); await app.close(); ({ app, page } = await launch(profile)); await page.waitForSelector('#view-app', { state: 'visible', timeout: 20000 }); await waitState(page, 'applied'); const restarted = await state(page); const settingsHidden = await page.$eval('#settings-view', (el) => el.hidden); step('restart re-applies the saved variant', { ...restarted, settingsHidden }); check(restarted.tsvBg === '#ff00ff' && settingsHidden, 'saved theme not applied on startup'); await app.close(); // 7) Selected extension removed while closed → stock theme, selection cleared, user told. rmSync(path.join(ext, ID), { recursive: true, force: true }); ({ app, page } = await launch(profile)); await page.waitForSelector('#view-app', { state: 'visible', timeout: 20000 }); await page.waitForFunction(() => document.querySelector('#toasts')?.textContent.includes('Magenta Variant'), null, { timeout: 15000 }); await waitState(page, 'stock'); const missing = await state(page); step('missing extension falls back to stock and clears the selection', { ...missing, stored: storedSelection(profile) }); check(missing.links === 0 && missing.tsvBg === stock.tsvBg && storedSelection(profile) === null, 'missing selection not reset'); } catch (err) { failed = err; step('FAILED', { error: String(err.stack || err) }); } finally { if (app) await app.close().catch(() => {}); for (const p of profiles) rmSync(p, { recursive: true, force: true }); } result.ok = !failed; writeFileSync(path.join(out, 'result.json'), JSON.stringify(result, null, 2)); console.log(`[user-styles] ${result.ok ? 'OK' : 'FAILED'} → ${out}`); process.exit(result.ok ? 0 : 1);