fix(webui): show per-run automation replies and simplify details

This commit is contained in:
chengyongru authored and chengyongru committed 2026-09-13 05:43:05 +08:00
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:
+2 -2
View File
@@ -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
+3 -3
View File
@@ -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)
+6 -2
View File
@@ -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:]
+11
View File
@@ -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,
)
+83
View File
@@ -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
+45
View File
@@ -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,
+118
View File
@@ -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
@@ -571,6 +571,7 @@ export function SettingsPage({
return (
<div className="settings-stack">
<AutomationsSettings
token={token}
payload={automations}
titleOverrides={titleOverrides}
settingsSnapshot={controller.settings}
@@ -1,6 +1,7 @@
import { CircleAlert, Loader2, X } from "lucide-react";
import { useId, useLayoutEffect, useMemo, useRef, useState } from "react";
import { AutomationRunDialog, type AutomationRunRecord } from "@/components/settings/system/AutomationRunDialog";
import { Button } from "@/components/ui/button";
import { formControlFocusClassName } from "@/components/ui/form-control";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
@@ -11,9 +12,8 @@ type CalendarEntry = {
id: string;
job: SessionAutomationJob;
startMs: number;
endMs: number | null;
kind: "planned" | "recorded";
status: string | null;
run: AutomationRunRecord | null;
};
type CalendarCopy = {
@@ -25,10 +25,12 @@ type CalendarCopy = {
close: string;
noEntries: string;
completed: string;
skipped: string;
system: string;
};
interface AutomationCalendarProps {
token?: string;
jobs: SessionAutomationJob[];
month: Date;
locale: string;
@@ -61,17 +63,15 @@ function entriesForJobs(jobs: SessionAutomationJob[]): CalendarEntry[] {
? history
: [{
run_at_ms: job.state.last_run_at_ms,
status: job.state.last_status ?? "ok",
status: job.state.last_status ?? "unknown",
error: job.state.last_error,
}];
const recorded = recordedRuns.map((run, index) => ({
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 = (
<>
<span className="min-w-0 flex-1">
<span className="block truncate font-medium text-foreground">{name}</span>
<span className="mt-0.5 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-[10px] leading-4 text-muted-foreground">
<span className={cn("block truncate", entry.kind === "recorded" && !failed ? "font-normal text-muted-foreground" : "font-medium text-foreground")}>{name}</span>
<span className={cn("mt-0.5 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-[10px] leading-4", failed ? "text-destructive" : "text-muted-foreground")}>
{running ? <Loader2 className="h-3 w-3 animate-spin motion-reduce:animate-none" aria-hidden /> : null}
{failed ? <CircleAlert className="h-3 w-3" aria-hidden /> : null}
<span className="tabular-nums">{entryTime(entry, locale)}</span>
{compact ? <span>{status}</span> : null}
{compact || entry.kind === "recorded" ? <span>{status}</span> : null}
{entry.job.protected ? <span>{copy.system}</span> : null}
</span>
</span>
@@ -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}
</button>
@@ -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<HTMLButtonElement | null>(null);
const pendingSelection = useRef<SessionAutomationJob | null>(null);
const pendingSelection = useRef<CalendarEntry | null>(null);
return (
<Popover open={open} onOpenChange={setOpen}>
@@ -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);
}}
>
<div className="mb-1 flex items-center gap-2 px-2 py-1">
@@ -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<HTMLElement | null>(null);
const runTrigger = useRef<HTMLElement | null>(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 (
<section ref={calendarRef} className="automation-calendar overflow-hidden bg-[hsl(var(--settings-surface))]">
<section ref={calendarRef} tabIndex={-1} className="automation-calendar overflow-hidden bg-[hsl(var(--settings-surface))]">
<div className="automation-calendar-header bg-foreground/[0.025]">
{wideCalendar ? <div className="automation-calendar-weekdays" aria-hidden>
{weekdayLabels.map((label) => <div key={label}>{label}</div>)}
@@ -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}
</div>
@@ -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
)}
</div> : null}
{selectedRun ? <AutomationRunDialog
token={token}
job={selectedRun.job} run={selectedRun.run} locale={locale} open={runOpen}
onOpenChange={setRunOpen}
onCloseAutoFocus={(event) => {
event.preventDefault();
if (runOpen) return;
setSelectedRun(null);
const target = runTrigger.current?.isConnected ? runTrigger.current : calendarRef.current;
target?.focus({ preventScroll: true });
}}
/> : null}
</section>
);
}
@@ -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<SessionAutomationJob["state"]["run_history"]>[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 (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent
{...(!open ? { inert: "", "aria-hidden": true } : {})}
className="flex max-h-[calc(100dvh-2rem)] max-w-[520px] flex-col gap-0 p-0 text-sm font-normal leading-normal text-foreground"
onCloseAutoFocus={onCloseAutoFocus}
>
<DialogHeader className="shrink-0 px-6 pb-4 pr-14 pt-5 text-left">
<DialogTitle className="min-w-0 break-words text-lg font-medium leading-snug tracking-normal text-balance">
{job.name || job.id}
</DialogTitle>
<DialogDescription className="text-sm font-normal text-muted-foreground">
<time dateTime={new Date(run.run_at_ms).toISOString()}>
{new Intl.DateTimeFormat(locale, { dateStyle: "medium", timeStyle: "short" }).format(run.run_at_ms)}
</time>
</DialogDescription>
</DialogHeader>
<div className="min-h-0 space-y-4 overflow-y-auto overscroll-contain px-6 pb-6">
<dl className="space-y-3">
<div className="flex items-start justify-between gap-4">
<dt className="text-muted-foreground">{t("settings.automations.runDetails.result")}</dt>
<dd className={cn("flex items-center gap-1.5 text-end", failed && "text-destructive")}>
{failed ? <CircleAlert className="h-3.5 w-3.5 shrink-0" strokeWidth={1.5} aria-hidden /> : null}
{status}
</dd>
</div>
{duration != null && Number.isFinite(duration) && duration >= 0 ? (
<div className="flex items-start justify-between gap-4">
<dt className="text-muted-foreground">{t("settings.automations.runDetails.duration")}</dt>
<dd className="text-end tabular-nums">{new Intl.NumberFormat(locale, {
style: "unit", unit: "second", unitDisplay: "short",
maximumFractionDigits: duration < 1000 ? 3 : 1,
}).format(duration / 1000)}</dd>
</div>
) : null}
</dl>
{run.error ? <p className={cn("whitespace-pre-wrap break-words [overflow-wrap:anywhere]", failed && "text-destructive")}>{run.error}</p> : null}
{!currentResult || currentResult.status === "loading" ? (
<p role="status" className="text-muted-foreground">{t("settings.automations.runDetails.loading")}</p>
) : currentResult.status === "error" ? (
<div className="flex flex-wrap items-center justify-between gap-2">
<p role="alert" className="text-muted-foreground">{t("settings.automations.runDetails.loadError")}</p>
<Button variant="ghost" size="sm" onClick={() => setAttempt((value) => value + 1)}>
{t("settings.automations.runDetails.retry")}
</Button>
</div>
) : currentResult.response?.trim() ? (
<MarkdownText className="min-w-0 text-sm [overflow-wrap:anywhere]">{currentResult.response}</MarkdownText>
) : (
<p className="text-muted-foreground">{t(currentResult.response === null
? "settings.automations.runDetails.noOutput"
: "settings.automations.runDetails.emptyOutput")}</p>
)}
</div>
{chatHref ? (
<div className="flex shrink-0 justify-end border-t border-border/45 px-6 py-3">
<Button asChild variant="ghost" size="sm" className="font-normal text-muted-foreground">
<a href={chatHref}>{t("settings.automations.emptyAction")}</a>
</Button>
</div>
) : null}
</DialogContent>
</Dialog>
);
}
@@ -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<string, string> = {};
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<string, string>;
settingsSnapshot?: SettingsPayload | null;
@@ -253,8 +256,8 @@ export function AutomationsSettings({
<div className="automation-view-switch" role="group" aria-label={tx("settings.automations.views.label", "Automation view")}>
<SegmentedControl
value={view}
className="bg-[var(--automation-view-track)]"
itemClassName="min-h-8"
className="rounded-[var(--radius-panel)] bg-[var(--automation-view-track)]"
itemClassName="min-h-8 rounded-[calc(var(--radius-panel)-0.25rem)]"
options={[
{ value: "tasks", label: tx("settings.automations.views.tasks", "Tasks") },
{ value: "calendar", label: tx("settings.automations.views.calendar", "Calendar") },
@@ -270,7 +273,7 @@ export function AutomationsSettings({
{filters ? <div className="automation-panel-filters min-w-0">{filters}</div> : null}
{view === "calendar" ? (
<div className="automation-calendar-navigation flex shrink-0 items-center gap-1">
<Button type="button" variant="outline" size="sm" className="h-8 rounded-control px-3 text-[12px]"
<Button type="button" variant="ghost" size="sm" className="h-8 rounded-full bg-background/60 px-3 text-[12px] text-foreground"
onClick={() => { const today = new Date(); setMonth(new Date(today.getFullYear(), today.getMonth(), 1)); }}>
{tx("settings.automations.calendar.today", "Today")}
</Button>
@@ -334,6 +337,7 @@ export function AutomationsSettings({
</section>
) : (
<AutomationCalendar
token={token}
jobs={filtered}
month={month}
locale={locale}
@@ -351,6 +355,7 @@ export function AutomationsSettings({
? tx("settings.automations.noMatches", "No automations match this view.")
: tx("settings.automations.empty", "No automations yet."),
completed: tx("settings.automations.status.completed", "Completed"),
skipped: tx("settings.automations.skipped", "Skipped"),
}}
onInspect={inspectJob}
/>
@@ -412,10 +417,10 @@ export function AutomationDetailDialog({
<Dialog open={open} onOpenChange={onOpenChange}>
{job ? (
<DialogContent
{...(job.protected ? { "aria-describedby": undefined } : {})}
aria-describedby={undefined}
{...(!open ? { inert: "", "aria-hidden": true } : {})}
className={cn(
"flex max-h-[calc(100dvh-2rem)] max-w-[520px] flex-col gap-0 overflow-hidden p-0",
"flex max-h-[calc(100dvh-2rem)] max-w-[520px] flex-col gap-0 p-0 text-sm font-normal leading-normal text-foreground",
job.protected && "max-w-[440px]",
)}
onCloseAutoFocus={onCloseAutoFocus}
@@ -475,40 +480,75 @@ function AutomationDetailPanel({
return (
<>
<DialogHeader className="shrink-0 px-6 pb-3 pr-14 pt-5 text-left">
<DialogTitle className="min-w-0 break-words leading-6 text-balance">{job.name || job.id}</DialogTitle>
{canManage ? (
<DialogDescription className="flex flex-wrap items-center gap-x-4 gap-y-1 text-[13px] leading-5">
<span className="font-medium text-foreground/80">{formatAutomationSchedule(job, locale, tx)}</span>
{!localTrigger ? <span className="inline-flex min-w-0 items-center gap-1.5">
<span>{tx("settings.automations.labels.next", "Next")}</span>
<span className="text-foreground/80" title={formatAutomationNextTitle(job, locale, tx)}>
{formatAutomationNext(job, tx)}
</span>
</span> : null}
</DialogDescription>
) : null}
<div className="absolute right-11 top-2.5">
<Popover>
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<PopoverTrigger asChild>
<Button variant="ghost" size="icon" className="h-7 w-7 shrink-0 rounded-full text-muted-foreground"
aria-label={tx("settings.automations.taskInfo", "Task information")}>
<Info className="h-3.5 w-3.5" strokeWidth={1.5} aria-hidden />
</Button>
</PopoverTrigger>
</TooltipTrigger>
<TooltipContent>{tx("settings.automations.taskInfo", "Task information")}</TooltipContent>
</Tooltip>
</TooltipProvider>
<PopoverContent side="bottom" align="end" collisionPadding={16}
aria-label={tx("settings.automations.taskInfo", "Task information")}
className="w-80 max-w-[calc(100vw-2rem)] p-4 text-sm font-normal">
<dl>
<AutomationDetail label={tx("settings.automations.labels.schedule", "Schedule")}>
{formatAutomationSchedule(job, locale, tx)}
</AutomationDetail>
{!localTrigger ? (
<AutomationDetail label={tx("settings.automations.sort.next", "Next run")} title={formatAutomationNextTitle(job, locale, tx)}>
{formatAutomationNext(job, tx)}
</AutomationDetail>
) : null}
<AutomationDetail label={tx("settings.automations.sort.last", "Last run")} title={job.state.last_run_at_ms ? fmtDateTime(job.state.last_run_at_ms, locale) : undefined}>
{job.state.last_run_at_ms
? <span className="flex flex-wrap gap-x-3 gap-y-1">
{lastStatus ? <span>{lastStatus}</span> : null}
<span>{relativeTime(job.state.last_run_at_ms)}</span>
</span>
: lastStatus || tx("settings.automations.neverRun", "Not run yet")}
</AutomationDetail>
{timezone ? (
<AutomationDetail label={tx("settings.automations.fields.timezone", "Timezone")}>{timezone}</AutomationDetail>
) : null}
{job.delete_after_run ? <AutomationDetail label={tx("settings.automations.oneShot", "One-time")}>{tx("settings.automations.oneShotHint", "Removed after running")}</AutomationDetail> : null}
{job.created_at_ms ? <AutomationDetail label={tx("settings.automations.labels.created", "Created")}>{fmtDateTime(job.created_at_ms, locale)}</AutomationDetail> : null}
{job.updated_at_ms ? <AutomationDetail label={tx("settings.automations.labels.updated", "Updated")}>{fmtDateTime(job.updated_at_ms, locale)}</AutomationDetail> : null}
<AutomationDetail label="ID"><span className="break-all font-mono">{job.id}</span></AutomationDetail>
</dl>
</PopoverContent>
</Popover>
</div>
<DialogHeader className="shrink-0 px-6 pb-3 pr-24 pt-5 text-left">
<DialogTitle className="min-w-0 break-words text-lg font-medium leading-snug tracking-normal text-balance">{job.name || job.id}</DialogTitle>
</DialogHeader>
<div className="min-h-0 overflow-y-auto overscroll-contain px-6 pb-3">
{canManage && message.trim() ? <section className="pb-4">
<div className="flex items-center justify-between gap-3 text-[12px] text-muted-foreground">
<span>{localTrigger ? tx("settings.automations.fields.command", "Command") : tx("settings.automations.instructions", "Instructions")}</span>
{localTrigger && command ? (
<Button variant="ghost" size="sm" onClick={() => {
{localTrigger && command ? (
<div className="mb-2 flex items-center justify-between gap-3 text-sm text-muted-foreground">
<span>{tx("settings.automations.fields.command", "Command")}</span>
<Button variant="ghost" size="sm" className="font-normal text-muted-foreground" onClick={() => {
void copyTextToClipboard(command).then((ok) => { if (ok) setCommandCopied(true); });
}}>
{commandCopied ? <Check className="mr-1.5 h-3.5 w-3.5" aria-hidden /> : <Clipboard className="mr-1.5 h-3.5 w-3.5" aria-hidden />}
{commandCopied ? tx("settings.automations.commandCopied", "Copied") : tx("settings.automations.copyCommand", "Copy")}
</Button>
) : null}
</div>
<div className="mt-2">
<ExpandableText id={messageId} expanded={messageExpanded || !messageNeedsExpansion} lines={6} className={cn("whitespace-pre-wrap break-words text-[13px] leading-5 text-foreground [overflow-wrap:anywhere]", localTrigger && "font-mono text-[12px]")}>
</div>
) : null}
<div>
<ExpandableText id={messageId} expanded={messageExpanded || !messageNeedsExpansion} lines={6} className={cn("whitespace-pre-wrap break-words text-sm leading-normal text-foreground [overflow-wrap:anywhere]", localTrigger && "font-mono")}>
{message}
</ExpandableText>
</div>
{messageNeedsExpansion ? (
<button type="button" aria-expanded={messageExpanded} aria-controls={messageId} onClick={() => setMessageExpanded((value) => !value)} className="mt-2 rounded-sm text-[12px] text-muted-foreground underline-offset-4 hover:text-foreground hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
<button type="button" aria-expanded={messageExpanded} aria-controls={messageId} onClick={() => setMessageExpanded((value) => !value)} className="mt-2 rounded-sm text-sm text-muted-foreground underline-offset-4 hover:text-foreground hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
{messageExpanded ? tx("settings.automations.message.showLess", "Show less") : tx("settings.automations.message.showMore", "Show full message")}
</button>
) : null}
@@ -516,65 +556,24 @@ function AutomationDetailPanel({
{job.state.last_error ? <AutomationError message={job.state.last_error} /> : null}
{error ? <AutomationError message={error} /> : null}
<dl>
{job.protected ? (
<>
<AutomationDetail label={tx("settings.automations.labels.schedule", "Schedule")}>
{formatAutomationSchedule(job, locale, tx)}
</AutomationDetail>
{timezone ? (
<AutomationDetail label={tx("settings.automations.fields.timezone", "Timezone")}>
{timezone}
</AutomationDetail>
) : null}
<AutomationDetail label={tx("settings.automations.sort.next", "Next run")} title={formatAutomationNextTitle(job, locale, tx)}>
{formatAutomationNext(job, tx)}
</AutomationDetail>
</>
) : null}
<AutomationDetail label={tx("settings.automations.sort.last", "Last run")} title={job.state.last_run_at_ms ? fmtDateTime(job.state.last_run_at_ms, locale) : undefined}>
{job.state.last_run_at_ms
? <span className="flex flex-wrap justify-end gap-x-3 gap-y-1">
{lastStatus ? <span>{lastStatus}</span> : null}
<span>{relativeTime(job.state.last_run_at_ms)}</span>
</span>
: lastStatus || tx("settings.automations.neverRun", "Not run yet")}
</AutomationDetail>
{!job.protected && job.origin?.channel && job.origin.channel !== "websocket" ? (
<AutomationDetail label={tx("settings.automations.labels.origin", "Linked chat")}>
{automationChannelLabel(job.origin.channel, t)}
</AutomationDetail>
) : null}
</dl>
<Disclosure
className="mt-2"
summaryClassName={cn("flex min-h-10 cursor-pointer items-center justify-between gap-3 rounded-control py-2.5 text-[13px] text-muted-foreground transition-colors hover:text-foreground", formControlFocusClassName)}
summary={<>
{tx("settings.automations.moreDetails", "More details")}
<ChevronDown className="h-3.5 w-3.5 transition-transform duration-200 group-data-[state=open]/disclosure:rotate-180 motion-reduce:transition-none" aria-hidden />
</>}
>
<dl>
{timezone && canManage ? (
<AutomationDetail label={tx("settings.automations.fields.timezone", "Timezone")}>
{timezone}
</AutomationDetail>
) : null}
{job.delete_after_run ? <AutomationDetail label={tx("settings.automations.oneShot", "One-time")}>{tx("settings.automations.oneShotHint", "Removed after running")}</AutomationDetail> : null}
{job.created_at_ms ? <AutomationDetail label={tx("settings.automations.labels.created", "Created")}>{fmtDateTime(job.created_at_ms, locale)}</AutomationDetail> : null}
{job.updated_at_ms ? <AutomationDetail label={tx("settings.automations.labels.updated", "Updated")}>{fmtDateTime(job.updated_at_ms, locale)}</AutomationDetail> : null}
<AutomationDetail label="ID"><span className="break-all font-mono text-[11px]">{job.id}</span></AutomationDetail>
</dl>
</Disclosure>
</div>
{canManage ? (
<div className="flex shrink-0 flex-col gap-2 border-t border-border/45 px-6 py-3 sm:flex-row sm:items-center">
<div className="flex min-w-0 flex-wrap items-center gap-1">
<Button variant="ghost" size="sm" className="text-muted-foreground" disabled={busy || !canToggle} onClick={() => void onAction(job.enabled ? "disable" : "enable", job)}>
{actionKey === `${job.enabled ? "disable" : "enable"}:${job.id}` ? <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden /> : null}
<div className="flex shrink-0 flex-wrap items-center gap-x-6 gap-y-2 border-t border-border/45 px-6 py-3">
<div className="flex max-w-full flex-wrap gap-2">
<Button variant="ghost" size="sm" className="font-normal text-muted-foreground" disabled={busy || !canToggle}
onClick={() => void onAction(job.enabled ? "disable" : "enable", job)}>
{actionKey === `enable:${job.id}` || actionKey === `disable:${job.id}`
? <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden /> : null}
{job.enabled ? tx("settings.automations.pause", "Disable") : tx("settings.automations.resume", "Enable")}
</Button>
{!localTrigger ? (
<Button variant="ghost" size="sm" className="text-muted-foreground" disabled={!canRun || busy} onClick={() => void onAction("run", job)}>
<Button variant="ghost" size="sm" className="font-normal text-muted-foreground" disabled={!canRun || busy} onClick={() => void onAction("run", job)}>
{actionKey === `run:${job.id}` ? <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden /> : null}
{tx("settings.automations.runNow", "Run now")}
</Button>
@@ -582,18 +581,18 @@ function AutomationDetailPanel({
<Button
variant="ghost"
size="sm"
className="text-destructive hover:bg-destructive/10 hover:text-destructive"
className="font-normal text-muted-foreground hover:bg-destructive/10 hover:text-destructive focus-visible:text-destructive"
disabled={busy}
onClick={() => onRequestDelete(job)}
>
{tx("settings.automations.delete", "Delete")}
</Button>
</div>
<div className="flex max-w-full flex-wrap justify-end gap-2 sm:ml-auto">
<Button variant="outline" size="sm" disabled={busy} onClick={() => onRequestEdit(job)}>
<div className="ms-auto flex max-w-full flex-wrap justify-end gap-2">
<Button variant="ghost" size="sm" className="font-normal text-muted-foreground" disabled={busy} onClick={() => onRequestEdit(job)}>
{tx("settings.automations.edit", "Edit")}
</Button>
{originHref ? <Button asChild size="sm"><a href={originHref}>{tx("settings.automations.emptyAction", "Open a chat")}</a></Button> : null}
{originHref ? <Button asChild variant="ghost" size="sm" className="font-normal text-muted-foreground"><a href={originHref}>{tx("settings.automations.emptyAction", "Open a chat")}</a></Button> : null}
</div>
</div>
) : 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 (
<div className="grid min-w-0 grid-cols-[minmax(6.5rem,0.75fr)_minmax(0,1.75fr)] items-start gap-4 py-2.5 text-[13px] leading-5">
<div className="grid min-w-0 grid-cols-[minmax(6.5rem,0.75fr)_minmax(0,1.75fr)] items-start gap-4 py-2.5 text-sm leading-normal">
<dt className="text-muted-foreground">{label}</dt>
<dd className="min-w-0 break-words text-right text-foreground [overflow-wrap:anywhere]" title={title}>{children}</dd>
<dd className="min-w-0 break-words text-start text-foreground [overflow-wrap:anywhere]" title={title}>{children}</dd>
</div>
);
}
+2 -1
View File
@@ -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;
+10
View File
@@ -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",
+10
View File
@@ -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",
+10
View File
@@ -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",
+10
View File
@@ -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",
+10
View File
@@ -888,6 +888,16 @@
"notEnabled": "無効"
},
"automations": {
"taskInfo": "タスク情報",
"runDetails": {
"loading": "応答を読み込み中…",
"loadError": "応答を読み込めませんでした。",
"retry": "再試行",
"emptyOutput": "応答は生成されませんでした。",
"result": "実行結果",
"duration": "所要時間",
"noOutput": "この記録に応答本文は保存されていません。"
},
"create": "自動タスクを作成",
"createPrompt": "nanobot に何を自動化してほしいですか?",
"createInput": "自動タスクを説明",
+10
View File
@@ -888,6 +888,16 @@
"notEnabled": "비활성화됨"
},
"automations": {
"taskInfo": "작업 정보",
"runDetails": {
"loading": "응답을 불러오는 중…",
"loadError": "응답을 불러오지 못했습니다.",
"retry": "다시 시도",
"emptyOutput": "생성된 응답이 없습니다.",
"result": "실행 결과",
"duration": "소요 시간",
"noOutput": "이 기록에는 응답 본문이 저장되지 않았습니다."
},
"create": "자동화 만들기",
"createPrompt": "nanobot이 무엇을 자동으로 해주면 좋을까요?",
"createInput": "자동화 설명",
+10
View File
@@ -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",
+10
View File
@@ -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",
+10
View File
@@ -1088,6 +1088,16 @@
"notEnabled": "未启用"
},
"automations": {
"taskInfo": "任务信息",
"runDetails": {
"loading": "正在加载回复…",
"loadError": "回复加载失败。",
"retry": "重试",
"emptyOutput": "本次运行未生成回复。",
"result": "运行结果",
"duration": "耗时",
"noOutput": "此记录未保存回复正文。"
},
"create": "创建自动任务",
"createPrompt": "想让 nanobot 自动帮你做什么?",
"createInput": "描述一个自动任务",
+10
View File
@@ -888,6 +888,16 @@
"notEnabled": "未啟用"
},
"automations": {
"taskInfo": "任務資訊",
"runDetails": {
"loading": "正在載入回覆…",
"loadError": "回覆載入失敗。",
"retry": "重試",
"emptyOutput": "本次執行未產生回覆。",
"result": "執行結果",
"duration": "耗時",
"noOutput": "此記錄未儲存回覆正文。"
},
"create": "建立自動任務",
"createPrompt": "想讓 nanobot 自動幫你做什麼?",
"createInput": "描述自動任務",
+13
View File
@@ -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",
+10
View File
@@ -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,
@@ -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(<AutomationRunDialog {...props} />);
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(<AutomationRunDialog {...props} />);
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(<AutomationRunDialog {...props} />);
const firstSignal = fetchResult.mock.calls[0][4]!;
rerender(<AutomationRunDialog {...props} run={{ ...run, run_at_ms: 2000 }} />);
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(<AutomationRunDialog {...props} job={{ ...job, kind: "local_trigger" }} />);
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(<AutomationRunDialog {...props} open={false} />);
await waitFor(() => expect(fetchResult).not.toHaveBeenCalled());
});
});
+185 -50
View File
@@ -127,7 +127,7 @@ describe("Automation task list and detail sheet", () => {
render(<Harness payload={{ jobs: [{ ...triggerTask, state: {
run_history: [{ run_at_ms: now, duration_ms: 60_000, status: "ok" }],
} }] }} />);
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(<Harness payload={{ jobs: [jobWithHistory] }} />);
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(<Harness payload={{ jobs: [job] }} />);
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(<Harness payload={{ jobs: [{ ...job, state: { run_history: [runs[4]] } }] }} />);
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(<Harness payload={{ jobs: [{ ...task, state: {
run_history: [{ run_at_ms: now, status }],
} }] }} />);
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(<Harness payload={{ jobs: [{ ...task, enabled: false, origin: null, state: {
last_run_at_ms: now,
} }] }} />);
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(<Harness payload={{ jobs: [{ ...task, state: {
run_history: [{ run_at_ms: now, status: "ok", duration_ms: 0 }],
} }] }} />);
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(<Harness payload={{ jobs: [{ ...task, state: {
run_history: [{ run_at_ms: now, status: "ok", duration_ms: 49_427 }],
} }] }} />);
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(<Harness payload={{ jobs: [{
...task,
@@ -546,11 +646,13 @@ describe("Automation task list and detail sheet", () => {
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(<Harness payload={{ jobs: [cronTask] }} />);
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(<Harness payload={{ jobs: [{ ...task, schedule: { kind: "cron", expr } }] }} />);
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(<Harness payload={{ jobs: [job] }} />);
fireEvent.click(screen.getByRole("button", { name: /PR watch/ }));
fireEvent.click(screen.getByRole("button", { name: "任务信息" }));
expect(screen.getByText("每月 25 日 13:30")).toBeVisible();
unmount();
render(<AutomationEditDialog job={job} saving={false} onOpenChange={() => {}} onSave={vi.fn()} />);
@@ -697,6 +803,7 @@ describe("Automation task list and detail sheet", () => {
expect(action).toHaveBeenCalledWith("disable", task);
rerender(<Harness payload={{ jobs: [{ ...task, enabled: false }] }} onAction={action} filter="active" />);
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(<Harness payload={{ jobs: [] }} />);
@@ -716,7 +823,7 @@ describe("Automation task list and detail sheet", () => {
expect(action).toHaveBeenLastCalledWith("disable", task);
const disabledTask = { ...task, enabled: false };
rerender(<Harness payload={{ jobs: [disabledTask] }} onAction={action} />);
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(<Harness />);
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(<Harness actionKey="run:private-job-id" />);
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(<Harness error="Unable to run task" />);
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(<Harness onAction={action} />);
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(<Harness onAction={action} actionKey={`disable:${task.id}`} />);
expect(control).toBeDisabled();
await user.click(control);
expect(action).toHaveBeenCalledTimes(1);
rerender(<Harness onAction={action} payload={{ jobs: [{ ...task, enabled: false }] }} />);
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(<Harness payload={{ jobs: [{
@@ -934,8 +1067,10 @@ describe("Automation task list and detail sheet", () => {
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();
});
});
@@ -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 () => {