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 (
({ id: `${job.id}:recorded:${run.run_at_ms}:${index}`, job, startMs: run.run_at_ms, - endMs: run.duration_ms != null && run.duration_ms > 0 - ? run.run_at_ms + run.duration_ms - : null, kind: "recorded" as const, - status: run.status ?? null, + run, })); return nextRun == null ? recorded : [ ...recorded, @@ -79,9 +79,8 @@ function entriesForJobs(jobs: SessionAutomationJob[]): CalendarEntry[] { id: `${job.id}:planned:${nextRun}`, job, startMs: nextRun, - endMs: null, kind: "planned" as const, - status: null, + run: null, }, ]; }); @@ -89,9 +88,7 @@ function entriesForJobs(jobs: SessionAutomationJob[]): CalendarEntry[] { function entryTime(entry: CalendarEntry, locale: string): string { const formatter = new Intl.DateTimeFormat(locale, { hour: "2-digit", minute: "2-digit" }); - const start = formatter.format(entry.startMs); - if (entry.endMs == null) return start; - return `${start}–${formatter.format(entry.endMs)}`; + return formatter.format(entry.startMs); } function isSameDay(left: Date, right: Date): boolean { @@ -102,34 +99,33 @@ function CalendarEntryRow({ entry, locale, copy, onInspect, compact = false }: { entry: CalendarEntry; locale: string; copy: CalendarCopy; - onInspect: AutomationCalendarProps["onInspect"]; + onInspect: (entry: CalendarEntry, trigger: HTMLElement) => void; compact?: boolean; }) { const name = entry.job.name || entry.job.id; const running = Boolean(entry.job.state.pending) && entry.kind === "planned"; - const failed = entry.kind === "recorded" && entry.status === "error"; - const completed = entry.kind === "recorded" - && Boolean(entry.job.delete_after_run) - && entry.job.state.next_run_at_ms == null - && entry.job.state.last_status === "ok"; + const failed = entry.run?.status === "error"; + const completed = entry.run?.status === "ok"; const status = running ? copy.running : failed ? copy.failed : completed ? copy.completed - : entry.kind === "planned" - ? copy.planned - : copy.recorded; + : entry.run?.status === "skipped" + ? copy.skipped + : entry.kind === "planned" + ? copy.planned + : copy.recorded; const content = ( <> - {name} - + {name} + {running ? : null} {failed ? : null} {entryTime(entry, locale)} - {compact ? {status} : null} + {compact || entry.kind === "recorded" ? {status} : null} {entry.job.protected ? {copy.system} : null} @@ -141,7 +137,6 @@ function CalendarEntryRow({ entry, locale, copy, onInspect, compact = false }: { formControlFocusClassName, compact && "py-2 text-[12px]", failed && "bg-destructive/[0.045]", - entry.kind === "recorded" && !failed && "bg-muted/45", ); return ( @@ -150,7 +145,7 @@ function CalendarEntryRow({ entry, locale, copy, onInspect, compact = false }: { className={actionClass} aria-label={`${name}, ${entryTime(entry, locale)}, ${status}${entry.job.protected ? `, ${copy.system}` : ""}`} aria-haspopup="dialog" - onClick={(event) => onInspect(entry.job, event.currentTarget)} + onClick={(event) => onInspect(entry, event.currentTarget)} > {content} @@ -162,12 +157,12 @@ function CalendarOverflowEntries({ entries, dayLabel, locale, copy, onInspect }: dayLabel: string; locale: string; copy: CalendarCopy; - onInspect: AutomationCalendarProps["onInspect"]; + onInspect: (entry: CalendarEntry, trigger: HTMLElement) => void; }) { const [open, setOpen] = useState(false); const titleId = useId(); const triggerRef = useRef(null); - const pendingSelection = useRef(null); + const pendingSelection = useRef(null); return ( @@ -190,12 +185,12 @@ function CalendarOverflowEntries({ entries, dayLabel, locale, copy, onInspect }: aria-labelledby={titleId} className="w-80 max-w-[calc(100vw-2rem)] overscroll-contain p-2" onCloseAutoFocus={(event) => { - const job = pendingSelection.current; + const entry = pendingSelection.current; pendingSelection.current = null; - if (!job || !triggerRef.current?.isConnected) return; + if (!entry || !triggerRef.current?.isConnected) return; // Hand off after the day popover exits, retaining a mounted return target. event.preventDefault(); - onInspect(job, triggerRef.current); + onInspect(entry, triggerRef.current); }} >
@@ -210,8 +205,8 @@ function CalendarOverflowEntries({ entries, dayLabel, locale, copy, onInspect }: entry={entry} locale={locale} copy={copy} - onInspect={(job) => { - pendingSelection.current = job; + onInspect={(entry) => { + pendingSelection.current = entry; setOpen(false); }} compact @@ -222,8 +217,20 @@ function CalendarOverflowEntries({ entries, dayLabel, locale, copy, onInspect }: ); } -export function AutomationCalendar({ jobs, month, locale, copy, onInspect }: AutomationCalendarProps) { +export function AutomationCalendar({ token = "", jobs, month, locale, copy, onInspect }: AutomationCalendarProps) { const calendarRef = useRef(null); + const runTrigger = useRef(null); + const [selectedRun, setSelectedRun] = useState<{ job: SessionAutomationJob; run: AutomationRunRecord } | null>(null); + const [runOpen, setRunOpen] = useState(false); + const inspectEntry = (entry: CalendarEntry, trigger: HTMLElement) => { + if (!entry.run) { + onInspect(entry.job, trigger); + return; + } + runTrigger.current = trigger; + setSelectedRun({ job: entry.job, run: entry.run }); + setRunOpen(true); + }; const [wideCalendar, setWideCalendar] = useState(true); const today = startOfDay(new Date()); const gridStart = addDays(month, -mondayIndex(month)); @@ -258,7 +265,7 @@ export function AutomationCalendar({ jobs, month, locale, copy, onInspect }: Aut }, []); return ( -
+
{wideCalendar ?
{weekdayLabels.map((label) =>
{label}
)} @@ -297,7 +304,7 @@ export function AutomationCalendar({ jobs, month, locale, copy, onInspect }: Aut entry={entry} locale={locale} copy={copy} - onInspect={onInspect} + onInspect={inspectEntry} /> ))} {entries.length > 3 ? ( @@ -306,7 +313,7 @@ export function AutomationCalendar({ jobs, month, locale, copy, onInspect }: Aut dayLabel={dayLabel} locale={locale} copy={copy} - onInspect={onInspect} + onInspect={inspectEntry} /> ) : null}
@@ -329,7 +336,7 @@ export function AutomationCalendar({ jobs, month, locale, copy, onInspect }: Aut entry={entry} locale={locale} copy={copy} - onInspect={onInspect} + onInspect={inspectEntry} compact /> ))} @@ -342,6 +349,18 @@ export function AutomationCalendar({ jobs, month, locale, copy, onInspect }: Aut )}
: null} + {selectedRun ? { + event.preventDefault(); + if (runOpen) return; + setSelectedRun(null); + const target = runTrigger.current?.isConnected ? runTrigger.current : calendarRef.current; + target?.focus({ preventScroll: true }); + }} + /> : null}
); } diff --git a/webui/src/components/settings/system/AutomationRunDialog.tsx b/webui/src/components/settings/system/AutomationRunDialog.tsx new file mode 100644 index 000000000..2fc019cdc --- /dev/null +++ b/webui/src/components/settings/system/AutomationRunDialog.tsx @@ -0,0 +1,126 @@ +import { CircleAlert } from "lucide-react"; +import { useEffect, useState } from "react"; +import { useTranslation } from "react-i18next"; + +import { MarkdownText } from "@/components/MarkdownText"; +import { Button } from "@/components/ui/button"; +import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog"; +import type { SessionAutomationJob } from "@/lib/types"; +import { fetchAutomationRunResult } from "@/lib/api"; +import { cn } from "@/lib/utils"; + +export type AutomationRunRecord = NonNullable[number]; + +export function AutomationRunDialog({ token = "", job, run, locale, open, onOpenChange, onCloseAutoFocus }: { + token?: string; + job: SessionAutomationJob; + run: AutomationRunRecord; + locale: string; + open: boolean; + onOpenChange: (open: boolean) => void; + onCloseAutoFocus: (event: Event) => void; +}) { + const { t } = useTranslation(); + const [attempt, setAttempt] = useState(0); + const kind = job.kind === "local_trigger" ? "local_trigger" : "cron"; + const resultKey = JSON.stringify([token, kind, job.id, run.run_at_ms, attempt]); + const [result, setResult] = useState<{ + key: string; status: "loading" | "loaded" | "error"; response: string | null; + } | null>(null); + useEffect(() => { + if (!open) return; + if (!token) { + setResult({ key: resultKey, status: "loaded", response: null }); + return; + } + const controller = new AbortController(); + setResult({ key: resultKey, status: "loading", response: null }); + void fetchAutomationRunResult(token, job.id, run.run_at_ms, kind, controller.signal) + .then((payload) => { + if (!controller.signal.aborted) { + setResult({ key: resultKey, status: "loaded", response: payload.response }); + } + }) + .catch(() => { + if (!controller.signal.aborted) { + setResult({ key: resultKey, status: "error", response: null }); + } + }); + return () => controller.abort(); + }, [job.id, kind, open, resultKey, run.run_at_ms, token]); + const currentResult = result?.key === resultKey ? result : null; + const failed = run.status === "error"; + const status = run.status === "ok" + ? t("settings.automations.status.completed") + : failed ? t("settings.automations.status.failed") + : run.status === "skipped" ? t("settings.automations.skipped") + : t("settings.automations.calendar.recorded"); + const duration = run.duration_ms; + const chatHref = job.origin?.channel === "websocket" && job.origin.session_key + ? `#/chat/${encodeURIComponent(job.origin.session_key)}` : null; + + return ( + + + + + {job.name || job.id} + + + + + +
+
+
+
{t("settings.automations.runDetails.result")}
+
+ {failed ? : null} + {status} +
+
+ {duration != null && Number.isFinite(duration) && duration >= 0 ? ( +
+
{t("settings.automations.runDetails.duration")}
+
{new Intl.NumberFormat(locale, { + style: "unit", unit: "second", unitDisplay: "short", + maximumFractionDigits: duration < 1000 ? 3 : 1, + }).format(duration / 1000)}
+
+ ) : null} +
+ {run.error ?

{run.error}

: null} + {!currentResult || currentResult.status === "loading" ? ( +

{t("settings.automations.runDetails.loading")}

+ ) : currentResult.status === "error" ? ( +
+

{t("settings.automations.runDetails.loadError")}

+ +
+ ) : currentResult.response?.trim() ? ( + {currentResult.response} + ) : ( +

{t(currentResult.response === null + ? "settings.automations.runDetails.noOutput" + : "settings.automations.runDetails.emptyOutput")}

+ )} +
+ {chatHref ? ( + + ) : null} +
+
+ ); +} diff --git a/webui/src/components/settings/system/AutomationsSettings.tsx b/webui/src/components/settings/system/AutomationsSettings.tsx index 8d61b976f..a55f9e82f 100644 --- a/webui/src/components/settings/system/AutomationsSettings.tsx +++ b/webui/src/components/settings/system/AutomationsSettings.tsx @@ -3,7 +3,7 @@ import type { FormEvent, ReactNode } from "react"; import type { TFunction } from "i18next"; import { Check, - ChevronDown, + Info, CircleAlert, Clipboard, ListFilter, @@ -21,7 +21,8 @@ import { } from "@/components/thread/model-preset"; import { ThreadComposer } from "@/components/thread/ThreadComposer"; import { Button } from "@/components/ui/button"; -import { Disclosure } from "@/components/ui/disclosure"; +import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"; +import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"; import { DropdownMenu, DropdownMenuContent, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"; import { ExpandableText } from "@/components/ui/expandable-text"; import { @@ -54,6 +55,7 @@ export type AutomationAction = "enable" | "disable" | "delete" | "run"; const EMPTY_TITLE_OVERRIDES: Record = {}; export function AutomationsSettings({ + token = "", payload, loading, filter, actionKey, error, titleOverrides = EMPTY_TITLE_OVERRIDES, settingsSnapshot = null, @@ -61,6 +63,7 @@ export function AutomationsSettings({ onRequestEdit, onRequestDelete, onStartChat, onManageModels, returnToDetailJob = null, onReturnToDetailHandled, }: { + token?: string; payload: AutomationsPayload | null; titleOverrides?: Record; settingsSnapshot?: SettingsPayload | null; @@ -253,8 +256,8 @@ export function AutomationsSettings({
{filters}
: null} {view === "calendar" ? (
- @@ -334,6 +337,7 @@ export function AutomationsSettings({
) : ( @@ -412,10 +417,10 @@ export function AutomationDetailDialog({ {job ? ( - - {job.name || job.id} - {canManage ? ( - - {formatAutomationSchedule(job, locale, tx)} - {!localTrigger ? - {tx("settings.automations.labels.next", "Next")} - - {formatAutomationNext(job, tx)} - - : null} - - ) : null} +
+ + + + + + + + + {tx("settings.automations.taskInfo", "Task information")} + + + +
+ + {formatAutomationSchedule(job, locale, tx)} + + {!localTrigger ? ( + + {formatAutomationNext(job, tx)} + + ) : null} + + {job.state.last_run_at_ms + ? + {lastStatus ? {lastStatus} : null} + {relativeTime(job.state.last_run_at_ms)} + + : lastStatus || tx("settings.automations.neverRun", "Not run yet")} + + {timezone ? ( + {timezone} + ) : null} + {job.delete_after_run ? {tx("settings.automations.oneShotHint", "Removed after running")} : null} + {job.created_at_ms ? {fmtDateTime(job.created_at_ms, locale)} : null} + {job.updated_at_ms ? {fmtDateTime(job.updated_at_ms, locale)} : null} + {job.id} +
+
+
+
+ + {job.name || job.id}
{canManage && message.trim() ?
-
- {localTrigger ? tx("settings.automations.fields.command", "Command") : tx("settings.automations.instructions", "Instructions")} - {localTrigger && command ? ( - - ) : null} -
-
- +
+ ) : null} +
+ {message}
{messageNeedsExpansion ? ( - ) : null} @@ -516,65 +556,24 @@ function AutomationDetailPanel({ {job.state.last_error ? : null} {error ? : null}
- {job.protected ? ( - <> - - {formatAutomationSchedule(job, locale, tx)} - - {timezone ? ( - - {timezone} - - ) : null} - - {formatAutomationNext(job, tx)} - - - ) : null} - - {job.state.last_run_at_ms - ? - {lastStatus ? {lastStatus} : null} - {relativeTime(job.state.last_run_at_ms)} - - : lastStatus || tx("settings.automations.neverRun", "Not run yet")} - {!job.protected && job.origin?.channel && job.origin.channel !== "websocket" ? ( {automationChannelLabel(job.origin.channel, t)} ) : null}
- - {tx("settings.automations.moreDetails", "More details")} - - } - > -
- {timezone && canManage ? ( - - {timezone} - - ) : null} - {job.delete_after_run ? {tx("settings.automations.oneShotHint", "Removed after running")} : null} - {job.created_at_ms ? {fmtDateTime(job.created_at_ms, locale)} : null} - {job.updated_at_ms ? {fmtDateTime(job.updated_at_ms, locale)} : null} - {job.id} -
-
{canManage ? ( -
-
- {!localTrigger ? ( - @@ -582,18 +581,18 @@ function AutomationDetailPanel({
-
- - {originHref ? : null} + {originHref ? : null}
) : null} @@ -631,11 +630,11 @@ function automationMessageNeedsExpansion(message: string): boolean { return message.length > 360 || message.split(/\r?\n/).length > 6; } -function AutomationDetail({ label, title, children }: { label: string; title?: string; children: ReactNode }) { +function AutomationDetail({ label, title, children }: { label: ReactNode; title?: string; children: ReactNode }) { return ( -
+
{label}
-
{children}
+
{children}
); } diff --git a/webui/src/globals.css b/webui/src/globals.css index 5c594bd57..c4e0cf7e5 100644 --- a/webui/src/globals.css +++ b/webui/src/globals.css @@ -1046,7 +1046,8 @@ align-items: center; gap: 0.5rem 1rem; min-block-size: 4rem; - padding: 0.75rem 0.25rem; + padding-block: 0.75rem; + padding-inline: 0.75rem 0.25rem; } .automation-create-composer .thread-composer-collapsible-layout { padding-block-start: 0; diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.json index 9478f157f..e97662068 100644 --- a/webui/src/i18n/locales/en/common.json +++ b/webui/src/i18n/locales/en/common.json @@ -1088,6 +1088,16 @@ "notEnabled": "Not enabled" }, "automations": { + "taskInfo": "Task information", + "runDetails": { + "loading": "Loading response…", + "loadError": "Couldn’t load the response.", + "retry": "Retry", + "emptyOutput": "No reply was generated.", + "result": "Result", + "duration": "Duration", + "noOutput": "This record doesn’t include the response text." + }, "create": "Create automation", "createPrompt": "What would you like nanobot to automate?", "createInput": "Describe an automation", diff --git a/webui/src/i18n/locales/es/common.json b/webui/src/i18n/locales/es/common.json index 340a62146..d46ce9523 100644 --- a/webui/src/i18n/locales/es/common.json +++ b/webui/src/i18n/locales/es/common.json @@ -889,6 +889,16 @@ "notEnabled": "No activado" }, "automations": { + "taskInfo": "Información de la tarea", + "runDetails": { + "loading": "Cargando respuesta…", + "loadError": "No se pudo cargar la respuesta.", + "retry": "Reintentar", + "emptyOutput": "No se generó ninguna respuesta.", + "result": "Resultado", + "duration": "Duración", + "noOutput": "Este registro no incluye el texto de la respuesta." + }, "create": "Crear automatización", "createPrompt": "¿Qué te gustaría automatizar con nanobot?", "createInput": "Describe una automatización", diff --git a/webui/src/i18n/locales/fr/common.json b/webui/src/i18n/locales/fr/common.json index f0b6c8088..f46452a2b 100644 --- a/webui/src/i18n/locales/fr/common.json +++ b/webui/src/i18n/locales/fr/common.json @@ -888,6 +888,16 @@ "notEnabled": "Non activé" }, "automations": { + "taskInfo": "Informations sur la tâche", + "runDetails": { + "loading": "Chargement de la réponse…", + "loadError": "Impossible de charger la réponse.", + "retry": "Réessayer", + "emptyOutput": "Aucune réponse n’a été générée.", + "result": "Résultat", + "duration": "Durée", + "noOutput": "Le texte de la réponse n’est pas conservé dans cet enregistrement." + }, "create": "Créer une automatisation", "createPrompt": "Que voulez-vous automatiser avec nanobot ?", "createInput": "Décrire une automatisation", diff --git a/webui/src/i18n/locales/id/common.json b/webui/src/i18n/locales/id/common.json index ebadbf693..5f4348f3f 100644 --- a/webui/src/i18n/locales/id/common.json +++ b/webui/src/i18n/locales/id/common.json @@ -888,6 +888,16 @@ "notEnabled": "Belum aktif" }, "automations": { + "taskInfo": "Informasi tugas", + "runDetails": { + "loading": "Memuat respons…", + "loadError": "Respons tidak dapat dimuat.", + "retry": "Coba lagi", + "emptyOutput": "Tidak ada respons yang dihasilkan.", + "result": "Hasil", + "duration": "Durasi", + "noOutput": "Catatan ini tidak menyimpan teks respons." + }, "create": "Buat otomatisasi", "createPrompt": "Apa yang ingin kamu otomatisasi dengan nanobot?", "createInput": "Jelaskan otomatisasi", diff --git a/webui/src/i18n/locales/ja/common.json b/webui/src/i18n/locales/ja/common.json index 92ffdf4fe..269907c59 100644 --- a/webui/src/i18n/locales/ja/common.json +++ b/webui/src/i18n/locales/ja/common.json @@ -888,6 +888,16 @@ "notEnabled": "無効" }, "automations": { + "taskInfo": "タスク情報", + "runDetails": { + "loading": "応答を読み込み中…", + "loadError": "応答を読み込めませんでした。", + "retry": "再試行", + "emptyOutput": "応答は生成されませんでした。", + "result": "実行結果", + "duration": "所要時間", + "noOutput": "この記録に応答本文は保存されていません。" + }, "create": "自動タスクを作成", "createPrompt": "nanobot に何を自動化してほしいですか?", "createInput": "自動タスクを説明", diff --git a/webui/src/i18n/locales/ko/common.json b/webui/src/i18n/locales/ko/common.json index e4cb55295..26bbfc1f2 100644 --- a/webui/src/i18n/locales/ko/common.json +++ b/webui/src/i18n/locales/ko/common.json @@ -888,6 +888,16 @@ "notEnabled": "비활성화됨" }, "automations": { + "taskInfo": "작업 정보", + "runDetails": { + "loading": "응답을 불러오는 중…", + "loadError": "응답을 불러오지 못했습니다.", + "retry": "다시 시도", + "emptyOutput": "생성된 응답이 없습니다.", + "result": "실행 결과", + "duration": "소요 시간", + "noOutput": "이 기록에는 응답 본문이 저장되지 않았습니다." + }, "create": "자동화 만들기", "createPrompt": "nanobot이 무엇을 자동으로 해주면 좋을까요?", "createInput": "자동화 설명", diff --git a/webui/src/i18n/locales/pt-BR/common.json b/webui/src/i18n/locales/pt-BR/common.json index 9a1768e36..ea8ead8ce 100644 --- a/webui/src/i18n/locales/pt-BR/common.json +++ b/webui/src/i18n/locales/pt-BR/common.json @@ -902,6 +902,16 @@ "notEnabled": "Não habilitado" }, "automations": { + "taskInfo": "Informações da tarefa", + "runDetails": { + "loading": "Carregando resposta…", + "loadError": "Não foi possível carregar a resposta.", + "retry": "Tentar novamente", + "emptyOutput": "Nenhuma resposta foi gerada.", + "result": "Resultado", + "duration": "Duração", + "noOutput": "Este registro não inclui o texto da resposta." + }, "create": "Criar automação", "createPrompt": "O que você gostaria de automatizar com o nanobot?", "createInput": "Descreva uma automação", diff --git a/webui/src/i18n/locales/vi/common.json b/webui/src/i18n/locales/vi/common.json index c1a3fa0ba..17252af08 100644 --- a/webui/src/i18n/locales/vi/common.json +++ b/webui/src/i18n/locales/vi/common.json @@ -888,6 +888,16 @@ "notEnabled": "Chưa bật" }, "automations": { + "taskInfo": "Thông tin tác vụ", + "runDetails": { + "loading": "Đang tải phản hồi…", + "loadError": "Không tải được phản hồi.", + "retry": "Thử lại", + "emptyOutput": "Lần chạy này không tạo phản hồi.", + "result": "Kết quả", + "duration": "Thời gian chạy", + "noOutput": "Bản ghi này không lưu nội dung phản hồi." + }, "create": "Tạo tự động hóa", "createPrompt": "Bạn muốn nanobot tự động làm gì?", "createInput": "Mô tả tác vụ tự động", diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.json index e7b946385..40a712f16 100644 --- a/webui/src/i18n/locales/zh-CN/common.json +++ b/webui/src/i18n/locales/zh-CN/common.json @@ -1088,6 +1088,16 @@ "notEnabled": "未启用" }, "automations": { + "taskInfo": "任务信息", + "runDetails": { + "loading": "正在加载回复…", + "loadError": "回复加载失败。", + "retry": "重试", + "emptyOutput": "本次运行未生成回复。", + "result": "运行结果", + "duration": "耗时", + "noOutput": "此记录未保存回复正文。" + }, "create": "创建自动任务", "createPrompt": "想让 nanobot 自动帮你做什么?", "createInput": "描述一个自动任务", diff --git a/webui/src/i18n/locales/zh-TW/common.json b/webui/src/i18n/locales/zh-TW/common.json index 71ff733dd..fc1205192 100644 --- a/webui/src/i18n/locales/zh-TW/common.json +++ b/webui/src/i18n/locales/zh-TW/common.json @@ -888,6 +888,16 @@ "notEnabled": "未啟用" }, "automations": { + "taskInfo": "任務資訊", + "runDetails": { + "loading": "正在載入回覆…", + "loadError": "回覆載入失敗。", + "retry": "重試", + "emptyOutput": "本次執行未產生回覆。", + "result": "執行結果", + "duration": "耗時", + "noOutput": "此記錄未儲存回覆正文。" + }, "create": "建立自動任務", "createPrompt": "想讓 nanobot 自動幫你做什麼?", "createInput": "描述自動任務", diff --git a/webui/src/lib/api.ts b/webui/src/lib/api.ts index 6cff19eec..e6c83df7b 100644 --- a/webui/src/lib/api.ts +++ b/webui/src/lib/api.ts @@ -336,6 +336,19 @@ export async function fetchAutomations( ); } +export async function fetchAutomationRunResult( + token: string, + id: string, + runAtMs: number, + kind: "cron" | "local_trigger", + signal?: AbortSignal, +): Promise<{ response: string | null }> { + const query = new URLSearchParams({ id, run_at_ms: String(runAtMs), kind }); + return request<{ response: string | null }>( + `/api/webui/automations/result?${query}`, token, { signal }, API_READ_TIMEOUT_MS, + ); +} + export async function runAutomationAction( transport: WebUIMutationTransport, action: "enable" | "disable" | "delete" | "run", diff --git a/webui/src/tests/api.test.ts b/webui/src/tests/api.test.ts index 37d4289c7..e68d3267a 100644 --- a/webui/src/tests/api.test.ts +++ b/webui/src/tests/api.test.ts @@ -13,6 +13,7 @@ import { fetchFilePreview, fetchFilePreviewAvailability, fetchAutomations, + fetchAutomationRunResult, fetchApiService, fetchCliApps, fetchInstalledCliApps, @@ -238,6 +239,15 @@ describe("webui API helpers", () => { ); }); + it("fetches the selected run response with authentication and an encoded identity", async () => { + const controller = new AbortController(); + await fetchAutomationRunResult("tok", "task/id", 1234, "cron", controller.signal); + expect(fetch).toHaveBeenCalledWith( + "/api/webui/automations/result?id=task%2Fid&run_at_ms=1234&kind=cron", + expect.objectContaining({ headers: { Authorization: "Bearer tok" }, signal: expect.any(AbortSignal) }), + ); + }); + it("validates channel settings with form values", async () => { await validateChannel( mutationTransport, diff --git a/webui/src/tests/automation-run-dialog.test.tsx b/webui/src/tests/automation-run-dialog.test.tsx new file mode 100644 index 000000000..f5a4ceaf4 --- /dev/null +++ b/webui/src/tests/automation-run-dialog.test.tsx @@ -0,0 +1,86 @@ +import { act, cleanup, render, screen, waitFor } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { AutomationRunDialog } from "@/components/settings/system/AutomationRunDialog"; +import { fetchAutomationRunResult } from "@/lib/api"; +import i18n from "@/i18n"; +import type { SessionAutomationJob } from "@/lib/types"; + +vi.mock("@/lib/api", () => ({ fetchAutomationRunResult: vi.fn() })); +const fetchResult = vi.mocked(fetchAutomationRunResult); +const job: SessionAutomationJob = { + id: "reminder", name: "Water reminder", enabled: true, + schedule: { kind: "every", every_ms: 60000 }, payload: { message: "Current instructions" }, + state: {}, origin: { channel: "websocket", session_key: "websocket:one" }, +}; +const run = { run_at_ms: 1000, status: "ok", duration_ms: 3000 }; +const props = { token: "test-token", job, run, locale: "en", open: true, + onOpenChange: vi.fn(), onCloseAutoFocus: vi.fn() }; + +beforeEach(async () => { + vi.clearAllMocks(); + await i18n.changeLanguage("en"); +}); +afterEach(cleanup); + +describe("Automation run response", () => { + it("loads only the selected run and renders its Markdown response", async () => { + let complete!: (value: { response: string }) => void; + fetchResult.mockReturnValue(new Promise((resolve) => { complete = resolve; })); + render(); + expect(screen.getByRole("status")).toHaveTextContent("Loading response…"); + expect(screen.queryByText("This record doesn’t include the response text.")).not.toBeInTheDocument(); + expect(fetchResult).toHaveBeenCalledWith("test-token", "reminder", 1000, "cron", expect.any(AbortSignal)); + await act(async () => complete({ response: "**Drink water**" })); + expect(await screen.findByText("Drink water")).toBeVisible(); + expect(screen.getByText("Drink water").tagName).toBe("STRONG"); + expect(screen.queryByText("Current instructions")).not.toBeInTheDocument(); + }); + + it("shows a retryable loading error instead of claiming no response exists", async () => { + fetchResult.mockRejectedValueOnce(new Error("Network error")); + fetchResult.mockResolvedValueOnce({ response: "Recovered response" }); + const user = userEvent.setup(); + render(); + expect(await screen.findByRole("alert")).toHaveTextContent("Couldn’t load the response."); + expect(screen.queryByText("This record doesn’t include the response text.")).not.toBeInTheDocument(); + await user.click(screen.getByRole("button", { name: "Retry" })); + expect(await screen.findByText("Recovered response")).toBeVisible(); + expect(fetchResult).toHaveBeenCalledTimes(2); + }); + + it("aborts stale requests and never shows an earlier run's reply", async () => { + let first!: (value: { response: string }) => void; + let second!: (value: { response: string }) => void; + fetchResult.mockReturnValueOnce(new Promise((resolve) => { first = resolve; })); + fetchResult.mockReturnValueOnce(new Promise((resolve) => { second = resolve; })); + const { rerender, unmount } = render(); + const firstSignal = fetchResult.mock.calls[0][4]!; + rerender(); + expect(firstSignal.aborted).toBe(true); + await act(async () => first({ response: "Wrong run" })); + expect(screen.queryByText("Wrong run")).not.toBeInTheDocument(); + expect(screen.getByRole("status")).toHaveTextContent("Loading response…"); + await act(async () => second({ response: "Selected run" })); + expect(await screen.findByText("Selected run")).toBeVisible(); + const secondSignal = fetchResult.mock.calls[1][4]!; + unmount(); + expect(secondSignal.aborted).toBe(true); + }); + + it.each([ + [null, "This record doesn’t include the response text."], + ["", "No reply was generated."], + ])("distinguishes unavailable and empty response: %s", async (response, message) => { + fetchResult.mockResolvedValue({ response }); + render(); + expect(await screen.findByText(message)).toBeVisible(); + expect(fetchResult).toHaveBeenCalledWith("test-token", "reminder", 1000, "local_trigger", expect.any(AbortSignal)); + }); + + it("does not fetch a closed result panel", async () => { + render(); + await waitFor(() => expect(fetchResult).not.toHaveBeenCalled()); + }); +}); diff --git a/webui/src/tests/automations-settings.test.tsx b/webui/src/tests/automations-settings.test.tsx index 63eb80a0c..de265df20 100644 --- a/webui/src/tests/automations-settings.test.tsx +++ b/webui/src/tests/automations-settings.test.tsx @@ -127,7 +127,7 @@ describe("Automation task list and detail sheet", () => { render(); - expect(screen.getByRole("button", { name: /Review on request.*Recorded/ })).toBeVisible(); + expect(screen.getByRole("button", { name: /Review on request.*Completed/ })).toBeVisible(); expect(screen.queryByRole("button", { name: /Review on request.*Planned/ })).not.toBeInTheDocument(); }); @@ -253,12 +253,12 @@ describe("Automation task list and detail sheet", () => { const row = screen.getByRole("button", { name: /PR watch/ }); await user.click(row); const dialog = screen.getByRole("dialog", { name: "PR watch" }); - expect(dialog).toHaveAccessibleDescription(/Every 30 minutes/); - expect(within(dialog).getByText("Instructions")).toBeVisible(); + expect(dialog).not.toHaveAttribute("aria-describedby"); + expect(within(dialog).queryByText("Instructions")).not.toBeInTheDocument(); expect(within(dialog).getByRole("link", { name: "Open a chat" })).toHaveAttribute( "href", "#/chat/websocket%3Ademo", ); - expect(within(dialog).getByRole("button", { name: "More details" })).toHaveAttribute("aria-expanded", "false"); + expect(within(dialog).getByRole("button", { name: "Task information" })).toHaveAttribute("aria-expanded", "false"); await user.click(within(dialog).getByRole("button", { name: "Close" })); await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument()); expect(row).toHaveFocus(); @@ -269,32 +269,132 @@ describe("Automation task list and detail sheet", () => { expect(row).toHaveFocus(); }); - it("opens both planned and recorded calendar blocks in details before linking to chat", async () => { + it("opens historical results separately from the planned task controls", async () => { const user = userEvent.setup(); const jobWithHistory: SessionAutomationJob = { ...task, state: { ...task.state, - run_history: [{ run_at_ms: now - 60_000, status: "ok", duration_ms: 120_000 }], + last_status: "error", + last_error: "A later run failed", + run_history: [{ run_at_ms: now - 60_000, status: "ok", duration_ms: 1_000 }], }, }; render(); const planned = screen.getByRole("button", { name: /PR watch.*Planned/ }); - const recorded = screen.getByRole("button", { name: /PR watch.*Recorded/ }); + const recorded = screen.getByRole("button", { name: /PR watch.*Completed/ }); expect(planned).toHaveAttribute("aria-haspopup", "dialog"); expect(recorded).toHaveAttribute("aria-haspopup", "dialog"); expect(planned.querySelector(".rounded-full")).toBeNull(); expect(recorded.querySelector(".rounded-full")).toBeNull(); expect(planned).not.toHaveClass("bg-muted/45"); - expect(recorded).toHaveClass("bg-muted/45", "rounded-compact"); + expect(recorded).not.toHaveClass("bg-muted/45"); + expect(within(recorded).getByText("PR watch")).toHaveClass("font-normal", "text-muted-foreground"); + expect(within(planned).getByText("PR watch")).toHaveClass("font-medium", "text-foreground"); + expect(recorded).toHaveTextContent("Completed"); + expect(recorded).not.toHaveTextContent("–"); expect(screen.queryByRole("link", { name: /PR watch/ })).not.toBeInTheDocument(); await user.click(recorded); const dialog = screen.getByRole("dialog", { name: "PR watch" }); + expect(within(dialog).getByText("Completed")).toBeVisible(); + expect(within(dialog).getByText("1 sec")).toBeVisible(); + expect(dialog.querySelector("time")).toHaveAttribute("dateTime", new Date(now - 60_000).toISOString()); + expect(dialog).not.toHaveTextContent("A later run failed"); + expect(dialog).not.toHaveTextContent(task.payload.message); + expect(dialog).toHaveTextContent("This record doesn’t include the response text."); + for (const name of ["Edit", "Run now", "Disable", "Delete", "Task information"]) { + expect(within(dialog).queryByRole("button", { name })).not.toBeInTheDocument(); + } expect(within(dialog).getByRole("link", { name: "Open a chat" })).toHaveAttribute( "href", "#/chat/websocket%3Ademo", ); + await user.keyboard("{Escape}"); + await waitFor(() => expect(recorded).toHaveFocus()); + await user.click(planned); + expect(within(screen.getByRole("dialog", { name: "PR watch" })).getByRole("button", { name: "Edit" })).toBeVisible(); + }); + + it("keeps the selected historical result across refreshes and restores focus when its day button disappears", async () => { + const user = userEvent.setup(); + const start = new Date(new Date(now).setHours(8, 0, 0, 0)).getTime(); + const runs = Array.from({ length: 5 }, (_, index) => ({ + run_at_ms: start + index * 60_000, status: "error", duration_ms: index * 1_000, + error: `Failure in run ${index + 1}`, + })); + const job = { ...task, state: { run_history: runs, last_error: "Latest unrelated error" } }; + const { rerender } = render(); + const more = screen.getByRole("button", { name: "+2 more" }); + await user.click(more); + const popover = screen.getByRole("dialog"); + await user.click(within(popover).getAllByRole("button", { name: /PR watch.*Failed/ })[3]); + const detail = await screen.findByRole("dialog", { name: "PR watch" }); + expect(detail).toHaveTextContent("Failure in run 4"); + expect(detail).not.toHaveTextContent("Latest unrelated error"); + expect(within(detail).getByText("3 sec")).toBeVisible(); + rerender(); + expect(detail).toHaveTextContent("Failure in run 4"); + await user.keyboard("{Escape}"); + await waitFor(() => expect(document.activeElement).toHaveClass("automation-calendar")); + }); + + it.each([ + ["skipped", "Skipped"], + ["unrecognized", "Recorded"], + ])("does not label a %s record as completed", (status, label) => { + render(); + const row = screen.getByRole("button", { name: new RegExp(`PR watch.*${label}`) }); + expect(within(row).getByText(label)).toBeVisible(); + fireEvent.click(row); + const dialog = screen.getByRole("dialog", { name: "PR watch" }); + expect(within(dialog).getByText(label)).toBeVisible(); + expect(within(dialog).queryByText("Duration")).not.toBeInTheDocument(); + expect(dialog).not.toHaveTextContent("Completed"); + }); + + it("does not infer success for an older record without a status", () => { + render(); + fireEvent.click(screen.getByRole("button", { name: /PR watch.*Recorded/ })); + const dialog = screen.getByRole("dialog", { name: "PR watch" }); + expect(dialog).not.toHaveTextContent("Completed"); + expect(within(dialog).queryByRole("link")).not.toBeInTheDocument(); + }); + + it("localizes historical results and zero durations in Chinese", async () => { + const language = i18n.language; + onTestFinished(() => i18n.changeLanguage(language)); + await act(() => i18n.changeLanguage("zh-CN")); + render(); + fireEvent.click(screen.getByRole("button", { name: /PR watch.*已完成/ })); + const dialog = screen.getByRole("dialog", { name: "PR watch" }); + for (const text of ["运行结果", "已完成", "耗时", "0秒", "此记录未保存回复正文。"]) { + expect(within(dialog).getByText(text)).toBeVisible(); + } + expect(within(dialog).getByRole("link", { name: "打开对话" })).toBeVisible(); + }); + + it("opens historical results from the narrow agenda with the keyboard", async () => { + vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockReturnValue(new DOMRect(0, 0, 360, 640)); + const user = userEvent.setup(); + render(); + const row = screen.getByRole("button", { name: /PR watch.*Completed/ }); + expect(row.closest(".automation-calendar-agenda")).not.toBeNull(); + expect(document.querySelector(".automation-calendar-grid")).toBeNull(); + row.focus(); + await user.keyboard("{Enter}"); + const dialog = screen.getByRole("dialog", { name: "PR watch" }); + expect(within(dialog).getByText("49.4 sec")).toBeVisible(); + await user.keyboard("{Escape}"); + await waitFor(() => expect(row).toHaveFocus()); }); it("opens the whole day in a popover and hands off to details without expanding the grid", async () => { @@ -479,24 +579,21 @@ describe("Automation task list and detail sheet", () => { expect(dialog.querySelector("p")).toBeNull(); expect(within(dialog).queryByText("Instructions")).not.toBeInTheDocument(); expect(within(dialog).queryByText("System-managed automation")).not.toBeInTheDocument(); - for (const label of ["Schedule", "Next run", "Last run"]) { - expect(within(dialog).getByText(label).tagName).toBe("DT"); - } - expect(within(dialog).getByText("Every 30 minutes")).toBeVisible(); - expect(within(dialog).getByText("Not run yet")).toBeVisible(); + expect(within(dialog).queryByText("Schedule")).not.toBeInTheDocument(); expect(within(dialog).getAllByRole("button")).toHaveLength(2); expect(within(dialog).getByRole("button", { name: "Close" })).toHaveClass("rounded-full", "h-7", "w-7"); - const toggle = within(dialog).getByRole("button", { name: "More details" }); - const metadata = document.getElementById(toggle.getAttribute("aria-controls")!)!; - expect(metadata).toHaveAttribute("data-state", "closed"); + const toggle = within(dialog).getByRole("button", { name: "Task information" }); + expect(screen.queryByRole("dialog", { name: "Task information" })).not.toBeInTheDocument(); fireEvent.click(toggle); - expect(metadata).toHaveAttribute("data-state", "open"); + const metadata = screen.getByRole("dialog", { name: "Task information" }); + for (const label of ["Schedule", "Next run", "Last run"]) { + expect(within(metadata).getByText(label).closest("dt")).not.toBeNull(); + } + expect(within(metadata).getByText("Every 30 minutes")).toBeVisible(); + expect(within(metadata).getByText("Not run yet")).toBeVisible(); expect(within(metadata).getByText("ID")).toBeVisible(); fireEvent.click(toggle); - expect(metadata).toHaveAttribute("data-state", "closed"); - expect(metadata).toHaveAttribute("inert"); - expect(metadata).toHaveClass("inline-disclosure"); - expect(within(metadata).getByText("ID")).toBeInTheDocument(); + expect(screen.queryByRole("dialog", { name: "Task information" })).not.toBeInTheDocument(); }); it("keeps the shared protected detail read-only and does not infer purpose from a task name", () => { @@ -506,6 +603,7 @@ describe("Automation task list and detail sheet", () => { const dialog = screen.getByRole("dialog", { name: "heartbeat" }); expect(within(dialog).queryByText("System-managed automation")).not.toBeInTheDocument(); expect(within(dialog).getByRole("alert")).toHaveTextContent("Background check failed"); + fireEvent.click(within(dialog).getByRole("button", { name: "Task information" })); expect(within(dialog).getByText("Failed")).toBeVisible(); expect(within(dialog).getByText("No next run")).toBeVisible(); expect(dialog).not.toHaveAttribute("aria-describedby"); @@ -517,27 +615,29 @@ describe("Automation task list and detail sheet", () => { expect(dialog).toHaveClass("rounded-modal"); expect(dialog).not.toHaveClass("rounded-[20px]"); const title = within(dialog).getByRole("heading", { name: job.name }); - expect(title).toHaveClass("text-lg", "leading-6"); + expect(title).toHaveClass("text-lg", "font-medium", "leading-snug"); + expect(dialog).toHaveClass("text-sm", "font-normal"); expect(title).not.toHaveClass("text-[22px]"); const close = within(dialog).getByRole("button", { name: "Close" }); expect(close).toHaveClass("rounded-full", "h-7", "w-7"); - const lastRun = within(dialog).getByText("Last run"); - expect(lastRun.closest("dl")).not.toHaveClass("divide-y", "border-y"); - expect(lastRun.parentElement).toHaveClass("py-2.5"); - const details = within(dialog).getByRole("button", { name: "More details" }); + expect(within(dialog).queryByText("Last run")).not.toBeInTheDocument(); + const details = within(dialog).getByRole("button", { name: "Task information" }); expect(details.parentElement).not.toHaveClass("border-t"); expect(details).toHaveAttribute("aria-expanded", "false"); if (!job.protected) { - const taskActions = within(dialog).getByRole("button", { name: "Disable" }).parentElement; - expect(within(dialog).getByRole("button", { name: "Run now" }).parentElement).toBe(taskActions); + expect(within(dialog).queryByRole("switch")).not.toBeInTheDocument(); + const disable = within(dialog).getByRole("button", { name: "Disable" }); + const taskActions = within(dialog).getByRole("button", { name: "Run now" }).parentElement; + expect(disable.parentElement).toBe(taskActions); expect(within(dialog).getByRole("button", { name: "Delete" }).parentElement).toBe(taskActions); const edit = within(dialog).getByRole("button", { name: "Edit" }); - expect(edit.parentElement).toHaveClass("sm:ml-auto", "flex-wrap", "justify-end"); + expect(edit.parentElement).not.toBe(taskActions); + expect(edit.parentElement).toHaveClass("ms-auto", "flex-wrap", "justify-end"); expect(within(dialog).getByRole("link", { name: "Open a chat" }).parentElement).toBe(edit.parentElement); } }); - it("keeps the header summary concise and moves timezone into more details", async () => { + it("keeps schedule and run metadata in task information", async () => { const user = userEvent.setup(); render( { await user.click(screen.getByRole("button", { name: /PR watch/ })); const dialog = screen.getByRole("dialog", { name: "PR watch" }); - const description = within(dialog).getByText("Weekdays at 09:15").parentElement!; - expect(description).toHaveTextContent("Next"); - expect(description).not.toHaveTextContent("Asia/Shanghai"); + for (const text of ["Weekdays at 09:15", "Next run", "Last run", "Asia/Shanghai"]) { + expect(within(dialog).queryByText(text)).not.toBeInTheDocument(); + } - await user.click(within(dialog).getByRole("button", { name: "More details" })); + await user.click(within(dialog).getByRole("button", { name: "Task information" })); + expect(within(dialog).getByText("Weekdays at 09:15")).toBeVisible(); + expect(within(dialog).getByText("Next run").closest("dl")).toContainElement(within(dialog).getByText("Last run")); expect(within(dialog).getByText("Timezone")).toBeVisible(); expect(within(dialog).getByText("Asia/Shanghai")).toBeVisible(); }); @@ -587,8 +689,11 @@ describe("Automation task list and detail sheet", () => { render(); fireEvent.click(screen.getByRole("button", { name: /PR watch/ })); const dialog = screen.getByRole("dialog", { name: "PR watch" }); - expect(dialog).toHaveTextContent("Weekdays at 09:00"); - expect(dialog).toHaveTextContent("Asia/Shanghai"); + expect(dialog).not.toHaveTextContent("Weekdays at 09:00"); + expect(dialog).not.toHaveTextContent("Asia/Shanghai"); + fireEvent.click(within(dialog).getByRole("button", { name: "Task information" })); + expect(screen.getByRole("dialog", { name: "Task information" })).toHaveTextContent("Asia/Shanghai"); + expect(screen.getByRole("dialog", { name: "Task information" })).toHaveTextContent("Weekdays at 09:00"); expect(dialog).not.toHaveTextContent("·"); }); @@ -607,8 +712,8 @@ describe("Automation task list and detail sheet", () => { render(); fireEvent.click(screen.getByRole("button", { name: /PR watch/ })); const dialog = screen.getByRole("dialog", { name: "PR watch" }); + fireEvent.click(within(dialog).getByRole("button", { name: "Task information" })); expect(within(dialog).getByText(summary)).toBeVisible(); - fireEvent.click(within(dialog).getByRole("button", { name: "More details" })); expect(dialog).not.toHaveTextContent(expr); expect(dialog).not.toHaveTextContent("Linked chat"); }); @@ -620,6 +725,7 @@ describe("Automation task list and detail sheet", () => { const job: SessionAutomationJob = { ...task, schedule: { kind: "cron", expr: "30 13 25 * *" } }; const { unmount } = render(); fireEvent.click(screen.getByRole("button", { name: /PR watch/ })); + fireEvent.click(screen.getByRole("button", { name: "任务信息" })); expect(screen.getByText("每月 25 日 13:30")).toBeVisible(); unmount(); render( {}} onSave={vi.fn()} />); @@ -697,6 +803,7 @@ describe("Automation task list and detail sheet", () => { expect(action).toHaveBeenCalledWith("disable", task); rerender(); expect(screen.getByRole("dialog", { name: "PR watch" })).toBeVisible(); + expect(screen.getByRole("button", { name: "Enable" })).toBeEnabled(); fireEvent.click(screen.getByRole("button", { name: "Enable" })); expect(action).toHaveBeenLastCalledWith("enable", { ...task, enabled: false }); rerender(); @@ -716,7 +823,7 @@ describe("Automation task list and detail sheet", () => { expect(action).toHaveBeenLastCalledWith("disable", task); const disabledTask = { ...task, enabled: false }; rerender(); - expect(within(dialog).getByText("已停用")).toBeVisible(); + expect(within(dialog).getByRole("button", { name: "启用", exact: true })).toBeEnabled(); fireEvent.click(within(dialog).getByRole("button", { name: "启用", exact: true })); expect(action).toHaveBeenLastCalledWith("enable", disabledTask); expect(dialog).not.toHaveTextContent("暂停"); @@ -742,7 +849,7 @@ describe("Automation task list and detail sheet", () => { expect(screen.queryByRole("button", { name: /PR watch/ })).not.toBeInTheDocument(); }); - it("uses chevrons only for disclosures, while task rows open dialogs", async () => { + it("opens task information from an icon and closes only the popover on Escape", async () => { const user = userEvent.setup(); render(); for (const name of [/PR watch/]) { @@ -750,11 +857,17 @@ describe("Automation task list and detail sheet", () => { expect(row).toHaveAttribute("aria-haspopup", "dialog"); expect(row.querySelector(".lucide-chevron-right, .lucide-chevron-down")).toBeNull(); await user.click(row); - const details = screen.getByRole("button", { name: "More details" }); - expect(details.querySelector("svg")).toHaveClass("lucide-chevron-down"); - await user.click(details); + const details = screen.getByRole("button", { name: "Task information" }); + expect(details.querySelector("svg")).toHaveClass("lucide-info"); + expect(details).toHaveTextContent(""); + act(() => details.focus()); + await user.keyboard("{Enter}"); expect(details).toHaveAttribute("aria-expanded", "true"); - expect(screen.getByRole("dialog")).toBeVisible(); + expect(screen.getByRole("dialog", { name: "Task information" })).toBeVisible(); + await user.keyboard("{Escape}"); + expect(screen.queryByRole("dialog", { name: "Task information" })).not.toBeInTheDocument(); + expect(screen.getByRole("dialog", { name: "PR watch" })).toBeVisible(); + expect(details).toHaveFocus(); await user.click(screen.getByRole("button", { name: "Close" })); } }); @@ -892,13 +1005,33 @@ describe("Automation task list and detail sheet", () => { await user.click(screen.getByRole("button", { name: "Run now" })); expect(action).toHaveBeenCalledWith("run", task); rerender(); - for (const name of ["Edit", "Disable", "Run now", "Delete"]) { + for (const name of ["Edit", "Run now", "Delete"]) { expect(screen.getByRole("button", { name })).toBeDisabled(); } + expect(screen.getByRole("button", { name: "Disable" })).toBeDisabled(); rerender(); expect(within(screen.getByRole("dialog")).getByRole("alert")).toHaveTextContent("Unable to run task"); }); + it("toggles with the keyboard and keeps the server state while updating", async () => { + const user = userEvent.setup(); + const action = vi.fn(); + const { rerender } = render(); + await user.click(screen.getByRole("button", { name: /PR watch/ })); + const control = screen.getByRole("button", { name: "Disable" }); + control.focus(); + await user.keyboard(" "); + expect(action).toHaveBeenCalledWith("disable", task); + expect(control).toHaveTextContent("Disable"); + rerender(); + expect(control).toBeDisabled(); + await user.click(control); + expect(action).toHaveBeenCalledTimes(1); + rerender(); + expect(control).toHaveTextContent("Enable"); + expect(control).toBeEnabled(); + }); + it("does not allow running a pending task or resuming an unlinked task", async () => { const user = userEvent.setup(); const { rerender } = render( { const row = screen.getByRole("button", { name: /PR watch.*Failed/ }); expect(within(openFilters()).getByRole("menuitemradio", { name: "Needs attention 1" })).toBeVisible(); fireEvent.click(row); - expect(within(screen.getByRole("dialog")).getByText("Failed")).toBeVisible(); - expect(within(screen.getByRole("dialog")).queryByText(/Completed/)).not.toBeInTheDocument(); + const info = screen.getByRole("dialog", { name: "PR watch" }); + expect(within(info).getByText("Failed")).toBeVisible(); + expect(within(info).getByText("Connection interrupted")).toBeVisible(); + expect(within(info).queryByText(/Completed/)).not.toBeInTheDocument(); }); it("allows expanding long instructions without exposing technical metadata by default", () => { @@ -946,12 +1081,12 @@ describe("Automation task list and detail sheet", () => { }] }} />); fireEvent.click(screen.getByRole("button", { name: /PR watch/ })); const dialog = screen.getByRole("dialog"); - expect(within(dialog).getByText("Not run yet")).toBeVisible(); + expect(within(dialog).queryByText("Not run yet")).not.toBeInTheDocument(); fireEvent.click(within(dialog).getByRole("button", { name: "Show full message" })); expect(within(dialog).getByRole("button", { name: "Show less" })).toHaveAttribute("aria-expanded", "true"); - const disclosure = within(dialog).getByRole("button", { name: "More details" }); + const disclosure = within(dialog).getByRole("button", { name: "Task information" }); expect(disclosure).toHaveAttribute("aria-expanded", "false"); - fireEvent.click(within(dialog).getByText("More details")); + fireEvent.click(disclosure); expect(disclosure).toHaveAttribute("aria-expanded", "true"); expect(within(dialog).getByText(task.id)).toBeVisible(); }); @@ -962,7 +1097,7 @@ describe("Automation task list and detail sheet", () => { const dialog = screen.getByRole("dialog", { name: "PR watch" }); expect(within(dialog).queryByText("Instructions")).not.toBeInTheDocument(); expect(within(dialog).queryByText("System-managed automation")).not.toBeInTheDocument(); - expect(within(dialog).getByText("Last run")).toBeVisible(); + expect(within(dialog).queryByText("Last run")).not.toBeInTheDocument(); expect(within(dialog).getByRole("button", { name: "Edit" })).toBeEnabled(); }); }); diff --git a/webui/src/tests/session-info-popover.test.tsx b/webui/src/tests/session-info-popover.test.tsx index dc4b8a5ee..ffabdcd78 100644 --- a/webui/src/tests/session-info-popover.test.tsx +++ b/webui/src/tests/session-info-popover.test.tsx @@ -79,7 +79,7 @@ describe("SessionInfoPopover", () => { await user.click(row); const detail = screen.getByRole("dialog", { name: "Morning check" }); expect(detail).toHaveClass("max-w-[520px]", "rounded-modal"); - expect(within(detail).getByText("Instructions")).toBeInTheDocument(); + expect(within(detail).queryByText("Instructions")).not.toBeInTheDocument(); expect(within(detail).getByText("Check the project status")).toBeInTheDocument(); await user.click(within(detail).getByRole("button", { name: "Close" })); await waitFor(() => expect(screen.queryByRole("dialog", { name: "Morning check" })).not.toBeInTheDocument()); @@ -110,7 +110,7 @@ describe("SessionInfoPopover", () => { { id: "job-1" }, 20_000, ); - expect(await within(detail).findByRole("button", { name: "Enable" })).toBeInTheDocument(); + await waitFor(() => expect(within(detail).getByRole("button", { name: "Enable" })).toBeVisible()); }); it("returns from the shared editor to the same task detail", async () => {