// Offscreen chat-editor regression: one CodeMirror composer, real keyboard/IME input through CDP, real toolbar, // slash/emoji completion, Settings toggle persistence, undo/selection across hybrid/raw, conversation isolation, // session gates and hostile Markdown in the live preview. Synthetic core IPC only; no server, network, media, // clipboard, native dialog or OS input. Never run on the interactive desktop: the shared harness enforces offscreen. import { closeSettings, launchApp } from './lib/electron-app.mjs'; import assert from 'node:assert/strict'; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import path from 'node:path'; import { maliciousMessages } from '../test/fixtures/chat-markup.mjs'; const args = process.argv.slice(2); const opt = (key, fallback) => args.includes(`--${key}`) ? args[args.indexOf(`--${key}`) + 1] : fallback; const out = path.resolve(opt('out', 'smoke-out/chat-editor')); const profile = mkdtempSync(path.join(tmpdir(), 'teamspeach-chat-editor-')); mkdirSync(out, { recursive: true }); const result = { scope: 'Offscreen disposable Electron; synthetic core IPC and snapshots; CDP keyboard/IME input into the real CodeMirror contentDOM. No server, network, capture, sound, OS clipboard, native dialog or global input.', checks: [], screenshots: [], errors: [], network: [] }; let app; let page; let revision = 0; const SELF = { id: 1, uid: 'ZWRpdG9yLXNlbGY=', nickname: 'EditorQA', channel_id: 10, is_self: true, input_muted: true, output_muted: true, input_hardware: true, output_hardware: true, server_groups: [] }; const PEER = { id: 2, uid: 'ZWRpdG9yLXBlZXI=', nickname: 'Peer', channel_id: 10, input_muted: false, output_muted: false, input_hardware: true, output_hardware: true, server_groups: [] }; const snapshot = (clients = [SELF, PEER]) => ({ event: 'snapshot', rev: ++revision, own_client_id: 1, own_channel_id: 10, server: { uid: 'ZWRpdG9yLXNlcnZlcg==', name: 'Editor QA', version: 'fixture', welcome_message: '', hostbanner_gfx_url: null, hostbanner_url: null }, channels: [{ id: 10, parent_id: 0, order: 0, depth: 0, name: 'Lobby', topic: '', codec: 'opus_voice', needed_talk_power: 0, has_password: false }], clients, server_groups: [], channel_groups: [], }); const send = (event) => app.evaluate(({ BrowserWindow }, value) => BrowserWindow.getAllWindows()[0].webContents.send('core:event', { ...value, connectionId: 'c1' }), event); const resize = (width, height) => app.evaluate(({ BrowserWindow }, size) => BrowserWindow.getAllWindows()[0].setContentSize(...size), [width, height]); const check = (name, data = {}) => result.checks.push({ name, ...data }); const shot = async (name) => { const file = `${name}.png`; await page.screenshot({ path: path.join(out, file) }); result.screenshots.push(file); }; const sent = () => app.evaluate(() => globalThis.__editorCommands.filter((c) => c.cmd === 'send_text')); const t = (key) => page.evaluate(async (k) => (await import('./js/i18n.js')).t(k), key); const state = () => page.evaluate(async () => { const editor = (await import('./js/chat.js')).composerEditor(); const root = document.querySelector('#chat-editor .cm-editor'); const input = document.querySelector('#chat-input'); return { value: editor.value, start: editor.selectionStart, end: editor.selectionEnd, disabled: editor.disabled, editable: input.contentEditable, ariaDisabled: input.getAttribute('aria-disabled'), focused: document.activeElement === input, hybrid: root.classList.contains('tp-chat-editor-hybrid'), blocks: root.querySelectorAll('.tp-chat-editor-block').length, views: document.querySelectorAll('#chat-editor .cm-editor').length }; }); const select = (start, end) => page.evaluate(async ([s, e]) => (await import('./js/chat.js')).composerEditor().setSelectionRange(s, e), [start, end]); const clear = async () => { await page.focus('#chat-input'); await page.keyboard.press('ControlOrMeta+A'); await page.keyboard.press('Delete'); }; const setRichText = async (on) => { await page.click('#btn-settings'); await page.click('#settings-nav [data-panel="chats"]'); const toggle = page.getByRole('switch', { name: await t('settings.chat.text_edit.rich_text'), exact: false }); if (on) await toggle.check(); else await toggle.uncheck(); const subtitle = await t(on ? 'settings.chat.text_edit.rich_text.enabled' : 'settings.chat.text_edit.rich_text.disabled'); await page.waitForFunction((text) => [...document.querySelectorAll('#settings-chat-markdown *')].some((n) => n.childElementCount === 0 && n.textContent === text), subtitle); const stored = await page.evaluate(async () => (await (await import('./js/core.js')).tp.getPrefs()).chatRichTextEditor); await closeSettings(page); return stored; }; try { app = await launchApp({ exe: opt('exe'), profile }); page = await app.firstWindow(); page.on('pageerror', (error) => result.errors.push(error.message)); page.on('console', (message) => { if (message.type() === 'error') result.errors.push(message.text()); }); await page.route(/^(https?|wss?|ftp):\/\//, (route) => { result.network.push(route.request().url()); return route.abort(); }); await page.waitForSelector('#view-onboarding', { state: 'visible', timeout: 30000 }); await page.evaluate(() => { for (const method of ['getUserMedia', 'getDisplayMedia']) navigator.mediaDevices[method] = async () => { throw new DOMException('Capture forbidden in editor QA', 'NotAllowedError'); }; }); await page.fill('#onboarding-nick', 'EditorQA'); await page.click('#onboarding-submit'); await page.waitForSelector('#view-app', { state: 'visible' }); await page.waitForFunction(() => window.teamspeachDiagnostics?.snapshot().core === 'ready'); // Only this disposable process replaces its request handler. send_text is recorded and refused, so no sent-message // sound plays and the failed send must keep the draft exactly as a real refusal would. await app.evaluate(({ ipcMain }) => { globalThis.__editorCommands = []; ipcMain.removeHandler('core:request'); ipcMain.handle('core:request', (_event, connectionId, cmd, args) => { globalThis.__editorCommands.push({ connectionId, cmd, args }); if (cmd === 'set_transmit') return { ok: true, result: { mode: args.mode, sensitivity: args.sensitivity } }; if (cmd === 'stream_list') return { ok: true, result: { results: [] } }; return { ok: false, error: { code: 'not_connected', message: 'Offline editor fixture' } }; }); }); await resize(1280, 800); await send({ event: 'audio_state', input_muted: true, output_muted: true, transmitting: false }); await send(snapshot()); await page.waitForFunction(() => document.querySelector('#chat-input')?.contentEditable === 'true'); // One editor, source placeholder metrics, rich text on by default. const initial = await page.evaluate(() => { const placeholder = document.querySelector('#chat-editor .cm-placeholder'); const style = placeholder && getComputedStyle(placeholder); const host = getComputedStyle(document.querySelector('#chat-editor')); return { textareas: document.querySelectorAll('#chat-form textarea').length, placeholder: placeholder?.textContent ?? null, letterSpacing: style?.letterSpacing, color: style?.color, fontSize: host.fontSize, lineHeight: host.lineHeight, subtitle: getComputedStyle(document.documentElement).getPropertyValue('--tsv-font-subtitle-color').trim(), role: document.querySelector('#chat-input').getAttribute('role'), label: document.querySelector('#chat-input').getAttribute('aria-label') }; }); const initialState = await state(); assert.equal(initial.textareas, 0, 'no hidden textarea mirror'); assert.equal(initialState.views, 1); assert.equal(initialState.hybrid, true, 'chatRichTextEditor defaults to hybrid preview'); assert.equal(initial.placeholder, await t('chat.sendMessage')); assert.equal(initial.letterSpacing, '-0.375px'); assert.equal(initial.fontSize, '14px'); assert.equal(initial.lineHeight, '18px'); assert.equal(initial.role, 'textbox'); assert.equal(initial.label, await t('ui.message')); check('Single CodeMirror composer with source placeholder metrics, hybrid by default', { ...initial, ...initialState }); await shot('01-empty-hybrid-dark'); // Real typing, Shift+Enter newline, Enter stays out of CodeMirror and leaves the line inactive/rendered. await page.focus('#chat-input'); await page.keyboard.type('Hello **bold** world'); await page.keyboard.press('Shift+Enter'); await page.keyboard.type('second line'); let now = await state(); assert.equal(now.value, 'Hello **bold** world\nsecond line'); assert.equal(now.start, now.value.length); assert.equal(now.end, now.value.length); const preview = await page.evaluate(() => ({ strong: [...document.querySelectorAll('#chat-editor .tp-chat-editor-block strong')].map((n) => n.textContent), rawActive: [...document.querySelectorAll('#chat-editor .cm-line')].some((n) => n.textContent === 'second line') })); assert.deepEqual(preview.strong, ['bold'], 'inactive line renders through the safe renderer'); assert.equal(preview.rawActive, true, 'active line stays raw source'); assert.deepEqual(await sent(), []); check('Typing, Shift+Enter and hybrid preview of the inactive line', { value: now.value, preview }); await shot('02-hybrid-typed-dark'); // Toolbar formatting is a text transaction with selection, undoable and redoable. CodeMirror joins adjacent // edits made within 500 ms into one undo event, so distinct steps wait past that window. const settle = () => page.waitForTimeout(600); await settle(); await select(21, 27); await page.click('#chat-format-bar [data-format="italic"]'); now = await state(); assert.equal(now.value, 'Hello **bold** world\n*second* line'); assert.deepEqual([now.start, now.end, now.focused], [22, 28, true]); await settle(); await page.click('#chat-format-bar [data-format="italic"]'); assert.equal((await state()).value, 'Hello **bold** world\nsecond line', 'toolbar toggles a wrapped selection back'); await page.keyboard.press('ControlOrMeta+Z'); assert.equal((await state()).value, 'Hello **bold** world\n*second* line', 'undo restores the formatted text'); await page.keyboard.press(process.platform === 'win32' ? 'Control+y' : 'ControlOrMeta+Shift+z'); assert.equal((await state()).value, 'Hello **bold** world\nsecond line', 'redo re-applies the unwrap'); check('Toolbar wrap/unwrap with selection, undo and redo'); // Slash completion consumes Enter before the send listener and CodeMirror. await page.keyboard.press('End'); await page.keyboard.press('Shift+Enter'); await page.keyboard.type('/bol'); await page.waitForSelector('#chat-slash-completion [role=option]'); assert.equal(await page.getAttribute('#chat-input', 'aria-activedescendant'), 'chat-slash-0'); await page.keyboard.press('Enter'); await page.keyboard.type('x'); now = await state(); assert.equal(now.value, 'Hello **bold** world\nsecond line\n**x**'); assert.equal(await page.locator('#chat-slash-completion').count(), 0); assert.equal(await page.getAttribute('#chat-input', 'aria-activedescendant'), null); assert.deepEqual(await sent(), [], 'completion Enter never sends'); check('Slash completion replaces its token and keeps the caret inside the snippet', { value: now.value }); // Emoji picker inserts at the remembered selection and returns focus. await settle(); await page.click('#chat-emoji'); await page.fill('.chat-emoji-picker input[type=search]', 'smile'); await page.click('.chat-emoji-picker button[title=":smile:"]'); now = await state(); assert.equal(now.value, 'Hello **bold** world\nsecond line\n**x:smile:**'); assert.equal(now.focused, true); check('Emoji insertion at the remembered caret'); // Raw/hybrid toggle through Settings: same view, same document/selection/history, persisted. await select(6, 14); const beforeToggle = await state(); assert.equal(await setRichText(false), false, 'raw choice persisted by main prefs'); now = await state(); assert.deepEqual({ value: now.value, start: now.start, end: now.end, views: now.views, hybrid: now.hybrid, blocks: now.blocks }, { value: beforeToggle.value, start: 6, end: 14, views: 1, hybrid: false, blocks: 0 }); await shot('03-raw-dark'); await page.focus('#chat-input'); await page.keyboard.press('ControlOrMeta+Z'); assert.equal((await state()).value, 'Hello **bold** world\nsecond line\n**x**', 'history survives the mode switch'); await page.keyboard.press(process.platform === 'win32' ? 'Control+y' : 'ControlOrMeta+Shift+z'); assert.equal((await state()).value, beforeToggle.value); assert.equal(await setRichText(true), true); now = await state(); assert.equal(now.hybrid, true); assert.equal(now.views, 1); assert.equal(now.value, beforeToggle.value); check('Settings toggle reconfigures the same editor immediately and persists', { stored: false, restored: true }); // Enter sends the exact trimmed text; the refused send keeps the draft and inserts no newline. await clear(); await page.keyboard.type('Ship it '); await page.keyboard.press('Enter'); await page.waitForFunction(() => document.querySelector('.toast[data-kind="error"]')); const attempts = await sent(); assert.equal(attempts.length, 1); assert.deepEqual({ cmd: attempts[0].cmd, target: attempts[0].args.target, message: attempts[0].args.message }, { cmd: 'send_text', target: 'channel', message: 'Ship it' }); assert.equal((await state()).value, 'Ship it '); await page.evaluate(() => document.querySelectorAll('.toast .icon-btn').forEach((button) => button.click())); check('Plain Enter sends through the chat listener; refused send preserves the draft'); // Conversation identity change resets document, selection and undo; returning restores only the draft. await clear(); await page.keyboard.type('channel draft'); await page.evaluate(async () => { const { S } = await import('./js/state.js'); (await import('./js/chat.js')).openPrivate(S.connections.get('c1'), 2); }); now = await state(); assert.deepEqual([now.value, now.start, now.end], ['', 0, 0]); await page.focus('#chat-input'); await page.keyboard.press('ControlOrMeta+Z'); assert.equal((await state()).value, '', 'undo cannot reach the other conversation'); await page.keyboard.type('private draft'); await page.evaluate(async () => (await import('./js/chat.js')).showOwnChannel()); assert.equal((await state()).value, 'channel draft'); await page.focus('#chat-input'); await page.keyboard.press('ControlOrMeta+Z'); assert.equal((await state()).value, 'channel draft', 'no cross-conversation undo after returning'); // Re-rendering the same conversation (snapshot) keeps the live editor history. await page.keyboard.type('!'); await send(snapshot()); await page.waitForTimeout(100); await page.focus('#chat-input'); await page.keyboard.press('ControlOrMeta+Z'); assert.equal((await state()).value, 'channel draft', 'same conversation keeps undo across re-render'); check('Conversation switch isolates drafts and undo history'); // Session gate: the private partner leaves; the surface is not editable and controls are disabled. await page.evaluate(async () => { const { S } = await import('./js/state.js'); (await import('./js/chat.js')).openPrivate(S.connections.get('c1'), 2); }); assert.equal((await state()).value, 'private draft'); await send(snapshot([SELF])); await page.waitForFunction(() => document.querySelector('#chat-input').contentEditable === 'false'); now = await state(); assert.deepEqual({ disabled: now.disabled, editable: now.editable, aria: now.ariaDisabled }, { disabled: true, editable: 'false', aria: 'true' }); await page.keyboard.type('ignored'); assert.equal((await state()).value, 'private draft'); assert.equal(await page.evaluate(() => [...document.querySelectorAll('#chat-format-bar button, #chat-emoji, #chat-send')].every((b) => b.disabled)), true); assert.equal(await page.locator('#chat-editor .cm-placeholder').count(), 0, 'the draft, not a placeholder, remains visible'); check('Disabled session gate on the real editable surface'); await page.evaluate(async () => (await import('./js/chat.js')).showOwnChannel()); await page.waitForFunction(() => document.querySelector('#chat-input').contentEditable === 'true'); // Toolbar collapse still measures the real buttons at both widths. for (const [width, height] of [[1280, 800], [880, 560]]) { await resize(width, height); await page.waitForTimeout(150); const bar = await page.evaluate(() => { const node = document.querySelector('#chat-format-bar'); const tools = [...node.querySelectorAll('button[data-format], button[data-format-group]')]; return { overflow: node.scrollWidth > node.clientWidth, hidden: tools.filter((n) => n.hidden).length, more: !document.querySelector('#chat-format-more').hidden }; }); assert.equal(bar.overflow, false); assert.equal(bar.more, bar.hidden > 0); check(`Toolbar collapse at ${width}px`, bar); } await resize(1280, 800); // Hostile Markdown typed into the hybrid editor renders inertly: no script, remote fetch, live link or handler. await clear(); await page.evaluate(() => { globalThis.CHAT_XSS = null; }); for (const source of maliciousMessages) { await page.keyboard.insertText(source); await page.keyboard.press('Shift+Enter'); } await page.keyboard.insertText('tail'); await page.waitForTimeout(300); const hostile = await page.evaluate(() => { const host = document.querySelector('#chat-editor'); return { blocks: host.querySelectorAll('.tp-chat-editor-block').length, // KaTeX draws some glyphs as local inline ; any other svg, or svg content that can act, is a failure. active: host.querySelectorAll('script,iframe,object,embed,foreignObject,frame,link,meta,style,svg:not(.katex svg),svg script,svg use,svg image,svg a').length, remoteImages: [...host.querySelectorAll('img')].filter((n) => !/^(data|blob):/.test(n.getAttribute('src') ?? 'data:')).length, hrefs: host.querySelectorAll('[href], [src^="javascript:"], [action], [formaction]').length, handlers: [...host.querySelectorAll('*')].flatMap((n) => [...n.attributes]).filter((a) => /^on/i.test(a.name)).length, styles: host.querySelectorAll('.cm-content [style*="url("]').length, xss: globalThis.CHAT_XSS }; }); now = await state(); assert.ok(hostile.blocks > 0, 'inactive hostile lines were rendered, not skipped'); assert.deepEqual({ ...hostile, blocks: 0 }, { blocks: 0, active: 0, remoteImages: 0, hrefs: 0, handlers: 0, styles: 0, xss: null }); assert.equal(now.value, `${maliciousMessages.join('\n')}\ntail`, 'source text is preserved exactly'); await page.click('#chat-editor .tp-chat-editor-block'); assert.equal(await page.evaluate(() => globalThis.CHAT_XSS ?? null), null); check('Hostile Markdown in hybrid preview stays inert and exact', hostile); await shot('04-hostile-hybrid-dark'); // IME composition commits through CodeMirror's input path. await clear(); const cdp = await page.context().newCDPSession(page); await cdp.send('Input.imeSetComposition', { text: 'にほん', selectionStart: 3, selectionEnd: 3 }); await cdp.send('Input.insertText', { text: '日本' }); await cdp.detach(); await page.waitForTimeout(100); assert.equal((await state()).value, '日本'); assert.deepEqual((await sent()).length, 1, 'composition never sends'); check('IME composition commit'); for (const [shortcut, expected] of [ ['ControlOrMeta+b', '**word**'], ['ControlOrMeta+i', '*word*'], ['ControlOrMeta+k', '[word](https://)'], ['ControlOrMeta+Backquote', '`word`'], ['ControlOrMeta+Alt+c', '```\nword\n```'], ]) { await clear(); await page.keyboard.type('word'); await select(0, 4); await page.keyboard.press(shortcut); assert.equal((await state()).value, expected, shortcut); } assert.equal((await sent()).length, 1, 'formatting shortcuts never send'); check('Original bold, italic, link, inline-code and code-block keyboard bindings'); await clear(); await page.keyboard.type('- first'); await page.keyboard.press('Shift+Enter'); assert.equal((await state()).value, '- first\n- '); await page.keyboard.type('second'); await page.keyboard.press('Tab'); assert.equal((await state()).value, '- first\n - second'); await page.keyboard.press('Shift+Tab'); assert.equal((await state()).value, '- first\n- second'); await page.keyboard.press('Shift+Enter'); await page.keyboard.press('Shift+Enter'); assert.equal((await state()).value, '- first\n- second\n'); await page.keyboard.type('plain'); await page.keyboard.press('Tab'); assert.equal((await state()).focused, false, 'ordinary Tab leaves non-list text'); await clear(); await page.keyboard.type('> ```'); await page.keyboard.press('Shift+Enter'); await page.keyboard.type('- literal'); await page.keyboard.press('Shift+Enter'); assert.equal((await state()).value, '> ```\n> - literal\n> ', 'quoted code retains quotes, not a list marker'); await clear(); await page.keyboard.type('- leave editor'); await page.keyboard.press('Escape'); await page.keyboard.press('Tab'); assert.equal((await state()).focused, false, 'Escape then Tab escapes list indentation'); assert.equal((await sent()).length, 1, 'list controls never send'); check('List continuation, indent/outdent, empty-item exit and accessible Tab escape'); assert.deepEqual(result.network, []); assert.deepEqual(result.errors, []); const safety = await app.evaluate(({ BrowserWindow }) => { const win = BrowserWindow.getAllWindows()[0]; return { visible: win.isVisible(), focused: win.isFocused(), focusable: win.isFocusable(), offscreen: win.webContents.isOffscreen(), muted: win.webContents.isAudioMuted() }; }); assert.deepEqual(safety, { visible: false, focused: false, focusable: false, offscreen: true, muted: true }); result.commands = (await app.evaluate(() => globalThis.__editorCommands)).map((c) => c.cmd); assert.equal(result.commands.includes('connect'), false); check('Offscreen safety and command log', { safety }); result.ok = true; } catch (error) { result.ok = false; result.errors.push(error.stack || String(error)); if (page) await page.screenshot({ path: path.join(out, 'failure.png') }).catch(() => {}); process.exitCode = 1; } finally { if (app) await app.close().catch(() => {}); rmSync(profile, { recursive: true, force: true }); writeFileSync(path.join(out, 'result.json'), JSON.stringify(result, null, 2)); } console.log(JSON.stringify({ ok: result.ok, out, checks: result.checks.length, errors: result.errors }, null, 2));