The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(bot-desktop): the idle stop of an abandoned human lease releases that lease
kshitijk4poord4046152960a
diff --git a/tests/tools/test_bot_desktop_idle.py b/tests/tools/test_bot_desktop_idle.pyindex 61366e15f1f..157d845e8ef 100644--- a/tests/tools/test_bot_desktop_idle.py+++ b/tests/tools/test_bot_desktop_idle.py@@ -3,6 +3,7 @@ one a human holds or that saw recent use is not."""from __future__ import annotations+import loggingimport osimport shleximport subprocess@@ -65,6 +66,63 @@ def test_a_human_lease_keeps_the_screen_until_nothing_has_used_it_for_four_windoassert runtime.stop_if_idle() is True and stops == [True], "abandoned: no use for four windows"[email protected]("meanwhile", ["nothing", "another viewer takes over", "the same viewer hands back and retakes",+ "the stop is refused"])+def test_the_idle_stop_hands_back_only_the_abandoned_human_lease(tmp_path, monkeypatch, meanwhile):+ """The lapse stops the screen, but a lease that still names the human fences the agent out of the next+ one ("a human has control"), so the next use never brings the screen back. Only the generation judged+ abandoned is released: a takeover made while the screen was being stopped is kept."""+ lease._reset_for_tests()+ sd, _ = _running(monkeypatch, tmp_path)+ path = lease._path(None)+ path.parent.mkdir(parents=True, exist_ok=True)+ same_viewer = meanwhile == "the same viewer hands back and retakes"+ # Abandoned; a null viewer id (a hand-edited lease) must not make the hand-back a bare release.+ path.write_text('{"holder": "human", "viewer_id": "v1", "epoch": 7}' if same_viewer else+ '{"holder": "human", "epoch": 7}', encoding="utf-8")+ (sd / "activity").touch()+ _age(sd / "activity", 600 * runtime.HUMAN_LEASE_ABANDONED_WINDOWS + 60)++ def stop(still_due=None):+ if meanwhile == "the stop is refused":+ return False+ assert still_due() # the real stop() re-judges under start.lock before it kills anything+ if meanwhile == "another viewer takes over":+ lease.acquire("v2")+ elif same_viewer:+ lease.release("v1")+ lease.acquire("v1")+ return True++ monkeypatch.setattr(runtime, "stop", stop)+ assert runtime.stop_if_idle() is (meanwhile != "the stop is refused")+ held = lease.get()+ if meanwhile == "the stop is refused":+ assert (held.holder, held.epoch) == (lease.HUMAN, 7), "a screen still running keeps its lease"+ elif meanwhile == "nothing":+ assert (held.holder, held.viewer_id) == (lease.AGENT, None)+ else:+ assert (held.holder, held.viewer_id) == (lease.HUMAN, "v1" if same_viewer else "v2"), \+ "a takeover made meanwhile was revoked"+++def test_a_lease_that_cannot_be_written_never_undoes_the_stop(tmp_path, monkeypatch, caplog):+ sd, _ = _running(monkeypatch, tmp_path)+ monkeypatch.setattr(lease, "get", lambda profile_key=None: lease.Lease(holder=lease.HUMAN, viewer_id="v1"))+ monkeypatch.setattr(runtime, "stop", lambda still_due=None: still_due())++ def full_disk(*_, **__):+ raise OSError(28, "No space left on device")++ monkeypatch.setattr(lease, "release", full_disk)+ (sd / "activity").touch()+ _age(sd / "activity", 600 * runtime.HUMAN_LEASE_ABANDONED_WINDOWS + 60)+ with caplog.at_level(logging.WARNING, logger=runtime.logger.name):+ assert runtime.stop_if_idle() is True+ # the only sign the agent is still fenced out by the old lease+ assert "its abandoned lease was not released" in caplog.text++def test_a_short_window_never_times_out_a_human_between_two_viewer_stamps(tmp_path, monkeypatch):"""An attached viewer stamps activity at most once a minute (and the panel clock repaints once aminute), so stamps can be about two minutes apart. With idle_stop_minutes: 0.1 four windows arediff --git a/tests/tools/test_bot_desktop_idle_self_stop.py b/tests/tools/test_bot_desktop_idle_self_stop.pyindex 8867ae9d401..cf93c65dacb 100644--- a/tests/tools/test_bot_desktop_idle_self_stop.py+++ b/tests/tools/test_bot_desktop_idle_self_stop.py@@ -208,3 +208,6 @@ def test_a_screen_in_use_is_kept_and_a_returning_gateway_reattaches(abandoned_scold = time.time() - 3600os.utime(sd / "activity", (old, old))wait_until(lambda: not _alive(launcher), timeout=30, what="the screen to stop once its human lease is abandoned")+ # ...and the check that stopped it hands the abandoned lease back, so the next use is not fenced out.+ wait_until(lambda: json.loads((sd / "lease.json").read_text(encoding="utf-8"))["holder"] == "agent", timeout=10,+ what="the abandoned human lease to be handed back to the agent")diff --git a/tools/bot_desktop/lease.py b/tools/bot_desktop/lease.pyindex 1d540cf1da1..1372083fbe3 100644--- a/tools/bot_desktop/lease.py+++ b/tools/bot_desktop/lease.py@@ -202,13 +202,18 @@ def acquire(viewer_id: str, *, profile_key: Optional[str] = None, reason: str =def release(viewer_id: Optional[str] = None, *, profile_key: Optional[str] = None,- unless_human: bool = False) -> Lease:+ unless_human: bool = False, epoch: Optional[int] = None) -> Lease:"""Return control to the agent. With ``viewer_id`` only that holder may release (a stale viewerclosing its window must not yank control from the one who took over after it). ``unless_human``makes a bare release a no-op while any human holds: the decision is taken under the file lock,- so a takeover racing a check-then-release cannot be silently revoked. Callers read the returned- lease's holder to learn whether anything happened."""+ so a takeover racing a check-then-release cannot be silently revoked. ``epoch`` releases only the+ lease generation the caller judged: any transition since (a takeover, a hand-back and re-take by the+ same viewer) keeps the lease. Callers read the returned lease's holder to learn whether anything+ happened."""def _m(lease: Lease) -> bool:+ if epoch is not None and lease.epoch != epoch:+ logger.info("bot-desktop lease: release of epoch %d ignored, the lease changed since", epoch)+ return Falseif unless_human and lease.holder == HUMAN:logger.info("bot-desktop lease: bare release ignored, a human holds")return Falsediff --git a/tools/bot_desktop/runtime.py b/tools/bot_desktop/runtime.pyindex 08279bed733..4ebf0094de6 100644--- a/tools/bot_desktop/runtime.py+++ b/tools/bot_desktop/runtime.py@@ -491,16 +491,38 @@ def _idle_due(launcher: Optional[tuple[int, float]]) -> Optional[float]:def stop_if_idle(launcher: Optional[tuple[int, float]] = None) -> bool:"""Stop this profile's screen when it has been idle past the limit and no human holds it (a human leasewith no use for ``HUMAN_LEASE_ABANDONED_WINDOWS`` windows, and at least ``HUMAN_LEASE_ABANDONED_MIN_S``,- counts as abandoned). True when- it was stopped. ``launcher`` names the screen the caller judges (the launcher's own check passes it).+ counts as abandoned). True when it was stopped. ``launcher`` names the screen the caller judges (the+ launcher's own check passes it). Stopping a screen for an abandoned human lease also hands that lease back+ to the agent.The decision is taken again under ``start.lock`` before anything is killed: a check that waited on thelock while the screen was stopped and started again (or used) must not kill the screen it finds then."""idle = _idle_due(launcher)if idle is None:return False+ from tools.bot_desktop import lease as _bd_lease+ held: Optional[_bd_lease.Lease] = None # the lease the final decision saw++ def still_due() -> bool:+ nonlocal held+ # Read before _idle_due reads it: a takeover landing between the two reads then carries a newer+ # epoch than the one released below, so it is kept instead of being handed back.+ held = _bd_lease.get()+ return _idle_due(launcher) is not None+logger.info("Bot Desktop for profile %s idle for %.0f min; stopping", _profile_name(), idle / 60)- return stop(still_due=lambda: _idle_due(launcher) is not None)+ if not stop(still_due=still_due):+ return False+ if held is not None and held.holder == _bd_lease.HUMAN:+ # An abandoned human lease stopped the screen. Left in place it would fence the agent out of the next+ # screen ("a human has control"); only the lease generation judged abandoned goes, so any takeover+ # since (another viewer, or the same one handing back and taking over again) is kept.+ try:+ _bd_lease.release(held.viewer_id, epoch=held.epoch)+ except OSError as exc: # the screen is already stopped: a full or read-only home must not undo that+ logger.warning("Bot Desktop for profile %s stopped, but its abandoned lease was not released: %s",+ _profile_name(), exc)+ return Truedef published_env() -> dict[str, str]: