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(safety): stop waiting a minute for an approval nobody can give
Harald75407ae41c56
diff --git a/jarvis/missions/workers/worker_tool_broker.py b/jarvis/missions/workers/worker_tool_broker.pyindex 47d370d489..b81108c05d 100644--- a/jarvis/missions/workers/worker_tool_broker.py+++ b/jarvis/missions/workers/worker_tool_broker.py@@ -26,6 +26,7 @@ from uuid import uuid4from jarvis.core import runtime_refsfrom jarvis.core.protocols import SupervisorToolDescriptor, SupervisorToolRequestfrom jarvis.core.redact import safe_preview+from jarvis.safety.approval_surface import INTERACTIVElogger = logging.getLogger(__name__)@@ -388,6 +389,13 @@ class _BrokerScope:worker_id=self.worker_id,config_snapshot={"voice_confirm": False,+ # A mission worker is unattended, but its approvals+ # are NOT unanswerable: the mission deck's tool-approval+ # panel renders this exact call and a human can grant it+ # while we wait (ADR-0031 + MissionToolApprovalCoordinator).+ # Declared explicitly so the channel does not hinge on a+ # mission_id being stamped further downstream.+ "approval_surface": INTERACTIVE,"worker_broker": True,},cancel_token=self._cancel_token,diff --git a/jarvis/safety/__init__.py b/jarvis/safety/__init__.pyindex 0c563e366b..b953a2b346 100644--- a/jarvis/safety/__init__.py+++ b/jarvis/safety/__init__.py@@ -11,15 +11,18 @@ from typing import TYPE_CHECKING, Anyif TYPE_CHECKING:from .approval import ApprovalWorkflow+ from .approval_surface import ApprovalSurface, resolve_approval_surfacefrom .risk_tier import ActionBlocked, RiskTierEvaluator, TierDecisionfrom .tool_executor import ToolExecutor__all__ = ["ActionBlocked",+ "ApprovalSurface","ApprovalWorkflow","RiskTierEvaluator","TierDecision","ToolExecutor",+ "resolve_approval_surface",]@@ -28,6 +31,13 @@ def __getattr__(name: str) -> Any:from .approval import ApprovalWorkflowreturn ApprovalWorkflow+ if name in {"ApprovalSurface", "resolve_approval_surface"}:+ from .approval_surface import ApprovalSurface, resolve_approval_surface++ return {+ "ApprovalSurface": ApprovalSurface,+ "resolve_approval_surface": resolve_approval_surface,+ }[name]if name in {"ActionBlocked", "RiskTierEvaluator", "TierDecision"}:from .risk_tier import ActionBlocked, RiskTierEvaluator, TierDecisiondiff --git a/jarvis/safety/approval.py b/jarvis/safety/approval.pyindex e0ada592b3..24ee58819b 100644--- a/jarvis/safety/approval.py+++ b/jarvis/safety/approval.py@@ -7,7 +7,13 @@ Sequence:4. User clicks Approve → UI sends `ActionApproved` via a channel →ChannelAdapter re-publishes onto the bus → `wait()`'s future is resolved5. User clicks Deny → analogous `ActionDenied`-6. Timeout → default = deny (`ActionDenied(reason="timeout")`)+6. Timeout → nothing runs (`ActionDenied(reason="timeout")`), and the caller+ is told it was a TIMEOUT, not a refusal++Step 2 only happens on a surface where an answer can actually arrive. Whether+this workflow is waited on at all, peeked at once, or skipped for a two-turn+spoken confirmation is decided by `jarvis.safety.approval_surface` — an+unattended runner must never block here for a decision nobody is there to make.The integration into a channel UI (WebSocket + desktop app) runs overthe same event bus. The UI only needs to publish `ActionApproved`/`ActionDenied`@@ -22,6 +28,12 @@ from uuid import UUIDfrom jarvis.core.bus import EventBusfrom jarvis.core.events import ActionApproved, ActionDenied+#: ``who_or_reason`` returned when the wait ran out before anyone decided.+#: A named constant because the caller MUST be able to tell "nobody answered"+#: apart from "somebody said no" — the two are different outcomes and used to+#: be reported with the same word (audit GT-12).+TIMEOUT_REASON = "timeout"+class ApprovalTicket:"""One armed approval decision that cannot lose an early bus response."""@@ -42,10 +54,30 @@ class ApprovalTicket:try:return await asyncio.wait_for(self._future, timeout=timeout_s)except TimeoutError:- return (False, "timeout")+ return (False, TIMEOUT_REASON)finally:self.close()+ def peek(self) -> tuple[bool, str] | None:+ """The decision if one has ALREADY been made, else ``None``. Never waits.++ An unattended caller uses this instead of :meth:`wait`: the+ pre-authorization bridges (``TaskAutoApprover``,+ ``MissionToolAutoApprover``) answer synchronously while the executor+ awaits its ``ActionApprovalRequired`` publish, so by the time that+ publish returns their verdict is already in the future. Everything+ else would be a wait for a human who is not there, which is why the+ unattended path must never call ``wait()``.++ Leaves the ticket open — the caller decides whether the outcome is a+ decision to act on or a dead end to close.+ """+ if not self._future.done() or self._future.cancelled():+ return None+ if self._future.exception() is not None:+ return None+ return self._future.result()+def close(self) -> None:"""Remove an unresolved ticket so cancellation cannot leak state."""if self._closed:diff --git a/jarvis/safety/approval_surface.py b/jarvis/safety/approval_surface.pynew file mode 100644index 0000000000..2b3435a357--- /dev/null+++ b/jarvis/safety/approval_surface.py@@ -0,0 +1,133 @@+"""Who — if anyone — can answer the approval gate for one tool call.++An ``ask``-tier tool must not run until somebody authorizes it. WHO that+somebody is depends entirely on the surface the call arrives from, and the+surfaces differ in kind:++``conversational``+ A human sits inside the turn (voice, realtime, chat). They cannot click a+ modal mid-sentence, so the executor defers the action and the surface ASKS+ on the next turn (``VOICE_CONFIRM_SENTINEL`` → the user's "ja" resumes it+ via ``ToolExecutor.execute_confirmed``).++``interactive``+ A human can answer OUT OF BAND while the call waits. Today that is exactly+ one channel: the mission deck's tool-approval panel+ (``MissionToolApprovalCoordinator`` behind+ ``POST /missions/{id}/tool-approvals/{trace_id}/approve``). Blocking for+ the approval timeout is correct here — the answer really can arrive.++``unattended``+ Nobody is reachable at all: a scheduled workflow, a cron run, a one-shot+ CLI invocation, a background job. Waiting cannot produce an answer, so the+ executor must not pretend it might. Pre-authorization bridges+ (``TaskAutoApprover``, ``MissionToolAutoApprover``) get their chance —+ they answer synchronously while ``ActionApprovalRequired`` is being+ published — and if none of them speaks up the call fails FAST and is+ reported as "approval was impossible", never as "the user refused".++Why this split exists (audit GT-12): every surface except voice and realtime+used to fall into the blocking wait. With no approval UI outside missions, a+CLI, REST, workflow, or chat call to an ask-tier tool sat silent for the full+60-second timeout and then recorded that timeout as a DENIAL — a minute of+nothing, followed by the wrong reason.++**The surface is declared by the calling LAYER, never by the model.** A tool+call's ``args`` come from the LLM; ``config_snapshot`` is built in code by the+surface itself (``jarvis/brain/tool_use_loop.py``,+``BrainSupervisorToolGateway``, ``WorkerToolBroker``). ``resolve_approval_+surface`` reads the snapshot ONLY — an ``args`` key of the same name is+invisible to it — so no prompt and no tool argument can talk the executor into+a channel that asks less. Unknown values are ignored rather than trusted, and+the fallback chain never widens what may run: it only decides who gets asked.++This module holds no policy about WHICH tools need approval. The tier+precedence (blacklist > whitelist > tool default) lives in+``jarvis.safety.risk_tier`` and is untouched by anything here.+"""+from __future__ import annotations++import logging+from collections.abc import Mapping+from typing import Any, Final, Literal, cast++log = logging.getLogger(__name__)++ApprovalSurface = Literal["conversational", "interactive", "unattended"]++#: A human is inside the turn — defer and ask on the next one.+CONVERSATIONAL: Final[ApprovalSurface] = "conversational"+#: A human can decide out of band while the call waits (mission deck).+INTERACTIVE: Final[ApprovalSurface] = "interactive"+#: Nobody can decide — fail fast and say so.+UNATTENDED: Final[ApprovalSurface] = "unattended"++VALID_APPROVAL_SURFACES: Final[frozenset[str]] = frozenset(+ {CONVERSATIONAL, INTERACTIVE, UNATTENDED}+)++#: ``config_snapshot`` key a surface uses to declare itself explicitly.+APPROVAL_SURFACE_KEY: Final[str] = "approval_surface"++#: The original boolean, kept as a first-class alias for ``conversational``.+#: Voice and realtime have set it since the two-turn confirmation flow shipped+#: and their behaviour must stay byte-identical.+VOICE_CONFIRM_KEY: Final[str] = "voice_confirm"++#: Presence of a mission id means the mission deck can render and answer this+#: call. It is stamped by ``BrainSupervisorToolGateway`` from the broker's+#: ``SupervisorToolRequest``, i.e. in code, out of the model's reach.+MISSION_ID_KEY: Final[str] = "mission_id"+++def resolve_approval_surface(+ config_snapshot: Mapping[str, Any] | None,+) -> ApprovalSurface:+ """Decide which approval channel this call actually has.++ Order (first match wins):++ 1. An explicit, valid ``approval_surface`` from the calling layer.+ 2. ``voice_confirm=True`` — the legacy conversational declaration.+ 3. A non-empty ``mission_id`` — the mission deck can answer out of band.+ 4. Otherwise ``unattended``: no channel is known to exist, so the honest+ answer is that nobody can approve.++ An unrecognised ``approval_surface`` string is logged and ignored; the+ remaining rules then apply. That is deliberate — a typo must not silently+ grant a call a channel it does not have, and it must not crash the gate+ either.+ """+ snapshot: Mapping[str, Any] = config_snapshot or {}++ declared = snapshot.get(APPROVAL_SURFACE_KEY)+ if declared is not None:+ text = str(declared).strip().lower()+ if text in VALID_APPROVAL_SURFACES:+ return cast(ApprovalSurface, text)+ log.warning(+ "Unknown %s=%r — falling back to the derived surface",+ APPROVAL_SURFACE_KEY,+ declared,+ )++ if bool(snapshot.get(VOICE_CONFIRM_KEY)):+ return CONVERSATIONAL++ if str(snapshot.get(MISSION_ID_KEY) or "").strip():+ return INTERACTIVE++ return UNATTENDED+++__all__ = [+ "APPROVAL_SURFACE_KEY",+ "CONVERSATIONAL",+ "INTERACTIVE",+ "MISSION_ID_KEY",+ "UNATTENDED",+ "VALID_APPROVAL_SURFACES",+ "VOICE_CONFIRM_KEY",+ "ApprovalSurface",+ "resolve_approval_surface",+]diff --git a/jarvis/safety/tool_executor.py b/jarvis/safety/tool_executor.pyindex b41cc8504e..e9a333f667 100644--- a/jarvis/safety/tool_executor.py+++ b/jarvis/safety/tool_executor.py@@ -33,7 +33,12 @@ from jarvis.core.protocols import ()from jarvis.core.redact import safe_preview-from .approval import ApprovalWorkflow+from .approval import TIMEOUT_REASON, ApprovalWorkflow+from .approval_surface import (+ CONVERSATIONAL,+ UNATTENDED,+ resolve_approval_surface,+)from .risk_tier import ActionBlocked, RiskTierEvaluatorif TYPE_CHECKING:@@ -54,6 +59,23 @@ log = logging.getLogger(__name__)VOICE_CONFIRM_SENTINEL = "__voice_confirm_required__"+# The three ways an approval-gated call can end WITHOUT running. They carry+# distinct ``ToolResult.error`` prefixes on purpose: until the GT-12 fix a+# 60-second timeout came back as ``approval-denied (timeout)``, so every+# consumer that classifies on ``startswith("approval-denied")`` — the mission+# ``WorkerToolBroker`` does exactly that — recorded "the user refused" for a+# decision nobody was ever asked to make. A refusal, a silence, and an absent+# human are three different facts and must read as three different facts.+APPROVAL_DENIED_PREFIX = "approval-denied"+APPROVAL_TIMEOUT_PREFIX = "approval-timeout"+APPROVAL_UNAVAILABLE_PREFIX = "approval-unavailable"++#: ``ToolResult.output["outcome"]`` for the unattended dead end, and the+#: ``ActionDenied.reason`` published alongside it. The word says what happened:+#: approval was impossible, not withheld.+APPROVAL_UNAVAILABLE_OUTCOME = "approval_unavailable"++# ``plausibility_context_fn`` returns (Transcript | None, wake_age_s | None).# The voice pipeline registers a provider that supplies the last user-turn# transcript and the seconds since the last wake trigger. On@@ -164,6 +186,61 @@ class ToolExecutor:except Exception: # noqa: BLE001log.debug("publish_guard_denied failed", exc_info=True)+ async def _approval_unavailable(+ self,+ tool: Tool,+ tid: UUID,+ risk_tier: str,+ config_snapshot: dict[str, Any] | None,+ ) -> ToolResult:+ """The honest dead end: this action needed a human and had none.++ Publishes ``ActionDenied`` so the refusal is visible in the timeline+ (same reasoning as :meth:`publish_guard_denied` — a call that silently+ vanishes is worse than one that failed), but says in the reason WHY it+ did not run. The returned error carries its own prefix so no consumer+ can mistake it for a user's "no", and the output carries a+ plain-language sentence a person can actually read in a run log.+ """+ reason = f"{APPROVAL_UNAVAILABLE_OUTCOME}: no approval channel on this surface"+ await self._bus.publish(ActionDenied(+ trace_id=tid,+ tool_name=tool.name,+ reason=reason,+ ))+ log.info(+ "approval-unavailable: %s (tier=%s) needed a confirmation and this "+ "surface has nobody to give it — failing fast",+ tool.name, risk_tier,+ )+ output: dict[str, Any] = {+ "outcome": APPROVAL_UNAVAILABLE_OUTCOME,+ "tool_name": tool.name,+ "trace_id": str(tid),+ "risk_tier": risk_tier,+ }+ # Plain-language sentence in the turn's ALREADY-RESOLVED output+ # language (Runtime Output Language doctrine: this layer reads the+ # resolved value, it never re-derives one). Phrasing lives in the one+ # channel-agnostic table, next to the confirmation question it belongs+ # to. Lazy import — ``jarvis.voice`` couples to ``jarvis.core.self_mod``+ # via its package __init__, so importing at module load would create an+ # order-dependent cycle (same pattern as the tool-use loop).+ try:+ from jarvis.voice.tool_confirmation import format_approval_unavailable++ output["message"] = format_approval_unavailable(+ tool.name,+ language=str((config_snapshot or {}).get("output_language") or ""),+ )+ except Exception as exc: # noqa: BLE001 — phrasing must not decide safety+ log.debug("approval-unavailable phrasing failed: %s", exc)+ return ToolResult(+ success=False,+ output=output,+ error=f"{APPROVAL_UNAVAILABLE_PREFIX} ({reason})",+ )+async def execute(self,tool: Tool,@@ -235,9 +312,17 @@ class ToolExecutor:tool.name, exc,)needs_confirm = tier_confirm or plaus_confirm- voice_confirm = bool((config_snapshot or {}).get("voice_confirm"))+ # WHO can answer this gate — declared by the calling layer, never by+ # the model (see ``approval_surface``). It changes only how the+ # approval is obtained, never whether one is needed: ``needs_confirm``+ # above is the untouched tier decision.+ surface = resolve_approval_surface(config_snapshot)+ voice_confirm = surface == CONVERSATIONALapproval_ticket = Noneif needs_confirm and not voice_confirm:+ # An unattended call arms too: the pre-authorization bridges answer+ # synchronously on the ActionApprovalRequired publish below, and+ # ADR-0031 relies on the ticket existing before that publish.approval_ticket = self._approval.arm(tid)# 3.5 Proposed event (the UI can use this as a live indicator). The@@ -261,6 +346,14 @@ class ToolExecutor:if plaus is not None and plaus.require_confirmationelse "risk_tier")+ # An unattended call expires immediately: it will not be waited on,+ # so advertising a 60-second window would invite a UI to offer a+ # decision that can no longer reach anybody.+ window_ns = (+ 0+ if surface == UNATTENDED+ else int(self._default_timeout_s * 1_000_000_000)+ )await self._bus.publish(ActionApprovalRequired(trace_id=tid,@@ -268,8 +361,7 @@ class ToolExecutor:risk_tier=decision.tier,reason=reason,args_preview=safe_preview(args),- expires_at_ns=time.time_ns()- + int(self._default_timeout_s * 1_000_000_000),+ expires_at_ns=time.time_ns() + window_ns,mission_id=_optional_string((config_snapshot or {}).get("mission_id")),@@ -318,24 +410,50 @@ class ToolExecutor:output=sentinel_output,error=VOICE_CONFIRM_SENTINEL,)- try:- approved, who_or_reason = await self._approval.wait(- tid, self._default_timeout_s+ if surface == UNATTENDED:+ # Nobody is there to ask. The pre-authorization bridges have+ # already had their say — they answer inline while the+ # ActionApprovalRequired publish above is awaited — so a ticket+ # that is still undecided will stay undecided forever. Waiting+ # the full timeout would buy a minute of silence and then+ # report a refusal nobody made (audit GT-12).+ decided = (+ approval_ticket.peek() if approval_ticket is not None else None)- finally:+ if decided is None:+ if approval_ticket is not None:+ approval_ticket.close()+ return await self._approval_unavailable(+ tool, tid, decision.tier, config_snapshot,+ )+ approved, who_or_reason = decidedif approval_ticket is not None:approval_ticket.close()+ else:+ try:+ approved, who_or_reason = await self._approval.wait(+ tid, self._default_timeout_s+ )+ finally:+ if approval_ticket is not None:+ approval_ticket.close()if not approved:await self._bus.publish(ActionDenied(trace_id=tid,tool_name=tool.name,reason=who_or_reason,))- return ToolResult(- success=False,- output=None,- error=f"approval-denied ({who_or_reason})",- )+ # A silence is not a "no". Keep the two apart so the caller,+ # the mission broker, and the run log can each say which+ # actually happened.+ if who_or_reason == TIMEOUT_REASON:+ error = (+ f"{APPROVAL_TIMEOUT_PREFIX} (nobody decided within "+ f"{self._default_timeout_s:.0f}s)"+ )+ else:+ error = f"{APPROVAL_DENIED_PREFIX} ({who_or_reason})"+ return ToolResult(success=False, output=None, error=error)approved_by = who_or_reason # "user" or "auto"if cancel_token is not None and cancel_token.is_cancelled():diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.pyindex 4da709694f..4a95acdbe1 100644--- a/jarvis/ui/desktop_app.py+++ b/jarvis/ui/desktop_app.py@@ -2045,12 +2045,26 @@ class DesktopApp:# recap (ui.web.ws.mission_inject) from force-spawn — a recap# is discussed inline, never re-dispatched (doom-loop fix# 2026-06-16). Other callers default to None (normal routing).+ # allow_voice_confirm=True is load-bearing here (audit+ # GT-12): a chat user IS present, but there is no approval+ # modal anywhere outside the mission deck, so without this+ # an ask-tier tool (send this mail, run this command) went+ # to the executor with no channel at all and came back+ # refused. With it, chat gets the same two-turn flow voice+ # has — the turn ENDS with the confirmation question as its+ # reply, and the user's next message ("ja"/"nein") resolves+ # it. The phrasing layer is channel-agnostic by design+ # (jarvis/voice/tool_confirmation.py); nothing here speaks.+ chat_kwargs: dict[str, Any] = {+ "trace_id": evt.trace_id,+ "source_layer": evt.source_layer,+ "conversation_id": thread_id,+ "allow_voice_confirm": True,+ }reply = await _await_cancellable_chat_turn(generate(evt.text,- trace_id=evt.trace_id,- source_layer=evt.source_layer,- conversation_id=thread_id,+ **_supported_call_kwargs(generate, chat_kwargs),),loop,)diff --git a/jarvis/voice/tool_confirmation.py b/jarvis/voice/tool_confirmation.pyindex 39be725093..3aa0289f1f 100644--- a/jarvis/voice/tool_confirmation.py+++ b/jarvis/voice/tool_confirmation.py@@ -157,6 +157,18 @@ _OUTCOME: dict[str, dict[str, str]] = {"en": "Please just say yes or no.","es": "Di simplemente sí o no, por favor.",},+ # Nobody could be asked at all — an unattended run (a scheduled workflow,+ # a cron job, a one-shot CLI call) reached a consequential tool. Says why+ # nothing happened without claiming a refusal that never took place+ # (audit GT-12). Read from a run log far more often than spoken.+ "unavailable": {+ "de": "Dafür brauche ich deine Freigabe, und hier kann sie niemand geben. "+ "Ich habe es nicht gemacht.",+ "en": "That needs your approval, and nobody here can give it. "+ "So I did not do it.",+ "es": "Eso necesita tu aprobación y aquí nadie puede darla. "+ "Así que no lo hice.",+ },}@@ -188,3 +200,22 @@ def format_confirm_outcome(if cleaned:phrase = f"{phrase} {cleaned}"return phrase+++def format_approval_unavailable(+ tool_name: str, *, language: str = DEFAULT_LOCALE+) -> str:+ """Render why a consequential action did not run when NOBODY could approve.++ Used by ``ToolExecutor`` on an unattended surface (a scheduled workflow, a+ cron run, a one-shot CLI call), where the two-turn confirmation above has+ no second turn to happen in. Deliberately a sibling of+ ``format_confirm_outcome`` over the same table: "the user said no",+ "nobody answered in time", and "there was nobody to ask" are three+ different facts, and the wording keeps them apart.++ ``tool_name`` is accepted for future tool-specific wording and is NOT+ interpolated today — a raw internal identifier ("gmail_rest") explains+ nothing to a person and has no place in a spoken line.+ """+ return format_confirm_outcome("unavailable", tool_name, language=language)diff --git a/tests/missions/test_mission_tool_auto_approver.py b/tests/missions/test_mission_tool_auto_approver.pyindex edee3f4053..b38345f63a 100644--- a/tests/missions/test_mission_tool_auto_approver.py+++ b/tests/missions/test_mission_tool_auto_approver.py@@ -235,7 +235,7 @@ async def test_armed_mission_call_executes_without_human() -> None:assert tool.approved_by == "mission-grant:m-e2e"-async def test_unarmed_mission_call_still_denies_on_timeout() -> None:+async def test_unarmed_mission_call_times_out_without_running() -> None:bus = EventBus()executor = ToolExecutor(bus,@@ -253,7 +253,12 @@ async def test_unarmed_mission_call_still_denies_on_timeout() -> None:)assert result.success is False- assert "approval-denied" in (result.error or "")+ # A mission call keeps its human channel (the deck's approval panel), so it+ # WAITS — and an unanswered wait is a timeout, not a refusal. Reporting it+ # as "approval-denied (timeout)" is what made the broker file every silence+ # as a maintainer veto (audit GT-12).+ assert (result.error or "").startswith("approval-timeout")+ assert not (result.error or "").startswith("approval-denied")assert tool.calls == 0diff --git a/tests/unit/safety/test_approval_surface.py b/tests/unit/safety/test_approval_surface.pynew file mode 100644index 0000000000..95ec0eebd1--- /dev/null+++ b/tests/unit/safety/test_approval_surface.py@@ -0,0 +1,65 @@+"""Which approval channel a tool call actually has (audit GT-12).++``resolve_approval_surface`` answers one question: if this ``ask``-tier call+needs a human, WHO can be reached? Getting that wrong is what made every+non-voice surface stall for the full approval timeout and then record the+silence as a refusal.+"""+from __future__ import annotations++from jarvis.safety.approval_surface import (+ CONVERSATIONAL,+ INTERACTIVE,+ UNATTENDED,+ resolve_approval_surface,+)+++def test_nothing_declared_is_unattended() -> None:+ """The honest default: no declaration means no known channel.++ A workflow step, a cron run, and a one-shot CLI call all reach the+ executor with an empty snapshot. Assuming a human would be a lie.+ """+ assert resolve_approval_surface(None) == UNATTENDED+ assert resolve_approval_surface({}) == UNATTENDED+ assert resolve_approval_surface({"output_language": "de"}) == UNATTENDED+++def test_voice_confirm_still_means_conversational() -> None:+ """The legacy boolean keeps voice and realtime byte-identical."""+ assert resolve_approval_surface({"voice_confirm": True}) == CONVERSATIONAL+ assert resolve_approval_surface({"voice_confirm": False}) == UNATTENDED+++def test_a_mission_id_grants_the_deck_channel() -> None:+ """The mission deck's tool-approval panel can answer out of band."""+ assert resolve_approval_surface({"mission_id": "m-1"}) == INTERACTIVE+ # Blank strings are not a channel.+ assert resolve_approval_surface({"mission_id": " "}) == UNATTENDED+ assert resolve_approval_surface({"mission_id": None}) == UNATTENDED+++def test_explicit_declaration_wins_over_the_derived_channel() -> None:+ for value in (CONVERSATIONAL, INTERACTIVE, UNATTENDED):+ assert resolve_approval_surface({"approval_surface": value}) == value+ # Explicit beats both the legacy boolean and the mission-id inference.+ assert (+ resolve_approval_surface(+ {"approval_surface": UNATTENDED, "voice_confirm": True, "mission_id": "m"}+ )+ == UNATTENDED+ )+++def test_unknown_declaration_never_invents_a_channel() -> None:+ """A typo must fall back, not crash and not grant a richer channel."""+ assert resolve_approval_surface({"approval_surface": "supervised"}) == UNATTENDED+ assert (+ resolve_approval_surface({"approval_surface": "", "mission_id": "m-1"})+ == INTERACTIVE+ )+++def test_declaration_is_case_and_whitespace_tolerant() -> None:+ assert resolve_approval_surface({"approval_surface": " Interactive "}) == INTERACTIVEdiff --git a/tests/unit/safety/test_tool_executor_plausibility.py b/tests/unit/safety/test_tool_executor_plausibility.pyindex f2a5c2fd8c..68bc051ad4 100644--- a/tests/unit/safety/test_tool_executor_plausibility.py+++ b/tests/unit/safety/test_tool_executor_plausibility.py@@ -19,9 +19,18 @@ from jarvis.core.bus import EventBusfrom jarvis.core.config import BrainPlausibilityConfig, SafetyConfigfrom jarvis.core.protocols import ExecutionContext, ToolResult, Transcriptfrom jarvis.safety.approval import ApprovalWorkflow+from jarvis.safety.approval_surface import INTERACTIVEfrom jarvis.safety.risk_tier import RiskTierEvaluatorfrom jarvis.safety.tool_executor import ToolExecutor+#: These tests measure WHETHER a confirmation was requested, by counting+#: ``ApprovalWorkflow.wait()`` calls. That only counts anything on a surface+#: where waiting is the right move — an unattended caller now fails fast+#: instead of waiting for nobody (GT-12), which would make every assertion+#: here trivially zero. Declaring the channel keeps the subject the+#: plausibility hook, not the approval channel.+_ATTENDED: dict[str, Any] = {"approval_surface": INTERACTIVE}+class _FakeTool:name = "test_tool"@@ -79,7 +88,7 @@ async def test_no_context_fn_runs_like_before() -> None:"""Without a registered ``plausibility_context_fn`` no guard kicks in."""executor, approval = _executor_with_plausibility(context_fn=None)tool = _FakeTool()- result = await executor.execute(tool, args={})+ result = await executor.execute(tool, args={}, config_snapshot=_ATTENDED)# ``ask`` tier triggers approval anyway -> 1 call via the tier workflow.assert approval.wait_calls == 1assert result.success is True@@ -94,7 +103,7 @@ async def test_low_confidence_monitor_does_not_force_approval() -> None:context_fn=lambda: (transcript, 5.0),)tool = _MonitorTool()- result = await executor.execute(tool, args={})+ result = await executor.execute(tool, args={}, config_snapshot=_ATTENDED)# ``monitor`` tier doesn't trigger approval by itself, and plausibility# at monitor doesn't require anything either -> 0 approval calls.assert approval.wait_calls == 0@@ -110,7 +119,7 @@ async def test_low_confidence_ask_with_normal_tier_workflow() -> None:context_fn=lambda: (transcript, 5.0),)tool = _FakeTool() # ask tier- result = await executor.execute(tool, args={})+ result = await executor.execute(tool, args={}, config_snapshot=_ATTENDED)assert approval.wait_calls == 1assert result.success is True@@ -145,7 +154,7 @@ async def test_whitelist_downgrade_skips_plausibility() -> None:safety=safety,)tool = _MonitorTool()- result = await executor.execute(tool, args={"target": "foo"})+ result = await executor.execute(tool, args={"target": "foo"}, config_snapshot=_ATTENDED)# Whitelist downgraded ``monitor_tool`` to ``safe`` -> no approval.assert approval.wait_calls == 0# Context fn must NOT be called, because of the whitelist skip.@@ -161,7 +170,7 @@ async def test_high_confidence_recent_wake_no_extra_confirmation() -> None:context_fn=lambda: (transcript, 2.0),)tool = _MonitorTool()- result = await executor.execute(tool, args={})+ result = await executor.execute(tool, args={}, config_snapshot=_ATTENDED)# ``monitor`` + plausibility=ok -> no approval.assert approval.wait_calls == 0assert result.success is True@@ -175,7 +184,7 @@ async def test_context_fn_exception_is_swallowed() -> None:executor, approval = _executor_with_plausibility(context_fn=broken_fn)tool = _MonitorTool()- result = await executor.execute(tool, args={})+ result = await executor.execute(tool, args={}, config_snapshot=_ATTENDED)# Despite the crash: the tool runs, no approval.assert approval.wait_calls == 0assert result.success is Truediff --git a/tests/unit/safety/test_tool_executor_unattended.py b/tests/unit/safety/test_tool_executor_unattended.pynew file mode 100644index 0000000000..e8a14593db--- /dev/null+++ b/tests/unit/safety/test_tool_executor_unattended.py@@ -0,0 +1,459 @@+"""An ask-tier tool must never wait for an approval nobody can give (GT-12).++Before this fix ``ToolExecutor.execute`` blocked in ``ApprovalWorkflow.wait()``+for 60 seconds on EVERY surface except voice and realtime, then returned the+timeout as ``approval-denied (timeout)``. A CLI call, a REST call, a scheduled+workflow, and a chat turn therefore all produced a minute of silence followed+by a refusal that no human ever made.++These tests pin the four outcomes apart:++* approved — somebody (or a pre-authorization bridge) said yes; the tool runs+* denied — somebody said no+* timed out — a channel existed, nobody answered in time+* unavailable— there was no channel at all; fail fast and say so++and guard that none of this widened what may run without approval.+"""+from __future__ import annotations++import asyncio+import time+from typing import Any+from uuid import UUID, uuid4++import pytest++from jarvis.core.bus import EventBus+from jarvis.core.config import SafetyConfig+from jarvis.core.events import (+ ActionApprovalRequired,+ ActionApproved,+ ActionDenied,+ ActionExecuted,+)+from jarvis.core.protocols import ExecutionContext, ToolResult+from jarvis.safety.approval import ApprovalWorkflow+from jarvis.safety.approval_surface import CONVERSATIONAL, INTERACTIVE, UNATTENDED+from jarvis.safety.risk_tier import RiskTierEvaluator+from jarvis.safety.tool_executor import (+ APPROVAL_DENIED_PREFIX,+ APPROVAL_TIMEOUT_PREFIX,+ APPROVAL_UNAVAILABLE_OUTCOME,+ APPROVAL_UNAVAILABLE_PREFIX,+ VOICE_CONFIRM_SENTINEL,+ ToolExecutor,+)++pytestmark = pytest.mark.asyncio+++class _AskTool:+ name = "gmail"+ risk_tier = "ask"+ schema: dict[str, Any] = {}++ def __init__(self) -> None:+ self.calls = 0+ self.last_ctx: ExecutionContext | None = None++ async def execute(self, args: dict[str, Any], ctx: ExecutionContext) -> ToolResult:+ self.calls += 1+ self.last_ctx = ctx+ return ToolResult(success=True, output="sent")+++class _SafeTool(_AskTool):+ name = "search_web"+ risk_tier = "safe"+++class _BlockTool(_AskTool):+ name = "wipe_disk"+ risk_tier = "block"+++class _WaitSpy(ApprovalWorkflow):+ """Records every blocking wait so a "fail fast" claim is provable."""++ def __init__(self, bus: EventBus, **kwargs: Any) -> None:+ super().__init__(bus, **kwargs)+ self.waits: list[float] = []++ async def wait( # type: ignore[override]+ self, trace_id: UUID, timeout_s: float | None = None+ ) -> tuple[bool, str]:+ self.waits.append(timeout_s if timeout_s is not None else -1.0)+ return await super().wait(trace_id, timeout_s)+++def _executor(+ *, timeout_s: float = 60.0, safety: SafetyConfig | None = None+) -> tuple[ToolExecutor, _WaitSpy, EventBus]:+ bus = EventBus()+ approval = _WaitSpy(bus, timeout_s=timeout_s)+ executor = ToolExecutor(+ bus,+ RiskTierEvaluator(safety or SafetyConfig()),+ approval,+ default_timeout_s=timeout_s,+ )+ return executor, approval, bus+++def _denials(bus: EventBus) -> list[ActionDenied]:+ seen: list[ActionDenied] = []++ async def _capture(event: ActionDenied) -> None:+ seen.append(event)++ bus.subscribe(ActionDenied, _capture)+ return seen+++# ---------------------------------------------------------------- unattended+++async def test_unattended_ask_tier_fails_fast_instead_of_stalling() -> None:+ """The whole bug in one test: no channel, no 60-second wait, honest reason."""+ executor, approval, bus = _executor(timeout_s=60.0)+ denials = _denials(bus)+ tool = _AskTool()++ started = time.perf_counter()+ result = await executor.execute(tool, args={"to": "tom"})+ elapsed = time.perf_counter() - started++ # Fast: the blocking waiter was never entered at all.+ assert approval.waits == []+ assert elapsed < 1.0+ # Honest: not run, and not reported as a refusal.+ assert result.success is False+ assert tool.calls == 0+ assert (result.error or "").startswith(APPROVAL_UNAVAILABLE_PREFIX)+ assert not (result.error or "").startswith(APPROVAL_DENIED_PREFIX)+ # Visible: the refusal reaches the timeline with its real reason.+ assert [e.reason for e in denials] == [+ f"{APPROVAL_UNAVAILABLE_OUTCOME}: no approval channel on this surface"+ ]+++async def test_unattended_result_states_what_happened() -> None:+ """The caller gets a structured outcome plus a sentence a person can read."""+ executor, _approval, _bus = _executor()+ tid = uuid4()++ result = await executor.execute(+ _AskTool(),+ args={},+ config_snapshot={"output_language": "de"},+ trace_id=tid,+ )++ assert result.output["outcome"] == APPROVAL_UNAVAILABLE_OUTCOME+ assert result.output["tool_name"] == "gmail"+ assert result.output["trace_id"] == str(tid)+ assert result.output["risk_tier"] == "ask"+ message = result.output["message"]+ # Rendered in the turn's already-resolved language, never re-derived here.+ assert "Freigabe" in message # i18n-allow — quoted runtime German output+ assert message == result.output["message"].strip()+++async def test_unattended_message_follows_the_resolved_language() -> None:+ executor, _approval, _bus = _executor()+ result = await executor.execute(+ _AskTool(), args={}, config_snapshot={"output_language": "es"},+ )+ assert "aprobación" in result.output["message"] # i18n-allow — runtime Spanish+++async def test_unattended_still_honours_a_synchronous_preauthorization() -> None:+ """A pre-authorized call must still run — bridges answer on the publish.++ ``TaskAutoApprover`` / ``MissionToolAutoApprover`` reply to+ ``ActionApprovalRequired`` inline, so the verdict is already in the ticket+ by the time the publish returns. Failing fast must not outrun them.+ """+ executor, approval, bus = _executor()+ tool = _AskTool()++ async def _bridge(event: ActionApprovalRequired) -> None:+ await bus.publish(+ ActionApproved(+ trace_id=event.trace_id,+ tool_name=event.tool_name,+ approved_by="scheduled-task:abc",+ )+ )++ bus.subscribe(ActionApprovalRequired, _bridge)++ result = await executor.execute(tool, args={})++ assert result.success is True+ assert tool.calls == 1+ assert tool.last_ctx is not None+ assert tool.last_ctx.approved_by == "scheduled-task:abc"+ # Ran without ever blocking a waiter.+ assert approval.waits == []+++async def test_unattended_preauthorization_can_also_refuse() -> None:+ """A bridge that says no is a real denial, not an absent human."""+ executor, _approval, bus = _executor()+ tool = _AskTool()++ async def _bridge(event: ActionApprovalRequired) -> None:+ await bus.publish(+ ActionDenied(+ trace_id=event.trace_id,+ tool_name=event.tool_name,+ reason="policy",+ )+ )++ bus.subscribe(ActionApprovalRequired, _bridge)++ result = await executor.execute(tool, args={})++ assert result.success is False+ assert tool.calls == 0+ assert (result.error or "").startswith(APPROVAL_DENIED_PREFIX)+ assert "policy" in (result.error or "")+++async def test_unattended_approval_request_advertises_no_window() -> None:+ """No UI should offer a decision on a call that is already over."""+ executor, _approval, bus = _executor(timeout_s=60.0)+ requests: list[ActionApprovalRequired] = []++ async def _capture(event: ActionApprovalRequired) -> None:+ requests.append(event)++ bus.subscribe(ActionApprovalRequired, _capture)++ await executor.execute(_AskTool(), args={})++ assert len(requests) == 1+ assert requests[0].expires_at_ns <= time.time_ns()+++# --------------------------------------------------------------- interactive+++async def test_interactive_surface_still_waits_for_the_mission_deck() -> None:+ """A mission call keeps its human channel — this must NOT fail fast."""+ executor, approval, bus = _executor(timeout_s=5.0)+ tool = _AskTool()+ tid = uuid4()++ async def _click_approve() -> None:+ await asyncio.sleep(0.02)+ await bus.publish(ActionApproved(trace_id=tid, approved_by="user"))++ clicker = asyncio.create_task(_click_approve())+ result = await executor.execute(+ tool,+ args={},+ config_snapshot={"mission_id": "m-1", "worker_id": "w-1"},+ trace_id=tid,+ )+ await clicker++ assert approval.waits == [5.0]+ assert result.success is True+ assert tool.calls == 1+ assert tool.last_ctx is not None+ assert tool.last_ctx.approved_by == "user"+++async def test_interactive_denial_reads_as_a_denial() -> None:+ executor, _approval, bus = _executor(timeout_s=5.0)+ tool = _AskTool()+ tid = uuid4()++ async def _click_deny() -> None:+ await asyncio.sleep(0.02)+ await bus.publish(ActionDenied(trace_id=tid, reason="user_vetoed"))++ clicker = asyncio.create_task(_click_deny())+ result = await executor.execute(+ tool, args={}, config_snapshot={"mission_id": "m-1"}, trace_id=tid,+ )+ await clicker++ assert result.success is False+ assert tool.calls == 0+ assert result.error == f"{APPROVAL_DENIED_PREFIX} (user_vetoed)"+++async def test_interactive_timeout_is_not_reported_as_a_denial() -> None:+ """A silence and a "no" are different facts and must read differently.++ ``WorkerToolBroker`` classifies on ``startswith("approval-denied")``, so+ the old ``approval-denied (timeout)`` filed every unanswered mission call+ as a refusal by the maintainer.+ """+ executor, approval, _bus = _executor(timeout_s=0.05)+ tool = _AskTool()++ result = await executor.execute(+ tool, args={}, config_snapshot={"mission_id": "m-1"},+ )++ assert approval.waits == [0.05]+ assert result.success is False+ assert tool.calls == 0+ assert (result.error or "").startswith(APPROVAL_TIMEOUT_PREFIX)+ assert not (result.error or "").startswith(APPROVAL_DENIED_PREFIX)+ assert not (result.error or "").startswith(APPROVAL_UNAVAILABLE_PREFIX)+++# ------------------------------------------------------------- conversational+++async def test_conversational_surface_defers_for_a_two_turn_question() -> None:+ """Chat and voice ask instead of blocking, then run on the user's "ja"."""+ executor, approval, _bus = _executor()+ tool = _AskTool()+ tid = uuid4()++ deferred = await executor.execute(+ tool,+ args={"to": "tom"},+ config_snapshot={"approval_surface": CONVERSATIONAL},+ trace_id=tid,+ )++ assert approval.waits == []+ assert tool.calls == 0+ assert deferred.error == VOICE_CONFIRM_SENTINEL+ assert deferred.output["trace_id"] == str(tid)++ resumed = await executor.execute_confirmed(tid)+ assert resumed.success is True+ assert tool.calls == 1+ assert tool.last_ctx is not None+ assert tool.last_ctx.approved_by == "user"+++async def test_conversational_veto_never_runs_the_action() -> None:+ executor, _approval, _bus = _executor()+ tool = _AskTool()+ tid = uuid4()++ await executor.execute(+ tool, args={}, config_snapshot={"voice_confirm": True}, trace_id=tid,+ )+ assert await executor.cancel_pending(tid) is True+ assert (await executor.execute_confirmed(tid)).success is False+ assert tool.calls == 0+++# ------------------------------------------------------- nothing was widened+++async def test_block_tier_is_still_blocked_on_every_surface() -> None:+ """Fail-fast is about WHO approves, never about what may run."""+ for snapshot in (+ None,+ {"voice_confirm": True},+ {"mission_id": "m-1"},+ {"approval_surface": UNATTENDED},+ ):+ executor, _approval, _bus = _executor()+ tool = _BlockTool()+ result = await executor.execute(tool, args={}, config_snapshot=snapshot)+ assert result.success is False+ assert tool.calls == 0+ assert "Blacklist match" in (result.error or "")+++async def test_blacklist_still_beats_everything_when_unattended() -> None:+ safety = SafetyConfig()+ safety.blacklist.commands = ["*rm -rf /*"]+ safety.whitelist.commands = ["*"]+ executor, _approval, _bus = _executor(safety=safety)+ tool = _AskTool()++ result = await executor.execute(tool, args={"command": "rm -rf /"})++ assert result.success is False+ assert tool.calls == 0+ assert "Blacklist match" in (result.error or "")+++async def test_whitelist_downgrade_still_runs_unattended() -> None:+ """A whitelisted tool needs no confirmation, so it has nothing to wait for."""+ safety = SafetyConfig()+ safety.whitelist.commands = ["gmail *"]+ executor, approval, _bus = _executor(safety=safety)+ tool = _AskTool()++ result = await executor.execute(tool, args={"to": "tom"})++ assert result.success is True+ assert tool.calls == 1+ assert approval.waits == []+ assert tool.last_ctx is not None+ assert tool.last_ctx.approved_by == "whitelist"+++async def test_safe_tier_is_untouched_by_the_surface() -> None:+ executor, approval, _bus = _executor()+ tool = _SafeTool()+ result = await executor.execute(tool, args={})+ assert result.success is True+ assert tool.calls == 1+ assert approval.waits == []+++async def test_the_model_cannot_declare_its_own_surface() -> None:+ """``args`` come from the LLM; the channel is read from the snapshot only.++ A tool argument named like the declaration key must be inert, or a prompt+ could talk the executor into a channel it does not have.+ """+ executor, _approval, _bus = _executor()+ tool = _AskTool()++ result = await executor.execute(+ tool,+ args={"approval_surface": CONVERSATIONAL, "voice_confirm": True},+ config_snapshot={},+ )++ assert result.error is not None+ assert result.error.startswith(APPROVAL_UNAVAILABLE_PREFIX)+ assert result.error != VOICE_CONFIRM_SENTINEL+ assert tool.calls == 0+++async def test_unattended_dead_end_publishes_no_execution() -> None:+ """Nothing ran, so nothing may claim it did."""+ executor, _approval, bus = _executor()+ executed: list[ActionExecuted] = []++ async def _capture(event: ActionExecuted) -> None:+ executed.append(event)++ bus.subscribe(ActionExecuted, _capture)++ await executor.execute(_AskTool(), args={})++ assert executed == []+++async def test_explicit_interactive_declaration_keeps_the_wait() -> None:+ """What the mission broker now passes, checked without a mission_id."""+ executor, approval, _bus = _executor(timeout_s=0.05)+ tool = _AskTool()++ result = await executor.execute(+ tool, args={}, config_snapshot={"approval_surface": INTERACTIVE},+ )++ assert approval.waits == [0.05]+ assert tool.calls == 0+ assert (result.error or "").startswith(APPROVAL_TIMEOUT_PREFIX)diff --git a/tests/unit/safety/test_tool_executor_voice_confirm.py b/tests/unit/safety/test_tool_executor_voice_confirm.pyindex 8c211f307f..f88a89f4c4 100644--- a/tests/unit/safety/test_tool_executor_voice_confirm.py+++ b/tests/unit/safety/test_tool_executor_voice_confirm.py@@ -21,7 +21,11 @@ from jarvis.core.events import ActionApprovalRequired, ActionExecutedfrom jarvis.core.protocols import ExecutionContext, ToolResultfrom jarvis.safety.approval import ApprovalWorkflowfrom jarvis.safety.risk_tier import RiskTierEvaluator-from jarvis.safety.tool_executor import VOICE_CONFIRM_SENTINEL, ToolExecutor+from jarvis.safety.tool_executor import (+ APPROVAL_UNAVAILABLE_PREFIX,+ VOICE_CONFIRM_SENTINEL,+ ToolExecutor,+)class _AskTool:@@ -254,14 +258,22 @@ async def test_cancel_pending_drops_the_action() -> None:@pytest.mark.asyncio-async def test_without_voice_confirm_ask_tier_still_blocks_on_approval() -> None:- """Regression guard: the non-conversational path is unchanged."""+async def test_without_a_channel_ask_tier_fails_fast_instead_of_waiting() -> None:+ """A surface with no approval channel must not wait for one (GT-12).++ This used to assert the opposite — that a bare ``execute`` blocks in+ ``ApprovalWorkflow.wait()``. On a CLI, REST, or workflow call there is+ nobody behind that wait, so it bought 60 seconds of silence and then+ reported a refusal nobody made. Detailed coverage lives in+ ``test_tool_executor_unattended.py``.+ """executor, approval, _bus = _executor()tool = _AskTool()- result = await executor.execute(tool, args={}) # no voice_confirm- assert approval.wait_calls == 1- assert tool.calls == 1- assert result.success is True+ result = await executor.execute(tool, args={}) # no surface declared+ assert approval.wait_calls == 0+ assert tool.calls == 0+ assert result.success is False+ assert (result.error or "").startswith(APPROVAL_UNAVAILABLE_PREFIX)@pytest.mark.asyncio