diff --git a/lab/server/README.md b/lab/server/README.md index e67810ac60..5dd822dcca 100644 --- a/lab/server/README.md +++ b/lab/server/README.md @@ -4,7 +4,8 @@ The local server designed in `docs/design/Agent-Integration.md` (fork #131, bran `design/agent-integration`). Slice 0: the version-1 contracts, golden examples and a parser. Slice 2: the attach-only read server ([below](#slice-2-the-attach-only-read-server)). Slice 3: the durable control plane ([below](#slice-3-the-durable-control-plane)): leases, request records, -tickets and events in SQLite. Nothing presses a button yet: that is Slice 5. +tickets and events in SQLite. Slice 5 ([below](#slice-5-leased-actions)), first sub-slice: `stop_program`, +the first leased action. Nothing starts a program or presses a button yet. | Path | What | |---|---| @@ -26,6 +27,8 @@ tickets and events in SQLite. Nothing presses a button yet: that is Slice 5. | `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 | +| `pa_lab/actions.py` | Leased actions (Slice 5): `stop_program`, the channel request it sends and how its reply is read | +| `tests/test_actions.py` | Slice 5's tests: the ticket, retries, refusals, UI takeover, app restart, a terminal event before the response | Stdlib only (Python 3.8+), so no venv: the MCP transport is small enough to write on `http.server`. Run the tests from the repo root: @@ -137,7 +140,9 @@ python3 -m pa_lab serve --config ~/.config/pa-lab/server.json "profile": "lab-B"}}} ``` -The config is the server's own, closed, and must list exactly `B`; it never reads +The config is the server's own, closed, and must list exactly `B`. `consoles.B.channel_owner` +(optional, one word, default the profile) is the token Slice 5's actions claim the app's channel +with; it never reads `~/BDSPLab/consoles.json`. A Claude Code client adds it as an HTTP MCP server at `http://127.0.0.1:8765/mcp` with the header `Authorization: Bearer `. @@ -264,3 +269,50 @@ every event after an active cursor (one used in the last 7 days), every event of and every pending record; finished records go after 7 days. A cursor behind the compacted range is refused (`invalid_arguments`, field `after_seq`, `evidence.compacted_through`), never served with a silent gap. + +## Slice 5: leased actions + +Built so far: `stop_program`, the first tool that changes what the app does. The rest of Slice 5 +(`preflight_program`, `run_program`, `cfr_batch`) needs app-side commands first; see the list in +the PR that added this section. + +**A leased action is a ticket.** `stop_program(console, request_id, lease_token)` returns its +request record at once: `pending` until the app reports the outcome, which arrives as a +`request_completed` / `request_failed` event (`next_events`) and in `request_status`. The tool +does not wait for the program to stop. `ControlPlane.begin_action` stores the call in one +transaction with the lease check: an exact retry gets the stored record and sends nothing; the +lease must be held by the token (an idle lease is renewed by the call); a program that is not +`running` completes at once with `outcome: not_running`; otherwise the record is `pending` and +remembers the app instance it was sent to (`requests.instance_id`, migration 2). + +**The channel request** (Lab.md "Requests", "Owner") is fixed text: + +``` +owner lab-B +request +owner claim lab-B +stop +``` + +The daemon claims the channel with `channel_owner` before each action rather than once at +attach, so it works across app restarts and beside `lab/scripts/lc.sh`, which uses the same +default token. The app puts `request_id` on `program.last_transition` and keeps it from +`stopping` to `stopped`. + +**What resolves the ticket.** The app's report, applied by `observe` on every read of +`console://B/state`, every `request_status`, and every poll of a waiting `next_events`: + +| The app shows | Ticket | +|---|---| +| `stopped`, `last_transition` `{stop, lab, }` | completed, `outcome: stopped` | +| `stopping` with that transition | still pending | +| `stopped` by `program` or `error` at or after the call | completed, `outcome: ended` (the run's own end) | +| a UI Start/Stop at or after the call | failed, `console_held_by_user`; the lease becomes `user` | +| another `instance.id` | failed, `app_unavailable`, `evidence.reason: instance_replaced` | +| (the stop line failed and nothing runs) | completed, `outcome: not_running` | +| (the stop line failed otherwise, e.g. `owned by `) | failed, `app_unavailable`, the journal in `evidence` | +| (no journal within 7 s and the request still in the inbox) | withdrawn; `refused`, `timeout`: nothing was sent | +| (no journal within 7 s and the app took the request) | still pending; the rows above resolve it | + +A stop by this lease holder ends `agent_running` as before (`lease_changed`, reason `run_ended`). +`begin_run` (Slice 3) is still entered only by tests: `run_program` will call it. diff --git a/lab/server/pa_lab/__main__.py b/lab/server/pa_lab/__main__.py index f12b07518d..f69307625c 100644 --- a/lab/server/pa_lab/__main__.py +++ b/lab/server/pa_lab/__main__.py @@ -94,7 +94,9 @@ def _serve(path: str) -> int: for reader in readers.values(): # restart reconciliation: apply what the app shows now reader.console_state() plane.compact() - server = mcp_server.make_server(cfg.port, token, readers, control_plane=plane) + server = mcp_server.make_server(cfg.port, token, readers, control_plane=plane, + channel_owners={name: entry.channel_owner for name, entry in cfg.consoles.items() + if entry.channel_owner is not None}) logging.getLogger('pa_lab.server').info('serving %s on http://127.0.0.1:%d%s', ', '.join(sorted(readers)), server.server_address[1], mcp_server.ENDPOINT) diff --git a/lab/server/pa_lab/actions.py b/lab/server/pa_lab/actions.py new file mode 100644 index 0000000000..352dfd071c --- /dev/null +++ b/lab/server/pa_lab/actions.py @@ -0,0 +1,141 @@ +"""Leased actions (Slice 5 of fork #131). First: `stop_program`. + +A leased action is a long operation: the tool stores a ticket, sends one fixed request into the +app's channel and returns; the app's own report in `Lab/state.json` completes it. Agents do not +park on the call: they read `request_status` or wait in `next_events` for the ticket's +`request_completed` / `request_failed` event. + +`stop_program(console, request_id, lease_token)`: + +1. Read `Lab/state.json` (the app is up; its instance) and apply it (`observe`), so a UI click + that already happened takes the console before this call is decided. +2. `ControlPlane.begin_action`: the lease must be held by the token; a program that is not + `running` completes at once (`outcome: not_running`); otherwise a `pending` ticket bound to + that app instance. An exact retry returns the stored record and sends nothing. +3. Send `owner T` / `request ` / `owner claim T` / `stop` (Lab.md "Requests", + "Owner"). `T` is the console's channel owner from the config; the app names `request_id` in + `program.last_transition` and keeps it from `stopping` to `stopped`. +4. Wait for the journal (the line itself is immediate; the program stops in the background): + - `ok`: read the state again; the ticket completes when the app reports `stopped` with this + request id, possibly already in this read (a terminal event before the response); + - a failed line: if the program is no longer running the stop is moot (`not_running`), + otherwise the ticket fails with the app's error; + - no journal in time: if the request is still in the inbox it is withdrawn and the ticket is + `refused` with `timeout` (nothing was sent); if the app took it, the ticket stays pending + and resolves from the state as above. + +No caller string reaches the inbox: the request id is a checked UUID and the rest is fixed text. +""" + +from __future__ import annotations + +import os +import time +from pathlib import Path +from typing import Any, Callable, Dict, List, Optional + +from pa_lab import control, shot +from pa_lab.lab_reader import ConsoleReader, Unavailable + +STOP_ANSWER_MS = 5000 +JOURNAL_POLL_S = 0.05 + +__all__ = ['stop_program', 'request_text'] + + +def request_text(owner: str, request_id: str, commands: List[str]) -> str: + """A channel request that claims the channel for `owner` and runs `commands` under it. + + `owner T` must be the first line and `request ` follows (Lab.md "Requests"); + `owner claim T` succeeds when the channel is free or already T's. + """ + return ''.join('{}\n'.format(line) for line in + ['owner ' + owner, 'request ' + request_id, 'owner claim ' + owner] + commands) + + +def _send(lab_dir: Path, name: str, text: str) -> Path: + part = lab_dir / 'outbox' / (name + '.part') + inbox = lab_dir / 'inbox' / (name + '.txt') + part.write_text(text, encoding='utf-8') + os.replace(part, inbox) + return inbox + + +def _journal(reader: ConsoleReader, sleep: Callable[[float], None], deadline: float, name: str) -> Optional[List[str]]: + path = reader.lab_dir / 'outbox' / (name + '.out') + while True: + if path.exists(): + lines = path.read_text(encoding='utf-8', errors='replace').splitlines() + if lines and lines[-1] == 'end': + return lines + if reader.now() >= deadline: + return None + sleep(JOURNAL_POLL_S) + + +def _withdrawn(inbox: Path) -> bool: + """True when the request was still in the inbox and is now gone: the app never saw it.""" + try: + os.remove(inbox) + return True + except FileNotFoundError: + return False + + +def _not_running(app: Dict[str, Any]) -> Dict[str, Any]: + program = app['program'] + return {'outcome': 'not_running', 'instance_id': app['instance']['id'], 'run_id': program['run_id'], + 'program_state': program['state']} + + +def stop_program(plane: control.ControlPlane, reader: ConsoleReader, client_id: str, request: Dict[str, Any], + owner: str, sleep: Callable[[float], None] = time.sleep) -> Dict[str, Any]: + """Runs one stop_program request; returns its request_record (pending, completed, refused or failed). + + Raises control.Refused for a request that cannot be keyed (bad console, request id or + arguments, or an id reused with other arguments); those are not stored. + """ + started = reader.now() + try: + app = reader.app_state() + except Unavailable as e: + app, unavailable = None, e + else: + plane.observe(reader.console, app) + + def decide(lease_row) -> Optional[Dict[str, Any]]: + if app is None: + refusal = unavailable.refusal() + raise control.Refused(refusal.pop('code'), refusal.pop('message'), **refusal) + if app['program']['state'] != 'running': + return _not_running(app) + return None + + record, send = plane.begin_action(client_id, request, None if app is None else app['instance']['id'], decide) + if not send: + return record + request_id = record['request_id'] + name = 'palab_stop_program_{}'.format(request_id.replace('-', '')) + inbox = _send(reader.lab_dir, name, request_text(owner, request_id, ['stop'])) + lines = _journal(reader, sleep, started + (STOP_ANSWER_MS + shot.ANSWER_GRACE_MS) / 1000.0, name) + if lines is None: + if _withdrawn(inbox): + return plane.resolve_ticket(client_id, 'stop_program', request_id, refusal={ + 'code': 'timeout', 'message': 'The app did not take the stop request in time; nothing was sent.', + 'evidence': {'request': name}}, acted=False) + return plane.record(client_id, 'stop_program', request_id) + errors = [line for line in lines if line.startswith('error ')] + if errors: + try: + now = reader.app_state() + except Unavailable: + now = None + if now is not None and now['instance']['id'] == app['instance']['id'] and \ + now['program']['state'] != 'running': + reader.console_state() + return plane.resolve_ticket(client_id, 'stop_program', request_id, result=_not_running(now)) + return plane.resolve_ticket(client_id, 'stop_program', request_id, refusal={ + 'code': 'app_unavailable', 'message': "The app refused the stop: {}".format(errors[0]), + 'evidence': {'journal': lines}}) + reader.console_state() # applies observe: the stop may already be reported + return plane.record(client_id, 'stop_program', request_id) diff --git a/lab/server/pa_lab/config.py b/lab/server/pa_lab/config.py index d193e19e27..e0430e0ad8 100644 --- a/lab/server/pa_lab/config.py +++ b/lab/server/pa_lab/config.py @@ -1,5 +1,7 @@ """The daemon's own config (Slice 2 of fork #131): a one-entry allowlist (console B), the loopback port and the bearer token file. It never reads `~/BDSPLab/consoles.json`, which also lists A. +`channel_owner` (optional; default the profile name, which is what `lab/scripts/lc.sh` uses) is the +token the daemon claims the app's channel with before a leased action (Slice 5, Lab.md "Owner"). {"schema": 1, "host": "127.0.0.1", "port": 8765, "token_file": "~/.config/pa-lab/token", "db_file": "~/.local/state/pa-lab/control.sqlite", @@ -11,6 +13,7 @@ import json import os +import re from pathlib import Path import secrets import stat @@ -19,8 +22,9 @@ ALLOWED_CONSOLES = ('B',) LOOPBACK_HOSTS = ('127.0.0.1',) TOP_KEYS = ('schema', 'host', 'port', 'token_file', 'db_file', 'consoles') +OWNER_RE = re.compile(r'^[A-Za-z0-9_.-]{1,64}$') DEFAULT_DB_FILE = '~/.local/state/pa-lab/control.sqlite' -CONSOLE_KEYS = ('lab_dir', 'profile') +CONSOLE_KEYS = ('lab_dir', 'profile', 'channel_owner') class ConfigError(ValueError): @@ -28,9 +32,10 @@ class ConfigError(ValueError): class ConsoleConfig: - def __init__(self, lab_dir: Path, profile: Optional[str]): + def __init__(self, lab_dir: Path, profile: Optional[str], channel_owner: Optional[str] = None): self.lab_dir = lab_dir self.profile = profile + self.channel_owner = channel_owner if channel_owner is not None else profile class Config: @@ -85,7 +90,11 @@ def load(path: Path) -> Config: profile = entry.get('profile') if profile is not None and (not isinstance(profile, str) or not profile): raise ConfigError('{}.profile: expected a profile name'.format(field)) - out[name] = ConsoleConfig(_path(entry.get('lab_dir'), field + '.lab_dir'), profile) + owner = entry.get('channel_owner', profile) + if owner is not None and (not isinstance(owner, str) or not OWNER_RE.match(owner)): + raise ConfigError('{}.channel_owner: expected one word of A-Z a-z 0-9 _ . - (it defaults to the ' + 'profile)'.format(field)) + out[name] = ConsoleConfig(_path(entry.get('lab_dir'), field + '.lab_dir'), profile, owner) return Config(host, port, _path(doc.get('token_file'), 'token_file'), out, _path(doc.get('db_file', DEFAULT_DB_FILE), 'db_file')) diff --git a/lab/server/pa_lab/control.py b/lab/server/pa_lab/control.py index 60ea27fb8b..f932432f9a 100644 --- a/lab/server/pa_lab/control.py +++ b/lab/server/pa_lab/control.py @@ -17,6 +17,11 @@ - **Reconciliation.** `observe(app)` is applied whenever the daemon reads the app's state and once at start: it applies each new transition exactly once (UI takeover, `stopped` events) and ends a running lease whose app instance is gone. +- **Leased actions** (Slice 5). `begin_action` checks the lease and the action's own + precondition and stores the call once: refused, completed at once, or a `pending` ticket that + remembers the app instance it was sent to. `observe` resolves the ticket from what the app + reports (`_resolve_actions`): the app's terminal transition, not the tool's reply, is the + completion. """ from __future__ import annotations @@ -27,7 +32,7 @@ import sqlite3 import threading import time -from typing import Any, Dict, Optional, Sequence, Tuple +from typing import Any, Callable, Dict, Optional, Sequence, Tuple from pa_lab import contracts, timestamps from pa_lab.db import Database @@ -37,6 +42,7 @@ DEFAULT_PAGE = 100 MAX_PAGE = 500 POLL_S = 0.2 # another process's writes are seen by polling; this process's wake the waiters +ACTION_TOOLS = ('stop_program',) LEASE_COLUMNS = frozenset({ @@ -137,11 +143,13 @@ def request_status(self, client_id: str, console: Any, request_id: str) -> Dict[ return record def next_events(self, client_id: str, console: str, after_seq: Any, timeout_s: Any = 0, - limit: Any = DEFAULT_PAGE) -> Dict[str, Any]: + limit: Any = DEFAULT_PAGE, refresh: Optional[Callable[[], Any]] = None) -> Dict[str, Any]: """Events with seq > after_seq, oldest first, waiting up to timeout_s (<= 60) for one. `after_seq` is also the client's confirmed position: compaction keeps everything after it, so a client that lost a response asks again with the same cursor and loses nothing. + `refresh` (the server's read of the app, which applies `observe`) runs before each look, so + a run's end or a pending action's terminal transition becomes an event while a client waits. """ self._check_console(console) after_seq = self._int_arg('after_seq', after_seq, 0, None) @@ -166,6 +174,8 @@ def next_events(self, client_id: str, console: str, after_seq: Any, timeout_s: A (client_id, console, after_seq, self._stamp())) deadline = time.monotonic() + timeout_s while True: + if refresh is not None: + refresh() rows = self.db.read().execute( 'SELECT * FROM events WHERE console = ? AND seq > ? ORDER BY seq LIMIT ?', (console, after_seq, limit)).fetchall() @@ -224,24 +234,71 @@ def open_ticket(self, client_id: str, request: Dict[str, Any]) -> Dict[str, Any] return self._record(self._request_row(conn, client_id, req['tool'], req['request_id'])) def resolve_ticket(self, client_id: str, tool: str, request_id: str, result: Optional[Dict[str, Any]] = None, - refusal: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: - """Completes (result) or fails (refusal) a pending ticket once; later calls return the record.""" + refusal: Optional[Dict[str, Any]] = None, acted: bool = True) -> Dict[str, Any]: + """Completes (result) or fails (refusal) a pending ticket once; later calls return the record. + + A refusal is `failed` (after acting) unless `acted` is False: then nothing reached the app + and the record is `refused`, as if it had been refused before acting. + """ if (result is None) == (refusal is None): raise ValueError('resolve_ticket needs exactly one of result and refusal') with self._writing() as conn: row = self._request_row(conn, client_id, tool, request_id) if row is None: raise Refused('invalid_arguments', 'No ticket {}.'.format(request_id), field='request_id') - if row['status'] != 'pending': - return self._record(row) - status = 'completed' if refusal is None else 'failed' - conn.execute('UPDATE requests SET status = ?, completed_at = ?, result = ?, refusal = ? ' - 'WHERE client_id = ? AND tool = ? AND request_id = ?', - (status, self._stamp(), None if result is None else _json(result), - None if refusal is None else _json(refusal), client_id, tool, request_id)) - record = self._record(self._request_row(conn, client_id, tool, request_id)) - self._request_event(conn, row['console'], request_id, tool, result, refusal) - return record + self._resolve(conn, row, result, refusal, acted) + return self._record(self._request_row(conn, client_id, tool, request_id)) + + def record(self, client_id: str, tool: str, request_id: str) -> Dict[str, Any]: + """One request record as stored (the lease token never is).""" + row = self.db.read().execute('SELECT * FROM requests WHERE client_id = ? AND tool = ? AND request_id = ?', + (client_id, tool, request_id)).fetchone() + if row is None: + raise Refused('invalid_arguments', 'No request {}.'.format(request_id), field='request_id') + return self._record(row) + + # ---- leased actions (Slice 5) -------------------------------------------------------------- + + def begin_action(self, client_id: str, request: Dict[str, Any], instance_id: str, + decide: Callable[[sqlite3.Row], Optional[Dict[str, Any]]]) -> Tuple[Dict[str, Any], bool]: + """Stores one leased action call once and says whether the caller must now send it. + + In one transaction: an exact retry gets its stored record (and is not sent again); the + lease must be held by the request's token (an idle lease is renewed by the call); then + `decide(lease_row)` raises Refused (stored `refused`), returns a result (stored `completed`: + nothing to do), or returns None: the record is a `pending` ticket bound to `instance_id`, + and the second value is True. Raises Refused only for a request that cannot be keyed. + """ + req, args, token_hash = self._parse_request(client_id, request) + if req['tool'] not in ACTION_TOOLS: + raise Refused('invalid_arguments', '{} is not served yet.'.format(req['tool']), field='tool') + console = req['console'] + with self._writing() as conn: + existing = self._existing(conn, req, args, token_hash) + if existing is not None: + return existing, False + self._expire_due(conn, console) + stamp = self._stamp() + try: + row = self._held(conn, console, token_hash) + if row['state'] == 'agent_idle': + conn.execute('UPDATE leases SET expires_at = ?, updated_at = ? WHERE console = ?', + (timestamps.format(self.now() + row['ttl_s']), stamp, console)) + result, refusal = decide(self._lease_row(conn, console)), None + except Refused as e: + result, refusal = None, e.refusal + status = 'refused' if refusal is not None else ('pending' if result is None else 'completed') + conn.execute('INSERT INTO requests (client_id, tool, request_id, console, token_hash, status, created_at, ' + 'completed_at, arguments, result, refusal, instance_id) ' + 'VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', + (client_id, req['tool'], req['request_id'], console, token_hash, status, stamp, + None if status == 'pending' else stamp, _json(args), + None if result is None else _json(result), None if refusal is None else _json(refusal), + instance_id)) + if status != 'pending': + self._request_event(conn, console, req['request_id'], req['tool'], result, refusal) + return self._record(self._request_row(conn, client_id, req['tool'], req['request_id'])), \ + status == 'pending' # ---- runs and the operator ---------------------------------------------------------------- @@ -286,7 +343,8 @@ def observe(self, console: str, app: Dict[str, Any]) -> Dict[str, Any]: - a new UI transition revokes any agent lease and installs the user lease (no timeout); - a new stop transition is a `stopped` event with its source; - a running lease ends (back to agent_idle with a fresh TTL) when its run's stop is - reported or its app instance is gone. + reported or its app instance is gone; + - a pending leased action resolves from the app's terminal transition (`_resolve_actions`). """ self._check_console(console) instance = app['instance']['id'] @@ -310,6 +368,7 @@ def observe(self, console: str, app: Dict[str, Any]) -> Dict[str, Any]: instance_id=instance, request_id=transition['request_id'], at=transition['at']) if transition['source'] == 'ui': self._take_over(conn, console, transition['at'], 'ui_takeover', instance) + self._resolve_actions(conn, console, app) conn.execute('INSERT OR REPLACE INTO observations (console, instance_id, transition_key, program_state, ' 'observed_at) VALUES (?, ?, ?, ?, ?)', (console, instance, key if transition is not None else @@ -447,6 +506,58 @@ def _request_event(self, conn, console, request_id, tool, result, refusal) -> No self._append(conn, 'request_failed', console, {'request_id': request_id, 'tool': tool, 'refusal': refusal}, request_id=request_id) + def _resolve(self, conn, row: sqlite3.Row, result: Optional[Dict[str, Any]], refusal: Optional[Dict[str, Any]], + acted: bool = True) -> None: + """Completes or fails one pending record, once; a resolved record is left as it is.""" + if row['status'] != 'pending': + return + status = 'completed' if refusal is None else ('failed' if acted else 'refused') + conn.execute('UPDATE requests SET status = ?, completed_at = ?, result = ?, refusal = ? ' + 'WHERE client_id = ? AND tool = ? AND request_id = ?', + (status, self._stamp(), None if result is None else _json(result), + None if refusal is None else _json(refusal), row['client_id'], row['tool'], row['request_id'])) + self._request_event(conn, row['console'], row['request_id'], row['tool'], result, refusal) + + def _resolve_actions(self, conn, console: str, app: Dict[str, Any]) -> None: + """Resolves the console's pending stop_program tickets from what the app reports. + + - another app instance than the one the stop was sent to: failed, `instance_replaced`; + - a UI Start/Stop at or after the call: failed, the user holds the console; + - the stop transition carrying the ticket's request id, and the program `stopped`: + completed (`outcome: stopped`); while `stopping` the ticket stays pending; + - the program ended by itself (`program`/`error`) at or after the call: completed + (`outcome: ended`), since that is the run's terminal event. + Timestamps compare as strings: both are UTC with milliseconds and `Z`. + """ + rows = conn.execute("SELECT * FROM requests WHERE console = ? AND status = 'pending' AND tool = 'stop_program'", + (console,)).fetchall() + instance = app['instance']['id'] + program = app['program'] + transition = program['last_transition'] + for row in rows: + if row['instance_id'] != instance: + self._resolve(conn, row, None, { + 'code': 'app_unavailable', 'message': 'The app restarted before the stop was confirmed.', + 'evidence': {'reason': 'instance_replaced', 'instance_id': row['instance_id'], + 'new_instance_id': instance}}) + continue + if transition is None or (transition['at'] < row['created_at'] and + transition['request_id'] != row['request_id']): + continue + done = {'outcome': 'stopped', 'instance_id': instance, 'run_id': program['run_id'], + 'source': transition['source'], 'stopped_at': transition['at'], 'program_state': program['state']} + if transition['source'] == 'ui': + self._resolve(conn, row, None, { + 'code': 'console_held_by_user', 'message': 'The user clicked {} in the app at {}.'.format( + transition['action'].capitalize(), _clock_time(transition['at'])), + 'evidence': {'since': transition['at']}}) + elif program['state'] != 'stopped' or transition['action'] != 'stop': + continue + elif transition['source'] == 'lab' and transition['request_id'] == row['request_id']: + self._resolve(conn, row, done, None) + elif transition['source'] in ('program', 'error'): + self._resolve(conn, row, dict(done, outcome='ended'), None) + # ---- lease rows @staticmethod diff --git a/lab/server/pa_lab/db.py b/lab/server/pa_lab/db.py index 6624b6e8bf..394ac71a74 100644 --- a/lab/server/pa_lab/db.py +++ b/lab/server/pa_lab/db.py @@ -86,6 +86,11 @@ )""", "CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)", ], + # 2 (Slice 5): the app instance a leased action was sent to, so a pending ticket fails when that + # instance is gone rather than waiting for a transition that can no longer come. + [ + "ALTER TABLE requests ADD COLUMN instance_id TEXT", + ], ] SCHEMA_VERSION = len(MIGRATIONS) diff --git a/lab/server/pa_lab/mcp_server.py b/lab/server/pa_lab/mcp_server.py index ac00a68b34..157ade13b4 100644 --- a/lab/server/pa_lab/mcp_server.py +++ b/lab/server/pa_lab/mcp_server.py @@ -7,8 +7,8 @@ Resources: `console://B/state` (console_state), `console://B/save` (save_resource). 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. +`renew_console`, `release_console`, `next_events`, `request_status` and the first leased action, +`stop_program` (Slice 5, pa_lab/actions.py). Nothing here starts a program or presses a button yet. """ from __future__ import annotations @@ -23,9 +23,10 @@ import re import secrets import threading +import time from typing import Any, Callable, Dict, Optional, Tuple -from pa_lab import app_query, contracts, control, shot, tools +from pa_lab import actions, app_query, contracts, control, shot, tools from pa_lab.lab_reader import ConsoleReader, Unavailable LOG = logging.getLogger('pa_lab.server') @@ -49,7 +50,8 @@ '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. describe_program gives the selected program\'s option contract; ' - 'game_open says whether a game is in front. Unknown observations are never success.') + 'game_open says whether a game is in front. Unknown observations are never success. ' + 'stop_program (with a lease) returns a ticket: follow it with request_status or next_events.') TOOL_LIST = [ { @@ -158,12 +160,21 @@ def _schema(properties: Dict[str, Any], required) -> Dict[str, Any]: 'limit': {'type': 'integer', 'minimum': 1, 'maximum': control.MAX_PAGE, 'default': control.DEFAULT_PAGE}}, ['after_seq']), 'annotations': _READ}, + {'name': 'stop_program', 'title': 'Stop the running program', + 'description': 'Asks the app to stop the running program, once, under your lease. Returns the request record: ' + 'pending until the app reports the program stopped by this request (completed, outcome ' + 'stopped), or the run ended by itself (outcome ended); completed at once with outcome ' + 'not_running when nothing runs. Follow it with request_status or next_events. Fails if ' + 'the user takes the console or the app restarts first.', + 'inputSchema': _schema({'request_id': _REQUEST_ID, 'lease_token': _LEASE_TOKEN}, + ['request_id', 'lease_token']), 'annotations': _MUTATING}, {'name': 'request_status', 'title': 'Request or ticket status', 'description': "This client's request record: pending, completed, refused or failed.", 'inputSchema': _schema({'request_id': _REQUEST_ID}, ['request_id']), 'annotations': _READ}, ] LEASE_TOOLS = ('acquire_console', 'renew_console', 'release_console') +REQUEST_TOOLS = LEASE_TOOLS + control.ACTION_TOOLS # keyed by request_id; refusals echo it class RpcError(Exception): @@ -188,10 +199,14 @@ class LabMcp: def __init__(self, consoles: Dict[str, ConsoleReader], take_shot: Callable[..., Dict[str, Any]] = shot.take_shot, - control_plane: Optional[control.ControlPlane] = None): + control_plane: Optional[control.ControlPlane] = None, + channel_owners: Optional[Dict[str, str]] = None, + sleep: Callable[[float], None] = time.sleep): self.consoles = consoles self.take_shot = take_shot self.control = control_plane + self.channel_owners = channel_owners or {} + self.sleep = sleep def call(self, method: str, params: Dict[str, Any], client: str = 'unnamed') -> Dict[str, Any]: if method == 'ping': @@ -299,25 +314,56 @@ def _call_control(self, client: str, name: str, arguments: Any) -> Dict[str, Any if 'after_seq' not in args: raise control.Refused('invalid_arguments', 'required', field='after_seq') result = self.control.next_events(client, console, args['after_seq'], args.get('timeout_s', 0), - args.get('limit', control.DEFAULT_PAGE)) + args.get('limit', control.DEFAULT_PAGE), + refresh=self._refresher(console)) elif name == 'request_status': if set(args) != {'request_id'} or request_id is None: raise control.Refused('invalid_arguments', 'expects request_id', field='request_id') + self._refresher(console)() result = self.control.request_status(client, console, request_id) + elif name in control.ACTION_TOOLS: + reader = self._console(console) + owner = self.channel_owners.get(console) + if reader is None: + raise control.Refused('console_not_allowed', 'Console {!r} is not served; only {}.'.format( + console, ', '.join(sorted(self.consoles)))) + if owner is None: + raise control.Refused('app_unavailable', 'No channel owner is configured for console {}; ' + 'set consoles.{}.channel_owner or profile.'.format(console, console)) + record = actions.stop_program(self.control, reader, client, self._request(name, console, args), + owner, sleep=self.sleep) + if record['refusal'] is not None: + return self._refused(name, record['refusal'], record['request_id']) + result = record else: - request = {'schema': 1, 'request_id': args.pop('request_id', None), 'tool': name, - 'console': console, 'arguments': args} - if 'lease_token' in args: - request['lease_token'] = args.pop('lease_token') - record = self.control.execute(client, request) + record = self.control.execute(client, self._request(name, console, args)) if record['refusal'] is not None: return self._refused(name, record['refusal'], record['request_id']) result = record except control.Refused as e: - return self._refused(name, e.refusal, request_id if name in LEASE_TOOLS else None) + return self._refused(name, e.refusal, request_id if name in REQUEST_TOOLS else None) return {'content': [{'type': 'text', 'text': _json_text(result)}], 'structuredContent': result, 'isError': False} + @staticmethod + def _request(name: str, console: Any, args: Dict[str, Any]) -> Dict[str, Any]: + """The request document of a keyed call; the lease token goes beside the arguments.""" + args = dict(args) + request = {'schema': 1, 'request_id': args.pop('request_id', None), 'tool': name, 'console': console, + 'arguments': args} + if 'lease_token' in args: + request['lease_token'] = args.pop('lease_token') + return request + + def _refresher(self, console: Any) -> Callable[[], None]: + """Reads the console's state, which applies `observe` (run ends, pending action tickets).""" + reader = self._console(console) + + def refresh() -> None: + if reader is not None: + reader.console_state() + return refresh + @staticmethod def _refused(tool: str, refusal: Dict[str, Any], request_id: Optional[str] = None) -> Dict[str, Any]: try: diff --git a/lab/server/tests/fake_lab.py b/lab/server/tests/fake_lab.py index 060795fcf0..00c377c820 100644 --- a/lab/server/tests/fake_lab.py +++ b/lab/server/tests/fake_lab.py @@ -111,6 +111,12 @@ class FakeApp: `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. + + A request ending in `stop` (Slice 5's stop_program) is run as the channel does: the `owner` + first line must match a claimed `channel_owner` (or the channel is free), `owner claim T` + takes it, and `stop` is refused unless the program is `running`. Otherwise the program goes + `stopping` with `last_transition {stop, lab, }` and, at the next tick (or at once + with `stop_at_once`), `stopped`. `stop_silent` takes the request without writing a journal. """ def __init__(self, lab, clock): @@ -130,6 +136,9 @@ def __init__(self, lab, clock): } self.line_errors = {} self.restart_on = None + self.channel_owner = None + self.stop_at_once = False + self.stop_silent = False self.requests = [] self.pending = [] clock.on_sleep.append(self.tick) @@ -142,6 +151,8 @@ def tick(self): changes['video.state'] = 'live' changes['video.captured_at'] = now self.lab.update_state(**changes) + if self.lab.state['program']['state'] == 'stopping': + self.lab.update_state(**{'program.state': 'stopped'}) for pending in list(self.pending): self.continue_snapshot(pending) if self.serve: @@ -154,6 +165,9 @@ def pick_up(self, request): self.requests.append(text) line = text.splitlines()[-1] words = line.split() + if words == ['stop']: + self.stop(request.stem, text.splitlines()) + return if words[0] in self.replies: self.answer(request.stem, line, words[0]) return @@ -176,6 +190,29 @@ def answer(self, name, line, command): else: self.finish(pending, self.replies[command]) + def stop(self, name, lines): + if self.stop_silent: + return + owner = lines[0].split()[1] + request_id = lines[1].split()[1] + out = (self.lab.dir / 'outbox' / (name + '.out')) + if self.channel_owner not in (None, owner): + out.write_text('error 3 (owner claim {}): owned by {}\nend\n'.format(owner, self.channel_owner), + encoding='utf-8') + return + self.channel_owner = owner + state = self.lab.state['program']['state'] + if state != 'running': + out.write_text('ok 3 owner claim {} @0-1ms\nerror 4 (stop): the program is {}, not RUNNING\nend\n'.format( + owner, state.upper()), encoding='utf-8') + return + self.lab.update_state(**{ + 'program.state': 'stopped' if self.stop_at_once else 'stopping', + 'program.last_transition': {'action': 'stop', 'source': 'lab', 'request_id': request_id, + 'at': timestamps.format(self.clock.now())}, + 'channel.owner_claimed': True}) + out.write_text('ok 3 owner claim {} @0-1ms\nok 4 stop @1-2ms\nend\n'.format(owner), encoding='utf-8') + 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_actions.py b/lab/server/tests/test_actions.py new file mode 100644 index 0000000000..30b0fccd2c --- /dev/null +++ b/lab/server/tests/test_actions.py @@ -0,0 +1,291 @@ +"""The first leased action, stop_program (Slice 5 of fork #131), against a fake app in a temp +`Lab/` folder: the ticket, the channel request it sends, and how the app's own report resolves +it, including the races the design names (duplicate requests, UI takeover, lease loss, app +restart, a terminal event before the response). No real profile or console is touched. + +Run from the repo root: python3 -m unittest discover -s lab/server/tests -t lab/server -v +""" + +import sqlite3 +import unittest + +from pa_lab import actions, control, db, lab_reader, mcp_server, timestamps +from tests.control_fixtures import START, acquire, app_state, clock, new_id, open_plane, temp_db_path, transition +from tests.fake_lab import FakeApp, FakeLab + +CLIENT = 'claude:frlg-lane' +OWNER = 'lab-B' +NEW_INSTANCE = '0b5e3f6c-9d2a-4e71-8c40-6f1a2b3c4d5e' + + +def stop_request(token, request_id=None): + request = {'schema': 1, 'request_id': request_id or new_id(), 'tool': 'stop_program', 'console': 'B', + 'arguments': {}} + if token is not None: + request['lease_token'] = token + return request + + +class ActionTest(unittest.TestCase): + def setUp(self): + self.clock = clock() + self.path = temp_db_path(self) + self.plane = open_plane(self, self.path, self.clock) + self.lab = FakeLab(self) + self.write_app(state='running', last=transition('start', 'lab', '2026-11-14T05:59:00.000Z', new_id())) + self.app = FakeApp(self.lab, self.clock) + self.reader = self.make_reader() + + def make_reader(self): + return lab_reader.ConsoleReader('B', self.lab.dir, profile='lab-B', now=self.clock.now, + pid_alive=lambda pid: True, control=self.plane) + + def write_app(self, state, last): + doc = app_state(last, state) + doc['written_at'] = START + doc['video']['captured_at'] = START + self.lab.write_state(doc) + + def acquired(self): + record = self.plane.execute(CLIENT, acquire()) + self.assertEqual(record['status'], 'completed', record) + return record['result']['lease_token'] + + def stop(self, token, request_id=None): + return actions.stop_program(self.plane, self.reader, CLIENT, stop_request(token, request_id), OWNER, + sleep=self.clock.sleep) + + def tick(self): + self.clock.sleep(0.5) + self.reader.console_state() + + def status(self, request_id): + return self.plane.request_status(CLIENT, 'B', request_id) + + def stop_requests(self): + return [text for text in self.app.requests if text.rstrip().endswith('stop')] + + def events(self): + return self.plane.next_events('reader', 'B', 0)['events'] + + +class StopTests(ActionTest): + def test_a_stop_is_pending_until_the_app_reports_it_stopped(self): + token = self.acquired() + request_id = new_id() + record = self.stop(token, request_id) + self.assertEqual(record['status'], 'pending') + self.assertEqual(self.lab.state['program']['state'], 'stopping') + self.tick() + record = self.status(request_id) + self.assertEqual(record['status'], 'completed') + self.assertEqual((record['result']['outcome'], record['result']['source']), ('stopped', 'lab')) + self.assertEqual(self.stop_requests(), ['owner lab-B\nrequest {}\nowner claim lab-B\nstop\n'.format(request_id)]) + last = self.events()[-1] + self.assertEqual((last['type'], last['payload']['tool'], last['request_id']), + ('request_completed', 'stop_program', request_id)) + + def test_the_stop_ends_a_running_lease(self): + token = self.acquired() + self.plane.begin_run('B', token, new_id(), self.lab.state['instance']['id']) + self.stop(token) + self.tick() + lease = self.plane.lease('B') + self.assertEqual(lease['state'], 'agent_idle') + reasons = [e['payload'].get('reason') for e in self.events() if e['type'] == 'lease_changed'] + self.assertEqual(reasons[-1], 'run_ended') + + def test_a_terminal_event_before_the_response_is_the_response(self): + self.app.stop_at_once = True + record = self.stop(self.acquired()) + self.assertEqual((record['status'], record['result']['outcome']), ('completed', 'stopped')) + + def test_an_exact_retry_sends_nothing_again(self): + token = self.acquired() + request_id = new_id() + first = self.stop(token, request_id) + again = self.stop(token, request_id) + self.assertEqual(again['status'], first['status']) + self.tick() + self.assertEqual(self.stop(token, request_id), self.status(request_id)) + self.assertEqual(len(self.stop_requests()), 1) + + def test_a_retry_after_a_daemon_restart_gets_the_same_record(self): + token = self.acquired() + request_id = new_id() + self.stop(token, request_id) + self.plane = open_plane(self, self.path, self.clock) + self.reader = self.make_reader() + self.tick() # the new daemon's first read resolves the ticket + self.assertEqual(self.stop(token, request_id)['status'], 'completed') + self.assertEqual(len(self.stop_requests()), 1) + + def test_nothing_running_completes_at_once_and_sends_nothing(self): + self.lab.update_state(**{'program.state': 'stopped'}) + record = self.stop(self.acquired()) + self.assertEqual((record['status'], record['result']['outcome']), ('completed', 'not_running')) + self.assertEqual(self.stop_requests(), []) + + def test_refused_before_acting_sends_nothing(self): + self.acquired() + cases = [ + dict(name='no lease token', input=None, expectation='invalid_arguments'), + dict(name='a token that does not hold the console', input='not-the-token', expectation='lease_invalid'), + ] + for case in cases: + with self.subTest(case['name']): + if case['input'] is None: + with self.assertRaises(control.Refused) as caught: + self.stop(None) + self.assertEqual(caught.exception.refusal['code'], case['expectation']) + else: + record = self.stop(case['input']) + self.assertEqual((record['status'], record['refusal']['code']), ('refused', case['expectation'])) + self.assertEqual(self.stop_requests(), []) + + def test_a_ui_click_before_the_call_takes_the_console(self): + token = self.acquired() + self.lab.update_state(**{'program.last_transition': transition('start', 'ui', START)}) + record = self.stop(token) + self.assertEqual((record['status'], record['refusal']['code']), ('refused', 'console_held_by_user')) + self.assertEqual(self.stop_requests(), []) + + def test_an_expired_lease_is_refused(self): + token = self.acquired() + self.clock.t += 1201 + self.lab.update_state(written_at=timestamps.format(self.clock.now())) + record = self.stop(token) + self.assertEqual(record['refusal']['code'], 'lease_expired') + + def test_an_unavailable_app_is_refused(self): + token = self.acquired() + self.clock.t += 60 # no heartbeat for a minute + record = self.stop(token) + self.assertEqual((record['status'], record['refusal']['code']), ('refused', 'app_unavailable')) + + +class RaceTests(ActionTest): + def test_a_ui_stop_after_the_request_fails_the_ticket_and_hands_over(self): + token = self.acquired() + request_id = new_id() + self.stop(token, request_id) + self.lab.update_state(**{'program.last_transition': transition( + 'stop', 'ui', timestamps.format(self.clock.now()))}) + self.tick() + record = self.status(request_id) + self.assertEqual((record['status'], record['refusal']['code']), ('failed', 'console_held_by_user')) + self.assertEqual(self.plane.lease('B')['state'], 'user') + + def test_an_app_restart_before_the_stop_is_confirmed_fails_the_ticket(self): + token = self.acquired() + request_id = new_id() + self.stop(token, request_id) + self.lab.update_state(**{'instance.id': NEW_INSTANCE, 'program.state': 'stopped', + 'program.last_transition': None}) + self.tick() + record = self.status(request_id) + self.assertEqual((record['status'], record['refusal']['evidence']['reason']), ('failed', 'instance_replaced')) + + def test_a_run_that_ends_by_itself_completes_the_ticket(self): + token = self.acquired() + self.app.stop_silent = True # the app took the request but has not answered yet + request_id = new_id() + self.assertEqual(self.stop(token, request_id)['status'], 'pending') + self.lab.update_state(**{'program.state': 'stopped', 'program.last_transition': transition( + 'stop', 'program', timestamps.format(self.clock.now()))}) + self.tick() + record = self.status(request_id) + self.assertEqual((record['status'], record['result']['outcome']), ('completed', 'ended')) + + def test_a_request_the_app_took_but_did_not_answer_stays_pending_until_reported(self): + token = self.acquired() + self.app.stop_silent = True + request_id = new_id() + self.assertEqual(self.stop(token, request_id)['status'], 'pending') + self.lab.update_state(**{'program.state': 'stopped', 'program.last_transition': transition( + 'stop', 'lab', timestamps.format(self.clock.now()), request_id)}) + self.tick() + self.assertEqual(self.status(request_id)['result']['outcome'], 'stopped') + + def test_a_busy_app_gets_the_request_withdrawn(self): + self.app.serve = False + record = self.stop(self.acquired()) + self.assertEqual((record['status'], record['refusal']['code']), ('refused', 'timeout')) + self.assertEqual(list((self.lab.dir / 'inbox').iterdir()), []) + + def test_a_channel_owned_by_another_script_fails_the_ticket(self): + self.app.channel_owner = 'someone-else' + record = self.stop(self.acquired()) + self.assertEqual((record['status'], record['refusal']['code']), ('failed', 'app_unavailable')) + self.assertIn('owned by someone-else', record['refusal']['message']) + + def test_a_run_that_ended_just_before_the_stop_line_is_its_end(self): + token = self.acquired() + original = self.app.stop + + def end_first(name, lines): + self.lab.update_state(**{'program.state': 'stopped', 'program.last_transition': transition( + 'stop', 'program', timestamps.format(self.clock.now()))}) + original(name, lines) + self.app.stop = end_first + record = self.stop(token) + self.assertEqual((record['status'], record['result']['outcome']), ('completed', 'ended')) + self.assertEqual(record['result']['source'], 'program') + + +class McpTests(ActionTest): + def setUp(self): + super().setUp() + self.mcp = mcp_server.LabMcp({'B': self.reader}, control_plane=self.plane, channel_owners={'B': OWNER}, + sleep=self.clock.sleep) + + def call(self, name, **arguments): + return self.mcp.call('tools/call', {'name': name, 'arguments': dict(arguments, console='B')}, client=CLIENT) + + def test_stop_program_then_wait_for_its_event(self): + token = self.acquired() + request_id = new_id() + reply = self.call('stop_program', request_id=request_id, lease_token=token) + self.assertFalse(reply['isError']) + self.assertEqual(reply['structuredContent']['status'], 'pending') + head = self.plane.next_events('reader', 'B', 0)['next_after_seq'] + self.clock.sleep(0.5) # the app reports stopped; the next read applies it + page = self.call('next_events', after_seq=head)['structuredContent'] + self.assertEqual([(e['type'], e['request_id']) for e in page['events'] if e['type'].startswith('request_')], + [('request_completed', request_id)]) + self.assertEqual(self.call('request_status', request_id=request_id)['structuredContent']['status'], + 'completed') + + def test_a_refusal_echoes_the_request_id(self): + request_id = new_id() + reply = self.call('stop_program', request_id=request_id, lease_token='nope') + self.assertTrue(reply['isError']) + self.assertEqual(reply['structuredContent']['request_id'], request_id) + self.assertEqual(reply['structuredContent']['refusal']['code'], 'lease_invalid') + + def test_no_channel_owner_is_refused(self): + self.mcp.channel_owners = {} + reply = self.call('stop_program', request_id=new_id(), lease_token=self.acquired()) + self.assertEqual(reply['structuredContent']['refusal']['code'], 'app_unavailable') + self.assertEqual(self.stop_requests(), []) + + +class MigrationTest(unittest.TestCase): + def test_a_version_1_file_gains_the_ticket_instance_column(self): + path = temp_db_path(self) + path.parent.mkdir(parents=True) + conn = sqlite3.connect(str(path)) + for statement in db.MIGRATIONS[0]: + conn.execute(statement) + conn.execute('PRAGMA user_version = 1') + conn.commit() + conn.close() + database = db.Database(path) + self.addCleanup(database.close) + columns = [row[1] for row in database.read().execute('PRAGMA table_info(requests)')] + self.assertIn('instance_id', columns) + self.assertEqual(database.found_version, 1) + + +if __name__ == '__main__': + unittest.main() diff --git a/lab/server/tests/test_config.py b/lab/server/tests/test_config.py index e41e8b8293..81fd30b071 100644 --- a/lab/server/tests/test_config.py +++ b/lab/server/tests/test_config.py @@ -43,6 +43,11 @@ def test_refused_configs(self): dict(name='relative lab dir', input={'consoles.B': {'lab_dir': 'Lab'}}, expectation='consoles.B.lab_dir'), dict(name='unknown key', input={'mutations': True}, expectation='mutations'), dict(name='future schema', input={'schema': 2}, expectation='schema'), + dict(name='channel owner with a space', input={'consoles.B.channel_owner': 'lab B'}, + expectation='consoles.B.channel_owner'), + dict(name='profile unusable as the channel owner', + input={'consoles.B': {'lab_dir': '/x/Lab', 'profile': 'lab B'}}, + expectation='consoles.B.channel_owner'), ] for case in cases: with self.subTest(case['name']): @@ -57,6 +62,17 @@ def test_refused_configs(self): config.load(self.write(doc)) self.assertIn(case['expectation'], str(raised.exception)) + def test_the_channel_owner_defaults_to_the_profile(self): + cases = [ + dict(name='default', input={}, expectation='lab-B'), + dict(name='explicit', input={'channel_owner': 'pa-lab-daemon'}, expectation='pa-lab-daemon'), + ] + for case in cases: + with self.subTest(case['name']): + doc = self.good() + doc['consoles']['B'].update(case['input']) + self.assertEqual(config.load(self.write(doc)).consoles['B'].channel_owner, case['expectation']) + def test_token_file_is_owner_only(self): self.assertEqual(os.stat(self.token).st_mode & 0o777, 0o600) self.assertGreaterEqual(len(config.read_token(self.token)), 32) diff --git a/lab/server/tests/test_control_mcp.py b/lab/server/tests/test_control_mcp.py index edeeba05a3..7e562a1f78 100644 --- a/lab/server/tests/test_control_mcp.py +++ b/lab/server/tests/test_control_mcp.py @@ -46,7 +46,7 @@ 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', 'describe_program', 'game_open', 'acquire_console', 'renew_console', 'release_console', - 'next_events', 'request_status']) + 'next_events', 'stop_program', 'request_status']) def test_acquire_then_state_shows_the_lease_and_a_retry_matches(self): request_id = str(uuid.uuid4())