fix(webui): show per-run automation replies and simplify details
This commit is contained in:
1 parent
e7da868574
commit
037438e7d1
28 files changed
+985
-183
No files matched your search
@@ -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
|
||||
@@ -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,
|
||||
|
||||
Reference in new issue
Block a user