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(self-build): decide when the person is quiet in Dodaios, not when the computer is idle (#796)
Ruben Lütke18598631cb12
diff --git a/docs/self-build-code.md b/docs/self-build-code.mdindex c353d277d1..b015afbfb4 100644--- a/docs/self-build-code.md+++ b/docs/self-build-code.md@@ -64,7 +64,9 @@ call.## ExecutionA case in `building` runs only while the person is away from the computer-(no keyboard or mouse input and no typing in an IDE pane for 15 minutes) and a+(for 15 minutes: no keyboard or mouse input, no turn spoken or typed to+Dodaios, no open call and no typing into a pane's terminal in the app; a+prompt Jarvis or an agent writes into a pane is not the person) and asubscription coding CLI is free (`seat.py`): its plan login is signed in, itsown API-key variable is not set (the CLI would bill that key), it is not in ausage cooldown and no usage window is over 80 %. Otherwise the case waits, fordiff --git a/docs/self-build.md b/docs/self-build.mdindex af49d4b05e..17ae36eb65 100644--- a/docs/self-build.md+++ b/docs/self-build.md@@ -155,11 +155,14 @@ earlier builds failed their proof twice, an installed skill already catchesits requests, or `admit` refuses every candidate kind.**Decide.** After 90 seconds of quiet (or when a call ends), at most one model-call per need and four per day. Quiet means no new turn and, where the-computer can tell, no keyboard or mouse input and no typing in an IDE pane for-those 90 seconds (the same idle reading the code builder uses,-`self_build/code/idle.py`); while the person is busy the need waits and is-looked at again after the next quiet stretch. Without a signed-in subscription or a local+call per need and four per day. Quiet means the person is not in the middle+of talking to Dodaios: no turn of theirs (voice, chat, agent chat, a prompt+typed to a pane through the app), no typing into a pane's terminal in the app+and no open call for those 90 seconds (`core/presence.py`). The operating+system's input idle time is not asked: a person working in other programs+moves the mouse every second, and the decide call is light. While the person+talks to Dodaios the need waits and is looked at again after the next quiet+stretch, and it is decided at the latest 20 minutes after it was queued. Without a signed-in subscription or a localmodel the loop writes a plain card from the counts and builds nothing until amodel can write the spec. Calls are tagged `self_build:decide` in the costledger; build calls `self_build:<id>`.diff --git a/dodaios/core/presence.py b/dodaios/core/presence.pynew file mode 100644index 0000000000..5fc6b8420f--- /dev/null+++ b/dodaios/core/presence.py@@ -0,0 +1,84 @@+"""When the person last did something in Dodaios itself.++The operating system's input idle time says whether anyone is at the+computer; it cannot say whether the person is in the middle of talking to+Dodaios. Someone working all day in other programs moves the mouse every+second, and background work that waits for "no input for 90 seconds" would+never run. This module records the person's own activity in Dodaios instead:++* a turn the person spoke or typed (voice, the Jarvis chat, an agent chat, a+ prompt typed to a coding pane through the app), noted by whoever observes+ it (the self-building loop);+* keys the person typed into a pane's terminal in the app (the pane's own+ viewer, never a prompt Jarvis or an agent wrote into it);+* a voice call that is open: the person is talking to Dodaios until it ends.++Plain in-memory stamps, one dict write per event; nothing is stored.+"""++from __future__ import annotations++import threading+import time+from collections.abc import Iterable+from typing import Final++#: Sources this module knows. ``pane`` is typing in a pane's terminal.+TURN: Final[str] = "turn"+PANE: Final[str] = "pane"++_lock = threading.Lock()+_last: dict[str, float] = {}+_calls: set[str] = set()+++def note(source: str, *, at: float | None = None) -> None:+ """The person did something in Dodaios (``at``: epoch seconds, default now)."""+ stamp = time.time() if at is None else float(at)+ with _lock:+ if stamp > _last.get(source, 0.0):+ _last[source] = stamp+++def call_started(session_id: str) -> None:+ with _lock:+ _calls.add(session_id or "call")+++def call_ended(session_id: str) -> None:+ note(TURN)+ with _lock:+ _calls.discard(session_id or "call")+ if not session_id:+ _calls.clear()+++def in_call() -> bool:+ with _lock:+ return bool(_calls)+++def idle_s(*, sources: Iterable[str] | None = None, now: float | None = None) -> float | None:+ """Seconds since the person's last activity in Dodaios; ``0`` during a call.++ ``None`` when nothing was noted since the app started (and no call is open).+ ``sources`` limits the reading (e.g. ``[PANE]``); a call counts for every+ reading but a pane-only one.+ """+ wanted = None if sources is None else set(sources)+ with _lock:+ if _calls and (wanted is None or TURN in wanted):+ return 0.0+ stamps = [t for s, t in _last.items() if wanted is None or s in wanted]+ if not stamps:+ return None+ return max(0.0, (time.time() if now is None else now) - max(stamps))+++def reset_for_tests() -> None:+ with _lock:+ _last.clear()+ _calls.clear()+++__all__ = ["PANE", "TURN", "call_ended", "call_started", "idle_s", "in_call", "note"]diff --git a/dodaios/self_build/code/idle.py b/dodaios/self_build/code/idle.pyindex 6e7c26114e..79c74d2551 100644--- a/dodaios/self_build/code/idle.py+++ b/dodaios/self_build/code/idle.py@@ -16,7 +16,6 @@ from __future__ import annotationsimport shutilimport subprocessimport sys-import timefrom typing import Finalfrom loguru import logger@@ -78,26 +77,28 @@ def os_idle_s() -> float | None:def ide_idle_s(now: float | None = None) -> float | None:- """Seconds since a key was typed into any Agentic IDE pane, None without panes."""- try:- from dodaios.agentic_ide.session import get_registry-- stamps = [- float(term.last_input_at)- for session in get_registry().sessions- for term in getattr(session, "terminals", []) or []- if getattr(term, "last_input_at", None)- ]- except Exception: # noqa: BLE001 - no registry (tests, CLI) means no pane input- logger.opt(exception=True).debug("self-build code: pane activity unreadable")- return None- if not stamps:- return None- return (now if now is not None else time.time()) - max(stamps)+ """Seconds since the person typed into a pane's terminal in the app, None if never."""+ from dodaios.core import presence++ return presence.idle_s(sources=[presence.PANE], now=now)+++def dodaios_idle_s(now: float | None = None) -> float | None:+ """Seconds since the person's last turn in Dodaios (0 during a call), None if never."""+ from dodaios.core import presence++ return presence.idle_s(sources=[presence.TURN], now=now)def person_idle(after_s: float = IDLE_AFTER_S) -> bool:- for reading in (os_idle_s(), ide_idle_s()):+ """No input from the person for ``after_s``: OS input, a turn in Dodaios, pane typing.++ A coding run is heavy, so it waits until the person is not working at all.+ A prompt Jarvis or an agent wrote into a pane is not the person: the+ pane's ``last_input_at`` stamps those too, so it is not read here; the+ pane reading is the person's own typing in the app (``core/presence.py``).+ """+ for reading in (os_idle_s(), dodaios_idle_s(), ide_idle_s()):if reading is not None and reading < after_s:return Falsereturn Truediff --git a/dodaios/self_build/loop.py b/dodaios/self_build/loop.pyindex c47dffddd0..e0c9635aae 100644--- a/dodaios/self_build/loop.py+++ b/dodaios/self_build/loop.py@@ -17,10 +17,12 @@ Wiring (all event-driven; nothing here runs on a timer that wakes a model):learning (``society/learning.py``) and is left to it; a need that spansagents, or agents and the assistant, is the loop's, unless one of thoseagents already has a skill that serves it. Most needs stop here.-* **Decide.** Needs that pass wait until the person has been quiet for- :data:`QUIET_S`: no new turn, and no keyboard or mouse input and no typing- in an IDE pane for that long (the idle reading the code builder uses,- :func:`.code.idle.person_idle`), or until a call ends. Then they get at most+* **Decide.** Needs that pass wait until the person is not in the middle of+ talking to Dodaios: no turn of theirs, no typing into a pane and no open+ call for :data:`QUIET_S` (:mod:`dodaios.core.presence`; the operating+ system's input idle time is not asked, so work in other programs does not+ hold it up), or until a call ends, and never longer than+ :data:`MAX_WAIT_S` after the first need was queued. Then they get at mostone model call each on a subscription or local seat, :data:`DECIDE_PER_DAY`at most per day. With no such seat a plain proposal is written from thecounts instead.@@ -60,9 +62,12 @@ from .signals import SignalStore, TurnRowlog = logging.getLogger(__name__)_DAY_MS: Final[int] = 86_400_000-#: Needs are decided after this much quiet: never while the person is busy.-#: Quiet means no new turn AND no keyboard, mouse or pane input for this long.+#: Needs are decided after this much quiet: never in the middle of a conversation.+#: Quiet means no turn of the person, no pane typing and no open call for this long.QUIET_S: Final[float] = 90.0+#: A queued need is decided at the latest this long after it was queued, even+#: when the person keeps talking to Dodaios the whole time.+MAX_WAIT_S: Final[float] = 20 * 60.0#: Model calls the decide step may make per day, whatever crosses.DECIDE_PER_DAY: Final[int] = 4#: A "build nothing" verdict holds this long, unless the need doubles.@@ -94,7 +99,7 @@ class SelfBuildLoop:store: SignalStore,*,builders: Builders,- idle: Callable[[float], bool] | None = None,+ idle: Callable[[], float | None] | None = None,) -> None:self.service = serviceself.store = store@@ -107,8 +112,11 @@ class SelfBuildLoop:self._subscriptions: list[tuple[type[Any], Any]] = []self._bus: Any = Noneself._maintained = 0.0- #: ``idle(seconds) -> bool``: no input for that long (``code/idle.py``).- self._idle = idle if idle is not None else _person_idle+ #: ``idle() -> seconds | None``: since the person's last activity in+ #: Dodaios (``core/presence.py``); ``None`` when there was none.+ self._idle = idle if idle is not None else _dodaios_idle_s+ #: When the queue last went from empty to waiting (monotonic seconds).+ self._queued_at: float | None = None#: The last self-built skill that fired: ``(build id, ms, conversation)``;#: the conversation is filled in by the turn that fired it, so the#: person's NEXT turn there is the one judged for a correction.@@ -135,6 +143,7 @@ class SelfBuildLoop:TaskCompleted,TaskFailed,VoiceSessionEnded,+ VoiceSessionStarted,VoiceTurnCompleted,)from dodaios.skills.schema import SkillInvoked@@ -144,6 +153,7 @@ class SelfBuildLoop:self._bus = busfor event_type, handler in ((VoiceTurnCompleted, self._on_voice_turn),+ (VoiceSessionStarted, self._on_voice_started),(VoiceSessionEnded, self._on_voice_ended),(SkillInvoked, self._on_skill_invoked),(TaskCompleted, self._on_task_completed),@@ -216,7 +226,15 @@ class SelfBuildLoop:"observe",)- async def _on_voice_ended(self, _event: Any) -> None:+ async def _on_voice_started(self, event: Any) -> None:+ from dodaios.core import presence++ presence.call_started(str(getattr(event, "session_id", "") or ""))++ async def _on_voice_ended(self, event: Any) -> None:+ from dodaios.core import presence++ presence.call_ended(str(getattr(event, "session_id", "") or ""))# A call that ended is the quiet moment the decide step waits for.if self._queue:self._spawn(self.run_queue(), "decide")@@ -273,7 +291,13 @@ class SelfBuildLoop:async def observe(self, obs: Observation) -> None:"""File one turn, count its uses and queue the needs it completes."""- if not obs.text.strip() or not self._active():+ if not obs.text.strip():+ return+ from dodaios.core import presence++ # The person spoke or typed to Dodaios: background work waits for quiet.+ presence.note(presence.TURN, at=obs.ts_ms / 1000 if obs.ts_ms else None)+ if not self._active():returnfrom dodaios.memory.learning.signals import is_correctionfrom dodaios.society.memory_intent import requested_memory@@ -303,27 +327,42 @@ class SelfBuildLoop:self._spawn(self.maintain(), "maintain")def _arm(self) -> None:+ """Look again after :data:`QUIET_S`, never later than the queue's deadline."""if self._timer is not None:self._timer.cancel()+ self._timer = Nonetry:loop = asyncio.get_running_loop()except RuntimeError: # no loop: the queue waits for the next eventreturn- self._timer = loop.call_later(QUIET_S, lambda: self._spawn(self._when_quiet(), "decide"))+ now = time.monotonic()+ if self._queued_at is None:+ self._queued_at = now+ left = MAX_WAIT_S - (now - self._queued_at)+ delay = max(0.0, min(QUIET_S, left))+ self._timer = loop.call_later(delay, lambda: self._spawn(self._when_quiet(), "decide"))++ def _busy(self) -> bool:+ """The person is talking to Dodaios: a turn, pane typing or a call within QUIET_S."""+ try:+ idle = self._idle()+ except Exception: # noqa: BLE001 - an unreadable reading never blocks deciding+ log.debug("self_build: presence reading failed", exc_info=True)+ return False+ return idle is not None and idle < QUIET_Sasync def _when_quiet(self) -> None:- """No turn for :data:`QUIET_S`; decide only if the person is away from the input too."""+ """Decide once the person is quiet in Dodaios, or the queue waited :data:`MAX_WAIT_S`."""self._timer = Noneif not self._queue:+ self._queued_at = Nonereturn- try:- idle = await asyncio.to_thread(self._idle, QUIET_S)- except Exception: # noqa: BLE001 - an unreadable idle clock never blocks deciding- log.debug("self_build: idle reading failed", exc_info=True)- idle = True- if not idle:- self._arm() # still typing or pointing: look again after another quiet stretch+ waited = time.monotonic() - (self._queued_at or time.monotonic())+ if waited < MAX_WAIT_S and self._busy():+ self._arm() # mid-conversation: look again after another quiet stretchreturn+ if waited >= MAX_WAIT_S:+ log.info("self_build: deciding after %.0f s of waiting for quiet", waited)await self.run_queue()# ------------------------------------------------------------ gate@@ -386,6 +425,8 @@ class SelfBuildLoop:continueif record is not None:opened.append(record)+ if not self._queue:+ self._queued_at = Nonereturn openedasync def decide(self, need: Need) -> BuildRecord | None:@@ -796,10 +837,10 @@ def core_stems(need: Need) -> frozenset[str]:return frozenset(stem for stem, n in counts.items() if n >= half)-def _person_idle(seconds: float) -> bool:- from .code.idle import person_idle+def _dodaios_idle_s() -> float | None:+ from dodaios.core import presence- return person_idle(seconds)+ return presence.idle_s()def _fields(obs: Observation) -> dict[str, Any]:diff --git a/dodaios/ui/web/agentic_ide_routes.py b/dodaios/ui/web/agentic_ide_routes.pyindex ad085abe16..d94d54acf0 100644--- a/dodaios/ui/web/agentic_ide_routes.py+++ b/dodaios/ui/web/agentic_ide_routes.py@@ -148,6 +148,7 @@ from dodaios.agentic_ide.workspace_view import (WORKSPACE_VIEWS,view_from_legacy_chat_flag,)+from dodaios.core import presencefrom .control_auth import person_at_windowfrom .surface_security import credentials_valid, is_loopback_request@@ -5637,6 +5638,8 @@ async def agentic_pty(ws: WebSocket, name: str) -> None:)else:registry.write(term.key, data, pane_workspace)+ # The pane's own viewer: the person at the keyboard.+ presence.note(presence.PANE)elif kind == "r":# ``on_output`` identifies THIS socket. A pane open in two# places has two viewers and one pseudo-terminal, so a sizediff --git a/tests/unit/self_build/test_self_build_clock_idle.py b/tests/unit/self_build/test_self_build_clock_idle.pyindex 8dd1d952de..91513ff7d0 100644--- a/tests/unit/self_build/test_self_build_clock_idle.py+++ b/tests/unit/self_build/test_self_build_clock_idle.py@@ -1,7 +1,8 @@-"""The person's clock without a UI zone, and deciding only while the person is away."""+"""The person's clock without a UI zone, and deciding only while the person is quiet in Dodaios."""from __future__ import annotations+import asyncioimport loggingfrom datetime import UTC, datetimefrom pathlib import Path@@ -10,7 +11,7 @@ from zoneinfo import ZoneInfoimport pytest-from dodaios.self_build import Kind, State, clock+from dodaios.self_build import Kind, State, clock, loopfrom dodaios.self_build.miner import Miner, Observationfrom dodaios.self_build.signals import UNKNOWN_CLOCK, SignalStore@@ -128,39 +129,146 @@ async def test_a_routine_without_a_ui_zone_runs_on_the_computers(world: Any, monassert spec.trigger.timezone == "UTC"-# ------------------------------------------------------------------ idle+# ------------------------------------------------------------------ quiet: the person in Dodaios-async def test_decide_waits_while_the_person_is_at_the_keyboard(world: Any) -> None:+async def test_decide_waits_while_the_person_talks_to_dodaios(world: Any) -> None:world.brain.answers = [ROUTINE_ANSWER]- asked: list[float] = []-- def busy(seconds: float) -> bool:- asked.append(seconds)- return False-- world.loop._idle = busy+ readings: list[float | None] = [10.0]+ world.loop._idle = lambda: readings[0]await _weekly_sales(world)assert world.loop._queue # a need waitsawait world.loop._when_quiet()- assert asked == [90.0]assert world.brain.decide_calls == 0 and world.loop._queueassert world.loop._timer is not None # looks again after another quiet stretch- world.loop._idle = lambda _seconds: True+ readings[0] = 120.0 # quiet in Dodaios, whatever the mouse does elsewhereawait world.loop._when_quiet()await world.loop.drain()assert world.brain.decide_calls == 1 and not world.loop._queue+ assert world.loop._queued_at is Noneassert len(world.service.ledger.list(kinds=[Kind.ROUTINE])) == 1-async def test_an_unreadable_idle_clock_does_not_block_deciding(world: Any) -> None:+async def test_no_activity_seen_since_start_is_quiet(world: Any) -> None:+ world.brain.answers = [ROUTINE_ANSWER]+ world.loop._idle = lambda: None+ await _weekly_sales(world)+ await world.loop._when_quiet()+ assert world.brain.decide_calls == 1+++async def test_constant_activity_still_decides_within_the_hard_wait(+ world: Any, monkeypatch+) -> None:+ world.brain.answers = [ROUTINE_ANSWER]+ world.loop._idle = lambda: 0.0 # talking to Dodaios the whole time+ await _weekly_sales(world)+ clock_now = [loop.time.monotonic()]+ monkeypatch.setattr(loop.time, "monotonic", lambda: clock_now[0])+ world.loop._queued_at = clock_now[0]+ await world.loop._when_quiet()+ assert world.brain.decide_calls == 0+ # Re-armed, never later than the deadline.+ clock_now[0] += loop.MAX_WAIT_S - 30+ world.loop._arm()+ assert world.loop._timer is not None+ assert world.loop._timer.when() - asyncio.get_running_loop().time() <= 31+ clock_now[0] += 31+ await world.loop._when_quiet()+ assert world.brain.decide_calls == 1+++async def test_turns_keep_the_timer_short_of_the_deadline(world: Any, monkeypatch) -> None:+ clock_now = [1000.0]+ monkeypatch.setattr(loop.time, "monotonic", lambda: clock_now[0])+ world.loop._queue["x"] = object() # type: ignore[assignment]+ world.loop._queued_at = None+ world.loop._arm()+ assert world.loop._queued_at == 1000.0+ first = world.loop._timer.when() - asyncio.get_running_loop().time()+ assert 85 <= first <= 90.5+ clock_now[0] += loop.MAX_WAIT_S + 5 # every later turn re-arms; the deadline holds+ world.loop._arm()+ assert world.loop._timer.when() - asyncio.get_running_loop().time() <= 0.5+ world.loop._timer.cancel()+ world.loop._queue.clear()+++async def test_an_unreadable_presence_reading_does_not_block_deciding(world: Any) -> None:world.brain.answers = [ROUTINE_ANSWER]- def broken(_seconds: float) -> bool:- raise OSError("no input clock")+ def broken() -> float:+ raise OSError("no reading")world.loop._idle = brokenawait _weekly_sales(world)await world.loop._when_quiet()assert world.brain.decide_calls == 1+++async def test_turns_and_calls_mark_the_person_present(world: Any) -> None:+ from types import SimpleNamespace++ from dodaios.core import presence++ presence.reset_for_tests()+ assert presence.idle_s() is None+ await _weekly_sales(world) # old turns: not "just now"+ assert presence.idle_s() > loop.QUIET_S+ await world.loop._on_voice_started(SimpleNamespace(session_id="s1"))+ assert presence.idle_s() == 0.0 # an open call is talking to Dodaios+ world.loop._idle = loop._dodaios_idle_s+ assert world.loop._busy()+ await world.loop._on_voice_ended(SimpleNamespace(session_id="s1"))+ assert not presence.in_call() and presence.idle_s() < 5+ presence.reset_for_tests()+++def test_presence_readings() -> None:+ from dodaios.core import presence++ presence.reset_for_tests()+ presence.note(presence.PANE, at=100.0)+ presence.note(presence.TURN, at=50.0)+ presence.note(presence.TURN, at=40.0) # older stamps never move it back+ assert presence.idle_s(now=160.0) == 60.0+ assert presence.idle_s(sources=[presence.TURN], now=160.0) == 110.0+ assert presence.idle_s(sources=[presence.PANE], now=160.0) == 60.0+ presence.call_started("c")+ assert presence.idle_s(sources=[presence.TURN]) == 0.0+ assert presence.idle_s(sources=[presence.PANE], now=160.0) == 60.0 # a call is not typing+ presence.call_ended("c")+ assert not presence.in_call()+ presence.reset_for_tests()+++# ------------------------------------------------------------------ the code builder's idle+++def test_the_code_builder_waits_for_the_person_not_for_agent_prompts(monkeypatch) -> None:+ from types import SimpleNamespace++ from dodaios.core import presence+ from dodaios.self_build.code import idle++ presence.reset_for_tests()+ monkeypatch.setattr(idle, "os_idle_s", lambda: None) # headless: no OS reading+ # Jarvis typed a brief into a pane a second ago: that stamps last_input_at,+ # but it is not the person at the keyboard.+ term = SimpleNamespace(last_input_at=loop.time.time())+ registry = SimpleNamespace(sessions=[SimpleNamespace(terminals=[term])])+ from dodaios.agentic_ide import session as ide_session++ monkeypatch.setattr(ide_session, "get_registry", lambda: registry)+ assert idle.person_idle(60)+ presence.note(presence.PANE) # the person typed in a pane's terminal+ assert not idle.person_idle(60)+ presence.reset_for_tests()+ presence.note(presence.TURN) # the person spoke to Dodaios+ assert not idle.person_idle(60)+ presence.reset_for_tests()+ monkeypatch.setattr(idle, "os_idle_s", lambda: 3.0) # someone at the keyboard elsewhere+ assert not idle.person_idle(60)+ monkeypatch.setattr(idle, "os_idle_s", lambda: 3600.0)+ assert idle.person_idle(60)