Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(voice): preserve delayed computer results and honest provider status (#453)
Ruben Lütke39b507305060
diff --git a/jarvis/live/native.py b/jarvis/live/native.pyindex 7477af6697..1228dd9315 100644--- a/jarvis/live/native.py+++ b/jarvis/live/native.py@@ -109,6 +109,11 @@ def _log_late_probe(task: asyncio.Future) -> None:class NativeLiveVoiceSession(LiveVoiceSession):"""Reuse native turn mechanics, without the legacy heuristic delegate loop."""+ def __init__(self, **kwargs: Any) -> None:+ super().__init__(**kwargs)+ self._late_tool_results: list[tuple[int, int, str, dict]] = []+ self._native_turn_complete = True+async def _start(self, message: dict) -> None:self._adopt_desktop_session()gateway = get_supervisor_tool_gateway()@@ -402,7 +407,8 @@ class NativeLiveVoiceSession(LiveVoiceSession):event = await anext(events)except asyncio.CancelledError:raise- except Exception: # Shutdown is quiet; active failures enter the reporting recovery loop.+ except Exception:+ # Shutdown is quiet; active failures enter the recovery loop.if self._closing:returnif await self._wait_for_connection():@@ -427,6 +433,10 @@ class NativeLiveVoiceSession(LiveVoiceSession):async def _native_event(self, event: Any) -> None:assert self._tools is not None and self._ledger is not None+ if event.type in {+ "audio_delta", "input_transcript", "output_transcript_delta", "tool_call",+ }:+ self._native_turn_complete = Falseif event.type == "audio_delta" and event.audio is not None:self._report_started()await self._note_speaking()@@ -513,9 +523,11 @@ class NativeLiveVoiceSession(LiveVoiceSession):await self._interrupt_reply()await self._emit_indicator({"type": "tts_cancel"})elif event.type == "turn_complete":+ self._native_turn_complete = Trueself._report_finished(delivered=True)self._transcript.finish("assistant")await self._note_turn_end()+ self._notify_pause()elif event.type == "usage":usage = event.usage or {}await asyncio.to_thread(@@ -571,19 +583,12 @@ class NativeLiveVoiceSession(LiveVoiceSession):work.cancel() # cancelling the call still cancels its tool, as beforeraiseexcept TimeoutError: # a slow tool is released, not dropped- result = self._release_slow_tool(work, str(event.tool_name or ""))- images = take_images(result)+ self._native_turn_complete = False # The pending answer starts another response.+ result = self._release_slow_tool(work, str(event.tool_name or ""), revision)if self._closing:return- send_image = getattr(self._connection, "send_image", None)- if images and not callable(send_image):- result = {- "success": False,- "error": "This voice server cannot receive screen images.",- }- if callable(send_image):- for image in images:- await send_image(base64.b64decode(image["data"]), image["mime"])+ result = await self._send_tool_images(result)+ self._native_turn_complete = Falseawait self._connection.send_tool_result(event.call_id, event.tool_name, result)if self._tools.end_requested:asyncio.create_task(self.end(reason="voice_pattern"), name="native-live-hangup")@@ -592,9 +597,94 @@ class NativeLiveVoiceSession(LiveVoiceSession):except Exception:log.exception("Native tool call failed; receipt retained")- def _release_slow_tool(self, work: asyncio.Future, name: str) -> dict:+ async def _send_tool_images(self, result: dict) -> dict:+ """Keep the execution receipt even when its visual evidence cannot be delivered."""+ images = take_images(result)+ if not images:+ return result+ send_image = getattr(self._connection, "send_image", None)+ try:+ if not callable(send_image):+ raise RuntimeError("This voice server cannot receive screen images.")+ for image in images:+ await send_image(base64.b64decode(image["data"]), image["mime"])+ except Exception:+ log.warning("Native tool screenshot delivery failed", exc_info=True)+ return {+ **result,+ "success": False,+ "verified": False,+ "error": (+ str(result.get("error") or "") + " The tool's screenshot could not be "+ "delivered. Its execution receipt is preserved below; an action may "+ "already have run. Do not claim visual success or repeat that action "+ "without checking the current screen."+ ).strip(),+ }+ return result++ def _notify_pause(self) -> None:+ # The original function call already received its pending answer. Its+ # final receipt is a new report at a pause, never a second function+ # response and never a repeated action. A changed request/connection+ # invalidates the queued report; the durable ledger still keeps it.+ if self._native_turn_complete and not self._has_pending_work():+ self._thinking = False+ if self._tools is not None:+ self._late_tool_results = [+ item for item in self._late_tool_results+ if item[0] == self._wire_epoch and item[1] == self._tools.revision+ and not self._tools.cancel_token.is_cancelled()+ ]+ if self._late_tool_results and self.ready_for_report:+ item = self._late_tool_results.pop(0)+ self._report_sent() # Reserve the pause before any asynchronous send.+ task = asyncio.create_task(self._report_late_tool(item), name="native-tool-report")+ self._control_tasks.add(task)+ task.add_done_callback(self._control_tasks.discard)+ return+ super()._notify_pause()++ async def _report_late_tool(self, item: tuple[int, int, str, dict]) -> None:+ from jarvis.realtime.report_prompt import report_update_prompt++ epoch, revision, name, result = item+ try:+ if not self._late_tool_current(epoch, revision):+ self._cancel_report_timeout()+ self._report_state = ""+ return+ result = await self._send_tool_images(result)+ if not self._late_tool_current(epoch, revision):+ self._cancel_report_timeout()+ self._report_state = ""+ return+ await self._connection.send_text(report_update_prompt(+ f"The previously pending tool {name} has finished.",+ json.dumps(result, ensure_ascii=False, default=str),+ language=self._language,+ kind="tool_completion",+ ))+ except asyncio.CancelledError:+ raise+ except Exception:+ # Delivery may be uncertain. Keep the durable receipt, but never+ # retry an action or automatically repeat a partially sent report.+ self._cancel_report_timeout()+ self._report_state = ""+ log.warning("Late native tool report could not be delivered", exc_info=True)++ def _late_tool_current(self, epoch: int, revision: int) -> bool:+ return bool(+ self.is_active and not self._recovering and not self._input_active+ and epoch == self._wire_epoch and self._tools is not None+ and revision == self._tools.revision and not self._tools.cancel_token.is_cancelled()+ )++ def _release_slow_tool(self, work: asyncio.Future, name: str, revision: int) -> dict:"""Answer the model honestly while the tool runs on in the background."""started = time.monotonic()+ epoch = self._wire_epochlog.warning("Native tool %s still running after %.0fs; releasing the live model with a ""pending result, the tool finishes in the background",@@ -619,6 +709,14 @@ class NativeLiveVoiceSession(LiveVoiceSession):waited_ms,bool(isinstance(outcome, dict) and outcome.get("success")),)+ if isinstance(outcome, dict) and not self._closing:+ self._late_tool_results.append((epoch, revision, name, outcome))+ if len(self._late_tool_results) > 16:+ self._late_tool_results.pop(0)+ log.warning(+ "Late native tool report queue full; oldest receipt stays in ledger"+ )+ self._notify_pause()work.add_done_callback(_late)return {@@ -636,6 +734,7 @@ class NativeLiveVoiceSession(LiveVoiceSession):if self._closing:returnif message.get("type") == "text_input" and self._connection is not None:+ self._native_turn_complete = Falseif self._tools is not None:self._tools.user_text = str(message.get("text", ""))self._tools.revision += 1@@ -702,6 +801,7 @@ class NativeLiveVoiceSession(LiveVoiceSession):self._stop_watching_input_mute()self._clear_media_levels()self._closing = True+ self._late_tool_results.clear()await self._publish_phase("idle")self._hangup_reason = reasonunregister(self.session_id)diff --git a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsx b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsxindex d45c19d7c4..331940fb4b 100644--- a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsx+++ b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsx@@ -20,6 +20,7 @@ import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-libraimport {PROVIDER_STATE_CHIPS,ProviderCard,+ providerStateChip,managedRuntimeBadge,type ProviderStateChip,} from "@/components/providers/ProviderTierSection";@@ -177,6 +178,34 @@ function polishPin(calls: Call[]): Record<string, unknown> {return JSON.parse(put!.body ?? "{}") as Record<string, unknown>;}+describe("ProviderCard selected without credentials", () => {+ afterEach(cleanup);++ it.each(["gemini", "openai", "claude-api"])("shows missing credentials for selected %s", (id) => {+ const calls = installFetchMock();+ useI18nStore.getState().setUi("en", { push: false });+ const descriptor = dictationCard({+ id, label: id, tier: "brain", active: true, configured: false,+ secret_keys: [], secrets_set: {},+ });+ renderCard(descriptor);+ expect((screen.getByRole("radio") as HTMLInputElement).checked).toBe(true);+ expect(screen.getByText(chipLabel("no_key"))).toBeTruthy();+ expect(screen.queryByText(enLocale.apikeys_view.provider_active)).toBeNull();+ expect(providerStateChip(descriptor, "ok")).toBe("no_key");+ expect(calls.some(call => call.method === "POST")).toBe(false);+ });++ it("shows a disconnected subscription despite its saved selection", () => {+ installFetchMock();+ useI18nStore.getState().setUi("en", { push: false });+ const descriptor = codexRealtimeCard({ active: true, configured: false });+ renderCard(descriptor);+ expect(screen.getByText(chipLabel("not_connected"))).toBeTruthy();+ expect(screen.queryByText(enLocale.apikeys_view.provider_active)).toBeNull();+ });+});+describe("ProviderCard — dictation polish activation", () => {beforeEach(() => {window.localStorage.clear();diff --git a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsxindex 0af1bb323f..7b7b4d384b 100644--- a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx+++ b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx@@ -824,7 +824,9 @@ export function ProviderCard({// assistive tech, and the billing line already says how you sign in.const summary = t(`provider_billing.${billingOverride ?? descriptor.billing}`);const collapsible = Boolean(onToggleExpanded);- const rowTitle = descriptor.active+ const rowTitle = descriptor.active && !descriptor.configured+ ? t("apikeys_view.needs_credentials")+ : descriptor.active? t("apikeys_view.active_tooltip"): !isBrainSwitchable? t("apikeys_view.agents_only_short").replace("{0}", agentsBrand(assistantName))@@ -1258,7 +1260,9 @@ export function ActiveControl({disabledReason?: string;}) {const t = useT();- const labelTitle = descriptor.active+ const labelTitle = descriptor.active && !descriptor.configured+ ? t("apikeys_view.needs_credentials")+ : descriptor.active? t("apikeys_view.activate_tooltip_active"): disabled? disabledReason ?? t("apikeys_view.activate_tooltip_blocked")@@ -1314,7 +1318,9 @@ export function ActiveControl({{activating? t("apikeys_view.provider_activating"): descriptor.active- ? t("apikeys_view.provider_active")+ ? descriptor.configured+ ? t("apikeys_view.provider_active")+ : t(PROVIDER_STATE_CHIPS[providerStateChip(descriptor)].key): t("apikeys_view.provider_set_active")}</label>);@@ -3802,7 +3808,8 @@ export function providerStateChip(descriptor: ProviderDescriptor,verification: Verification = null,): ProviderStateChip {- if (descriptor.active) return "active";+ // Selection alone proves neither a saved key nor a connected account.+ if (descriptor.active && descriptor.configured) return "active";if (descriptor.auth_mode === "codex") {const status = descriptor.codex_status;// Transient: the status is being probed right now. Neither "missing" nor@@ -3824,7 +3831,7 @@ export function providerStateChip(// A live verdict outranks everything below: the provider was asked and// answered (or did not).if (verification === "failed") return "not_working";- if (verification === "ok") return "ready";+ if (verification === "ok" && descriptor.configured) return "ready";// On-device engine: the server's on-disk probe is the verdict.if (descriptor.local_runtime) {return descriptor.local_runtime.ready ? "ready" : "not_installed";diff --git a/tests/fakes/fake_native_voice.py b/tests/fakes/fake_native_voice.pyindex 73bcc5f180..ac773a1ff7 100644--- a/tests/fakes/fake_native_voice.py+++ b/tests/fakes/fake_native_voice.py@@ -54,6 +54,9 @@ class FakeNativeConnection:async def send_text(self, text: str) -> None:self.calls.append(("send_text", text))+ async def send_image(self, image: bytes, mime: str) -> None:+ self.calls.append(("send_image", (image, mime)))+async def update_session(self, **changes: Any) -> None:self.calls.append(("update_session", changes))@@ -162,6 +165,8 @@ class FakeToolGateway:self.gates: dict[str, asyncio.Event] = {}self.calls: list[tuple[str, dict[str, Any]]] = []self.finished: list[str] = []+ self.results: dict[str, ToolResult] = {}+ self.execution_started = asyncio.Event()def catalog(self) -> tuple[SupervisorToolDescriptor, ...]:return self._descriptors@@ -174,11 +179,12 @@ class FakeToolGateway:async def execute(self, name: str, arguments: dict[str, Any], request: Any) -> ToolResult:del requestself.calls.append((name, arguments))+ self.execution_started.set()gate = self.gates.get(name)if gate is not None:await gate.wait()self.finished.append(name)- return ToolResult(True, {"verified": True})+ return self.results.get(name, ToolResult(True, {"verified": True}))async def execute_confirmed(self, trace: Any, request: Any) -> ToolResult:del trace, requestdiff --git a/tests/unit/live/test_native_live_fixes.py b/tests/unit/live/test_native_live_fixes.pyindex cb4cf13d22..b1c3d49a8b 100644--- a/tests/unit/live/test_native_live_fixes.py+++ b/tests/unit/live/test_native_live_fixes.py@@ -13,6 +13,8 @@ from types import SimpleNamespaceimport pytest+from jarvis.core.protocols import SupervisorToolDescriptor, ToolResult+from jarvis.cu.direct import tool_schemafrom jarvis.live import native, runtimefrom jarvis.live.native import NativeLiveVoiceSessionfrom jarvis.live.state import LiveLedger@@ -338,6 +340,202 @@ async def test_fast_tool_answers_with_its_real_result(tmp_path, monkeypatch, maksession._ledger.close()+def _screen_gateway(*, success=True):+ gateway = FakeToolGateway((+ SupervisorToolDescriptor("computer", "Operate the screen", tool_schema(), "monitor"),+ ))+ gateway.results["computer"] = ToolResult(+ success,+ {"executed": ["click at (20,30)"] if success else [],+ "frame": {"frame_id": "fresh-frame"},+ "_image": {"mime": "image/jpeg", "data": "ZnJlc2gtc2NyZWVu"}},+ None if success else "The foreground window changed; nothing was pressed.",+ )+ return gateway+++def _screen_call():+ return RealtimeEvent(type="tool_call", call_id="screen-call", tool_name="computer",+ tool_args={"steps": [{"action": "screenshot"}]})+++@both_providers[email protected]("entry", ["speech", "text"])+async def test_new_user_input_does_not_open_a_report_pause_during_reasoning(+ tmp_path, make_provider, entry,+):+ session, _, _ = _in_call(make_provider(), tmp_path)+ try:+ await session._native_event(RealtimeEvent(type="turn_complete"))+ if entry == "speech":+ await session._native_event(RealtimeEvent(+ type="input_transcript", text="Check the current screen", is_final=True,+ ))+ else:+ await session.handle_control({"type": "text_input", "text": "Check the screen"})+ await session._note_thinking()+ session._notify_pause()+ assert not session.ready_for_report+ await _settle(session)+ finally:+ session._ledger.close()+++@both_providers[email protected]("success", [True, False])+async def test_late_computer_receipt_and_image_reach_the_model_at_a_pause(+ tmp_path, monkeypatch, make_provider, success,+):+ monkeypatch.setattr(native, "_TOOL_DEADLINE_S", 0.01)+ gateway = _screen_gateway(success=success)+ release = gateway.hold("computer")+ session, connection, _ = _in_call(make_provider(), tmp_path, gateway=gateway)+ try:+ await session._native_event(_screen_call())+ await asyncio.wait_for(connection.tool_result_sent.wait(), _HANG_GUARD_S)+ assert connection.tool_results[0][2]["pending"] is True+ # The pending spoken answer must finish before its final result interrupts it.+ release.set()+ await asyncio.wait_for(asyncio.gather(*session._jobs), _HANG_GUARD_S)+ assert "send_image" not in connection.names()+ assert "send_text" not in connection.names()+ await session._native_event(RealtimeEvent(type="turn_complete"))+ await _settle(session)+ assert connection.names()[-2:] == ["send_image", "send_text"]+ report = connection.calls[-1][1]+ assert '"success": ' + str(success).lower() in report+ assert "fresh-frame" in report+ assert ("click at (20,30)" if success else "nothing was pressed") in report+ assert gateway.calls == [("computer", {"steps": [{"action": "screenshot"}]})]+ assert len(connection.tool_results) == 1 # No duplicate function response.+ session._notify_pause()+ await _settle(session)+ assert connection.names().count("send_text") == 1+ finally:+ session._cancel_report_timeout()+ session._ledger.close()+++@both_providers+async def test_computer_finishing_after_pending_speech_wakes_its_report(+ tmp_path, monkeypatch, make_provider,+):+ monkeypatch.setattr(native, "_TOOL_DEADLINE_S", 0.01)+ gateway = _screen_gateway()+ release = gateway.hold("computer")+ session, connection, _ = _in_call(make_provider(), tmp_path, gateway=gateway)+ try:+ await session._native_event(_screen_call())+ await asyncio.wait_for(connection.tool_result_sent.wait(), _HANG_GUARD_S)+ await session._native_event(RealtimeEvent(type="turn_complete"))+ session._input_active = True+ release.set()+ await asyncio.wait_for(asyncio.gather(*session._jobs), _HANG_GUARD_S)+ await _settle(session)+ assert "send_text" not in connection.names() # The person is speaking.+ session._input_active = False+ session._notify_pause()+ await _settle(session)+ assert connection.names().count("send_text") == 1+ finally:+ session._cancel_report_timeout()+ session._ledger.close()+++@both_providers+async def test_late_computer_report_waits_for_other_pending_work(+ tmp_path, monkeypatch, make_provider,+):+ monkeypatch.setattr(native, "_TOOL_DEADLINE_S", 0.01)+ gateway = _screen_gateway()+ release = gateway.hold("computer")+ session, connection, _ = _in_call(make_provider(), tmp_path, gateway=gateway)+ other_done = asyncio.Event()+ other = asyncio.create_task(other_done.wait())+ session._track_job(other)+ try:+ await session._call(_screen_call(), 0)+ await session._native_event(RealtimeEvent(type="turn_complete"))+ work = tuple(job for job in session._jobs if job is not other)+ release.set()+ await asyncio.wait_for(asyncio.gather(*work), _HANG_GUARD_S)+ assert "send_text" not in connection.names()+ other_done.set()+ await other+ await _settle(session)+ assert connection.names().count("send_text") == 1+ finally:+ other.cancel()+ await asyncio.gather(other, return_exceptions=True)+ session._cancel_report_timeout()+ session._ledger.close()+++@both_providers[email protected]("change", ["request", "connection", "stop", "close"])+async def test_late_computer_never_revives_an_obsolete_request(+ tmp_path, monkeypatch, make_provider, change,+):+ monkeypatch.setattr(native, "_TOOL_DEADLINE_S", 0.01)+ gateway = _screen_gateway()+ release = gateway.hold("computer")+ session, connection, _ = _in_call(make_provider(), tmp_path, gateway=gateway)+ try:+ await session._native_event(_screen_call())+ await asyncio.wait_for(connection.tool_result_sent.wait(), _HANG_GUARD_S)+ # Receipt I/O can outlive the short deadline on a loaded host. This+ # case stops an action already running, not one still being claimed.+ await asyncio.wait_for(gateway.execution_started.wait(), _HANG_GUARD_S)+ await session._native_event(RealtimeEvent(type="turn_complete"))+ if change == "request":+ session._tools.revision += 1+ elif change == "connection":+ session._wire_epoch += 1+ elif change == "stop":+ session._tools.cancel_token.cancel("escape")+ else:+ session._closing = True+ release.set()+ await asyncio.wait_for(asyncio.gather(*session._jobs), _HANG_GUARD_S)+ await _settle(session)+ assert "send_image" not in connection.names()+ assert "send_text" not in connection.names()+ assert gateway.finished == ["computer"]+ assert session._ledger.operation("native-live", "0:screen-call")["success"] is True+ finally:+ session._cancel_report_timeout()+ session._ledger.close()+++@both_providers[email protected]("image_support", ["missing", "fails"])+async def test_image_delivery_failure_still_answers_with_the_execution_receipt(+ tmp_path, monkeypatch, make_provider, image_support,+):+ monkeypatch.setattr(native, "_TOOL_DEADLINE_S", _HANG_GUARD_S)+ session, connection, _ = _in_call(make_provider(), tmp_path, gateway=_screen_gateway())++ async def failed_image(*_args):+ raise OSError("Image transport failed")++ connection.send_image = None if image_support == "missing" else failed_image+ try:+ await session._call(_screen_call(), 0)+ assert len(connection.tool_results) == 1+ result = connection.tool_results[0][2]+ assert result["success"] is False and result["verified"] is False+ assert result["output"]["executed"] == ["click at (20,30)"]+ assert "Do not claim visual success" in result["error"]+ finally:+ session._ledger.close()++# 5. Declaration budget -------------------------------------------------------------