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(agentic-ide): reap compose()'s background tasks on any early exit
rubenluetke10-beepe38eafe7cdf7
diff --git a/jarvis/agentic_ide/prompt_composer.py b/jarvis/agentic_ide/prompt_composer.pyindex b849839152..52e436106e 100644--- a/jarvis/agentic_ide/prompt_composer.py+++ b/jarvis/agentic_ide/prompt_composer.py@@ -835,7 +835,16 @@ async def compose(asyncio.create_task(asyncio.to_thread(_resolve_writer)) if brain is None else None)- candidates = await asyncio.to_thread(_file_candidates, session, subject, max_files * 2)+ try:+ candidates = await asyncio.to_thread(_file_candidates, session, subject, max_files * 2)+ except BaseException:+ # Cancelled — or broken — before the writer probe was consumed. The+ # probe task is OURS: abandoned here it would run on unobserved and+ # complain at teardown. Today's callers shield this whole call, but+ # that is their defence, not a property of this function.+ if writer_task is not None:+ _discard(writer_task)+ raisedef degrade(note: str) -> ComposedPrompt:notify(STAGE_FALLBACK, f"{terminal_name} gets the plain brief instead: {note}.")@@ -845,9 +854,16 @@ async def compose(# subscription CLI the probe is the longer of the two.context_task = asyncio.create_task(_read_context(session, candidates))- writer, writer_source = (- (brain, "") if writer_task is None else await _resolved_writer(writer_task)- )+ try:+ writer, writer_source = (+ (brain, "") if writer_task is None else await _resolved_writer(writer_task)+ )+ except BaseException:+ # Same property one step later: cancelling the wait on the writer+ # probe reaps the probe itself (we are awaiting it), but the context+ # read is a sibling task nobody else knows about.+ _discard(context_task)+ raiseif writer is None:# An unhonourable PIN still degrades here rather than quietly landing on# a provider the user did not choose: plain and honest beats polished@@ -987,10 +1003,11 @@ async def compose(STAGE_RETRY,_retry_message(terminal_name, reason=reason, writer=_writer_label(nxt)),)- except asyncio.CancelledError:- # The caller died mid-composition (voice hangup, dropped client). The- # attempt tasks are OURS — without this they would keep spending- # providers on a brief nobody can deliver.+ except BaseException:+ # The caller died mid-composition (voice hangup, dropped client), or+ # something unforeseen escaped the loop. Either way the attempt tasks+ # are OURS — without this they would keep spending providers on a+ # brief nobody can deliver._cancel_attempts()_discard(context_task)raisediff --git a/jarvis/agentic_ide/writer.py b/jarvis/agentic_ide/writer.pyindex d09b2ec648..8f88d0a08c 100644--- a/jarvis/agentic_ide/writer.py+++ b/jarvis/agentic_ide/writer.py@@ -65,6 +65,13 @@ _cache_lock = threading.Lock()#: Deliberately NOT the resolver's shared ``(provider, model)`` cache: these are#: structured-prompt instances, and parking one where a voice tier could pick it#: up is the exact leak ``resolve_subscription_brain`` documents against.+#:+#: A SINGLE slot, on purpose. Every production caller passes the same+#: ``COMPOSE_TIMEOUT_S`` budget, so one slot answers all of them; a second call+#: site with a different budget would make the two alternate on the slot and+#: mostly miss. If that caller ever appears, key this by budget instead.+#: Concurrent misses are also not coalesced — each pays the full resolution and+#: the last one wins the slot, which is wasteful but never wrong._cached: tuple[float, float | None, Any, str] | None = Nonediff --git a/jarvis/plugins/brain/claude_cli.py b/jarvis/plugins/brain/claude_cli.pyindex 097710a2d9..ee57b71654 100644--- a/jarvis/plugins/brain/claude_cli.py+++ b/jarvis/plugins/brain/claude_cli.py@@ -103,6 +103,12 @@ _CONVO_TURNS = 6# may be older than these flags — an unknown option makes the CLI exit with an# error instead of an answer, which would turn a speed-up into a broken writer# (§3: any CLI version keeps working).+#+# The probe below is a SYNTAX check, not a semantics one: ``--tools ""`` also+# assumes the empty value stays the documented "disable all" spelling. If a+# future CLI keeps the flag but stops accepting "", the turn ends as a usage+# error on stdout — which the empty-answer path already reports and the+# composer's rescue chain absorbs, so the worst case is one wasted rung._FAST_STRUCTURED_ARGS: tuple[tuple[str, tuple[str, ...]], ...] = (("--tools", ("--tools", "")), # no built-in tools at all — writing only("--strict-mcp-config", ("--strict-mcp-config",)), # no MCP serversdiff --git a/tests/unit/agentic_ide/test_composer_hedge.py b/tests/unit/agentic_ide/test_composer_hedge.pyindex e8cbd06de0..7ef6581059 100644--- a/tests/unit/agentic_ide/test_composer_hedge.py+++ b/tests/unit/agentic_ide/test_composer_hedge.py@@ -7,6 +7,7 @@ old loop was not allowed to start anyone else until that call ended or thewhole budget was gone. After ``HEDGE_AFTER_S`` the next rung now writesALONGSIDE the first, and the first valid brief wins."""+from __future__ import annotationsimport asyncio@@ -136,9 +137,7 @@ async def test_no_hedge_fires_while_the_writer_is_healthy(async def _compose(**_kwargs: object) -> str:return BRIEF- monkeypatch.setattr(- prompt_composer, "_resolve_writer", lambda: (_Writer("prompt"), "api")- )+ monkeypatch.setattr(prompt_composer, "_resolve_writer", lambda: (_Writer("prompt"), "api"))monkeypatch.setattr(prompt_composer,"_rescue_writer",@@ -188,6 +187,96 @@ async def test_a_pinned_brain_is_never_hedged(assert result.composed_by == "fallback"+async def test_cancelling_compose_reaps_every_background_task(+ workspace: _Session, monkeypatch: pytest.MonkeyPatch+) -> None:+ """The attempt tasks and the context read are compose()'s own children.++ Today's callers shield the whole call, so a hangup never cancels compose+ mid-flight — but that is their defence. A future unshielded caller must+ not leak a running provider call and a pending disk read into the loop.+ """+ entered = asyncio.Event()+ reaped = asyncio.Event()++ async def _hang_compose(**_kwargs: object) -> str:+ entered.set()+ try:+ await asyncio.Event().wait()+ except asyncio.CancelledError:+ reaped.set()+ raise+ return BRIEF++ monkeypatch.setattr(prompt_composer, "_resolve_writer", lambda: (_Writer("w"), "api"))+ monkeypatch.setattr(prompt_composer, "_rescue_writer", lambda tried: (None, ""))+ monkeypatch.setattr(prompt_composer, "_llm_compose", _hang_compose)++ work = asyncio.create_task(+ prompt_composer.compose("make the wake path faster", session=workspace, terminal_name="Kai")+ )+ await entered.wait()+ work.cancel()+ with pytest.raises(asyncio.CancelledError):+ await work+ await asyncio.wait_for(reaped.wait(), timeout=2.0)++ # Nothing of compose()'s survives it: no attempt task, no context read.+ for _ in range(20):+ pending = [+ task+ for task in asyncio.all_tasks()+ if task is not asyncio.current_task() and not task.done()+ ]+ if not pending:+ break+ await asyncio.sleep(0.05)+ assert not pending+++async def test_cancelling_compose_mid_resolution_reaps_the_context_read(+ workspace: _Session, monkeypatch: pytest.MonkeyPatch+) -> None:+ """The window BEFORE any attempt exists: the writer probe is still being+ awaited and the context read runs as a sibling task nobody else knows."""+ import threading++ hold = threading.Event()+ ctx_entered = asyncio.Event()+ ctx_reaped = asyncio.Event()++ async def _hanging_context(session: object, candidates: object) -> object:+ ctx_entered.set()+ try:+ await asyncio.Event().wait()+ except asyncio.CancelledError:+ ctx_reaped.set()+ raise+ return {}, ""++ def _slow_resolve() -> tuple[object, str]:+ hold.wait(timeout=5.0)+ return (_Writer("w"), "api")++ monkeypatch.setattr(prompt_composer, "_read_context", _hanging_context)+ monkeypatch.setattr(prompt_composer, "_resolve_writer", _slow_resolve)+ monkeypatch.setattr(+ prompt_composer,+ "_llm_compose",+ lambda **_kwargs: pytest.fail("no attempt may start"),+ )++ work = asyncio.create_task(+ prompt_composer.compose("make the wake path faster", session=workspace, terminal_name="Kai")+ )+ await ctx_entered.wait()+ work.cancel()+ hold.set() # let the probe thread finish so the cancellation lands+ with pytest.raises(asyncio.CancelledError):+ await work+ await asyncio.wait_for(ctx_reaped.wait(), timeout=2.0)++async def test_the_hedge_respects_the_shared_budget(workspace: _Session, monkeypatch: pytest.MonkeyPatch) -> None: