Skip to content

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

feat(ui): retire Jarvis schedules, scheduling lives on agent routines

rubenluetke10-beep20c19138903e
diff --git a/docs/authoring/public-docs-manifest.yaml b/docs/authoring/public-docs-manifest.yaml
index 0a924969d2..1c98718bf4 100644
--- a/docs/authoring/public-docs-manifest.yaml
+++ b/docs/authoring/public-docs-manifest.yaml
@@ -190,9 +190,10 @@ pages:
file: docs/product/everyday-use/tasks-and-reminders.md
title: Tasks and Reminders
diataxis: howto
- summary: Create, review, approve, and complete tasks, including scheduled and recurring work.
+ summary: Schedule recurring and one-off work as routines on your agents, then review, pause or stop each run.
authoritative_sources:
- - jarvis/ui/web/frontend/src/views/AutomationsView.tsx
+ - jarvis/ui/web/frontend/src/components/society/card/AgentRoutinesList.tsx
+ - jarvis/society/routines.py
- jarvis/ui/web/tasks_routes.py
- jarvis/tasks/store.py
- jarvis/tasks/scheduler.py
diff --git a/docs/commands-reference.md b/docs/commands-reference.md
index be977f6b29..86615a5c24 100644
--- a/docs/commands-reference.md
+++ b/docs/commands-reference.md
@@ -373,12 +373,12 @@ Cancel a running Jarvis-Agent mission by id.
## `tasks-list` — List tasks
-List scheduled and running tasks.
+List scheduled and running tasks (agent routines).
- **Endpoint:** `GET /api/tasks`
- **Arguments:** none
- **Requires confirmation:** no
-- **Desktop UI section:** `tasks`
+- **Desktop UI section:** `agents`
- **Voice example (EN):** "show me my tasks"
## `task-cancel` — Cancel a task
@@ -388,7 +388,7 @@ Cancel a running or scheduled task by id.
- **Endpoint:** `POST /api/tasks/{task_id}/cancel`
- **Arguments:** `task_id` (string; required)
- **Requires confirmation:** yes
-- **Desktop UI section:** `tasks`
+- **Desktop UI section:** `agents`
- **Voice example (EN):** "cancel the task"
## `skills-list` — List installed skills
diff --git a/docs/product/everyday-use/tasks-and-reminders.md b/docs/product/everyday-use/tasks-and-reminders.md
index b2b9f46daf..076c37cb48 100644
--- a/docs/product/everyday-use/tasks-and-reminders.md
+++ b/docs/product/everyday-use/tasks-and-reminders.md
@@ -1,174 +1,91 @@
---
title: "Tasks and Reminders"
slug: tasks-and-reminders
-summary: "Create, review, approve, and complete tasks, including scheduled and recurring work."
+summary: "Schedule recurring and one-off work as routines on your agents, then review, pause or stop each run."
section: "Everyday use"
section_order: 2
order: 3
diataxis: howto
status: active
owner: maintainers
-last_reviewed: 2026-07-30
+last_reviewed: 2026-10-01
phase: "-"
audience: end-user
-tags: [tasks, reminders, scheduling, recurring, automation, approvals]
+tags: [tasks, reminders, scheduling, recurring, routines, agents]
related: [jarvis-agents, workflows-and-commands, safety-and-approvals]
---
-Use **Tasks** when one instruction should run later or repeat. The saved card is
-the source of truth: saying “remind me” in chat does not create a durable task.
-
-A reminder is not a separate record. A time or mission event starts a task.
-Time-based tasks run an isolated Brain turn; there is no alarm-only option.
+Scheduled work lives on your **Agents**. Each agent can carry **routines**: a
+saved job that runs on a schedule or when something happens, in that agent's
+own chat, with its instructions and permissions. There is no separate
+schedules page any more; the old Automations section and its catalogue of
+ready-made schedules were retired in favour of agent routines.
## Before You Start
-- Keep the app running when work is due. Schedules survive a normal restart;
- one overdue occurrence runs when the scheduler returns.
-- Under **API Keys & Providers > Brain**, test the provider that should answer.
- The task uses whichever Brain is active when it runs.
-- Connect required services under **Skills, Plugins & MCPs** first. Only
- connected plugins are offered.
-- Write a self-contained prompt. Tasks do not receive the current chat history.
-
-> [!warning] Never put credentials, recovery codes, or private keys in a task
-> name or prompt. Use only the protected connection fields for that service.
-
-## Choose the Right Path
-
-Use **Once** for one later result, **Recurring** for an interval, and
-**When-Then** to react to a mission outcome. Use **Agents** for longer reviewed
-work with files, or **Workflows** for reusable ordered steps. A task does not
-gain an agent workspace or review loop. Agent names follow your configured
-assistant name.
-
-## Create a One-Time Task or Reminder
-
-1. Open **Tasks**, then select **New**.
-2. Enter a short, recognizable **Name**.
-3. Keep **Trigger** on **Schedule**, then select **Once**.
-4. Choose **At date/time** or **After delay**. Dates use this device’s local
- time. A past date becomes due immediately.
-5. Under **What should it do?**, request one observable result. For a reminder,
- ask for the exact short text to return. Trust the Timeline over speech.
-6. Leave plugins off unless the result needs them. Choose a model tier, then
- select **Create task**.
-7. Confirm a **scheduled** card and countdown appear.
-
-Chat and voice can list tasks or confirmation-gate cancellation, but cannot
-create them. Trust only a saved card.
-
-## Create a Recurring Task
-
-1. Choose **Schedule > Recurring**, then **Hourly**, **Daily**, or **Custom**.
- Custom accepts minutes or hours.
-3. Choose an interval longer than a run. The next occurrence is queued when a
- run starts, so slow runs can overlap.
-4. Complete the form and create the task.
-
-**Daily** means every 24 hours after the first selected local time, not a
-calendar rule. A daylight-saving change can shift later wall-clock times.
-There is no pause or edit control; cancel and recreate to make changes.
+- Create an agent for the job first, or pick an existing one under **Agents**.
+ The routine runs with that agent's model seat and permissions.
+- Connect the services the job needs. A routine never grants an agent extra
+ plugin permissions.
+- Keep the app running when work is due. A slot missed while the app was
+ closed is skipped, not caught up hours later.
-Failure has no immediate retry. A queued next occurrence can run while the app
-stays open, but a failed recurring card is not restored after restart.
+> [!warning] Never put credentials, recovery codes, or private keys in a
+> routine's title or prompt.
-## Choose Models and Plugin Permissions
+## Add a Routine
-- **Fast** and **Auto** both use the active provider’s fast model.
-- **Deep** uses that provider’s deep model when configured, otherwise its fast
- model.
-- Scheduled turns do not cross provider families after failure. Test or switch
- the active Brain before the due time.
-- A disconnected plugin is skipped. Verify the Timeline rather than assuming
- an action ran.
+1. Open **Agents** and open the agent that should do the work.
+2. In its card, open **Routines**, then **Add a routine**.
+3. Enter a short **Title** and, under **What to do**, a self-contained
+ instruction. The routine does not see your earlier chat.
+4. Under **When**, choose **Every few hours**, **Every day at a time**, or
+ **When something happens**, and fill in the time or event.
+5. Select **Add**. The routine appears in the list with its **Next run**.
-| Plugin scope | Unattended boundary |
-|---|---|
-| **Read** | Offers the plugin but pre-approves nothing; confirmation-level calls can time out and fail |
-| **Write** or **Full** | Pre-approves confirmation-level calls from that plugin for this task’s current turn |
-| Off | Does not offer that plugin to the task |
-
-Write and Full currently have the same effect. They cannot override blocked
-actions or grant other plugins. The prompt is the explicit request; a broad
-grant alone is not an instruction.
-
-## React to Agent Work with When-Then
-
-Choose **When-Then** to react when a mission succeeds, fails, or is cancelled.
-Then choose:
-
-- **Computer-Use** runs the written goal unattended on a compatible graphical
- desktop. Selecting it and creating the rule is the explicit authorization.
-- **Agent task** for one isolated Brain turn with the selected plugins.
-- **Just notify me** currently ends as failed because fixed speech is not
- connected to this task path.
-
-For Computer-Use or Agent task, **Say when done** requests an announcement.
-Mission fields such as `{result_uri}` can be inserted; unknown fields remain.
-
-When-Then is still a preview: the rule can fire for every matching mission in
-the current app session, but its card shows **done** after the first match and
-is not restored after restart. Delete the done card to stop later matches.
-
-## Review, Stop, Complete, and Delete
-
-Tasks refresh about every three seconds. Filter by **All**, **Active**, **Done**,
-or **Problems**. Expand a card for its saved **Spec**, results, and errors.
-
-| State | Meaning | Available action |
-|---|---|---|
-| **scheduled** | Waiting for a time or event | Review or **Cancel** |
-| **running** | The action has started | Review or request **Cancel** |
-| **done** | A one-time task succeeded | Review or **Delete** |
-| **failed** | The run ended without an automatic retry | Read the error, then delete or recreate |
-| **cancelled** | Future scheduling was removed | Review or delete |
-| **interrupted** | The app closed during the run | Review, then recreate if still needed |
+You can also ask the agent in its chat, for example "every weekday at 8, check
+my inbox and summarize what needs an answer". The agent saves the routine and
+reads back when it runs next.
-Completion is automatic; there is no **Mark complete** button. Recurring tasks
-return to scheduled. Cancel before deleting an active task. Delete removes its
-local card and Timeline with no undo.
+## Review, Pause, and Stop
-Cancel is a signal, not a reversal. Use the Computer-Use emergency stop if
-desktop activity continues. A Brain turn may finish after cancellation. No
-task control can undo external messages, posts, or file changes.
+Open a routine in the agent's **Routines** list to see its schedule, its runs
+and their results. From there you can run it now, pause and resume it, stop
+it, or delete it. Chat and voice can list routines ("show me my tasks") and
+cancel one after a confirmation.
## How It Fits Together
-1. The local scheduler restores saved cards and watches their time or event.
-2. At the trigger, the app starts one isolated action with the active Brain and
- only the plugins selected for that task.
-3. Safety checks classify each tool call. Read grants leave confirmation gates
- closed; Write or Full can answer them only for the matching plugin and turn.
-4. Results and failures return to the Timeline; announcements are additional.
-5. Background agents keep longer work, review, and files; Workflows keep
- reusable multi-step definitions.
+1. A routine is saved with its agent, its instruction, and its trigger.
+2. The local scheduler watches the time or event. At the trigger it starts one
+ run in the agent's own chat, on the agent's model seat.
+3. The agent's permissions decide which tools the run may use; safety checks
+ classify every tool call as usual.
+4. The result lands in the routine's run history on the agent card.
-Task records stay on this device. A remote Brain or plugin may receive the
-prompt and relevant data under its service policy.
+Routine records stay on this device. The agent's model provider and any
+connected service receive the prompt and the data the run needs.
## Check That It Works
-1. Create **Once > After delay** for one minute, with all plugins off.
-2. Name it **Schedule check** and request exactly `Scheduled check complete`.
-3. Confirm the card changes from **scheduled** to **running** to **done**.
-4. Expand it and confirm the Timeline contains the requested result.
+1. Add a routine that runs soon with a harmless instruction, such as "reply
+ with the words Routine check complete".
+2. Wait for its next run, then open the routine.
+3. Confirm the run shows the requested text.
## Troubleshooting
| What you see | Likely cause | What to do |
|---|---|---|
-| **Create task** is disabled | A name, prompt, action text, or time is missing | Complete every visible required field |
-| A plugin is absent | It is disconnected or needs sign-in again | Reconnect it, then reopen the task form |
-| A task stays **scheduled** past its time | The app or scheduler was not running | Keep the app open; restart if the whole view remains unavailable |
-| A task is **failed** | The Brain, plugin, runner, or requested capability was unavailable | Read the Timeline, test the dependency, then recreate if needed |
-| Cancelled desktop work continues | The best-effort Computer-Use stop has not finished | Use the Computer-Use emergency stop, then review the Timeline |
+| A routine did not run at its time | The app was closed at that moment | Keep the app open; the next slot runs normally |
+| A run failed | The agent's model or a needed service was unavailable | Open the run, read the error, then fix the connection or the agent's seat |
+| An old schedule is listed as cancelled | It came from the retired Automations catalogue | Give the job to an agent as a routine |
## Next Steps
-- Read [Agents and Background Work](jarvis-agents) for reviewed, longer work and
- generated files.
+- Read [Agents and Background Work](jarvis-agents) to set up the agents that
+ own your routines.
- Use [Workflows and App Commands](workflows-and-commands) for reusable
multi-step automation.
-- Review [Safety and Approvals](safety-and-approvals) before allowing
- unattended external changes.
+- Review [Safety and Approvals](safety-and-approvals) before letting an agent
+ make external changes unattended.
diff --git a/docs/product/extend-and-automate/jarvis-agents.md b/docs/product/extend-and-automate/jarvis-agents.md
index bf2f609452..3cab198de9 100644
--- a/docs/product/extend-and-automate/jarvis-agents.md
+++ b/docs/product/extend-and-automate/jarvis-agents.md
@@ -147,10 +147,10 @@ read credentials, or change protected configuration through the worker grant.
5. **Outputs retains the result.** Use [Outputs and Files](outputs-and-files)
to preview files, cancel active work, or create a linked continuation or
restart.
-6. **Tasks can react to the outcome.** A When-Then task can listen for a final
- mission result. A normal scheduled task does not automatically gain an
- agent workspace or review loop. Read [Tasks and Reminders](tasks-and-reminders)
- before relying on mission events.
+6. **Routines can follow up.** An agent's routine can run on a schedule or
+ when something happens. A routine runs in the agent's own chat; it does not
+ gain a mission workspace or review loop. Read
+ [Tasks and Reminders](tasks-and-reminders) before relying on routines.
## Check That It Works
@@ -185,7 +185,7 @@ For repeated startup, provider, or connection failures, follow
and understand where copied files are stored.
- Read [Skills](skills) to turn repeatable instructions into a reviewed
background mission.
-- Read [Tasks and Reminders](tasks-and-reminders) to react to a mission's final
- state.
+- Read [Tasks and Reminders](tasks-and-reminders) to give an agent scheduled
+ work.
- Review [Safety and Approvals](safety-and-approvals) before a mission uses a
connected service or changes anything outside its isolated files.
diff --git a/docs/product/extend-and-automate/workflows-and-commands.md b/docs/product/extend-and-automate/workflows-and-commands.md
index 82c2253a01..fa3c67de45 100644
--- a/docs/product/extend-and-automate/workflows-and-commands.md
+++ b/docs/product/extend-and-automate/workflows-and-commands.md
@@ -234,8 +234,8 @@ For repeated provider, connection, or startup failures, follow the main
## Next Steps
-- Read [Tasks and Reminders](tasks-and-reminders) when one saved action should
- start at a time, interval, or mission event.
+- Read [Tasks and Reminders](tasks-and-reminders) when an agent should run a
+ saved job at a time, an interval, or an event.
- Read [Skills](skills) when you want repeatable instructions that can choose
from currently connected capabilities.
- Use the [CLI Reference](cli-reference) to browse safe workflow and feature
diff --git a/docs/product/privacy-safety-and-support/safety-and-approvals.md b/docs/product/privacy-safety-and-support/safety-and-approvals.md
index aefaad29ad..904aba1167 100644
--- a/docs/product/privacy-safety-and-support/safety-and-approvals.md
+++ b/docs/product/privacy-safety-and-support/safety-and-approvals.md
@@ -269,8 +269,8 @@ approval field is not proof that no standing rule applied.
- Read [Computer Use](computer-use) before allowing live mouse and keyboard
control.
-- Review [Tasks and Reminders](tasks-and-reminders) before granting unattended
- Write or Full access.
+- Review [Tasks and Reminders](tasks-and-reminders) before letting an agent's
+ routine act unattended.
- Use [Skills](skills) to understand drafts, activation, and how instructions
call normal tools.
- Read [Privacy and Local Data](privacy-and-local-data) to understand what an
diff --git a/docs/routines.md b/docs/routines.md
index 3412893a4b..ab7cc6627d 100644
--- a/docs/routines.md
+++ b/docs/routines.md
@@ -1,7 +1,7 @@
# Agent routines
-Routines reuse the Automations task store and scheduler. Each routine belongs
-to an agent, appears in its Routines rail and in Automations, and executes
+Routines run on the task store and scheduler (`jarvis/tasks`). Each routine
+belongs to an agent, appears in its Routines rail, and executes
through that agent's canonical chat with its current instructions and permissions.
Creating a routine never grants additional plugin permissions.
@@ -79,8 +79,8 @@ event uses `{"kind":"event_hook","event_name":"crm.customer.created"}`.
Both kinds accept optional `conditions`, `max_firings` and `cooldown_seconds`.
Conditions compare scalar JSON fields; dotted paths access nested objects.
-Use **Connect webhook** on the agent's routine or in its expanded Automations
-row. The app shows the endpoint and a masked, copyable credential. Credentials
+Use **Connect webhook** on the agent's routine. The app shows the endpoint and
+a masked, copyable credential. Credentials
are stored through the existing portable secret store and never included in the
routine specification or returned by the agent's routine tools. Rotation revokes
the old credential without changing other routines.
diff --git a/docs/trigger-sources.md b/docs/trigger-sources.md
index 757624974a..1d31aa45ac 100644
--- a/docs/trigger-sources.md
+++ b/docs/trigger-sources.md
@@ -1,8 +1,8 @@
# Routine trigger sources
Routines use the existing task store, scheduler, agent permissions and execution
-history. Create and manage them in an agent chat or through **Routines** and
-**Automations**. A trigger decides when to submit the saved action; it does not
+history. Create and manage them in an agent chat or through the agent's
+**Routines**. A trigger decides when to submit the saved action; it does not
grant access to an account or install an external subscription.
| Group | Entry points | Requirements |
diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.py
index 6713ca065c..44f26a203c 100644
--- a/jarvis/brain/manager.py
+++ b/jarvis/brain/manager.py
@@ -13415,10 +13415,10 @@ class BrainManager:
Unknown grants (e.g. a plugin that isn't connected) are silently
skipped — the task runs with whatever of its allowlist is live.
- A grant is matched by :func:`jarvis.tasks.templates.grant_matches`:
+ A grant is matched by :func:`jarvis.tasks.grants.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 routine 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
@@ -13428,7 +13428,7 @@ class BrainManager:
dispatcher — never the router surface.
"""
from jarvis.clis.capability_provider import equivalent_grants # noqa: PLC0415
- from jarvis.tasks.templates import grant_matches # noqa: PLC0415
+ from jarvis.tasks.grants import grant_matches # noqa: PLC0415
if not allowed_tools:
return {}
diff --git a/jarvis/commands/registry.py b/jarvis/commands/registry.py
index b5a1a07d89..97af9e900b 100644
--- a/jarvis/commands/registry.py
+++ b/jarvis/commands/registry.py
@@ -1062,11 +1062,11 @@ def _build_registry() -> tuple[AppCommand, ...]:
AppCommand(
id="tasks-list",
title="List tasks",
- description="List scheduled and running tasks.",
+ description="List scheduled and running tasks (agent routines).",
method="GET",
path="/api/tasks",
worker_allowed=True,
- ui_section="tasks",
+ ui_section="agents",
voice_aliases={
"de": ("zeig mir meine aufgaben",), # i18n-allow: input vocab
"en": ("show me my tasks",),
@@ -1088,7 +1088,7 @@ def _build_registry() -> tuple[AppCommand, ...]:
},
path_params=("task_id",),
dangerous=True,
- ui_section="tasks",
+ ui_section="agents",
voice_aliases={
"de": ("brich die aufgabe ab",), # i18n-allow: input vocab
"en": ("cancel the task",),
diff --git a/jarvis/plugins/tool/navigate.py b/jarvis/plugins/tool/navigate.py
index 2d1b93587a..dbd0d52a70 100644
--- a/jarvis/plugins/tool/navigate.py
+++ b/jarvis/plugins/tool/navigate.py
@@ -29,7 +29,6 @@ KNOWN: frozenset[str] = frozenset(
"plugins",
"docs",
"mcps",
- "tasks",
"sessions",
"run_inspector",
# Spend & Tokens.
@@ -137,9 +136,15 @@ _ALIASES: dict[str, str] = {
"dokumente": "docs",
"doku": "docs",
"mcp": "mcps",
- "task": "tasks",
- "aufgaben": "tasks",
- "aufgabe": "tasks",
+ # The retired Automations section: scheduled work lives on agents now
+ # (each agent's routines), so its old id and spoken names land there.
+ "tasks": "agents",
+ "task": "agents",
+ "aufgaben": "agents",
+ "aufgabe": "agents",
+ "automations": "agents",
+ "routines": "agents",
+ "schedules": "agents",
"transkription": "sessions",
"transcription": "sessions",
"session": "sessions",
diff --git a/jarvis/tasks/approval_bridge.py b/jarvis/tasks/approval_bridge.py
index 1dba2d1927..588f2f3ba9 100644
--- a/jarvis/tasks/approval_bridge.py
+++ b/jarvis/tasks/approval_bridge.py
@@ -77,6 +77,6 @@ class TaskAutoApprover:
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.
"""
- from jarvis.tasks.templates import grant_matches # noqa: PLC0415
+ from jarvis.tasks.grants import grant_matches # noqa: PLC0415
return any(grant_matches(grant, tool_name) for grant in granted)
diff --git a/jarvis/tasks/grants.py b/jarvis/tasks/grants.py
new file mode 100644
index 0000000000..da33b456df
--- /dev/null
+++ b/jarvis/tasks/grants.py
@@ -0,0 +1,18 @@
+"""How a task's plugin grant covers a live tool name.
+
+One rule, shared by the brain's per-task tool allowlist
+(``BrainManager._select_task_tools``) and the unattended-approval bridge
+(``TaskAutoApprover``), so a tool a routine can SEE is exactly a tool its
+grant can pre-authorize.
+"""
+
+from __future__ import annotations
+
+__all__ = ["grant_matches"]
+
+
+def grant_matches(grant: str, tool_name: str) -> bool:
+ """A grant names a tool exactly, or is a prefix grant for a bridged
+ plugin whose tools are namespaced ``<plugin>/<tool>`` (``github`` covers
+ ``github/list_issues``)."""
+ return tool_name == grant or tool_name.startswith(grant + "/")
diff --git a/jarvis/tasks/store.py b/jarvis/tasks/store.py
index baa7da09fa..047aa42185 100644
--- a/jarvis/tasks/store.py
+++ b/jarvis/tasks/store.py
@@ -552,3 +552,30 @@ class TaskStore:
rowcount = cur.rowcount
await cur.close()
return int(rowcount or 0)
+
+ async def retire_catalogue_tasks(self) -> int:
+ """Startup cleanup: cancel every live task the retired automations
+ catalogue created (``created_by="template"``).
+
+ Scheduling now lives on agents (``jarvis/society/routines.py``); the
+ catalogue and the standalone Automations section are gone, so such a
+ task would keep firing with nowhere left to see, pause or stop it.
+ The row is kept, only its state changes. Returns the number of
+ retired tasks; called at app start, before the scheduler hydrates.
+ """
+ conn = self._require_conn()
+ now_ns = time.time_ns()
+ cur = await conn.execute(
+ """
+ UPDATE tasks
+ SET state = 'cancelled',
+ finished_at_ns = ?,
+ last_error = 'Standalone schedules were retired; give this job to an agent instead'
+ WHERE state IN ('pending', 'scheduled', 'paused')
+ AND json_extract(spec_json, '$.created_by') = 'template'
+ """,
+ (now_ns,),
+ )
+ rowcount = cur.rowcount
+ await cur.close()
+ return int(rowcount or 0)
diff --git a/jarvis/tasks/templates/__init__.py b/jarvis/tasks/templates/__init__.py
deleted file mode 100644
index b5b6f98cd7..0000000000
--- a/jarvis/tasks/templates/__init__.py
+++ /dev/null
@@ -1,372 +0,0 @@
-"""Automation templates — the pre-built automations catalogue.
-
-An *automation* is a recurring scheduled task (``jarvis/tasks``) whose action
-is an agentic brain turn with a plugin allowlist. A *template* is the
-ready-made blueprint for one: a name, a category, a default schedule, the
-prompt, the plugin grants it needs, and optional user inputs (a watchlist, a
-city, a repository path) that are substituted into the prompt when the user
-adds it.
-
-Layout — ONE MODULE PER TEMPLATE. Every ``jarvis/tasks/templates/<key>.py``
-exports a module-level ``TEMPLATE: AutomationTemplate``; :func:`all_templates`
-discovers them with ``pkgutil`` so adding a template never touches a shared
-file (ten authors can land ten templates in parallel without a merge
-conflict). Modules starting with ``_`` are helpers and are skipped.
-
-Rules for a template:
-
-- ``prompt`` is English. It asks for the reply in the configured output
- language — the one resolver (``jarvis/core/turn_language.py``) decides.
-- ``plugin_grants`` name LIVE TOOL NAMES (``gmail``, ``google_calendar``,
- ``search_web``, ``wiki-recall``, ``github`` — the last one is a prefix
- grant that covers every ``github/<tool>``). ``requires`` lists the subset
- the automation cannot work without; the API reports ``ready`` per
- template by checking those against the live tool registry so the card can
- say "needs Gmail" instead of failing at 09:00.
-- ``{placeholders}`` in ``prompt`` are template inputs (``inputs``), filled
- from the user's values (or the input's ``default``) when the template is
- instantiated. No other brace syntax — ``build_spec`` escapes the rest.
-- ``name``/``description`` carry ``en``/``de``/``es`` — the UI picks the
- active locale and falls back to ``en``.
-"""
-
-from __future__ import annotations
-
-import importlib
-import pkgutil
-import re
-from collections.abc import Iterable
-from datetime import datetime, timedelta
-from typing import Any, Literal
-
-from pydantic import BaseModel, ConfigDict, Field
-
-from jarvis.tasks.schema import (
- AgentAction,
- PluginGrant,
- TaskSpec,
- TriggerCalendar,
- TriggerEvery,
-)
-
-Locale = Literal["en", "de", "es"]
-LOCALES: tuple[Locale, ...] = ("en", "de", "es")
-
-TemplateCategory = Literal["news", "productivity", "finance", "research", "developer"]
-#: Display order of the catalogue sections (the UI groups cards by this).
-CATEGORIES: tuple[TemplateCategory, ...] = (
- "news",
- "productivity",
- "finance",
- "research",
- "developer",
-)
-
-#: Tag that marks a task as "created from template <key>" — the UI uses it to
-#: show the template as installed and to pair a task with its card.
-TEMPLATE_TAG_PREFIX = "template:"
-
-
-class LocalizedText(BaseModel):
- """A short UI string in the three product locales (``en`` is mandatory)."""
-
- model_config = ConfigDict(frozen=True, extra="forbid")
- en: str = Field(min_length=1, max_length=512)
- de: str = Field(default="", max_length=512)
- es: str = Field(default="", max_length=512)
-
- def for_locale(self, locale: str) -> str:
- return getattr(self, locale, "") or self.en
-
-
-class TemplateInput(BaseModel):
- """A value the user may fill in when adding the template (a watchlist, a
- city, a repo path). ``key`` is the ``{placeholder}`` used in the prompt."""
-
- model_config = ConfigDict(frozen=True, extra="forbid")
- key: str = Field(min_length=1, max_length=32, pattern=r"^[a-z][a-z0-9_]*$")
- label: LocalizedText
- placeholder: LocalizedText | None = None
- default: str = Field(default="", max_length=2048)
- required: bool = False
-
-
-class TemplateSchedule(BaseModel):
- """Default schedule, expressed the way the UI shows it ("Daily at 07:30",
- "Mondays at 09:00"), not as a cron expression. Mapped onto the
- ``every`` trigger by :func:`schedule_to_trigger`.
-
- ``weekday`` follows ``datetime.weekday()``: 0 = Monday … 6 = Sunday.
- """
-
- model_config = ConfigDict(frozen=True, extra="forbid")
- kind: Literal["hourly", "daily", "weekly"] = "daily"
- time: str = Field(default="08:00", pattern=r"^([01]\d|2[0-3]):[0-5]\d$")
- weekday: int = Field(default=0, ge=0, le=6)
- timezone: str | None = None
-
-
-class AutomationTemplate(BaseModel):
- model_config = ConfigDict(frozen=True, extra="forbid")
-
- key: str = Field(min_length=1, max_length=48, pattern=r"^[a-z][a-z0-9_]*$")
- category: TemplateCategory
- #: A lucide icon name the UI resolves (``sun``, ``mail``, ``dollar-sign``).
- icon: str = Field(default="sparkles", max_length=48)
- name: LocalizedText
- description: LocalizedText
- schedule: TemplateSchedule = Field(default_factory=TemplateSchedule)
- prompt: str = Field(min_length=1, max_length=16_384)
- plugin_grants: tuple[PluginGrant, ...] = Field(default_factory=tuple)
- #: Tool names (or ``prefix`` grants like ``github``) the automation cannot
- #: run without. Empty = works on any install (brain only).
- requires: tuple[str, ...] = Field(default_factory=tuple)
- inputs: tuple[TemplateInput, ...] = Field(default_factory=tuple)
- model_tier: Literal["fast", "deep", "auto"] = "auto"
- tags: tuple[str, ...] = Field(default_factory=tuple)
-
- @property
- def tag(self) -> str:
- return f"{TEMPLATE_TAG_PREFIX}{self.key}"
-
- def to_api(self, locale: str, *, live_tools: Iterable[str] | None = None) -> dict[str, Any]:
- """Flat dict for ``GET /api/tasks/templates`` — localized, with the
- readiness verdict so the card can say what is missing."""
- missing = missing_requirements(self.requires, live_tools) if live_tools is not None else []
- return {
- "key": self.key,
- "category": self.category,
- "icon": self.icon,
- "name": self.name.for_locale(locale),
- "description": self.description.for_locale(locale),
- "schedule": self.schedule.model_dump(),
- "schedule_label": schedule_label(self.schedule, locale),
- "plugin_grants": [g.model_dump() for g in self.plugin_grants],
- "requires": list(self.requires),
- "missing": missing,
- "ready": not missing,
- "inputs": [
- {
- "key": i.key,
- "label": i.label.for_locale(locale),
- "placeholder": i.placeholder.for_locale(locale) if i.placeholder else "",
- "default": i.default,
- "required": i.required,
- }
- for i in self.inputs
- ],
- "model_tier": self.model_tier,
- "tags": list(self.tags),
- "prompt": self.prompt,
- }
-
-
-# ---------------------------------------------------------------------
-# Discovery
-# ---------------------------------------------------------------------
-
-_cache: dict[str, AutomationTemplate] | None = None
-
-
-def all_templates(*, refresh: bool = False) -> dict[str, AutomationTemplate]:
- """Every template module in this package, keyed by ``template.key``,
- ordered by category (catalogue order) and then by key."""
- global _cache
- if _cache is not None and not refresh:
- return _cache
- found: dict[str, AutomationTemplate] = {}
- for info in pkgutil.iter_modules(__path__):
- if info.name.startswith("_"):
- continue
- module = importlib.import_module(f"{__name__}.{info.name}")
- template = getattr(module, "TEMPLATE", None)
- if not isinstance(template, AutomationTemplate):
- continue
- if template.key in found:
- raise RuntimeError(
- f"duplicate automation template key {template.key!r} ({info.name}.py)"
- )
- found[template.key] = template
- order = {c: i for i, c in enumerate(CATEGORIES)}
- _cache = dict(sorted(found.items(), key=lambda kv: (order[kv[1].category], kv[0])))
- return _cache
-
-
-def get_template(key: str) -> AutomationTemplate | None:
- return all_templates().get(key)
-
-
-# ---------------------------------------------------------------------
-# Readiness
-# ---------------------------------------------------------------------
-
-
-def grant_matches(grant: str, tool_name: str) -> bool:
- """A grant names a tool exactly, or is a prefix grant for a bridged
- plugin whose tools are namespaced ``<plugin>/<tool>`` (``github`` covers
- ``github/list_issues``)."""
- return tool_name == grant or tool_name.startswith(grant + "/")
-
-
-def missing_requirements(
- requires: Iterable[str],
- live_tools: Iterable[str] | None,
-) -> list[str]:
- live = list(live_tools or ())
- return [req for req in requires if not any(grant_matches(req, name) for name in live)]
-
-
-# ---------------------------------------------------------------------
-# Schedule → trigger
-# ---------------------------------------------------------------------
-
-
-def _parse_hhmm(value: str) -> tuple[int, int]:
- hh, mm = value.split(":")
- return int(hh), int(mm)
-
-
-def next_occurrence(schedule: TemplateSchedule, now: datetime) -> datetime:
- """The first wall-clock moment strictly after ``now`` that matches the
- schedule (local time, naive — the scheduler treats ISO without a zone as
- the system zone)."""
- if schedule.kind == "hourly":
- return (now + timedelta(hours=1)).replace(minute=0, second=0, microsecond=0)
- hh, mm = _parse_hhmm(schedule.time)
- candidate = now.replace(hour=hh, minute=mm, second=0, microsecond=0)
- if schedule.kind == "daily":
- if candidate <= now:
- candidate += timedelta(days=1)
- return candidate
- # weekly
- days_ahead = (schedule.weekday - now.weekday()) % 7
- candidate += timedelta(days=days_ahead)
- if candidate <= now:
- candidate += timedelta(days=7)
- return candidate
-
-
-def schedule_to_trigger(
- schedule: TemplateSchedule, now: datetime | None = None
-) -> TriggerEvery | TriggerCalendar:
- if schedule.timezone and schedule.kind != "hourly":
- return TriggerCalendar(
- timezone=schedule.timezone,
- local_time=schedule.time,
- weekdays=(schedule.weekday,) if schedule.kind == "weekly" else (),
- )
- # Legacy API callers with no client timezone retain interval semantics.
- now = now or datetime.now()
- interval = {"hourly": 3600, "daily": 86_400, "weekly": 7 * 86_400}[schedule.kind]
- first = next_occurrence(schedule, now)
- return TriggerEvery(
- interval_seconds=float(interval),
- start_at=first.isoformat(timespec="seconds"),
- )
-
-
-_WEEKDAY_NAMES: dict[str, tuple[str, ...]] = {
- "en": ("Mondays", "Tuesdays", "Wednesdays", "Thursdays", "Fridays", "Saturdays", "Sundays"),
- "de": ( # i18n-allow
- "Montags",
- "Dienstags",
- "Mittwochs",
- "Donnerstags",
- "Freitags",
- "Samstags",
- "Sonntags",
- ),
- "es": ("Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábados", "Domingos"),
-}
-_SCHEDULE_WORDS: dict[str, dict[str, str]] = {
- "en": {"hourly": "Every hour", "daily": "Daily at {time}", "weekly": "{day} at {time}"},
- "de": { # i18n-allow
- "hourly": "Stündlich",
- "daily": "Täglich um {time}",
- "weekly": "{day} um {time}",
- },
- "es": {"hourly": "Cada hora", "daily": "Diario a las {time}", "weekly": "{day} a las {time}"},
-}
-
-
-def schedule_label(schedule: TemplateSchedule, locale: str = "en") -> str:
- """ "Daily at 07:30" / "Täglich um 07:30" / "Mondays at 09:00"."""
- loc = locale if locale in _SCHEDULE_WORDS else "en"
- words = _SCHEDULE_WORDS[loc]
- if schedule.kind == "hourly":
- return words["hourly"]
- if schedule.kind == "daily":
- return words["daily"].format(time=schedule.time)
- day = _WEEKDAY_NAMES[loc][schedule.weekday]
- return words["weekly"].format(day=day, time=schedule.time)
-
-
-# ---------------------------------------------------------------------
-# Instantiate
-# ---------------------------------------------------------------------
-
-_PLACEHOLDER = re.compile(r"\{([a-z][a-z0-9_]*)\}")
-
-
-def render_prompt(template: AutomationTemplate, inputs: dict[str, str] | None) -> str:
- """Substitute ``{input_key}`` placeholders; unknown braces stay literal."""
- values = {
- i.key: ((inputs or {}).get(i.key) or "").strip() or i.default for i in template.inputs
- }
-
- def _sub(match: re.Match[str]) -> str:
- key = match.group(1)
- return values.get(key, match.group(0))
-
- return _PLACEHOLDER.sub(_sub, template.prompt)
-
-
-def build_spec(
- template: AutomationTemplate,
- *,
- inputs: dict[str, str] | None = None,
- schedule: TemplateSchedule | None = None,
- title: str | None = None,
- locale: str = "en",
- now: datetime | None = None,
-) -> TaskSpec:
- """The TaskSpec a template turns into when the user adds it."""
- missing_inputs = [
- i.key
- for i in template.inputs
- if i.required and not (((inputs or {}).get(i.key) or "").strip() or i.default)
- ]
- if missing_inputs:
- raise ValueError(f"missing required inputs: {', '.join(missing_inputs)}")
- sched = schedule or template.schedule
- return TaskSpec(
- title=(title or "").strip() or template.name.for_locale(locale),
- trigger=schedule_to_trigger(sched, now),
- action=AgentAction(
- prompt=render_prompt(template, inputs),
- plugin_grants=template.plugin_grants,
- model_tier=template.model_tier,
- ),
- created_by="template",
- tags=(template.tag, *template.tags),
- )
-
-
-__all__ = [
- "CATEGORIES",
- "LOCALES",
- "TEMPLATE_TAG_PREFIX",
- "AutomationTemplate",
- "LocalizedText",
- "TemplateInput",
- "TemplateSchedule",
- "all_templates",
- "build_spec",
- "get_template",
- "grant_matches",
- "missing_requirements",
- "next_occurrence",
- "render_prompt",
- "schedule_label",
- "schedule_to_trigger",
-]
diff --git a/jarvis/tasks/templates/ai_news_digest.py b/jarvis/tasks/templates/ai_news_digest.py
deleted file mode 100644
index 7bbeff450a..0000000000
--- a/jarvis/tasks/templates/ai_news_digest.py
+++ /dev/null
@@ -1,91 +0,0 @@
-"""AI News Digest — model releases, research, and funding that actually matter.
-
-A daily ``search_web`` sweep over the last 24–48 hours, de-duplicated and
-stripped of hype, delivered as at most six one-liners with a "why it
-matters" and a source name.
-"""
-from __future__ import annotations
-
-from jarvis.tasks.schema import PluginGrant
-from jarvis.tasks.templates import (
- AutomationTemplate,
- LocalizedText,
- TemplateInput,
- TemplateSchedule,
-)
-
-_PROMPT = """\
-You are compiling today's AI news digest. Focus areas: {focus}.
-
-This is a written, scheduled digest — not a spoken reply. Any "answer in one \
-or two spoken sentences / never name a source" note attached to search \
-results does not apply here; the format below does.
-
-Step 1 — gather. Call the `search_web` tool at least three times with \
-`max_results` 8, each call with 2–3 different query phrasings in `queries`, \
-covering separately: (a) new model releases and open-source model launches, \
-(b) notable AI research papers or technical breakthroughs, (c) AI funding \
-rounds, acquisitions, and major company announcements. Put a recency cue in \
-every query ("this week", "today", the current month and year) so results \
-come from the last 24–48 hours. Results carry only a title, a snippet, and a \
-URL — judge recency from the text itself (an explicit date, "today", "this \
-week", a version or event that is plainly new). Discard anything that reads \
-as older than 48 hours or whose timing you cannot tell.
-
-Step 2 — filter. Merge duplicates (the same story from several outlets \
-counts once). Drop hype, opinion pieces, listicles, product marketing, minor \
-version bumps, and anything you cannot ground in a search result. Keep \
-only items a practitioner would want to know about. If fewer than six items \
-survive, report fewer — never pad.
-
-Step 3 — write. Return at most 6 items. For each item, exactly three lines:
-- Line 1: one factual sentence stating what happened (who, what, when).
-- Line 2: "Why it matters:" followed by at most 15 words.
-- Line 3: "Source:" followed by the outlet or organisation name (no URL).
-
-Separate items with a blank line. Rules: write in the configured output \
-language (translate the two labels accordingly); no headline, no preamble, \
-no closing remark; no emojis; no bold, asterisks, or markdown formatting; \
-never invent names, numbers, or dates; state only what the search results \
-support. If the searches return nothing usable, reply with one sentence \
-saying that no significant AI news was found for the period.
-"""
-
-TEMPLATE = AutomationTemplate(
- key="ai_news_digest",
- category="news",
- icon="bot",
- name=LocalizedText(
- en="AI News Digest",
- de="KI-News-Digest",
- es="Resumen de noticias de IA",
- ),
- description=LocalizedText(
- en="Model releases, research, and funding that actually matter.",
- de="Modell-Releases, Forschung und Finanzierungen, die wirklich zählen.",
- es="Lanzamientos de modelos, investigación y financiación que realmente importan.",
- ),
- schedule=TemplateSchedule(kind="daily", time="08:00"),
- prompt=_PROMPT,
- plugin_grants=(PluginGrant(plugin_id="search_web", scope="read"),),
- requires=("search_web",),
- inputs=(
- TemplateInput(
- key="focus",
- label=LocalizedText(
- en="Focus areas",
- de="Schwerpunkte",
- es="Áreas de enfoque",
- ),
- placeholder=LocalizedText(
- en="e.g. open-source models, agents, robotics",
- de="z. B. Open-Source-Modelle, Agenten, Robotik",
- es="p. ej. modelos de código abierto, agentes, robótica",
- ),
- default="model releases, open-source models, AI research, AI funding",
- required=False,
- ),
- ),
- model_tier="auto",
- tags=("ai", "news", "daily"),
-)
diff --git a/jarvis/tasks/templates/daily_planner.py b/jarvis/tasks/templates/daily_planner.py
deleted file mode 100644
index 24c9732935..0000000000
--- a/jarvis/tasks/templates/daily_planner.py
+++ /dev/null
@@ -1,103 +0,0 @@
-"""Daily Planner — a realistic plan for today: the meetings, the free focus
-blocks between them, and three quick wins."""
-from __future__ import annotations
-
-from jarvis.tasks.schema import PluginGrant
-from jarvis.tasks.templates import (
- AutomationTemplate,
- LocalizedText,
- TemplateInput,
- TemplateSchedule,
-)
-
-_PROMPT = """\
-You are compiling the user's Daily Planner for today. The user's work hours \
-are {work_hours} (local time).
-
-Procedure:
-1. Call `google_calendar` with action `list_events`, `time_min` = today at \
-00:00 and `time_max` = today at 23:59 as RFC3339 datetimes in the local time \
-zone (e.g. 2026-08-24T00:00:00+02:00), `max_results` 50. Use the current \
-date from your context; never guess a different day.
-2. From the returned events keep only those on today's date. Sort them by \
-start time. All-day events count as context, not as meetings.
-3. Compute the free blocks: the gaps between the timed events inside the \
-work hours {work_hours}. Merge gaps shorter than 30 minutes into the \
-neighbouring meeting; keep at most the 3 longest gaps.
-4. Call `gmail` with action `list_messages`, `query` "is:unread \
-newer_than:2d", `max_results` 15. Read only subjects and senders. Note \
-anything that clearly has to be handled today (a deadline, a direct \
-question, a confirmation someone is waiting for). Do not open or reply to \
-messages.
-
-Output rules:
-- Write in the configured output language. At most 12 lines in total. No \
-preamble, no closing remarks, no emojis, no markdown headings or tables.
-- Line block 1 — meetings: one line per timed meeting, "HH:MM–HH:MM Title". \
-If there are no timed events today, write exactly one line saying the \
-calendar is empty today.
-- Line block 2 — focus blocks: 1 to 3 lines, "HH:MM–HH:MM Focus: <one \
-concrete suggestion>". Base the suggestion on the mail findings or the \
-meetings (prepare for X, answer Y, finish Z); when neither gives a hint, \
-suggest deep work on the day's most important project. If the calendar is \
-empty, the whole work window is one focus block.
-- Line block 3 — quick wins: exactly 3 lines, each starting with "Quick win:" \
-followed by one small task of 15 minutes or less, taken from the unread \
-mail when possible (name the sender or subject), otherwise a sensible \
-generic one (confirm tomorrow's meetings, clear the inbox to zero, prepare \
-the next agenda).
-- Use only facts the tools returned. Never invent events, senders or \
-deadlines. If a tool call fails, say so in one line and continue with the \
-rest.
-"""
-
-TEMPLATE = AutomationTemplate(
- key="daily_planner",
- category="productivity",
- icon="calendar-check",
- name=LocalizedText(
- en="Daily Planner",
- de="Tagesplaner", # i18n-allow
- es="Planificador diario",
- ),
- description=LocalizedText(
- en=(
- "A realistic plan for today: your meetings, the free focus blocks "
- "between them, and three quick wins."
- ),
- de=( # i18n-allow
- "Ein realistischer Plan für heute: deine Termine, die freien "
- "Fokusblöcke dazwischen und drei schnelle Erfolge."
- ),
- es=(
- "Un plan realista para hoy: tus reuniones, los bloques de "
- "concentración libres entre ellas y tres logros rápidos."
- ),
- ),
- schedule=TemplateSchedule(kind="daily", time="08:30"),
- prompt=_PROMPT,
- plugin_grants=(
- PluginGrant(plugin_id="google_calendar", scope="read"),
- PluginGrant(plugin_id="gmail", scope="read"),
- ),
- requires=("google_calendar",),
- inputs=(
- TemplateInput(
- key="work_hours",
- label=LocalizedText(
- en="Work hours",
- de="Arbeitszeit", # i18n-allow
- es="Horario laboral",
- ),
- placeholder=LocalizedText(
- en="09:00-18:00",
- de="09:00-18:00",
- es="09:00-18:00",
- ),
- default="09:00-18:00",
- required=False,
- ),
- ),
- model_tier="auto",
- tags=("productivity", "calendar", "mail", "daily"),
-)
diff --git a/jarvis/tasks/templates/inbox_brief.py b/jarvis/tasks/templates/inbox_brief.py
deleted file mode 100644
index fcde71df2b..0000000000
--- a/jarvis/tasks/templates/inbox_brief.py
+++ /dev/null
@@ -1,97 +0,0 @@
-"""``inbox_brief`` — unread mail sorted by urgency, once a day.
-
-The automation only READS mail: the ``gmail`` grant stays at ``read`` scope
-because ``list_messages`` / ``get_message`` are ``safe``-tier actions
-(``jarvis/plugins/tool/gmail_rest.py``), so an unattended run never hits the
-approval gate and never sends anything.
-"""
-from __future__ import annotations
-
-from jarvis.tasks.schema import PluginGrant
-from jarvis.tasks.templates import (
- AutomationTemplate,
- LocalizedText,
- TemplateInput,
- TemplateSchedule,
-)
-
-_PROMPT = """\
-You are compiling the user's daily inbox brief. Use the `gmail` tool — you \
-never send, modify or delete anything.
-
-Steps:
-1. Call `gmail` with action `list_messages`, query \
-`is:unread newer_than:{lookback_hours}h in:inbox -category:promotions \
--category:social` and max_results 15. The result contains message ids only — \
-no subjects, no senders — so you cannot judge anything from it yet.
-2. Call `gmail` with action `get_message` for EVERY id returned (one call per \
-id). Only then do you know sender, subject, date and a short body.
-3. Skip newsletters, marketing, social notifications, automated receipts and \
-system alerts — unless one is clearly urgent (payment failed, account locked, \
-security warning, deadline today). Keep mail where a person wants something \
-from the user: a question, a request, a deadline, an invoice, a confirmation.
-4. Sort what remains into three groups, most urgent first:
- - "Needs reply today": a person is waiting for an answer, or something is due today.
- - "FYI": worth knowing, no action needed.
- - "Can wait": low priority, can be handled later.
-
-Output rules — follow them exactly:
-- Write in the configured output language.
-- No emojis, no preamble, no closing remark, no markdown headings.
-- Three short group labels (translate them), each followed by its items.
-- One line per mail: the sender's name (person or company, never the address), \
-then a comma, then ONE clause saying what they want or what it is about. \
-Mention a deadline or amount only when the mail states it.
-- Maximum 8 lines in total including the group labels; drop the least \
-important items first, and drop an empty group entirely.
-- Only report what the tool actually returned. Never invent senders, subjects \
-or deadlines. Do not describe how you worked.
-- If there is no unread or recent mail worth mentioning, reply with exactly \
-one sentence saying the inbox is clear.
-- If the `gmail` tool reports that Gmail is not connected, say so in one \
-sentence and stop.
-"""
-
-TEMPLATE = AutomationTemplate(
- key="inbox_brief",
- category="productivity",
- icon="mail",
- name=LocalizedText(
- en="Inbox Brief",
- de="Posteingang-Briefing", # i18n-allow
- es="Resumen de bandeja",
- ),
- description=LocalizedText(
- en=(
- "Unread mail sorted by urgency, with who wants what, and which "
- "ones need a reply today."
- ),
- de=( # i18n-allow
- "Ungelesene Mails nach Dringlichkeit sortiert: wer will was, und "
- "welche brauchen heute eine Antwort."
- ),
- es=(
- "Correo sin leer ordenado por urgencia: quién quiere qué y cuáles "
- "necesitan respuesta hoy."
- ),
- ),
- schedule=TemplateSchedule(kind="daily", time="09:00"),
- prompt=_PROMPT,
- plugin_grants=(PluginGrant(plugin_id="gmail", scope="read"),),
- requires=("gmail",),
- inputs=(
- TemplateInput(
- key="lookback_hours",
- label=LocalizedText(
- en="Look back (hours)",
- de="Zeitraum (Stunden)", # i18n-allow
- es="Periodo (horas)",
- ),
- placeholder=LocalizedText(en="24", de="24", es="24"),
- default="24",
- required=False,
- ),
- ),
- model_tier="auto",
- tags=("mail", "daily"),
-)
diff --git a/jarvis/tasks/templates/memory_recap.py b/jarvis/tasks/templates/memory_recap.py
deleted file mode 100644
index a51503de8b..0000000000
--- a/jarvis/tasks/templates/memory_recap.py
+++ /dev/null
@@ -1,103 +0,0 @@
-"""Memory Recap — a weekly look at what Jarvis learned about the user and
-their projects, drawn from the local wiki/memory only.
-
-This is the one catalogue template that works fully offline: every grant
-is a read-only local memory tool, no external key or network is needed.
-"""
-from __future__ import annotations
-
-from jarvis.tasks.schema import PluginGrant
-from jarvis.tasks.templates import (
- AutomationTemplate,
- LocalizedText,
- TemplateSchedule,
-)
-
-_PROMPT = """\
-You are compiling the weekly Memory Recap: what Jarvis learned about the \
-user and their projects during the last 7 days, and the open threads worth \
-picking up. Everything comes from the user's LOCAL wiki/memory — do not use \
-the web, and never fill gaps from general knowledge.
-
-Procedure:
-1. Call `wiki-list` once to see every page that actually exists (path, size, \
-title). The listing carries no modification dates. A page flagged as a \
-system file is the vault's editing contract (`schema.md`) — never treat its \
-example layout as content. Exception: a self-description page such as \
-`memory.md` ("My Memory") may be flagged too, yet it holds a "Recently \
-updated" list and live status — read it FIRST with `wiki-page-read` when it \
-exists and use its list as the shortlist of pages that changed recently.
-2. Work out today's date and the dates of the last 7 days from the \
-timestamp context you have. Run `wiki-recall` with 2-3 of those dates as \
-plain ISO strings (for example "2026-08-24") — the vault's activity log \
-records dated entries and page frontmatter carries `updated:` dates, so the \
-hits reveal which pages and events belong to this week. The log page itself \
-can be too large to read; rely on the recall snippets for it.
-3. Call `wiki-page-read` on the pages most likely to have changed this week \
-(at most 8: the "Recently updated" shortlist, then hits from step 2). On \
-each page look at frontmatter `updated:`, facts marked "(as of <date>)", \
-"Current Status" and "Open Threads" sections — those are the source for the \
-themes and the open items.
-4. Then run `wiki-recall` with 2-3 short keyword queries built from the \
-names and projects you found, plus one for open items (e.g. "open threads", \
-"blocked", "next steps"). Follow at most 3 promising hits with \
-`wiki-page-read`.
-5. Keep only facts that appear in the tool output. Never invent people, \
-projects, dates or decisions. If you cannot tell whether a note is from this \
-week, treat it as recent background rather than claiming a date.
-
-Output rules:
-- Write in the configured output language.
-- Cluster the findings into 3 to 5 themes (projects, people, decisions, \
-habits, tools). One theme per block: a heading line with the theme name, \
-then one line with what was learned (concrete names and facts from the \
-notes), then one line beginning with "Open:" that names ONE open question or \
-next step for that theme. Never leave the "Open:" line empty; when the notes \
-contain no open item, propose the most natural next step for that theme.
-- At most 12 lines in total. Short, specific sentences.
-- No preamble, no closing remarks, no emojis, no markdown tables.
-- When `wiki-list` reports that the vault is empty or does not exist, or \
-when no page carries any usable content, reply with exactly one line saying \
-plainly that the memory is empty and there is nothing to recap yet. Do not \
-add advice.
-- If a memory tool itself fails, say so in one line instead of guessing.
-"""
-
-TEMPLATE = AutomationTemplate(
- key="memory_recap",
- category="research",
- icon="brain",
- name=LocalizedText(
- en="Memory Recap",
- de="Gedächtnis-Rückblick", # i18n-allow
- es="Resumen de memoria",
- ),
- description=LocalizedText(
- en=(
- "What Jarvis learned about you and your projects this week, and "
- "the open threads worth picking up. Runs fully offline from your "
- "local memory — no external key needed."
- ),
- de=( # i18n-allow
- "Was Jarvis diese Woche über dich und deine Projekte gelernt hat, "
- "und welche offenen Fäden sich lohnen. Läuft komplett offline aus "
- "deinem lokalen Gedächtnis — kein externer Schlüssel nötig."
- ),
- es=(
- "Lo que Jarvis aprendió esta semana sobre ti y tus proyectos, y los "
- "hilos abiertos que vale la pena retomar. Funciona totalmente sin "
- "conexión desde tu memoria local — no necesita ninguna clave externa."
- ),
- ),
- schedule=TemplateSchedule(kind="weekly", weekday=6, time="18:00"),
- prompt=_PROMPT,
- plugin_grants=(
- PluginGrant(plugin_id="wiki-recall", scope="read"),
- PluginGrant(plugin_id="wiki-list", scope="read"),
- PluginGrant(plugin_id="wiki-page-read", scope="read"),
- ),
- requires=("wiki-recall",),
- inputs=(),
- model_tier="auto",
- tags=("research", "memory", "offline", "weekly"),
-)
diff --git a/jarvis/tasks/templates/morning_brief.py b/jarvis/tasks/templates/morning_brief.py
deleted file mode 100644
index a76d6f72e6..0000000000
--- a/jarvis/tasks/templates/morning_brief.py
+++ /dev/null
@@ -1,95 +0,0 @@
-"""Morning Brief — headlines, market mood and (optionally) the weather.
-
-Runs once a day, early. The prompt forces several ``search_web`` calls so the
-brief is grounded in live results rather than the brain's memory: one call
-per interest area, one for the market mood, and one weather lookup when the
-user configured a city (``search_web`` routes a query naming a location plus
-a weather word to Open-Meteo). Without a city the brief simply has no
-weather line — it must never guess where the user lives.
-"""
-from __future__ import annotations
-
-from jarvis.tasks.schema import PluginGrant
-from jarvis.tasks.templates import (
- AutomationTemplate,
- LocalizedText,
- TemplateInput,
- TemplateSchedule,
-)
-
-_PROMPT = """\
-You are compiling a morning brief for {interests}. City for the weather: "{city}".
-Today's date is in your context; every fact below MUST come from tool output.
-
-Gather the material with the `search_web` tool — at least three separate calls:
-1. One call PER interest area listed above (e.g. "top {interests} headlines today").
- Use the `queries` parameter with 2-3 phrasings in one call to get better coverage.
-2. One call for the market mood: "stock market today S&P 500 DAX Nasdaq".
-3. If, and only if, the city above is NOT empty: one call whose query is
- "weather <city> today" — the tool answers weather queries directly when the
- query names a location. If the city is empty, skip the weather entirely;
- never pick or guess a city.
-
-Then write the brief. Rules:
-- 5 to 7 bullets maximum, most important first. Each bullet is one specific,
- concrete finding (who, what, number, date) and ends with the source name in
- parentheses, e.g. "(Reuters)". The weather, if available, is one of those
- bullets: current conditions and today's high/low.
-- After the bullets, ONE sentence starting with "What matters today:" (translated
- into the output language) that connects the most important items.
-- Only report what the tool results actually say. If a search returned nothing
- useful for a topic, say so in one short bullet instead of inventing news.
-- Do NOT mention that you searched, do NOT describe your process, no preamble,
- no closing remark, no emojis, no markdown headings.
-- Write the whole brief in the configured output language.
-"""
-
-TEMPLATE = AutomationTemplate(
- key="morning_brief",
- category="news",
- icon="sun",
- name=LocalizedText(
- en="Morning Brief",
- de="Morgen-Briefing", # i18n-allow
- es="Resumen matutino",
- ),
- description=LocalizedText(
- en="Start the day with headlines, market moves, and your weather.",
- de="Starte den Tag mit Schlagzeilen, Börsenlage und deinem Wetter.", # i18n-allow
- es="Empieza el día con titulares, la bolsa y el tiempo en tu ciudad.",
- ),
- schedule=TemplateSchedule(kind="daily", time="07:30"),
- prompt=_PROMPT,
- plugin_grants=(PluginGrant(plugin_id="search_web", scope="read"),),
- requires=("search_web",),
- inputs=(
- TemplateInput(
- key="city",
- label=LocalizedText(
- en="City for the weather",
- de="Stadt für das Wetter", # i18n-allow
- es="Ciudad para el tiempo",
- ),
- placeholder=LocalizedText(
- en="e.g. Berlin (leave empty to skip weather)",
- de="z. B. Berlin (leer = kein Wetter)", # i18n-allow
- es="p. ej. Madrid (vacío = sin tiempo)",
- ),
- default="",
- required=False,
- ),
- TemplateInput(
- key="interests",
- label=LocalizedText(en="Topics", de="Themen", es="Temas"), # i18n-allow
- placeholder=LocalizedText(
- en="world news, technology, business",
- de="Weltnachrichten, Technik, Wirtschaft", # i18n-allow
- es="noticias del mundo, tecnología, negocios",
- ),
- default="world news, technology, business",
- required=False,
- ),
- ),
- model_tier="auto",
- tags=("news", "weather", "markets"),
-)
diff --git a/jarvis/tasks/templates/repo_pulse.py b/jarvis/tasks/templates/repo_pulse.py
deleted file mode 100644
index 2f2442e198..0000000000
--- a/jarvis/tasks/templates/repo_pulse.py
+++ /dev/null
@@ -1,96 +0,0 @@
-"""Repo Pulse — a daily developer briefing for one GitHub repository:
-yesterday's commits, the open pull requests waiting on the user, and the
-issues opened since the last run."""
-from __future__ import annotations
-
-from jarvis.tasks.schema import PluginGrant
-from jarvis.tasks.templates import (
- AutomationTemplate,
- LocalizedText,
- TemplateInput,
- TemplateSchedule,
-)
-
-_PROMPT = """\
-You are compiling the daily Repo Pulse for the GitHub repository `{repo}` \
-(format owner/name; split it at the slash into the `owner` and `repo` tool \
-arguments).
-
-Procedure — use ONLY the GitHub tools, never memory or guesses. Compute the \
-cutoff as now minus 24 hours in ISO 8601 (UTC) and pass it as `since`:
-1. Commits: `github/list_commits` with `since` = cutoff, `perPage` 30, \
-`fields` ["sha", "commit", "author"]. Note the count, the authors and the \
-first line of each message.
-2. Pull requests: `github/list_pull_requests` with `state` "open", `sort` \
-"updated", `direction` "desc", `perPage` 20, `fields` ["number", "title", \
-"draft", "user", "requested_reviewers", "mergeable_state", "created_at"]. \
-Flag a PR when it has requested reviewers, is a draft, or has \
-`mergeable_state` "dirty" or "blocked". For at most 3 flagged PRs you may \
-call `github/pull_request_read` with `method` "get_check_runs" to name the \
-failing checks.
-3. Issues: `github/list_issues` with `state` "OPEN", `since` = cutoff, \
-`orderBy` "CREATED_AT", `direction` "DESC", `perPage` 20, `fields` \
-["number", "title", "user", "labels", "created_at"]. Keep only issues whose \
-`created_at` is after the cutoff.
-
-Output rules:
-- Write in the configured output language.
-- Exactly three short sections in this order: commits, pull requests, \
-issues. Each starts with a one-line heading, followed by at most 3 \
-one-line bullets naming the concrete item (short SHA or #number, message or \
-title, author) — most important first.
-- When a section has nothing in the window, write exactly one line saying \
-so under its heading — never pad with older activity.
-- At most 12 lines in total. No preamble, no closing remarks, no emojis, no \
-markdown tables.
-- Only state facts that appear in the tool results. If a tool call fails, \
-say so in one line for that section instead of guessing.
-"""
-
-TEMPLATE = AutomationTemplate(
- key="repo_pulse",
- category="developer",
- icon="git-branch",
- name=LocalizedText(
- en="Repo Pulse",
- de="Repo-Puls", # i18n-allow
- es="Pulso del repositorio",
- ),
- description=LocalizedText(
- en=(
- "Yesterday's commits, open pull requests waiting on you, and new "
- "issues for one repository."
- ),
- de=( # i18n-allow
- "Die Commits von gestern, offene Pull Requests, die auf dich "
- "warten, und neue Issues für ein Repository."
- ),
- es=(
- "Los commits de ayer, los pull requests abiertos que te esperan y "
- "los issues nuevos de un repositorio."
- ),
- ),
- schedule=TemplateSchedule(kind="daily", time="09:00"),
- prompt=_PROMPT,
- # A prefix grant: covers every bridged ``github/<tool>``.
- plugin_grants=(PluginGrant(plugin_id="github", scope="read"),),
- requires=("github",),
- inputs=(
- TemplateInput(
- key="repo",
- label=LocalizedText(
- en="Repository",
- de="Repository", # i18n-allow
- es="Repositorio",
- ),
- placeholder=LocalizedText(
- en="owner/name",
- de="owner/name", # i18n-allow
- es="owner/name",
- ),
- required=True,
- ),
- ),
- model_tier="auto",
- tags=("developer", "github", "daily"),
-)
diff --git a/jarvis/tasks/templates/stock_tracker.py b/jarvis/tasks/templates/stock_tracker.py
deleted file mode 100644
index 88524d49ca..0000000000
--- a/jarvis/tasks/templates/stock_tracker.py
+++ /dev/null
@@ -1,99 +0,0 @@
-"""Daily Stock Tracker — prices, sentiment, and catalysts for a watchlist.
-
-Two ``search_web`` calls per ticker (one for the latest price and day move,
-one for news), then one line per ticker with the approximate last price as
-the source reported it, the day move, and one catalyst with its source
-name. Numbers are never invented: a ticker whose price the searches did not
-surface is reported as "price not found".
-"""
-from __future__ import annotations
-
-from jarvis.tasks.schema import PluginGrant
-from jarvis.tasks.templates import (
- AutomationTemplate,
- LocalizedText,
- TemplateInput,
- TemplateSchedule,
-)
-
-_PROMPT = """\
-You are compiling today's stock tracker for this watchlist: {watchlist}.
-
-Step 1 — gather, per ticker. For EACH ticker in the watchlist call the \
-`search_web` tool exactly twice, with `max_results` 8. Call A (price): \
-`query` "<TICKER> stock price today" plus two variants in `queries` such as \
-"<TICKER> share price change today" and "<TICKER> stock quote <current \
-date>". Call B (news): `query` "<TICKER> stock news today" plus variants \
-such as "<TICKER> earnings analyst news this week" and "why is <TICKER> \
-stock up or down today". Put a recency cue in every query ("today", the \
-current date). Do not skip a ticker and do not stop after the first ticker; \
-two tickers means four calls.
-
-Step 2 — extract. The tool returns RAW web hits (title, snippet, url) — \
-read figures only from that text. For each ticker take the most recent price \
-figure and the day's percentage or point move exactly as a snippet or title \
-states them, and name the outlet from the hit's title or domain. Prefer the \
-hit with the newest date cue; ignore hits with no date or older than two \
-trading days. If no hit states a concrete price, the price is unknown — \
-never estimate it from memory or from an older figure. Pick ONE catalyst: \
-the single most relevant news item explaining the move or likely to move \
-the stock next (earnings, guidance, product, regulation, analyst action, \
-macro event).
-
-Step 3 — write. Return exactly one line per ticker, in watchlist order, in \
-this shape:
-<TICKER> — approx. <price> <currency>, <day move> (per <source name>) — \
-<one catalyst sentence> (<source name>)
-If the price could not be established, write "price not found" in place of \
-the price and move, and still give the catalyst if one was found. If no \
-news was found either, say "no notable news found" in place of the catalyst.
-
-Then end with ONE sentence describing the overall market mood for the day \
-based only on what the searches returned.
-
-Rules: write in the configured output language (translate the fixed phrases \
-accordingly, but keep ticker symbols as they are); no headline, no preamble, \
-no closing remark; no emojis; no bold, asterisks, or markdown formatting; \
-never invent or round-trip numbers from memory — every figure must come from \
-a search result; this is information only, so give no buy, sell, or hold \
-advice and no predictions of your own.
-"""
-
-TEMPLATE = AutomationTemplate(
- key="stock_tracker",
- category="finance",
- icon="dollar-sign",
- name=LocalizedText(
- en="Daily Stock Tracker",
- de="Täglicher Aktien-Tracker",
- es="Seguimiento diario de acciones",
- ),
- description=LocalizedText(
- en="Prices, sentiment, and catalysts for your watchlist every day.",
- de="Kurse, Stimmung und Kurstreiber für deine Watchlist, jeden Tag.",
- es="Precios, sentimiento y catalizadores de tu lista de seguimiento cada día.",
- ),
- schedule=TemplateSchedule(kind="daily", time="14:00"),
- prompt=_PROMPT,
- plugin_grants=(PluginGrant(plugin_id="search_web", scope="read"),),
- requires=("search_web",),
- inputs=(
- TemplateInput(
- key="watchlist",
- label=LocalizedText(
- en="Watchlist",
- de="Watchlist",
- es="Lista de seguimiento",
- ),
- placeholder=LocalizedText(
- en="NVDA, AAPL, TSLA",
- de="NVDA, AAPL, TSLA",
- es="NVDA, AAPL, TSLA",
- ),
- default="",
- required=True,
- ),
- ),
- model_tier="auto",
- tags=("stocks", "finance", "daily"),
-)
diff --git a/jarvis/tasks/templates/task_extractor.py b/jarvis/tasks/templates/task_extractor.py
deleted file mode 100644
index 356e7cad00..0000000000
--- a/jarvis/tasks/templates/task_extractor.py
+++ /dev/null
@@ -1,117 +0,0 @@
-"""Task Extractor — the action items hiding in today's mail, remembered.
-
-Runs once a day, late afternoon. The prompt grounds everything in the Gmail
-tool: one ``list_messages`` search over the lookback window (newsletters and
-notifications excluded by query), then ``get_message`` for each hit, because
-``list_messages`` only returns ids. Every action item must be traceable to a
-mail the tool actually returned. The list is then persisted through
-``wiki-ingest`` (a ``write`` grant, so the unattended run never blocks on an
-approval prompt) as one note headed ``Action items <date>``, and the final
-answer IS the list — short, in the configured output language, or the single
-sentence "no action items today" when the mail contained none.
-
-Why ``wiki-ingest`` and not ``remember``: ``remember`` is registered as an
-entry point but is deliberately NOT a router-tier tool (ADR-0011), so the
-brain's live tool dict never contains it and a task grant for it is silently
-dropped by ``BrainManager._select_task_tools``. ``wiki-ingest`` IS live,
-takes free text, and lands in the long-term wiki the brain recalls from.
-Storage is a soft requirement — ``requires`` names only ``gmail``; if the
-wiki tool is missing the prompt says so instead of pretending.
-"""
-from __future__ import annotations
-
-from jarvis.tasks.schema import PluginGrant
-from jarvis.tasks.templates import (
- AutomationTemplate,
- LocalizedText,
- TemplateInput,
- TemplateSchedule,
-)
-
-_PROMPT = """\
-You are extracting the concrete action items from the user's mail of the last \
-{lookback_hours} hours. Today's date is in your context; every item below MUST \
-come from a message the `gmail` tool actually returned — never invent a task, \
-a sender or a deadline.
-
-Step 1 — find the mail. Call `gmail` with action "list_messages", max_results 25 \
-and this query (convert the hours into whole days, rounding up: 24 hours = 1d, \
-48 hours = 2d):
- in:inbox newer_than:<N>d -category:promotions -category:social -category:forums \
--unsubscribe -"no-reply"
-Step 2 — read it. `list_messages` returns only ids: call `gmail` with action \
-"get_message" for each id (at most 15 messages, newest first). Read the sender, \
-subject, date and body.
-Step 3 — extract. An action item is something a real person asks the user to do, \
-decide, send, review, pay, confirm or answer, or an obligation with a date \
-(invoice due, appointment to confirm, form to return). Skip newsletters, \
-marketing, automated notifications, receipts and "FYI" mail with nothing to do. \
-For each item capture: who asked (name, no email address), what exactly, and by \
-when (the stated date or "no deadline given"). Merge duplicates from the same \
-thread. Keep at most 8 items, most urgent first.
-Step 4 — store. If at least one item exists, call `wiki-ingest` ONCE with \
-`source` "automation:task_extractor" and `text` being one self-contained \
-block of plain prose of the form
- Action items <today's date YYYY-MM-DD>: 1) <who> — <what> — <by when>; 2) ...
-so the list survives this turn as a wiki note. Do not call it when there are \
-no items. If the `wiki-ingest` tool is not available or returns an error, do \
-not pretend the list was stored — say so in one short final sentence.
-Step 5 — answer. Reply with the numbered list only, one line per item in the \
-form "<who>: <what> (by <when>)". If there are no action items, reply with the \
-single sentence "no action items today" (translated into the output language).
-
-Rules: no preamble, no closing remark, no emojis, no markdown headings, do not \
-describe your process or the tools. If the mail tool returned an error, say that \
-in one sentence instead of inventing a list. Write everything in the configured \
-output language.
-"""
-
-TEMPLATE = AutomationTemplate(
- key="task_extractor",
- category="productivity",
- icon="list-checks",
- name=LocalizedText(
- en="Task Extractor",
- de="Aufgaben-Extraktor", # i18n-allow
- es="Extractor de tareas",
- ),
- description=LocalizedText(
- en="Pulls the action items out of today's mail and remembers them, so nothing slips.",
- de=( # i18n-allow
- "Zieht die Aufgaben aus den Mails von heute und merkt sie sich, "
- "damit nichts durchrutscht."
- ),
- es=(
- "Saca las tareas pendientes del correo de hoy y las recuerda "
- "para que nada se escape."
- ),
- ),
- schedule=TemplateSchedule(kind="daily", time="17:00"),
- prompt=_PROMPT,
- plugin_grants=(
- PluginGrant(plugin_id="gmail", scope="read"),
- # write: the unattended run must be allowed to store the list
- # without a human answering an approval prompt.
- PluginGrant(plugin_id="wiki-ingest", scope="write"),
- ),
- requires=("gmail",),
- inputs=(
- TemplateInput(
- key="lookback_hours",
- label=LocalizedText(
- en="Lookback window (hours)",
- de="Zeitfenster (Stunden)", # i18n-allow
- es="Ventana de tiempo (horas)",
- ),
- placeholder=LocalizedText(
- en="24",
- de="24",
- es="24",
- ),
- default="24",
- required=False,
- ),
- ),
- model_tier="auto",
- tags=("mail", "tasks", "memory"),
-)
diff --git a/jarvis/tasks/templates/topic_watch.py b/jarvis/tasks/templates/topic_watch.py
deleted file mode 100644
index b75cfd4376..0000000000
--- a/jarvis/tasks/templates/topic_watch.py
+++ /dev/null
@@ -1,99 +0,0 @@
-"""Topic Watch — a weekly digest of what changed around the companies,
-products or topics the user follows."""
-from __future__ import annotations
-
-from jarvis.tasks.schema import PluginGrant
-from jarvis.tasks.templates import (
- AutomationTemplate,
- LocalizedText,
- TemplateInput,
- TemplateSchedule,
-)
-
-_PROMPT = """\
-You are compiling a weekly Topic Watch digest. The user follows these topics \
-(companies, products or themes): {topics}
-
-Procedure:
-1. Split the list into individual topics.
-2. For EVERY topic make at least one `search_web` call. Use the `queries` \
-argument with up to 3 phrasings in the same call, each scoped to the past \
-week (e.g. "<topic> news this week", "<topic> launch OR pricing OR hires past \
-7 days", "<topic> controversy OR lawsuit OR funding"). Set `max_results` to 8. \
-Make a second call with different wording when the first returns nothing \
-relevant.
-3. The tool has no date filter: judge recency from the date shown in each \
-hit or its snippet. Keep only findings dated within the last seven days that \
-actually come from the search results. Drop undated items whose recency you \
-cannot tell. Never invent, extrapolate or recall events from memory.
-4. Ignore the tool's `answer_instruction` — it is written for short spoken \
-answers. This run produces a WRITTEN digest, so source names are required and \
-several bullets are expected.
-
-Output rules:
-- Write in the configured output language.
-- Group findings per topic. One heading line per topic (the topic name), \
-followed by at most 3 bullets. Each bullet is one or two sentences that name \
-the concrete change and end with the source name in parentheses, e.g. \
-"(Reuters)".
-- Lead with the most consequential item per topic.
-- When the search returned nothing notable for a topic, write exactly one \
-line under its heading saying that nothing notable happened this week — never \
-pad with background information, older news or generic descriptions of the \
-company.
-- No preamble, no closing remarks, no emojis, no markdown tables.
-- If `search_web` reports `status` "unavailable" or times out, write one line \
-under that topic saying the web search could not be reached — never present \
-that as "nothing notable" and never guess.
-"""
-
-TEMPLATE = AutomationTemplate(
- key="topic_watch",
- category="news",
- icon="radar",
- name=LocalizedText(
- en="Topic Watch",
- de="Themen-Radar", # i18n-allow
- es="Radar de temas",
- ),
- description=LocalizedText(
- en=(
- "Weekly digest of what changed around the companies, products or "
- "topics you follow (launches, pricing, hires, controversies)."
- ),
- de=( # i18n-allow
- "Wöchentliche Zusammenfassung, was sich bei den Firmen, Produkten "
- "oder Themen getan hat, die du verfolgst (Launches, Preise, "
- "Personalien, Kontroversen)."
- ),
- es=(
- "Resumen semanal de lo que cambió en las empresas, productos o "
- "temas que sigues (lanzamientos, precios, fichajes, polémicas)."
- ),
- ),
- schedule=TemplateSchedule(kind="weekly", weekday=0, time="09:00"),
- prompt=_PROMPT,
- plugin_grants=(PluginGrant(plugin_id="search_web", scope="read"),),
- requires=("search_web",),
- inputs=(
- TemplateInput(
- key="topics",
- label=LocalizedText(
- en="Topics to follow",
- de="Themen, die du verfolgst", # i18n-allow
- es="Temas que sigues",
- ),
- placeholder=LocalizedText(
- en="OpenAI, Anthropic, xAI — the competitors or topics you follow",
- de=( # i18n-allow
- "OpenAI, Anthropic, xAI — die Konkurrenten oder Themen, "
- "die du verfolgst"
- ),
- es="OpenAI, Anthropic, xAI — los competidores o temas que sigues",
- ),
- required=True,
- ),
- ),
- model_tier="auto",
- tags=("news", "web", "weekly"),
-)
diff --git a/jarvis/tasks/templates/weekly_review.py b/jarvis/tasks/templates/weekly_review.py
deleted file mode 100644
index 9517b6f62c..0000000000
--- a/jarvis/tasks/templates/weekly_review.py
+++ /dev/null
@@ -1,95 +0,0 @@
-"""Weekly Review — wrap the week: what got done, what is still open, and the
-three priorities for next week.
-
-Runs once a week, Friday afternoon. The review is grounded in three sources
-the automation may or may not have on a given install: this week's calendar
-events (``google_calendar``), the notable mail threads (``gmail``) and the
-memory notes of the past seven days (``wiki-recall``). None of them is a hard
-requirement — with no calendar or mailbox connected the review is written
-from memory alone, and the prompt tells the brain to use whatever tools are
-available and to state which sources it actually used, so a thin review is
-never mistaken for a full one.
-"""
-from __future__ import annotations
-
-from jarvis.tasks.schema import PluginGrant
-from jarvis.tasks.templates import (
- AutomationTemplate,
- LocalizedText,
- TemplateSchedule,
-)
-
-_PROMPT = """\
-You are writing the user's Weekly Review. Today's date is in your context; \
-"this week" means the last 7 days up to and including today.
-
-Gather the material from whichever of these tools you have — use every one \
-that is available, and if a tool is missing or fails, carry on without it:
-1. `google_calendar` — call it with action "list_events", time_min = 7 days \
-ago at 00:00 and time_max = today at 23:59 (RFC3339), max_results 50. \
-These events are what happened this week.
-2. `gmail` — call it with action "list_messages" and query "newer_than:7d", \
-max_results 20. Keep only the threads that carry a decision, a request \
-addressed to the user, a deadline or an open reply; ignore newsletters, \
-notifications and promotions.
-3. `wiki-recall` — run two or three short keyword searches for this week's \
-projects, decisions and plans (e.g. the names of the projects and people \
-that appear in the calendar and mail results, plus generic words like \
-"plan", "decision", "todo"). Treat the hits as the user's own memory notes.
-
-Then write the review. Rules:
-- Exactly three sections with these headings, translated into the output \
-language: "Done", "Open", "Next week (3 priorities)". Each line under a \
-heading is one bullet.
-- "Done": concrete things that happened or were completed this week (meetings \
-held, decisions made, tasks closed) — who, what, when.
-- "Open": items still waiting: unanswered mail, unresolved threads, notes that \
-name a pending task, events that need follow-up.
-- "Next week (3 priorities)": exactly three bullets, the most consequential \
-things to do next week, each derived from an Open item or an upcoming event.
-- Every fact MUST come from tool output. Never invent events, mails or notes; \
-never fill a section with generic advice. If a section has nothing, write \
-one bullet saying so.
-- The whole review is at most 15 lines including the headings.
-- End with ONE final line, translated into the output language, that names \
-the sources actually used, e.g. "Sources: calendar, mail, memory" — list \
-only the tools that returned data, and name the ones that were unavailable.
-- No preamble, no closing remark, no emojis, no markdown tables. Do not \
-describe your process.
-- Write the whole review in the configured output language.
-"""
-
-TEMPLATE = AutomationTemplate(
- key="weekly_review",
- category="productivity",
- icon="clipboard-list",
- name=LocalizedText(
- en="Weekly Review",
- de="Wochenrückblick", # i18n-allow
- es="Revisión semanal",
- ),
- description=LocalizedText(
- en="Wrap the week: what you did, what's still open, and next week's three priorities.",
- de=( # i18n-allow
- "Schließe die Woche ab: was du geschafft hast, was offen ist "
- "und die drei Prioritäten für nächste Woche."
- ),
- es=(
- "Cierra la semana: lo que hiciste, lo que sigue abierto "
- "y las tres prioridades de la próxima."
- ),
- ),
- schedule=TemplateSchedule(kind="weekly", weekday=4, time="16:00"),
- prompt=_PROMPT,
- plugin_grants=(
- PluginGrant(plugin_id="google_calendar", scope="read"),
- PluginGrant(plugin_id="gmail", scope="read"),
- PluginGrant(plugin_id="wiki-recall", scope="read"),
- ),
- # Deliberately empty: the review degrades to memory-only without a
- # calendar or mailbox, so nothing blocks the card on a bare install.
- requires=(),
- inputs=(),
- model_tier="auto",
- tags=("review", "planning", "calendar", "mail", "memory"),
-)
diff --git a/jarvis/ui/web/frontend/src/components/icons/sectionIcons.tsx b/jarvis/ui/web/frontend/src/components/icons/sectionIcons.tsx
index 8a4c444e1c..8a7d03d78f 100644
--- a/jarvis/ui/web/frontend/src/components/icons/sectionIcons.tsx
+++ b/jarvis/ui/web/frontend/src/components/icons/sectionIcons.tsx
@@ -170,16 +170,6 @@ export const MarketplaceIcon = defineIcon(
</>,
);
-/** A clock inside a turning arrow: work that runs again on a schedule. */
-export const AutomationIcon = defineIcon(
- "AutomationIcon",
- <>
- <path d="M20 12a8 8 0 1 1-2.35-5.65" />
- <path d="M20 4.5v3.75h-3.75" />
- <path d="M12 8v4l2.5 1.75" />
- </>,
-);
-
/** A card on top of a card: the things a run produced. */
export const ArtifactsIcon = defineIcon(
"ArtifactsIcon",
diff --git a/jarvis/ui/web/frontend/src/components/layout/DockRail.test.tsx b/jarvis/ui/web/frontend/src/components/layout/DockRail.test.tsx
index 14aa19b856..e77876bfe0 100644
--- a/jarvis/ui/web/frontend/src/components/layout/DockRail.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/layout/DockRail.test.tsx
@@ -73,7 +73,7 @@ describe("DockRail", () => {
test("keeps the active control on a lit fill", () => {
renderRail();
expect(screen.getByTestId("nav-row-chats").classList).toContain("jarvis-nav-active");
- expect(screen.getByTestId("nav-row-tasks").classList).not.toContain(
+ expect(screen.getByTestId("nav-row-board").classList).not.toContain(
"jarvis-nav-active",
);
});
@@ -148,9 +148,9 @@ describe("DockRail", () => {
test("picking an icon jumps to its section", () => {
renderRail();
act(() => {
- fireEvent.click(screen.getByTestId("nav-row-tasks"));
+ fireEvent.click(screen.getByTestId("nav-row-board"));
});
- expect(useEventStore.getState().activeSection).toBe("tasks");
+ expect(useEventStore.getState().activeSection).toBe("board");
});
test("keyboard focus names the icon too, so the rail is not a row of blank glyphs", () => {
diff --git a/jarvis/ui/web/frontend/src/components/layout/MainView.tsx b/jarvis/ui/web/frontend/src/components/layout/MainView.tsx
index 4db2654f87..0e585bc6f7 100644
--- a/jarvis/ui/web/frontend/src/components/layout/MainView.tsx
+++ b/jarvis/ui/web/frontend/src/components/layout/MainView.tsx
@@ -118,9 +118,6 @@ const PluginsDialog = lazyPropView<{ onClose: () => void; area: PluginArea; onAr
const AgenticIdeView = lazyPropView<AgenticIdeViewProps>(() =>
import("@/views/AgenticIdeView").then((m) => ({ default: m.AgenticIdeView })),
);
-const AutomationsView = lazyView(() =>
- import("@/views/AutomationsView").then((m) => ({ default: m.AutomationsView })),
-);
const SessionsView = lazyView(() =>
import("@/views/SessionsView").then((m) => ({ default: m.SessionsView })),
);
@@ -495,8 +492,6 @@ function SwitchOnActiveSection({ active }: { active: string }) {
return <ClisHubView />;
case "docs":
return <DocsView />;
- case "tasks":
- return <AutomationsView />;
case "sessions":
return <SessionsView />;
case "run_inspector":
diff --git a/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx b/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx
index 226d1710d9..f9ba7fee0e 100644
--- a/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx
+++ b/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx
@@ -323,7 +323,7 @@ export function Sidebar({
const allItems = NAV_GROUPS.flat();
const findItem = (id: string) => allItems.find((item) => item.id === id)!;
- const toolIds = ["memory", "board", "docs", "sessions", "run_inspector", "clis", "tasks"];
+ const toolIds = ["memory", "board", "docs", "sessions", "run_inspector", "clis"];
const toolItems = toolIds.map(findItem);
// Artifacts ("visualization") sits directly in the main list where the
// retired "Jarvis Tools" folder used to be — it was the only entry hiding
@@ -553,7 +553,7 @@ export function Sidebar({
<ChevronDown aria-hidden strokeWidth={1.75} className={cn("h-[18px] w-[18px] shrink-0 transition-transform", moreOpen && "rotate-180")} />
{!railed && <span>{t(moreOpen ? "sidebar.show_less" : "sidebar.more")}</span>}
</button>
- {moreOpen && <ul id="sidebar-more" className="space-y-1">{moreItems.map((item) => item.id === "tasks" ? renderRow({ ...item, labelKey: "sidebar.scheduled" }) : renderRow(item))}</ul>}
+ {moreOpen && <ul id="sidebar-more" className="space-y-1">{moreItems.map((item) => renderRow(item))}</ul>}
</nav>}
{!railed && (onIdeSection
? <IdeProjectTree />
diff --git a/jarvis/ui/web/frontend/src/components/layout/navGroups.ts b/jarvis/ui/web/frontend/src/components/layout/navGroups.ts
index 56dc7117cd..0765707d2c 100644
--- a/jarvis/ui/web/frontend/src/components/layout/navGroups.ts
+++ b/jarvis/ui/web/frontend/src/components/layout/navGroups.ts
@@ -14,7 +14,6 @@ import { OllamaIcon } from "@/components/icons/OllamaIcon";
import {
AgentsIcon,
ArtifactsIcon,
- AutomationIcon,
BoardIcon,
CaptureIcon,
ChatIcon,
@@ -143,9 +142,6 @@ export const NAV_GROUPS: NavItem[][] = [
icon: MarketplaceIcon,
fallbackLabel: "Marketplace",
},
- // Automations — the recurring agent tasks and their catalogue. The id stays
- // "tasks" (navigate parity, deep links); only the label and glyph changed.
- { id: "tasks", labelKey: "nav.tasks", icon: AutomationIcon, fallbackLabel: "Automations" },
// Artifacts — everything a run produced. The id stays "visualization"
// because it crosses the navigate parity test, the detachable-view
// registry and deep links.
diff --git a/jarvis/ui/web/frontend/src/components/society/card/AgentRoutineDetail.test.tsx b/jarvis/ui/web/frontend/src/components/society/card/AgentRoutineDetail.test.tsx
index ec219077dd..f0e2d1ce64 100644
--- a/jarvis/ui/web/frontend/src/components/society/card/AgentRoutineDetail.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/card/AgentRoutineDetail.test.tsx
@@ -3,7 +3,7 @@ import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/re
import { afterEach, expect, test, vi } from "vitest";
import { AgentRoutineDetail, routineRuns } from "./AgentRoutineDetail";
import type { LiveRoutine } from "../cardData";
-import type { TaskDetail, TaskStep } from "@/views/automations/automationsModel";
+import type { TaskDetail, TaskStep } from "@/lib/tasksApi";
import en from "@/i18n/locales/society/en.json";
import { RoutineChatHost } from "../chat/RoutineChatHost";
import { useRoutineNavigation } from "../chat/routineNavigation";
diff --git a/jarvis/ui/web/frontend/src/components/society/card/AgentRoutineDetail.tsx b/jarvis/ui/web/frontend/src/components/society/card/AgentRoutineDetail.tsx
index e079d55c2a..c49febb4f7 100644
--- a/jarvis/ui/web/frontend/src/components/society/card/AgentRoutineDetail.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/card/AgentRoutineDetail.tsx
@@ -4,9 +4,9 @@ import { useQueries, useQueryClient } from "@tanstack/react-query";
import { ArrowLeft, Check, Clock, Plus, X } from "lucide-react";
import { useT } from "@/i18n";
import { Switch } from "@/components/ui/switch";
-import { cancelAndDeleteTask, cancelTask, fetchTask, runTaskNow, setTaskEnabled } from "@/hooks/useAutomations";
+import { cancelAndDeleteTask, cancelTask, fetchTask, runTaskNow, setTaskEnabled } from "@/lib/tasksApi";
import { describeTrigger, displayRoutineTitle, type LiveRoutine } from "../cardData";
-import type { TaskDetail, TaskStep } from "@/views/automations/automationsModel";
+import type { TaskDetail, TaskStep } from "@/lib/tasksApi";
import { TriggerBuilder } from "./TriggerBuilder";
import { WebhookConnection } from "./WebhookConnection";
import { SourceControls } from "./SourceControls";
@@ -192,7 +192,7 @@ export function AgentRoutineDetail({ agentId, routine, onClose }: {
<button className="flex w-full items-start gap-2 rounded text-left text-[12px] disabled:opacity-70" disabled={pending || !editable || Boolean(draft) || !detail || !timeKinds.includes(detail.trigger_type)} onClick={() => { setEditing({ ...member, trigger: detail?.trigger }); setSchedule(null); }}>
<Clock size={14} className="mt-0.5 shrink-0" /><span>{describeTrigger(detail?.trigger ?? member.trigger, t)}</span>
</button>
- {detail?.due_at_ns && detail.state === "scheduled" ? <p className="pl-5 text-[11px] text-muted-foreground">{t("automations_view.next_run")}: {new Date(detail.due_at_ns / 1e6).toLocaleString(undefined, { timeZoneName: "short" })}</p> : null}
+ {detail?.due_at_ns && detail.state === "scheduled" ? <p className="pl-5 text-[11px] text-muted-foreground">{t("society.card.next_run")}: {new Date(detail.due_at_ns / 1e6).toLocaleString(undefined, { timeZoneName: "short" })}</p> : null}
{detail && renderConnection(detail)}
{index > 0 && <button className="pl-5 text-[11px] text-muted-foreground" disabled={pending || !editable || Boolean(draft)} onClick={() => void act(async () => { await cancelTask(member.id); })}>{label("remove_schedule")}</button>}
</div>;
diff --git a/jarvis/ui/web/frontend/src/components/society/card/AgentRoutineDetailSeat.test.tsx b/jarvis/ui/web/frontend/src/components/society/card/AgentRoutineDetailSeat.test.tsx
index c6fd7c63ea..e3552f1b92 100644
--- a/jarvis/ui/web/frontend/src/components/society/card/AgentRoutineDetailSeat.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/card/AgentRoutineDetailSeat.test.tsx
@@ -2,7 +2,7 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, expect, test, vi } from "vitest";
import { AgentRoutineDetail } from "./AgentRoutineDetail";
-import type { TaskDetail } from "@/views/automations/automationsModel";
+import type { TaskDetail } from "@/lib/tasksApi";
import en from "@/i18n/locales/society/en.json";
vi.mock("@/components/agentchat/AgentTimeline", () => ({ AgentTimeline: () => null }));
diff --git a/jarvis/ui/web/frontend/src/components/society/card/AgentRoutinesList.tsx b/jarvis/ui/web/frontend/src/components/society/card/AgentRoutinesList.tsx
index b74f2824a7..56633624f7 100644
--- a/jarvis/ui/web/frontend/src/components/society/card/AgentRoutinesList.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/card/AgentRoutinesList.tsx
@@ -57,7 +57,7 @@ export function AgentRoutinesList({ agentId, sampleRoutines, variant = "rail", c
<span className="min-w-0 flex-1">
<span className="block truncate text-[13px] font-medium text-foreground">{displayRoutineTitle(routine.title)}</span>
<span className="block break-words text-[11px] leading-snug text-muted-foreground">{routineScheduleLine(routine, t)}{routine.state === "paused" ? ` · ${t("tasks_view.state.paused")}` : ""}</span>
- {routine.dueMs && active ? <span className="block text-[11px] text-muted-foreground">{t("automations_view.next_run")}: {new Date(routine.dueMs).toLocaleString(undefined, { timeZoneName: "short" })}</span> : null}
+ {routine.dueMs && active ? <span className="block text-[11px] text-muted-foreground">{t("society.card.next_run")}: {new Date(routine.dueMs).toLocaleString(undefined, { timeZoneName: "short" })}</span> : null}
</span>
</button>
{trigger?.type === "webhook" && <div className="pl-6"><WebhookConnection key={routine.id} taskId={routine.id} /></div>}
diff --git a/jarvis/ui/web/frontend/src/hooks/useAutomations.ts b/jarvis/ui/web/frontend/src/hooks/useAutomations.ts
deleted file mode 100644
index 0f8c2ba81d..0000000000
--- a/jarvis/ui/web/frontend/src/hooks/useAutomations.ts
+++ /dev/null
@@ -1,203 +0,0 @@
-/**
- * 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/hooks/useSectionHistory.test.ts b/jarvis/ui/web/frontend/src/hooks/useSectionHistory.test.ts
index c03531b819..b0b0088a6e 100644
--- a/jarvis/ui/web/frontend/src/hooks/useSectionHistory.test.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useSectionHistory.test.ts
@@ -8,7 +8,7 @@ import {
useSectionNavHistory,
} from "./useSectionHistory";
-function visit(section: "chats" | "agents" | "dictation" | "tasks"): void {
+function visit(section: "chats" | "agents" | "dictation" | "board"): void {
act(() => useEventStore.getState().setActiveSection(section));
}
@@ -75,7 +75,7 @@ describe("useSectionHistory", () => {
});
expect(result.current.canGoForward).toBe(true);
- visit("tasks");
+ visit("board");
expect(result.current.canGoForward).toBe(false);
expect(result.current.canGoBack).toBe(true);
});
@@ -84,7 +84,7 @@ describe("useSectionHistory", () => {
const { result } = renderHook(() => useSectionHistory());
visit("agents");
visit("dictation");
- visit("tasks");
+ visit("board");
act(() => {
result.current.goBack();
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index d6a9faecd7..d6868dee62 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -139,7 +139,6 @@
"plugins": "Plugins",
"docs": "Docs",
"mcps": "MCPs",
- "tasks": "Automatisierungen",
"sessions": "Transkription",
"run_inspector": "Run Inspector",
"costs": "Kosten",
@@ -549,7 +548,6 @@
"unpin_chat": "Chat lösen",
"jarvis_tools": "Jarvis Tools",
- "scheduled": "Geplant",
"more": "Mehr",
"instance_dev_hint": "Dev-Instanz — eine zweite, frei neustartbare Kopie der App mit eigenen Daten, Ports und eigenem Icon. Die normale App läuft daneben weiter.",
@@ -1168,128 +1166,6 @@
"in_prefix": "in",
"due_now": "fällig"
},
- "automations_view": {
- "title": "Automatisierungen",
- "subtitle": "Alles, was Jarvis von selbst tut — wiederkehrende Automatisierungen, einmalige Zeitpläne und ein Katalog fertiger Vorlagen.",
- "new_button": "Neue Automatisierung",
- "refresh": "Aktualisieren",
- "tab_automations": "Automatisierungen",
- "tab_schedules": "Zeitpläne",
- "tab_runs": "Läufe",
- "tab_catalogue": "Katalog",
- "tabs_label": "Bereich",
- "browse_catalogue": "Katalog ansehen",
- "col_automation": "Automatisierung",
- "col_schedule": "Termin",
- "col_run": "Lauf",
- "col_when": "Wann",
- "col_in": "In",
- "col_duration": "Dauer",
- "col_actions": "Aktionen",
- "armed": "Aktiv",
- "stat_active": "Aktiv",
- "stat_active_hint": "laufen nach Zeitplan",
- "stat_active_paused": "{n} pausiert",
- "stat_next": "Nächster Lauf",
- "stat_next_hint": "nichts geplant",
- "stat_schedules": "Zeitpläne",
- "stat_schedules_hint": "einmalige Termine",
- "stat_problems": "Probleme",
- "stat_problems_hint": "alles sauber gelaufen",
- "yours_subtitle": "Läuft nach Zeitplan, bis du sie pausierst.",
- "schedules_heading": "Zeitpläne",
- "schedules_subtitle": "Einmalige Termine — laufen einmal und sind dann fertig.",
- "schedules_empty": "Keine Zeitpläne geplant.",
- "schedules_empty_hint": "Ein Zeitplan läuft genau einmal — zu einer festen Uhrzeit oder nach einer Wartezeit.",
- "new_schedule": "Neuer Zeitplan",
- "cancel_schedule": "Termin absagen",
- "runs_heading": "Läufe",
- "runs_subtitle": "Der letzte Lauf von allem, was schon gelaufen ist — mit dem Ergebnis.",
- "runs_filter_label": "Filter",
- "category_all": "Alle",
- "category_label": "Kategorie",
- "custom_title": "Eigene Automatisierung",
- "custom_description": "Beschreibe in eigenen Worten, was regelmäßig passieren soll.",
- "yours_heading": "Deine Automatisierungen",
- "yours_empty": "Noch keine Automatisierungen.",
- "yours_empty_hint": "Nimm eine fertige aus dem Katalog oder beschreibe deine eigene.",
- "catalogue_heading": "Katalog",
- "catalogue_hint": "Fertige Automatisierungen — hinzufügen und den Zeitplan anpassen.",
- "catalogue_loading": "Lade Katalog…",
- "catalogue_error": "Katalog konnte nicht geladen werden",
- "catalogue_empty": "Der Katalog ist leer.",
- "catalogue_unavailable": "Der Katalog ist noch nicht verfügbar — starte die App neu, um ihn zu aktivieren.",
- "route_unavailable": "Diese Aktion braucht das aktualisierte Backend — starte die App neu.",
- "already_running": "Diese Automatisierung läuft gerade schon.",
- "category": {
- "news": "Nachrichten",
- "productivity": "Produktivität",
- "finance": "Finanzen",
- "research": "Recherche",
- "developer": "Entwickler"
- },
- "add": "Hinzufügen",
- "added": "Hinzugefügt",
- "show_installed": "Deine Automatisierung anzeigen",
- "needs": "Braucht {tools}",
- "needs_warning": "Diese Automatisierung braucht {tools} — das ist nicht verbunden. Du kannst sie trotzdem hinzufügen; sie läuft, sobald das Plugin verbunden ist.",
- "add_dialog_title": "Hinzufügen: {title}",
- "add_error": "Automatisierung konnte nicht hinzugefügt werden.",
- "added_notice": "„{title}“ hinzugefügt.",
- "required": "Pflichtfeld",
- "kind": {
- "hourly": "Stündlich",
- "daily": "Täglich",
- "weekly": "Wöchentlich"
- },
- "weekday_label": "Wochentag",
- "time_label": "Uhrzeit",
- "weekday": {
- "0": "Montags",
- "1": "Dienstags",
- "2": "Mittwochs",
- "3": "Donnerstags",
- "4": "Freitags",
- "5": "Samstags",
- "6": "Sonntags"
- },
- "schedule": {
- "hourly": "Stündlich",
- "daily": "Täglich um {time}",
- "weekly": "{day} um {time}",
- "every_minutes": "Alle {n} Min.",
- "every_hours": "Alle {n} Std.",
- "on_event": "Bei einem Ereignis"
- },
- "schedule_label": "Zeitplan",
- "next_run": "Nächster Lauf",
- "last_run": "Letzter Lauf",
- "never_ran": "noch nie gelaufen",
- "run_now": "Jetzt ausführen",
- "run_started": "Läuft jetzt.",
- "run_error": "Lauf konnte nicht gestartet werden.",
- "pause": "Pausieren",
- "resume": "Fortsetzen",
- "paused_notice": "Pausiert.",
- "resumed": "Fortgesetzt.",
- "toggle_error": "Automatisierung konnte nicht geändert werden.",
- "deleted": "Gelöscht.",
- "delete_error": "Automatisierung konnte nicht gelöscht werden.",
- "delete_confirm": "Löschen?",
- "keep": "Behalten",
- "details": "Details",
- "latest_result": "Letztes Ergebnis",
- "result": "Ergebnis",
- "timeline": "Verlauf",
- "no_result_yet": "Noch kein Ergebnis.",
- "runs_empty": "Noch keine Läufe — sie erscheinen hier, sobald die erste Automatisierung gelaufen ist.",
- "runs_filter": {
- "all": "Alle",
- "running": "Laufend",
- "done": "Fertig",
- "problems": "Probleme"
- }
- },
"plugins_view": {
"title": "Plugins",
"count": "{n} verfügbar · {connected} verbunden",
@@ -5427,6 +5303,7 @@
"browser_error": "Der Browser ist nicht erreichbar.",
"routines_add": "Routine hinzufügen",
"routines_title": "Titel",
+ "next_run": "Nächster Lauf",
"routines_prompt": "Was zu tun ist",
"routines_kind": "Wann",
"routines_every": "Alle paar Stunden",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 4d7b6d545b..9348ce2b51 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -139,7 +139,6 @@
"plugins": "Plugins",
"docs": "Docs",
"mcps": "MCPs",
- "tasks": "Automations",
"sessions": "Transcription",
"run_inspector": "Run Inspector",
"costs": "Spend",
@@ -549,7 +548,6 @@
"unpin_chat": "Unpin chat",
"jarvis_tools": "Jarvis Tools",
- "scheduled": "Scheduled",
"more": "More",
"instance_dev_hint": "Dev instance — a second, freely restartable copy of the app with its own data, ports and icon. The regular app keeps running beside it.",
@@ -1168,128 +1166,6 @@
"in_prefix": "in",
"due_now": "due"
},
- "automations_view": {
- "title": "Automations",
- "subtitle": "Everything Jarvis does on its own — recurring automations, one-off schedules, and a catalogue of ready-made ones.",
- "new_button": "New automation",
- "refresh": "Refresh",
- "tab_automations": "Automations",
- "tab_schedules": "Schedules",
- "tab_runs": "Runs",
- "tab_catalogue": "Catalogue",
- "tabs_label": "Area",
- "browse_catalogue": "Browse catalogue",
- "col_automation": "Automation",
- "col_schedule": "Schedule",
- "col_run": "Run",
- "col_when": "When",
- "col_in": "In",
- "col_duration": "Duration",
- "col_actions": "Actions",
- "armed": "Armed",
- "stat_active": "Armed",
- "stat_active_hint": "running on schedule",
- "stat_active_paused": "{n} paused",
- "stat_next": "Next run",
- "stat_next_hint": "nothing scheduled",
- "stat_schedules": "Schedules",
- "stat_schedules_hint": "one-off moments",
- "stat_problems": "Problems",
- "stat_problems_hint": "everything ran clean",
- "yours_subtitle": "They run on their schedule until you pause them.",
- "schedules_heading": "Schedules",
- "schedules_subtitle": "One-off moments — they run once and are done.",
- "schedules_empty": "Nothing scheduled.",
- "schedules_empty_hint": "A schedule runs exactly once, at a time you pick or after a delay.",
- "new_schedule": "New schedule",
- "cancel_schedule": "Cancel schedule",
- "runs_heading": "Runs",
- "runs_subtitle": "The latest run of everything that has run — with what it produced.",
- "runs_filter_label": "Filter",
- "category_all": "All",
- "category_label": "Category",
- "custom_title": "Your own automation",
- "custom_description": "Describe in your own words what should happen regularly.",
- "yours_heading": "Your automations",
- "yours_empty": "No automations yet.",
- "yours_empty_hint": "Take a ready-made one from the catalogue, or describe your own.",
- "catalogue_heading": "Catalogue",
- "catalogue_hint": "Ready-made automations — add one and adjust its schedule.",
- "catalogue_loading": "Loading catalogue…",
- "catalogue_error": "Could not load the catalogue",
- "catalogue_empty": "The catalogue is empty.",
- "catalogue_unavailable": "The catalogue is not available yet — restart the app to enable it.",
- "route_unavailable": "This action needs the updated backend — restart the app.",
- "already_running": "This automation is already running.",
- "category": {
- "news": "News",
- "productivity": "Productivity",
- "finance": "Finance",
- "research": "Research",
- "developer": "Developer"
- },
- "add": "Add",
- "added": "Added",
- "show_installed": "Show your automation",
- "needs": "Needs {tools}",
- "needs_warning": "This automation needs {tools}, which is not connected. You can add it anyway — it will run once the plugin is connected.",
- "add_dialog_title": "Add: {title}",
- "add_error": "Could not add the automation.",
- "added_notice": "\"{title}\" added.",
- "required": "Required",
- "kind": {
- "hourly": "Hourly",
- "daily": "Daily",
- "weekly": "Weekly"
- },
- "weekday_label": "Weekday",
- "time_label": "Time",
- "weekday": {
- "0": "Mondays",
- "1": "Tuesdays",
- "2": "Wednesdays",
- "3": "Thursdays",
- "4": "Fridays",
- "5": "Saturdays",
- "6": "Sundays"
- },
- "schedule": {
- "hourly": "Every hour",
- "daily": "Daily at {time}",
- "weekly": "{day} at {time}",
- "every_minutes": "Every {n} min",
- "every_hours": "Every {n} h",
- "on_event": "When an event fires"
- },
- "schedule_label": "Schedule",
- "next_run": "Next run",
- "last_run": "Last run",
- "never_ran": "never ran",
- "run_now": "Run now",
- "run_started": "Running now.",
- "run_error": "Could not start the run.",
- "pause": "Pause",
- "resume": "Resume",
- "paused_notice": "Paused.",
- "resumed": "Resumed.",
- "toggle_error": "Could not change the automation.",
- "deleted": "Deleted.",
- "delete_error": "Could not delete the automation.",
- "delete_confirm": "Delete?",
- "keep": "Keep",
- "details": "Details",
- "latest_result": "Latest result",
- "result": "Result",
- "timeline": "Timeline",
- "no_result_yet": "No result yet.",
- "runs_empty": "No runs yet — they show up here after the first automation has run.",
- "runs_filter": {
- "all": "All",
- "running": "Running",
- "done": "Done",
- "problems": "Problems"
- }
- },
"plugins_view": {
"title": "Plugins",
"count": "{n} available · {connected} connected",
@@ -5460,6 +5336,7 @@
"browser_error": "Could not reach the browser.",
"routines_add": "Add a routine",
"routines_title": "Title",
+ "next_run": "Next run",
"routines_prompt": "What to do",
"routines_kind": "When",
"routines_every": "Every few hours",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index a56f625ebf..eda263d807 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -139,7 +139,6 @@
"plugins": "Plugins",
"docs": "Documentos",
"mcps": "MCPs",
- "tasks": "Automatizaciones",
"sessions": "Transcripción",
"run_inspector": "Run Inspector",
"costs": "Gastos",
@@ -549,7 +548,6 @@
"unpin_chat": "Desfijar chat",
"jarvis_tools": "Herramientas Jarvis",
- "scheduled": "Programado",
"more": "Más",
"instance_dev_hint": "Instancia de desarrollo: una segunda copia de la app que puedes reiniciar libremente, con sus propios datos, puertos e icono. La app normal sigue funcionando al lado.",
@@ -1168,128 +1166,6 @@
"in_prefix": "en",
"due_now": "pendiente"
},
- "automations_view": {
- "title": "Automatizaciones",
- "subtitle": "Todo lo que Jarvis hace por su cuenta: automatizaciones recurrentes, programaciones únicas y un catálogo de plantillas listas.",
- "new_button": "Nueva automatización",
- "refresh": "Actualizar",
- "tab_automations": "Automatizaciones",
- "tab_schedules": "Programaciones",
- "tab_runs": "Ejecuciones",
- "tab_catalogue": "Catálogo",
- "tabs_label": "Área",
- "browse_catalogue": "Ver catálogo",
- "col_automation": "Automatización",
- "col_schedule": "Programación",
- "col_run": "Ejecución",
- "col_when": "Cuándo",
- "col_in": "En",
- "col_duration": "Duración",
- "col_actions": "Acciones",
- "armed": "Activa",
- "stat_active": "Activas",
- "stat_active_hint": "se ejecutan según su horario",
- "stat_active_paused": "{n} en pausa",
- "stat_next": "Próxima ejecución",
- "stat_next_hint": "nada programado",
- "stat_schedules": "Programaciones",
- "stat_schedules_hint": "momentos únicos",
- "stat_problems": "Problemas",
- "stat_problems_hint": "todo salió bien",
- "yours_subtitle": "Se ejecutan según su horario hasta que las pauses.",
- "schedules_heading": "Programaciones",
- "schedules_subtitle": "Momentos únicos: se ejecutan una vez y ya está.",
- "schedules_empty": "Nada programado.",
- "schedules_empty_hint": "Una programación se ejecuta una sola vez, a la hora que elijas o tras una espera.",
- "new_schedule": "Nueva programación",
- "cancel_schedule": "Cancelar programación",
- "runs_heading": "Ejecuciones",
- "runs_subtitle": "La última ejecución de todo lo que ya se ejecutó, con su resultado.",
- "runs_filter_label": "Filtro",
- "category_all": "Todas",
- "category_label": "Categoría",
- "custom_title": "Tu propia automatización",
- "custom_description": "Describe con tus palabras lo que debe ocurrir de forma periódica.",
- "yours_heading": "Tus automatizaciones",
- "yours_empty": "Aún no hay automatizaciones.",
- "yours_empty_hint": "Toma una lista del catálogo o describe la tuya.",
- "catalogue_heading": "Catálogo",
- "catalogue_hint": "Automatizaciones listas: añade una y ajusta su horario.",
- "catalogue_loading": "Cargando catálogo…",
- "catalogue_error": "No se pudo cargar el catálogo",
- "catalogue_empty": "El catálogo está vacío.",
- "catalogue_unavailable": "El catálogo aún no está disponible: reinicia la app para activarlo.",
- "route_unavailable": "Esta acción necesita el backend actualizado: reinicia la app.",
- "already_running": "Esta automatización ya se está ejecutando.",
- "category": {
- "news": "Noticias",
- "productivity": "Productividad",
- "finance": "Finanzas",
- "research": "Investigación",
- "developer": "Desarrollo"
- },
- "add": "Añadir",
- "added": "Añadida",
- "show_installed": "Mostrar tu automatización",
- "needs": "Necesita {tools}",
- "needs_warning": "Esta automatización necesita {tools}, que no está conectado. Puedes añadirla igualmente; se ejecutará cuando el plugin esté conectado.",
- "add_dialog_title": "Añadir: {title}",
- "add_error": "No se pudo añadir la automatización.",
- "added_notice": "«{title}» añadida.",
- "required": "Obligatorio",
- "kind": {
- "hourly": "Cada hora",
- "daily": "Diario",
- "weekly": "Semanal"
- },
- "weekday_label": "Día de la semana",
- "time_label": "Hora",
- "weekday": {
- "0": "Lunes",
- "1": "Martes",
- "2": "Miércoles",
- "3": "Jueves",
- "4": "Viernes",
- "5": "Sábados",
- "6": "Domingos"
- },
- "schedule": {
- "hourly": "Cada hora",
- "daily": "Diario a las {time}",
- "weekly": "{day} a las {time}",
- "every_minutes": "Cada {n} min",
- "every_hours": "Cada {n} h",
- "on_event": "Cuando ocurre un evento"
- },
- "schedule_label": "Horario",
- "next_run": "Próxima ejecución",
- "last_run": "Última ejecución",
- "never_ran": "nunca ejecutada",
- "run_now": "Ejecutar ahora",
- "run_started": "Ejecutándose ahora.",
- "run_error": "No se pudo iniciar la ejecución.",
- "pause": "Pausar",
- "resume": "Reanudar",
- "paused_notice": "En pausa.",
- "resumed": "Reanudada.",
- "toggle_error": "No se pudo cambiar la automatización.",
- "deleted": "Eliminada.",
- "delete_error": "No se pudo eliminar la automatización.",
- "delete_confirm": "¿Eliminar?",
- "keep": "Conservar",
- "details": "Detalles",
- "latest_result": "Último resultado",
- "result": "Resultado",
- "timeline": "Cronología",
- "no_result_yet": "Aún no hay resultado.",
- "runs_empty": "Aún no hay ejecuciones: aparecerán aquí cuando la primera automatización se haya ejecutado.",
- "runs_filter": {
- "all": "Todas",
- "running": "En curso",
- "done": "Hechas",
- "problems": "Problemas"
- }
- },
"plugins_view": {
"title": "Plugins",
"count": "{n} disponibles · {connected} conectados",
@@ -5427,6 +5303,7 @@
"browser_error": "No se pudo alcanzar el navegador.",
"routines_add": "Añadir una rutina",
"routines_title": "Título",
+ "next_run": "Próxima ejecución",
"routines_prompt": "Qué hacer",
"routines_kind": "Cuándo",
"routines_every": "Cada pocas horas",
diff --git a/jarvis/ui/web/frontend/src/lib/quickSwitch.ts b/jarvis/ui/web/frontend/src/lib/quickSwitch.ts
index 7a9050b987..494d77d9aa 100644
--- a/jarvis/ui/web/frontend/src/lib/quickSwitch.ts
+++ b/jarvis/ui/web/frontend/src/lib/quickSwitch.ts
@@ -72,13 +72,12 @@ const ALIASES: Partial<Record<string, readonly string[]>> = {
chat: ["home", "start", "message", "conversation"],
"agentic-ide": ["ide", "code", "coding", "terminal", "panes", "workspace"],
"agentic-ide-classic": ["terminal", "grid", "panes"],
- agents: ["society", "world", "team"],
+ agents: ["society", "world", "team", "routines", "schedule", "automations"],
settings: ["preferences", "options", "config", "configuration", "general"],
apikeys: ["keys", "credentials", "tokens", "providers"],
"local-models": ["ollama", "llama", "offline", "models"],
memory: ["notes", "knowledge", "obsidian"],
visualization: ["outputs", "results", "images", "pages"],
- tasks: ["routines", "schedule", "cron", "recurring"],
costs: ["tokens", "usage", "money", "billing", "budget"],
sessions: ["transcripts", "recordings", "history"],
run_inspector: ["runs", "debug", "trace"],
diff --git a/jarvis/ui/web/frontend/src/lib/tasksApi.ts b/jarvis/ui/web/frontend/src/lib/tasksApi.ts
new file mode 100644
index 0000000000..9d60caa95a
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/tasksApi.ts
@@ -0,0 +1,123 @@
+/**
+ * The task API under agent routines (`/api/tasks`).
+ *
+ * An agent's routine is a tagged task in the backend scheduler
+ * (`jarvis/society/routines.py`); the agent card reads one and runs, pauses,
+ * stops or deletes it through these calls. Types mirror
+ * `jarvis/tasks/schema.py` (`TASK_STATES`) and `jarvis/ui/web/tasks_routes.py`.
+ */
+
+export type TaskState =
+ | "pending"
+ | "scheduled"
+ | "running"
+ | "paused"
+ | "completed"
+ | "failed"
+ | "cancelled"
+ | "interrupted";
+
+export type TriggerType = "after_delay" | "at_time" | "on_event" | "every" | "calendar" | "webhook" | "event_hook" | "source" | "cron";
+
+export interface TaskSummary {
+ id: string;
+ title: string;
+ state: TaskState;
+ trigger_type: TriggerType;
+ trigger?: unknown;
+ 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;
+ // Older backends omit these, so every field is optional.
+ 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[];
+}
+
+/** 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 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 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);
+}
diff --git a/jarvis/ui/web/frontend/src/store/events.test.ts b/jarvis/ui/web/frontend/src/store/events.test.ts
index 2d7a45f5b7..8498469818 100644
--- a/jarvis/ui/web/frontend/src/store/events.test.ts
+++ b/jarvis/ui/web/frontend/src/store/events.test.ts
@@ -41,7 +41,7 @@ describe("initial section deep links", () => {
it("prefers ?view= over ?doc when both are present", () => {
// Pinned: the explicit deep link wins over the docs shortcut.
- expect(initialSectionFromSearch("?view=tasks&doc=x")).toBe("tasks");
+ expect(initialSectionFromSearch("?view=board&doc=x")).toBe("board");
});
});
diff --git a/jarvis/ui/web/frontend/src/store/events.ts b/jarvis/ui/web/frontend/src/store/events.ts
index 169e02615a..7d6d0b2142 100644
--- a/jarvis/ui/web/frontend/src/store/events.ts
+++ b/jarvis/ui/web/frontend/src/store/events.ts
@@ -59,7 +59,6 @@ export type SectionId =
| "plugins"
| "docs"
| "mcps"
- | "tasks"
| "sessions"
| "run_inspector"
// Spend & Tokens — what every provider, model and role actually cost.
@@ -129,7 +128,6 @@ export const SECTION_IDS = [
"plugins",
"docs",
"mcps",
- "tasks",
"sessions",
"run_inspector",
"costs",
@@ -183,10 +181,13 @@ export function isSectionId(value: unknown): value is SectionId {
* - "wallpaper": the Wallpaper page was removed (2026-09-30); the app paints
* its flat theme colour only. A remembered link lands in Settings, where
* the page used to live.
+ * - "tasks": the Automations section was removed (2026-10-01); scheduled work
+ * lives on agents now, as each agent's routines.
*/
export const LEGACY_SECTION_ALIASES: Readonly<Record<string, SectionId>> = {
outputs: "visualization",
wallpaper: "settings",
+ tasks: "agents",
};
/** The section an id names today — itself, its successor, or null. */
@@ -226,7 +227,6 @@ export const SECTION_LABELS: Record<SectionId, string> = {
plugins: "Plugins",
docs: "Docs",
mcps: "MCPs",
- tasks: "Tasks",
sessions: "Transcription",
run_inspector: "Run Inspector",
costs: "Spend",
diff --git a/jarvis/ui/web/frontend/src/views/AutomationsView.test.tsx b/jarvis/ui/web/frontend/src/views/AutomationsView.test.tsx
deleted file mode 100644
index a7e296d6b1..0000000000
--- a/jarvis/ui/web/frontend/src/views/AutomationsView.test.tsx
+++ /dev/null
@@ -1,396 +0,0 @@
-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": '"{title}" added.',
- "automations_view.stat_active_paused": "{n} paused",
-};
-
-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, and
-// the draft it opens with is what tells "New schedule" apart from "New".
-vi.mock("@/views/tasks/TaskCreateDialog", () => ({
- TaskCreateDialog: ({ initialDraft }: { initialDraft?: { scheduleMode?: string } }) => (
- <div>CREATE_DIALOG:{initialDraft?.scheduleMode ?? "default"}</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.",
-};
-
-/** A one-off that has NOT fired yet — the whole point of the Schedules tab. */
-const SCHEDULE = {
- id: "sched1",
- title: "Call the dentist",
- state: "scheduled",
- trigger_type: "at_time",
- due_at_ns: NOW_NS + 1800e9,
- created_at_ns: NOW_NS - 10e9,
- started_at_ns: null,
- finished_at_ns: null,
- attempts: 0,
- last_error: null,
- tags: [],
- created_by: "user",
- interval_seconds: null,
- next_due_at_ns: null,
- last_run_state: null,
- last_result: null,
-};
-
-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, SCHEDULE, 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/sched1/cancel" && method === "POST") return json(200, { ok: true });
- if (url === "/api/tasks/sched1" && 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/sched1") return json(200, { ...SCHEDULE, spec: null, steps: [] });
- 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>,
- );
-}
-
-/** Switch tabs by the chip rail's accessible name. */
-function goToTab(key: string) {
- fireEvent.click(screen.getByRole("tab", { name: new RegExp(`automations_view.tab_${key}`) }));
-}
-
-/** Open a row's "⋯" menu and pick an entry by its label. */
-function pickRowAction(rowLabel: string, action: string) {
- const row = screen.getByRole("row", { name: rowLabel });
- fireEvent.click(within(row).getByLabelText("automations_view.col_actions"));
- fireEvent.click(screen.getByRole("menuitem", { name: action }));
-}
-
-afterEach(() => {
- cleanup();
- vi.restoreAllMocks();
-});
-
-describe("AutomationsView", () => {
- it("opens on the user's automations, with the headline numbers above them", async () => {
- installFetch();
- renderView();
- expect(await screen.findByText("My inbox triage")).toBeTruthy();
- // The row borrows the template's description via its `template:` tag.
- expect(screen.getByText("Sort the inbox.")).toBeTruthy();
- // One armed automation, one waiting schedule, nothing broken.
- const armed = screen.getByRole("group", { name: "automations_view.stat_active" });
- expect(within(armed).getByText("1")).toBeTruthy();
- const scheduled = screen.getByRole("group", { name: "automations_view.stat_schedules" });
- expect(within(scheduled).getByText("1")).toBeTruthy();
- const problems = screen.getByRole("group", { name: "automations_view.stat_problems" });
- expect(within(problems).getByText("automations_view.stat_problems_hint")).toBeTruthy();
- });
-
- it("the header button opens the create dialog", async () => {
- installFetch();
- renderView();
- await screen.findByText("My inbox triage");
- expect(screen.queryByText(/CREATE_DIALOG/)).toBeNull();
- fireEvent.click(screen.getByText("automations_view.new_button"));
- expect(screen.getByText("CREATE_DIALOG:default")).toBeTruthy();
- });
-
- it("a waiting one-shot lives on the Schedules tab, not in the run history", async () => {
- installFetch();
- renderView();
- await screen.findByText("My inbox triage");
- // Not a row on the automations tab (it IS named by the "next run" tile,
- // which is the point of that tile — so this asks about rows, not text).
- expect(screen.queryByRole("row", { name: "Call the dentist" })).toBeNull();
-
- goToTab("schedules");
- expect(await screen.findByRole("row", { name: "Call the dentist" })).toBeTruthy();
-
- goToTab("runs");
- expect(await screen.findByRole("row", { name: "Weekly report" })).toBeTruthy();
- expect(screen.queryByRole("row", { name: "Call the dentist" })).toBeNull();
- });
-
- it("the Schedules tab creates a one-off, not a recurring automation", async () => {
- installFetch();
- renderView();
- await screen.findByText("My inbox triage");
- goToTab("schedules");
- fireEvent.click(await screen.findByText("automations_view.new_schedule"));
- expect(screen.getByText("CREATE_DIALOG:once")).toBeTruthy();
- });
-
- it("the catalogue filters by category and offers a custom automation", async () => {
- installFetch();
- renderView();
- await screen.findByText("My inbox triage");
- goToTab("catalogue");
-
- expect(await screen.findByText("Morning briefing")).toBeTruthy();
- expect(screen.getByText("Inbox triage")).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();
-
- // "Build your own" sits in the grid, so creating is never a hunt.
- fireEvent.click(screen.getByTestId("catalogue-custom"));
- expect(screen.getByText("CREATE_DIALOG:default")).toBeTruthy();
- });
-
- it("a category chip narrows the grid", async () => {
- installFetch();
- renderView();
- await screen.findByText("My inbox triage");
- goToTab("catalogue");
- await screen.findByText("Morning briefing");
- fireEvent.click(screen.getByRole("tab", { name: /automations_view.category.news/ }));
- expect(screen.getByText("Morning briefing")).toBeTruthy();
- expect(screen.queryByText("Inbox triage")).toBeNull();
- // The custom tile belongs to the unfiltered grid only.
- expect(screen.queryByTestId("catalogue-custom")).toBeNull();
- });
-
- it("shows an honest note when the catalogue route does not exist yet", async () => {
- installFetch({ templatesStatus: 404 });
- renderView();
- await screen.findByText("My inbox triage");
- goToTab("catalogue");
- expect(await screen.findByText("automations_view.catalogue_unavailable")).toBeTruthy();
- });
-
- it("Add opens the dialog, validates required inputs and posts to the template route", async () => {
- const calls = installFetch();
- renderView();
- await screen.findByText("My inbox triage");
- goToTab("catalogue");
- 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,
- timezone: expect.any(String),
- });
- 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 });
- });
- pickRowAction("My inbox triage", "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");
- pickRowAction("My inbox triage", "tasks_view.delete");
- expect(screen.getByText("automations_view.delete_confirm")).toBeTruthy();
- fireEvent.click(screen.getByRole("button", { name: "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("a run row expands to the readable result text, and the chips filter", async () => {
- installFetch();
- renderView();
- await screen.findByText("My inbox triage");
- goToTab("runs");
- fireEvent.click(await screen.findByRole("row", { name: "Weekly report" }));
- 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");
- fireEvent.click(screen.getByRole("tab", { name: "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.tsx
deleted file mode 100644
index b2ee93f314..0000000000
--- a/jarvis/ui/web/frontend/src/views/AutomationsView.tsx
+++ /dev/null
@@ -1,454 +0,0 @@
-/**
- * The Automations section — everything Jarvis does on its own, in one place.
- *
- * Four tabs over one content column: the user's recurring automations, the
- * one-off schedules waiting to fire, the run history, and the catalogue of
- * ready-made automations. The split is what the section was missing: a
- * waiting one-shot used to be filed under "Runs", so schedules had no home
- * and nobody found them, and the catalogue printed one sparse grid per
- * category down an unbounded-width page.
- *
- * The layout is the section design the rest of the app converged on: the
- * section header bar, a row of headline tiles, a chip rail of tabs, and the
- * tables themselves — the same shapes as Spend and Local models. The measure
- * comes from the shell (MainView caps every non-bleed section at the page
- * width), so this view sets no width of its own, and the tables sit directly
- * on the page: a --card panel drawn around a full-width table is a surface
- * far wider than the 720px at which lift stops being an object and starts
- * being a wall.
- *
- * Degrades honestly against an older backend: when the catalogue route does
- * not exist yet (404 — it goes live with the next restart) the tab says so
- * inline, and a failed run/pause/delete call becomes a notice, not a crash.
- */
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import {
- AlertTriangle,
- CalendarClock,
- LayoutGrid,
- Plus,
- RefreshCw,
- Timer,
- Workflow,
- X,
- Zap,
-} from "lucide-react";
-import { ViewHeader } from "@/views/ChatsView";
-import { ScrollArea } from "@/components/ui/scroll-area";
-import { EmptyState } from "@/components/layout/EmptyState";
-import { PanelSkeleton } from "@/components/layout/PanelSkeleton";
-import {
- IconButton,
- PanelHeader,
- SegmentedFilter,
- SoftButton,
- StatGroup,
- StatTile,
-} from "@/components/extensions/primitives";
-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 type { TaskDraft } from "./tasks/taskSpec";
-import { AutomationsPanel } from "./automations/AutomationsPanel";
-import { CataloguePanel } from "./automations/CataloguePanel";
-import { RunsPanel, RUN_FILTERS } from "./automations/RunsPanel";
-import { SchedulesPanel } from "./automations/SchedulesPanel";
-import { TemplateAddDialog } from "./automations/TemplateAddDialog";
-import {
- automationStats,
- formatDelta,
- selectAutomations,
- selectRuns,
- selectSchedules,
- templateKeyOf,
- type AutomationTemplate,
- type RunFilter,
-} from "./automations/automationsModel";
-import { useTick } from "./automations/shared";
-
-type Tab = "automations" | "schedules" | "runs" | "catalogue";
-
-interface Notice {
- text: string;
- kind: "info" | "error";
-}
-
-/** The create dialog opened as "a schedule" starts on the one-off branch. */
-const SCHEDULE_DRAFT: Partial<TaskDraft> = { triggerMode: "schedule", scheduleMode: "once" };
-
-export function AutomationsView() {
- const t = useT();
- const [tab, setTab] = useState<Tab>("automations");
- const [createDraft, setCreateDraft] = useState<Partial<TaskDraft> | null>(null);
- const [adding, setAdding] = useState<AutomationTemplate | null>(null);
- const [highlightId, setHighlightId] = useState<string | null>(null);
- const [runFilter, setRunFilter] = useState<RunFilter>("all");
- 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 schedules = useMemo(() => selectSchedules(tasks), [tasks]);
- const runsCount = useMemo(() => selectRuns(tasks).length, [tasks]);
- const stats = useMemo(() => automationStats(tasks), [tasks]);
-
- const templates = useMemo(
- () => templatesQuery.data?.templates ?? [],
- [templatesQuery.data],
- );
- 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 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 row 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"), { title: 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;
- const openCreate = useCallback(() => setCreateDraft({}), []);
- const openScheduleCreate = useCallback(() => setCreateDraft(SCHEDULE_DRAFT), []);
- const openCatalogue = useCallback(() => setTab("catalogue"), []);
-
- return (
- <div className="flex h-full flex-col">
- <ViewHeader
- icon={<Workflow />}
- title={t("automations_view.title")}
- subtitle={t("automations_view.subtitle")}
- right={
- <div className="flex items-center gap-1.5">
- <IconButton
- label={t("automations_view.refresh")}
- onClick={() => {
- tasksQuery.refetch();
- templatesQuery.refetch();
- }}
- disabled={tasksQuery.isRefetching}
- >
- <RefreshCw className={cn("h-4 w-4", tasksQuery.isRefetching && "animate-spin")} />
- </IconButton>
- <SoftButton primary onClick={openCreate}>
- <Plus className="h-3.5 w-3.5" />
- {t("automations_view.new_button")}
- </SoftButton>
- </div>
- }
- />
- {createDraft && (
- <TaskCreateDialog initialDraft={createDraft} onClose={() => setCreateDraft(null)} />
- )}
- {adding && (
- <TemplateAddDialog template={adding} onClose={() => setAdding(null)} onAdded={handleAdded} />
- )}
-
- <ScrollArea className="flex-1">
- <div className="flex flex-col gap-6 px-8 py-6">
- {notice && (
- <div
- role="status"
- className={cn(
- "flex items-center gap-2 rounded-md bg-secondary px-3 py-2 text-body",
- notice.kind === "error" ? "text-destructive" : "text-foreground",
- )}
- >
- <span className="min-w-0 flex-1 truncate">{notice.text}</span>
- <button
- type="button"
- onClick={() => setNotice(null)}
- aria-label={t("common.close")}
- className="shrink-0 opacity-70 transition-opacity hover:opacity-100"
- >
- <X className="h-3.5 w-3.5" />
- </button>
- </div>
- )}
-
- {tasksQuery.error && (
- <div className="rounded-md bg-secondary px-3 py-2 text-body text-destructive">
- {t("tasks_view.load_error")}: {(tasksQuery.error as Error).message}
- </div>
- )}
-
- {/* Headline numbers — what is armed, what happens next, what broke. */}
- <StatGroup>
- <StatTile
- cell
- icon={<Zap className="h-4 w-4" />}
- label={t("automations_view.stat_active")}
- value={stats.active}
- hint={
- stats.paused > 0
- ? fill(t("automations_view.stat_active_paused"), { n: stats.paused })
- : t("automations_view.stat_active_hint")
- }
- tone="success"
- loading={tasksQuery.isLoading}
- />
- <StatTile
- cell
- icon={<Timer className="h-4 w-4" />}
- label={t("automations_view.stat_next")}
- value={<NextRunValue dueNs={stats.nextDueNs} />}
- hint={stats.nextTitle || t("automations_view.stat_next_hint")}
- loading={tasksQuery.isLoading}
- />
- <StatTile
- cell
- icon={<CalendarClock className="h-4 w-4" />}
- label={t("automations_view.stat_schedules")}
- value={stats.schedules}
- hint={t("automations_view.stat_schedules_hint")}
- loading={tasksQuery.isLoading}
- />
- <StatTile
- cell
- icon={<AlertTriangle className="h-4 w-4" />}
- label={t("automations_view.stat_problems")}
- value={stats.problems}
- hint={stats.problemTitle || t("automations_view.stat_problems_hint")}
- tone={stats.problems > 0 ? "danger" : "success"}
- loading={tasksQuery.isLoading}
- />
- </StatGroup>
-
- <SegmentedFilter<Tab>
- label={t("automations_view.tabs_label")}
- value={tab}
- onChange={setTab}
- options={[
- { id: "automations", label: t("automations_view.tab_automations"), count: automations.length },
- { id: "schedules", label: t("automations_view.tab_schedules"), count: schedules.length },
- { id: "runs", label: t("automations_view.tab_runs"), count: runsCount },
- { id: "catalogue", label: t("automations_view.tab_catalogue"), count: templates.length },
- ]}
- />
-
- {tab === "automations" && (
- <section className="space-y-stack">
- <PanelHeader
- title={t("automations_view.yours_heading")}
- subtitle={t("automations_view.yours_subtitle")}
- actions={
- <SoftButton onClick={openCatalogue}>
- <LayoutGrid className="h-3.5 w-3.5" />
- {t("automations_view.browse_catalogue")}
- </SoftButton>
- }
- />
- <AutomationsPanel
- automations={automations}
- templatesByKey={templatesByKey}
- highlightId={highlightId}
- onRunNow={handleRunNow}
- onSetEnabled={handleSetEnabled}
- onDelete={handleDelete}
- onCreate={openCreate}
- onBrowseCatalogue={openCatalogue}
- busy={{
- runId: runNow.isPending ? runNow.variables : undefined,
- toggleId: setEnabled.isPending ? setEnabled.variables?.id : undefined,
- deleteId: deleteTask.isPending ? deleteTask.variables?.id : undefined,
- }}
- loading={tasksQuery.isLoading}
- />
- </section>
- )}
-
- {tab === "schedules" && (
- <section className="space-y-stack">
- <PanelHeader
- title={t("automations_view.schedules_heading")}
- subtitle={t("automations_view.schedules_subtitle")}
- actions={
- <SoftButton primary onClick={openScheduleCreate}>
- <Plus className="h-3.5 w-3.5" />
- {t("automations_view.new_schedule")}
- </SoftButton>
- }
- />
- <SchedulesPanel
- schedules={schedules}
- onRunNow={handleRunNow}
- onDelete={handleDelete}
- onCreate={openScheduleCreate}
- busy={{
- runId: runNow.isPending ? runNow.variables : undefined,
- deleteId: deleteTask.isPending ? deleteTask.variables?.id : undefined,
- }}
- loading={tasksQuery.isLoading}
- />
- </section>
- )}
-
- {tab === "runs" && (
- <section className="space-y-stack">
- <PanelHeader
- title={t("automations_view.runs_heading")}
- subtitle={t("automations_view.runs_subtitle")}
- actions={
- <SegmentedFilter<RunFilter>
- label={t("automations_view.runs_filter_label")}
- value={runFilter}
- onChange={setRunFilter}
- options={RUN_FILTERS.map((f) => ({
- id: f,
- label: t(`automations_view.runs_filter.${f}`),
- }))}
- />
- }
- />
- <RunsPanel tasks={tasks} filter={runFilter} onNotice={showNotice} />
- </section>
- )}
-
- {tab === "catalogue" && (
- <section className="space-y-stack">
- <PanelHeader
- title={t("automations_view.catalogue_heading")}
- subtitle={t("automations_view.catalogue_hint")}
- />
- {catalogueUnavailable ? (
- <EmptyState body={t("automations_view.catalogue_unavailable")} />
- ) : templatesQuery.isLoading ? (
- // The catalogue is a card grid, so its wait is card-shaped —
- // a dimmed "Loading…" line in a black rectangle is the one
- // loading state this design system does not allow.
- <div className="grid grid-cols-1 gap-stack sm:grid-cols-2 xl:grid-cols-3">
- <PanelSkeleton
- rows={3}
- rowHeight={148}
- label={t("automations_view.catalogue_loading")}
- />
- <PanelSkeleton rows={3} rowHeight={148} />
- <PanelSkeleton rows={3} rowHeight={148} />
- </div>
- ) : templatesQuery.error ? (
- <p className="text-body text-destructive">
- {t("automations_view.catalogue_error")}:{" "}
- {(templatesQuery.error as Error).message}
- </p>
- ) : templates.length === 0 ? (
- <EmptyState body={t("automations_view.catalogue_empty")} />
- ) : (
- <CataloguePanel
- templates={templates}
- installedByKey={installedByKey}
- onAdd={setAdding}
- onShowInstalled={scrollToTask}
- onCreateCustom={openCreate}
- />
- )}
- </section>
- )}
- </div>
- </ScrollArea>
- </div>
- );
-}
-
-/** The countdown as a tile value — "3h", "7min", "due now". Ticks each second. */
-function NextRunValue({ dueNs }: { dueNs: number | null }) {
- const t = useT();
- useTick();
- if (dueNs == null) return <>—</>;
- const delta = dueNs - Date.now() * 1e6;
- if (delta <= 0) return <>{t("tasks_view.due_now")}</>;
- return <>{formatDelta(delta)}</>;
-}
diff --git a/jarvis/ui/web/frontend/src/views/automations/AutomationsPanel.tsx b/jarvis/ui/web/frontend/src/views/automations/AutomationsPanel.tsx
deleted file mode 100644
index d683e831ce..0000000000
--- a/jarvis/ui/web/frontend/src/views/automations/AutomationsPanel.tsx
+++ /dev/null
@@ -1,383 +0,0 @@
-import { SourceControls } from "@/components/society/card/SourceControls";
-/**
- * The user's recurring automations, as one dense table.
- *
- * This used to be a grid of large cards. On a wide pane those cards stretched
- * to a third of a 4K screen each and a category with a single entry left two
- * thirds of the row empty — a lot of surface saying very little. The section
- * design's table says the same in one line per automation: what it is, when it
- * runs, when it ran last and how that went, with the arm switch and the action
- * menu on the right. A row opens to the latest result and the step timeline.
- */
-import { Fragment, useState } from "react";
-import { Loader2, MoreHorizontal, Play, Trash2 } from "lucide-react";
-import { Switch } from "@/components/ui/switch";
-import { PanelSkeleton } from "@/components/layout/PanelSkeleton";
-import { describeTrigger } from "@/lib/triggerDescription";
-import { WebhookConnection } from "@/components/society/card/WebhookConnection";
-import {
- ActionMenu,
- Cell,
- EmptyRow,
- IconButton,
- SoftButton,
- Table,
- TableHead,
- TableRow,
- type Column,
-} from "@/components/extensions/primitives";
-import { useT, useLocaleChunk } 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,
- IdentityGlyph,
- ResultText,
- SectionLabel,
- StateDot,
- StepTimeline,
- formatWhen,
- useScheduleWords,
- useStateLabels,
-} from "./shared";
-
-export interface AutomationsPanelProps {
- automations: TaskSummary[];
- /** Template key → template, so a row can borrow its catalogue description. */
- templatesByKey: Map<string, AutomationTemplate>;
- highlightId: string | null;
- onRunNow: (id: string) => void;
- onSetEnabled: (id: string, enabled: boolean) => void;
- onDelete: (id: string, active: boolean) => void;
- onCreate: () => void;
- onBrowseCatalogue: () => void;
- busy: {
- runId?: string;
- toggleId?: string;
- deleteId?: string;
- };
- loading: boolean;
-}
-
-export function AutomationsPanel({
- automations,
- templatesByKey,
- highlightId,
- onRunNow,
- onSetEnabled,
- onDelete,
- onCreate,
- onBrowseCatalogue,
- busy,
- loading,
-}: AutomationsPanelProps) {
- const t = useT();
- const [openId, setOpenId] = useState<string | null>(null);
- const [confirmId, setConfirmId] = useState<string | null>(null);
-
- const columns: Column[] = [
- { id: "name", label: t("automations_view.col_automation") },
- { id: "schedule", label: t("automations_view.schedule_label"), width: "minmax(0, 150px)" },
- { id: "next", label: t("automations_view.next_run"), width: "minmax(0, 120px)" },
- { id: "last", label: t("automations_view.last_run"), width: "minmax(0, 190px)" },
- { id: "toggle", label: t("automations_view.armed"), width: "48px", align: "center", srOnly: true },
- { id: "actions", label: t("automations_view.col_actions"), width: "36px", align: "right", srOnly: true },
- ];
-
- // While the list is in flight the table would otherwise render its header
- // over nothing, which reads as "you have no automations" rather than as
- // "these are on their way". Real rows, real height, no content.
- if (loading) {
- return (
- <div className="px-3">
- <PanelSkeleton rows={4} rowHeight={54} label={t("automations_view.tab_automations")} />
- </div>
- );
- }
-
- if (automations.length === 0) {
- return (
- <EmptyRow>
- <p>{t("automations_view.yours_empty")}</p>
- <p className="mx-auto mt-1 max-w-md text-meta text-muted-foreground">
- {t("automations_view.yours_empty_hint")}
- </p>
- <div className="mt-4 flex items-center justify-center gap-2">
- <SoftButton primary onClick={onCreate}>
- {t("automations_view.new_button")}
- </SoftButton>
- <SoftButton onClick={onBrowseCatalogue}>
- {t("automations_view.browse_catalogue")}
- </SoftButton>
- </div>
- </EmptyRow>
- );
- }
-
- return (
- <Table label={t("automations_view.tab_automations")}>
- <TableHead columns={columns} />
- {automations.map((task) => {
- const key = templateKeyOf(task);
- const template = key ? templatesByKey.get(key) : undefined;
- return (
- <Fragment key={task.id}>
- <AutomationRow
- columns={columns}
- task={task}
- template={template}
- highlighted={highlightId === task.id}
- open={openId === task.id}
- onToggleOpen={() => setOpenId((cur) => (cur === task.id ? null : task.id))}
- onRunNow={() => onRunNow(task.id)}
- onSetEnabled={(on) => onSetEnabled(task.id, on)}
- onAskDelete={() => setConfirmId(task.id)}
- busy={{
- run: busy.runId === task.id,
- toggle: busy.toggleId === task.id,
- }}
- />
- {confirmId === task.id && (
- <ConfirmDeleteRow
- busy={busy.deleteId === task.id}
- onConfirm={() => {
- onDelete(task.id, isActive(task.state));
- setConfirmId(null);
- }}
- onKeep={() => setConfirmId(null)}
- />
- )}
- {openId === task.id && (
- <AutomationDetail taskId={task.id} fallbackResult={task.last_result} />
- )}
- </Fragment>
- );
- })}
- </Table>
- );
-}
-
-function AutomationRow({
- columns,
- task,
- template,
- highlighted,
- open,
- onToggleOpen,
- onRunNow,
- onSetEnabled,
- onAskDelete,
- busy,
-}: {
- columns: Column[];
- task: TaskSummary;
- template?: AutomationTemplate;
- highlighted: boolean;
- open: boolean;
- onToggleOpen: () => void;
- onRunNow: () => void;
- onSetEnabled: (on: boolean) => void;
- onAskDelete: () => void;
- busy: { run: boolean; toggle: boolean };
-}) {
- const t = useT();
- const words = useScheduleWords();
- const stateLabels = useStateLabels();
- const Icon = templateIcon(template?.icon);
- const paused = task.state === "paused";
- const running = task.state === "running";
- const lastState = task.last_run_state ?? null;
- const seed = templateKeyOf(task) || task.id;
-
- return (
- <TableRow
- columns={columns}
- id={`automation-${task.id}`}
- onClick={onToggleOpen}
- selected={open}
- ariaLabel={task.title || t("tasks_view.untitled")}
- className={cn(
- // "I just added this one" — the row is lifted and ringed, the way a
- // focused row is, rather than washed in a --primary tint.
- highlighted && "bg-secondary ring-2 ring-inset ring-border-strong",
- paused && "opacity-70",
- )}
- >
- <Cell>
- <div className="flex min-w-0 items-center gap-3">
- <IdentityGlyph
- seed={seed}
- className="h-8 w-8"
- >
- <Icon className="h-4 w-4" />
- </IdentityGlyph>
- <span className="min-w-0">
- <span className="block truncate text-base font-medium text-foreground">
- {task.title || t("tasks_view.untitled")}
- </span>
- <AutomationSubline task={task} fallback={template?.description ?? ""} />
- </span>
- </div>
- </Cell>
- <Cell muted className="truncate">
- {scheduleLineForTask(task, words)}
- </Cell>
- <Cell muted>
- {running ? (
- <span className="text-success">{t("tasks_view.running_now")}</span>
- ) : paused ? (
- <span>{stateLabels.paused}</span>
- ) : (
- <Countdown dueNs={task.next_due_at_ns ?? task.due_at_ns} />
- )}
- </Cell>
- <Cell muted>
- <span className="flex min-w-0 items-center gap-2">
- <StateDot state={lastState} />
- <span className="truncate">
- {lastState ? stateLabels[lastState] : t("automations_view.never_ran")}
- {task.finished_at_ns ? ` · ${formatWhen(task.finished_at_ns)}` : ""}
- </span>
- </span>
- </Cell>
- <Cell align="center" stop>
- <Switch
- checked={!paused}
- disabled={busy.toggle || running}
- onCheckedChange={onSetEnabled}
- aria-label={paused ? t("automations_view.resume") : t("automations_view.pause")}
- title={paused ? t("automations_view.resume") : t("automations_view.pause")}
- />
- </Cell>
- <Cell align="right" stop>
- <ActionMenu
- label={t("automations_view.col_actions")}
- actions={[
- {
- id: "run",
- label: t("automations_view.run_now"),
- icon: busy.run ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Play className="h-3.5 w-3.5" />,
- disabled: busy.run || running,
- onSelect: onRunNow,
- },
- {
- id: "delete",
- label: t("tasks_view.delete"),
- icon: <Trash2 className="h-3.5 w-3.5" />,
- destructive: true,
- separatorAbove: true,
- onSelect: onAskDelete,
- },
- ]}
- trigger={({ open: menuOpen, toggle }) => (
- <IconButton
- label={t("automations_view.col_actions")}
- active={menuOpen}
- onClick={toggle}
- className="h-7 w-7"
- >
- <MoreHorizontal className="h-4 w-4" />
- </IconButton>
- )}
- />
- </Cell>
- </TableRow>
- );
-}
-
-/** 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 AutomationSubline({ 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 <span className="block truncate text-sm text-muted-foreground">{text}</span>;
-}
-
-/** The one-question delete confirmation, in place under its row. */
-function ConfirmDeleteRow({
- busy,
- onConfirm,
- onKeep,
-}: {
- busy: boolean;
- onConfirm: () => void;
- onKeep: () => void;
-}) {
- const t = useT();
- return (
- <div
- role="presentation"
- className="flex items-center gap-2 border-b border-border bg-secondary px-3 py-2.5 text-body last:border-b-0"
- >
- <span className="flex-1 text-foreground">{t("automations_view.delete_confirm")}</span>
- <button
- type="button"
- disabled={busy}
- onClick={onConfirm}
- className="inline-flex h-8 items-center gap-1.5 rounded-md bg-destructive px-3 text-body font-medium text-destructive-foreground transition-opacity hover:opacity-90 disabled:opacity-50"
- >
- {busy && <Loader2 className="h-3.5 w-3.5 animate-spin" />}
- {t("tasks_view.delete")}
- </button>
- <SoftButton onClick={onKeep}>{t("automations_view.keep")}</SoftButton>
- </div>
- );
-}
-
-function AutomationDetail({
- taskId,
- fallbackResult,
-}: {
- taskId: string;
- fallbackResult?: string | null;
-}) {
- const t = useT();
- useLocaleChunk("society");
- const { data, isLoading, error } = useTaskDetail(taskId);
- // No fill of its own: the rows around it already answer to the pointer with
- // one, and a second resting surface here leaves them nowhere to travel to.
- if (isLoading) {
- return (
- <div role="presentation" className="border-b border-border px-4 py-4 last:border-b-0">
- <PanelSkeleton rows={3} rowHeight={28} label={t("tasks_view.loading_details")} />
- </div>
- );
- }
- if (error) {
- return (
- <div role="presentation" className="border-b border-border px-4 py-3 text-body text-destructive last:border-b-0">
- {t("common.error")}: {(error as Error).message}
- </div>
- );
- }
- const steps = data?.steps ?? [];
- return (
- <div role="presentation" className="space-y-group border-b border-border px-4 py-4 last:border-b-0">
- {data?.trigger_type === "webhook" || data?.trigger_type === "event_hook" ? <p className="text-body text-muted-foreground">{describeTrigger(data.trigger, t)}</p> : null}
- {data?.trigger_type === "source" ? <SourceControls key={taskId} taskId={taskId} source={(data.trigger as { source: { kind: string } }).source} /> : null}
- {data?.trigger_type === "webhook" ? <WebhookConnection key={taskId} taskId={taskId} /> : null}
- <div>
- <SectionLabel className="mb-stack">{t("automations_view.latest_result")}</SectionLabel>
- <ResultText steps={steps} fallback={fallbackResult} />
- </div>
- <div>
- <SectionLabel className="mb-stack">
- {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.tsx
deleted file mode 100644
index b570c70c10..0000000000
--- a/jarvis/ui/web/frontend/src/views/automations/CatalogueCard.tsx
+++ /dev/null
@@ -1,93 +0,0 @@
-/**
- * A catalogue entry: icon, name, description, default schedule and Add.
- *
- * The card carries a minimum height so a one-sentence template and a
- * three-sentence one line up in the same row instead of stair-stepping — the
- * ragged grid was most of what made the section look thrown together. When
- * the template is already installed the card says so and links to the user's
- * row; when a required plugin is missing it carries a quiet "needs Gmail"
- * line (Add still works — the dialog repeats the warning).
- */
-import { Check, Clock, Plus } from "lucide-react";
-import { fill, useT } from "@/i18n";
-import { templateIcon } from "./automationIcons";
-import { humanizeMissing, type AutomationTemplate } from "./automationsModel";
-import { IdentityGlyph } from "./shared";
-
-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);
- const needsSomething = !template.ready && template.missing.length > 0;
-
- return (
- <article
- data-testid={`catalogue-${template.key}`}
- className="card-outline flex min-h-[148px] flex-col p-4 shadow-rim"
- >
- <div className="flex items-start gap-3">
- <IdentityGlyph seed={template.key} className="h-9 w-9">
- <Icon className="h-4 w-4" />
- </IdentityGlyph>
- <div className="min-w-0 flex-1">
- <h3 className="truncate text-title font-semibold text-foreground-strong">
- {template.name}
- </h3>
- <p className="mt-1 line-clamp-2 text-meta text-muted-foreground">
- {template.description}
- </p>
- </div>
- </div>
-
- {/* "needs Gmail" is a degraded state, not a headline: it used to be the
- brightest line on the card at --foreground. */}
- {needsSomething && (
- <p className="mt-2 truncate text-micro text-warning">
- {fill(t("automations_view.needs"), { tools: humanizeMissing(template.missing) })}
- </p>
- )}
-
- <div className="mt-auto flex items-center gap-2 pt-3">
- <span className="inline-flex min-w-0 items-center gap-1.5 text-micro text-muted-foreground">
- <Clock className="h-3 w-3 shrink-0" />
- <span className="truncate">{template.schedule_label}</span>
- </span>
- <span className="ml-auto shrink-0">
- {installed && installedTaskId ? (
- <button
- type="button"
- onClick={() => onShowInstalled(installedTaskId)}
- title={t("automations_view.show_installed")}
- className="inline-flex h-8 items-center gap-1.5 rounded-md bg-secondary px-2.5 text-meta font-medium text-foreground transition-colors hover:bg-popover"
- >
- <Check className="h-3.5 w-3.5" />
- {t("automations_view.added")}
- </button>
- ) : (
- <button
- type="button"
- onClick={() => onAdd(template)}
- className="inline-flex h-8 items-center gap-1.5 rounded-md bg-secondary px-2.5 text-meta font-medium text-foreground transition-colors hover:bg-popover"
- >
- <Plus className="h-3.5 w-3.5" />
- {t("automations_view.add")}
- </button>
- )}
- </span>
- </div>
- </article>
- );
-}
diff --git a/jarvis/ui/web/frontend/src/views/automations/CataloguePanel.tsx b/jarvis/ui/web/frontend/src/views/automations/CataloguePanel.tsx
deleted file mode 100644
index 26f1408623..0000000000
--- a/jarvis/ui/web/frontend/src/views/automations/CataloguePanel.tsx
+++ /dev/null
@@ -1,123 +0,0 @@
-/**
- * The catalogue of ready-made automations.
- *
- * The old layout printed one grid per category down the page, so a category
- * holding a single template left two thirds of a row empty and the page read
- * as mostly whitespace. Categories are a filter now, not five separate grids:
- * one chip row, one grid, three columns inside the section's content width.
- *
- * The first tile is deliberately not a template — it is "build your own",
- * because the catalogue is where someone looks when they want an automation,
- * and the only way to make a custom one used to be a small button in the far
- * corner of the header.
- */
-import { useMemo, useState } from "react";
-import { Plus, Wand2 } from "lucide-react";
-import { SegmentedFilter } from "@/components/extensions/primitives";
-import { useT } from "@/i18n";
-import { CatalogueCard } from "./CatalogueCard";
-import {
- TEMPLATE_CATEGORIES,
- type AutomationTemplate,
- type TemplateCategory,
-} from "./automationsModel";
-
-type CategoryFilter = TemplateCategory | "all";
-
-export interface CataloguePanelProps {
- templates: AutomationTemplate[];
- /** Template key → the user's task created from it, when installed. */
- installedByKey: Map<string, string>;
- onAdd: (template: AutomationTemplate) => void;
- onShowInstalled: (taskId: string) => void;
- onCreateCustom: () => void;
-}
-
-export function CataloguePanel({
- templates,
- installedByKey,
- onAdd,
- onShowInstalled,
- onCreateCustom,
-}: CataloguePanelProps) {
- const t = useT();
- const [category, setCategory] = useState<CategoryFilter>("all");
-
- // Only categories that actually hold something become chips — an empty
- // "Finance" chip that filters to nothing is a dead end, not a feature.
- const options = useMemo(() => {
- const present = TEMPLATE_CATEGORIES.filter((c) =>
- templates.some((tpl) => tpl.category === c),
- );
- return [
- { id: "all" as CategoryFilter, label: t("automations_view.category_all"), count: templates.length },
- ...present.map((c) => ({
- id: c as CategoryFilter,
- label: t(`automations_view.category.${c}`),
- count: templates.filter((tpl) => tpl.category === c).length,
- })),
- ];
- }, [templates, t]);
-
- const shown = useMemo(
- () => (category === "all" ? templates : templates.filter((tpl) => tpl.category === category)),
- [templates, category],
- );
-
- return (
- <div className="space-y-group">
- <SegmentedFilter<CategoryFilter>
- label={t("automations_view.category_label")}
- value={category}
- onChange={setCategory}
- options={options}
- />
- <div className="grid grid-cols-1 gap-stack sm:grid-cols-2 xl:grid-cols-3">
- {category === "all" && <CustomTile onClick={onCreateCustom} />}
- {shown.map((tpl) => (
- <CatalogueCard
- key={tpl.key}
- template={tpl}
- installedTaskId={installedByKey.get(tpl.key)}
- onAdd={onAdd}
- onShowInstalled={onShowInstalled}
- />
- ))}
- </div>
- </div>
- );
-}
-
-/**
- * "Build your own" — the same size as a template card, drawn as an offer.
- *
- * A real card with a dashed rim (the one thing that says "not a template
- * yet"), lifting on hover like every other row in the app. The wand used to
- * be painted --primary inside a --primary-tinted tile, which made the ONE
- * tile in the grid that holds no automation the brightest object in it.
- */
-function CustomTile({ onClick }: { onClick: () => void }) {
- const t = useT();
- return (
- <button
- type="button"
- onClick={onClick}
- data-testid="catalogue-custom"
- className="flex min-h-[148px] flex-col items-start gap-2 rounded-lg border border-dashed border-border-strong bg-card p-4 text-left shadow-rim transition-colors hover:bg-secondary"
- >
- <span className="grid h-9 w-9 place-items-center rounded-md bg-secondary">
- <Wand2 className="h-4 w-4 text-muted-foreground" />
- </span>
- <span className="text-title font-semibold text-foreground-strong">
- {t("automations_view.custom_title")}
- </span>
- <span className="text-meta text-muted-foreground">
- {t("automations_view.custom_description")}
- </span>
- <span className="mt-auto inline-flex items-center gap-1 text-meta font-medium text-foreground">
- <Plus className="h-3.5 w-3.5" />
- {t("automations_view.new_button")}
- </span>
- </button>
- );
-}
diff --git a/jarvis/ui/web/frontend/src/views/automations/RunsPanel.tsx b/jarvis/ui/web/frontend/src/views/automations/RunsPanel.tsx
deleted file mode 100644
index d1afeaaef3..0000000000
--- a/jarvis/ui/web/frontend/src/views/automations/RunsPanel.tsx
+++ /dev/null
@@ -1,231 +0,0 @@
-/**
- * The run history — every task that ran or is running, newest first.
- *
- * Was a stack of full-width cards in `TasksView.tsx`; it is a table now, like
- * the two tabs beside it, so a long history stays scannable. A row opens to
- * the readable result text and the step timeline. Still-waiting one-shots are
- * NOT here any more — they belong to the Schedules tab, which is the whole
- * point of that tab existing.
- */
-import { Fragment, useMemo, useState } from "react";
-import { Loader2, MoreHorizontal, Trash2, X } from "lucide-react";
-import { PanelSkeleton } from "@/components/layout/PanelSkeleton";
-import {
- ActionMenu,
- Cell,
- EmptyRow,
- IconButton,
- Table,
- TableHead,
- TableRow,
- type Column,
-} from "@/components/extensions/primitives";
-import { useT } from "@/i18n";
-import { cn } from "@/lib/utils";
-import { useCancelTask, useDeleteTask, useTaskDetail } from "@/hooks/useAutomations";
-import {
- filterRuns,
- formatDuration,
- isActive,
- isRecurringTrigger,
- runStateOf,
- selectRuns,
- type RunFilter,
- type TaskSummary,
-} from "./automationsModel";
-import {
- ResultText,
- SectionLabel,
- StateDot,
- StepTimeline,
- formatWhen,
- useStateLabels,
-} from "./shared";
-
-export const RUN_FILTERS: RunFilter[] = ["all", "running", "done", "problems"];
-
-export interface RunsPanelProps {
- tasks: TaskSummary[];
- filter: RunFilter;
- onNotice: (text: string, kind?: "info" | "error") => void;
-}
-
-export function RunsPanel({ tasks, filter, onNotice }: RunsPanelProps) {
- const t = useT();
- const stateLabels = useStateLabels();
- const [openId, setOpenId] = useState<string | null>(null);
- const cancelMut = useCancelTask();
- const deleteMut = useDeleteTask();
-
- const runs = useMemo(() => filterRuns(selectRuns(tasks), filter), [tasks, filter]);
-
- const columns: Column[] = [
- { id: "name", label: t("automations_view.col_run") },
- { id: "result", label: t("automations_view.result"), width: "minmax(0, 1.1fr)" },
- { id: "when", label: t("automations_view.col_when"), width: "minmax(0, 130px)" },
- { id: "duration", label: t("automations_view.col_duration"), width: "minmax(0, 90px)", align: "right" },
- { id: "actions", label: t("automations_view.col_actions"), width: "36px", align: "right", srOnly: true },
- ];
-
- if (runs.length === 0) {
- return <EmptyRow>{t("automations_view.runs_empty")}</EmptyRow>;
- }
-
- return (
- <Table label={t("automations_view.tab_runs")}>
- <TableHead columns={columns} />
- {runs.map((run) => {
- // A recurring automation sits at "scheduled" between runs; the row is
- // about the run, so it reads the derived state, not the task's.
- const state = runStateOf(run);
- const active = run.state === "running";
- // A recurring automation's row is its latest run; deleting it is the
- // Automations tab's job, so only one-shots offer Delete here.
- const canDelete = !isRecurringTrigger(run.trigger_type) || !active;
- const duration = formatDuration(run.started_at_ns, run.finished_at_ns);
- const open = openId === run.id;
- return (
- <Fragment key={run.id}>
- <TableRow
- columns={columns}
- onClick={() => setOpenId((cur) => (cur === run.id ? null : run.id))}
- selected={open}
- ariaLabel={run.title || t("tasks_view.untitled")}
- >
- <Cell>
- <span className="flex min-w-0 items-center gap-2.5">
- <StateDot state={state} />
- <span className="min-w-0">
- <span className="block truncate font-medium text-foreground">
- {run.title || t("tasks_view.untitled")}
- </span>
- <span className="block truncate text-meta text-muted-foreground">
- {stateLabels[state]}
- </span>
- </span>
- </span>
- </Cell>
- <Cell muted>
- <span
- className={cn(
- "block truncate",
- run.last_error && !run.last_result && "text-destructive",
- )}
- >
- {run.last_result || run.last_error || "—"}
- </span>
- </Cell>
- <Cell muted className="truncate">
- {formatWhen(
- run.finished_at_ns ?? run.started_at_ns ?? run.due_at_ns ?? run.created_at_ns,
- )}
- </Cell>
- <Cell muted align="right" className="font-mono tabular-nums">
- {duration ?? "—"}
- </Cell>
- <Cell align="right" stop>
- <ActionMenu
- label={t("automations_view.col_actions")}
- actions={[
- ...(active
- ? [
- {
- id: "cancel",
- label: t("tasks_view.cancel"),
- icon:
- cancelMut.isPending && cancelMut.variables === run.id ? (
- <Loader2 className="h-3.5 w-3.5 animate-spin" />
- ) : (
- <X className="h-3.5 w-3.5" />
- ),
- onSelect: () =>
- cancelMut.mutate(run.id, {
- onError: (err) =>
- onNotice(
- `${t("common.error")}: ${(err as Error).message}`,
- "error",
- ),
- }),
- },
- ]
- : []),
- ...(canDelete
- ? [
- {
- id: "delete",
- label: t("tasks_view.delete"),
- icon: <Trash2 className="h-3.5 w-3.5" />,
- destructive: true,
- separatorAbove: active,
- onSelect: () =>
- deleteMut.mutate(
- { id: run.id, active: isActive(run.state) },
- {
- onError: (err) =>
- onNotice(
- `${t("common.error")}: ${(err as Error).message}`,
- "error",
- ),
- },
- ),
- },
- ]
- : []),
- ]}
- trigger={({ open: menuOpen, toggle }) => (
- <IconButton
- label={t("automations_view.col_actions")}
- active={menuOpen}
- onClick={toggle}
- className="h-7 w-7"
- >
- <MoreHorizontal className="h-4 w-4" />
- </IconButton>
- )}
- />
- </Cell>
- </TableRow>
- {open && <RunDetail taskId={run.id} fallbackResult={run.last_result} />}
- </Fragment>
- );
- })}
- </Table>
- );
-}
-
-function RunDetail({ taskId, fallbackResult }: { taskId: string; fallbackResult?: string | null }) {
- const t = useT();
- const { data, isLoading, error } = useTaskDetail(taskId);
- // The opened row's detail. No fill of its own: the rows above and below
- // already answer to the pointer with one, and a second resting surface here
- // would give them nowhere left to travel to.
- if (isLoading) {
- return (
- <div role="presentation" className="border-b border-border px-4 py-4 last:border-b-0">
- <PanelSkeleton rows={3} rowHeight={28} label={t("tasks_view.loading_details")} />
- </div>
- );
- }
- if (error) {
- return (
- <div role="presentation" className="border-b border-border px-4 py-3 text-body text-destructive last:border-b-0">
- {t("common.error")}: {(error as Error).message}
- </div>
- );
- }
- const steps = data?.steps ?? [];
- return (
- <div role="presentation" className="space-y-group border-b border-border px-4 py-4 last:border-b-0">
- <div>
- <SectionLabel className="mb-stack">{t("automations_view.result")}</SectionLabel>
- <ResultText steps={steps} fallback={fallbackResult} />
- </div>
- <div>
- <SectionLabel className="mb-stack">
- {t("automations_view.timeline")} ({steps.length})
- </SectionLabel>
- <StepTimeline steps={steps} />
- </div>
- </div>
- );
-}
diff --git a/jarvis/ui/web/frontend/src/views/automations/SchedulesPanel.tsx b/jarvis/ui/web/frontend/src/views/automations/SchedulesPanel.tsx
deleted file mode 100644
index 578603cffd..0000000000
--- a/jarvis/ui/web/frontend/src/views/automations/SchedulesPanel.tsx
+++ /dev/null
@@ -1,154 +0,0 @@
-/**
- * Schedules — the one-off timed tasks ("remind me at 18:00", "run this in an
- * hour"). They were always creatable, but they had nowhere to live: a waiting
- * one-shot was mixed into the run history, which reads as a list of things
- * that already happened, so nobody found them. They get their own tab here,
- * sorted forwards, with the moment written out and a countdown beside it.
- */
-import { Loader2, MoreHorizontal, Play, Trash2 } from "lucide-react";
-import { PanelSkeleton } from "@/components/layout/PanelSkeleton";
-import {
- ActionMenu,
- Cell,
- EmptyRow,
- IconButton,
- SoftButton,
- Table,
- TableHead,
- TableRow,
- type Column,
-} from "@/components/extensions/primitives";
-import { useT, useUiLanguage } from "@/i18n";
-import { isActive, type TaskSummary } from "./automationsModel";
-import { Countdown, StateDot, formatDueAt, useStateLabels } from "./shared";
-
-export interface SchedulesPanelProps {
- schedules: TaskSummary[];
- onRunNow: (id: string) => void;
- onDelete: (id: string, active: boolean) => void;
- onCreate: () => void;
- busy: { runId?: string; deleteId?: string };
- loading: boolean;
-}
-
-export function SchedulesPanel({
- schedules,
- onRunNow,
- onDelete,
- onCreate,
- busy,
- loading,
-}: SchedulesPanelProps) {
- const t = useT();
- const locale = useUiLanguage();
- const stateLabels = useStateLabels();
-
- const columns: Column[] = [
- { id: "name", label: t("automations_view.col_schedule") },
- { id: "due", label: t("automations_view.col_when"), width: "minmax(0, 200px)" },
- { id: "in", label: t("automations_view.col_in"), width: "minmax(0, 110px)" },
- { id: "state", label: t("common.status"), width: "minmax(0, 130px)" },
- { id: "actions", label: t("automations_view.col_actions"), width: "36px", align: "right", srOnly: true },
- ];
-
- // Real rows at real height while the list is in flight — a bare table head
- // over nothing reads as "you have no schedules".
- if (loading) {
- return (
- <div className="px-3">
- <PanelSkeleton rows={3} rowHeight={54} label={t("automations_view.tab_schedules")} />
- </div>
- );
- }
-
- if (schedules.length === 0) {
- return (
- <EmptyRow>
- <p>{t("automations_view.schedules_empty")}</p>
- <p className="mx-auto mt-1 max-w-md text-meta text-muted-foreground">
- {t("automations_view.schedules_empty_hint")}
- </p>
- <div className="mt-4 flex justify-center">
- <SoftButton primary onClick={onCreate}>
- {t("automations_view.new_schedule")}
- </SoftButton>
- </div>
- </EmptyRow>
- );
- }
-
- return (
- <Table label={t("automations_view.tab_schedules")}>
- <TableHead columns={columns} />
- {schedules.map((task) => (
- <TableRow
- key={task.id}
- columns={columns}
- id={`schedule-${task.id}`}
- ariaLabel={task.title || t("tasks_view.untitled")}
- >
- <Cell>
- <span className="block truncate font-medium text-foreground">
- {task.title || t("tasks_view.untitled")}
- </span>
- </Cell>
- <Cell muted className="truncate">
- {formatDueAt(task.due_at_ns, locale)}
- </Cell>
- <Cell muted>
- <Countdown dueNs={task.due_at_ns} />
- </Cell>
- <Cell muted>
- <span className="flex min-w-0 items-center gap-2">
- <StateDot state={task.state} />
- <span className="truncate">{stateLabels[task.state]}</span>
- </span>
- </Cell>
- <Cell align="right" stop>
- <ActionMenu
- label={t("automations_view.col_actions")}
- actions={[
- {
- id: "run",
- label: t("automations_view.run_now"),
- icon:
- busy.runId === task.id ? (
- <Loader2 className="h-3.5 w-3.5 animate-spin" />
- ) : (
- <Play className="h-3.5 w-3.5" />
- ),
- disabled: busy.runId === task.id,
- onSelect: () => onRunNow(task.id),
- },
- {
- id: "delete",
- label: t("automations_view.cancel_schedule"),
- icon:
- busy.deleteId === task.id ? (
- <Loader2 className="h-3.5 w-3.5 animate-spin" />
- ) : (
- <Trash2 className="h-3.5 w-3.5" />
- ),
- destructive: true,
- separatorAbove: true,
- disabled: busy.deleteId === task.id,
- onSelect: () => onDelete(task.id, isActive(task.state)),
- },
- ]}
- trigger={({ open, toggle }) => (
- <IconButton
- label={t("automations_view.col_actions")}
- active={open}
- onClick={toggle}
- className="h-7 w-7"
- >
- <MoreHorizontal className="h-4 w-4" />
- </IconButton>
- )}
- />
- </Cell>
- </TableRow>
- ))}
- </Table>
- );
-}
diff --git a/jarvis/ui/web/frontend/src/views/automations/TemplateAddDialog.tsx b/jarvis/ui/web/frontend/src/views/automations/TemplateAddDialog.tsx
deleted file mode 100644
index ede413a5d7..0000000000
--- a/jarvis/ui/web/frontend/src/views/automations/TemplateAddDialog.tsx
+++ /dev/null
@@ -1,235 +0,0 @@
-/**
- * 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 { BrandedSelect } from "@/components/ui/select";
-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";
-
-/*
- * A field inside a dialog.
- *
- * The dialog IS the floating layer, so there is no surface left above it to
- * fill a field with — a child darker than its parent is the one nesting error
- * this system calls hard. So the field is described by a rim instead, the way
- * the composer is, and focus thickens that same rim rather than inventing a
- * third colour.
- */
-const inputCls =
- "w-full rounded-md border border-border-strong bg-transparent px-3 py-2 text-body text-foreground " +
- "placeholder:text-faint-foreground focus:outline-none focus:ring-2 focus:ring-border-strong";
-
-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, timezone: Intl.DateTimeFormat().resolvedOptions().timeZone };
- 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"), { title: template.name })}
- className="flex max-h-[90vh] w-full max-w-lg flex-col overflow-hidden rounded-lg bg-popover shadow-float"
- 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">
- <Icon className="h-5 w-5 shrink-0 text-muted-foreground" />
- <div className="min-w-0">
- <h2 className="truncate text-title font-semibold text-foreground-strong">
- {fill(t("automations_view.add_dialog_title"), { title: template.name })}
- </h2>
- <p className="truncate text-meta 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-group px-5 py-4">
- {/* Missing prerequisites are a degraded state, not a headline. */}
- {!template.ready && template.missing.length > 0 && (
- <p className="flex items-start gap-1.5 rounded-md border border-border-strong px-3 py-2 text-meta text-warning">
- <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-muted-foreground">*</span>
- )}
- </SectionLabel>
- <input
- className={cn(inputCls, invalid && "border-destructive")}
- 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-meta text-destructive">
- {t("automations_view.required")}
- </span>
- )}
- </label>
- );
- })}
-
- <div className="space-y-stack rounded-lg border border-border p-4">
- <SectionLabel>{t("tasks_view.create.schedule_label")}</SectionLabel>
- {/* On the floating layer the surface ladder has run out, so the
- chosen segment is an --primary FILL (an active indicator, the
- one job that token has) rather than a fourth grey. */}
- <div className="inline-flex rounded-md border border-border-strong p-0.5">
- {KINDS.map((k) => (
- <button
- key={k}
- type="button"
- onClick={() => setKind(k)}
- className={cn(
- "rounded-md px-3 py-1.5 text-meta font-medium transition-colors",
- kind === k
- ? "bg-primary text-primary-foreground"
- : "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" && (
- <BrandedSelect
- className={cn(inputCls, "w-auto")}
- value={String(weekday)}
- onValueChange={(value) => setWeekday(Number(value))}
- ariaLabel={t("automations_view.weekday_label")}
- options={weekdays.map((name, idx) => ({
- value: String(idx),
- label: name,
- }))}
- />
- )}
- <span className="text-body 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-meta 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.ts
deleted file mode 100644
index 03775ef054..0000000000
--- a/jarvis/ui/web/frontend/src/views/automations/automationIcons.ts
+++ /dev/null
@@ -1,201 +0,0 @@
-/**
- * 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.ts
deleted file mode 100644
index d71ac574de..0000000000
--- a/jarvis/ui/web/frontend/src/views/automations/automationsModel.test.ts
+++ /dev/null
@@ -1,217 +0,0 @@
-import { describe, expect, it } from "vitest";
-import {
- automationStats,
- extractAgentResult,
- filterRuns,
- firstLine,
- formatDuration,
- groupTemplates,
- humanizeMissing,
- scheduleLineForTask,
- selectAutomations,
- selectRuns,
- selectSchedules,
- 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("schedules = waiting one-shots, soonest first", () => {
- const later = task({ id: "g", trigger_type: "after_delay", state: "pending", due_at_ns: 9 });
- expect(selectSchedules([...all, later]).map((t) => t.id)).toEqual(["d", "g"]);
- });
-
- it("runs = ran/running only — a waiting one-shot is a schedule, not a run", () => {
- expect(selectRuns(all).map((t) => t.id)).toEqual(["e", "f", "c"]);
- });
-
- it("a waiting one-shot lives on exactly one tab", () => {
- // The bug this split fixes: a schedule that had not fired yet was listed
- // under Runs, so it read as history and its own tab looked empty. A
- // RECURRING automation that is running right now is a different story —
- // it is legitimately both something you own and something happening, so
- // only the one-shot is pinned down here.
- const onTabs = (id: string) =>
- [selectAutomations(all), selectSchedules(all), selectRuns(all)].filter((list) =>
- list.some((t) => t.id === id),
- ).length;
- expect(onTabs("d")).toBe(1);
- expect(onTabs("e")).toBe(1);
- });
-
- it("a recurring automation joins the runs once it has one behind it", () => {
- // Without this the Runs tab was permanently empty for anyone whose
- // automations all recur: such a task returns to "scheduled" after a run,
- // so only `last_run_state` remembers that anything happened.
- const ran = task({
- id: "h",
- trigger_type: "every",
- state: "scheduled",
- last_run_state: "failed",
- finished_at_ns: 12,
- });
- const runs = selectRuns([...all, ran]);
- expect(runs.map((t) => t.id)).toEqual(["h", "e", "f", "c"]);
- expect(filterRuns(runs, "problems").map((t) => t.id)).toEqual(["h", "c"]);
- });
-
- 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"]);
- });
-});
-
-describe("headline numbers", () => {
- const now = Date.now() * 1e6;
-
- it("counts what is armed, finds the soonest moment and names what broke", () => {
- const stats = automationStats([
- task({ id: "a", title: "Digest", state: "scheduled", next_due_at_ns: now + 7200e9 }),
- task({ id: "b", title: "Triage", state: "paused", next_due_at_ns: now + 60e9 }),
- task({ id: "c", title: "Pulse", state: "scheduled", next_due_at_ns: now + 600e9, last_run_state: "failed" }),
- task({ id: "d", title: "Ping", trigger_type: "at_time", state: "pending", due_at_ns: now + 300e9 }),
- task({ id: "e", title: "Old", state: "completed", trigger_type: "after_delay" }),
- ]);
- expect(stats.active).toBe(2);
- expect(stats.paused).toBe(1);
- expect(stats.schedules).toBe(1);
- // The paused one is due soonest but is not armed, so it must not win.
- expect(stats.nextTitle).toBe("Ping");
- expect(stats.problems).toBe(1);
- expect(stats.problemTitle).toBe("Pulse");
- });
-
- it("says nothing rather than zero when there is nothing to say", () => {
- const stats = automationStats([]);
- expect(stats.nextDueNs).toBeNull();
- expect(stats.nextTitle).toBe("");
- expect(stats.problemTitle).toBe("");
- });
-});
-
-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"]);
- });
-});
-
-
-it("calendar routines appear in Automations with their own clock and zone", () => {
- const row = task({ trigger_type: "calendar", trigger: { type: "calendar", local_time: "08:00", timezone: "America/Los_Angeles" } });
- expect(selectAutomations([row])).toEqual([row]);
- expect(scheduleLineForTask(row, WORDS)).toBe("Daily at 08:00 · America/Los_Angeles");
-});
diff --git a/jarvis/ui/web/frontend/src/views/automations/automationsModel.ts b/jarvis/ui/web/frontend/src/views/automations/automationsModel.ts
deleted file mode 100644
index b6e973ab5f..0000000000
--- a/jarvis/ui/web/frontend/src/views/automations/automationsModel.ts
+++ /dev/null
@@ -1,462 +0,0 @@
-import { describeTrigger } from "@/lib/triggerDescription";
-
-/**
- * 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" | "calendar" | "webhook" | "event_hook" | "source" | "cron";
-
-export interface TaskSummary {
- id: string;
- title: string;
- state: TaskState;
- trigger_type: TriggerType;
- trigger?: unknown;
- 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 {
- timezone?: string;
- 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 === "calendar" || trigger === "on_event" || trigger === "webhook" || trigger === "event_hook" || trigger === "source" || trigger === "cron";
-}
-
-/** A one-off timed task (a "schedule") — the `after_delay` / `at_time` triggers. */
-export function isOneShotTrigger(trigger: TriggerType): boolean {
- return trigger === "after_delay" || trigger === "at_time";
-}
-
-/** 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 user's schedules: one-off timed tasks that are still waiting for their
- * moment. Soonest first — a schedule is read as "what happens next", not as
- * "what happened last", so this list is the only one sorted forwards.
- *
- * A one-shot that is already running belongs to the run history instead; the
- * three selections here are deliberately disjoint so no task shows up on two
- * tabs and gets deleted twice.
- */
-export function selectSchedules(tasks: TaskSummary[]): TaskSummary[] {
- return tasks
- .filter(
- (t) =>
- isOneShotTrigger(t.trigger_type) &&
- (t.state === "pending" || t.state === "scheduled" || t.state === "paused"),
- )
- .sort((a, b) => (a.due_at_ns ?? Number.MAX_SAFE_INTEGER) - (b.due_at_ns ?? Number.MAX_SAFE_INTEGER));
-}
-
-/**
- * The state a run row should show.
- *
- * A recurring automation goes straight back to `scheduled` after a run, so its
- * own `state` says nothing about how that run went — `last_run_state` does.
- * One value, derived in one place, so the dot, the label and the "problems"
- * filter can never disagree about the same row.
- */
-export function runStateOf(task: TaskSummary): TaskState {
- if (isTerminal(task.state) || task.state === "running") return task.state;
- return task.last_run_state ?? task.state;
-}
-
-/**
- * The run history: everything that has actually run, newest activity first.
- *
- * A recurring automation belongs here once it has a run behind it — the task
- * row carries only its LATEST one, which is why the tab is worded as the last
- * run of each rather than a full log. Without this the tab was permanently
- * empty for anyone whose automations are all recurring, which is everyone.
- *
- * A still-waiting one-shot is NOT a run — it lives on the Schedules tab until
- * it fires.
- */
-export function selectRuns(tasks: TaskSummary[]): TaskSummary[] {
- return tasks
- .filter((t) => isTerminal(t.state) || t.state === "running" || Boolean(t.last_run_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;
-}
-
-/** The four headline numbers above the tabs. */
-export interface AutomationStats {
- /** Automations that are armed (everything except a paused one). */
- active: number;
- paused: number;
- /** The soonest upcoming moment across armed automations and schedules. */
- nextDueNs: number | null;
- /** Title of the task that owns `nextDueNs` ("" when nothing is due). */
- nextTitle: string;
- /** One-off schedules still waiting to fire. */
- schedules: number;
- /** Automations whose last run failed or was interrupted. */
- problems: number;
- /** Title of one such automation, for the tile's second line. */
- problemTitle: string;
-}
-
-/**
- * Derives the headline numbers from the task list.
- *
- * Deliberately NOT "runs in the last 7 days": a recurring task carries only
- * its latest run, so a per-week count would silently undercount and read as a
- * broken number. Every figure here is one the list can actually answer.
- */
-export function automationStats(tasks: TaskSummary[]): AutomationStats {
- const automations = selectAutomations(tasks);
- const schedules = selectSchedules(tasks);
-
- let nextDueNs: number | null = null;
- let nextTitle = "";
- for (const task of [...automations, ...schedules]) {
- if (task.state === "paused") continue;
- const due = task.next_due_at_ns ?? task.due_at_ns ?? null;
- if (due == null) continue;
- if (nextDueNs == null || due < nextDueNs) {
- nextDueNs = due;
- nextTitle = task.title;
- }
- }
-
- const broken = automations.filter(
- (t) => t.last_run_state === "failed" || t.last_run_state === "interrupted",
- );
-
- return {
- active: automations.filter((t) => t.state !== "paused").length,
- paused: automations.filter((t) => t.state === "paused").length,
- nextDueNs,
- nextTitle,
- schedules: schedules.length,
- problems: broken.length,
- problemTitle: broken[0]?.title ?? "",
- };
-}
-
-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");
- case "done":
- return runs.filter((r) => runStateOf(r) === "completed");
- case "problems":
- return runs.filter((r) => {
- const state = runStateOf(r);
- return state === "failed" || state === "interrupted" || 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" | "trigger_type" | "interval_seconds" | "next_due_at_ns" | "due_at_ns">,
- words: ScheduleWords,
-): string {
- if (task.trigger_type === "cron") { const rule = task.trigger as { expression: string; timezone: string }; return `${rule.expression} · ${rule.timezone}`; }
- if (task.trigger_type === "source") { const source = (task.trigger as { source: { kind: string; topic?: string; path?: string } }).source; return [source.kind, source.topic || source.path].filter(Boolean).join(" · "); }
- if (task.trigger_type === "calendar") return describeTrigger(task.trigger, () => words.daily.replace("{time}", "{0}"));
- if (task.trigger_type === "webhook") return "Webhook";
- if (task.trigger_type === "event_hook") return `${words.onEvent} · ${String((task.trigger as { event_name?: string } | undefined)?.event_name ?? "")}`;
- 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",
- "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.identity.test.tsx b/jarvis/ui/web/frontend/src/views/automations/shared.identity.test.tsx
deleted file mode 100644
index b95d3c3a5c..0000000000
--- a/jarvis/ui/web/frontend/src/views/automations/shared.identity.test.tsx
+++ /dev/null
@@ -1,38 +0,0 @@
-import { render } from "@testing-library/react";
-import { describe, expect, it } from "vitest";
-
-import { IdentityGlyph, identityTint } from "./shared";
-
-describe("identityTint", () => {
- it("is stable for the same seed", () => {
- expect(identityTint("inbox-triage")).toBe(identityTint("inbox-triage"));
- });
-
- it("does not collapse every name onto one hue", () => {
- const seeds = [
- "inbox-triage",
- "morning-briefing",
- "x-marketing",
- "github-hooks",
- "discord-bot",
- "youtube",
- "weather",
- "standup",
- ];
- const hues = new Set(seeds.map(identityTint));
- expect(hues.size).toBeGreaterThan(3);
- });
-});
-
-describe("IdentityGlyph", () => {
- it("paints the hashed colour onto the chip", () => {
- const { container } = render(
- <IdentityGlyph seed="x-marketing" className="h-8 w-8">
- <span>X</span>
- </IdentityGlyph>,
- );
- const chip = container.firstElementChild as HTMLElement;
- expect(chip.style.backgroundColor).toBeTruthy();
- expect(chip.className).toContain("rounded-full");
- });
-});
diff --git a/jarvis/ui/web/frontend/src/views/automations/shared.tsx b/jarvis/ui/web/frontend/src/views/automations/shared.tsx
deleted file mode 100644
index 868493cf9f..0000000000
--- a/jarvis/ui/web/frontend/src/views/automations/shared.tsx
+++ /dev/null
@@ -1,274 +0,0 @@
-/**
- * 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.
- *
- * Every colour is a named token. Status is the only thing here that carries
- * hue, and it carries exactly three: life, degraded, fault. The one documented
- * exception is `identityTint`, which derives a stable avatar hue from a name —
- * an identity mark, never a state.
- */
-import { useEffect, useMemo, useState, type ReactNode } 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],
- );
-}
-
-/**
- * The state ramp. Anything alive or finished well is `life`; anything that
- * needs a person is `degraded`; a failure is `fault`; and the three states
- * that mean "nothing is happening" recede to the faint step.
- *
- * `interrupted` used to be painted --foreground, which made the one state
- * nobody acts on the brightest mark in a list of running automations.
- */
-const DOT_CLASS: Record<TaskState, string> = {
- pending: "bg-faint-foreground",
- scheduled: "bg-success",
- running: "bg-success animate-pulse",
- paused: "bg-faint-foreground",
- completed: "bg-success",
- failed: "bg-destructive",
- cancelled: "bg-faint-foreground",
- interrupted: "bg-warning",
-};
-
-/**
- * A stable saturated hue for an identity chip — the Grok-Bot coloured
- * avatar trick. Hash the seed onto a short palette so two nearby rows
- * do not land on neighbouring yellows.
- */
-const IDENTITY_HUES = [262, 221, 199, 152, 28, 8, 338, 291] as const;
-
-export function identityTint(seed: string): string {
- let hash = 2166136261;
- for (let i = 0; i < seed.length; i += 1) {
- hash ^= seed.charCodeAt(i);
- hash = Math.imul(hash, 16777619);
- }
- const hue = IDENTITY_HUES[Math.abs(hash) % IDENTITY_HUES.length];
- return `hsl(${hue} 58% 46%)`;
-}
-
-/** Coloured round mark for a person / bot / automation — the live-dot's sibling. */
-export function IdentityGlyph({
- seed,
- children,
- className,
-}: {
- seed: string;
- children: ReactNode;
- className?: string;
-}) {
- return (
- <span
- aria-hidden
- className={cn(
- "grid shrink-0 place-items-center rounded-full text-white",
- className,
- )}
- style={{ backgroundColor: identityTint(seed) }}
- >
- {children}
- </span>
- );
-}
-
-/** 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 "";
- }
-}
-
-/**
- * A schedule's moment, written out: "Wed, 27.08., 07:00".
- *
- * `formatWhen` above answers "when did this happen" and drops the weekday for
- * anything today; a schedule is read forwards, and the weekday is the part a
- * person checks first ("is that before or after the weekend?").
- */
-export function formatDueAt(ns: number | null | undefined, locale?: string): string {
- if (!ns) return "—";
- try {
- const d = new Date(ns / 1e6);
- return d.toLocaleString(locale, {
- weekday: "short",
- 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-body text-muted-foreground">
- {t("automations_view.no_result_yet")}
- </p>
- );
- }
- return (
- <div
- data-testid="run-result"
- className="max-w-reading whitespace-pre-wrap rounded-lg bg-secondary px-4 py-3 text-reading 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-body text-muted-foreground">{t("tasks_view.no_steps")}</div>;
- }
- return (
- <ol>
- {steps.map((s) => (
- <li
- key={s.seq}
- className="flex items-start gap-3 rounded-md px-2.5 py-1.5 text-micro transition-colors hover:bg-secondary"
- >
- <span className="w-5 shrink-0 font-mono tabular-nums text-muted-foreground">
- {s.seq}
- </span>
- <span className="w-20 shrink-0 text-foreground">{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 tabular-nums text-muted-foreground">
- {formatWhen(s.timestamp_ns)}
- </span>
- </li>
- ))}
- </ol>
- );
-}
-
-/**
- * A group's name inside a panel.
- *
- * Was an 11px letter-spaced all-caps line — the construction that makes an
- * interface read as an admin panel, and the one this design system bans
- * outright. A group label is a title: sentence case, one weight up, in the
- * ink ceiling.
- */
-export function SectionLabel({ children, className }: { children: React.ReactNode; className?: string }) {
- return (
- <div className={cn("text-title font-semibold text-foreground-strong", className)}>
- {children}
- </div>
- );
-}
diff --git a/jarvis/ui/web/frontend/src/views/tasks/TaskCreateDialog.test.tsx b/jarvis/ui/web/frontend/src/views/tasks/TaskCreateDialog.test.tsx
deleted file mode 100644
index 5880dd84e6..0000000000
--- a/jarvis/ui/web/frontend/src/views/tasks/TaskCreateDialog.test.tsx
+++ /dev/null
@@ -1,174 +0,0 @@
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import { cleanup, render, screen, fireEvent, waitFor } from "@testing-library/react";
-import { afterEach, describe, expect, it, vi } from "vitest";
-
-import { TaskCreateDialog } from "./TaskCreateDialog";
-
-const PLUGINS = {
- connected: 1,
- total: 1,
- plugins: [{ id: "gmail", name: "Gmail", status: "connected", live_callable: true }],
-};
-
-function installFetch(
- onPost?: (body: Record<string, unknown>) => void,
- pluginsResponse: unknown = PLUGINS,
-) {
- const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
- const url = String(input);
- if (url === "/api/marketplace/plugins") {
- return { ok: true, status: 200, json: async () => pluginsResponse } as Response;
- }
- if (url === "/api/tasks" && init?.method === "POST") {
- onPost?.(JSON.parse(String(init.body)));
- return { ok: true, status: 201, json: async () => ({ id: "new1" }) } as Response;
- }
- throw new Error(`unexpected fetch ${url}`);
- });
- (globalThis as unknown as { fetch: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
-}
-
-function renderDialog(onClose = vi.fn()) {
- const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
- return render(
- <QueryClientProvider client={qc}>
- <TaskCreateDialog onClose={onClose} />
- </QueryClientProvider>,
- );
-}
-
-afterEach(() => {
- cleanup();
- vi.restoreAllMocks();
-});
-
-describe("TaskCreateDialog", () => {
- it("renders the form with name + prompt fields and the connected plugin", async () => {
- installFetch();
- renderDialog();
- expect(await screen.findByText("Gmail")).toBeTruthy();
- // name input + prompt textarea
- expect(screen.getAllByRole("textbox").length).toBeGreaterThanOrEqual(2);
- // recurring is the default schedule mode
- expect(screen.getByText("Recurring")).toBeTruthy();
- });
-
- it("toggling a plugin reveals its read/write/full scope picker", async () => {
- installFetch();
- renderDialog();
- await screen.findByText("Gmail");
- expect(screen.queryByText("Read")).toBeNull();
- fireEvent.click(screen.getByRole("switch"));
- expect(screen.getByText("Read")).toBeTruthy();
- expect(screen.getByText("Write")).toBeTruthy();
- expect(screen.getByText("Full")).toBeTruthy();
- });
-
- it("submits an agent task spec with the granted plugin and a recurring trigger", async () => {
- const posted: Record<string, unknown>[] = [];
- installFetch((b) => posted.push(b));
- renderDialog();
- await screen.findByText("Gmail");
-
- const boxes = screen.getAllByRole("textbox");
- fireEvent.change(boxes[0], { target: { value: "Morning Briefing" } });
- fireEvent.change(boxes[1], { target: { value: "Summarize inbox" } });
- fireEvent.click(screen.getByRole("switch")); // enable gmail (default scope read)
- fireEvent.click(screen.getByText("Create"));
-
- await waitFor(() => expect(posted.length).toBe(1));
- const spec = posted[0] as {
- title: string;
- trigger: { type: string };
- action: { kind: string; plugin_grants: unknown[] };
- };
- expect(spec.title).toBe("Morning Briefing");
- expect(spec.trigger.type).toBe("calendar");
- expect(spec.action.kind).toBe("agent");
- expect(spec.action.plugin_grants).toEqual([{ plugin_id: "gmail", scope: "read" }]);
- });
-
- it("shows the unattended warning only at write/full scope", async () => {
- installFetch();
- renderDialog();
- await screen.findByText("Gmail");
- // no warning before any plugin is enabled
- expect(screen.queryByText(/unattended/i)).toBeNull();
- fireEvent.click(screen.getByRole("switch")); // enable gmail (default: read)
- expect(screen.queryByText(/unattended/i)).toBeNull();
- fireEvent.click(screen.getByText("Write")); // elevate to write
- expect(screen.getByText(/unattended/i)).toBeTruthy();
- });
-
- it("renders the body as a native overflow scroll container so a long plugin list stays reachable", async () => {
- // Regression guard for the non-scrolling dialog: a Radix ScrollArea nested a
- // `height:100%` viewport inside a `max-h-[90vh]` flex column, where the height
- // never resolved, so Radix kept `overflow:hidden` and the lower plugins + the
- // model tier picker were clipped and unreachable. The fix is a native
- // `overflow-y-auto` flex child (the ConductorView pattern), which is itself the
- // scroll container and needs no resolved viewport height.
- installFetch();
- const { container } = renderDialog();
- await screen.findByText("Gmail");
- const scrollBody = container.querySelector(".overflow-y-auto");
- expect(scrollBody).toBeTruthy();
- // The scroll container must wrap the WHOLE form — from the name input at the top
- // down to the model tier section at the very bottom (the part that was clipped).
- expect(scrollBody!.querySelector("input")).toBeTruthy();
- expect(scrollBody!.textContent).toContain("Fast");
- });
-
- it("only lists plugins the user has actually connected — not the whole catalog", async () => {
- // `live_callable` is a CATALOG property (the plugin has an MCP transport or a
- // native ROUTER_TOOLS tool), NOT a connection state — it is `true` even for
- // plugins the user never connected. The dialog must offer only `status ===
- // "connected"` plugins; offering not_connected / needs_reauth ones makes no
- // sense (an unattended task can't use a plugin that isn't connected).
- const MIXED = {
- connected: 1,
- total: 3,
- plugins: [
- { id: "github", name: "GitHub", status: "connected", live_callable: true },
- { id: "vercel", name: "Vercel", status: "not_connected", live_callable: true },
- { id: "gmail", name: "Gmail", status: "needs_reauth", live_callable: true },
- ],
- };
- installFetch(undefined, MIXED);
- renderDialog();
- await screen.findByText("GitHub");
- // exactly one toggle — the connected plugin; the catalog-callable-but-unconnected ones are excluded
- expect(screen.getAllByRole("switch")).toHaveLength(1);
- expect(screen.queryByText("Vercel")).toBeNull();
- expect(screen.queryByText("Gmail")).toBeNull();
- });
-
- it("disables submit until name and prompt are filled", async () => {
- installFetch();
- renderDialog();
- await screen.findByText("Gmail");
- const saveBtn = screen.getByText("Create").closest("button") as HTMLButtonElement;
- expect(saveBtn.disabled).toBe(true);
- const boxes = screen.getAllByRole("textbox");
- fireEvent.change(boxes[0], { target: { value: "X" } });
- fireEvent.change(boxes[1], { target: { value: "Y" } });
- expect(saveBtn.disabled).toBe(false);
- });
- it("submits the selected source after the trigger editor changes", async () => {
- const posted: Record<string, unknown>[] = [];
- installFetch((body) => posted.push(body));
- renderDialog();
- await screen.findByText("Gmail");
- const boxes = screen.getAllByRole("textbox");
- fireEvent.change(boxes[0], { target: { value: "New event" } });
- fireEvent.change(boxes[1], { target: { value: "Handle incoming events" } });
- fireEvent.click(await screen.findByText("All triggers"));
- fireEvent.click(screen.getByTestId("routine-trigger-group"));
- fireEvent.click(await screen.findByRole("option", { name: "API" }));
- fireEvent.click(screen.getByTestId("agent-routines-kind"));
- fireEvent.click(await screen.findByRole("option", { name: "MCP" }));
- fireEvent.click(screen.getByText("Create"));
- await waitFor(() => expect(posted.length).toBe(1));
- expect(posted[0].trigger).toEqual({ type: "source", source: { kind: "mcp" }, conditions: {} });
- });
-
-});
diff --git a/jarvis/ui/web/frontend/src/views/tasks/TaskCreateDialog.tsx b/jarvis/ui/web/frontend/src/views/tasks/TaskCreateDialog.tsx
deleted file mode 100644
index c11f76fc64..0000000000
--- a/jarvis/ui/web/frontend/src/views/tasks/TaskCreateDialog.tsx
+++ /dev/null
@@ -1,623 +0,0 @@
-import { TriggerBuilder } from "@/components/society/card/TriggerBuilder";
-import type { TaskTrigger } from "./taskSpec";
-import { useMemo, useState } from "react";
-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import {
- X,
- Clock,
- CalendarClock,
- Repeat,
- Loader2,
- Plug,
- Sparkles,
- AlertTriangle,
- CalendarDays,
- Zap,
- MonitorPlay,
- Bot,
- Bell,
-} from "lucide-react";
-import { Button } from "@/components/ui/button";
-import { Switch } from "@/components/ui/switch";
-import { cn } from "@/lib/utils";
-import { useLocaleChunk, useT, useUiLanguage } from "@/i18n";
-import { humanizeToolName } from "@/views/automations/automationsModel";
-import {
- buildTaskSpec,
- defaultAtTimeLocal,
- formatWatermarkDate,
- type ModelTier,
- type ScopeValue,
- type TaskDraft,
- type ThenKind,
- type WhenKey,
-} from "./taskSpec";
-
-interface PluginItem {
- id: string;
- name?: string;
- status: string;
- live_callable?: boolean;
-}
-
-interface PluginsResponse {
- plugins: PluginItem[];
- connected: number;
-}
-
-async function fetchPlugins(): Promise<PluginsResponse> {
- // `cache: "no-store"` bypasses the embedded WebView2 HTTP cache so the
- // desktop app never shows a stale connection state for plugins (see the
- // matching note in PluginsView.fetchCatalog).
- const res = await fetch("/api/marketplace/plugins", { cache: "no-store" });
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
- return res.json();
-}
-
-async function createTask(spec: ReturnType<typeof buildTaskSpec>): Promise<{ id: string }> {
- const res = await fetch("/api/tasks", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(spec),
- });
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
- return res.json();
-}
-
-const SCOPES: ScopeValue[] = ["read", "write", "full"];
-const TIERS: ModelTier[] = ["fast", "auto", "deep"];
-
-/** A small inline segmented control — used for mode pickers and scope. */
-function Segmented<T extends string>({
- value,
- options,
- onChange,
- size = "md",
-}: {
- value: T;
- options: { id: T; label: string; icon?: typeof Clock }[];
- onChange: (v: T) => void;
- size?: "sm" | "md";
-}) {
- return (
- <div className="inline-flex rounded-lg border border-border bg-background/40 p-0.5">
- {options.map((o) => {
- const Icon = o.icon;
- const active = value === o.id;
- return (
- <button
- key={o.id}
- type="button"
- onClick={() => onChange(o.id)}
- className={cn(
- "inline-flex items-center gap-1.5 rounded-md font-medium transition-colors",
- size === "sm" ? "px-2 py-1 text-xs" : "px-3 py-1.5 text-xs",
- active
- ? "bg-primary/15 text-primary"
- : "text-muted-foreground hover:text-foreground",
- )}
- >
- {Icon && <Icon className="h-3.5 w-3.5" />}
- {o.label}
- </button>
- );
- })}
- </div>
- );
-}
-
-function Field({ label, children }: { label: string; children: React.ReactNode }) {
- return (
- <label className="block space-y-1.5">
- <span className="text-xs font-medium uppercase tracking-wider text-muted-foreground">
- {label}
- </span>
- {children}
- </label>
- );
-}
-
-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 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) {
- useLocaleChunk("society");
- const t = useT();
- const uiLang = useUiLanguage();
- const qc = useQueryClient();
- const init = initialDraft ?? {};
-
- const [title, setTitle] = useState(init.title ?? "");
- const [prompt, setPrompt] = useState(init.prompt ?? "");
- const [triggerMode, setTriggerMode] = useState<"schedule" | "event" | "source">(init.triggerMode ?? "schedule");
- const [sourceTrigger, setSourceTrigger] = useState<Record<string, unknown> | null>(null);
- 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(() => 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"],
- queryFn: fetchPlugins,
- });
- // Only plugins the user has actually connected belong here. `live_callable` is a
- // catalog property (the plugin ships an MCP transport or a native ROUTER_TOOLS
- // tool) and is `true` even for unconnected plugins, so it must NOT widen this
- // list — a scheduled task can only use a plugin whose auth is live ("connected"),
- // never a `not_connected` or `needs_reauth` one.
- const plugins = (pluginsData?.plugins ?? []).filter((p) => p.status === "connected");
-
- const draft: TaskDraft = useMemo(
- () => ({
- title,
- prompt,
- triggerMode,
- sourceTrigger: sourceTrigger as TaskTrigger | undefined,
- scheduleMode,
- onceMode,
- delaySeconds: delayValue * (delayUnit === "hours" ? 3600 : 60),
- atTimeLocal,
- recurringMode,
- customIntervalSeconds: customValue * (customUnit === "hours" ? 3600 : 60),
- dailyTime,
- modelTier,
- grants: Object.entries(grants).map(([plugin_id, scope]) => ({ plugin_id, scope })),
- whenKey,
- thenKind,
- cuPrompt,
- announceText,
- }),
- [title, prompt, triggerMode, sourceTrigger, scheduleMode, onceMode, delayValue, delayUnit, atTimeLocal,
- recurringMode, customValue, customUnit, dailyTime, modelTier, grants,
- whenKey, thenKind, cuPrompt, announceText],
- );
-
- const createMut = useMutation({
- mutationFn: () => createTask(buildTaskSpec(draft)),
- onSuccess: () => {
- qc.invalidateQueries({ queryKey: ["tasks"] });
- onClose();
- },
- });
-
- // The agent prompt + plugins + model picker only apply to an agentic action:
- // every time-based task, and an event rule whose "then" is an agent turn.
- const showAgentConfig = triggerMode !== "event" || thenKind === "agent";
-
- const valid =
- title.trim().length > 0 && (triggerMode !== "source" || sourceTrigger !== null) &&
- (triggerMode === "event"
- ? thenKind === "computer_use"
- ? cuPrompt.trim().length > 0
- : thenKind === "agent"
- ? prompt.trim().length > 0
- : announceText.trim().length > 0 // notify
- : prompt.trim().length > 0 &&
- (scheduleMode !== "once" || onceMode !== "at_time" || atTimeLocal !== ""));
-
- const hasElevatedGrant = Object.values(grants).some(
- (s) => s === "write" || s === "full",
- );
-
- function togglePlugin(id: string) {
- setGrants((prev) => {
- const next = { ...prev };
- if (id in next) delete next[id];
- else next[id] = "read";
- return next;
- });
- }
-
- function setScope(id: string, scope: ScopeValue) {
- setGrants((prev) => ({ ...prev, [id]: scope }));
- }
-
- return (
- <div
- className="fixed inset-0 z-50 flex items-center justify-center bg-scrim/60 p-4 backdrop-blur-sm"
- onClick={onClose}
- >
- <div
- className="flex max-h-[90vh] w-full max-w-2xl flex-col overflow-hidden rounded-lg bg-popover shadow-float"
- onClick={(e) => e.stopPropagation()}
- >
- {/* Header */}
- <div className="flex items-center justify-between border-b border-border px-6 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">
- <Sparkles className="h-4 w-4 text-primary" />
- </div>
- <div>
- <h2 className="text-sm font-semibold">{t("tasks_view.create.title")}</h2>
- <p className="text-xs text-muted-foreground">
- {t("tasks_view.create.subtitle")}
- </p>
- </div>
- </div>
- <Button size="sm" variant="ghost" onClick={onClose}>
- <X className="h-4 w-4" />
- </Button>
- </div>
-
- {/* Body — a native overflow scroll container (the ConductorView pattern).
- A Radix <ScrollArea> nests a `height:100%` viewport that never resolves
- inside this `max-h-[90vh]` flex column, so Radix kept `overflow:hidden`
- and clipped the lower plugins + the model picker. `min-h-0` lets this
- flex child shrink below its content so it actually scrolls. */}
- <div className="min-h-0 flex-1 overflow-y-auto scrollbar-jarvis">
- <div className="space-y-5 px-6 py-5">
- <Field label={t("tasks_view.create.name_label")}>
- <input
- className={inputCls}
- value={title}
- onChange={(e) => setTitle(e.target.value)}
- placeholder={t("tasks_view.create.name_placeholder")}
- maxLength={256}
- />
- </Field>
-
- {/* Trigger mode: a time-based schedule vs. an event-driven
- "When-Then" rule (e.g. when a mission finishes → do X). */}
- <div className="flex items-center justify-between">
- <span className="text-xs font-medium uppercase tracking-wider text-muted-foreground">
- {t("tasks_view.create.trigger_mode_label")}
- </span>
- <Segmented
- value={triggerMode}
- onChange={setTriggerMode}
- options={[
- { id: "schedule", label: t("tasks_view.create.mode_schedule"), icon: CalendarDays },
- { id: "event", label: t("tasks_view.create.mode_event"), icon: Zap },
- { id: "source", label: t("society.triggers.all_sources"), icon: Zap },
- ]}
- />
- </div>
-
- {/* When-Then rule: curated "when" event + "then" action */}
- {triggerMode === "source" && <TriggerBuilder onChange={setSourceTrigger} />}
- {triggerMode === "event" && (
- <div className="space-y-4 rounded-xl border border-border/70 bg-background/30 p-4">
- <div className="space-y-2">
- <span className="text-xs font-medium uppercase tracking-wider text-muted-foreground">
- {t("tasks_view.create.when_label")}
- </span>
- <div className="flex flex-wrap gap-1.5">
- <Segmented
- size="sm"
- value={whenKey}
- onChange={setWhenKey}
- options={[
- { id: "mission_succeeded", label: t("tasks_view.create.when_mission_succeeded") },
- { id: "mission_failed", label: t("tasks_view.create.when_mission_failed") },
- { id: "mission_cancelled", label: t("tasks_view.create.when_mission_cancelled") },
- ]}
- />
- </div>
- </div>
-
- <div className="space-y-2">
- <span className="text-xs font-medium uppercase tracking-wider text-muted-foreground">
- {t("tasks_view.create.then_label")}
- </span>
- <Segmented
- size="sm"
- value={thenKind}
- onChange={setThenKind}
- options={[
- { id: "computer_use", label: t("tasks_view.create.then_computer_use"), icon: MonitorPlay },
- { id: "agent", label: t("tasks_view.create.then_agent"), icon: Bot },
- { id: "notify", label: t("tasks_view.create.then_notify"), icon: Bell },
- ]}
- />
- </div>
-
- {thenKind === "computer_use" && (
- <Field label={t("tasks_view.create.cu_goal_label")}>
- <textarea
- className={cn(inputCls, "min-h-[72px] resize-y leading-relaxed")}
- value={cuPrompt}
- onChange={(e) => setCuPrompt(e.target.value)}
- placeholder={t("tasks_view.create.cu_goal_placeholder")}
- maxLength={16384}
- />
- </Field>
- )}
-
- <Field
- label={
- thenKind === "notify"
- ? t("tasks_view.create.notify_text_label")
- : t("tasks_view.create.announce_label")
- }
- >
- <input
- className={inputCls}
- value={announceText}
- onChange={(e) => setAnnounceText(e.target.value)}
- placeholder={t("tasks_view.create.announce_placeholder")}
- maxLength={2048}
- />
- </Field>
- <p className="text-xs leading-relaxed text-muted-foreground">
- {t("tasks_view.create.when_then_hint")}
- </p>
- </div>
- )}
-
- {/* Schedule */}
- {triggerMode === "schedule" && (
- <div className="space-y-3 rounded-xl border border-border/70 bg-background/30 p-4">
- <div className="flex items-center justify-between">
- <span className="text-xs font-medium uppercase tracking-wider text-muted-foreground">
- {t("tasks_view.create.schedule_label")}
- </span>
- <Segmented
- value={scheduleMode}
- onChange={setScheduleMode}
- options={[
- { id: "once", label: t("tasks_view.create.once"), icon: Clock },
- { id: "recurring", label: t("tasks_view.create.recurring"), icon: Repeat },
- ]}
- />
- </div>
-
- {scheduleMode === "once" ? (
- <div className="space-y-3">
- <Segmented
- size="sm"
- value={onceMode}
- onChange={setOnceMode}
- options={[
- { id: "at_time", label: t("tasks_view.create.at_time"), icon: CalendarClock },
- { id: "delay", label: t("tasks_view.create.after_delay"), icon: Clock },
- ]}
- />
- {onceMode === "at_time" ? (
- <div className="relative overflow-hidden rounded-lg">
- {/* The selected date, written out long-form and very faint,
- sitting behind the picker — "the current date, but a
- little in the background". It tracks whatever value the
- picker holds and is purely decorative (no pointer
- events), so the native control stays fully usable. */}
- <div
- aria-hidden
- className="pointer-events-none absolute inset-y-0 left-3 right-11 flex items-center justify-end"
- >
- <span className="truncate text-lg font-semibold leading-none text-foreground/[0.06]">
- {formatWatermarkDate(atTimeLocal, uiLang)}
- </span>
- </div>
- <input
- type="datetime-local"
- className={cn(inputCls, "relative bg-transparent [color-scheme:dark]")}
- value={atTimeLocal}
- onChange={(e) => setAtTimeLocal(e.target.value)}
- />
- </div>
- ) : (
- <div className="flex items-center gap-2">
- <span className="text-xs text-muted-foreground">
- {t("tasks_view.create.in")}
- </span>
- <input
- type="number"
- min={1}
- className={cn(inputCls, "w-24")}
- value={delayValue}
- onChange={(e) => setDelayValue(Math.max(1, Number(e.target.value)))}
- />
- <Segmented
- size="sm"
- value={delayUnit}
- onChange={setDelayUnit}
- options={[
- { id: "minutes", label: t("tasks_view.create.minutes") },
- { id: "hours", label: t("tasks_view.create.hours") },
- ]}
- />
- </div>
- )}
- </div>
- ) : (
- <div className="space-y-3">
- <Segmented
- size="sm"
- value={recurringMode}
- onChange={setRecurringMode}
- options={[
- { id: "hourly", label: t("tasks_view.create.hourly") },
- { id: "daily", label: t("tasks_view.create.daily") },
- { id: "custom", label: t("tasks_view.create.custom") },
- ]}
- />
- {recurringMode === "daily" && (
- <div className="flex items-center gap-2">
- <span className="text-xs text-muted-foreground">
- {t("tasks_view.create.at")}
- </span>
- <input
- type="time"
- className={cn(inputCls, "w-32")}
- value={dailyTime}
- onChange={(e) => setDailyTime(e.target.value)}
- />
- </div>
- )}
- {recurringMode === "custom" && (
- <div className="flex items-center gap-2">
- <span className="text-xs text-muted-foreground">
- {t("tasks_view.create.every")}
- </span>
- <input
- type="number"
- min={1}
- className={cn(inputCls, "w-24")}
- value={customValue}
- onChange={(e) => setCustomValue(Math.max(1, Number(e.target.value)))}
- />
- <Segmented
- size="sm"
- value={customUnit}
- onChange={setCustomUnit}
- options={[
- { id: "minutes", label: t("tasks_view.create.minutes") },
- { id: "hours", label: t("tasks_view.create.hours") },
- ]}
- />
- </div>
- )}
- </div>
- )}
- </div>
- )}
-
- {showAgentConfig && (
- <Field label={t("tasks_view.create.prompt_label")}>
- <textarea
- className={cn(inputCls, "min-h-[96px] resize-y leading-relaxed")}
- value={prompt}
- onChange={(e) => setPrompt(e.target.value)}
- placeholder={t("tasks_view.create.prompt_placeholder")}
- maxLength={16384}
- />
- </Field>
- )}
-
- {showAgentConfig && (
- <>
- {/* Plugins */}
- <div className="space-y-2.5 rounded-xl border border-border/70 bg-background/30 p-4">
- <div className="flex items-center gap-2">
- <Plug className="h-3.5 w-3.5 text-primary" />
- <span className="text-xs font-medium uppercase tracking-wider text-muted-foreground">
- {t("tasks_view.create.plugins_label")}
- </span>
- </div>
- {pluginsLoading ? (
- <p className="text-xs text-muted-foreground">{t("tasks_view.create.plugins_loading")}</p>
- ) : plugins.length === 0 ? (
- <p className="flex items-center gap-1.5 text-xs text-muted-foreground">
- <AlertTriangle className="h-3.5 w-3.5 text-foreground/80" />
- {t("tasks_view.create.plugins_empty")}
- </p>
- ) : (
- <div className="space-y-1.5">
- {plugins.map((p) => {
- const on = p.id in grants;
- return (
- <div
- key={p.id}
- className={cn(
- "flex items-center justify-between rounded-lg border px-3 py-2 transition-colors",
- on ? "border-primary/40 bg-primary/5" : "border-border/60",
- )}
- >
- <div className="flex items-center gap-2.5">
- <Switch checked={on} onCheckedChange={() => togglePlugin(p.id)} />
- {/* A catalog entry without a display name would
- otherwise show its raw id — "google_calendar",
- "youtube_music" — in a list a person reads. */}
- <span className="text-sm">{p.name || humanizeToolName(p.id)}</span>
- </div>
- {on && (
- <Segmented
- size="sm"
- value={grants[p.id]}
- onChange={(s) => setScope(p.id, s)}
- options={SCOPES.map((s) => ({
- id: s,
- label: t(`tasks_view.create.scope_${s}`),
- }))}
- />
- )}
- </div>
- );
- })}
- </div>
- )}
- {hasElevatedGrant && (
- <p className="flex items-start gap-1.5 rounded-lg border border-foreground/30 bg-foreground/5 px-3 py-2 text-xs leading-relaxed text-foreground/90">
- <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0 text-foreground/80" />
- {t("tasks_view.create.unattended_hint")}
- </p>
- )}
- </div>
-
- {/* Model tier */}
- <div className="flex items-center justify-between">
- <span className="text-xs font-medium uppercase tracking-wider text-muted-foreground">
- {t("tasks_view.create.model_label")}
- </span>
- <Segmented
- size="sm"
- value={modelTier}
- onChange={setModelTier}
- options={TIERS.map((tier) => ({
- id: tier,
- label: t(`tasks_view.create.tier_${tier}`),
- }))}
- />
- </div>
- </>
- )}
- </div>
- </div>
-
- {/* Footer */}
- <div className="flex items-center justify-end gap-2 border-t border-border px-6 py-4">
- {createMut.isError && (
- <span className="mr-auto text-xs text-destructive">
- {t("tasks_view.create.save_error")}
- </span>
- )}
- <Button variant="ghost" size="sm" onClick={onClose}>
- {t("tasks_view.create.cancel")}
- </Button>
- <Button
- size="sm"
- disabled={!valid || createMut.isPending}
- onClick={() => createMut.mutate()}
- >
- {createMut.isPending && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}
- {t("tasks_view.create.save")}
- </Button>
- </div>
- </div>
- </div>
- );
-}
diff --git a/jarvis/ui/web/frontend/src/views/tasks/taskSpec.test.ts b/jarvis/ui/web/frontend/src/views/tasks/taskSpec.test.ts
deleted file mode 100644
index a1bdf8a602..0000000000
--- a/jarvis/ui/web/frontend/src/views/tasks/taskSpec.test.ts
+++ /dev/null
@@ -1,206 +0,0 @@
-import { describe, it, expect } from "vitest";
-import {
- buildTaskSpec,
- defaultAtTimeLocal,
- formatWatermarkDate,
- nextDailyOccurrence,
- type TaskDraft,
-} from "./taskSpec";
-
-function baseDraft(over: Partial<TaskDraft> = {}): TaskDraft {
- return {
- title: "My Task",
- prompt: "Do the thing.",
- triggerMode: "schedule",
- scheduleMode: "once",
- onceMode: "delay",
- delaySeconds: 3600,
- atTimeLocal: "",
- recurringMode: "hourly",
- customIntervalSeconds: 1800,
- dailyTime: "07:00",
- modelTier: "auto",
- grants: [],
- whenKey: "mission_succeeded",
- thenKind: "computer_use",
- cuPrompt: "",
- announceText: "",
- ...over,
- };
-}
-
-describe("buildTaskSpec — trigger mapping", () => {
- it("maps once+delay to after_delay", () => {
- const spec = buildTaskSpec(baseDraft({ scheduleMode: "once", onceMode: "delay", delaySeconds: 120 }));
- expect(spec.trigger).toEqual({ type: "after_delay", delay_seconds: 120 });
- });
-
- it("maps once+at_time to at_time with an ISO timestamp", () => {
- const spec = buildTaskSpec(
- baseDraft({ scheduleMode: "once", onceMode: "at_time", atTimeLocal: "2099-01-01T09:30" }),
- );
- expect(spec.trigger.type).toBe("at_time");
- // iso_timestamp must be a parseable absolute timestamp
- expect(new Date((spec.trigger as { iso_timestamp: string }).iso_timestamp).getFullYear()).toBe(2099);
- });
-
- it("maps recurring+hourly to every(3600)", () => {
- const spec = buildTaskSpec(baseDraft({ scheduleMode: "recurring", recurringMode: "hourly" }));
- expect(spec.trigger).toEqual({ type: "every", interval_seconds: 3600 });
- });
-
- it("maps daily to local calendar time with the client IANA timezone", () => {
- const spec = buildTaskSpec(
- baseDraft({ scheduleMode: "recurring", recurringMode: "daily", dailyTime: "07:00" }),
- );
- expect(spec.trigger).toEqual({ type: "calendar", local_time: "07:00", timezone: Intl.DateTimeFormat().resolvedOptions().timeZone });
- });
-
- it("maps recurring+custom to every(customIntervalSeconds)", () => {
- const spec = buildTaskSpec(
- baseDraft({ scheduleMode: "recurring", recurringMode: "custom", customIntervalSeconds: 900 }),
- );
- expect(spec.trigger).toEqual({ type: "every", interval_seconds: 900 });
- });
-});
-
-describe("buildTaskSpec — agent action mapping", () => {
- it("builds an agent action with prompt + grants + tier", () => {
- const spec = buildTaskSpec(
- baseDraft({
- prompt: "Summarize my inbox.",
- modelTier: "deep",
- grants: [
- { plugin_id: "gmail", scope: "read" },
- { plugin_id: "buffer", scope: "write" },
- ],
- }),
- );
- const action = spec.action;
- expect(action.kind).toBe("agent");
- if (action.kind !== "agent") return; // narrow the union
- expect(action.prompt).toBe("Summarize my inbox.");
- expect(action.model_tier).toBe("deep");
- expect(action.plugin_grants).toEqual([
- { plugin_id: "gmail", scope: "read" },
- { plugin_id: "buffer", scope: "write" },
- ]);
- });
-
- it("carries the title through", () => {
- const spec = buildTaskSpec(baseDraft({ title: "Morning Briefing" }));
- expect(spec.title).toBe("Morning Briefing");
- });
-});
-
-describe("buildTaskSpec — When-Then event mapping", () => {
- it("maps a 'mission succeeds → Computer-Use' rule", () => {
- const spec = buildTaskSpec(
- baseDraft({
- triggerMode: "event",
- whenKey: "mission_succeeded",
- thenKind: "computer_use",
- cuPrompt: "Open {result_uri} in the browser",
- announceText: "Your mission is ready.",
- }),
- );
- expect(spec.trigger).toEqual({
- type: "on_event",
- event_name: "MissionCompleted",
- filter_expr: "status == 'approved'",
- max_firings: null,
- });
- const action = spec.action;
- expect(action.kind).toBe("harness_dispatch");
- if (action.kind !== "harness_dispatch") return;
- expect(action.harness).toBe("screenshot");
- expect(action.prompt).toBe("Open {result_uri} in the browser");
- expect(action.allow_computer_use).toBe(true);
- // CU/agent actions carry the announcement as a separate readback field.
- expect(spec.announce_on_success).toBe("Your mission is ready.");
- });
-
- it("maps the failed/cancelled when-keys to the right filter", () => {
- const failed = buildTaskSpec(baseDraft({ triggerMode: "event", whenKey: "mission_failed" }));
- expect((failed.trigger as { filter_expr: string }).filter_expr).toBe("status == 'failed'");
- const cancelled = buildTaskSpec(
- baseDraft({ triggerMode: "event", whenKey: "mission_cancelled" }),
- );
- expect((cancelled.trigger as { filter_expr: string }).filter_expr).toBe(
- "status == 'cancelled'",
- );
- });
-
- it("a 'just notify' rule is a speak action with no separate announce field", () => {
- const spec = buildTaskSpec(
- baseDraft({
- triggerMode: "event",
- thenKind: "notify",
- announceText: "Mission done.",
- }),
- );
- const action = spec.action;
- expect(action.kind).toBe("speak");
- if (action.kind !== "speak") return;
- expect(action.text).toBe("Mission done.");
- expect(spec.announce_on_success).toBeUndefined();
- });
-});
-
-describe("defaultAtTimeLocal", () => {
- it("returns a local datetime-local string one hour ahead, rounded up to the next quarter hour", () => {
- // 13:07 -> +1h = 14:07 -> round up to 14:15
- expect(defaultAtTimeLocal(new Date(2026, 5, 24, 13, 7, 0))).toBe("2026-06-24T14:15");
- });
-
- it("rolls the hour over when rounding crosses the top of the hour", () => {
- // 13:52 -> +1h = 14:52 -> round up to 15:00
- expect(defaultAtTimeLocal(new Date(2026, 5, 24, 13, 52, 0))).toBe("2026-06-24T15:00");
- });
-
- it("leaves a value already on a quarter hour unchanged", () => {
- // 13:00 -> +1h = 14:00 -> already aligned
- expect(defaultAtTimeLocal(new Date(2026, 5, 24, 13, 0, 0))).toBe("2026-06-24T14:00");
- });
-
- it("always emits a full, non-empty datetime-local shape (never the native placeholder)", () => {
- const out = defaultAtTimeLocal(new Date(2026, 5, 24, 13, 7));
- expect(out).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/);
- expect(out.length).toBe(16);
- });
-});
-
-describe("formatWatermarkDate", () => {
- it("writes the selected date long-form in English", () => {
- const out = formatWatermarkDate("2026-06-24T15:30", "en");
- expect(out).toContain("June");
- expect(out).toContain("24");
- });
-
- it("localizes the same date to German", () => {
- const out = formatWatermarkDate("2026-06-24T15:30", "de");
- expect(out).toContain("Juni");
- expect(out).toContain("24");
- });
-
- it("falls back to `now` for an empty / unparseable field value", () => {
- const out = formatWatermarkDate("", "en", new Date(2026, 5, 24, 9, 0));
- expect(out).toContain("June");
- expect(out).toContain("24");
- });
-});
-
-describe("nextDailyOccurrence", () => {
- it("returns today's time when it is still in the future", () => {
- const now = new Date("2026-06-17T05:00:00");
- const iso = nextDailyOccurrence("07:00", now);
- expect(new Date(iso).getTime()).toBeGreaterThan(now.getTime());
- expect(new Date(iso).getDate()).toBe(17);
- });
-
- it("rolls over to tomorrow when the time already passed", () => {
- const now = new Date("2026-06-17T09:00:00");
- const iso = nextDailyOccurrence("07:00", now);
- expect(new Date(iso).getDate()).toBe(18);
- });
-});
diff --git a/jarvis/ui/web/frontend/src/views/tasks/taskSpec.ts b/jarvis/ui/web/frontend/src/views/tasks/taskSpec.ts
deleted file mode 100644
index f7439df129..0000000000
--- a/jarvis/ui/web/frontend/src/views/tasks/taskSpec.ts
+++ /dev/null
@@ -1,257 +0,0 @@
-import { DEFAULT_MANUAL_SOURCE, type SourceSettings } from "@/lib/sourceTypes";
-/**
- * Pure mapping from the create-form draft to the backend TaskSpec payload.
- *
- * Kept free of React so the schedule/action translation (the part that is
- * easy to get wrong) is unit-testable in isolation. Mirrors the Pydantic
- * schema in jarvis/tasks/schema.py (trigger + agent action + plugin grants).
- */
-
-export type ScopeValue = "read" | "write" | "full";
-export type ModelTier = "fast" | "deep" | "auto";
-
-export interface DraftPluginGrant {
- plugin_id: string;
- scope: ScopeValue;
-}
-
-/** Curated "when" events for the When-Then builder. Each maps onto one bus
- * event class plus a filter_expr — the user never sees raw event names. */
-export type WhenKey =
- | "mission_succeeded"
- | "mission_failed"
- | "mission_cancelled";
-
-/** The "then" action a When-Then rule runs. */
-export type ThenKind = "computer_use" | "agent" | "notify";
-
-export interface TaskDraft {
- title: string;
- prompt: string;
- // Top-level: a time-based schedule vs. an event-driven When-Then rule.
- triggerMode: "schedule" | "event" | "source";
- sourceTrigger?: TaskTrigger;
- scheduleMode: "once" | "recurring";
- onceMode: "delay" | "at_time";
- delaySeconds: number;
- atTimeLocal: string; // value of <input type="datetime-local">
- recurringMode: "hourly" | "daily" | "custom";
- customIntervalSeconds: number;
- dailyTime: string; // "HH:MM"
- modelTier: ModelTier;
- grants: DraftPluginGrant[];
- // When-Then fields (only meaningful when triggerMode === "event").
- whenKey: WhenKey;
- thenKind: ThenKind;
- cuPrompt: string; // Computer-Use goal, supports {result_uri} placeholders
- announceText: string; // spoken confirmation after the action finishes
-}
-
-export interface HookOptions { conditions?: Record<string, string | number | boolean | null>; max_firings?: number | null; cooldown_seconds?: number; }
-
-export type TaskTrigger =
- | ({ type: "source"; source: SourceSettings } & HookOptions)
- | { type: "cron"; expression: string; timezone: string }
- | ({ type: "webhook" } & HookOptions)
- | ({ type: "event_hook"; event_name: string } & HookOptions)
- | { type: "after_delay"; delay_seconds: number }
- | { type: "at_time"; iso_timestamp: string }
- | { type: "calendar"; local_time: string; timezone: string; weekdays?: number[]; month_days?: number[]; months?: number[]; start_date?: string }
- | { type: "every"; interval_seconds: number; start_at?: string }
- | {
- type: "on_event";
- event_name: string;
- filter_expr?: string | null;
- max_firings?: number | null;
- };
-
-export interface AgentActionPayload {
- kind: "agent";
- prompt: string;
- plugin_grants: DraftPluginGrant[];
- model_tier: ModelTier;
-}
-
-export interface HarnessDispatchActionPayload {
- kind: "harness_dispatch";
- harness: string;
- prompt: string;
- allow_computer_use: boolean;
-}
-
-export interface SpeakActionPayload {
- kind: "speak";
- text: string;
-}
-
-export type TaskActionPayload =
- | AgentActionPayload
- | HarnessDispatchActionPayload
- | SpeakActionPayload;
-
-export interface TaskSpecPayload {
- title: string;
- trigger: TaskTrigger;
- action: TaskActionPayload;
- announce_on_success?: string;
- announce_on_failure?: string;
-}
-
-/** Curated "when" → (event class, filter) mapping. The single place that knows
- * a mission outcome is a `MissionCompleted` filtered by `status`. */
-export const WHEN_FILTERS: Record<WhenKey, string> = {
- mission_succeeded: "status == 'approved'",
- mission_failed: "status == 'failed'",
- mission_cancelled: "status == 'cancelled'",
-};
-
-/** The CU harness name a Computer-Use "then" action dispatches to. */
-export const CU_HARNESS = "screenshot";
-
-function pad2(n: number): string {
- return String(n).padStart(2, "0");
-}
-
-/**
- * A sensible default for the "at date/time" picker, formatted for an
- * `<input type="datetime-local">` (local wall-clock "YYYY-MM-DDTHH:mm", never
- * UTC): one hour from now, rounded up to the next quarter hour.
- *
- * Pre-filling the field is what kills the browser's raw, locale-ugly empty
- * placeholder ("TT.mm.jjjj --:--" on a German system) — a freshly opened
- * picker now shows a real, editable value instead of dead grey hint text.
- */
-export function defaultAtTimeLocal(now: Date = new Date()): string {
- const d = new Date(now.getTime() + 60 * 60 * 1000);
- // setMinutes carries overflow: 60 rolls into the next hour cleanly.
- d.setMinutes(Math.ceil(d.getMinutes() / 15) * 15, 0, 0);
- return (
- `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}` +
- `T${pad2(d.getHours())}:${pad2(d.getMinutes())}`
- );
-}
-
-/**
- * The selected date written out long-form for the dialog's faint background
- * watermark — e.g. "Wednesday, 24 June" / "Mittwoch, 24. Juni". Locale-aware,
- * date only (the time already shows inside the input, so the watermark stays
- * calm). Falls back to `now` for an unparseable field value, and to the "en"
- * locale if the requested one is unavailable in the runtime's ICU data.
- */
-export function formatWatermarkDate(
- atTimeLocal: string,
- locale: string,
- now: Date = new Date(),
-): string {
- const parsed = atTimeLocal ? new Date(atTimeLocal) : now;
- const d = Number.isNaN(parsed.getTime()) ? now : parsed;
- const opts: Intl.DateTimeFormatOptions = {
- weekday: "long",
- day: "numeric",
- month: "long",
- };
- try {
- return new Intl.DateTimeFormat(locale, opts).format(d);
- } catch {
- return new Intl.DateTimeFormat("en", opts).format(d);
- }
-}
-
-/** Next absolute occurrence of an "HH:MM" wall-clock time, as an ISO string. */
-export function nextDailyOccurrence(timeHHMM: string, now: Date): string {
- const [h, m] = timeHHMM.split(":").map((x) => parseInt(x, 10));
- const d = new Date(now);
- d.setHours(Number.isFinite(h) ? h : 0, Number.isFinite(m) ? m : 0, 0, 0);
- if (d.getTime() <= now.getTime()) {
- d.setDate(d.getDate() + 1);
- }
- return d.toISOString();
-}
-
-/** A When-Then event trigger: a `MissionCompleted` filtered by the curated
- * `whenKey`. A standing rule (max_firings null) — it fires for every matching
- * mission until the user deletes it. */
-export function buildEventTrigger(draft: TaskDraft): TaskTrigger {
- return {
- type: "on_event",
- event_name: "MissionCompleted",
- filter_expr: WHEN_FILTERS[draft.whenKey] ?? null,
- max_firings: null,
- };
-}
-
-export function buildTrigger(draft: TaskDraft, _now: Date = new Date()): TaskTrigger {
- if (draft.triggerMode === "source") return draft.sourceTrigger ?? { type: "source", source: DEFAULT_MANUAL_SOURCE };
- if (draft.triggerMode === "event") {
- return buildEventTrigger(draft);
- }
- if (draft.scheduleMode === "once") {
- if (draft.onceMode === "at_time") {
- return { type: "at_time", iso_timestamp: new Date(draft.atTimeLocal).toISOString() };
- }
- return { type: "after_delay", delay_seconds: draft.delaySeconds };
- }
- // recurring
- if (draft.recurringMode === "hourly") {
- return { type: "every", interval_seconds: 3600 };
- }
- if (draft.recurringMode === "daily") {
- return {
- type: "calendar",
- local_time: draft.dailyTime,
- timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
- };
- }
- return { type: "every", interval_seconds: draft.customIntervalSeconds };
-}
-
-/** The "then" action for a When-Then rule, derived from the chosen `thenKind`.
- * Computer-Use dispatches to the CU harness; "agent" runs a brain turn; "notify"
- * speaks the announcement as its sole action. */
-export function buildEventAction(draft: TaskDraft): TaskActionPayload {
- if (draft.thenKind === "computer_use") {
- return {
- kind: "harness_dispatch",
- harness: CU_HARNESS,
- prompt: draft.cuPrompt.trim() || "Open the mission result in the browser.",
- allow_computer_use: true,
- };
- }
- if (draft.thenKind === "agent") {
- return {
- kind: "agent",
- prompt: draft.prompt.trim(),
- plugin_grants: draft.grants,
- model_tier: draft.modelTier,
- };
- }
- // "notify" — the spoken confirmation IS the action.
- return { kind: "speak", text: draft.announceText.trim() || "Done." };
-}
-
-export function buildTaskSpec(draft: TaskDraft, now: Date = new Date()): TaskSpecPayload {
- if (draft.triggerMode === "event") {
- const spec: TaskSpecPayload = {
- title: draft.title.trim(),
- trigger: buildTrigger(draft, now),
- action: buildEventAction(draft),
- };
- // For CU/agent actions the announcement is a separate post-action readback;
- // for "notify" the speak action already says it, so no announce field.
- const announce = draft.announceText.trim();
- if (draft.thenKind !== "notify" && announce) {
- spec.announce_on_success = announce;
- }
- return spec;
- }
- return {
- title: draft.title.trim(),
- trigger: buildTrigger(draft, now),
- action: {
- kind: "agent",
- prompt: draft.prompt.trim(),
- plugin_grants: draft.grants,
- model_tier: draft.modelTier,
- },
- };
-}
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index b0860bb18b..28b06a635f 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -3373,6 +3373,12 @@ class WebServer:
"TaskStack: cleaned up {} interrupted tasks from the previous run",
recovered,
)
+ retired = await store.retire_catalogue_tasks()
+ if retired:
+ logger.info(
+ "TaskStack: cancelled {} schedules from the retired automations catalogue",
+ retired,
+ )
# Wire the brain so agentic (`agent`) tasks can run a tool-restricted
# turn unattended. app.state.brain is set before server.start() (see
diff --git a/jarvis/ui/web/tasks_routes.py b/jarvis/ui/web/tasks_routes.py
index 92620f8ba2..833522dc80 100644
--- a/jarvis/ui/web/tasks_routes.py
+++ b/jarvis/ui/web/tasks_routes.py
@@ -1,8 +1,9 @@
-"""REST API for the task queue (Phase 5 Capability 4) — the Automations section.
+"""REST API for the task queue (Phase 5 Capability 4) — the engine under agent routines.
+
+Agent routines (``jarvis/society/routines.py``) are tagged tasks; the agent
+card reads and drives them through these endpoints.
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.
@@ -14,11 +15,11 @@ Endpoints:
The router expects a ``TaskStore`` + ``TaskScheduler`` on
``app.state.task_store`` resp. ``app.state.task_scheduler`` — these are
set by the DesktopApp at startup. If neither is set, the endpoints answer
-with ``503`` (Service Unavailable). Template readiness reads the live tool
-names from ``app.state.brain`` when it exists.
+with ``503`` (Service Unavailable).
-Route order matters: the ``/templates`` routes are registered BEFORE the
-``/{task_id}`` routes so "templates" is never captured as a task id.
+Route order matters: the fixed-path routes (``/client-timezone``) are
+registered BEFORE the ``/{task_id}`` routes so they are never captured as a
+task id.
"""
from __future__ import annotations
@@ -29,7 +30,6 @@ from typing import Any
from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel, ConfigDict, Field
-from jarvis.tasks import templates as tpl
from jarvis.tasks.scheduler import TaskNotFound, TaskStateConflict
from jarvis.tasks.schema import PAUSABLE_TRIGGER_TYPES, TERMINAL_STATES, TaskSpec
@@ -58,22 +58,6 @@ def _require_scheduler(request: Request) -> Any:
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.
@@ -133,65 +117,6 @@ def _row_to_summary(
}
-# ----------------------------------------------------------------------
-# 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)
- try:
- if scheduler is not None:
- task_id = await scheduler.schedule(spec)
- else:
- task_id = await store.insert(spec)
- except ValueError as exc:
- raise HTTPException(422, str(exc)) from exc
- return {"id": task_id}
-
-
class ClientTimezoneBody(BaseModel):
model_config = ConfigDict(extra="forbid")
timezone: str = Field(min_length=1, max_length=100)
diff --git a/scripts/ci/german-allowlist.txt b/scripts/ci/german-allowlist.txt
index 7fb3d84903..d4bf378918 100644
--- a/scripts/ci/german-allowlist.txt
+++ b/scripts/ci/german-allowlist.txt
@@ -453,10 +453,6 @@ docs/commands-reference.md
jarvis/brain/artifact_gate.py
tests/unit/brain/test_artifact_tool_hide.py
-# --- Automation templates (2026-08-24): localized card copy (en/de/es) lives
-# next to each template so ten authors never edit one shared i18n file ---
-jarvis/tasks/templates/*
-
# --- Dictation Prompt Mode (2026-08-27): the worked de/en example pair in the
# system prompt and the closed thanks pool are product output, plus the
# fixtures that pin them ---
diff --git a/tests/contract/test_calendar_routines.py b/tests/contract/test_calendar_routines.py
index d1841b25b7..aed0f58736 100644
--- a/tests/contract/test_calendar_routines.py
+++ b/tests/contract/test_calendar_routines.py
@@ -202,7 +202,8 @@ def test_calendar_contract_reaches_sql_api_and_typescript():
assert "calendar" in TRIGGER_TYPES and "calendar" in PAUSABLE_TRIGGER_TYPES
assert "'calendar'" in SCHEMA_FILE.read_text(encoding="utf-8")
root = Path(__file__).resolve().parents[2]
- typescript = (root / "jarvis/ui/web/frontend/src/views/tasks/taskSpec.ts").read_text(
+ # The agent card describes a routine's calendar trigger from these fields.
+ typescript = (root / "jarvis/ui/web/frontend/src/lib/triggerDescription.ts").read_text(
encoding="utf-8"
)
for field in (
@@ -212,7 +213,6 @@ def test_calendar_contract_reaches_sql_api_and_typescript():
"weekdays",
"month_days",
"months",
- "start_date",
):
assert field in typescript
diff --git a/tests/unit/brain/test_navigation_intent.py b/tests/unit/brain/test_navigation_intent.py
index ea76c940fd..bd0019e340 100644
--- a/tests/unit/brain/test_navigation_intent.py
+++ b/tests/unit/brain/test_navigation_intent.py
@@ -20,7 +20,7 @@ from jarvis.brain.navigation_intent import match_navigation_intent
("zeig die Socials", "socials"),
("zeige mir die Socials", "socials"),
("öffne die Einstellungen", "settings"),
- ("geh zu den Aufgaben", "tasks"),
+ ("geh zu den Aufgaben", "agents"),
("wechsel zu den Notizen", "memory"),
("show the agents", "agents"),
("open settings", "settings"),
@@ -100,7 +100,7 @@ def test_unbound_cue_and_section_do_not_navigate(text: str) -> None:
[
# An article and a filler between verb and target still binds.
("zeig mir doch bitte die Einstellungen", "settings"),
- ("geh zu den offenen Aufgaben", "tasks"),
+ ("geh zu den offenen Aufgaben", "agents"),
("open the settings", "settings"),
],
)
diff --git a/tests/unit/ci/test_pipeline_scripts.py b/tests/unit/ci/test_pipeline_scripts.py
index b65f2d6442..5e00e23c73 100644
--- a/tests/unit/ci/test_pipeline_scripts.py
+++ b/tests/unit/ci/test_pipeline_scripts.py
@@ -35,7 +35,7 @@ def test_pipeline_change_runs_everything():
def test_frontend_source_change_keeps_python_on_because_tests_read_it():
- result = classify_changes.classify(["jarvis/ui/web/frontend/src/views/tasks/taskSpec.ts"])
+ result = classify_changes.classify(["jarvis/ui/web/frontend/src/lib/tasksApi.ts"])
assert result["frontend"] is True
assert result["python"] is True
assert result["realtime"] is False
diff --git a/tests/unit/plugins/tool/test_navigate.py b/tests/unit/plugins/tool/test_navigate.py
index 89ae90b202..dbc6824e5e 100644
--- a/tests/unit/plugins/tool/test_navigate.py
+++ b/tests/unit/plugins/tool/test_navigate.py
@@ -59,7 +59,9 @@ async def test_canonical_id_publishes_navigate(tool: NavigateTool, bus: Recordin
("settings", "settings"),
("agenten", "agents"),
("sub-agents", "agents"),
- ("Aufgaben", "tasks"),
+ # The retired Automations section: scheduled work lives on agents.
+ ("Aufgaben", "agents"),
+ ("tasks", "agents"),
("notizen", "memory"),
("Kontakte", "contacts"),
("kontakt", "contacts"),
diff --git a/tests/unit/tasks/templates/__init__.py b/tests/unit/tasks/templates/__init__.py
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/tests/unit/tasks/templates/test_ai_news_digest.py b/tests/unit/tasks/templates/test_ai_news_digest.py
deleted file mode 100644
index 46038e2cde..0000000000
--- a/tests/unit/tasks/templates/test_ai_news_digest.py
+++ /dev/null
@@ -1,85 +0,0 @@
-"""The ``ai_news_digest`` automation template — validates, builds a spec,
-renders its prompt, and is discoverable through the catalogue."""
-from __future__ import annotations
-
-from datetime import datetime
-
-from jarvis.tasks.schema import TriggerEvery
-from jarvis.tasks.templates import (
- LOCALES,
- all_templates,
- build_spec,
- missing_requirements,
- render_prompt,
-)
-from jarvis.tasks.templates.ai_news_digest import TEMPLATE
-
-_DEFAULT_FOCUS = "model releases, open-source models, AI research, AI funding"
-
-
-def test_identity_and_catalogue_placement() -> None:
- assert TEMPLATE.key == "ai_news_digest"
- assert TEMPLATE.category == "news"
- assert TEMPLATE.icon == "bot"
- assert TEMPLATE.schedule.kind == "daily"
- assert TEMPLATE.schedule.time == "08:00"
-
-
-def test_discovered_by_catalogue() -> None:
- assert all_templates(refresh=True)["ai_news_digest"] is TEMPLATE
-
-
-def test_copy_present_in_every_locale() -> None:
- for locale in LOCALES:
- assert TEMPLATE.name.for_locale(locale).strip()
- assert TEMPLATE.description.for_locale(locale).strip()
- for inp in TEMPLATE.inputs:
- assert inp.label.for_locale(locale).strip()
- assert TEMPLATE.name.for_locale("en") == "AI News Digest"
-
-
-def test_requires_is_subset_of_grants_and_read_only() -> None:
- granted = {g.plugin_id for g in TEMPLATE.plugin_grants}
- assert set(TEMPLATE.requires) <= granted
- assert granted == {"search_web"}
- assert all(g.scope == "read" for g in TEMPLATE.plugin_grants)
-
-
-def test_readiness_against_live_tools() -> None:
- assert missing_requirements(TEMPLATE.requires, ["search_web", "gmail"]) == []
- assert missing_requirements(TEMPLATE.requires, ["gmail"]) == ["search_web"]
-
-
-def test_prompt_renders_default_focus_and_leaves_no_placeholder() -> None:
- text = render_prompt(TEMPLATE, None)
- assert _DEFAULT_FOCUS in text
- assert "{focus}" not in text
- custom = render_prompt(TEMPLATE, {"focus": "robotics"})
- assert "robotics" in custom
- assert _DEFAULT_FOCUS not in custom
-
-
-def test_prompt_states_the_contract() -> None:
- text = TEMPLATE.prompt
- assert "search_web" in text
- assert "at most 6" in text
- assert "48" in text
- assert "no emojis" in text
- assert "configured output language" in text
- assert "no preamble" in text
-
-
-def test_build_spec_without_inputs() -> None:
- now = datetime(2026, 8, 24, 9, 30)
- spec = build_spec(TEMPLATE, locale="de", now=now)
- assert spec.title == "KI-News-Digest"
- assert spec.created_by == "template"
- assert "template:ai_news_digest" in spec.tags
- assert spec.action.kind == "agent"
- assert spec.action.plugin_grants == TEMPLATE.plugin_grants
- assert _DEFAULT_FOCUS in spec.action.prompt
- assert isinstance(spec.trigger, TriggerEvery)
- assert spec.trigger.interval_seconds == 86_400
- # 09:30 is past 08:00, so the first run is tomorrow at 08:00.
- assert spec.trigger.start_at == "2026-08-25T08:00:00"
- assert spec.model_dump(mode="json")["action"]["prompt"] == spec.action.prompt
diff --git a/tests/unit/tasks/templates/test_daily_planner.py b/tests/unit/tasks/templates/test_daily_planner.py
deleted file mode 100644
index b9f14fcc51..0000000000
--- a/tests/unit/tasks/templates/test_daily_planner.py
+++ /dev/null
@@ -1,68 +0,0 @@
-"""The ``daily_planner`` automation template validates, renders and builds a spec."""
-from __future__ import annotations
-
-from datetime import datetime
-
-from jarvis.tasks.templates import (
- LOCALES,
- AutomationTemplate,
- all_templates,
- build_spec,
- render_prompt,
-)
-from jarvis.tasks.templates.daily_planner import TEMPLATE
-
-
-def test_template_is_discovered_and_well_formed() -> None:
- assert isinstance(TEMPLATE, AutomationTemplate)
- assert all_templates(refresh=True)["daily_planner"] is TEMPLATE
- assert TEMPLATE.category == "productivity"
- assert TEMPLATE.icon == "calendar-check"
- assert TEMPLATE.schedule.kind == "daily"
- assert TEMPLATE.schedule.time == "08:30"
-
-
-def test_all_locales_present() -> None:
- for locale in LOCALES:
- assert TEMPLATE.name.for_locale(locale)
- assert TEMPLATE.description.for_locale(locale)
- for inp in TEMPLATE.inputs:
- assert inp.label.for_locale(locale)
- assert inp.placeholder is not None and inp.placeholder.for_locale(locale)
-
-
-def test_requires_is_subset_of_grants_and_read_only() -> None:
- granted = {g.plugin_id for g in TEMPLATE.plugin_grants}
- assert set(TEMPLATE.requires) <= granted
- assert TEMPLATE.requires == ("google_calendar",)
- assert granted == {"google_calendar", "gmail"}
- assert all(g.scope == "read" for g in TEMPLATE.plugin_grants)
-
-
-def test_prompt_renders_default_work_hours() -> None:
- rendered = render_prompt(TEMPLATE, None)
- assert "09:00-18:00" in rendered
- assert "{work_hours}" not in rendered
- assert "list_events" in rendered
- assert "list_messages" in rendered
- assert "calendar is empty" in rendered
-
-
-def test_prompt_renders_custom_work_hours() -> None:
- rendered = render_prompt(TEMPLATE, {"work_hours": "08:00-16:00"})
- assert "08:00-16:00" in rendered
- assert "09:00-18:00" not in rendered
-
-
-def test_build_spec_builds_daily_agent_task_without_inputs() -> None:
- now = datetime(2026, 8, 24, 9, 0)
- spec = build_spec(TEMPLATE, inputs={}, locale="de", now=now)
- assert spec.created_by == "template"
- assert "template:daily_planner" in spec.tags
- assert spec.title == "Tagesplaner" # i18n-allow
- assert spec.trigger.type == "every"
- assert spec.trigger.interval_seconds == 86_400
- assert spec.trigger.start_at == "2026-08-25T08:30:00"
- assert spec.action.kind == "agent"
- assert "09:00-18:00" in spec.action.prompt
- assert spec.action.plugin_grants == TEMPLATE.plugin_grants
diff --git a/tests/unit/tasks/templates/test_inbox_brief.py b/tests/unit/tasks/templates/test_inbox_brief.py
deleted file mode 100644
index 19102c6796..0000000000
--- a/tests/unit/tasks/templates/test_inbox_brief.py
+++ /dev/null
@@ -1,71 +0,0 @@
-"""The ``inbox_brief`` automation template validates, renders and builds a spec."""
-from __future__ import annotations
-
-from datetime import datetime
-
-from jarvis.tasks.templates import (
- LOCALES,
- AutomationTemplate,
- all_templates,
- build_spec,
- render_prompt,
-)
-from jarvis.tasks.templates.inbox_brief import TEMPLATE
-
-
-def test_template_is_discovered_and_well_formed() -> None:
- assert isinstance(TEMPLATE, AutomationTemplate)
- assert all_templates(refresh=True)["inbox_brief"] is TEMPLATE
- assert TEMPLATE.category == "productivity"
- assert TEMPLATE.icon == "mail"
- assert TEMPLATE.schedule.kind == "daily"
- assert TEMPLATE.schedule.time == "09:00"
-
-
-def test_all_locales_present() -> None:
- for locale in LOCALES:
- assert TEMPLATE.name.for_locale(locale)
- assert TEMPLATE.description.for_locale(locale)
- for inp in TEMPLATE.inputs:
- assert inp.label.for_locale(locale)
- assert inp.placeholder is not None and inp.placeholder.for_locale(locale)
-
-
-def test_requires_is_subset_of_read_only_gmail_grant() -> None:
- granted = {g.plugin_id for g in TEMPLATE.plugin_grants}
- assert set(TEMPLATE.requires) <= granted
- assert granted == {"gmail"}
- # The brief never sends — a read grant is all it may ever hold.
- assert all(g.scope == "read" for g in TEMPLATE.plugin_grants)
-
-
-def test_prompt_renders_lookback_and_keeps_output_rules() -> None:
- default = render_prompt(TEMPLATE, None)
- assert "newer_than:24h" in default
- custom = render_prompt(TEMPLATE, {"lookback_hours": "48"})
- assert "newer_than:48h" in custom
- assert "{lookback_hours}" not in custom
- assert "list_messages" in custom
- assert "get_message" in custom
- # list_messages returns ids only (gmail_rest.py), so the prompt must
- # force a get_message per id and pre-filter noise in the query itself.
- assert "EVERY id" in custom
- assert "-category:promotions" in custom
- assert "send" in custom and "never send" in custom
- assert "Maximum 8 lines" in custom
- assert "No emojis" in custom
- assert "inbox is clear" in custom
-
-
-def test_build_spec_builds_daily_agent_task_without_inputs() -> None:
- now = datetime(2026, 8, 24, 12, 0)
- spec = build_spec(TEMPLATE, locale="de", now=now)
- assert spec.created_by == "template"
- assert "template:inbox_brief" in spec.tags
- assert spec.title == "Posteingang-Briefing" # i18n-allow
- assert spec.trigger.type == "every"
- assert spec.trigger.interval_seconds == 86_400
- assert spec.trigger.start_at == "2026-08-25T09:00:00"
- assert spec.action.kind == "agent"
- assert "newer_than:24h" in spec.action.prompt
- assert spec.action.plugin_grants == TEMPLATE.plugin_grants
diff --git a/tests/unit/tasks/templates/test_memory_recap.py b/tests/unit/tasks/templates/test_memory_recap.py
deleted file mode 100644
index 2f5333eedf..0000000000
--- a/tests/unit/tasks/templates/test_memory_recap.py
+++ /dev/null
@@ -1,86 +0,0 @@
-"""The ``memory_recap`` automation template validates, renders and builds a spec."""
-from __future__ import annotations
-
-from datetime import datetime
-
-from jarvis.tasks.templates import (
- LOCALES,
- AutomationTemplate,
- all_templates,
- build_spec,
- missing_requirements,
- render_prompt,
-)
-from jarvis.tasks.templates.memory_recap import TEMPLATE
-
-_LOCAL_MEMORY_TOOLS = ("wiki-recall", "wiki-list", "wiki-page-read")
-
-
-def test_template_is_discovered_and_well_formed() -> None:
- assert isinstance(TEMPLATE, AutomationTemplate)
- assert all_templates(refresh=True)["memory_recap"] is TEMPLATE
- assert TEMPLATE.category == "research"
- assert TEMPLATE.icon == "brain"
- assert TEMPLATE.schedule.kind == "weekly"
- assert TEMPLATE.schedule.weekday == 6 # Sunday
- assert TEMPLATE.schedule.time == "18:00"
- assert TEMPLATE.inputs == ()
-
-
-def test_all_locales_present() -> None:
- for locale in LOCALES:
- assert TEMPLATE.name.for_locale(locale)
- assert TEMPLATE.description.for_locale(locale)
-
-
-def test_description_says_it_works_offline_without_a_key() -> None:
- en = TEMPLATE.description.en.lower()
- assert "offline" in en
- assert "key" in en
- assert "offline" in TEMPLATE.description.de.lower()
- assert "sin conexión" in TEMPLATE.description.es.lower()
-
-
-def test_requires_is_subset_of_grants_and_all_read_only() -> None:
- granted = {g.plugin_id for g in TEMPLATE.plugin_grants}
- assert set(TEMPLATE.requires) <= granted
- assert granted == set(_LOCAL_MEMORY_TOOLS)
- assert TEMPLATE.requires == ("wiki-recall",)
- assert all(g.scope == "read" for g in TEMPLATE.plugin_grants)
-
-
-def test_only_local_tools_no_external_dependency() -> None:
- # Ready on a box that has nothing but the local memory tools.
- assert missing_requirements(TEMPLATE.requires, ["wiki-recall"]) == []
- # Not ready when the memory tool is absent.
- assert missing_requirements(TEMPLATE.requires, ["search_web"]) == ["wiki-recall"]
- for external in ("search_web", "gmail", "google_calendar", "github"):
- assert external not in {g.plugin_id for g in TEMPLATE.plugin_grants}
-
-
-def test_prompt_renders_without_placeholders() -> None:
- rendered = render_prompt(TEMPLATE, None)
- assert rendered == TEMPLATE.prompt
- assert "{" not in rendered and "}" not in rendered
- for tool in _LOCAL_MEMORY_TOOLS:
- assert tool in rendered
- assert "7 days" in rendered
- assert "3 to 5 themes" in rendered
- assert "12 lines" in rendered
- assert "configured output language" in rendered
- assert "no emojis" in rendered
- assert "memory is empty" in rendered
-
-
-def test_build_spec_builds_weekly_sunday_agent_task() -> None:
- now = datetime(2026, 8, 19, 12, 0) # a Wednesday
- spec = build_spec(TEMPLATE, locale="de", now=now)
- assert spec.created_by == "template"
- assert "template:memory_recap" in spec.tags
- assert spec.title == "Gedächtnis-Rückblick" # i18n-allow
- assert spec.trigger.type == "every"
- assert spec.trigger.interval_seconds == 7 * 86_400
- assert spec.trigger.start_at == "2026-08-23T18:00:00"
- assert spec.action.kind == "agent"
- assert spec.action.prompt == TEMPLATE.prompt
- assert spec.action.plugin_grants == TEMPLATE.plugin_grants
diff --git a/tests/unit/tasks/templates/test_morning_brief.py b/tests/unit/tasks/templates/test_morning_brief.py
deleted file mode 100644
index dae1ff4eea..0000000000
--- a/tests/unit/tasks/templates/test_morning_brief.py
+++ /dev/null
@@ -1,77 +0,0 @@
-"""The ``morning_brief`` automation template validates, renders and builds a spec."""
-from __future__ import annotations
-
-from datetime import datetime
-
-from jarvis.tasks.templates import (
- LOCALES,
- AutomationTemplate,
- all_templates,
- build_spec,
- render_prompt,
-)
-from jarvis.tasks.templates.morning_brief import TEMPLATE
-
-
-def test_template_is_discovered_and_well_formed() -> None:
- assert isinstance(TEMPLATE, AutomationTemplate)
- assert all_templates(refresh=True)["morning_brief"] is TEMPLATE
- assert TEMPLATE.category == "news"
- assert TEMPLATE.icon == "sun"
- assert TEMPLATE.schedule.kind == "daily"
- assert TEMPLATE.schedule.time == "07:30"
-
-
-def test_all_locales_present() -> None:
- for locale in LOCALES:
- assert TEMPLATE.name.for_locale(locale)
- assert TEMPLATE.description.for_locale(locale)
- for inp in TEMPLATE.inputs:
- assert inp.label.for_locale(locale)
- assert inp.placeholder is not None and inp.placeholder.for_locale(locale)
-
-
-def test_requires_is_subset_of_grants() -> None:
- granted = {g.plugin_id for g in TEMPLATE.plugin_grants}
- assert set(TEMPLATE.requires) <= granted
- assert granted == {"search_web"}
- assert all(g.scope == "read" for g in TEMPLATE.plugin_grants)
-
-
-def test_inputs_are_optional_with_sane_defaults() -> None:
- by_key = {i.key: i for i in TEMPLATE.inputs}
- assert set(by_key) == {"city", "interests"}
- assert not by_key["city"].required and by_key["city"].default == ""
- assert not by_key["interests"].required
- assert by_key["interests"].default == "world news, technology, business"
-
-
-def test_prompt_renders_inputs_and_keeps_the_weather_conditional() -> None:
- rendered = render_prompt(TEMPLATE, {"city": "Hamburg", "interests": "AI, football"})
- assert 'City for the weather: "Hamburg"' in rendered
- assert "morning brief for AI, football" in rendered
- assert "{city}" not in rendered and "{interests}" not in rendered
- # The prompt tells the agent how to call the tool and how to stay honest.
- assert "search_web" in rendered
- assert "never pick or guess a city" in rendered
- assert "output language" in rendered
-
-
-def test_prompt_without_city_leaves_the_field_empty_not_invented() -> None:
- rendered = render_prompt(TEMPLATE, {})
- assert 'City for the weather: ""' in rendered
- assert "world news, technology, business" in rendered
-
-
-def test_build_spec_produces_a_daily_agent_task() -> None:
- now = datetime(2026, 8, 24, 9, 0, 0)
- spec = build_spec(TEMPLATE, inputs={"city": "Berlin"}, locale="de", now=now)
- assert spec.title == "Morgen-Briefing" # i18n-allow
- assert spec.created_by == "template"
- assert "template:morning_brief" in spec.tags
- assert spec.trigger.type == "every"
- assert spec.trigger.interval_seconds == 86_400
- assert spec.trigger.start_at == "2026-08-25T07:30:00"
- assert spec.action.kind == "agent"
- assert 'City for the weather: "Berlin"' in spec.action.prompt
- assert [g.plugin_id for g in spec.action.plugin_grants] == ["search_web"]
diff --git a/tests/unit/tasks/templates/test_repo_pulse.py b/tests/unit/tasks/templates/test_repo_pulse.py
deleted file mode 100644
index 80b8fdabbb..0000000000
--- a/tests/unit/tasks/templates/test_repo_pulse.py
+++ /dev/null
@@ -1,83 +0,0 @@
-"""The ``repo_pulse`` automation template validates, renders and builds a spec."""
-from __future__ import annotations
-
-from datetime import datetime
-
-import pytest
-
-from jarvis.tasks.templates import (
- LOCALES,
- AutomationTemplate,
- all_templates,
- build_spec,
- grant_matches,
- missing_requirements,
- render_prompt,
-)
-from jarvis.tasks.templates.repo_pulse import TEMPLATE
-
-
-def test_template_is_discovered_and_well_formed() -> None:
- assert isinstance(TEMPLATE, AutomationTemplate)
- assert all_templates(refresh=True)["repo_pulse"] is TEMPLATE
- assert TEMPLATE.category == "developer"
- assert TEMPLATE.icon == "git-branch"
- assert TEMPLATE.schedule.kind == "daily"
- assert TEMPLATE.schedule.time == "09:00"
-
-
-def test_all_locales_present() -> None:
- for locale in LOCALES:
- assert TEMPLATE.name.for_locale(locale)
- assert TEMPLATE.description.for_locale(locale)
- for inp in TEMPLATE.inputs:
- assert inp.label.for_locale(locale)
- assert inp.placeholder is not None and inp.placeholder.for_locale(locale)
-
-
-def test_requires_is_subset_of_grants() -> None:
- granted = {g.plugin_id for g in TEMPLATE.plugin_grants}
- assert set(TEMPLATE.requires) <= granted
- assert granted == {"github"}
- assert all(g.scope == "read" for g in TEMPLATE.plugin_grants)
-
-
-def test_prefix_grant_covers_bridged_github_tools() -> None:
- live = ["gmail", "github/list_commits", "github/list_pull_requests", "github/list_issues"]
- assert grant_matches("github", "github/list_commits")
- assert not grant_matches("github", "githubish/list_commits")
- assert missing_requirements(TEMPLATE.requires, live) == []
- assert missing_requirements(TEMPLATE.requires, ["gmail", "search_web"]) == ["github"]
-
-
-def test_prompt_renders_repo() -> None:
- rendered = render_prompt(TEMPLATE, {"repo": "octo/hello"})
- assert "`octo/hello`" in rendered
- assert "{repo}" not in rendered
- for tool in ("github/list_commits", "github/list_pull_requests", "github/list_issues"):
- assert tool in rendered
- assert "24 hours" in rendered
- assert "12 lines" in rendered
-
-
-def test_build_spec_requires_repo() -> None:
- with pytest.raises(ValueError, match="repo"):
- build_spec(TEMPLATE, inputs={})
- with pytest.raises(ValueError, match="repo"):
- build_spec(TEMPLATE, inputs={"repo": ""})
- with pytest.raises(ValueError, match="repo"):
- build_spec(TEMPLATE)
-
-
-def test_build_spec_builds_daily_agent_task() -> None:
- now = datetime(2026, 8, 24, 12, 0)
- spec = build_spec(TEMPLATE, inputs={"repo": "octo/hello"}, locale="de", now=now)
- assert spec.created_by == "template"
- assert "template:repo_pulse" in spec.tags
- assert spec.title == "Repo-Puls" # i18n-allow
- assert spec.trigger.type == "every"
- assert spec.trigger.interval_seconds == 86_400
- assert spec.trigger.start_at == "2026-08-25T09:00:00"
- assert spec.action.kind == "agent"
- assert "octo/hello" in spec.action.prompt
- assert spec.action.plugin_grants == TEMPLATE.plugin_grants
diff --git a/tests/unit/tasks/templates/test_stock_tracker.py b/tests/unit/tasks/templates/test_stock_tracker.py
deleted file mode 100644
index edf3601cb0..0000000000
--- a/tests/unit/tasks/templates/test_stock_tracker.py
+++ /dev/null
@@ -1,74 +0,0 @@
-"""The ``stock_tracker`` automation template validates, renders and builds a spec."""
-from __future__ import annotations
-
-from datetime import datetime
-
-import pytest
-
-from jarvis.tasks.templates import (
- LOCALES,
- AutomationTemplate,
- all_templates,
- build_spec,
- render_prompt,
-)
-from jarvis.tasks.templates.stock_tracker import TEMPLATE
-
-
-def test_template_is_discovered_and_well_formed() -> None:
- assert isinstance(TEMPLATE, AutomationTemplate)
- assert all_templates(refresh=True)["stock_tracker"] is TEMPLATE
- assert TEMPLATE.category == "finance"
- assert TEMPLATE.icon == "dollar-sign"
- assert TEMPLATE.schedule.kind == "daily"
- assert TEMPLATE.schedule.time == "14:00"
-
-
-def test_all_locales_present() -> None:
- for locale in LOCALES:
- assert TEMPLATE.name.for_locale(locale)
- assert TEMPLATE.description.for_locale(locale)
- for inp in TEMPLATE.inputs:
- assert inp.label.for_locale(locale)
- assert inp.placeholder is not None and inp.placeholder.for_locale(locale)
-
-
-def test_requires_is_subset_of_grants() -> None:
- granted = {g.plugin_id for g in TEMPLATE.plugin_grants}
- assert set(TEMPLATE.requires) <= granted
- assert granted == {"search_web"}
- assert all(g.scope == "read" for g in TEMPLATE.plugin_grants)
-
-
-def test_prompt_renders_watchlist_and_guardrails() -> None:
- rendered = render_prompt(TEMPLATE, {"watchlist": "NVDA, AAPL"})
- assert "NVDA, AAPL" in rendered
- assert "{watchlist}" not in rendered
- assert "search_web" in rendered
- assert "price not found" in rendered
- assert "no emojis" in rendered
- assert "configured output language" in rendered
- assert "advice" in rendered
-
-
-def test_build_spec_requires_watchlist() -> None:
- with pytest.raises(ValueError, match="watchlist"):
- build_spec(TEMPLATE, inputs={})
- with pytest.raises(ValueError, match="watchlist"):
- build_spec(TEMPLATE, inputs={"watchlist": ""})
- with pytest.raises(ValueError, match="watchlist"):
- build_spec(TEMPLATE)
-
-
-def test_build_spec_builds_daily_agent_task() -> None:
- now = datetime(2026, 8, 24, 15, 0) # after 14:00 -> next day
- spec = build_spec(TEMPLATE, inputs={"watchlist": "NVDA, AAPL"}, locale="de", now=now)
- assert spec.created_by == "template"
- assert "template:stock_tracker" in spec.tags
- assert spec.title == "Täglicher Aktien-Tracker" # i18n-allow
- assert spec.trigger.type == "every"
- assert spec.trigger.interval_seconds == 86_400
- assert spec.trigger.start_at == "2026-08-25T14:00:00"
- assert spec.action.kind == "agent"
- assert "NVDA, AAPL" in spec.action.prompt
- assert spec.action.plugin_grants == TEMPLATE.plugin_grants
diff --git a/tests/unit/tasks/templates/test_task_extractor.py b/tests/unit/tasks/templates/test_task_extractor.py
deleted file mode 100644
index 6a7d2bc0fa..0000000000
--- a/tests/unit/tasks/templates/test_task_extractor.py
+++ /dev/null
@@ -1,71 +0,0 @@
-"""The ``task_extractor`` automation template validates, renders and builds a spec."""
-from __future__ import annotations
-
-from datetime import datetime
-
-from jarvis.tasks.templates import (
- LOCALES,
- AutomationTemplate,
- all_templates,
- build_spec,
- render_prompt,
-)
-from jarvis.tasks.templates.task_extractor import TEMPLATE
-
-
-def test_template_is_discovered_and_well_formed() -> None:
- assert isinstance(TEMPLATE, AutomationTemplate)
- assert all_templates(refresh=True)["task_extractor"] is TEMPLATE
- assert TEMPLATE.category == "productivity"
- assert TEMPLATE.icon == "list-checks"
- assert TEMPLATE.schedule.kind == "daily"
- assert TEMPLATE.schedule.time == "17:00"
-
-
-def test_all_locales_present() -> None:
- for locale in LOCALES:
- assert TEMPLATE.name.for_locale(locale)
- assert TEMPLATE.description.for_locale(locale)
- for inp in TEMPLATE.inputs:
- assert inp.label.for_locale(locale)
- assert inp.placeholder is not None and inp.placeholder.for_locale(locale)
-
-
-def test_requires_is_subset_of_grants_and_storage_may_write() -> None:
- scopes = {g.plugin_id: g.scope for g in TEMPLATE.plugin_grants}
- assert set(TEMPLATE.requires) <= set(scopes)
- # Storage is a soft requirement: the card is "ready" with Gmail alone.
- assert TEMPLATE.requires == ("gmail",)
- assert scopes["gmail"] == "read"
- # The unattended run must be able to store the list without approval,
- # through a tool that is actually live for task turns (not `remember`,
- # which ADR-0011 keeps out of the router tool set).
- assert scopes["wiki-ingest"] == "write"
- assert "remember" not in scopes
-
-
-def test_prompt_renders_lookback_default_and_override() -> None:
- rendered = render_prompt(TEMPLATE, None)
- assert "last 24 hours" in rendered
- assert "{lookback_hours}" not in rendered
- rendered = render_prompt(TEMPLATE, {"lookback_hours": "48"})
- assert "last 48 hours" in rendered
- for needle in ("list_messages", "get_message", "wiki-ingest",
- "automation:task_extractor", "Action items",
- "no action items today", "no emojis"):
- assert needle in rendered
- assert "`remember`" not in rendered
-
-
-def test_build_spec_builds_daily_agent_task() -> None:
- now = datetime(2026, 8, 24, 18, 0) # after 17:00 → tomorrow
- spec = build_spec(TEMPLATE, inputs={}, locale="de", now=now)
- assert spec.created_by == "template"
- assert "template:task_extractor" in spec.tags
- assert spec.title == "Aufgaben-Extraktor" # i18n-allow
- assert spec.trigger.type == "every"
- assert spec.trigger.interval_seconds == 86_400
- assert spec.trigger.start_at == "2026-08-25T17:00:00"
- assert spec.action.kind == "agent"
- assert "last 24 hours" in spec.action.prompt
- assert spec.action.plugin_grants == TEMPLATE.plugin_grants
diff --git a/tests/unit/tasks/templates/test_topic_watch.py b/tests/unit/tasks/templates/test_topic_watch.py
deleted file mode 100644
index 387f854a66..0000000000
--- a/tests/unit/tasks/templates/test_topic_watch.py
+++ /dev/null
@@ -1,72 +0,0 @@
-"""The ``topic_watch`` automation template validates, renders and builds a spec."""
-from __future__ import annotations
-
-from datetime import datetime
-
-import pytest
-
-from jarvis.tasks.templates import (
- LOCALES,
- AutomationTemplate,
- all_templates,
- build_spec,
- render_prompt,
-)
-from jarvis.tasks.templates.topic_watch import TEMPLATE
-
-
-def test_template_is_discovered_and_well_formed() -> None:
- assert isinstance(TEMPLATE, AutomationTemplate)
- assert all_templates(refresh=True)["topic_watch"] is TEMPLATE
- assert TEMPLATE.category == "news"
- assert TEMPLATE.icon == "radar"
- assert TEMPLATE.schedule.kind == "weekly"
- assert TEMPLATE.schedule.weekday == 0
- assert TEMPLATE.schedule.time == "09:00"
-
-
-def test_all_locales_present() -> None:
- for locale in LOCALES:
- assert TEMPLATE.name.for_locale(locale)
- assert TEMPLATE.description.for_locale(locale)
- for inp in TEMPLATE.inputs:
- assert inp.label.for_locale(locale)
- assert inp.placeholder is not None and inp.placeholder.for_locale(locale)
-
-
-def test_requires_is_subset_of_grants() -> None:
- granted = {g.plugin_id for g in TEMPLATE.plugin_grants}
- assert set(TEMPLATE.requires) <= granted
- assert "search_web" in granted
- assert all(g.scope == "read" for g in TEMPLATE.plugin_grants)
-
-
-def test_prompt_renders_topics() -> None:
- rendered = render_prompt(TEMPLATE, {"topics": "OpenAI, xAI"})
- assert "OpenAI, xAI" in rendered
- assert "{topics}" not in rendered
- assert "search_web" in rendered
- assert "nothing notable" in rendered
-
-
-def test_build_spec_requires_topics() -> None:
- with pytest.raises(ValueError, match="topics"):
- build_spec(TEMPLATE, inputs={})
- with pytest.raises(ValueError, match="topics"):
- build_spec(TEMPLATE, inputs={"topics": ""})
- with pytest.raises(ValueError, match="topics"):
- build_spec(TEMPLATE)
-
-
-def test_build_spec_builds_weekly_agent_task() -> None:
- now = datetime(2026, 8, 19, 12, 0) # a Wednesday
- spec = build_spec(TEMPLATE, inputs={"topics": "OpenAI, xAI"}, locale="de", now=now)
- assert spec.created_by == "template"
- assert "template:topic_watch" in spec.tags
- assert spec.title == "Themen-Radar" # i18n-allow
- assert spec.trigger.type == "every"
- assert spec.trigger.interval_seconds == 7 * 86_400
- assert spec.trigger.start_at == "2026-08-24T09:00:00"
- assert spec.action.kind == "agent"
- assert "OpenAI, xAI" in spec.action.prompt
- assert spec.action.plugin_grants == TEMPLATE.plugin_grants
diff --git a/tests/unit/tasks/templates/test_weekly_review.py b/tests/unit/tasks/templates/test_weekly_review.py
deleted file mode 100644
index 094611970f..0000000000
--- a/tests/unit/tasks/templates/test_weekly_review.py
+++ /dev/null
@@ -1,83 +0,0 @@
-"""The ``weekly_review`` automation template validates, renders and builds a spec."""
-from __future__ import annotations
-
-from datetime import datetime
-
-from jarvis.tasks.templates import (
- LOCALES,
- AutomationTemplate,
- all_templates,
- build_spec,
- missing_requirements,
- render_prompt,
- schedule_label,
-)
-from jarvis.tasks.templates.weekly_review import TEMPLATE
-
-
-def test_template_is_discovered_and_well_formed() -> None:
- assert isinstance(TEMPLATE, AutomationTemplate)
- assert all_templates(refresh=True)["weekly_review"] is TEMPLATE
- assert TEMPLATE.category == "productivity"
- assert TEMPLATE.icon == "clipboard-list"
- assert TEMPLATE.schedule.kind == "weekly"
- assert TEMPLATE.schedule.weekday == 4 # Friday
- assert TEMPLATE.schedule.time == "16:00"
- assert schedule_label(TEMPLATE.schedule, "en") == "Fridays at 16:00"
-
-
-def test_all_locales_present() -> None:
- for locale in LOCALES:
- assert TEMPLATE.name.for_locale(locale)
- assert TEMPLATE.description.for_locale(locale)
- assert TEMPLATE.inputs == ()
-
-
-def test_grants_are_read_only_and_nothing_is_required() -> None:
- granted = {g.plugin_id for g in TEMPLATE.plugin_grants}
- assert granted == {"google_calendar", "gmail", "wiki-recall"}
- assert all(g.scope == "read" for g in TEMPLATE.plugin_grants)
- # Degrades to memory-only: no hard requirement, so the card is ready on
- # an install without a calendar or a mailbox.
- assert TEMPLATE.requires == ()
- assert set(TEMPLATE.requires) <= granted
- assert missing_requirements(TEMPLATE.requires, ["wiki-recall"]) == []
- assert missing_requirements(TEMPLATE.requires, []) == []
-
-
-def test_prompt_renders_without_inputs_and_names_every_tool() -> None:
- rendered = render_prompt(TEMPLATE, None)
- assert rendered == TEMPLATE.prompt
- assert "{" not in rendered # no placeholders: the template has no inputs
- for tool in ("google_calendar", "gmail", "wiki-recall"):
- assert f"`{tool}`" in rendered
- for heading in ("Done", "Open", "Next week (3 priorities)"):
- assert f'"{heading}"' in rendered
- assert "15 lines" in rendered
- assert "no emojis" in rendered
- assert "no preamble" in rendered.lower()
- assert "configured output language" in rendered
- # Degradation contract: use what is available, say which sources were used.
- assert "carry on without it" in rendered
- assert "sources actually used" in rendered
-
-
-def test_build_spec_builds_weekly_friday_agent_task() -> None:
- now = datetime(2026, 8, 19, 12, 0) # a Wednesday
- spec = build_spec(TEMPLATE, locale="de", now=now)
- assert spec.created_by == "template"
- assert "template:weekly_review" in spec.tags
- assert spec.title == "Wochenrückblick" # i18n-allow
- assert spec.trigger.type == "every"
- assert spec.trigger.interval_seconds == 7 * 86_400
- assert spec.trigger.start_at == "2026-08-21T16:00:00"
- assert spec.action.kind == "agent"
- assert spec.action.prompt == TEMPLATE.prompt
- assert spec.action.plugin_grants == TEMPLATE.plugin_grants
- assert spec.action.model_tier == "auto"
-
-
-def test_build_spec_after_friday_cutoff_rolls_to_next_week() -> None:
- now = datetime(2026, 8, 21, 16, 30) # Friday, past 16:00
- spec = build_spec(TEMPLATE, now=now)
- assert spec.trigger.start_at == "2026-08-28T16:00:00"
diff --git a/tests/unit/tasks/test_action_parity.py b/tests/unit/tasks/test_action_parity.py
deleted file mode 100644
index d1cb564d37..0000000000
--- a/tests/unit/tasks/test_action_parity.py
+++ /dev/null
@@ -1,38 +0,0 @@
-"""Parity test for the task ACTION vocabulary across Python ↔ TypeScript.
-
-The create dialog must never emit an action ``kind`` the Pydantic
-``TaskAction`` discriminator rejects (that is an instant HTTP 422 on save).
-The TS side is a SUBSET of Python by design — the UI does not surface every
-action kind (e.g. ``tool_call`` has no dialog) — so the contract is
-containment, not equality: every kind the frontend builds must be a known
-Python kind.
-
-Source of truth: ``ACTION_KINDS`` in ``jarvis/tasks/schema.py``.
-"""
-from __future__ import annotations
-
-import re
-from pathlib import Path
-
-from jarvis.tasks.schema import ACTION_KINDS
-
-REPO_ROOT = Path(__file__).resolve().parents[3]
-TASK_SPEC_TS = REPO_ROOT / "jarvis/ui/web/frontend/src/views/tasks/taskSpec.ts"
-
-
-def test_ts_action_kinds_are_all_known_to_python() -> None:
- text = TASK_SPEC_TS.read_text(encoding="utf-8")
- found = set(re.findall(r'kind:\s*"([^"]+)"', text))
- assert found, "no action kinds found in taskSpec.ts"
- unknown = found - set(ACTION_KINDS)
- assert unknown == set(), (
- f"taskSpec.ts emits action kinds the Python schema rejects: {unknown}"
- )
-
-
-def test_whenthen_uses_harness_dispatch_for_computer_use() -> None:
- """The When-Then Computer-Use path must dispatch via the harness action —
- a regression here would silently drop CU rules."""
- text = TASK_SPEC_TS.read_text(encoding="utf-8")
- assert "harness_dispatch" in text
- assert "harness_dispatch" in ACTION_KINDS
diff --git a/tests/unit/tasks/test_grant_matching.py b/tests/unit/tasks/test_grant_matching.py
index e7376c5477..0c4e340185 100644
--- a/tests/unit/tasks/test_grant_matching.py
+++ b/tests/unit/tasks/test_grant_matching.py
@@ -1,10 +1,10 @@
"""Plugin grants match by PREFIX everywhere a task's allowlist is applied.
-A template grants ``github`` while the live tools are ``github/list_issues``,
+A routine 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`.
+apply one and the same rule: :func:`jarvis.tasks.grants.grant_matches`.
"""
from __future__ import annotations
diff --git a/tests/unit/tasks/test_state_parity.py b/tests/unit/tasks/test_state_parity.py
index 5884c94abb..eafc4c967e 100644
--- a/tests/unit/tasks/test_state_parity.py
+++ b/tests/unit/tasks/test_state_parity.py
@@ -2,9 +2,9 @@
``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
+and the migration rebuild target), TypeScript (the ``TaskState`` union the
+agent card reads routines with) 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``.
@@ -23,8 +23,7 @@ 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"
+MODEL_TS = FRONTEND / "lib/tasksApi.ts"
LOCALES = FRONTEND / "i18n/locales"
@@ -58,17 +57,9 @@ def test_migration_rebuild_target_matches_python() -> None:
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"
+ assert block is not None, "could not find TaskState union in tasksApi.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"
+ assert found == _expected(), f"tasksApi.ts TaskState drift: {found ^ _expected()}"
@pytest.mark.parametrize("locale", ["de", "en", "es"])
diff --git a/tests/unit/tasks/test_store.py b/tests/unit/tasks/test_store.py
index 7a2754053f..4ae1beb48e 100644
--- a/tests/unit/tasks/test_store.py
+++ b/tests/unit/tasks/test_store.py
@@ -163,6 +163,32 @@ async def test_cleanup_interrupted_flips_running_to_interrupted(store: TaskStore
assert task["finished_at_ns"] is not None
+async def test_retire_catalogue_tasks_cancels_only_live_template_tasks(store: TaskStore) -> None:
+ def spec(title: str, created_by: str) -> TaskSpec:
+ return TaskSpec(title=title, trigger=TriggerAfterDelay(delay_seconds=60),
+ action=SpeakAction(text="x"), created_by=created_by)
+
+ live_template = await store.insert(spec("recap", "template"))
+ paused_template = await store.insert(spec("digest", "template"))
+ await store.update_state(paused_template, "paused")
+ done_template = await store.insert(spec("old", "template"))
+ await store.update_state(done_template, "completed")
+ routine = await store.insert(spec("[agent:Scout] brief", "society"))
+
+ assert await store.retire_catalogue_tasks() == 2
+
+ for tid in (live_template, paused_template):
+ task = await store.get(tid)
+ assert task is not None
+ assert task["state"] == "cancelled"
+ assert "retired" in task["last_error"]
+ done = await store.get(done_template)
+ assert done is not None and done["state"] == "completed"
+ kept = await store.get(routine)
+ assert kept is not None and kept["state"] == "scheduled"
+ assert await store.retire_catalogue_tasks() == 0
+
+
async def test_get_spec_deserialises(store: TaskStore) -> None:
spec = TaskSpec(
title="Hallo",
diff --git a/tests/unit/tasks/test_tasks_routes.py b/tests/unit/tasks/test_tasks_routes.py
index 85734721fb..9f717beef6 100644
--- a/tests/unit/tasks/test_tasks_routes.py
+++ b/tests/unit/tasks/test_tasks_routes.py
@@ -1,8 +1,8 @@
-"""``/api/tasks`` — the Automations API contract the UI codes against.
+"""``/api/tasks`` — the routine API contract the agent card 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``.
+a real ``TaskStore`` + ``TaskScheduler`` (with a fake agent brain). No
+``unittest.mock``.
"""
from __future__ import annotations
@@ -15,7 +15,6 @@ 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
@@ -24,15 +23,12 @@ from jarvis.ui.web import tasks_routes
class FakeBrain:
- """The two things the routes touch on ``app.state.brain``."""
+ """The agent brain a routine's turn runs on."""
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
@@ -81,89 +77,13 @@ def _every_body(**overrides: Any) -> dict[str, Any]:
title="recurring",
trigger=TriggerEvery(interval_seconds=3600),
action=AgentAction(prompt="hello"),
- tags=("template:morning_brief", "news"),
- created_by="template",
+ tags=("society", "agent:scout"),
+ created_by="society",
**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
# ----------------------------------------------------------------------
@@ -173,8 +93,8 @@ async def test_list_summaries_carry_automation_fields(harness: Harness) -> None:
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["tags"] == ["society", "agent:scout"]
+ assert first["created_by"] == "society"
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
diff --git a/tests/unit/tasks/test_trigger_parity.py b/tests/unit/tasks/test_trigger_parity.py
index d858fd41a9..e55709deb2 100644
--- a/tests/unit/tasks/test_trigger_parity.py
+++ b/tests/unit/tasks/test_trigger_parity.py
@@ -1,13 +1,10 @@
"""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 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 layer
-must spell exactly the same four values. (When-Then added ``on_event`` to the TS
-side; this test would have failed on the missing value before that change.)
+BUG-008 class: a vocabulary that spans Python (the Pydantic discriminator) and
+the TS task model the agent card reads routines with drifts silently — the card
+mislabels a trigger it never learned.
+
+Source of truth: ``TRIGGER_TYPES`` in ``jarvis/tasks/schema.py``.
"""
from __future__ import annotations
@@ -17,8 +14,7 @@ from pathlib import Path
from jarvis.tasks.schema import PAUSABLE_TRIGGER_TYPES, TRIGGER_TYPES
REPO_ROOT = Path(__file__).resolve().parents[3]
-TASK_SPEC_TS = REPO_ROOT / "jarvis/ui/web/frontend/src/views/tasks/taskSpec.ts"
-MODEL_TS = REPO_ROOT / "jarvis/ui/web/frontend/src/views/automations/automationsModel.ts"
+MODEL_TS = REPO_ROOT / "jarvis/ui/web/frontend/src/lib/tasksApi.ts"
def _expected() -> set[str]:
@@ -29,25 +25,12 @@ 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
- # `;` (e.g. `{ type: "after_delay"; ... }`) so a non-greedy `;` stops short.
- block = re.search(r"export type TaskTrigger =([\s\S]+?)\nexport ", text)
- assert block is not None, "could not find TaskTrigger union in taskSpec.ts"
- found = set(re.findall(r'type:\s*"([^"]+)"', block.group(1)))
- assert found == _expected(), (
- f"taskSpec.ts TaskTrigger drift: extra={found - _expected()}, "
- f"missing={_expected() - found}"
- )
-
-
-def test_automations_model_triggertype_matches_python() -> None:
+def test_tasks_api_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"
+ assert block is not None, "could not find TriggerType in tasksApi.ts"
found = set(re.findall(r'"([^"]+)"', block.group(1)))
assert found == _expected(), (
- f"automationsModel.ts TriggerType drift: extra={found - _expected()}, "
+ f"tasksApi.ts TriggerType drift: extra={found - _expected()}, "
f"missing={_expected() - found}"
)