Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(agents): retired agents stop their routines, plus small routine and card fixes (#1035)
Ruben Lütke9dc89c1c75df
diff --git a/dodaios/agent_chat/approval_card.py b/dodaios/agent_chat/approval_card.pyindex 09d4c9b426..2bc332aa50 100644--- a/dodaios/agent_chat/approval_card.py+++ b/dodaios/agent_chat/approval_card.py@@ -187,9 +187,24 @@ def _describe("rule": None if kind == "plan" else rule,"brief": display_paths(redact_secrets(summary or ""), cwd)[:_LINE_CHARS],}+ if kind == "files" and _creates_files(args, cwd):+ # "Create this file?", not "Change this file?", for a file not there yet.+ fields["creates"] = Truereturn fields+def _creates_files(args: dict[str, Any], cwd: str) -> bool:+ """Whether every file the call names is missing, so the call creates it."""+ paths = _call_paths(args)+ if not paths:+ return False+ try:+ return not any(os.path.lexists(_absolute(path, cwd)) for path in paths)+ except (OSError, ValueError) as exc:+ log.debug("approval card: could not check whether %s exist: %s", paths, exc)+ return False++# ------------------------------------------------------------ paths as shown_SEP: Final[str] = r"[\\/]"diff --git a/dodaios/agent_chat/runner_cli.py b/dodaios/agent_chat/runner_cli.pyindex 7d83929e59..bdbcdc9a5b 100644--- a/dodaios/agent_chat/runner_cli.py+++ b/dodaios/agent_chat/runner_cli.py@@ -1226,6 +1226,26 @@ def _agy_catalog_cached() -> list[dict[str, Any]] | None:return rows if isinstance(rows, list) else None+def agy_probe_cwd() -> Path:+ """An empty, app-owned folder the ``agy models`` probe runs in.++ agy boots every MCP server of its global ``mcp_config.json`` even for+ ``models``, through ``cmd.exe`` on Windows. A server argument like+ ``pkg@>=0.26.0`` reaches cmd unquoted and its ``>`` redirects into an+ empty file named ``0.26.0`` in the probe's folder. Run in an agent's+ workspace (or the home folder) that left a stray file in every fresh+ agent; this scratch folder keeps it out of anything the person reads.+ """+ import tempfile++ folder = Path(tempfile.gettempdir()) / "dodaios-agy-probe"+ try:+ folder.mkdir(parents=True, exist_ok=True)+ except OSError:+ return _catalog_cwd()+ return folder++def read_agy_models(timeout_s: float = 8.0, *, required_model: str = "") -> list[dict[str, Any]]:"""``agy --output-format json models`` -> the folded catalog (cached 10 min).@@ -1254,7 +1274,8 @@ def read_agy_models(timeout_s: float = 8.0, *, required_model: str = "") -> listcapture_output=True,timeout=timeout_s,env=env,- cwd=str(cwd),+ # Never the workspace: see agy_probe_cwd.+ cwd=str(agy_probe_cwd()),creationflags=NO_WINDOW_CREATIONFLAGS,)text = proc.stdout.decode("utf-8", errors="replace")diff --git a/dodaios/society/routine_runner.py b/dodaios/society/routine_runner.pyindex b3dd3db8ab..d86e2114ef 100644--- a/dodaios/society/routine_runner.py+++ b/dodaios/society/routine_runner.py@@ -190,6 +190,20 @@ def _left_runtime(agent: Any, run_runtime: str) -> str:return owner if owner != "jarvis" and not run_runtime else ""+async def _routine_title(task_store: Any, task_id: str) -> str:+ """The routine's name without its ``[agent:<name>]`` prefix, or ""."""+ if task_store is None:+ return ""+ try:+ row = await task_store.get(task_id)+ except Exception: # noqa: BLE001 — the run goes on without a name+ return ""+ raw = str((row or {}).get("title") or "").strip()+ if raw.startswith("[agent:") and "]" in raw:+ raw = raw.split("]", 1)[1].strip()+ return raw++async def run_owned_routine(runtime: Any,task_id: str,@@ -279,6 +293,7 @@ async def run_owned_routine(# The run keeps its own seat and chat; the agent's one chat shows a card# that opens it (MASTERPLAN §2.10).title = next((line.strip() for line in task.splitlines() if line.strip()), task_id)+ routine_title = await _routine_title(task_store, task_id)try:await runtime.post_chat_notice(agent,@@ -289,6 +304,8 @@ async def run_owned_routine("agent_id": agent.agent_id,"agent_name": display_name(agent),"text": title[:200],+ # The routine's own name: the run's opening line in its chat.+ "title": routine_title[:200],},)except Exception: # noqa: BLE001 — the card is a projection; the run itself goes ondiff --git a/dodaios/society/routines.py b/dodaios/society/routines.pyindex b85ed608ff..02a725630a 100644--- a/dodaios/society/routines.py+++ b/dodaios/society/routines.py@@ -56,6 +56,7 @@ __all__ = ["list_routines","missing_timezone","next_run_readback",+ "retire_agent_routines","routine_seat",]@@ -392,6 +393,54 @@ async def count_routines(task_store: Any, agent_id: str) -> int:MAX_ROUTINES_PER_AGENT: Final[int] = _MAX_ROUTINES+#: Why a retired agent's routine stopped (the task's error and run log).+OWNER_ARCHIVED: Final[str] = "owner_archived"+++async def retire_agent_routines(task_store: Any, scheduler: Any | None, agent_id: str) -> int:+ """Switch off every live routine and trigger of a retired agent.++ Recurring, webhook, event and source routines are paused, so nothing+ fires for an archived agent and bringing the agent back never resumes+ them silently: the person switches each one on again. One-time+ follow-ups cannot be paused and are cancelled; a running routine is+ cancelled too. Returns how many routines were switched off.+ """+ from dodaios.tasks.scheduler import TaskStateConflict+ from dodaios.tasks.schema import PAUSABLE_TRIGGER_TYPES, TERMINAL_STATES++ stopped = 0+ live = ["pending", "scheduled", "running"]+ # Only live rows: a long Automations history cannot push a routine out of the scan.+ for row in await task_store.list(state_filter=live, limit=100_000):+ if not is_agent_routine(row, agent_id):+ continue+ state = str(row.get("state") or "")+ if state in TERMINAL_STATES or state == "paused":+ continue+ tid = str(row.get("id"))+ trigger = row.get("trigger_type") or (_summary(row).get("trigger") or {}).get("type")+ pausable = trigger in PAUSABLE_TRIGGER_TYPES and state != "running"+ if scheduler is not None:+ if pausable:+ try:+ await scheduler.pause(tid)+ stopped += 1+ continue+ except TaskStateConflict:+ # Not pausable after all (it started meanwhile): cancel it.+ pass+ if await scheduler.cancel_task(tid, reason=OWNER_ARCHIVED):+ stopped += 1+ continue+ # No live scheduler (early boot): write the state directly.+ if pausable:+ await task_store.update_state(tid, "paused")+ else:+ await task_store.update_state(tid, "cancelled", error=OWNER_ARCHIVED)+ stopped += 1+ return stopped+async def manage_routine(agent: AgentRecord, payload: dict[str, Any], task_store: Any, scheduler: Anydiff --git a/dodaios/tasks/scheduler.py b/dodaios/tasks/scheduler.pyindex d97925fd42..6e7c04ab38 100644--- a/dodaios/tasks/scheduler.py+++ b/dodaios/tasks/scheduler.py@@ -25,6 +25,7 @@ import heapqimport jsonimport loggingimport time+from collections.abc import Awaitable, Callablefrom datetime import datetimefrom typing import TYPE_CHECKING, Any, Protocol@@ -147,6 +148,8 @@ class TaskScheduler:self._running_tokens: dict[str, Any] = {}# Retained after cancel/pause so an already queued firing is revalidated.self._autonomous_ids: set[str] = set()+ #: Optional owner check (see :meth:`attach_owner_gate`).+ self._owner_gate: Callable[[tuple[str, ...]], Awaitable[bool]] | None = None# ------------------------------------------------------------------# Runner wiring (DI — the runner can be set after construction)@@ -155,6 +158,35 @@ class TaskScheduler:def attach_runner(self, runner: _Dispatchable | TaskRunner) -> None:self._runner = runner+ def attach_owner_gate(self, gate: Callable[[tuple[str, ...]], Awaitable[bool]]) -> None:+ """``gate(tags)`` is true when the task's owner is retired: skip it."""+ self._owner_gate = gate++ async def _owner_retired(self, task_id: str) -> bool:+ """Switch off a task whose owner was retired instead of running it."""+ gate = self._owner_gate+ if gate is None:+ return False+ spec = await self._store.get_spec(task_id)+ if spec is None:+ return False+ try:+ retired = await gate(tuple(spec.tags))+ except Exception: # noqa: BLE001 — an unreadable owner falls through to the runner guard+ log.warning("owner gate failed for task %s", task_id, exc_info=True)+ return False+ if not retired:+ return False+ self._remove_from_memory(task_id)+ pausable = spec.trigger.type in PAUSABLE_TRIGGER_TYPES+ await self._store.update_state(+ task_id, "paused" if pausable else "cancelled", error="owner_archived"+ )+ await self._store.append_step(+ task_id, "log", {"event": "skipped", "reason": "owner_archived"}+ )+ return True+# ------------------------------------------------------------------# Public API# ------------------------------------------------------------------@@ -1005,6 +1037,8 @@ class TaskScheduler:allowed = {"scheduled", "paused"} if allow_paused else {"scheduled"}if row is None or row["state"] not in allowed:return+ if await self._owner_retired(task_id):+ returnawait self._runner.run( # type: ignore[union-attr]task_id,token,diff --git a/dodaios/ui/web/frontend/src/components/agentchat/AgentTimeline.test.tsx b/dodaios/ui/web/frontend/src/components/agentchat/AgentTimeline.test.tsxindex 0623698802..e2f6740c5d 100644--- a/dodaios/ui/web/frontend/src/components/agentchat/AgentTimeline.test.tsx+++ b/dodaios/ui/web/frontend/src/components/agentchat/AgentTimeline.test.tsx@@ -107,3 +107,20 @@ it("says who still works on a request whose turn made room for the next message"]);expect(screen.getByTestId("turn-background").textContent).toContain("Agent T2");});++describe("the turn header's seat", () => {+ it("names the provider and model by their readable names", () => {+ const events = [+ ev("turn_started", { turn_id: "s1", provider: "claude-api", model: "claude-sonnet-5-5" }),+ ev("assistant_text", { turn_id: "s1", message_id: "m", text: "ok" }),+ ev("turn_finished", { turn_id: "s1", status: "done" }),+ ];+ render(<AgentTimeline items={reduceEvents(EMPTY_TIMELINE, events).items} assistantName="Mailbox"+ providerLabel={(id) => (id === "claude-api" ? "Anthropic Claude" : id)}+ modelLabel={(_p, model) => (model === "claude-sonnet-5-5" ? "Claude Sonnet 5.5" : model)}+ onDecide={() => undefined} />);+ const turn = screen.getByTestId("agent-turn");+ expect(turn.textContent).toContain("Anthropic Claude · Claude Sonnet 5.5");+ expect(turn.textContent).not.toContain("claude-sonnet-5-5");+ });+});diff --git a/dodaios/ui/web/frontend/src/components/agentchat/AgentTimeline.tsx b/dodaios/ui/web/frontend/src/components/agentchat/AgentTimeline.tsxindex 3502850f02..4e317821b9 100644--- a/dodaios/ui/web/frontend/src/components/agentchat/AgentTimeline.tsx+++ b/dodaios/ui/web/frontend/src/components/agentchat/AgentTimeline.tsx@@ -21,6 +21,7 @@ export function AgentTimeline({items,assistantName,providerLabel,+ modelLabel,onDecide,recipientName,agentsById,@@ -32,6 +33,8 @@ export function AgentTimeline({items: TimelineItem[];assistantName: string;providerLabel: (providerId: string) => string;+ /** The model's readable name; the raw id when absent. */+ modelLabel?: (providerId: string, modelId: string) => string;onDecide: Decide;/** Who an internal agent message was sent to — the chat owner (defaults to the assistant). */recipientName?: string;@@ -257,6 +260,7 @@ export function AgentTimeline({turn={item}assistantName={assistantName}providerLabel={providerLabel(item.provider)}+ modelName={item.model ? (modelLabel?.(item.provider, item.model) || item.model) : ""}onDecide={onDecide}bubbles={bubbles}traceLook={traceLook}@@ -306,8 +310,8 @@ function stampLabel(at: Date, now: Date): string {const NO_MESSAGES = new Map<string, TraceMessage[]>();-const Turn = memo(function Turn({ turn, assistantName, providerLabel, onDecide, bubbles = false, traceLook, traceCompanion = false, traceFace, messages }: {- turn: TurnItem; assistantName: string; providerLabel: string; onDecide: Decide; bubbles?: boolean; traceLook: TraceLook; traceCompanion?: boolean; traceFace?: ReactNode;+const Turn = memo(function Turn({ turn, assistantName, providerLabel, modelName, onDecide, bubbles = false, traceLook, traceCompanion = false, traceFace, messages }: {+ turn: TurnItem; assistantName: string; providerLabel: string; modelName?: string; onDecide: Decide; bubbles?: boolean; traceLook: TraceLook; traceCompanion?: boolean; traceFace?: ReactNode;/** Agent messages that arrived while this turn worked. */messages?: TraceMessage[];}) {@@ -321,7 +325,7 @@ const Turn = memo(function Turn({ turn, assistantName, providerLabel, onDecide,<div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground"><span className="font-medium text-foreground">{assistantName}</span><ProviderLogo providerId={turn.provider} label={providerLabel} size="sm" />- <span>{providerLabel}{turn.model ? ` · ${turn.model}` : ""}</span>+ <span>{providerLabel}{turn.model ? ` · ${modelName || turn.model}` : ""}</span>{turn.effort ? <span>{effortLabel(turn.effort, t)}</span> : null}</div>)}diff --git a/dodaios/ui/web/frontend/src/components/agentchat/actionCard/approvalCopy.ts b/dodaios/ui/web/frontend/src/components/agentchat/actionCard/approvalCopy.tsindex d47820251e..4626d93818 100644--- a/dodaios/ui/web/frontend/src/components/agentchat/actionCard/approvalCopy.ts+++ b/dodaios/ui/web/frontend/src/components/agentchat/actionCard/approvalCopy.ts@@ -148,6 +148,7 @@ export function approvalTitle(info: ApprovalCardInfo, t: T): string {return app ? fill(t("action_card.title.connector"), { app }) : t("action_card.title.tool_plain");}if (kind === "tool") return app ? fill(t("action_card.title.tool"), { tool: app }) : t("action_card.title.tool_plain");+ if (kind === "files" && info.creates) return t("action_card.title.files_create");return t(`action_card.title.${kind}`);}diff --git a/dodaios/ui/web/frontend/src/components/agentchat/actionCard/approvalCreateTitle.test.ts b/dodaios/ui/web/frontend/src/components/agentchat/actionCard/approvalCreateTitle.test.tsnew file mode 100644index 0000000000..0b7335fe13--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/agentchat/actionCard/approvalCreateTitle.test.ts@@ -0,0 +1,20 @@+import { describe, expect, it } from "vitest";+import { parseApprovalCard } from "./approvalInfo";+import { approvalTitle } from "./approvalCopy";++const t = (key: string) => key;+const card = (extra: Record<string, unknown> = {}) => parseApprovalCard({+ source: { kind: "files", app: "", verb: "" }, where: "", where_full: "", why: "", caution: "", detail: "", brief: "", rule: null, ...extra,+})!;++describe("a file approval's question", () => {+ it("asks to create a file that does not exist yet", () => {+ expect(card({ creates: true }).creates).toBe(true);+ expect(approvalTitle(card({ creates: true }), t)).toBe("action_card.title.files_create");+ });++ it("asks to change a file that is already there", () => {+ expect(card().creates).toBeUndefined();+ expect(approvalTitle(card(), t)).toBe("action_card.title.files");+ });+});diff --git a/dodaios/ui/web/frontend/src/components/agentchat/actionCard/approvalInfo.ts b/dodaios/ui/web/frontend/src/components/agentchat/actionCard/approvalInfo.tsindex 26c4ea5f0d..0a6e0d443c 100644--- a/dodaios/ui/web/frontend/src/components/agentchat/actionCard/approvalInfo.ts+++ b/dodaios/ui/web/frontend/src/components/agentchat/actionCard/approvalInfo.ts@@ -51,6 +51,8 @@ export interface ApprovalCardInfo {rule: ApprovalRuleOffer | null;/** One of the agents' own tools, by what it does ("Create a routine"); absent for any other call. */action?: string;+ /** A file call whose target does not exist yet: the card asks to create it. */+ creates?: boolean;}/** A standing rule saved from a card (`notice{kind:"approval_rule"}`). */@@ -90,6 +92,7 @@ export function parseApprovalCard(payload: Record<string, unknown>): ApprovalCardetail: text(payload.detail),brief: text(payload.brief),rule: parseRuleOffer(payload.rule),+ ...(payload.creates === true ? { creates: true } : {}),};}diff --git a/dodaios/ui/web/frontend/src/components/agentchat/inspector/WorkInspector.test.tsx b/dodaios/ui/web/frontend/src/components/agentchat/inspector/WorkInspector.test.tsxindex 5198ce8291..f46bea28d8 100644--- a/dodaios/ui/web/frontend/src/components/agentchat/inspector/WorkInspector.test.tsx+++ b/dodaios/ui/web/frontend/src/components/agentchat/inspector/WorkInspector.test.tsx@@ -239,6 +239,8 @@ describe("the inspector's cost", () => {const meta = screen.getByTestId("work-inspector").querySelector(".wi-meta")!.textContent ?? "";expect(meta).toContain("Included in your plan");expect(meta).not.toContain("$");+ // Cost and model have a line of their own, so a narrow pane never cuts them off.+ expect(screen.getByTestId("work-inspector-seat").textContent).toContain("Included in your plan");});it("keeps the amount for a per-token key", () => {diff --git a/dodaios/ui/web/frontend/src/components/agentchat/inspector/WorkInspector.tsx b/dodaios/ui/web/frontend/src/components/agentchat/inspector/WorkInspector.tsxindex 206d988bd2..7fd32c1548 100644--- a/dodaios/ui/web/frontend/src/components/agentchat/inspector/WorkInspector.tsx+++ b/dodaios/ui/web/frontend/src/components/agentchat/inspector/WorkInspector.tsx@@ -105,11 +105,14 @@ export const WorkInspector = memo(function WorkInspector({if (turn.status === "running") meta.push(t("run_view.work.working"));else if (turn.durationMs) meta.push(fill(t("run_view.work.worked_for"), { duration: traceDuration(turn.durationMs) }));if (tokens && tokens > 0) meta.push(fill(t("run_view.inspector.tokens"), { count: formatTokens(tokens) }));+ // Cost and model sit on a quiet line of their own, so a narrow pane never+ // cuts "Included in your plan" off the end of one long line.+ const seat: string[] = [];if (turn.costUsd !== null && turn.costUsd > 0) {// A subscription bills nothing per turn: a dollar figure would contradict "$0.00 spent".- meta.push(billedPerToken(turn) ? `$${turn.costUsd.toFixed(4)}` : t("run_view.inspector.included"));+ seat.push(billedPerToken(turn) ? `$${turn.costUsd.toFixed(4)}` : t("run_view.inspector.included"));}- if (turn.model) meta.push(turn.model);+ if (turn.model) seat.push(turn.model);return <aside ref={pane} tabIndex={-1} aria-labelledby={titleId}className={cn("work-inspector", floating && "is-floating")}@@ -120,7 +123,10 @@ export const WorkInspector = memo(function WorkInspector({{avatar ? <span className="wi-head-mark" aria-hidden>{avatar}</span> : null}<div className="min-w-0 flex-1"><h2 id={titleId} className="wi-title">{t("run_view.inspector.title")}</h2>- <p className="wi-meta">{meta.join(" · ")}</p>+ <p className="wi-meta">+ <span className="wi-meta-line">{meta.join(" · ")}</span>+ {seat.length ? <span className="wi-meta-line wi-meta-seat" data-testid="work-inspector-seat">{seat.join(" · ")}</span> : null}+ </p></div><button type="button" className="wi-icon-btn" onClick={onClose} aria-label={t("run_view.inspector.close")} title={t("run_view.inspector.close")}data-testid="work-inspector-close">diff --git a/dodaios/ui/web/frontend/src/components/agentchat/inspector/inspector.css b/dodaios/ui/web/frontend/src/components/agentchat/inspector/inspector.cssindex 4d205a0af9..50194872bd 100644--- a/dodaios/ui/web/frontend/src/components/agentchat/inspector/inspector.css+++ b/dodaios/ui/web/frontend/src/components/agentchat/inspector/inspector.css@@ -79,14 +79,22 @@color: hsl(var(--foreground-strong));}.wi-meta {- overflow: hidden;+ display: flex;+ flex-direction: column;+ min-width: 0;color: hsl(var(--muted-foreground));font-size: 13px;line-height: 18px;font-variant-numeric: tabular-nums;+}+.wi-meta-line {+ overflow: hidden;text-overflow: ellipsis;white-space: nowrap;}+.wi-meta-seat {+ font-size: 12px;+}.wi-icon-btn {display: inline-flex;flex: none;diff --git a/dodaios/ui/web/frontend/src/components/society/card/AgentRoutinesList.test.tsx b/dodaios/ui/web/frontend/src/components/society/card/AgentRoutinesList.test.tsxindex 059c211ce0..27024fc94b 100644--- a/dodaios/ui/web/frontend/src/components/society/card/AgentRoutinesList.test.tsx+++ b/dodaios/ui/web/frontend/src/components/society/card/AgentRoutinesList.test.tsx@@ -117,6 +117,26 @@ describe("AgentRoutinesList", () => {expect(await screen.findByTestId("routine-opened")).toBeTruthy();});+ test("closing the form drops its draft, so new text never lands in front of a hidden one", async () => {+ mount();+ await screen.findByRole("button", { name: "Morning inbox" });+ const add = screen.getByTestId("agent-routines-add");+ fireEvent.click(add);+ const composer = screen.getByTestId("agent-routines-composer");+ const [title] = composer.querySelectorAll("input");+ const prompt = composer.querySelector("textarea")!;+ fireEvent.change(title, { target: { value: "Old title" } });+ fireEvent.change(prompt, { target: { value: "Old prompt" } });+ fireEvent.change(screen.getByTestId("agent-routines-when"), { target: { value: "every day at 7" } });+ fireEvent.click(add); // the X+ expect(screen.queryByTestId("agent-routines-composer")).toBeNull();+ fireEvent.click(add);+ const reopened = screen.getByTestId("agent-routines-composer");+ expect((reopened.querySelector("input") as HTMLInputElement).value).toBe("");+ expect((reopened.querySelector("textarea") as HTMLTextAreaElement).value).toBe("");+ expect((screen.getByTestId("agent-routines-when") as HTMLInputElement).value).toBe("");+ });+test("adding a routine posts to this agent and shows the new row", async () => {mount();fireEvent.click(await screen.findByTestId("agent-routines-add"));diff --git a/dodaios/ui/web/frontend/src/components/society/card/AgentRoutinesList.tsx b/dodaios/ui/web/frontend/src/components/society/card/AgentRoutinesList.tsxindex b1d5d0f121..7c5bda0607 100644--- a/dodaios/ui/web/frontend/src/components/society/card/AgentRoutinesList.tsx+++ b/dodaios/ui/web/frontend/src/components/society/card/AgentRoutinesList.tsx@@ -55,10 +55,15 @@ export function AgentRoutinesList({ agentId, sampleRoutines, variant = "rail", cconst target = { tier: agent?.tier ?? "specialist", chatSessionId: agent?.chatSessionId ?? `society:${agentId}` };const setUpInChat = () => void seedAgentComposer(target, own("setup_prompt"));const field = "w-full rounded-lg border border-border bg-background px-2.5 py-1.5 text-[12px] text-foreground placeholder:text-faint-foreground transition-colors focus:border-border-strong focus:outline-none";+ // Closing the form drops what it held: a draft nobody sees must never+ // come back under the caret the next time the form opens.+ const closeForm = () => {+ setOpen(false); setTitle(""); setPrompt(""); setWhen(""); setMore(false); setBuilt(null); setError("");+ };const submit = async () => {if (!title.trim() || !prompt.trim() || !schedule) return;setSaving(true); setError("");- try { await create(agentId, { title: title.trim(), prompt: prompt.trim(), schedule }); setTitle(""); setPrompt(""); setWhen(""); setMore(false); setOpen(false); }+ try { await create(agentId, { title: title.trim(), prompt: prompt.trim(), schedule }); closeForm(); }catch (err) { setError(err instanceof Error ? err.message : String(err)); }finally { setSaving(false); }};@@ -72,7 +77,7 @@ export function AgentRoutinesList({ agentId, sampleRoutines, variant = "rail", c{t("society.card.routines")}</h3><div className="flex items-center gap-0.5">- <button type="button" data-testid="agent-routines-add" className="as-round-button h-7 w-7" aria-label={t("society.card.routines_add")} aria-expanded={open} onClick={() => setOpen((v) => !v)}>{open ? <X size={14} /> : <Plus size={14} />}</button>+ <button type="button" data-testid="agent-routines-add" className="as-round-button h-7 w-7" aria-label={t("society.card.routines_add")} aria-expanded={open} onClick={() => (open ? closeForm() : setOpen(true))}>{open ? <X size={14} /> : <Plus size={14} />}</button></div></div>{parking?.banner && parking.parked_ids.length > 0 && <ParkingBanner agentId={agentId} parking={parking} onAnswered={() => void refresh()} />}@@ -92,7 +97,7 @@ export function AgentRoutinesList({ agentId, sampleRoutines, variant = "rail", conClick={() => setMore((v) => !v)} data-testid="agent-routines-more">{own(more ? "fewer_options" : "more_options")}</button>{more ? <TriggerBuilder onChange={setBuilt} /> : null}<div className="flex items-center justify-between gap-2 pt-0.5">- {!isSample ? <button type="button" className="text-[12px] text-muted-foreground underline-offset-2 hover:text-foreground hover:underline" onClick={() => { setOpen(false); setUpInChat(); }}>{own("or_chat")}</button> : <span />}+ {!isSample ? <button type="button" className="text-[12px] text-muted-foreground underline-offset-2 hover:text-foreground hover:underline" onClick={() => { closeForm(); setUpInChat(); }}>{own("or_chat")}</button> : <span />}<button type="submit" disabled={saving || !title.trim() || !prompt.trim() || !schedule} className="rounded-full bg-foreground px-3.5 py-1.5 text-[13px] font-medium text-background transition-colors hover:bg-foreground/90 disabled:opacity-40">{t(saving ? "society.card.saving" : "society.card.routines_save")}</button></div>{error && <p role="alert" className="text-[12px] text-destructive">{error}</p>}diff --git a/dodaios/ui/web/frontend/src/components/society/card/RoutineChat.test.tsx b/dodaios/ui/web/frontend/src/components/society/card/RoutineChat.test.tsxindex 716c111d57..0d72795524 100644--- a/dodaios/ui/web/frontend/src/components/society/card/RoutineChat.test.tsx+++ b/dodaios/ui/web/frontend/src/components/society/card/RoutineChat.test.tsx@@ -1,7 +1,7 @@import { cleanup, render, screen } from "@testing-library/react";import { afterEach, expect, test, vi } from "vitest";import type { TimelineItem } from "@/components/agentchat/reduce";-import RoutineChat from "./RoutineChat";+import RoutineChat, { splitOpening } from "./RoutineChat";import type { RoutineChatTarget } from "../chat/routineExecution";vi.mock("@/i18n", () => ({ useT: () => (key: string) => key, useUiLanguage: () => "en" }));@@ -33,8 +33,9 @@ test("an old execution loads its own turn without opening a writable main chat",expect(transcript.textContent).not.toContain("Follow your CURRENT");expect(socket).not.toHaveBeenCalled();expect(screen.queryByRole("textbox")).toBeNull();- expect(fetcher).toHaveBeenCalledOnce();- expect(fetcher.mock.calls[0]).toEqual(["/api/agent-chat/sessions/society%3Amail"]);+ // The seat names may load the chat catalog; the transcript is one read of its session.+ const sessionReads = fetcher.mock.calls.filter((call: unknown[]) => String(call[0]).startsWith("/api/agent-chat/sessions"));+ expect(sessionReads).toEqual([["/api/agent-chat/sessions/society%3Amail"]]);// An old task could succeed through a fallback after its chat attempt failed.expect(screen.getByTestId("routine-saved-result").textContent).toContain("Saved result");});@@ -53,3 +54,28 @@ test("a missing historical turn shows only that execution's saved result", asyncexpect(screen.queryByTestId("selected-transcript")).toBeNull();expect(screen.queryByRole("textbox")).toBeNull();});++test("a run opens with the routine's name; the scheduler's instructions wait behind a toggle", async () => {+ vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({ session: { title: "Mail" }, events }))));+ render(<RoutineChat target={target} onClose={() => {}} />);+ const opening = await screen.findByTestId("routine-opening");+ expect(opening.textContent).toContain("Inbox");+ expect(opening.querySelector("details")?.textContent).toContain("Read mail.");+ expect(opening.textContent).not.toContain("Scheduled routine");+});++test("the current scheduler envelope never shows raw in a run", () => {+ const current = "Scheduled routine 96a6671f-0b1c-4f7e-9a51-1c2d3e4f5a6b. Follow your CURRENT standing instructions.\n"+ + "This execution has its own background chat and must honor its permission limits.\n"+ + "Use your memory and conversation archive for prior results. For information watches, check sources and dates, remember last-seen items, and report only meaningful new findings.\n\nSummarize the inbox.";+ const items = [+ { type: "user", id: "u1", text: current, attachments: [], tsMs: 1 },+ { type: "user", id: "u2", text: "And the calendar?", attachments: [], tsMs: 2 },+ ] as unknown as TimelineItem[];+ const { prompt, rest } = splitOpening(items);+ expect(prompt).toBe("Summarize the inbox.");+ expect(rest).toHaveLength(1);+ expect(JSON.stringify(rest)).not.toContain("Scheduled routine");+ // A conversation that is not a routine run keeps its first message.+ expect(splitOpening([items[1]]).prompt).toBeNull();+});diff --git a/dodaios/ui/web/frontend/src/components/society/card/RoutineChat.tsx b/dodaios/ui/web/frontend/src/components/society/card/RoutineChat.tsxindex ad25a05e4e..17b17939b3 100644--- a/dodaios/ui/web/frontend/src/components/society/card/RoutineChat.tsx+++ b/dodaios/ui/web/frontend/src/components/society/card/RoutineChat.tsx@@ -2,14 +2,14 @@* The selected routine run or agent conversation occupies the agent's chat* lane and loads only on navigation.*/-import { useEffect, useMemo, useState, type ReactNode } from "react";+import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react";import { ArrowLeft, Send, Square } from "lucide-react";import { AgentTimeline } from "@/components/agentchat/AgentTimeline";import { ChatMarkdown } from "@/components/agentchat/ChatMarkdown";import { EMPTY_TIMELINE, reduceEvents, runningTurn, type TimelineItem } from "@/components/agentchat/reduce";import { AgentChatStoreProvider } from "@/components/agentchat/AgentChatStoreContext";import { fetchAgentChatSession } from "@/lib/agentChatApi";-import { createAgentChatStore } from "@/store/agentChat";+import { createAgentChatStore, useAgentChatStore } from "@/store/agentChat";import { useStickToBottom } from "@/hooks/useStickToBottom";import { useT } from "@/i18n";import { useRunLocale } from "@/components/runs/format";@@ -19,6 +19,51 @@ function displayItems(items: TimelineItem[]): TimelineItem[] {return items.map((item) => item.type === "user" ? { ...item, text: routineTask(item.text) ?? item.text } : item);}+/**+ * A run opens with the scheduler's instructions to the agent. The person+ * reads the routine's name there; the full prompt stays one click away.+ */+export function splitOpening(items: TimelineItem[]): { prompt: string | null; rest: TimelineItem[] } {+ const index = items.findIndex((item) => item.type === "user");+ const first = index >= 0 ? items[index] : null;+ const prompt = first && first.type === "user" ? routineTask(first.text) : null;+ if (prompt === null) return { prompt: null, rest: displayItems(items) };+ return { prompt, rest: displayItems(items.filter((_, i) => i !== index)) };+}++function RoutineOpening({ title, prompt }: { title: string; prompt: string }) {+ const t = useT();+ return <div className="ml-auto flex max-w-[min(85%,42rem)] flex-col gap-1 rounded-lg bg-card px-4 py-2.5 text-sm" data-testid="routine-opening">+ <p className="font-medium text-foreground">{title}</p>+ {prompt.trim() && prompt.trim() !== title.trim() ? <details className="text-xs text-muted-foreground">+ <summary className="cursor-pointer select-none">{t("society.routine_detail.full_prompt")}</summary>+ <ChatMarkdown text={prompt} className="mt-1 text-muted-foreground" />+ </details> : null}+ </div>;+}++/** Readable provider and model names from the chat catalog; the raw id until it loads. */+function useSeatLabels() {+ const catalog = useAgentChatStore((s) => s.catalog);+ const catalogStale = useAgentChatStore((s) => s.catalogStale);+ const loadCatalog = useAgentChatStore((s) => s.loadCatalog);+ useEffect(() => {+ if (!catalog || catalogStale) void loadCatalog();+ }, [catalog, catalogStale, loadCatalog]);+ const providerLabel = useCallback(+ (id: string) => catalog?.providers.find((p) => p.id === id)?.label ?? id,+ [catalog],+ );+ const modelLabel = useCallback(+ (providerId: string, modelId: string) =>+ catalog?.providers.find((p) => p.id === providerId)?.curated_models.find((m) => m.id === modelId)?.label+ ?? catalog?.providers.flatMap((p) => p.curated_models).find((m) => m.id === modelId)?.label+ ?? modelId,+ [catalog],+ );+ return { providerLabel, modelLabel };+}+export default function RoutineChat({ target, onClose, face }: {target: RoutineChatTarget; onClose: () => void;/** The agent's face for the live line of a running trace. */@@ -34,23 +79,25 @@ export default function RoutineChat({ target, onClose, face }: {</div><span className="text-xs text-muted-foreground">{t(target.kind === "conversation" ? "society.conversations.badge" : "society.routine_detail.background_chat")}</span></header>- {target.legacy ? <HistoricalExecution target={target} /> : <LiveExecution sessionId={target.sessionId} conversation={target.kind === "conversation"} face={face} />}+ {target.legacy ? <HistoricalExecution target={target} /> : <LiveExecution sessionId={target.sessionId} title={target.title} conversation={target.kind === "conversation"} face={face} />}</section>;}function HistoricalExecution({ target }: { target: RoutineChatTarget }) {const t = useT();- const [snapshot, setSnapshot] = useState<{ name: string; items: TimelineItem[]; resultInChat: boolean } | null>(null);+ const [snapshot, setSnapshot] = useState<{ name: string; items: TimelineItem[]; opening: string | null; resultInChat: boolean } | null>(null);const [error, setError] = useState("");+ const labels = useSeatLabels();useEffect(() => {let alive = true;void fetchAgentChatSession(target.sessionId).then(({ session, events }) => {if (!alive) return;const selected = legacyRoutineEvents(events, target);- const items = displayItems(reduceEvents(EMPTY_TIMELINE, selected).items).map((item) => item.type === "turn"+ const { prompt: opening, rest } = splitOpening(reduceEvents(EMPTY_TIMELINE, selected).items);+ const items = rest.map((item) => item.type === "turn"? { ...item, blocks: item.blocks.map((block) => block.kind === "tool" ? { ...block, approval: null } : block) } : item);const replies = items.flatMap((item) => item.type === "turn" ? item.blocks.flatMap((block) => block.kind === "text" ? [block.text] : []) : []).join("\n");- setSnapshot({ name: session.title, items, resultInChat: Boolean(target.result?.trim() && replies.includes(target.result.trim())) });+ setSnapshot({ name: session.title, items, opening, resultInChat: Boolean(target.result?.trim() && replies.includes(target.result.trim())) });}).catch((err) => { if (alive) setError(err instanceof Error ? err.message : String(err)); });return () => { alive = false; };}, [target]);@@ -58,8 +105,9 @@ function HistoricalExecution({ target }: { target: RoutineChatTarget }) {<div className="min-h-0 flex-1 space-y-4 overflow-y-auto py-4" data-testid="routine-historical-transcript">{!snapshot && !error && <p role="status">{t("tasks_view.loading_details")}</p>}{error && <p role="alert" className="text-sm text-destructive">{error}</p>}- {snapshot?.items.length ? <AgentTimeline items={snapshot.items} assistantName={snapshot.name} providerLabel={(id) => id} onDecide={async () => { /* Historical approvals are hidden; this transcript cannot act. */ }} /> : null}- {(snapshot?.items.length === 0 || error) && <>+ {snapshot?.opening != null ? <RoutineOpening title={target.title} prompt={snapshot.opening} /> : null}+ {snapshot?.items.length ? <AgentTimeline items={snapshot.items} assistantName={snapshot.name} providerLabel={labels.providerLabel} modelLabel={labels.modelLabel} onDecide={async () => { /* Historical approvals are hidden; this transcript cannot act. */ }} /> : null}+ {(snapshot?.items.length === 0 && snapshot.opening == null || error) && <><p className="text-sm text-muted-foreground">{t("society.routine_detail.trace_unavailable")}</p></>}{(snapshot || error) && target.result && !snapshot?.resultInChat && <section className="space-y-2 border-t border-border pt-3" data-testid="routine-saved-result">@@ -71,13 +119,14 @@ function HistoricalExecution({ target }: { target: RoutineChatTarget }) {</>;}-function LiveExecution({ sessionId, conversation = false, face }: { sessionId: string; conversation?: boolean; face?: ReactNode }) {+function LiveExecution({ sessionId, title, conversation = false, face }: { sessionId: string; title: string; conversation?: boolean; face?: ReactNode }) {const t = useT();const label = (key: string) => t(`society.routine_detail.${key}`);const followUp = conversation ? t("society.conversations.follow_up") : label("follow_up");const [store] = useState(() => createAgentChatStore("society", "routine"));const timeline = store((state) => state.timeline);- const visibleItems = useMemo(() => displayItems(timeline.items), [timeline.items]);+ const { prompt: opening, rest: visibleItems } = useMemo(() => splitOpening(timeline.items), [timeline.items]);+ const labels = useSeatLabels();const session = store((state) => state.activeSession);const busy = store((state) => state.busy);const socketState = store((state) => state.socketState);@@ -93,7 +142,8 @@ function LiveExecution({ sessionId, conversation = false, face }: { sessionId: sreturn <AgentChatStoreProvider store={store}><div ref={scroll.rootRef} className="min-h-0 flex-1 overflow-y-auto py-4"><div ref={scroll.contentRef} className="space-y-3">{!ready && !error && <p role="status" className="text-sm">{t("tasks_view.loading_details")}</p>}- <AgentTimeline items={visibleItems} assistantName={session?.title.split(" · ")[0] ?? ""} providerLabel={(id) => id} onDecide={store.getState().decide} traceFace={face} />+ {opening !== null ? <RoutineOpening title={title} prompt={opening} /> : null}+ <AgentTimeline items={visibleItems} assistantName={session?.title.split(" · ")[0] ?? ""} providerLabel={labels.providerLabel} modelLabel={labels.modelLabel} onDecide={store.getState().decide} traceFace={face} /></div></div>{error && <p role="alert" className="text-sm text-destructive">{error}</p>}<form className="mt-3 flex shrink-0 items-end gap-2" onSubmit={(event) => {diff --git a/dodaios/ui/web/frontend/src/components/society/card/pane/OverviewTab.tsx b/dodaios/ui/web/frontend/src/components/society/card/pane/OverviewTab.tsxindex 2d30d8c509..9368cf3ec8 100644--- a/dodaios/ui/web/frontend/src/components/society/card/pane/OverviewTab.tsx+++ b/dodaios/ui/web/frontend/src/components/society/card/pane/OverviewTab.tsx@@ -124,6 +124,7 @@ export function OverviewTab({ agent, sample, queue, onTab, onPage, onModelSaving? t("society.agent_pane.tools_allowlist_detail").replace("{0}", String(agent.toolGrants.length)): t("society.agent_pane.tools_all_detail");+ const perToken = agent.billedPerToken !== false;const capped = agent.dailyBudgetUsd > 0;const spent = agent.stats.spentTodayUsd;const share = capped ? Math.min(1, spent / agent.dailyBudgetUsd) : 0;@@ -260,19 +261,17 @@ export function OverviewTab({ agent, sample, queue, onTab, onPage, onModelSaving</PaneSection><div className="ap-record" data-testid="agent-pane-record">- <p>- {t("society.agent_pane.record_line")- .replace("{0}", String(agent.stats.runs))- .replace("{1}", `$${agent.stats.totalCostUsd.toFixed(2)}`)- .replace("{2}", lastActive)}- </p>- <p>- {t("society.card.meter_today")}:{" "}- {capped- ? t("society.card.spent_of").replace("{0}", spent.toFixed(2)).replace("{1}", agent.dailyBudgetUsd.toFixed(2))- : `$${spent.toFixed(2)} · ${t("society.card.no_cap")}`}- </p>- {capped ? (+ <p>{recordLine(t, locale, agent, lastActive)}</p>+ {/* A subscription or local model spends nothing per run: no dollar lines. */}+ {perToken ? (+ <p>+ {t("society.card.meter_today")}:{" "}+ {capped+ ? t("society.card.spent_of").replace("{0}", spent.toFixed(2)).replace("{1}", agent.dailyBudgetUsd.toFixed(2))+ : `$${spent.toFixed(2)} · ${t("society.card.no_cap")}`}+ </p>+ ) : null}+ {perToken && capped ? (<div className="ap-meter" data-full={share >= 1 ? "true" : undefined} role="img" aria-label={`${t("society.card.meter_today")}: $${spent.toFixed(2)}`}><span className="ap-meter-fill" style={{ width: `${Math.round(share * 100)}%` }} /></div>@@ -282,6 +281,32 @@ export function OverviewTab({ agent, sample, queue, onTab, onPage, onModelSaving);}+/**+ * "3 runs · $1.20 spent · last active 12 Oct": the money only where a+ * per-token key pays for the runs; a plan or a local model shows none.+ */+export function recordLine(+ t: (key: string) => string,+ locale: string,+ agent: Pick<SocietyAgent, "stats" | "billedPerToken">,+ lastActive: string,+): string {+ const runs = agent.stats.runs;+ const one = (() => {+ try {+ return new Intl.PluralRules(locale).select(runs) === "one";+ } catch {+ return runs === 1;+ }+ })();+ const parts = [t(one ? "society.agent_pane.record_runs_one" : "society.agent_pane.record_runs").replace("{0}", String(runs))];+ if (agent.billedPerToken !== false) {+ parts.push(t("society.agent_pane.record_spent").replace("{0}", `$${agent.stats.totalCostUsd.toFixed(2)}`));+ }+ parts.push(t("society.agent_pane.record_last_active").replace("{0}", lastActive));+ return parts.join(" · ");+}+/** The lead thinks with the app's own model choice; shown here, changed in its chat. */function LeadModelRow() {const t = useT();diff --git a/dodaios/ui/web/frontend/src/components/society/card/pane/recordLine.test.ts b/dodaios/ui/web/frontend/src/components/society/card/pane/recordLine.test.tsnew file mode 100644index 0000000000..ac76c828c8--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/card/pane/recordLine.test.ts@@ -0,0 +1,23 @@+import { describe, expect, it } from "vitest";++import en from "@/i18n/locales/society/en.json";+import de from "@/i18n/locales/society/de.json";+import { recordLine } from "./OverviewTab";++type Dict = Record<string, unknown>;+const lookup = (dict: Dict) => (key: string) =>+ String(key.split(".").reduce<unknown>((node, part) => (node as Dict | undefined)?.[part], dict) ?? key);+const stats = (runs: number) => ({ runs, totalCostUsd: 1.2, spentTodayUsd: 0, lastActiveMs: null });++describe("the agent's record line", () => {+ it("says one run, not one runs", () => {+ expect(recordLine(lookup(en as Dict), "en", { stats: stats(1) }, "12 Oct")).toBe("1 run · $1.20 spent · last active 12 Oct");+ expect(recordLine(lookup(en as Dict), "en", { stats: stats(3) }, "12 Oct")).toBe("3 runs · $1.20 spent · last active 12 Oct");+ expect(recordLine(lookup(de as Dict), "de", { stats: stats(1) }, "12. Okt.")).toBe("1 Lauf · $1.20 ausgegeben · zuletzt aktiv 12. Okt.");+ });++ it("shows no money on a subscription seat", () => {+ const line = recordLine(lookup(en as Dict), "en", { stats: stats(2), billedPerToken: false }, "12 Oct");+ expect(line).toBe("2 runs · last active 12 Oct");+ });+});diff --git a/dodaios/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx b/dodaios/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsxindex 09ab79d921..d245a6367a 100644--- a/dodaios/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx+++ b/dodaios/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx@@ -933,9 +933,11 @@ export function NoticeLine({ item }: { item: NoticeItem }) {if (item.kind === "routine_run") {const sessionId = String(item.data.session_id ?? "");const agentId = item.agentId || String(item.data.agent_id ?? "");- return <RoutineActivity task={item.text} original={item.text}+ // The routine's own name labels the run; older notices fall back to its first line.+ const name = String(item.data.title ?? "").trim() || item.text;+ return <RoutineActivity task={name} original={item.text}onOpen={sessionId && agentId ? () => useRoutineNavigation.getState().open({- agentId, sessionId, title: item.text, timestamp: item.tsMs,+ agentId, sessionId, title: name, timestamp: item.tsMs,}) : undefined} />;}if (item.kind === "coding_thread") {diff --git a/dodaios/ui/web/frontend/src/components/society/chat/RuntimeNotices.test.tsx b/dodaios/ui/web/frontend/src/components/society/chat/RuntimeNotices.test.tsxindex 959b7b0a40..9b1f603ba6 100644--- a/dodaios/ui/web/frontend/src/components/society/chat/RuntimeNotices.test.tsx+++ b/dodaios/ui/web/frontend/src/components/society/chat/RuntimeNotices.test.tsx@@ -35,3 +35,10 @@ it("announces a runtime setup, the one-time Hermes prepare included", () => {render(<NoticeLine item={notice("runtime_setup", { runtime: "hermes", turn_id: "t1" })} />);expect(screen.getByTestId("runtime-setup-notice").textContent).toBe("society.runtime.setting_up_chat");});++it("labels a routine run with the routine's name, not the first line of its prompt", () => {+ render(<NoticeLine item={notice("routine_run", { session_id: "s1", agent_id: "mail", title: "Morning inbox" }, "Read every new mail and sort it.")} />);+ const card = screen.getByRole("button");+ expect(card.textContent).toContain("Morning inbox");+ expect(card.textContent).not.toContain("Read every new mail");+});diff --git a/dodaios/ui/web/frontend/src/components/society/chat/routineExecution.ts b/dodaios/ui/web/frontend/src/components/society/chat/routineExecution.tsindex 874158440f..235f20c5b3 100644--- a/dodaios/ui/web/frontend/src/components/society/chat/routineExecution.ts+++ b/dodaios/ui/web/frontend/src/components/society/chat/routineExecution.ts@@ -16,8 +16,12 @@ export interface RoutineChatTarget {};}-/** Only a complete scheduler envelope is a routine, never a similar user message. */-const envelope = /^Scheduled routine ([^\s.]+)\. Follow your CURRENT standing instructions(?: and permissions)?\.\r?\n(?:This execution has its own background chat with bypass permissions\.\r?\n)?Use your memory and conversation archive for prior results\. For information watches, check sources and dates, remember last-seen items, and report only meaningful new findings\.\r?\n\r?\n/;+/**+ * Only a complete scheduler envelope is a routine, never a similar user+ * message. Its middle line has said different things over time ("with bypass+ * permissions", "and must honor its permission limits"); any wording counts.+ */+const envelope = /^Scheduled routine ([^\s.]+)\. Follow your CURRENT standing instructions(?: and permissions)?\.\r?\n(?:This execution has its own background chat[^\r\n]*\r?\n)?Use your memory and conversation archive for prior results\. For information watches, check sources and dates, remember last-seen items, and report only meaningful new findings\.\r?\n\r?\n/;export function routineTask(text: string): string | null {const match = envelope.exec(text);diff --git a/dodaios/ui/web/frontend/src/components/society/data.ts b/dodaios/ui/web/frontend/src/components/society/data.tsindex 6555a73ace..7f0d2f308c 100644--- a/dodaios/ui/web/frontend/src/components/society/data.ts+++ b/dodaios/ui/web/frontend/src/components/society/data.ts@@ -162,6 +162,9 @@ export interface SocietyAgent {permissionCeiling: PermissionCeiling;approvalMode?: AgentApprovalMode | null;dailyBudgetUsd: number;+ /** The seat pays per token (an API key). False on a subscription or local+ * model, where no money flows per run; absent reads as true. */+ billedPerToken?: boolean;checkpoint: AgentCheckpoint;state: AgentRunState;/** The durable lifecycle state behind `state` ("active" | "paused" | "archived"). */@@ -290,6 +293,7 @@ export function rowToAgent(row: SocietyAgentRow): SocietyAgent {permissionCeiling: row.permission_ceiling as PermissionCeiling,approvalMode: row.approval_mode ?? null,dailyBudgetUsd: row.daily_budget_usd,+ billedPerToken: row.billed_per_token ?? true,checkpoint: row.checkpoint as AgentCheckpoint,state: runState,lifecycle: row.state,diff --git a/dodaios/ui/web/frontend/src/i18n/locales/de.json b/dodaios/ui/web/frontend/src/i18n/locales/de.jsonindex 2470db8830..03bea66719 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/de.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/de.json@@ -10801,6 +10801,7 @@"title": {"terminal": "Diesen Befehl ausführen?","files": "Diese Datei ändern?",+ "files_create": "Diese Datei erstellen?","browser": "Den Browser verwenden?","computer": "Diesen Computer steuern?","plan": "Nach diesem Plan loslegen?",diff --git a/dodaios/ui/web/frontend/src/i18n/locales/en.json b/dodaios/ui/web/frontend/src/i18n/locales/en.jsonindex 2ae9304d31..a8bdc4b2c4 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/en.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/en.json@@ -10801,6 +10801,7 @@"title": {"terminal": "Run this command?","files": "Change this file?",+ "files_create": "Create this file?","browser": "Use the browser?","computer": "Control this computer?","plan": "Start building from this plan?",diff --git a/dodaios/ui/web/frontend/src/i18n/locales/es.json b/dodaios/ui/web/frontend/src/i18n/locales/es.jsonindex 94bb50f229..18bbb6c38f 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/es.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/es.json@@ -10801,6 +10801,7 @@"title": {"terminal": "¿Ejecutar este comando?","files": "¿Cambiar este archivo?",+ "files_create": "¿Crear este archivo?","browser": "¿Usar el navegador?","computer": "¿Controlar este ordenador?","plan": "¿Empezar a construir con este plan?",diff --git a/dodaios/ui/web/frontend/src/i18n/locales/pt.json b/dodaios/ui/web/frontend/src/i18n/locales/pt.jsonindex 3eb6f7329c..eea4bb732b 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/pt.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/pt.json@@ -10801,6 +10801,7 @@"title": {"terminal": "Executar este comando?","files": "Alterar este arquivo?",+ "files_create": "Criar este arquivo?","browser": "Usar o navegador?","computer": "Controlar este computador?","plan": "Começar a construir com este plano?",diff --git a/dodaios/ui/web/frontend/src/i18n/locales/society/de.json b/dodaios/ui/web/frontend/src/i18n/locales/society/de.jsonindex ab7a4240eb..4792bda309 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/society/de.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/society/de.json@@ -122,7 +122,10 @@"runtime": "Laufzeit","see_all": "Alle anzeigen","history_detail": "Chats und Anrufe",- "record_line": "{0} Läufe · {1} ausgegeben · zuletzt aktiv {2}"+ "record_runs_one": "{0} Lauf",+ "record_runs": "{0} Läufe",+ "record_spent": "{0} ausgegeben",+ "record_last_active": "zuletzt aktiv {0}"},"browser_profiles": {"profile_unavailable": "Profil getrennt — bitte ein Profil auswählen",@@ -289,6 +292,7 @@"latest_chat": "Letzten Chat öffnen","open_chat": "Chat öffnen","background_chat": "Hintergrund-Ausführung",+ "full_prompt": "Vollständige Anweisungen anzeigen","follow_up": "Zu dieser Ausführung nachfragen…","stop_run": "Ausführung stoppen","send": "Senden",diff --git a/dodaios/ui/web/frontend/src/i18n/locales/society/en.json b/dodaios/ui/web/frontend/src/i18n/locales/society/en.jsonindex 22b93bfaf4..6ae203cf05 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/society/en.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/society/en.json@@ -122,7 +122,10 @@"runtime": "Runtime","see_all": "See all","history_detail": "Chats and calls",- "record_line": "{0} runs · {1} spent · last active {2}"+ "record_runs_one": "{0} run",+ "record_runs": "{0} runs",+ "record_spent": "{0} spent",+ "record_last_active": "last active {0}"},"browser_profiles": {"profile_unavailable": "Profile disconnected — choose a profile",@@ -289,6 +292,7 @@"latest_chat": "Open latest chat","open_chat": "Open chat","background_chat": "Background execution",+ "full_prompt": "Show the full instructions","follow_up": "Ask about this execution…","stop_run": "Stop execution","send": "Send",diff --git a/dodaios/ui/web/frontend/src/i18n/locales/society/es.json b/dodaios/ui/web/frontend/src/i18n/locales/society/es.jsonindex 0b62b22026..46ead6b37a 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/society/es.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/society/es.json@@ -122,7 +122,10 @@"runtime": "Entorno","see_all": "Ver todo","history_detail": "Chats y llamadas",- "record_line": "{0} ejecuciones · {1} gastado · última actividad {2}"+ "record_runs_one": "{0} ejecución",+ "record_runs": "{0} ejecuciones",+ "record_spent": "{0} gastado",+ "record_last_active": "última actividad {0}"},"browser_profiles": {"profile_unavailable": "Perfil desconectado — elige un perfil",@@ -289,6 +292,7 @@"latest_chat": "Abrir último chat","open_chat": "Abrir chat","background_chat": "Ejecución en segundo plano",+ "full_prompt": "Mostrar las instrucciones completas","follow_up": "Preguntar sobre esta ejecución…","stop_run": "Detener ejecución","send": "Enviar",diff --git a/dodaios/ui/web/frontend/src/i18n/locales/society/pt.json b/dodaios/ui/web/frontend/src/i18n/locales/society/pt.jsonindex fb0d2e5bb7..17e5f2e0d7 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/society/pt.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/society/pt.json@@ -122,7 +122,10 @@"runtime": "Ambiente","see_all": "Ver tudo","history_detail": "Conversas e chamadas",- "record_line": "{0} execuções · {1} gasto · última atividade {2}"+ "record_runs_one": "{0} execução",+ "record_runs": "{0} execuções",+ "record_spent": "{0} gasto",+ "record_last_active": "última atividade {0}"},"browser_profiles": {"profile_unavailable": "Perfil desligado — escolhe um perfil",@@ -289,6 +292,7 @@"latest_chat": "Abrir o chat mais recente","open_chat": "Abrir chat","background_chat": "Execução em segundo plano",+ "full_prompt": "Mostrar as instruções completas","follow_up": "Pergunta sobre esta execução…","stop_run": "Parar execução","send": "Enviar",diff --git a/dodaios/ui/web/frontend/src/i18n/locales/society/zh.json b/dodaios/ui/web/frontend/src/i18n/locales/society/zh.jsonindex 85e811fe1c..e25df9594c 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/society/zh.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/society/zh.json@@ -122,7 +122,10 @@"runtime": "运行环境","see_all": "查看全部","history_detail": "聊天和通话",- "record_line": "{0} 次运行 · 已花费 {1} · 最近活跃 {2}"+ "record_runs_one": "{0} 次运行",+ "record_runs": "{0} 次运行",+ "record_spent": "已花费 {0}",+ "record_last_active": "最近活跃 {0}"},"browser_profiles": {"profile_unavailable": "配置文件已断开 — 请选择一个配置文件",@@ -289,6 +292,7 @@"latest_chat": "打开最新对话","open_chat": "打开对话","background_chat": "后台执行",+ "full_prompt": "显示完整指令","follow_up": "询问这次执行…","stop_run": "停止执行","send": "发送",diff --git a/dodaios/ui/web/frontend/src/i18n/locales/zh.json b/dodaios/ui/web/frontend/src/i18n/locales/zh.jsonindex 7066b437b0..984e74b93a 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/zh.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/zh.json@@ -10801,6 +10801,7 @@"title": {"terminal": "运行这个命令?","files": "修改这个文件?",+ "files_create": "创建这个文件?","browser": "使用浏览器?","computer": "控制这台电脑?","plan": "按这个计划开始构建?",diff --git a/dodaios/ui/web/frontend/src/lib/societyApi.ts b/dodaios/ui/web/frontend/src/lib/societyApi.tsindex 66a16fd435..1a1d1b5d41 100644--- a/dodaios/ui/web/frontend/src/lib/societyApi.ts+++ b/dodaios/ui/web/frontend/src/lib/societyApi.ts@@ -180,6 +180,8 @@ export interface SocietyAgentRow {approval_mode: AgentApprovalMode | null;approval_rules: ApprovalRules;daily_budget_usd: number;+ /** The seat pays per token (an API key); false on a subscription or local model. */+ billed_per_token?: boolean;max_concurrent_runs: number;browser_mode: BrowserMode;browser_allowed_domains: string[];diff --git a/dodaios/ui/web/server.py b/dodaios/ui/web/server.pyindex 1a6c91883b..eefbe3f526 100644--- a/dodaios/ui/web/server.py+++ b/dodaios/ui/web/server.py@@ -3755,6 +3755,7 @@ class WebServer:scheduler = TaskScheduler(store=store, bus=self.bus, runner=runner, workflow_services=workflow_services,)+ scheduler.attach_owner_gate(self._society_owner_retired)scheduler.bind_bus()await scheduler.hydrate()@@ -3992,6 +3993,22 @@ class WebServer:except Exception: # noqa: BLE001 — the task already recorded its result; delivery is best effortlogger.warning("society: routine result not delivered to {}", agent_id, exc_info=True)+ async def _society_owner_retired(self, tags: tuple[str, ...]) -> bool:+ """Whether a task belongs to a retired (archived) society agent."""+ from dodaios.society.routines import agent_id_from_tags+ from dodaios.society.runtime import current_runtime++ agent_id = agent_id_from_tags(tags)+ if agent_id is None:+ return False+ runtime = current_runtime()+ if runtime is None:+ runtime = self._build_society_runtime()+ self.app.state.society = runtime+ await runtime.ensure_started()+ agent = await runtime.roster.get(agent_id)+ return agent is not None and str(agent.state) == "archived"+async def _guard_society_routine_action(self, tags: tuple[str, ...]) -> None:from dodaios.society.routine_runner import guard_owned_routinefrom dodaios.society.runtime import current_runtimediff --git a/dodaios/ui/web/society_routes.py b/dodaios/ui/web/society_routes.pyindex a5d39ea6a4..398830dd83 100644--- a/dodaios/ui/web/society_routes.py+++ b/dodaios/ui/web/society_routes.py@@ -348,7 +348,31 @@ def _agent_row(agent: AgentRecord, request: HTTPConnection) -> dict[str, Any]:surface (office, roster, chat, CLI) shows what the user calls it. Resolved perrequest, so a changed wake word shows up without a restart."""- return display_row(agent, getattr(request.app.state, "config", None))+ row = display_row(agent, getattr(request.app.state, "config", None))+ row["billed_per_token"] = _billed_per_token(agent, getattr(request.app.state, "config", None))+ return row+++def _billed_per_token(agent: AgentRecord, cfg: Any = None) -> bool:+ """Whether the agent's seat pays per token (an API key), not a plan.++ A subscription or a keyless local model spends no money per run, so the+ card shows runs and activity there instead of dollar amounts. An agent+ without its own seat answers on the app's default model: that one decides.+ """+ provider = str(agent.provider or "")+ try:+ if not provider and cfg is not None:+ from dodaios.society.chat_binding import pair_for++ provider = str(pair_for(cfg, agent)[0] or "")+ if not provider:+ return True+ from dodaios.society.routine_runner import _billed_via_api++ return _billed_via_api(provider, str(agent.account_id or ""))+ except Exception: # noqa: BLE001 — unknown seats keep showing their costs+ return True@router.get("/agents")@@ -670,6 +694,14 @@ async def archive_agent(agent_id: str, request: Request) -> dict[str, Any]:archived = await rt.roster.archive(agent.agent_id)except RosterError as exc:raise _typed_error(exc) from exc+ # A retired agent keeps no routine, webhook or trigger armed.+ store = getattr(request.app.state, "task_store", None)+ if store is not None:+ from dodaios.society.routines import retire_agent_routines++ await retire_agent_routines(+ store, getattr(request.app.state, "task_scheduler", None), agent.agent_id+ )return {"agent": _agent_row(archived, request)}@@ -1801,6 +1833,8 @@ async def create_agent_routine(agent = await rt.roster.resolve(agent_id)if agent is None:raise HTTPException(404, {"reason": str(FailureReason.TARGET_UNKNOWN)})+ if str(getattr(agent, "state", "")) == "archived":+ raise HTTPException(409, "The agent is retired")with _turn_timezone(request):return await _create_routine_for(agent, body, request)@@ -1830,6 +1864,9 @@ async def operate_agent_routine(scheduler = getattr(request.app.state, "task_scheduler", None)if scheduler is None:raise HTTPException(503, "The task scheduler is unavailable")+ if str(getattr(agent, "state", "")) == "archived" and body.operation in ("run", "resume"):+ # A retired agent runs nothing; bring the agent back first.+ raise HTTPException(409, "The routine's agent is retired")if body.operation == "run" and row.get("state") == "running":raise HTTPException(409, "The routine is already running")try:diff --git a/tests/contract/test_society_voice_management.py b/tests/contract/test_society_voice_management.pyindex a5c8c45558..41fc790f96 100644--- a/tests/contract/test_society_voice_management.py+++ b/tests/contract/test_society_voice_management.py@@ -65,7 +65,10 @@ async def test_management_persists_and_echoes_same_roster_without_starting_work()assert updated.success, updated.errorstored = await runtime.roster.get("scout")- assert updated.output["response"]["agent"] == stored.to_dict()+ row = dict(updated.output["response"]["agent"])+ # The route adds a derived display field (whether the seat pays per token).+ assert isinstance(row.pop("billed_per_token"), bool)+ assert row == stored.to_dict()assert stored.title == "Invoice reviewer" and stored.state == "paused"assert stored.daily_budget_usd == 2status = await SocietyStatusTool(runtime_resolver=lambda: runtime).execute(diff --git a/tests/unit/agent_chat/test_approval_card.py b/tests/unit/agent_chat/test_approval_card.pyindex f34a169dbe..a2acb68aed 100644--- a/tests/unit/agent_chat/test_approval_card.py+++ b/tests/unit/agent_chat/test_approval_card.py@@ -932,3 +932,13 @@ def narrow_options_for(args, cwd):from dodaios.agent_chat.approval_card import narrow_optionsreturn narrow_options("files", args, cwd, "C:/Users/Ada")+++def test_a_file_call_on_a_missing_file_asks_to_create_it(tmp_path):+ """"Create this file?" for a new file, "Change this file?" for one already there."""+ (tmp_path / "notes.md").write_text("x", encoding="utf-8")+ new = describe_call("Write", {"file_path": "draft.md", "content": "hi"}, cwd=str(tmp_path))+ assert new.get("creates") is True+ existing = describe_call("Write", {"file_path": "notes.md", "content": "hi"}, cwd=str(tmp_path))+ assert "creates" not in existing+ assert "creates" not in describe_call("Bash", {"command": "ls"}, cwd=str(tmp_path))diff --git a/tests/unit/agent_chat/test_cli_catalog_isolation.py b/tests/unit/agent_chat/test_cli_catalog_isolation.pyindex 97ae1a4993..48962f7f41 100644--- a/tests/unit/agent_chat/test_cli_catalog_isolation.py+++ b/tests/unit/agent_chat/test_cli_catalog_isolation.py@@ -320,3 +320,31 @@ async def test_claude_effort_is_folded_onto_the_models_own_ladder(monkeypatch, t[(sent, prompt)] = seenassert sent == "high"assert "Reasoning effort for this turn: high" in prompt+++def test_agy_models_probe_never_runs_in_the_agent_workspace(monkeypatch, tmp_path):+ """agy boots its global MCP servers for ``models``; on Windows an argument+ like ``pkg@>=0.26.0`` reaches cmd.exe unquoted and leaves an empty file+ named ``0.26.0`` in the probe's folder. A fresh agent's workspace stays clean."""+ import subprocess+ import tempfile++ workspace = tmp_path / "agent" / "workspace"+ workspace.mkdir(parents=True)+ monkeypatch.setattr(tempfile, "gettempdir", lambda: str(tmp_path / "temp"))+ monkeypatch.setattr(rc, "_account_env", lambda platform: {})+ monkeypatch.setattr(rc, "agy_argv_prefix", lambda: ["agy"])+ monkeypatch.setattr(rc, "_AGY_CATALOG", {"at": 0.0, "rows": None})+ seen: list[str] = []++ def run(*args, **kwargs):+ seen.append(kwargs["cwd"])+ # What cmd.exe's redirect does with the unquoted MCP argument.+ (Path(kwargs["cwd"]) / "0.26.0").write_text("", encoding="utf-8")+ return SimpleNamespace(returncode=0, stdout=b"")++ monkeypatch.setattr(subprocess, "run", run)+ with rc.cli_catalog_scope(cwd=workspace):+ rc.read_agy_models()+ assert seen and Path(seen[0]) != workspace+ assert list(workspace.iterdir()) == []diff --git a/tests/unit/society/test_retired_agent_routines.py b/tests/unit/society/test_retired_agent_routines.pynew file mode 100644index 0000000000..da4afeb370--- /dev/null+++ b/tests/unit/society/test_retired_agent_routines.py@@ -0,0 +1,157 @@+"""A retired (archived) agent keeps no routine, webhook or trigger armed."""++from __future__ import annotations++import asyncio+from pathlib import Path++import pytest++from dodaios.core.bus import EventBus+from dodaios.society.routines import retire_agent_routines+from dodaios.tasks.scheduler import TaskScheduler+from dodaios.tasks.schema import (+ AgentAction,+ TaskSpec,+ TriggerAfterDelay,+ TriggerEvery,+ TriggerWebhook,+)+from dodaios.tasks.store import TaskStore+++class _Runner:+ def __init__(self) -> None:+ self.ran: list[str] = []++ async def run(self, task_id: str, *_args, **_kwargs) -> None:+ self.ran.append(task_id)+++async def store(tmp_path: Path):+ s = TaskStore(tmp_path / "tasks.db")+ await s.init()+ try:+ yield s+ finally:+ await s.close()+++def _spec(agent_id: str, trigger, title: str = "Brief") -> TaskSpec:+ return TaskSpec(+ title=f"[agent:{agent_id}] {title}",+ trigger=trigger,+ action=AgentAction(prompt="Do the work."),+ tags=("society", f"agent:{agent_id}"),+ created_by="society",+ )+++async def test_retiring_pauses_recurring_and_webhook_and_cancels_one_shots(store) -> None:+ scheduler = TaskScheduler(store=store, bus=EventBus(), runner=_Runner())+ every = await scheduler.schedule(_spec("mailbox", TriggerEvery(interval_seconds=3600)))+ hook = await scheduler.schedule(_spec("mailbox", TriggerWebhook()))+ once = await scheduler.schedule(_spec("mailbox", TriggerAfterDelay(delay_seconds=600)))+ other = await scheduler.schedule(_spec("scout", TriggerEvery(interval_seconds=3600)))++ stopped = await retire_agent_routines(store, scheduler, "mailbox")++ assert stopped == 3+ assert (await store.get(every))["state"] == "paused"+ assert (await store.get(hook))["state"] == "paused"+ assert (await store.get(once))["state"] == "cancelled"+ # Another agent's routine is untouched.+ assert (await store.get(other))["state"] == "scheduled"+ # Nothing of the retired agent stays armed in the scheduler.+ assert {every, hook, once}.isdisjoint(scheduler._known)+ # Idempotent: a second retire finds nothing left to stop.+ assert await retire_agent_routines(store, scheduler, "mailbox") == 0+++async def test_retiring_without_a_scheduler_writes_the_states(store) -> None:+ every = await store.insert(_spec("mailbox", TriggerEvery(interval_seconds=60)))+ once = await store.insert(_spec("mailbox", TriggerAfterDelay(delay_seconds=60)))+ assert await retire_agent_routines(store, None, "mailbox") == 2+ assert (await store.get(every))["state"] == "paused"+ assert (await store.get(once))["state"] == "cancelled"+++async def test_scheduler_skips_a_routine_whose_owner_is_archived(store) -> None:+ runner = _Runner()+ scheduler = TaskScheduler(store=store, bus=EventBus(), runner=runner)+ retired = {"mailbox"}++ async def gate(tags: tuple[str, ...]) -> bool:+ return any(t == f"agent:{a}" for t in tags for a in retired)++ scheduler.attach_owner_gate(gate)+ every = await scheduler.schedule(_spec("mailbox", TriggerEvery(interval_seconds=3600)))+ live = await scheduler.schedule(_spec("scout", TriggerEvery(interval_seconds=3600)))++ await scheduler._safe_run(every)+ await scheduler._safe_run(live)++ assert runner.ran == [live]+ row = await store.get(every)+ assert row["state"] == "paused"+ assert row["last_error"] == "owner_archived"+ assert every not in scheduler._known+++async def test_a_run_names_its_routine_without_the_agent_prefix(store) -> None:+ from dodaios.society.routine_runner import _routine_title++ tid = await store.insert(_spec("mailbox", TriggerEvery(interval_seconds=60), "Morning inbox"))+ assert await _routine_title(store, tid) == "Morning inbox"+ assert await _routine_title(None, tid) == ""+ assert await _routine_title(store, "missing") == ""+++async def _gated(store, retired: set[str]) -> tuple[TaskScheduler, _Runner]:+ runner = _Runner()+ scheduler = TaskScheduler(store=store, bus=EventBus(), runner=runner)++ async def gate(tags: tuple[str, ...]) -> bool:+ return any(t == f"agent:{a}" for t in tags for a in retired)++ scheduler.attach_owner_gate(gate)+ return scheduler, runner+++async def test_a_webhook_delivery_for_a_retired_owner_never_runs(store) -> None:+ scheduler, runner = await _gated(store, {"mailbox"})+ hook = await scheduler.schedule(_spec("mailbox", TriggerWebhook()))+ assert await scheduler.receive_hook(hook, {"ref": "main"}, "d-1") == "queued"++ await scheduler._drain_hooks()+ await asyncio.gather(*list(scheduler._runner_tasks))++ assert runner.ran == []+ assert (await store.get(hook))["state"] == "paused"+ assert await store.last_log_event(hook) == "skipped"+++async def test_run_now_for_a_retired_owner_never_runs(store) -> None:+ scheduler, runner = await _gated(store, {"mailbox"})+ every = await scheduler.schedule(_spec("mailbox", TriggerEvery(interval_seconds=3600)))+ await scheduler.pause(every)++ await scheduler.run_now(every)+ await asyncio.gather(*list(scheduler._runner_tasks))++ assert runner.ran == []+ assert (await store.get(every))["state"] == "paused"+++async def test_an_autonomous_routine_of_a_retired_owner_never_runs(store) -> None:+ scheduler, runner = await _gated(store, {"mailbox"})+ spec = _spec("mailbox", TriggerEvery(interval_seconds=3600)).model_copy(+ update={"tags": ("society", "agent:mailbox", "autonomous")}+ )+ tid = await scheduler.schedule(spec)++ await scheduler._safe_run(tid)++ assert runner.ran == []+ assert (await store.get(tid))["state"] == "paused"diff --git a/tests/unit/society/test_routines.py b/tests/unit/society/test_routines.pyindex d8989cc3bc..fcc7c06545 100644--- a/tests/unit/society/test_routines.py+++ b/tests/unit/society/test_routines.py@@ -69,8 +69,9 @@ class FakeScheduler:async def resume(self, task_id: str) -> None:await self.store.update_state(task_id, "scheduled")- async def cancel_task(self, task_id: str) -> None:+ async def cancel_task(self, task_id: str, reason: str = "user_cancel") -> bool:await self.store.update_state(task_id, "cancelled")+ return Trueasync def run_now(self, task_id: str) -> None:self.ran.append(task_id)diff --git a/tests/unit/ui/web/test_society_routes.py b/tests/unit/ui/web/test_society_routes.pyindex 170155689d..49421a686c 100644--- a/tests/unit/ui/web/test_society_routes.py+++ b/tests/unit/ui/web/test_society_routes.py@@ -376,6 +376,40 @@ def test_routines_over_rest(client):assert c.get("/api/society/agents/ghost/routines").status_code == 404+def test_retiring_an_agent_pauses_its_routines(client):+ from tests.unit.society.test_routines import FakeScheduler, FakeTaskStore++ c, _ = client+ c.post("/api/society/agents", json={"name": "Mailbox", "title": "Gmail agent"})+ store = FakeTaskStore()+ c.app.state.task_store = store+ c.app.state.task_scheduler = FakeScheduler(store)+ for kind in ("every", "webhook"):+ res = c.post(+ "/api/society/agents/mailbox/routines",+ json={"title": f"Brief {kind}", "prompt": "Summarize.", "schedule": {"kind": kind}},+ )+ assert res.status_code == 200, res.text+ assert c.delete("/api/society/agents/mailbox").status_code == 200+ listed = c.get("/api/society/agents/mailbox/routines").json()["routines"]+ assert [r["state"] for r in listed] == ["paused", "paused"]+ # A retired agent runs, resumes and gains nothing until it is brought back.+ tid = listed[0]["id"]+ for operation in ("run", "resume"):+ res = c.post(+ f"/api/society/agents/mailbox/routines/{tid}/operation",+ json={"operation": operation},+ )+ assert res.status_code == 409, (operation, res.text)+ res = c.post(+ "/api/society/agents/mailbox/routines",+ json={"title": "Again", "prompt": "Summarize.", "schedule": {"kind": "every"}},+ )+ assert res.status_code == 409+ after = c.get("/api/society/agents/mailbox/routines").json()["routines"]+ assert [r["state"] for r in after] == ["paused", "paused"]++def test_browser_routes(client, tmp_path, monkeypatch):c, _ = clientstatus = c.get("/api/society/browser/status").json()@@ -562,3 +596,33 @@ def test_a_runtime_agent_on_an_unsupported_provider_names_a_translatable_reason(# The UI shows its own sentence for the reason; the detail names every way that works.assert detail["reason"] == "runtime_provider_unsupported"assert "ChatGPT subscription" in detail["detail"]+++def test_agent_rows_say_whether_the_seat_pays_per_token(client, monkeypatch):+ from dodaios.society import routine_runner++ c, _ = client+ c.post("/api/society/agents", json={"name": "Mailbox", "title": "Gmail agent"})+ monkeypatch.setattr(routine_runner, "_billed_via_api", lambda provider, account_id="": False)+ rows = {a["agent_id"]: a for a in c.get("/api/society/agents").json()["agents"]}+ # No own seat (the default brain): its costs stay visible.+ assert rows["mailbox"]["billed_per_token"] is True+ from dodaios.ui.web import society_routes++ seat = SimpleNamespace(provider="claude-api", account_id="subscription")+ assert society_routes._billed_per_token(seat) is False+++def test_an_agent_without_its_own_seat_follows_the_default_model(monkeypatch):+ from dodaios.society import chat_binding, routine_runner+ from dodaios.ui.web import society_routes++ monkeypatch.setattr(chat_binding, "pair_for", lambda cfg, agent: ("codex-cli", "gpt", ""))+ monkeypatch.setattr(+ routine_runner, "_billed_via_api", lambda provider, account_id="": provider != "codex-cli"+ )+ seatless = SimpleNamespace(provider="", account_id="")+ # The default model is a subscription: no dollar lines for this agent.+ assert society_routes._billed_per_token(seatless, object()) is False+ # Without a config the costs stay visible.+ assert society_routes._billed_per_token(seatless) is True