Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(agents): routines as readable tasks with run history and away-pausing (#900)

Ruben Lütkea366226aa918
diff --git a/dodaios/society/routine_history.py b/dodaios/society/routine_history.py
new file mode 100644
index 0000000000..136b54aaf8
--- /dev/null
+++ b/dodaios/society/routine_history.py
@@ -0,0 +1,246 @@
+"""A routine's run history, derived from what is already stored.
+
+A routine is a task in the Automations scheduler (``routines.py``); every
+execution leaves log steps on that task (``run_now``, ``run_started``,
+``routine_chat``, ``agent_result``, ``run_completed`` / ``error`` /
+``skipped`` …) and, since the run summary step, one ``routine_summary`` step
+with the seat, duration and cost of the run's turn. Older runs have no
+summary step; their duration and cost are read from the run's own chat
+(``turn_finished``) when it still exists.
+
+Nothing here writes, calls a model or bills anything: it is a read-only
+projection for the routine detail panel and the routine list.
+"""
+
+from __future__ import annotations
+
+import re
+from dataclasses import asdict, dataclass, field
+from typing import Any, Final
+
+__all__ = [
+ "RoutineRun",
+ "enrich_from_chat",
+ "parse_runs",
+ "run_summary_line",
+]
+
+#: The first line of a reply, at most this long, describes a run in a list.
+SUMMARY_CHARS: Final[int] = 160
+
+_MARKDOWN_LEAD = re.compile(r"^\s*(?:#{1,6}\s+|[-*+]\s+|>\s*|\d+[.)]\s+)")
+_MARKDOWN_INLINE = re.compile(r"(\*\*|__|`+|~~)")
+
+
+@dataclass
+class RoutineRun:
+ """One execution of one routine task."""
+
+ id: str
+ task_id: str
+ #: ``running | completed | failed | cancelled | skipped | pending | waiting | legacy``
+ status: str
+ #: ``manual`` for Run now / Test run, ``automatic`` for its own trigger.
+ origin: str = "automatic"
+ started_ms: int | None = None
+ finished_ms: int | None = None
+ duration_ms: int | None = None
+ cost_usd: float | None = None
+ #: Whether the run's seat bills a per-token key (``None`` = not recorded).
+ billed_via_key: bool | None = None
+ provider: str = ""
+ model: str = ""
+ session_id: str = ""
+ summary: str = ""
+ error: str = ""
+ skip_code: str = ""
+ skip_provider: str = ""
+ #: Internal: the full result text, for the transcript fallback.
+ result: str = field(default="", repr=False)
+ #: Internal: a ``routine_summary`` step was recorded, so the chat holds
+ #: nothing the history still needs (CLI seats often report no cost).
+ recorded: bool = field(default=False, repr=False)
+
+ def to_dict(self) -> dict[str, Any]:
+ data = asdict(self)
+ data.pop("recorded", None)
+ return data
+
+
+def run_summary_line(text: str, limit: int = SUMMARY_CHARS) -> str:
+ """The first meaningful line of a reply, without Markdown furniture."""
+ for raw in (text or "").splitlines():
+ line = _MARKDOWN_INLINE.sub("", _MARKDOWN_LEAD.sub("", raw)).strip()
+ if line and not set(line) <= set("-=*_|:"):
+ return line if len(line) <= limit else line[: limit - 1].rstrip() + "…"
+ return ""
+
+
+def _ms(step: dict[str, Any]) -> int:
+ return int(int(step.get("timestamp_ns") or 0) / 1_000_000)
+
+
+def _number(value: Any) -> float | None:
+ try:
+ return None if value is None or isinstance(value, bool) else float(value)
+ except (TypeError, ValueError): # a non-numeric cost or duration reads as unknown
+ return None
+
+
+def parse_runs(task_id: str, steps: list[dict[str, Any]]) -> list[RoutineRun]:
+ """The runs of one task, oldest first, from its log steps.
+
+ Mirrors how the task runner writes a run: an optional ``run_now`` marks
+ the next start as the person's own, ``run_started`` opens a run and one
+ terminal step (``run_completed``, ``run_cancelled``, ``error``,
+ ``deferred``, ``waiting`` or ``skipped``) closes it. Records from before
+ explicit run boundaries (a bare ``agent_result``) become ``legacy`` runs.
+ """
+ runs: list[RoutineRun] = []
+ current: RoutineRun | None = None
+ manual_next = False
+ for step in steps:
+ payload = step.get("payload") or {}
+ event = str(payload.get("event") or "")
+ at = _ms(step)
+ text = str(payload.get("message") or payload.get("text") or "")
+ if event == "run_now":
+ manual_next = True
+ elif event == "run_started":
+ if current is not None and current.status == "running":
+ current.status = "interrupted"
+ current = RoutineRun(
+ id=f"{task_id}:{step.get('seq')}",
+ task_id=task_id,
+ status="running",
+ origin="manual" if manual_next else "automatic",
+ started_ms=at,
+ )
+ manual_next = False
+ runs.append(current)
+ elif event == "routine_chat" and current is not None:
+ current.session_id = str(payload.get("session_id") or "")
+ elif event == "routine_summary" and current is not None:
+ current.recorded = True
+ current.duration_ms = int(_number(payload.get("duration_ms")) or 0) or None
+ current.cost_usd = _number(payload.get("cost_usd"))
+ billed = payload.get("billed_via_key")
+ current.billed_via_key = billed if isinstance(billed, bool) else None
+ current.provider = str(payload.get("provider") or "")
+ current.model = str(payload.get("model") or "")
+ current.session_id = current.session_id or str(payload.get("session_id") or "")
+ elif event == "agent_result":
+ if current is not None:
+ current.result = text
+ else:
+ runs.append(
+ RoutineRun(
+ id=f"{task_id}:{step.get('seq')}",
+ task_id=task_id,
+ status="legacy",
+ started_ms=at,
+ finished_ms=at,
+ result=text,
+ )
+ )
+ elif event == "skipped":
+ target = current
+ if target is None:
+ target = RoutineRun(
+ id=f"{task_id}:{step.get('seq')}",
+ task_id=task_id,
+ status="skipped",
+ started_ms=at,
+ )
+ runs.append(target)
+ target.status = "skipped"
+ target.finished_ms = at
+ target.skip_code = str(payload.get("code") or "")
+ target.skip_provider = str(payload.get("provider") or "")
+ target.error = text
+ # An older history also logged an "error" right after the skip.
+ current = target
+ elif event in ("run_completed", "run_cancelled", "error", "deferred", "waiting"):
+ status = {
+ "run_completed": "completed",
+ "run_cancelled": "cancelled",
+ "deferred": "pending",
+ "waiting": "waiting",
+ }.get(event, "failed")
+ if current is not None and current.status == "skipped":
+ current = None
+ continue
+ if current is None:
+ runs.append(
+ RoutineRun(
+ id=f"{task_id}:{step.get('seq')}",
+ task_id=task_id,
+ status=status,
+ started_ms=at,
+ finished_ms=at,
+ error=text if status != "completed" else "",
+ )
+ )
+ continue
+ current.status = status
+ current.finished_ms = at
+ if status == "completed":
+ duration = _number(payload.get("duration_ms"))
+ if duration and current.duration_ms is None:
+ current.duration_ms = int(duration)
+ elif text or payload.get("reason"):
+ current.error = text or str(payload.get("reason") or "")
+ current = None
+ for run in runs:
+ if run.duration_ms is None and run.started_ms and run.finished_ms:
+ run.duration_ms = max(0, run.finished_ms - run.started_ms) or None
+ run.summary = run.summary or run_summary_line(run.result)
+ return runs
+
+
+def _first_turn(events: list[dict[str, Any]]) -> tuple[str, dict[str, Any] | None, str]:
+ """The routine's own turn in its chat: ``(turn_id, turn_finished, reply)``."""
+ turn_id = ""
+ for event in events:
+ if event.get("kind") == "turn_started":
+ turn_id = str((event.get("payload") or {}).get("turn_id") or "")
+ break
+ finished: dict[str, Any] | None = None
+ texts: list[str] = []
+ for event in events:
+ payload = event.get("payload") or {}
+ if turn_id and payload.get("turn_id") not in (None, turn_id):
+ continue
+ if event.get("kind") == "assistant_text":
+ texts.append(str(payload.get("text") or ""))
+ elif event.get("kind") == "turn_finished":
+ finished = payload
+ break
+ return turn_id, finished, "\n\n".join(t for t in texts if t.strip())
+
+
+def enrich_from_chat(run: RoutineRun, chat_store: Any) -> None:
+ """Fill duration, cost and summary of a run without a summary step.
+
+ Reads the run's own chat once; a missing store or session leaves the run
+ as parsed. Only the routine's first turn counts: later turns are the
+ person's follow-up questions in that chat.
+ """
+ if chat_store is None or not run.session_id or run.recorded:
+ return
+ if run.cost_usd is not None and run.summary:
+ return
+ try:
+ events = chat_store.list_events(run.session_id)
+ except Exception: # noqa: BLE001 — a closed or missing chat store is not an error here
+ return
+ _, finished, reply = _first_turn(events)
+ if finished is not None:
+ if run.cost_usd is None:
+ run.cost_usd = _number(finished.get("cost_usd"))
+ if run.duration_ms is None:
+ run.duration_ms = int(_number(finished.get("duration_ms")) or 0) or None
+ if not run.error and finished.get("error"):
+ run.error = str(finished.get("error"))
+ if not run.summary:
+ run.summary = run_summary_line(reply)
diff --git a/dodaios/society/routine_parking.py b/dodaios/society/routine_parking.py
new file mode 100644
index 0000000000..45e8235c6b
--- /dev/null
+++ b/dodaios/society/routine_parking.py
@@ -0,0 +1,433 @@
+"""Away-parking: pause routines whose results nobody reads.
+
+A routine that keeps producing results while the person has not looked at
+that agent's routine results for a while spends seats on reports that go
+unread. When one of those routines fires again, this module pauses the
+agent's unread time-based routines and records why, once per away period.
+The person then sees one banner in the agent's routine list with three
+choices: keep running, keep paused, or keep running and never ask again.
+
+Deterministic code only: it reads task steps and one chat tail, writes the
+pause through the scheduler and a JSON record into ``society_meta``. It never
+calls a model, never bills anything and never speaks.
+
+What counts as "the person looked":
+* opening the agent's routine list or a routine's run history
+ (``POST /agents/{id}/routines/seen``), and
+* writing to the agent in its own chat.
+
+What is never parked:
+* runs the person started (Run now / Test run): the check is skipped;
+* routines with a non-time trigger (webhooks, events, forms, sources), which
+ serve something outside that the person set up to react to;
+* a routine the person ran by hand within the window;
+* goal-derived background work and routines that announce their result
+ elsewhere (their result is read where it is delivered).
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import logging
+import time
+from collections.abc import Iterable
+from dataclasses import asdict, dataclass, field
+from typing import Any, Final
+
+from dodaios.core.trigger_context import CapacityDeferred
+
+from .routine_history import parse_runs
+
+log = logging.getLogger(__name__)
+
+__all__ = [
+ "DEFAULT_DAYS",
+ "ParkingState",
+ "RoutineActivity",
+ "RoutineParked",
+ "activity_of",
+ "apply_choice",
+ "load_days",
+ "load_state",
+ "mark_seen",
+ "maybe_park",
+ "parking_candidates",
+ "save_days",
+ "save_state",
+]
+
+DAY_MS: Final[int] = 86_400_000
+#: Default away window; ``0`` switches away-parking off.
+DEFAULT_DAYS: Final[int] = 7
+MAX_DAYS: Final[int] = 90
+#: Fewer unread results than this is not "keeps producing results".
+MIN_UNREAD_RESULTS: Final[int] = 3
+#: Triggers that fire on their own clock. Everything else reacts to the outside.
+TIME_TRIGGERS: Final[frozenset[str]] = frozenset({"every", "calendar", "cron"})
+
+_DAYS_KEY: Final[str] = "routine_parking:days"
+_AGENT_KEY: Final[str] = "routine_parking:agent:"
+#: How long a parked run waits for its own task to leave ``running``.
+_IDLE_WAIT_S: Final[float] = 120.0
+
+#: Stable reason word for the skipped run's history line.
+PARKED_CODE: Final[str] = "away_parked"
+
+CHOICES: Final[frozenset[str]] = frozenset(
+ {"keep_running", "keep_paused", "never_ask", "ask_again"}
+)
+
+
+class RoutineParked(CapacityDeferred):
+ """The run was skipped because its agent's routines were parked."""
+
+
+@dataclass
+class ParkingState:
+ """What away-parking remembers per agent (``society_meta`` JSON)."""
+
+ seen_ms: int = 0
+ parked_ms: int = 0
+ parked_ids: list[str] = field(default_factory=list)
+ unread: int = 0
+ days: int = 0
+ #: A park the person has not answered yet: the banner shows.
+ banner: bool = False
+ never_ask: bool = False
+
+ def to_json(self) -> str:
+ return json.dumps(asdict(self), separators=(",", ":"))
+
+ @classmethod
+ def from_json(cls, raw: str) -> ParkingState:
+ try:
+ data = json.loads(raw) if raw else {}
+ except ValueError: # a corrupt parking file starts fresh with defaults
+ data = {}
+ if not isinstance(data, dict):
+ data = {}
+ return cls(
+ seen_ms=int(data.get("seen_ms") or 0),
+ parked_ms=int(data.get("parked_ms") or 0),
+ parked_ids=[str(v) for v in data.get("parked_ids") or [] if v],
+ unread=int(data.get("unread") or 0),
+ days=int(data.get("days") or 0),
+ banner=bool(data.get("banner")),
+ never_ask=bool(data.get("never_ask")),
+ )
+
+
+@dataclass(frozen=True)
+class RoutineActivity:
+ """The facts the parking decision needs about one routine task."""
+
+ task_id: str
+ state: str
+ trigger_type: str
+ #: Finish times (ms) of runs that fired on their own and completed.
+ result_ms: tuple[int, ...] = ()
+ #: Start time (ms) of the newest run the person started, or 0.
+ last_manual_ms: int = 0
+ autonomous: bool = False
+ announces: bool = False
+
+
+def parking_candidates(
+ activities: Iterable[RoutineActivity],
+ *,
+ seen_ms: int,
+ now_ms: int,
+ days: int,
+ never_ask: bool = False,
+) -> tuple[list[str], int]:
+ """Which routines to park now, and how many unread results they made.
+
+ Pure: the same facts always give the same answer. A routine qualifies when
+ it fires on a clock, is live, made results after ``seen_ms`` and was not
+ run by hand inside the window. The agent as a whole qualifies when those
+ routines made at least :data:`MIN_UNREAD_RESULTS` unread results, the
+ person has not looked for ``days`` days, and results are still coming in
+ (the newest one is inside the window).
+ """
+ if days <= 0 or never_ask:
+ return [], 0
+ window = days * DAY_MS
+ chosen: list[str] = []
+ unread_times: list[int] = []
+ for item in activities:
+ if item.state not in ("scheduled", "running"):
+ continue
+ if item.trigger_type not in TIME_TRIGGERS or item.autonomous or item.announces:
+ continue
+ if item.last_manual_ms and item.last_manual_ms >= now_ms - window:
+ continue
+ unread = [at for at in item.result_ms if at > seen_ms]
+ if not unread:
+ continue
+ chosen.append(item.task_id)
+ unread_times.extend(unread)
+ if len(unread_times) < MIN_UNREAD_RESULTS:
+ return [], 0
+ reference = seen_ms or min(unread_times)
+ if now_ms - reference < window or max(unread_times) < now_ms - window:
+ return [], 0
+ return chosen, len(unread_times)
+
+
+def activity_of(row: dict[str, Any]) -> RoutineActivity:
+ """One routine's activity from its full task row (with ``steps``)."""
+ spec: dict[str, Any] = {}
+ raw = row.get("spec_json")
+ if raw:
+ try:
+ spec = json.loads(raw) if isinstance(raw, str) else dict(raw)
+ except ValueError: # an unreadable spec reads as a routine with no trigger
+ spec = {}
+ trigger = spec.get("trigger") or {}
+ tags = [str(t) for t in spec.get("tags") or []]
+ task_id = str(row.get("id") or "")
+ runs = parse_runs(task_id, list(row.get("steps") or []))
+ results = tuple(
+ int(run.finished_ms)
+ for run in runs
+ if run.origin == "automatic" and run.status == "completed" and run.finished_ms
+ )
+ manual = max((int(run.started_ms or 0) for run in runs if run.origin == "manual"), default=0)
+ return RoutineActivity(
+ task_id=task_id,
+ state=str(row.get("state") or ""),
+ trigger_type=str(row.get("trigger_type") or trigger.get("type") or ""),
+ result_ms=results,
+ last_manual_ms=manual,
+ autonomous="autonomous" in tags,
+ announces=bool(spec.get("announce_on_success")),
+ )
+
+
+# ------------------------------------------------------------------ storage
+
+
+async def load_days(society_store: Any) -> int:
+ raw = await society_store.get_meta(_DAYS_KEY, "")
+ try:
+ days = int(raw) if raw != "" else DEFAULT_DAYS
+ except ValueError: # a non-numeric setting falls back to the default window
+ days = DEFAULT_DAYS
+ return max(0, min(MAX_DAYS, days))
+
+
+async def save_days(society_store: Any, days: int) -> int:
+ value = max(0, min(MAX_DAYS, int(days)))
+ await society_store.set_meta(_DAYS_KEY, str(value))
+ return value
+
+
+async def load_state(society_store: Any, agent_id: str) -> ParkingState:
+ return ParkingState.from_json(await society_store.get_meta(_AGENT_KEY + agent_id, ""))
+
+
+async def save_state(society_store: Any, agent_id: str, state: ParkingState) -> None:
+ await society_store.set_meta(_AGENT_KEY + agent_id, state.to_json())
+
+
+async def mark_seen(society_store: Any, agent_id: str, now_ms: int | None = None) -> ParkingState:
+ state = await load_state(society_store, agent_id)
+ state.seen_ms = max(state.seen_ms, int(now_ms if now_ms is not None else _now_ms()))
+ await save_state(society_store, agent_id, state)
+ return state
+
+
+def last_person_message_ms(chat_service: Any, session_id: str, *, tail: int = 300) -> int:
+ """When the person last wrote in the agent's own chat (0 when unknown).
+
+ Messages from Jarvis, teammates, chat controls and background results
+ carry an ``origin`` or ``author``; the person's own typed messages do not.
+ """
+ store = getattr(chat_service, "store", None)
+ if store is None or not session_id:
+ return 0
+ try:
+ events = store.list_events(session_id, tail=tail)
+ except Exception: # noqa: BLE001 — an unreadable chat reads as "no message"
+ return 0
+ for event in reversed(events):
+ payload = event.get("payload") or {}
+ if (
+ event.get("kind") == "user_message"
+ and not payload.get("origin")
+ and not payload.get("author")
+ ):
+ return int(event.get("ts_ms") or 0)
+ return 0
+
+
+# ------------------------------------------------------------------ actions
+
+
+async def _pause_when_idle(
+ society_store: Any, task_store: Any, scheduler: Any, agent_id: str, task_id: str
+) -> None:
+ """Pause ``task_id`` once its current (skipped) run has settled.
+
+ Re-reads the park record first: when the person already chose "keep
+ running" in the meantime, the routine stays on.
+ """
+ deadline = time.monotonic() + _IDLE_WAIT_S
+ while time.monotonic() < deadline:
+ row = await task_store.get(task_id)
+ if row is None:
+ return
+ if row.get("state") == "paused":
+ return
+ if row.get("state") == "scheduled":
+ if task_id not in (await load_state(society_store, agent_id)).parked_ids:
+ return
+ try:
+ await scheduler.pause(task_id)
+ except Exception: # noqa: BLE001 — a conflict means the person acted first
+ log.info("routine parking: %s not paused (state changed)", task_id)
+ return
+ if row.get("state") != "running":
+ return
+ await asyncio.sleep(0.5)
+
+
+#: Delayed pauses still waiting for their run to settle, by task id.
+_PENDING: dict[str, asyncio.Task[None]] = {}
+
+
+async def maybe_park(
+ runtime: Any,
+ agent: Any,
+ task_id: str,
+ *,
+ now_ms: int | None = None,
+) -> None:
+ """Before an unattended run: park the agent's unread routines, if due.
+
+ Raises :class:`RoutineParked` when this run's own routine was parked, so
+ the task runner records a skipped run and no seat is used. Any error in
+ the check itself lets the run go on: parking is a saving, never a gate.
+ """
+ from dodaios.core.protocols import current_started_by_user
+
+ if current_started_by_user.get():
+ return
+ services = getattr(runtime, "task_services", None)
+ if services is None or getattr(runtime, "store", None) is None:
+ return
+ now = int(now_ms if now_ms is not None else _now_ms())
+ try:
+ task_store, scheduler = services()
+ if task_store is None or scheduler is None:
+ return
+ days = await load_days(runtime.store)
+ if days <= 0:
+ return
+ state = await load_state(runtime.store, agent.agent_id)
+ if state.never_ask or state.banner:
+ return
+ from .routines import list_routines
+
+ seen = max(
+ state.seen_ms,
+ last_person_message_ms(runtime.chat_service(), str(agent.session_id or "")),
+ )
+ activities = []
+ for summary in await list_routines(task_store, agent.agent_id):
+ row = await task_store.get(str(summary.get("id")))
+ if row is not None:
+ activities.append(activity_of(row))
+ chosen, unread = parking_candidates(
+ activities, seen_ms=seen, now_ms=now, days=days, never_ask=state.never_ask
+ )
+ if task_id not in chosen:
+ return
+ state.parked_ms = now
+ state.parked_ids = chosen
+ state.unread = unread
+ state.days = days
+ state.banner = True
+ await save_state(runtime.store, agent.agent_id, state)
+ for tid in chosen:
+ await task_store.append_step(
+ tid, "log", {"event": "parked", "reason": "away", "days": days, "unread": unread}
+ )
+ if tid == task_id:
+ pending = asyncio.create_task(
+ _pause_when_idle(runtime.store, task_store, scheduler, agent.agent_id, tid)
+ )
+ _PENDING[tid] = pending
+ pending.add_done_callback(lambda _t, key=tid: _PENDING.pop(key, None))
+ continue
+ try:
+ await scheduler.pause(tid)
+ except Exception: # noqa: BLE001 — a running sibling is parked on its own turn
+ log.info("routine parking: %s not paused now", tid)
+ log.info(
+ "routine parking: paused %d routine(s) of %s after %d unread result(s)",
+ len(chosen),
+ agent.agent_id,
+ unread,
+ )
+ except Exception: # noqa: BLE001 — parking must never stop a run on its own failure
+ log.warning("routine parking check failed for %s", task_id, exc_info=True)
+ return
+ raise RoutineParked(
+ f"Paused: this agent's routine results have not been opened for {days} days "
+ f"({unread} unread). Resume it from the agent's routines.",
+ code=PARKED_CODE,
+ )
+
+
+async def apply_choice(
+ society_store: Any,
+ task_store: Any,
+ scheduler: Any,
+ agent_id: str,
+ choice: str,
+ *,
+ now_ms: int | None = None,
+) -> ParkingState:
+ """The person's answer to the banner.
+
+ ``keep_running`` resumes every parked routine that is still paused and
+ starts a new away period; ``keep_paused`` only closes the banner;
+ ``never_ask`` resumes and switches parking off for this agent;
+ ``ask_again`` switches it back on.
+ """
+ if choice not in CHOICES:
+ raise ValueError(f"unknown choice {choice!r}")
+ now = int(now_ms if now_ms is not None else _now_ms())
+ state = await load_state(society_store, agent_id)
+ if choice in ("keep_running", "never_ask"):
+ for tid in state.parked_ids:
+ waiting = _PENDING.pop(tid, None)
+ if waiting is not None:
+ waiting.cancel()
+ row = await task_store.get(tid)
+ if row is None or row.get("state") != "paused":
+ continue
+ try:
+ await scheduler.resume(tid)
+ await task_store.append_step(tid, "log", {"event": "unparked"})
+ except Exception: # noqa: BLE001 — one routine that cannot resume does not block the rest
+ log.info("routine parking: %s not resumed", tid)
+ if choice == "ask_again":
+ state.never_ask = False
+ else:
+ state.banner = False
+ state.seen_ms = now
+ if choice != "keep_paused":
+ state.parked_ids = []
+ state.parked_ms = 0
+ state.unread = 0
+ if choice == "never_ask":
+ state.never_ask = True
+ await save_state(society_store, agent_id, state)
+ return state
+
+
+def _now_ms() -> int:
+ return int(time.time() * 1000)
diff --git a/dodaios/society/routine_runner.py b/dodaios/society/routine_runner.py
index 46f9aeb1e2..b3dd3db8ab 100644
--- a/dodaios/society/routine_runner.py
+++ b/dodaios/society/routine_runner.py
@@ -213,6 +213,10 @@ async def run_owned_routine(
"Background work is waiting for a subscription or local model on its owner's seat"
)
await _hold_unattended_run_off_keys(provider, account_id)
+ # Results nobody opens for days: pause instead of producing another one.
+ from .routine_parking import maybe_park
+
+ await maybe_park(runtime, agent, task_id)
permission_mode = "bypass"
if autonomous:
from .autonomous_routines import ORIGIN_PERMISSION_TAG, ORIGIN_SESSION_TAG
@@ -338,6 +342,10 @@ async def run_owned_routine(
if event.get("kind") == "assistant_text":
answer = str(payload.get("text") or answer)
if event.get("kind") == "turn_finished":
+ await _record_run_summary(
+ task_store, task_id, session.session_id, turn_id, payload,
+ provider=provider, model=model, account_id=account_id,
+ )
if payload.get("status") == "cancelled":
raise asyncio.CancelledError
if payload.get("status") not in {"done", "ok", "completed"}:
@@ -355,6 +363,45 @@ async def run_owned_routine(
service.unsubscribe(session.session_id, queue)
+async def _record_run_summary(
+ task_store: Any,
+ task_id: str,
+ session_id: str,
+ turn_id: str,
+ finished: dict[str, Any],
+ *,
+ provider: str,
+ model: str,
+ account_id: str,
+) -> None:
+ """One ``routine_summary`` step per run: seat, duration and cost of its turn.
+
+ The run history reads it instead of opening every run's chat. Written
+ once, best effort: a failed write leaves the history to the chat fallback.
+ """
+ if task_store is None:
+ return
+ cost = finished.get("cost_usd")
+ try:
+ await task_store.append_step(
+ task_id,
+ "log",
+ {
+ "event": "routine_summary",
+ "session_id": session_id,
+ "turn_id": turn_id,
+ "status": str(finished.get("status") or ""),
+ "duration_ms": int(finished.get("duration_ms") or 0),
+ "cost_usd": float(cost) if isinstance(cost, int | float) else None,
+ "provider": provider,
+ "model": model,
+ "billed_via_key": _billed_via_api(provider, account_id),
+ },
+ )
+ except Exception: # noqa: BLE001 — the summary is a projection of the run's own chat
+ log.warning("routine: run summary not recorded for %s", task_id, exc_info=True)
+
+
async def _report_autonomous_result(
runtime: Any, agent: Any, tags: tuple[str, ...], task_id: str, answer: str,
) -> None:
diff --git a/dodaios/ui/web/frontend/src/components/society/card/AgentRoutineDetail.tsx b/dodaios/ui/web/frontend/src/components/society/card/AgentRoutineDetail.tsx
index 178831ec2e..13f969256f 100644
--- a/dodaios/ui/web/frontend/src/components/society/card/AgentRoutineDetail.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/card/AgentRoutineDetail.tsx
@@ -1,67 +1,46 @@
-/** The agent's routine editor, backed by the existing task scheduler. */
-import { useState } from "react";
+/**
+ * One routine, as a task the person can understand at a glance and leave
+ * running: what triggers it (as a sentence), whether it is on, a test run,
+ * "edit in chat", the last failure, every run with its duration and cost,
+ * and the full editor (instruction, model seat, schedules, connections).
+ * Backed by the existing task scheduler.
+ */
+import { useEffect, useState } from "react";
import { useQueries, useQueryClient } from "@tanstack/react-query";
-import { ArrowLeft, Check, Clock, Plus, SkipForward, X } from "lucide-react";
+import { AlertTriangle, ArrowLeft, Clock, Loader2, MessageSquareText, Play, Plus, Trash2 } from "lucide-react";
import { useT } from "@/i18n";
import { useRunLocale } from "@/components/runs/format";
import { Switch } from "@/components/ui/switch";
+import { cn } from "@/lib/utils";
import { cancelAndDeleteTask, cancelTask, fetchTask, runTaskNow, setTaskEnabled } from "@/lib/tasksApi";
import { describeTrigger, displayRoutineTitle, type LiveRoutine } from "../cardData";
-import type { TaskDetail, TaskStep } from "@/lib/tasksApi";
+import type { TaskDetail } from "@/lib/tasksApi";
+import { useSocietyAgent } from "../data";
import { TriggerBuilder } from "./TriggerBuilder";
import { WebhookConnection } from "./WebhookConnection";
import { SourceControls } from "./SourceControls";
import { RoutineSeatPicker, type RoutineSeat } from "./RoutineSeatPicker";
import { useRoutineNavigation } from "../chat/routineNavigation";
import { routineSkipReason } from "@/lib/skipReasons";
+import { TriggerIcon, type RoutineTone } from "./routines/TriggerIcon";
+import { humanSchedule } from "./routines/humanSchedule";
+import { fill, formatDuration, relativeTime } from "./routines/format";
+import { markRoutinesSeen, useRoutineRuns } from "./routines/routinesApi";
+import { mergeRunDetails, routineRuns, type Run } from "./routines/runs";
+import { RunHistory, runReason } from "./routines/RunHistory";
+import { seedAgentComposer } from "./routines/editThroughChat";
+import { useNow } from "./routines/useNow";
-const field = "w-full rounded-lg border border-border bg-background px-3 py-2 text-[12px] text-foreground";
-const button = "rounded-md bg-secondary px-2.5 py-1.5 text-[12px] text-foreground hover:bg-secondary/70 disabled:opacity-50";
+export { routineRuns } from "./routines/runs";
+
+const field = "w-full rounded-lg border border-border bg-background px-3 py-2 text-[12px] text-foreground transition-colors focus:border-border-strong focus:outline-none disabled:opacity-60";
+const button = "inline-flex items-center gap-1.5 rounded-lg border border-border bg-background px-2.5 py-1.5 text-[12px] font-medium text-foreground transition-colors duration-150 hover:bg-secondary disabled:opacity-40";
+const primary = "inline-flex items-center gap-1.5 rounded-lg bg-foreground px-3 py-1.5 text-[12px] font-medium text-background transition-colors duration-150 hover:bg-foreground/90 disabled:opacity-40";
+const heading = "text-[11px] font-semibold uppercase tracking-[0.08em] text-muted-foreground";
const recurring = ["every", "calendar", "cron", "webhook", "event_hook", "source", "on_event"];
const terminal = ["completed", "failed", "cancelled", "interrupted"];
const timeKinds = ["every", "calendar", "cron"];
-interface Run {
- id: string; taskId: string; timestamp: number; status: string; text: string; sessionId?: string; startedMs?: number; finishedMs?: number;
- /** A skipped run's reason code and seat (`skipped` step), worded by `routineSkipReason`. */
- skipCode?: string; skipProvider?: string;
-}
-
-/** New runs have explicit boundaries; retain older result/error records too. */
-export function routineRuns(taskId: string, steps: TaskStep[]): Run[] {
- const runs: Run[] = [];
- let current: Run | undefined;
- for (const step of steps) {
- const event = step.payload.event;
- const text = String(step.payload.message ?? step.payload.text ?? "");
- if (event === "run_started") {
- if (current?.status === "running") current.status = "interrupted";
- current = { id: `${taskId}:${step.seq}`, taskId, timestamp: step.timestamp_ns / 1e6, startedMs: step.timestamp_ns / 1e6, status: "running", text: "" };
- runs.push(current);
- } else if (event === "routine_chat" && current && typeof step.payload.session_id === "string") {
- current.sessionId = step.payload.session_id;
- } else if (event === "agent_result" && current) {
- current.text = text;
- } else if (event === "skipped") {
- // Unattended work that may not bill its seat: no turn started. The skip
- // ends the run; an older history also logged an "error" right after it.
- const skip = { status: "skipped", text, finishedMs: step.timestamp_ns / 1e6,
- skipCode: String(step.payload.code ?? ""), skipProvider: String(step.payload.provider ?? "") };
- if (current) Object.assign(current, skip);
- else { current = { id: `${taskId}:${step.seq}`, taskId, timestamp: step.timestamp_ns / 1e6, ...skip }; runs.push(current); }
- } else if (["run_completed", "run_cancelled", "error", "deferred"].includes(String(event))) {
- const status = event === "run_completed" ? "completed" : event === "run_cancelled" ? "cancelled" : event === "deferred" ? "pending" : "failed";
- if (current?.status === "skipped") current = undefined;
- else if (current) { current.status = status; current.finishedMs = step.timestamp_ns / 1e6; if (text) current.text = text; current = undefined; }
- else runs.push({ id: `${taskId}:${step.seq}`, taskId, timestamp: step.timestamp_ns / 1e6, finishedMs: step.timestamp_ns / 1e6, status, text });
- } else if (event === "agent_result") {
- // Legacy runners persisted the result before the final state transition.
- runs.push({ id: `${taskId}:${step.seq}`, taskId, timestamp: step.timestamp_ns / 1e6, finishedMs: step.timestamp_ns / 1e6, status: "legacy", text });
- }
- }
- return runs;
-}
-
async function writeRoutine(url: string, body: unknown, method = "PATCH") {
const response = await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
if (!response.ok) {
@@ -70,18 +49,22 @@ async function writeRoutine(url: string, body: unknown, method = "PATCH") {
}
}
-export function AgentRoutineDetail({ agentId, routine, onClose }: {
+export function AgentRoutineDetail({ agentId, routine, onClose, parked = false }: {
agentId: string; routine: LiveRoutine; onClose: () => void;
+ /** Paused by away-parking (the list knows; the banner explains). */
+ parked?: boolean;
}) {
const t = useT();
const locale = useRunLocale();
const label = (key: string) => t(`society.routine_detail.${key}`);
+ const own = (key: string) => t(`society.agent_routines.detail.${key}`);
const client = useQueryClient();
const members = routine.members ?? [routine];
const queries = useQueries({ queries: members.map((member) => ({
queryKey: ["tasks", "detail", member.id], queryFn: () => fetchTask(member.id),
retry: false, refetchInterval: import.meta.env.MODE === "test" ? false : 3000,
})) });
+ const { agent } = useSocietyAgent(agentId);
const [draft, setDraft] = useState<{ title: string; prompt: string } | null>(null);
const [editing, setEditing] = useState<LiveRoutine | "new" | null>(null);
const [schedule, setSchedule] = useState<Record<string, unknown> | null>(null);
@@ -90,6 +73,7 @@ export function AgentRoutineDetail({ agentId, routine, onClose }: {
const [notice, setNotice] = useState("");
const [confirmDelete, setConfirmDelete] = useState(false);
const openChat = useRoutineNavigation((state) => state.open);
+ useEffect(() => { markRoutinesSeen(agentId); }, [agentId]);
const details = queries.map((query) => query.data);
const first = details[0];
const rawPrompt = String((first?.spec?.action as { prompt?: string } | undefined)?.prompt ?? "");
@@ -112,6 +96,7 @@ export function AgentRoutineDetail({ agentId, routine, onClose }: {
);
const ready = details.every(Boolean);
const running = details.some((detail) => detail?.state === "running");
+ const now = useNow(running ? 1000 : 30_000);
const active = details.some((detail) => detail && detail.state !== "paused" && !terminal.includes(detail.state));
const editable = ready && !running && details.every((detail, index) => detail && (
index > 0 && terminal.includes(detail.state) || recurring.includes(detail.trigger_type) && !terminal.includes(detail.state)
@@ -121,6 +106,8 @@ export function AgentRoutineDetail({ agentId, routine, onClose }: {
const refresh = () => Promise.all([
client.invalidateQueries({ queryKey: ["tasks"] }),
client.invalidateQueries({ queryKey: ["society", "agent-routines", agentId] }),
+ client.invalidateQueries({ queryKey: ["society", "routine-activity", agentId] }),
+ client.invalidateQueries({ queryKey: ["society", "routine-runs", agentId] }),
]);
const act = async (fn: () => Promise<void>) => {
setPending(true); setError(""); setNotice("");
@@ -133,12 +120,24 @@ export function AgentRoutineDetail({ agentId, routine, onClose }: {
...(seatDirty ? { provider: seat.provider, model: seat.model, effort: seat.effort, account_id: seat.account_id } : {}),
});
const valid = Boolean(values.title.trim() && values.prompt.trim());
- const runs = details.flatMap((detail) => detail ? routineRuns(detail.id, detail.steps) : []).sort((a, b) => b.timestamp - a.timestamp);
+ const history = useRoutineRuns(agentId, members.map((member) => member.id), running);
+ const localRuns = details.flatMap((detail) => detail ? routineRuns(detail.id, detail.steps) : []).sort((a, b) => b.timestamp - a.timestamp);
+ const runs = mergeRunDetails(localRuns, history.runs);
+ const latest = runs[0];
+ const lastFailure = runs.find((run) => run.status === "failed");
+ const showFailure = lastFailure && (latest?.status === "failed" || latest?.status === "interrupted") ? lastFailure : undefined;
const renderConnection = (detail: TaskDetail) => {
if (detail.trigger_type === "webhook") return <WebhookConnection taskId={detail.id} />;
if (detail.trigger_type === "source") return <SourceControls taskId={detail.id} source={(detail.trigger as { source: { kind: string } }).source} />;
return null;
};
+ const sentenceOf = (trigger: unknown) => humanSchedule(trigger, { t, locale }) || describeTrigger(trigger, t);
+ const headTrigger = first?.trigger ?? routine.trigger;
+ const sentence = sentenceOf(headTrigger);
+ const due = details.filter((detail) => detail?.state === "scheduled" && detail.due_at_ns).map((detail) => detail!.due_at_ns! / 1e6);
+ const nextMs = due.length ? Math.min(...due) : null;
+ const tone: RoutineTone = running ? "running" : !active ? (parked ? "parked" : "paused") : latest?.status === "failed" ? "failed" : "active";
+ const canTest = !(pending || !ready || running || Boolean(draft) || Boolean(editing) || !first || terminal.includes(first.state) || first.trigger_type === "source");
const openRun = (run: Run) => {
const ownChat = run.sessionId?.startsWith(`society:${agentId}:routine:${run.taskId}:`);
@@ -148,41 +147,70 @@ export function AgentRoutineDetail({ agentId, routine, onClose }: {
...(!ownChat ? { legacy: { taskId: run.taskId, startedMs: run.startedMs, finishedMs: run.finishedMs } } : {}),
});
};
+ const editInChat = () => void seedAgentComposer(
+ { tier: agent?.tier ?? "specialist", chatSessionId: agent?.chatSessionId ?? `society:${agentId}` },
+ fill(own("edit_prompt"), { title: saved.title, schedule: sentence }),
+ );
+ const runningRun = runs.find((run) => run.status === "running");
+ const status = running
+ ? `${own("running")}${runningRun?.startedMs ? ` · ${formatDuration(Math.max(0, now - runningRun.startedMs))}` : ""}`
+ : !active ? (parked ? own("parked") : t("tasks_view.state.paused"))
+ : nextMs ? `${t("society.card.next_run")} ${nextMs <= now ? own("due_now") : relativeTime(nextMs, now, locale)}` : own("active");
return <section className="min-h-0 flex-1 space-y-4 overflow-y-auto pb-4 text-foreground" data-testid="agent-routine-detail">
- <button type="button" className="flex items-center gap-1 text-[12px] text-muted-foreground" disabled={pending} onClick={onClose}><ArrowLeft size={14} />{t("society.card.routines")}</button>
- <div className="flex flex-wrap items-center gap-2">
- <label className="mr-auto flex items-center gap-2 text-[12px]"><Switch aria-label={label("active")} checked={active} disabled={pending || !editable} onCheckedChange={(enabled) => void act(async () => {
- for (const detail of details) if (detail && !terminal.includes(detail.state) && (detail.state === "paused") === enabled) await setTaskEnabled(detail.id, enabled);
- })} />{label("active")}</label>
- <button type="button" className={button} disabled={pending || !ready || running} onClick={() => setConfirmDelete(true)}>{label("delete")}</button>
- <button type="button" className={button} disabled={pending || !ready || running || Boolean(draft) || Boolean(editing) || !first || terminal.includes(first.state) || first.trigger_type === "source"} onClick={() => void act(async () => {
- await runTaskNow(routine.id); setNotice(label("test_started"));
- })}>{label("test")}</button>
- </div>
- {confirmDelete && <div className="space-y-2 rounded-lg border border-border p-3" role="alert">
- <p className="text-[12px]">{label("delete_confirm")}</p>
- <button className={button} disabled={pending} onClick={() => void act(async () => {
- for (const detail of [...details].reverse()) if (detail) await cancelAndDeleteTask(detail.id, !terminal.includes(detail.state));
- onClose();
- })}>{label("delete")}</button>{" "}<button className={button} disabled={pending} onClick={() => setConfirmDelete(false)}>{label("cancel")}</button>
- </div>}
- {queries.some((query) => query.isLoading) && <p role="status" className="text-[12px]">{t("tasks_view.loading_details")}</p>}
+ <button type="button" className="-ml-1 flex items-center gap-1 rounded-md px-1 py-0.5 text-[12px] text-muted-foreground transition-colors hover:text-foreground" disabled={pending} onClick={onClose}><ArrowLeft size={14} />{t("society.card.routines")}</button>
+
+ <header className="rounded-2xl border border-border bg-card p-3 shadow-[0_1px_2px_rgb(var(--scrim-rgb)/0.05),0_6px_16px_-10px_rgb(var(--scrim-rgb)/0.18)]">
+ <div className="flex items-start gap-3">
+ <TriggerIcon trigger={headTrigger} tone={tone} size="lg" />
+ <div className="min-w-0 flex-1">
+ <h3 className="truncate text-[14px] font-semibold leading-5 text-foreground-strong" title={saved.title}>{saved.title}</h3>
+ {sentence && <p className="text-[12px] leading-snug text-foreground-secondary" data-testid="routine-schedule-sentence">{sentence}</p>}
+ <p className={cn("mt-0.5 text-[11px] leading-4", tone === "parked" ? "text-warning" : tone === "running" ? "text-primary" : "text-muted-foreground")}
+ title={nextMs ? new Date(nextMs).toLocaleString(locale, { timeZoneName: "short" }) : undefined}>{status}</p>
+ </div>
+ <label className="flex shrink-0 items-center gap-1.5 text-[11px] text-muted-foreground"><Switch aria-label={label("active")} checked={active} disabled={pending || !editable} onCheckedChange={(enabled) => void act(async () => {
+ for (const detail of details) if (detail && !terminal.includes(detail.state) && (detail.state === "paused") === enabled) await setTaskEnabled(detail.id, enabled);
+ })} /><span className="sr-only sm:not-sr-only">{label("active")}</span></label>
+ </div>
+ <div className="mt-3 flex flex-wrap items-center gap-1.5">
+ <button type="button" className={primary} disabled={!canTest} onClick={() => void act(async () => {
+ await runTaskNow(routine.id); setNotice(label("test_started"));
+ })}>{running ? <Loader2 size={13} className="motion-safe:animate-spin" /> : <Play size={13} />}{label("test")}</button>
+ <button type="button" className={button} onClick={editInChat}><MessageSquareText size={13} />{own("edit_in_chat")}</button>
+ </div>
+ </header>
+
+ {queries.some((query) => query.isLoading) && <p role="status" className="text-[12px] text-muted-foreground">{t("tasks_view.loading_details")}</p>}
{queries.some((query) => query.error) && <p role="alert" className="text-[12px] text-destructive">{t("tasks_view.load_error")}</p>}
{error && <p role="alert" className="break-words text-[12px] text-destructive">{error}</p>}
{notice && <p role="status" className="text-[12px] text-success">{notice}</p>}
- <label className="block space-y-1 text-[11px] text-muted-foreground">{label("name")}<input className={field} aria-label={label("name")} maxLength={200} disabled={pending || !editable || Boolean(editing)} value={values.title} onChange={(event) => setDraft({ ...values, title: event.target.value })} /></label>
- <label className="block space-y-1 text-[11px] text-muted-foreground">{label("prompt")}<textarea className={field} aria-label={label("prompt")} maxLength={16000} rows={7} disabled={pending || !editable || Boolean(editing) || (first?.spec?.action as { kind?: string } | undefined)?.kind !== "agent"} value={values.prompt} onChange={(event) => setDraft({ ...values, prompt: event.target.value })} /></label>
- {draft && <div className="flex gap-2"><button className={button} disabled={pending || !valid || !editable || Boolean(editing)} onClick={() => void act(async () => {
- for (const [index, member] of members.entries()) if (!terminal.includes(details[index]!.state)) await update(member, details[index]?.trigger);
- setDraft(null); setSeatDraft(null); setSeatOpen(false); setNotice(label("saved"));
- })}>{label("save")}</button><button className={button} disabled={pending} onClick={() => setDraft(null)}>{label("cancel")}</button></div>}
+
+ {showFailure && <div className="rounded-xl border border-destructive/30 bg-destructive/[0.05] p-3" data-testid="routine-last-failure">
+ <div className="flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.08em] text-destructive">
+ <AlertTriangle size={13} aria-hidden />{own("last_failure")}
+ <span className="ml-auto font-normal normal-case tracking-normal text-muted-foreground">{relativeTime(showFailure.finishedMs ?? showFailure.timestamp, now, locale)}</span>
+ </div>
+ <p className="mt-1.5 break-words text-[12px] leading-snug text-foreground-secondary">{runReason(t, showFailure) || own("failed_no_detail")}</p>
+ <button type="button" className="mt-2 text-[11px] text-muted-foreground underline-offset-2 hover:text-foreground hover:underline" onClick={() => openRun(showFailure)}>{own("open_failed_run")}</button>
+ </div>}
+
+ <section className="space-y-2">
+ <h4 className={heading}>{own("instruction")}</h4>
+ <label className="block space-y-1 text-[11px] text-muted-foreground">{label("name")}<input className={field} aria-label={label("name")} maxLength={200} disabled={pending || !editable || Boolean(editing)} value={values.title} onChange={(event) => setDraft({ ...values, title: event.target.value })} /></label>
+ <label className="block space-y-1 text-[11px] text-muted-foreground">{label("prompt")}<textarea className={cn(field, "resize-y leading-relaxed")} aria-label={label("prompt")} maxLength={16000} rows={6} disabled={pending || !editable || Boolean(editing) || (first?.spec?.action as { kind?: string } | undefined)?.kind !== "agent"} value={values.prompt} onChange={(event) => setDraft({ ...values, prompt: event.target.value })} /></label>
+ {draft && <div className="flex gap-2"><button className={primary} disabled={pending || !valid || !editable || Boolean(editing)} onClick={() => void act(async () => {
+ for (const [index, member] of members.entries()) if (!terminal.includes(details[index]!.state)) await update(member, details[index]?.trigger);
+ setDraft(null); setSeatDraft(null); setSeatOpen(false); setNotice(label("saved"));
+ })}>{label("save")}</button><button className={button} disabled={pending} onClick={() => setDraft(null)}>{label("cancel")}</button></div>}
+ </section>
+
{seatEditable && <div className="space-y-2 rounded-xl border border-border p-3">
<div className="flex items-center justify-between gap-2">
- <h4 className="text-[11px] text-muted-foreground">{label("model")}</h4>
+ <h4 className={heading}>{label("model")}</h4>
<button
type="button"
- className="text-[11px] text-muted-foreground underline disabled:opacity-50"
+ className="text-[11px] text-muted-foreground underline-offset-2 hover:text-foreground hover:underline disabled:opacity-50"
disabled={pending || !editable || Boolean(editing)}
onClick={() => setSeatOpen((open) => !open)}
>
@@ -194,49 +222,55 @@ export function AgentRoutineDetail({ agentId, routine, onClose }: {
</p>
{seatOpen && <RoutineSeatPicker seat={seat} disabled={pending || !editable || Boolean(editing)} onChange={setSeatDraft} />}
</div>}
- {seatDirty && <div className="flex gap-2"><button className={button} disabled={pending || !valid || !editable || Boolean(editing) || Boolean(draft)} onClick={() => void act(async () => {
+ {seatDirty && <div className="flex gap-2"><button className={primary} disabled={pending || !valid || !editable || Boolean(editing) || Boolean(draft)} onClick={() => void act(async () => {
for (const [index, member] of members.entries()) if (!terminal.includes(details[index]!.state)) await update(member, details[index]?.trigger);
setSeatDraft(null); setSeatOpen(false); setNotice(label("saved"));
})}>{label("save")}</button><button className={button} disabled={pending} onClick={() => setSeatDraft(null)}>{label("cancel")}</button></div>}
- <div className="space-y-2">
- <h4 className="text-[11px] text-muted-foreground">{label("when")}</h4>
- <div className="space-y-2 rounded-xl border border-border p-3">
+
+ <section className="space-y-2">
+ <h4 className={heading}>{label("when")}</h4>
+ <div className="divide-y divide-border/70 overflow-hidden rounded-xl border border-border">
{members.map((member, index) => {
const detail = details[index];
if (index > 0 && detail && terminal.includes(detail.state)) return null;
- return <div key={member.id} className="space-y-1">
- <button className="flex w-full items-start gap-2 rounded text-left text-[12px] disabled:opacity-70" disabled={pending || !editable || Boolean(draft) || !detail || !timeKinds.includes(detail.trigger_type)} onClick={() => { setEditing({ ...member, trigger: detail?.trigger }); setSchedule(null); }}>
- <Clock size={14} className="mt-0.5 shrink-0" /><span>{describeTrigger(detail?.trigger ?? member.trigger, t)}</span>
+ return <div key={member.id} className="space-y-1 px-3 py-2.5">
+ <button className="flex w-full items-start gap-2 rounded text-left text-[12px] transition-colors enabled:hover:text-foreground disabled:opacity-80" disabled={pending || !editable || Boolean(draft) || !detail || !timeKinds.includes(detail.trigger_type)} onClick={() => { setEditing({ ...member, trigger: detail?.trigger }); setSchedule(null); }}>
+ <Clock size={14} className="mt-0.5 shrink-0 text-muted-foreground" /><span>{sentenceOf(detail?.trigger ?? member.trigger)}</span>
</button>
{detail?.due_at_ns && detail.state === "scheduled" ? <p className="pl-5 text-[11px] text-muted-foreground">{t("society.card.next_run")}: {new Date(detail.due_at_ns / 1e6).toLocaleString(locale, { timeZoneName: "short" })}</p> : null}
- {detail && renderConnection(detail)}
- {index > 0 && <button className="pl-5 text-[11px] text-muted-foreground" disabled={pending || !editable || Boolean(draft)} onClick={() => void act(async () => { await cancelTask(member.id); })}>{label("remove_schedule")}</button>}
+ {detail && <div className="pl-5">{renderConnection(detail)}</div>}
+ {index > 0 && <button className="pl-5 text-[11px] text-muted-foreground hover:text-foreground" disabled={pending || !editable || Boolean(draft)} onClick={() => void act(async () => { await cancelTask(member.id); })}>{label("remove_schedule")}</button>}
</div>;
})}
- <button className="flex items-center gap-1 text-[12px] text-muted-foreground disabled:opacity-50" disabled={pending || !editable || Boolean(draft)} onClick={() => { setEditing("new"); setSchedule(null); }}><Plus size={14} />{label("add_schedule")}</button>
+ <div className="px-3 py-2">
+ <button className="flex items-center gap-1 text-[12px] text-muted-foreground transition-colors enabled:hover:text-foreground disabled:opacity-50" disabled={pending || !editable || Boolean(draft)} onClick={() => { setEditing("new"); setSchedule(null); }}><Plus size={14} />{label("add_schedule")}</button>
+ </div>
</div>
- {editing && <div className="space-y-2 rounded-lg border border-border p-3">
+ {editing && <div className="space-y-2 rounded-xl border border-border bg-card p-3">
<TriggerBuilder key={editing === "new" ? "new" : editing.id} timeOnly initialValue={editing === "new" ? undefined : editing.trigger as Record<string, unknown>} onChange={setSchedule} />
- <button className={button} disabled={pending || !schedule || !valid} onClick={() => void act(async () => {
+ <button className={primary} disabled={pending || !schedule || !valid} onClick={() => void act(async () => {
if (editing === "new") await writeRoutine(url, { title: values.title, prompt: values.prompt, schedule, parent_task_id: routine.id }, "POST");
else await update(editing, schedule);
setEditing(null); setNotice(label("saved"));
})}>{label("save")}</button>{" "}<button className={button} disabled={pending} onClick={() => setEditing(null)}>{label("cancel")}</button>
</div>}
- </div>
- <div className="space-y-2">
- <h4 className="text-[11px] text-muted-foreground">{label("history")}</h4>
- {runs.length > 0 && <button type="button" className={button} onClick={() => openRun(runs[0])}>{label("latest_chat")}</button>}
- {ready && runs.length === 0 && <p className="text-[12px] text-muted-foreground">{label("no_runs")}</p>}
- {runs.map((run) => {
- const state = run.status === "legacy" ? label("legacy") : run.status === "skipped" ? label("skipped") : t(`tasks_view.state.${run.status}`);
- return <button key={run.id} type="button" data-testid={`routine-run-${run.id}`} aria-label={`${label("open_chat")} · ${new Date(run.timestamp).toLocaleString(locale)} · ${state}`} onClick={() => openRun(run)} className="block w-full cursor-pointer rounded py-1 text-left text-[12px] hover:bg-secondary focus-visible:outline focus-visible:outline-ring">
- <span className="flex items-center justify-between gap-2"><time dateTime={new Date(run.timestamp).toISOString()}>{new Date(run.timestamp).toLocaleString()}</time><span className="flex items-center gap-1" title={state}>
- {run.status === "completed" ? <Check size={15} className="text-success" aria-label={state} /> : run.status === "failed" || run.status === "cancelled" ? <X size={15} className="text-destructive" aria-label={state} /> : run.status === "skipped" ? <SkipForward size={15} className="text-muted-foreground" aria-label={state} /> : <Clock size={15} aria-label={state} />}
- </span></span>
- {run.status === "skipped" && <span data-testid="routine-run-skip-reason" className="mt-0.5 block text-[11px] leading-snug text-muted-foreground">{routineSkipReason(t, run.skipCode, run.skipProvider, run.text)}</span>}
- </button>;
- })}
- </div>
+ </section>
+
+ <RunHistory runs={runs} ready={ready} locale={locale} onOpen={openRun} />
+
+ <footer className="space-y-2 border-t border-border/70 pt-3">
+ <button type="button" className="inline-flex items-center gap-1.5 rounded-md px-1 py-0.5 text-[12px] text-muted-foreground transition-colors hover:text-destructive disabled:opacity-40" disabled={pending || !ready || running} onClick={() => setConfirmDelete(true)}><Trash2 size={13} aria-hidden />{label("delete")}</button>
+ {confirmDelete && <div className="space-y-2 rounded-xl border border-destructive/30 bg-destructive/[0.04] p-3" role="alert">
+ <p className="text-[12px] text-foreground">{label("delete_confirm")}</p>
+ <p className="text-[11px] text-muted-foreground">{own("delete_note")}</p>
+ <div className="flex gap-2">
+ <button className="rounded-lg bg-destructive px-2.5 py-1.5 text-[12px] font-medium text-destructive-foreground disabled:opacity-50" disabled={pending} onClick={() => void act(async () => {
+ for (const detail of [...details].reverse()) if (detail) await cancelAndDeleteTask(detail.id, !terminal.includes(detail.state));
+ onClose();
+ })}>{label("delete")}</button>
+ <button className={button} disabled={pending} onClick={() => setConfirmDelete(false)}>{label("cancel")}</button>
+ </div>
+ </div>}
+ </footer>
</section>;
}
diff --git a/dodaios/ui/web/frontend/src/components/society/card/AgentRoutinesList.test.tsx b/dodaios/ui/web/frontend/src/components/society/card/AgentRoutinesList.test.tsx
index 9365a93807..45f125810a 100644
--- a/dodaios/ui/web/frontend/src/components/society/card/AgentRoutinesList.test.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/card/AgentRoutinesList.test.tsx
@@ -46,6 +46,8 @@ describe("AgentRoutinesList", () => {
fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
const path = String(url);
const method = init?.method ?? "GET";
+ // Run activity, "seen" and parking routes are enrichment; they answer empty here.
+ if (path.includes("/routines-") || path.includes("/routine-parking")) return json({});
if (path.includes("/routines") && method === "POST") {
const body = JSON.parse(String(init?.body ?? "{}")) as { title?: string; prompt?: string };
routines = [
@@ -93,7 +95,9 @@ describe("AgentRoutinesList", () => {
test("shows an empty list only after the routine request succeeds", async () => {
let respond!: (response: Response) => void;
- fetchMock.mockImplementation(() => new Promise<Response>((resolve) => { respond = resolve; }));
+ fetchMock.mockImplementation((url: string) => String(url).endsWith("/routines")
+ ? new Promise<Response>((resolve) => { respond = resolve; })
+ : Promise.resolve(json({})));
mount();
expect(await screen.findByText("Loading…")).toBeTruthy();
expect(screen.queryByText("No routines yet.")).toBeNull();
diff --git a/dodaios/ui/web/frontend/src/components/society/card/AgentRoutinesList.tsx b/dodaios/ui/web/frontend/src/components/society/card/AgentRoutinesList.tsx
index 6b23066ccb..65267144e0 100644
--- a/dodaios/ui/web/frontend/src/components/society/card/AgentRoutinesList.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/card/AgentRoutinesList.tsx
@@ -1,22 +1,36 @@
-/** Per-agent routines use the same task store and trigger editor as Automations. */
+/**
+ * Per-agent routines: the jobs an agent runs on its own. They live in the
+ * same task store and trigger editor as Automations; this list adds the
+ * schedule as a sentence, the next run, the last result and its cost, quick
+ * pause/test actions, "set one up in chat", and the away-parking note.
+ */
import { useEffect, useMemo, useState } from "react";
-import { Clock, Plus, X } from "lucide-react";
+import { MessageSquarePlus, Plus, Sparkles, X } from "lucide-react";
import { useLocaleChunk, useT } from "@/i18n";
import { useRunLocale } from "@/components/runs/format";
import { cn } from "@/lib/utils";
-import { displayRoutineTitle, routineScheduleLine, useAgentRoutines, useCreateAgentRoutine, type LiveRoutine } from "../cardData";
-import type { AgentRoutine } from "../data";
-import { WebhookConnection } from "./WebhookConnection";
+import { useAgentRoutines, useCreateAgentRoutine, type LiveRoutine } from "../cardData";
+import { useSocietyAgent, type AgentRoutine } from "../data";
import { TriggerBuilder } from "./TriggerBuilder";
-import { SourceControls } from "./SourceControls";
import { AgentRoutineDetail } from "./AgentRoutineDetail";
-import { BuiltByBadge } from "@/components/selfBuild/BuiltByBadge";
+import { RoutineRow } from "./routines/RoutineRow";
+import { ParkingBanner } from "./routines/ParkingBanner";
+import { AwaySetting } from "./routines/AwaySetting";
+import { markRoutinesSeen, useRoutineActivity, useRoutineRefresh } from "./routines/routinesApi";
+import { seedAgentComposer } from "./routines/editThroughChat";
+import { useNow } from "./routines/useNow";
export interface AgentRoutinesListProps { agentId: string; sampleRoutines?: AgentRoutine[]; variant?: "rail" | "sheet"; className?: string; onDetailOpenChange?: (open: boolean) => void; }
export function AgentRoutinesList({ agentId, sampleRoutines, variant = "rail", className, onDetailOpenChange }: AgentRoutinesListProps) {
const t = useT(); useLocaleChunk("society");
const locale = useRunLocale();
+ const own = (key: string) => t(`society.agent_routines.list.${key}`);
const live = useAgentRoutines(agentId); const create = useCreateAgentRoutine();
+ const isSample = Boolean(sampleRoutines);
+ const activity = useRoutineActivity(isSample ? null : agentId);
+ const refresh = useRoutineRefresh(agentId);
+ const { agent } = useSocietyAgent(agentId);
+ const now = useNow();
const [open, setOpen] = useState(false); const [title, setTitle] = useState("");
const [prompt, setPrompt] = useState(""); const [schedule, setSchedule] = useState<Record<string, unknown> | null>(null);
const [saving, setSaving] = useState(false); const [error, setError] = useState("");
@@ -26,7 +40,14 @@ export function AgentRoutinesList({ agentId, sampleRoutines, variant = "rail", c
const selectedRoutine = rows.find((row) => row.id === selected);
const detailOpen = Boolean(selectedRoutine);
useEffect(() => { onDetailOpenChange?.(detailOpen); }, [detailOpen, onDetailOpenChange]);
- const field = "w-full rounded-md border border-border bg-background px-2 py-1.5 text-[12px] text-foreground placeholder:text-muted-foreground";
+ // Showing the routines is looking at their results: a new away period starts.
+ useEffect(() => { if (!isSample) markRoutinesSeen(agentId); }, [agentId, isSample]);
+ const parking = activity.data?.parking ?? null;
+ const parked = new Set(parking?.parked_ids ?? []);
+ const lastRuns = activity.data?.lastRuns ?? {};
+ const target = { tier: agent?.tier ?? "specialist", chatSessionId: agent?.chatSessionId ?? `society:${agentId}` };
+ const setUpInChat = () => void seedAgentComposer(target, own("setup_prompt"));
+ const field = "w-full rounded-lg border border-border bg-background px-2.5 py-1.5 text-[12px] text-foreground placeholder:text-faint-foreground transition-colors focus:border-border-strong focus:outline-none";
const submit = async () => {
if (!title.trim() || !prompt.trim() || !schedule) return;
setSaving(true); setError("");
@@ -34,44 +55,46 @@ export function AgentRoutinesList({ agentId, sampleRoutines, variant = "rail", c
catch (err) { setError(err instanceof Error ? err.message : String(err)); }
finally { setSaving(false); }
};
- if (selectedRoutine) return <AgentRoutineDetail key={`${agentId}:${selected}`} agentId={agentId} routine={selectedRoutine} onClose={() => setSelected(null)} />;
+ if (selectedRoutine) return <AgentRoutineDetail key={`${agentId}:${selected}`} agentId={agentId} routine={selectedRoutine} parked={parked.has(selectedRoutine.id)} onClose={() => setSelected(null)} />;
+ const lastRunOf = (routine: LiveRoutine) => (routine.members ?? [routine])
+ .map((member) => lastRuns[member.id]).filter(Boolean)
+ .sort((a, b) => (b!.started_ms ?? 0) - (a!.started_ms ?? 0))[0] ?? null;
+ const activeCount = rows.filter((row) => row.state !== "paused").length;
return <section className={cn("flex min-h-0 flex-col", className)} data-testid="agent-routines">
- <div className="mb-1.5 flex shrink-0 items-center justify-between gap-2">
- <h3 className={variant === "sheet" ? "ac-head" : "font-display text-[13px] font-semibold text-foreground"}>{t("society.card.routines")}{rows.length > 0 && <span className="ml-1.5 text-muted-foreground">{rows.length}</span>}</h3>
- <button type="button" data-testid="agent-routines-add" className="rounded p-1 text-muted-foreground hover:bg-secondary" aria-label={t("society.card.routines_add")} onClick={() => setOpen((v) => !v)}>{open ? <X size={14} /> : <Plus size={14} />}</button>
+ <div className="mb-2 flex shrink-0 items-center justify-between gap-2">
+ <h3 className={variant === "sheet" ? "ac-head" : "font-display text-[13px] font-semibold text-foreground"}>
+ {t("society.card.routines")}
+ {rows.length > 0 && <span className="ml-1.5 font-normal text-muted-foreground" title={own("active_hint")}>{activeCount === rows.length ? rows.length : `${activeCount}/${rows.length}`}</span>}
+ </h3>
+ <div className="flex items-center gap-0.5">
+ {!isSample && <button type="button" data-testid="agent-routines-chat" className="rounded-md p-1 text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground" aria-label={own("setup_in_chat")} title={own("setup_in_chat")} onClick={setUpInChat}><MessageSquarePlus size={14} /></button>}
+ <button type="button" data-testid="agent-routines-add" className="rounded-md p-1 text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground" aria-label={t("society.card.routines_add")} aria-expanded={open} onClick={() => setOpen((v) => !v)}>{open ? <X size={14} /> : <Plus size={14} />}</button>
+ </div>
</div>
- {open && <form className="mb-3 space-y-2 rounded-md border border-border p-2" data-testid="agent-routines-composer" onSubmit={(e) => { e.preventDefault(); void submit(); }}>
+ {parking?.banner && parking.parked_ids.length > 0 && <ParkingBanner agentId={agentId} parking={parking} onAnswered={() => void refresh()} />}
+ {open && <form className="mb-3 space-y-2 rounded-xl border border-border bg-card p-2.5 shadow-[0_1px_2px_rgb(var(--scrim-rgb)/0.05),0_4px_12px_-6px_rgb(var(--scrim-rgb)/0.12)]" data-testid="agent-routines-composer" onSubmit={(e) => { e.preventDefault(); void submit(); }}>
<input className={field} aria-label={t("society.card.routines_title")} placeholder={t("society.card.routines_title")} value={title} onChange={(e) => setTitle(e.target.value)} />
- <textarea className={field} aria-label={t("society.card.routines_prompt")} placeholder={t("society.card.routines_prompt")} value={prompt} onChange={(e) => setPrompt(e.target.value)} rows={3} />
+ <textarea className={cn(field, "resize-y leading-snug")} aria-label={t("society.card.routines_prompt")} placeholder={t("society.card.routines_prompt")} value={prompt} onChange={(e) => setPrompt(e.target.value)} rows={3} />
<TriggerBuilder onChange={setSchedule} />
- <button type="submit" disabled={saving || !title.trim() || !prompt.trim() || !schedule} className="rounded bg-primary px-2.5 py-1 text-[12px] text-primary-foreground disabled:opacity-50">{t(saving ? "society.card.saving" : "society.card.routines_save")}</button>
+ <div className="flex items-center justify-between gap-2 pt-0.5">
+ {!isSample ? <button type="button" className="text-[11px] text-muted-foreground underline-offset-2 hover:text-foreground hover:underline" onClick={() => { setOpen(false); setUpInChat(); }}>{own("or_chat")}</button> : <span />}
+ <button type="submit" disabled={saving || !title.trim() || !prompt.trim() || !schedule} className="rounded-lg bg-foreground px-3 py-1 text-[12px] font-medium text-background transition-colors hover:bg-foreground/90 disabled:opacity-40">{t(saving ? "society.card.saving" : "society.card.routines_save")}</button>
+ </div>
{error && <p role="alert" className="text-[11px] text-destructive">{error}</p>}
</form>}
- <ul className="min-h-0 flex-1 overflow-y-auto">
+ <ul className="-mx-1 min-h-0 flex-1 space-y-0.5 overflow-y-auto px-1">
{live.error && <li role="alert" className="text-[12px] text-destructive">{t("tasks_view.load_error")}</li>}
{rows.length === 0 && live.isPending && <li className="text-[12px] text-muted-foreground">{t("society.profile_card.loading")}</li>}
- {rows.length === 0 && !live.isPending && !live.error && <li className="text-[12px] text-muted-foreground">{t("society.card.no_routines")}</li>}
- {rows.map((routine) => {
- const active = ["scheduled", "active", "enabled", ""].includes(routine.state);
- const trigger = routine.trigger as { type?: string; source?: { kind: string } } | null;
- return <li key={routine.id} className="rounded-md">
- <div className="flex items-start gap-1">
- <button type="button" aria-label={displayRoutineTitle(routine.title)} className="flex w-full cursor-pointer select-none items-start gap-2 rounded-md px-0.5 py-1.5 text-left hover:bg-secondary/60 focus-visible:outline focus-visible:outline-ring" onClick={() => setSelected(routine.id)}>
- <Clock size={16} aria-hidden className={cn("mt-0.5 shrink-0", active ? "text-success" : "text-muted-foreground")} />
- <span className="min-w-0 flex-1">
- <span className="block truncate text-[13px] font-medium text-foreground">{displayRoutineTitle(routine.title)}</span>
- <span className="block break-words text-[11px] leading-snug text-muted-foreground">{routineScheduleLine(routine, t)}{routine.state === "paused" ? ` · ${t("tasks_view.state.paused")}` : ""}</span>
- {routine.dueMs && active ? <span className="block text-[11px] text-muted-foreground">{t("society.card.next_run")}: {new Date(routine.dueMs).toLocaleString(locale, { timeZoneName: "short" })}</span> : null}
- </span>
- </button>
- {/* Outside the row button: the badge is a link of its own. */}
- <BuiltByBadge compact type="routine" id={routine.id} className="mt-1.5" />
- </div>
- {trigger?.type === "webhook" && <div className="pl-6"><WebhookConnection key={routine.id} taskId={routine.id} /></div>}
- {trigger?.type === "source" && trigger.source && <div className="pl-6"><SourceControls key={routine.id} taskId={routine.id} source={trigger.source} /></div>}
- </li>;
- })}
+ {rows.length === 0 && !live.isPending && !live.error && <li className="rounded-xl border border-dashed border-border px-3 py-4 text-center">
+ <Sparkles size={16} aria-hidden className="mx-auto mb-1.5 text-faint-foreground" />
+ <p className="text-[12.5px] font-medium text-foreground">{t("society.card.no_routines")}</p>
+ <p className="mx-auto mt-1 max-w-[30ch] text-[11.5px] leading-snug text-muted-foreground">{own("empty_body")}</p>
+ {!isSample && <button type="button" onClick={setUpInChat} className="mt-2.5 inline-flex items-center gap-1.5 rounded-full border border-border px-2.5 py-1 text-[11.5px] text-foreground transition-colors hover:bg-secondary"><MessageSquarePlus size={12} />{own("setup_in_chat")}</button>}
+ </li>}
+ {rows.map((routine) => <RoutineRow key={routine.id} routine={routine} lastRun={lastRunOf(routine)} parked={parked.has(routine.id)}
+ locale={locale} now={now} onOpen={() => setSelected(routine.id)} onChanged={() => void refresh()} />)}
</ul>
+ {!isSample && rows.length > 0 && <AwaySetting agentId={agentId} neverAsk={Boolean(parking?.never_ask)} onChanged={() => void refresh()} />}
</section>;
}
export default AgentRoutinesList;
diff --git a/dodaios/ui/web/frontend/src/components/society/card/TriggerBuilder.tsx b/dodaios/ui/web/frontend/src/components/society/card/TriggerBuilder.tsx
index a544ddb0e6..3dda87ef1b 100644
--- a/dodaios/ui/web/frontend/src/components/society/card/TriggerBuilder.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/card/TriggerBuilder.tsx
@@ -2,6 +2,8 @@ import { useEffect, useMemo, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { BrandedSelect } from "@/components/ui/select";
import { useLocaleChunk, useT } from "@/i18n";
+import { useRunLocale } from "@/components/runs/format";
+import { humanSchedule } from "./routines/humanSchedule";
export const TRIGGER_GROUPS = {
human: ["manual", "chat", "form"],
@@ -22,6 +24,7 @@ export function TriggerBuilder({ onChange, initialValue, timeOnly = false }: {
}) {
const t = useT();
useLocaleChunk("society");
+ const locale = useRunLocale();
const [group, setGroup] = useState<Group>(() => {
const kind = String(initialValue?.type ?? "every");
return (Object.entries(TRIGGER_GROUPS).find(([, kinds]) => (kinds as readonly string[]).includes(kind))?.[0] ?? "time") as Group;
@@ -98,6 +101,7 @@ export function TriggerBuilder({ onChange, initialValue, timeOnly = false }: {
{kind === "calendar" && input("time", time, setTime, "time")}
{kind === "cron" && input("expression", expression, setExpression)}
{(kind === "calendar" || kind === "cron") && input("timezone", timezone, setTimezone)}
+ {value && ["every", "calendar", "cron", "after_delay"].includes(kind) && <p data-testid="trigger-preview" aria-live="polite" className="text-[11px] leading-snug text-foreground-secondary">{humanSchedule(initialValue?.type === value.type ? { ...initialValue, ...value } : value, { t, locale })}</p>}
{kind === "at_time" && input("date", date, setDate, "datetime-local")}
{group === "stream" && <>{input("endpoint", endpoint, setEndpoint)}{kind !== "sse" && <>{input("topic", topic, setTopic)}{input("consumer_group", consumerGroup, setConsumerGroup)}</>}<p className="text-[11px] text-muted-foreground">{label("credentials_hint")}</p></>}
{kind === "file" && <>{input("path", path, setPath)}{input("pattern", pattern, setPattern)}<label className="text-[11px]"><input type="checkbox" checked={recursive} onChange={(e) => setRecursive(e.target.checked)} /> {label("recursive")}</label></>}
diff --git a/dodaios/ui/web/frontend/src/components/society/card/WebhookConnection.tsx b/dodaios/ui/web/frontend/src/components/society/card/WebhookConnection.tsx
index 2f8e11a674..2a041275ed 100644
--- a/dodaios/ui/web/frontend/src/components/society/card/WebhookConnection.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/card/WebhookConnection.tsx
@@ -1,23 +1,49 @@
import { ProviderVerification } from "./ProviderVerification";
-import { useState } from "react";
+import { useState, type ReactNode } from "react";
+import { Check, Copy, Eye, EyeOff, KeyRound, Link2, RotateCw, TerminalSquare } from "lucide-react";
import { useLocaleChunk, useT } from "@/i18n";
+import { cn } from "@/lib/utils";
type Connection = { path: string; token: string; provider?: string; configured?: boolean; oidc_audience?: string; service_account?: string };
-/** Credentials stay in this UI's memory, never in chat or the routine spec. */
+const MASK = "•".repeat(20);
+
+const ICON = "shrink-0 rounded-md p-1 text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground";
+
+function CopyButton({ label, copiedLabel, done, onCopy }: { label: string; copiedLabel: string; done: boolean; onCopy: () => void }) {
+ return <button type="button" className={ICON} onClick={onCopy} aria-label={label} title={done ? copiedLabel : undefined}>
+ {done ? <Check size={13} className="text-success" /> : <Copy size={13} />}
+ </button>;
+}
+
+function Row({ glyph, title, help, children }: { glyph: ReactNode; title: string; help: string; children: ReactNode }) {
+ return <div className="space-y-1">
+ <div className="flex items-center gap-1.5 text-[11px] font-medium text-muted-foreground">{glyph}{title}</div>
+ <div className="flex items-center gap-1 rounded-lg border border-border bg-background px-2 py-1">{children}</div>
+ <p className="text-[10.5px] leading-snug text-faint-foreground">{help}</p>
+ </div>;
+}
+
+/**
+ * A webhook routine's connection: the URL to POST to, its key (masked until
+ * revealed) and a ready header line, each with copy and one line of help.
+ * Credentials stay in this UI's memory, never in chat or the routine spec.
+ */
export function WebhookConnection({ taskId }: { taskId: string }) {
const t = useT();
const ready = useLocaleChunk("society");
const [connection, setConnection] = useState<Connection | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
- const [copied, setCopied] = useState(false);
+ const [copied, setCopied] = useState<"url" | "token" | "header" | null>(null);
+ const [revealed, setRevealed] = useState(false);
+ const own = (key: string) => t(`society.agent_routines.webhook.${key}`);
const load = async (rotate = false) => {
if (rotate && !window.confirm(t("society.hooks.rotate_confirm"))) return;
setBusy(true);
setError("");
- setCopied(false);
+ setCopied(null);
try {
const response = await fetch(`/api/tasks/${encodeURIComponent(taskId)}/webhook-connection${rotate ? "/rotate" : ""}`, {
method: rotate ? "POST" : "GET", cache: "no-store",
@@ -32,38 +58,48 @@ export function WebhookConnection({ taskId }: { taskId: string }) {
}
};
- const copy = async () => {
- if (!connection) return;
+ const copy = async (which: "url" | "token" | "header", text: string) => {
try {
- await navigator.clipboard.writeText(connection.token);
- setCopied(true);
+ await navigator.clipboard.writeText(text);
+ setCopied(which);
+ window.setTimeout(() => setCopied((current) => (current === which ? null : current)), 1800);
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
}
};
if (!ready) return null;
- const button = "rounded border border-border px-2 py-1 text-[11px] text-foreground hover:bg-secondary disabled:opacity-50";
- const field = "w-full rounded border border-border bg-background p-1 text-[11px] text-foreground";
+ const button = "inline-flex items-center gap-1.5 rounded-lg border border-border px-2.5 py-1 text-[11.5px] text-foreground transition-colors hover:bg-secondary disabled:opacity-50";
+ const value = "min-w-0 flex-1 truncate bg-transparent font-mono text-[11px] text-foreground focus:outline-none";
+ const href = connection ? new URL(connection.path, window.location.origin).href : "";
+ const header = connection ? `Authorization: Bearer ${connection.token}` : "";
return (
- <div className="mt-2 block space-y-2" data-testid="webhook-connection">
+ <div className="mt-2 block space-y-2.5" data-testid="webhook-connection">
{!connection ? <button type="button" className={button} disabled={busy} onClick={() => void load()}>
- {t(busy ? "society.hooks.loading" : "society.hooks.connect")}
+ <Link2 size={13} />{t(busy ? "society.hooks.loading" : "society.hooks.connect")}
</button> : <>
- <label className="block text-[11px] text-muted-foreground">{t("society.hooks.endpoint")}
- <input className={field} readOnly value={new URL(connection.path, window.location.origin).href} />
- </label>
+ <Row glyph={<Link2 size={12} />} title={t("society.hooks.endpoint")} help={own("url_help")}>
+ <input className={value} readOnly aria-label={t("society.hooks.endpoint")} value={href} onFocus={(e) => e.currentTarget.select()} />
+ <CopyButton label={own("copy_url")} copiedLabel={t("society.hooks.copied")} done={copied === "url"} onCopy={() => void copy("url", href)} />
+ </Row>
{connection.provider && !["generic", "github"].includes(connection.provider) ? <ProviderVerification taskId={taskId} provider={connection.provider} configured={connection.configured} audience={connection.oidc_audience} serviceAccount={connection.service_account} /> : <>
- <label className="block text-[11px] text-muted-foreground">{t("society.hooks.token")}
- <input className={field} type="password" readOnly autoComplete="off" value={connection.token} />
- </label>
- <span className="flex flex-wrap gap-2">
- <button type="button" className={button} onClick={() => void copy()}>{t(copied ? "society.hooks.copied" : "society.hooks.copy")}</button>
- <button type="button" className={button} disabled={busy} onClick={() => void load(true)}>{t("society.hooks.rotate")}</button>
- </span>
- <span className="block text-[11px] text-muted-foreground">{t("society.hooks.auth")}</span>
+ <Row glyph={<KeyRound size={12} />} title={t("society.hooks.token")} help={own("key_help")}>
+ <input className={value} type={revealed ? "text" : "password"} readOnly autoComplete="off" aria-label={t("society.hooks.token")} value={connection.token} />
+ <button type="button" className={ICON} onClick={() => setRevealed((v) => !v)} aria-label={revealed ? own("hide") : own("reveal")} aria-pressed={revealed}>
+ {revealed ? <EyeOff size={13} /> : <Eye size={13} />}
+ </button>
+ <CopyButton label={t("society.hooks.copy")} copiedLabel={t("society.hooks.copied")} done={copied === "token"} onCopy={() => void copy("token", connection.token)} />
+ </Row>
+ <Row glyph={<TerminalSquare size={12} />} title={own("header")} help={own("header_help")}>
+ <code className={cn(value, "select-all")} data-testid="webhook-header-line">{revealed ? header : `Authorization: Bearer ${MASK}`}</code>
+ <CopyButton label={own("copy_header")} copiedLabel={t("society.hooks.copied")} done={copied === "header"} onCopy={() => void copy("header", header)} />
+ </Row>
+ <span className="flex flex-wrap gap-2">
+ <button type="button" className={button} disabled={busy} onClick={() => void load(true)}><RotateCw size={12} />{t("society.hooks.rotate")}</button>
+ </span>
+ <span className="block text-[10.5px] leading-snug text-faint-foreground">{t("society.hooks.auth")}</span>
</>}
- <span className="block text-[11px] text-muted-foreground">{t("society.hooks.remote")}</span>
+ <span className="block text-[10.5px] leading-snug text-faint-foreground">{t("society.hooks.remote")}</span>
</>}
{error ? <span role="alert" className="block text-[11px] text-destructive">{error}</span> : null}
</div>
diff --git a/dodaios/ui/web/frontend/src/components/society/card/routines/AwaySetting.tsx b/dodaios/ui/web/frontend/src/components/society/card/routines/AwaySetting.tsx
new file mode 100644
index 0000000000..a2497094ce
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/card/routines/AwaySetting.tsx
@@ -0,0 +1,40 @@
+/** The away-parking window, as one quiet line under the routine list. */
+import { useQueryClient } from "@tanstack/react-query";
+import { MoonStar } from "lucide-react";
+import { useState } from "react";
+import { useT } from "@/i18n";
+import { BrandedSelect } from "@/components/ui/select";
+import { answerParking, saveParkingDays, useParkingDays } from "./routinesApi";
+import { fill } from "./format";
+
+const CHOICES = [0, 3, 7, 14, 30];
+
+export function AwaySetting({ agentId, neverAsk, onChanged }: { agentId: string; neverAsk: boolean; onChanged: () => void }) {
+ const t = useT();
+ const own = (key: string) => t(`society.agent_routines.away.${key}`);
+ const days = useParkingDays();
+ const client = useQueryClient();
+ const [error, setError] = useState("");
+ if (days.isError || days.data === undefined) return null;
+ const value = String(days.data);
+ const options = [...new Set([...CHOICES, days.data])].sort((a, b) => a - b)
+ .map((n) => ({ value: String(n), label: n === 0 ? own("never") : fill(own("after_days"), { n }) }));
+ return <div className="mt-3 flex shrink-0 items-center gap-2 border-t border-border/70 pt-2.5 text-[11px] text-muted-foreground" data-testid="routine-away-setting">
+ <MoonStar size={13} aria-hidden className="shrink-0" />
+ <span className="min-w-0 flex-1 leading-tight" title={own("hint")}>{neverAsk ? own("off_for_agent") : own("label")}</span>
+ {neverAsk ? <button type="button" className="shrink-0 rounded-md px-1.5 py-0.5 text-foreground hover:bg-secondary" onClick={() => {
+ setError("");
+ void answerParking(agentId, "ask_again").then(onChanged).catch((err: unknown) => setError(err instanceof Error ? err.message : String(err)));
+ }}>{own("turn_on")}</button> : <div className="w-[112px] shrink-0">
+ <BrandedSelect value={value} options={options} ariaLabel={own("label")} onValueChange={(next) => {
+ setError("");
+ void saveParkingDays(Number(next)).then((saved) => {
+ client.setQueryData(["society", "routine-parking-days"], saved);
+ void client.invalidateQueries({ queryKey: ["society", "routine-activity", agentId] });
+ onChanged();
+ }).catch((err: unknown) => setError(err instanceof Error ? err.message : String(err)));
+ }} />
+ </div>}
+ {error && <span role="alert" className="text-destructive">{error}</span>}
+ </div>;
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/card/routines/ParkingBanner.tsx b/dodaios/ui/web/frontend/src/components/society/card/routines/ParkingBanner.tsx
new file mode 100644
index 0000000000..2d27ba5521
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/card/routines/ParkingBanner.tsx
@@ -0,0 +1,48 @@
+/**
+ * The one-time note after away-parking paused an agent's routines: resume,
+ * keep them paused, or resume and never pause them again. It shows once per
+ * park; any answer closes it for good.
+ */
+import { useState } from "react";
+import { MoonStar } from "lucide-react";
+import { useT } from "@/i18n";
+import { answerParking, type ParkingChoice, type ParkingView } from "./routinesApi";
+import { fill } from "./format";
+
+export function ParkingBanner({ agentId, parking, onAnswered }: {
+ agentId: string; parking: ParkingView; onAnswered: () => void;
+}) {
+ const t = useT();
+ const own = (key: string) => t(`society.agent_routines.parking.${key}`);
+ const [busy, setBusy] = useState<ParkingChoice | null>(null);
+ const [error, setError] = useState("");
+ const choose = async (choice: ParkingChoice) => {
+ setBusy(choice); setError("");
+ try { await answerParking(agentId, choice); onAnswered(); }
+ catch (err) { setError(err instanceof Error ? err.message : String(err)); }
+ finally { setBusy(null); }
+ };
+ const count = parking.parked_ids.length;
+ const button = "rounded-lg px-2.5 py-1 text-[12px] font-medium transition-colors duration-150 disabled:opacity-50";
+ return <div role="status" data-testid="routine-parking-banner"
+ className="mb-3 rounded-xl border border-warning/30 bg-warning/[0.06] p-3 shadow-[0_1px_2px_rgb(var(--scrim-rgb)/0.06)]">
+ <div className="flex items-start gap-2.5">
+ <MoonStar size={16} aria-hidden className="mt-0.5 shrink-0 text-warning" />
+ <div className="min-w-0 flex-1 space-y-1">
+ <p className="text-[13px] font-semibold leading-tight text-foreground-strong">{own("title")}</p>
+ <p className="text-[12px] leading-snug text-foreground-secondary">
+ {fill(own(count === 1 ? "body_one" : "body"), { count, unread: parking.unread, days: parking.parked_days })}
+ </p>
+ </div>
+ </div>
+ <div className="mt-2.5 flex flex-wrap gap-1.5 pl-[26px]">
+ <button type="button" disabled={busy !== null} onClick={() => void choose("keep_running")}
+ className={`${button} bg-foreground text-background hover:bg-foreground/90`}>{own("keep_running")}</button>
+ <button type="button" disabled={busy !== null} onClick={() => void choose("keep_paused")}
+ className={`${button} border border-border bg-background text-foreground hover:bg-secondary`}>{own("keep_paused")}</button>
+ <button type="button" disabled={busy !== null} onClick={() => void choose("never_ask")}
+ className={`${button} text-muted-foreground hover:bg-secondary hover:text-foreground`}>{own("never_ask")}</button>
+ </div>
+ {error && <p role="alert" className="mt-2 pl-[26px] text-[11px] text-destructive">{error}</p>}
+ </div>;
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/card/routines/RoutineRow.tsx b/dodaios/ui/web/frontend/src/components/society/card/routines/RoutineRow.tsx
new file mode 100644
index 0000000000..68a836ce16
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/card/routines/RoutineRow.tsx
@@ -0,0 +1,99 @@
+/**
+ * One routine in the agent's list: what triggers it, the schedule as a
+ * sentence, when it runs next, how the last run went and what it cost.
+ * Pause/resume and a test run sit on the row and appear on hover or focus.
+ */
+import { useId, useState } from "react";
+import { Pause, Play, Loader2 } from "lucide-react";
+import { useT } from "@/i18n";
+import { cn } from "@/lib/utils";
+import { runTaskNow, setTaskEnabled } from "@/lib/tasksApi";
+import { BuiltByBadge } from "@/components/selfBuild/BuiltByBadge";
+import { displayRoutineTitle, type LiveRoutine } from "../../cardData";
+import { TriggerIcon, type RoutineTone } from "./TriggerIcon";
+import { RunStatusIcon } from "./RunStatus";
+import { humanSchedule, triggerFamily } from "./humanSchedule";
+import { formatCost, relativeTime } from "./format";
+import type { RoutineRunRow } from "./routinesApi";
+import { runStateLabel } from "./RunHistory";
+
+const ACTIVE = ["scheduled", "active", "enabled", ""];
+const TERMINAL = ["completed", "failed", "cancelled", "interrupted"];
+
+export function routineTone(routine: LiveRoutine, lastRun: RoutineRunRow | null | undefined, parked: boolean): RoutineTone {
+ if (routine.state === "running") return "running";
+ if (routine.state === "paused") return parked ? "parked" : "paused";
+ if (lastRun?.status === "failed") return "failed";
+ return ACTIVE.includes(routine.state) ? "active" : "paused";
+}
+
+export function RoutineRow({ routine, lastRun, parked, locale, now, onOpen, onChanged }: {
+ routine: LiveRoutine; lastRun?: RoutineRunRow | null; parked: boolean; locale: string; now: number;
+ onOpen: () => void; onChanged: () => void;
+}) {
+ const t = useT();
+ const own = (key: string) => t(`society.agent_routines.list.${key}`);
+ const describedBy = useId();
+ const [busy, setBusy] = useState<"run" | "toggle" | null>(null);
+ const [problem, setProblem] = useState("");
+ const title = displayRoutineTitle(routine.title);
+ const tone = routineTone(routine, lastRun, parked);
+ const active = ACTIVE.includes(routine.state);
+ const sentence = humanSchedule(routine.trigger, { t, locale }) || routine.schedule;
+ const members = routine.members ?? [routine];
+ const family = triggerFamily(routine.trigger);
+ const canRun = routine.state !== "running" && !TERMINAL.includes(routine.state) && family !== "source" && family !== "manual";
+ const canToggle = routine.state === "paused" || (active && routine.state !== "running");
+ const act = async (kind: "run" | "toggle") => {
+ setBusy(kind); setProblem("");
+ try {
+ if (kind === "run") await runTaskNow(routine.id);
+ else for (const member of members) {
+ if (TERMINAL.includes(member.state)) continue;
+ if ((member.state === "paused") === (routine.state === "paused")) await setTaskEnabled(member.id, routine.state === "paused");
+ }
+ } catch (err) { setProblem(err instanceof Error ? err.message : String(err)); }
+ finally { setBusy(null); onChanged(); }
+ };
+ const cost = formatCost(lastRun?.cost_usd, locale);
+ const lastAt = lastRun?.finished_ms ?? lastRun?.started_ms ?? null;
+ const tool = "rounded-md p-1.5 text-muted-foreground transition-colors duration-150 hover:bg-background hover:text-foreground focus-visible:outline focus-visible:outline-1 focus-visible:outline-ring disabled:opacity-40";
+ return <li className="group relative">
+ <div className="flex items-start gap-1 rounded-xl transition-colors duration-150 hover:bg-secondary/55 focus-within:bg-secondary/55">
+ <button type="button" aria-label={title} aria-describedby={describedBy} onClick={onOpen}
+ className="flex min-w-0 flex-1 cursor-pointer select-none items-start gap-2.5 rounded-xl px-2 py-2 text-left focus-visible:outline focus-visible:outline-1 focus-visible:outline-ring">
+ <TriggerIcon trigger={routine.trigger} tone={tone} />
+ <span className="min-w-0 flex-1">
+ <span className={cn("block truncate text-[13px] font-medium leading-5", tone === "paused" || tone === "parked" ? "text-muted-foreground" : "text-foreground")}>{title}</span>
+ <span id={describedBy} className="contents">
+ <span className="block break-words text-[11.5px] leading-snug text-foreground-secondary">{sentence}</span>
+ <span className="mt-0.5 flex flex-wrap items-center gap-x-1.5 gap-y-0.5 text-[11px] leading-4 text-muted-foreground">
+ {routine.state === "running" && <span className="font-medium text-primary">{own("running")}</span>}
+ {routine.state === "paused" && <span className={cn("font-medium", parked ? "text-warning" : "")}>{parked ? own("parked") : t("tasks_view.state.paused")}</span>}
+ {routine.dueMs && active ? <span title={new Date(routine.dueMs).toLocaleString(locale, { timeZoneName: "short" })}>{t("society.card.next_run")}: {routine.dueMs <= now ? own("due_now") : relativeTime(routine.dueMs, now, locale)}</span> : null}
+ {lastRun && lastRun.status !== "running" && lastAt ? <span className="inline-flex items-center gap-1" title={lastRun.error || lastRun.summary || undefined}>
+ <span aria-hidden className="text-faint-foreground">·</span>
+ <RunStatusIcon status={lastRun.status} label={runStateLabel(t, lastRun.status)} size={12} />
+ <span className={lastRun.status === "failed" ? "text-destructive/90" : ""}>{relativeTime(lastAt, now, locale)}</span>
+ {cost && <span className="tabular-nums">· {cost}</span>}
+ </span> : null}
+ </span>
+ {lastRun?.status === "failed" && lastRun.error && <span className="mt-0.5 block truncate text-[11px] text-destructive/80" title={lastRun.error}>{lastRun.error}</span>}
+ </span>
+ </span>
+ </button>
+ <div className="flex shrink-0 items-center gap-0.5 self-center pr-1 opacity-0 transition-opacity duration-150 group-hover:opacity-100 group-focus-within:opacity-100 [@media(hover:none)]:opacity-100">
+ {canRun && <button type="button" className={tool} disabled={busy !== null} onClick={() => void act("run")} aria-label={own("test_run")} title={own("test_run")}>
+ {busy === "run" ? <Loader2 size={14} className="motion-safe:animate-spin" /> : <Play size={14} />}
+ </button>}
+ {canToggle && <button type="button" className={tool} disabled={busy !== null} onClick={() => void act("toggle")}
+ aria-label={routine.state === "paused" ? own("resume") : own("pause")} title={routine.state === "paused" ? own("resume") : own("pause")}>
+ {busy === "toggle" ? <Loader2 size={14} className="motion-safe:animate-spin" /> : routine.state === "paused" ? <Play size={14} className="text-success" /> : <Pause size={14} />}
+ </button>}
+ </div>
+ {/* Outside the row button: the badge is a link of its own. */}
+ <BuiltByBadge compact type="routine" id={routine.id} className="mt-2.5" />
+ </div>
+ {problem && <p role="alert" className="px-2 pb-1 text-[11px] text-destructive">{problem}</p>}
+ </li>;
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/card/routines/RunHistory.tsx b/dodaios/ui/web/frontend/src/components/society/card/routines/RunHistory.tsx
new file mode 100644
index 0000000000..1c4379d200
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/card/routines/RunHistory.tsx
@@ -0,0 +1,93 @@
+/** A routine's runs: outcome, when, how it started, how long, what it cost, what it said. */
+import { useEffect, useState } from "react";
+import { ChevronRight } from "lucide-react";
+import { useT } from "@/i18n";
+import { cn } from "@/lib/utils";
+import { routineSkipReason } from "@/lib/skipReasons";
+import { RunStatusIcon } from "./RunStatus";
+import { fill, formatCost, formatDuration, shortDateTime } from "./format";
+import type { Run } from "./runs";
+
+const FIRST_PAGE = 12;
+
+function useTicking(active: boolean): number {
+ const [now, setNow] = useState(() => Date.now());
+ useEffect(() => {
+ if (!active) return;
+ const timer = window.setInterval(() => setNow(Date.now()), 1000);
+ return () => window.clearInterval(timer);
+ }, [active]);
+ return now;
+}
+
+export function runStateLabel(t: (key: string) => string, status: string): string {
+ if (status === "legacy") return t("society.routine_detail.legacy");
+ if (status === "skipped") return t("society.routine_detail.skipped");
+ const own = t(`society.agent_routines.status.${status}`);
+ return own.startsWith("society.") ? t(`tasks_view.state.${status}`) : own;
+}
+
+export function runReason(t: (key: string) => string, run: Run): string {
+ if (run.status === "skipped") {
+ return run.skipCode === "away_parked" ? t("society.agent_routines.runs.skip_away") : routineSkipReason(t, run.skipCode, run.skipProvider, run.text);
+ }
+ if (run.status === "failed" || run.status === "interrupted") return run.error || run.text;
+ return run.summary ?? "";
+}
+
+export function RunHistory({ runs, ready, locale, onOpen }: {
+ runs: Run[]; ready: boolean; locale: string; onOpen: (run: Run) => void;
+}) {
+ const t = useT();
+ const label = (key: string) => t(`society.routine_detail.${key}`);
+ const own = (key: string) => t(`society.agent_routines.runs.${key}`);
+ const [all, setAll] = useState(false);
+ const running = runs.some((run) => run.status === "running");
+ const now = useTicking(running);
+ const shown = all ? runs : runs.slice(0, FIRST_PAGE);
+ return <section className="space-y-2" aria-labelledby="routine-runs-heading">
+ <div className="flex items-center justify-between gap-2">
+ <h4 id="routine-runs-heading" className="text-[11px] font-semibold uppercase tracking-[0.08em] text-muted-foreground">
+ {label("history")}{runs.length > 0 && <span className="ml-1.5 font-normal normal-case tracking-normal text-faint-foreground">{runs.length}</span>}
+ </h4>
+ {runs.length > 0 && <button type="button" className="rounded-md px-1.5 py-0.5 text-[11px] text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground" onClick={() => onOpen(runs[0])}>{label("latest_chat")}</button>}
+ </div>
+ {ready && runs.length === 0 && <p className="rounded-xl border border-dashed border-border px-3 py-4 text-center text-[12px] leading-snug text-muted-foreground">{own("empty")}</p>}
+ {runs.length > 0 && <ol className="divide-y divide-border/70 overflow-hidden rounded-xl border border-border">
+ {shown.map((run) => {
+ const state = runStateLabel(t, run.status);
+ const reason = runReason(t, run);
+ const elapsed = run.status === "running" && run.startedMs ? Math.max(0, now - run.startedMs) : undefined;
+ const duration = formatDuration(elapsed ?? run.durationMs);
+ const cost = formatCost(run.costUsd, locale);
+ const at = new Date(run.timestamp);
+ return <li key={run.id}>
+ <button type="button" data-testid={`routine-run-${run.id}`}
+ aria-label={`${label("open_chat")} · ${at.toLocaleString(locale)} · ${state}`}
+ onClick={() => onOpen(run)}
+ className="group flex w-full cursor-pointer items-start gap-2.5 px-3 py-2 text-left transition-colors duration-150 hover:bg-secondary/60 focus-visible:bg-secondary/60 focus-visible:outline-none">
+ <RunStatusIcon status={run.status} label={state} className="mt-[1px]" />
+ <span className="min-w-0 flex-1">
+ <span className="flex items-baseline gap-2">
+ <time dateTime={at.toISOString()} title={at.toLocaleString(locale)} className="text-[12px] font-medium text-foreground">{shortDateTime(run.timestamp, now, locale)}</time>
+ {run.origin === "manual" && <span className="rounded-full border border-border px-1.5 text-[10px] leading-4 text-muted-foreground">{own("manual")}</span>}
+ <span className="ml-auto flex shrink-0 items-baseline gap-1.5 text-[11px] tabular-nums text-muted-foreground">
+ {duration && <span>{duration}</span>}
+ {duration && cost && <span aria-hidden className="text-faint-foreground">·</span>}
+ {cost && <span title={run.billedViaKey === false ? own("included") : undefined}>{cost}</span>}
+ </span>
+ </span>
+ {reason && <span data-testid={run.status === "skipped" ? "routine-run-skip-reason" : undefined}
+ className={cn("mt-0.5 block truncate text-[11px] leading-snug", run.status === "failed" ? "text-destructive/90" : "text-muted-foreground")}
+ title={reason}>{reason}</span>}
+ </span>
+ <ChevronRight size={14} aria-hidden className="mt-0.5 shrink-0 text-faint-foreground opacity-0 transition-opacity group-hover:opacity-100 group-focus-visible:opacity-100" />
+ </button>
+ </li>;
+ })}
+ </ol>}
+ {runs.length > FIRST_PAGE && <button type="button" className="text-[11px] text-muted-foreground hover:text-foreground" onClick={() => setAll((v) => !v)}>
+ {all ? own("show_less") : fill(own("show_all"), { n: runs.length })}
+ </button>}
+ </section>;
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/card/routines/RunStatus.tsx b/dodaios/ui/web/frontend/src/components/society/card/routines/RunStatus.tsx
new file mode 100644
index 0000000000..6589c21370
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/card/routines/RunStatus.tsx
@@ -0,0 +1,24 @@
+import { CheckCircle2, CircleDashed, Clock, Loader2, PauseCircle, SkipForward, XCircle, type LucideIcon } from "lucide-react";
+import { cn } from "@/lib/utils";
+
+const STATUS: Record<string, { icon: LucideIcon; tone: string; spin?: boolean }> = {
+ completed: { icon: CheckCircle2, tone: "text-success" },
+ failed: { icon: XCircle, tone: "text-destructive" },
+ cancelled: { icon: XCircle, tone: "text-muted-foreground" },
+ interrupted: { icon: XCircle, tone: "text-warning" },
+ skipped: { icon: SkipForward, tone: "text-muted-foreground" },
+ running: { icon: Loader2, tone: "text-primary", spin: true },
+ pending: { icon: Clock, tone: "text-muted-foreground" },
+ waiting: { icon: PauseCircle, tone: "text-warning" },
+ legacy: { icon: CircleDashed, tone: "text-muted-foreground" },
+};
+
+/** One run's outcome as a glyph; `label` is its accessible name. */
+export function RunStatusIcon({ status, label, size = 15, className }: {
+ status: string; label: string; size?: number; className?: string;
+}) {
+ const entry = STATUS[status] ?? STATUS.pending;
+ const Icon = entry.icon;
+ return <Icon size={size} strokeWidth={2} role="img" aria-label={label}
+ className={cn("shrink-0", entry.tone, entry.spin && "motion-safe:animate-spin", className)} />;
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/card/routines/TriggerIcon.tsx b/dodaios/ui/web/frontend/src/components/society/card/routines/TriggerIcon.tsx
new file mode 100644
index 0000000000..64559fce12
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/card/routines/TriggerIcon.tsx
@@ -0,0 +1,40 @@
+import { CalendarClock, Clock, Hand, Radio, Repeat, Timer, Webhook, Zap, type LucideIcon } from "lucide-react";
+import { cn } from "@/lib/utils";
+import { triggerFamily, type TriggerFamily } from "./humanSchedule";
+
+const ICONS: Record<TriggerFamily, LucideIcon> = {
+ clock: CalendarClock,
+ interval: Repeat,
+ once: Timer,
+ webhook: Webhook,
+ event: Zap,
+ source: Radio,
+ manual: Hand,
+ unknown: Clock,
+};
+
+export type RoutineTone = "active" | "paused" | "running" | "failed" | "parked";
+
+/** The routine's trigger as a small tile; the ring says how it is doing. */
+export function TriggerIcon({ trigger, tone = "active", size = "md", className }: {
+ trigger: unknown; tone?: RoutineTone; size?: "md" | "lg"; className?: string;
+}) {
+ const Icon = ICONS[triggerFamily(trigger)];
+ return <span
+ aria-hidden
+ data-tone={tone}
+ className={cn(
+ "relative inline-flex shrink-0 items-center justify-center border transition-colors duration-200",
+ size === "lg" ? "h-10 w-10 rounded-xl" : "h-8 w-8 rounded-[10px]",
+ tone === "paused" || tone === "parked" ? "border-border bg-secondary/40 text-faint-foreground"
+ : tone === "failed" ? "border-destructive/35 bg-destructive/[0.07] text-destructive"
+ : tone === "running" ? "border-primary/45 bg-primary/[0.08] text-primary"
+ : "border-border bg-secondary text-foreground-secondary",
+ className,
+ )}
+ >
+ <Icon size={size === "lg" ? 18 : 15} strokeWidth={1.75} />
+ {tone === "running" && <span className="absolute -right-0.5 -top-0.5 h-2 w-2 rounded-full bg-primary motion-safe:animate-pulse" />}
+ {tone === "parked" && <span className="absolute -right-0.5 -top-0.5 h-2 w-2 rounded-full bg-warning" />}
+ </span>;
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/card/routines/TriggerPreview.test.tsx b/dodaios/ui/web/frontend/src/components/society/card/routines/TriggerPreview.test.tsx
new file mode 100644
index 0000000000..07ee410519
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/card/routines/TriggerPreview.test.tsx
@@ -0,0 +1,24 @@
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, expect, test, vi } from "vitest";
+import en from "@/i18n/locales/society/en.json";
+
+vi.mock("@/i18n", () => ({
+ useLocaleChunk: () => true,
+ useUiLanguage: () => "en",
+ useI18nStore: { getState: () => ({ ui: "en" }) },
+ useT: () => (key: string) => key.split(".").reduce<unknown>((value, part) => (value as Record<string, unknown>)?.[part], en) as string ?? key,
+}));
+
+import { TriggerBuilder } from "../TriggerBuilder";
+
+afterEach(cleanup);
+
+test("the trigger editor reads the schedule back as a sentence while typing", () => {
+ render(<QueryClientProvider client={new QueryClient()}>
+ <TriggerBuilder timeOnly initialValue={{ type: "cron", expression: "0 9 * * 1", timezone: Intl.DateTimeFormat().resolvedOptions().timeZone }} onChange={() => {}} />
+ </QueryClientProvider>);
+ expect(screen.getByTestId("trigger-preview").textContent).toMatch(/^Every Monday at 09:00/);
+ fireEvent.change(screen.getByDisplayValue("0 9 * * 1"), { target: { value: "*/15 * * * *" } });
+ expect(screen.getByTestId("trigger-preview").textContent).toBe("Every 15 minutes");
+});
diff --git a/dodaios/ui/web/frontend/src/components/society/card/routines/editThroughChat.ts b/dodaios/ui/web/frontend/src/components/society/card/routines/editThroughChat.ts
new file mode 100644
index 0000000000..074be068e5
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/card/routines/editThroughChat.ts
@@ -0,0 +1,44 @@
+/**
+ * "Edit in chat": put a ready sentence into the agent's own composer so the
+ * agent rewrites its routine itself. Nothing is sent; the person finishes the
+ * sentence and presses Send.
+ */
+import { writeComposerDraft } from "@/components/agentchat/composerDrafts";
+import { useRoutineNavigation } from "../../chat/routineNavigation";
+
+export interface ComposerTarget {
+ tier: string;
+ chatSessionId: string | null;
+}
+
+/** Focus the visible chat field and put the caret at the end. */
+function focusComposer(): void {
+ const fields = [...document.querySelectorAll<HTMLElement>("[data-jarvis-chat-input]")]
+ .filter((field) => field.isContentEditable && field.offsetParent !== null && !field.closest("[data-testid='routine-chat']"));
+ const field = fields[0];
+ if (!field) return;
+ field.focus();
+ const selection = window.getSelection();
+ if (!selection) return;
+ const range = document.createRange();
+ range.selectNodeContents(field);
+ range.collapse(false);
+ selection.removeAllRanges();
+ selection.addRange(range);
+}
+
+/** Seed the agent's composer with `text`; resolves once the draft is written. */
+export async function seedAgentComposer(agent: ComposerTarget, text: string): Promise<void> {
+ // Loaded on click: the chat panel module is large and imports this card.
+ const [{ useSocietyChatStore }, { useAgentChatStore }] = await Promise.all([
+ import("../../chat/AgentChatPanel"),
+ import("@/store/agentChat"),
+ ]);
+ const store = agent.tier === "lead" ? useAgentChatStore : useSocietyChatStore;
+ const active = store.getState().activeSessionId;
+ const sessionId = agent.tier === "lead" ? active : agent.chatSessionId ?? active;
+ writeComposerDraft(store, sessionId, { text, choices: [] });
+ // A run transcript may cover the chat lane; the composer lives behind it.
+ useRoutineNavigation.getState().close();
+ window.requestAnimationFrame(() => window.requestAnimationFrame(focusComposer));
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/card/routines/format.ts b/dodaios/ui/web/frontend/src/components/society/card/routines/format.ts
new file mode 100644
index 0000000000..9175785c12
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/card/routines/format.ts
@@ -0,0 +1,58 @@
+/** Numbers and times on the routine panels, in the UI language. */
+
+const UNITS: [Intl.RelativeTimeFormatUnit, number][] = [
+ ["year", 365 * 86_400_000],
+ ["month", 30 * 86_400_000],
+ ["week", 7 * 86_400_000],
+ ["day", 86_400_000],
+ ["hour", 3_600_000],
+ ["minute", 60_000],
+];
+
+/** "in 3 hours", "2 days ago", "now". */
+export function relativeTime(atMs: number, nowMs: number, locale: string): string {
+ const diff = atMs - nowMs;
+ const format = new Intl.RelativeTimeFormat(locale, { numeric: "auto" });
+ for (const [unit, size] of UNITS) {
+ if (Math.abs(diff) >= size) return format.format(Math.round(diff / size), unit);
+ }
+ return format.format(0, "minute");
+}
+
+/** "Mon, 08:00" this week, otherwise "12 Oct, 08:00". */
+export function shortDateTime(atMs: number, nowMs: number, locale: string): string {
+ const at = new Date(atMs);
+ const sameDay = new Date(nowMs).toDateString() === at.toDateString();
+ const time = at.toLocaleTimeString(locale, { hour: "2-digit", minute: "2-digit" });
+ if (sameDay) return time;
+ const withinWeek = Math.abs(atMs - nowMs) < 6 * 86_400_000;
+ const day = withinWeek
+ ? at.toLocaleDateString(locale, { weekday: "short" })
+ : at.toLocaleDateString(locale, { day: "numeric", month: "short" });
+ return `${day}, ${time}`;
+}
+
+/** "850 ms", "42 s", "3 min 5 s", "1 h 4 min". */
+export function formatDuration(ms: number | null | undefined): string {
+ if (ms === null || ms === undefined || !Number.isFinite(ms) || ms < 0) return "";
+ if (ms < 1000) return `${Math.round(ms)} ms`;
+ const seconds = Math.round(ms / 1000);
+ if (seconds < 60) return `${seconds} s`;
+ const minutes = Math.floor(seconds / 60);
+ if (minutes < 60) return seconds % 60 ? `${minutes} min ${seconds % 60} s` : `${minutes} min`;
+ const hours = Math.floor(minutes / 60);
+ return minutes % 60 ? `${hours} h ${minutes % 60} min` : `${hours} h`;
+}
+
+/** "$0.04", "<$0.01", "$1.20"; "" when the cost is unknown. */
+export function formatCost(usd: number | null | undefined, locale: string): string {
+ if (usd === null || usd === undefined || !Number.isFinite(usd)) return "";
+ if (usd === 0) return new Intl.NumberFormat(locale, { style: "currency", currency: "USD" }).format(0);
+ if (usd < 0.01) return `<${new Intl.NumberFormat(locale, { style: "currency", currency: "USD" }).format(0.01)}`;
+ return new Intl.NumberFormat(locale, { style: "currency", currency: "USD", maximumFractionDigits: usd < 1 ? 3 : 2, minimumFractionDigits: 2 }).format(usd);
+}
+
+/** `{name}` placeholders. */
+export function fill(template: string, values: Record<string, string | number>): string {
+ return template.replace(/\{(\w+)\}/g, (match, name: string) => (name in values ? String(values[name]) : match));
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/card/routines/humanSchedule.test.ts b/dodaios/ui/web/frontend/src/components/society/card/routines/humanSchedule.test.ts
new file mode 100644
index 0000000000..40370055c8
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/card/routines/humanSchedule.test.ts
@@ -0,0 +1,146 @@
+import { describe, expect, test } from "vitest";
+import en from "@/i18n/locales/society/en.json";
+import de from "@/i18n/locales/society/de.json";
+import { humanSchedule, parseCronField, triggerFamily, zoneOffsetMinutes } from "./humanSchedule";
+
+function translator(bundle: unknown) {
+ return (key: string) => {
+ const value = key.split(".").reduce<unknown>((node, part) => (node as Record<string, unknown> | undefined)?.[part], bundle);
+ return typeof value === "string" ? value : key;
+ };
+}
+
+const t = translator(en);
+// A winter day: Berlin is UTC+1, New York UTC-5, Kolkata UTC+5:30.
+const WINTER = new Date(Date.UTC(2026, 0, 14, 12));
+const SUMMER = new Date(Date.UTC(2026, 6, 14, 12));
+const inBerlin = { t, locale: "en-GB", viewerZone: "Europe/Berlin", now: WINTER };
+const say = (trigger: unknown, options: Partial<typeof inBerlin> = {}) => humanSchedule(trigger, { ...inBerlin, ...options });
+
+describe("cron forms", () => {
+ test.each([
+ ["* * * * *", "Every minute"],
+ ["*/15 * * * *", "Every 15 minutes"],
+ ["0/10 * * * *", "Every 10 minutes"],
+ ["0 * * * *", "Every hour"],
+ ["30 * * * *", "Every hour at :30"],
+ ["0 */2 * * *", "Every 2 hours"],
+ ["15 */6 * * *", "Every 6 hours at :15"],
+ ["0 8 * * *", "Every day at 08:00"],
+ ["30 7 * * 1-5", "Weekdays at 07:30"],
+ ["0 10 * * 6,0", "Weekends at 10:00"],
+ ["0 10 * * SAT,SUN", "Weekends at 10:00"],
+ ["0 9 * * 1", "Every Monday at 09:00"],
+ ["0 9 * * 1,3,5", "Every Monday, Wednesday and Friday at 09:00"],
+ ["0 9 * * 7", "Every Sunday at 09:00"],
+ ["0 9 * * 5-7", "Every Friday, Saturday and Sunday at 09:00"],
+ ["0 9 * * 0-6", "Every day at 09:00"],
+ ["*/30 * * * 1-7", "Every 30 minutes"],
+ ["0 8,18 * * *", "Every day at 08:00 and 18:00"],
+ ["0 9 1 * *", "Monthly on day 1 at 09:00"],
+ ["0 9 1,15 * *", "Monthly on day 1 and 15 at 09:00"],
+ ["0 9 1 1 *", "Every year on 1 January at 09:00"],
+ ["0 9 * 6-8 *", "Every day at 09:00, only in June, July and August"],
+ ["*/30 * * * 1-5", "Every 30 minutes on weekdays"],
+ ["@daily", "Every day at 00:00"],
+ ["@hourly", "Every hour"],
+ ])("%s", (expression, sentence) => {
+ expect(say({ type: "cron", expression, timezone: "Europe/Berlin" })).toBe(sentence);
+ });
+
+ test("shapes without a sentence are shown raw, never guessed", () => {
+ expect(say({ type: "cron", expression: "*/5 9-17 * * 1-5", timezone: "Europe/Berlin" })).toBe("Custom schedule: */5 9-17 * * 1-5");
+ expect(say({ type: "cron", expression: "0 9 1 * 1", timezone: "Europe/Berlin" })).toBe("Custom schedule: 0 9 1 * 1");
+ expect(say({ type: "cron", expression: "not a cron", timezone: "Europe/Berlin" })).toBe("Custom schedule: not a cron");
+ expect(say({ type: "cron", expression: "99 * * * *", timezone: "Europe/Berlin" })).toBe("Custom schedule: 99 * * * *");
+ });
+
+ test("field parser expands ranges, lists and steps", () => {
+ expect(parseCronField("1-5", 0, 6)).toEqual({ any: false, values: [1, 2, 3, 4, 5] });
+ expect(parseCronField("*/20", 0, 59)).toEqual({ any: false, values: [0, 20, 40], step: 20 });
+ expect(parseCronField("0-59", 0, 59)).toEqual({ any: true });
+ expect(() => parseCronField("5-1", 0, 6)).toThrow();
+ });
+});
+
+describe("time zones", () => {
+ test("a clock time moves into the reader's zone and names the routine's own", () => {
+ expect(say({ type: "calendar", local_time: "08:00", timezone: "America/New_York" }))
+ .toBe("Every day at 14:00 · 08:00 in New York");
+ });
+
+ test("weekdays shift with a time that crosses midnight", () => {
+ // Monday 22:00 in New York is Tuesday 04:00 in Berlin.
+ expect(say({ type: "cron", expression: "0 22 * * 1", timezone: "America/New_York" }))
+ .toBe("Every Tuesday at 04:00 · 22:00 in New York");
+ });
+
+ test("daylight saving time is read on the day, not assumed", () => {
+ const options = { viewerZone: "UTC" };
+ expect(say({ type: "calendar", local_time: "08:00", timezone: "Europe/Berlin" }, { ...options, now: WINTER })).toBe("Every day at 07:00 · 08:00 in Berlin");
+ expect(say({ type: "calendar", local_time: "08:00", timezone: "Europe/Berlin" }, { ...options, now: SUMMER })).toBe("Every day at 06:00 · 08:00 in Berlin");
+ });
+
+ test("half-hour zones and month days that would change date keep the routine's zone", () => {
+ expect(say({ type: "calendar", local_time: "08:00", timezone: "Asia/Kolkata" })).toBe("Every day at 03:30 · 08:00 in Kolkata");
+ expect(say({ type: "calendar", local_time: "03:00", timezone: "Asia/Tokyo", month_days: [1] }))
+ .toBe("Monthly on day 1 at 03:00 (Tokyo time)");
+ });
+
+ test("the same zone reads without any suffix; an unknown zone is named", () => {
+ expect(say({ type: "calendar", local_time: "08:00", timezone: "Europe/Berlin", weekdays: [0, 2] })).toBe("Every Monday and Wednesday at 08:00");
+ expect(say({ type: "calendar", local_time: "08:00", timezone: "Mars/Olympus" })).toBe("Every day at 08:00 (Olympus time)");
+ expect(zoneOffsetMinutes("Mars/Olympus", WINTER)).toBeNull();
+ expect(zoneOffsetMinutes("Asia/Kolkata", WINTER)).toBe(330);
+ });
+});
+
+describe("other triggers", () => {
+ test.each([
+ [{ type: "every", interval_seconds: 60 }, "Every minute"],
+ [{ type: "every", interval_seconds: 3600 }, "Every hour"],
+ [{ kind: "every", interval_seconds: 18000 }, "Every 5 hours"],
+ [{ type: "every", interval_seconds: 86400 }, "Every day"],
+ [{ type: "every", interval_seconds: 172800 }, "Every 2 days"],
+ [{ type: "every", interval_seconds: 1800 }, "Every 30 minutes"],
+ [{ type: "every", interval_seconds: 45 }, "Every 45 seconds"],
+ [{ type: "after_delay", delay_seconds: 7200 }, "Once, in 2 hours"],
+ [{ type: "on_event", event_name: "MissionCompleted" }, "When MissionCompleted happens"],
+ [{ type: "webhook", provider: "generic" }, "When its webhook is called"],
+ [{ type: "webhook", provider: "github" }, "On Github events"],
+ [{ type: "event_hook", event_name: "crm.customer.created" }, "On the integration event crm.customer.created"],
+ [{ type: "source", source: { kind: "form" } }, "When you start it"],
+ [{ type: "source", source: { kind: "file", path: "C:/inbox" } }, "When files change in C:/inbox"],
+ ])("%j", (trigger, sentence) => {
+ expect(say(trigger)).toBe(sentence);
+ });
+
+ test("an anchored daily interval reads its clock time in the reader's zone", () => {
+ expect(say({ type: "every", interval_seconds: 86400, start_at: "2026-01-10T07:00:00Z" })).toBe("Every day at 08:00");
+ });
+
+ test("a one-time run names its moment", () => {
+ expect(say({ type: "at_time", iso_timestamp: "2026-01-20T09:00:00Z" })).toMatch(/^Once, /);
+ });
+
+ test("nothing stored reads as nothing; unknown kinds name themselves", () => {
+ expect(say(null)).toBe("");
+ expect(say({ type: "teleport" })).toBe("Schedule: teleport");
+ });
+
+ test("families pick the row icon", () => {
+ expect(triggerFamily({ type: "cron" })).toBe("clock");
+ expect(triggerFamily({ kind: "every" })).toBe("interval");
+ expect(triggerFamily({ type: "webhook" })).toBe("webhook");
+ expect(triggerFamily({ type: "source", source: { kind: "form" } })).toBe("manual");
+ expect(triggerFamily({ type: "source", source: { kind: "kafka" } })).toBe("source");
+ expect(triggerFamily(undefined)).toBe("unknown");
+ });
+});
+
+test("other languages read naturally, with their own weekday names", () => {
+ const options = { ...inBerlin, t: translator(de), locale: "de-DE" };
+ expect(humanSchedule({ type: "cron", expression: "30 7 * * 1-5", timezone: "Europe/Berlin" }, options)).toBe("Werktags um 07:30");
+ expect(humanSchedule({ type: "cron", expression: "0 9 * * 1,3", timezone: "Europe/Berlin" }, options)).toBe("Jeden Montag und Mittwoch um 09:00");
+ expect(humanSchedule({ type: "every", interval_seconds: 900 }, options)).toBe("Alle 15 Minuten");
+});
diff --git a/dodaios/ui/web/frontend/src/components/society/card/routines/humanSchedule.ts b/dodaios/ui/web/frontend/src/components/society/card/routines/humanSchedule.ts
new file mode 100644
index 0000000000..e334af66dd
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/card/routines/humanSchedule.ts
@@ -0,0 +1,356 @@
+/**
+ * A routine's trigger as one plain-language sentence, in the reader's time.
+ *
+ * The scheduler stores a raw TaskSpec trigger (`dodaios/tasks/schema.py`):
+ * `every` / `calendar` / `cron` / `at_time` / `after_delay` / `on_event`,
+ * webhooks, integration hooks and sources. Clock times are converted from
+ * the routine's own zone into the reader's zone, weekdays shift with them
+ * when the conversion crosses midnight, and the routine's zone is named
+ * when it differs. A cron line the sentence builder does not understand is
+ * shown raw rather than guessed.
+ *
+ * `t` is the locale function; all words come from `society.agent_routines.schedule.*`,
+ * weekday and month names from `Intl`, so every language reads naturally.
+ */
+
+export type Translate = (key: string) => string;
+
+export interface HumanScheduleOptions {
+ t: Translate;
+ /** BCP 47 locale for weekday/month names and clock times. */
+ locale?: string;
+ /** The reader's IANA zone (default: the browser's). */
+ viewerZone?: string;
+ /** "Now", for the zone offsets (DST) — tests pin it. */
+ now?: Date;
+}
+
+const KEY = "society.agent_routines.schedule.";
+const WEEKDAYS_ONLY = [0, 1, 2, 3, 4];
+const WEEKEND_ONLY = [5, 6];
+
+function fill(template: string, values: Record<string, string | number>): string {
+ return template.replace(/\{(\w+)\}/g, (match, name: string) => (name in values ? String(values[name]) : match));
+}
+
+function say(t: Translate, key: string, values: Record<string, string | number> = {}): string {
+ return fill(t(KEY + key), values);
+}
+
+function list(items: string[], locale: string): string {
+ if (items.length <= 1) return items[0] ?? "";
+ try {
+ return new Intl.ListFormat(locale, { style: "long", type: "conjunction" }).format(items);
+ } catch {
+ return items.join(", ");
+ }
+}
+
+function sameSet(a: number[], b: number[]): boolean {
+ return a.length === b.length && a.every((value) => b.includes(value));
+}
+
+/** Minutes east of UTC that `zone` is at `at`; null for an unknown zone. */
+export function zoneOffsetMinutes(zone: string, at: Date): number | null {
+ try {
+ const parts = new Intl.DateTimeFormat("en-US", {
+ timeZone: zone, hourCycle: "h23", year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit",
+ }).formatToParts(at);
+ const get = (type: string) => Number(parts.find((part) => part.type === type)?.value ?? "0");
+ const wall = Date.UTC(get("year"), get("month") - 1, get("day"), get("hour") % 24, get("minute"));
+ const instant = Math.floor(at.getTime() / 60_000) * 60_000;
+ return Math.round((wall - instant) / 60_000);
+ } catch {
+ return null;
+ }
+}
+
+function viewerZoneOf(options: HumanScheduleOptions): string {
+ if (options.viewerZone) return options.viewerZone;
+ try { return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"; } catch { return "UTC"; }
+}
+
+function clock(minutes: number, locale: string): string {
+ const at = new Date(Date.UTC(2024, 0, 1, Math.floor(minutes / 60), minutes % 60));
+ return at.toLocaleTimeString(locale, { hour: "2-digit", minute: "2-digit", timeZone: "UTC" });
+}
+
+function weekdayName(day: number, locale: string): string {
+ // 2024-01-01 was a Monday: day 0 = Monday, as the calendar trigger stores it.
+ return new Date(Date.UTC(2024, 0, 1 + day)).toLocaleDateString(locale, { weekday: "long", timeZone: "UTC" });
+}
+
+function monthName(month: number, locale: string): string {
+ return new Date(Date.UTC(2024, month - 1, 1)).toLocaleDateString(locale, { month: "long", timeZone: "UTC" });
+}
+
+function dayOfYear(month: number, day: number, locale: string): string {
+ return new Date(Date.UTC(2024, month - 1, day)).toLocaleDateString(locale, { month: "long", day: "numeric", timeZone: "UTC" });
+}
+
+/** A short city-ish label for a zone: "Europe/Berlin" → "Berlin". */
+export function zoneLabel(zone: string): string {
+ const tail = zone.split("/").pop() ?? zone;
+ return tail.replace(/_/g, " ");
+}
+
+interface Wall {
+ /** Minutes after midnight in the reader's zone. */
+ times: number[];
+ /** Weekdays (0 = Monday) in the reader's zone, or [] for every day. */
+ weekdays: number[];
+ monthDays: number[];
+ months: number[];
+ /** The routine's own zone, when it is not the reader's and the sentence keeps it. */
+ keptZone: string;
+ /** The routine's own clock times, when they were converted. */
+ originalTimes: number[];
+ originalZone: string;
+}
+
+/**
+ * Move clock times (and weekdays with them) from `zone` into the reader's
+ * zone. Month days do not move across midnight cleanly, so a converted
+ * time that changes the date of a month-day rule keeps the routine's zone.
+ */
+function toViewer(times: number[], weekdays: number[], monthDays: number[], months: number[], zone: string, options: HumanScheduleOptions): Wall {
+ const viewer = viewerZoneOf(options);
+ const base: Wall = { times, weekdays, monthDays, months, keptZone: "", originalTimes: [], originalZone: "" };
+ if (!zone || zone === viewer) return base;
+ const now = options.now ?? new Date();
+ const from = zoneOffsetMinutes(zone, now);
+ const to = zoneOffsetMinutes(viewer, now);
+ if (from === null || to === null) return { ...base, keptZone: zone };
+ const delta = to - from;
+ if (delta === 0) return base;
+ const shifted = times.map((minutes) => minutes + delta);
+ const dayShifts = new Set(shifted.map((minutes) => Math.floor(minutes / 1440)));
+ if (dayShifts.size > 1 || ((monthDays.length || months.length) && !dayShifts.has(0))) {
+ return { ...base, keptZone: zone };
+ }
+ const shift = [...dayShifts][0] ?? 0;
+ return {
+ times: shifted.map((minutes) => ((minutes % 1440) + 1440) % 1440),
+ weekdays: weekdays.map((day) => (((day + shift) % 7) + 7) % 7).sort((a, b) => a - b),
+ monthDays, months, keptZone: "", originalTimes: times, originalZone: zone,
+ };
+}
+
+/** The sentence for clock times on a day pattern, in the reader's zone. */
+function wallSentence(wall: Wall, options: HumanScheduleOptions): string {
+ const { t } = options;
+ const locale = options.locale ?? "en";
+ const at = list([...wall.times].sort((a, b) => a - b).map((minutes) => clock(minutes, locale)), locale);
+ let sentence: string;
+ const days = [...new Set(wall.weekdays)].sort((a, b) => a - b);
+ if (wall.monthDays.length && wall.months.length === 1 && !days.length) {
+ sentence = say(t, "yearly_at", { date: list(wall.monthDays.map((day) => dayOfYear(wall.months[0], day, locale)), locale), time: at });
+ } else if (wall.monthDays.length) {
+ sentence = say(t, "monthly_at", { days: list(wall.monthDays.map(String), locale), time: at });
+ } else if (!days.length || days.length === 7) {
+ sentence = say(t, "daily_at", { time: at });
+ } else if (sameSet(days, WEEKDAYS_ONLY)) {
+ sentence = say(t, "weekdays_at", { time: at });
+ } else if (sameSet(days, WEEKEND_ONLY)) {
+ sentence = say(t, "weekends_at", { time: at });
+ } else {
+ sentence = say(t, "days_at", { days: list(days.map((day) => weekdayName(day, locale)), locale), time: at });
+ }
+ if (wall.months.length && !(wall.monthDays.length && wall.months.length === 1 && !days.length)) {
+ sentence = say(t, "in_months", { schedule: sentence, months: list(wall.months.map((month) => monthName(month, locale)), locale) });
+ }
+ if (wall.keptZone) return say(t, "zone_time", { schedule: sentence, zone: zoneLabel(wall.keptZone) });
+ if (wall.originalZone && wall.originalTimes.length) {
+ const original = list(wall.originalTimes.map((minutes) => clock(minutes, locale)), locale);
+ return say(t, "converted", { schedule: sentence, time: original, zone: zoneLabel(wall.originalZone) });
+ }
+ return sentence;
+}
+
+// ------------------------------------------------------------------- cron
+
+type CronField = { any: true } | { any: false; values: number[]; step?: number };
+
+const MONTH_NAMES = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
+const DAY_NAMES = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
+const ALIASES: Record<string, string> = {
+ "@yearly": "0 0 1 1 *", "@annually": "0 0 1 1 *", "@monthly": "0 0 1 * *",
+ "@weekly": "0 0 * * 0", "@daily": "0 0 * * *", "@midnight": "0 0 * * *", "@hourly": "0 * * * *",
+};
+
+function cronNumber(token: string, names?: string[], offset = 0): number {
+ const lower = token.toLowerCase();
+ const named = names?.indexOf(lower) ?? -1;
+ if (named >= 0) return named + offset;
+ if (!/^\d+$/.test(token)) throw new Error(`bad cron token ${token}`);
+ return Number(token);
+}
+
+/** One cron field as "any" or the explicit values it allows. */
+export function parseCronField(text: string, min: number, max: number, names?: string[], nameOffset = 0): CronField {
+ if (text === "*" || text === "?") return { any: true };
+ const values = new Set<number>();
+ let step: number | undefined;
+ for (const part of text.split(",")) {
+ const [range, stepText] = part.split("/");
+ const by = stepText === undefined ? 1 : Number(stepText);
+ if (!Number.isInteger(by) || by < 1) throw new Error("bad cron step");
+ let lo: number; let hi: number;
+ if (range === "*" || range === "?") { lo = min; hi = max; if (stepText !== undefined && text.split(",").length === 1) step = by; }
+ else if (range.includes("-")) { const [a, b] = range.split("-"); lo = cronNumber(a, names, nameOffset); hi = cronNumber(b, names, nameOffset); }
+ else {
+ lo = cronNumber(range, names, nameOffset); hi = stepText !== undefined ? max : lo;
+ if (stepText !== undefined && lo === min && text.split(",").length === 1) step = by;
+ }
+ if (lo < min || hi > max || lo > hi) throw new Error("cron value out of range");
+ for (let value = lo; value <= hi; value += by) values.add(value);
+ }
+ const sorted = [...values].sort((a, b) => a - b);
+ if (step === undefined && sorted.length === max - min + 1) return { any: true };
+ return { any: false, values: sorted, ...(step !== undefined ? { step } : {}) };
+}
+
+function cronSentence(expression: string, zone: string, options: HumanScheduleOptions): string {
+ const { t } = options;
+ const fields = (ALIASES[expression.trim().toLowerCase()] ?? expression).trim().split(/\s+/);
+ if (fields.length !== 5) throw new Error("not a five-field cron line");
+ const minute = parseCronField(fields[0], 0, 59);
+ const hour = parseCronField(fields[1], 0, 23);
+ const dom = parseCronField(fields[2], 1, 31);
+ const month = parseCronField(fields[3], 1, 12, MONTH_NAMES, 1);
+ // Cron counts Sunday as 0 (and 7); the calendar trigger counts Monday as 0.
+ // Parsed over 0–7 so ranges like "1-7" stay valid; 7 folds onto Sunday.
+ const dowRaw = parseCronField(fields[4], 0, 7, DAY_NAMES);
+ const dowSet = dowRaw.any ? [] : [...new Set(dowRaw.values.map((day) => (day + 6) % 7))].sort((a, b) => a - b);
+ const dow = dowSet.length === 7 ? [] : dowSet;
+ const months = month.any ? [] : month.values;
+ const daysSuffix = (sentence: string) => {
+ if (!dow.length) return sentence;
+ const locale = options.locale ?? "en";
+ const days = sameSet(dow, WEEKDAYS_ONLY) ? say(t, "on_weekdays") : sameSet(dow, WEEKEND_ONLY) ? say(t, "on_weekends")
+ : list(dow.map((day) => weekdayName(day, locale)), locale);
+ return say(t, "with_days", { schedule: sentence, days });
+ };
+ const restOpen = dom.any && month.any;
+ if (minute.any && hour.any && restOpen) return daysSuffix(say(t, "every_minute"));
+ if (!minute.any && minute.step && minute.values[0] === 0 && hour.any && restOpen) {
+ return daysSuffix(say(t, "every_minutes", { n: minute.step }));
+ }
+ if (!minute.any && minute.values.length === 1 && restOpen && (hour.any || (hour.step && hour.values[0] === 0))) {
+ const at = minute.values[0];
+ const step = hour.any ? 1 : hour.step!;
+ const sentence = step === 1
+ ? (at === 0 ? say(t, "every_hour") : say(t, "every_hour_at", { minute: String(at).padStart(2, "0") }))
+ : (at === 0 ? say(t, "every_hours", { n: step }) : say(t, "every_hours_at", { n: step, minute: String(at).padStart(2, "0") }));
+ return daysSuffix(sentence);
+ }
+ if (!minute.any && !hour.any && minute.values.length * hour.values.length <= 6 && (dom.any || !dow.length)) {
+ const times = hour.values.flatMap((h) => minute.values.map((m) => h * 60 + m));
+ return wallSentence(toViewer(times, dow, dom.any ? [] : dom.values, months, zone, options), options);
+ }
+ throw new Error("cron shape without a sentence");
+}
+
+// ------------------------------------------------------------------ entry
+
+function durationWords(seconds: number, t: Translate): string {
+ if (seconds >= 86_400 && seconds % 86_400 === 0) return say(t, "n_days", { n: seconds / 86_400 });
+ if (seconds >= 3_600 && seconds % 3_600 === 0) return say(t, "n_hours", { n: seconds / 3_600 });
+ if (seconds >= 60 && seconds % 60 === 0) return say(t, "n_minutes", { n: seconds / 60 });
+ return say(t, "n_seconds", { n: Math.round(seconds) });
+}
+
+function parseClock(text: unknown): number | null {
+ const match = /^(\d{1,2}):(\d{2})$/.exec(String(text ?? ""));
+ if (!match) return null;
+ const hours = Number(match[1]); const minutes = Number(match[2]);
+ return hours < 24 && minutes < 60 ? hours * 60 + minutes : null;
+}
+
+function numbers(value: unknown): number[] {
+ return Array.isArray(value) ? value.map(Number).filter((n) => Number.isFinite(n)) : [];
+}
+
+/**
+ * The plain-language sentence for a stored trigger, or "" when there is none.
+ * Never throws: an unreadable shape falls back to the raw text.
+ */
+export function humanSchedule(trigger: unknown, options: HumanScheduleOptions): string {
+ if (!trigger || typeof trigger !== "object") return "";
+ const raw = trigger as Record<string, unknown>;
+ const { t } = options;
+ const locale = options.locale ?? "en";
+ const kind = String(raw.type ?? raw.kind ?? "");
+ try {
+ if (kind === "cron") {
+ const expression = String(raw.expression ?? "").trim();
+ try {
+ return cronSentence(expression, String(raw.timezone ?? ""), options);
+ } catch {
+ return say(t, "custom_cron", { expression });
+ }
+ }
+ if (kind === "calendar") {
+ const time = parseClock(raw.local_time);
+ if (time === null) return say(t, "custom", { kind });
+ return wallSentence(toViewer([time], numbers(raw.weekdays), numbers(raw.month_days), numbers(raw.months), String(raw.timezone ?? ""), options), options);
+ }
+ if (kind === "every") {
+ const seconds = Number(raw.interval_seconds ?? 0);
+ if (!(seconds > 0)) return say(t, "custom", { kind });
+ const start = typeof raw.start_at === "string" ? new Date(raw.start_at) : null;
+ if (start && !Number.isNaN(start.getTime()) && seconds % 86_400 === 0) {
+ const at = start.toLocaleTimeString(locale, { hour: "2-digit", minute: "2-digit", ...(options.viewerZone ? { timeZone: options.viewerZone } : {}) });
+ return seconds === 86_400 ? say(t, "daily_at", { time: at }) : say(t, "every_n_days_at", { n: seconds / 86_400, time: at });
+ }
+ if (seconds === 60) return say(t, "every_minute");
+ if (seconds === 3_600) return say(t, "every_hour");
+ if (seconds === 86_400) return say(t, "every_day");
+ if (seconds === 604_800) return say(t, "every_week");
+ return say(t, "every_duration", { duration: durationWords(seconds, t) });
+ }
+ if (kind === "at_time") {
+ const at = new Date(String(raw.iso_timestamp ?? ""));
+ if (Number.isNaN(at.getTime())) return say(t, "custom", { kind });
+ const when = at.toLocaleString(locale, { weekday: "short", day: "numeric", month: "short", hour: "2-digit", minute: "2-digit", ...(options.viewerZone ? { timeZone: options.viewerZone } : {}) });
+ return say(t, "once_at", { when });
+ }
+ if (kind === "after_delay") return say(t, "once_in", { duration: durationWords(Number(raw.delay_seconds ?? 0), t) });
+ if (kind === "on_event") return say(t, "on_event", { event: String(raw.event_name ?? "") });
+ if (kind === "webhook") {
+ const provider = String(raw.provider ?? "generic");
+ return provider && provider !== "generic" ? say(t, "on_provider", { provider: provider.charAt(0).toUpperCase() + provider.slice(1) }) : say(t, "on_webhook");
+ }
+ if (kind === "event_hook") return say(t, "on_integration", { event: String(raw.event_name ?? "") });
+ if (kind === "source") {
+ const source = (raw.source ?? {}) as { kind?: string; topic?: string; path?: string };
+ const sourceKind = String(source.kind ?? "");
+ if (sourceKind === "manual" || sourceKind === "form" || sourceKind === "chat") return say(t, "on_demand");
+ if (sourceKind === "file") return say(t, "on_file", { path: String(source.path ?? "") });
+ const label = t(`society.triggers.kinds.${sourceKind}`);
+ return say(t, "on_source", { source: label.startsWith("society.") ? sourceKind : label });
+ }
+ } catch {
+ // Fall through to the raw kind below.
+ }
+ return kind ? say(t, "custom", { kind }) : "";
+}
+
+/** The trigger family, for the row icon and the "test run" rules. */
+export type TriggerFamily = "clock" | "interval" | "once" | "webhook" | "event" | "source" | "manual" | "unknown";
+
+export function triggerFamily(trigger: unknown): TriggerFamily {
+ if (!trigger || typeof trigger !== "object") return "unknown";
+ const raw = trigger as Record<string, unknown>;
+ const kind = String(raw.type ?? raw.kind ?? "");
+ if (kind === "calendar" || kind === "cron") return "clock";
+ if (kind === "every") return "interval";
+ if (kind === "at_time" || kind === "after_delay") return "once";
+ if (kind === "webhook") return "webhook";
+ if (kind === "on_event" || kind === "event_hook") return "event";
+ if (kind === "source") {
+ const sourceKind = String((raw.source as { kind?: string } | undefined)?.kind ?? "");
+ return ["manual", "form", "chat"].includes(sourceKind) ? "manual" : "source";
+ }
+ return "unknown";
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/card/routines/routines.test.tsx b/dodaios/ui/web/frontend/src/components/society/card/routines/routines.test.tsx
new file mode 100644
index 0000000000..0d81739aef
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/card/routines/routines.test.tsx
@@ -0,0 +1,182 @@
+/**
+ * Routines as tasks: the list's last result and cost, the away-parking note,
+ * "set up / edit in chat", run history with duration and cost, and the
+ * webhook card's masked key and header line.
+ */
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import type { ReactNode } from "react";
+import en from "@/i18n/locales/society/en.json";
+import type { TaskStep } from "@/lib/tasksApi";
+
+const seed = vi.fn(async (_agent: unknown, _text: string) => {});
+vi.mock("./editThroughChat", () => ({ seedAgentComposer: (agent: unknown, text: string) => seed(agent, text) }));
+vi.mock("@/components/agentchat/AgentTimeline", () => ({ AgentTimeline: () => null }));
+vi.mock("@/i18n", () => ({
+ useLocaleChunk: () => true,
+ useUiLanguage: () => "en",
+ useI18nStore: { getState: () => ({ ui: "en" }) },
+ useT: () => (key: string) => key.split(".").reduce<unknown>((value, part) => (value as Record<string, unknown>)?.[part], en) as string ?? key,
+}));
+
+import { AgentRoutinesList } from "../AgentRoutinesList";
+import { AgentRoutineDetail } from "../AgentRoutineDetail";
+import { WebhookConnection } from "../WebhookConnection";
+import { mergeRunDetails, routineRuns } from "./runs";
+import { resetSeenThrottle, type RoutineRunRow } from "./routinesApi";
+import type { LiveRoutine } from "../../cardData";
+
+const json = (body: unknown, status = 200) => ({ ok: status < 400, status, json: async () => body }) as Response;
+
+function wrap(node: ReactNode) {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity, refetchInterval: false } } });
+ return render(<QueryClientProvider client={client}>{node}</QueryClientProvider>);
+}
+
+function runRow(overrides: Partial<RoutineRunRow>): RoutineRunRow {
+ return {
+ id: "r1:1", task_id: "r1", status: "completed", origin: "automatic", started_ms: Date.now() - 3_600_000,
+ finished_ms: Date.now() - 3_590_000, duration_ms: 10_000, cost_usd: 0.042, billed_via_key: false,
+ provider: "claude-cli", model: "sonnet", session_id: "", summary: "Three new invoices", error: "",
+ skip_code: "", skip_provider: "", ...overrides,
+ };
+}
+
+let fetchMock: ReturnType<typeof vi.fn>;
+beforeEach(() => { resetSeenThrottle(); seed.mockClear(); });
+afterEach(() => { cleanup(); vi.unstubAllGlobals(); });
+
+describe("routine list", () => {
+ function mountList(activity: unknown) {
+ fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
+ if (url.endsWith("/routines-activity")) return json(activity);
+ if (url.endsWith("/routines-parking")) return json({ parking: { banner: false } });
+ if (url.endsWith("/routine-parking")) return json({ days: 7 });
+ if (url.endsWith("/routines") && (init?.method ?? "GET") === "GET") return json({ routines: [
+ { id: "r1", title: "[agent:Mail] Inbox digest", state: "scheduled", trigger: { type: "cron", expression: "30 7 * * 1-5", timezone: Intl.DateTimeFormat().resolvedOptions().timeZone }, due_at_ns: (Date.now() + 3 * 3_600_000) * 1e6 },
+ { id: "r2", title: "[agent:Mail] Weekly cleanup", state: "paused", trigger: { type: "every", interval_seconds: 604800 } },
+ ] });
+ return json({});
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ return wrap(<AgentRoutinesList agentId="mail" />);
+ }
+
+ test("rows read as sentences with the last result and its cost, and looking is recorded", async () => {
+ mountList({ last_runs: { r1: runRow({}), r2: runRow({ id: "r2:9", task_id: "r2", status: "failed", error: "RuntimeError: seat offline", cost_usd: null }) }, parking: null });
+ const row = (await screen.findByRole("button", { name: "Inbox digest" })).closest("li")!;
+ expect(row.textContent).toMatch(/Weekdays at 07:30( AM)?/);
+ await waitFor(() => expect(row.textContent).toContain("$0.042"));
+ expect(row.textContent).toMatch(/next_run: in 3 hours/);
+ const paused = screen.getByRole("button", { name: "Weekly cleanup" }).closest("li")!;
+ expect(paused.textContent).toContain("Every week");
+ expect(paused.textContent).toContain("state.paused");
+ expect(paused.textContent).toContain("RuntimeError: seat offline");
+ expect(fetchMock.mock.calls.some(([url, init]) => String(url).endsWith("/routines-seen") && init?.method === "POST")).toBe(true);
+ });
+
+ test("a parked agent shows the note once, and Resume answers it", async () => {
+ mountList({ last_runs: {}, parking: { enabled: true, days: 7, banner: true, parked_ids: ["r2"], parked_ms: 1, parked_days: 7, unread: 5, never_ask: false } });
+ const banner = await screen.findByTestId("routine-parking-banner");
+ expect(banner.textContent).toContain("This routine made 5 results in 7 days");
+ expect(screen.getByRole("button", { name: "Weekly cleanup" }).closest("li")!.textContent).toContain("Paused while you were away");
+ fireEvent.click(within(banner).getByText("Resume"));
+ await waitFor(() => {
+ const call = fetchMock.mock.calls.find(([url]) => String(url).endsWith("/routines-parking"));
+ expect(JSON.parse(String(call?.[1]?.body))).toEqual({ choice: "keep_running" });
+ });
+ });
+
+ test("set up in chat seeds the agent's composer instead of a form", async () => {
+ mountList({ last_runs: {}, parking: null });
+ fireEvent.click(await screen.findByTestId("agent-routines-chat"));
+ await waitFor(() => expect(seed).toHaveBeenCalledWith({ tier: "specialist", chatSessionId: "society:mail" }, "Set up a routine for me: "));
+ });
+
+ test("the row's test run starts it right away", async () => {
+ mountList({ last_runs: {}, parking: null });
+ await screen.findByRole("button", { name: "Inbox digest" });
+ fireEvent.click(screen.getAllByRole("button", { name: "Test run now" })[0]);
+ await waitFor(() => expect(fetchMock.mock.calls.some(([url, init]) => url === "/api/tasks/r1/run" && init?.method === "POST")).toBe(true));
+ });
+});
+
+describe("routine detail", () => {
+ const steps = (events: Record<string, unknown>[]) => events.map((payload, seq) => ({ seq, kind: "log", timestamp_ns: (Date.now() - (events.length - seq) * 60_000) * 1e6, payload } as TaskStep));
+
+ function mountDetail(taskSteps: TaskStep[], runs: RoutineRunRow[] = []) {
+ const trigger = { type: "calendar", local_time: "08:00", timezone: Intl.DateTimeFormat().resolvedOptions().timeZone, weekdays: [0, 1, 2, 3, 4] };
+ const routine: LiveRoutine = { id: "r1", title: "[agent:Mail] Inbox", prompt: "Read mail.", trigger, schedule: "", state: "scheduled", dueMs: null, lastRunMs: null };
+ fetchMock = vi.fn(async (url: string) => {
+ if (url.includes("/runs")) return json({ runs });
+ if (url === "/api/tasks/r1") return json({ ...routine, trigger_type: "calendar", trigger, state: "scheduled", spec: { action: { kind: "agent", prompt: "Identity\nRoutine:\nRead mail." } }, steps: taskSteps });
+ return json({});
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ return wrap(<AgentRoutineDetail agentId="mail" routine={routine} onClose={() => {}} />);
+ }
+
+ test("the header says what triggers it; edit in chat names the routine and its schedule", async () => {
+ mountDetail([]);
+ const sentence = (await screen.findByTestId("routine-schedule-sentence")).textContent ?? "";
+ expect(sentence).toMatch(/^Weekdays at 08:00( AM)?$/);
+ fireEvent.click(screen.getByText("Edit in chat"));
+ await waitFor(() => expect(seed).toHaveBeenCalledWith(
+ { tier: "specialist", chatSessionId: "society:mail" }, `Change my routine "Inbox" (${sentence}): `,
+ ));
+ expect(await screen.findByText("No runs yet. Use Test run to try it now.")).toBeTruthy();
+ });
+
+ test("runs show manual starts, duration and cost; a failed latest run is explained", async () => {
+ const taskSteps = steps([
+ { event: "run_now" }, { event: "run_started" }, { event: "routine_summary", duration_ms: 42_000, cost_usd: 0.31, billed_via_key: true },
+ { event: "agent_result", text: "**Done**: sorted 12 mails" }, { event: "run_completed" },
+ { event: "run_started" }, { event: "error", message: "RuntimeError: quota exhausted" },
+ ]);
+ mountDetail(taskSteps, [runRow({ id: "r1:0", cost_usd: 9 })]);
+ const manual = await screen.findByTestId("routine-run-r1:1");
+ expect(manual.textContent).toContain("Manual");
+ expect(manual.textContent).toContain("42 s");
+ expect(manual.textContent).toContain("$0.31");
+ expect(manual.textContent).toContain("Done: sorted 12 mails");
+ const failure = screen.getByTestId("routine-last-failure");
+ expect(failure.textContent).toContain("RuntimeError: quota exhausted");
+ });
+});
+
+describe("run model", () => {
+ test("the route fills cost and summary the steps do not know", () => {
+ const runs = routineRuns("r1", [
+ { seq: 1, kind: "log", timestamp_ns: 1e12, payload: { event: "run_started" } },
+ { seq: 2, kind: "log", timestamp_ns: 2e12, payload: { event: "run_completed", duration_ms: 1500 } },
+ ] as TaskStep[]);
+ const merged = mergeRunDetails(runs, [runRow({ id: "r1:1", cost_usd: 0.5, summary: "From the chat", duration_ms: 99 })]);
+ expect(merged[0]).toMatchObject({ costUsd: 0.5, summary: "From the chat", durationMs: 1500, origin: "automatic" });
+ });
+
+ test("an away-parked skip reads in plain words", async () => {
+ const { runReason } = await import("./RunHistory");
+ const t = (key: string) => key;
+ expect(runReason(t, { id: "x", taskId: "r1", timestamp: 0, status: "skipped", text: "", origin: "automatic", skipCode: "away_parked" }))
+ .toBe("society.agent_routines.runs.skip_away");
+ });
+});
+
+describe("webhook card", () => {
+ test("the key and header stay masked until revealed, and copy takes the full line", async () => {
+ const writeText = vi.fn(async () => {});
+ vi.stubGlobal("navigator", { ...navigator, clipboard: { writeText } });
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({ path: "/api/tasks/hooks/r1", token: "tok-123" }), { status: 200 })));
+ render(<WebhookConnection taskId="r1" />);
+ fireEvent.click(await screen.findByText("Connect webhook"));
+ const key = await screen.findByDisplayValue("tok-123");
+ expect(key.getAttribute("type")).toBe("password");
+ expect(screen.getByTestId("webhook-header-line").textContent).not.toContain("tok-123");
+ fireEvent.click(screen.getByRole("button", { name: "Copy header line" }));
+ await waitFor(() => expect(writeText).toHaveBeenCalledWith("Authorization: Bearer tok-123"));
+ fireEvent.click(screen.getByRole("button", { name: "Show key" }));
+ expect(key.getAttribute("type")).toBe("text");
+ expect(screen.getByTestId("webhook-header-line").textContent).toBe("Authorization: Bearer tok-123");
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/components/society/card/routines/routinesApi.ts b/dodaios/ui/web/frontend/src/components/society/card/routines/routinesApi.ts
new file mode 100644
index 0000000000..aca485f8e9
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/card/routines/routinesApi.ts
@@ -0,0 +1,152 @@
+/**
+ * Run history, newest runs and away-parking for an agent's routines.
+ *
+ * Every hook here is enrichment: a backend without these routes (an older
+ * build, a test) answers with an error and the panels fall back to what the
+ * routine list already shows. Nothing retries loudly.
+ */
+import { useQueries, useQuery, useQueryClient } from "@tanstack/react-query";
+
+export interface RoutineRunRow {
+ id: string;
+ task_id: string;
+ status: string;
+ origin: "manual" | "automatic" | string;
+ started_ms: number | null;
+ finished_ms: number | null;
+ duration_ms: number | null;
+ cost_usd: number | null;
+ billed_via_key: boolean | null;
+ provider: string;
+ model: string;
+ session_id: string;
+ summary: string;
+ error: string;
+ skip_code: string;
+ skip_provider: string;
+}
+
+export interface ParkingView {
+ enabled: boolean;
+ days: number;
+ banner: boolean;
+ parked_ids: string[];
+ parked_ms: number;
+ parked_days: number;
+ unread: number;
+ never_ask: boolean;
+}
+
+export interface RoutineActivity {
+ lastRuns: Record<string, RoutineRunRow | null>;
+ parking: ParkingView | null;
+}
+
+export type ParkingChoice = "keep_running" | "keep_paused" | "never_ask" | "ask_again";
+
+const live = import.meta.env.MODE !== "test";
+const base = (agentId: string) => `/api/society/agents/${encodeURIComponent(agentId)}`;
+
+async function readJson<T>(response: Response): Promise<T> {
+ const body = await response.json().catch(() => null) as (T & { detail?: unknown }) | null;
+ if (!response.ok) throw new Error(typeof body?.detail === "string" ? body.detail : `HTTP ${response.status}`);
+ return body as T;
+}
+
+export const activityKey = (agentId: string) => ["society", "routine-activity", agentId] as const;
+export const runsKey = (agentId: string, taskId: string) => ["society", "routine-runs", agentId, taskId] as const;
+
+/** Each routine's newest run plus the agent's parking banner. */
+export function useRoutineActivity(agentId: string | null) {
+ return useQuery({
+ queryKey: activityKey(agentId ?? ""),
+ enabled: Boolean(agentId),
+ retry: false,
+ staleTime: 5_000,
+ refetchInterval: live ? 15_000 : false,
+ queryFn: async (): Promise<RoutineActivity> => {
+ const body = await readJson<{ last_runs?: Record<string, RoutineRunRow | null>; parking?: ParkingView }>(
+ await fetch(`${base(agentId ?? "")}/routines-activity`),
+ );
+ return { lastRuns: body.last_runs ?? {}, parking: body.parking ?? null };
+ },
+ });
+}
+
+/** The runs of every member task of one routine, merged newest first. */
+export function useRoutineRuns(agentId: string, taskIds: string[], fast = false) {
+ const queries = useQueries({
+ queries: taskIds.map((taskId) => ({
+ queryKey: runsKey(agentId, taskId),
+ retry: false,
+ refetchInterval: live ? (fast ? 3_000 : 15_000) : false,
+ queryFn: async (): Promise<RoutineRunRow[]> => {
+ const body = await readJson<{ runs?: RoutineRunRow[] }>(
+ await fetch(`${base(agentId)}/routines/${encodeURIComponent(taskId)}/runs?limit=50`),
+ );
+ return body.runs ?? [];
+ },
+ })),
+ });
+ const runs = queries.flatMap((query) => query.data ?? [])
+ .sort((a, b) => (b.started_ms ?? b.finished_ms ?? 0) - (a.started_ms ?? a.finished_ms ?? 0));
+ return {
+ runs,
+ loading: queries.some((query) => query.isPending),
+ unavailable: queries.length > 0 && queries.every((query) => query.isError),
+ };
+}
+
+/** Refresh every routine view of one agent after an action. */
+export function useRoutineRefresh(agentId: string) {
+ const client = useQueryClient();
+ return () => Promise.all([
+ client.invalidateQueries({ queryKey: ["tasks"] }),
+ client.invalidateQueries({ queryKey: ["society", "agent-routines", agentId] }),
+ client.invalidateQueries({ queryKey: ["society", "routine-activity", agentId] }),
+ client.invalidateQueries({ queryKey: ["society", "routine-runs", agentId] }),
+ ]);
+}
+
+const SEEN_EVERY_MS = 60_000;
+const lastSeen = new Map<string, number>();
+
+/**
+ * The person looked at this agent's routine results. Throttled to one
+ * request a minute per agent; failures are ignored (it only feeds parking).
+ */
+export function markRoutinesSeen(agentId: string, now = Date.now()): void {
+ if (!agentId) return;
+ const previous = lastSeen.get(agentId) ?? 0;
+ if (now - previous < SEEN_EVERY_MS) return;
+ lastSeen.set(agentId, now);
+ void fetch(`${base(agentId)}/routines-seen`, { method: "POST" }).catch(() => undefined);
+}
+
+/** Test helper: forget the throttle. */
+export function resetSeenThrottle(): void {
+ lastSeen.clear();
+}
+
+export async function answerParking(agentId: string, choice: ParkingChoice): Promise<ParkingView> {
+ const body = await readJson<{ parking: ParkingView }>(await fetch(`${base(agentId)}/routines-parking`, {
+ method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ choice }),
+ }));
+ return body.parking;
+}
+
+export function useParkingDays() {
+ return useQuery({
+ queryKey: ["society", "routine-parking-days"],
+ retry: false,
+ staleTime: 60_000,
+ queryFn: async () => (await readJson<{ days: number }>(await fetch("/api/society/routine-parking"))).days,
+ });
+}
+
+export async function saveParkingDays(days: number): Promise<number> {
+ const body = await readJson<{ days: number }>(await fetch("/api/society/routine-parking", {
+ method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ days }),
+ }));
+ return body.days;
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/card/routines/runs.ts b/dodaios/ui/web/frontend/src/components/society/card/routines/runs.ts
new file mode 100644
index 0000000000..f4253ea4da
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/card/routines/runs.ts
@@ -0,0 +1,115 @@
+/**
+ * A routine's runs from its task steps, the same way the backend reads them
+ * (`dodaios/society/routine_history.py`). The detail panel already polls the
+ * task with its steps, so this is always available; the run-history route
+ * adds what only the run's chat knows (cost and summary of older runs).
+ */
+import type { TaskStep } from "@/lib/tasksApi";
+import type { RoutineRunRow } from "./routinesApi";
+
+export interface Run {
+ id: string;
+ taskId: string;
+ /** Start in epoch ms (or the record's time for runs without a start). */
+ timestamp: number;
+ status: string;
+ /** The saved result text (or the skip / failure message). */
+ text: string;
+ sessionId?: string;
+ startedMs?: number;
+ finishedMs?: number;
+ /** A skipped run's reason code and seat (`skipped` step), worded by `routineSkipReason`. */
+ skipCode?: string;
+ skipProvider?: string;
+ origin: "manual" | "automatic";
+ durationMs?: number;
+ costUsd?: number | null;
+ billedViaKey?: boolean | null;
+ provider?: string;
+ model?: string;
+ summary?: string;
+ error?: string;
+}
+
+const firstLine = (text: string) => text.split(/\r?\n/).map((line) => line.replace(/^\s*(?:#{1,6}\s+|[-*+>]\s+|\d+[.)]\s+)/, "").replace(/(\*\*|__|`+|~~)/g, "").trim())
+ .find((line) => line && !/^[-=*_|:]+$/.test(line)) ?? "";
+
+const asNumber = (value: unknown) => (typeof value === "number" && Number.isFinite(value) ? value : undefined);
+
+/** New runs have explicit boundaries; retain older result/error records too. */
+export function routineRuns(taskId: string, steps: TaskStep[]): Run[] {
+ const runs: Run[] = [];
+ let current: Run | undefined;
+ let manualNext = false;
+ for (const step of steps) {
+ const event = step.payload.event;
+ const at = step.timestamp_ns / 1e6;
+ const text = String(step.payload.message ?? step.payload.text ?? "");
+ if (event === "run_now") {
+ manualNext = true;
+ } else if (event === "run_started") {
+ if (current?.status === "running") current.status = "interrupted";
+ current = { id: `${taskId}:${step.seq}`, taskId, timestamp: at, startedMs: at, status: "running", text: "", origin: manualNext ? "manual" : "automatic" };
+ manualNext = false;
+ runs.push(current);
+ } else if (event === "routine_chat" && current && typeof step.payload.session_id === "string") {
+ current.sessionId = step.payload.session_id;
+ } else if (event === "routine_summary" && current) {
+ current.durationMs = asNumber(step.payload.duration_ms) || undefined;
+ current.costUsd = asNumber(step.payload.cost_usd) ?? null;
+ current.billedViaKey = typeof step.payload.billed_via_key === "boolean" ? step.payload.billed_via_key : null;
+ current.provider = String(step.payload.provider ?? "");
+ current.model = String(step.payload.model ?? "");
+ } else if (event === "agent_result" && current) {
+ current.text = text;
+ } else if (event === "skipped") {
+ // Unattended work that may not bill its seat: no turn started. The skip
+ // ends the run; an older history also logged an "error" right after it.
+ const skip = { status: "skipped", text, finishedMs: at,
+ skipCode: String(step.payload.code ?? ""), skipProvider: String(step.payload.provider ?? "") };
+ if (current) Object.assign(current, skip);
+ else { current = { id: `${taskId}:${step.seq}`, taskId, timestamp: at, origin: "automatic", ...skip }; runs.push(current); }
+ } else if (["run_completed", "run_cancelled", "error", "deferred", "waiting"].includes(String(event))) {
+ const status = event === "run_completed" ? "completed" : event === "run_cancelled" ? "cancelled"
+ : event === "deferred" ? "pending" : event === "waiting" ? "waiting" : "failed";
+ if (current?.status === "skipped") current = undefined;
+ else if (current) {
+ current.status = status; current.finishedMs = at;
+ if (text) current.text = text;
+ if (status !== "completed") current.error = text || String(step.payload.reason ?? "");
+ else if (current.durationMs === undefined) current.durationMs = asNumber(step.payload.duration_ms) || undefined;
+ current = undefined;
+ } else runs.push({ id: `${taskId}:${step.seq}`, taskId, timestamp: at, finishedMs: at, status, text, origin: "automatic", error: status !== "completed" ? text : undefined });
+ } else if (event === "agent_result") {
+ // Legacy runners persisted the result before the final state transition.
+ runs.push({ id: `${taskId}:${step.seq}`, taskId, timestamp: at, finishedMs: at, status: "legacy", text, origin: "automatic" });
+ }
+ }
+ for (const run of runs) {
+ if (run.durationMs === undefined && run.startedMs !== undefined && run.finishedMs !== undefined && run.finishedMs > run.startedMs) {
+ run.durationMs = run.finishedMs - run.startedMs;
+ }
+ if (run.status !== "failed" && run.status !== "skipped") run.summary = firstLine(run.text);
+ }
+ return runs;
+}
+
+/** Add what the run-history route knows (cost and summary of older runs). */
+export function mergeRunDetails(runs: Run[], rows: RoutineRunRow[]): Run[] {
+ if (!rows.length) return runs;
+ const byId = new Map(rows.map((row) => [row.id, row]));
+ return runs.map((run) => {
+ const row = byId.get(run.id);
+ if (!row) return run;
+ return {
+ ...run,
+ costUsd: run.costUsd ?? row.cost_usd,
+ billedViaKey: run.billedViaKey ?? row.billed_via_key,
+ durationMs: run.durationMs ?? row.duration_ms ?? undefined,
+ summary: run.summary || row.summary || undefined,
+ error: run.error || row.error || undefined,
+ provider: run.provider || row.provider || undefined,
+ model: run.model || row.model || undefined,
+ };
+ });
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/card/routines/useNow.ts b/dodaios/ui/web/frontend/src/components/society/card/routines/useNow.ts
new file mode 100644
index 0000000000..a4ef99ba8a
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/card/routines/useNow.ts
@@ -0,0 +1,11 @@
+import { useEffect, useState } from "react";
+
+/** "Now", refreshed every `intervalMs` so relative times stay true without churn. */
+export function useNow(intervalMs = 30_000): number {
+ const [now, setNow] = useState(() => Date.now());
+ useEffect(() => {
+ const timer = window.setInterval(() => setNow(Date.now()), intervalMs);
+ return () => window.clearInterval(timer);
+ }, [intervalMs]);
+ return now;
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/chat/RoutineChatHost.tsx b/dodaios/ui/web/frontend/src/components/society/chat/RoutineChatHost.tsx
index 40eacd20e8..56e22bd171 100644
--- a/dodaios/ui/web/frontend/src/components/society/chat/RoutineChatHost.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/chat/RoutineChatHost.tsx
@@ -3,6 +3,7 @@ import { useT } from "@/i18n";
import { useRoutineNavigation } from "./routineNavigation";
import { AgentSwatch } from "../AgentSwatch";
import { useSocietyAgent } from "../data";
+import { markRoutinesSeen } from "../card/routines/routinesApi";
const RoutineChat = lazy(() => import("../card/RoutineChat"));
@@ -14,6 +15,8 @@ export function RoutineChatHost({ agentId, onOpen, children }: {
const close = useRoutineNavigation((state) => state.close);
const selected = target?.agentId === agentId ? target : null;
useEffect(() => { if (selected) onOpen(); }, [selected, onOpen]);
+ // Opening a run's transcript is reading its result (away-parking).
+ useEffect(() => { if (selected && selected.kind !== "conversation") markRoutinesSeen(agentId); }, [selected, agentId]);
useEffect(() => () => {
if (useRoutineNavigation.getState().target?.agentId === agentId) close();
}, [close, agentId]);
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/society/de.json b/dodaios/ui/web/frontend/src/i18n/locales/society/de.json
index 91b4017dcd..b26d135478 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/society/de.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/society/de.json
@@ -1908,6 +1908,112 @@
"look_start": "Von Anfang an",
"next_look": "Nächster Look: {0} ab Level {1}",
"team_note": "Agenten steigen durch erledigte Arbeit auf und tragen immer ihre besten Teile."
+ },
+ "agent_routines": {
+ "schedule": {
+ "every_minute": "Jede Minute",
+ "every_minutes": "Alle {n} Minuten",
+ "every_hour": "Jede Stunde",
+ "every_hour_at": "Jede Stunde um :{minute}",
+ "every_hours": "Alle {n} Stunden",
+ "every_hours_at": "Alle {n} Stunden um :{minute}",
+ "every_day": "Jeden Tag",
+ "every_week": "Jede Woche",
+ "daily_at": "Jeden Tag um {time}",
+ "every_n_days_at": "Alle {n} Tage um {time}",
+ "weekdays_at": "Werktags um {time}",
+ "weekends_at": "Am Wochenende um {time}",
+ "days_at": "Jeden {days} um {time}",
+ "monthly_at": "Monatlich am Tag {days} um {time}",
+ "yearly_at": "Jedes Jahr am {date} um {time}",
+ "in_months": "{schedule}, nur im {months}",
+ "with_days": "{schedule}, {days}",
+ "on_weekdays": "werktags",
+ "on_weekends": "am Wochenende",
+ "zone_time": "{schedule} (Zeit in {zone})",
+ "converted": "{schedule} · {time} in {zone}",
+ "custom_cron": "Eigener Zeitplan: {expression}",
+ "custom": "Zeitplan: {kind}",
+ "every_duration": "Alle {duration}",
+ "n_days": "{n} Tage",
+ "n_hours": "{n} Stunden",
+ "n_minutes": "{n} Minuten",
+ "n_seconds": "{n} Sekunden",
+ "once_at": "Einmal, {when}",
+ "once_in": "Einmal, in {duration}",
+ "on_event": "Wenn {event} eintritt",
+ "on_webhook": "Wenn sein Webhook aufgerufen wird",
+ "on_provider": "Bei Ereignissen von {provider}",
+ "on_integration": "Beim Integrationsereignis {event}",
+ "on_demand": "Wenn du sie startest",
+ "on_file": "Wenn sich Dateien in {path} ändern",
+ "on_source": "Bei neuen {source}-Nachrichten"
+ },
+ "list": {
+ "running": "Läuft gerade",
+ "parked": "Pausiert, während du weg warst",
+ "test_run": "Jetzt testweise ausführen",
+ "pause": "Pausieren",
+ "resume": "Fortsetzen",
+ "due_now": "jetzt fällig",
+ "setup_in_chat": "Im Chat einrichten",
+ "setup_prompt": "Richte mir eine Routine ein: ",
+ "or_chat": "Oder im Chat beschreiben",
+ "empty_body": "Aufgaben, die dieser Agent von selbst erledigt, etwa eine Morgenübersicht oder ein Wochencheck.",
+ "active_hint": "Aktive von allen Routinen"
+ },
+ "parking": {
+ "title": "Pausiert, während du weg warst",
+ "body": "{count} Routinen haben in {days} Tagen {unread} Ergebnisse erzeugt, die niemand geöffnet hat. Sie wurden pausiert, um Läufe zu sparen.",
+ "body_one": "Diese Routine hat in {days} Tagen {unread} Ergebnisse erzeugt, die niemand geöffnet hat. Sie wurde pausiert, um Läufe zu sparen.",
+ "keep_running": "Fortsetzen",
+ "keep_paused": "Pausiert lassen",
+ "never_ask": "Fortsetzen und nie wieder pausieren"
+ },
+ "away": {
+ "label": "Routinen mit ungelesenen Ergebnissen pausieren",
+ "never": "Nie",
+ "after_days": "Nach {n} Tagen",
+ "hint": "Gilt für geplante Routinen aller Agenten. Läufe, die du selbst startest, werden nie pausiert.",
+ "off_for_agent": "Für diesen Agenten nie pausiert",
+ "turn_on": "Einschalten"
+ },
+ "detail": {
+ "edit_in_chat": "Im Chat ändern",
+ "edit_prompt": "Ändere meine Routine „{title}“ ({schedule}): ",
+ "running": "Läuft gerade",
+ "parked": "Pausiert, während du weg warst",
+ "due_now": "jetzt fällig",
+ "active": "Aktiv",
+ "last_failure": "Letzter Fehler",
+ "failed_no_detail": "Der Lauf ist ohne Fehlermeldung fehlgeschlagen.",
+ "open_failed_run": "Diesen Lauf öffnen",
+ "instruction": "Anweisung",
+ "delete_note": "Künftige Läufe enden. Bereits gelieferte Ergebnisse bleiben im Chat des Agenten."
+ },
+ "runs": {
+ "empty": "Noch keine Läufe. Mit „Testlauf“ probierst du sie sofort aus.",
+ "manual": "Manuell",
+ "included": "In deinem Abo enthalten",
+ "skip_away": "Übersprungen: Die Ergebnisse wurden länger nicht geöffnet, daher wurde die Routine pausiert.",
+ "show_all": "Alle {n} zeigen",
+ "show_less": "Weniger zeigen"
+ },
+ "status": {
+ "waiting": "Wartet",
+ "pending": "Verschoben",
+ "interrupted": "Unterbrochen"
+ },
+ "webhook": {
+ "url_help": "Sende JSON per POST an diese Adresse, um die Routine zu starten.",
+ "key_help": "Halte ihn geheim. Erneuere ihn, falls er bekannt wird.",
+ "header": "Header",
+ "header_help": "Füge diese Zeile in die Request-Header des sendenden Dienstes ein.",
+ "reveal": "Schlüssel zeigen",
+ "hide": "Schlüssel verbergen",
+ "copy_url": "URL kopieren",
+ "copy_header": "Header-Zeile kopieren"
+ }
}
}
}
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/society/en.json b/dodaios/ui/web/frontend/src/i18n/locales/society/en.json
index 6ca01af25a..6374e0274b 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/society/en.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/society/en.json
@@ -1908,6 +1908,112 @@
"look_start": "From the start",
"next_look": "Next look: {0} at level {1}",
"team_note": "Agents level up from finished work and always wear their best unlocks."
+ },
+ "agent_routines": {
+ "schedule": {
+ "every_minute": "Every minute",
+ "every_minutes": "Every {n} minutes",
+ "every_hour": "Every hour",
+ "every_hour_at": "Every hour at :{minute}",
+ "every_hours": "Every {n} hours",
+ "every_hours_at": "Every {n} hours at :{minute}",
+ "every_day": "Every day",
+ "every_week": "Every week",
+ "daily_at": "Every day at {time}",
+ "every_n_days_at": "Every {n} days at {time}",
+ "weekdays_at": "Weekdays at {time}",
+ "weekends_at": "Weekends at {time}",
+ "days_at": "Every {days} at {time}",
+ "monthly_at": "Monthly on day {days} at {time}",
+ "yearly_at": "Every year on {date} at {time}",
+ "in_months": "{schedule}, only in {months}",
+ "with_days": "{schedule} on {days}",
+ "on_weekdays": "weekdays",
+ "on_weekends": "weekends",
+ "zone_time": "{schedule} ({zone} time)",
+ "converted": "{schedule} · {time} in {zone}",
+ "custom_cron": "Custom schedule: {expression}",
+ "custom": "Schedule: {kind}",
+ "every_duration": "Every {duration}",
+ "n_days": "{n} days",
+ "n_hours": "{n} hours",
+ "n_minutes": "{n} minutes",
+ "n_seconds": "{n} seconds",
+ "once_at": "Once, {when}",
+ "once_in": "Once, in {duration}",
+ "on_event": "When {event} happens",
+ "on_webhook": "When its webhook is called",
+ "on_provider": "On {provider} events",
+ "on_integration": "On the integration event {event}",
+ "on_demand": "When you start it",
+ "on_file": "When files change in {path}",
+ "on_source": "On new {source} messages"
+ },
+ "list": {
+ "running": "Running now",
+ "parked": "Paused while you were away",
+ "test_run": "Test run now",
+ "pause": "Pause",
+ "resume": "Resume",
+ "due_now": "due now",
+ "setup_in_chat": "Set one up in chat",
+ "setup_prompt": "Set up a routine for me: ",
+ "or_chat": "Or describe it in chat",
+ "empty_body": "Jobs this agent runs on its own, like a morning digest or a weekly check.",
+ "active_hint": "Active of all routines"
+ },
+ "parking": {
+ "title": "Paused while you were away",
+ "body": "{count} routines made {unread} results in {days} days that nobody opened, so they were paused to save runs.",
+ "body_one": "This routine made {unread} results in {days} days that nobody opened, so it was paused to save runs.",
+ "keep_running": "Resume",
+ "keep_paused": "Keep paused",
+ "never_ask": "Resume and don't pause again"
+ },
+ "away": {
+ "label": "Pause routines whose results go unread",
+ "never": "Never",
+ "after_days": "After {n} days",
+ "hint": "Applies to scheduled routines of every agent. Runs you start yourself are never paused.",
+ "off_for_agent": "Never paused for this agent",
+ "turn_on": "Turn on"
+ },
+ "detail": {
+ "edit_in_chat": "Edit in chat",
+ "edit_prompt": "Change my routine \"{title}\" ({schedule}): ",
+ "running": "Running now",
+ "parked": "Paused while you were away",
+ "due_now": "due now",
+ "active": "Active",
+ "last_failure": "Last failure",
+ "failed_no_detail": "The run failed without an error message.",
+ "open_failed_run": "Open that run",
+ "instruction": "Instruction",
+ "delete_note": "Future runs stop. Results already delivered stay in the agent's chat."
+ },
+ "runs": {
+ "empty": "No runs yet. Use Test run to try it now.",
+ "manual": "Manual",
+ "included": "Included in your subscription",
+ "skip_away": "Skipped: nobody opened the results for a while, so the routine was paused.",
+ "show_all": "Show all {n}",
+ "show_less": "Show fewer"
+ },
+ "status": {
+ "waiting": "Waiting",
+ "pending": "Deferred",
+ "interrupted": "Interrupted"
+ },
+ "webhook": {
+ "url_help": "POST JSON to this address to start the routine.",
+ "key_help": "Keep it secret. Rotate it if it ever leaks.",
+ "header": "Header",
+ "header_help": "Paste this line into the sending service's request headers.",
+ "reveal": "Show key",
+ "hide": "Hide key",
+ "copy_url": "Copy URL",
+ "copy_header": "Copy header line"
+ }
}
}
}
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/society/es.json b/dodaios/ui/web/frontend/src/i18n/locales/society/es.json
index 9b71d8fe94..9b6074a235 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/society/es.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/society/es.json
@@ -1908,6 +1908,112 @@
"look_start": "Desde el inicio",
"next_look": "Próximo look: {0} en el nivel {1}",
"team_note": "Los agentes suben de nivel con el trabajo terminado y siempre llevan sus mejores piezas."
+ },
+ "agent_routines": {
+ "schedule": {
+ "every_minute": "Cada minuto",
+ "every_minutes": "Cada {n} minutos",
+ "every_hour": "Cada hora",
+ "every_hour_at": "Cada hora a los :{minute}",
+ "every_hours": "Cada {n} horas",
+ "every_hours_at": "Cada {n} horas a los :{minute}",
+ "every_day": "Todos los días",
+ "every_week": "Cada semana",
+ "daily_at": "Todos los días a las {time}",
+ "every_n_days_at": "Cada {n} días a las {time}",
+ "weekdays_at": "Entre semana a las {time}",
+ "weekends_at": "Los fines de semana a las {time}",
+ "days_at": "Cada {days} a las {time}",
+ "monthly_at": "Cada mes el día {days} a las {time}",
+ "yearly_at": "Cada año el {date} a las {time}",
+ "in_months": "{schedule}, solo en {months}",
+ "with_days": "{schedule}, {days}",
+ "on_weekdays": "entre semana",
+ "on_weekends": "los fines de semana",
+ "zone_time": "{schedule} (hora de {zone})",
+ "converted": "{schedule} · {time} en {zone}",
+ "custom_cron": "Horario personalizado: {expression}",
+ "custom": "Horario: {kind}",
+ "every_duration": "Cada {duration}",
+ "n_days": "{n} días",
+ "n_hours": "{n} horas",
+ "n_minutes": "{n} minutos",
+ "n_seconds": "{n} segundos",
+ "once_at": "Una vez, {when}",
+ "once_in": "Una vez, dentro de {duration}",
+ "on_event": "Cuando ocurre {event}",
+ "on_webhook": "Cuando se llama a su webhook",
+ "on_provider": "Con eventos de {provider}",
+ "on_integration": "Con el evento de integración {event}",
+ "on_demand": "Cuando tú la inicias",
+ "on_file": "Cuando cambian archivos en {path}",
+ "on_source": "Con mensajes nuevos de {source}"
+ },
+ "list": {
+ "running": "En curso",
+ "parked": "En pausa mientras no estabas",
+ "test_run": "Ejecutar prueba ahora",
+ "pause": "Pausar",
+ "resume": "Reanudar",
+ "due_now": "toca ahora",
+ "setup_in_chat": "Configurar en el chat",
+ "setup_prompt": "Configúrame una rutina: ",
+ "or_chat": "O descríbela en el chat",
+ "empty_body": "Tareas que este agente hace por su cuenta, como un resumen matutino o una revisión semanal.",
+ "active_hint": "Activas de todas las rutinas"
+ },
+ "parking": {
+ "title": "En pausa mientras no estabas",
+ "body": "{count} rutinas generaron {unread} resultados en {days} días que nadie abrió, así que se pausaron para ahorrar ejecuciones.",
+ "body_one": "Esta rutina generó {unread} resultados en {days} días que nadie abrió, así que se pausó para ahorrar ejecuciones.",
+ "keep_running": "Reanudar",
+ "keep_paused": "Mantener en pausa",
+ "never_ask": "Reanudar y no volver a pausar"
+ },
+ "away": {
+ "label": "Pausar rutinas cuyos resultados nadie lee",
+ "never": "Nunca",
+ "after_days": "Tras {n} días",
+ "hint": "Se aplica a las rutinas programadas de todos los agentes. Lo que inicias tú nunca se pausa.",
+ "off_for_agent": "Nunca se pausa para este agente",
+ "turn_on": "Activar"
+ },
+ "detail": {
+ "edit_in_chat": "Editar en el chat",
+ "edit_prompt": "Cambia mi rutina «{title}» ({schedule}): ",
+ "running": "En curso",
+ "parked": "En pausa mientras no estabas",
+ "due_now": "toca ahora",
+ "active": "Activa",
+ "last_failure": "Último fallo",
+ "failed_no_detail": "La ejecución falló sin mensaje de error.",
+ "open_failed_run": "Abrir esa ejecución",
+ "instruction": "Instrucción",
+ "delete_note": "Las próximas ejecuciones se detienen. Los resultados ya entregados se quedan en el chat del agente."
+ },
+ "runs": {
+ "empty": "Aún no hay ejecuciones. Usa Prueba para probarla ya.",
+ "manual": "Manual",
+ "included": "Incluido en tu suscripción",
+ "skip_away": "Omitida: nadie abrió los resultados durante un tiempo, así que la rutina se pausó.",
+ "show_all": "Ver las {n}",
+ "show_less": "Ver menos"
+ },
+ "status": {
+ "waiting": "Esperando",
+ "pending": "Aplazada",
+ "interrupted": "Interrumpida"
+ },
+ "webhook": {
+ "url_help": "Envía JSON por POST a esta dirección para iniciar la rutina.",
+ "key_help": "Mantenla en secreto. Renuévala si se filtra.",
+ "header": "Cabecera",
+ "header_help": "Pega esta línea en las cabeceras de la petición del servicio que envía.",
+ "reveal": "Mostrar clave",
+ "hide": "Ocultar clave",
+ "copy_url": "Copiar URL",
+ "copy_header": "Copiar línea de cabecera"
+ }
}
}
}
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/society/pt.json b/dodaios/ui/web/frontend/src/i18n/locales/society/pt.json
index 2ebf79cfbf..4b979c9880 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/society/pt.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/society/pt.json
@@ -1908,6 +1908,112 @@
"look_start": "Desde o início",
"next_look": "Próximo aspeto: {0} no nível {1}",
"team_note": "Os agentes sobem de nível com trabalho concluído e usam sempre os seus melhores desbloqueios."
+ },
+ "agent_routines": {
+ "schedule": {
+ "every_minute": "A cada minuto",
+ "every_minutes": "A cada {n} minutos",
+ "every_hour": "A cada hora",
+ "every_hour_at": "A cada hora aos :{minute}",
+ "every_hours": "A cada {n} horas",
+ "every_hours_at": "A cada {n} horas aos :{minute}",
+ "every_day": "Todos os dias",
+ "every_week": "Todas as semanas",
+ "daily_at": "Todos os dias às {time}",
+ "every_n_days_at": "A cada {n} dias às {time}",
+ "weekdays_at": "Nos dias úteis às {time}",
+ "weekends_at": "Aos fins de semana às {time}",
+ "days_at": "Todas as {days} às {time}",
+ "monthly_at": "Todos os meses no dia {days} às {time}",
+ "yearly_at": "Todos os anos a {date} às {time}",
+ "in_months": "{schedule}, só em {months}",
+ "with_days": "{schedule}, {days}",
+ "on_weekdays": "nos dias úteis",
+ "on_weekends": "aos fins de semana",
+ "zone_time": "{schedule} (hora de {zone})",
+ "converted": "{schedule} · {time} em {zone}",
+ "custom_cron": "Horário personalizado: {expression}",
+ "custom": "Horário: {kind}",
+ "every_duration": "A cada {duration}",
+ "n_days": "{n} dias",
+ "n_hours": "{n} horas",
+ "n_minutes": "{n} minutos",
+ "n_seconds": "{n} segundos",
+ "once_at": "Uma vez, {when}",
+ "once_in": "Uma vez, dentro de {duration}",
+ "on_event": "Quando acontece {event}",
+ "on_webhook": "Quando o seu webhook é chamado",
+ "on_provider": "Com eventos de {provider}",
+ "on_integration": "Com o evento de integração {event}",
+ "on_demand": "Quando a inicia",
+ "on_file": "Quando mudam ficheiros em {path}",
+ "on_source": "Com novas mensagens de {source}"
+ },
+ "list": {
+ "running": "A correr agora",
+ "parked": "Em pausa enquanto esteve fora",
+ "test_run": "Executar teste agora",
+ "pause": "Pausar",
+ "resume": "Retomar",
+ "due_now": "para agora",
+ "setup_in_chat": "Configurar no chat",
+ "setup_prompt": "Configura-me uma rotina: ",
+ "or_chat": "Ou descreva-a no chat",
+ "empty_body": "Tarefas que este agente faz sozinho, como um resumo da manhã ou uma verificação semanal.",
+ "active_hint": "Ativas de todas as rotinas"
+ },
+ "parking": {
+ "title": "Em pausa enquanto esteve fora",
+ "body": "{count} rotinas geraram {unread} resultados em {days} dias que ninguém abriu, por isso foram pausadas para poupar execuções.",
+ "body_one": "Esta rotina gerou {unread} resultados em {days} dias que ninguém abriu, por isso foi pausada para poupar execuções.",
+ "keep_running": "Retomar",
+ "keep_paused": "Manter em pausa",
+ "never_ask": "Retomar e não voltar a pausar"
+ },
+ "away": {
+ "label": "Pausar rotinas cujos resultados ninguém lê",
+ "never": "Nunca",
+ "after_days": "Após {n} dias",
+ "hint": "Aplica-se às rotinas agendadas de todos os agentes. O que inicia por si nunca é pausado.",
+ "off_for_agent": "Nunca pausado para este agente",
+ "turn_on": "Ativar"
+ },
+ "detail": {
+ "edit_in_chat": "Editar no chat",
+ "edit_prompt": "Altera a minha rotina «{title}» ({schedule}): ",
+ "running": "A correr agora",
+ "parked": "Em pausa enquanto esteve fora",
+ "due_now": "para agora",
+ "active": "Ativa",
+ "last_failure": "Última falha",
+ "failed_no_detail": "A execução falhou sem mensagem de erro.",
+ "open_failed_run": "Abrir essa execução",
+ "instruction": "Instrução",
+ "delete_note": "As próximas execuções param. Os resultados já entregues ficam no chat do agente."
+ },
+ "runs": {
+ "empty": "Ainda sem execuções. Use Execução de teste para experimentar já.",
+ "manual": "Manual",
+ "included": "Incluído na sua subscrição",
+ "skip_away": "Ignorada: ninguém abriu os resultados durante algum tempo, por isso a rotina foi pausada.",
+ "show_all": "Mostrar todas as {n}",
+ "show_less": "Mostrar menos"
+ },
+ "status": {
+ "waiting": "À espera",
+ "pending": "Adiada",
+ "interrupted": "Interrompida"
+ },
+ "webhook": {
+ "url_help": "Envie JSON por POST para este endereço para iniciar a rotina.",
+ "key_help": "Mantenha-a secreta. Renove-a se for divulgada.",
+ "header": "Cabeçalho",
+ "header_help": "Cole esta linha nos cabeçalhos do pedido do serviço que envia.",
+ "reveal": "Mostrar chave",
+ "hide": "Ocultar chave",
+ "copy_url": "Copiar URL",
+ "copy_header": "Copiar linha de cabeçalho"
+ }
}
}
}
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/society/zh.json b/dodaios/ui/web/frontend/src/i18n/locales/society/zh.json
index 479f73af8f..a7972e9893 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/society/zh.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/society/zh.json
@@ -1908,6 +1908,112 @@
"look_start": "初始造型",
"next_look": "下一个造型:{0}(等级 {1})",
"team_note": "智能体通过完成工作升级,并始终穿着已解锁的最佳装备。"
+ },
+ "agent_routines": {
+ "schedule": {
+ "every_minute": "每分钟",
+ "every_minutes": "每 {n} 分钟",
+ "every_hour": "每小时",
+ "every_hour_at": "每小时的第 {minute} 分",
+ "every_hours": "每 {n} 小时",
+ "every_hours_at": "每 {n} 小时的第 {minute} 分",
+ "every_day": "每天",
+ "every_week": "每周",
+ "daily_at": "每天 {time}",
+ "every_n_days_at": "每 {n} 天 {time}",
+ "weekdays_at": "工作日 {time}",
+ "weekends_at": "周末 {time}",
+ "days_at": "每{days} {time}",
+ "monthly_at": "每月 {days} 日 {time}",
+ "yearly_at": "每年 {date} {time}",
+ "in_months": "{schedule},仅限 {months}",
+ "with_days": "{schedule},{days}",
+ "on_weekdays": "工作日",
+ "on_weekends": "周末",
+ "zone_time": "{schedule}({zone} 时间)",
+ "converted": "{schedule} · {zone} 时间 {time}",
+ "custom_cron": "自定义计划:{expression}",
+ "custom": "计划:{kind}",
+ "every_duration": "每 {duration}",
+ "n_days": "{n} 天",
+ "n_hours": "{n} 小时",
+ "n_minutes": "{n} 分钟",
+ "n_seconds": "{n} 秒",
+ "once_at": "一次,{when}",
+ "once_in": "一次,{duration}后",
+ "on_event": "当 {event} 发生时",
+ "on_webhook": "当它的 Webhook 被调用时",
+ "on_provider": "收到 {provider} 事件时",
+ "on_integration": "收到集成事件 {event} 时",
+ "on_demand": "由你手动启动",
+ "on_file": "当 {path} 中的文件变化时",
+ "on_source": "收到新的 {source} 消息时"
+ },
+ "list": {
+ "running": "正在运行",
+ "parked": "你不在时已暂停",
+ "test_run": "立即测试运行",
+ "pause": "暂停",
+ "resume": "恢复",
+ "due_now": "现在到期",
+ "setup_in_chat": "在聊天中设置",
+ "setup_prompt": "帮我设置一个例行任务:",
+ "or_chat": "或在聊天中描述",
+ "empty_body": "这个智能体自行完成的工作,例如早间摘要或每周检查。",
+ "active_hint": "启用的例行任务 / 全部"
+ },
+ "parking": {
+ "title": "你不在时已暂停",
+ "body": "{count} 个例行任务在 {days} 天内产生了 {unread} 条无人打开的结果,因此已暂停以节省运行。",
+ "body_one": "此例行任务在 {days} 天内产生了 {unread} 条无人打开的结果,因此已暂停以节省运行。",
+ "keep_running": "恢复",
+ "keep_paused": "保持暂停",
+ "never_ask": "恢复且不再暂停"
+ },
+ "away": {
+ "label": "结果无人查看时暂停例行任务",
+ "never": "从不",
+ "after_days": "{n} 天后",
+ "hint": "适用于所有智能体的定时例行任务。你自己启动的运行永远不会被暂停。",
+ "off_for_agent": "此智能体从不暂停",
+ "turn_on": "开启"
+ },
+ "detail": {
+ "edit_in_chat": "在聊天中修改",
+ "edit_prompt": "修改我的例行任务「{title}」({schedule}):",
+ "running": "正在运行",
+ "parked": "你不在时已暂停",
+ "due_now": "现在到期",
+ "active": "已启用",
+ "last_failure": "最近一次失败",
+ "failed_no_detail": "这次运行失败了,但没有错误信息。",
+ "open_failed_run": "打开那次运行",
+ "instruction": "指令",
+ "delete_note": "之后的运行将停止。已送达的结果会保留在智能体的聊天中。"
+ },
+ "runs": {
+ "empty": "还没有运行记录。点击“测试运行”立即试试。",
+ "manual": "手动",
+ "included": "包含在你的订阅中",
+ "skip_away": "已跳过:结果一段时间无人打开,因此例行任务已暂停。",
+ "show_all": "显示全部 {n} 条",
+ "show_less": "收起"
+ },
+ "status": {
+ "waiting": "等待中",
+ "pending": "已推迟",
+ "interrupted": "已中断"
+ },
+ "webhook": {
+ "url_help": "向此地址 POST JSON 即可启动例行任务。",
+ "key_help": "请妥善保密。如有泄露请轮换。",
+ "header": "请求头",
+ "header_help": "将这一行粘贴到发送方服务的请求头中。",
+ "reveal": "显示密钥",
+ "hide": "隐藏密钥",
+ "copy_url": "复制 URL",
+ "copy_header": "复制请求头"
+ }
}
}
}
diff --git a/dodaios/ui/web/society_routes.py b/dodaios/ui/web/society_routes.py
index f5e5fe56cf..d1da3e82a3 100644
--- a/dodaios/ui/web/society_routes.py
+++ b/dodaios/ui/web/society_routes.py
@@ -1810,6 +1810,132 @@ async def update_agent_routine(
return {"ok": True, "id": task_id}
+# ------------------------------------------------- routine runs and parking
+
+
+async def _owned_agent(request: Request, agent_id: str) -> tuple[Any, AgentRecord]:
+ rt = await _runtime(request)
+ agent = await rt.roster.resolve(agent_id)
+ if agent is None:
+ raise HTTPException(404, {"reason": str(FailureReason.TARGET_UNKNOWN)})
+ return rt, agent
+
+
+def _routine_runs_of(row: dict[str, Any], chat_service: Any, limit: int) -> list[dict[str, Any]]:
+ """Newest first, at most ``limit``; older runs read their own chat once."""
+ from dodaios.society.routine_history import enrich_from_chat, parse_runs
+
+ runs = parse_runs(str(row.get("id") or ""), list(row.get("steps") or []))
+ newest = list(reversed(runs))[: max(1, limit)]
+ chat_store = getattr(chat_service, "store", None)
+ for run in newest:
+ if run.status != "running":
+ enrich_from_chat(run, chat_store)
+ return [{k: v for k, v in run.to_dict().items() if k != "result"} for run in newest]
+
+
[email protected]("/agents/{agent_id}/routines/{task_id}/runs")
+async def list_routine_runs(
+ agent_id: str, task_id: str, request: Request, limit: int = 30
+) -> dict[str, Any]:
+ """One routine's executions: status, start, duration, cost and a summary line."""
+ from dodaios.society.routines import is_agent_routine
+
+ rt, agent = await _owned_agent(request, agent_id)
+ row = await _task_store(request).get(task_id)
+ if row is None or not is_agent_routine(row, agent.agent_id):
+ raise HTTPException(404, "Routine not found")
+ runs = _routine_runs_of(row, rt.chat_service(), min(max(1, limit), 200))
+ return {"runs": runs, "total": len(runs)}
+
+
[email protected]("/agents/{agent_id}/routines-activity")
+async def routine_activity(agent_id: str, request: Request) -> dict[str, Any]:
+ """Each routine's newest run plus the agent's away-parking state."""
+ from dodaios.society.routine_parking import load_days, load_state
+ from dodaios.society.routines import list_routines
+
+ rt, agent = await _owned_agent(request, agent_id)
+ store = _task_store(request)
+ last: dict[str, Any] = {}
+ for summary in await list_routines(store, agent.agent_id):
+ row = await store.get(str(summary.get("id")))
+ if row is None:
+ continue
+ runs = _routine_runs_of(row, rt.chat_service(), 1)
+ last[str(row.get("id"))] = runs[0] if runs else None
+ days = await load_days(rt.store)
+ state = await load_state(rt.store, agent.agent_id)
+ return {"last_runs": last, "parking": _parking_view(state, days)}
+
+
+def _parking_view(state: Any, days: int) -> dict[str, Any]:
+ return {
+ "enabled": days > 0 and not state.never_ask,
+ "days": days,
+ "banner": bool(state.banner),
+ "parked_ids": list(state.parked_ids),
+ "parked_ms": state.parked_ms,
+ "parked_days": state.days or days,
+ "unread": state.unread,
+ "never_ask": state.never_ask,
+ }
+
+
[email protected]("/agents/{agent_id}/routines-seen")
+async def routines_seen(agent_id: str, request: Request) -> dict[str, Any]:
+ """The person opened this agent's routine results: a new away period starts."""
+ from dodaios.society.routine_parking import mark_seen
+
+ rt, agent = await _owned_agent(request, agent_id)
+ state = await mark_seen(rt.store, agent.agent_id)
+ return {"ok": True, "seen_ms": state.seen_ms}
+
+
+class ParkingChoiceBody(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+ choice: Literal["keep_running", "keep_paused", "never_ask", "ask_again"]
+
+
[email protected]("/agents/{agent_id}/routines-parking", openapi_extra={"x-jarvis-dangerous": True})
+async def routines_parking_choice(
+ agent_id: str, body: ParkingChoiceBody, request: Request
+) -> dict[str, Any]:
+ """Answer the away-parking banner (resume, keep paused, never ask)."""
+ from dodaios.society.routine_parking import apply_choice, load_days
+
+ rt, agent = await _owned_agent(request, agent_id)
+ scheduler = getattr(request.app.state, "task_scheduler", None)
+ if scheduler is None:
+ raise HTTPException(503, "The task scheduler is unavailable")
+ state = await apply_choice(
+ rt.store, _task_store(request), scheduler, agent.agent_id, body.choice
+ )
+ return {"ok": True, "parking": _parking_view(state, await load_days(rt.store))}
+
+
+class ParkingSettingsBody(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+ days: int = Field(ge=0, le=90)
+
+
[email protected]("/routine-parking")
+async def get_routine_parking(request: Request) -> dict[str, Any]:
+ from dodaios.society.routine_parking import load_days
+
+ rt = await _runtime(request)
+ return {"days": await load_days(rt.store)}
+
+
[email protected]("/routine-parking")
+async def put_routine_parking(body: ParkingSettingsBody, request: Request) -> dict[str, Any]:
+ """Days without opened results before routines are parked; 0 = never."""
+ from dodaios.society.routine_parking import save_days
+
+ rt = await _runtime(request)
+ return {"days": await save_days(rt.store, body.days)}
+
+
# ---------------------------------------------------------------- approvals
diff --git a/tests/contract/test_agent_mcp_harmony.py b/tests/contract/test_agent_mcp_harmony.py
index 930672d8d9..4e2bc9ddc0 100644
--- a/tests/contract/test_agent_mcp_harmony.py
+++ b/tests/contract/test_agent_mcp_harmony.py
@@ -218,6 +218,24 @@ WITHHELD: Final[dict[str, str]] = {
"pausing, deleting or running a routine now changes recurring spend; "
"the owner does it on the routine card, not via a remote client"
),
+ "GET /api/society/agents/{agent_id}/routines/{task_id}/runs": (
+ "a routine's run history is the owner's read-out on the routine card; "
+ "a remote client reads results in the agent's own chat"
+ ),
+ "GET /api/society/agents/{agent_id}/routines-activity": (
+ "newest run per routine and the away-parking banner feed the routine "
+ "list in the app; nothing a remote client acts on"
+ ),
+ "POST /api/society/agents/{agent_id}/routines-seen": (
+ "records that the owner looked at routine results in the app; a remote "
+ "client reporting it would defeat away-parking"
+ ),
+ "POST /api/society/agents/{agent_id}/routines-parking": (
+ "answering the away-parking banner resumes recurring spend; the owner "
+ "does it on the routine list, not via a remote client"
+ ),
+ "GET /api/society/routine-parking": "the away-parking window is an owner setting in the app",
+ "PUT /api/society/routine-parking": "changing the away-parking window is an owner setting",
"GET /api/society/agents/{agent_id}/conversations": (
"lists the agent's chats with Jarvis and teammates for the owner's "
"history rail in the app; a remote client messages agents directly"
diff --git a/tests/contract/test_routine_chats.py b/tests/contract/test_routine_chats.py
index 8feb32b611..bc7ab422a8 100644
--- a/tests/contract/test_routine_chats.py
+++ b/tests/contract/test_routine_chats.py
@@ -32,7 +32,15 @@ async def test_persisted_run_links_survive_reopening_without_loading_main_chat(w
await run_owned_routine(runtime, task_id, spec.tags, spec.action.prompt)
await run_owned_routine(runtime, task_id, spec.tags, spec.action.prompt)
row = await store.get(task_id)
- links = [step["payload"]["session_id"] for step in row["steps"]]
+ links = [
+ step["payload"]["session_id"]
+ for step in row["steps"]
+ if step["payload"].get("event") == "routine_chat"
+ ]
+ # Each run also leaves one summary step naming its own chat.
+ summaries = [s["payload"] for s in row["steps"]
+ if s["payload"].get("event") == "routine_summary"]
+ assert [s["session_id"] for s in summaries] == links
assert len(set(links)) == 2
reopened = AgentChatStore(tmp_path / "chat.db")
try:
diff --git a/tests/unit/society/test_routine_history.py b/tests/unit/society/test_routine_history.py
new file mode 100644
index 0000000000..d146ad7982
--- /dev/null
+++ b/tests/unit/society/test_routine_history.py
@@ -0,0 +1,206 @@
+"""A routine's run history is read from its task steps and, for older runs, its chat."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+from typing import Any
+
+from dodaios.society.routine_history import enrich_from_chat, parse_runs, run_summary_line
+
+
+def _steps(*events: tuple[float, dict[str, Any]]) -> list[dict[str, Any]]:
+ return [
+ {"seq": i + 1, "kind": "log", "timestamp_ns": int(at * 1e9), "payload": payload}
+ for i, (at, payload) in enumerate(events)
+ ]
+
+
+def test_a_completed_run_carries_its_seat_duration_and_cost() -> None:
+ runs = parse_runs(
+ "t1",
+ _steps(
+ (100, {"event": "run_started"}),
+ (100, {"event": "routine_chat", "session_id": "society:a:routine:t1:x"}),
+ (
+ 142,
+ {
+ "event": "routine_summary",
+ "duration_ms": 41_500,
+ "cost_usd": 0.0123,
+ "provider": "claude-cli",
+ "model": "sonnet",
+ "billed_via_key": False,
+ },
+ ),
+ (142, {"event": "agent_result", "text": "## Inbox\n- **3** new invoices"}),
+ (142, {"event": "run_completed", "duration_ms": 42_000}),
+ ),
+ )
+ assert len(runs) == 1
+ run = runs[0]
+ assert run.status == "completed" and run.origin == "automatic"
+ assert run.duration_ms == 41_500 # the turn's own time wins over the task wrapper
+ assert run.cost_usd == 0.0123 and run.billed_via_key is False
+ assert run.provider == "claude-cli" and run.model == "sonnet"
+ assert run.session_id == "society:a:routine:t1:x"
+ assert run.summary == "Inbox"
+ assert run.started_ms == 100_000 and run.finished_ms == 142_000
+
+
+def test_run_now_marks_the_next_run_as_the_persons_own() -> None:
+ runs = parse_runs(
+ "t1",
+ _steps(
+ (10, {"event": "run_started"}),
+ (11, {"event": "run_completed", "duration_ms": 1000}),
+ (20, {"event": "run_now"}),
+ (20, {"event": "run_started"}),
+ (25, {"event": "error", "message": "RuntimeError: seat offline"}),
+ ),
+ )
+ assert [r.origin for r in runs] == ["automatic", "manual"]
+ assert runs[1].status == "failed" and runs[1].error == "RuntimeError: seat offline"
+ assert runs[1].duration_ms == 5000
+
+
+def test_a_skip_keeps_its_reason_code_and_absorbs_the_legacy_error_line() -> None:
+ runs = parse_runs(
+ "t1",
+ _steps(
+ (10, {"event": "run_started"}),
+ (
+ 10,
+ {
+ "event": "skipped",
+ "code": "api_key_seat",
+ "provider": "gemini",
+ "message": "did not bill",
+ },
+ ),
+ (10, {"event": "error", "message": "did not bill"}),
+ ),
+ )
+ assert len(runs) == 1
+ assert runs[0].status == "skipped"
+ assert (runs[0].skip_code, runs[0].skip_provider) == ("api_key_seat", "gemini")
+
+
+def test_older_records_without_boundaries_stay_visible() -> None:
+ runs = parse_runs("t1", _steps((5, {"event": "agent_result", "text": "Old answer"})))
+ assert runs[0].status == "legacy" and runs[0].summary == "Old answer"
+
+
+def test_a_run_cut_off_by_a_new_start_reads_as_interrupted() -> None:
+ runs = parse_runs("t1", _steps((1, {"event": "run_started"}), (9, {"event": "run_started"})))
+ assert [r.status for r in runs] == ["interrupted", "running"]
+
+
+def test_an_older_run_reads_cost_and_summary_from_its_own_first_turn() -> None:
+ runs = parse_runs(
+ "t1",
+ _steps(
+ (1, {"event": "run_started"}),
+ (1, {"event": "routine_chat", "session_id": "s1"}),
+ (3, {"event": "run_completed", "duration_ms": 2000}),
+ ),
+ )
+ events = [
+ {"kind": "turn_started", "payload": {"turn_id": "a"}},
+ {"kind": "assistant_text", "payload": {"turn_id": "a", "text": "Found two new posts."}},
+ {
+ "kind": "turn_finished",
+ "payload": {"turn_id": "a", "cost_usd": 0.5, "duration_ms": 1800},
+ },
+ # A follow-up the person asked later in the same chat does not count.
+ {"kind": "turn_started", "payload": {"turn_id": "b"}},
+ {"kind": "turn_finished", "payload": {"turn_id": "b", "cost_usd": 9.0}},
+ ]
+ store = SimpleNamespace(list_events=lambda session_id: events if session_id == "s1" else [])
+ enrich_from_chat(runs[0], store)
+ assert runs[0].cost_usd == 0.5
+ assert runs[0].summary == "Found two new posts."
+ assert runs[0].duration_ms == 2000
+
+
+def test_a_run_with_a_summary_step_never_reopens_its_chat() -> None:
+ # CLI seats often report no cost: the history must not re-read that chat
+ # on every poll just because cost_usd stays empty.
+ runs = parse_runs(
+ "t1",
+ _steps(
+ (1, {"event": "run_started"}),
+ (1, {"event": "routine_chat", "session_id": "s1"}),
+ (2, {"event": "routine_summary", "duration_ms": 900, "cost_usd": None}),
+ (3, {"event": "run_completed", "duration_ms": 2000}),
+ ),
+ )
+
+ def explode(session_id: str) -> list[dict[str, Any]]:
+ raise AssertionError("the chat was read")
+
+ enrich_from_chat(runs[0], SimpleNamespace(list_events=explode))
+ assert runs[0].duration_ms == 900 and runs[0].cost_usd is None
+ assert "recorded" not in runs[0].to_dict()
+
+
+def test_a_missing_chat_store_leaves_the_run_as_parsed() -> None:
+ run = parse_runs("t1", _steps((1, {"event": "run_started"})))[0]
+ enrich_from_chat(run, None)
+ assert run.cost_usd is None
+
+
+def test_summary_lines_drop_markdown_and_are_capped() -> None:
+ assert run_summary_line("---\n> **Done**: all good") == "Done: all good"
+ assert len(run_summary_line("x" * 400)) == 160
+ assert run_summary_line("") == ""
+
+
+async def test_the_runner_records_one_summary_step_per_run(monkeypatch) -> None:
+ from dodaios.society import routine_runner
+
+ steps: list[tuple[str, str, dict[str, Any]]] = []
+
+ async def append_step(task_id: str, kind: str, payload: dict[str, Any]) -> int:
+ steps.append((task_id, kind, payload))
+ return len(steps)
+
+ monkeypatch.setattr(routine_runner, "_billed_via_api", lambda provider, account_id="": False)
+ await routine_runner._record_run_summary(
+ SimpleNamespace(append_step=append_step),
+ "t1",
+ "s1",
+ "turn",
+ {"status": "done", "duration_ms": 1234, "cost_usd": 0.5},
+ provider="hermes",
+ model="m",
+ account_id="",
+ )
+ assert steps == [
+ (
+ "t1",
+ "log",
+ {
+ "event": "routine_summary",
+ "session_id": "s1",
+ "turn_id": "turn",
+ "status": "done",
+ "duration_ms": 1234,
+ "cost_usd": 0.5,
+ "provider": "hermes",
+ "model": "m",
+ "billed_via_key": False,
+ },
+ )
+ ]
+ run = parse_runs(
+ "t1",
+ [
+ {"seq": 1, "kind": "log", "timestamp_ns": 0, "payload": {"event": "run_started"}},
+ {"seq": 2, "kind": "log", "timestamp_ns": 0, "payload": steps[0][2]},
+ ],
+ )[0]
+ assert run.duration_ms == 1234 and run.provider == "hermes"
+ # No store (a bare runtime) is not an error.
+ await routine_runner._record_run_summary(
+ None, "t1", "s1", "turn", {}, provider="x", model="", account_id=""
+ )
diff --git a/tests/unit/society/test_routine_parking.py b/tests/unit/society/test_routine_parking.py
new file mode 100644
index 0000000000..14b8bd91fd
--- /dev/null
+++ b/tests/unit/society/test_routine_parking.py
@@ -0,0 +1,300 @@
+"""Away-parking pauses only routines whose results nobody opens, and unparks them."""
+
+from __future__ import annotations
+
+import asyncio
+import time
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from dodaios.core.protocols import started_by_user
+from dodaios.society import routine_parking
+from dodaios.society.roster import Roster
+from dodaios.society.routine_parking import (
+ DAY_MS,
+ RoutineActivity,
+ RoutineParked,
+ apply_choice,
+ load_state,
+ mark_seen,
+ maybe_park,
+ parking_candidates,
+ save_days,
+)
+from dodaios.society.routines import build_task_spec
+from dodaios.society.store import SocietyStore
+from dodaios.tasks.store import TaskStore
+
+NOW = 1_800_000_000_000
+
+
+def _activity(task_id: str = "a", **overrides: Any) -> RoutineActivity:
+ values: dict[str, Any] = {
+ "task_id": task_id,
+ "state": "scheduled",
+ "trigger_type": "calendar",
+ "result_ms": tuple(NOW - d * DAY_MS for d in (6, 4, 1)),
+ }
+ values.update(overrides)
+ return RoutineActivity(**values)
+
+
+# ── the pure decision ────────────────────────────────────────────────────────
+
+
+def test_unread_results_over_the_window_park_the_routine() -> None:
+ chosen, unread = parking_candidates([_activity()], seen_ms=NOW - 8 * DAY_MS, now_ms=NOW, days=7)
+ assert chosen == ["a"] and unread == 3
+
+
+def test_a_recent_look_keeps_routines_running() -> None:
+ assert parking_candidates([_activity()], seen_ms=NOW - 2 * DAY_MS, now_ms=NOW, days=7) == (
+ [],
+ 0,
+ )
+
+
+def test_too_few_unread_results_is_not_wasted_spend() -> None:
+ item = _activity(result_ms=(NOW - DAY_MS,))
+ assert parking_candidates([item], seen_ms=NOW - 9 * DAY_MS, now_ms=NOW, days=7)[0] == []
+
+
+def test_routines_that_stopped_producing_are_left_alone() -> None:
+ item = _activity(result_ms=tuple(NOW - d * DAY_MS for d in (20, 15, 9)))
+ assert parking_candidates([item], seen_ms=NOW - 30 * DAY_MS, now_ms=NOW, days=7)[0] == []
+
+
+ "overrides",
+ [
+ {"trigger_type": "webhook"},
+ {"trigger_type": "source"},
+ {"trigger_type": "on_event"},
+ {"last_manual_ms": NOW - DAY_MS},
+ {"autonomous": True},
+ {"announces": True},
+ {"state": "paused"},
+ ],
+)
+def test_user_facing_and_already_quiet_routines_are_never_parked(
+ overrides: dict[str, Any],
+) -> None:
+ chosen, _ = parking_candidates(
+ [_activity(**overrides)], seen_ms=NOW - 8 * DAY_MS, now_ms=NOW, days=7
+ )
+ assert chosen == []
+
+
+def test_parking_off_or_opted_out_changes_nothing() -> None:
+ seen = NOW - 30 * DAY_MS
+ assert parking_candidates([_activity()], seen_ms=seen, now_ms=NOW, days=0)[0] == []
+ assert (
+ parking_candidates([_activity()], seen_ms=seen, now_ms=NOW, days=7, never_ask=True)[0] == []
+ )
+
+
+def test_without_any_look_the_oldest_unread_result_starts_the_window() -> None:
+ young = _activity(result_ms=tuple(NOW - d * DAY_MS for d in (3, 2, 1)))
+ assert parking_candidates([young], seen_ms=0, now_ms=NOW, days=7)[0] == []
+ old = _activity(result_ms=tuple(NOW - d * DAY_MS for d in (8, 5, 1)))
+ assert parking_candidates([old], seen_ms=0, now_ms=NOW, days=7)[0] == ["a"]
+
+
+# ── the run-time check against real stores ───────────────────────────────────
+
+
+class _Scheduler:
+ def __init__(self, store: TaskStore) -> None:
+ self.store = store
+
+ async def pause(self, task_id: str) -> None:
+ row = await self.store.get(task_id)
+ if row and row["state"] == "running":
+ raise RuntimeError("task is running")
+ await self.store.update_state(task_id, "paused")
+
+ async def resume(self, task_id: str) -> None:
+ await self.store.update_state(task_id, "scheduled")
+
+
+async def world(tmp_path: Path):
+ society = SocietyStore(tmp_path / "society.db")
+ await society.open()
+ tasks = TaskStore(tmp_path / "tasks.db")
+ await tasks.init()
+ agent, _ = await Roster(society).create(name="Scout", title="Researcher")
+ scheduler = _Scheduler(tasks)
+ chat_events: list[dict[str, Any]] = []
+ chat = SimpleNamespace(
+ store=SimpleNamespace(list_events=lambda session_id, tail=None: list(chat_events))
+ )
+ runtime = SimpleNamespace(
+ store=society,
+ task_services=lambda: (tasks, scheduler),
+ chat_service=lambda: chat,
+ )
+ try:
+ yield SimpleNamespace(
+ society=society,
+ tasks=tasks,
+ agent=agent,
+ scheduler=scheduler,
+ runtime=runtime,
+ chat_events=chat_events,
+ )
+ finally:
+ await tasks.close()
+ await society.close()
+
+
+async def _routine(
+ world: Any, schedule: dict[str, Any], *, results: int = 3, manual: bool = False
+) -> str:
+ spec = build_task_spec(world.agent, title="Digest", prompt="Summarize.", schedule=schedule)
+ task_id = await world.tasks.insert(spec)
+ for _ in range(results):
+ if manual:
+ await world.tasks.append_step(task_id, "log", {"event": "run_now"})
+ await world.tasks.append_step(task_id, "log", {"event": "run_started"})
+ await world.tasks.append_step(task_id, "log", {"event": "run_completed"})
+ return task_id
+
+
+def _now() -> int:
+ return int(time.time() * 1000)
+
+
+async def _settle() -> None:
+ for task in list(routine_parking._PENDING.values()):
+ await asyncio.wait_for(task, timeout=5)
+
+
+async def test_a_firing_routine_parks_the_agents_unread_routines(world: Any) -> None:
+ daily = {"kind": "calendar", "local_time": "08:00", "timezone": "Europe/Berlin"}
+ firing = await _routine(world, daily)
+ sibling = await _routine(world, {"kind": "every", "interval_seconds": 3600})
+ hook = await _routine(world, {"kind": "webhook"})
+ await mark_seen(world.society, world.agent.agent_id, now_ms=_now() - 8 * DAY_MS)
+ await world.tasks.update_state(firing, "running")
+
+ with pytest.raises(RoutineParked) as caught:
+ await maybe_park(world.runtime, world.agent, firing, now_ms=_now() + 1000)
+ assert caught.value.code == "away_parked"
+
+ assert (await world.tasks.get(sibling))["state"] == "paused"
+ assert (await world.tasks.get(hook))["state"] == "scheduled"
+ # The firing routine pauses once its skipped run has settled.
+ await world.tasks.update_state(firing, "scheduled")
+ await _settle()
+ assert (await world.tasks.get(firing))["state"] == "paused"
+ steps = [s["payload"] for s in (await world.tasks.get(sibling))["steps"]]
+ assert {"event": "parked", "reason": "away", "days": 7, "unread": 6} in steps
+
+ state = await load_state(world.society, world.agent.agent_id)
+ assert state.banner and sorted(state.parked_ids) == sorted([firing, sibling])
+
+ # Keep running: both come back, a new away period starts, the banner closes.
+ await apply_choice(
+ world.society, world.tasks, world.scheduler, world.agent.agent_id, "keep_running"
+ )
+ assert (await world.tasks.get(firing))["state"] == "scheduled"
+ assert (await world.tasks.get(sibling))["state"] == "scheduled"
+ after = await load_state(world.society, world.agent.agent_id)
+ assert not after.banner and after.parked_ids == [] and after.seen_ms > 0
+
+
+async def test_a_run_the_person_started_is_never_parked(world: Any) -> None:
+ task = await _routine(world, {"kind": "every", "interval_seconds": 3600})
+ await mark_seen(world.society, world.agent.agent_id, now_ms=_now() - 8 * DAY_MS)
+ with started_by_user():
+ await maybe_park(world.runtime, world.agent, task, now_ms=_now() + 1000)
+ assert (await world.tasks.get(task))["state"] == "scheduled"
+
+
+async def test_a_routine_the_person_just_ran_by_hand_keeps_running(world: Any) -> None:
+ task = await _routine(world, {"kind": "every", "interval_seconds": 3600})
+ await world.tasks.append_step(task, "log", {"event": "run_now"})
+ await world.tasks.append_step(task, "log", {"event": "run_started"})
+ await world.tasks.append_step(task, "log", {"event": "run_completed"})
+ await mark_seen(world.society, world.agent.agent_id, now_ms=_now() - 8 * DAY_MS)
+ await maybe_park(world.runtime, world.agent, task, now_ms=_now() + 1000)
+ assert (await world.tasks.get(task))["state"] == "scheduled"
+
+
+async def test_writing_to_the_agent_counts_as_looking(world: Any) -> None:
+ task = await _routine(world, {"kind": "every", "interval_seconds": 3600})
+ await mark_seen(world.society, world.agent.agent_id, now_ms=_now() - 8 * DAY_MS)
+ # A teammate's message does not count; the person's own does.
+ world.chat_events.append(
+ {"kind": "user_message", "ts_ms": _now(), "payload": {"text": "hi", "author": {"id": "x"}}}
+ )
+ with pytest.raises(RoutineParked):
+ await maybe_park(world.runtime, world.agent, task, now_ms=_now() + 1000)
+ await apply_choice(
+ world.society, world.tasks, world.scheduler, world.agent.agent_id, "keep_running"
+ )
+ state = await load_state(world.society, world.agent.agent_id)
+ state.seen_ms = _now() - 8 * DAY_MS
+ await routine_parking.save_state(world.society, world.agent.agent_id, state)
+ world.chat_events.append({"kind": "user_message", "ts_ms": _now(), "payload": {"text": "hi"}})
+ await maybe_park(world.runtime, world.agent, task, now_ms=_now() + 1000)
+ assert (await world.tasks.get(task))["state"] == "scheduled"
+
+
+async def test_never_ask_and_the_off_setting_stop_parking(world: Any) -> None:
+ task = await _routine(world, {"kind": "every", "interval_seconds": 3600})
+ await apply_choice(
+ world.society, world.tasks, world.scheduler, world.agent.agent_id, "never_ask"
+ )
+ state = await load_state(world.society, world.agent.agent_id)
+ state.seen_ms = _now() - 8 * DAY_MS
+ await routine_parking.save_state(world.society, world.agent.agent_id, state)
+ await maybe_park(world.runtime, world.agent, task, now_ms=_now() + 1000)
+ assert (await world.tasks.get(task))["state"] == "scheduled"
+
+ await apply_choice(
+ world.society, world.tasks, world.scheduler, world.agent.agent_id, "ask_again"
+ )
+ await save_days(world.society, 0)
+ await maybe_park(world.runtime, world.agent, task, now_ms=_now() + 1000)
+ assert (await world.tasks.get(task))["state"] == "scheduled"
+
+
+async def test_keep_paused_closes_the_banner_and_one_park_per_away_period(world: Any) -> None:
+ task = await _routine(world, {"kind": "every", "interval_seconds": 3600})
+ other = await _routine(world, {"kind": "every", "interval_seconds": 7200})
+ await mark_seen(world.society, world.agent.agent_id, now_ms=_now() - 8 * DAY_MS)
+ await world.tasks.update_state(task, "running")
+ with pytest.raises(RoutineParked):
+ await maybe_park(world.runtime, world.agent, task, now_ms=_now() + 1000)
+ await world.tasks.update_state(task, "scheduled")
+ await _settle()
+ # The person resumes one routine by hand; the open banner prevents a re-park.
+ await world.scheduler.resume(other)
+ await maybe_park(world.runtime, world.agent, other, now_ms=_now() + 2000)
+ assert (await world.tasks.get(other))["state"] == "scheduled"
+
+ state = await apply_choice(
+ world.society, world.tasks, world.scheduler, world.agent.agent_id, "keep_paused"
+ )
+ assert not state.banner
+ assert (await world.tasks.get(task))["state"] == "paused"
+
+
+async def test_a_broken_check_never_stops_the_run(world: Any) -> None:
+ async def broken(*_: Any, **__: Any) -> int:
+ raise RuntimeError("store gone")
+
+ world.runtime.store = SimpleNamespace(get_meta=broken)
+ await maybe_park(world.runtime, world.agent, "missing")
+
+
+async def test_an_unknown_choice_is_refused(world: Any) -> None:
+ with pytest.raises(ValueError):
+ await apply_choice(
+ world.society, world.tasks, world.scheduler, world.agent.agent_id, "explode"
+ )
diff --git a/tests/unit/society/test_routine_runs_routes.py b/tests/unit/society/test_routine_runs_routes.py
new file mode 100644
index 0000000000..df25124529
--- /dev/null
+++ b/tests/unit/society/test_routine_runs_routes.py
@@ -0,0 +1,170 @@
+"""The run history and away-parking routes over the real task store and scheduler."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import httpx
+import pytest
+from fastapi import FastAPI
+
+from dodaios.core.bus import EventBus
+from dodaios.society.routine_parking import load_state, save_state
+from dodaios.society.store import SocietyStore
+from dodaios.tasks.scheduler import TaskScheduler
+from dodaios.tasks.store import TaskStore
+from dodaios.ui.web.society_routes import router
+
+URL = "/api/society/agents/mail"
+BODY = {
+ "title": "Inbox",
+ "prompt": "Read the inbox.",
+ "schedule": {"type": "every", "interval_seconds": 3600},
+}
+
+
+class _Runtime:
+ def __init__(self, store: SocietyStore, chat: Any) -> None:
+ self.roster = self
+ self.store = store
+ self._chat = chat
+
+ async def ensure_started(self) -> None:
+ pass # No background society workers are needed for route tests.
+
+ async def resolve(self, agent_id: str) -> Any:
+ if agent_id not in ("mail", "other"):
+ return None
+ return SimpleNamespace(
+ agent_id=agent_id,
+ name=agent_id,
+ title="",
+ description="",
+ focus=[],
+ session_id=f"society:{agent_id}",
+ )
+
+ def chat_service(self) -> Any:
+ return self._chat
+
+
+async def api(tmp_path: Path):
+ tasks = TaskStore(tmp_path / "tasks.db")
+ await tasks.init()
+ society = SocietyStore(tmp_path / "society.db")
+ await society.open()
+ chat_events: dict[str, list[dict[str, Any]]] = {}
+ chat = SimpleNamespace(
+ store=SimpleNamespace(
+ list_events=lambda session_id, tail=None: chat_events.get(session_id, [])
+ )
+ )
+ app = FastAPI()
+ app.include_router(router)
+ app.state.society = _Runtime(society, chat)
+ app.state.task_store = tasks
+ app.state.task_scheduler = TaskScheduler(tasks, EventBus())
+ async with httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=app), base_url="http://test"
+ ) as client:
+ yield SimpleNamespace(
+ client=client,
+ tasks=tasks,
+ society=society,
+ scheduler=app.state.task_scheduler,
+ chat_events=chat_events,
+ )
+ await society.close()
+ await tasks.close()
+
+
+async def test_runs_list_newest_first_with_duration_cost_and_origin(api: Any) -> None:
+ task_id = (await api.client.post(f"{URL}/routines", json=BODY)).json()["id"]
+ log = api.tasks.append_step
+ await log(task_id, "log", {"event": "run_started"})
+ await log(task_id, "log", {"event": "routine_chat", "session_id": "old-chat"})
+ await log(task_id, "log", {"event": "run_completed", "duration_ms": 900})
+ await log(task_id, "log", {"event": "run_now"})
+ await log(task_id, "log", {"event": "run_started"})
+ await log(
+ task_id,
+ "log",
+ {
+ "event": "routine_summary",
+ "duration_ms": 1200,
+ "cost_usd": 0.02,
+ "provider": "codex-cli",
+ "model": "gpt",
+ "billed_via_key": False,
+ },
+ )
+ await log(task_id, "log", {"event": "agent_result", "text": "Two new mails."})
+ await log(task_id, "log", {"event": "run_completed", "duration_ms": 1300})
+ api.chat_events["old-chat"] = [
+ {"kind": "turn_started", "payload": {"turn_id": "t"}},
+ {"kind": "assistant_text", "payload": {"turn_id": "t", "text": "Nothing new."}},
+ {"kind": "turn_finished", "payload": {"turn_id": "t", "cost_usd": 0.01}},
+ ]
+
+ response = await api.client.get(f"{URL}/routines/{task_id}/runs")
+ assert response.status_code == 200, response.text
+ runs = response.json()["runs"]
+ assert [r["origin"] for r in runs] == ["manual", "automatic"]
+ assert runs[0]["duration_ms"] == 1200 and runs[0]["cost_usd"] == 0.02
+ assert runs[0]["summary"] == "Two new mails." and "result" not in runs[0]
+ assert runs[1]["cost_usd"] == 0.01 and runs[1]["summary"] == "Nothing new."
+
+ activity = (await api.client.get(f"{URL}/routines-activity")).json()
+ assert activity["last_runs"][task_id]["origin"] == "manual"
+ assert activity["parking"] == {
+ "enabled": True,
+ "days": 7,
+ "banner": False,
+ "parked_ids": [],
+ "parked_ms": 0,
+ "parked_days": 7,
+ "unread": 0,
+ "never_ask": False,
+ }
+
+
+async def test_runs_belong_to_their_owner(api: Any) -> None:
+ task_id = (await api.client.post(f"{URL}/routines", json=BODY)).json()["id"]
+ assert (
+ await api.client.get(f"/api/society/agents/other/routines/{task_id}/runs")
+ ).status_code == 404
+ assert (await api.client.get("/api/society/agents/nobody/routines-activity")).status_code == 404
+
+
+async def test_seen_choice_and_settings_round_trip(api: Any) -> None:
+ task_id = (await api.client.post(f"{URL}/routines", json=BODY)).json()["id"]
+ seen = (await api.client.post(f"{URL}/routines-seen")).json()
+ assert seen["ok"] and seen["seen_ms"] > 0
+
+ await api.scheduler.pause(task_id)
+ state = await load_state(api.society, "mail")
+ state.banner, state.parked_ids, state.unread = True, [task_id], 4
+ await save_state(api.society, "mail", state)
+ banner = (await api.client.get(f"{URL}/routines-activity")).json()["parking"]
+ assert banner["banner"] and banner["parked_ids"] == [task_id] and banner["unread"] == 4
+
+ answer = await api.client.post(f"{URL}/routines-parking", json={"choice": "keep_running"})
+ assert answer.status_code == 200, answer.text
+ assert answer.json()["parking"]["banner"] is False
+ assert (await api.tasks.get(task_id))["state"] == "scheduled"
+ assert (
+ await api.client.post(f"{URL}/routines-parking", json={"choice": "nope"})
+ ).status_code == 422
+
+ assert (await api.client.get("/api/society/routine-parking")).json() == {"days": 7}
+ assert (await api.client.put("/api/society/routine-parking", json={"days": 0})).json() == {
+ "days": 0
+ }
+ off = (await api.client.get(f"{URL}/routines-activity")).json()["parking"]
+ assert off["enabled"] is False
+ assert (
+ await api.client.put("/api/society/routine-parking", json={"days": 400})
+ ).status_code == 422