"""Terminal-truth receipts for the Mini App coding assistant.
The UI bug this guards against: a provider/model error *after* a successful tool call
must not look like success, and must not let the client claim that no external actions
ran. Receipts therefore carry an explicit `side_effect_started` boolean next to
`uncertain`, and terminal failures report `state='failed'` (never 'completed').
These tests use the real chat()/_chat_work()/_finish_operation()/cancel() bodies; only the
network edges (complete/execute/user_key) are scripted, so no provider or SQLite data is
touched.
"""
import asyncio
import importlib
import sys
import unittest
from pathlib import Path
BOT = Path(__file__).resolve().parents[1] / "bot"
sys.path.insert(0, str(BOT))
runtime_module = importlib.import_module("assistant_runtime")
AssistantError = runtime_module.AssistantError
AssistantRuntime = runtime_module.AssistantRuntime
UID = 424242
class ScriptedRuntime(AssistantRuntime):
"""Real runtime, scripted edges: no provider, no sandbox, no database."""
def __init__(self, replies, exec_result=None, key_error=None):
super().__init__("bot.db", "newapi.db", "http://127.0.0.1:9/v1", ("test-model",), None, None)
self.replies = list(replies)
self.exec_result = exec_result if exec_result is not None else {
"cmd": "echo ok", "out": "ok", "exit_code": 0, "connected": True, "uncertain": False,
}
self.key_error = key_error
self.complete_calls = []
self.exec_calls = []
def user_key(self, uid):
if self.key_error is not None:
raise self.key_error
return "sk-test-key"
async def complete(self, model, messages, key, *, fast=False, max_tokens=2048):
self.complete_calls.append({"model": model, "fast": fast, "messages": list(messages)})
if not self.replies:
raise AssertionError("runtime asked for more upstream answers than the scenario provides")
reply = self.replies.pop(0)
if isinstance(reply, BaseException):
raise reply
return reply
async def execute(self, uid, command):
self.exec_calls.append(command)
return dict(self.exec_result)
def payload(operation_id, text="привет"):
return {
"operation_id": operation_id,
"model": "test-model",
"messages": [{"role": "user", "content": text}],
}
class TerminalTruthTests(unittest.TestCase):
def setUp(self):
import os
previous = os.environ.get("IISHKO_SANDBOX_ENABLED")
os.environ["IISHKO_SANDBOX_ENABLED"] = "1"
def restore():
if previous is None:
os.environ.pop("IISHKO_SANDBOX_ENABLED", None)
else:
os.environ["IISHKO_SANDBOX_ENABLED"] = previous
self.addCleanup(restore)
def run_chat(self, runtime, operation_id, text="привет"):
async def scenario():
try:
result = await runtime.chat(UID, payload(operation_id, text))
except AssistantError as error:
await asyncio.sleep(0) # let the done-callback publish the finished record
return error
await asyncio.sleep(0)
return result
return asyncio.run(scenario())
def finished_record(self, runtime, operation_id):
return runtime.finished.get((UID, operation_id))
def test_rejected_before_tool_is_failed_without_side_effects(self):
"""403 from user_key: nothing ran, so the UI may restore the draft and retry."""
refusal = AssistantError(403, "need_key", "Сначала создай активный API-ключ во вкладке «Ключи».")
runtime = ScriptedRuntime(replies=[], key_error=refusal)
error = self.run_chat(runtime, "op403beforetool")
self.assertIsInstance(error, AssistantError)
self.assertEqual(error.status, 403)
self.assertEqual(error.details.get("operation_id"), "op403beforetool")
self.assertEqual(error.details.get("state"), "failed")
self.assertIs(error.details.get("uncertain"), False)
self.assertIs(error.details.get("side_effect_started"), False)
self.assertEqual(runtime.complete_calls, [])
self.assertEqual(runtime.exec_calls, [])
record = self.finished_record(runtime, "op403beforetool")
self.assertIsNotNone(record, "a terminal failure must have a finished record")
self.assertEqual(record["state"], "failed")
self.assertIs(record["uncertain"], False)
self.assertIs(record["side_effect_started"], False)
receipt = runtime.cancel(UID, "op403beforetool")
# [CANCEL-COMPAT] legacy cancel whitelist: state stays terminal-but-known,
# the failure itself rides in explicit markers.
self.assertEqual(receipt["state"], "completed")
self.assertIs(receipt.get("failed"), True)
self.assertEqual(receipt.get("terminal_state"), "failed")
self.assertIs(receipt["uncertain"], False)
self.assertIs(receipt["side_effect_started"], False)
self.assertNotIn("finished_at", receipt)
def test_failure_after_successful_tool_keeps_side_effect_truth(self):
"""Model error after exec: state failed, side effects started, outcome uncertain."""
runtime = ScriptedRuntime(
replies=["echo ok", AssistantError(503, "model_unavailable", "Модель сейчас не ответила.")],
exec_result={"cmd": "echo ok", "out": "ok", "exit_code": 0, "connected": True, "uncertain": False},
)
error = self.run_chat(runtime, "op503aftertool")
self.assertIsInstance(error, AssistantError)
self.assertEqual(error.status, 503)
self.assertEqual(error.details.get("state"), "failed")
self.assertIs(error.details.get("uncertain"), True)
self.assertIs(error.details.get("side_effect_started"), True)
self.assertEqual(runtime.exec_calls, ["echo ok"])
record = self.finished_record(runtime, "op503aftertool")
self.assertEqual(record["state"], "failed")
self.assertIs(record["uncertain"], True)
self.assertIs(record["side_effect_started"], True)
receipt = runtime.cancel(UID, "op503aftertool")
# [CANCEL-COMPAT] legacy cancel whitelist: state stays terminal-but-known,
# the failure itself rides in explicit markers.
self.assertEqual(receipt["state"], "completed")
self.assertIs(receipt.get("failed"), True)
self.assertEqual(receipt.get("terminal_state"), "failed")
self.assertIs(receipt["side_effect_started"], True)
def test_definitive_tool_then_answer_is_completed_not_uncertain(self):
runtime = ScriptedRuntime(replies=["echo ok", "Готово: команда выполнена."])
result = self.run_chat(runtime, "op200withtool")
self.assertNotIsInstance(result, BaseException)
self.assertEqual(result["state"], "completed")
self.assertIs(result["uncertain"], False)
self.assertIs(result["side_effect_started"], True)
self.assertIn("Готово", result["reply"])
self.assertEqual(runtime.exec_calls, ["echo ok"])
self.assertGreaterEqual(len(runtime.complete_calls), 2, "the tool result must be shown back to the model")
def test_unconfirmed_tool_answers_but_stays_uncertain(self):
runtime = ScriptedRuntime(
replies=["echo ok", "Не смог подтвердить результат."],
exec_result={"cmd": "echo ok", "out": "VM не подтвердила завершение. Проверь файлы перед повтором.",
"connected": False, "uncertain": True},
)
result = self.run_chat(runtime, "op200ambiguous")
self.assertNotIsInstance(result, BaseException)
self.assertEqual(result["state"], "completed")
self.assertIs(result["uncertain"], True)
self.assertIs(result["side_effect_started"], True)
self.assertTrue(result["reply"].strip())
def test_cancel_receipt_moves_from_requested_to_cancelled(self):
class BlockingRuntime(ScriptedRuntime):
def __init__(self):
super().__init__(replies=["never returned"])
self.entered = asyncio.Event()
async def complete(self, model, messages, key, *, fast=False, max_tokens=2048):
self.entered.set()
await asyncio.sleep(3600)
raise AssertionError("unreachable")
async def scenario():
runtime = BlockingRuntime()
task = asyncio.create_task(runtime.chat(UID, payload("opcancelrunning")))
await asyncio.wait_for(runtime.entered.wait(), 5)
first = runtime.cancel(UID, "opcancelrunning")
settled = await asyncio.wait_for(task, 5)
return runtime, first, settled
runtime, first, settled = asyncio.run(scenario())
self.assertEqual(first["state"], "cancel_requested")
self.assertIs(first["uncertain"], False)
self.assertEqual(settled["state"], "cancelled")
self.assertIs(settled.get("cancelled"), True)
self.assertIs(settled["side_effect_started"], False)
record = self.finished_record(runtime, "opcancelrunning")
self.assertEqual(record["state"], "cancelled")
self.assertIs(record["side_effect_started"], False)
def test_unknown_operation_keeps_legacy_receipt_shape(self):
"""No claim about side effects is made for an operation the server never saw."""
runtime = ScriptedRuntime(replies=[])
receipt = runtime.cancel(UID, "opunknownop")
self.assertEqual(receipt, {"ok": True, "operation_id": "opunknownop",
"state": "not_found", "uncertain": False})
self.assertEqual(runtime._state("opx", "not_found"),
{"ok": True, "operation_id": "opx", "state": "not_found", "uncertain": False})
def test_request_validation_rejection_is_not_stamped_as_failed(self):
"""A 400 before an operation exists must not carry operation-level receipt fields."""
runtime = ScriptedRuntime(replies=[])
with self.assertRaises(AssistantError) as caught:
asyncio.run(runtime.chat(UID, {"model": "nope", "messages": [{"role": "user", "content": "привет"}]}))
details = getattr(caught.exception, "details", {}) or {}
self.assertNotIn("state", details)
self.assertNotIn("side_effect_started", details)
if __name__ == "__main__":
unittest.main()