import test from 'node:test';
import assert from 'node:assert/strict';
import vm from 'node:vm';
import {readFileSync} from 'node:fs';
// Parent may target the assembled bot/webapp/static/index.html without copying fixtures.
const html=readFileSync(process.env.IISHKO_UI_HTML||new URL('../bot/webapp/static/index.html',import.meta.url),'utf8');
const scripts=[...html.matchAll(/',checked_at:null}}]};
const view=h.run('providersHtml(data)');
assert.match(view,/Доступность неизвестна/);assert.match(view,/Происхождение не подтверждено/);assert.match(view,/Поддержка effort неизвестна/);
assert.match(view,/<img/);assert.match(view,/<script>/);assert.doesNotMatch(view,/ {
const h=harness();h.c.apiResponse={model:'vendor/sample-model',providers:[]};
assert.equal(await h.run('providerOpen("vendor/sample-model")'),true);
assert.equal(h.gets[0],'providers?model=vendor%2Fsample-model');assert.equal(h.get('#providerdlg').open,true);
assert.equal(h.get('#provider-content').attributes['aria-busy'],'false');assert.match(h.get('#provider-content').innerHTML,/нет опубликованных/);
assert.equal(h.focus.at(-1),'#provider-close');
h.get('#providerdlg').close();assert.equal(h.focus.at(-1),'#trigger');
});
test('provider mismatch and transport failure never create a positive verified state',async()=>{
const h=harness();h.c.apiResponse={model:'different-model',providers:[]};
assert.equal(await h.run('providerOpen("sample-model")'),false);assert.match(h.get('#provider-content').innerHTML,/Метаданные провайдеров не подтверждены/);
h.c.apiFresh=async()=>{throw new Error('');};
assert.equal(await h.run('providerOpen("sample-model")'),false);assert.match(h.get('#provider-content').innerHTML,/<svg/);assert.doesNotMatch(h.get('#provider-content').innerHTML,/{
const h=harness();h.c.apiResponse={model:'sample-model',providers:[{id:'route-one',name:'Route',available:true,effort:true,effort_levels:['low','high'],verification:{status:'verified',method:'operator_probe',checked_at:1790000000}}]};
await h.run('providerOpen("sample-model")');
// Contract is read from the real gateway sources, not from a string oracle:
// relay rejects an effort header the body does not carry, registry reads effort from body fields.
const relay=readFileSync(new URL('../gateway/gateway_provider_relay.py',import.meta.url),'utf8');
const registry=readFileSync(new URL('../gateway/gateway_providers.py',import.meta.url),'utf8');
const parser=readFileSync(new URL('../gateway/request_effort.py',import.meta.url),'utf8');
const effortFn=registry.slice(registry.indexOf('def response_effort'),registry.indexOf('def safe_to_retry'));
assert.match(relay,/headers do not rewrite generation parameters/);
assert.match(relay,/X-Iishko-Effort[\s\S]*effort_requires_request_field/);
assert.match(registry,/from request_effort import InvalidEffort, read_effort/);
assert.match(effortFn,/return read_effort\(payload\)/);
assert.match(parser,/"reasoning_effort"/);
const view=h.get('#provider-content').innerHTML;
assert.doesNotMatch(view,/X-Iishko-Effort/,'the copied example must never suggest an effort header');
assert.match(view,/data-provider-copy-body="0"/);assert.match(view,/Фрагмент тела запроса/);
assert.equal(h.run('providerSelectEffort(0,"high")'),true);
assert.equal(h.get('#provider-example-0').value,'X-Iishko-Provider: route-one','selecting effort must not add a header');
const fragment=JSON.parse(h.get('#provider-body-0').value);
assert.deepEqual(Object.keys(fragment),['reasoning_effort']);assert.equal(fragment.reasoning_effort,'high');
assert.ok(Object.keys(fragment).every(key=>parser.includes('"'+key+'"')),'fragment key must be one the shared gateway parser reads from the request body');
assert.equal(h.run('providerSelectEffort(0,"high\\r\\nInjected: value")'),false);
assert.equal(h.get('#provider-body-0').value,'{"reasoning_effort": "high"}','rejected value must not reach the fragment');
assert.equal(h.run('providerSelectEffort(0,"medium")'),false,'unconfigured level is not selectable');
let copyButton=h.c.copyButton=h.button({providerCopy:'0'});await h.emit('click',copyButton);
assert.deepEqual(h.copies,['X-Iishko-Provider: route-one']);
copyButton=h.c.copyButton=h.button({providerCopyBody:'0'});await h.emit('click',copyButton);
assert.deepEqual(h.copies,['X-Iishko-Provider: route-one','{"reasoning_effort": "high"}']);
assert.equal(await h.run('providerSelectEffort(0,"")'),true);
assert.equal(h.get('#provider-body-0').value,'');
assert.equal(await h.run('providerCopy(0,copyButton,"body")'),false,'an empty fragment is not copyable');
assert.deepEqual(h.copies,['X-Iishko-Provider: route-one','{"reasoning_effort": "high"}']);
assert.match(h.run('providersHtml(apiResponse)'),/operator_probe/);
});
test('real model card exposes provider action rather than an API-only feature',()=>{
const h=harness();h.c.model={name:'sample-model',available:true,checked_at:0,rank_name:'Участник'};
const view=h.run('modelCard(model)');assert.match(view,/data-provider-model="sample-model"/);assert.match(view,/aria-haspopup="dialog"/);assert.match(view,/Провайдеры · effort · проверка/);
});
test('payment disabled keeps topup visible but inert and never invents offers/prices',async()=>{
const h=harness();const view=h.state('commerce',commerce({payment_enabled:false,wallet_cents:0}));
assert.match(view,/оплата отключена или ещё не настроена/);
assert.match(view,/data-commerce="create_invoice"[^>]*disabled/);assert.equal(h.run('commerceOpen("create_invoice","topup")'),false);
await h.emit('click',h.button({commerce:'create_invoice',offerId:'topup'}));assert.equal(h.posts.length,0);assert.equal(h.get('#contestdlg').open,false);
const empty=h.state('commerce',commerce({payment_enabled:false,offers:[]}));assert.match(empty,/Предложения пока не настроены/);assert.doesNotMatch(empty,/data-commerce=/);
});
test('configured limit/model passes are purchasable from a separate USD-cent wallet',async()=>{
const h=harness(),view=h.state('commerce',commerce());h.c.current='econ';
assert.match(view,/50 дополнительных запросов/);assert.match(view,/Пропуск на 24 часа: sample-model/);assert.match(view,/\$2\.50 USD/);
assert.match(view,/Эти балансы не складываются/);await h.emit('click',h.button({commerce:'purchase',offerId:'requests'}));
assert.equal(h.get('#contestdlg').open,true);assert.match(h.get('#contest-desc').textContent,/денежного кошелька/);
await h.run('contestPerform("commerce",contestFormBody(contestState.operation,{}))');
assert.equal(h.posts[0].path,'commerce/action');assert.equal(h.posts[0].body.offer_id,'requests');assert.match(h.run('contestState.notices.commerce'),/Покупка подтверждена/);
});
test('payment metadata/links are escaped and an unsafe pay URL is never clickable',()=>{
const h=harness(),view=h.state('commerce',commerce({offers:[{id:'safe-id',kind:'model_pass',title:' ',price_cents:250,model:''}],invoices:[{id:'invoice-one',status:'pending',amount_cents:500,pay_url:'javascript:alert(1)'}],history:[{delta_cents:-250,kind:'',offer_id:' ',ts:1790000000}]}));
assert.match(view,/<img/);assert.match(view,/<svg/);assert.match(view,/<script>/);assert.doesNotMatch(view,/ {
const h=harness();h.c.current='econ';h.state('commerce',commerce({invoices:[{id:'invoice-one',status:'pending',amount_cents:500}]}));
assert.equal(h.run('commerceOpen("create_invoice","topup")'),false,'never create duplicate invoice while one is open');
await h.run('contestPerform("commerce",{action:"check_invoice",invoice_id:"invoice-one"})');
assert.match(h.run('contestState.notices.commerce'),/Оплата ещё не подтверждена/);assert.equal(h.store.size,0);
await h.run('contestPerform("commerce",{action:"check_invoice",invoice_id:"invoice-one"})');
assert.notEqual(h.posts[0].body.request_id,h.posts[1].body.request_id);
});
test('lost purchase survives webview reopen and replays same id/body without a second charge',async()=>{
const h=harness(),receipts=new Map();let charges=0;
const backend=async(path,body)=>{const fingerprint=JSON.stringify(body);if(receipts.has(body.request_id)){assert.equal(receipts.get(body.request_id).fingerprint,fingerprint);return {...receipts.get(body.request_id).receipt,replayed:true};}charges++;const receipt={ok:true,action:'purchase',offer_id:body.offer_id,charged_cents:250};receipts.set(body.request_id,{fingerprint,receipt});throw new Error('response lost after charge');};
h.c.post=backend;await assert.rejects(h.run('contestMutation("commerce",{action:"purchase",offer_id:"requests"})'),/response lost/);
const saved=JSON.parse(h.store.get('contest-pending:commerce:123'));
await assert.rejects(h.run('contestMutation("commerce",{action:"purchase",offer_id:"model-day"})'),/Сначала проверь/);
const reopened=harness(h.store);reopened.c.post=backend;reopened.c.current='econ';
await reopened.run('contestPerform("commerce",{},true)');assert.equal(charges,1);assert.equal(reopened.store.size,0);
assert.match(reopened.run('contestState.notices.commerce'),/сохранённая квитанция/);assert.equal(receipts.has(saved.body.request_id),true);
});
test('lost private submission/review retains raw body and cannot silently become a new mutation',async()=>{
for(const action of [{action:'submit',kind:'bug',category:'high',title:'Private report',description:'Detailed safe reproduction of the defect.',proof:'safe-request-id'},{action:'review',id:8,decision:'accepted',reward_rep:5,reason:'Independently reproduced'}]){
const h=harness();h.c.post=async()=>{throw new Error('network uncertainty');};h.c.body=action;
await assert.rejects(h.run('contestMutation("activities",body)'));
const saved=JSON.parse(h.store.get('contest-pending:activities:123'));assert.deepEqual({...saved.body,request_id:undefined},{...action,request_id:undefined});
const reopened=harness(h.store);await reopened.run('contestMutation("activities",{},true)');assert.deepEqual(reopened.posts[0].body,saved.body);assert.equal(reopened.store.size,0);
}
});
test('401, server errors, conflicts and malformed 2xx preserve the uncertain id',async()=>{
for(const failure of [Object.assign(new Error('auth'),{status:401,data:{operation_rejected:true}}),Object.assign(new Error('server'),{status:503}),Object.assign(new Error('conflict'),{status:409,data:{error:'request_conflict',operation_rejected:true}}),null]){
const h=harness();h.c.post=async()=>{if(failure)throw failure;return {ok:true};};
await assert.rejects(h.run('contestMutation("commerce",{action:"purchase",offer_id:"requests"})'));
assert.equal(h.store.size,1);assert.equal(h.run('contestState.busy.size'),0);
}
});
test('definitive rejection permits correction but storage denial blocks sending',async()=>{
const h=harness();h.c.post=async()=>{throw Object.assign(new Error('bad input'),{status:400,data:{operation_rejected:true,error:'invalid_title'}});};
await assert.rejects(h.run('contestMutation("activities",{action:"submit",kind:"bug"})'));assert.equal(h.store.size,0);
const blocked=harness();blocked.c.localStorage.setItem=()=>{throw new Error('denied');};
await assert.rejects(blocked.run('contestMutation("commerce",{action:"purchase",offer_id:"requests"})'),/Хранилище/);assert.equal(blocked.posts.length,0);
});
test('pending state and late results remain scoped to signed identity',async()=>{
const h=harness();h.state('commerce',commerce());h.state('activities',board());
h.c.post=async()=>{h.c.resolvedUid='456';return {ok:true,action:'purchase',offer_id:'requests',charged_cents:250};};
await assert.rejects(h.run('contestMutation("commerce",{action:"purchase",offer_id:"requests"})'),/Аккаунт изменился/);
assert.equal(h.run('contestPending("commerce")'),null);assert.ok(h.store.has('contest-pending:commerce:123'));
assert.equal(h.run('commerceOpen("purchase","requests")'),false);assert.equal(h.run('boardOpen("bug")'),false);
const view=h.state('activities',board());assert.doesNotMatch(view,/data-board-kind=/);
});
test('in-flight guard prevents double clicks and corrupt pending state fails closed',async()=>{
const h=harness();let release;h.c.post=async()=>new Promise(resolve=>{release=resolve;});
const first=h.run('contestMutation("commerce",{action:"purchase",offer_id:"requests"})');
await assert.rejects(h.run('contestMutation("commerce",{action:"purchase",offer_id:"requests"})'),/Дождись/);
release({ok:true,action:'purchase',offer_id:'requests',charged_cents:250});await first;
h.store.set('contest-pending:commerce:123','not-json');assert.match(h.state('commerce',commerce()),/Новые действия заблокированы/);
assert.equal(h.run('commerceOpen("purchase","requests")'),false);
});
test('real bound submit handler validates and sends private reports without a public action',async()=>{
const h=harness();h.state('activities',board());h.run('boardOpen("bug")');
const form=h.get('#contest-form');form.fields=validBug().fields;
await form.listeners.get('submit')[0]({target:form,preventDefault(){}});
assert.equal(h.posts.length,1);assert.equal(h.posts[0].path,'activities/action');assert.equal(h.posts[0].body.kind,'bug');
assert.equal(h.get('#contestdlg').open,false);assert.equal(h.store.size,0);
});
test('real bound invoice confirmation creates a payable invoice, never a wallet credit',async()=>{
const h=harness();h.c.current='econ';h.state('commerce',commerce());
assert.equal(h.run('commerceOpen("create_invoice","topup")'),true);
const form=h.get('#contest-form');
await form.listeners.get('submit')[0]({target:form,preventDefault(){}});
assert.equal(h.posts[0].path,'commerce/action');assert.equal(h.posts[0].body.action,'create_invoice');assert.equal(h.posts[0].body.offer_id,'topup');
assert.match(h.run('contestState.notices.commerce'),/Деньги ещё не зачислены/);assert.equal(h.store.size,0);
});
test('creating/uncertain invoice or inconsistent paid receipt is not a false success',async()=>{
for(const result of [
{ok:true,action:'create_invoice',invoice:{id:'invoice-one',currency:'USD',amount_cents:500,status:'uncertain',pay_url:'https://example.org/pay'}},
{ok:true,action:'check_invoice',paid:true,credited_cents:500,invoice:{id:'invoice-one',currency:'USD',amount_cents:500,status:'pending'}}
]){
const h=harness();h.c.post=async()=>result;h.c.body=result.action==='create_invoice'?{action:result.action,offer_id:'topup'}:{action:result.action,invoice_id:'invoice-one'};
await assert.rejects(h.run('contestMutation("commerce",body)'),/квитанцию/);assert.equal(h.store.size,1);
}
});