Files
iishko-public/tests/test_model_moderation_frontend.mjs
reformandClaude Opus 5.5 0ee6fb843b
checks / pytest (push) Has been cancelled
checks / moderation (push) Has been cancelled
checks / node (push) Has been cancelled
IISHKO: Telegram bot, Mini App and gateway
Initial public release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 21:51:30 +03:00

147 lines
7.9 KiB
JavaScript
Raw Permalink 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.
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import vm from 'node:vm';
const html = readFileSync(process.env.IISHKO_UI_HTML || new URL('../bot/webapp/static/index.html', import.meta.url), 'utf8');
const lines = html.split(/\r?\n/);
function declaration(prefix) {
const line = lines.find(value => value.startsWith(prefix));
assert.ok(line, `Missing application declaration: ${prefix}`);
return line;
}
function between(start, end) {
const first = html.indexOf(start);
const last = html.indexOf(end, first + start.length);
assert.ok(first >= 0 && last > first, `Missing source block: ${start}`);
return html.slice(first, last);
}
const source = [
...['const esc=', 'const num=', 'const fmt=', 'const STATUS_UI='].map(declaration),
between('function publicConnectionField(', 'function connectionHelpHtml('),
between('function modelStatus(', 'const STATUS_UI='),
between('function modelAgentEligible(', 'function modelsEmptyHtml('),
between('function uptimeHtml(', 'function modelsFiltered('),
].join('\n');
const advisory = {
label: 'Строгая модерация провайдера',
notice: 'На части маршрутов действует контент-фильтр провайдера. Отказ не означает недоступность модели; повтор того же текста может не помочь.',
};
const badgePattern = /<span class="tag moderation-advisory" role="note" title="[^"]*" aria-label="[^"]*">[^<]*<\/span>/g;
const badgeAbsent = /<span class="tag moderation-advisory"/;
const model = overrides => ({
name: 'vendor/exact-model:v1', display_name: 'Название модели', available: true,
min_rank: 2, rank_name: 'Участник', status: 'up', checked_at: Date.now() / 1000,
ms: 42, p_in: 0.1, p_out: 0.2, desc: 'Описание модели', ...overrides,
});
function harness(row) {
const selected = [], routes = [];
const context = vm.createContext({
row, mList: [row], mMeta: {status_ts: 0, status_stale_after: 120}, AG_LABEL: {},
agentModelsLoaded: true, agentModels: [row.name], agentBusy: false,
agentOperations: {current: () => null}, resolvedUid: '123', current: 'models',
ago: () => 'только что', $: () => null,
selectAgentModel: id => { selected.push(id); return true; },
goRoute: route => routes.push(route),
loadAgentModels: async () => { throw new Error('Loaded model selection must not reload'); },
button: {disabled: false, isConnected: true},
});
vm.runInContext(source, context);
return {
context, selected, routes,
run: expression => vm.runInContext(expression, context),
render: (chatModel = '') => { context.chatModel = chatModel; return vm.runInContext('modelCard(row, chatModel)', context); },
};
}
test('actual modelCard renders advisory as visible tag text with the notice in title', () => {
const row = model({provider_moderation: advisory});
const before = JSON.stringify(row);
const view = harness(row).render();
assert.ok(view.includes(`<span class="tag moderation-advisory" role="note" title="${advisory.notice}" aria-label="${advisory.label}. ${advisory.notice}">${advisory.label}</span>`));
assert.equal(view.match(badgePattern)?.length, 1);
assert.equal(JSON.stringify(row), before, 'rendering must not mutate model metadata');
assert.ok(view.indexOf('model-name') < view.indexOf('moderation-advisory'));
assert.ok(view.indexOf('moderation-advisory') < view.indexOf('ID модели'));
});
test('missing, null, non-object and incomplete advisory values produce no badge', () => {
assert.doesNotMatch(harness(model()).render(), badgeAbsent);
const invalid = [
undefined, null, false, 1, 'strict', [], {},
{label: advisory.label}, {notice: advisory.notice},
{label: '', notice: advisory.notice}, {label: ' \n\t', notice: advisory.notice},
{label: advisory.label, notice: ''}, {label: advisory.label, notice: ' \n\t'},
{label: 42, notice: advisory.notice}, {label: advisory.label, notice: 42},
{label: {}, notice: advisory.notice}, {label: advisory.label, notice: {}},
Object.assign([], advisory),
];
for (const value of invalid) {
assert.doesNotMatch(harness(model({provider_moderation: value})).render(), badgeAbsent, JSON.stringify(value));
}
});
test('actual existing esc utility escapes malicious label text and title attribute independently', () => {
const label = '<img src=x onerror="alert(1)"> & \'label\'';
const notice = '"><svg onload=\'alert(2)\'> & "notice"';
const view = harness(model({provider_moderation: {label, notice}})).render();
const escapedLabel = '&lt;img src=x onerror=&quot;alert(1)&quot;&gt; &amp; &#39;label&#39;';
const escapedNotice = '&quot;&gt;&lt;svg onload=&#39;alert(2)&#39;&gt; &amp; &quot;notice&quot;';
assert.ok(view.includes(`<span class="tag moderation-advisory" role="note" title="${escapedNotice}" aria-label="${escapedLabel}. ${escapedNotice}">${escapedLabel}</span>`));
assert.equal(view.match(badgePattern)?.length, 1);
assert.doesNotMatch(view, /<img\b|<svg\b|"\s+onload=|"\s+onerror=/);
assert.ok(!view.includes(label));
assert.ok(!view.includes(notice));
});
test('advisory is additive only: display, identity, ACL, rank, health and actions stay identical', () => {
for (const status of ['up', 'busy', 'down', 'stale']) {
for (const available of [true, false]) {
for (const selected of [true, false]) {
const row = model({status, available, name: 'vendor/exact<id>&"\':v1'});
const chatModel = selected ? row.name : 'another-model';
const baseline = harness(row).render(chatModel);
const marked = harness({...row, provider_moderation: advisory}).render(chatModel);
assert.equal(marked.replace(badgePattern, ''), baseline);
assert.match(marked, /value="vendor\/exact&lt;id&gt;&amp;&quot;&#39;:v1"/);
// Canonical UI has the provider action; the production fork may not.
// Never add an unrelated action during an advisory-only production rebase.
if (!process.env.IISHKO_UI_HTML || baseline.includes('data-provider-model=')) {
assert.match(marked, /data-provider-model="vendor\/exact&lt;id&gt;&amp;&quot;&#39;:v1"/);
}
assert.equal(marked.includes('В чате бота'), selected);
assert.equal(marked.includes('data-open-agent='), available);
}
}
}
});
test('actual selection handler preserves the exact model ID and route with or without advisory', async () => {
for (const provider_moderation of [undefined, advisory]) {
const row = model({provider_moderation});
const h = harness(row);
assert.ok(h.render().includes(`data-open-agent="${row.name}"`));
assert.equal(await h.run('openModelInAgent(row.name, button)'), true);
assert.deepEqual(h.selected, [row.name]);
assert.deepEqual(h.routes, ['agent']);
assert.equal(h.context.button.disabled, false);
}
assert.ok(html.includes("const agentOpen=event.target.closest('[data-open-agent]');"));
assert.ok(html.includes('openModelInAgent(agentOpen.dataset.openAgent,agentOpen)'));
});
test('advisory never enables an unavailable model or bypasses an active agent operation', async () => {
for (const provider_moderation of [undefined, advisory]) {
const locked = harness(model({available: false, provider_moderation}));
assert.doesNotMatch(locked.render(), /data-open-agent=/);
assert.equal(await locked.run('openModelInAgent(row.name, button)'), false);
assert.deepEqual(locked.selected, []);
assert.deepEqual(locked.routes, []);
const busy = harness(model({provider_moderation}));
busy.context.agentBusy = true;
assert.equal(await busy.run('openModelInAgent(row.name, button)'), false);
assert.deepEqual(busy.selected, []);
assert.deepEqual(busy.routes, []);
}
});