// Receipt-driven UX for the coding assistant in the Mini App. // The regression: a provider error arriving with a *terminal* receipt used to be routed // through agentStop(), which posted agent_cancel to a finished operation and rendered // «Операция уже завершилась. Уже выполненные действия не отменяются.» — a false claim about // a request that never ran. The driver now trusts the receipt: failed/cancelled are errors, // and the draft is restored only when uncertain===false && side_effect_started===false. import test from 'node:test'; import assert from 'node:assert/strict'; import {readFileSync} from 'node:fs'; import vm from 'node:vm'; const html = new URL(process.env.IISHKO_UI_HTML || '../bot/webapp/static/index.html', import.meta.url); const source = readFileSync(html, 'utf8'); function scriptBlocks(text) { const blocks = []; const pattern = /]*>([\s\S]*?)<\/script>/g; let match; while ((match = pattern.exec(text))) blocks.push(match[1]); return blocks; } function between(text, start, end) { const from = text.indexOf(start); assert.ok(from >= 0, 'missing anchor: ' + start); const to = text.indexOf(end, from + start.length); assert.ok(to >= 0, 'missing end anchor: ' + end); return text.slice(from, to); } const helpers = scriptBlocks(source).find((block) => block.includes('const MiniAppFlows=')); assert.ok(helpers, 'the MiniAppFlows helper script must exist'); const helperContext = vm.createContext({ window: {}, document: {getElementById: () => null}, crypto: globalThis.crypto, setTimeout, clearTimeout, console, }); vm.runInContext(helpers, helperContext, {filename: 'miniapp-flow-helpers.js'}); const MiniAppFlows = vm.runInContext('MiniAppFlows', helperContext); const region = between(source, 'function agentFailureText(error){', '/* ---------- напоминания'); assert.ok(region.includes('async function agentSend('), 'agentSend must live inside the extracted region'); assert.ok(region.includes('function agentStop('), 'agentStop must live inside the extracted region'); function makeHarness() { const state = { posted: [], texts: [], restores: 0, busy: [], notice: '', released: 0, chatReceipt: () => null, cancelReply: {ok: true, state: 'completed', uncertain: false, side_effect_started: true}, }; const operation = {id: '', stopping: false, cancelPromise: null, epoch: 0, uid: 'u1'}; const capture = (...args) => { state.texts.push(args.map((value) => { if (typeof value === 'string') return value; try { return JSON.stringify(value); } catch { return String(value); } }).join(' | ')); }; const draftSnapshot = {text: 'привет', revision: 0}; const draft = { snapshot: () => draftSnapshot, consume: () => 0, restore: () => { state.restores += 1; return true; }, read: () => 'привет', write() {}, clear() {}, }; const context = [ {role: 'user', content: 'привет'}, ]; context.messages = context; const scope = { MiniAppFlows, document: {getElementById: () => null, addEventListener() {}, createElement: () => ({style: {}})}, $: (selector) => (selector === '#ain' ? {value: 'привет', style: {}, focus() {}, disabled: false, scrollHeight: 0} : null), TIMEOUTS: {agent_chat: 1000}, post: async (action, body) => { state.posted.push({action, body}); if (action === 'agent_chat') { const receipt = state.chatReceipt(body) || null; if (receipt) { const error = new Error(receipt.message || 'request failed'); error.status = receipt.status || 503; error.data = Object.assign({}, receipt, { operation_id: receipt.operation_id === undefined ? body?.operation_id : receipt.operation_id, }); delete error.data.status; throw error; } return {ok: true, operation_id: body?.operation_id}; } // The real endpoint always echoes operation_id; agentStop validates it. if (action === 'agent_cancel') return Object.assign({operation_id: body?.operation_id}, state.cancelReply); return {ok: true}; }, agentOperations: { current: () => (operation.id ? operation : null), begin: (id) => { operation.id = typeof id === 'string' && id ? id : 'op-generated'; operation.stopping = false; operation.cancelError = ''; // Same epoch/uid the real begin() stamps; otherwise every guard drops the receipt. operation.epoch = scope.agentEpoch; operation.uid = scope.resolvedUid; return operation; }, start: (id) => scope.agentOperations.begin(id), new: (id) => scope.agentOperations.begin(id), owns: () => true, release: () => { state.released += 1; }, }, agentDraft: draft, createRamDraft: () => draft, restoreAgentDraft: () => { state.restores += 1; return true; }, rememberAgentDraft: () => {}, agentMsgs: [], agentBubble: capture, logAppend: capture, popup: capture, alert: capture, agentOperationNotice: (text) => { state.notice = String(text ?? ''); capture(text); }, agentTypingStart: () => {}, agentTypingStop: () => {}, agentTypingHtml: () => '', agentScroll: () => {}, haptic: () => {}, agSetBusy: (value) => state.busy.push(value), agSave: () => {}, agContext: () => context, updateAgentFile: () => {}, updateAgentModelControl: () => {}, loadAgentModels: async () => {}, agentFile: null, agentFileEpoch: 0, agentModel: 'test-model', agentModels: ['test-model'], agentBusy: false, agentComposing: false, agentClearPending: false, agentEpoch: 0, agentLastPrompt: '', agentLastActual: '', agentVmSeen: false, agentSandboxOn: true, agentRetry: null, resolvedUid: 'u1', escapeHtml: (value) => String(value ?? ''), esc: (value) => String(value ?? ''), isExactModelId: (id) => typeof id === 'string' && id.length > 0, opaquePattern: /^[A-Za-z0-9_.:-]{4,80}$/, retryAfterText: () => '', fetch: async () => ({ok: false, status: 500, json: async () => ({})}), setTimeout, clearTimeout, requestAnimationFrame: (fn) => setTimeout(fn, 0), }; const proxy = new Proxy(scope, { has: () => true, get: (target, key) => { if (key === Symbol.unscopables) return undefined; if (key in target) return target[key]; if (typeof key === 'string' && key in globalThis) return globalThis[key]; return undefined; }, set: (target, key, value) => { target[key] = value; return true; }, }); const factory = new Function('__scope__', `with(__scope__){\n${region}\nreturn {agentSend:agentSend,agentStop:agentStop};\n}`); return {driver: factory(proxy), state, operation, draft}; } function chatPostCount(state) { return state.posted.filter((entry) => entry.action === 'agent_chat').length; } function cancelPostCount(state) { return state.posted.filter((entry) => entry.action === 'agent_cancel').length; } test('receipt helpers treat a missing side_effect_started flag as unknown, never as "nothing ran"', () => { assert.deepEqual({...MiniAppFlows.agentReceiptView(null)}, {state: '', uncertain: true, side_effect_started: null}); assert.equal(MiniAppFlows.agentReceiptView({state: 'failed', uncertain: false}).side_effect_started, null); assert.equal(MiniAppFlows.agentFailureReceipt({data: {operation_id: 'op-a', state: 'failed'}}, 'op-b'), null); assert.equal(MiniAppFlows.agentFailureReceipt({data: {state: 'failed'}}, 'op-a'), null); assert.equal(MiniAppFlows.agentFailureReceipt({data: {operation_id: 'op-a', state: 'completed'}}, 'op-a'), null); assert.equal(MiniAppFlows.agentFailureReceipt({data: {operation_id: 'op-a', state: 'failed'}}, 'op-a').state, 'failed'); assert.equal(MiniAppFlows.agentSafeToRestore({state: 'failed', uncertain: false}), false); assert.equal(MiniAppFlows.agentSafeToRestore({state: 'failed', uncertain: false, side_effect_started: true}), false); assert.equal(MiniAppFlows.agentSafeToRestore({state: 'failed', uncertain: true, side_effect_started: false}), false); assert.equal(MiniAppFlows.agentSafeToRestore({state: 'completed', uncertain: false, side_effect_started: false}), false); assert.equal(MiniAppFlows.agentSafeToRestore({state: 'failed', uncertain: false, side_effect_started: false}), true); // [CANCEL-COMPAT] failed:true beats the legacy state string. const legacy = MiniAppFlows.agentReceiptView({state: 'completed', failed: true, uncertain: false, side_effect_started: false}); assert.equal(legacy.state, 'failed'); assert.equal(MiniAppFlows.agentSafeToRestore(legacy), true); const refused = MiniAppFlows.agentTerminalNote('failed', {state: 'failed', uncertain: false, side_effect_started: false}); assert.match(refused, /Запрос не выполнен/); assert.match(refused, /Внешние действия не запускались/); const unknown = MiniAppFlows.agentTerminalNote('failed', {state: 'failed', uncertain: true, side_effect_started: true}); assert.match(unknown, /неизвестен/); const completed = MiniAppFlows.agentTerminalNote('completed', {state: 'completed', uncertain: false, side_effect_started: true}); assert.match(completed, /Операция уже завершилась/); assert.match(completed, /уже запускались/); }); test('a terminal failed receipt before any tool restores the draft without posting agent_cancel', async () => { const {driver, state} = makeHarness(); state.chatReceipt = () => ({ status: 403, state: 'failed', uncertain: false, side_effect_started: false, message: 'Сначала создай активный API-ключ во вкладке «Ключи».', }); await driver.agentSend(); assert.equal(chatPostCount(state), 1); assert.equal(cancelPostCount(state), 0, 'a definitive terminal failure must not be replayed as a cancel'); assert.equal(state.restores, 1, 'the draft must be restored exactly once'); const text = state.texts.join('\n'); assert.match(text, /Запрос не выполнен/); assert.match(text, /Внешние действия не запускались/); assert.match(text, /Черновик сохранён/); assert.doesNotMatch(text, /Уже выполненные действия не отменяются/); assert.ok(state.busy.includes(false), 'the send button must be released'); }); test('a failed receipt after side effects keeps the draft and says the outcome is unknown', async () => { const {driver, state} = makeHarness(); state.chatReceipt = () => ({ status: 503, state: 'failed', uncertain: true, side_effect_started: true, message: 'Модель сейчас не ответила.', }); await driver.agentSend(); assert.equal(cancelPostCount(state), 0); assert.equal(state.restores, 0, 'a draft must not be restored when external actions already ran'); const text = state.texts.join('\n'); assert.match(text, /неизвестен/); assert.doesNotMatch(text, /Черновик сохранён/); assert.doesNotMatch(text, /Уже выполненные действия не отменяются/); }); test('an error without a matching receipt stays conservative and asks the server to stop', async () => { const {driver, state} = makeHarness(); state.chatReceipt = () => ({ status: 500, state: 'failed', uncertain: true, side_effect_started: true, operation_id: 'some-other-operation', message: 'Внутренняя ошибка.', }); // [CANCEL-COMPAT] the server answers a failed finished record with state='completed' // plus failed:true; the UI must explain the failure, never imply a clean finish. state.cancelReply = {ok: true, state: 'completed', failed: true, uncertain: true, side_effect_started: true}; await driver.agentSend(); assert.equal(cancelPostCount(state), 1, 'an unverifiable error must still try to stop the operation'); assert.equal(state.restores, 0); const text = state.texts.join('\n'); assert.match(text, /Запрос не выполнен/); assert.match(text, /неизвестен/); assert.doesNotMatch(text, /Операция уже завершилась/); }); test('agentStop reports a failed operation as a failure, not as success', async () => { const {driver, state, operation} = makeHarness(); operation.id = 'op-failed'; state.cancelReply = {ok: true, operation_id: 'op-failed', state: 'completed', failed: true, uncertain: false, side_effect_started: false}; await driver.agentStop(); assert.equal(cancelPostCount(state), 1); const text = state.texts.join('\n'); assert.match(text, /Запрос не выполнен/); assert.match(text, /Внешние действия не запускались/); assert.doesNotMatch(text, /Операция уже завершилась/); // Forward-compatible: a server that can emit state='failed' directly is honoured too. const direct = makeHarness(); direct.operation.id = 'op-failed-direct'; direct.state.cancelReply = {ok: true, operation_id: 'op-failed-direct', state: 'failed', uncertain: false, side_effect_started: false}; await direct.driver.agentStop(); assert.match(direct.state.texts.join('\n'), /Запрос не выполнен/); }); test('agentStop keeps the truthful note for completed and cancelled receipts', async () => { const completed = makeHarness(); completed.operation.id = 'op-completed'; completed.state.cancelReply = {ok: true, operation_id: 'op-completed', state: 'completed', uncertain: false, side_effect_started: true}; await completed.driver.agentStop(); const completedText = completed.state.texts.join('\n'); assert.match(completedText, /Операция уже завершилась/); assert.match(completedText, /уже запускались/); assert.doesNotMatch(completedText, /Внешние действия не запускались/); const cancelled = makeHarness(); cancelled.operation.id = 'op-cancelled'; cancelled.state.cancelReply = {ok: true, operation_id: 'op-cancelled', state: 'cancelled', uncertain: false, side_effect_started: false}; await cancelled.driver.agentStop(); const cancelledText = cancelled.state.texts.join('\n'); assert.match(cancelledText, /остановлена на сервере/); assert.match(cancelledText, /Внешние действия не запускались/); }); test('agentStop keeps the manual-stop fast path for an operation the server never saw', async () => { const {driver, state, operation} = makeHarness(); operation.id = 'op-unknown'; // Real path: a send already failed (failureText set) and the user presses Stop. operation.failureText = 'Модель сейчас не ответила.'; state.cancelReply = {ok: true, operation_id: 'op-unknown', state: 'not_found', uncertain: false}; await driver.agentStop(); const text = state.texts.join('\n'); assert.match(text, /Запрос не был принят/); assert.match(text, /только вручную/); });