Skip to content

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

fix: separate screen observation from desktop control

Ruben Lütke5c38f307da7d
diff --git a/jarvis/audio/chime.py b/jarvis/audio/chime.py
index dc5506eef9..b4250fa732 100644
--- a/jarvis/audio/chime.py
+++ b/jarvis/audio/chime.py
@@ -85,8 +85,41 @@ def generate_ready_pcm(
return (np.clip(wave, -1.0, 1.0) * 32767.0).astype(np.int16).tobytes()
+def generate_screen_capture_pcm(
+ sample_rate: int = 24_000,
+ amplitude: float = 0.42,
+) -> bytes:
+ """Generate an original mechanical-camera shutter cue.
+
+ Two short deterministic noise transients form the shutter blades, with a
+ quiet resonant body underneath. The sound is synthesized in memory so it
+ is portable and carries no third-party recording or licensing baggage.
+ """
+ duration_s = 0.16
+ n = int(duration_s * sample_rate)
+ t = np.arange(n, dtype=np.float32) / float(sample_rate)
+ rng = np.random.default_rng(0x5C4E_454E)
+ noise = rng.uniform(-1.0, 1.0, n).astype(np.float32)
+
+ wave = np.zeros(n, dtype=np.float32)
+ for onset, strength, decay in ((0.0, 1.0, 150.0), (0.052, 0.78, 115.0)):
+ local_t = np.maximum(t - onset, 0.0)
+ active = (t >= onset).astype(np.float32)
+ transient = noise * np.exp(-local_t * decay) * active
+ resonance = np.sin(2.0 * np.pi * 1850.0 * local_t) * np.exp(
+ -local_t * (decay * 0.62)
+ ) * active
+ wave += strength * (0.78 * transient + 0.22 * resonance)
+
+ # A short fade avoids a digital edge while preserving the crisp first hit.
+ fade_out = np.minimum((duration_s - t) * 180.0, 1.0)
+ wave *= np.clip(fade_out, 0.0, 1.0) * amplitude
+ return (np.clip(wave, -1.0, 1.0) * 32767.0).astype(np.int16).tobytes()
+
+
# Pre-generated at import time — loaded once by the pipeline
CHIME_PCM: bytes = generate_chime_pcm()
CHIME_SAMPLE_RATE: int = 24_000
DISCONNECT_PCM: bytes = generate_disconnect_pcm()
READY_PCM: bytes = generate_ready_pcm()
+SCREEN_CAPTURE_PCM: bytes = generate_screen_capture_pcm()
diff --git a/jarvis/audio/effects.py b/jarvis/audio/effects.py
new file mode 100644
index 0000000000..97fa5c21b9
--- /dev/null
+++ b/jarvis/audio/effects.py
@@ -0,0 +1,130 @@
+"""Process-wide, best-effort playback for short product sound effects.
+
+Attaching this service imports no native audio backend and opens no device. The
+first audible event reuses the SpeechPipeline player when one exists, or lazily
+creates one standalone player for a chat-only desktop. Headless hosts log and
+continue without audio.
+"""
+from __future__ import annotations
+
+import asyncio
+import logging
+import weakref
+from typing import Any
+
+from jarvis.audio.chime import CHIME_SAMPLE_RATE, SCREEN_CAPTURE_PCM
+from jarvis.core.events import ScreenCaptureGrabbed
+
+log = logging.getLogger(__name__)
+
+_PLAYBACK_TIMEOUT_S = 1.0
+
+
+class AudioEffectsService:
+ """Own one serialized capture cue across voice and chat surfaces."""
+
+ def __init__(self) -> None:
+ self._attached_buses: weakref.WeakSet[Any] = weakref.WeakSet()
+ self._shared_player_ref: weakref.ReferenceType[Any] | None = None
+ self._owned_player: Any | None = None
+ self._capture_task: asyncio.Task[None] | None = None
+
+ def attach(self, bus: Any) -> None:
+ """Subscribe once to a bus without initializing audio."""
+ if not hasattr(bus, "subscribe") or bus in self._attached_buses:
+ return
+ bus.subscribe(ScreenCaptureGrabbed, self._on_screen_capture_grabbed)
+ self._attached_buses.add(bus)
+
+ def bind_player(self, player: Any) -> None:
+ """Prefer the SpeechPipeline's shared, lock-serialized player."""
+ try:
+ self._shared_player_ref = weakref.ref(player)
+ except TypeError:
+ # Extension-backed player objects may not support weak references.
+ self._shared_player_ref = lambda: player # type: ignore[assignment]
+
+ async def _on_screen_capture_grabbed(
+ self, _event: ScreenCaptureGrabbed
+ ) -> None:
+ """Schedule and return; EventBus publication must never wait on audio."""
+ current = self._capture_task
+ if current is not None and not current.done():
+ return
+ task = asyncio.create_task(self._play_capture(), name="screen-capture-cue")
+ self._capture_task = task
+
+ def _clear(done: asyncio.Task[None]) -> None:
+ if self._capture_task is done:
+ self._capture_task = None
+
+ task.add_done_callback(_clear)
+
+ async def _play_capture(self) -> None:
+ try:
+ config = await asyncio.to_thread(self._load_config)
+ if not bool(getattr(getattr(config, "ui", None), "sound_effects", True)):
+ return
+ player = self._bound_player()
+ if player is None:
+ player = await asyncio.to_thread(self._make_player, config)
+ self._owned_player = player
+ await asyncio.wait_for(
+ player.play_pcm(SCREEN_CAPTURE_PCM, sample_rate=CHIME_SAMPLE_RATE),
+ timeout=_PLAYBACK_TIMEOUT_S,
+ )
+ except TimeoutError:
+ log.warning("Screen capture cue timed out and was safely aborted.")
+ except Exception as exc: # noqa: BLE001 - headless/no-audio is supported
+ log.info("Screen capture cue unavailable; continuing without audio (%s).", exc)
+
+ def _bound_player(self) -> Any | None:
+ if self._shared_player_ref is not None:
+ player = self._shared_player_ref()
+ if player is not None:
+ return player
+ return self._owned_player
+
+ @staticmethod
+ def _load_config() -> Any:
+ from jarvis.core.config import load_config # noqa: PLC0415
+
+ return load_config()
+
+ @staticmethod
+ def _make_player(config: Any) -> Any:
+ from jarvis.audio.player import AudioPlayer # noqa: PLC0415
+
+ audio = getattr(config, "audio", None)
+ tts = getattr(config, "tts", None)
+ return AudioPlayer(
+ device=getattr(audio, "output_device", None),
+ volume=getattr(tts, "volume", 1.0),
+ device_priority=tuple(
+ getattr(audio, "output_device_priority", None) or ()
+ ),
+ )
+
+
+_SERVICE = AudioEffectsService()
+
+
+def attach_audio_effects(bus: Any) -> None:
+ _SERVICE.attach(bus)
+
+
+def bind_shared_audio_player(player: Any) -> None:
+ _SERVICE.bind_player(player)
+
+
+def get_audio_effects_service() -> AudioEffectsService:
+ """Return the singleton for lifecycle integration and focused tests."""
+ return _SERVICE
+
+
+__all__ = [
+ "AudioEffectsService",
+ "attach_audio_effects",
+ "bind_shared_audio_player",
+ "get_audio_effects_service",
+]
diff --git a/jarvis/audio/player.py b/jarvis/audio/player.py
index d369e4d196..6d81960099 100644
--- a/jarvis/audio/player.py
+++ b/jarvis/audio/player.py
@@ -50,6 +50,7 @@ TTS_SAMPLE_RATE = 24_000 # Gemini 3.1 Flash TTS output rate
TTS_FIRST_WRITE_BUFFER_MS = 40
TTS_WRITE_BUFFER_MS = 120
_MAX_REPORTED_OUTPUT_LATENCY_S = 5.0
+_ONE_SHOT_CANCEL_JOIN_TIMEOUT_S = 0.5
# How much audio the OUTPUT DEVICE is asked to hold (PortAudio's ``latency``).
#
@@ -503,6 +504,11 @@ class AudioPlayer:
# from a running event loop. stop() deliberately stays outside the
# lock so barge-in can preempt a held playback.
self._play_lock: asyncio.Lock | None = None
+ # A cancelled ``to_thread`` worker that ignored PortAudio abort keeps
+ # this player fail-closed. No later producer may open a second native
+ # stream until that exact worker exits (AP-24-style native isolation).
+ self._poisoned_worker: asyncio.Task[None] | None = None
+ self._unclean_stream: sd.OutputStream | None = None
# Persistent OutputStream across play_chunks() calls. The streaming-
# TTS pipeline calls play_chunks() once per sentence; without a
# persistent stream every sentence boundary triggered a fresh
@@ -571,6 +577,33 @@ class AudioPlayer:
self._play_lock = asyncio.Lock()
return self._play_lock
+ def _native_playback_poisoned(self) -> bool:
+ worker = getattr(self, "_poisoned_worker", None)
+ return (
+ (worker is not None and not worker.done())
+ or getattr(self, "_unclean_stream", None) is not None
+ )
+
+ def _mark_native_playback_poisoned(self, worker: asyncio.Task[None]) -> None:
+ self._poisoned_worker = worker
+
+ def _recover(done: asyncio.Task[None]) -> None:
+ try:
+ done.exception()
+ except asyncio.CancelledError:
+ pass
+ if getattr(self, "_poisoned_worker", None) is done:
+ self._poisoned_worker = None
+ if getattr(self, "_unclean_stream", None) is None:
+ log.info("Native one-shot audio worker exited; playback recovered.")
+ else:
+ log.error(
+ "Native audio worker exited but its stream did not close; "
+ "this player remains fail-closed."
+ )
+
+ worker.add_done_callback(_recover)
+
def _get_stream_state_lock(self) -> threading.Lock:
lock = getattr(self, "_stream_state_lock", None)
if lock is None:
@@ -724,20 +757,118 @@ class AudioPlayer:
stream produces no clicks. For streaming TTS playback see
``play_chunks``, which keeps a persistent stream open.
"""
+ if self._native_playback_poisoned():
+ log.error("One-shot playback skipped: native audio worker is still wedged.")
+ return
self._log_device_once()
rate = sample_rate or self._sample_rate
pcm = _apply_edge_fades(pcm, rate)
async with self._get_play_lock():
- await asyncio.to_thread(self._play_blob, pcm, rate)
+ if self._native_playback_poisoned():
+ log.error(
+ "One-shot playback skipped after lock wait: native audio "
+ "worker is still wedged."
+ )
+ return
+ playback_generation = getattr(self, "_playback_generation", 0)
+ worker = asyncio.create_task(
+ asyncio.to_thread(
+ self._play_blob,
+ pcm,
+ rate,
+ playback_generation,
+ )
+ )
+ try:
+ await asyncio.shield(worker)
+ except asyncio.CancelledError:
+ # A timeout/caller cancellation cannot stop ``to_thread``.
+ # Abort the registered native stream and JOIN the worker while
+ # still holding the async playback lock; otherwise a later TTS
+ # call could open a second PortAudio stream beside the orphan.
+ self.abort_active()
+ # Mark BEFORE awaiting cleanup: a second Task.cancel() may
+ # interrupt any await, but it must never reopen the overlap race.
+ self._mark_native_playback_poisoned(worker)
+ try:
+ await asyncio.wait_for(
+ asyncio.shield(worker),
+ timeout=_ONE_SHOT_CANCEL_JOIN_TIMEOUT_S,
+ )
+ except TimeoutError:
+ log.error(
+ "Native one-shot audio worker ignored abort for %.1fs; "
+ "this player is fail-closed until that worker exits.",
+ _ONE_SHOT_CANCEL_JOIN_TIMEOUT_S,
+ )
+ except Exception as exc: # noqa: BLE001 - preserve cancellation
+ log.debug("Cancelled one-shot playback unwound (%s).", exc)
+ raise
+ except _PlaybackSuperseded: # stop() won; its generation owns cleanup
+ return
- def _play_blob(self, pcm: bytes, source_rate: int) -> None:
- """Sync: open stream, write blob, close stream."""
+ def _play_blob(
+ self, pcm: bytes, source_rate: int, playback_generation: int
+ ) -> None:
+ """Sync: open, register, write, and close one cancellation-safe stream."""
arr = np.frombuffer(pcm, dtype=np.int16)
+ state_lock = self._get_stream_state_lock()
+ with state_lock:
+ if getattr(self, "_playback_generation", 0) != playback_generation:
+ raise _PlaybackSuperseded
+ # ``play_chunks`` intentionally keeps its stream open between
+ # sentences. The async playback lock guarantees it is idle here;
+ # retire it before opening the one-shot stream so two native
+ # outputs never coexist.
+ old_stream = self._active_stream
+ self._active_stream = None
+ self._active_source_rate = None
+ self._active_device_rate = None
+ if old_stream is not None:
+ if self._close_output_stream(old_stream) is False:
+ with state_lock:
+ self._unclean_stream = old_stream
+ raise _PlaybackSuperseded
+
stream, device_rate = self._open_output_stream(source_rate)
+ with state_lock:
+ superseded = (
+ getattr(self, "_playback_generation", 0) != playback_generation
+ )
+ if not superseded:
+ self._active_stream = stream
+ self._active_source_rate = source_rate
+ self._active_device_rate = device_rate
+ if superseded:
+ if self._close_output_stream(stream) is False:
+ with state_lock:
+ self._unclean_stream = stream
+ raise _PlaybackSuperseded
try:
- self._write_samples(stream, arr, source_rate, device_rate)
+ self._write_samples(
+ stream,
+ arr,
+ source_rate,
+ device_rate,
+ playback_generation=playback_generation,
+ )
finally:
- self._close_output_stream(stream)
+ should_close = False
+ with state_lock:
+ if self._active_stream is stream:
+ self._active_stream = None
+ self._active_source_rate = None
+ self._active_device_rate = None
+ should_close = True
+ # ``abort_active`` already closes a cancelled stream. Avoid a
+ # second native close while still joining the worker deterministically.
+ if should_close:
+ closed = self._close_output_stream(stream)
+ with state_lock:
+ if closed is not False and getattr(self, "_unclean_stream", None) is stream:
+ self._unclean_stream = None
+ elif closed is False:
+ self._unclean_stream = stream
def _open_output_stream(self, source_rate: int) -> tuple[sd.OutputStream, int]:
"""Open a persistent ``sd.OutputStream`` (float32 stereo or mono).
@@ -977,7 +1108,7 @@ class AudioPlayer:
out.shape[0] / device_rate,
)
- def _close_output_stream(self, stream: sd.OutputStream) -> None:
+ def _close_output_stream(self, stream: sd.OutputStream) -> bool:
"""Flush and stop: ``stream.stop()`` blocks until the buffer is empty."""
try:
stream.stop()
@@ -987,6 +1118,8 @@ class AudioPlayer:
stream.close()
except Exception: # noqa: BLE001
log.debug("Output stream close failed", exc_info=True)
+ return False
+ return True
async def play_chunks(
self,
@@ -1027,6 +1160,9 @@ class AudioPlayer:
No edge fades on chunks: the stream stays open and chunks are
appended seamlessly → no discontinuity, no clicks.
"""
+ if self._native_playback_poisoned():
+ log.error("Streaming playback skipped: native audio worker is still wedged.")
+ return False
self._log_device_once()
stream_state_lock = self._get_stream_state_lock()
with stream_state_lock:
@@ -1079,6 +1215,12 @@ class AudioPlayer:
yield _c
async with self._get_play_lock():
+ if self._native_playback_poisoned():
+ log.error(
+ "Streaming playback skipped after lock wait: native audio "
+ "worker is still wedged."
+ )
+ return False
# Staleness gate: re-check at the last moment before any audio is
# written. A preamble whose synthesis / lock-wait was overtaken by
# the main answer is dropped here rather than queued behind it.
@@ -1314,8 +1456,14 @@ class AudioPlayer:
log.debug("abort_active: stream.abort() failed: %s", exc)
try:
stream.close()
- except Exception: # noqa: BLE001, S110
- pass
+ except Exception as exc: # noqa: BLE001
+ log.warning("abort_active: stream.close() failed: %s", exc)
+ # Preserve ownership so the worker's ``finally`` retries the
+ # close after the blocked write unwinds. Until that succeeds,
+ # poison prevents every producer from opening another stream.
+ with self._get_stream_state_lock():
+ self._active_stream = stream
+ self._unclean_stream = stream
def stop(self) -> None:
"""Abort ongoing playback (e.g. for barge-in).
diff --git a/jarvis/brain/cu_gate.py b/jarvis/brain/cu_gate.py
index 6cf0523521..02b3ccc81d 100644
--- a/jarvis/brain/cu_gate.py
+++ b/jarvis/brain/cu_gate.py
@@ -115,6 +115,7 @@ _DESKTOP_VEHICLE_RE: re.Pattern[str] = re.compile(
r"\bopen(?:s|ed|ing)?\b|\blaunch\w*\b|\bclick\w*\b|\bdouble-?click\w*\b|\btap\b"
r"|\bscroll\w*\b|\bdrag\w*\b|\bhover\b|\bpress\w*\b|\bpaste\b"
r"|\bminimi[sz]e\b|\bmaximi[sz]e\b|\bnavigate\b|\bbrowse\b"
+ r"|\brefresh\w*\b|\breload\w*\b"
r"|\blog\s?in\b|\bsign\s?in\b|\bgo\s+to\b"
r"|(?<!what )(?<!which )(?<!of )\btype\b"
r"|\bstart(?:s|ed|ing)?\s+(?:up\s+)?(?:the|a|an|my)\b"
@@ -122,12 +123,14 @@ _DESKTOP_VEHICLE_RE: re.Pattern[str] = re.compile(
r"|\boeffn\w*|\baufmach\w*|\bklick\w*|\btipp\w*|\bscroll\w*"
r"|\bzieh\w*\b|\bdrueck\w*|\bschliess\w*|\bnavigier\w*|\beinfueg\w*"
r"|\bstart(?:e|et|en)\b"
+ r"|\baktualisier\w*\b|\bneu\s+lad\w*\b"
r"|\bmach\w*\b[^.?!]{0,40}\b(?:auf|zu)\b"
r"|\bgeh\w*\s+(?:auf|zu|in)\b"
r"|\blogg\w*\b"
# --- action verbs (es) --- # i18n-allow: Spanish speech-input matching data
r"|\babr(?:e|a|as|ir)\b|\bcli(?:c|ca|quea)\b|\bpincha\w*|\bpulsa\w*"
r"|\btecle\w*|\bdesplaz\w*|\barrastr\w*|\bpega\b|\bcierr\w*|\bnaveg\w*"
+ r"|\bactualiz\w*|\brecarg\w*"
# --- screen/app/browser nouns (en/de/es share most brand tokens) ---
r"|\bscreen\w*|\bdesktop\b|\bbrowser\w*|\bchrome\b|\bsafari\b"
r"|\bfirefox\b|\bedge\b|\btabs?\b|\bwindows?\b|\bmouse\b|\bcursor\w*"
diff --git a/jarvis/brain/router.py b/jarvis/brain/router.py
index 8f05cdc7d0..00b85a9a7c 100644
--- a/jarvis/brain/router.py
+++ b/jarvis/brain/router.py
@@ -675,8 +675,6 @@ class RouterBrain:
self._manager.active_provider,
self._manager._fast_model(self._manager.active_provider),
)
- dispatcher = self._manager._build_dispatcher(brain)
-
images: tuple[ImageBlock, ...] = ()
screen_note = ""
@@ -697,12 +695,9 @@ class RouterBrain:
# 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
- # An expected unavailable host may keep the old non-capture path open;
- # an unexpected failure closes every alternate screen path so the turn
- # cannot trigger a second, unindicated screenshot attempt.
+ # window the user's rule protects. A TECHNICAL failure (no display, no
+ # permission) also ends honestly: a pure look must never turn into a
+ # Computer-Use action just because the capture backend is unavailable.
turn_trace_id = trace_id or uuid4()
screen = await self._manager._resolve_screen_context_turn(
utterance,
@@ -834,6 +829,13 @@ class RouterBrain:
)
)
+ # A successful one-shot look is evidence-only. Build the dispatcher
+ # without tools so neither Computer-Use nor any other action can be
+ # selected from untrusted pixels. The production BrainManager already
+ # enforces this boundary; RouterBrain must enforce the same contract.
+ dispatcher = self._manager._build_dispatcher(
+ brain, tools_override={} if screen.has_image else None
+ )
tools_payload = dispatcher.tools_payload()
system_prompt = self._manager._build_system_prompt()
diff --git a/jarvis/core/events.py b/jarvis/core/events.py
index 037741e80c..8be9d0e6cd 100644
--- a/jarvis/core/events.py
+++ b/jarvis/core/events.py
@@ -979,6 +979,19 @@ class ScreenCaptureAnnounced(Event):
reason: str = ""
+@dataclass(frozen=True, slots=True)
+class ScreenCaptureGrabbed(Event):
+ """Raw pixels were grabbed for a one-off Screen Context request.
+
+ Published immediately after the platform capture returns, before redaction
+ and encoding. Carries dimensions only: pixels and captured text never enter
+ the event bus. A later privacy recheck may still discard the frame.
+ """
+
+ width: int = 0
+ height: int = 0
+
+
@dataclass(frozen=True, slots=True)
class ScreenCaptureCompleted(Event):
"""A Screen Context capture finished — the receipt.
diff --git a/jarvis/screen_context/intent.py b/jarvis/screen_context/intent.py
index 452f0dc668..b5830912ee 100644
--- a/jarvis/screen_context/intent.py
+++ b/jarvis/screen_context/intent.py
@@ -200,6 +200,114 @@ _SCREEN_INTENT_RE: re.Pattern[str] = re.compile(
)
+# --------------------------------------------------------------------------
+# Ownership boundary — observing is not operating
+# --------------------------------------------------------------------------
+
+# Split only at command-sequencing boundaries. This lets an explanatory clause
+# stay read-only while a later independent clause still owns its operation:
+# "Explain this, then close the window." -> [observe, operate].
+_COMMAND_CLAUSE_SPLIT_RE: re.Pattern[str] = re.compile(
+ r"[.!?;]+|,\s*(?=(?:then|dann|luego)\b)|"
+ r"\b(?:and\s+then|then|und\s+dann|dann|y\s+luego|luego)\b",
+ re.IGNORECASE,
+)
+
+_EXPLICIT_COMPUTER_USE_RE: re.Pattern[str] = re.compile(
+ r"\b(?:use|with|via|using)\s+(?:the\s+)?computer[-\s]?use\b"
+ # i18n-allow: German speech-input matching data
+ r"|\b(?:mit|per|ueber|via|nutz\w*|benutz\w*|verwend\w*)\s+" # i18n-allow
+ r"(?:der\s+|die\s+|das\s+|den\s+)?computer[-\s]?use\b", # i18n-allow
+ re.IGNORECASE,
+)
+
+_EN_ACTION = (
+ r"(?:click|double-?click|right-?click|tap|scroll|drag|drop|hover|press|"
+ r"type|enter|paste|select|choose|submit|zoom|save|delete|remove|download|"
+ r"upload|open|close|refresh|reload|minimi[sz]e|maximi[sz]e|move|resize|"
+ r"switch|navigate|log\s+(?:in|out))\w*"
+)
+_DE_ACTION = (
+ # i18n-allow: German speech-input matching data
+ r"(?:(?:an|drauf|darauf|doppel|rechts)?klick|(?:hoch|runter)?scroll|"
+ r"(?:ein)?tipp|zieh|verschieb|drueck|(?:ein)?fueg|(?:aus)?waehl|markier|" # i18n-allow
+ r"kopier|reich\w*\s+ein|send\w*\s+ab|zoom|speicher|loesch|entfern|"
+ r"lad\w*\s+(?:hoch|runter)|oeffn|schliess|aktualisier|neu\s+lad|"
+ r"anmeld|abmeld|minimier|maximier|verkleiner|vergroesser|wechsel|navigier)\w*"
+)
+_ES_ACTION = (
+ r"(?:haz\s+clic|cliquea|pincha|pulsa|teclea|escribe|pega|desplaza|arrastr|"
+ r"selecciona|elige|envia|guarda|elimina|borra|descarga|sube|abre|cierra|"
+ r"actualiza|recarga|inicia\s+sesion|cierra\s+sesion|minimiza|maximiza|"
+ r"mueve|cambia|navega|amplia|reduce)\w*"
+)
+
+_ACTION_CONNECTOR_SPLIT_RE: re.Pattern[str] = re.compile(
+ rf"\b(?:and|und|y)\s+(?=(?:{_EN_ACTION}|{_DE_ACTION}|{_ES_ACTION})\b)",
+ re.IGNORECASE,
+)
+
+_OPERATION_EXPLANATION_CLAUSE_RE: re.Pattern[str] = re.compile(
+ r"^(?:(?:can|could|would|will)\s+you\s+(?:please\s+)?|please\s+)?"
+ r"(?:explain|show|tell)\b"
+ # i18n-allow: German speech-input matching data
+ r"|^(?:(?:kannst|koenntest|wuerdest|wirst)\s+du\s+(?:bitte\s+)?|bitte\s+)?"
+ r"(?:erklaer|zeig|sag)\w*\b"
+ r"|^(?:(?:puedes|podrias)\s+(?:por\s+favor\s+)?|por\s+favor\s+)?"
+ r"(?:explica|muestra|dime)\b",
+ re.IGNORECASE,
+)
+
+_SCREEN_OPERATION_CLAUSE_RE: re.Pattern[str] = re.compile(
+ # English imperatives and request forms, including "would you mind clicking".
+ rf"^(?:please\s+)?{_EN_ACTION}\b"
+ rf"|^(?:can|could|will)\s+you\s+(?:please\s+)?[^.?!]{{0,72}}?{_EN_ACTION}\b"
+ rf"|^would\s+you\s+(?:please\s+)?(?:mind\s+)?[^.?!]{{0,72}}?{_EN_ACTION}\b"
+ rf"|^i\s+(?:want|need)\s+you\s+to\s+[^.?!]{{0,72}}?{_EN_ACTION}\b"
+ # German: allow the object before the final infinitive ("Bitte den Knopf anklicken").
+ rf"|^(?:bitte\s+)?{_DE_ACTION}\b" # i18n-allow
+ rf"|^bitte\s+[^.?!]{{0,96}}?{_DE_ACTION}\b" # i18n-allow
+ rf"|^(?:kannst|koenntest|wuerdest|wirst)\s+du\s+(?:bitte\s+)?"
+ rf"[^.?!]{{0,96}}?{_DE_ACTION}\b" # i18n-allow
+ # Spanish imperative and modal request forms.
+ rf"|^(?:por\s+favor\s+)?{_ES_ACTION}\b"
+ rf"|^(?:puedes|podrias)\s+(?:por\s+favor\s+)?[^.?!]{{0,96}}?{_ES_ACTION}\b",
+ re.IGNORECASE,
+)
+
+_ACTION_STATE_OBSERVATION_RE: re.Pattern[str] = re.compile(
+ rf"^(?:{_EN_ACTION})\s+(?:is|are|was|were|looks?|seems?|appears?)\b"
+ rf"|^(?:{_DE_ACTION})\s+(?:ist|sind|war|waren|scheint)\b" # i18n-allow
+ rf"|^(?:{_ES_ACTION})\s+(?:esta|estan|parece)\b",
+ re.IGNORECASE,
+)
+
+
+def requests_screen_operation(text: str) -> bool:
+ """Return whether the turn asks Jarvis to operate the live desktop.
+
+ This is the hard ownership boundary between Screen Context and
+ Computer-Use. It is deliberately deterministic and multilingual: an
+ operation request never captures a separate one-shot context first, while
+ a question about what to operate remains a read-only look.
+ """
+ normalized = _normalize(text).strip()
+ if not normalized:
+ return False
+ if _EXPLICIT_COMPUTER_USE_RE.search(normalized):
+ return True
+ for sequence in _COMMAND_CLAUSE_SPLIT_RE.split(normalized):
+ for raw_clause in _ACTION_CONNECTOR_SPLIT_RE.split(sequence):
+ clause = raw_clause.strip(" ,:\t\r\n")
+ if not clause or _OPERATION_EXPLANATION_CLAUSE_RE.search(clause):
+ continue
+ if _ACTION_STATE_OBSERVATION_RE.search(clause):
+ continue
+ if _SCREEN_OPERATION_CLAUSE_RE.search(clause):
+ return True
+ return False
+
+
# --------------------------------------------------------------------------
# Level 3 — weak signals: ask, never capture
# --------------------------------------------------------------------------
@@ -256,6 +364,12 @@ def classify(text: str, *, locale: str = "") -> IntentVerdict:
if not normalized:
return IntentVerdict(intent=VisualIntent.NONE, locale=locale)
+ # Operating the desktop is Computer-Use's job. This check precedes every
+ # visual noun match so phrases such as "click the button on my screen" do
+ # not take a one-shot screenshot and then disable the very tools requested.
+ if requests_screen_operation(normalized):
+ return IntentVerdict(intent=VisualIntent.NONE, locale=locale)
+
window_hits = _evidence(_WINDOW_SCOPE_RE, normalized)
screen_hits = _evidence(_SCREEN_INTENT_RE, normalized)
@@ -339,6 +453,78 @@ _CAPTURE_FAILURE_REPLY: dict[str, str] = {
),
}
+_CAPTURE_UNAVAILABLE_REPLY: dict[str, dict[str, str]] = {
+ "en": {
+ "capture_permission": (
+ "I cannot capture your screen until Screen Recording is allowed in "
+ "system settings. Grant that permission and ask again. No desktop "
+ "action was started."
+ ),
+ "wayland_portal": (
+ "Screen capture is unavailable in this Wayland session. Install and "
+ "enable an XDG desktop portal for your compositor, or sign in with "
+ "an X11 session, then ask again. No desktop action was started."
+ ),
+ "no_display": (
+ "I cannot access an interactive display on this device. Sign in to "
+ "a desktop session or connect a display, then ask again. No desktop "
+ "action was started."
+ ),
+ "capture_backend_unavailable": (
+ "The screen-capture backend is unavailable right now. Restart the "
+ "desktop app and ask again. No desktop action was started."
+ ),
+ },
+ "de": { # i18n-allow: spoken
+ "capture_permission": (
+ "Ich kann deinen Bildschirm erst aufnehmen, wenn die " # i18n-allow
+ "Bildschirmaufnahme in den Systemeinstellungen erlaubt ist. " # i18n-allow
+ "Erteile die Berechtigung und frag noch einmal. Es wurde keine " # i18n-allow
+ "Desktop-Aktion gestartet." # i18n-allow
+ ),
+ "wayland_portal": (
+ "Die Bildschirmaufnahme ist in dieser Wayland-Sitzung nicht " # i18n-allow
+ "verfügbar. Installiere und aktiviere ein XDG-Desktop-Portal für " # i18n-allow
+ "deinen Compositor oder melde dich über X11 an und frag noch " # i18n-allow
+ "einmal. Es wurde keine Desktop-Aktion gestartet." # i18n-allow
+ ),
+ "no_display": (
+ "Ich kann auf diesem Gerät gerade keine interaktive Anzeige " # i18n-allow
+ "erreichen. Melde dich an einer Desktop-Sitzung an oder verbinde " # i18n-allow
+ "einen Bildschirm und frag noch einmal. Es wurde keine " # i18n-allow
+ "Desktop-Aktion gestartet." # i18n-allow
+ ),
+ "capture_backend_unavailable": (
+ "Die Bildschirmaufnahme ist gerade nicht verfügbar. Starte die " # i18n-allow
+ "Desktop-App neu und frag noch einmal. Es wurde keine " # i18n-allow
+ "Desktop-Aktion gestartet." # i18n-allow
+ ),
+ },
+ "es": {
+ "capture_permission": (
+ "No puedo capturar tu pantalla hasta que permitas la grabación de "
+ "pantalla en los ajustes del sistema. Concede el permiso y vuelve a "
+ "pedirlo. No se inició ninguna acción de escritorio."
+ ),
+ "wayland_portal": (
+ "La captura de pantalla no está disponible en esta sesión de "
+ "Wayland. Instala y activa un portal de escritorio XDG para tu "
+ "compositor, o inicia una sesión X11, y vuelve a pedirlo. No se "
+ "inició ninguna acción de escritorio."
+ ),
+ "no_display": (
+ "No puedo acceder a una pantalla interactiva en este dispositivo. "
+ "Inicia una sesión de escritorio o conecta una pantalla y vuelve a "
+ "pedirlo. No se inició ninguna acción de escritorio."
+ ),
+ "capture_backend_unavailable": (
+ "El sistema de captura de pantalla no está disponible ahora. "
+ "Reinicia la aplicación de escritorio y vuelve a pedirlo. No se "
+ "inició ninguna acción de escritorio."
+ ),
+ },
+}
+
#: Fallback locale for a language with no entry — the repo-wide default.
_FALLBACK_LOCALE = "en"
@@ -377,6 +563,16 @@ def capture_failure_reply(locale: str) -> str:
return _CAPTURE_FAILURE_REPLY.get(base) or _CAPTURE_FAILURE_REPLY[_FALLBACK_LOCALE]
+def capture_unavailable_reply(locale: str, reason_code: str = "") -> str:
+ """Honest no-action reply when this host cannot provide screen evidence."""
+ base = (locale or "").split("-")[0].split("_")[0].strip().lower()
+ phrases = _CAPTURE_UNAVAILABLE_REPLY.get(base) or _CAPTURE_UNAVAILABLE_REPLY[
+ _FALLBACK_LOCALE
+ ]
+ fallback = "capture_backend_unavailable"
+ return phrases.get(reason_code) or phrases[fallback]
+
+
#: Locales with a clarifying question. Used by the parity test that pins this
#: table to the supported-locale list, so a new locale cannot ship half-wired.
SUPPORTED_CLARIFY_LOCALES: frozenset[str] = frozenset(_CLARIFY_QUESTION)
@@ -386,7 +582,9 @@ __all__ = [
"SUPPORTED_CLARIFY_LOCALES",
"cancelled_reply",
"capture_failure_reply",
+ "capture_unavailable_reply",
"clarifying_question",
"classify",
"no_vision_provider_reply",
+ "requests_screen_operation",
]
diff --git a/jarvis/screen_context/ports.py b/jarvis/screen_context/ports.py
index 7f4f6511f4..f301f23173 100644
--- a/jarvis/screen_context/ports.py
+++ b/jarvis/screen_context/ports.py
@@ -30,7 +30,7 @@ from collections.abc import Iterator
from contextlib import contextmanager
from dataclasses import dataclass
from pathlib import Path
-from typing import Protocol, runtime_checkable
+from typing import Literal, Protocol, runtime_checkable
from jarvis.screen_context.models import WindowFacts
@@ -78,6 +78,14 @@ class CaptureUnavailable(RuntimeError):
"""
+@dataclass(frozen=True, slots=True)
+class CapturePermissionIssue:
+ """Structured platform remediation returned before any pixels are read."""
+
+ code: Literal["capture_permission", "wayland_portal"]
+ message: str
+
+
# --------------------------------------------------------------------------
# Cursor
# --------------------------------------------------------------------------
@@ -500,7 +508,7 @@ class AccessibilityTextReader:
# --------------------------------------------------------------------------
-def capture_permission_error() -> str | None:
+def capture_permission_error() -> CapturePermissionIssue | None:
"""``None`` when capture is permitted, else an actionable English message.
Deliberately uncached: macOS can revoke a TCC grant while Jarvis runs, and
@@ -509,10 +517,13 @@ def capture_permission_error() -> str | None:
the right price for not lying about what was seen.
"""
if _is_wayland():
- return (
- "Screen capture is unavailable in this Wayland session because "
- "no desktop-portal capture backend is installed. Use an X11 "
- "session or install a supported portal backend, then ask again."
+ return CapturePermissionIssue(
+ code="wayland_portal",
+ message=(
+ "Screen capture is unavailable in this Wayland session because "
+ "no desktop-portal capture backend is installed. Use an X11 "
+ "session or install a supported portal backend, then ask again."
+ ),
)
try:
from jarvis.platform.permissions import ( # noqa: PLC0415
@@ -523,11 +534,14 @@ def capture_permission_error() -> str | None:
port = get_system_permission_port()
if port.runtime_access_granted(PermissionId.SCREEN_RECORDING):
return None
- return (
- "Screen capture is blocked because this app does not have the "
- "screen-recording permission. Grant it in your system privacy "
- "settings (macOS: System Settings > Privacy & Security > Screen "
- "Recording), then ask again."
+ return CapturePermissionIssue(
+ code="capture_permission",
+ message=(
+ "Screen capture is blocked because this app does not have the "
+ "screen-recording permission. Grant it in your system privacy "
+ "settings (macOS: System Settings > Privacy & Security > Screen "
+ "Recording), then ask again."
+ ),
)
except Exception: # noqa: BLE001 — an unavailable probe must not block Windows/Linux
log.debug("screen-recording permission probe failed", exc_info=True)
diff --git a/jarvis/screen_context/service.py b/jarvis/screen_context/service.py
index b4e590d178..7810a7996d 100644
--- a/jarvis/screen_context/service.py
+++ b/jarvis/screen_context/service.py
@@ -46,6 +46,7 @@ from jarvis.screen_context.models import (
VisualIntent,
)
from jarvis.screen_context.ports import (
+ CapturePermissionIssue,
CaptureUnavailable,
accessibility_permission_error,
capture_permission_error,
@@ -120,8 +121,8 @@ class CaptureOutcome:
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.
+ caller should expose the structured remediation and must not turn a pure
+ observation into Computer-Use as an implicit fallback.
* ``failure`` — an unexpected implementation/backend defect. Alternate
screen paths stay closed so they cannot retry without this policy layer.
"""
@@ -133,6 +134,13 @@ class CaptureOutcome:
question: str | None = None
message: str | None = None
reason_kind: Literal["", "policy", "technical", "failure"] = ""
+ reason_code: Literal[
+ "",
+ "capture_permission",
+ "wayland_portal",
+ "no_display",
+ "capture_backend_unavailable",
+ ] = ""
@dataclass
@@ -159,7 +167,9 @@ class ScreenContextService:
clock: Any | None = None,
) -> None:
self._settings = settings or ScreenContextSettings()
- self._bus = bus
+ self._bus = None
+ if bus is not None:
+ self.bind_bus(bus)
# Ports are constructed lazily on first use, never at import or at
# boot (AP-26): building a cursor backend or an accessibility source
# costs native library loads that must not sit on the startup path.
@@ -221,13 +231,18 @@ class ScreenContextService:
return self._ui_text_reader
def bind_bus(self, bus: Any) -> None:
- """Attach the application bus when REST created the service first."""
+ """Attach receipts and the lazy process-wide sound-effect service."""
if self._bus is None:
self._bus = bus
elif self._bus is not bus:
log.warning(
"screen_context: ignored an attempt to bind a second EventBus"
)
+ return
+ if hasattr(bus, "subscribe"):
+ from jarvis.audio.effects import attach_audio_effects # noqa: PLC0415
+
+ attach_audio_effects(bus)
# ---- intent ----------------------------------------------------------
@@ -302,14 +317,23 @@ class ScreenContextService:
"""Take exactly one capture. Assumes intent is already established."""
verdict = verdict or IntentVerdict(intent=VisualIntent.SCREEN)
- permission_error = await asyncio.to_thread(self._permission_probe)
- if permission_error:
- log.info("screen_context: capture refused — %s", permission_error)
+ permission_issue = await asyncio.to_thread(self._permission_probe)
+ if permission_issue:
+ if isinstance(permission_issue, CapturePermissionIssue):
+ reason_code = permission_issue.code
+ permission_message = permission_issue.message
+ else:
+ # Compatibility for injected third-party/test probes that still
+ # implement the original ``str | None`` port contract.
+ reason_code = "capture_permission"
+ permission_message = str(permission_issue)
+ log.info("screen_context: capture refused — %s", permission_message)
return CaptureOutcome(
status="refused",
verdict=verdict,
reason_kind="technical",
- message=permission_error,
+ reason_code=reason_code,
+ message=permission_message,
)
# The cursor is sampled ONCE, here, and threaded through. See
@@ -404,6 +428,7 @@ class ScreenContextService:
status="refused",
verdict=verdict,
reason_kind="technical",
+ reason_code="no_display",
message=str(exc),
)
degradations.extend(target_degradations)
@@ -486,6 +511,7 @@ class ScreenContextService:
status="refused",
verdict=verdict,
reason_kind="technical",
+ reason_code="capture_backend_unavailable",
message=str(exc),
)
except Exception: # noqa: BLE001 - port bugs stay turn-local
@@ -500,6 +526,11 @@ class ScreenContextService:
),
)
+ # This is the shutter boundary: pixels exist now. Publish only
+ # metadata so the shared audio layer can play its cue at the
+ # truthful moment without receiving or retaining screen content.
+ await self._publish_grabbed(size, trace_id=event_trace_id)
+
# Treat a post-shutter identity change as untrusted: discard the
# raw bytes before redaction/storage rather than attaching pixels
# from a surface different from the one that passed policy.
@@ -858,6 +889,27 @@ class ScreenContextService:
exc_info=True,
)
+ async def _publish_grabbed(
+ self, size: tuple[int, int], *, trace_id: UUID
+ ) -> None:
+ if self._bus is None:
+ return
+ try:
+ from jarvis.core.events import ScreenCaptureGrabbed # noqa: PLC0415
+
+ await self._bus.publish(
+ ScreenCaptureGrabbed(
+ trace_id=trace_id,
+ width=size[0],
+ height=size[1],
+ )
+ )
+ except Exception: # noqa: BLE001 - an audio receipt cannot erase pixels
+ log.warning(
+ "screen_context: shutter receipt publication failed",
+ exc_info=True,
+ )
+
def _safe_target_label(target: CaptureTarget) -> str:
"""Metadata-only target label; never expose an app or document title."""
diff --git a/jarvis/screen_context/turn.py b/jarvis/screen_context/turn.py
index bb2ced585a..a4af12cccc 100644
--- a/jarvis/screen_context/turn.py
+++ b/jarvis/screen_context/turn.py
@@ -68,7 +68,8 @@ def get_service(*, bus: Any | None = None) -> ScreenContextService:
from jarvis.core.config import load_config # noqa: PLC0415
_service = ScreenContextService(
- settings=settings_from_config(load_config()), bus=bus
+ settings=settings_from_config(load_config()),
+ bus=bus,
)
elif bus is not None:
# REST may create the service before the conversational brain is ready.
@@ -104,17 +105,15 @@ class TurnScreenContext:
``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.
+ * ``unavailable`` — this machine could not capture (no display, no
+ permission, capture error). Speak ``message`` and stop. A pure look turn
+ must never fall through into Computer-Use as an accidental fallback.
* ``cancelled`` — the user answered no to the clarifying question. Speak
``message`` and end the turn without consulting another screen path.
- 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).
+ The ``refused`` / ``unavailable`` split remains observable for diagnostics,
+ but both close alternate screen paths. Headless hosts degrade honestly
+ instead of starting a desktop-driving tool that cannot work there.
"""
status: TurnStatus
@@ -126,6 +125,10 @@ class TurnScreenContext:
text: str = ""
question: str | None = None
message: str | None = None
+ #: Stable machine-readable remediation category for technical unavailability.
+ reason_code: str = ""
+ #: Internal platform detail for logs/diagnostics; never spoken directly.
+ diagnostic_detail: str = ""
#: One user-facing line naming what was captured, for the transcript.
receipt: str = ""
source_hash: str = ""
@@ -138,16 +141,17 @@ class TurnScreenContext:
@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", "cancelled")
+ return self.status in ("clarify", "refused", "unavailable", "cancelled")
@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.
+ True for every requested look that did not produce evidence. This keeps
+ permanent vision and Computer-Use from silently bypassing the one-shot
+ Screen Context contract.
"""
- return self.status in ("clarify", "refused", "cancelled")
+ return self.status in ("clarify", "refused", "unavailable", "cancelled")
def _model_note(context: ScreenContext) -> str:
@@ -261,16 +265,20 @@ async def screen_context_for_turn(
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.
+ # Impossible here. End honestly instead of letting a pure look
+ # request fall into Computer-Use or permanent vision.
log.info(
"screen_context: capture unavailable on this machine (%s) "
- "— the turn continues on the existing path",
+ "— alternate screen paths stay closed",
outcome.message,
)
return TurnScreenContext(
- status="unavailable", message=outcome.message or ""
+ status="unavailable",
+ message=intent_module.capture_unavailable_reply(
+ locale, outcome.reason_code
+ ),
+ reason_code=outcome.reason_code,
+ diagnostic_detail=outcome.message or "",
)
if outcome.reason_kind == "failure":
log.error(
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index 6bca12f90b..e5358257d2 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -37,8 +37,14 @@ from jarvis.audio.capture import (
capture_chunks_for_duration,
pcm_bytes_to_np,
)
-from jarvis.audio.chime import CHIME_PCM, CHIME_SAMPLE_RATE, DISCONNECT_PCM, READY_PCM
+from jarvis.audio.chime import (
+ CHIME_PCM,
+ CHIME_SAMPLE_RATE,
+ DISCONNECT_PCM,
+ READY_PCM,
+)
from jarvis.audio.device_init import wait_for_stable_audio_devices
+from jarvis.audio.effects import bind_shared_audio_player
from jarvis.audio.player import AudioPlayer
from jarvis.audio.vad import SileroEndpointer
from jarvis.audio.vad_reasons import FORCED_CUT_REASONS
@@ -2346,6 +2352,7 @@ class SpeechPipeline:
volume=_tts_volume,
device_priority=self._output_priority,
)
+ bind_shared_audio_player(self._player)
# Kept so warm-up can re-resolve the output device against a freshly
# re-enumerated PortAudio table (post-reboot idx-drift cure, BUG-014).
self._output_device = output_device
diff --git a/tests/unit/audio/test_chime_ready.py b/tests/unit/audio/test_chime_ready.py
index c08497c50f..66d1241c8c 100644
--- a/tests/unit/audio/test_chime_ready.py
+++ b/tests/unit/audio/test_chime_ready.py
@@ -12,7 +12,9 @@ from jarvis.audio.chime import (
CHIME_PCM,
DISCONNECT_PCM,
READY_PCM,
+ SCREEN_CAPTURE_PCM,
generate_ready_pcm,
+ generate_screen_capture_pcm,
)
@@ -32,3 +34,9 @@ def test_ready_pcm_distinct_from_wake_and_disconnect() -> None:
def test_generate_ready_pcm_is_deterministic() -> None:
"""Same parameters -> identical bytes (pre-generated once at import)."""
assert generate_ready_pcm() == generate_ready_pcm()
+
+
+def test_screen_capture_cue_is_original_and_deterministic() -> None:
+ assert SCREEN_CAPTURE_PCM == generate_screen_capture_pcm()
+ assert SCREEN_CAPTURE_PCM not in (CHIME_PCM, READY_PCM, DISCONNECT_PCM)
+ assert len(SCREEN_CAPTURE_PCM) % 2 == 0
diff --git a/tests/unit/audio/test_effects.py b/tests/unit/audio/test_effects.py
new file mode 100644
index 0000000000..521032398d
--- /dev/null
+++ b/tests/unit/audio/test_effects.py
@@ -0,0 +1,88 @@
+"""Process-wide screenshot sound works with voice, chat-only, and no audio."""
+from __future__ import annotations
+
+import asyncio
+from types import SimpleNamespace
+
+from jarvis.audio.chime import CHIME_SAMPLE_RATE, SCREEN_CAPTURE_PCM
+from jarvis.audio.effects import AudioEffectsService
+from jarvis.core.bus import EventBus
+from jarvis.core.events import ScreenCaptureGrabbed
+
+
+class RecordingPlayer:
+ def __init__(self) -> None:
+ self.plays: list[tuple[bytes, int | None]] = []
+
+ async def play_pcm(self, pcm: bytes, sample_rate: int | None = None) -> None:
+ self.plays.append((pcm, sample_rate))
+
+
+async def _finish(service: AudioEffectsService) -> None:
+ for _ in range(20):
+ task = service._capture_task
+ if task is None:
+ return
+ await asyncio.sleep(0)
+ task = service._capture_task
+ if task is not None:
+ await task
+
+
+async def test_capture_cue_reuses_shared_voice_player_without_blocking_bus(
+ monkeypatch,
+) -> None:
+ service = AudioEffectsService()
+ player = RecordingPlayer()
+ service.bind_player(player)
+ monkeypatch.setattr(
+ service,
+ "_load_config",
+ lambda: SimpleNamespace(ui=SimpleNamespace(sound_effects=True)),
+ )
+ bus = EventBus()
+ service.attach(bus)
+
+ await asyncio.wait_for(
+ bus.publish(ScreenCaptureGrabbed(width=1920, height=1080)), timeout=0.05
+ )
+ await _finish(service)
+
+ assert player.plays == [(SCREEN_CAPTURE_PCM, CHIME_SAMPLE_RATE)]
+
+
+async def test_chat_only_capture_lazily_creates_one_player(monkeypatch) -> None:
+ service = AudioEffectsService()
+ player = RecordingPlayer()
+ config = SimpleNamespace(ui=SimpleNamespace(sound_effects=True))
+ builds: list[object] = []
+ monkeypatch.setattr(service, "_load_config", lambda: config)
+ monkeypatch.setattr(
+ service, "_make_player", lambda cfg: (builds.append(cfg), player)[1]
+ )
+ bus = EventBus()
+ service.attach(bus)
+
+ await bus.publish(ScreenCaptureGrabbed(width=800, height=600))
+ await _finish(service)
+
+ assert builds == [config]
+ assert player.plays == [(SCREEN_CAPTURE_PCM, CHIME_SAMPLE_RATE)]
+
+
+async def test_global_sound_switch_mutes_capture_cue(monkeypatch) -> None:
+ service = AudioEffectsService()
+ player = RecordingPlayer()
+ service.bind_player(player)
+ monkeypatch.setattr(
+ service,
+ "_load_config",
+ lambda: SimpleNamespace(ui=SimpleNamespace(sound_effects=False)),
+ )
+ bus = EventBus()
+ service.attach(bus)
+
+ await bus.publish(ScreenCaptureGrabbed(width=800, height=600))
+ await _finish(service)
+
+ assert player.plays == []
diff --git a/tests/unit/audio/test_player_lock.py b/tests/unit/audio/test_player_lock.py
index f64fd8d4ad..54a0185b7c 100644
--- a/tests/unit/audio/test_player_lock.py
+++ b/tests/unit/audio/test_player_lock.py
@@ -19,6 +19,7 @@ monkeypatched to no-ops.
from __future__ import annotations
import asyncio
+import threading
from collections.abc import AsyncIterator
import pytest
@@ -124,6 +125,293 @@ async def test_lock_is_lazy_constructed_and_idempotent(monkeypatch) -> None:
assert lock1 is lock2, "lock must be idempotent across calls"
+async def test_cancelled_one_shot_aborts_and_joins_native_thread_before_unlock(
+ monkeypatch,
+) -> None:
+ """A timed-out cue cannot orphan a PortAudio stream beside later TTS."""
+ player, _ = _make_player_with_recorded_inner(monkeypatch)
+ player._stream_state_lock = threading.Lock()
+ player._playback_generation = 0
+ started = threading.Event()
+ released = threading.Event()
+ active = 0
+ max_active = 0
+
+ class BlockingStream:
+ def abort(self) -> None:
+ released.set()
+
+ def close(self) -> None:
+ return None
+
+ stream = BlockingStream()
+ monkeypatch.setattr(player, "_open_output_stream", lambda rate: (stream, rate))
+ monkeypatch.setattr(player, "_close_output_stream", lambda _stream: None)
+
+ def blocking_write(*_args, **_kwargs) -> None:
+ nonlocal active, max_active
+ active += 1
+ max_active = max(max_active, active)
+ started.set()
+ try:
+ assert released.wait(1.0), "abort_active did not release native playback"
+ finally:
+ active -= 1
+
+ monkeypatch.setattr(player, "_write_samples", blocking_write)
+
+ task = asyncio.create_task(player.play_pcm(b"\x01\x00" * 100))
+ assert await asyncio.to_thread(started.wait, 1.0)
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+ assert released.is_set()
+ assert active == 0, "the native worker must be joined before cancellation returns"
+ assert not player._get_play_lock().locked()
+ await player.play_pcm(b"\x02\x00" * 100)
+ assert max_active == 1
+
+
+async def test_one_shot_retires_idle_stream_before_opening_its_stream(
+ monkeypatch,
+) -> None:
+ """A persistent TTS stream and a shutter stream never coexist."""
+ player, _ = _make_player_with_recorded_inner(monkeypatch)
+ player._stream_state_lock = threading.Lock()
+ player._playback_generation = 0
+ old_stream = object()
+ new_stream = object()
+ player._active_stream = old_stream
+ player._active_source_rate = 24_000
+ player._active_device_rate = 48_000
+ closed: list[object] = []
+
+ def open_after_old_closed(rate: int) -> tuple[object, int]:
+ assert closed == [old_stream]
+ return new_stream, rate
+
+ monkeypatch.setattr(player, "_open_output_stream", open_after_old_closed)
+ monkeypatch.setattr(player, "_close_output_stream", closed.append)
+ monkeypatch.setattr(player, "_write_samples", lambda *_a, **_kw: None)
+
+ await player.play_pcm(b"\x01\x00" * 100)
+
+ assert closed == [old_stream, new_stream]
+ assert player._active_stream is None
+
+
+async def test_failed_idle_stream_retirement_prevents_replacement_open(
+ monkeypatch,
+) -> None:
+ player, _ = _make_player_with_recorded_inner(monkeypatch)
+ player._stream_state_lock = threading.Lock()
+ player._playback_generation = 0
+ old_stream = object()
+ player._active_stream = old_stream
+ player._active_source_rate = 24_000
+ player._active_device_rate = 48_000
+ opens = 0
+
+ def forbidden_open(rate: int) -> tuple[object, int]:
+ nonlocal opens
+ opens += 1
+ return object(), rate
+
+ monkeypatch.setattr(player, "_open_output_stream", forbidden_open)
+ monkeypatch.setattr(player, "_close_output_stream", lambda _stream: False)
+
+ await player.play_pcm(b"\x01\x00" * 100)
+
+ assert opens == 0
+ assert player._unclean_stream is old_stream
+ assert player._native_playback_poisoned()
+
+
+async def test_failed_late_stream_close_keeps_player_fail_closed(
+ monkeypatch,
+) -> None:
+ player, _ = _make_player_with_recorded_inner(monkeypatch)
+ player._stream_state_lock = threading.Lock()
+ player._playback_generation = 0
+ late_stream = object()
+
+ def superseded_open(rate: int) -> tuple[object, int]:
+ player._playback_generation += 1
+ return late_stream, rate
+
+ monkeypatch.setattr(player, "_open_output_stream", superseded_open)
+ monkeypatch.setattr(player, "_close_output_stream", lambda _stream: False)
+
+ await player.play_pcm(b"\x01\x00" * 100)
+
+ assert player._unclean_stream is late_stream
+ assert player._native_playback_poisoned()
+
+
+async def test_failed_native_abort_poison_closes_player_until_worker_exits(
+ monkeypatch,
+) -> None:
+ """A broken PortAudio abort degrades audio without opening a rival stream."""
+ player, _ = _make_player_with_recorded_inner(monkeypatch)
+ player._stream_state_lock = threading.Lock()
+ player._playback_generation = 0
+ started = threading.Event()
+ release = threading.Event()
+ opens = 0
+
+ class UnabortableStream:
+ def abort(self) -> None:
+ raise OSError("abort failed")
+
+ def close(self) -> None:
+ raise OSError("close failed")
+
+ stream = UnabortableStream()
+
+ def open_stream(rate: int) -> tuple[UnabortableStream, int]:
+ nonlocal opens
+ opens += 1
+ return stream, rate
+
+ def wedged_write(*_args, **_kwargs) -> None:
+ started.set()
+ assert release.wait(1.0)
+
+ monkeypatch.setattr(player, "_open_output_stream", open_stream)
+ monkeypatch.setattr(player, "_write_samples", wedged_write)
+ monkeypatch.setattr(player, "_close_output_stream", lambda _stream: False)
+ monkeypatch.setattr(
+ "jarvis.audio.player._ONE_SHOT_CANCEL_JOIN_TIMEOUT_S", 0.01
+ )
+
+ task = asyncio.create_task(player.play_pcm(b"\x01\x00" * 100))
+ assert await asyncio.to_thread(started.wait, 1.0)
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+ assert player._native_playback_poisoned()
+ await player.play_pcm(b"\x02\x00" * 100)
+ assert opens == 1, "a poisoned player must not open a second native stream"
+
+ poisoned_worker = player._poisoned_worker
+ assert poisoned_worker is not None
+ release.set()
+ await asyncio.gather(poisoned_worker, return_exceptions=True)
+ await asyncio.sleep(0)
+ assert player._native_playback_poisoned()
+ await player.play_pcm(b"\x03\x00" * 100)
+ assert opens == 1, "repeated close failure must keep the player fail-closed"
+
+
+async def test_cancel_during_native_open_is_bounded_and_fail_closed(
+ monkeypatch,
+) -> None:
+ """A wedged PortAudio open has no handle to abort, so poison gates recovery."""
+ player, _ = _make_player_with_recorded_inner(monkeypatch)
+ player._stream_state_lock = threading.Lock()
+ player._playback_generation = 0
+ started = threading.Event()
+ release = threading.Event()
+ opened_stream = object()
+ opens = 0
+ closed: list[object] = []
+
+ def wedged_open(rate: int) -> tuple[object, int]:
+ nonlocal opens
+ opens += 1
+ started.set()
+ assert release.wait(1.0)
+ return opened_stream, rate
+
+ monkeypatch.setattr(player, "_open_output_stream", wedged_open)
+ monkeypatch.setattr(player, "_close_output_stream", closed.append)
+ monkeypatch.setattr(
+ "jarvis.audio.player._ONE_SHOT_CANCEL_JOIN_TIMEOUT_S", 0.01
+ )
+
+ task = asyncio.create_task(player.play_pcm(b"\x01\x00" * 100))
+ assert await asyncio.to_thread(started.wait, 1.0)
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+ assert player._native_playback_poisoned()
+ await player.play_pcm(b"\x02\x00" * 100)
+ assert opens == 1
+
+ poisoned_worker = player._poisoned_worker
+ assert poisoned_worker is not None
+ release.set()
+ await asyncio.gather(poisoned_worker, return_exceptions=True)
+ await asyncio.sleep(0)
+ assert not player._native_playback_poisoned()
+ assert closed == [opened_stream]
+
+
+async def test_double_cancel_keeps_worker_poisoned_until_native_exit(
+ monkeypatch,
+) -> None:
+ """A second cancellation cannot bypass the fail-closed worker marker."""
+ player, _ = _make_player_with_recorded_inner(monkeypatch)
+ player._stream_state_lock = threading.Lock()
+ player._playback_generation = 0
+ started = threading.Event()
+ release = threading.Event()
+ opens = 0
+
+ class UnabortableStream:
+ def abort(self) -> None:
+ raise OSError("abort failed")
+
+ def close(self) -> None:
+ raise OSError("close failed")
+
+ stream = UnabortableStream()
+
+ def open_stream(rate: int) -> tuple[UnabortableStream, int]:
+ nonlocal opens
+ opens += 1
+ return stream, rate
+
+ def wedged_write(*_args, **_kwargs) -> None:
+ started.set()
+ assert release.wait(1.0)
+
+ monkeypatch.setattr(player, "_open_output_stream", open_stream)
+ monkeypatch.setattr(player, "_write_samples", wedged_write)
+ monkeypatch.setattr(player, "_close_output_stream", lambda _stream: True)
+
+ task = asyncio.create_task(player.play_pcm(b"\x01\x00" * 100))
+ assert await asyncio.to_thread(started.wait, 1.0)
+ task.cancel()
+ for _ in range(20):
+ if player._native_playback_poisoned():
+ break
+ await asyncio.sleep(0)
+ assert player._native_playback_poisoned()
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+ await player.play_pcm(b"\x02\x00" * 100)
+ assert opens == 1
+ poisoned_worker = player._poisoned_worker
+ assert poisoned_worker is not None
+ release.set()
+ await asyncio.gather(poisoned_worker, return_exceptions=True)
+ await asyncio.sleep(0)
+ assert not player._native_playback_poisoned()
+
+
@pytest.mark.asyncio
async def test_real_play_chunks_holds_lock_while_streaming(monkeypatch) -> None:
"""End-to-end on the real ``play_chunks`` coroutine: while one call
diff --git a/tests/unit/brain/test_cu_gate.py b/tests/unit/brain/test_cu_gate.py
index 3ba6fd6328..75e1104b12 100644
--- a/tests/unit/brain/test_cu_gate.py
+++ b/tests/unit/brain/test_cu_gate.py
@@ -124,7 +124,11 @@ def test_product_name_masking_leaves_real_commands_intact(utterance: str) -> Non
"Open the browser and search for Gulfstream G100 runway length.",
"Click the settings icon.",
"Type hello into the search field.",
+ "Refresh this page.",
+ "Reload the current tab.",
+ "Aktualisiere diese Seite.", # i18n-allow: DE trigger
"Abre el navegador.",
+ "Actualiza esta página.",
"Haz clic en el botón azul.",
# Naming the vehicle makes even a web lookup a desktop task.
"Google das mal im Browser.", # i18n-allow: DE trigger
diff --git a/tests/unit/brain/test_drop_silent_context.py b/tests/unit/brain/test_drop_silent_context.py
index b76a3cca06..355bac87a6 100644
--- a/tests/unit/brain/test_drop_silent_context.py
+++ b/tests/unit/brain/test_drop_silent_context.py
@@ -18,6 +18,7 @@ from jarvis.brain.streaming import StreamingAggregate
from jarvis.core.bus import EventBus
from jarvis.core.config import JarvisConfig
from jarvis.core.protocols import BrainDelta, BrainRequest, ImageBlock
+from jarvis.screen_context.turn import TurnScreenContext
class _FakeBrain:
@@ -51,6 +52,16 @@ def _manager() -> tuple[BrainManager, _RecordingDispatcher]:
m._build_fallback_chain = lambda _l: [("fake", "fake-model")] # type: ignore[method-assign]
m._get_brain = lambda _n, _mo: _FakeBrain() # type: ignore[method-assign]
m._build_dispatcher = lambda _b, *, tools_override=None: rec # type: ignore[method-assign]
+
+ async def _screen_not_requested(*_args, **_kwargs) -> TurnScreenContext:
+ return TurnScreenContext(status="none")
+
+ m._resolve_screen_context_turn = _screen_not_requested # type: ignore[method-assign]
+
+ async def _no_permanent_vision(**_kwargs) -> tuple[ImageBlock, ...]:
+ return ()
+
+ m._collect_vision_images = _no_permanent_vision # type: ignore[method-assign]
return m, rec
@@ -83,7 +94,7 @@ async def test_dropped_image_reaches_next_turn_only() -> None:
m, rec = _manager()
m.add_dropped_context("[dropped photo.png]", (_IMG,))
- await m.generate("what is this", trace_id=uuid4(), use_history=True)
+ await m.generate("describe the dropped photo", trace_id=uuid4(), use_history=True)
await m.generate("and now", trace_id=uuid4(), use_history=True)
assert _IMG in rec.calls[0]["images"] # consumed on the first real turn
diff --git a/tests/unit/brain/test_manager_pointer.py b/tests/unit/brain/test_manager_pointer.py
index 70dc6c7e22..f0913da2ff 100644
--- a/tests/unit/brain/test_manager_pointer.py
+++ b/tests/unit/brain/test_manager_pointer.py
@@ -16,6 +16,7 @@ from jarvis.core.config import JarvisConfig
from jarvis.core.protocols import ImageBlock
from jarvis.pointer import turn as pturn
from jarvis.pointer.context import PointerContext
+from jarvis.screen_context.turn import TurnScreenContext
from jarvis.vision.pointer_types import PointerElement
@@ -25,6 +26,10 @@ class _FakeNamed:
self.schema: dict = {}
+class _FakeBrain:
+ supports_vision = True
+
+
class _Recorder:
def __init__(self) -> None:
self.calls: list[dict] = []
@@ -46,13 +51,18 @@ def _manager(
manager = BrainManager(config=cfg, bus=EventBus(), tools=tools or {})
rec = _Recorder()
manager._build_fallback_chain = lambda _level: [("fake", "fake-model")] # type: ignore[method-assign]
- manager._get_brain = lambda _name, _model: object() # type: ignore[method-assign]
+ manager._get_brain = lambda _name, _model: _FakeBrain() # type: ignore[method-assign]
async def _civ(**_kw):
return vision_images
manager._collect_vision_images = _civ # type: ignore[method-assign]
+ async def _screen_not_requested(*_args, **_kwargs) -> TurnScreenContext:
+ return TurnScreenContext(status="none")
+
+ manager._resolve_screen_context_turn = _screen_not_requested # type: ignore[method-assign]
+
def _bd(_brain, *, tools_override=None):
rec.tools_seen.append(dict(tools_override or {}))
return rec
@@ -112,7 +122,12 @@ async def test_push_turn_suppresses_inspect_pointer_tool(monkeypatch) -> None:
monkeypatch.setattr(pturn, "resolve_pointer_context_async", fake_resolve)
- manager, rec = _manager(tools={"inspect-pointer": _FakeNamed("inspect-pointer"), "other": _FakeNamed("other")})
+ manager, rec = _manager(
+ tools={
+ "inspect-pointer": _FakeNamed("inspect-pointer"),
+ "other": _FakeNamed("other"),
+ }
+ )
await manager.generate("was ist das da?", use_history=False)
tools = rec.tools_seen[0]
@@ -129,7 +144,12 @@ async def test_non_push_turn_keeps_inspect_pointer_tool(monkeypatch) -> None:
monkeypatch.setattr(pturn, "resolve_pointer_context_async", fake_resolve)
- manager, rec = _manager(tools={"inspect-pointer": _FakeNamed("inspect-pointer"), "other": _FakeNamed("other")})
+ manager, rec = _manager(
+ tools={
+ "inspect-pointer": _FakeNamed("inspect-pointer"),
+ "other": _FakeNamed("other"),
+ }
+ )
await manager.generate("erzaehl mir einen Witz", use_history=False)
tools = rec.tools_seen[0]
diff --git a/tests/unit/brain/test_manager_vision.py b/tests/unit/brain/test_manager_vision.py
index 0d15cb83db..41c0c857d4 100644
--- a/tests/unit/brain/test_manager_vision.py
+++ b/tests/unit/brain/test_manager_vision.py
@@ -98,13 +98,13 @@ def _manager_with_recorder() -> tuple[BrainManager, _RecordingDispatcher]:
manager._get_brain = lambda _name, _model: _FakeBrain() # type: ignore[method-assign]
manager._build_dispatcher = lambda _brain, *, tools_override=None: recorder # type: ignore[method-assign]
- async def _screen_unavailable(*_args, **_kwargs) -> TurnScreenContext:
+ async def _screen_not_requested(*_args, **_kwargs) -> TurnScreenContext:
# These tests pin the legacy permanent-vision fallback specifically.
# The production Screen Context path has its own manager integration
# tests and must not capture the developer's real display here.
- return TurnScreenContext(status="unavailable")
+ return TurnScreenContext(status="none")
- manager._resolve_screen_context_turn = _screen_unavailable # type: ignore[method-assign]
+ manager._resolve_screen_context_turn = _screen_not_requested # type: ignore[method-assign]
return manager, recorder
@@ -181,4 +181,7 @@ async def test_brain_manager_continues_on_vision_failure(caplog) -> None:
await manager.generate("was siehst du", use_history=False)
assert recorder.calls[0]["images"] == ()
- assert any("Vision-Inject fehlgeschlagen" in rec.message for rec in caplog.records) # i18n-allow
+ assert any(
+ "Vision-Inject fehlgeschlagen" in rec.message # i18n-allow
+ for rec in caplog.records
+ )
diff --git a/tests/unit/brain/test_router_screen_context.py b/tests/unit/brain/test_router_screen_context.py
index d94f5d6dd5..3b017c39d7 100644
--- a/tests/unit/brain/test_router_screen_context.py
+++ b/tests/unit/brain/test_router_screen_context.py
@@ -50,6 +50,7 @@ class _FakeBrain:
class _RecordingDispatcher:
def __init__(self) -> None:
self.calls: list[dict[str, Any]] = []
+ self.tool_overrides: list[dict[str, Any] | None] = []
def tools_payload(self) -> list[dict[str, Any]]:
return []
@@ -127,7 +128,11 @@ def _build_router(vision_provider: Any = None) -> tuple[RouterBrain, _RecordingD
)
router.manager._brain_cache[("fake", "fake-model")] = _FakeBrain()
recorder = _RecordingDispatcher()
- router.manager._build_dispatcher = lambda _brain: recorder # type: ignore[method-assign]
+ def _dispatcher(_brain: Any, *, tools_override=None, **_kwargs: Any):
+ recorder.tool_overrides.append(tools_override)
+ return recorder
+
+ router.manager._build_dispatcher = _dispatcher # type: ignore[method-assign]
return router, recorder
@@ -164,6 +169,9 @@ async def test_captured_context_is_attached_with_its_note(
"the raw utterance must reach the gates unchanged — the note travels "
"in turn_context precisely so it cannot widen cu_gate/spawn_gate"
)
+ assert recorder.tool_overrides == [{}], (
+ "a read-only screen turn must expose no Computer-Use or action tools"
+ )
async def test_screen_context_wins_over_permanent_vision(
@@ -228,10 +236,10 @@ async def test_privacy_refusal_is_spoken_and_shuts_the_fallback(
)
-async def test_technical_failure_falls_through_to_the_old_path(
+async def test_technical_failure_ends_honestly_without_computer_use(
monkeypatch: pytest.MonkeyPatch,
) -> None:
- """Headless / unpermitted hosts must answer normally, not refuse."""
+ """Headless hosts degrade honestly and never turn looking into acting."""
_patch_screen(
monkeypatch,
TurnScreenContext(status="unavailable", message="No display available."),
@@ -241,11 +249,9 @@ async def test_technical_failure_falls_through_to_the_old_path(
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"
- )
+ assert recorder.calls == []
+ assert provider.consulted == 0
+ assert "No display" in "".join(d.content or "" for d in deltas)
async def test_a_plain_turn_is_untouched(monkeypatch: pytest.MonkeyPatch) -> None:
diff --git a/tests/unit/brain/test_router_vision.py b/tests/unit/brain/test_router_vision.py
index 742a7b3534..b4cda0409d 100644
--- a/tests/unit/brain/test_router_vision.py
+++ b/tests/unit/brain/test_router_vision.py
@@ -41,7 +41,6 @@ from jarvis.core.protocols import (
ToolResult,
)
-
# ----------------------------------------------------------------------
# Fakes
# ----------------------------------------------------------------------
@@ -214,7 +213,10 @@ def _make_jpeg_file() -> tuple[str, bytes]:
return fh.name, data
-def _make_obs(path: str | None = "/tmp/fake.png", sha: str = "abc123") -> Observation:
+def _make_obs(
+ path: str | None = "/tmp/fake.png", # noqa: S108 - inert fake path, never written
+ sha: str = "abc123",
+) -> Observation:
return Observation(
trace_id=uuid4(),
timestamp_ns=time.time_ns(),
@@ -245,7 +247,9 @@ def _build_router(
fb = _FakeBrain()
router.manager._brain_cache[("fake", "fake-model")] = fb
recorder = _RecordingDispatcher()
- router.manager._build_dispatcher = lambda _brain: recorder # type: ignore[method-assign]
+ router.manager._build_dispatcher = ( # type: ignore[method-assign]
+ lambda _brain, *, tools_override=None, **_kwargs: recorder
+ )
return router, recorder
@@ -396,7 +400,10 @@ async def test_router_continues_on_vision_failure(caplog: pytest.LogCaptureFixtu
assert len(recorder.calls) == 1
assert recorder.calls[0]["images"] == ()
assert any(d.content for d in deltas)
- assert any("Vision-Inject fehlgeschlagen" in rec.message for rec in caplog.records) # i18n-allow
+ assert any(
+ "Vision-Inject fehlgeschlagen" in rec.message # i18n-allow
+ for rec in caplog.records
+ )
@pytest.mark.asyncio
diff --git a/tests/unit/screen_context/test_intent.py b/tests/unit/screen_context/test_intent.py
index 87cdcceec3..a6069a0531 100644
--- a/tests/unit/screen_context/test_intent.py
+++ b/tests/unit/screen_context/test_intent.py
@@ -18,6 +18,7 @@ from jarvis.screen_context.intent import (
SUPPORTED_CLARIFY_LOCALES,
clarifying_question,
classify,
+ requests_screen_operation,
)
from jarvis.screen_context.models import VisualIntent
@@ -43,6 +44,7 @@ from jarvis.screen_context.models import VisualIntent
"was steht da?",
"lies mir das vor",
"auf dem Bildschirm ist eine Fehlermeldung", # i18n-allow: DE input
+ "Wenn sowas auf meinem Bildschirm ist, was bedeutet das?", # i18n-allow: DE input
"mach einen Screenshot", # i18n-allow: DE input
# -- Spanish
"mira esto",
@@ -58,6 +60,65 @@ def test_unambiguous_requests_capture(utterance: str) -> None:
assert verdict.evidence, "an unambiguous verdict must record its evidence"
+ "utterance",
+ [
+ "click the button on my screen",
+ "look at this and then scroll down",
+ "use Computer-Use and take a screenshot",
+ "submit this form on my screen",
+ "zoom in on my screen",
+ "save this document on my screen",
+ "delete this file on my screen",
+ "Refresh this page",
+ "Log in",
+ "Would you mind clicking the button?",
+ "Klick den Knopf auf meinem Bildschirm", # i18n-allow: DE input
+ "Kannst du den Button auf meinem Bildschirm anklicken?", # i18n-allow: DE input
+ "Bitte den Knopf auf meinem Bildschirm anklicken", # i18n-allow: DE input
+ "Schau dir das an und scrolle dann nach unten", # i18n-allow: DE input
+ "pulsa el botón en mi pantalla",
+ "Explain this, then close the window.",
+ ],
+)
+def test_desktop_operations_belong_to_computer_use(utterance: str) -> None:
+ assert requests_screen_operation(utterance)
+ assert classify(utterance).intent is VisualIntent.NONE
+
+
+ "utterance",
+ [
+ "which button should I click on my screen?",
+ "Welchen Knopf soll ich auf meinem Bildschirm anklicken?", # i18n-allow: DE input
+ "¿qué botón debo pulsar en mi pantalla?",
+ ],
+)
+def test_operation_advice_remains_a_read_only_look(utterance: str) -> None:
+ assert not requests_screen_operation(utterance)
+ assert classify(utterance).wants_capture
+
+
+ "utterance",
+ [
+ "I clicked the button and now this error is on my screen",
+ "can you explain which button to click on my screen?",
+ "Save is greyed out on my screen",
+ # i18n-allow: German speech-input fixtures
+ (
+ "Ich habe den Knopf angeklickt und jetzt ist der Fehler " # i18n-allow
+ "auf meinem Bildschirm" # i18n-allow
+ ),
+ "Kannst du erklären, welchen Knopf ich auf meinem Bildschirm anklicken soll?", # i18n-allow
+ "Pulsé el botón y ahora aparece este error en mi pantalla",
+ ],
+)
+def test_past_actions_and_action_advice_never_drive_the_desktop(utterance: str) -> None:
+ assert not requests_screen_operation(utterance)
+ assert classify(utterance).wants_capture
+
+
@pytest.mark.parametrize(
"utterance",
[
diff --git a/tests/unit/screen_context/test_ports.py b/tests/unit/screen_context/test_ports.py
index 6b8596982e..524ef4f2cd 100644
--- a/tests/unit/screen_context/test_ports.py
+++ b/tests/unit/screen_context/test_ports.py
@@ -29,10 +29,11 @@ def test_wayland_permission_probe_is_actionable(
) -> None:
monkeypatch.setattr(ports, "_is_wayland", lambda: True)
- message = ports.capture_permission_error()
+ issue = ports.capture_permission_error()
- assert message is not None
- assert "portal" in message.lower()
+ assert issue is not None
+ assert issue.code == "wayland_portal"
+ assert "portal" in issue.message.lower()
def test_visible_windows_retains_untitled_password_manager_candidate(
diff --git a/tests/unit/screen_context/test_service.py b/tests/unit/screen_context/test_service.py
index e1d5d413d9..7cc52b2c08 100644
--- a/tests/unit/screen_context/test_service.py
+++ b/tests/unit/screen_context/test_service.py
@@ -22,7 +22,11 @@ from jarvis.screen_context.models import (
TargetReason,
WindowFacts,
)
-from jarvis.screen_context.ports import CaptureUnavailable, WindowSnapshot
+from jarvis.screen_context.ports import (
+ CapturePermissionIssue,
+ CaptureUnavailable,
+ WindowSnapshot,
+)
from jarvis.screen_context.service import (
ScreenContextService,
ScreenContextSettings,
@@ -183,6 +187,19 @@ async def test_a_plain_turn_captures_nothing() -> None:
assert capturer.grabs == [], "a normal turn must never touch the screen"
+async def test_a_desktop_operation_is_left_to_computer_use_without_a_capture() -> None:
+ capturer = FakeCapturer()
+ service = make_service(capturer=capturer)
+
+ outcome = await service.capture_for_turn(
+ "Klick den Knopf auf meinem Bildschirm", # i18n-allow: DE input
+ locale="de",
+ )
+
+ assert outcome.status == "not_requested"
+ assert capturer.grabs == []
+
+
async def test_an_ambiguous_turn_asks_and_does_not_capture() -> None:
capturer = FakeCapturer()
service = make_service(capturer=capturer)
@@ -285,6 +302,21 @@ async def test_native_capture_probes_run_off_the_asyncio_thread() -> None:
)
+async def test_wayland_permission_issue_keeps_its_platform_reason_code() -> None:
+ service = make_service(
+ permission_probe=lambda: CapturePermissionIssue(
+ code="wayland_portal",
+ message="A desktop portal is required in this Wayland session.",
+ )
+ )
+
+ outcome = await service.capture_for_turn("look at this", locale="en")
+
+ assert outcome.status == "refused"
+ assert outcome.reason_kind == "technical"
+ assert outcome.reason_code == "wayland_portal"
+
+
async def test_window_scoped_request_captures_the_window() -> None:
capturer = FakeCapturer()
service = make_service(capturer=capturer)
@@ -618,7 +650,10 @@ async def test_focus_change_during_shutter_discards_raw_frame() -> None:
)
capturer = FakeCapturer()
- service = make_service(window_probe=SwitchingWindowProbe(), capturer=capturer)
+ bus = RecordingBus()
+ service = make_service(
+ bus=bus, window_probe=SwitchingWindowProbe(), capturer=capturer
+ )
outcome = await service.capture_for_turn("look at this", locale="en")
@@ -626,6 +661,11 @@ async def test_focus_change_during_shutter_discards_raw_frame() -> None:
assert outcome.reason_kind == "policy"
assert len(capturer.grabs) == 1
assert service.held_count == 0
+ assert [type(event).__name__ for event in bus.events] == [
+ "ScreenCaptureAnnounced",
+ "ScreenCaptureGrabbed",
+ "ScreenCaptureIndicatorDismissed",
+ ]
async def test_new_denylisted_monitor_window_during_shutter_discards_frame() -> None:
@@ -726,6 +766,7 @@ async def test_the_capture_is_announced_before_the_shutter() -> None:
names = [type(e).__name__ for e in bus.events]
assert names == [
"ScreenCaptureAnnounced",
+ "ScreenCaptureGrabbed",
"ScreenCaptureCompleted",
"ScreenCaptureIndicatorDismissed",
]
@@ -746,6 +787,7 @@ async def test_capture_events_keep_the_turn_trace_id() -> None:
trace_id,
trace_id,
trace_id,
+ trace_id,
]
diff --git a/tests/unit/screen_context/test_turn.py b/tests/unit/screen_context/test_turn.py
index f7078d82da..ff2e14f969 100644
--- a/tests/unit/screen_context/test_turn.py
+++ b/tests/unit/screen_context/test_turn.py
@@ -1,12 +1,12 @@
"""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:
+The refused/unavailable split stays observable for diagnostics, while both
+outcomes shut alternate screen paths:
* 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.
+* letting a missing display fall through can turn a read-only look into
+ Computer-Use, which is a materially different action.
"""
from __future__ import annotations
@@ -104,17 +104,41 @@ async def test_privacy_refusal_ends_the_turn_and_shuts_other_paths() -> None:
)
-async def test_technical_unavailability_lets_the_turn_continue() -> None:
- """A headless host must answer normally, not refuse every look-request."""
+async def test_technical_unavailability_ends_without_an_action_fallback() -> None:
+ """A headless host must degrade honestly without starting Computer-Use."""
service = FakeService(
- outcome("refused", reason_kind="technical", message="No display available.")
+ outcome(
+ "refused",
+ reason_kind="technical",
+ reason_code="no_display",
+ 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"
+ assert result.ends_the_turn
+ assert result.blocks_other_screen_paths
+ assert "No desktop action" in (result.message or "")
+ assert result.reason_code == "no_display"
+ assert result.diagnostic_detail == "No display available."
+
+
+async def test_wayland_unavailability_returns_portal_remediation() -> None:
+ service = FakeService(
+ outcome(
+ "refused",
+ reason_kind="technical",
+ reason_code="wayland_portal",
+ message="portal missing",
+ )
+ )
+
+ result = await screen_context_for_turn("look at this", locale="en", service=service)
+
+ assert result.status == "unavailable"
+ assert "XDG desktop portal" in (result.message or "")
+ assert "No desktop action" in (result.message or "")
async def test_unexpected_capture_failure_shuts_other_screen_paths() -> None: