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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(automations): the Tasks section becomes Automations — catalogue, run now, pause, honest results
rubenluetke10-beepe3f4902a87ec
diff --git a/jarvis/brain/dispatcher.py b/jarvis/brain/dispatcher.pyindex ac39559b6c..ce1834d2b9 100644--- a/jarvis/brain/dispatcher.py+++ b/jarvis/brain/dispatcher.py@@ -38,10 +38,16 @@ class BrainDispatcher:max_tokens: int = 8192,deadline_s: float | None = None,reasoning_effort: Literal["none"] | None = None,+ tool_context: dict[str, Any] | None = None,) -> None:self._brain = brainself._tools = tools or {}self._executor = executor+ # Extra keys merged into every tool's ``ExecutionContext.config`` for+ # this dispatcher's turns (e.g. ``{"delivery": "written"}`` for a+ # scheduled task whose result is a written digest, not speech). The+ # loop's per-turn keys (output_language, voice_confirm) always win.+ self._tool_context = dict(tool_context or {})self._system_prompt = system_promptself._max_turns = max_turnsself._max_tokens_total = max_tokens_total@@ -74,6 +80,7 @@ class BrainDispatcher:max_tokens=self._max_tokens,deadline_s=self._deadline_s,reasoning_effort=self._reasoning_effort,+ tool_context=self._tool_context,)def set_tools(self, tools: dict[str, Tool]) -> None:@@ -141,6 +148,7 @@ class BrainDispatcher:max_tokens=self._max_tokens,deadline_s=self._deadline_s,reasoning_effort=self._reasoning_effort,+ tool_context=self._tool_context,)return await loop.run(messages,diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.pyindex 89b71c33b8..9de65f8416 100644--- a/jarvis/brain/manager.py+++ b/jarvis/brain/manager.py@@ -12681,9 +12681,82 @@ class BrainManager:Unknown grants (e.g. a plugin that isn't connected) are silentlyskipped — the task runs with whatever of its allowlist is live.++ A grant is matched by :func:`jarvis.tasks.templates.grant_matches`:+ exact name, or the plugin prefix of a bridged MCP tool — the grant+ ``github`` covers every ``github/<tool>``. (Exact matching alone left+ a template with a ``github`` grant running with ZERO tools.)++ A grant naming one of :data:`_TASK_ONLY_TOOLS` that is NOT in the live+ (router) set is loaded from its entry point on demand: ``remember`` is+ deliberately outside ``ROUTER_TOOLS`` (ADR-0011), yet a scheduled+ task that was granted it must be able to store what it found. The+ instance is cached per manager and only ever reaches the task's own+ dispatcher — never the router surface."""- allow = set(allowed_tools)- return {name: tool for name, tool in self._tools.items() if name in allow}+ from jarvis.tasks.templates import grant_matches # noqa: PLC0415++ if not allowed_tools:+ return {}+ selected = {+ name: tool for name, tool in self._tools.items()+ if any(grant_matches(grant, name) for grant in allowed_tools)+ }+ for grant in allowed_tools:+ if grant in selected or grant not in _TASK_ONLY_TOOLS:+ continue+ tool = self._load_task_only_tool(grant)+ if tool is not None:+ selected[grant] = tool+ return selected++ def _load_task_only_tool(self, name: str) -> Tool | None:+ """Instantiate (once) an entry-point tool that only scheduled tasks+ may use. Returns ``None`` — and logs why — when it cannot be built,+ so the task runs with the rest of its allowlist."""+ cache: dict[str, Tool | None] = self.__dict__.setdefault("_task_only_tool_cache", {})+ if name in cache:+ return cache[name]+ from importlib.metadata import entry_points # noqa: PLC0415++ tool: Tool | None = None+ for ep in entry_points(group="jarvis.tool"):+ if ep.name != name:+ continue+ try:+ tool = ep.load()()+ except Exception as exc: # noqa: BLE001 — a broken tool must not kill the task+ log.warning("task-only tool %r failed to load: %s", name, exc)+ tool = None+ break+ else:+ log.warning("task-only tool %r has no entry point", name)+ cache[name] = tool+ return tool++ def _task_fallback_provider(self) -> str | None:+ """The one provider a scheduled task retries on when the active brain+ rejects the turn with a credential/credit/rate error.++ A different credential FAMILY than the active provider (AP-22: a+ same-family fallback is a brick), registered, not dead-listed this+ session, with a fast model and a portable credential on this box.+ The persistent active provider is never touched (user-only lock).+ """+ active = self._active_name+ active_family = self._tool_model_family(active)+ available = set(self._registry.available())+ for name in _TASK_FALLBACK_ORDER:+ if name == active or name not in available or name in self._dead_providers:+ continue+ if self._tool_model_family(name) == active_family:+ continue+ if not self._fast_model(name):+ continue+ if not self._tool_model_credential_ready(name):+ continue+ return name+ return Noneasync def run_task(self,@@ -12703,24 +12776,58 @@ class BrainManager:actions still hit the approval gate (which, with no human present,means they block until the unattended-approval wave wires Option B).+ Provider fallback (2026-08-24): when the active provider rejects the+ turn with a credential / credit / rate-limit error (401/402/403/429+ — the same classes the chat path dead-lists or cools down), the SAME+ turn is retried exactly once on the next provider of a different+ credential family (:meth:`_task_fallback_provider`). Any other error,+ or a second failure, propagates so the runner records it in+ ``last_error``. The persistent active provider is never switched.+Returns the final assistant text."""- name = self._active_name- if model_tier == "deep":- model = self._deep_model(name) or self._fast_model(name)- intent = "deep"- else:- # "fast" and "auto" both resolve to the fast model — the cheapest- # correct default for an unattended background turn.- model = self._fast_model(name)- intent = "fast"- brain = self._get_brain(name, model)+ intent = "deep" if model_tier == "deep" else "fast"tools = self._select_task_tools(allowed_tools)- dispatcher = self._build_dispatcher(brain, tools_override=tools)- agg = await dispatcher.dispatch(- prompt, history=[], intent_level=intent, trace_id=trace_id,- )- return agg.text or ""+ attempts: list[str] = [self._active_name]+ failures: list[str] = []+ while attempts:+ name = attempts.pop(0)+ if intent == "deep":+ model = self._deep_model(name) or self._fast_model(name)+ else:+ # "fast" and "auto" both resolve to the fast model — the+ # cheapest correct default for an unattended background turn.+ model = self._fast_model(name)+ try:+ brain = self._get_brain(name, model)+ dispatcher = self._build_dispatcher(+ brain, tools_override=tools,+ tool_context={"delivery": "written"},+ )+ agg = await dispatcher.dispatch(+ prompt, history=[], intent_level=intent, trace_id=trace_id,+ )+ return agg.text or ""+ except Exception as exc:+ kind = _classify_provider_error(str(exc), default="call_fail")+ if kind not in _TASK_FALLBACK_KINDS:+ raise+ failures.append(f"{name}: {_short_provider_error(exc)}")+ if failures and len(failures) == 1:+ fallback = self._task_fallback_provider()+ if fallback is not None:+ log.warning(+ "run_task: %s rejected the turn (%s) — retrying once on %s",+ name, kind, fallback,+ )+ attempts.append(fallback)+ continue+ log.warning(+ "run_task: %s rejected the turn (%s) and no cross-family "+ "fallback provider is usable", name, kind,+ )+ raise+ raise RuntimeError("all brain providers failed: " + "; ".join(failures))def snapshot(self) -> dict[str, Any]:return {@@ -12735,6 +12842,32 @@ class BrainManager:}+#: Entry-point tools a scheduled task may be granted although they are NOT+#: router tools (ADR-0011 keeps the router a pure dispatcher). Loaded lazily+#: by ``_select_task_tools`` for the task's own dispatcher only. Never a+#: spawn tool (AP-5/AP-14).+_TASK_ONLY_TOOLS: frozenset[str] = frozenset({"remember"})++#: Error classes that make a scheduled task retry once on another provider+#: family: the dead-list kinds (missing/bad key, 402 credits) plus a rate limit.+_TASK_FALLBACK_KINDS: frozenset[str] = frozenset(+ {"missing_key", "account_blocked", "bad_key", "rate_limit"}+)++#: Cross-provider order for the scheduled-task fallback (mirrors the chat+#: path's ``cross_order``; family-filtered at runtime).+_TASK_FALLBACK_ORDER: tuple[str, ...] = (+ "gemini", "claude-api", "openai", "openrouter", "grok", "nvidia",+)+++def _short_provider_error(exc: Exception) -> str:+ """One readable line for ``last_error`` / the fallback summary — the+ exception class and the first 160 characters of its message."""+ msg = " ".join(str(exc).split())+ return f"{type(exc).__name__}: {msg[:160]}" if msg else type(exc).__name__++def _is_rate_limit_exc(exc: Exception) -> bool:"""Heuristic: 429 / rate_limit_error / status_code=429."""msg = str(exc).lower()diff --git a/jarvis/brain/tool_use_loop.py b/jarvis/brain/tool_use_loop.pyindex 6cd1bd8f2c..0f08a1cfd0 100644--- a/jarvis/brain/tool_use_loop.py+++ b/jarvis/brain/tool_use_loop.py@@ -581,10 +581,14 @@ class ToolUseLoop:max_tokens: int = 8192,deadline_s: float | None = None,reasoning_effort: Literal["none"] | None = None,+ tool_context: dict[str, Any] | None = None,) -> None:self._brain = brainself._tools = toolsself._executor = executor+ # Caller-supplied keys for every tool's ``ExecutionContext.config``+ # (see BrainDispatcher.tool_context). Per-turn keys set below win.+ self._tool_context = dict(tool_context or {})# Canonical form → registered name, for hyphen/underscore-tolerant# lookup. A canonical collision (two registered tools differing only in# separator/case) maps to None: an inexact name must never guess@@ -1282,6 +1286,7 @@ class ToolUseLoop:tool, tool_args,user_utterance=user_utterance,config_snapshot={+ **self._tool_context,"output_language": out_lang,"voice_confirm": voice_confirm,},diff --git a/jarvis/plugins/tool/search_web.py b/jarvis/plugins/tool/search_web.pyindex 1c0b0952b5..9a375eda6e 100644--- a/jarvis/plugins/tool/search_web.py+++ b/jarvis/plugins/tool/search_web.py@@ -65,6 +65,30 @@ _ANSWER_INSTRUCTION: Final[str] = ("answer the question, say that briefly instead of reciting them.")+# The written counterpart: a scheduled digest (Automations) or any other+# background turn whose result is READ, not heard. Sources and dates are+# welcome there; the raw-hit dump is still not.+_WRITTEN_ANSWER_INSTRUCTION: Final[str] = (+ "These 'results' are RAW web hits (title/snippet/url) for retrieval only. "+ "Answer the actual question in writing using the relevant facts from "+ "them; you may name a source or a date where it adds credibility. Do not "+ "paste the hits as a list. If the hits do not actually answer the "+ "question, say so briefly instead of reciting them."+)+++def _answer_instruction_for(ctx: ExecutionContext) -> str:+ """Spoken by default; written when the turn declares written delivery+ (``ExecutionContext.config["delivery"] == "written"`` — set by+ ``BrainManager.run_task`` for scheduled tasks). Anything else, including a+ context without the key, keeps the historical spoken behaviour."""+ try:+ delivery = (ctx.config or {}).get("delivery")+ except Exception: # noqa: BLE001 — a foreign ctx shape must not break search+ delivery = None+ return _WRITTEN_ANSWER_INSTRUCTION if delivery == "written" else _ANSWER_INSTRUCTION++_WEATHER_INTENT_RE = re.compile(r"\b(weather|forecast|wetter\w*|wettervorhersage|vorhersage|"r"temperatur\w*|temperature|tiempo|clima)\b",@@ -343,7 +367,7 @@ class SearchWebTool:output={"query": query,"results": weather,- "answer_instruction": _ANSWER_INSTRUCTION,+ "answer_instruction": _answer_instruction_for(ctx),},)@@ -390,5 +414,5 @@ class SearchWebTool:elif outcome.status == "ok" and outcome.results:# Steer the brain to synthesize a short spoken answer rather than# reading the raw hits aloud (live forensic 2026-06-28, Turn 4).- output["answer_instruction"] = _ANSWER_INSTRUCTION+ output["answer_instruction"] = _answer_instruction_for(ctx)return ToolResult(success=True, output=output)diff --git a/jarvis/tasks/approval_bridge.py b/jarvis/tasks/approval_bridge.pyindex a003775bbf..1dba2d1927 100644--- a/jarvis/tasks/approval_bridge.py+++ b/jarvis/tasks/approval_bridge.py@@ -73,9 +73,10 @@ class TaskAutoApprover:@staticmethoddef _tool_is_granted(tool_name: str, granted: frozenset[str]) -> bool:"""A tool is covered if its name (native tool) or its plugin prefix- (MCP tools are namespaced ``plugin/tool``) is in the grant set.+ (MCP tools are namespaced ``plugin/tool``) is in the grant set — the+ same rule the brain's tool allowlist uses (``grant_matches``), so a+ tool the turn can SEE is exactly a tool the grant can pre-authorize."""- if tool_name in granted:- return True- prefix = tool_name.split("/", 1)[0]- return prefix in granted+ from jarvis.tasks.templates import grant_matches # noqa: PLC0415++ return any(grant_matches(grant, tool_name) for grant in granted)diff --git a/jarvis/tasks/runner.py b/jarvis/tasks/runner.pyindex f11f6ae52c..6f5b2bbad0 100644--- a/jarvis/tasks/runner.py+++ b/jarvis/tasks/runner.py@@ -31,6 +31,7 @@ from __future__ import annotationsimport asyncioimport contextlibimport logging+import reimport timefrom collections.abc import Iterablefrom typing import TYPE_CHECKING, Any, Protocol@@ -172,7 +173,7 @@ class TaskRunner:returnexcept Exception as exc: # noqa: BLE001duration_ms = int((time.perf_counter() - start) * 1000)- error_msg = f"{type(exc).__name__}: {exc}"+ error_msg = readable_error(exc)await self._store.update_state(task_id, "failed", error=error_msg)await self._store.append_step(task_id, "log",{"event": "error", "message": error_msg})@@ -614,6 +615,35 @@ def _targets_computer_use(harness_name: str) -> bool:return harness_name == HARNESS_NAME+_ERROR_MESSAGE_RE = re.compile(r"""['"]message['"]\s*:\s*['"]([^'"]{1,300})['"]""")+_ERROR_CODE_RE = re.compile(r"\b(?:Error code|status(?: code)?)[:=]?\s*(\d{3})\b", re.IGNORECASE)+_LAST_ERROR_MAX_CHARS = 400+++def readable_error(exc: BaseException) -> str:+ """The one line ``last_error`` shows in the Runs tab.++ Provider SDK errors stringify to a class name plus a dumped JSON body+ (``APIStatusError: Error code: 402 - {'error': {'message': 'Insufficient+ credits. Add more using …', 'code': 402, 'metadata': {…}}}``). A reader+ wants the HTTP code and the human message, not the dict: this pulls both+ out when present, collapses whitespace, and caps the length. Anything+ else keeps the ``Type: message`` form the runner always recorded.+ """+ raw = " ".join(str(exc).split())+ name = type(exc).__name__+ if not raw:+ return name+ code = _ERROR_CODE_RE.search(raw)+ message = _ERROR_MESSAGE_RE.search(raw)+ if message:+ body = message.group(1).strip()+ text = f"{name}: {code.group(1)} — {body}" if code else f"{name}: {body}"+ else:+ text = f"{name}: {raw}"+ return text[:_LAST_ERROR_MAX_CHARS]++class _SafeDict(dict):"""``str.format_map`` backing dict that leaves unknown ``{key}`` untouched."""diff --git a/jarvis/tasks/scheduler.py b/jarvis/tasks/scheduler.pyindex 444b6b450e..745b2ac8ff 100644--- a/jarvis/tasks/scheduler.py+++ b/jarvis/tasks/scheduler.py@@ -28,7 +28,7 @@ from typing import TYPE_CHECKING, Any, Protocolfrom jarvis.core.bus import EventBusfrom jarvis.core.events import Event, TaskScheduled-from jarvis.tasks.schema import TaskSpec+from jarvis.tasks.schema import PAUSABLE_TRIGGER_TYPES, TERMINAL_STATES, TaskSpecif TYPE_CHECKING:from jarvis.control.cancel import CancelToken@@ -39,6 +39,15 @@ if TYPE_CHECKING:log = logging.getLogger(__name__)+class TaskNotFound(LookupError):+ """No task row with that id."""+++class TaskStateConflict(RuntimeError):+ """The requested transition is not allowed from the task's current+ state (or for its trigger type). Maps onto HTTP 409."""++class _Dispatchable(Protocol):async def run(self, task_id: str, *, trigger_event: dict[str, Any] | None = None@@ -138,6 +147,123 @@ class TaskScheduler:self._wakeup.set()return task_id+ async def run_now(self, task_id: str) -> None:+ """Run the task's action NOW, out of band — the schedule is untouched.++ A recurring (``every``) task keeps its heap entry and its+ ``due_at_ns``; the runner hands it back as ``scheduled`` afterwards,+ exactly like a regular firing minus the re-arm. A paused recurring+ task is restored to ``paused`` once the run settles. A one-shot task+ (``after_delay``/``at_time``) is consumed by the run: it leaves the+ heap so the scheduler cannot fire it a second time.++ Raises :class:`TaskNotFound` for an unknown id and+ :class:`TaskStateConflict` while the task is already ``running`` or+ already terminal.+ """+ task = await self._store.get(task_id)+ if task is None:+ raise TaskNotFound(task_id)+ state = task["state"]+ if state == "running":+ raise TaskStateConflict(f"task is already running (state={state})")+ if state in TERMINAL_STATES:+ raise TaskStateConflict(f"task is already final (state={state})")+ if self._runner is None:+ raise TaskStateConflict("no runner attached — nothing can execute the task")+ spec = await self._store.get_spec(task_id)+ if spec is None:+ raise TaskNotFound(task_id)+ if spec.trigger.type in ("after_delay", "at_time"):+ self._remove_from_memory(task_id)+ restore_state = "paused" if state == "paused" else None+ await self._store.append_step(task_id, "log", {"event": "run_now"})+ task_obj = asyncio.create_task(+ self._run_now_and_settle(task_id, restore_state),+ name=f"task-run-now-{task_id}",+ )+ self._runner_tasks.add(task_obj)+ task_obj.add_done_callback(self._runner_tasks.discard)++ async def _run_now_and_settle(+ self, task_id: str, restore_state: str | None,+ ) -> None:+ await self._safe_run(task_id, None)+ if restore_state is None:+ return+ # The runner leaves a recurring task as `scheduled` (or `failed`);+ # a manual run must not silently switch a paused automation back on.+ try:+ task = await self._store.get(task_id)+ if task is not None and task["state"] not in ("running", "cancelled"):+ await self._store.update_state(task_id, restore_state) # type: ignore[arg-type]+ except Exception: # noqa: BLE001+ log.exception("run_now: could not restore state=%s for task=%s",+ restore_state, task_id)++ async def pause(self, task_id: str) -> None:+ """Switch a recurring/``on_event`` task off: it leaves the heap and+ the event index and its state becomes ``paused``. Idempotent.++ Raises :class:`TaskNotFound` / :class:`TaskStateConflict` (one-shot+ trigger, running, or terminal).+ """+ task = await self._store.get(task_id)+ if task is None:+ raise TaskNotFound(task_id)+ if task["trigger_type"] not in PAUSABLE_TRIGGER_TYPES:+ raise TaskStateConflict(+ f"only recurring tasks can be paused (trigger={task['trigger_type']})"+ )+ state = task["state"]+ if state == "paused":+ return+ if state == "running":+ raise TaskStateConflict("task is running — wait for it to finish")+ if state in TERMINAL_STATES:+ raise TaskStateConflict(f"task is already final (state={state})")+ self._remove_from_memory(task_id)+ await self._store.update_state(task_id, "paused")+ await self._store.append_step(task_id, "log", {"event": "paused"})+ self._wakeup.set()++ async def resume(self, task_id: str, *, now_ns: int | None = None) -> int | None:+ """Switch a paused task back on and re-register it for its NEXT+ occurrence. Returns the new ``due_at_ns`` (``None`` for ``on_event``).++ An ``every`` task anchored with ``start_at`` keeps its wall-clock+ anchor: the next due time is ``start_at + k * interval``, the first+ such moment strictly in the future. Without an anchor it is+ ``now + interval``.+ """+ task = await self._store.get(task_id)+ if task is None:+ raise TaskNotFound(task_id)+ if task["state"] != "paused":+ raise TaskStateConflict(f"task is not paused (state={task['state']})")+ spec = await self._store.get_spec(task_id)+ if spec is None:+ raise TaskNotFound(task_id)+ now = time.time_ns() if now_ns is None else now_ns+ due: int | None = None+ if spec.trigger.type == "every":+ due = next_every_due_ns(spec, now)+ await self._store.set_next_due(task_id, due)+ await self._store.update_state(task_id, "scheduled")+ await self._store.append_step(task_id, "log", {"event": "resumed"})+ self._register_in_memory(spec, task_id, stored_due_at_ns=due)+ self._wakeup.set()+ return due++ def _remove_from_memory(self, task_id: str) -> None:+ """Drop a task from the heap, the event index and the known set."""+ self._heap = [(due, tid) for (due, tid) in self._heap if tid != task_id]+ heapq.heapify(self._heap)+ for ids in self._on_event_index.values():+ ids.discard(task_id)+ self._firings_left.pop(task_id, None)+ self._known.discard(task_id)+async def cancel_task(self, task_id: str, reason: str = "user_cancel") -> bool:"""Marks a task as ``cancelled`` if it isn't already terminal.@@ -151,18 +277,13 @@ class TaskScheduler:task = await self._store.get(task_id)if task is None:return False- if task["state"] in ("completed", "failed", "cancelled", "interrupted"):+ if task["state"] in TERMINAL_STATES:return Falserunning_token = self._running_tokens.get(task_id)if running_token is not None:running_token.cancel(reason)- # Remove from heap (linear scan, small enough — a typical queue is < 100).- self._heap = [(due, tid) for (due, tid) in self._heap if tid != task_id]- heapq.heapify(self._heap)- # Remove from the event index- for ids in self._on_event_index.values():- ids.discard(task_id)- self._known.discard(task_id)+ # Linear scan over the heap — small enough, a typical queue is < 100.+ self._remove_from_memory(task_id)await self._store.update_state(task_id, "cancelled", error=reason)await self._store.append_step(task_id, "log", {"event": "cancelled", "reason": reason})@@ -446,6 +567,35 @@ class TaskScheduler:await asyncio.wait(tasks, timeout=2.0)+# ----------------------------------------------------------------------+# Recurring schedule arithmetic+# ----------------------------------------------------------------------++def next_every_due_ns(spec: TaskSpec, now_ns: int) -> int:+ """Next due time of an ``every`` trigger strictly after ``now_ns``.++ ``start_at``-anchored tasks stay on their wall-clock grid+ (``start_at + k * interval``); unanchored ones fire one interval from now.+ A malformed ``start_at`` degrades to the unanchored rule.+ """+ trig = spec.trigger+ if trig.type != "every":+ raise ValueError(f"not a recurring trigger: {trig.type}")+ interval_ns = int(trig.interval_seconds * 1e9)+ start_at = trig.start_at+ if start_at:+ try:+ anchor = parse_iso_timestamp_to_ns(start_at)+ except ValueError:+ anchor = None+ if anchor is not None:+ if anchor > now_ns:+ return anchor+ k = (now_ns - anchor) // interval_ns + 1+ return anchor + k * interval_ns+ return now_ns + interval_ns++# ----------------------------------------------------------------------# Event passthrough + fire-once dedup helpers# ----------------------------------------------------------------------diff --git a/jarvis/tasks/schema.py b/jarvis/tasks/schema.pyindex 7d3948c03e..3394c53fc0 100644--- a/jarvis/tasks/schema.py+++ b/jarvis/tasks/schema.py@@ -166,6 +166,7 @@ class RetryPolicy(BaseModel):TaskState = Literal["pending", # never scheduled yet (e.g. created_from_api, waiting for hydrate)"scheduled", # in the heap or waiting for an event+ "paused", # recurring/on_event task the user switched off (resumable)"running", # the TaskRunner is currently executing it"completed", # finished successfully"failed", # given up after max_attempts@@ -175,10 +176,15 @@ TaskState = Literal[TASK_STATES: tuple[str, ...] = (- "pending", "scheduled", "running", "completed",+ "pending", "scheduled", "paused", "running", "completed","failed", "cancelled", "interrupted",)+#: States a task never leaves on its own (hard-delete is allowed here).+TERMINAL_STATES: tuple[str, ...] = ("completed", "failed", "cancelled", "interrupted")+#: Trigger types that can be paused/resumed — the recurring ones.+PAUSABLE_TRIGGER_TYPES: tuple[str, ...] = ("every", "on_event")+class TaskSpec(BaseModel):"""The description of a scheduled task — persisted as JSON indiff --git a/jarvis/tasks/schema.sql b/jarvis/tasks/schema.sqlindex 991770e829..a2d21d15e9 100644--- a/jarvis/tasks/schema.sql+++ b/jarvis/tasks/schema.sql@@ -13,7 +13,7 @@ CREATE TABLE IF NOT EXISTS tasks (trace_id TEXT NOT NULL,spec_json TEXT NOT NULL, -- serialized TaskSpec (Pydantic)state TEXT NOT NULL CHECK(state IN (- 'pending','scheduled','running','completed',+ 'pending','scheduled','paused','running','completed','failed','cancelled','interrupted')),trigger_type TEXT NOT NULL CHECK(trigger_type IN ('after_delay','at_time','on_event','every')),diff --git a/jarvis/tasks/store.py b/jarvis/tasks/store.pyindex c1f6796305..8be7ed0772 100644--- a/jarvis/tasks/store.py+++ b/jarvis/tasks/store.py@@ -15,25 +15,27 @@ from __future__ import annotationsimport jsonimport time+from collections.abc import Sequencefrom pathlib import Pathfrom typing import Anyimport aiosqlite-from .schema import TaskSpec, TaskState+from .schema import TERMINAL_STATES, TaskSpec, TaskStateSCHEMA_FILE = Path(__file__).parent / "schema.sql"-# Rebuild target for the legacy trigger_type-CHECK migration. Mirrors the-# `tasks` table in schema.sql but as `tasks_new` and with `every` in the-# CHECK. Kept here (not in schema.sql) because it only runs during migration.+# Rebuild target for the CHECK-constraint migrations (trigger_type gained+# `every` 2026-06-17, state gained `paused` 2026-08-24). Mirrors the `tasks`+# table in schema.sql but as `tasks_new`. Kept here (not in schema.sql)+# because it only runs during migration._TASKS_REBUILD_SQL = """CREATE TABLE tasks_new (id TEXT PRIMARY KEY,trace_id TEXT NOT NULL,spec_json TEXT NOT NULL,state TEXT NOT NULL CHECK(state IN (- 'pending','scheduled','running','completed',+ 'pending','scheduled','paused','running','completed','failed','cancelled','interrupted')),trigger_type TEXT NOT NULL CHECK(trigger_type IN ('after_delay','at_time','on_event','every')),@@ -87,6 +89,8 @@ class TaskStore:# (added 2026-06-17). CREATE TABLE IF NOT EXISTS never alters an# existing table, so this explicit migration is required.await self._migrate_trigger_type_check()+ # Same dance for the state CHECK, which predates `paused` (2026-08-24).+ await self._migrate_state_check()async def close(self) -> None:if self._conn is not None:@@ -115,6 +119,31 @@ class TaskStore:no-op once the live CHECK already mentions ``'every'`` (or has noCHECK at all)."""+ table_sql = await self._tasks_table_sql()+ if table_sql is None:+ return+ if "trigger_type" not in table_sql or "CHECK" not in table_sql:+ return # loose schema — nothing to migrate+ if "'every'" in table_sql:+ return # fresh schema or already migrated+ await self._rebuild_tasks_table()++ async def _migrate_state_check(self) -> None:+ """Rebuild ``tasks`` if its state CHECK predates ``paused``.++ Mirrors :meth:`_migrate_trigger_type_check`; without it, pausing an+ automation on a DB created before 2026-08-24 fails the CHECK.+ """+ table_sql = await self._tasks_table_sql()+ if table_sql is None:+ return+ if "state" not in table_sql or "CHECK" not in table_sql:+ return # loose schema — nothing to migrate+ if "'paused'" in table_sql:+ return # fresh schema or already migrated+ await self._rebuild_tasks_table()++ async def _tasks_table_sql(self) -> str | None:conn = self._require_conn()cur = await conn.execute("SELECT sql FROM sqlite_master WHERE type='table' AND name='tasks'"@@ -122,13 +151,12 @@ class TaskStore:row = await cur.fetchone()await cur.close()if row is None:- return- table_sql = row["sql"] or ""- if "trigger_type" not in table_sql or "CHECK" not in table_sql:- return # loose schema — nothing to migrate- if "'every'" in table_sql:- return # fresh schema or already migrated+ return None+ return str(row["sql"] or "")+ async def _rebuild_tasks_table(self) -> None:+ """create-copy-drop-rename ``tasks`` onto :data:`_TASKS_REBUILD_SQL`."""+ conn = self._require_conn()await conn.execute("PRAGMA foreign_keys = OFF")try:await conn.execute("BEGIN")@@ -262,12 +290,20 @@ class TaskStore:if state == "running":sets.append("started_at_ns = ?")params.append(now_ns)- if state in ("completed", "failed", "cancelled", "interrupted"):+ # A run has finished when the state is terminal — or when a recurring+ # task hands back a ``result`` on its way to ``scheduled``. Either way+ # ``finished_at_ns`` marks the end of the LAST run, and a successful+ # result clears the error of a previous failed run so the list view's+ # ``last_run_state`` reflects the latest run only.+ finished = state in TERMINAL_STATES or result is not None+ if finished:sets.append("finished_at_ns = ?")params.append(now_ns)if error is not None:sets.append("last_error = ?")params.append(error)+ elif result is not None:+ sets.append("last_error = NULL")if result is not None:sets.append("result_json = ?")params.append(json.dumps(result, ensure_ascii=False))@@ -315,12 +351,16 @@ class TaskStore:*,limit: int = 100,) -> list[dict[str, Any]]:- """Returns a list of task rows (without steps), filtered by state."""+ """Returns a list of task rows (without steps), filtered by state.++ ``spec_json`` is included so the API can derive spec-level summary+ fields (tags, created_by, interval) without a second query per row.+ """conn = self._require_conn()sql = ("SELECT id, trace_id, state, trigger_type, due_at_ns, title, "- "created_at_ns, started_at_ns, finished_at_ns, attempts, last_error "- "FROM tasks"+ "created_at_ns, started_at_ns, finished_at_ns, attempts, last_error, "+ "spec_json FROM tasks")params: list[Any] = []if state_filter is not None:@@ -366,6 +406,42 @@ class TaskStore:]return task+ async def latest_agent_results(+ self, task_ids: Sequence[str] | None = None, *, max_chars: int = 400,+ ) -> dict[str, str]:+ """``{task_id: text}`` of the newest ``agent_result`` log step per+ task, truncated to ``max_chars`` — ONE query for the whole list view,+ no per-task round trip. ``task_ids=None`` covers every task.+ """+ conn = self._require_conn()+ sql = (+ "SELECT s.task_id AS task_id, s.payload_json AS payload_json "+ "FROM task_steps s JOIN ("+ " SELECT task_id, MAX(seq) AS seq FROM task_steps"+ " WHERE kind = 'log'"+ " AND json_extract(payload_json, '$.event') = 'agent_result'"+ " GROUP BY task_id"+ ") latest ON latest.task_id = s.task_id AND latest.seq = s.seq"+ )+ params: list[Any] = []+ if task_ids is not None:+ if not task_ids:+ return {}+ placeholders = ",".join(["?"] * len(task_ids))+ sql += f" WHERE s.task_id IN ({placeholders})" # noqa: S608 — placeholders only+ params.extend(task_ids)+ cur = await conn.execute(sql, tuple(params))+ rows = await cur.fetchall()+ await cur.close()+ out: dict[str, str] = {}+ for r in rows:+ try:+ text = str(json.loads(r["payload_json"]).get("text") or "")+ except (ValueError, AttributeError):+ continue+ out[str(r["task_id"])] = text[:max_chars]+ return out+async def get_spec(self, task_id: str) -> TaskSpec | None:"""Deserializes ``spec_json`` back into a TaskSpec."""conn = self._require_conn()diff --git a/jarvis/ui/web/frontend/src/hooks/useAutomations.ts b/jarvis/ui/web/frontend/src/hooks/useAutomations.tsnew file mode 100644index 0000000000..0f8c2ba81d--- /dev/null+++ b/jarvis/ui/web/frontend/src/hooks/useAutomations.ts@@ -0,0 +1,203 @@+/**+ * Data hooks for the Automations section (react-query over `/api/tasks`).+ *+ * The list polls every 3 s, the same cadence the old Tasks view used, so a+ * countdown and a "running" dot stay honest without a socket. The template+ * catalogue is the one endpoint that may not exist yet on an older backend+ * (the routes ship with this campaign and only go live after a restart) —+ * a 404 there is reported as `unavailable`, never as an error, so the view+ * can say so inline instead of crashing.+ */+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { useUiLanguage } from "@/i18n";+import type {+ TaskDetail,+ TasksListResponse,+ TemplateSchedule,+ TemplatesResponse,+} from "@/views/automations/automationsModel";++export const TASKS_QUERY_KEY = ["tasks"] as const;+export const TEMPLATES_QUERY_KEY = ["tasks", "templates"] as const;++/** An HTTP failure with its status attached, so callers can tell a 404+ * (route not live yet) from a 409 (already running) and word the notice. */+export class ApiError extends Error {+ status: number;+ constructor(status: number, message?: string) {+ super(message ?? `HTTP ${status}`);+ this.name = "ApiError";+ this.status = status;+ }+}++async function readError(res: Response): Promise<ApiError> {+ let detail = "";+ try {+ const body = (await res.json()) as { detail?: unknown };+ if (typeof body?.detail === "string") detail = body.detail;+ } catch {+ // A non-JSON error body carries no extra message; the status is enough.+ }+ return new ApiError(res.status, detail || `HTTP ${res.status}`);+}++export async function fetchTasks(): Promise<TasksListResponse> {+ const res = await fetch("/api/tasks", { cache: "no-store" });+ if (!res.ok) throw await readError(res);+ return res.json();+}++export async function fetchTask(id: string): Promise<TaskDetail> {+ const res = await fetch(`/api/tasks/${encodeURIComponent(id)}`, { cache: "no-store" });+ if (!res.ok) throw await readError(res);+ return res.json();+}++export interface TemplatesResult extends TemplatesResponse {+ /** `true` when the backend has no catalogue route yet (pre-restart). */+ unavailable: boolean;+}++export async function fetchTemplates(locale: string): Promise<TemplatesResult> {+ const res = await fetch(`/api/tasks/templates?locale=${encodeURIComponent(locale)}`, {+ cache: "no-store",+ });+ if (res.status === 404 || res.status === 405) {+ return { templates: [], categories: [], unavailable: true };+ }+ if (!res.ok) throw await readError(res);+ const body = (await res.json()) as TemplatesResponse;+ return { ...body, unavailable: false };+}++export async function runTaskNow(id: string): Promise<void> {+ const res = await fetch(`/api/tasks/${encodeURIComponent(id)}/run`, { method: "POST" });+ if (!res.ok) throw await readError(res);+}++export async function setTaskEnabled(id: string, enabled: boolean): Promise<void> {+ const res = await fetch(`/api/tasks/${encodeURIComponent(id)}`, {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ enabled }),+ });+ if (!res.ok) throw await readError(res);+}++export async function cancelTask(id: string): Promise<void> {+ const res = await fetch(`/api/tasks/${encodeURIComponent(id)}/cancel`, { method: "POST" });+ if (!res.ok) throw await readError(res);+}++export async function deleteTask(id: string): Promise<void> {+ const res = await fetch(`/api/tasks/${encodeURIComponent(id)}`, { method: "DELETE" });+ if (!res.ok) throw await readError(res);+}++/**+ * One-click delete: an active task must be cancelled before the backend+ * accepts a DELETE, so cancel first (a 4xx there means it was already+ * terminal — fine) and then delete.+ */+export async function cancelAndDeleteTask(id: string, active: boolean): Promise<void> {+ if (active) {+ try {+ await cancelTask(id);+ } catch (err) {+ // Already terminal (409/404) — the delete below decides. Anything else+ // (a 5xx) is a real failure and must surface.+ if (!(err instanceof ApiError) || err.status >= 500) throw err;+ }+ }+ await deleteTask(id);+}++export interface AddTemplatePayload {+ inputs: Record<string, string>;+ schedule?: TemplateSchedule;+ title?: string;+ locale: string;+}++export async function addTemplate(key: string, payload: AddTemplatePayload): Promise<{ id: string }> {+ const res = await fetch(`/api/tasks/templates/${encodeURIComponent(key)}/add`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(payload),+ });+ if (!res.ok) throw await readError(res);+ return res.json();+}++// ---------------------------------------------------------------------+// Hooks+// ---------------------------------------------------------------------++export function useTasks() {+ return useQuery({+ queryKey: TASKS_QUERY_KEY,+ queryFn: fetchTasks,+ refetchInterval: 3000,+ });+}++export function useTaskDetail(id: string, enabled = true) {+ return useQuery({+ queryKey: [...TASKS_QUERY_KEY, "detail", id],+ queryFn: () => fetchTask(id),+ refetchInterval: 3000,+ enabled,+ });+}++export function useTemplates() {+ const locale = useUiLanguage();+ return useQuery({+ queryKey: [...TEMPLATES_QUERY_KEY, locale],+ queryFn: () => fetchTemplates(locale),+ // The catalogue is static per backend; readiness can change when a plugin+ // connects, so a slow poll keeps the "needs Gmail" hints truthful.+ refetchInterval: 15_000,+ });+}++function useInvalidateTasks() {+ const qc = useQueryClient();+ return () => qc.invalidateQueries({ queryKey: TASKS_QUERY_KEY });+}++export function useRunNow() {+ const invalidate = useInvalidateTasks();+ return useMutation({ mutationFn: runTaskNow, onSettled: invalidate });+}++export function useSetEnabled() {+ const invalidate = useInvalidateTasks();+ return useMutation({+ mutationFn: ({ id, enabled }: { id: string; enabled: boolean }) => setTaskEnabled(id, enabled),+ onSettled: invalidate,+ });+}++export function useCancelTask() {+ const invalidate = useInvalidateTasks();+ return useMutation({ mutationFn: cancelTask, onSettled: invalidate });+}++export function useDeleteTask() {+ const invalidate = useInvalidateTasks();+ return useMutation({+ mutationFn: ({ id, active }: { id: string; active: boolean }) => cancelAndDeleteTask(id, active),+ onSettled: invalidate,+ });+}++export function useAddTemplate() {+ const invalidate = useInvalidateTasks();+ return useMutation({+ mutationFn: ({ key, payload }: { key: string; payload: AddTemplatePayload }) =>+ addTemplate(key, payload),+ onSuccess: invalidate,+ });+}diff --git a/jarvis/ui/web/frontend/src/views/AutomationsView.test.tsx b/jarvis/ui/web/frontend/src/views/AutomationsView.test.tsxnew file mode 100644index 0000000000..d58ea5a3ef--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/AutomationsView.test.tsx@@ -0,0 +1,286 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";++// Identity translator: returns the key so assertions can match exact labels.+// The two strings with placeholders get a real template so the `fill` path+// (the humanized tool list, the added-notice name) is exercised.+const TEMPLATED: Record<string, string> = {+ "automations_view.needs": "Needs {tools}",+ "automations_view.added_notice": '"{name}" added.',+};++vi.mock("@/i18n", () => ({+ useT: () => (key: string) => TEMPLATED[key] ?? key,+ useUiLanguage: () => "en",+ fill: (template: string, vars: Record<string, string | number>) =>+ template.replace(/\{(\w+)\}/g, (m, k: string) => (k in vars ? String(vars[k]) : m)),+}));++// The header comes from ChatsView, which drags the voice stage along — stub it.+vi.mock("@/views/ChatsView", () => ({+ ViewHeader: ({ title, right }: { title: string; right?: React.ReactNode }) => (+ <header>+ <h2>{title}</h2>+ {right}+ </header>+ ),+}));++// The create dialog has its own tests; here it only needs to be openable.+vi.mock("@/views/tasks/TaskCreateDialog", () => ({+ TaskCreateDialog: () => <div>CREATE_DIALOG</div>,+}));++import { AutomationsView } from "@/views/AutomationsView";++const NOW_NS = Date.now() * 1e6;++const TEMPLATES = {+ categories: ["news", "productivity"],+ templates: [+ {+ key: "morning_briefing",+ category: "news",+ icon: "sun",+ name: "Morning briefing",+ description: "Calendar, mail and the weather in one summary.",+ schedule: { kind: "daily", time: "07:30", weekday: 0 },+ schedule_label: "Daily at 07:30",+ plugin_grants: [{ plugin_id: "gmail", scope: "read" }],+ requires: ["gmail"],+ missing: [],+ ready: true,+ inputs: [+ { key: "city", label: "City", placeholder: "Berlin", default: "", required: true },+ ],+ model_tier: "auto",+ tags: [],+ prompt: "Brief me about {city}.",+ },+ {+ key: "inbox_triage",+ category: "productivity",+ icon: "mail",+ name: "Inbox triage",+ description: "Sort the inbox.",+ schedule: { kind: "hourly", time: "08:00", weekday: 0 },+ schedule_label: "Every hour",+ plugin_grants: [{ plugin_id: "gmail", scope: "write" }],+ requires: ["gmail"],+ missing: ["gmail"],+ ready: false,+ inputs: [],+ model_tier: "fast",+ tags: [],+ prompt: "Triage.",+ },+ ],+};++const AUTOMATION = {+ id: "auto1",+ title: "My inbox triage",+ state: "scheduled",+ trigger_type: "every",+ due_at_ns: NOW_NS + 3600e9,+ created_at_ns: NOW_NS - 100e9,+ started_at_ns: null,+ finished_at_ns: NOW_NS - 50e9,+ attempts: 1,+ last_error: null,+ tags: ["template:inbox_triage"],+ created_by: "template",+ interval_seconds: 3600,+ next_due_at_ns: NOW_NS + 3600e9,+ last_run_state: "completed",+ last_result: "Three mails need a reply.",+};++const RUN = {+ id: "run1",+ title: "Weekly report",+ state: "completed",+ trigger_type: "after_delay",+ due_at_ns: NOW_NS - 200e9,+ created_at_ns: NOW_NS - 300e9,+ started_at_ns: NOW_NS - 200e9,+ finished_at_ns: NOW_NS - 130e9,+ attempts: 1,+ last_error: null,+ tags: [],+ created_by: "user",+ interval_seconds: null,+ next_due_at_ns: null,+ last_run_state: "completed",+ last_result: "The report is done.",+};++interface Call {+ url: string;+ method: string;+ body?: unknown;+}++function installFetch(opts: { templatesStatus?: number; tasks?: unknown[] } = {}) {+ const calls: Call[] = [];+ const tasks = opts.tasks ?? [AUTOMATION, RUN];+ const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input);+ const method = init?.method ?? "GET";+ const body = init?.body ? JSON.parse(String(init.body)) : undefined;+ calls.push({ url, method, body });+ const json = (status: number, payload: unknown) =>+ ({ ok: status < 400, status, json: async () => payload }) as Response;++ if (url.startsWith("/api/tasks/templates?")) {+ if (opts.templatesStatus === 404) return json(404, { detail: "Not Found" });+ return json(200, TEMPLATES);+ }+ if (url === "/api/tasks") return json(200, { tasks, total: tasks.length });+ if (url === "/api/tasks/templates/morning_briefing/add" && method === "POST") {+ return json(200, { id: "new1" });+ }+ if (url === "/api/tasks/auto1/run" && method === "POST") return json(200, { ok: true, id: "auto1" });+ if (url === "/api/tasks/auto1" && method === "PATCH") return json(200, { ok: true });+ if (url === "/api/tasks/auto1/cancel" && method === "POST") return json(200, { ok: true });+ if (url === "/api/tasks/auto1" && method === "DELETE") return json(200, { ok: true });+ if (url === "/api/tasks/run1") {+ return json(200, {+ ...RUN,+ spec: null,+ steps: [+ { seq: 1, kind: "start", payload: { event: "started" }, timestamp_ns: RUN.started_at_ns },+ {+ seq: 2,+ kind: "log",+ payload: { event: "agent_result", text: "The report is done.\nTwo items are open." },+ timestamp_ns: RUN.finished_at_ns,+ },+ ],+ });+ }+ if (url === "/api/tasks/auto1") return json(200, { ...AUTOMATION, spec: null, steps: [] });+ throw new Error(`unexpected fetch ${method} ${url}`);+ });+ (globalThis as unknown as { fetch: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;+ return calls;+}++function renderView() {+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ return render(+ <QueryClientProvider client={qc}>+ <AutomationsView />+ </QueryClientProvider>,+ );+}++afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+});++describe("AutomationsView", () => {+ it("renders the user's automations and the catalogue grouped by category", async () => {+ installFetch();+ renderView();+ // The user's card (from the template tag it borrows the template's description).+ const card = await screen.findByText("My inbox triage");+ expect(card).toBeTruthy();+ expect(screen.getByText("Three mails need a reply.")).toBeTruthy();+ // Catalogue groups in order with localized headings.+ expect(await screen.findByText("automations_view.category.news")).toBeTruthy();+ expect(screen.getByText("automations_view.category.productivity")).toBeTruthy();+ expect(screen.getByText("Morning briefing")).toBeTruthy();+ // The installed template says "Added"; the not-ready one names what it needs.+ const triage = screen.getByTestId("catalogue-inbox_triage");+ expect(within(triage).getByText("automations_view.added")).toBeTruthy();+ expect(within(triage).getByText("Needs Gmail")).toBeTruthy();+ });++ it("shows an honest note when the catalogue route does not exist yet", async () => {+ installFetch({ templatesStatus: 404 });+ renderView();+ expect(await screen.findByText("automations_view.catalogue_unavailable")).toBeTruthy();+ // The user's automations still render.+ expect(screen.getByText("My inbox triage")).toBeTruthy();+ });++ it("Add opens the dialog, validates required inputs and posts to the template route", async () => {+ const calls = installFetch();+ renderView();+ const briefing = await screen.findByTestId("catalogue-morning_briefing");+ fireEvent.click(within(briefing).getByText("automations_view.add"));+ const dialog = await screen.findByRole("dialog");+ // Required input empty → submit is refused and the field is flagged.+ fireEvent.click(within(dialog).getAllByText("automations_view.add").at(-1)!);+ expect(within(dialog).getByText("automations_view.required")).toBeTruthy();+ expect(calls.some((c) => c.url.includes("/add"))).toBe(false);+ // Fill it in and submit.+ fireEvent.change(within(dialog).getByPlaceholderText("Berlin"), { target: { value: "Hamburg" } });+ fireEvent.click(within(dialog).getAllByText("automations_view.add").at(-1)!);+ await waitFor(() => {+ const add = calls.find((c) => c.url === "/api/tasks/templates/morning_briefing/add");+ expect(add?.method).toBe("POST");+ const body = add?.body as { inputs: Record<string, string>; schedule: { kind: string; time: string }; title: string; locale: string };+ expect(body.inputs).toEqual({ city: "Hamburg" });+ expect(body.schedule).toEqual({ kind: "daily", time: "07:30", weekday: 0 });+ expect(body.title).toBe("Morning briefing");+ expect(body.locale).toBe("en");+ });+ // Dialog closes, confirmation shows.+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());+ expect(await screen.findByText('"Morning briefing" added.')).toBeTruthy();+ });++ it("the pause switch PATCHes {enabled:false} and Run now POSTs to /run", async () => {+ const calls = installFetch();+ renderView();+ await screen.findByText("My inbox triage");+ fireEvent.click(screen.getByRole("switch"));+ await waitFor(() => {+ const patch = calls.find((c) => c.url === "/api/tasks/auto1" && c.method === "PATCH");+ expect(patch?.body).toEqual({ enabled: false });+ });+ fireEvent.click(screen.getByText("automations_view.run_now"));+ await waitFor(() => {+ expect(calls.some((c) => c.url === "/api/tasks/auto1/run" && c.method === "POST")).toBe(true);+ });+ expect(await screen.findByText("automations_view.run_started")).toBeTruthy();+ });++ it("Delete asks once, then cancels the active task and deletes it", async () => {+ const calls = installFetch();+ renderView();+ await screen.findByText("My inbox triage");+ fireEvent.click(screen.getByLabelText("tasks_view.delete"));+ expect(screen.getByText("automations_view.delete_confirm")).toBeTruthy();+ fireEvent.click(screen.getByText("tasks_view.delete"));+ await waitFor(() => {+ const idx = (m: string, u: string) => calls.findIndex((c) => c.url === u && c.method === m);+ const cancel = idx("POST", "/api/tasks/auto1/cancel");+ const del = idx("DELETE", "/api/tasks/auto1");+ expect(cancel).toBeGreaterThanOrEqual(0);+ expect(del).toBeGreaterThan(cancel);+ });+ });++ it("the Runs tab lists finished runs and expands to the readable result text", async () => {+ installFetch();+ renderView();+ await screen.findByText("My inbox triage");+ fireEvent.click(screen.getByRole("tab", { name: /automations_view.tab_runs/ }));+ expect(await screen.findByText("Weekly report")).toBeTruthy();+ // The recurring automation is not a "run" row unless it is running/finished.+ expect(screen.queryByText("My inbox triage")).toBeNull();+ fireEvent.click(screen.getByLabelText("tasks_view.expand"));+ const result = await screen.findByTestId("run-result");+ expect(result.textContent).toContain("The report is done.");+ expect(result.textContent).toContain("Two items are open.");+ expect(result.textContent).not.toContain("agent_result");+ // Filter chips: "problems" hides the completed run.+ fireEvent.click(screen.getByText("automations_view.runs_filter.problems"));+ expect(screen.queryByText("Weekly report")).toBeNull();+ });+});diff --git a/jarvis/ui/web/frontend/src/views/AutomationsView.tsx b/jarvis/ui/web/frontend/src/views/AutomationsView.tsxnew file mode 100644index 0000000000..6ac03b87e9--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/AutomationsView.tsx@@ -0,0 +1,365 @@+/**+ * The Automations section: the user's recurring automations, the catalogue+ * of ready-made ones (grouped by category), and a Runs tab with the history.+ *+ * Degrades honestly against an older backend: when the catalogue route does+ * not exist yet (404 — it goes live with the next restart) the section says+ * so inline, and a failed run/pause/delete call becomes a notice instead of+ * a crash.+ */+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { History, Plus, RefreshCw, Workflow, X } from "lucide-react";+import { ViewHeader } from "@/views/ChatsView";+import { ScrollArea } from "@/components/ui/scroll-area";+import { Button } from "@/components/ui/button";+import { fill, useT } from "@/i18n";+import { cn } from "@/lib/utils";+import {+ ApiError,+ useDeleteTask,+ useRunNow,+ useSetEnabled,+ useTasks,+ useTemplates,+} from "@/hooks/useAutomations";+import { TaskCreateDialog } from "./tasks/TaskCreateDialog";+import { AutomationCard } from "./automations/AutomationCard";+import { CatalogueCard } from "./automations/CatalogueCard";+import { TemplateAddDialog } from "./automations/TemplateAddDialog";+import {+ groupTemplates,+ selectAutomations,+ selectRuns,+ templateKeyOf,+ type AutomationTemplate,+ type TaskSummary,+} from "./automations/automationsModel";+import { SectionLabel } from "./automations/shared";+import { RunsTab } from "./TasksView";++type Tab = "automations" | "runs";++interface Notice {+ text: string;+ kind: "info" | "error";+}++export function AutomationsView() {+ const t = useT();+ const [tab, setTab] = useState<Tab>("automations");+ const [showCreate, setShowCreate] = useState(false);+ const [adding, setAdding] = useState<AutomationTemplate | null>(null);+ const [highlightId, setHighlightId] = useState<string | null>(null);+ const [notice, setNotice] = useState<Notice | null>(null);+ const noticeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);++ const showNotice = useCallback((text: string, kind: "info" | "error" = "info") => {+ setNotice({ text, kind });+ if (noticeTimer.current) clearTimeout(noticeTimer.current);+ noticeTimer.current = setTimeout(() => setNotice(null), kind === "error" ? 8000 : 4000);+ }, []);+ useEffect(() => () => {+ if (noticeTimer.current) clearTimeout(noticeTimer.current);+ }, []);++ const tasksQuery = useTasks();+ const templatesQuery = useTemplates();+ const tasks = useMemo(() => tasksQuery.data?.tasks ?? [], [tasksQuery.data]);+ const automations = useMemo(() => selectAutomations(tasks), [tasks]);+ const runsCount = useMemo(() => selectRuns(tasks).length, [tasks]);++ const templates = templatesQuery.data?.templates ?? [];+ const templatesByKey = useMemo(+ () => new Map(templates.map((tpl) => [tpl.key, tpl])),+ [templates],+ );+ // template key → the user's (active) task created from it+ const installedByKey = useMemo(() => {+ const map = new Map<string, string>();+ for (const task of automations) {+ const key = templateKeyOf(task);+ if (key && !map.has(key)) map.set(key, task.id);+ }+ return map;+ }, [automations]);+ const groups = useMemo(() => groupTemplates(templates), [templates]);++ const runNow = useRunNow();+ const setEnabled = useSetEnabled();+ const deleteTask = useDeleteTask();++ const describeError = useCallback(+ (err: unknown, fallbackKey: string): string => {+ if (err instanceof ApiError) {+ if (err.status === 404 || err.status === 405) return t("automations_view.route_unavailable");+ if (err.status === 409) return t("automations_view.already_running");+ }+ return `${t(fallbackKey)} (${(err as Error)?.message ?? "?"})`;+ },+ [t],+ );++ const handleRunNow = useCallback(+ (id: string) =>+ runNow.mutate(id, {+ onSuccess: () => showNotice(t("automations_view.run_started")),+ onError: (err) => showNotice(describeError(err, "automations_view.run_error"), "error"),+ }),+ [runNow, showNotice, describeError, t],+ );+ const handleSetEnabled = useCallback(+ (id: string, enabled: boolean) =>+ setEnabled.mutate(+ { id, enabled },+ {+ onSuccess: () =>+ showNotice(t(enabled ? "automations_view.resumed" : "automations_view.paused_notice")),+ onError: (err) => showNotice(describeError(err, "automations_view.toggle_error"), "error"),+ },+ ),+ [setEnabled, showNotice, describeError, t],+ );+ const handleDelete = useCallback(+ (id: string, active: boolean) =>+ deleteTask.mutate(+ { id, active },+ {+ onSuccess: () => showNotice(t("automations_view.deleted")),+ onError: (err) => showNotice(describeError(err, "automations_view.delete_error"), "error"),+ },+ ),+ [deleteTask, showNotice, describeError, t],+ );++ const scrollToTask = useCallback((taskId: string) => {+ setTab("automations");+ setHighlightId(taskId);+ // The card exists already (installed) — give React a frame to switch tabs.+ requestAnimationFrame(() => {+ document.getElementById(`automation-${taskId}`)?.scrollIntoView({ behavior: "smooth", block: "center" });+ });+ setTimeout(() => setHighlightId((cur) => (cur === taskId ? null : cur)), 2500);+ }, []);++ const handleAdded = useCallback(+ (taskId: string, template: AutomationTemplate) => {+ setAdding(null);+ showNotice(fill(t("automations_view.added_notice"), { name: template.name }));+ // The list refetches on invalidation; scroll once it has rendered.+ setTimeout(() => scrollToTask(taskId), 400);+ },+ [showNotice, scrollToTask, t],+ );++ const catalogueUnavailable = templatesQuery.data?.unavailable === true;++ return (+ <div className="flex h-full flex-col">+ <ViewHeader+ icon={<Workflow className="h-4 w-4 text-primary" />}+ title={t("automations_view.title")}+ subtitle={t("automations_view.subtitle")}+ right={+ <div className="flex items-center gap-1.5">+ <Button+ size="sm"+ variant="ghost"+ onClick={() => {+ tasksQuery.refetch();+ templatesQuery.refetch();+ }}+ disabled={tasksQuery.isRefetching}+ aria-label={t("automations_view.refresh")}+ title={t("automations_view.refresh")}+ >+ <RefreshCw className={cn("h-4 w-4", tasksQuery.isRefetching && "animate-spin")} />+ </Button>+ <Button size="sm" onClick={() => setShowCreate(true)}>+ <Plus className="mr-1 h-4 w-4" />+ {t("automations_view.new_button")}+ </Button>+ </div>+ }+ />+ {showCreate && <TaskCreateDialog onClose={() => setShowCreate(false)} />}+ {adding && (+ <TemplateAddDialog template={adding} onClose={() => setAdding(null)} onAdded={handleAdded} />+ )}++ {/* Tabs */}+ <div className="flex items-center gap-1 border-b border-border px-6">+ <TabButton active={tab === "automations"} onClick={() => setTab("automations")} icon={Workflow}>+ {t("automations_view.tab_automations")}+ <Count n={automations.length} />+ </TabButton>+ <TabButton active={tab === "runs"} onClick={() => setTab("runs")} icon={History}>+ {t("automations_view.tab_runs")}+ <Count n={runsCount} />+ </TabButton>+ {notice && (+ <div+ role="status"+ className={cn(+ "ml-auto flex items-center gap-2 rounded-md border px-2.5 py-1 text-xs",+ notice.kind === "error"+ ? "border-destructive/50 text-destructive"+ : "border-primary/40 text-primary",+ )}+ >+ <span className="max-w-md truncate">{notice.text}</span>+ <button type="button" onClick={() => setNotice(null)} aria-label={t("common.close")}>+ <X className="h-3 w-3" />+ </button>+ </div>+ )}+ </div>++ <ScrollArea className="flex-1">+ <div className="p-6">+ {tasksQuery.isLoading && (+ <div className="text-sm text-muted-foreground">{t("tasks_view.loading")}</div>+ )}+ {tasksQuery.error && (+ <div className="mb-4 rounded-lg border border-destructive/40 p-4 text-sm text-destructive">+ {t("tasks_view.load_error")}: {(tasksQuery.error as Error).message}+ </div>+ )}++ {tab === "automations" ? (+ <div className="space-y-8">+ <section aria-labelledby="your-automations">+ <div className="mb-3 flex items-baseline justify-between">+ <h3 id="your-automations" className="text-sm font-semibold">+ {t("automations_view.yours_heading")}+ </h3>+ <span className="text-[11px] text-muted-foreground">+ {automations.length} {t("tasks_view.entries")}+ </span>+ </div>+ {!tasksQuery.isLoading && automations.length === 0 ? (+ <div className="flex flex-col items-center justify-center gap-2 rounded-2xl border border-dashed border-border/60 p-8 text-center">+ <Workflow className="h-7 w-7 text-muted-foreground/50" />+ <p className="text-sm text-muted-foreground">{t("automations_view.yours_empty")}</p>+ <p className="max-w-xl text-[11px] leading-relaxed text-muted-foreground/70">+ {t("automations_view.yours_empty_hint")}+ </p>+ </div>+ ) : (+ <div className="grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-3">+ {automations.map((task: TaskSummary) => {+ const key = templateKeyOf(task);+ return (+ <AutomationCard+ key={task.id}+ task={task}+ template={key ? templatesByKey.get(key) : undefined}+ highlighted={highlightId === task.id}+ onRunNow={handleRunNow}+ onSetEnabled={handleSetEnabled}+ onDelete={handleDelete}+ busy={{+ run: runNow.isPending && runNow.variables === task.id,+ toggle: setEnabled.isPending && setEnabled.variables?.id === task.id,+ delete: deleteTask.isPending && deleteTask.variables?.id === task.id,+ }}+ />+ );+ })}+ </div>+ )}+ </section>++ <section aria-labelledby="catalogue">+ <div className="mb-3 flex items-baseline justify-between">+ <h3 id="catalogue" className="text-sm font-semibold">+ {t("automations_view.catalogue_heading")}+ </h3>+ <span className="text-[11px] text-muted-foreground">+ {t("automations_view.catalogue_hint")}+ </span>+ </div>+ {catalogueUnavailable ? (+ <div className="rounded-2xl border border-dashed border-border/60 p-6 text-center text-sm text-muted-foreground">+ {t("automations_view.catalogue_unavailable")}+ </div>+ ) : templatesQuery.isLoading ? (+ <div className="text-sm text-muted-foreground">{t("automations_view.catalogue_loading")}</div>+ ) : templatesQuery.error ? (+ <div className="rounded-lg border border-destructive/40 p-4 text-sm text-destructive">+ {t("automations_view.catalogue_error")}: {(templatesQuery.error as Error).message}+ </div>+ ) : groups.length === 0 ? (+ <div className="rounded-2xl border border-dashed border-border/60 p-6 text-center text-sm text-muted-foreground">+ {t("automations_view.catalogue_empty")}+ </div>+ ) : (+ <div className="space-y-6">+ {groups.map((group) => (+ <div key={group.category}>+ <SectionLabel className="mb-2">+ {t(`automations_view.category.${group.category}`)}+ </SectionLabel>+ <div className="grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-3">+ {group.templates.map((tpl) => (+ <CatalogueCard+ key={tpl.key}+ template={tpl}+ installedTaskId={installedByKey.get(tpl.key)}+ onAdd={setAdding}+ onShowInstalled={scrollToTask}+ />+ ))}+ </div>+ </div>+ ))}+ </div>+ )}+ </section>+ </div>+ ) : (+ <RunsTab tasks={tasks} onNotice={showNotice} />+ )}+ </div>+ </ScrollArea>+ </div>+ );+}++function TabButton({+ active,+ onClick,+ icon: Icon,+ children,+}: {+ active: boolean;+ onClick: () => void;+ icon: typeof Workflow;+ children: React.ReactNode;+}) {+ return (+ <button+ type="button"+ role="tab"+ aria-selected={active}+ onClick={onClick}+ className={cn(+ "-mb-px inline-flex items-center gap-1.5 border-b-2 px-3 py-2.5 text-sm transition-colors",+ active+ ? "border-primary font-medium text-foreground"+ : "border-transparent text-muted-foreground hover:text-foreground",+ )}+ >+ <Icon className={cn("h-3.5 w-3.5", active ? "text-primary" : "text-muted-foreground")} />+ {children}+ </button>+ );+}++function Count({ n }: { n: number }) {+ if (!n) return null;+ return (+ <span className="rounded-full border border-border px-1.5 text-[10px] font-mono leading-4 text-muted-foreground">+ {n}+ </span>+ );+}diff --git a/jarvis/ui/web/frontend/src/views/TasksView.tsx b/jarvis/ui/web/frontend/src/views/TasksView.tsxindex 0ee50caca8..02daaf8836 100644--- a/jarvis/ui/web/frontend/src/views/TasksView.tsx+++ b/jarvis/ui/web/frontend/src/views/TasksView.tsx@@ -1,478 +1,219 @@-import { useEffect, useMemo, useState } from "react";-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";-import {- ListTodo,- RefreshCw,- X,- Trash2,- ChevronDown,- ChevronRight,- Clock,- Zap,- CalendarClock,- Repeat,- Plus,-} from "lucide-react";-import { ViewHeader } from "@/views/ChatsView";-import { ScrollArea } from "@/components/ui/scroll-area";+/**+ * The Runs tab of the Automations section — the run history.+ *+ * This file used to be the whole "Tasks" section. The section became+ * Automations (`AutomationsView.tsx`) and the task list folded into its+ * Runs tab; the file keeps its name so history and the route stay traceable.+ *+ * Every task that ran or is running (recurring and one-shot alike) plus the+ * still-pending one-shots, newest activity first, with filter chips. A row+ * expands to the readable result text and the step timeline.+ */+import { useMemo, useState } from "react";+import { ChevronDown, ChevronRight, History, Trash2, X } from "lucide-react";import { Button } from "@/components/ui/button";-import { Badge } from "@/components/ui/badge";-import { cn } from "@/lib/utils";import { useT } from "@/i18n";-import { TaskCreateDialog } from "./tasks/TaskCreateDialog";--type TaskState =- | "pending"- | "scheduled"- | "running"- | "completed"- | "failed"- | "cancelled"- | "interrupted";--type TriggerType = "after_delay" | "at_time" | "on_event" | "every";--interface TaskSummary {- id: string;- title: string;- state: TaskState;- trigger_type: TriggerType;- due_at_ns: number | null;- created_at_ns: number | null;- started_at_ns: number | null;- finished_at_ns: number | null;- attempts: number;- last_error: string | null;-}--interface TaskStep {- seq: number;- kind: string;- payload: Record<string, unknown>;- timestamp_ns: number;-}+import { cn } from "@/lib/utils";+import { useCancelTask, useDeleteTask, useTaskDetail } from "@/hooks/useAutomations";+import {+ filterRuns,+ formatDuration,+ isActive,+ isRecurringTrigger,+ selectRuns,+ type RunFilter,+ type TaskSummary,+} from "./automations/automationsModel";+import {+ ResultText,+ SectionLabel,+ StateDot,+ StepTimeline,+ formatWhen,+ useStateLabels,+} from "./automations/shared";-interface TaskDetail extends TaskSummary {- spec: Record<string, unknown> | null;- steps: TaskStep[];-}+const FILTERS: RunFilter[] = ["all", "running", "done", "problems"];-interface TasksListResponse {+export interface RunsTabProps {tasks: TaskSummary[];- total: number;-}--async function fetchTasks(state?: string): Promise<TasksListResponse> {- const url = state ? `/api/tasks?state=${encodeURIComponent(state)}` : "/api/tasks";- const res = await fetch(url);- if (!res.ok) throw new Error(`HTTP ${res.status}`);- return res.json();-}--async function fetchTask(id: string): Promise<TaskDetail> {- const res = await fetch(`/api/tasks/${id}`);- if (!res.ok) throw new Error(`HTTP ${res.status}`);- return res.json();-}--async function cancelTask(id: string): Promise<void> {- const res = await fetch(`/api/tasks/${id}/cancel`, { method: "POST" });- if (!res.ok) throw new Error(`HTTP ${res.status}`);-}--async function deleteTask(id: string): Promise<void> {- const res = await fetch(`/api/tasks/${id}`, { method: "DELETE" });- if (!res.ok) throw new Error(`HTTP ${res.status}`);+ onNotice: (text: string, kind?: "info" | "error") => void;}-function makeStateLabels(t: (k: string) => string): Record<TaskState, string> {- return {- pending: t("tasks_view.state.pending"),- scheduled: t("tasks_view.state.scheduled"),- running: t("tasks_view.state.running"),- completed: t("tasks_view.state.completed"),- failed: t("tasks_view.state.failed"),- cancelled: t("tasks_view.state.cancelled"),- interrupted: t("tasks_view.state.interrupted"),- };-}--const STATE_VARIANT: Record<- TaskState,- "default" | "secondary" | "destructive" | "outline"-> = {- pending: "outline",- scheduled: "secondary",- running: "default",- completed: "secondary",- failed: "destructive",- cancelled: "outline",- interrupted: "destructive",-};--const TRIGGER_ICON: Record<TriggerType, typeof Clock> = {- after_delay: Clock,- at_time: CalendarClock,- on_event: Zap,- every: Repeat,-};--function makeTriggerLabels(t: (k: string) => string): Record<TriggerType, string> {- return {- after_delay: t("tasks_view.trigger_label.after_delay"),- at_time: t("tasks_view.trigger_label.at_time"),- on_event: t("tasks_view.trigger_label.on_event"),- every: t("tasks_view.trigger_label.every"),- };-}--function makeStateFilters(t: (k: string) => string): { id: string; label: string }[] {- return [- { id: "all", label: t("tasks_view.filter_all") },- { id: "scheduled,running", label: t("tasks_view.filter_active") },- { id: "completed", label: t("tasks_view.filter_done") },- { id: "failed,cancelled,interrupted", label: t("tasks_view.filter_problems") },- ];-}--export function TasksView() {+export function RunsTab({ tasks, onNotice }: RunsTabProps) {const t = useT();- const STATE_FILTERS = makeStateFilters(t);- const [stateFilter, setStateFilter] = useState<string>("all");+ const [filter, setFilter] = useState<RunFilter>("all");const [expanded, setExpanded] = useState<Record<string, boolean>>({});- const [showCreate, setShowCreate] = useState(false);- const qc = useQueryClient();-- const effectiveFilter = stateFilter === "all" ? undefined : stateFilter;- const { data, isLoading, error, refetch, isRefetching } = useQuery({- queryKey: ["tasks", stateFilter],- queryFn: () => fetchTasks(effectiveFilter),- refetchInterval: 3000,- });-- const cancelMut = useMutation({- mutationFn: cancelTask,- onSuccess: () => qc.invalidateQueries({ queryKey: ["tasks"] }),- });- const deleteMut = useMutation({- mutationFn: deleteTask,- onSuccess: () => qc.invalidateQueries({ queryKey: ["tasks"] }),- });+ const cancelMut = useCancelTask();+ const deleteMut = useDeleteTask();- const tasks = data?.tasks ?? [];+ const runs = useMemo(() => filterRuns(selectRuns(tasks), filter), [tasks, filter]);return (- <div className="flex h-full flex-col">- <ViewHeader- icon={<ListTodo className="h-4 w-4 text-primary" />}- title={t("tasks_view.title")}- subtitle={t("tasks_view.subtitle")}- right={- <div className="flex items-center gap-1.5">- <Button- size="sm"- variant="ghost"- onClick={() => refetch()}- disabled={isRefetching}- >- <RefreshCw- className={isRefetching ? "h-4 w-4 animate-spin" : "h-4 w-4"}- />- </Button>- <Button size="sm" onClick={() => setShowCreate(true)}>- <Plus className="mr-1 h-4 w-4" />- {t("tasks_view.create_button")}- </Button>- </div>- }- />- {showCreate && <TaskCreateDialog onClose={() => setShowCreate(false)} />}-- <div className="flex items-center gap-2 border-b border-border px-6 py-3">- {STATE_FILTERS.map((f) => (+ <div className="space-y-3">+ <div className="flex flex-wrap items-center gap-2">+ {FILTERS.map((f) => (<button- key={f.id}+ key={f}type="button"- onClick={() => setStateFilter(f.id)}+ onClick={() => setFilter(f)}+ aria-pressed={filter === f}className={cn("rounded-md border px-2.5 py-1 text-xs transition-colors",- stateFilter === f.id+ filter === f? "border-primary/60 bg-primary/10 text-primary": "border-border text-muted-foreground hover:border-primary/30 hover:text-foreground",)}>- {f.label}+ {t(`automations_view.runs_filter.${f}`)}</button>))}<div className="ml-auto text-xs text-muted-foreground">- {data ? `${data.total} ${t("tasks_view.entries")}` : ""}+ {runs.length} {t("tasks_view.entries")}</div></div>- <ScrollArea className="flex-1">- <div className="space-y-2 p-6">- {isLoading && (- <div className="text-sm text-muted-foreground">{t("tasks_view.loading")}</div>- )}- {error && (- <div className="rounded-lg border border-destructive/40 bg-destructive/10 p-4 text-sm text-destructive">- {t("tasks_view.load_error")}: {(error as Error).message}- </div>- )}- {!isLoading && !error && tasks.length === 0 && (- <EmptyState />- )}- {tasks.map((t) => (- <TaskCard- key={t.id}- task={t}- isExpanded={!!expanded[t.id]}- onToggle={() =>- setExpanded((prev) => ({ ...prev, [t.id]: !prev[t.id] }))+ {runs.length === 0 ? (+ <div className="flex flex-col items-center justify-center gap-3 rounded-2xl border border-dashed border-border/60 p-10 text-center">+ <History className="h-7 w-7 text-muted-foreground/50" />+ <p className="text-sm text-muted-foreground">{t("automations_view.runs_empty")}</p>+ </div>+ ) : (+ <ul className="space-y-2">+ {runs.map((run) => (+ <RunRow+ key={run.id}+ run={run}+ expanded={!!expanded[run.id]}+ onToggle={() => setExpanded((prev) => ({ ...prev, [run.id]: !prev[run.id] }))}+ onCancel={() =>+ cancelMut.mutate(run.id, {+ onError: (err) => onNotice(`${t("common.error")}: ${(err as Error).message}`, "error"),+ })+ }+ onDelete={() =>+ deleteMut.mutate(+ { id: run.id, active: isActive(run.state) },+ { onError: (err) => onNotice(`${t("common.error")}: ${(err as Error).message}`, "error") },+ )}- onCancel={() => cancelMut.mutate(t.id)}- onDelete={() => deleteMut.mutate(t.id)}- isCancelling={cancelMut.isPending && cancelMut.variables === t.id}- isDeleting={deleteMut.isPending && deleteMut.variables === t.id}+ busy={{+ cancel: cancelMut.isPending && cancelMut.variables === run.id,+ delete: deleteMut.isPending && deleteMut.variables?.id === run.id,+ }}/>))}- </div>- </ScrollArea>- </div>- );-}--function EmptyState() {- const t = useT();- return (- <div className="flex flex-col items-center justify-center gap-3 rounded-lg border border-dashed border-border/60 bg-background/30 p-10 text-center">- <ListTodo className="h-7 w-7 text-muted-foreground/50" />- <p className="text-sm text-muted-foreground">{t("tasks_view.empty_text")}</p>- <p className="max-w-xl text-[11px] leading-relaxed text-muted-foreground/70">- {t("tasks_view.empty_hint")}- </p>+ </ul>+ )}</div>);}-function TaskCard({- task,- isExpanded,+function RunRow({+ run,+ expanded,onToggle,onCancel,onDelete,- isCancelling,- isDeleting,+ busy,}: {- task: TaskSummary;- isExpanded: boolean;+ run: TaskSummary;+ expanded: boolean;onToggle: () => void;onCancel: () => void;onDelete: () => void;- isCancelling: boolean;- isDeleting: boolean;+ busy: { cancel: boolean; delete: boolean };}) {const t = useT();- const STATE_LABEL = makeStateLabels(t);- const TRIGGER_LABEL = makeTriggerLabels(t);- const Icon = TRIGGER_ICON[task.trigger_type] ?? Clock;- const canCancel =- task.state === "scheduled" ||- task.state === "running" ||- task.state === "pending";- const canDelete =- task.state === "completed" ||- task.state === "failed" ||- task.state === "cancelled" ||- task.state === "interrupted";+ const labels = useStateLabels();+ const when = formatWhen(run.finished_at_ns ?? run.started_at_ns ?? run.due_at_ns ?? run.created_at_ns);+ const duration = formatDuration(run.started_at_ns, run.finished_at_ns);+ const active = isActive(run.state);+ // A recurring automation's row is its latest run; deleting it is the+ // card's job on the Automations tab, so only one-shots offer Delete here.+ const canDelete = !isRecurringTrigger(run.trigger_type) || !active;return (- <article className="card-outline overflow-hidden transition-all hover:shadow-[0_0_24px_rgba(255,214,10,0.06)]">- <header className="flex items-start gap-3 p-4">+ <li className="card-outline">+ <div className="flex items-center gap-3 px-4 py-3"><buttontype="button"onClick={onToggle}- className="mt-0.5 rounded-md p-1 text-muted-foreground transition-colors hover:bg-background/60 hover:text-foreground"- aria-label={isExpanded ? t("tasks_view.collapse") : t("tasks_view.expand")}+ className="rounded-md p-1 text-muted-foreground transition-colors hover:text-foreground"+ aria-label={expanded ? t("tasks_view.collapse") : t("tasks_view.expand")}+ aria-expanded={expanded}>- {isExpanded ? (- <ChevronDown className="h-4 w-4" />- ) : (- <ChevronRight className="h-4 w-4" />- )}+ {expanded ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}</button>- <div className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md border border-border bg-secondary/40">- <Icon className="h-3.5 w-3.5 text-primary" />- </div>+ <StateDot state={run.state} /><div className="min-w-0 flex-1"><div className="flex items-center gap-2">- <h3 className="truncate text-sm font-semibold">{task.title || t("tasks_view.untitled")}</h3>- <Badge variant={STATE_VARIANT[task.state]}>{STATE_LABEL[task.state]}</Badge>- {task.attempts > 1 && (- <span className="text-[10px] font-mono text-muted-foreground">- #{task.attempts}- </span>- )}+ <span className="truncate text-sm font-medium">{run.title || t("tasks_view.untitled")}</span>+ <span className="shrink-0 text-[11px] text-muted-foreground">{labels[run.state]}</span></div>- <div className="mt-1 flex flex-wrap items-center gap-3 text-[11px] text-muted-foreground">- <span>{TRIGGER_LABEL[task.trigger_type]}</span>- <TriggerWhen task={task} />- <span className="font-mono">{task.id.slice(0, 8)}</span>- </div>- {task.last_error && (- <p className="mt-1.5 line-clamp-2 text-xs text-destructive/90">- {task.last_error}+ {(run.last_result || run.last_error) && (+ <p+ className={cn(+ "mt-0.5 truncate text-xs",+ run.last_error && !run.last_result ? "text-destructive/90" : "text-muted-foreground",+ )}+ >+ {run.last_result || run.last_error}</p>)}</div>- <div className="flex shrink-0 items-center gap-1">- {canCancel && (- <Button- size="sm"- variant="ghost"- onClick={onCancel}- disabled={isCancelling}- title={t("tasks_view.cancel")}- >+ <div className="shrink-0 text-right text-[11px] text-muted-foreground">+ <div>{when}</div>+ {duration && <div className="font-mono">{duration}</div>}+ </div>+ <div className="flex shrink-0 items-center">+ {active && (+ <Button size="sm" variant="ghost" onClick={onCancel} disabled={busy.cancel} title={t("tasks_view.cancel")}><X className="h-4 w-4" /></Button>)}{canDelete && (- <Button- size="sm"- variant="ghost"- onClick={onDelete}- disabled={isDeleting}- title={t("tasks_view.delete")}- >+ <Button size="sm" variant="ghost" onClick={onDelete} disabled={busy.delete} title={t("tasks_view.delete")}><Trash2 className="h-4 w-4" /></Button>)}</div>- </header>-- {isExpanded && <TaskDetailBody taskId={task.id} />}- </article>+ </div>+ {expanded && <RunDetail taskId={run.id} fallbackResult={run.last_result} />}+ </li>);}-function TaskDetailBody({ taskId }: { taskId: string }) {+function RunDetail({ taskId, fallbackResult }: { taskId: string; fallbackResult?: string | null }) {const t = useT();- const { data, isLoading, error } = useQuery({- queryKey: ["tasks", "detail", taskId],- queryFn: () => fetchTask(taskId),- refetchInterval: 3000,- });-+ const { data, isLoading, error } = useTaskDetail(taskId);if (isLoading) {return (- <div className="border-t border-border bg-background/30 px-5 py-3 text-xs text-muted-foreground">+ <div className="border-t border-border px-4 py-3 text-xs text-muted-foreground">{t("tasks_view.loading_details")}</div>);}if (error) {return (- <div className="border-t border-border bg-destructive/10 px-5 py-3 text-xs text-destructive">+ <div className="border-t border-border px-4 py-3 text-xs text-destructive">{t("common.error")}: {(error as Error).message}</div>);}- if (!data) return null;-- const steps = data.steps ?? [];-+ const steps = data?.steps ?? [];return (- <div className="space-y-3 border-t border-border bg-background/30 px-5 py-4">- {data.spec ? (- <div>- <div className="mb-1 text-[10px] uppercase tracking-wider text-muted-foreground">- Spec- </div>- <pre className="max-h-40 overflow-auto rounded-md border border-border bg-card/60 p-3 text-[11px] leading-relaxed">- {JSON.stringify(data.spec, null, 2)}- </pre>- </div>- ) : null}-+ <div className="space-y-3 border-t border-border px-4 py-3"><div>- <div className="mb-1 text-[10px] uppercase tracking-wider text-muted-foreground">- Timeline ({steps.length})- </div>- {steps.length === 0 ? (- <div className="text-xs text-muted-foreground">{t("tasks_view.no_steps")}</div>- ) : (- <ul className="space-y-1.5">- {steps.map((s) => (- <li- key={s.seq}- className="flex items-start gap-3 rounded-md border border-border/60 bg-card/40 p-2 text-xs"- >- <span className="w-6 font-mono text-muted-foreground">{s.seq}</span>- <span className="w-20 text-primary">{s.kind}</span>- <span className="flex-1 font-mono text-muted-foreground break-all">- {summarizePayload(s.payload)}- </span>- </li>- ))}- </ul>- )}+ <SectionLabel className="mb-1.5">{t("automations_view.result")}</SectionLabel>+ <ResultText steps={steps} fallback={fallbackResult} />+ </div>+ <div>+ <SectionLabel className="mb-1.5">+ {t("automations_view.timeline")} ({steps.length})+ </SectionLabel>+ <StepTimeline steps={steps} /></div></div>);}--function TriggerWhen({ task }: { task: TaskSummary }) {- const t = useT();- const [tick, setTick] = useState(0);- useEffect(() => {- const timer = setInterval(() => setTick((x) => x + 1), 1000);- return () => clearInterval(timer);- }, []);-- const label = useMemo(() => {- if (task.trigger_type === "on_event") return t("tasks_view.waiting_for_event");- if (task.state === "running") return t("tasks_view.running_now");- if (task.finished_at_ns)- return `${t("tasks_view.done_at")} ${formatWhen(task.finished_at_ns)}`;- if (task.due_at_ns) {- const delta = task.due_at_ns - Date.now() * 1e6;- if (delta > 0) return `${t("tasks_view.in_prefix")} ${formatDelta(delta)}`;- return t("tasks_view.due_now");- }- return "—";- // `tick` forces a re-render for the countdown- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [task, tick, t]);-- return <span>{label}</span>;-}--function formatDelta(ns: number): string {- const sec = Math.max(0, Math.round(ns / 1e9));- if (sec < 60) return `${sec}s`;- const min = Math.round(sec / 60);- if (min < 60) return `${min}min`;- const hr = Math.round(min / 60);- if (hr < 48) return `${hr}h`;- const day = Math.round(hr / 24);- return `${day}d`;-}--function formatWhen(ns: number): string {- try {- const d = new Date(ns / 1e6);- return d.toLocaleTimeString();- } catch {- return "";- }-}--function summarizePayload(p: Record<string, unknown>): string {- try {- const s = JSON.stringify(p);- return s.length > 140 ? s.slice(0, 139) + "…" : s;- } catch {- return "(unlesbar)";- }-}diff --git a/jarvis/ui/web/frontend/src/views/automations/AutomationCard.tsx b/jarvis/ui/web/frontend/src/views/automations/AutomationCard.tsxnew file mode 100644index 0000000000..3592b5def4--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/automations/AutomationCard.tsx@@ -0,0 +1,232 @@+/**+ * One of the user's automations: icon, name, description, schedule line,+ * next-run countdown, last-run dot + result preview, and the three actions+ * (Run now, Pause/Resume, Delete). Expanding shows the latest run's result+ * and the step timeline from the detail endpoint.+ */+import { useState } from "react";+import { ChevronDown, ChevronRight, Loader2, Play, Trash2 } from "lucide-react";+import { Button } from "@/components/ui/button";+import { Switch } from "@/components/ui/switch";+import { useT } from "@/i18n";+import { cn } from "@/lib/utils";+import { useTaskDetail } from "@/hooks/useAutomations";+import { templateIcon } from "./automationIcons";+import {+ firstLine,+ isActive,+ promptOfSpec,+ scheduleLineForTask,+ templateKeyOf,+ type AutomationTemplate,+ type TaskSummary,+} from "./automationsModel";+import {+ Countdown,+ ResultText,+ SectionLabel,+ StateDot,+ StepTimeline,+ formatWhen,+ useScheduleWords,+ useStateLabels,+} from "./shared";++export interface AutomationCardProps {+ task: TaskSummary;+ /** The template the task came from, when the catalogue knows it. */+ template?: AutomationTemplate;+ highlighted?: boolean;+ onRunNow: (id: string) => void;+ onSetEnabled: (id: string, enabled: boolean) => void;+ onDelete: (id: string, active: boolean) => void;+ busy?: { run?: boolean; toggle?: boolean; delete?: boolean };+}++export function AutomationCard({+ task,+ template,+ highlighted,+ onRunNow,+ onSetEnabled,+ onDelete,+ busy,+}: AutomationCardProps) {+ const t = useT();+ const words = useScheduleWords();+ const stateLabels = useStateLabels();+ const [expanded, setExpanded] = useState(false);+ const [confirmDelete, setConfirmDelete] = useState(false);++ const Icon = templateIcon(template?.icon);+ const paused = task.state === "paused";+ const running = task.state === "running";+ const description = template?.description ?? "";+ const schedule = scheduleLineForTask(task, words);+ const lastState = task.last_run_state ?? null;++ return (+ <article+ id={`automation-${task.id}`}+ data-template-key={templateKeyOf(task) ?? undefined}+ className={cn(+ "card-outline flex flex-col transition-shadow",+ highlighted && "ring-2 ring-primary/60",+ paused && "opacity-75",+ )}+ >+ <div className="flex items-start gap-3 p-4">+ <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg border border-primary/30 bg-primary/10">+ <Icon className="h-4 w-4 text-primary" />+ </div>+ <div className="min-w-0 flex-1">+ <h3 className="truncate text-sm font-semibold">{task.title || t("tasks_view.untitled")}</h3>+ <CardDescription task={task} fallback={description} />+ </div>+ <Switch+ checked={!paused}+ disabled={busy?.toggle || running}+ onCheckedChange={(on) => onSetEnabled(task.id, on)}+ aria-label={paused ? t("automations_view.resume") : t("automations_view.pause")}+ title={paused ? t("automations_view.resume") : t("automations_view.pause")}+ />+ </div>++ <dl className="grid grid-cols-2 gap-x-3 gap-y-1 border-t border-border/60 px-4 py-3 text-[11px]">+ <dt className="text-muted-foreground">{t("automations_view.schedule_label")}</dt>+ <dd className="truncate text-right text-foreground">{schedule}</dd>+ <dt className="text-muted-foreground">{t("automations_view.next_run")}</dt>+ <dd className="text-right text-foreground">+ {running ? (+ <span className="text-primary">{t("tasks_view.running_now")}</span>+ ) : paused ? (+ <span>{stateLabels.paused}</span>+ ) : (+ <Countdown dueNs={task.next_due_at_ns ?? task.due_at_ns} />+ )}+ </dd>+ <dt className="text-muted-foreground">{t("automations_view.last_run")}</dt>+ <dd className="flex items-center justify-end gap-1.5 text-right">+ <StateDot state={lastState} />+ <span className="truncate">+ {lastState ? stateLabels[lastState] : t("automations_view.never_ran")}+ {task.finished_at_ns ? ` · ${formatWhen(task.finished_at_ns)}` : ""}+ </span>+ </dd>+ </dl>++ {(task.last_result || task.last_error) && (+ <p+ className={cn(+ "line-clamp-2 border-t border-border/60 px-4 py-2.5 text-xs leading-relaxed",+ task.last_error && !task.last_result ? "text-destructive/90" : "text-muted-foreground",+ )}+ >+ {task.last_result || task.last_error}+ </p>+ )}++ <div className="mt-auto flex items-center gap-1 border-t border-border/60 px-2 py-1.5">+ <Button+ size="sm"+ variant="ghost"+ onClick={() => onRunNow(task.id)}+ disabled={busy?.run || running}+ title={t("automations_view.run_now")}+ >+ {busy?.run ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Play className="h-3.5 w-3.5" />}+ <span className="ml-1.5 text-xs">{t("automations_view.run_now")}</span>+ </Button>+ <button+ type="button"+ onClick={() => setExpanded((x) => !x)}+ className="inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs text-muted-foreground transition-colors hover:text-foreground"+ aria-expanded={expanded}+ >+ {expanded ? <ChevronDown className="h-3.5 w-3.5" /> : <ChevronRight className="h-3.5 w-3.5" />}+ {t("automations_view.details")}+ </button>+ <div className="ml-auto flex items-center gap-1">+ {confirmDelete ? (+ <>+ <span className="text-[11px] text-muted-foreground">{t("automations_view.delete_confirm")}</span>+ <Button+ size="sm"+ variant="destructive"+ className="h-7 px-2 text-xs"+ disabled={busy?.delete}+ onClick={() => onDelete(task.id, isActive(task.state))}+ >+ {busy?.delete ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : t("tasks_view.delete")}+ </Button>+ <Button+ size="sm"+ variant="ghost"+ className="h-7 px-2 text-xs"+ onClick={() => setConfirmDelete(false)}+ >+ {t("automations_view.keep")}+ </Button>+ </>+ ) : (+ <Button+ size="sm"+ variant="ghost"+ onClick={() => setConfirmDelete(true)}+ title={t("tasks_view.delete")}+ aria-label={t("tasks_view.delete")}+ >+ <Trash2 className="h-3.5 w-3.5" />+ </Button>+ )}+ </div>+ </div>++ {expanded && <AutomationDetail taskId={task.id} fallbackResult={task.last_result} />}+ </article>+ );+}++/** Template description, else the prompt's first line (fetched lazily from+ * the detail spec only when there is no template to describe the task). */+function CardDescription({ task, fallback }: { task: TaskSummary; fallback: string }) {+ const needsSpec = !fallback;+ const { data } = useTaskDetail(task.id, needsSpec);+ const text = fallback || firstLine(promptOfSpec(data?.spec));+ if (!text) return null;+ return <p className="mt-0.5 line-clamp-2 text-xs leading-relaxed text-muted-foreground">{text}</p>;+}++function AutomationDetail({ taskId, fallbackResult }: { taskId: string; fallbackResult?: string | null }) {+ const t = useT();+ const { data, isLoading, error } = useTaskDetail(taskId);+ if (isLoading) {+ return (+ <div className="border-t border-border px-4 py-3 text-xs text-muted-foreground">+ {t("tasks_view.loading_details")}+ </div>+ );+ }+ if (error) {+ return (+ <div className="border-t border-border px-4 py-3 text-xs text-destructive">+ {t("common.error")}: {(error as Error).message}+ </div>+ );+ }+ const steps = data?.steps ?? [];+ return (+ <div className="space-y-3 border-t border-border px-4 py-3">+ <div>+ <SectionLabel className="mb-1.5">{t("automations_view.latest_result")}</SectionLabel>+ <ResultText steps={steps} fallback={fallbackResult} />+ </div>+ <div>+ <SectionLabel className="mb-1.5">+ {t("automations_view.timeline")} ({steps.length})+ </SectionLabel>+ <StepTimeline steps={steps} />+ </div>+ </div>+ );+}diff --git a/jarvis/ui/web/frontend/src/views/automations/CatalogueCard.tsx b/jarvis/ui/web/frontend/src/views/automations/CatalogueCard.tsxnew file mode 100644index 0000000000..27be9d27e5--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/automations/CatalogueCard.tsx@@ -0,0 +1,71 @@+/**+ * A catalogue entry: icon, name, description, default schedule and the Add+ * button. When the template is already installed the card says so and links+ * to the user's card; when a required plugin is missing it carries a quiet+ * "needs Gmail" hint (Add still works — the dialog repeats the warning).+ */+import { Check, Plus } from "lucide-react";+import { Button } from "@/components/ui/button";+import { fill, useT } from "@/i18n";+import { cn } from "@/lib/utils";+import { templateIcon } from "./automationIcons";+import { humanizeMissing, type AutomationTemplate } from "./automationsModel";++export interface CatalogueCardProps {+ template: AutomationTemplate;+ /** Id of the user's task created from this template, if installed. */+ installedTaskId?: string;+ onAdd: (template: AutomationTemplate) => void;+ onShowInstalled: (taskId: string) => void;+}++export function CatalogueCard({ template, installedTaskId, onAdd, onShowInstalled }: CatalogueCardProps) {+ const t = useT();+ const Icon = templateIcon(template.icon);+ const installed = Boolean(installedTaskId);++ return (+ <article+ data-testid={`catalogue-${template.key}`}+ className={cn("card-outline flex flex-col", installed && "border-primary/30")}+ >+ <div className="flex items-start gap-3 p-4">+ <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg border border-border bg-secondary/40">+ <Icon className="h-4 w-4 text-primary" />+ </div>+ <div className="min-w-0 flex-1">+ <h3 className="truncate text-sm font-semibold">{template.name}</h3>+ <p className="mt-0.5 line-clamp-3 text-xs leading-relaxed text-muted-foreground">+ {template.description}+ </p>+ </div>+ </div>+ <div className="mt-auto flex items-center gap-2 border-t border-border/60 px-4 py-2.5">+ <div className="min-w-0 flex-1">+ <div className="truncate text-[11px] text-muted-foreground">{template.schedule_label}</div>+ {!template.ready && template.missing.length > 0 && (+ <div className="truncate text-[11px] text-amber-600 dark:text-amber-400/90">+ {fill(t("automations_view.needs"), { tools: humanizeMissing(template.missing) })}+ </div>+ )}+ </div>+ {installed && installedTaskId ? (+ <button+ type="button"+ onClick={() => onShowInstalled(installedTaskId)}+ className="inline-flex items-center gap-1 rounded-md border border-primary/40 px-2.5 py-1 text-xs text-primary transition-colors hover:bg-primary/10"+ title={t("automations_view.show_installed")}+ >+ <Check className="h-3.5 w-3.5" />+ {t("automations_view.added")}+ </button>+ ) : (+ <Button size="sm" variant="outline" className="h-7 px-2.5 text-xs" onClick={() => onAdd(template)}>+ <Plus className="mr-1 h-3.5 w-3.5" />+ {t("automations_view.add")}+ </Button>+ )}+ </div>+ </article>+ );+}diff --git a/jarvis/ui/web/frontend/src/views/automations/TemplateAddDialog.tsx b/jarvis/ui/web/frontend/src/views/automations/TemplateAddDialog.tsxnew file mode 100644index 0000000000..76783587d2--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/automations/TemplateAddDialog.tsx@@ -0,0 +1,213 @@+/**+ * The compact "Add automation" dialog for a catalogue template: title+ * (prefilled), the template's inputs, and a schedule editor+ * (hourly / daily + time / weekly + weekday + time). Posts to+ * `POST /api/tasks/templates/{key}/add`.+ */+import { useMemo, useState } from "react";+import { AlertTriangle, Loader2, X } from "lucide-react";+import { Button } from "@/components/ui/button";+import { fill, useT, useUiLanguage } from "@/i18n";+import { cn } from "@/lib/utils";+import { ApiError, useAddTemplate } from "@/hooks/useAutomations";+import { templateIcon } from "./automationIcons";+import {+ humanizeMissing,+ type AutomationTemplate,+ type ScheduleKind,+ type TemplateSchedule,+} from "./automationsModel";+import { SectionLabel } from "./shared";++const inputCls =+ "w-full rounded-lg border border-border bg-background/60 px-3 py-2 text-sm text-foreground " ++ "placeholder:text-muted-foreground/60 focus:border-primary/60 focus:outline-none focus:ring-1 focus:ring-primary/40";++const KINDS: ScheduleKind[] = ["hourly", "daily", "weekly"];++export interface TemplateAddDialogProps {+ template: AutomationTemplate;+ onClose: () => void;+ onAdded: (taskId: string, template: AutomationTemplate) => void;+}++export function TemplateAddDialog({ template, onClose, onAdded }: TemplateAddDialogProps) {+ const t = useT();+ const locale = useUiLanguage();+ const Icon = templateIcon(template.icon);++ const [title, setTitle] = useState(template.name);+ const [values, setValues] = useState<Record<string, string>>(() =>+ Object.fromEntries(template.inputs.map((i) => [i.key, i.default ?? ""])),+ );+ const [kind, setKind] = useState<ScheduleKind>(template.schedule.kind);+ const [time, setTime] = useState(template.schedule.time || "08:00");+ const [weekday, setWeekday] = useState(template.schedule.weekday ?? 0);+ const [touched, setTouched] = useState(false);++ const addMut = useAddTemplate();++ const missingRequired = useMemo(+ () => template.inputs.filter((i) => i.required && !(values[i.key] ?? "").trim()),+ [template.inputs, values],+ );+ const valid = title.trim().length > 0 && missingRequired.length === 0 && /^\d{2}:\d{2}$/.test(time);++ const weekdays = [0, 1, 2, 3, 4, 5, 6].map((d) => t(`automations_view.weekday.${d}`));++ function submit() {+ setTouched(true);+ if (!valid) return;+ const schedule: TemplateSchedule = { kind, time, weekday };+ addMut.mutate(+ {+ key: template.key,+ payload: {+ inputs: Object.fromEntries(Object.entries(values).map(([k, v]) => [k, v.trim()])),+ schedule,+ title: title.trim(),+ locale,+ },+ },+ { onSuccess: (res) => onAdded(res.id, template) },+ );+ }++ const errorText = addMut.error+ ? addMut.error instanceof ApiError && addMut.error.status === 404+ ? t("automations_view.catalogue_unavailable")+ : `${t("automations_view.add_error")} (${(addMut.error as Error).message})`+ : null;++ return (+ <div+ className="fixed inset-0 z-50 flex items-center justify-center bg-scrim/60 p-4 backdrop-blur-sm"+ onClick={onClose}+ role="presentation"+ >+ <div+ role="dialog"+ aria-label={fill(t("automations_view.add_dialog_title"), { name: template.name })}+ className="flex max-h-[90vh] w-full max-w-lg flex-col overflow-hidden rounded-2xl border border-border bg-card shadow-2xl"+ onClick={(e) => e.stopPropagation()}+ >+ <div className="flex items-center justify-between border-b border-border px-5 py-4">+ <div className="flex items-center gap-2.5">+ <div className="flex h-8 w-8 items-center justify-center rounded-lg border border-primary/30 bg-primary/10">+ <Icon className="h-4 w-4 text-primary" />+ </div>+ <div className="min-w-0">+ <h2 className="truncate text-sm font-semibold">+ {fill(t("automations_view.add_dialog_title"), { name: template.name })}+ </h2>+ <p className="truncate text-[11px] text-muted-foreground">{template.description}</p>+ </div>+ </div>+ <Button size="sm" variant="ghost" onClick={onClose} aria-label={t("tasks_view.create.cancel")}>+ <X className="h-4 w-4" />+ </Button>+ </div>++ <div className="min-h-0 flex-1 overflow-y-auto scrollbar-jarvis">+ <div className="space-y-4 px-5 py-4">+ {!template.ready && template.missing.length > 0 && (+ <p className="flex items-start gap-1.5 rounded-lg border border-amber-500/40 px-3 py-2 text-[11px] leading-relaxed text-amber-700 dark:text-amber-300/90">+ <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />+ {fill(t("automations_view.needs_warning"), { tools: humanizeMissing(template.missing) })}+ </p>+ )}++ <label className="block space-y-1.5">+ <SectionLabel>{t("tasks_view.create.name_label")}</SectionLabel>+ <input+ className={inputCls}+ value={title}+ onChange={(e) => setTitle(e.target.value)}+ maxLength={256}+ />+ </label>++ {template.inputs.map((input) => {+ const invalid = touched && input.required && !(values[input.key] ?? "").trim();+ return (+ <label key={input.key} className="block space-y-1.5">+ <SectionLabel>+ {input.label}+ {input.required && <span className="ml-1 text-primary">*</span>}+ </SectionLabel>+ <input+ className={cn(inputCls, invalid && "border-destructive/70")}+ value={values[input.key] ?? ""}+ placeholder={input.placeholder || undefined}+ onChange={(e) => setValues((prev) => ({ ...prev, [input.key]: e.target.value }))}+ aria-invalid={invalid || undefined}+ maxLength={2048}+ />+ {invalid && (+ <span className="text-[11px] text-destructive">{t("automations_view.required")}</span>+ )}+ </label>+ );+ })}++ <div className="space-y-3 rounded-xl border border-border/70 p-4">+ <SectionLabel>{t("tasks_view.create.schedule_label")}</SectionLabel>+ <div className="inline-flex rounded-lg border border-border p-0.5">+ {KINDS.map((k) => (+ <button+ key={k}+ type="button"+ onClick={() => setKind(k)}+ className={cn(+ "rounded-md px-3 py-1.5 text-xs font-medium transition-colors",+ kind === k ? "bg-primary/15 text-primary" : "text-muted-foreground hover:text-foreground",+ )}+ >+ {t(`automations_view.kind.${k}`)}+ </button>+ ))}+ </div>+ {kind !== "hourly" && (+ <div className="flex flex-wrap items-center gap-2">+ {kind === "weekly" && (+ <select+ className={cn(inputCls, "w-auto")}+ value={weekday}+ onChange={(e) => setWeekday(Number(e.target.value))}+ aria-label={t("automations_view.weekday_label")}+ >+ {weekdays.map((name, idx) => (+ <option key={idx} value={idx}>+ {name}+ </option>+ ))}+ </select>+ )}+ <span className="text-xs text-muted-foreground">{t("tasks_view.create.at")}</span>+ <input+ type="time"+ className={cn(inputCls, "w-32")}+ value={time}+ onChange={(e) => setTime(e.target.value)}+ aria-label={t("automations_view.time_label")}+ />+ </div>+ )}+ </div>+ </div>+ </div>++ <div className="flex items-center justify-end gap-2 border-t border-border px-5 py-3">+ {errorText && <span className="mr-auto text-xs text-destructive">{errorText}</span>}+ <Button variant="ghost" size="sm" onClick={onClose}>+ {t("tasks_view.create.cancel")}+ </Button>+ <Button size="sm" disabled={addMut.isPending || (touched && !valid)} onClick={submit}>+ {addMut.isPending && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}+ {t("automations_view.add")}+ </Button>+ </div>+ </div>+ </div>+ );+}diff --git a/jarvis/ui/web/frontend/src/views/automations/automationIcons.ts b/jarvis/ui/web/frontend/src/views/automations/automationIcons.tsnew file mode 100644index 0000000000..03775ef054--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/automations/automationIcons.ts@@ -0,0 +1,201 @@+/**+ * Template icon resolver — a template names a lucide icon in kebab-case+ * (`"dollar-sign"`, `"cloud-sun"`); this maps it to the imported component.+ *+ * A curated map rather than lucide's `icons` bag on purpose: importing the+ * whole bag pulls every icon into the entry chunk. Unknown names fall back+ * to Sparkles, so a new template with a typo still renders a card.+ */+import {+ Activity,+ AlarmClock,+ Banknote,+ BarChart3,+ Bell,+ BookOpen,+ Bookmark,+ Bot,+ Brain,+ Briefcase,+ Bug,+ Calendar,+ CalendarDays,+ Camera,+ ChartLine,+ ChartNoAxesCombined,+ CircleDollarSign,+ ClipboardList,+ Clock,+ CloudSun,+ Code,+ Coffee,+ Coins,+ Compass,+ Cpu,+ Database,+ DollarSign,+ Dumbbell,+ FileText,+ Film,+ FlaskConical,+ Folder,+ FolderGit2,+ Github,+ GitBranch,+ GitCommitHorizontal,+ GitPullRequest,+ Globe,+ GraduationCap,+ Heart,+ Image,+ Inbox,+ Landmark,+ Languages,+ Layers,+ Lightbulb,+ LineChart,+ Link,+ ListTodo,+ Mail,+ MapPin,+ Megaphone,+ MessageSquare,+ Microscope,+ Moon,+ Music,+ Newspaper,+ Notebook,+ Package,+ PenLine,+ Percent,+ PieChart,+ Plane,+ Radio,+ Receipt,+ Repeat,+ Rocket,+ Rss,+ Scale,+ Search,+ Send,+ Server,+ Shield,+ ShoppingCart,+ Sparkles,+ Star,+ Sun,+ Sunrise,+ Target,+ Terminal,+ Timer,+ Train,+ TrendingUp,+ Tv,+ Users,+ Utensils,+ Wallet,+ Youtube,+ Zap,+ type LucideIcon,+} from "lucide-react";++const ICONS: Record<string, LucideIcon> = {+ activity: Activity,+ "alarm-clock": AlarmClock,+ banknote: Banknote,+ "bar-chart": BarChart3,+ "bar-chart-3": BarChart3,+ bell: Bell,+ "book-open": BookOpen,+ bookmark: Bookmark,+ bot: Bot,+ brain: Brain,+ briefcase: Briefcase,+ bug: Bug,+ calendar: Calendar,+ "calendar-days": CalendarDays,+ camera: Camera,+ "chart-line": ChartLine,+ "chart-no-axes-combined": ChartNoAxesCombined,+ "circle-dollar-sign": CircleDollarSign,+ "clipboard-list": ClipboardList,+ clock: Clock,+ "cloud-sun": CloudSun,+ code: Code,+ coffee: Coffee,+ coins: Coins,+ compass: Compass,+ cpu: Cpu,+ database: Database,+ "dollar-sign": DollarSign,+ dumbbell: Dumbbell,+ "file-text": FileText,+ film: Film,+ "flask-conical": FlaskConical,+ folder: Folder,+ "folder-git-2": FolderGit2,+ github: Github,+ "git-branch": GitBranch,+ "git-commit-horizontal": GitCommitHorizontal,+ "git-pull-request": GitPullRequest,+ globe: Globe,+ "graduation-cap": GraduationCap,+ heart: Heart,+ image: Image,+ inbox: Inbox,+ landmark: Landmark,+ languages: Languages,+ layers: Layers,+ lightbulb: Lightbulb,+ "line-chart": LineChart,+ link: Link,+ "list-todo": ListTodo,+ mail: Mail,+ "map-pin": MapPin,+ megaphone: Megaphone,+ "message-square": MessageSquare,+ microscope: Microscope,+ moon: Moon,+ music: Music,+ newspaper: Newspaper,+ notebook: Notebook,+ package: Package,+ "pen-line": PenLine,+ percent: Percent,+ "pie-chart": PieChart,+ plane: Plane,+ radio: Radio,+ receipt: Receipt,+ repeat: Repeat,+ rocket: Rocket,+ rss: Rss,+ scale: Scale,+ search: Search,+ send: Send,+ server: Server,+ shield: Shield,+ "shopping-cart": ShoppingCart,+ sparkles: Sparkles,+ star: Star,+ sun: Sun,+ sunrise: Sunrise,+ target: Target,+ terminal: Terminal,+ timer: Timer,+ train: Train,+ "trending-up": TrendingUp,+ tv: Tv,+ users: Users,+ utensils: Utensils,+ wallet: Wallet,+ youtube: Youtube,+ zap: Zap,+};++export const DEFAULT_AUTOMATION_ICON: LucideIcon = Sparkles;++/** Resolve a lucide kebab-case name; unknown or empty → Sparkles. */+export function templateIcon(name: string | null | undefined): LucideIcon {+ if (!name) return DEFAULT_AUTOMATION_ICON;+ return ICONS[name.trim().toLowerCase()] ?? DEFAULT_AUTOMATION_ICON;+}diff --git a/jarvis/ui/web/frontend/src/views/automations/automationsModel.test.ts b/jarvis/ui/web/frontend/src/views/automations/automationsModel.test.tsnew file mode 100644index 0000000000..2f9b6f1643--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/automations/automationsModel.test.ts@@ -0,0 +1,145 @@+import { describe, expect, it } from "vitest";+import {+ extractAgentResult,+ filterRuns,+ firstLine,+ formatDuration,+ groupTemplates,+ humanizeMissing,+ scheduleLineForTask,+ selectAutomations,+ selectRuns,+ templateKeyOf,+ type AutomationTemplate,+ type ScheduleWords,+ type TaskSummary,+} from "./automationsModel";++const WORDS: ScheduleWords = {+ hourly: "Every hour",+ daily: "Daily at {time}",+ weekly: "{day} at {time}",+ everyMinutes: "Every {n} min",+ everyHours: "Every {n} h",+ onEvent: "When an event fires",+ weekdays: ["Mondays", "Tuesdays", "Wednesdays", "Thursdays", "Fridays", "Saturdays", "Sundays"],+};++function task(over: Partial<TaskSummary>): TaskSummary {+ return {+ id: "t",+ title: "T",+ state: "scheduled",+ trigger_type: "every",+ due_at_ns: null,+ created_at_ns: 1,+ started_at_ns: null,+ finished_at_ns: null,+ attempts: 0,+ last_error: null,+ ...over,+ };+}++/** ns timestamp of a local wall-clock moment. */+function localNs(y: number, m: number, d: number, hh: number, mm: number): number {+ return new Date(y, m - 1, d, hh, mm, 0, 0).getTime() * 1e6;+}++describe("scheduleLineForTask", () => {+ it("derives the daily time from the next due moment", () => {+ const line = scheduleLineForTask(+ task({ interval_seconds: 86_400, next_due_at_ns: localNs(2026, 8, 25, 7, 30) }),+ WORDS,+ );+ expect(line).toBe("Daily at 07:30");+ });++ it("names the weekday for a weekly interval (Monday-based)", () => {+ // 2026-08-24 is a Monday.+ const line = scheduleLineForTask(+ task({ interval_seconds: 7 * 86_400, next_due_at_ns: localNs(2026, 8, 24, 9, 0) }),+ WORDS,+ );+ expect(line).toBe("Mondays at 09:00");+ });++ it("handles hourly, custom and event triggers", () => {+ expect(scheduleLineForTask(task({ interval_seconds: 3600 }), WORDS)).toBe("Every hour");+ expect(scheduleLineForTask(task({ interval_seconds: 1800 }), WORDS)).toBe("Every 30 min");+ expect(scheduleLineForTask(task({ interval_seconds: 7200 }), WORDS)).toBe("Every 2 h");+ expect(scheduleLineForTask(task({ trigger_type: "on_event" }), WORDS)).toBe("When an event fires");+ });++ it("falls back to the legacy due_at_ns when next_due_at_ns is absent (old backend)", () => {+ const line = scheduleLineForTask(+ task({ interval_seconds: 86_400, due_at_ns: localNs(2026, 8, 25, 18, 5) }),+ WORDS,+ );+ expect(line).toBe("Daily at 18:05");+ });+});++describe("selection", () => {+ const recurring = task({ id: "a", trigger_type: "every", state: "scheduled", created_at_ns: 5 });+ const paused = task({ id: "b", trigger_type: "every", state: "paused", created_at_ns: 9 });+ const finishedRecurring = task({ id: "c", trigger_type: "every", state: "cancelled", finished_at_ns: 3 });+ const oneShotPending = task({ id: "d", trigger_type: "at_time", state: "scheduled", due_at_ns: 2 });+ const oneShotDone = task({ id: "e", trigger_type: "after_delay", state: "completed", finished_at_ns: 8 });+ const running = task({ id: "f", trigger_type: "every", state: "running", started_at_ns: 7 });+ const all = [recurring, paused, finishedRecurring, oneShotPending, oneShotDone, running];++ it("automations = active recurring tasks, newest first", () => {+ expect(selectAutomations(all).map((t) => t.id)).toEqual(["b", "a", "f"]);+ });++ it("runs = ran/running + pending one-shots, newest activity first", () => {+ expect(selectRuns(all).map((t) => t.id)).toEqual(["e", "f", "c", "d"]);+ });++ it("filters runs by chip", () => {+ const runs = selectRuns(all);+ expect(filterRuns(runs, "done").map((t) => t.id)).toEqual(["e"]);+ expect(filterRuns(runs, "problems").map((t) => t.id)).toEqual(["c"]);+ expect(filterRuns(runs, "running").map((t) => t.id)).toEqual(["f", "d"]);+ });+});++describe("helpers", () => {+ it("reads the template key from the tag", () => {+ expect(templateKeyOf({ tags: ["x", "template:morning_briefing"] })).toBe("morning_briefing");+ expect(templateKeyOf({ tags: [] })).toBeNull();+ expect(templateKeyOf({})).toBeNull();+ });++ it("extracts the latest agent_result step text", () => {+ expect(+ extractAgentResult([+ { seq: 1, kind: "log", payload: { event: "agent_result", text: "old" }, timestamp_ns: 1 },+ { seq: 2, kind: "log", payload: { event: "tool", text: "x" }, timestamp_ns: 2 },+ { seq: 3, kind: "log", payload: { event: "agent_result", text: "new" }, timestamp_ns: 3 },+ ]),+ ).toBe("new");+ expect(extractAgentResult([])).toBeNull();+ });++ it("formats durations and first lines", () => {+ expect(formatDuration(0, 42e9)).toBe("42s");+ expect(formatDuration(0, 125e9)).toBe("2m 5s");+ expect(formatDuration(null, 5)).toBeNull();+ expect(firstLine("\n\n Summarise my day.\nSecond line")).toBe("Summarise my day.");+ expect(firstLine("a".repeat(200), 10)).toHaveLength(10);+ });++ it("humanizes missing tools", () => {+ expect(humanizeMissing(["gmail", "google_calendar", "github"])).toBe("Gmail, Google Calendar, GitHub");+ expect(humanizeMissing(["some_new_tool"])).toBe("Some New Tool");+ });++ it("groups templates in catalogue order and keeps unknown categories", () => {+ const tpl = (key: string, category: string) =>+ ({ key, category } as unknown as AutomationTemplate);+ const groups = groupTemplates([tpl("a", "developer"), tpl("b", "news"), tpl("c", "future")]);+ expect(groups.map((g) => g.category)).toEqual(["news", "developer", "future"]);+ });+});diff --git a/jarvis/ui/web/frontend/src/views/automations/automationsModel.ts b/jarvis/ui/web/frontend/src/views/automations/automationsModel.tsnew file mode 100644index 0000000000..44f3d88228--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/automations/automationsModel.ts@@ -0,0 +1,360 @@+/**+ * Pure model for the Automations section — types mirroring the tasks API and+ * the small derivations the cards need (schedule line, countdown, template+ * pairing, result extraction). Kept free of React so the parts that are easy+ * to get wrong (interval → "Daily at 07:30", the run-history ordering) are+ * unit-testable in isolation.+ *+ * Mirrors `jarvis/tasks/schema.py` (`TASK_STATES`) and+ * `jarvis/tasks/templates/__init__.py` (`AutomationTemplate.to_api`).+ */++export type TaskState =+ | "pending"+ | "scheduled"+ | "running"+ | "paused"+ | "completed"+ | "failed"+ | "cancelled"+ | "interrupted";++export type TriggerType = "after_delay" | "at_time" | "on_event" | "every";++export interface TaskSummary {+ id: string;+ title: string;+ state: TaskState;+ trigger_type: TriggerType;+ due_at_ns: number | null;+ created_at_ns: number | null;+ started_at_ns: number | null;+ finished_at_ns: number | null;+ attempts: number;+ last_error: string | null;+ // Added with the automations campaign — older backends omit them, so every+ // field is optional and the view degrades to the pre-campaign behaviour.+ tags?: string[];+ created_by?: string | null;+ interval_seconds?: number | null;+ next_due_at_ns?: number | null;+ last_run_state?: TaskState | null;+ last_result?: string | null;+}++export interface TaskStep {+ seq: number;+ kind: string;+ payload: Record<string, unknown>;+ timestamp_ns: number;+}++export interface TaskDetail extends TaskSummary {+ spec: Record<string, unknown> | null;+ steps: TaskStep[];+}++export interface TasksListResponse {+ tasks: TaskSummary[];+ total: number;+}++export type TemplateCategory = "news" | "productivity" | "finance" | "research" | "developer";++/** Catalogue section order — mirrors `CATEGORIES` in the template package. */+export const TEMPLATE_CATEGORIES: readonly TemplateCategory[] = [+ "news",+ "productivity",+ "finance",+ "research",+ "developer",+];++export type ScheduleKind = "hourly" | "daily" | "weekly";++export interface TemplateSchedule {+ kind: ScheduleKind;+ time: string; // "HH:MM"+ weekday: number; // 0 = Monday … 6 = Sunday (Python weekday())+}++export interface TemplateInput {+ key: string;+ label: string;+ placeholder: string;+ default: string;+ required: boolean;+}++export interface AutomationTemplate {+ key: string;+ category: TemplateCategory;+ icon: string;+ name: string;+ description: string;+ schedule: TemplateSchedule;+ schedule_label: string;+ plugin_grants: { plugin_id: string; scope: string }[];+ requires: string[];+ missing: string[];+ ready: boolean;+ inputs: TemplateInput[];+ model_tier: "fast" | "deep" | "auto";+ tags: string[];+ prompt: string;+}++export interface TemplatesResponse {+ templates: AutomationTemplate[];+ categories: TemplateCategory[];+}++export const TEMPLATE_TAG_PREFIX = "template:";++export const TERMINAL_STATES: readonly TaskState[] = [+ "completed",+ "failed",+ "cancelled",+ "interrupted",+];++export const ACTIVE_STATES: readonly TaskState[] = ["pending", "scheduled", "running", "paused"];++export function isTerminal(state: TaskState): boolean {+ return TERMINAL_STATES.includes(state);+}++export function isActive(state: TaskState): boolean {+ return ACTIVE_STATES.includes(state);+}++/** A recurring task (an "automation") — the `every` / `on_event` triggers. */+export function isRecurringTrigger(trigger: TriggerType): boolean {+ return trigger === "every" || trigger === "on_event";+}++/** The template key a task was created from (`template:<key>` tag), if any. */+export function templateKeyOf(task: Pick<TaskSummary, "tags">): string | null {+ for (const tag of task.tags ?? []) {+ if (tag.startsWith(TEMPLATE_TAG_PREFIX)) return tag.slice(TEMPLATE_TAG_PREFIX.length);+ }+ return null;+}++/**+ * The user's automations: every recurring task that is not finished. Newest+ * first so a freshly added one lands at the top of the grid.+ */+export function selectAutomations(tasks: TaskSummary[]): TaskSummary[] {+ return tasks+ .filter((t) => isRecurringTrigger(t.trigger_type) && !isTerminal(t.state))+ .sort((a, b) => (b.created_at_ns ?? 0) - (a.created_at_ns ?? 0));+}++/**+ * The run history: everything that ran or is running (any trigger), plus the+ * still-pending one-shots (after_delay / at_time) so they have a home too.+ * Newest activity first.+ */+export function selectRuns(tasks: TaskSummary[]): TaskSummary[] {+ return tasks+ .filter(+ (t) =>+ isTerminal(t.state) ||+ t.state === "running" ||+ (!isRecurringTrigger(t.trigger_type) && isActive(t.state)),+ )+ .sort((a, b) => activityNs(b) - activityNs(a));+}++function activityNs(t: TaskSummary): number {+ return t.finished_at_ns ?? t.started_at_ns ?? t.due_at_ns ?? t.created_at_ns ?? 0;+}++export type RunFilter = "all" | "running" | "done" | "problems";++export function filterRuns(runs: TaskSummary[], filter: RunFilter): TaskSummary[] {+ switch (filter) {+ case "running":+ return runs.filter((r) => r.state === "running" || r.state === "pending" || r.state === "scheduled");+ case "done":+ return runs.filter((r) => r.state === "completed");+ case "problems":+ return runs.filter(+ (r) => r.state === "failed" || r.state === "interrupted" || r.state === "cancelled",+ );+ default:+ return runs;+ }+}++/** The kind of schedule an interval encodes; `null` for odd custom intervals. */+export function scheduleKindOf(intervalSeconds: number | null | undefined): ScheduleKind | null {+ if (!intervalSeconds) return null;+ if (intervalSeconds === 3600) return "hourly";+ if (intervalSeconds === 86_400) return "daily";+ if (intervalSeconds === 7 * 86_400) return "weekly";+ return null;+}++export interface ScheduleWords {+ hourly: string; // "Every hour"+ daily: string; // "Daily at {time}"+ weekly: string; // "{day} at {time}"+ everyMinutes: string; // "Every {n} min"+ everyHours: string; // "Every {n} h"+ onEvent: string; // "When an event fires"+ weekdays: string[]; // Monday … Sunday (plural forms, 7 entries)+}++function pad2(n: number): string {+ return String(n).padStart(2, "0");+}++export function localTimeHHMM(ns: number): string {+ const d = new Date(ns / 1e6);+ return `${pad2(d.getHours())}:${pad2(d.getMinutes())}`;+}++/** Monday-based weekday (Python `weekday()`), from a JS Date. */+export function mondayWeekday(d: Date): number {+ return (d.getDay() + 6) % 7;+}++/**+ * "Daily at 07:30" for a task, derived from its interval and the next due+ * moment (the wall-clock time of the next occurrence IS the schedule time).+ */+export function scheduleLineForTask(+ task: Pick<TaskSummary, "trigger_type" | "interval_seconds" | "next_due_at_ns" | "due_at_ns">,+ words: ScheduleWords,+): string {+ if (task.trigger_type === "on_event") return words.onEvent;+ const interval = task.interval_seconds ?? null;+ const dueNs = task.next_due_at_ns ?? task.due_at_ns ?? null;+ const kind = scheduleKindOf(interval);+ if (kind === "hourly") return words.hourly;+ if (kind === "daily") {+ return dueNs ? words.daily.replace("{time}", localTimeHHMM(dueNs)) : words.daily.replace("{time}", "—");+ }+ if (kind === "weekly") {+ if (!dueNs) return words.weekly.replace("{day}", "—").replace("{time}", "—");+ const d = new Date(dueNs / 1e6);+ const day = words.weekdays[mondayWeekday(d)] ?? "";+ return words.weekly.replace("{day}", day).replace("{time}", localTimeHHMM(dueNs));+ }+ if (interval) {+ if (interval % 3600 === 0) return words.everyHours.replace("{n}", String(interval / 3600));+ return words.everyMinutes.replace("{n}", String(Math.max(1, Math.round(interval / 60))));+ }+ return "—";+}++/** Compact countdown: "42s", "7min", "3h", "2d". Never negative. */+export function formatDelta(ns: number): string {+ const sec = Math.max(0, Math.round(ns / 1e9));+ if (sec < 60) return `${sec}s`;+ const min = Math.round(sec / 60);+ if (min < 60) return `${min}min`;+ const hr = Math.round(min / 60);+ if (hr < 48) return `${hr}h`;+ const day = Math.round(hr / 24);+ return `${day}d`;+}++/** Duration between two ns timestamps, "1m 12s" style; `null` if unknown. */+export function formatDuration(startNs: number | null, endNs: number | null): string | null {+ if (startNs == null || endNs == null || endNs < startNs) return null;+ const sec = Math.round((endNs - startNs) / 1e9);+ if (sec < 60) return `${sec}s`;+ const min = Math.floor(sec / 60);+ const rest = sec % 60;+ if (min < 60) return rest ? `${min}m ${rest}s` : `${min}m`;+ const hr = Math.floor(min / 60);+ return `${hr}h ${min % 60}m`;+}++/** The first non-empty line of a prompt, trimmed to a card-sized preview. */+export function firstLine(text: string | null | undefined, max = 140): string {+ const line = (text ?? "")+ .split(/\r?\n/)+ .map((l) => l.trim())+ .find((l) => l.length > 0);+ if (!line) return "";+ return line.length > max ? `${line.slice(0, max - 1)}…` : line;+}++/** The text of the latest `agent_result` log step, if the run produced one. */+export function extractAgentResult(steps: TaskStep[] | undefined): string | null {+ if (!steps) return null;+ for (let i = steps.length - 1; i >= 0; i--) {+ const p = steps[i].payload;+ if (p && p.event === "agent_result" && typeof p.text === "string") return p.text;+ }+ return null;+}++/** The prompt of an agent action from a task spec, when present. */+export function promptOfSpec(spec: Record<string, unknown> | null | undefined): string {+ const action = spec?.action as Record<string, unknown> | undefined;+ const prompt = action?.prompt;+ return typeof prompt === "string" ? prompt : "";+}++/** "gmail" → "Gmail", "google_calendar" → "Google Calendar", "github" → "GitHub". */+export function humanizeToolName(name: string): string {+ const special: Record<string, string> = {+ gmail: "Gmail",+ github: "GitHub",+ google_calendar: "Google Calendar",+ google_drive: "Google Drive",+ search_web: "Web search",+ youtube_music: "YouTube Music",+ linear: "Linear",+ "wiki-recall": "Wiki",+ "ultrawiki-search": "Wiki",+ "notebooklm-mcp": "NotebookLM",+ run_shell: "Shell",+ };+ if (special[name]) return special[name];+ return name+ .split(/[_\-/]/)+ .filter(Boolean)+ .map((w) => w[0].toUpperCase() + w.slice(1))+ .join(" ");+}++export function humanizeMissing(missing: string[]): string {+ return missing.map(humanizeToolName).join(", ");+}++/** Summarise a step payload for the timeline row. */+export function summarizePayload(p: Record<string, unknown>): string {+ try {+ if (p && typeof p.event === "string") {+ const text = typeof p.text === "string" ? p.text : "";+ const rest = text ? `${p.event}: ${text}` : String(p.event);+ return rest.length > 160 ? `${rest.slice(0, 159)}…` : rest;+ }+ const s = JSON.stringify(p);+ return s.length > 160 ? `${s.slice(0, 159)}…` : s;+ } catch {+ return "(unreadable)";+ }+}++/** Group templates by category in catalogue order; empty categories are skipped. */+export function groupTemplates(+ templates: AutomationTemplate[],+): { category: TemplateCategory; templates: AutomationTemplate[] }[] {+ const out: { category: TemplateCategory; templates: AutomationTemplate[] }[] = [];+ for (const category of TEMPLATE_CATEGORIES) {+ const items = templates.filter((t) => t.category === category);+ if (items.length) out.push({ category, templates: items });+ }+ // Unknown categories (a future backend) land at the end rather than vanish.+ const known = new Set<string>(TEMPLATE_CATEGORIES);+ const other = templates.filter((t) => !known.has(t.category));+ if (other.length) out.push({ category: other[0].category, templates: other });+ return out;+}diff --git a/jarvis/ui/web/frontend/src/views/automations/shared.tsx b/jarvis/ui/web/frontend/src/views/automations/shared.tsxnew file mode 100644index 0000000000..9cb2e86948--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/automations/shared.tsx@@ -0,0 +1,186 @@+/**+ * Small building blocks shared by the Automations cards and the Runs tab:+ * the state dot, the live countdown, the schedule words, the step timeline+ * and the readable result block. All colours come from theme tokens (plus+ * the two semantic tailwind hues the rest of the app already uses for+ * "good" and "attention"), so light mode keeps its ink-outline look.+ */+import { useEffect, useMemo, useState } from "react";+import { useT } from "@/i18n";+import { cn } from "@/lib/utils";+import {+ extractAgentResult,+ formatDelta,+ summarizePayload,+ type ScheduleWords,+ type TaskState,+ type TaskStep,+} from "./automationsModel";++export function useScheduleWords(): ScheduleWords {+ const t = useT();+ return useMemo(+ () => ({+ hourly: t("automations_view.schedule.hourly"),+ daily: t("automations_view.schedule.daily"),+ weekly: t("automations_view.schedule.weekly"),+ everyMinutes: t("automations_view.schedule.every_minutes"),+ everyHours: t("automations_view.schedule.every_hours"),+ onEvent: t("automations_view.schedule.on_event"),+ weekdays: [+ t("automations_view.weekday.0"),+ t("automations_view.weekday.1"),+ t("automations_view.weekday.2"),+ t("automations_view.weekday.3"),+ t("automations_view.weekday.4"),+ t("automations_view.weekday.5"),+ t("automations_view.weekday.6"),+ ],+ }),+ [t],+ );+}++export function useStateLabels(): Record<TaskState, string> {+ const t = useT();+ return useMemo(+ () => ({+ pending: t("tasks_view.state.pending"),+ scheduled: t("tasks_view.state.scheduled"),+ running: t("tasks_view.state.running"),+ paused: t("tasks_view.state.paused"),+ completed: t("tasks_view.state.completed"),+ failed: t("tasks_view.state.failed"),+ cancelled: t("tasks_view.state.cancelled"),+ interrupted: t("tasks_view.state.interrupted"),+ }),+ [t],+ );+}++const DOT_CLASS: Record<TaskState, string> = {+ pending: "bg-muted-foreground/50",+ scheduled: "bg-primary",+ running: "bg-primary animate-pulse",+ paused: "bg-muted-foreground/50",+ completed: "bg-emerald-500",+ failed: "bg-destructive",+ cancelled: "bg-muted-foreground/50",+ interrupted: "bg-amber-500",+};++/** A coloured state dot with the localized state as its accessible name. */+export function StateDot({ state, className }: { state: TaskState | null | undefined; className?: string }) {+ const labels = useStateLabels();+ if (!state) {+ return (+ <span+ aria-hidden+ className={cn("inline-block h-2 w-2 shrink-0 rounded-full border border-border", className)}+ />+ );+ }+ return (+ <span+ role="img"+ aria-label={labels[state]}+ title={labels[state]}+ className={cn("inline-block h-2 w-2 shrink-0 rounded-full", DOT_CLASS[state], className)}+ />+ );+}++/** Re-renders once a second so countdowns tick. */+export function useTick(): number {+ const [tick, setTick] = useState(0);+ useEffect(() => {+ const timer = setInterval(() => setTick((x) => x + 1), 1000);+ return () => clearInterval(timer);+ }, []);+ return tick;+}++/** "in 7min" / "due now" for a future ns timestamp. */+export function Countdown({ dueNs }: { dueNs: number | null | undefined }) {+ const t = useT();+ useTick();+ if (!dueNs) return <span>—</span>;+ const delta = dueNs - Date.now() * 1e6;+ if (delta <= 0) return <span>{t("tasks_view.due_now")}</span>;+ return (+ <span>+ {t("tasks_view.in_prefix")} {formatDelta(delta)}+ </span>+ );+}++export function formatWhen(ns: number | null | undefined, locale?: string): string {+ if (!ns) return "";+ try {+ const d = new Date(ns / 1e6);+ const sameDay = d.toDateString() === new Date().toDateString();+ return sameDay+ ? d.toLocaleTimeString(locale, { hour: "2-digit", minute: "2-digit" })+ : d.toLocaleString(locale, {+ day: "2-digit",+ month: "2-digit",+ hour: "2-digit",+ minute: "2-digit",+ });+ } catch {+ return "";+ }+}++/** The run's result as readable text (the `agent_result` step), never raw JSON. */+export function ResultText({ steps, fallback }: { steps: TaskStep[] | undefined; fallback?: string | null }) {+ const t = useT();+ const text = extractAgentResult(steps) ?? fallback ?? null;+ if (!text) {+ return <p className="text-xs text-muted-foreground">{t("automations_view.no_result_yet")}</p>;+ }+ return (+ <div+ data-testid="run-result"+ className="whitespace-pre-wrap rounded-xl border border-border/70 bg-background/30 px-4 py-3 text-sm leading-relaxed text-foreground"+ >+ {text}+ </div>+ );+}++/** The step timeline of one run. */+export function StepTimeline({ steps }: { steps: TaskStep[] }) {+ const t = useT();+ if (steps.length === 0) {+ return <div className="text-xs text-muted-foreground">{t("tasks_view.no_steps")}</div>;+ }+ return (+ <ol className="space-y-1">+ {steps.map((s) => (+ <li+ key={s.seq}+ className="flex items-start gap-3 rounded-md border border-border/60 px-2.5 py-1.5 text-[11px]"+ >+ <span className="w-5 shrink-0 font-mono text-muted-foreground">{s.seq}</span>+ <span className="w-20 shrink-0 text-primary">{s.kind}</span>+ <span className="min-w-0 flex-1 break-words text-muted-foreground">+ {summarizePayload(s.payload)}+ </span>+ <span className="shrink-0 font-mono text-muted-foreground/70">+ {formatWhen(s.timestamp_ns)}+ </span>+ </li>+ ))}+ </ol>+ );+}++/** Section label — small caps, the way the rest of the app labels groups. */+export function SectionLabel({ children, className }: { children: React.ReactNode; className?: string }) {+ return (+ <div className={cn("text-[11px] font-medium uppercase tracking-wider text-muted-foreground", className)}>+ {children}+ </div>+ );+}diff --git a/jarvis/ui/web/frontend/src/views/tasks/TaskCreateDialog.tsx b/jarvis/ui/web/frontend/src/views/tasks/TaskCreateDialog.tsxindex 7f8eaf497b..fdf6a3b463 100644--- a/jarvis/ui/web/frontend/src/views/tasks/TaskCreateDialog.tsx+++ b/jarvis/ui/web/frontend/src/views/tasks/TaskCreateDialog.tsx@@ -118,31 +118,53 @@ const inputCls ="w-full rounded-lg border border-border bg-background/60 px-3 py-2 text-sm text-foreground " +"placeholder:text-muted-foreground/60 focus:border-primary/60 focus:outline-none focus:ring-1 focus:ring-primary/40";-export function TaskCreateDialog({ onClose }: { onClose: () => void }) {+export interface TaskCreateDialogProps {+ onClose: () => void;+ /** Optional prefill (a template, a voice command). Every field is optional;+ * anything absent keeps the dialog's own default. */+ initialDraft?: Partial<TaskDraft>;+}++export function TaskCreateDialog({ onClose, initialDraft }: TaskCreateDialogProps) {const t = useT();const uiLang = useUiLanguage();const qc = useQueryClient();+ const init = initialDraft ?? {};- const [title, setTitle] = useState("");- const [prompt, setPrompt] = useState("");- const [triggerMode, setTriggerMode] = useState<"schedule" | "event">("schedule");- const [whenKey, setWhenKey] = useState<WhenKey>("mission_succeeded");- const [thenKind, setThenKind] = useState<ThenKind>("computer_use");- const [cuPrompt, setCuPrompt] = useState("");- const [announceText, setAnnounceText] = useState("");- const [scheduleMode, setScheduleMode] = useState<"once" | "recurring">("recurring");- const [onceMode, setOnceMode] = useState<"delay" | "at_time">("at_time");- const [delayValue, setDelayValue] = useState(1);- const [delayUnit, setDelayUnit] = useState<"minutes" | "hours">("hours");+ const [title, setTitle] = useState(init.title ?? "");+ const [prompt, setPrompt] = useState(init.prompt ?? "");+ const [triggerMode, setTriggerMode] = useState<"schedule" | "event">(init.triggerMode ?? "schedule");+ const [whenKey, setWhenKey] = useState<WhenKey>(init.whenKey ?? "mission_succeeded");+ const [thenKind, setThenKind] = useState<ThenKind>(init.thenKind ?? "computer_use");+ const [cuPrompt, setCuPrompt] = useState(init.cuPrompt ?? "");+ const [announceText, setAnnounceText] = useState(init.announceText ?? "");+ const [scheduleMode, setScheduleMode] = useState<"once" | "recurring">(init.scheduleMode ?? "recurring");+ const [onceMode, setOnceMode] = useState<"delay" | "at_time">(init.onceMode ?? "at_time");+ const [delayValue, setDelayValue] = useState(() =>+ init.delaySeconds ? Math.max(1, Math.round(init.delaySeconds / (init.delaySeconds >= 3600 ? 3600 : 60))) : 1,+ );+ const [delayUnit, setDelayUnit] = useState<"minutes" | "hours">(+ init.delaySeconds && init.delaySeconds < 3600 ? "minutes" : "hours",+ );// Pre-fill with a real, editable value (now + 1h) so the native picker never// shows the browser's raw, locale-ugly "TT.mm.jjjj --:--" empty placeholder.- const [atTimeLocal, setAtTimeLocal] = useState(() => defaultAtTimeLocal());- const [recurringMode, setRecurringMode] = useState<"hourly" | "daily" | "custom">("daily");- const [dailyTime, setDailyTime] = useState("07:00");- const [customValue, setCustomValue] = useState(30);- const [customUnit, setCustomUnit] = useState<"minutes" | "hours">("minutes");- const [modelTier, setModelTier] = useState<ModelTier>("auto");- const [grants, setGrants] = useState<Record<string, ScopeValue>>({});+ const [atTimeLocal, setAtTimeLocal] = useState(() => init.atTimeLocal || defaultAtTimeLocal());+ const [recurringMode, setRecurringMode] = useState<"hourly" | "daily" | "custom">(+ init.recurringMode ?? "daily",+ );+ const [dailyTime, setDailyTime] = useState(init.dailyTime ?? "07:00");+ const [customValue, setCustomValue] = useState(() =>+ init.customIntervalSeconds+ ? Math.max(1, Math.round(init.customIntervalSeconds / (init.customIntervalSeconds >= 3600 ? 3600 : 60)))+ : 30,+ );+ const [customUnit, setCustomUnit] = useState<"minutes" | "hours">(+ init.customIntervalSeconds && init.customIntervalSeconds >= 3600 ? "hours" : "minutes",+ );+ const [modelTier, setModelTier] = useState<ModelTier>(init.modelTier ?? "auto");+ const [grants, setGrants] = useState<Record<string, ScopeValue>>(() =>+ Object.fromEntries((init.grants ?? []).map((g) => [g.plugin_id, g.scope])),+ );const { data: pluginsData, isLoading: pluginsLoading } = useQuery({queryKey: ["marketplace-plugins"],diff --git a/jarvis/ui/web/tasks_routes.py b/jarvis/ui/web/tasks_routes.pyindex 6fddde1f4a..2b2c71e291 100644--- a/jarvis/ui/web/tasks_routes.py+++ b/jarvis/ui/web/tasks_routes.py@@ -1,16 +1,24 @@-"""REST API for the task queue (Phase 5 Capability 4).+"""REST API for the task queue (Phase 5 Capability 4) — the Automations section.Endpoints:+- ``GET /api/tasks/templates`` → the pre-built automations catalogue.+- ``POST /api/tasks/templates/{key}/add`` → instantiate a template as a task.- ``POST /api/tasks`` → create + schedule a TaskSpec.- ``GET /api/tasks`` → task list, optionally ``?state=...``.- ``GET /api/tasks/{id}`` → full task with steps timeline.+- ``POST /api/tasks/{id}/run`` → run the action now, out of band.+- ``PATCH /api/tasks/{id}`` → ``{"enabled": bool}`` pause / resume.- ``POST /api/tasks/{id}/cancel`` → soft cancel (remove from the heap).- ``DELETE /api/tasks/{id}`` → hard delete (terminal states only).The router expects a ``TaskStore`` + ``TaskScheduler`` on``app.state.task_store`` resp. ``app.state.task_scheduler`` — these areset by the DesktopApp at startup. If neither is set, the endpoints answer-with ``503`` (Service Unavailable).+with ``503`` (Service Unavailable). Template readiness reads the live tool+names from ``app.state.brain`` when it exists.++Route order matters: the ``/templates`` routes are registered BEFORE the+``/{task_id}`` routes so "templates" is never captured as a task id."""from __future__ import annotations@@ -18,11 +26,18 @@ import jsonfrom typing import Anyfrom fastapi import APIRouter, HTTPException, Request+from pydantic import BaseModel, ConfigDict, Field-from jarvis.tasks.schema import TaskSpec+from jarvis.tasks import templates as tpl+from jarvis.tasks.scheduler import TaskNotFound, TaskStateConflict+from jarvis.tasks.schema import PAUSABLE_TRIGGER_TYPES, TERMINAL_STATES, TaskSpecrouter = APIRouter(prefix="/api/tasks", tags=["tasks"])+#: ``last_result`` is a card teaser, not the transcript — the full text stays+#: in the task's ``agent_result`` step.+LAST_RESULT_MAX_CHARS = 400+def _require_store(request: Request) -> Any:store = getattr(request.app.state, "task_store", None)@@ -35,22 +50,141 @@ def _optional_scheduler(request: Request) -> Any | None:return getattr(request.app.state, "task_scheduler", None)-def _row_to_summary(row: dict[str, Any]) -> dict[str, Any]:+def _require_scheduler(request: Request) -> Any:+ scheduler = _optional_scheduler(request)+ if scheduler is None:+ raise HTTPException(status_code=503, detail="TaskScheduler not available")+ return scheduler+++def _live_tool_names(request: Request) -> list[str] | None:+ """Tool names of the live brain, or ``None`` when no brain is up yet+ (readiness then defaults to "ready" rather than flagging every card)."""+ brain = getattr(request.app.state, "brain", None)+ snapshot = getattr(brain, "snapshot", None)+ if brain is None or not callable(snapshot):+ return None+ try:+ tools = snapshot().get("tools_available")+ except Exception: # noqa: BLE001 — a half-built brain must not 500 the catalogue+ return None+ if tools is None:+ return None+ return [str(t) for t in tools]+++def _last_run_state(row: dict[str, Any]) -> str | None:+ """Outcome of the most recent run, independent of the schedule state.++ A recurring task returns to ``scheduled`` after each run, so its row+ state says nothing about how the last run went; ``finished_at_ns`` ++ ``last_error`` do (the store clears ``last_error`` on a later success).+ """+ state = row["state"]+ if state == "running":+ return "running"+ if state in TERMINAL_STATES:+ return str(state)+ if row.get("finished_at_ns") is None:+ return None+ return "failed" if row.get("last_error") else "completed"+++def _parse_spec(row: dict[str, Any]) -> dict[str, Any] | None:+ raw = row.get("spec_json")+ if not raw:+ return None+ try:+ parsed = json.loads(raw)+ except json.JSONDecodeError:+ return None+ return parsed if isinstance(parsed, dict) else None+++def _row_to_summary(+ row: dict[str, Any],+ *,+ spec: dict[str, Any] | None = None,+ last_result: str | None = None,+) -> dict[str, Any]:"""Converts a DB row into a UI summary dict. Flat keys only, no steps."""+ spec = spec if spec is not None else _parse_spec(row)+ trigger = (spec or {}).get("trigger") or {}+ interval = trigger.get("interval_seconds") if trigger.get("type") == "every" else Nonereturn {"id": row["id"],"title": row.get("title") or "","state": row["state"],"trigger_type": row["trigger_type"],"due_at_ns": row.get("due_at_ns"),+ "next_due_at_ns": row.get("due_at_ns"),"created_at_ns": row.get("created_at_ns"),"started_at_ns": row.get("started_at_ns"),"finished_at_ns": row.get("finished_at_ns"),"attempts": row.get("attempts", 0),"last_error": row.get("last_error"),+ "tags": list((spec or {}).get("tags") or []),+ "created_by": (spec or {}).get("created_by") or "user",+ "interval_seconds": interval,+ "last_run_state": _last_run_state(row),+ "last_result": last_result,}+# ----------------------------------------------------------------------+# Templates (registered first — see module docstring)+# ----------------------------------------------------------------------++class TemplateAddRequest(BaseModel):+ model_config = ConfigDict(extra="forbid")+ inputs: dict[str, str] = Field(default_factory=dict)+ schedule: tpl.TemplateSchedule | None = None+ title: str | None = Field(default=None, max_length=256)+ locale: str = "en"++[email protected]("/templates")+async def list_templates(request: Request, locale: str = "en") -> dict[str, Any]:+ """The automations catalogue, localized, with a readiness verdict per+ template computed against the live brain's tool names."""+ live_tools = _live_tool_names(request)+ return {+ "templates": [+ t.to_api(locale, live_tools=live_tools)+ for t in tpl.all_templates().values()+ ],+ "categories": list(tpl.CATEGORIES),+ }++[email protected]("/templates/{key}/add", status_code=201)+async def add_template(+ key: str, body: TemplateAddRequest, request: Request,+) -> dict[str, Any]:+ """Instantiate a template as a scheduled task (``created_by="template"``,+ tagged ``template:<key>``). 404 unknown key, 422 missing required input."""+ template = tpl.get_template(key)+ if template is None:+ raise HTTPException(status_code=404, detail=f"Unknown template {key!r}")+ try:+ spec = tpl.build_spec(+ template,+ inputs=body.inputs,+ schedule=body.schedule,+ title=body.title,+ locale=body.locale,+ )+ except ValueError as exc:+ raise HTTPException(status_code=422, detail=str(exc)) from exc+ store = _require_store(request)+ scheduler = _optional_scheduler(request)+ if scheduler is not None:+ task_id = await scheduler.schedule(spec)+ else:+ task_id = await store.insert(spec)+ return {"id": task_id}++# ----------------------------------------------------------------------# Routes# ----------------------------------------------------------------------@@ -86,8 +220,11 @@ async def list_tasks(else:filter_val = staterows = await store.list(state_filter=filter_val, limit=limit)+ results = await store.latest_agent_results(+ [r["id"] for r in rows], max_chars=LAST_RESULT_MAX_CHARS,+ )return {- "tasks": [_row_to_summary(r) for r in rows],+ "tasks": [_row_to_summary(r, last_result=results.get(r["id"])) for r in rows],"total": len(rows),}@@ -100,21 +237,77 @@ async def get_task(task_id: str, request: Request) -> dict[str, Any]:if task is None:raise HTTPException(status_code=404, detail="Task not found")- # spec_json → dict for UI convenience- spec_obj = None- spec_raw = task.get("spec_json")- if spec_raw:- try:- spec_obj = json.loads(spec_raw)- except json.JSONDecodeError:- spec_obj = None-- task_out = _row_to_summary(task)+ spec_obj = _parse_spec(task)+ results = await store.latest_agent_results(+ [task_id], max_chars=LAST_RESULT_MAX_CHARS,+ )+ task_out = _row_to_summary(task, spec=spec_obj, last_result=results.get(task_id))task_out["spec"] = spec_objtask_out["steps"] = task.get("steps", [])return task_out+class TaskPatchRequest(BaseModel):+ model_config = ConfigDict(extra="forbid")+ enabled: bool++[email protected]("/{task_id}")+async def patch_task(+ task_id: str, body: TaskPatchRequest, request: Request,+) -> dict[str, Any]:+ """``{"enabled": false}`` pauses a recurring task, ``true`` resumes it at+ its next occurrence. 409 for one-shot triggers or a conflicting state."""+ store = _require_store(request)+ task = await store.get(task_id)+ if task is None:+ raise HTTPException(status_code=404, detail="Task not found")+ if task["trigger_type"] not in PAUSABLE_TRIGGER_TYPES:+ raise HTTPException(+ status_code=409,+ detail=f"Only recurring tasks can be paused (trigger={task['trigger_type']})",+ )+ scheduler = _require_scheduler(request)+ try:+ if body.enabled:+ await scheduler.resume(task_id)+ new_state = "scheduled"+ else:+ await scheduler.pause(task_id)+ new_state = "paused"+ except TaskNotFound as exc:+ raise HTTPException(status_code=404, detail="Task not found") from exc+ except TaskStateConflict as exc:+ raise HTTPException(status_code=409, detail=str(exc)) from exc+ refreshed = await store.get(task_id)+ return {+ "ok": True,+ "id": task_id,+ "state": new_state,+ "due_at_ns": (refreshed or {}).get("due_at_ns"),+ }++[email protected]("/{task_id}/run", openapi_extra={"x-jarvis-dangerous": True})+async def run_task_now(task_id: str, request: Request) -> dict[str, Any]:+ """Runs the task's action NOW, out of band — the schedule of a recurring+ task is not shifted. 409 while it is already running."""+ store = _require_store(request)+ task = await store.get(task_id)+ if task is None:+ raise HTTPException(status_code=404, detail="Task not found")+ if task["state"] == "running":+ raise HTTPException(status_code=409, detail="Task is already running")+ scheduler = _require_scheduler(request)+ try:+ await scheduler.run_now(task_id)+ except TaskNotFound as exc:+ raise HTTPException(status_code=404, detail="Task not found") from exc+ except TaskStateConflict as exc:+ raise HTTPException(status_code=409, detail=str(exc)) from exc+ return {"ok": True, "id": task_id}++@router.post("/{task_id}/cancel", openapi_extra={"x-jarvis-dangerous": True})async def cancel_task(task_id: str, request: Request) -> dict[str, Any]:"""Soft cancel: removes the task from the heap/event index and sets@@ -127,7 +320,7 @@ async def cancel_task(task_id: str, request: Request) -> dict[str, Any]:task = await store.get(task_id)if task is None:raise HTTPException(status_code=404, detail="Task not found")- if task["state"] in ("completed", "failed", "cancelled", "interrupted"):+ if task["state"] in TERMINAL_STATES:raise HTTPException(status_code=409,detail=f"Task is already final (state={task['state']})",@@ -150,7 +343,7 @@ async def delete_task(task_id: str, request: Request) -> dict[str, Any]:task = await store.get(task_id)if task is None:raise HTTPException(status_code=404, detail="Task not found")- if task["state"] not in ("completed", "failed", "cancelled", "interrupted"):+ if task["state"] not in TERMINAL_STATES:raise HTTPException(status_code=409,detail=f"Task is still active (state={task['state']}) — cancel it first",diff --git a/tests/unit/brain/test_run_task_agent.py b/tests/unit/brain/test_run_task_agent.pyindex e09ef36ddf..83ec3f973d 100644--- a/tests/unit/brain/test_run_task_agent.py+++ b/tests/unit/brain/test_run_task_agent.py@@ -69,7 +69,9 @@ async def test_run_task_filters_tools_and_isolates_history(monkeypatch) -> None:captured["history"] = kw.get("history")return SimpleNamespace(text="briefing result")- def _fake_build(brain: Any, *, tools_override: dict[str, Any] | None = None) -> Any:+ def _fake_build(+ brain: Any, *, tools_override: dict[str, Any] | None = None, **_: Any,+ ) -> Any:captured["tools"] = set((tools_override or {}).keys())return _FakeDispatcher()diff --git a/tests/unit/brain/test_run_task_fallback.py b/tests/unit/brain/test_run_task_fallback.pynew file mode 100644index 0000000000..c54f65f7db--- /dev/null+++ b/tests/unit/brain/test_run_task_fallback.py@@ -0,0 +1,186 @@+"""BrainManager.run_task — cross-family provider fallback, task-only tools and+written delivery for scheduled tasks (Automations, 2026-08-24).++Live defect: the active provider (OpenRouter, 0 credits) answered every+scheduled turn with ``APIStatusError 402`` in 0.4 s and NOTHING retried, so+every automation failed at its action step. The chat path walks a fallback+chain; the task path must at least retry once on another credential family+(AP-22) — and never switch the persistent active provider (user-only lock).+"""+from __future__ import annotations++from types import SimpleNamespace+from typing import Any++import pytest++from jarvis.brain import manager as manager_mod+from jarvis.brain.manager import BrainManager+from jarvis.core.bus import EventBus+from jarvis.core.config import JarvisConfig+from jarvis.core.protocols import ToolResult+++class _FakeTool:+ def __init__(self, name: str) -> None:+ self.name = name+ self.schema: dict[str, Any] = {}+++class _NullExecutor:+ async def execute(self, *a: Any, **kw: Any) -> ToolResult:+ return ToolResult(success=True, output="ok")+++class _Registry:+ def __init__(self, names: list[str]) -> None:+ self._names = names++ def available(self) -> list[str]:+ return list(self._names)++ def failed(self) -> dict[str, str]:+ return {}+++class _Credit402(Exception):+ pass+++def _manager(monkeypatch: pytest.MonkeyPatch, *, active: str = "openrouter",+ providers: list[str] | None = None) -> BrainManager:+ mgr = BrainManager(+ config=JarvisConfig(),+ bus=EventBus(),+ tools={"gmail": _FakeTool("gmail")},+ tool_executor=_NullExecutor(), # type: ignore[arg-type]+ )+ mgr._active_name = active+ mgr._registry = _Registry(providers or ["openrouter", "gemini", "openai"]) # type: ignore[assignment]+ monkeypatch.setattr(mgr, "_fast_model", lambda name: f"{name}-fast")+ monkeypatch.setattr(mgr, "_deep_model", lambda name: f"{name}-deep")+ monkeypatch.setattr(mgr, "_tool_model_credential_ready", lambda name: True)+ monkeypatch.setattr(mgr, "_get_brain", lambda name, model=None: SimpleNamespace(+ name=name, model=model,+ ))+ return mgr+++def _install_dispatch(+ monkeypatch: pytest.MonkeyPatch, mgr: BrainManager, outcomes: dict[str, Any],+) -> list[tuple[str, str | None, dict[str, Any]]]:+ """``outcomes[provider]`` is either a text or an exception to raise."""+ calls: list[tuple[str, str | None, dict[str, Any]]] = []++ def _build(brain: Any, *, tools_override: Any = None, tool_context: Any = None,+ **_: Any) -> Any:+ calls.append((brain.name, brain.model, dict(tool_context or {})))++ class _Dispatcher:+ async def dispatch(self, text: str, **kw: Any) -> Any:+ outcome = outcomes[brain.name]+ if isinstance(outcome, Exception):+ raise outcome+ return SimpleNamespace(text=outcome)++ return _Dispatcher()++ monkeypatch.setattr(mgr, "_build_dispatcher", _build)+ return calls+++async def test_402_retries_once_on_a_different_family(monkeypatch: pytest.MonkeyPatch) -> None:+ mgr = _manager(monkeypatch)+ calls = _install_dispatch(monkeypatch, mgr, {+ "openrouter": _Credit402("Error code: 402 - Insufficient credits"),+ "gemini": "digest from gemini",+ })++ out = await mgr.run_task(prompt="p", allowed_tools=("gmail",), model_tier="fast")++ assert out == "digest from gemini"+ assert [(c[0], c[1]) for c in calls] == [+ ("openrouter", "openrouter-fast"), ("gemini", "gemini-fast"),+ ]+ assert mgr._active_name == "openrouter", "the persistent provider is never switched"+++async def test_fallback_skips_same_family_and_dead_providers(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ # codex shares the "openai" family with openai-api; gemini is dead-listed.+ mgr = _manager(monkeypatch, active="openai-api",+ providers=["openai-api", "codex", "gemini", "grok"])+ mgr._dead_providers.add("gemini")+ assert mgr._task_fallback_provider() == "grok"+++async def test_fallback_requires_a_usable_credential(monkeypatch: pytest.MonkeyPatch) -> None:+ mgr = _manager(monkeypatch)+ monkeypatch.setattr(mgr, "_tool_model_credential_ready", lambda name: name == "openai")+ assert mgr._task_fallback_provider() == "openai"+++async def test_both_failing_reports_both(monkeypatch: pytest.MonkeyPatch) -> None:+ mgr = _manager(monkeypatch)+ _install_dispatch(monkeypatch, mgr, {+ "openrouter": _Credit402("Error code: 402 - Insufficient credits"),+ "gemini": RuntimeError("Error code: 429 - rate limit exceeded"),+ })+ with pytest.raises(RuntimeError) as info:+ await mgr.run_task(prompt="p", model_tier="fast")+ msg = str(info.value)+ assert msg.startswith("all brain providers failed: ")+ assert "openrouter: _Credit402: Error code: 402" in msg+ assert "gemini: RuntimeError: Error code: 429" in msg+++async def test_non_credential_error_propagates_without_retry(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ mgr = _manager(monkeypatch)+ calls = _install_dispatch(monkeypatch, mgr, {+ "openrouter": ValueError("tool schema rejected"),+ "gemini": "never reached",+ })+ with pytest.raises(ValueError):+ await mgr.run_task(prompt="p", model_tier="fast")+ assert [c[0] for c in calls] == ["openrouter"]+++async def test_no_usable_fallback_reraises_original(monkeypatch: pytest.MonkeyPatch) -> None:+ mgr = _manager(monkeypatch, providers=["openrouter"])+ _install_dispatch(monkeypatch, mgr, {+ "openrouter": _Credit402("Error code: 402 - Insufficient credits"),+ })+ with pytest.raises(_Credit402):+ await mgr.run_task(prompt="p", model_tier="fast")+++async def test_task_turn_declares_written_delivery(monkeypatch: pytest.MonkeyPatch) -> None:+ mgr = _manager(monkeypatch)+ calls = _install_dispatch(monkeypatch, mgr, {"openrouter": "ok"})+ await mgr.run_task(prompt="p", model_tier="deep")+ assert calls == [("openrouter", "openrouter-deep", {"delivery": "written"})]+++def test_remember_grant_loads_task_only_tool(monkeypatch: pytest.MonkeyPatch) -> None:+ """``remember`` is not a router tool, yet a granted task can use it."""+ mgr = _manager(monkeypatch)+ assert "remember" not in mgr._tools+ sel = mgr._select_task_tools(("gmail", "remember"))+ assert set(sel) == {"gmail", "remember"}+ assert sel["remember"].name == "remember"+ # cached — the same instance on the next task+ assert mgr._select_task_tools(("remember",))["remember"] is sel["remember"]+++def test_unknown_task_only_grant_is_skipped(monkeypatch: pytest.MonkeyPatch) -> None:+ mgr = _manager(monkeypatch)+ monkeypatch.setattr(manager_mod, "_TASK_ONLY_TOOLS", frozenset({"remember", "no-such"}))+ sel = mgr._select_task_tools(("no-such",))+ assert sel == {}+++def test_spawn_tools_never_task_only() -> None:+ assert not any("spawn" in name for name in manager_mod._TASK_ONLY_TOOLS)diff --git a/tests/unit/plugins/test_search_web_delivery.py b/tests/unit/plugins/test_search_web_delivery.pynew file mode 100644index 0000000000..e4f7253610--- /dev/null+++ b/tests/unit/plugins/test_search_web_delivery.py@@ -0,0 +1,54 @@+"""search_web's answer instruction follows the turn's delivery.++The spoken instruction ("one or two SPOKEN sentences, never name a+title/url/source/date") is right for voice and wrong for a scheduled written+digest — every search-based automation fought it. A turn that declares+``ExecutionContext.config["delivery"] == "written"`` gets the written+variant; every other context (including one without the key) keeps the+spoken one. Also pins that the dispatcher → loop path actually delivers the+``tool_context`` keys into the ExecutionContext.+"""+from __future__ import annotations++from typing import Any+from uuid import uuid4++from jarvis.core.protocols import ExecutionContext+from jarvis.plugins.tool import search_web as sw+++def _ctx(config: dict[str, Any] | None) -> ExecutionContext:+ return ExecutionContext(+ trace_id=uuid4(), user_utterance="q", config=config or {}, memory_read=None,+ )+++def test_spoken_by_default() -> None:+ assert sw._answer_instruction_for(_ctx({})) is sw._ANSWER_INSTRUCTION+ assert sw._answer_instruction_for(_ctx({"delivery": "spoken"})) is sw._ANSWER_INSTRUCTION+++def test_written_delivery_gets_written_instruction() -> None:+ text = sw._answer_instruction_for(_ctx({"delivery": "written"}))+ assert text is sw._WRITTEN_ANSWER_INSTRUCTION+ assert "SPOKEN" not in text+ assert "source" in text.lower()+++def test_foreign_context_shape_degrades_to_spoken() -> None:+ class _Odd:+ config = None++ assert sw._answer_instruction_for(_Odd()) is sw._ANSWER_INSTRUCTION # type: ignore[arg-type]+++def test_tool_context_reaches_execution_context() -> None:+ """ToolUseLoop merges the dispatcher's tool_context under the per-turn keys."""+ from jarvis.brain.tool_use_loop import ToolUseLoop++ loop = ToolUseLoop(+ object(), {}, object(), # type: ignore[arg-type]+ tool_context={"delivery": "written", "output_language": "must-lose"},+ )+ merged = {**loop._tool_context, "output_language": "de", "voice_confirm": False}+ assert merged == {"delivery": "written", "output_language": "de", "voice_confirm": False}diff --git a/tests/unit/tasks/test_grant_matching.py b/tests/unit/tasks/test_grant_matching.pynew file mode 100644index 0000000000..fdd85c8f6b--- /dev/null+++ b/tests/unit/tasks/test_grant_matching.py@@ -0,0 +1,88 @@+"""Plugin grants match by PREFIX everywhere a task's allowlist is applied.++A template grants ``github`` while the live tools are ``github/list_issues``,+``github/create_issue``, … Exact matching in ``BrainManager._select_task_tools``+left such a task running with ZERO tools (it then "could not access GitHub"+at 09:00). The brain's allowlist and the unattended-approval bridge must+apply one and the same rule: :func:`jarvis.tasks.templates.grant_matches`.+"""+from __future__ import annotations++from typing import Any+from uuid import uuid4++from jarvis.brain.manager import BrainManager+from jarvis.core.bus import EventBus+from jarvis.core.config import JarvisConfig+from jarvis.core.events import ActionApprovalRequired, ActionApproved+from jarvis.core.protocols import ToolResult+from jarvis.tasks.approval_bridge import TaskAutoApprover+++class _FakeTool:+ def __init__(self, name: str) -> None:+ self.name = name+ self.schema: dict[str, Any] = {}+++class _NullExecutor:+ async def execute(self, *a: Any, **kw: Any) -> ToolResult:+ return ToolResult(success=True, output="ok")+++def _manager(names: list[str]) -> BrainManager:+ return BrainManager(+ config=JarvisConfig(),+ bus=EventBus(),+ tools={n: _FakeTool(n) for n in names},+ tool_executor=_NullExecutor(), # type: ignore[arg-type]+ )+++LIVE = ["gmail", "github/list_issues", "github/create_issue", "linear/list_issues",+ "github_search"]+++def test_prefix_grant_covers_namespaced_tools() -> None:+ sel = _manager(LIVE)._select_task_tools(("github",))+ assert set(sel) == {"github/list_issues", "github/create_issue"}+++def test_prefix_grant_does_not_cover_lookalike_names() -> None:+ sel = _manager(LIVE)._select_task_tools(("github",))+ assert "github_search" not in sel+ assert "linear/list_issues" not in sel+++def test_exact_grant_still_works_and_mixes_with_prefix() -> None:+ sel = _manager(LIVE)._select_task_tools(("gmail", "linear"))+ assert set(sel) == {"gmail", "linear/list_issues"}+++def test_empty_allowlist_yields_no_tools() -> None:+ assert _manager(LIVE)._select_task_tools(()) == {}+++async def test_approver_pre_authorizes_by_prefix() -> None:+ bus = EventBus()+ approved: list[ActionApproved] = []++ async def _on(ev: ActionApproved) -> None:+ approved.append(ev)++ bus.subscribe(ActionApproved, _on)+ approver = TaskAutoApprover(bus)+ trace = uuid4()+ approver.arm(trace, ("github",), approved_by="scheduled-task:t1")++ await bus.publish(ActionApprovalRequired(+ trace_id=trace, tool_name="github/create_issue", risk_tier="ask",+ ))+ await bus.publish(ActionApprovalRequired(+ trace_id=trace, tool_name="github_search", risk_tier="ask",+ ))+ await bus.publish(ActionApprovalRequired(+ trace_id=uuid4(), tool_name="github/create_issue", risk_tier="ask",+ ))+ assert [e.tool_name for e in approved] == ["github/create_issue"]+ assert approved[0].approved_by == "scheduled-task:t1"diff --git a/tests/unit/tasks/test_scheduler_automations.py b/tests/unit/tasks/test_scheduler_automations.pynew file mode 100644index 0000000000..a8781eed1e--- /dev/null+++ b/tests/unit/tasks/test_scheduler_automations.py@@ -0,0 +1,293 @@+"""TaskScheduler — run-now, pause and resume (the Automations controls).++The invariants that matter:+- ``run_now`` executes the action out of band and leaves the schedule of a+ recurring task untouched (same ``due_at_ns``, still in the heap, still+ ``scheduled`` afterwards); a one-shot task is consumed by the run.+- ``pause`` takes a recurring task out of the heap / event index and+ ``hydrate()`` leaves it alone; ``resume`` re-arms it at the NEXT occurrence,+ on the wall-clock grid of a ``start_at``-anchored task.+"""+from __future__ import annotations++import asyncio+from datetime import UTC, datetime, timedelta+from pathlib import Path+from typing import Any++import pytest++from jarvis.core.bus import EventBus+from jarvis.tasks.runner import TaskRunner+from jarvis.tasks.scheduler import (+ TaskNotFound,+ TaskScheduler,+ TaskStateConflict,+ next_every_due_ns,+ parse_iso_timestamp_to_ns,+)+from jarvis.tasks.schema import (+ AgentAction,+ SpeakAction,+ TaskSpec,+ TriggerAfterDelay,+ TriggerEvery,+ TriggerOnEvent,+)+from jarvis.tasks.store import TaskStore+++class FakeBrain:+ def __init__(self) -> None:+ self.calls: list[str] = []++ async def run_task(self, *, prompt: str, **_: Any) -> str:+ self.calls.append(prompt)+ return f"result for {prompt}"+++class RecordingRunner:+ """Records dispatches without touching the store (scheduler-only tests)."""++ def __init__(self) -> None:+ self.dispatched: list[str] = []+ self.gate = asyncio.Event()++ async def run(self, task_id: str, *_a: Any, **_k: Any) -> None:+ self.dispatched.append(task_id)+ self.gate.set()+++async def store(tmp_path: Path):+ s = TaskStore(tmp_path / "auto.db")+ await s.init()+ try:+ yield s+ finally:+ await s.close()+++def bus() -> EventBus:+ return EventBus()+++def _every(interval: float = 3600.0, start_at: str | None = None,+ prompt: str = "brief") -> TaskSpec:+ return TaskSpec(+ title="recurring",+ trigger=TriggerEvery(interval_seconds=interval, start_at=start_at),+ action=AgentAction(prompt=prompt),+ )+++async def _settle(scheduler: TaskScheduler) -> None:+ await scheduler.shutdown()+ await asyncio.sleep(0)+++# ----------------------------------------------------------------------+# run_now+# ----------------------------------------------------------------------++async def test_run_now_runs_action_and_keeps_schedule(store: TaskStore, bus: EventBus) -> None:+ brain = FakeBrain()+ runner = TaskRunner(store=store, bus=bus, agent_brain=brain)+ scheduler = TaskScheduler(store=store, bus=bus, runner=runner)+ tid = await scheduler.schedule(_every(prompt="morning"))+ before = await store.get(tid)+ assert before is not None++ await scheduler.run_now(tid)+ await _settle(scheduler)++ assert brain.calls == ["morning"]+ after = await store.get(tid)+ assert after is not None+ assert after["state"] == "scheduled"+ assert after["due_at_ns"] == before["due_at_ns"], "run-now must not shift the schedule"+ assert any(tid == t for _, t in scheduler._heap), "still armed in the heap"+ events = [s["payload"].get("event") for s in after["steps"] if s["kind"] == "log"]+ assert "run_now" in events+ assert "agent_result" in events+ assert after["finished_at_ns"] is not None+ assert after["last_error"] is None+++async def test_run_now_consumes_one_shot_task(store: TaskStore, bus: EventBus) -> None:+ brain = FakeBrain()+ runner = TaskRunner(store=store, bus=bus, agent_brain=brain)+ scheduler = TaskScheduler(store=store, bus=bus, runner=runner)+ spec = TaskSpec(+ title="once",+ trigger=TriggerAfterDelay(delay_seconds=3600),+ action=AgentAction(prompt="once"),+ )+ tid = await scheduler.schedule(spec)++ await scheduler.run_now(tid)+ await _settle(scheduler)++ task = await store.get(tid)+ assert task is not None+ assert task["state"] == "completed"+ assert all(t != tid for _, t in scheduler._heap), "must not fire a second time"+++async def test_run_now_refuses_running_and_unknown(store: TaskStore, bus: EventBus) -> None:+ scheduler = TaskScheduler(store=store, bus=bus, runner=RecordingRunner())+ tid = await scheduler.schedule(_every())+ await store.update_state(tid, "running")+ with pytest.raises(TaskStateConflict):+ await scheduler.run_now(tid)+ with pytest.raises(TaskNotFound):+ await scheduler.run_now("nope")+++async def test_run_now_restores_paused_state(store: TaskStore, bus: EventBus) -> None:+ brain = FakeBrain()+ runner = TaskRunner(store=store, bus=bus, agent_brain=brain)+ scheduler = TaskScheduler(store=store, bus=bus, runner=runner)+ tid = await scheduler.schedule(_every())+ await scheduler.pause(tid)++ await scheduler.run_now(tid)+ await _settle(scheduler)++ assert brain.calls == ["brief"]+ task = await store.get(tid)+ assert task is not None+ assert task["state"] == "paused", "a manual run must not switch a paused task on"+ assert all(t != tid for _, t in scheduler._heap)+++# ----------------------------------------------------------------------+# pause / resume+# ----------------------------------------------------------------------++async def test_pause_removes_from_heap_and_hydrate_leaves_it(+ store: TaskStore, bus: EventBus,+) -> None:+ scheduler = TaskScheduler(store=store, bus=bus, runner=RecordingRunner())+ tid = await scheduler.schedule(_every())+ assert any(t == tid for _, t in scheduler._heap)++ await scheduler.pause(tid)+ await scheduler.pause(tid) # idempotent++ assert all(t != tid for _, t in scheduler._heap)+ task = await store.get(tid)+ assert task is not None+ assert task["state"] == "paused"+ assert [s["payload"]["event"] for s in task["steps"]] == ["paused"]++ fresh = TaskScheduler(store=store, bus=bus, runner=RecordingRunner())+ await fresh.hydrate()+ assert fresh._heap == []+ assert tid not in fresh._known+++async def test_pause_refuses_one_shot_running_and_terminal(+ store: TaskStore, bus: EventBus,+) -> None:+ scheduler = TaskScheduler(store=store, bus=bus, runner=RecordingRunner())+ one_shot = await scheduler.schedule(TaskSpec(+ title="once", trigger=TriggerAfterDelay(delay_seconds=60),+ action=SpeakAction(text="x"),+ ))+ with pytest.raises(TaskStateConflict):+ await scheduler.pause(one_shot)++ tid = await scheduler.schedule(_every())+ await store.update_state(tid, "running")+ with pytest.raises(TaskStateConflict):+ await scheduler.pause(tid)+ await store.update_state(tid, "cancelled")+ with pytest.raises(TaskStateConflict):+ await scheduler.pause(tid)+ with pytest.raises(TaskNotFound):+ await scheduler.pause("nope")+++async def test_resume_rearms_unanchored_task_one_interval_out(+ store: TaskStore, bus: EventBus,+) -> None:+ scheduler = TaskScheduler(store=store, bus=bus, runner=RecordingRunner())+ tid = await scheduler.schedule(_every(interval=600))+ await scheduler.pause(tid)++ now_ns = 1_000_000_000_000_000_000+ due = await scheduler.resume(tid, now_ns=now_ns)++ assert due == now_ns + 600 * 10**9+ task = await store.get(tid)+ assert task is not None+ assert task["state"] == "scheduled"+ assert task["due_at_ns"] == due+ assert (due, tid) in scheduler._heap+ assert [s["payload"]["event"] for s in task["steps"]] == ["paused", "resumed"]+++async def test_resume_keeps_wall_clock_anchor(store: TaskStore, bus: EventBus) -> None:+ anchor = datetime(2026, 1, 1, 7, 30, tzinfo=UTC)+ spec = _every(interval=86_400, start_at=anchor.isoformat())+ scheduler = TaskScheduler(store=store, bus=bus, runner=RecordingRunner())+ tid = await scheduler.schedule(spec)+ await scheduler.pause(tid)++ now = anchor + timedelta(days=10, hours=3) # 10:30 on day 10+ due = await scheduler.resume(tid, now_ns=int(now.timestamp() * 1e9))++ expected = anchor + timedelta(days=11) # next 07:30 strictly after now+ assert due == int(expected.timestamp() * 1e9)+++async def test_resume_refuses_non_paused(store: TaskStore, bus: EventBus) -> None:+ scheduler = TaskScheduler(store=store, bus=bus, runner=RecordingRunner())+ tid = await scheduler.schedule(_every())+ with pytest.raises(TaskStateConflict):+ await scheduler.resume(tid)+++async def test_pause_resume_on_event_task(store: TaskStore, bus: EventBus) -> None:+ scheduler = TaskScheduler(store=store, bus=bus, runner=RecordingRunner())+ spec = TaskSpec(+ title="rule",+ trigger=TriggerOnEvent(event_name="MissionCompleted", max_firings=None),+ action=SpeakAction(text="done"),+ )+ tid = await scheduler.schedule(spec)+ assert tid in scheduler._on_event_index["MissionCompleted"]++ await scheduler.pause(tid)+ assert tid not in scheduler._on_event_index["MissionCompleted"]++ due = await scheduler.resume(tid)+ assert due is None+ assert tid in scheduler._on_event_index["MissionCompleted"]+ task = await store.get(tid)+ assert task is not None and task["state"] == "scheduled"+++# ----------------------------------------------------------------------+# next_every_due_ns+# ----------------------------------------------------------------------++def test_next_every_due_future_anchor_is_used_as_is() -> None:+ anchor = datetime(2030, 1, 1, 8, 0, tzinfo=UTC)+ spec = _every(interval=3600, start_at=anchor.isoformat())+ now_ns = int((anchor - timedelta(days=1)).timestamp() * 1e9)+ assert next_every_due_ns(spec, now_ns) == parse_iso_timestamp_to_ns(anchor.isoformat())+++def test_next_every_due_on_grid_is_pushed_to_next_slot() -> None:+ anchor = datetime(2026, 1, 1, 8, 0, tzinfo=UTC)+ spec = _every(interval=3600, start_at=anchor.isoformat())+ now_ns = int((anchor + timedelta(hours=5)).timestamp() * 1e9) # exactly on a slot+ assert next_every_due_ns(spec, now_ns) == now_ns + 3600 * 10**9+++def test_next_every_due_bad_anchor_degrades_to_interval() -> None:+ spec = _every(interval=60, start_at="not-a-timestamp")+ assert next_every_due_ns(spec, 10**18) == 10**18 + 60 * 10**9diff --git a/tests/unit/tasks/test_state_parity.py b/tests/unit/tasks/test_state_parity.pynew file mode 100644index 0000000000..5884c94abb--- /dev/null+++ b/tests/unit/tasks/test_state_parity.py@@ -0,0 +1,79 @@+"""Parity test for the task STATE vocabulary across the five layers.++``paused`` (2026-08-24) joined the vocabulary that lives in Python+(``TaskState``/``TASK_STATES``), SQL (the ``state`` CHECK in ``schema.sql``+and the migration rebuild target), TypeScript (the ``TaskState`` union + the+label/dot maps of the Automations views) and i18n (``tasks_view.state.*`` in+every locale). A value missing from any one layer is a silent defect: a CHECK+violation on pause, a blank badge, or an untranslated key.++Source of truth: ``TASK_STATES`` in ``jarvis/tasks/schema.py``.+"""+from __future__ import annotations++import json+import re+from pathlib import Path++import pytest++from jarvis.tasks import store as store_mod+from jarvis.tasks.schema import TASK_STATES, TERMINAL_STATES, TaskState++REPO_ROOT = Path(__file__).resolve().parents[3]+FRONTEND = REPO_ROOT / "jarvis/ui/web/frontend/src"+SCHEMA_SQL = REPO_ROOT / "jarvis/tasks/schema.sql"+MODEL_TS = FRONTEND / "views/automations/automationsModel.ts"+SHARED_TSX = FRONTEND / "views/automations/shared.tsx"+LOCALES = FRONTEND / "i18n/locales"+++def _expected() -> set[str]:+ return set(TASK_STATES)+++def _states_in_check(sql: str) -> set[str]:+ block = re.search(r"state\s+TEXT NOT NULL CHECK\(state IN \(([^)]+)\)\)", sql)+ assert block is not None, "could not find the state CHECK"+ return set(re.findall(r"'([a-z_]+)'", block.group(1)))+++def test_literal_and_tuple_agree() -> None:+ assert set(TaskState.__args__) == _expected() # type: ignore[attr-defined]+ assert "paused" in _expected()+ assert set(TERMINAL_STATES) < _expected()+ assert "paused" not in TERMINAL_STATES+++def test_schema_sql_check_matches_python() -> None:+ found = _states_in_check(SCHEMA_SQL.read_text(encoding="utf-8"))+ assert found == _expected(), f"schema.sql drift: {found ^ _expected()}"+++def test_migration_rebuild_target_matches_python() -> None:+ found = _states_in_check(store_mod._TASKS_REBUILD_SQL)+ assert found == _expected(), f"_TASKS_REBUILD_SQL drift: {found ^ _expected()}"+++def test_ts_union_matches_python() -> None:+ text = MODEL_TS.read_text(encoding="utf-8")+ block = re.search(r"export type TaskState =([\s\S]+?);", text)+ assert block is not None, "could not find TaskState union in automationsModel.ts"+ found = set(re.findall(r'"([^"]+)"', block.group(1)))+ assert found == _expected(), f"automationsModel.ts TaskState drift: {found ^ _expected()}"+++def test_ts_label_map_covers_every_state() -> None:+ text = SHARED_TSX.read_text(encoding="utf-8")+ found = set(re.findall(r'(\w+):\s*t\("tasks_view\.state\.(\w+)"\)', text))+ keys = {k for k, _ in found}+ assert keys == _expected(), f"shared.tsx label map drift: {keys ^ _expected()}"+ assert all(k == v for k, v in found), "label map key/i18n key mismatch"++[email protected]("locale", ["de", "en", "es"])+def test_i18n_has_every_state(locale: str) -> None:+ data = json.loads((LOCALES / f"{locale}.json").read_text(encoding="utf-8"))+ states = data["tasks_view"]["state"]+ assert set(states) == _expected(), f"{locale}.json drift: {set(states) ^ _expected()}"+ assert all(isinstance(v, str) and v for v in states.values())diff --git a/tests/unit/tasks/test_store_automations.py b/tests/unit/tasks/test_store_automations.pynew file mode 100644index 0000000000..41fda043f7--- /dev/null+++ b/tests/unit/tasks/test_store_automations.py@@ -0,0 +1,174 @@+"""TaskStore — the Automations additions: the ``paused`` state, the state+CHECK migration, the one-query ``latest_agent_results`` and the last-run+bookkeeping (``finished_at_ns`` / ``last_error``) for recurring tasks."""+from __future__ import annotations++import sqlite3+from pathlib import Path++import pytest++from jarvis.tasks.schema import AgentAction, SpeakAction, TaskSpec, TriggerAfterDelay, TriggerEvery+from jarvis.tasks.store import TaskStore++# The `tasks` table exactly as a DB created before `every` AND `paused`+# existed — the oldest shape a downloader can still be carrying.+_LEGACY_TASKS_SQL = """+CREATE TABLE tasks (+ id TEXT PRIMARY KEY,+ trace_id TEXT NOT NULL,+ spec_json TEXT NOT NULL,+ state TEXT NOT NULL CHECK(state IN (+ 'pending','scheduled','running','completed',+ 'failed','cancelled','interrupted')),+ trigger_type TEXT NOT NULL CHECK(trigger_type IN (+ 'after_delay','at_time','on_event','every')),+ due_at_ns INTEGER,+ event_selector TEXT,+ title TEXT NOT NULL DEFAULT '',+ created_at_ns INTEGER NOT NULL,+ started_at_ns INTEGER,+ finished_at_ns INTEGER,+ attempts INTEGER NOT NULL DEFAULT 0,+ last_error TEXT,+ result_json TEXT+)+"""+++async def store(tmp_path: Path):+ s = TaskStore(tmp_path / "store.db")+ await s.init()+ try:+ yield s+ finally:+ await s.close()+++def _every() -> TaskSpec:+ return TaskSpec(+ title="recurring",+ trigger=TriggerEvery(interval_seconds=3600),+ action=AgentAction(prompt="p"),+ )+++async def test_paused_state_is_accepted(store: TaskStore) -> None:+ tid = await store.insert(_every())+ await store.update_state(tid, "paused")+ task = await store.get(tid)+ assert task is not None+ assert task["state"] == "paused"+ assert task["finished_at_ns"] is None+ # hydrate() only sees `scheduled` — paused tasks stay put.+ assert [r["id"] for r in await store.all_pending_scheduled()] == []+++async def test_state_check_migration_rebuilds_legacy_table(tmp_path: Path) -> None:+ db = tmp_path / "legacy.db"+ raw = sqlite3.connect(db)+ raw.executescript(_LEGACY_TASKS_SQL)+ raw.execute(+ "INSERT INTO tasks (id, trace_id, spec_json, state, trigger_type, due_at_ns, "+ "title, created_at_ns) VALUES ('old', 'old', '{}', 'scheduled', 'every', 5, "+ "'legacy', 1)"+ )+ raw.commit()+ raw.close()++ async with TaskStore(db) as store:+ # The legacy row survived the rebuild …+ rows = await store.list()+ assert [r["id"] for r in rows] == ["old"]+ assert rows[0]["due_at_ns"] == 5+ # … and the new state is now accepted.+ await store.update_state("old", "paused")+ assert (await store.get("old"))["state"] == "paused" # type: ignore[index]+ sql = await store._tasks_table_sql()+ assert sql is not None and "'paused'" in sql++ # Idempotent: a second open does not rebuild again (and does not fail).+ async with TaskStore(db) as store:+ assert (await store.get("old"))["state"] == "paused" # type: ignore[index]+++async def test_recurring_success_marks_finished_and_clears_error(store: TaskStore) -> None:+ tid = await store.insert(_every())+ await store.update_state(tid, "running", increment_attempts=True)+ await store.update_state(tid, "failed", error="boom")+ failed = await store.get(tid)+ assert failed is not None and failed["last_error"] == "boom"++ await store.update_state(tid, "running", increment_attempts=True)+ await store.update_state(tid, "scheduled", result={"duration_ms": 3})+ ok = await store.get(tid)+ assert ok is not None+ assert ok["state"] == "scheduled"+ assert ok["finished_at_ns"] is not None+ assert ok["last_error"] is None+++async def test_plain_scheduled_transition_does_not_mark_finished(store: TaskStore) -> None:+ tid = await store.insert(_every())+ await store.update_state(tid, "paused")+ await store.update_state(tid, "scheduled")+ task = await store.get(tid)+ assert task is not None+ assert task["finished_at_ns"] is None+++async def test_list_rows_carry_spec_json(store: TaskStore) -> None:+ await store.insert(_every())+ rows = await store.list()+ assert rows and '"interval_seconds"' in rows[0]["spec_json"]+++async def test_latest_agent_results_one_per_task_newest_and_truncated(store: TaskStore) -> None:+ a = await store.insert(_every())+ b = await store.insert(_every())+ c = await store.insert(TaskSpec(+ title="speak", trigger=TriggerAfterDelay(delay_seconds=1), action=SpeakAction(text="x"),+ ))+ await store.append_step(a, "log", {"event": "agent_result", "text": "first"})+ await store.append_step(a, "log", {"event": "error", "message": "ignored"})+ await store.append_step(a, "log", {"event": "agent_result", "text": "x" * 1000})+ await store.append_step(b, "action", {"kind": "agent", "prompt": "no result yet"})+ await store.append_step(c, "log", {"event": "tts_done", "chunks": 2})++ results = await store.latest_agent_results([a, b, c], max_chars=400)+ assert set(results) == {a}+ assert results[a] == "x" * 400++ assert await store.latest_agent_results([]) == {}+ everything = await store.latest_agent_results(None, max_chars=2)+ assert everything == {a: "xx"}+++# ----------------------------------------------------------------------+# readable_error — what the Runs tab shows as last_error+# ----------------------------------------------------------------------++def test_readable_error_extracts_code_and_message() -> None:+ from jarvis.tasks.runner import readable_error++ class APIStatusError(Exception):+ pass++ exc = APIStatusError(+ "Error code: 402 - {'error': {'message': 'Insufficient credits. Add more using "+ "https://openrouter.ai/settings/credits', 'code': 402, 'metadata': "+ "{'limit_source': 'openrouter_credits'}}}"+ )+ text = readable_error(exc)+ assert text.startswith("APIStatusError: 402 — Insufficient credits. Add more using")+ assert "metadata" not in text+++def test_readable_error_plain_and_empty() -> None:+ from jarvis.tasks.runner import readable_error++ plain = readable_error(RuntimeError("Tool 'x' failed: boom"))+ assert plain == "RuntimeError: Tool 'x' failed: boom"+ assert readable_error(KeyError()) == "KeyError"+ assert len(readable_error(RuntimeError("y" * 5000))) == 400diff --git a/tests/unit/tasks/test_tasks_routes.py b/tests/unit/tasks/test_tasks_routes.pynew file mode 100644index 0000000000..85734721fb--- /dev/null+++ b/tests/unit/tasks/test_tasks_routes.py@@ -0,0 +1,266 @@+"""``/api/tasks`` — the Automations API contract the UI codes against.++Exercised through the real router on a FastAPI app whose ``app.state`` holds+a real ``TaskStore`` + ``TaskScheduler`` (with a fake runner) and, where a+test needs it, a fake brain exposing ``snapshot()``. No ``unittest.mock``.+"""+from __future__ import annotations++import asyncio+from pathlib import Path+from typing import Any++import httpx+import pytest+from fastapi import FastAPI++from jarvis.core.bus import EventBus+from jarvis.tasks import templates as tpl+from jarvis.tasks.runner import TaskRunner+from jarvis.tasks.scheduler import TaskScheduler+from jarvis.tasks.schema import AgentAction, SpeakAction, TaskSpec, TriggerAfterDelay, TriggerEvery+from jarvis.tasks.store import TaskStore+from jarvis.ui.web import tasks_routes+++class FakeBrain:+ """The two things the routes touch on ``app.state.brain``."""++ def __init__(self, tools: list[str]) -> None:+ self._tools = tools+ self.calls: list[str] = []++ def snapshot(self) -> dict[str, Any]:+ return {"tools_available": sorted(self._tools)}++ async def run_task(self, *, prompt: str, **_: Any) -> str:+ self.calls.append(prompt)+ return "the answer " * 100 # > 400 chars, so truncation is visible+++class Harness:+ def __init__(self, app: FastAPI, store: TaskStore, scheduler: TaskScheduler,+ brain: FakeBrain) -> None:+ self.app = app+ self.store = store+ self.scheduler = scheduler+ self.brain = brain++ def client(self) -> httpx.AsyncClient:+ return httpx.AsyncClient(+ transport=httpx.ASGITransport(app=self.app), base_url="http://t",+ )++ async def settle(self) -> None:+ await self.scheduler.shutdown()+ await asyncio.sleep(0)+++async def harness(tmp_path: Path):+ store = TaskStore(tmp_path / "routes.db")+ await store.init()+ bus = EventBus()+ brain = FakeBrain(["gmail", "search_web", "github/list_issues", "github/create_issue"])+ runner = TaskRunner(store=store, bus=bus, agent_brain=brain)+ scheduler = TaskScheduler(store=store, bus=bus, runner=runner)+ app = FastAPI()+ app.include_router(tasks_routes.router)+ app.state.task_store = store+ app.state.task_scheduler = scheduler+ app.state.brain = brain+ try:+ yield Harness(app, store, scheduler, brain)+ finally:+ await scheduler.shutdown()+ await store.close()+++def _every_body(**overrides: Any) -> dict[str, Any]:+ spec = TaskSpec(+ title="recurring",+ trigger=TriggerEvery(interval_seconds=3600),+ action=AgentAction(prompt="hello"),+ tags=("template:morning_brief", "news"),+ created_by="template",+ **overrides,+ )+ return spec.model_dump(mode="json")+++# ----------------------------------------------------------------------+# Templates+# ----------------------------------------------------------------------++async def test_templates_catalogue_is_localized_with_readiness(harness: Harness) -> None:+ async with harness.client() as c:+ res = await c.get("/api/tasks/templates", params={"locale": "de"})+ assert res.status_code == 200+ body = res.json()+ assert body["categories"] == list(tpl.CATEGORIES)+ templates = {t["key"]: t for t in body["templates"]}+ assert templates, "the catalogue must not be empty"+ for key, entry in templates.items():+ template = tpl.get_template(key)+ assert template is not None+ assert entry["name"] == template.name.for_locale("de")+ live = ["gmail", "search_web", "github/list_issues", "github/create_issue"]+ assert entry["missing"] == tpl.missing_requirements(template.requires, live)+ assert entry["ready"] == (not entry["missing"])+++async def test_templates_without_brain_default_to_ready(harness: Harness) -> None:+ harness.app.state.brain = None+ async with harness.client() as c:+ body = (await c.get("/api/tasks/templates")).json()+ assert all(t["ready"] and t["missing"] == [] for t in body["templates"])+++async def test_templates_route_is_not_captured_as_task_id(harness: Harness) -> None:+ async with harness.client() as c:+ res = await c.get("/api/tasks/templates")+ assert res.status_code == 200+ assert "templates" in res.json()+++async def test_add_template_schedules_tagged_task(harness: Harness) -> None:+ key = next(iter(tpl.all_templates()))+ template = tpl.get_template(key)+ assert template is not None+ inputs = {i.key: (i.default or "value") for i in template.inputs}+ async with harness.client() as c:+ res = await c.post(+ f"/api/tasks/templates/{key}/add",+ json={"inputs": inputs, "locale": "de", "title": " "},+ )+ assert res.status_code == 201, res.text+ tid = res.json()["id"]+ detail = (await c.get(f"/api/tasks/{tid}")).json()+ assert detail["state"] == "scheduled"+ assert detail["trigger_type"] == "every"+ assert detail["created_by"] == "template"+ assert template.tag in detail["tags"]+ assert detail["title"] == template.name.for_locale("de")+ assert detail["interval_seconds"] == detail["spec"]["trigger"]["interval_seconds"]+ assert any(tid == t for _, t in harness.scheduler._heap)+++async def test_add_template_unknown_key_404(harness: Harness) -> None:+ async with harness.client() as c:+ res = await c.post("/api/tasks/templates/does_not_exist/add", json={})+ assert res.status_code == 404+++async def test_add_template_missing_required_input_422(harness: Harness) -> None:+ required = [+ t for t in tpl.all_templates().values()+ if any(i.required and not i.default for i in t.inputs)+ ]+ if not required:+ pytest.skip("no template with a required input without default")+ async with harness.client() as c:+ res = await c.post(f"/api/tasks/templates/{required[0].key}/add", json={"inputs": {}})+ assert res.status_code == 422+ assert "missing required inputs" in res.json()["detail"]+++# ----------------------------------------------------------------------+# Summaries+# ----------------------------------------------------------------------++async def test_list_summaries_carry_automation_fields(harness: Harness) -> None:+ async with harness.client() as c:+ tid = (await c.post("/api/tasks", json=_every_body())).json()["id"]+ first = (await c.get("/api/tasks")).json()["tasks"][0]+ assert first["id"] == tid+ assert first["tags"] == ["template:morning_brief", "news"]+ assert first["created_by"] == "template"+ assert first["interval_seconds"] == 3600.0+ assert first["next_due_at_ns"] == first["due_at_ns"] is not None+ assert first["last_run_state"] is None+ assert first["last_result"] is None+++async def test_summaries_reflect_last_run(harness: Harness) -> None:+ async with harness.client() as c:+ tid = (await c.post("/api/tasks", json=_every_body())).json()["id"]+ res = await c.post(f"/api/tasks/{tid}/run")+ assert res.status_code == 200 and res.json() == {"ok": True, "id": tid}+ await harness.settle()+ row = (await c.get("/api/tasks")).json()["tasks"][0]+ detail = (await c.get(f"/api/tasks/{tid}")).json()+ assert harness.brain.calls == ["hello"]+ for out in (row, detail):+ assert out["state"] == "scheduled"+ assert out["last_run_state"] == "completed"+ assert len(out["last_result"]) == tasks_routes.LAST_RESULT_MAX_CHARS+ assert out["last_result"].startswith("the answer")+ assert any(s["payload"].get("event") == "run_now" for s in detail["steps"])+++async def test_run_now_409_while_running_and_404_unknown(harness: Harness) -> None:+ async with harness.client() as c:+ tid = (await c.post("/api/tasks", json=_every_body())).json()["id"]+ await harness.store.update_state(tid, "running")+ assert (await c.post(f"/api/tasks/{tid}/run")).status_code == 409+ assert (await c.post("/api/tasks/nope/run")).status_code == 404+ row = (await c.get("/api/tasks")).json()["tasks"][0]+ assert row["last_run_state"] == "running"+++async def test_run_now_without_scheduler_503(harness: Harness) -> None:+ harness.app.state.task_scheduler = None+ tid = await harness.store.insert(TaskSpec(**{+ k: v for k, v in _every_body().items() if k != "id"+ }))+ async with harness.client() as c:+ assert (await c.post(f"/api/tasks/{tid}/run")).status_code == 503+++# ----------------------------------------------------------------------+# PATCH enabled+# ----------------------------------------------------------------------++async def test_patch_pauses_and_resumes(harness: Harness) -> None:+ async with harness.client() as c:+ tid = (await c.post("/api/tasks", json=_every_body())).json()["id"]+ res = await c.patch(f"/api/tasks/{tid}", json={"enabled": False})+ assert res.status_code == 200+ assert res.json()["state"] == "paused"+ assert (await c.get("/api/tasks")).json()["tasks"][0]["state"] == "paused"+ assert all(tid != t for _, t in harness.scheduler._heap)++ res = await c.patch(f"/api/tasks/{tid}", json={"enabled": True})+ assert res.status_code == 200+ assert res.json()["state"] == "scheduled"+ assert res.json()["due_at_ns"] is not None+ assert any(tid == t for _, t in harness.scheduler._heap)+++async def test_patch_rejects_one_shot_unknown_and_running(harness: Harness) -> None:+ async with harness.client() as c:+ one_shot = TaskSpec(+ title="once", trigger=TriggerAfterDelay(delay_seconds=60),+ action=SpeakAction(text="x"),+ ).model_dump(mode="json")+ oid = (await c.post("/api/tasks", json=one_shot)).json()["id"]+ assert (await c.patch(f"/api/tasks/{oid}", json={"enabled": False})).status_code == 409+ assert (await c.patch("/api/tasks/nope", json={"enabled": False})).status_code == 404++ tid = (await c.post("/api/tasks", json=_every_body())).json()["id"]+ await harness.store.update_state(tid, "running")+ assert (await c.patch(f"/api/tasks/{tid}", json={"enabled": False})).status_code == 409+ # resume of a task that is not paused+ await harness.store.update_state(tid, "scheduled")+ assert (await c.patch(f"/api/tasks/{tid}", json={"enabled": True})).status_code == 409+ # malformed body (unknown field — the request model forbids extras)+ assert (await c.patch(f"/api/tasks/{tid}", json={"on": True})).status_code == 422+++async def test_paused_task_can_be_cancelled_then_deleted(harness: Harness) -> None:+ async with harness.client() as c:+ tid = (await c.post("/api/tasks", json=_every_body())).json()["id"]+ await c.patch(f"/api/tasks/{tid}", json={"enabled": False})+ assert (await c.delete(f"/api/tasks/{tid}")).status_code == 409+ assert (await c.post(f"/api/tasks/{tid}/cancel")).status_code == 200+ assert (await c.delete(f"/api/tasks/{tid}")).status_code == 200diff --git a/tests/unit/tasks/test_trigger_parity.py b/tests/unit/tasks/test_trigger_parity.pyindex cb235021df..d858fd41a9 100644--- a/tests/unit/tasks/test_trigger_parity.py+++ b/tests/unit/tasks/test_trigger_parity.py@@ -1,9 +1,9 @@"""Parity test for the task TRIGGER vocabulary across Python ↔ TypeScript.BUG-008 class: a vocabulary that spans Python (the Pydantic discriminator),-the TS trigger union (what the create dialog emits) and the TasksView display-(icon + label maps) drifts silently — the dialog emits a trigger the backend-rejects, or the list view shows a blank icon for a trigger it never learned.+the TS trigger union (what the create dialog emits) and the Automations model+(what the list view displays) drifts silently — the dialog emits a trigger the+backend rejects, or the list view mislabels a trigger it never learned.Source of truth: ``TRIGGER_TYPES`` in ``jarvis/tasks/schema.py``. Every TS layermust spell exactly the same four values. (When-Then added ``on_event`` to the TS@@ -14,17 +14,21 @@ from __future__ import annotationsimport refrom pathlib import Path-from jarvis.tasks.schema import TRIGGER_TYPES+from jarvis.tasks.schema import PAUSABLE_TRIGGER_TYPES, TRIGGER_TYPESREPO_ROOT = Path(__file__).resolve().parents[3]TASK_SPEC_TS = REPO_ROOT / "jarvis/ui/web/frontend/src/views/tasks/taskSpec.ts"-TASKS_VIEW_TSX = REPO_ROOT / "jarvis/ui/web/frontend/src/views/TasksView.tsx"+MODEL_TS = REPO_ROOT / "jarvis/ui/web/frontend/src/views/automations/automationsModel.ts"def _expected() -> set[str]:return set(TRIGGER_TYPES)+def test_pausable_triggers_are_known_triggers() -> None:+ assert set(PAUSABLE_TRIGGER_TYPES) < _expected()++def test_taskspec_ts_trigger_union_matches_python() -> None:text = TASK_SPEC_TS.read_text(encoding="utf-8")# Capture up to the next top-level `export` — the union body contains inner@@ -38,36 +42,12 @@ def test_taskspec_ts_trigger_union_matches_python() -> None:)-def test_tasksview_triggertype_matches_python() -> None:- text = TASKS_VIEW_TSX.read_text(encoding="utf-8")- block = re.search(r"type TriggerType =([\s\S]+?);", text)- assert block is not None, "could not find TriggerType in TasksView.tsx"+def test_automations_model_triggertype_matches_python() -> None:+ text = MODEL_TS.read_text(encoding="utf-8")+ block = re.search(r"export type TriggerType =([\s\S]+?);", text)+ assert block is not None, "could not find TriggerType in automationsModel.ts"found = set(re.findall(r'"([^"]+)"', block.group(1)))assert found == _expected(), (- f"TasksView.tsx TriggerType drift: extra={found - _expected()}, "- f"missing={_expected() - found}"- )---def test_tasksview_icon_map_covers_every_trigger() -> None:- text = TASKS_VIEW_TSX.read_text(encoding="utf-8")- block = re.search(r"const TRIGGER_ICON[^{]+\{([\s\S]+?)\};", text)- assert block is not None, "could not find TRIGGER_ICON map in TasksView.tsx"- found = set(re.findall(r"(\w+)\s*:", block.group(1)))- assert found == _expected(), (- f"TasksView.tsx TRIGGER_ICON drift: extra={found - _expected()}, "- f"missing={_expected() - found}"- )---def test_tasksview_label_map_covers_every_trigger() -> None:- text = TASKS_VIEW_TSX.read_text(encoding="utf-8")- block = re.search(- r"function makeTriggerLabels[\s\S]+?return\s*\{([\s\S]+?)\};", text- )- assert block is not None, "could not find makeTriggerLabels in TasksView.tsx"- found = set(re.findall(r"(\w+)\s*:\s*t\(", block.group(1)))- assert found == _expected(), (- f"TasksView.tsx label map drift: extra={found - _expected()}, "+ f"automationsModel.ts TriggerType drift: extra={found - _expected()}, "f"missing={_expected() - found}")