diff --git a/nanobot/channels/websocket/tests/test_websocket_http_routes.py b/nanobot/channels/websocket/tests/test_websocket_http_routes.py index c93d809d6..ade609824 100644 --- a/nanobot/channels/websocket/tests/test_websocket_http_routes.py +++ b/nanobot/channels/websocket/tests/test_websocket_http_routes.py @@ -18,7 +18,7 @@ from nanobot.channels.base import BaseChannel from nanobot.channels.websocket.runtime import WebSocketChannel, WebSocketConfig from nanobot.config.loader import load_config, save_config from nanobot.cron.service import CronService -from nanobot.cron.types import CronJob, CronPayload, CronSchedule +from nanobot.cron.types import CronJob, CronPayload, CronRunResult, CronSchedule from nanobot.optional_features import InstallResult from nanobot.security.workspace_access import WORKSPACE_SCOPE_METADATA_KEY from nanobot.session.keys import UNIFIED_SESSION_KEY @@ -2417,6 +2417,57 @@ async def test_session_delete_removes_unpersisted_new_chat( @pytest.mark.asyncio +async def test_webui_automation_result_is_authenticated_and_returns_only_selected_response( + bus: MagicMock, tmp_path: Path, +) -> None: + port = _free_port() + base_url = f"http://127.0.0.1:{port}" + + async def execute(job: CronJob) -> CronRunResult: + cron.write_run_record("selected-run", { + "job_id": job.id, "session_key": job.payload.session_key, + "status": "ok", "response": "Selected **reply**", "rendered_prompt": "private prompt", + }) + return CronRunResult(run_id="selected-run", response="Selected **reply**") + + cron = CronService(tmp_path / "cron" / "jobs.json", on_job=execute) + job = cron.add_job(name="Reminder", schedule=CronSchedule(kind="every", every_ms=86400000), + message="hi", session_key="websocket:abc", origin_channel="websocket", + origin_chat_id="abc") + assert await cron.run_job(job.id, force=True) + completed = cron.get_job(job.id) + assert completed is not None + run_at = completed.state.run_history[-1].run_at_ms + cron.register_system_job(CronJob(id="system", name="system", + schedule=CronSchedule(kind="every", every_ms=86400000), + payload=CronPayload(kind="system_event"))) + channel = _ch(bus, session_manager=_seed_session(tmp_path, key="websocket:abc"), + cron_service=cron, port=port) + server_task = asyncio.create_task(channel.start()) + try: + path = f"{base_url}/api/webui/automations/result?id={job.id}&run_at_ms={run_at}" + assert (await _http_get(path)).status_code == 401 + token = channel.gateway.tokens.issue_api_token(300) + auth = {"Authorization": f"Bearer {token}"} + result = await _http_get(path, headers=auth) + assert result.status_code == 200, result.text + assert result.json() == {"response": "Selected **reply**"} + listed = await _http_get(f"{base_url}/api/webui/automations", headers=auth) + assert "Selected **reply**" not in listed.text + for query, status in [ + (f"id={job.id}&run_at_ms=invalid", 400), + (f"id={job.id}&run_at_ms=0", 404), + (f"id=missing&run_at_ms={run_at}", 404), + (f"id=system&run_at_ms={run_at}", 403), + (f"id={job.id}&run_at_ms={run_at}&kind=invalid", 400), + ]: + response = await _http_get(f"{base_url}/api/webui/automations/result?{query}", headers=auth) + assert response.status_code == status + finally: + await channel.stop() + await server_task + + async def test_webui_automations_route_lists_all_jobs_and_allows_user_actions( bus: MagicMock, tmp_path: Path ) -> None: diff --git a/nanobot/cli/gateway_runtime.py b/nanobot/cli/gateway_runtime.py index 87a02c761..dff86e244 100644 --- a/nanobot/cli/gateway_runtime.py +++ b/nanobot/cli/gateway_runtime.py @@ -362,7 +362,7 @@ def _run_gateway( from nanobot.cron.bound_runner import run_bound_cron_job from nanobot.cron.service import CronJobSkippedError, CronService from nanobot.cron.session_turns import is_bound_cron_job - from nanobot.cron.types import CronJob + from nanobot.cron.types import CronJob, CronRunResult from nanobot.llm_usage import record_llm_call from nanobot.llm_usage.context import llm_usage_source from nanobot.providers.factory import ( @@ -553,7 +553,7 @@ def _run_gateway( message_tool.set_send_callback(_deliver_to_channel) # Set cron callback (needs agent) - async def on_cron_job(job: CronJob) -> str | None: + async def on_cron_job(job: CronJob) -> str | CronRunResult | None: """Execute a cron job through the agent.""" async def _silent(*_args: Any, **_kwargs: Any) -> None: pass diff --git a/nanobot/cron/bound_runner.py b/nanobot/cron/bound_runner.py index eff121a13..f1133490c 100644 --- a/nanobot/cron/bound_runner.py +++ b/nanobot/cron/bound_runner.py @@ -12,7 +12,7 @@ from nanobot.agent.tools.cron import CronTool from nanobot.bus.events import InboundMessage, OutboundMessage from nanobot.cron.session_delivery import origin_delivery_context from nanobot.cron.session_turns import CRON_DEFER_UNTIL_IDLE_META, CRON_TRIGGER_META -from nanobot.cron.types import CronJob +from nanobot.cron.types import CronJob, CronRunResult from nanobot.cron.webui_metadata import cron_proactive_delivery_metadata from nanobot.utils.prompt_templates import render_template @@ -67,7 +67,7 @@ async def run_bound_cron_job( *, agent: BoundCronAgent, cron: CronRunRecorder, -) -> str | None: +) -> CronRunResult: """Execute a session-bound cron job as a normal agent session turn.""" session_key = job.payload.session_key if not session_key: @@ -151,4 +151,4 @@ async def run_bound_cron_job( "response": response, }, ) - return response + return CronRunResult(run_id=run_id, response=response) diff --git a/nanobot/cron/service.py b/nanobot/cron/service.py index 6ef5aa1bc..0b19ce3b0 100644 --- a/nanobot/cron/service.py +++ b/nanobot/cron/service.py @@ -22,6 +22,7 @@ from nanobot.cron.types import ( CronJobState, CronPayload, CronRunRecord, + CronRunResult, CronSchedule, CronStore, ) @@ -176,7 +177,7 @@ class CronService: def __init__( self, store_path: Path, - on_job: Callable[[CronJob], Coroutine[Any, Any, str | None]] | None = None, + on_job: Callable[[CronJob], Coroutine[Any, Any, str | CronRunResult | None]] | None = None, max_sleep_ms: int = 300_000, # 5 minutes ): self.store_path = store_path @@ -413,6 +414,7 @@ class CronService: "status": r.status, "durationMs": r.duration_ms, "error": r.error, + "runId": r.run_id, } for r in j.state.run_history ], @@ -586,10 +588,11 @@ class CronService: """Execute a single job.""" start_ms = _now_ms() logger.info("Cron: executing job '{}' ({})", job.name, job.id) + result: str | CronRunResult | None = None try: if self.on_job: - await self.on_job(job) + result = await self.on_job(job) job.state.last_status = "ok" job.state.last_error = None @@ -620,6 +623,7 @@ class CronService: status=job.state.last_status, duration_ms=end_ms - start_ms, error=job.state.last_error, + run_id=result.run_id if isinstance(result, CronRunResult) else None, )) job.state.run_history = job.state.run_history[-self._MAX_RUN_HISTORY:] diff --git a/nanobot/cron/types.py b/nanobot/cron/types.py index 77273f547..789e7a72b 100644 --- a/nanobot/cron/types.py +++ b/nanobot/cron/types.py @@ -82,6 +82,14 @@ class CronPayload: ) +@dataclass +class CronRunResult: + """Result and durable record identity returned by a cron executor.""" + + run_id: str + response: str + + @dataclass class CronRunRecord: """A single execution record for a cron job.""" @@ -89,14 +97,17 @@ class CronRunRecord: status: Literal["ok", "error", "skipped"] duration_ms: int = 0 error: str | None = None + run_id: str | None = None @classmethod def from_store_dict(cls, data: dict[str, Any]) -> CronRunRecord: + run_id = get_camel_snake(data, "runId", "run_id") return cls( run_at_ms=_store_int(get_camel_snake(data, "runAtMs", "run_at_ms", 0)), status=data["status"], duration_ms=_store_int(get_camel_snake(data, "durationMs", "duration_ms", 0)), error=data.get("error"), + run_id=run_id if isinstance(run_id, str) else None, ) diff --git a/nanobot/webui/automation_results.py b/nanobot/webui/automation_results.py new file mode 100644 index 000000000..4e7dab0cf --- /dev/null +++ b/nanobot/webui/automation_results.py @@ -0,0 +1,83 @@ +"""Read the response of a selected automation run without exposing its audit metadata.""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import cast + +from nanobot.cron.types import CronJob, CronRunRecord +from nanobot.triggers.local_types import LocalTrigger, TriggerRunRecord +from nanobot.utils.run_records import safe_run_record_name + + +def _read_record(path: Path, runs_dir: Path) -> dict[str, object] | None: + if path.is_symlink() or path.resolve().parent != runs_dir.resolve(): + return None + try: + if path.stat().st_size > 2 * 1024 * 1024: + return None + value: object = json.loads(path.read_text(encoding="utf-8")) + except (FileNotFoundError, json.JSONDecodeError, UnicodeError): + return None + # JSON objects have string keys; values remain untrusted until checked below. + return cast(dict[str, object], value) if isinstance(value, dict) else None + + +def cron_run_response(runs_dir: Path, job: CronJob, run: CronRunRecord) -> str | None: + """Resolve explicit run IDs, or uniquely match older records within their execution interval.""" + if run.run_id: + path = runs_dir / f"{safe_run_record_name(run.run_id)}.json" + record = _read_record(path, runs_dir) + if not record or record.get("run_id") != run.run_id: + return None + records = [record] + else: + records: list[dict[str, object]] = [] + prefix = f"{job.id}:" + for path in runs_dir.glob("*.json"): + if not path.name.startswith(safe_run_record_name(prefix)): + continue + record = _read_record(path, runs_dir) + run_id = record.get("run_id") if record else None + if not isinstance(run_id, str) or not run_id.startswith(prefix): + continue + timestamp = run_id[len(prefix):].split(":", 1)[0] + if not timestamp.isdecimal(): + continue + started = int(timestamp) + if not run.run_at_ms <= started <= run.run_at_ms + run.duration_ms: + continue + # An overlapping run must not borrow a neighbouring execution's response. + matches = [item for item in job.state.run_history + if item.run_at_ms <= started <= item.run_at_ms + item.duration_ms] + if len(matches) != 1 or matches[0] != run: + return None + if record is not None: + records.append(record) + matching = [record for record in records + if record.get("job_id") == job.id + and record.get("session_key") == job.payload.session_key + and record.get("status") == run.status] + if len(matching) != 1: + return None + response = matching[0].get("response") + return response if isinstance(response, str) else None + + +def trigger_run_response( + runs_dir: Path, trigger: LocalTrigger, run: TriggerRunRecord, +) -> str | None: + """Match a trigger delivery by its saved creation time and session, never the latest reply.""" + matching: list[dict[str, object]] = [] + for path in runs_dir.glob("*.json"): + record = _read_record(path, runs_dir) + if (record and record.get("trigger_id") == trigger.id + and record.get("session_key") == trigger.session_key + and record.get("created_at_ms") == run.run_at_ms + and record.get("status") == run.status): + matching.append(record) + if len(matching) != 1: + return None + response = matching[0].get("response") + return response if isinstance(response, str) else None diff --git a/nanobot/webui/ws_http.py b/nanobot/webui/ws_http.py index 2f780e043..998f58cf5 100644 --- a/nanobot/webui/ws_http.py +++ b/nanobot/webui/ws_http.py @@ -36,6 +36,7 @@ from nanobot.session.session_handles import ( SessionHandleResolver, ) from nanobot.triggers.local_types import LocalTrigger +from nanobot.webui.automation_results import cron_run_response, trigger_run_response from nanobot.webui.file_preview import ( WebUIFilePreviewError, file_preview_availability_payload, @@ -1171,6 +1172,8 @@ class GatewayHTTPHandler: ) -> Response | None: if got == "/api/webui/automations": return self._handle_webui_automations(request) + if got == "/api/webui/automations/result": + return await self._handle_webui_automation_result(request) m = re.match(r"^/api/webui/automations/(enable|disable|delete|run|update)$", got) if m: return await self._handle_webui_automation_action(request, m.group(1)) @@ -1222,6 +1225,48 @@ class GatewayHTTPHandler: ) ) + async def _handle_webui_automation_result(self, request: WsRequest) -> Response: + if not self.check_api_token(request): + return _http_error(401, "Unauthorized") + query = _request_query(request) + job_id = (_query_first(query, "id") or "").strip() + try: + run_at_ms = int(_query_first(query, "run_at_ms") or "") + except ValueError: + return _http_error(400, "invalid run timestamp") + if not job_id or run_at_ms < 0: + return _http_error(400, "invalid automation run") + kind = _query_first(query, "kind") or "cron" + try: + if kind == "local_trigger": + trigger = self.local_trigger_store.get(job_id) if self.local_trigger_store else None + if trigger is None or self.local_trigger_store is None: + return _http_error(404, "automation not found") + deliveries = [item for item in trigger.run_history if item.run_at_ms == run_at_ms] + if len(deliveries) != 1: + return _http_error(404, "run not found") + response = await asyncio.to_thread( + trigger_run_response, self.local_trigger_store.runs_dir, trigger, deliveries[0], + ) + elif kind == "cron": + job = self.cron_service.get_job(job_id) if self.cron_service else None + if job is None or self.cron_service is None: + return _http_error(404, "automation not found") + if job.payload.kind == "system_event": + return _http_error(403, "system automation is protected") + runs = [item for item in job.state.run_history if item.run_at_ms == run_at_ms] + if len(runs) != 1: + return _http_error(404, "run not found") + response = await asyncio.to_thread( + cron_run_response, self.cron_service.store_path.parent / "runs", job, runs[0], + ) + else: + return _http_error(400, "invalid automation kind") + except OSError: + self._log.exception("Could not read automation run result") + return _http_error(500, "Could not read run result") + return _http_json_response({"response": response}) + async def _handle_webui_automation_action( self, request: WsRequest, diff --git a/tests/webui/test_automation_results.py b/tests/webui/test_automation_results.py new file mode 100644 index 000000000..e3e571460 --- /dev/null +++ b/tests/webui/test_automation_results.py @@ -0,0 +1,118 @@ +from pathlib import Path + +import pytest + +from nanobot.agent.tools.registry import ToolRegistry +from nanobot.bus.events import InboundMessage, OutboundMessage +from nanobot.cron.bound_runner import run_bound_cron_job +from nanobot.cron.service import CronService +from nanobot.cron.types import CronJob, CronPayload, CronRunRecord, CronRunResult, CronSchedule +from nanobot.triggers.local_types import LocalTrigger, TriggerRunRecord +from nanobot.utils.run_records import write_run_record +from nanobot.webui.automation_results import cron_run_response, trigger_run_response + + +def job_with_run(run: CronRunRecord) -> CronJob: + job = CronJob(id="job-1", name="Reminder", schedule=CronSchedule(kind="every", every_ms=60000), + payload=CronPayload(message="private prompt", session_key="websocket:one")) + job.state.run_history = [run] + return job + + +def write_result(path: Path, run_id: str, **changes: object) -> None: + write_run_record(path, run_id, { + "job_id": "job-1", "session_key": "websocket:one", "status": "ok", + "response": "The selected response", "rendered_prompt": "private prompt", **changes, + }) + + +def test_reads_explicit_identity_not_the_latest_run(tmp_path: Path) -> None: + run = CronRunRecord(run_at_ms=1000, status="ok", duration_ms=100, run_id="job-1:1001:one") + job = job_with_run(run) + write_result(tmp_path, run.run_id) + write_result(tmp_path, "job-1:2001:two", response="The latest response") + assert cron_run_response(tmp_path, job, run) == "The selected response" + + +@pytest.mark.parametrize("changes", [ + {"job_id": "other"}, {"session_key": "websocket:other"}, {"status": "error"}, + {"response": {"secret": "not text"}}, +]) +def test_validates_result_identity_and_response(tmp_path: Path, changes: dict[str, object]) -> None: + run = CronRunRecord(1000, "ok", 100, run_id="job-1:1001:one") + write_result(tmp_path, "job-1:1001:one", **changes) + assert cron_run_response(tmp_path, job_with_run(run), run) is None + + +def test_legacy_lookup_is_unique_and_confined_to_the_execution_interval(tmp_path: Path) -> None: + run = CronRunRecord(1000, "ok", 100) + job = job_with_run(run) + write_result(tmp_path, "job-1:900:old", response="old") + write_result(tmp_path, "job-1:1002:one") + write_result(tmp_path, "job-1:1200:later", response="later") + assert cron_run_response(tmp_path, job, run) == "The selected response" + write_result(tmp_path, "job-1:1003:ambiguous", response="different") + assert cron_run_response(tmp_path, job, run) is None + + +def test_overlapping_history_does_not_borrow_another_runs_output(tmp_path: Path) -> None: + run = CronRunRecord(1000, "ok", 100) + job = job_with_run(run) + job.state.run_history.append(CronRunRecord(1001, "ok", 99)) + write_result(tmp_path, "job-1:1002:other") + assert cron_run_response(tmp_path, job, run) is None + + +def test_missing_record_is_distinct_from_empty_response(tmp_path: Path) -> None: + run = CronRunRecord(1000, "ok", 100, run_id="job-1:1001:one") + job = job_with_run(run) + assert cron_run_response(tmp_path, job, run) is None + write_result(tmp_path, "job-1:1001:one", response="") + assert cron_run_response(tmp_path, job, run) == "" + + +def test_result_path_cannot_escape_the_runs_directory(tmp_path: Path) -> None: + run = CronRunRecord(1000, "ok", 100, run_id="../private") + runs = tmp_path / "runs" + runs.mkdir() + write_result(tmp_path, "private", response="outside") + assert cron_run_response(runs, job_with_run(run), run) is None + (runs / "broken.json").write_text("{", encoding="utf-8") + run.run_id = "broken" + assert cron_run_response(runs, job_with_run(run), run) is None + + +def test_local_trigger_uses_exact_delivery_time_and_session(tmp_path: Path) -> None: + trigger = LocalTrigger("trg_one", "Reminder", True, "websocket", "one", "websocket:one") + run = TriggerRunRecord(1000, "ok") + for run_id, created, response in [("delivery-one", 1000, "first"), ("delivery-two", 2000, "latest")]: + write_run_record(tmp_path, run_id, { + "trigger_id": trigger.id, "session_key": trigger.session_key, + "created_at_ms": created, "status": "ok", "response": response, + }) + assert trigger_run_response(tmp_path, trigger, run) == "first" + trigger.session_key = "websocket:other" + assert trigger_run_response(tmp_path, trigger, run) is None + + +async def test_new_cron_run_identity_survives_reload(tmp_path: Path) -> None: + class Agent: + tools = ToolRegistry() + + async def submit_cron_turn(self, msg: InboundMessage) -> OutboundMessage: + return OutboundMessage(channel=msg.channel, chat_id=msg.chat_id, content="reply") + + async def execute(job: CronJob) -> CronRunResult: + return await run_bound_cron_job(job, agent=Agent(), cron=service) + + service = CronService(tmp_path / "jobs.json", on_job=execute) + job = service.add_job(name="Reminder", schedule=CronSchedule(kind="every", every_ms=60000), + message="hi", session_key="websocket:one", origin_channel="websocket", + origin_chat_id="one") + assert await service.run_job(job.id, force=True) + reloaded = CronService(tmp_path / "jobs.json").get_job(job.id) + assert reloaded is not None + record = reloaded.state.run_history[-1] + assert record.run_id is not None + assert cron_run_response(tmp_path / "runs", reloaded, record) == "reply" + assert CronRunRecord.from_store_dict({"runAtMs": 1000, "status": "ok", "runId": 42}).run_id is None diff --git a/webui/src/components/settings/SettingsPage.tsx b/webui/src/components/settings/SettingsPage.tsx index 3dd9f3eec..344000a6c 100644 --- a/webui/src/components/settings/SettingsPage.tsx +++ b/webui/src/components/settings/SettingsPage.tsx @@ -571,6 +571,7 @@ export function SettingsPage({ return (