diff --git a/lab/server/README.md b/lab/server/README.md index 68b259bf64..8404c253d3 100644 --- a/lab/server/README.md +++ b/lab/server/README.md @@ -19,8 +19,10 @@ tickets and events in SQLite. Nothing presses a button yet: that is Slice 5. | `pa_lab/lab_reader.py` | Strict reads of `Lab/state.json` and `Lab/save.json`; `console://B/state` and `/save` | | `pa_lab/tools.py`, `pa_lab/shot.py` | `ensure_game` (verification only) and `shot` (newer than the call) | | `pa_lab/mcp_server.py` | MCP over Streamable HTTP on `127.0.0.1`: bearer, Host/Origin, sessions, size caps | -| `tests/fake_lab.py` | A fake `Lab/` folder and a fake app answering `snapshot` requests, in temp dirs | +| `pa_lab/app_query.py` | `describe_program` and `game_open`: one-line reads through the app's channel (#504) | +| `tests/fake_lab.py` | A fake `Lab/` folder and a fake app answering `snapshot`, `describe_program` and `game_open` requests, in temp dirs | | `tests/test_{lab_reader,ensure_game,shot,config,mcp_server}.py` | Slice 2's fake-lab tests | +| `tests/test_app_query.py` | `describe_program` and `game_open` against the fake app | | `pa_lab/db.py` | The SQLite file: migrations (`PRAGMA user_version`), owner-only file, `BEGIN IMMEDIATE` writes | | `pa_lab/control.py` | Leases, idempotent requests, tickets, events, `next_events`, reconciliation, compaction | | `tests/test_{db,control,control_concurrency,control_mcp}.py` | Slice 3's tests: restarts, threads and processes racing, kills mid-write | @@ -189,6 +191,29 @@ or the saved frame is older than `max_age_ms`), `video_bad_signal`, `app_unavail from another instance: `evidence.reason` `instance_replaced`; `panel_changed`, `app_closing`, `save_failed` as `evidence.reason`; a line error or an incomplete PNG). +**`describe_program(console)`** and **`game_open(console)`** send the app's channel commands of +the same names (#504, `Lab.md` "Describe program" and "Screen"); both read only and need no +lease, owner token or program state. Each reads `state.json` (the app is up; its `instance.id`), +writes the fixed request `request ` / `` into `Lab/inbox` as `shot` does, waits +up to 5 s + 2 s for the journal, and reads `state.json` again. Arguments are closed: only +`console` (no `game_open image`). + +- `describe_program` parses `describe_program ` and returns it as `program`: + `{"id", "options", "prechecks", "schema": 1}` (the option entries as the app prints them) with + `prechecks_supported`. `prechecks` is the string `unsupported` until the program declares a + list (#485); that is a valid reply, not an error. A list is passed through. +- `game_open` parses `game_open yes` / `game_open no REASON` and returns `open` and `reason` + (`null`, `home`, `user_select`, `black` or `no_video`). `open: false` is an answer, not a tool + error; it does not tell one game from another (`ensure_game` does). + +| What the daemon finds | Refusal | +|---|---| +| `describe_program: the selected panel is not a program.` | `panel_not_program` | +| `schema` other than 1 | `unsupported_schema` | +| a failed line, no single reply line and `ok` line, bad JSON, a missing `id`/`options`/`prechecks`, an unknown `game_open` reason | `app_unavailable` (the journal in `evidence`) | +| a reply from another instance | `app_unavailable`, `evidence.reason` `instance_replaced` | +| no journal within 7 s | `timeout`; the request is withdrawn from the inbox | + ## Slice 3: the durable control plane SQLite (`db_file` in the config, default `~/.local/state/pa-lab/control.sqlite`, created `0600`) diff --git a/lab/server/pa_lab/app_query.py b/lab/server/pa_lab/app_query.py new file mode 100644 index 0000000000..a875cd147a --- /dev/null +++ b/lab/server/pa_lab/app_query.py @@ -0,0 +1,156 @@ +"""`describe_program` and `game_open`: one-line reads through the app's channel (Slice 4, fork #131). + +Both are app commands from #504 (Lab.md "Describe program" and "Screen") that need no owner +token, no program state and no lease: + +- `describe_program` prints `describe_program `, the selected program's id and the static + contract of its options: `{"id", "options", "prechecks", "schema": 1}`. `prechecks` is the + string `unsupported` until the program declares a precheck list (#485); a list after that. +- `game_open` prints `game_open yes`, or `game_open no REASON` with REASON `home`, + `user_select`, `black` or `no_video`. It never fails the line and does not tell one game from + another. + +Each call reads `Lab/state.json` (the app is up; its `instance.id`), writes a fixed request into +`Lab/inbox` the way `shot` does, reads the journal, and reads `state.json` again: a reply that +spans an app restart is refused. No caller input reaches the inbox. +""" + +from __future__ import annotations + +import json +import re +import time +import uuid +from typing import Any, Callable, Dict, List + +from pa_lab import shot +from pa_lab.lab_reader import ConsoleReader, Unavailable +from pa_lab.shot import Refused +from pa_lab.tools import check_arguments + +QUERY_TIMEOUT_MS = 5000 +GAME_OPEN_REASONS = ('home', 'user_select', 'black', 'no_video') +PROGRAM_SCHEMA = 1 +PRECHECKS_UNSUPPORTED = 'unsupported' +NOT_A_PROGRAM = 'the selected panel is not a program' + +JOURNAL_ERROR_RE = re.compile(r'^error \d+ \([^)]*\): (.*)$') +DESCRIBE_RE = re.compile(r'^describe_program (\{.*\})$') +GAME_OPEN_RE = re.compile(r'^game_open (yes|no(?: (\S+))?)$') + +__all__ = ['describe_program', 'game_open', 'Refused'] + + +def _instance_id(console: ConsoleReader) -> str: + try: + return console.app_state()['instance']['id'] + except Unavailable as e: + raise Refused(e.refusal()['code'], e.message, e.evidence) + + +def _ask(console: ConsoleReader, command: str, sleep: Callable[[float], None], + new_uuid: Callable[[], uuid.UUID]) -> Dict[str, Any]: + """Sends `command` (fixed text) and returns the journal's lines, the instance and the request.""" + started = console.now() + instance_id = _instance_id(console) + request_id = str(new_uuid()) + name = 'palab_{}_{}'.format(command, request_id.replace('-', '')) + inbox = shot.write_request(console.lab_dir, name, request_id, command) + deadline = started + (QUERY_TIMEOUT_MS + shot.ANSWER_GRACE_MS) / 1000.0 + lines = shot.wait_for_journal(console, sleep, deadline, console.lab_dir, name, inbox, command) + after = _instance_id(console) + if after != instance_id: + raise Refused('app_unavailable', 'The app restarted during the call.', { + 'reason': 'instance_replaced', 'instance_id': instance_id, 'new_instance_id': after}) + return {'lines': lines, 'instance_id': instance_id, 'request': name} + + +def _line_error(lines: List[str]): + for line in lines: + match = JOURNAL_ERROR_RE.match(line) + if match: + return match.group(1) + return None + + +def _one_reply(lines: List[str], pattern: 're.Pattern[str]', command: str): + """The single printed reply line, after an `ok N ` line.""" + ok_re = re.compile(r'^ok \d+ ' + command + r'\b') + replies = [m for m in (pattern.match(line) for line in lines) if m] + if len(replies) != 1 or not any(ok_re.match(line) for line in lines): + raise Refused('app_unavailable', 'The {} journal has no single reply line and ok line.'.format(command), + {'journal': lines}) + return replies[0] + + +def _check_contract(doc: Any, lines: List[str]) -> Dict[str, Any]: + if not isinstance(doc, dict): + raise Refused('app_unavailable', 'describe_program did not print a JSON object.', {'journal': lines}) + if doc.get('schema') != PROGRAM_SCHEMA: + raise Refused('unsupported_schema', 'describe_program schema {!r}; this daemon reads {}.'.format( + doc.get('schema'), PROGRAM_SCHEMA), {'schema': doc.get('schema')}) + problems = [] + if not isinstance(doc.get('id'), str) or not doc['id']: + problems.append('id') + if not isinstance(doc.get('options'), list) or not all(isinstance(o, dict) for o in doc['options']): + problems.append('options') + prechecks = doc.get('prechecks') + if prechecks != PRECHECKS_UNSUPPORTED and not isinstance(prechecks, list): + problems.append('prechecks') + if problems: + raise Refused('app_unavailable', 'describe_program printed a bad {}.'.format(', '.join(problems)), + {'journal': lines}) + return doc + + +def describe_program(console: ConsoleReader, arguments: Dict[str, Any], + sleep: Callable[[float], None] = time.sleep, + new_uuid: Callable[[], uuid.UUID] = uuid.uuid4) -> Dict[str, Any]: + """The selected program's id and option contract. Raises InvalidArguments or Refused.""" + check_arguments('describe_program', arguments) + reply = _ask(console, 'describe_program', sleep, new_uuid) + lines = reply['lines'] + error = _line_error(lines) + if error is not None: + if NOT_A_PROGRAM in error: + raise Refused('panel_not_program', 'The selected panel is not a program.', {'journal': lines}) + raise Refused('app_unavailable', "The app's describe_program line failed: {}".format(error), + {'journal': lines}) + match = _one_reply(lines, DESCRIBE_RE, 'describe_program') + try: + doc = json.loads(match.group(1)) + except ValueError: + raise Refused('app_unavailable', 'describe_program printed invalid JSON.', {'journal': lines}) from None + program = _check_contract(doc, lines) + return { + 'console': console.console, + 'instance_id': reply['instance_id'], + 'program': program, + 'prechecks_supported': program['prechecks'] != PRECHECKS_UNSUPPORTED, + 'request': reply['request'], + } + + +def game_open(console: ConsoleReader, arguments: Dict[str, Any], + sleep: Callable[[float], None] = time.sleep, + new_uuid: Callable[[], uuid.UUID] = uuid.uuid4) -> Dict[str, Any]: + """Whether a game is in front (`open`), and why not (`reason`). Raises InvalidArguments or Refused.""" + check_arguments('game_open', arguments) + reply = _ask(console, 'game_open', sleep, new_uuid) + lines = reply['lines'] + error = _line_error(lines) + if error is not None: + raise Refused('app_unavailable', "The app's game_open line failed: {}".format(error), {'journal': lines}) + match = _one_reply(lines, GAME_OPEN_RE, 'game_open') + is_open = match.group(1) == 'yes' + reason = match.group(2) + if not is_open and reason not in GAME_OPEN_REASONS: + raise Refused('app_unavailable', 'The app gave an unknown game_open reason {!r}.'.format(reason), + {'journal': lines}) + return { + 'console': console.console, + 'instance_id': reply['instance_id'], + 'open': is_open, + 'reason': reason, + 'request': reply['request'], + } diff --git a/lab/server/pa_lab/mcp_server.py b/lab/server/pa_lab/mcp_server.py index fbbe5f86e6..ac00a68b34 100644 --- a/lab/server/pa_lab/mcp_server.py +++ b/lab/server/pa_lab/mcp_server.py @@ -6,7 +6,7 @@ `Mcp-Session-Id`. The bearer token is never logged or returned. Resources: `console://B/state` (console_state), `console://B/save` (save_resource). -Tools: `shot`, `ensure_game`; with a control plane also `acquire_console`, +Tools: `shot`, `ensure_game`, `describe_program`, `game_open`; with a control plane also `acquire_console`, `renew_console`, `release_console`, `next_events` and `request_status`. Nothing here presses a button or starts or stops a program: that is not served yet. """ @@ -25,7 +25,7 @@ import threading from typing import Any, Callable, Dict, Optional, Tuple -from pa_lab import contracts, control, shot, tools +from pa_lab import app_query, contracts, control, shot, tools from pa_lab.lab_reader import ConsoleReader, Unavailable LOG = logging.getLogger('pa_lab.server') @@ -48,7 +48,8 @@ INSTRUCTIONS = ( 'Read-only view of lab console B. Read console://B/state before acting on the console and ' 'console://B/save for the last known save. shot returns a PNG newer than the call; ensure_game ' - 'only verifies, it never navigates. Unknown observations are never success.') + 'only verifies, it never navigates. describe_program gives the selected program\'s option contract; ' + 'game_open says whether a game is in front. Unknown observations are never success.') TOOL_LIST = [ { @@ -87,8 +88,39 @@ }, 'annotations': {'readOnlyHint': True, 'destructiveHint': False, 'idempotentHint': True}, }, + { + 'name': 'describe_program', + 'title': "The selected program's option contract", + 'description': "The selected program's id and the static contract of its options (keys, types, " + 'defaults, bounds, enum entries) and its prechecks (the string "unsupported" until the ' + 'program declares them). Read-only; needs no lease. Refuses when the selected panel is ' + 'not a program.', + 'inputSchema': { + 'type': 'object', + 'properties': {'console': {'type': 'string', 'enum': ['B']}}, + 'required': ['console'], + 'additionalProperties': False, + }, + 'annotations': {'readOnlyHint': True, 'destructiveHint': False, 'idempotentHint': True}, + }, + { + 'name': 'game_open', + 'title': 'Is a game in front', + 'description': 'Whether a game is in front of the console now: open true, or open false with reason ' + 'home, user_select, black (loading or no signal) or no_video. It does not tell one game ' + 'from another; use ensure_game for that. Read-only; needs no lease.', + 'inputSchema': { + 'type': 'object', + 'properties': {'console': {'type': 'string', 'enum': ['B']}}, + 'required': ['console'], + 'additionalProperties': False, + }, + 'annotations': {'readOnlyHint': True, 'destructiveHint': False, 'idempotentHint': False}, + }, ] +APP_QUERIES = {'describe_program': app_query.describe_program, 'game_open': app_query.game_open} + _REQUEST_ID = {'type': 'string', 'description': 'client-generated lower-case UUID; a retry reuses it'} _LEASE_TOKEN = {'type': 'string', 'description': 'the token acquire_console returned'} @@ -220,7 +252,7 @@ def _read_resource(self, uri: Any) -> Dict[str, Any]: return {'contents': [{'uri': uri, 'mimeType': 'application/json', 'text': _json_text(doc)}]} def _call_tool(self, name: Any, arguments: Any) -> Dict[str, Any]: - if name not in ('shot', 'ensure_game'): + if name not in ('shot', 'ensure_game') and name not in APP_QUERIES: raise RpcError(INVALID_PARAMS, 'Unknown tool: {}'.format(name)) if not isinstance(arguments, dict): return self._refused(name, {'code': 'invalid_arguments', 'field': 'arguments', @@ -235,6 +267,10 @@ def _call_tool(self, name: Any, arguments: Any) -> Dict[str, Any]: result = tools.ensure_game(reader, arguments) return {'content': [{'type': 'text', 'text': _json_text(result)}], 'structuredContent': result, 'isError': not result['verified']} + if name in APP_QUERIES: + result = APP_QUERIES[name](reader, arguments) + return {'content': [{'type': 'text', 'text': _json_text(result)}], + 'structuredContent': result, 'isError': False} result = self.take_shot(reader, arguments) except tools.InvalidArguments as e: return self._refused(name, e.refusal()) diff --git a/lab/server/pa_lab/shot.py b/lab/server/pa_lab/shot.py index 828365dcb8..b39b8fcba4 100644 --- a/lab/server/pa_lab/shot.py +++ b/lab/server/pa_lab/shot.py @@ -68,10 +68,11 @@ def _check_start(app: Dict[str, Any]) -> None: # app writes after its next 500 ms poll. A local socket is the likely replacement if poll latency # or missed events become a measured problem; the alternatives are in lab/tooling's # docs/design/Agent-Integration.md, "Transport: now and later". -def _write_request(lab_dir: Path, name: str, request_id: str, timeout_ms: int) -> Path: +def write_request(lab_dir: Path, name: str, request_id: str, line: str) -> Path: + """`line` is fixed text built by the daemon; no caller string reaches the inbox.""" part = lab_dir / 'outbox' / (name + '.part') inbox = lab_dir / 'inbox' / (name + '.txt') - part.write_text('request {}\nsnapshot {} {}\n'.format(request_id, LABEL, timeout_ms), encoding='utf-8') + part.write_text('request {}\n{}\n'.format(request_id, line), encoding='utf-8') os.replace(part, inbox) return inbox @@ -83,8 +84,8 @@ def _withdraw(inbox: Path) -> None: pass -def _wait_for_journal(console: ConsoleReader, sleep: Callable[[float], None], deadline: float, - lab_dir: Path, name: str, inbox: Path) -> List[str]: +def wait_for_journal(console: ConsoleReader, sleep: Callable[[float], None], deadline: float, + lab_dir: Path, name: str, inbox: Path, command: str = 'snapshot') -> List[str]: journal = lab_dir / 'outbox' / (name + '.out') while True: if journal.exists(): @@ -95,8 +96,8 @@ def _wait_for_journal(console: ConsoleReader, sleep: Callable[[float], None], de break sleep(POLL_S) _withdraw(inbox) - raise Refused('timeout', 'The app did not answer the snapshot request in time (busy with another ' - 'request?).', {'request': name}) + raise Refused('timeout', 'The app did not answer the {} request in time (busy with another ' + 'request?).'.format(command), {'request': name}) def _check_instance(reply_instance: str, instance_id: str) -> None: @@ -182,9 +183,9 @@ def take_shot(console: ConsoleReader, arguments: Dict[str, Any], request_id = str(new_uuid()) name = 'palab_shot_' + request_id.replace('-', '') - inbox = _write_request(console.lab_dir, name, request_id, timeout_ms) + inbox = write_request(console.lab_dir, name, request_id, 'snapshot {} {}'.format(LABEL, timeout_ms)) deadline = started + (timeout_ms + ANSWER_GRACE_MS) / 1000.0 - lines = _wait_for_journal(console, sleep, deadline, console.lab_dir, name, inbox) + lines = wait_for_journal(console, sleep, deadline, console.lab_dir, name, inbox) png_path = console.lab_dir / 'outbox' / '{}_{}.png'.format(name, LABEL) frame = _parse_saved(lines, instance_id, png_path) age_ms = int(round((console.now() - timestamps.parse(frame['captured_at'])) * 1000)) diff --git a/lab/server/pa_lab/tools.py b/lab/server/pa_lab/tools.py index 21c81f22f5..ecaa255f72 100644 --- a/lab/server/pa_lab/tools.py +++ b/lab/server/pa_lab/tools.py @@ -1,6 +1,6 @@ """The read-only tools of Slice 2 (fork #131): argument checks and `ensure_game`. -`shot` lives in pa_lab/shot.py. No tool here presses a button, starts or stops a program, or +`shot` lives in pa_lab/shot.py; `describe_program` and `game_open` in pa_lab/app_query.py. No tool here presses a button, starts or stops a program, or changes what the app shows; mutating tools arrive with leases (Slices 3 and 5). """ @@ -27,6 +27,8 @@ required=False), F('max_age_ms', Int(minimum=100, maximum=600000), required=False, doc='default 5000'), ], open=False), + 'describe_program': Obj([F('console', Str())], open=False), + 'game_open': Obj([F('console', Str())], open=False), } diff --git a/lab/server/tests/fake_lab.py b/lab/server/tests/fake_lab.py index 72c72ea900..060795fcf0 100644 --- a/lab/server/tests/fake_lab.py +++ b/lab/server/tests/fake_lab.py @@ -81,6 +81,19 @@ def _atomic(path, text): os.replace(tmp, path) +PROGRAM_CONTRACT = { + 'id': 'PokemonFRLG:AutoStory', + 'options': [ + {'key': 'LANGUAGE', 'type': 'enum', 'default': 'en', + 'entries': [{'slug': 'en', 'enabled': True}, {'slug': 'ja', 'enabled': False}]}, + {'key': 'START_SEGMENT', 'type': 'integer', 'default': 0, 'min': 0, 'max': 40}, + {'key': 'NOTIFICATIONS', 'type': 'group', 'toggleable': True, + 'options': [{'key': 'Enabled', 'type': 'boolean', 'default': True}]}, + ], + 'prechecks': 'unsupported', + 'schema': 1, +} + PNG = b'\x89PNG\r\n\x1a\n' + b'\x00\x00\x00\rIHDR' + b'\x00' * 17 + b'\x00\x00\x00\x00IEND\xaeB`\x82' @@ -94,6 +107,10 @@ class FakeApp: (the line fails without a snapshot line), `unavailable` (a `snapshot unavailable` reason), `reply_instance` (the instance the reply names), `reply_dir` (the folder the reply's path names; the PNG is still saved in outbox/), `png` (the bytes the app saves). + + `describe_program` and `game_open` (#504) are answered at once: `replies[command]` is the + printed text (default below), `line_errors[command]` fails the line instead, and + `restart_on` names a command whose answer comes from a new app instance. """ def __init__(self, lab, clock): @@ -106,6 +123,13 @@ def __init__(self, lab, clock): self.reply_instance = None self.reply_dir = None self.png = PNG + self.replies = { + 'describe_program': 'describe_program ' + json.dumps(PROGRAM_CONTRACT, sort_keys=True, + separators=(',', ':')) + '\n', + 'game_open': 'game_open yes\n', + } + self.line_errors = {} + self.restart_on = None self.requests = [] self.pending = [] clock.on_sleep.append(self.tick) @@ -130,6 +154,9 @@ def pick_up(self, request): self.requests.append(text) line = text.splitlines()[-1] words = line.split() + if words[0] in self.replies: + self.answer(request.stem, line, words[0]) + return pending = {'name': request.stem, 'line': line, 'label': words[1], 'timeout_ms': int(words[2]), 'started': self.clock.now(), 'after': self.lab.state['video']['frame_seq'] or 0} if self.journal_error is not None: @@ -140,6 +167,15 @@ def pick_up(self, request): else: self.pending.append(pending) + def answer(self, name, line, command): + if self.restart_on == command: + self.lab.update_state(**{'instance.id': '11111111-2222-4333-8444-555555555555'}) + pending = {'name': name, 'line': line} + if command in self.line_errors: + self.finish(pending, '', self.line_errors[command]) + else: + self.finish(pending, self.replies[command]) + def continue_snapshot(self, pending): video = self.lab.state['video'] if video['frame_seq'] is not None and video['frame_seq'] > pending['after']: diff --git a/lab/server/tests/test_app_query.py b/lab/server/tests/test_app_query.py new file mode 100644 index 0000000000..b6553ff1a4 --- /dev/null +++ b/lab/server/tests/test_app_query.py @@ -0,0 +1,163 @@ +"""describe_program and game_open through the app's channel (Slice 4, fork #131), on a fake app. + +Run from the repo root: python3 -m unittest discover -s lab/server/tests -t lab/server -v +""" + +import copy +import json +import unittest + +from pa_lab import app_query, lab_reader, tools +from tests.fake_lab import PROGRAM_CONTRACT, FakeApp, FakeClock, FakeLab, golden + +START = '2026-11-14T06:10:12.400Z' +INSTANCE = 'd8ea6a9d-1eab-4a40-b355-d88072b289a1' +NEW_INSTANCE = '11111111-2222-4333-8444-555555555555' + + +def describe_line(doc): + return 'describe_program ' + json.dumps(doc, sort_keys=True, separators=(',', ':')) + '\n' + + +class AppQueryTest(unittest.TestCase): + def setUp(self): + self.lab = FakeLab(self) + self.lab.write_state(golden('app_state', 'stopped_ui')) + self.clock = FakeClock(START) + self.app = FakeApp(self.lab, self.clock) + self.console = lab_reader.ConsoleReader('B', self.lab.dir, profile='lab-B', now=self.clock.now, + pid_alive=lambda pid: True) + + def ask(self, command, **arguments): + query = getattr(app_query, command) + return query(self.console, dict(arguments, console='B'), sleep=self.clock.sleep) + + def refusal(self, command, **arguments): + with self.assertRaises(app_query.Refused) as raised: + self.ask(command, **arguments) + return raised.exception.refusal + + +class DescribeProgramTests(AppQueryTest): + def test_returns_the_contract(self): + result = self.ask('describe_program') + self.assertEqual(result['program'], PROGRAM_CONTRACT) + self.assertFalse(result['prechecks_supported']) + self.assertEqual(result['instance_id'], INSTANCE) + self.assertEqual(result['console'], 'B') + + def test_the_request_is_one_fixed_line(self): + self.ask('describe_program') + self.assertEqual(len(self.app.requests), 1) + lines = self.app.requests[0].splitlines() + self.assertRegex(lines[0], r'^request [0-9a-f-]{36}$') + self.assertEqual(lines[1:], ['describe_program']) + + def test_a_precheck_list_is_supported(self): + doc = dict(PROGRAM_CONTRACT, prechecks=[{'name': 'game_open', 'needs': 'a game in front'}]) + self.app.replies['describe_program'] = describe_line(doc) + result = self.ask('describe_program') + self.assertTrue(result['prechecks_supported']) + self.assertEqual(result['program']['prechecks'], doc['prechecks']) + + def test_refusals(self): + bad_options = dict(PROGRAM_CONTRACT, options=['LANGUAGE']) + no_id = {k: v for k, v in PROGRAM_CONTRACT.items() if k != 'id'} + bad_prechecks = dict(PROGRAM_CONTRACT, prechecks='none') + cases = [ + dict(name='not a program', + input=dict(error='describe_program: the selected panel is not a program.'), + expectation='panel_not_program'), + dict(name='no options', + input=dict(error='describe_program: the selected program has no options the lab can read.'), + expectation='app_unavailable'), + dict(name='schema 2', input=dict(reply=describe_line(dict(PROGRAM_CONTRACT, schema=2))), + expectation='unsupported_schema'), + dict(name='bad json', input=dict(reply='describe_program {"id":\n'), expectation='app_unavailable'), + dict(name='not an object', input=dict(reply='describe_program [1]\n'), expectation='app_unavailable'), + dict(name='options not objects', input=dict(reply=describe_line(bad_options)), + expectation='app_unavailable'), + dict(name='no id', input=dict(reply=describe_line(no_id)), expectation='app_unavailable'), + dict(name='bad prechecks', input=dict(reply=describe_line(bad_prechecks)), + expectation='app_unavailable'), + dict(name='no reply line', input=dict(reply=''), expectation='app_unavailable'), + dict(name='two reply lines', input=dict(reply=describe_line(PROGRAM_CONTRACT) * 2), + expectation='app_unavailable'), + ] + for case in cases: + with self.subTest(case['name']): + self.setUp() + if 'error' in case['input']: + self.app.line_errors['describe_program'] = case['input']['error'] + else: + self.app.replies['describe_program'] = case['input']['reply'] + self.assertEqual(self.refusal('describe_program')['code'], case['expectation']) + + def test_closed_arguments(self): + with self.assertRaises(tools.InvalidArguments) as raised: + self.ask('describe_program', panel='PokemonFRLG:AutoStory') + self.assertEqual(raised.exception.field, 'panel') + self.assertEqual(self.app.requests, []) + + +class GameOpenTests(AppQueryTest): + def test_yes(self): + result = self.ask('game_open') + self.assertEqual((result['open'], result['reason']), (True, None)) + self.assertEqual(self.app.requests[0].splitlines()[1:], ['game_open']) + + def test_no_with_each_reason(self): + for reason in app_query.GAME_OPEN_REASONS: + with self.subTest(reason): + self.app.replies['game_open'] = 'game_open no {}\n'.format(reason) + result = self.ask('game_open') + self.assertEqual((result['open'], result['reason']), (False, reason)) + + def test_refusals(self): + cases = [ + dict(name='unknown reason', input=dict(reply='game_open no gremlins\n'), expectation='app_unavailable'), + dict(name='no reason', input=dict(reply='game_open no\n'), expectation='app_unavailable'), + dict(name='garbled', input=dict(reply='game_open maybe\n'), expectation='app_unavailable'), + dict(name='line failed', input=dict(error='Unknown command: game_open (try "help")'), + expectation='app_unavailable'), + ] + for case in cases: + with self.subTest(case['name']): + self.setUp() + if 'error' in case['input']: + self.app.line_errors['game_open'] = case['input']['error'] + else: + self.app.replies['game_open'] = case['input']['reply'] + self.assertEqual(self.refusal('game_open')['code'], case['expectation']) + + +class SharedTests(AppQueryTest): + def test_app_busy_times_out_and_withdraws(self): + for command in ('describe_program', 'game_open'): + with self.subTest(command): + self.setUp() + self.app.serve = False + refusal = self.refusal(command) + self.assertEqual(refusal['code'], 'timeout') + self.assertEqual(list((self.lab.dir / 'inbox').iterdir()), []) + + def test_a_restart_during_the_call_is_refused(self): + for command in ('describe_program', 'game_open'): + with self.subTest(command): + self.setUp() + self.app.restart_on = command + refusal = self.refusal(command) + self.assertEqual(refusal['code'], 'app_unavailable') + self.assertEqual(refusal['evidence']['reason'], 'instance_replaced') + self.assertEqual(refusal['evidence']['new_instance_id'], NEW_INSTANCE) + + def test_app_down_is_refused_before_any_request(self): + state = copy.deepcopy(self.lab.state) + state['written_at'] = '2026-11-14T06:00:00.000Z' + self.lab.write_state(state) + self.assertEqual(self.refusal('game_open')['code'], 'app_unavailable') + self.assertEqual(self.app.requests, []) + + +if __name__ == '__main__': + unittest.main() diff --git a/lab/server/tests/test_control_mcp.py b/lab/server/tests/test_control_mcp.py index 0f2c8f1791..edeeba05a3 100644 --- a/lab/server/tests/test_control_mcp.py +++ b/lab/server/tests/test_control_mcp.py @@ -45,7 +45,7 @@ def heartbeat(self, **changes): def test_the_control_tools_are_listed(self): _, body = self.client.rpc('tools/list') names = [t['name'] for t in body['result']['tools']] - self.assertEqual(names, ['shot', 'ensure_game', 'acquire_console', 'renew_console', 'release_console', + self.assertEqual(names, ['shot', 'ensure_game', 'describe_program', 'game_open', 'acquire_console', 'renew_console', 'release_console', 'next_events', 'request_status']) def test_acquire_then_state_shows_the_lease_and_a_retry_matches(self): diff --git a/lab/server/tests/test_mcp_server.py b/lab/server/tests/test_mcp_server.py index 2367f11fbc..568f164490 100644 --- a/lab/server/tests/test_mcp_server.py +++ b/lab/server/tests/test_mcp_server.py @@ -12,7 +12,7 @@ import unittest from pa_lab import lab_reader, mcp_server, timestamps -from tests.fake_lab import PNG, FakeApp, FakeLab, golden +from tests.fake_lab import PNG, PROGRAM_CONTRACT, FakeApp, FakeLab, golden TOKEN = 'test-token-' + 'x' * 32 @@ -170,7 +170,7 @@ def test_lists_only_console_b(self): _, body = self.client.rpc('resources/list') self.assertEqual([r['uri'] for r in body['result']['resources']], ['console://B/state', 'console://B/save']) _, body = self.client.rpc('tools/list') - self.assertEqual([t['name'] for t in body['result']['tools']], ['shot', 'ensure_game']) + self.assertEqual([t['name'] for t in body['result']['tools']], ['shot', 'ensure_game', 'describe_program', 'game_open']) def test_state_resource(self): state = self.client.read('console://B/state') @@ -216,6 +216,35 @@ def test_ensure_game(self): result = self.client.tool('ensure_game', console='B', expected='Pokemon BDSP') self.assertEqual(result['structuredContent']['refusal']['field'], 'expected') + def test_describe_program(self): + result = self.client.tool('describe_program', console='B') + self.assertFalse(result['isError'], result) + self.assertEqual(result['structuredContent']['program'], PROGRAM_CONTRACT) + self.assertEqual(json.loads(result['content'][0]['text']), result['structuredContent']) + + def test_describe_program_on_a_settings_panel_is_a_refusal(self): + self.app.line_errors['describe_program'] = 'describe_program: the selected panel is not a program.' + result = self.client.tool('describe_program', console='B') + self.assertTrue(result['isError']) + self.assertEqual(result['structuredContent']['refusal']['code'], 'panel_not_program') + + def test_game_open(self): + result = self.client.tool('game_open', console='B') + self.assertFalse(result['isError'], result) + self.assertEqual((result['structuredContent']['open'], result['structuredContent']['reason']), (True, None)) + self.app.replies['game_open'] = 'game_open no home\n' + result = self.client.tool('game_open', console='B') + self.assertFalse(result['isError'], result) + self.assertEqual((result['structuredContent']['open'], result['structuredContent']['reason']), + (False, 'home')) + + def test_app_queries_refuse_unknown_arguments(self): + for name in ('describe_program', 'game_open'): + with self.subTest(name): + result = self.client.tool(name, console='B', image='/etc/passwd') + self.assertTrue(result['isError']) + self.assertEqual(result['structuredContent']['refusal']['field'], 'image') + def test_unknown_method_and_tool(self): _, body = self.client.rpc('tools/press') self.assertEqual(body['error']['code'], mcp_server.METHOD_NOT_FOUND)