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
@@ -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:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
@@ -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:]
|
||||
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -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