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(tasks): keep unattended agent runs off per-token API keys (#555)
Ruben Lütkea250a8bdf8fd
diff --git a/jarvis/brain/background_policy.py b/jarvis/brain/background_policy.pyindex 0dce16ed5a..138ba21663 100644--- a/jarvis/brain/background_policy.py+++ b/jarvis/brain/background_policy.py@@ -38,6 +38,8 @@ from collections.abc import Callable, Iterablefrom dataclasses import dataclassfrom pathlib import Path+from jarvis.core.protocols import CapacityDeferred+log = logging.getLogger(__name__)#: How long one connected sighting keeps the install in subscription mode.@@ -54,7 +56,7 @@ _probe_cache: dict[str, tuple[float, bool | None]] = {}_probe_override: Callable[[str], bool | None] | None = None-class BackgroundDeferred(RuntimeError):+class BackgroundDeferred(CapacityDeferred):"""No provider background work may bill is usable right now; retry later."""diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.pyindex 4a90324849..ffd5e8f089 100644--- a/jarvis/brain/manager.py+++ b/jarvis/brain/manager.py@@ -13580,13 +13580,25 @@ class BrainManager:allowed_tools = (*allowed_tools, _ARTIFACT_TOOL_NAME)tools = self._select_task_tools(allowed_tools)from jarvis.core.model_selection import operation_model, worker_selection- from jarvis.core.task_agent import run_selected, subscription_seat_off_loop+ from jarvis.core.task_agent import (+ dual_seat_subscription,+ run_selected,+ subscription_seat_off_loop,+ )selected = operation_model.get() or worker_selection(self._config)if (selected is not Noneand await subscription_seat_off_loop(selected.provider) is not None):+ subscription = dual_seat_subscription(selected.provider)+ if subscription is not None:+ # A dual slot only gets its seat while that login answers. The+ # sighting is what later keeps an unattended turn off the+ # slot's per-token row when the login stops answering.+ from jarvis.brain.background_policy import note_connected++ await asyncio.to_thread(note_connected, subscription)return await run_selected(selection=selected, prompt=prompt, tool_names=tuple(tools), trace_id=trace_id)@@ -13601,6 +13613,13 @@ class BrainManager:log.debug("run_task: turn context skipped", exc_info=True)turn_context = ""attempts = self._task_provider_chain(intent)+ from jarvis.core.protocols import current_started_by_user++ if not current_started_by_user.get():+ # Nobody started this turn (a schedule, a trigger, a background+ # start): it may only bill what background work may bill — a+ # subscription or a local model, never a per-token key on its own.+ attempts = await self._unattended_task_chain(attempts, selected)failures: list[str] = []original: Exception | None = Nonefor index, (name, model) in enumerate(attempts):@@ -13645,6 +13664,58 @@ class BrainManager:raise originalraise RuntimeError("all brain providers failed: " + "; ".join(failures))+ async def _unattended_task_chain(+ self,+ attempts: list[tuple[str, str | None]],+ selected: Any,+ ) -> list[tuple[str, str | None]]:+ """Hold an unattended turn's chain to the background policy.++ - An explicit agent selection is the person's own choice and stays —+ except a dual slot (one that is a subscription seat while its login+ is ready and a per-token row otherwise). Its login is not ready here+ (a ready one ran on the subscription above), so the row it fell back+ to was never picked and follows the same policy as the automatic+ chain.+ - The automatic chain keeps only subscriptions and local models once a+ subscription is connected; an install without one keeps its chain,+ so a single-key download still works.++ Nothing usable raises :class:`BackgroundDeferred` instead of billing a+ key; the runner records the skipped run.+ """+ from jarvis.brain.background_policy import BackgroundDeferred, background_providers+ from jarvis.core.task_agent import dual_seat_subscription++ if selected is not None:+ provider = str(getattr(selected, "provider", "") or "")+ if dual_seat_subscription(provider) is None:+ return attempts+ policy = await asyncio.to_thread(+ background_providers, [name for name, _model in attempts]+ )+ if not policy.subscription_mode:+ return attempts+ kept = [(name, model) for name, model in attempts if policy.permits(name)]+ dropped = [name for name, _model in attempts if not policy.permits(name)]+ if kept:+ if dropped:+ log.info(+ "run_task (unattended): skipping per-token providers %s; "+ "background work stays on %s",+ dropped, [name for name, _model in kept],+ )+ return kept+ log.warning(+ "run_task (unattended): no subscription or local model can run this "+ "turn (%s); deferring instead of billing %s",+ policy.reason, dropped,+ )+ raise BackgroundDeferred(+ "No subscription or local model is available for this unattended run; "+ "a paid API key is not used without your approval."+ )+def _task_provider_chain(self, intent: str) -> list[tuple[str, str | None]]:"""The providers a scheduled turn tries, in order.diff --git a/jarvis/core/protocols.py b/jarvis/core/protocols.pyindex 904513b256..cc4950fbe2 100644--- a/jarvis/core/protocols.py+++ b/jarvis/core/protocols.py@@ -19,8 +19,11 @@ from uuid import UUIDfrom .chat_turn import ChatCompletion as ChatCompletionfrom .chat_turn import ChatTurn as ChatTurnfrom .chat_turn import current_chat_turn as current_chat_turn+from .trigger_context import CapacityDeferred as CapacityDeferredfrom .trigger_context import RoutineDeferred as RoutineDeferred+from .trigger_context import current_started_by_user as current_started_by_userfrom .trigger_context import current_trigger_path as current_trigger_path+from .trigger_context import started_by_user as started_by_userif TYPE_CHECKING: # pragma: no cover - typing only; the contract has no runtime importfrom jarvis.platform.permission_service import EnsureResultdiff --git a/jarvis/core/task_agent.py b/jarvis/core/task_agent.pyindex 43024e934b..0b4903ef62 100644--- a/jarvis/core/task_agent.py+++ b/jarvis/core/task_agent.py@@ -45,6 +45,36 @@ def release_scope(session_id: str) -> None:_scopes.pop(session_id, None)+#: Slots that always answer through their vendor CLI.+_SEATS: dict[str, tuple[str, str]] = {+ "codex": ("openai-codex", "codex-cli"),+ "claude-cli": ("claude-api", "claude-cli"),+ "antigravity": ("antigravity", "agy-cli"),+ "grok-build": ("grok-build", "grok-cli"),+}+++@dataclass(frozen=True)+class DualSeat:+ """A slot that is a subscription seat only while that login is ready, and+ the same family's per-token API row otherwise."""++ seat: tuple[str, str]+ #: Provider card of the subscription the seat spends.+ subscription: str+ ready: Callable[[], bool]+++_DUAL_SEATS: dict[str, DualSeat] = {+ "claude-api": DualSeat(+ seat=("claude-api", "claude-cli"),+ subscription="claude-cli",+ # Looked up per call so a replaced probe (tests) is the one asked.+ ready=lambda: _claude_subscription_ready(),+ ),+}++def subscription_seat(provider: str) -> tuple[str, str] | None:"""Identity aliases, not model or feature gates.@@ -55,26 +85,35 @@ def subscription_seat(provider: str) -> tuple[str, str] | None:Live 2026-09-29: the front-page chat answered through a stale Anthropickey while the Agents tab showed Claude Max as active."""- seat = {- "codex": ("openai-codex", "codex-cli"),- "claude-cli": ("claude-api", "claude-cli"),- "antigravity": ("antigravity", "agy-cli"),- "grok-build": ("grok-build", "grok-cli"),- }.get(provider)- if seat is None and provider == "claude-api" and _claude_subscription_ready():- seat = ("claude-api", "claude-cli")+ seat = _SEATS.get(provider)+ if seat is None:+ dual = _DUAL_SEATS.get(provider)+ if dual is not None and dual.ready():+ seat = dual.seatreturn seat+def dual_seat_subscription(provider: str) -> str | None:+ """The subscription card behind a dual slot, ``None`` for every other slot.++ A dual slot reaches its per-token row only while that subscription is not+ ready, so the row is a fallback and not something the person picked. A+ caller that must not bill a key on its own asks this instead of comparing+ provider names.+ """+ dual = _DUAL_SEATS.get(provider)+ return dual.subscription if dual is not None else None++async def subscription_seat_off_loop(provider: str) -> tuple[str, str] | None:"""``subscription_seat`` for code running on the event loop.- The Claude slot's login probe can run two blocking ``claude`` subprocesses+ A dual slot's login probe can run two blocking vendor subprocesses(4 s + 6 s) when its cache is cold; on the loop that froze voice,WebSockets and the IDE for up to ~10 s (#251). Other seats are a dictlookup and stay inline."""- if provider != "claude-api":+ if provider not in _DUAL_SEATS:return subscription_seat(provider)return await asyncio.to_thread(subscription_seat, provider)diff --git a/jarvis/core/trigger_context.py b/jarvis/core/trigger_context.pyindex bbddf470ed..0c81f5d60a 100644--- a/jarvis/core/trigger_context.py+++ b/jarvis/core/trigger_context.py@@ -1,9 +1,31 @@"""Trusted execution ancestry, separate from externally supplied payloads."""+from collections.abc import Iterator+from contextlib import contextmanagerfrom contextvars import ContextVarcurrent_trigger_path: ContextVar[tuple[str, ...]] = ContextVar("current_trigger_path", default=())+#: True while work the person started THEMSELVES runs — "Run now" on a task,+#: routine or workflow. The default (False) means unattended: a schedule, a+#: trigger, a webhook or any other background start. asyncio tasks copy the+#: context when they are created, so a run spawned inside the block keeps it.+current_started_by_user: ContextVar[bool] = ContextVar("current_started_by_user", default=False)+++@contextmanager+def started_by_user() -> Iterator[None]:+ """Mark the work started inside this block as started by the person."""+ token = current_started_by_user.set(True)+ try:+ yield+ finally:+ current_started_by_user.reset(token)+++class CapacityDeferred(RuntimeError):+ """Unattended work found nothing it may bill and was skipped, not run."""+class RoutineDeferred(RuntimeError):"""Admission succeeded, but the owning agent has not started any side effect."""diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.pyindex ee12ea6fb0..c51398cb75 100644--- a/jarvis/realtime/session.py+++ b/jarvis/realtime/session.py@@ -12467,19 +12467,24 @@ class RealtimeVoiceSession:"does not answer the question, say that honestly.\n\n"f"User question: {query}\n\nEvidence:\n{evidence}")+ from jarvis.core.protocols import started_by_user+try:- reply = str(- await asyncio.wait_for(- run_task(- prompt=prompt,- allowed_tools=(),- model_tier="fast",- trace_id=self._turn_trace_id,- ),- timeout=_DELEGATE_TIMEOUT_S,- )- or ""- ).strip()+ # The person asked this question in a live call: it is their turn,+ # not unattended work, so it keeps the chain an asked turn runs on.+ with started_by_user():+ reply = str(+ await asyncio.wait_for(+ run_task(+ prompt=prompt,+ allowed_tools=(),+ model_tier="fast",+ trace_id=self._turn_trace_id,+ ),+ timeout=_DELEGATE_TIMEOUT_S,+ )+ or ""+ ).strip()except asyncio.CancelledError:raiseexcept Exception: # noqa: BLE001 - evidence exists but synthesis did notdiff --git a/jarvis/tasks/runner.py b/jarvis/tasks/runner.pyindex 7f474dbeba..742309bc3b 100644--- a/jarvis/tasks/runner.py+++ b/jarvis/tasks/runner.py@@ -46,7 +46,7 @@ from jarvis.core.events import (TaskStarted,TaskStepRecorded,)-from jarvis.core.protocols import RoutineDeferred+from jarvis.core.protocols import CapacityDeferred, RoutineDeferredif TYPE_CHECKING:from jarvis.control.cancel import CancelToken@@ -227,6 +227,16 @@ class TaskRunner:raiseduration_ms = int((time.perf_counter() - start) * 1000)error_msg = readable_error(exc)+ if isinstance(exc, CapacityDeferred):+ # Nothing this unattended run may bill was usable: the run is+ # skipped (no key was used); a recurring task tries again next time.+ error_msg = str(exc)+ await self._store.append_step(+ task_id,+ "log",+ {"event": "skipped", "reason": "waiting_capacity", "message": error_msg},+ )+ log.warning("Task %s skipped: %s", task_id, error_msg)# A recurring automation survives a failed run: it goes back to# `scheduled` with the reason in `last_error`, and fires again at# its next occurrence. Only one-shot tasks end in `failed`@@ -703,7 +713,7 @@ class TaskRunner:prefer_api=owned_failed is not None,)except Exception as exc:- if owned_failed is not None:+ if owned_failed is not None and not isinstance(exc, CapacityDeferred):raise RuntimeError(f"{readable_error(exc)} "f"(agent seat had already failed: {readable_error(owned_failed)})"diff --git a/jarvis/ui/web/society_routes.py b/jarvis/ui/web/society_routes.pyindex edb0c6d3a9..5af6e8aed8 100644--- a/jarvis/ui/web/society_routes.py+++ b/jarvis/ui/web/society_routes.py@@ -24,6 +24,7 @@ from pydantic import BaseModel, ConfigDict, Fieldfrom starlette.requests import HTTPConnectionfrom jarvis.brain.assistant_name import DEFAULT_ASSISTANT_NAME, resolve_assistant_name+from jarvis.core.protocols import started_by_userfrom jarvis.society.companion import CompanionSkinfrom jarvis.society.events import MsgTypefrom jarvis.society.failure_reasons import FailureReason, retry_action@@ -1650,7 +1651,8 @@ async def operate_agent_routine(raise HTTPException(409, "The routine is already running")try:if body.operation == "run":- await scheduler.run_now(task_id)+ with started_by_user():+ await scheduler.run_now(task_id)else:await manage_routine(agent, {"task_id": task_id, "operation": body.operation}, store, schedulerdiff --git a/jarvis/ui/web/tasks_routes.py b/jarvis/ui/web/tasks_routes.pyindex 92f3ca7793..d237eaab32 100644--- a/jarvis/ui/web/tasks_routes.py+++ b/jarvis/ui/web/tasks_routes.py@@ -30,6 +30,7 @@ from typing import Anyfrom fastapi import APIRouter, HTTPException, Requestfrom pydantic import BaseModel, ConfigDict, Field+from jarvis.core.protocols import started_by_userfrom jarvis.tasks.scheduler import TaskNotFound, TaskStateConflictfrom jarvis.tasks.schema import PAUSABLE_TRIGGER_TYPES, TERMINAL_STATES, TaskSpec@@ -257,7 +258,8 @@ async def run_task_now(task_id: str, request: Request) -> dict[str, Any]:raise HTTPException(status_code=409, detail="Task is already running")scheduler = _require_scheduler(request)try:- await scheduler.run_now(task_id)+ with started_by_user():+ await scheduler.run_now(task_id)except TaskNotFound as exc:raise HTTPException(status_code=404, detail="Task not found") from excexcept TaskStateConflict as exc:diff --git a/jarvis/ui/web/workflows_routes.py b/jarvis/ui/web/workflows_routes.pyindex e4f9b914bb..11c658720b 100644--- a/jarvis/ui/web/workflows_routes.py+++ b/jarvis/ui/web/workflows_routes.py@@ -25,6 +25,7 @@ from typing import Anyfrom fastapi import APIRouter, Body, HTTPException, Request+from jarvis.core.protocols import started_by_userfrom jarvis.workflows.schema import WorkflowDefrouter = APIRouter(prefix="/api/workflows", tags=["workflows"])@@ -240,11 +241,12 @@ async def run_workflow(_require_store(request)runner = _require_runner(request)try:- run_id = await runner.trigger(- workflow_id,- trigger_reason="manual",- input_data=input_data or {},- )+ with started_by_user():+ run_id = await runner.trigger(+ workflow_id,+ trigger_reason="manual",+ input_data=input_data or {},+ )except KeyError as exc:raise HTTPException(status_code=404, detail=str(exc)) from excreturn {"run_id": run_id, "workflow_id": workflow_id}diff --git a/tests/unit/brain/test_run_task_unattended_policy.py b/tests/unit/brain/test_run_task_unattended_policy.pynew file mode 100644index 0000000000..4c98de8594--- /dev/null+++ b/tests/unit/brain/test_run_task_unattended_policy.py@@ -0,0 +1,285 @@+"""An unattended scheduled turn never bills a per-token key on its own.++User rule (2026-10-06): once a subscription is connected, a run nobody started+(a schedule, a trigger, a webhook) runs only on a subscription or a local+model; with none usable it is deferred, never moved onto an API key. A run the+person started ("Run now") and an install without any subscription keep the+existing chain. Every login is a fake probe; no provider is called.+"""++from __future__ import annotations++from types import SimpleNamespace+from typing import Any++import pytest++from jarvis.brain import background_policy+from jarvis.brain.background_policy import BackgroundDeferred+from jarvis.brain.manager import BrainManager+from jarvis.core import task_agent+from jarvis.core.bus import EventBus+from jarvis.core.config import JarvisConfig+from jarvis.core.model_selection import ModelSelection, use_operation_model+from jarvis.core.protocols import CapacityDeferred, ToolResult, started_by_user+++class _NullExecutor:+ async def execute(self, *a: Any, **kw: Any) -> ToolResult:+ return ToolResult(success=True, output="ok")+++class _Turns:+ """Records which provider each attempt was built for; never calls one."""++ def __init__(self, mgr: BrainManager, monkeypatch: pytest.MonkeyPatch) -> None:+ self.built: list[str] = []+ self.fail: dict[str, str] = {}++ def _get_brain(name: str, _model: Any = None) -> Any:+ self.built.append(name)+ return SimpleNamespace(name=name)++ def _build_dispatcher(brain: Any, **_: Any) -> Any:+ fail = self.fail.get(brain.name)++ class _Dispatcher:+ async def dispatch(self, _text: str, **_kw: Any) -> Any:+ if fail:+ raise RuntimeError(fail)+ return SimpleNamespace(text=f"answered by {brain.name}")++ return _Dispatcher()++ monkeypatch.setattr(mgr, "_get_brain", _get_brain)+ monkeypatch.setattr(mgr, "_build_dispatcher", _build_dispatcher)+++def _manager() -> BrainManager:+ return BrainManager(+ config=JarvisConfig(),+ bus=EventBus(),+ tools={},+ tool_executor=_NullExecutor(), # type: ignore[arg-type]+ )+++def _chain(mgr: BrainManager, monkeypatch: pytest.MonkeyPatch, *names: str) -> None:+ monkeypatch.setattr(mgr, "_task_provider_chain", lambda _intent: [(n, None) for n in names])+++def _logins(monkeypatch: pytest.MonkeyPatch, **states: bool | None) -> None:+ """Fake subscription logins: ``codex=True`` = signed in, False = signed out."""+ monkeypatch.setattr(background_policy, "_probe_override", lambda provider: states.get(provider))+++async def _no_seat(_provider: str) -> None:+ return None+++def mgr(monkeypatch: pytest.MonkeyPatch) -> BrainManager:+ m = _manager()+ # No subscription CLI seat answers off the loop; the chain decides.+ monkeypatch.setattr("jarvis.core.task_agent.subscription_seat_off_loop", _no_seat)+ return m+++# --- No subscription connected: the single-key install keeps working ----------+++async def test_without_a_subscription_the_unattended_chain_is_unchanged(+ mgr: BrainManager, monkeypatch: pytest.MonkeyPatch+) -> None:+ turns = _Turns(mgr, monkeypatch)+ _chain(mgr, monkeypatch, "openai", "gemini")++ assert await mgr.run_task(prompt="daily digest") == "answered by openai"+ assert turns.built == ["openai"]+++# --- Subscription connected: unattended turns stay on subscriptions -----------+++async def test_unattended_turn_skips_the_key_and_runs_on_the_subscription(+ mgr: BrainManager, monkeypatch: pytest.MonkeyPatch+) -> None:+ turns = _Turns(mgr, monkeypatch)+ _logins(monkeypatch, codex=True)+ _chain(mgr, monkeypatch, "openai", "codex")++ assert await mgr.run_task(prompt="daily digest") == "answered by codex"+ assert turns.built == ["codex"]+++async def test_unattended_turn_runs_on_a_local_model(+ mgr: BrainManager, monkeypatch: pytest.MonkeyPatch+) -> None:+ turns = _Turns(mgr, monkeypatch)+ _logins(monkeypatch, codex=False)+ background_policy.note_connected("codex") # a subscription was connected earlier+ _chain(mgr, monkeypatch, "openai", "ollama")++ assert await mgr.run_task(prompt="daily digest") == "answered by ollama"+ assert turns.built == ["ollama"]++[email protected]("codex_login", [False, None])+async def test_unattended_turn_defers_when_only_keys_remain(+ mgr: BrainManager, monkeypatch: pytest.MonkeyPatch, codex_login: bool | None+) -> None:+ """A spent or signed-out subscription: no key is billed, the run is deferred."""+ turns = _Turns(mgr, monkeypatch)+ _logins(monkeypatch, codex=codex_login)+ background_policy.note_connected("codex")+ _chain(mgr, monkeypatch, "openai", "gemini", "codex")++ with pytest.raises(BackgroundDeferred) as exc:+ await mgr.run_task(prompt="daily digest")++ assert isinstance(exc.value, CapacityDeferred)+ assert "approval" in str(exc.value)+ assert turns.built == []+++async def test_a_spent_subscription_does_not_fall_through_to_a_key(+ mgr: BrainManager, monkeypatch: pytest.MonkeyPatch+) -> None:+ turns = _Turns(mgr, monkeypatch)+ turns.fail["codex"] = "429 rate limit: usage window exhausted"+ _logins(monkeypatch, codex=True)+ _chain(mgr, monkeypatch, "codex", "openai", "gemini")++ with pytest.raises(RuntimeError):+ await mgr.run_task(prompt="daily digest")++ assert turns.built == ["codex"]+++# --- A run the person started keeps the existing chain ------------------------+++async def test_run_now_by_the_person_keeps_the_existing_chain(+ mgr: BrainManager, monkeypatch: pytest.MonkeyPatch+) -> None:+ turns = _Turns(mgr, monkeypatch)+ _logins(monkeypatch, codex=False)+ background_policy.note_connected("codex")+ _chain(mgr, monkeypatch, "openai", "gemini")++ with started_by_user():+ assert await mgr.run_task(prompt="daily digest") == "answered by openai"+ assert turns.built == ["openai"]+++# --- An explicit agent selection ---------------------------------------------+++def _dual_slot() -> str:+ """A slot that is a subscription seat while signed in, else a per-token row."""+ return next(iter(task_agent._DUAL_SEATS)) # noqa: SLF001 - the table under test+++async def test_dual_slot_never_bills_its_api_row_unattended_once_a_subscription_was_connected(+ mgr: BrainManager, monkeypatch: pytest.MonkeyPatch+) -> None:+ """The slot fell back to its per-token row because its login is not ready;+ nobody picked that row, so an unattended turn waits instead of billing it."""+ turns = _Turns(mgr, monkeypatch)+ slot = _dual_slot()+ background_policy.note_connected(task_agent.dual_seat_subscription(slot))++ with use_operation_model(ModelSelection(slot, "some-model", "")):+ with pytest.raises(BackgroundDeferred):+ await mgr.run_task(prompt="daily digest")+ assert turns.built == []++ with started_by_user():+ assert await mgr.run_task(prompt="daily digest") == f"answered by {slot}"+ assert turns.built == [slot]+++async def test_dual_slot_waits_while_any_other_subscription_is_connected(+ mgr: BrainManager, monkeypatch: pytest.MonkeyPatch+) -> None:+ turns = _Turns(mgr, monkeypatch)+ background_policy.note_connected("codex")++ with (+ use_operation_model(ModelSelection(_dual_slot(), "some-model", "")),+ pytest.raises(BackgroundDeferred),+ ):+ await mgr.run_task(prompt="daily digest")+ assert turns.built == []+++async def test_dual_slot_on_a_key_only_install_is_the_users_api_choice(+ mgr: BrainManager, monkeypatch: pytest.MonkeyPatch+) -> None:+ """No subscription was ever connected: the key is all this install has, and+ an installed vendor CLI that was never signed in changes nothing."""+ turns = _Turns(mgr, monkeypatch)+ slot = _dual_slot()++ with use_operation_model(ModelSelection(slot, "some-model", "")):+ assert await mgr.run_task(prompt="daily digest") == f"answered by {slot}"+ assert turns.built == [slot]+++async def test_a_dual_slot_run_on_its_seat_remembers_the_subscription(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The seat answered, so the login was working: that sighting is what makes+ the next unattended turn wait once the login stops answering."""+ mgr = _manager()+ turns = _Turns(mgr, monkeypatch)+ slot = _dual_slot()+ ready = {"value": True}+ monkeypatch.setitem(+ task_agent._DUAL_SEATS, # noqa: SLF001 - scripted login, no vendor CLI+ slot,+ task_agent.DualSeat(+ seat=task_agent._DUAL_SEATS[slot].seat, # noqa: SLF001+ subscription=task_agent.dual_seat_subscription(slot),+ ready=lambda: ready["value"],+ ),+ )+ seat_runs: list[str] = []++ async def _seat_runner(*, selection: Any, **_: Any) -> str:+ seat_runs.append(selection.provider)+ return "answered on the subscription"++ monkeypatch.setattr(task_agent, "_runner", _seat_runner)++ with use_operation_model(ModelSelection(slot, "some-model", "")):+ assert await mgr.run_task(prompt="daily digest") == "answered on the subscription"+ assert background_policy.subscription_mode() is True++ ready["value"] = False # the login expired+ with pytest.raises(BackgroundDeferred):+ await mgr.run_task(prompt="daily digest")+ assert seat_runs == [slot]+ assert turns.built == []+++async def test_no_provider_name_decides_the_unattended_chain() -> None:+ """AP-21: the rule asks the seat table and the billing cards, never a name."""+ import inspect++ source = inspect.getsource(BrainManager._unattended_task_chain) # noqa: SLF001+ for slot in task_agent._DUAL_SEATS: # noqa: SLF001+ assert slot not in source+++async def test_an_explicitly_selected_agent_is_kept(+ mgr: BrainManager, monkeypatch: pytest.MonkeyPatch+) -> None:+ """The person picked this agent for tasks; the policy filters only the+ automatic chain, it never overrides an explicit choice."""+ turns = _Turns(mgr, monkeypatch)+ _logins(monkeypatch, codex=True)++ with use_operation_model(ModelSelection("openai", "gpt-x", "")):+ assert await mgr.run_task(prompt="daily digest") == "answered by openai"+ assert turns.built == ["openai"]diff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.pyindex 2e2c1550d7..e1f9c1bac0 100644--- a/tests/unit/realtime/test_session.py+++ b/tests/unit/realtime/test_session.py@@ -2599,9 +2599,13 @@ async def test_local_public_fact_uses_exactly_one_supervisor_search(def __init__(self):super().__init__()self.run_task_calls = []+ self.started_by_user = []async def run_task(self, **kwargs):+ from jarvis.core.protocols import current_started_by_user+self.run_task_calls.append(kwargs)+ self.started_by_user.append(current_started_by_user.get())return "Ada Lovelace was born in 1815 according to the source."class _GroundedResultSession(FakeSession):@@ -2643,6 +2647,9 @@ async def test_local_public_fact_uses_exactly_one_supervisor_search(}assert len(brain.run_task_calls) == 1assert brain.run_task_calls[0]["allowed_tools"] == ()+ # A question asked in a live call is the person's own turn, not unattended+ # work: it must not be held to the background billing policy.+ assert brain.started_by_user == [True]assert brain.calls == []# Exactly ONE result is spoken. An instant-ack line ("Quick online# search, one moment.") may land before it on a slow runner — that is thediff --git a/tests/unit/tasks/test_runner_unattended_capacity.py b/tests/unit/tasks/test_runner_unattended_capacity.pynew file mode 100644index 0000000000..95e9a556b9--- /dev/null+++ b/tests/unit/tasks/test_runner_unattended_capacity.py@@ -0,0 +1,197 @@+"""Scheduled agent runs that find no billable capacity are skipped, not billed.++The brain raises a :class:`CapacityDeferred` when an unattended turn has no+subscription or local model left (see+``tests/unit/brain/test_run_task_unattended_policy.py``). The runner records+the skip, keeps a recurring task on its schedule, and the "Run now" routes mark+their run as started by the person while a scheduled firing stays unattended.+"""++from __future__ import annotations++import asyncio+from pathlib import Path+from typing import Any++import httpx+import pytest+from fastapi import FastAPI++from jarvis.brain.background_policy import BackgroundDeferred+from jarvis.control.cancel import CancelToken+from jarvis.core.bus import EventBus+from jarvis.core.protocols import current_started_by_user+from jarvis.tasks.runner import TaskRunner+from jarvis.tasks.scheduler import TaskScheduler+from jarvis.tasks.schema import AgentAction, TaskSpec, TriggerAfterDelay, TriggerEvery+from jarvis.tasks.store import TaskStore+from jarvis.ui.web import tasks_routes, workflows_routes+++class DeferringBrain:+ """Raises what the real brain raises when only per-token keys remain."""++ def __init__(self) -> None:+ self.started_by_user: list[bool] = []++ async def run_task(self, **_: Any) -> str:+ self.started_by_user.append(current_started_by_user.get())+ raise BackgroundDeferred(+ "No subscription or local model is available for this unattended run; "+ "a paid API key is not used without your approval."+ )+++class RecordingBrain:+ def __init__(self) -> None:+ self.started_by_user: list[bool] = []++ async def run_task(self, **_: Any) -> str:+ self.started_by_user.append(current_started_by_user.get())+ return "done"+++async def store(tmp_path: Path):+ s = TaskStore(tmp_path / "runner.db")+ await s.init()+ try:+ yield s+ finally:+ await s.close()+++def _events(row: dict[str, Any]) -> list[dict[str, Any]]:+ return [step["payload"] for step in row["steps"]]+++async def test_a_deferred_recurring_run_is_skipped_and_stays_scheduled(+ store: TaskStore,+) -> None:+ runner = TaskRunner(store, EventBus(), agent_brain=DeferringBrain())+ task_id = await store.insert(+ TaskSpec(+ title="Morning digest",+ trigger=TriggerEvery(interval_seconds=86400),+ action=AgentAction(prompt="Summarise my day."),+ )+ )+ await asyncio.wait_for(runner.run(task_id, CancelToken()), timeout=2.0)++ row = await store.get(task_id)+ assert row is not None+ assert row["state"] == "scheduled" # tries again at its next occurrence+ assert "paid API key is not used" in (row["last_error"] or "")+ skipped = [e for e in _events(row) if e.get("event") == "skipped"]+ assert skipped and skipped[0]["reason"] == "waiting_capacity"+++async def test_a_deferred_one_shot_run_fails_with_the_reason(store: TaskStore) -> None:+ runner = TaskRunner(store, EventBus(), agent_brain=DeferringBrain())+ task_id = await store.insert(+ TaskSpec(+ title="Once",+ trigger=TriggerAfterDelay(delay_seconds=0.01),+ action=AgentAction(prompt="Summarise my day."),+ )+ )+ await asyncio.wait_for(runner.run(task_id, CancelToken()), timeout=2.0)++ row = await store.get(task_id)+ assert row is not None+ assert row["state"] == "failed"+ assert "paid API key is not used" in (row["last_error"] or "")+ assert any(e.get("event") == "skipped" for e in _events(row))+++async def test_a_deferral_after_a_failed_owner_seat_is_still_a_skip(store: TaskStore) -> None:+ """The owner seat failed and the task-tools retry found nothing it may+ bill: the run is recorded as skipped, not as a provider error."""++ async def owned_runner(task_id: str, tags: tuple[str, ...], prompt: str, cancel: Any) -> str:+ raise RuntimeError("the seat's CLI has no task tools")++ runner = TaskRunner(+ store, EventBus(), agent_brain=DeferringBrain(), owned_agent_runner=owned_runner+ )+ task_id = await store.insert(+ TaskSpec(+ title="Team sweep",+ trigger=TriggerEvery(interval_seconds=86400),+ action=AgentAction(prompt="Sort the inbox."),+ tags=("team",),+ )+ )+ await asyncio.wait_for(runner.run(task_id, CancelToken()), timeout=2.0)++ row = await store.get(task_id)+ assert row is not None+ assert row["state"] == "scheduled"+ skipped = [e for e in _events(row) if e.get("event") == "skipped"]+ assert skipped and skipped[0]["reason"] == "waiting_capacity"+++async def test_a_scheduled_firing_is_unattended(store: TaskStore) -> None:+ brain = RecordingBrain()+ runner = TaskRunner(store, EventBus(), agent_brain=brain)+ task_id = await store.insert(+ TaskSpec(+ title="Once",+ trigger=TriggerAfterDelay(delay_seconds=0.01),+ action=AgentAction(prompt="hi"),+ )+ )+ await asyncio.wait_for(runner.run(task_id, CancelToken()), timeout=2.0)+ assert brain.started_by_user == [False]+++async def test_run_now_marks_the_run_as_started_by_the_person(tmp_path: Path) -> None:+ store = TaskStore(tmp_path / "routes.db")+ await store.init()+ bus = EventBus()+ brain = RecordingBrain()+ scheduler = TaskScheduler(+ store=store, bus=bus, runner=TaskRunner(store, bus, agent_brain=brain)+ )+ app = FastAPI()+ app.include_router(tasks_routes.router)+ app.state.task_store = store+ app.state.task_scheduler = scheduler+ try:+ task_id = await store.insert(+ TaskSpec(+ title="Digest",+ trigger=TriggerEvery(interval_seconds=86400),+ action=AgentAction(prompt="hi"),+ )+ )+ await store.update_state(task_id, "scheduled")+ transport = httpx.ASGITransport(app=app)+ async with httpx.AsyncClient(transport=transport, base_url="http://t") as client:+ res = await client.post(f"/api/tasks/{task_id}/run")+ assert res.status_code == 200+ await scheduler.shutdown()+ assert brain.started_by_user == [True]+ assert current_started_by_user.get() is False # the marker never leaks out+ finally:+ await scheduler.shutdown()+ await store.close()+++async def test_manual_workflow_run_is_started_by_the_person() -> None:+ seen: list[tuple[str, bool]] = []++ class _Runner:+ async def trigger(self, workflow_id: str, *, trigger_reason: str, **_: Any) -> str:+ seen.append((trigger_reason, current_started_by_user.get()))+ return "run-1"++ app = FastAPI()+ app.include_router(workflows_routes.router)+ app.state.workflow_store = object()+ app.state.workflow_runner = _Runner()+ transport = httpx.ASGITransport(app=app)+ async with httpx.AsyncClient(transport=transport, base_url="http://t") as client:+ res = await client.post("/api/workflows/wf-1/run", json={})+ assert res.status_code == 200+ assert seen == [("manual", True)]