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
@ feat(screen-context): wire the one-shot screen look into the live voice turn
Ruben Lütke082dc5de1e00
diff --git a/jarvis/brain/router.py b/jarvis/brain/router.pyindex ff75a58be2..c6f8248087 100644--- a/jarvis/brain/router.py+++ b/jarvis/brain/router.py@@ -579,6 +579,35 @@ class RouterBrain:return "en"return "de"+ def _output_locale(self, utterance: str) -> str:+ """The turn's output language, via the ONE resolver (CLAUDE.md §1.3).++ Deliberately NOT ``_detect_utterance_language`` above: that helper is a+ de/en-only ack heuristic with a German default, so a Spanish user would+ be asked a clarifying question in German. Anything Jarvis actually says+ to the user resolves through ``resolve_output_language``, which honours+ the ``brain.reply_language`` pin, conversation stickiness, and every+ supported locale equally.+ """+ try:+ from jarvis.core.config import load_config # noqa: PLC0415+ from jarvis.core.turn_language import ( # noqa: PLC0415+ DEFAULT_LOCALE,+ resolve_output_language,+ )++ cfg = load_config()+ pin = str(getattr(cfg.brain, "reply_language", "") or "")+ stt_language = str(getattr(cfg.stt, "language", "") or "")+ return resolve_output_language(+ pin, stt_language, utterance, default=DEFAULT_LOCALE+ )+ except Exception: # noqa: BLE001 — never fail a turn over a language probe+ log.debug("router: output-locale resolution failed", exc_info=True)+ from jarvis.core.turn_language import DEFAULT_LOCALE # noqa: PLC0415++ return DEFAULT_LOCALE+def _build_ack_emitter(self, utterance: str):"""Construct the async callback that publishes ``AnnouncementRequested``.@@ -647,10 +676,64 @@ class RouterBrain:)dispatcher = self._manager._build_dispatcher(brain)+ images: tuple[ImageBlock, ...] = ()+ screen_note = ""++ # --- Screen Context: the user explicitly asked Jarvis to LOOK --------+ #+ # Runs BEFORE the permanent-vision path and takes precedence over it,+ # because it answers a stricter question with a better answer: it+ # captures the monitor the CURSOR is on (permanent vision follows the+ # foreground window, which is a different screen whenever the user+ # reads one display while typing on another), it redacts secure fields+ # before the pixels leave the process, and it never persists them.+ #+ # It is additive, not a replacement: `should_attach_screenshot` below+ # also fires on on-screen ACTION turns ("click the button"), which are+ # not look-requests but still need an image, so that path stays.+ #+ # An AMBIGUOUS turn ends here with a question instead of a capture —+ # falling through would attach an image while asking whether to look+ # at one. A PRIVACY refusal likewise ends the turn and shuts the path+ # below, because falling through there would photograph the exact+ # window the user's rule protects. A merely TECHNICAL failure (no+ # display, no permission) does NOT end the turn: it returns+ # "unavailable" and the existing path runs, so a headless or+ # unpermitted host behaves exactly as it did before this feature.+ # Any unexpected failure inside returns "none" for the same reason —+ # this block cannot break a voice turn.+ from jarvis.screen_context.turn import screen_context_for_turn++ screen = await screen_context_for_turn(+ utterance, locale=self._output_locale(utterance), bus=self._bus+ )+ if screen.ends_the_turn:+ spoken = screen.question or screen.message or ""+ if spoken:+ log.info(+ "screen_context: turn ended without capture (status=%s)",+ screen.status,+ )+ yield BrainDelta(content=spoken)+ yield BrainDelta(finish_reason="stop")+ return+ elif screen.has_image:+ import base64 as _base64 # noqa: PLC0415++ images = (+ ImageBlock(+ mime=screen.mime,+ data_b64=_base64.b64encode(screen.image or b"").decode("ascii"),+ source_hash=screen.source_hash,+ ),+ )+ screen_note = screen.note+ log.info("screen_context: %s", screen.receipt)+# Permanent vision: inject a fresh screen observation as an ImageBlock# when the provider is available and not paused. Errors are not fatal- # — the text-only fallback keeps the conversation running.- images: tuple[ImageBlock, ...] = ()+ # — the text-only fallback keeps the conversation running. Skipped+ # entirely when Screen Context already supplied an image above.vision_none = self._vision is Nonepaused = (bool(getattr(self._vision, "is_paused", False))@@ -672,7 +755,9 @@ class RouterBrain:from jarvis.brain.vision_gate import should_attach_screenshotif (- self._vision is not None+ not images+ and not screen.blocks_other_screen_paths+ and self._vision is not Noneand not self._vision.is_pausedand should_attach_screenshot(utterance)):@@ -724,7 +809,13 @@ class RouterBrain:)messages: list[BrainMessage] = list(history or [])- messages.append(BrainMessage(role="user", content=utterance, images=images))+ messages.append(+ BrainMessage(+ role="user",+ content=f"{screen_note}\n\n{utterance}" if screen_note else utterance,+ images=images,+ )+ )tools_payload = dispatcher.tools_payload()system_prompt = self._manager._build_system_prompt()@@ -735,12 +826,18 @@ class RouterBrain:# gives the caller a uniform AsyncIterator regardless of whether# a tool call or plain text was produced.ack_emitter = self._build_ack_emitter(utterance)+ # ``turn_context`` rather than prefixing the utterance: the raw+ # utterance is what every downstream gate matches on (cu_gate,+ # spawn_gate, voice-control), and prefixing it with a description+ # full of words like "window" and "screen" would quietly widen+ # those gates. This channel reaches the model without touching them.agg = await dispatcher.dispatch(utterance,images=images,history=history,trace_id=trace_id,ack_emitter=ack_emitter,+ turn_context=screen_note,)# Perceived-latency completion marker. The user opted for an# unconditional "Erledigt." at the end of any turn thatdiff --git a/jarvis/screen_context/service.py b/jarvis/screen_context/service.pyindex b2f0c8646b..31a4d57461 100644--- a/jarvis/screen_context/service.py+++ b/jarvis/screen_context/service.py@@ -110,6 +110,16 @@ class CaptureOutcome:* ``clarify`` — ambiguous. Ask ``question`` and capture nothing.* ``refused`` — capture was not possible or not allowed. Say ``message``.* ``captured`` — ``handle_id`` and ``context`` are set.++ A refusal additionally carries ``reason_kind``, and the difference matters+ more than it looks:++ * ``policy`` — the user's own rules said no (denylist, feature off). A+ caller must NOT quietly fall back to some other way of seeing the screen;+ that would photograph the very window the rule protects.+ * ``technical`` — this machine could not (no display, no permission). A+ caller MAY fall back to whatever it did before this feature existed,+ because nothing was forbidden — it was merely impossible here."""status: CaptureStatus@@ -118,6 +128,7 @@ class CaptureOutcome:handle_id: str | None = Nonequestion: str | None = Nonemessage: str | None = None+ reason_kind: Literal["", "policy", "technical"] = ""@dataclass@@ -237,6 +248,7 @@ class ScreenContextService:return CaptureOutcome(status="refused",verdict=verdict,+ reason_kind="policy",message=("Screen context is switched off. You can turn it back on in ""Settings."@@ -268,7 +280,10 @@ class ScreenContextService:if permission_error:log.info("screen_context: capture refused — %s", permission_error)return CaptureOutcome(- status="refused", verdict=verdict, message=permission_error+ status="refused",+ verdict=verdict,+ reason_kind="technical",+ message=permission_error,)# The cursor is sampled ONCE, here, and threaded through. See@@ -301,6 +316,7 @@ class ScreenContextService:return CaptureOutcome(status="refused",verdict=verdict,+ reason_kind="policy",message=(f"I did not capture the screen: the active window matches "f"your privacy rule '{blocked_by}', so screen context is "@@ -327,7 +343,12 @@ class ScreenContextService:)except CaptureUnavailable as exc:log.info("screen_context: no capture target — %s", exc)- return CaptureOutcome(status="refused", verdict=verdict, message=str(exc))+ return CaptureOutcome(+ status="refused",+ verdict=verdict,+ reason_kind="technical",+ message=str(exc),+ )degradations.extend(target_degradations)# Announce BEFORE the shutter so the indicator is up while there is@@ -350,12 +371,18 @@ class ScreenContextService:)except CaptureUnavailable as exc:log.info("screen_context: capture failed — %s", exc)- return CaptureOutcome(status="refused", verdict=verdict, message=str(exc))+ return CaptureOutcome(+ status="refused",+ verdict=verdict,+ reason_kind="technical",+ message=str(exc),+ )except Exception as exc: # noqa: BLE001 — a port bug must not kill the turnlog.error("screen_context: unexpected capture failure", exc_info=True)return CaptureOutcome(status="refused",verdict=verdict,+ reason_kind="technical",message=f"The screen could not be captured ({exc}).",)diff --git a/jarvis/screen_context/turn.py b/jarvis/screen_context/turn.pynew file mode 100644index 0000000000..50ad208b3b--- /dev/null+++ b/jarvis/screen_context/turn.py@@ -0,0 +1,242 @@+"""Turn integration — the one call a conversation layer makes.++A brain/voice layer should not have to know about intent verdicts, capture+targets, TTL handles or redaction reports. It asks one question — "does this+turn need the screen, and if so, what does the model get?" — and receives a+:class:`TurnScreenContext` with four possible shapes it must handle.++Deliberately **additive**. This does NOT replace ``jarvis.brain.vision_gate``,+which also fires on on-screen ACTION turns ("click the button", "close this+window") so Computer-Use is not blind. Those are a different question: the+vision gate asks "would an image help this turn?", Screen Context asks "did the+user ask me to LOOK?". A turn can be the first without being the second, and+collapsing them would either blind Computer-Use or capture on every click.++Layering: this module returns raw bytes and plain text, never a brain-layer+type. The caller builds whatever image block its provider needs, so+``jarvis.screen_context`` keeps depending on nothing above ``jarvis.core``.+"""+from __future__ import annotations++import logging+from dataclasses import dataclass, field+from typing import Any, Literal++from jarvis.screen_context.models import ScreenContext+from jarvis.screen_context.service import ScreenContextService, settings_from_config++log = logging.getLogger(__name__)++TurnStatus = Literal["none", "clarify", "captured", "refused", "unavailable"]++#: Process-wide service. Built on first use, never at import (AP-26).+_service: ScreenContextService | None = None+++def get_service(*, bus: Any | None = None) -> ScreenContextService:+ """The shared service, built from live config on first use."""+ global _service+ if _service is None:+ from jarvis.core.config import load_config # noqa: PLC0415++ _service = ScreenContextService(+ settings=settings_from_config(load_config()), bus=bus+ )+ return _service+++def reset_service() -> None:+ """Drop the shared service (settings changed, or a test needs a clean one).++ Discards whatever it still holds: a settings change that tightens the+ privacy rules must not leave a capture taken under the old ones in memory.+ """+ global _service+ if _service is not None:+ _service.discard_all()+ _service = None+++@dataclass(frozen=True, slots=True)+class TurnScreenContext:+ """What a conversation turn should do about the screen.++ Five shapes, and a caller must handle all five:++ * ``none`` — no visual request. Continue exactly as before.+ * ``clarify`` — ambiguous. Speak ``question`` and end the turn. Do NOT+ capture, and do NOT fall through to any other screen path: falling+ through would attach an image while asking whether to look at one.+ * ``captured`` — ``image`` and ``note`` are set. Attach both.+ * ``refused`` — the USER's rules said no (denylist, feature off). Speak+ ``message`` and end the turn. A caller must not reach the screen by some+ other route here; that would photograph the very window the rule exists+ to protect.+ * ``unavailable`` — this machine could not (no display, no permission,+ capture error). Nothing was forbidden, so the caller SHOULD continue with+ whatever it did before this feature existed. The reason is logged, and+ the fallback path reports its own failure honestly if it also fails.++ The ``refused`` / ``unavailable`` split is the important one: collapsing+ them either leaks a protected window (treating a privacy rule as a+ technical hiccup) or breaks every look-request on a headless host (treating+ a missing display as a prohibition).+ """++ status: TurnStatus+ image: bytes | None = None+ mime: str = ""+ #: Model-facing preamble: what the image shows, and what was withheld.+ note: str = ""+ #: The visible UI text, already scrubbed.+ text: str = ""+ question: str | None = None+ message: str | None = None+ #: One user-facing line naming what was captured, for the transcript.+ receipt: str = ""+ source_hash: str = ""+ context: ScreenContext | None = field(default=None, repr=False)++ @property+ def has_image(self) -> bool:+ return self.status == "captured" and bool(self.image)++ @property+ def ends_the_turn(self) -> bool:+ """Whether the caller must stop and speak instead of calling the brain."""+ return self.status in ("clarify", "refused")++ @property+ def blocks_other_screen_paths(self) -> bool:+ """Whether any OTHER way of seeing the screen must stay shut this turn.++ True for a privacy refusal and for the clarifying question. False for+ ``unavailable``, which is the whole point of that status.+ """+ return self.status in ("clarify", "refused")+++def _model_note(context: ScreenContext) -> str:+ """The English preamble that rides with the image.++ Three jobs, all of them about not letting the model invent things:++ * name the surface, so it does not claim to see the whole desktop when it+ was handed one monitor;+ * name the app and window, which the picture alone often does not show;+ * declare the redactions, so black rectangles are understood as withheld+ content rather than narrated as user interface.+ """+ target = context.target+ where = (+ f"the '{target.window.title}' window"+ if target.kind.value == "window" and target.window.title+ else f"monitor {target.monitor_name or '?'}"+ )+ lines = [f"Screen capture of {where}, taken just now at the user's request."]++ if target.window.is_known and target.kind.value != "window":+ app = target.window.app_name or "an unknown application"+ title = target.window.title or "untitled"+ lines.append(f"Active application: {app} — window title: {title}.")++ if not context.redactions.is_empty:+ lines.append(+ "Privacy filter applied before you received this: "+ f"{context.redactions.summary()}. Black rectangles are withheld "+ "content, not part of the interface — do not describe or guess them."+ )++ if context.degradations:+ limits = "; ".join(d.message for d in context.degradations)+ lines.append(f"Limitations of this capture: {limits}")++ if context.ui_text:+ lines.append(+ "Visible on-screen text, read from the accessibility layer:\n"+ f"{context.ui_text}"+ )++ return "\n".join(lines)+++async def screen_context_for_turn(+ utterance: str,+ *,+ locale: str,+ bus: Any | None = None,+ service: ScreenContextService | None = None,+) -> TurnScreenContext:+ """Resolve the screen question for one conversation turn.++ ``locale`` must already be resolved via+ ``jarvis.core.turn_language.resolve_output_language`` — this function never+ derives a language, so a clarifying question cannot flip the conversation's+ language mid-session (CLAUDE.md §1.3).++ Never raises. Any unexpected failure degrades to ``none``, which means the+ caller behaves exactly as it did before this feature existed — a bug in+ Screen Context must not be able to break a voice turn.+ """+ try:+ svc = service or get_service(bus=bus)+ outcome = await svc.capture_for_turn(utterance, locale=locale)++ if outcome.status == "not_requested":+ return TurnScreenContext(status="none")++ if outcome.status == "clarify":+ return TurnScreenContext(+ status="clarify", question=outcome.question or ""+ )++ if outcome.status == "refused":+ if outcome.reason_kind == "technical":+ # Not forbidden — impossible here. Log it and let the caller+ # carry on with whatever it did before; ending the turn would+ # break every look-request on a headless or unpermitted host.+ log.info(+ "screen_context: capture unavailable on this machine (%s) "+ "— the turn continues on the existing path",+ outcome.message,+ )+ return TurnScreenContext(+ status="unavailable", message=outcome.message or ""+ )+ return TurnScreenContext(status="refused", message=outcome.message or "")++ context = outcome.context+ if context is None: # defensive: 'captured' always carries one+ return TurnScreenContext(status="none")++ # Consume immediately: this turn IS the single use. Leaving the handle+ # parked would keep the pixels alive for the whole TTL for no reason.+ if outcome.handle_id:+ svc.consume(outcome.handle_id)++ return TurnScreenContext(+ status="captured",+ image=context.image,+ mime=context.mime,+ note=_model_note(context),+ text=context.ui_text,+ receipt=context.describe(),+ source_hash=f"{context.captured_at_ns:x}",+ context=context,+ )+ except Exception: # noqa: BLE001 — a bug here must never kill a voice turn+ log.error(+ "screen_context: turn integration failed — the turn continues "+ "without screen context",+ exc_info=True,+ )+ return TurnScreenContext(status="none")+++__all__ = [+ "TurnScreenContext",+ "TurnStatus",+ "get_service",+ "reset_service",+ "screen_context_for_turn",+]diff --git a/tests/integration/test_router_permanent_vision.py b/tests/integration/test_router_permanent_vision.pyindex 5c8978dfb4..201602ec6b 100644--- a/tests/integration/test_router_permanent_vision.py+++ b/tests/integration/test_router_permanent_vision.py@@ -28,8 +28,30 @@ import pytestpytestmark = pytest.mark.integration[email protected](autouse=True)+def _no_screen_context(monkeypatch: pytest.MonkeyPatch):+ """Keep Screen Context out of this file, deterministically.++ ``RouterBrain.handle`` consults ``jarvis.screen_context`` before the+ permanent-vision path and takes precedence on an explicit look-request,+ which some utterances here are. Left alone, these tests would pass or fail+ depending on whether the host running them has a screen — captured on a dev+ box, unavailable in headless CI.++ These cases pin the permanent-vision path itself; Screen Context precedence+ is covered by ``tests/unit/brain/test_router_screen_context.py``.+ """+ from jarvis.screen_context.turn import TurnScreenContext++ async def _none(*_args: Any, **_kwargs: Any) -> TurnScreenContext:+ return TurnScreenContext(status="none")++ monkeypatch.setattr("jarvis.screen_context.turn.screen_context_for_turn", _none)+ return None++# ======================================================================-# Gemeinsame Fakes+# Shared fakes# ======================================================================diff --git a/tests/unit/brain/test_router_screen_context.py b/tests/unit/brain/test_router_screen_context.pynew file mode 100644index 0000000000..d94f5d6dd5--- /dev/null+++ b/tests/unit/brain/test_router_screen_context.py@@ -0,0 +1,259 @@+"""RouterBrain × Screen Context: precedence, refusal, and the fallback rule.++Pins the wiring added when Screen Context landed. The interesting cases are the+ones where the two screen paths meet:++* an explicit look-request must be served by Screen Context (cursor monitor,+ redacted, non-persistent) rather than by permanent vision (foreground window,+ unfiltered, written to the blob store);+* an ambiguous turn must ask AND leave permanent vision shut, or Jarvis attaches+ an image while asking whether it may look at one;+* a privacy refusal must leave permanent vision shut, or the fallback+ photographs the exact window the rule protects;+* a technical failure must NOT shut it, or every look-request on a headless host+ turns into a refusal instead of an answer.+"""+from __future__ import annotations++from collections.abc import AsyncIterator+from typing import Any+from uuid import UUID++import pytest++from jarvis.brain.router import RouterBrain+from jarvis.brain.streaming import StreamingAggregate+from jarvis.core.bus import EventBus+from jarvis.core.config import BrainProviderConfig, BrainTierConfig, JarvisConfig+from jarvis.core.protocols import (+ BrainDelta,+ BrainRequest,+ ImageBlock,+ Observation,+ ToolResult,+)+from jarvis.screen_context.turn import TurnScreenContext+++class _FakeBrain:+ name = "fake"+ context_window = 8192+ supports_tools = True+ supports_vision = True+ model = "fake-model"++ async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:+ yield BrainDelta(content="ok")+ yield BrainDelta(finish_reason="stop")+++class _RecordingDispatcher:+ def __init__(self) -> None:+ self.calls: list[dict[str, Any]] = []++ def tools_payload(self) -> list[dict[str, Any]]:+ return []++ async def dispatch(+ self,+ user_text: str,+ *,+ images: tuple[ImageBlock, ...] = (),+ history: Any = None,+ trace_id: UUID | None = None,+ ack_emitter: Any = None,+ turn_context: str = "",+ **_kwargs: Any,+ ) -> StreamingAggregate:+ self.calls.append(+ {"user_text": user_text, "images": images, "turn_context": turn_context}+ )+ agg = StreamingAggregate()+ agg.text = "ok"+ agg.finish_reason = "stop"+ return agg+++class _FakeTool:+ name = "bash"+ description = "Run shell commands."+ risk_tier = "monitor"+ schema: dict[str, Any] = {"type": "object", "properties": {}}++ async def execute(self, args: dict[str, Any], ctx: Any) -> ToolResult:+ return ToolResult(success=True, output="ok")+++class _FakeVisionProvider:+ """Stands in for permanent vision; records whether it was consulted."""++ is_paused = False++ def __init__(self) -> None:+ self.consulted = 0++ async def current(self) -> Observation:+ self.consulted += 1+ raise RuntimeError("permanent vision must not be reached in these cases")+++def _build_router_config() -> JarvisConfig:+ cfg = JarvisConfig()+ cfg.brain.providers["fake"] = BrainProviderConfig(+ model="fake-model", deep_model="fake-model"+ )+ cfg.brain.router = BrainTierConfig(+ provider="fake",+ model="fake-model",+ fallback_provider="fake",+ fallback_model="fake-model",+ )+ cfg.brain.worker = BrainTierConfig(provider="fake", model="fake-model")+ return cfg+++class _NoopToolExecutor:+ async def execute(self, tool: Any, args: dict[str, Any], **_: Any) -> ToolResult:+ return await tool.execute(args, ctx=None)+++def _build_router(vision_provider: Any = None) -> tuple[RouterBrain, _RecordingDispatcher]:+ router = RouterBrain(+ _build_router_config(),+ EventBus(),+ tools={"bash": _FakeTool()},+ tool_executor=_NoopToolExecutor(),+ vision_provider=vision_provider,+ )+ router.manager._brain_cache[("fake", "fake-model")] = _FakeBrain()+ recorder = _RecordingDispatcher()+ router.manager._build_dispatcher = lambda _brain: recorder # type: ignore[method-assign]+ return router, recorder+++def _patch_screen(monkeypatch: pytest.MonkeyPatch, result: TurnScreenContext) -> None:+ async def _fake(*_args: Any, **_kwargs: Any) -> TurnScreenContext:+ return result++ monkeypatch.setattr("jarvis.screen_context.turn.screen_context_for_turn", _fake)+++async def test_captured_context_is_attached_with_its_note(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _patch_screen(+ monkeypatch,+ TurnScreenContext(+ status="captured",+ image=b"jpeg",+ mime="image/jpeg",+ note="Screen capture of monitor 2.",+ receipt="captured monitor 2",+ source_hash="abc",+ ),+ )+ router, recorder = _build_router()++ [d async for d in router.handle("look at this")]++ call = recorder.calls[0]+ assert len(call["images"]) == 1+ assert call["images"][0].mime == "image/jpeg"+ assert call["turn_context"] == "Screen capture of monitor 2."+ assert call["user_text"] == "look at this", (+ "the raw utterance must reach the gates unchanged — the note travels "+ "in turn_context precisely so it cannot widen cu_gate/spawn_gate"+ )+++async def test_screen_context_wins_over_permanent_vision(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The better path serves the request; the old one is not also consulted."""+ _patch_screen(+ monkeypatch,+ TurnScreenContext(+ status="captured", image=b"jpeg", mime="image/jpeg", note="note"+ ),+ )+ provider = _FakeVisionProvider()+ router, recorder = _build_router(vision_provider=provider)++ [d async for d in router.handle("look at this")]++ assert provider.consulted == 0+ assert len(recorder.calls[0]["images"]) == 1+++async def test_ambiguous_turn_asks_and_never_calls_the_brain(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _patch_screen(+ monkeypatch,+ TurnScreenContext(status="clarify", question="Shall I take a look?"),+ )+ provider = _FakeVisionProvider()+ router, recorder = _build_router(vision_provider=provider)++ deltas = [d async for d in router.handle("what is that?")]++ spoken = "".join(d.content or "" for d in deltas)+ assert spoken == "Shall I take a look?"+ assert recorder.calls == [], "an ambiguous turn must not reach the brain"+ assert provider.consulted == 0, (+ "attaching an image while asking whether to look is the exact outcome "+ "the clarify path exists to prevent"+ )+ assert deltas[-1].finish_reason == "stop"+++async def test_privacy_refusal_is_spoken_and_shuts_the_fallback(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _patch_screen(+ monkeypatch,+ TurnScreenContext(+ status="refused", message="Your privacy rule blocked that window."+ ),+ )+ provider = _FakeVisionProvider()+ router, recorder = _build_router(vision_provider=provider)++ deltas = [d async for d in router.handle("look at this")]++ assert "privacy rule" in "".join(d.content or "" for d in deltas)+ assert recorder.calls == []+ assert provider.consulted == 0, (+ "falling back here would capture the very window the rule protects"+ )+++async def test_technical_failure_falls_through_to_the_old_path(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Headless / unpermitted hosts must answer normally, not refuse."""+ _patch_screen(+ monkeypatch,+ TurnScreenContext(status="unavailable", message="No display available."),+ )+ provider = _FakeVisionProvider()+ router, recorder = _build_router(vision_provider=provider)++ deltas = [d async for d in router.handle("look at this")]++ assert recorder.calls, "the turn must still reach the brain"+ assert provider.consulted == 1, "the existing vision path must be tried"+ assert "No display" not in "".join(d.content or "" for d in deltas), (+ "a technical limitation is logged, not spoken as a refusal"+ )+++async def test_a_plain_turn_is_untouched(monkeypatch: pytest.MonkeyPatch) -> None:+ _patch_screen(monkeypatch, TurnScreenContext(status="none"))+ router, recorder = _build_router()++ [d async for d in router.handle("what did we discuss?")]++ call = recorder.calls[0]+ assert call["images"] == ()+ assert call["turn_context"] == ""diff --git a/tests/unit/brain/test_router_vision.py b/tests/unit/brain/test_router_vision.pyindex 7e0e740582..742a7b3534 100644--- a/tests/unit/brain/test_router_vision.py+++ b/tests/unit/brain/test_router_vision.py@@ -76,6 +76,33 @@ class _FakeBrain:yield BrainDelta(finish_reason="stop")[email protected](autouse=True)+def _no_screen_context(monkeypatch: pytest.MonkeyPatch):+ """Keep Screen Context out of this file, deterministically.++ ``RouterBrain.handle`` consults ``jarvis.screen_context`` before the+ permanent-vision path and takes precedence when the user explicitly asked+ Jarvis to LOOK — which several of the utterances in this file do. Without+ this fixture the outcome would depend on whether the machine running the+ tests has a screen: captured on a dev box, unavailable in headless CI.+ A test that passes or fails based on the host's hardware is worse than no+ test.++ These cases exist to pin the permanent-vision path itself, so Screen+ Context is neutralised here. Its own precedence is covered by+ ``test_router_screen_context.py``.+ """+ from jarvis.screen_context.turn import TurnScreenContext++ async def _none(*_args: Any, **_kwargs: Any) -> TurnScreenContext:+ return TurnScreenContext(status="none")++ monkeypatch.setattr(+ "jarvis.screen_context.turn.screen_context_for_turn", _none+ )+ return None++class _NoopToolExecutor:async def execute(self, tool: Any, args: dict[str, Any], **_: Any) -> ToolResult:return await tool.execute(args, ctx=None) # type: ignore[arg-type]diff --git a/tests/unit/screen_context/test_turn.py b/tests/unit/screen_context/test_turn.pynew file mode 100644index 0000000000..fc32dffaa9--- /dev/null+++ b/tests/unit/screen_context/test_turn.py@@ -0,0 +1,212 @@+"""Turn integration — the contract a conversation layer relies on.++The refused/unavailable split gets the most attention here. Collapsing it fails+in one of two ways, and both are the kind that ship quietly:++* treating a privacy refusal as technical lets the caller fall back to another+ screen path and photograph the protected window;+* treating a missing display as a prohibition ends every look-request on a+ headless host with a refusal instead of a normal answer.+"""+from __future__ import annotations++from jarvis.screen_context.models import (+ CaptureTarget,+ Degradation,+ DegradationCode,+ IntentVerdict,+ RedactionHit,+ RedactionReport,+ RedactionRule,+ ScreenContext,+ TargetKind,+ TargetReason,+ VisualIntent,+ WindowFacts,+)+from jarvis.screen_context.service import CaptureOutcome+from jarvis.screen_context.turn import screen_context_for_turn+++class FakeService:+ """Returns a scripted outcome and records what it was consumed for."""++ def __init__(self, outcome: CaptureOutcome) -> None:+ self._outcome = outcome+ self.consumed: list[str] = []++ async def capture_for_turn(self, text, *, locale="", force=False):+ return self._outcome++ def consume(self, handle_id):+ self.consumed.append(handle_id)+ return None+++def make_context(**overrides) -> ScreenContext:+ defaults = {+ "image": b"jpeg-bytes",+ "mime": "image/jpeg",+ "size": (1920, 1080),+ "target": CaptureTarget(+ kind=TargetKind.MONITOR,+ bbox=(0, 0, 1920, 1080),+ reason=TargetReason.CURSOR_MONITOR,+ monitor_name="2",+ window=WindowFacts(app_name="editor", title="notes.md"),+ ),+ "ui_text": "Build failed: 3 errors",+ "ui_text_source": "accessibility",+ "captured_at_ns": 123,+ }+ defaults.update(overrides)+ return ScreenContext(**defaults)+++def outcome(status, **kwargs) -> CaptureOutcome:+ return CaptureOutcome(+ status=status, verdict=IntentVerdict(intent=VisualIntent.SCREEN), **kwargs+ )+++async def test_no_visual_intent_leaves_the_turn_alone() -> None:+ service = FakeService(outcome("not_requested"))+ result = await screen_context_for_turn("hello", locale="en", service=service)++ assert result.status == "none"+ assert not result.ends_the_turn+ assert not result.blocks_other_screen_paths+++async def test_ambiguous_ends_the_turn_and_shuts_other_paths() -> None:+ service = FakeService(outcome("clarify", question="Shall I look?"))+ result = await screen_context_for_turn("what is that?", locale="en", service=service)++ assert result.status == "clarify"+ assert result.question == "Shall I look?"+ assert result.ends_the_turn+ assert result.blocks_other_screen_paths, (+ "asking whether to look while another path attaches an image is the "+ "one outcome this must never allow"+ )+++async def test_privacy_refusal_ends_the_turn_and_shuts_other_paths() -> None:+ service = FakeService(+ outcome("refused", reason_kind="policy", message="Your privacy rule blocked it.")+ )+ result = await screen_context_for_turn("look at this", locale="en", service=service)++ assert result.status == "refused"+ assert result.ends_the_turn+ assert result.blocks_other_screen_paths, (+ "falling back here would capture the very window the rule protects"+ )+++async def test_technical_failure_lets_the_turn_continue() -> None:+ """A headless host must answer normally, not refuse every look-request."""+ service = FakeService(+ outcome("refused", reason_kind="technical", message="No display available.")+ )+ result = await screen_context_for_turn("look at this", locale="en", service=service)++ assert result.status == "unavailable"+ assert not result.ends_the_turn+ assert not result.blocks_other_screen_paths+ assert result.message, "the reason must survive for the log"+++async def test_captured_carries_image_and_note() -> None:+ service = FakeService(+ outcome("captured", context=make_context(), handle_id="abc123")+ )+ result = await screen_context_for_turn("look at this", locale="en", service=service)++ assert result.status == "captured"+ assert result.has_image+ assert result.image == b"jpeg-bytes"+ assert result.mime == "image/jpeg"+ assert "monitor 2" in result.note+ assert "editor" in result.note+ assert "Build failed" in result.note+++async def test_the_capture_is_consumed_by_the_turn() -> None:+ """This turn IS the single use; parking it for the TTL helps nobody."""+ service = FakeService(+ outcome("captured", context=make_context(), handle_id="abc123")+ )+ await screen_context_for_turn("look at this", locale="en", service=service)++ assert service.consumed == ["abc123"]+++async def test_redactions_are_declared_to_the_model() -> None:+ """Unexplained black boxes get narrated as user interface."""+ context = make_context(+ redactions=RedactionReport(+ hits=(+ RedactionHit(+ rule=RedactionRule.PASSWORD_FIELD,+ label="password_field",+ region=(0, 0, 10, 10),+ ),+ )+ )+ )+ service = FakeService(outcome("captured", context=context, handle_id="h"))++ result = await screen_context_for_turn("look at this", locale="en", service=service)++ assert "withheld" in result.note.lower()+ assert "do not describe" in result.note.lower()+++async def test_degradations_are_declared_to_the_model() -> None:+ context = make_context(+ degradations=(+ Degradation(+ code=DegradationCode.NO_UI_TEXT,+ message="On-screen text could not be read on this system.",+ ),+ )+ )+ service = FakeService(outcome("captured", context=context, handle_id="h"))++ result = await screen_context_for_turn("look at this", locale="en", service=service)++ assert "Limitations" in result.note+ assert "could not be read" in result.note+++async def test_window_scope_names_the_window_not_the_monitor() -> None:+ context = make_context(+ target=CaptureTarget(+ kind=TargetKind.WINDOW,+ bbox=(0, 0, 800, 600),+ reason=TargetReason.FOCUSED_WINDOW,+ monitor_name="1",+ window=WindowFacts(app_name="editor", title="report.pdf"),+ )+ )+ service = FakeService(outcome("captured", context=context, handle_id="h"))++ result = await screen_context_for_turn("look at this window", locale="en", service=service)++ assert "report.pdf" in result.note+++async def test_a_broken_service_never_breaks_the_turn() -> None:+ """A bug in Screen Context must degrade to 'no screen context', not raise."""++ class ExplodingService:+ async def capture_for_turn(self, text, *, locale="", force=False):+ raise RuntimeError("boom")++ result = await screen_context_for_turn(+ "look at this", locale="en", service=ExplodingService()+ )++ assert result.status == "none"+ assert not result.ends_the_turn