Skip to content

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

feat(agents): add routine details with schedules and execution history

rubenluetke10-beepb586eda408cc
diff --git a/jarvis/tasks/runner.py b/jarvis/tasks/runner.py
index 6fb92ff099..f70c7c0a48 100644
--- a/jarvis/tasks/runner.py
+++ b/jarvis/tasks/runner.py
@@ -189,6 +189,7 @@ class TaskRunner:
ctx = _event_context(trigger_event)
await self._store.update_state(task_id, "running", increment_attempts=True)
+ await self._store.append_step(task_id, "log", {"event": "run_started"})
await self._bus.publish(TaskStarted(task_id=task_id, source_layer="tasks.runner"))
start = time.perf_counter()
@@ -196,6 +197,9 @@ class TaskRunner:
await self._execute_action(task_id, spec, cancel_token, ctx)
except _Cancelled as exc:
await self._store.update_state(task_id, "cancelled", error=str(exc))
+ await self._store.append_step(
+ task_id, "log", {"event": "run_cancelled", "message": str(exc)}
+ )
return
except Exception as exc: # noqa: BLE001
if isinstance(exc, RoutineDeferred) and ctx.get("hook_delivery_id"):
@@ -241,6 +245,9 @@ class TaskRunner:
final_state,
result={"duration_ms": duration_ms},
)
+ await self._store.append_step(
+ task_id, "log", {"event": "run_completed", "duration_ms": duration_ms}
+ )
await self._bus.publish(
TaskCompleted(
task_id=task_id,
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
new file mode 100644
index 0000000000..9bcd3975d5
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/card/AgentRoutineDetail.test.tsx
@@ -0,0 +1,112 @@
+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, routineRuns } from "./AgentRoutineDetail";
+import type { LiveRoutine } from "../cardData";
+import type { TaskDetail, TaskStep } from "@/views/automations/automationsModel";
+import en from "@/i18n/locales/society/en.json";
+
+vi.mock("@/i18n", () => ({
+ useLocaleChunk: () => {},
+ useT: () => (key: string) => key.split(".").reduce<unknown>((value, part) => (value as Record<string, unknown>)?.[part], en) ?? key,
+}));
+
+afterEach(() => { cleanup(); vi.unstubAllGlobals(); });
+
+function setup(multiple = false) {
+ const trigger = { type: "calendar", local_time: "08:00", timezone: "Europe/Berlin", weekdays: [0, 2] };
+ const member: LiveRoutine = { id: "r1", title: "[agent:Mail] Inbox", prompt: "Read mail.", trigger, schedule: "", state: "scheduled", dueMs: null, lastRunMs: null };
+ const members = multiple ? [member, { ...member, id: "r2" }] : [member];
+ const tasks = new Map(members.map((m) => [m.id, {
+ ...m, trigger_type: "calendar", spec: { action: { kind: "agent", prompt: "Identity\nRoutine:\nRead mail." } }, steps: [],
+ } as unknown as TaskDetail]));
+ const fetcher = vi.fn(async (url: string, init?: RequestInit) => {
+ const method = init?.method ?? "GET";
+ const id = url.split("/").at(-1)!;
+ if (method === "PATCH" && url.startsWith("/api/tasks/")) tasks.get(id)!.state = JSON.parse(String(init?.body)).enabled ? "scheduled" : "paused";
+ return { ok: true, status: 200, json: async () => tasks.get(id) ?? {} } as Response;
+ });
+ vi.stubGlobal("fetch", fetcher);
+ const onClose = vi.fn();
+ render(<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
+ <AgentRoutineDetail routine={{ ...member, members }} agentId="mail" onClose={onClose} />
+ </QueryClientProvider>);
+ return { fetcher, onClose };
+}
+
+test("loads the instruction and saves all timings under the original ids", async () => {
+ const { fetcher } = setup(true);
+ await waitFor(() => expect((screen.getByLabelText("Name") as HTMLButtonElement).disabled).toBe(false));
+ expect((screen.getByLabelText("Instruction") as HTMLTextAreaElement).value).toBe("Read mail.");
+ fireEvent.change(screen.getByLabelText("Name"), { target: { value: "Updated inbox" } });
+ fireEvent.click(screen.getByText("Save"));
+ await screen.findByText("Saved.");
+ const writes = fetcher.mock.calls.filter(([url, init]) => url.includes("/routines/") && init?.method === "PATCH");
+ expect(writes.map(([url]) => url)).toEqual(["/api/society/agents/mail/routines/r1", "/api/society/agents/mail/routines/r2"]);
+ expect(JSON.parse(String(writes[0][1]?.body))).toMatchObject({ title: "Updated inbox", prompt: "Read mail.", schedule: { weekdays: [0, 2] } });
+});
+
+test("pauses every timing, tests once, and requires a delete confirmation", async () => {
+ const { fetcher, onClose } = setup(true);
+ await waitFor(() => expect((screen.getByRole("switch") as HTMLButtonElement).disabled).toBe(false));
+ fireEvent.click(screen.getByRole("switch"));
+ await waitFor(() => expect(screen.getByRole("switch").getAttribute("aria-checked")).toBe("false"));
+ expect(fetcher.mock.calls.filter(([, init]) => init?.method === "PATCH")).toHaveLength(2);
+ fireEvent.click(screen.getByText("Test run"));
+ await waitFor(() => expect(fetcher.mock.calls.filter(([url]) => url.endsWith("/run"))).toHaveLength(1));
+ await waitFor(() => expect((screen.getByText("Delete") as HTMLButtonElement).disabled).toBe(false));
+ fireEvent.click(screen.getByText("Delete"));
+ expect(fetcher.mock.calls.some(([, init]) => init?.method === "DELETE")).toBe(false);
+ fireEvent.click(screen.getAllByText("Delete")[1]);
+ await waitFor(() => expect(onClose).toHaveBeenCalledOnce());
+ expect(fetcher.mock.calls.filter(([, init]) => init?.method === "DELETE").map(([url]) => url)).toEqual(["/api/tasks/r2", "/api/tasks/r1"]);
+});
+
+test("schedule editing keeps calendar restrictions and adding uses the parent", async () => {
+ const { fetcher } = setup();
+ await waitFor(() => expect((screen.getByText("Add another schedule") as HTMLButtonElement).disabled).toBe(false));
+ fireEvent.click(screen.getByText("Add another schedule"));
+ fireEvent.click(screen.getByText("Save"));
+ await screen.findByText("Saved.");
+ const post = fetcher.mock.calls.find(([, init]) => init?.method === "POST");
+ expect(JSON.parse(String(post?.[1]?.body))).toMatchObject({ parent_task_id: "r1", prompt: "Read mail.", schedule: { type: "every" } });
+});
+
+test("failed saves remain editable and expose the error", async () => {
+ const { fetcher } = setup();
+ await waitFor(() => expect((screen.getByLabelText("Name") as HTMLButtonElement).disabled).toBe(false));
+ const original = fetcher.getMockImplementation()!;
+ fetcher.mockImplementation(async (url, init) => init?.method === "PATCH" ? { ok: false, status: 409, json: async () => ({ detail: "Routine is running" }) } as Response : original(url, init));
+ fireEvent.change(screen.getByLabelText("Name"), { target: { value: "Unsaved name" } });
+ fireEvent.click(screen.getByText("Save"));
+ expect((await screen.findByRole("alert")).textContent).toContain("Routine is running");
+ expect((screen.getByLabelText("Name") as HTMLInputElement).value).toBe("Unsaved name");
+});
+
+test("history distinguishes success, failure, active and legacy executions", () => {
+ const events = ["agent_result", "run_started", "agent_result", "run_completed", "run_started", "error", "run_started"];
+ const steps = events.map((event, seq) => ({ seq, kind: "log", timestamp_ns: seq * 1e9, payload: { event, text: "Result" } } as TaskStep));
+ expect(routineRuns("r1", steps).map((run) => run.status)).toEqual(["legacy", "completed", "failed", "running"]);
+});
+
+
+test("editing the time saves the new value without dropping weekdays", async () => {
+ const { fetcher } = setup();
+ await waitFor(() => expect((screen.getByLabelText("Name") as HTMLInputElement).disabled).toBe(false));
+ const timing = screen.getAllByRole("button").find((el) => el.textContent?.includes("08:00"))!;
+ fireEvent.click(timing);
+ fireEvent.change(screen.getByLabelText("Time"), { target: { value: "09:30" } });
+ fireEvent.click(screen.getByText("Save"));
+ await screen.findByText("Saved.");
+ const patch = fetcher.mock.calls.find(([url, init]) => url.includes("/routines/") && init?.method === "PATCH");
+ expect(JSON.parse(String(patch?.[1]?.body)).schedule).toMatchObject({ local_time: "09:30", weekdays: [0, 2] });
+});
+
+
+test("removing a timing cancels it instead of deleting its history", async () => {
+ const { fetcher } = setup(true);
+ await waitFor(() => expect((screen.getByText("Remove schedule") as HTMLButtonElement).disabled).toBe(false));
+ fireEvent.click(screen.getByText("Remove schedule"));
+ await waitFor(() => expect(fetcher.mock.calls.some(([url, init]) => url === "/api/tasks/r2/cancel" && init?.method === "POST")).toBe(true));
+ expect(fetcher.mock.calls.some(([, init]) => init?.method === "DELETE")).toBe(false);
+});
diff --git a/jarvis/ui/web/frontend/src/components/society/card/AgentRoutineDetail.tsx b/jarvis/ui/web/frontend/src/components/society/card/AgentRoutineDetail.tsx
new file mode 100644
index 0000000000..158854ea80
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/card/AgentRoutineDetail.tsx
@@ -0,0 +1,172 @@
+/** The agent's routine editor, backed by the existing task scheduler. */
+import { useState } from "react";
+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 { describeTrigger, displayRoutineTitle, type LiveRoutine } from "../cardData";
+import type { TaskDetail, TaskStep } from "@/views/automations/automationsModel";
+import { TriggerBuilder } from "./TriggerBuilder";
+import { WebhookConnection } from "./WebhookConnection";
+import { SourceControls } from "./SourceControls";
+
+const field = "w-full rounded-lg border border-border bg-background px-3 py-2 text-[12px] text-foreground";
+const button = "rounded-md bg-secondary px-2.5 py-1.5 text-[12px] text-foreground hover:bg-secondary/70 disabled:opacity-50";
+const recurring = ["every", "calendar", "cron", "webhook", "event_hook", "source", "on_event"];
+const terminal = ["completed", "failed", "cancelled", "interrupted"];
+const timeKinds = ["every", "calendar", "cron"];
+
+interface Run { id: string; timestamp: number; status: string; text: string }
+
+/** New runs have explicit boundaries; retain older result/error records too. */
+export function routineRuns(taskId: string, steps: TaskStep[]): Run[] {
+ const runs: Run[] = [];
+ let current: Run | undefined;
+ for (const step of steps) {
+ const event = step.payload.event;
+ const text = String(step.payload.message ?? step.payload.text ?? "");
+ if (event === "run_started") {
+ if (current?.status === "running") current.status = "interrupted";
+ current = { id: `${taskId}:${step.seq}`, timestamp: step.timestamp_ns / 1e6, status: "running", text: "" };
+ runs.push(current);
+ } else if (event === "agent_result" && current) {
+ current.text = text;
+ } else if (["run_completed", "run_cancelled", "error", "deferred"].includes(String(event))) {
+ const status = event === "run_completed" ? "completed" : event === "run_cancelled" ? "cancelled" : event === "deferred" ? "pending" : "failed";
+ if (current) { current.status = status; if (text) current.text = text; current = undefined; }
+ else runs.push({ id: `${taskId}:${step.seq}`, timestamp: step.timestamp_ns / 1e6, status, text });
+ } else if (event === "agent_result") {
+ // Legacy runners persisted the result before the final state transition.
+ runs.push({ id: `${taskId}:${step.seq}`, timestamp: step.timestamp_ns / 1e6, status: "legacy", text });
+ }
+ }
+ return runs;
+}
+
+async function writeRoutine(url: string, body: unknown, method = "PATCH") {
+ const response = await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
+ if (!response.ok) {
+ const error = await response.json().catch(() => null) as { detail?: unknown } | null;
+ throw new Error(typeof error?.detail === "string" ? error.detail : `HTTP ${response.status}`);
+ }
+}
+
+export function AgentRoutineDetail({ agentId, routine, onClose }: {
+ agentId: string; routine: LiveRoutine; onClose: () => void;
+}) {
+ const t = useT();
+ const label = (key: string) => t(`society.routine_detail.${key}`);
+ const client = useQueryClient();
+ const members = routine.members ?? [routine];
+ const queries = useQueries({ queries: members.map((member) => ({
+ queryKey: ["tasks", "detail", member.id], queryFn: () => fetchTask(member.id),
+ retry: false, refetchInterval: import.meta.env.MODE === "test" ? false : 3000,
+ })) });
+ const [draft, setDraft] = useState<{ title: string; prompt: string } | null>(null);
+ const [editing, setEditing] = useState<LiveRoutine | "new" | null>(null);
+ const [schedule, setSchedule] = useState<Record<string, unknown> | null>(null);
+ const [pending, setPending] = useState(false);
+ const [error, setError] = useState("");
+ const [notice, setNotice] = useState("");
+ const [confirmDelete, setConfirmDelete] = useState(false);
+ const details = queries.map((query) => query.data);
+ const first = details[0];
+ const rawPrompt = String((first?.spec?.action as { prompt?: string } | undefined)?.prompt ?? "");
+ const marker = rawPrompt.indexOf("\nRoutine:\n");
+ const saved = { title: displayRoutineTitle(first?.title ?? routine.title), prompt: marker >= 0 ? rawPrompt.slice(marker + 10) : routine.prompt ?? rawPrompt };
+ const values = draft ?? saved;
+ const ready = details.every(Boolean);
+ const running = details.some((detail) => detail?.state === "running");
+ const active = details.some((detail) => detail && detail.state !== "paused" && !terminal.includes(detail.state));
+ const editable = ready && !running && details.every((detail, index) => detail && (
+ index > 0 && terminal.includes(detail.state) || recurring.includes(detail.trigger_type) && !terminal.includes(detail.state)
+ ));
+ const url = `/api/society/agents/${encodeURIComponent(agentId)}/routines`;
+ const refresh = () => Promise.all([
+ client.invalidateQueries({ queryKey: ["tasks"] }),
+ client.invalidateQueries({ queryKey: ["society", "agent-routines", agentId] }),
+ ]);
+ const act = async (fn: () => Promise<void>) => {
+ setPending(true); setError(""); setNotice("");
+ try { await fn(); }
+ catch (err) { setError(err instanceof Error ? err.message : String(err)); }
+ finally { await refresh(); setPending(false); }
+ };
+ const update = (member: LiveRoutine, nextSchedule: unknown) => writeRoutine(`${url}/${encodeURIComponent(member.id)}`, {
+ title: values.title.trim(), prompt: values.prompt.trim(), schedule: nextSchedule,
+ });
+ const valid = Boolean(values.title.trim() && values.prompt.trim());
+ const runs = details.flatMap((detail) => detail ? routineRuns(detail.id, detail.steps) : []).sort((a, b) => b.timestamp - a.timestamp);
+ const renderConnection = (detail: TaskDetail) => {
+ if (detail.trigger_type === "webhook") return <WebhookConnection taskId={detail.id} />;
+ if (detail.trigger_type === "source") return <SourceControls taskId={detail.id} source={(detail.trigger as { source: { kind: string } }).source} />;
+ return null;
+ };
+
+ return <section className="min-h-0 flex-1 space-y-4 overflow-y-auto pb-4 text-foreground" data-testid="agent-routine-detail">
+ <button type="button" className="flex items-center gap-1 text-[12px] text-muted-foreground" disabled={pending} onClick={onClose}><ArrowLeft size={14} />{t("society.card.routines")}</button>
+ <div className="flex flex-wrap items-center gap-2">
+ <label className="mr-auto flex items-center gap-2 text-[12px]"><Switch aria-label={label("active")} checked={active} disabled={pending || !editable} onCheckedChange={(enabled) => void act(async () => {
+ for (const detail of details) if (detail && !terminal.includes(detail.state) && (detail.state === "paused") === enabled) await setTaskEnabled(detail.id, enabled);
+ })} />{label("active")}</label>
+ <button type="button" className={button} disabled={pending || !ready || running} onClick={() => setConfirmDelete(true)}>{label("delete")}</button>
+ <button type="button" className={button} disabled={pending || !ready || running || Boolean(draft) || Boolean(editing) || !first || terminal.includes(first.state) || first.trigger_type === "source"} onClick={() => void act(async () => {
+ await runTaskNow(routine.id); setNotice(label("test_started"));
+ })}>{label("test")}</button>
+ </div>
+ {confirmDelete && <div className="space-y-2 rounded-lg border border-border p-3" role="alert">
+ <p className="text-[12px]">{label("delete_confirm")}</p>
+ <button className={button} disabled={pending} onClick={() => void act(async () => {
+ for (const detail of [...details].reverse()) if (detail) await cancelAndDeleteTask(detail.id, !terminal.includes(detail.state));
+ onClose();
+ })}>{label("delete")}</button>{" "}<button className={button} disabled={pending} onClick={() => setConfirmDelete(false)}>{label("cancel")}</button>
+ </div>}
+ {queries.some((query) => query.isLoading) && <p role="status" className="text-[12px]">{t("tasks_view.loading_details")}</p>}
+ {queries.some((query) => query.error) && <p role="alert" className="text-[12px] text-destructive">{t("tasks_view.load_error")}</p>}
+ {error && <p role="alert" className="break-words text-[12px] text-destructive">{error}</p>}
+ {notice && <p role="status" className="text-[12px] text-success">{notice}</p>}
+ <label className="block space-y-1 text-[11px] text-muted-foreground">{label("name")}<input className={field} aria-label={label("name")} maxLength={200} disabled={pending || !editable || Boolean(editing)} value={values.title} onChange={(event) => setDraft({ ...values, title: event.target.value })} /></label>
+ <label className="block space-y-1 text-[11px] text-muted-foreground">{label("prompt")}<textarea className={field} aria-label={label("prompt")} maxLength={16000} rows={7} disabled={pending || !editable || Boolean(editing) || (first?.spec?.action as { kind?: string } | undefined)?.kind !== "agent"} value={values.prompt} onChange={(event) => setDraft({ ...values, prompt: event.target.value })} /></label>
+ {draft && <div className="flex gap-2"><button className={button} disabled={pending || !valid || !editable || Boolean(editing)} onClick={() => void act(async () => {
+ for (const [index, member] of members.entries()) if (!terminal.includes(details[index]!.state)) await update(member, details[index]?.trigger);
+ setDraft(null); setNotice(label("saved"));
+ })}>{label("save")}</button><button className={button} disabled={pending} onClick={() => setDraft(null)}>{label("cancel")}</button></div>}
+ <div className="space-y-2">
+ <h4 className="text-[11px] text-muted-foreground">{label("when")}</h4>
+ <div className="space-y-2 rounded-xl border border-border p-3">
+ {members.map((member, index) => {
+ const detail = details[index];
+ if (index > 0 && detail && terminal.includes(detail.state)) return null;
+ return <div key={member.id} className="space-y-1">
+ <button className="flex w-full items-start gap-2 rounded text-left text-[12px] disabled:opacity-70" disabled={pending || !editable || Boolean(draft) || !detail || !timeKinds.includes(detail.trigger_type)} onClick={() => { setEditing({ ...member, trigger: detail?.trigger }); setSchedule(null); }}>
+ <Clock size={14} className="mt-0.5 shrink-0" /><span>{describeTrigger(detail?.trigger ?? member.trigger, t)}</span>
+ </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 && 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>;
+ })}
+ <button className="flex items-center gap-1 text-[12px] text-muted-foreground disabled:opacity-50" disabled={pending || !editable || Boolean(draft)} onClick={() => { setEditing("new"); setSchedule(null); }}><Plus size={14} />{label("add_schedule")}</button>
+ </div>
+ {editing && <div className="space-y-2 rounded-lg border border-border p-3">
+ <TriggerBuilder key={editing === "new" ? "new" : editing.id} timeOnly initialValue={editing === "new" ? undefined : editing.trigger as Record<string, unknown>} onChange={setSchedule} />
+ <button className={button} disabled={pending || !schedule || !valid} onClick={() => void act(async () => {
+ if (editing === "new") await writeRoutine(url, { title: values.title, prompt: values.prompt, schedule, parent_task_id: routine.id }, "POST");
+ else await update(editing, schedule);
+ setEditing(null); setNotice(label("saved"));
+ })}>{label("save")}</button>{" "}<button className={button} disabled={pending} onClick={() => setEditing(null)}>{label("cancel")}</button>
+ </div>}
+ </div>
+ <div className="space-y-2">
+ <h4 className="text-[11px] text-muted-foreground">{label("history")}</h4>
+ {ready && runs.length === 0 && <p className="text-[12px] text-muted-foreground">{label("no_runs")}</p>}
+ {runs.map((run) => <details key={run.id} className="text-[12px]">
+ <summary className="flex cursor-pointer items-center justify-between gap-2 rounded py-1 hover:bg-secondary"><time dateTime={new Date(run.timestamp).toISOString()}>{new Date(run.timestamp).toLocaleString()}</time><span className="flex items-center gap-1" title={run.status === "legacy" ? label("legacy") : t(`tasks_view.state.${run.status}`)}>
+ {run.status === "completed" ? <Check size={15} className="text-success" aria-label={t("tasks_view.state.completed")} /> : run.status === "failed" || run.status === "cancelled" ? <X size={15} className="text-destructive" aria-label={t(`tasks_view.state.${run.status}`)} /> : <Clock size={15} aria-label={run.status === "legacy" ? label("legacy") : t(`tasks_view.state.${run.status}`)} />}
+ </span></summary>
+ <p className="whitespace-pre-wrap break-words rounded bg-secondary p-2">{run.text || (run.status === "legacy" ? label("legacy") : t(`tasks_view.state.${run.status}`))}</p>
+ </details>)}
+ </div>
+ </section>;
+}
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 4a46bc537b..a3aea04047 100644
--- a/jarvis/ui/web/frontend/src/components/society/card/AgentRoutinesList.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/card/AgentRoutinesList.tsx
@@ -1,5 +1,5 @@
/** Per-agent routines use the same task store and trigger editor as Automations. */
-import { useMemo, useState } from "react";
+import { useEffect, useMemo, useState } from "react";
import { Clock, Plus, X } from "lucide-react";
import { useLocaleChunk, useT } from "@/i18n";
import { cn } from "@/lib/utils";
@@ -8,16 +8,21 @@ import type { AgentRoutine } from "../data";
import { WebhookConnection } from "./WebhookConnection";
import { TriggerBuilder } from "./TriggerBuilder";
import { SourceControls } from "./SourceControls";
+import { AgentRoutineDetail } from "./AgentRoutineDetail";
-export interface AgentRoutinesListProps { agentId: string; sampleRoutines?: AgentRoutine[]; variant?: "rail" | "sheet"; className?: string; }
-export function AgentRoutinesList({ agentId, sampleRoutines, variant = "rail", className }: AgentRoutinesListProps) {
+export interface AgentRoutinesListProps { agentId: string; sampleRoutines?: AgentRoutine[]; variant?: "rail" | "sheet"; className?: string; onDetailOpenChange?: (open: boolean) => void; }
+export function AgentRoutinesList({ agentId, sampleRoutines, variant = "rail", className, onDetailOpenChange }: AgentRoutinesListProps) {
const t = useT(); useLocaleChunk("society");
const live = useAgentRoutines(agentId); const create = useCreateAgentRoutine();
const [open, setOpen] = useState(false); const [title, setTitle] = useState("");
const [prompt, setPrompt] = useState(""); const [schedule, setSchedule] = useState<Record<string, unknown> | null>(null);
const [saving, setSaving] = useState(false); const [error, setError] = useState("");
+ const [selected, setSelected] = useState<string | null>(null);
const sample = useMemo(() => (sampleRoutines ?? []).map((row) => ({ id: row.id, title: row.label, state: "scheduled", trigger: null, schedule: row.schedule, dueMs: row.nextFire ? Date.parse(row.nextFire) : null, lastRunMs: null })), [sampleRoutines]);
- const rows: LiveRoutine[] = live.data?.length ? live.data : sample.length && !live.data?.length ? sample : live.data ?? [];
+ const rows: LiveRoutine[] = live.data ?? sample;
+ const selectedRoutine = rows.find((row) => row.id === selected);
+ const detailOpen = Boolean(selectedRoutine);
+ useEffect(() => { onDetailOpenChange?.(detailOpen); }, [detailOpen, onDetailOpenChange]);
const field = "w-full rounded-md border border-border bg-background px-2 py-1.5 text-[12px] text-foreground placeholder:text-muted-foreground";
const submit = async () => {
if (!title.trim() || !prompt.trim() || !schedule) return;
@@ -26,6 +31,7 @@ export function AgentRoutinesList({ agentId, sampleRoutines, variant = "rail", c
catch (err) { setError(err instanceof Error ? err.message : String(err)); }
finally { setSaving(false); }
};
+ if (selectedRoutine) return <AgentRoutineDetail key={`${agentId}:${selected}`} agentId={agentId} routine={selectedRoutine} onClose={() => setSelected(null)} />;
return <section className={cn("flex min-h-0 flex-col", className)} data-testid="agent-routines">
<div className="mb-1.5 flex shrink-0 items-center justify-between gap-2">
<h3 className={variant === "sheet" ? "ac-head" : "font-display text-[13px] font-semibold text-foreground"}>{t("society.card.routines")}{rows.length > 0 && <span className="ml-1.5 text-muted-foreground">{rows.length}</span>}</h3>
@@ -39,6 +45,7 @@ export function AgentRoutinesList({ agentId, sampleRoutines, variant = "rail", c
{error && <p role="alert" className="text-[11px] text-destructive">{error}</p>}
</form>}
<ul className="min-h-0 flex-1 overflow-y-auto">
+ {live.error && <li role="alert" className="text-[12px] text-destructive">{t("tasks_view.load_error")}</li>}
{rows.length === 0 && <li className="text-[12px] text-muted-foreground">{t("society.card.no_routines")}</li>}
{rows.map((routine) => {
const active = ["scheduled", "active", "enabled", ""].includes(routine.state);
@@ -46,7 +53,7 @@ export function AgentRoutinesList({ agentId, sampleRoutines, variant = "rail", c
return <li key={routine.id} className="flex items-start gap-2 rounded-md px-0.5 py-1.5 hover:bg-secondary/60">
<Clock size={16} aria-hidden className={cn("mt-0.5 shrink-0", active ? "text-success" : "text-muted-foreground")} />
<div className="min-w-0 flex-1">
- <span className="block truncate text-[13px] font-medium text-foreground">{displayRoutineTitle(routine.title)}</span>
+ <button type="button" className="block w-full truncate rounded text-left text-[13px] font-medium text-foreground focus-visible:outline focus-visible:outline-ring" onClick={() => setSelected(routine.id)}>{displayRoutineTitle(routine.title)}</button>
<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}
{trigger?.type === "webhook" && <WebhookConnection key={routine.id} taskId={routine.id} />}
diff --git a/jarvis/ui/web/frontend/src/components/society/card/OptionsRail.tsx b/jarvis/ui/web/frontend/src/components/society/card/OptionsRail.tsx
index 2342a87d8e..fe9fe0819d 100644
--- a/jarvis/ui/web/frontend/src/components/society/card/OptionsRail.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/card/OptionsRail.tsx
@@ -26,6 +26,7 @@ export interface OptionsRailProps {
export function OptionsRail({ agent, onRetired, sample = false }: OptionsRailProps) {
const t = useT();
const [more, setMore] = useState(false);
+ const [routineOpen, setRoutineOpen] = useState(false);
const moreRef = useRef<HTMLDivElement>(null);
useEffect(() => {
@@ -81,10 +82,14 @@ export function OptionsRail({ agent, onRetired, sample = false }: OptionsRailPro
</div>
</header>
<div className="flex min-h-0 flex-1 flex-col gap-3 overflow-hidden px-3 pb-3 pt-2">
- <AgentBrowserPreview agent={agent} />
- {agent.tier === "lead" ? <JarvisHistoryRail /> : null}
+ <div className={routineOpen ? "hidden" : "contents"}>
+ <AgentBrowserPreview agent={agent} />
+ {agent.tier === "lead" ? <JarvisHistoryRail /> : null}
+ </div>
<AgentRoutinesList
+ key={agent.agentId}
agentId={agent.agentId}
+ onDetailOpenChange={setRoutineOpen}
sampleRoutines={sample ? agent.routines : undefined}
variant="rail"
className="min-h-0 flex-1"
diff --git a/jarvis/ui/web/frontend/src/components/society/card/TriggerBuilder.tsx b/jarvis/ui/web/frontend/src/components/society/card/TriggerBuilder.tsx
index 6dc687b3a8..a544ddb0e6 100644
--- a/jarvis/ui/web/frontend/src/components/society/card/TriggerBuilder.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/card/TriggerBuilder.tsx
@@ -15,16 +15,23 @@ export const TRIGGER_GROUPS = {
type Group = keyof typeof TRIGGER_GROUPS;
/** Jarvis' trigger editor: choose an entry point, then its connection or input. */
-export function TriggerBuilder({ onChange }: { onChange: (value: Record<string, unknown> | null) => void }) {
+export function TriggerBuilder({ onChange, initialValue, timeOnly = false }: {
+ onChange: (value: Record<string, unknown> | null) => void;
+ initialValue?: Record<string, unknown>;
+ timeOnly?: boolean;
+}) {
const t = useT();
useLocaleChunk("society");
- const [group, setGroup] = useState<Group>("time");
- const [kind, setKind] = useState<string>("every");
- const [time, setTime] = useState("08:00");
- const [timezone, setTimezone] = useState(() => Intl.DateTimeFormat().resolvedOptions().timeZone);
- const [amount, setAmount] = useState("5");
+ const [group, setGroup] = useState<Group>(() => {
+ const kind = String(initialValue?.type ?? "every");
+ return (Object.entries(TRIGGER_GROUPS).find(([, kinds]) => (kinds as readonly string[]).includes(kind))?.[0] ?? "time") as Group;
+ });
+ const [kind, setKind] = useState<string>(String(initialValue?.type ?? "every"));
+ const [time, setTime] = useState(String(initialValue?.local_time ?? "08:00"));
+ const [timezone, setTimezone] = useState(() => String(initialValue?.timezone ?? Intl.DateTimeFormat().resolvedOptions().timeZone));
+ const [amount, setAmount] = useState(String(Number(initialValue?.interval_seconds ?? initialValue?.delay_seconds ?? 18000) / 3600));
const [unit, setUnit] = useState("3600");
- const [expression, setExpression] = useState("0 8 * * 1-5");
+ const [expression, setExpression] = useState(String(initialValue?.expression ?? "0 8 * * 1-5"));
const [date, setDate] = useState("");
const [endpoint, setEndpoint] = useState("");
const [topic, setTopic] = useState("");
@@ -77,13 +84,16 @@ export function TriggerBuilder({ onChange }: { onChange: (value: Record<string,
return { type: "source", source, conditions };
} catch { return null; /* Invalid editor input is never submitted. */ }
}, [kind, group, filters, amount, unit, time, timezone, expression, date, endpoint, topic, consumerGroup, path, pattern, recursive, fields, upstreamKind, upstreamId, when, eventName]);
- useEffect(() => onChange(value), [onChange, value]);
+ useEffect(() => {
+ // Keep calendar restrictions and hook options the compact editor does not expose.
+ onChange(value && initialValue?.type === value.type ? { ...initialValue, ...value } : value);
+ }, [onChange, value, initialValue]);
const field = "w-full rounded-md border border-border bg-background px-2 py-1.5 text-[12px] text-foreground";
const label = (key: string) => t(`society.triggers.${key}`);
const input = (name: string, current: string, set: (v: string) => void, type = "text") => <label className="block text-[11px] text-muted-foreground">{label(name)}<input type={type} aria-label={label(name)} value={current} onChange={(e) => set(e.target.value)} className={field} /></label>;
return <div className="space-y-2" data-testid="trigger-builder">
- <BrandedSelect value={group} onValueChange={(next) => { setGroup(next as Group); setKind(TRIGGER_GROUPS[next as Group][0]); }} options={Object.keys(TRIGGER_GROUPS).map((key) => ({ value: key, label: label(`groups.${key}`) }))} testId="routine-trigger-group" ariaLabel={label("group")} />
- <BrandedSelect value={kind} onValueChange={(next) => { setKind(next); if (next.startsWith("workflow_")) { setUpstreamKind("workflow"); setUpstreamId(""); } }} options={TRIGGER_GROUPS[group].map((key) => ({ value: key, label: label(`kinds.${key}`) }))} testId="agent-routines-kind" ariaLabel={label("kind")} />
+ {!timeOnly && <BrandedSelect value={group} onValueChange={(next) => { setGroup(next as Group); setKind(TRIGGER_GROUPS[next as Group][0]); }} options={Object.keys(TRIGGER_GROUPS).map((key) => ({ value: key, label: label(`groups.${key}`) }))} testId="routine-trigger-group" ariaLabel={label("group")} />}
+ <BrandedSelect value={kind} onValueChange={(next) => { setKind(next); if (next.startsWith("workflow_")) { setUpstreamKind("workflow"); setUpstreamId(""); } }} options={TRIGGER_GROUPS[group].filter((key) => !timeOnly || ["every", "calendar", "cron"].includes(key)).map((key) => ({ value: key, label: label(`kinds.${key}`) }))} testId="agent-routines-kind" ariaLabel={label("kind")} />
{(kind === "every" || kind === "after_delay") && <div className="flex gap-2">{input("amount", amount, setAmount, "number")}<BrandedSelect ariaLabel={label("hours")} value={unit} onValueChange={setUnit} options={[{ value: "60", label: label("minutes") }, { value: "3600", label: label("hours") }, { value: "86400", label: label("days") }]} /></div>}
{kind === "calendar" && input("time", time, setTime, "time")}
{kind === "cron" && input("expression", expression, setExpression)}
diff --git a/jarvis/ui/web/frontend/src/components/society/cardData.ts b/jarvis/ui/web/frontend/src/components/society/cardData.ts
index 46568f6a11..f4de52f3cd 100644
--- a/jarvis/ui/web/frontend/src/components/society/cardData.ts
+++ b/jarvis/ui/web/frontend/src/components/society/cardData.ts
@@ -50,6 +50,8 @@ export interface LiveRoutine {
/** Next fire in epoch ms, or null when the scheduler knows none. */
dueMs: number | null;
lastRunMs: number | null;
+ prompt?: string;
+ members?: LiveRoutine[];
}
/** Per-agent browser status from `GET /api/society/agents/{id}/browser`. */
@@ -173,7 +175,9 @@ export function useAgentRoutines(agentId: string | null) {
refetchInterval: import.meta.env.MODE === "test" ? false : 5_000,
retry: false,
queryFn: async (): Promise<LiveRoutine[]> => {
- const body = await getJson<{
+ const response = await fetch(`/api/society/agents/${encodeURIComponent(agentId ?? "")}/routines`);
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
+ const body = await response.json() as {
routines?: {
id?: string;
title?: string;
@@ -181,9 +185,12 @@ export function useAgentRoutines(agentId: string | null) {
trigger?: unknown;
due_at_ns?: number;
last_run_ns?: number;
+ prompt?: string;
+ tags?: string[];
}[];
- }>(`/api/society/agents/${encodeURIComponent(agentId ?? "")}/routines`);
- return (body?.routines ?? []).map((r, i) => ({
+ };
+ const raw = body?.routines ?? [];
+ const mapped = raw.map((r, i) => ({
id: String(r.id ?? i),
title: String(r.title ?? ""),
state: String(r.state ?? ""),
@@ -191,7 +198,20 @@ export function useAgentRoutines(agentId: string | null) {
schedule: "",
dueMs: nsToMs(r.due_at_ns),
lastRunMs: nsToMs(r.last_run_ns),
+ prompt: r.prompt ?? "",
}));
+ const groups = new Map<string, LiveRoutine[]>();
+ mapped.forEach((row, i) => {
+ const group = raw[i].tags?.find((tag) => tag.startsWith("routine-group:"))?.slice(14) ?? row.id;
+ groups.set(group, [...(groups.get(group) ?? []), row]);
+ });
+ return [...groups.entries()].map(([id, members]) => {
+ members.sort((a, b) => Number(b.id === id) - Number(a.id === id));
+ const due = members.filter((m) => m.state === "scheduled" && m.dueMs).map((m) => m.dueMs!);
+ const state = members.some((m) => m.state === "running") ? "running"
+ : members.some((m) => m.state === "scheduled") ? "scheduled" : members[0].state;
+ return { ...members[0], state, members, dueMs: due.length ? Math.min(...due) : null };
+ });
},
});
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json b/jarvis/ui/web/frontend/src/i18n/locales/society/de.json
index 1b53404ad7..e491f02983 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/de.json
@@ -1,5 +1,23 @@
{
"society": {
+ "routine_detail": {
+ "test_started": "Testlauf gestartet.",
+ "active": "Aktiv",
+ "delete": "Löschen",
+ "test": "Testlauf",
+ "delete_confirm": "Diese Routine mit allen Zeitplänen und ihrem Ausführungsverlauf löschen?",
+ "cancel": "Abbrechen",
+ "name": "Name",
+ "prompt": "Anweisung",
+ "save": "Speichern",
+ "saved": "Gespeichert.",
+ "when": "Wann ausführen",
+ "add_schedule": "Weiteren Zeitplan hinzufügen",
+ "remove_schedule": "Zeitplan entfernen",
+ "history": "Ausführungsverlauf",
+ "no_runs": "Noch keine Ausführungen.",
+ "legacy": "Ältere Ausführung: Ergebnis vorhanden; Abschlussstatus wurde nicht aufgezeichnet."
+ },
"chat": {
"activity_details": "Details",
"activity_trace": "Aktivität · {count} Schritte",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json b/jarvis/ui/web/frontend/src/i18n/locales/society/en.json
index f25f71ead3..516d9ab0e5 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/en.json
@@ -1,5 +1,23 @@
{
"society": {
+ "routine_detail": {
+ "test_started": "Test run started.",
+ "active": "Active",
+ "delete": "Delete",
+ "test": "Test run",
+ "delete_confirm": "Delete this routine, all its schedules and execution history?",
+ "cancel": "Cancel",
+ "name": "Name",
+ "prompt": "Instruction",
+ "save": "Save",
+ "saved": "Saved.",
+ "when": "When to run",
+ "add_schedule": "Add another schedule",
+ "remove_schedule": "Remove schedule",
+ "history": "Execution history",
+ "no_runs": "No executions yet.",
+ "legacy": "Older execution: result available; final status was not recorded."
+ },
"chat": {
"activity_details": "Details",
"activity_trace": "Activity · {count} steps",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json b/jarvis/ui/web/frontend/src/i18n/locales/society/es.json
index ed23117764..a6e90b2978 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/es.json
@@ -1,5 +1,23 @@
{
"society": {
+ "routine_detail": {
+ "test_started": "Prueba iniciada.",
+ "active": "Activo",
+ "delete": "Eliminar",
+ "test": "Prueba",
+ "delete_confirm": "¿Eliminar esta rutina, todos sus horarios y su historial?",
+ "cancel": "Cancelar",
+ "name": "Nombre",
+ "prompt": "Instrucción",
+ "save": "Guardar",
+ "saved": "Guardado.",
+ "when": "Cuándo ejecutar",
+ "add_schedule": "Añadir otro horario",
+ "remove_schedule": "Eliminar horario",
+ "history": "Historial de ejecuciones",
+ "no_runs": "Todavía no hay ejecuciones.",
+ "legacy": "Ejecución anterior: resultado disponible; no se registró el estado final."
+ },
"chat": {
"activity_details": "Detalles",
"activity_trace": "Actividad · {count} pasos",
diff --git a/jarvis/ui/web/society_routes.py b/jarvis/ui/web/society_routes.py
index 4aa78476a6..6c3c6577d8 100644
--- a/jarvis/ui/web/society_routes.py
+++ b/jarvis/ui/web/society_routes.py
@@ -16,7 +16,7 @@ import logging
from typing import Any
from fastapi import APIRouter, HTTPException, Request
-from pydantic import BaseModel, Field
+from pydantic import BaseModel, ConfigDict, Field
from starlette.requests import HTTPConnection
from jarvis.society.events import MsgType
@@ -724,6 +724,7 @@ class RoutineBody(BaseModel):
schedule: dict[str, Any] = Field(default_factory=lambda: {"kind": "every"})
plugin_grants: list[dict[str, str]] = Field(default_factory=list)
announce_on_success: str | None = None
+ parent_task_id: str | None = None
def _task_store(request: Request) -> Any:
@@ -755,6 +756,7 @@ async def create_agent_routine(
build_task_spec,
count_routines,
create_routine,
+ is_agent_routine,
)
rt = await _runtime(request)
@@ -764,6 +766,15 @@ async def create_agent_routine(
store = _task_store(request)
if await count_routines(store, agent.agent_id) >= MAX_ROUTINES_PER_AGENT:
raise HTTPException(409, {"reason": str(FailureReason.BLOCKED_BY_POLICY)})
+ parent_spec = None
+ parent_row = None
+ if body.parent_task_id:
+ parent_row = await store.get(body.parent_task_id)
+ if parent_row is None or not is_agent_routine(parent_row, agent.agent_id):
+ raise HTTPException(404, "Parent routine not found")
+ if parent_row["state"] not in ("scheduled", "paused"):
+ raise HTTPException(409, "Wait until the routine is idle before adding a schedule")
+ parent_spec = await store.get_spec(body.parent_task_id)
try:
spec = build_task_spec(
agent,
@@ -773,17 +784,81 @@ async def create_agent_routine(
plugin_grants=body.plugin_grants,
announce_on_success=body.announce_on_success,
)
+ if parent_spec is not None:
+ if spec.trigger.type not in ("calendar", "cron", "every"):
+ raise ValueError("Additional schedules must use a recurring time trigger")
+ # Additional timings keep the existing action, grants, and identity.
+ group_tag = next(
+ (tag for tag in parent_spec.tags if tag.startswith("routine-group:")),
+ f"routine-group:{parent_spec.id}",
+ )
+ spec = parent_spec.model_copy(
+ update={
+ "id": spec.id,
+ "created_at_ns": spec.created_at_ns,
+ "trigger": spec.trigger,
+ "tags": tuple(
+ tag for tag in parent_spec.tags if not tag.startswith("routine-group:")
+ )
+ + (group_tag,),
+ }
+ )
except (ValueError, KeyError) as exc:
raise HTTPException(422, f"invalid routine: {exc}") from exc
try:
- task_id = await create_routine(
- store, getattr(request.app.state, "task_scheduler", None), spec
- )
+ if parent_row is not None and parent_row["state"] == "paused":
+ # Never register an inactive routine, even briefly, with the scheduler.
+ task_id = str(await store.insert(spec))
+ await store.update_state(task_id, "paused")
+ else:
+ task_id = await create_routine(
+ store, getattr(request.app.state, "task_scheduler", None), spec
+ )
except ValueError as exc:
raise HTTPException(422, str(exc)) from exc
return {"id": task_id, "title": spec.title, "tags": list(spec.tags)}
+class RoutineUpdateBody(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+ title: str = Field(min_length=1, max_length=200)
+ prompt: str = Field(min_length=1, max_length=16_000)
+ schedule: dict[str, Any]
+
+
[email protected]("/agents/{agent_id}/routines/{task_id}")
+async def update_agent_routine(
+ agent_id: str, task_id: str, body: RoutineUpdateBody, request: Request
+) -> dict[str, Any]:
+ """Edit an agent's routine without losing its identity or execution history."""
+ from jarvis.society.routines import is_agent_routine, manage_routine
+ from jarvis.tasks.scheduler import TaskNotFound, TaskStateConflict
+
+ rt = await _runtime(request)
+ agent = await rt.roster.resolve(agent_id)
+ store = _task_store(request)
+ row = await store.get(task_id)
+ if agent is None or row is None or not is_agent_routine(row, agent.agent_id):
+ raise HTTPException(404, "Routine not found")
+ scheduler = getattr(request.app.state, "task_scheduler", None)
+ if scheduler is None:
+ raise HTTPException(503, "The task scheduler is unavailable")
+ try:
+ await manage_routine(
+ agent,
+ {**body.model_dump(), "task_id": task_id, "operation": "update"},
+ store,
+ scheduler,
+ )
+ except TaskNotFound as exc:
+ raise HTTPException(404, "Routine not found") from exc
+ except TaskStateConflict as exc:
+ raise HTTPException(409, str(exc)) from exc
+ except (ValueError, KeyError) as exc:
+ raise HTTPException(422, str(exc)) from exc
+ return {"ok": True, "id": task_id}
+
+
# ---------------------------------------------------------------- approvals
diff --git a/tests/unit/ui/web/test_routine_editor.py b/tests/unit/ui/web/test_routine_editor.py
new file mode 100644
index 0000000000..af36d7ea6b
--- /dev/null
+++ b/tests/unit/ui/web/test_routine_editor.py
@@ -0,0 +1,148 @@
+"""Routine editing exercises the real store and scheduler without external providers."""
+
+from types import SimpleNamespace
+
+import httpx
+import pytest
+from fastapi import FastAPI
+
+from jarvis.core.bus import EventBus
+from jarvis.tasks.runner import TaskRunner
+from jarvis.tasks.scheduler import TaskScheduler
+from jarvis.tasks.store import TaskStore
+from jarvis.ui.web.society_routes import router
+
+
+class EditorRuntime:
+ def __init__(self):
+ self.roster = self
+
+ async def ensure_started(self):
+ pass # No background society workers are needed for route tests.
+
+ async def resolve(self, agent_id):
+ if agent_id not in ("mail", "other"):
+ return None
+ return SimpleNamespace(agent_id=agent_id, name=agent_id, title="", description="", focus=[])
+
+
+async def editor(tmp_path):
+ store = TaskStore(tmp_path / "tasks.db")
+ await store.init()
+ app = FastAPI()
+ app.include_router(router)
+ app.state.society = EditorRuntime()
+ app.state.task_store = store
+ app.state.task_scheduler = TaskScheduler(store, EventBus())
+ async with httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=app), base_url="http://test"
+ ) as client:
+ yield client, store, app.state.task_scheduler
+ await store.close()
+
+
+BODY = {
+ "title": "Inbox",
+ "prompt": "Read the inbox.",
+ "schedule": {"type": "calendar", "local_time": "08:00", "timezone": "Europe/Berlin"},
+ "plugin_grants": [{"plugin_id": "gmail", "scope": "read"}],
+ "announce_on_success": "Inbox ready",
+}
+URL = "/api/society/agents/mail/routines"
+
+
+async def test_update_preserves_identity_permissions_history_and_pause(editor):
+ client, store, scheduler = editor
+ response = await client.post(URL, json=BODY)
+ assert response.status_code == 200, response.text
+ task_id = response.json()["id"]
+ old = await store.get_spec(task_id)
+ await store.append_step(task_id, "log", {"event": "agent_result", "text": "Previous run"})
+ await scheduler.pause(task_id)
+ update = {k: v for k, v in BODY.items() if k in ("title", "prompt", "schedule")}
+ update.update(title="Updated", prompt="New instruction")
+ update["schedule"] = {**BODY["schedule"], "local_time": "09:30"}
+ response = await client.patch(f"{URL}/{task_id}", json=update)
+ assert response.status_code == 200, response.text
+ spec = await store.get_spec(task_id)
+ row = await store.get(task_id)
+ assert spec.id == old.id and spec.tags == old.tags
+ assert spec.action.plugin_grants == old.action.plugin_grants
+ assert spec.announce_on_success == old.announce_on_success
+ assert spec.action.prompt.endswith("New instruction")
+ assert spec.trigger.local_time == "09:30"
+ assert row["state"] == "paused"
+ assert row["steps"][0]["payload"]["text"] == "Previous run"
+ assert (
+ await client.patch(f"/api/society/agents/other/routines/{task_id}", json=update)
+ ).status_code == 404
+ await store.update_state(task_id, "running")
+ assert (await client.patch(f"{URL}/{task_id}", json=update)).status_code == 409
+
+
+async def test_add_schedule_inherits_action_and_stays_paused(editor):
+ client, store, scheduler = editor
+ root = (await client.post(URL, json=BODY)).json()["id"]
+ await scheduler.pause(root)
+ response = await client.post(
+ URL,
+ json={
+ **BODY,
+ "parent_task_id": root,
+ "prompt": "Must not replace the action",
+ "plugin_grants": [{"plugin_id": "gmail", "scope": "write"}],
+ "schedule": {"type": "every", "interval_seconds": 7200},
+ },
+ )
+ assert response.status_code == 200, response.text
+ child = response.json()["id"]
+ parent_spec, child_spec = await store.get_spec(root), await store.get_spec(child)
+ assert child_spec.action == parent_spec.action
+ assert f"routine-group:{root}" in child_spec.tags
+ assert (await store.get(child))["state"] == "paused"
+ assert child not in [task_id for _, task_id in scheduler._heap]
+ response = await client.post(
+ "/api/society/agents/other/routines", json={**BODY, "parent_task_id": root}
+ )
+ assert response.status_code == 404
+
+
+async def test_invalid_schedule_cannot_alter_existing_routine(editor):
+ client, store, _ = editor
+ root = (await client.post(URL, json=BODY)).json()["id"]
+ old = await store.get_spec(root)
+ response = await client.patch(
+ f"{URL}/{root}",
+ json={
+ "title": "Bad",
+ "prompt": "Bad",
+ "schedule": {"type": "calendar", "local_time": "25:00"},
+ },
+ )
+ assert response.status_code == 422
+ assert await store.get_spec(root) == old
+
+
+async def test_runner_records_each_success_and_failure(editor):
+ client, store, _ = editor
+ root = (await client.post(URL, json=BODY)).json()["id"]
+
+ class Brain:
+ failing = False
+
+ async def run_task(self, **kwargs):
+ if self.failing:
+ raise RuntimeError("Example failure")
+ return "Example result"
+
+ brain = Brain()
+ runner = TaskRunner(store, EventBus(), agent_brain=brain)
+ await runner.run(root)
+ brain.failing = True
+ await runner.run(root)
+ events = [step["payload"].get("event") for step in (await store.get(root))["steps"]]
+ assert events.count("run_started") == 2
+ assert events.count("run_completed") == 1
+ assert events.count("error") == 1
+ assert (await store.get(root))["state"] == "scheduled"