Files
client/test/admin-renderer.test.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

207 lines
15 KiB
JavaScript

// Deterministic DOM/bridge contract tests. No Electron, server, device or native dialogs.
import { test, beforeEach } from 'node:test';
import assert from 'node:assert/strict';
import { env } from './fixtures/renderer-env.mjs';
// Extend this suite's disposable renderer environment, not the shared fixture used by audio tests.
class Element extends globalThis.Node {
constructor(tag = 'div') {
super(); this.tagName = tag.toUpperCase(); this.parentNode = null; this.listeners = new Map();
this.attributes = new Map(); this.disabled = false; this.checked = false; this.required = false;
this.id = ''; this.type = ''; this._value = ''; this._text = ''; this.open = false;
this.style = { setProperty() {}, removeProperty() {} };
}
get textContent() { return this._text + this.children.map((c) => c.textContent).join(''); }
set textContent(value) { this._text = String(value ?? ''); this.children = []; }
get value() { return this.tagName === 'SELECT' && !this._value ? this.options[0]?.value ?? '' : this._value; }
set value(value) { this._value = String(value); }
get options() { return this.children.filter((c) => c.tagName === 'OPTION'); }
get selectedOptions() { return this.options.filter((c) => c.value === this.value); }
get isConnected() { return this === document.body || Boolean(this.parentNode?.isConnected); }
appendChild(child) { child.parentNode = this; this.children.push(child); return child; }
append(...children) { for (const child of children.flat()) this.appendChild(child); }
replaceChildren(...children) { for (const child of this.children) child.parentNode = null; this.children = []; this._text = ''; this.append(...children); }
remove() { if (this.parentNode) this.parentNode.children = this.parentNode.children.filter((c) => c !== this); this.parentNode = null; }
setAttribute(key, value) { this.attributes.set(key, String(value)); if (['id', 'type', 'value'].includes(key)) this[key] = String(value); }
getAttribute(key) { return this.attributes.get(key) ?? null; }
removeAttribute(key) { this.attributes.delete(key); }
addEventListener(type, fn) { if (!this.listeners.has(type)) this.listeners.set(type, new Set()); this.listeners.get(type).add(fn); }
removeEventListener(type, fn) { this.listeners.get(type)?.delete(fn); }
dispatch(type) { const event = { type, target: this, currentTarget: this, preventDefault() {}, stopPropagation() {} }; for (const fn of this.listeners.get(type) ?? []) fn(event); }
click() { if (!this.disabled) this.dispatch('click'); }
focus() { document.activeElement = this; }
showModal() { this.open = true; }
close() { this.open = false; }
matches(selector) {
if (selector.includes(',')) return selector.split(',').some((s) => this.matches(s));
const attribute = selector.match(/\[([^=\]]+)(?:="([^"]*)")?\]/);
const bare = selector.replace(/\[.*\]/, '');
const match = !bare || (bare.startsWith('.') ? this.className.split(' ').includes(bare.slice(1)) : bare.startsWith('#') ? this.id === bare.slice(1) : this.tagName === bare.toUpperCase());
return match && (!attribute || (attribute[2] == null ? this.getAttribute(attribute[1]) != null : String(this[attribute[1]] ?? this.getAttribute(attribute[1])) === attribute[2]));
}
querySelectorAll(selector) { return this.children.flatMap((c) => [...(c.matches(selector) ? [c] : []), ...c.querySelectorAll(selector)]); }
querySelector(selector) { return this.querySelectorAll(selector)[0] ?? null; }
reportValidity() {
return this.querySelectorAll('input,textarea,select').every((c) => c.disabled || (!c.required || (c.type === 'checkbox' ? c.checked : c.value !== '')));
}
}
const body = new Element('body');
const events = new Element();
Object.assign(globalThis.document, {
body, activeElement: null, createElement: (tag) => new Element(tag), createElementNS: (_, tag) => new Element(tag),
createTextNode: (text) => { const node = new Element('#text'); node.textContent = text; return node; },
querySelector: (selector) => body.querySelector(selector), querySelectorAll: (selector) => body.querySelectorAll(selector),
getElementById: (id) => body.querySelector(`#${id}`),
addEventListener: (...args) => events.addEventListener(...args), removeEventListener: (...args) => events.removeEventListener(...args),
});
globalThis.removeEventListener = () => {};
const { S, newConnection, emit, on } = await import('../app/renderer/js/state.js');
const { t } = await import('../app/renderer/js/i18n.js');
const { initAdmin, openAdminAction, renderChannelInfo } = await import('../app/renderer/js/admin.js');
initAdmin();
const tick = async () => { for (let i = 0; i < 12; i++) await Promise.resolve(); };
const context = { generation: 17, server_uid: 'server-fixture=', own_client_id: 1, permissions: {} };
const ok = (result = {}) => ({ ok: true, result });
let conn;
function button(key) { const node = body.querySelectorAll('button').find((b) => b.textContent === t(key)); assert.ok(node, `button ${key}`); return node; }
function field(key) { const label = body.querySelectorAll('label').find((l) => l.children[0]?.textContent === t(key)); assert.ok(label, `field ${key}`); return label.children[1]; }
function input(key, value) { const el = field(`admin.${key}`); if (el.type === 'checkbox') el.checked = value; else el.value = value; el.dispatch('input'); el.dispatch('change'); return el; }
// Popup forms are <dialog>s appended after the detail pane; the pane hosts info/settings/list views.
async function submit() { const form = (body.querySelector('dialog') ?? body).querySelector('form'); assert.ok(form); form.dispatch('submit'); await tick(); }
const views = [];
on('admin-view', (view) => views.push(view));
const last = (cmd) => env.requests.filter((r) => r.cmd === cmd).at(-1);
beforeEach(() => {
S.connections.clear(); emit('view'); body.replaceChildren(); env.requests.length = 0; views.length = 0;
const host = new Element('section'); host.id = 'channel-info-view'; body.append(host);
conn = newConnection('original'); conn.conn = { state: 'connected', address: 'fixture.invalid' };
conn.snap = { server: { name: 'Fixture' }, own_client_id: 1, own_channel_id: 1,
channels: [{ id: 1, parent_id: 0, order: 0, name: 'Lobby', channel_type: 'permanent', codec: 'opus_voice', codec_quality: 5 }, { id: 2, parent_id: 0, order: 1, name: 'Other', channel_type: 'temporary', codec: 'opus_voice' }],
clients: [{ id: 1, uid: 'self=', nickname: 'Self', channel_id: 1 }, { id: 9, uid: 'alice=', nickname: 'Alice', channel_id: 1, talk_request: { time_unix: 5, message: 'Please' } }],
server_groups: [{ id: 8, name: 'Member', type: 'normal' }], channel_groups: [{ id: 5, name: 'Guest', type: 'normal' }] };
S.connections.set(conn.id, conn); S.viewId = conn.id;
env.respond = async (cmd) => cmd === 'admin_context' ? ok(structuredClone(context)) : cmd === 'channel_description' ? ok({ description: 'Description' }) : cmd.endsWith('_list') || cmd.endsWith('_info') ? ok({ rows: [] }) : ok();
});
test('channel create and changed-only edit carry captured connection and native generation', async () => {
await openAdminAction('channel.create'); input('name', 'New Channel'); await submit();
assert.equal(last('channel_create').connectionId, 'original');
assert.equal(last('channel_create').args.generation, 17);
assert.equal(last('channel_create').args.properties.channel_name, 'New Channel');
assert.equal(last('channel_create').args.parent_id, 0);
await openAdminAction('channel.edit', { channelId: 1 }); input('topic', 'New topic'); await submit();
assert.deepEqual(last('channel_edit').args, { generation: 17, channel_id: 1, properties: { channel_topic: 'New topic' } });
});
test('channel move and deletion use real target and explicit destructive confirmation', async () => {
await openAdminAction('channel.move', { channelId: 2 }); input('parent', '1'); await submit();
assert.deepEqual(last('channel_move').args, { generation: 17, channel_id: 2, parent_id: 1, order: 0 });
await openAdminAction('channel.delete', { channelId: 2 }); await submit(); assert.equal(last('channel_delete'), undefined);
input('confirm', true); await submit();
assert.deepEqual(last('channel_delete').args, { generation: 17, channel_id: 2, force: false, confirm: 'Other' });
});
test('failed ack preserves input; successful ack alone replaces form', async () => {
let fail = true;
env.respond = async (cmd) => cmd === 'admin_context' ? ok(context) : fail ? { ok: false, error: { code: 'permission_denied', message: 'No permission' } } : ok();
await openAdminAction('channel.create'); input('name', 'Keep me'); await submit();
assert.equal(field('admin.name').value, 'Keep me'); assert.ok(body.textContent.includes('No permission'));
fail = false; await submit(); assert.equal(body.querySelector('form'), null); assert.ok(body.textContent.includes(t('admin.success')));
});
test('away and talk request/withdraw send bounded message and target-bound grant', async () => {
await openAdminAction('away'); input('away', true); input('awayMessage', 'Lunch'); await submit();
assert.deepEqual(last('set_away').args, { away: true, message: 'Lunch' });
await openAdminAction('talk.request'); input('message', 'Please'); await submit();
assert.deepEqual(last('talk_request').args, { request: true, message: 'Please' });
await openAdminAction('talk.queue'); button('admin.talk.withdraw').click(); await submit();
assert.deepEqual(last('talk_request').args, { request: false });
await openAdminAction('talk.queue'); button('admin.talk.grant').click(); await tick();
assert.deepEqual(last('talk_power').args, { generation: 17, client_id: 9, uid: 'alice=', grant: true });
});
test('closing or switching server before context resolves cannot produce a mutation', async () => {
let resolve;
env.respond = () => new Promise((r) => { resolve = r; });
const pending = openAdminAction('channel.create');
S.viewId = 'different'; emit('view'); resolve(ok(context)); await pending;
assert.equal(body.querySelector('dialog'), null); assert.equal(body.querySelector('form'), null);
assert.ok(body.textContent.includes(t('admin.changed')));
assert.deepEqual(env.requests.map((r) => r.cmd), ['admin_context']);
});
test('reconnect during request discards old success and never routes to the new session', async () => {
await openAdminAction('channel.create'); input('name', 'Old session');
let resolve; env.respond = () => new Promise((r) => { resolve = r; });
body.querySelector('form').dispatch('submit');
conn.session++; emit('connection', {}, conn); resolve(ok({ channel_id: 3 })); await tick();
assert.equal(body.querySelector('dialog'), null); assert.equal(last('channel_create').connectionId, 'original');
});
test('client database pagination and exact deletion confirmation use server rows', async () => {
env.respond = async (cmd) => cmd === 'admin_context' ? ok(context) : cmd === 'client_database_list' ? ok({ rows: Array.from({ length: 100 }, (_, i) => ({ cldbid: String(i + 1), client_nickname: `Client ${i + 1}` })) }) : ok();
await openAdminAction('clients'); await tick();
assert.deepEqual(last('client_database_list').args, { start: 0, duration: 25 });
button('admin.next').click(); await tick(); assert.equal(last('client_database_list').args.start, 25);
button('admin.delete').click(); await submit(); assert.equal(last('client_database_delete'), undefined);
input('confirm', true); await submit(); assert.deepEqual(last('client_database_delete').args, { generation: 17, client_database_id: 1, confirm: '1' });
});
test('privilege server-group key omits channel_id and shows acknowledged token', async () => {
env.respond = async (cmd) => cmd === 'admin_context' ? ok(context) : ok({ token: 'created-token' });
await openAdminAction('keys'); await tick(); button('admin.create').click(); await submit();
assert.equal(last('privilege_key_add').args.kind, 'server_group');
assert.equal(Object.hasOwn(last('privilege_key_add').args, 'channel_id'), false);
assert.equal(field('admin.token').value, 'created-token');
});
test('inline channel info discards delayed old-connection rows', async () => {
const host = body.querySelector('#channel-info-view');
let resolve; env.respond = () => new Promise((r) => { resolve = r; });
const pending = renderChannelInfo({ channelId: 1 });
conn.session++; emit('connection', {}, conn); resolve(ok({ rows: [{ secret_old_value: 'old result' }] })); await pending;
assert.ok(!host.textContent.includes('old result')); assert.ok(host.textContent.includes(t('admin.changed')));
assert.equal(views.at(-1).kind, null);
});
test('subscriptions use the chosen channel without mutation generation', async () => {
await openAdminAction('channel.subscribe', { channelId: 2 });
assert.deepEqual(last('channel_subscribe').args, { channel_id: 2, subscribe: true });
await openAdminAction('channel.unsubscribe', { channelId: 2 });
assert.deepEqual(last('channel_subscribe').args, { channel_id: 2, subscribe: false });
});
test('server settings send changed properties only after explicit server confirmation', async () => {
env.respond = async (cmd) => cmd === 'admin_context' ? ok(context) : cmd === 'server_info' ? ok({ rows: [{ virtualserver_name: 'Fixture' }] }) : ok();
await openAdminAction('server.edit'); await tick();
input('serverField.name', 'Renamed'); await submit(); assert.equal(last('server_edit'), undefined);
input('confirm', true); await submit();
assert.deepEqual(last('server_edit').args, { generation: 17, confirm: 'server-fixture=', properties: { virtualserver_name: 'Renamed' } });
});
test('temporary password and ban management dispatch real typed commands', async () => {
await openAdminAction('passwords'); await tick();
assert.ok(last('temp_password_list'));
button('admin.create').click(); input('password', 'GuestPass'); input('description', 'Guest'); await submit();
assert.deepEqual(last('temp_password_add').args, { generation: 17, password: 'GuestPass', description: 'Guest', duration_s: 3600, channel_id: 0, channel_password: '' });
await openAdminAction('bans'); await tick(); assert.ok(last('ban_list'));
button('admin.create').click(); input('uid', 'blocked='); await submit();
assert.equal(last('ban_add').args.uid, 'blocked='); assert.equal(last('ban_add').args.generation, 17);
});
test('server log keeps explicit position and limits instead of claiming complete history', async () => {
env.respond = async (cmd) => cmd === 'admin_context' ? ok(context) : ok({ rows: [{ last_pos: '200', l: 'log line' }] });
await openAdminAction('log'); input('logPosition', '100'); await submit();
assert.deepEqual(last('server_log').args, { lines: 100, begin_pos: 100, reverse: true, instance: false });
assert.ok(body.textContent.includes('log line'));
});
test('channel settings quality slider uses the official steps and bandwidth estimate', async () => {
await openAdminAction('channel.edit', { channelId: 1 });
const slider = body.querySelectorAll('input').find((el) => el.type === 'range');
slider.value = '3'; slider.dispatch('input');
await submit();
assert.deepEqual(last('channel_edit').args, { generation: 17, channel_id: 1, properties: { channel_codec_quality: 6 } });
});