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): Codex on its plan without the app's keys, Linux idle fallbacks, live-run fixes for the code builder (#797)
Ruben Lütke3d9bb574448e
diff --git a/docs/self-build-code.md b/docs/self-build-code.mdindex b015afbfb4..307a72c3be 100644--- a/docs/self-build-code.md+++ b/docs/self-build-code.md@@ -68,8 +68,19 @@ A case in `building` runs only while the person is away from the computerDodaios, no open call and no typing into a pane's terminal in the app; aprompt 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, its-own API-key variable is not set (the CLI would bill that key), it is not in a-usage cooldown and no usage window is over 80 %. Otherwise the case waits, for+own API-key variable does not reach it (the CLI would bill that key), it is not+in a usage cooldown and no usage window is over 80 %. Codex signed in with a+ChatGPT plan (`auth.json` holds the plan tokens and no key, and `config.toml`+does not force the API login) runs with `OPENAI_API_KEY` and `CODEX_API_KEY`+removed from its own child environment, so it bills the plan; the app's+environment is not changed. Claude Code with `ANTHROPIC_API_KEY` set is skipped.++Input idle time comes from `GetLastInputInfo` on Windows and `ioreg`'s+`HIDIdleTime` on macOS. On Linux the first reading that answers counts: GNOME's+idle monitor over D-Bus (`gdbus` or `dbus-send`, X11 and Wayland),+`xprintidle` (X11 sessions only), the freedesktop screen saver's active time+(KDE and others), systemd-logind's `IdleHint`. Without any of them only typing+in IDE panes counts. Otherwise the case waits, forup to three days; a case that never got to run may be offered again later. Thekill switch stops a running build at its next step and puts the case back inthe queue; an undo stops it the same way and removes what it made.@@ -97,8 +108,8 @@ the queue; an undo stops it the same way and removes what it made.4. The judge (`judge.py`), which the agent cannot edit: nothing protected waschanged, and the test commands the brief read before the run pass.5. Push the branch (only when `origin` fetches from and pushes to that very- repository) and open a pull request that says `Closes #<n>`, with the agent's summary and what was- checked. Draft by default.+ repository) and open a pull request that says `Closes #<n>`, with the agent's closing+ summary (paths on this computer removed) and what was checked. Draft by default.Nothing else leaves the machine: no issue comments, labels or reviews, and nopush to a repository the person does not own.@@ -125,8 +136,10 @@ minutes):The record's `artefact` follows the provenance convention every "built byDodaios" badge joins on: `{"type": "code", "id": <pull request URL>, "repo":"<owner>/<repo>"}`, plus `stage` (`worktree`, `coding`, `pushing`, `pushed`,-`pull_request`), `branch`, `draft`, the local test result and the changed-files. Before the pull request exists, `id` is empty.+`pull_request`), `branch`, `draft`, the local test result, the changed files+and `thread`, the coding run's agent-chat session, which the build detail opens+in the Agentic IDE's threads view. Before the pull request exists, `id` is+empty.## Undodiff --git a/dodaios/agent_chat/runner_cli.py b/dodaios/agent_chat/runner_cli.pyindex 6f72aa0113..d3bfb78dc6 100644--- a/dodaios/agent_chat/runner_cli.py+++ b/dodaios/agent_chat/runner_cli.py@@ -63,7 +63,7 @@ import osimport shutilimport timeimport uuid-from collections.abc import Callable+from collections.abc import Callable, Iterablefrom concurrent.futures import Futurefrom contextlib import contextmanagerfrom contextvars import ContextVar@@ -349,6 +349,39 @@ def _login_id(account_id: str) -> str:return "" if account_id in ACCESS_ACCOUNTS else account_id+#: Sessions whose CLI must start without these environment variables+#: (``drop_child_env``). In memory: a run that outlives the app keeps the+#: environment it was spawned with in the turn host.+_CHILD_ENV_DROPS: dict[str, frozenset[str]] = {}+++def drop_child_env(session_id: str, names: Iterable[str]) -> None:+ """Spawn this session's CLI turns without ``names`` in their environment.++ For background work on a subscription (the self-building loop's coding+ runs): a key variable in the app's environment would make the CLI bill the+ key instead of the plan it is signed in with. Only the child's environment+ changes; the app's own is never touched.+ """+ cleaned = frozenset(str(name) for name in names if str(name).strip())+ if cleaned:+ _CHILD_ENV_DROPS[session_id] = cleaned+++def release_child_env(session_id: str) -> None:+ _CHILD_ENV_DROPS.pop(session_id, None)+++def apply_child_env_drops(session_id: str, env: dict[str, str] | None) -> None:+ """Remove the variables :func:`drop_child_env` named for ``session_id`` from ``env``."""+ names = _CHILD_ENV_DROPS.get(session_id)+ if not names or env is None:+ return+ upper = {name.upper() for name in names}+ for key in [key for key in env if key.upper() in upper]:+ env.pop(key, None)++def _account_env(platform: str) -> dict[str, str]:"""The child environment for the subscription seat of ``platform`` — theturn's pinned account when its session names one, else the active one."""@@ -3098,7 +3131,10 @@ def _tool_abort_is_recoverable(error: str | None) -> bool:def _keep_going_prompt(- user_text: str, error: str | None, *, receipt_hint: str | None = None,+ user_text: str,+ error: str | None,+ *,+ receipt_hint: str | None = None,) -> str:err = (error or "the last tool call failed").strip()[:500]review = f"{receipt_hint}\n\n" if receipt_hint else ""@@ -3581,6 +3617,7 @@ async def _run_cli_once(identity=identity,)await asyncio.to_thread(_carry_thread_conversation, runner, resume, plan.env)+ apply_child_env_drops(session.session_id, plan.env)if getattr(handle, "tools_disabled", False):from .native_control import disable_cli_tools@@ -4245,7 +4282,12 @@ async def _drive_cli(if not task.done():task.cancel()await asyncio.gather(- watcher, provider_watcher, stall_watcher, pump, drain, feeder,+ watcher,+ provider_watcher,+ stall_watcher,+ pump,+ drain,+ feeder,return_exceptions=True,)if tracker is not None:diff --git a/dodaios/self_build/code/builder.py b/dodaios/self_build/code/builder.pyindex 4d79701392..60e54a3953 100644--- a/dodaios/self_build/code/builder.py+++ b/dodaios/self_build/code/builder.py@@ -123,7 +123,9 @@ def collect(worktree: str, branch: str, base_sha: str, message: str) -> list[strdone = gitcmd.git(["commit", "-m", message], root)if not done.ok:raise BuildError(f"the change could not be committed: {done.tail(300)}")- listing = gitcmd.git(["diff", "--name-only", f"{base_sha}..HEAD"], root)+ # "--": git would otherwise also stat the range as a path, which fails on+ # Windows once the worktree path is deep ("Filename too long").+ listing = gitcmd.git(["diff", "--name-only", f"{base_sha}..HEAD", "--"], root)if not listing.ok:raise BuildError("the change could not be read")return [line.strip() for line in listing.out.splitlines() if line.strip()]@@ -167,13 +169,76 @@ def remove_local(if not force and _unsaved(worktree):logger.info("self-build code: kept {}: it has uncommitted changes", worktree)return False- gitcmd.git(["worktree", "remove", *(["--force"] if force else []), worktree], root)+ removed = gitcmd.git(+ ["worktree", "remove", *(["--force"] if force else []), worktree], root+ )+ if not removed.ok:+ logger.info("self-build code: git left {}: {}", worktree, removed.tail(200))gitcmd.git(["worktree", "prune"], root)+ if worktree and not _registered(root, worktree):+ # What git could not delete (Windows: a long path or a held file).+ _sweep(Path(worktree))+ _drop_if_empty(Path(worktree).parent)if tip:gitcmd.git(["branch", "-D", branch], root)return True+def _registered(root: Path, worktree: str) -> bool:+ """Does git still know ``worktree`` as one of the repository's worktrees?"""+ listing = gitcmd.git(["worktree", "list", "--porcelain"], root)+ if not listing.ok:+ return True # unknown: nothing is deleted+ want = Path(worktree).resolve()+ for line in listing.out.splitlines():+ if line.startswith("worktree ") and Path(line[9:].strip()).resolve() == want:+ return True+ return False+++def _sweep(worktree: Path, *, attempts: int = 5, pause_s: float = 1.0) -> None:+ """Delete what is left of the loop's worktree once git forgot it: caches only.++ Live on Windows the folder stayed behind with the test run's+ ``__pycache__`` when git could not delete a path past the length limit or+ a file a finished process still held. Only a folder that holds nothing but+ such caches is deleted; a short retry covers a handle being released.+ """+ import shutil+ import time++ for attempt in range(attempts):+ if not worktree.is_dir():+ return+ try:+ files = [path for path in worktree.rglob("*") if path.is_file()]+ except OSError: # unreadable: left alone+ return+ parts = [path.relative_to(worktree).parts for path in files]+ if any(not any(part in _JUNK for part in rel) for rel in parts):+ logger.info("self-build code: kept {}: it holds more than caches", worktree)+ return+ try:+ shutil.rmtree(worktree)+ return+ except OSError: # still held by a process that is ending: try again shortly+ if attempt + 1 < attempts:+ time.sleep(pause_s)+ logger.info("self-build code: {} is still in use; left for now", worktree)+++def _drop_if_empty(folder: Path) -> None:+ """Remove ``<repo>/.worktrees`` once the loop's worktree was the last one in it."""+ from dodaios.agentic_ide import git_ops++ if folder.name != git_ops.WORKTREE_DIR:+ return+ try:+ folder.rmdir() # only succeeds while empty+ except OSError: # other worktrees live there, or it is already gone+ pass++def _unsaved(worktree: str) -> list[str]:"""Changes in the worktree someone would miss (caches and builds do not count)."""lines = gitcmd.out(["status", "--porcelain"], worktree).splitlines()@@ -249,15 +314,36 @@ def compose_prompt("the instruction files (CLAUDE.md). A change that does is thrown away.","- Do not push, open pull requests, comment on GitHub, change git remotes or switch ""branches; Dodaios checks your work and does that.",- "- Run the tests before you finish; they must pass: " + "; ".join(tests) + ".",+ "- Run the tests before you finish; Dodaios runs exactly these to judge the "+ "change, so run them the same way: " + "; ".join(tests) + ".","- Commit your work on this branch with a clear message.","- If the issue cannot be done safely, change nothing and say why in one paragraph.","- End with a short summary of what you changed and how you checked it; it becomes "- "the pull request description.",+ "the pull request description, so write it for the repository's reviewers: no paths "+ "on this computer, no notes about its tools or shell. Write it in the language the "+ "issue is written in.",]return "\n".join(parts)+_LOCAL_PATH: Final[re.Pattern[str]] = re.compile(+ r"(?i)(?<![\w/])(?:[a-z]:[\\/]|/(?:users|home|private|tmp|var/folders)/)[^\s`'\")\]]+"+)+_QUOTED_LOCAL_PATH: Final[re.Pattern[str]] = re.compile(+ r"(?i)`[^`\n]*?(?<![\w/])(?:[a-z]:[\\/]|/(?:users|home|private|tmp|var/folders)/)[^`\n]*`"+)+++def scrub(text: str, worktree: str = "") -> str:+ """The agent's summary without this computer's paths (it goes to GitHub)."""+ if worktree:+ for form in {worktree, worktree.replace("\\", "/"), worktree.replace("/", "\\")}:+ text = text.replace(form + "\\", "").replace(form + "/", "").replace(form, ".")+ # A quoted path may hold spaces ("C:\Program Files\..."): the whole span goes.+ text = _QUOTED_LOCAL_PATH.sub("`<local path>`", text)+ return _LOCAL_PATH.sub("<local path>", text)++def pr_body(*,issue: Issue,@@ -266,8 +352,10 @@ def pr_body(changed: list[str],build_id: str,plan: Plan,+ worktree: str = "",) -> str:text = re.sub(r"(?im)^\s*(closes|fixes|resolves)\s+#\d+\s*$", "", summary).strip()+ text = scrub(text, worktree)lines = [f"Closes #{issue.number}", "", text[:_SUMMARY_CHARS] or "(no summary)", ""]lines += ["### Checked", *[f"- {line}" for line in tests_detail.splitlines() if line]]shown = ", ".join(f"`{path}`" for path in changed[:15])@@ -362,11 +450,19 @@ async def _record("repo": undo["repo"],"branch": undo["branch"],"stage": stage,+ **_thread(undo),**extra,}await asyncio.to_thread(ctx.ledger.attach_artefact, record.id, artefact, dict(undo))+def _thread(undo: dict[str, Any]) -> dict[str, str]:+ """``{"thread": <agent-chat session id>}`` once the coding run has one: the+ build detail links to it, so the person can read every step."""+ session_id = str(undo.get("session_id") or "")+ return {"thread": session_id} if session_id else {}++async def _fail(ctx: Context, record: BuildRecord, error: BuildError, *, repo: str) -> None:from .watch import cleanup@@ -412,11 +508,18 @@ async def _guarded(ctx: Context, record: BuildRecord, step: Any) -> None:await _fail(ctx, record, BuildError(f"unexpected error: {type(exc).__name__}"), repo=repo)-async def build(ctx: Context, record: BuildRecord, *, provider: str) -> None:- """Run one build to ``proving`` (pull request open), ``failed``, or back to the queue."""+async def build(+ ctx: Context, record: BuildRecord, *, provider: str, drop_env: tuple[str, ...] = ()+) -> None:+ """Run one build to ``proving`` (pull request open), ``failed``, or back to the queue.++ ``drop_env``: variables the coding CLI's process must not see (``seat``).+ """async def step(repo: str, issue: Issue, data: dict[str, Any]) -> None:- await _build(ctx, record, repo=repo, issue=issue, data=data, provider=provider)+ await _build(+ ctx, record, repo=repo, issue=issue, data=data, provider=provider, drop_env=drop_env+ )await _guarded(ctx, record, step)@@ -454,6 +557,7 @@ async def _build(issue: Issue,data: dict[str, Any],provider: str,+ drop_env: tuple[str, ...] = (),) -> None:folder = str(data["folder"])issue = await recheck(ctx, repo, issue, data)@@ -495,12 +599,12 @@ async def _build(base=base,brief_text=brief.render(),plan=plan,- tests=[commands.shown(cmd) for cmd in tests],+ tests=[commands.runnable(cmd) for cmd in tests],)async def remember_session(session_id: str) -> None:undo["session_id"] = session_id- await _record(ctx, record, "coding", undo, thread=session_id)+ await _record(ctx, record, "coding", undo)def should_stop() -> bool:try:@@ -517,6 +621,7 @@ async def _build(timeout_s=ctx.run_timeout_s,should_stop=should_stop,on_session=remember_session,+ drop_env=drop_env,)checkpoint(ctx, record)if not result.ok:@@ -589,6 +694,7 @@ async def finish(changed=changed,build_id=record.id,plan=plan,+ worktree=worktree,),draft=draft,)@@ -605,6 +711,7 @@ async def finish("tests": detail[:500],"changed": changed[:30],"opened_ms": now_ms(),+ **_thread(undo),}await asyncio.to_thread(ledger.attach_artefact, record.id, artefact, dict(undo))checkpoint(ctx, record)diff --git a/dodaios/self_build/code/commands.py b/dodaios/self_build/code/commands.pyindex f5b12e80e6..acaaf7ed22 100644--- a/dodaios/self_build/code/commands.py+++ b/dodaios/self_build/code/commands.py@@ -10,6 +10,9 @@ from __future__ import annotationsimport jsonimport re+import shlex+import subprocess+import sysfrom pathlib import Pathfrom typing import Any@@ -124,6 +127,11 @@ def detect(folder: str | Path) -> dict[str, Any]:return {"label": label, "setup": setup, "test": test, "ci": ci_lines(root)}+def runnable(argv: list[str]) -> str:+ """A command exactly as the judge runs it, quoted for this platform's shell."""+ return subprocess.list2cmdline(argv) if sys.platform == "win32" else shlex.join(argv)++def shown(argv: list[str]) -> str:"""A command as the person would type it (the venv path shortened)."""if argv and Path(argv[0]).name.lower().startswith("python") and len(argv[0]) > 12:diff --git a/dodaios/self_build/code/gitcmd.py b/dodaios/self_build/code/gitcmd.pyindex 120ca1fa2e..f49ee95a38 100644--- a/dodaios/self_build/code/gitcmd.py+++ b/dodaios/self_build/code/gitcmd.py@@ -67,7 +67,14 @@ def run(def git(args: Sequence[str], cwd: str | Path, *, timeout: float = GIT_TIMEOUT_S) -> Result:- return run(["git", "-c", "core.quotepath=off", *args], cwd, timeout=timeout)+ # core.longpaths: a worktree under a deep project folder holds paths past+ # Windows' 260 characters (a test run's __pycache__); without it git could+ # not remove the worktree. Other platforms ignore the setting.+ return run(+ ["git", "-c", "core.quotepath=off", "-c", "core.longpaths=true", *args],+ cwd,+ timeout=timeout,+ )def out(args: Sequence[str], cwd: str | Path) -> str:diff --git a/dodaios/self_build/code/github.py b/dodaios/self_build/code/github.pyindex 37e90d0567..165d2e0a6c 100644--- a/dodaios/self_build/code/github.py+++ b/dodaios/self_build/code/github.py@@ -16,6 +16,8 @@ from __future__ import annotationsfrom dataclasses import dataclass, fieldfrom typing import Any, Protocol+from loguru import logger+from dodaios.agentic_ide import github_linkfrom dodaios.agentic_ide.github_link import GitHubError@@ -138,11 +140,13 @@ class GitHub(Protocol):_VIEWER = """+query { viewer { login } }+"""+#: Asked apart from the login: it needs the ``read:org`` scope, which a token+#: from the in-app GitHub connection may not carry.+_VIEWER_ORGS = """query {- viewer {- login- organizations(first: 100) { nodes { login viewerCanAdminister } }- }+ viewer { organizations(first: 100) { nodes { login viewerCanAdminister } } }}"""@@ -303,12 +307,27 @@ class GitHubApi:def viewer(self) -> Viewer:data = (self._q(_VIEWER).get("data") or {}).get("viewer") or {}+ return Viewer(login=str(data.get("login") or ""), admin_orgs=self._admin_orgs())++ def _admin_orgs(self) -> frozenset[str]:+ """Organisations the person administers; none when the token may not read them.++ Without ``read:org`` GitHub refuses the whole query. The person's own+ repositories are still theirs; only organisation repositories are left+ out until the connection can read organisations.+ """+ try:+ payload = self._q(_VIEWER_ORGS)+ except GitHubError as exc:+ logger.info("self-build code: organisations unreadable ({}); own repos only", exc)+ return frozenset()+ data = (payload.get("data") or {}).get("viewer") or {}orgs = frozenset(str(node.get("login") or "").lower()for node in (data.get("organizations") or {}).get("nodes") or []if isinstance(node, dict) and node.get("viewerCanAdminister"))- return Viewer(login=str(data.get("login") or ""), admin_orgs=orgs - {""})+ return orgs - {""}def snapshot(self, repo: str) -> Snapshot:owner, name = _split(repo)diff --git a/dodaios/self_build/code/idle.py b/dodaios/self_build/code/idle.pyindex 79c74d2551..332c93e8c1 100644--- a/dodaios/self_build/code/idle.py+++ b/dodaios/self_build/code/idle.py@@ -3,19 +3,34 @@Two readings, both must agree:* the operating system's input idle time (keyboard and mouse), where it can be- read without a dependency: Windows (``GetLastInputInfo``), macOS- (``ioreg``'s ``HIDIdleTime``), Linux with ``xprintidle`` on PATH;+ read without a dependency:++ - Windows: ``GetLastInputInfo``;+ - macOS: ``ioreg``'s ``HIDIdleTime`` of the ``IOHIDSystem`` (nanoseconds);+ - Linux, the first that answers: GNOME's idle monitor over D-Bus (``gdbus``+ or ``dbus-send``; X11 and Wayland), ``xprintidle`` (X11 only: under+ Wayland it sees only X clients, so it is not asked there), the+ freedesktop screen saver's active time (KDE and others: idle at least+ that long), and systemd-logind's ``IdleHint``/``IdleSinceHint``;+* the Agentic IDE: no key typed into a terminal pane lately.-A platform where neither can be read counts as idle only when the IDE shows-no input, which is the honest best a headless machine allows.+A platform where no OS reading answers counts as idle only when the IDE shows+no input, which is the honest best a headless machine allows. A reading that+can only say "idle since" (screen saver, logind) answers nothing while the+person is active rather than "zero": desktops that never set it would+otherwise block every build."""from __future__ import annotations+import os+import reimport shutilimport subprocessimport sys+import time+from collections.abc import Callablefrom typing import Finalfrom loguru import logger@@ -24,6 +39,16 @@ from dodaios.core.process_utils import NO_WINDOW_CREATIONFLAGS#: No input for this long counts as away.IDLE_AFTER_S: Final[float] = 15 * 60.0+_NUMBER: Final[re.Pattern[str]] = re.compile(r"(?<![A-Za-z0-9_.=:])(\d+)(?![A-Za-z0-9_.])")+_MUTTER: Final[tuple[str, str, str]] = (+ "org.gnome.Mutter.IdleMonitor",+ "/org/gnome/Mutter/IdleMonitor/Core",+ "org.gnome.Mutter.IdleMonitor.GetIdletime",+)+_SAVER_DEST: Final[str] = "org.freedesktop.ScreenSaver"+_SAVER_PATH: Final[str] = "/org/freedesktop/ScreenSaver"++Run = Callable[[list[str]], "str | None"]def _windows_idle_s() -> float | None:@@ -41,7 +66,10 @@ def _windows_idle_s() -> float | None:return ((ticks - info.dwTime) & 0xFFFFFFFF) / 1000.0-def _command_idle_s(argv: list[str], *, scale: float) -> float | None:+def _output(argv: list[str]) -> str | None:+ """The command's stdout, or None when it is missing, fails or hangs."""+ if not shutil.which(argv[0]):+ return Nonetry:done = subprocess.run(argv,@@ -51,26 +79,106 @@ def _command_idle_s(argv: list[str], *, scale: float) -> float | None:check=False,creationflags=NO_WINDOW_CREATIONFLAGS,)- except (OSError, subprocess.TimeoutExpired): # unknown idle time: the IDE reading decides- return None- if done.returncode != 0:+ except (OSError, subprocess.TimeoutExpired): # unknown idle time: the next reading decidesreturn None- for token in done.stdout.replace('"', " ").replace("=", " ").split():- if token.isdigit():- return int(token) / scale+ return done.stdout if done.returncode == 0 else None+++def _first_number(text: str | None) -> int | None:+ """The first standalone integer (``(uint64 12345,)`` -> 12345, never the ``64``)."""+ match = _NUMBER.search(text or "")+ return int(match.group(1)) if match else None+++def _mac_idle_s(run: Run) -> float | None:+ out = run(["ioreg", "-c", "IOHIDSystem", "-d", "4", "-k", "HIDIdleTime"])+ for line in (out or "").splitlines():+ if "HIDIdleTime" in line:+ # Only this line: the tree lines around it carry other numbers ("busy 0 (0 ms)").+ value = _first_number(line.split("=", 1)[-1])+ return value / 1e9 if value is not None else Nonereturn None-def os_idle_s() -> float | None:- """Seconds since the last keyboard or mouse input, or None when unknown."""+def _dbus(run: Run, dest: str, path: str, method: str) -> str | None:+ out = run(+ ["gdbus", "call", "--session", "--dest", dest, "--object-path", path, "--method", method]+ )+ if out is None:+ out = run(["dbus-send", "--session", "--print-reply", f"--dest={dest}", path, method])+ if out is not None:+ # Its first line is the reply header ("method return time=... serial=7").+ out = "\n".join(+ line for line in out.splitlines() if not line.startswith("method return")+ )+ return out+++def _wayland(env: dict[str, str]) -> bool:+ return bool(env.get("WAYLAND_DISPLAY")) or env.get("XDG_SESSION_TYPE", "").lower() == "wayland"+++def _screensaver_idle_s(run: Run) -> float | None:+ active = _dbus(run, _SAVER_DEST, _SAVER_PATH, f"{_SAVER_DEST}.GetActive")+ if active is None or "true" not in active.lower():+ return None+ seconds = _first_number(_dbus(run, _SAVER_DEST, _SAVER_PATH, f"{_SAVER_DEST}.GetActiveTime"))+ # The screen saver came on after some idle time already: at least this long.+ return float(seconds) if seconds is not None else None+++def _logind_idle_s(run: Run, env: dict[str, str], now: float) -> float | None:+ session = env.get("XDG_SESSION_ID") or "self"+ out = run(["loginctl", "show-session", session, "-p", "IdleHint", "-p", "IdleSinceHint"])+ if not out:+ return None+ props = dict(line.strip().split("=", 1) for line in out.splitlines() if "=" in line)+ if props.get("IdleHint", "").strip().lower() != "yes":+ return None # "no" is also all a desktop that never sets the hint says+ since_us = _first_number(props.get("IdleSinceHint"))+ if not since_us:+ return None+ return max(0.0, now - since_us / 1e6)+++def _linux_idle_s(run: Run, env: dict[str, str], now: float) -> float | None:+ millis = _first_number(_dbus(run, *_MUTTER))+ if millis is not None:+ return millis / 1000.0+ if env.get("DISPLAY") and not _wayland(env):+ millis = _first_number(run(["xprintidle"]))+ if millis is not None:+ return millis / 1000.0+ saver = _screensaver_idle_s(run)+ if saver is not None:+ return saver+ return _logind_idle_s(run, env, now)+++def os_idle_s(+ *,+ platform: str | None = None,+ run: Run | None = None,+ env: dict[str, str] | None = None,+ now: float | None = None,+) -> float | None:+ """Seconds since the last keyboard or mouse input, or None when unknown.++ The keyword arguments are test seams (faked command output).+ """+ platform = platform or sys.platform+ run = run or _outputtry:- if sys.platform == "win32":+ if platform == "win32":return _windows_idle_s()- if sys.platform == "darwin":- argv = ["ioreg", "-c", "IOHIDSystem", "-d", "4", "-k", "HIDIdleTime"]- return _command_idle_s(argv, scale=1e9)- if shutil.which("xprintidle"):- return _command_idle_s(["xprintidle"], scale=1000.0)+ if platform == "darwin":+ return _mac_idle_s(run)+ if platform.startswith("linux") or "bsd" in platform:+ return _linux_idle_s(+ run,+ dict(os.environ) if env is None else env,+ time.time() if now is None else now,+ )except Exception: # noqa: BLE001 - an unreadable clock is an unknown, not an errorlogger.opt(exception=True).debug("self-build code: idle time unreadable")return Nonediff --git a/dodaios/self_build/code/loop.py b/dodaios/self_build/code/loop.pyindex 3ba7ec3ce4..6c9195f6ae 100644--- a/dodaios/self_build/code/loop.py+++ b/dodaios/self_build/code/loop.py@@ -210,7 +210,10 @@ class CodeLoop:chosen, why = await ctx.seat()if chosen is None:return f"waiting: {why}"- self._start(record, builder.build(ctx, record, provider=chosen.provider))+ self._start(+ record,+ builder.build(ctx, record, provider=chosen.provider, drop_env=chosen.drop_env),+ )return f"building {record.signature} on {chosen.label}"async def _resume(self, record: BuildRecord) -> str:diff --git a/dodaios/self_build/code/runner.py b/dodaios/self_build/code/runner.pyindex b49274477d..5df84f9dde 100644--- a/dodaios/self_build/code/runner.py+++ b/dodaios/self_build/code/runner.py@@ -45,6 +45,7 @@ class Runner(Protocol):timeout_s: float,should_stop: Callable[[], bool],on_session: Callable[[str], Awaitable[None]] | None = None,+ drop_env: tuple[str, ...] = (),) -> RunResult: ...async def outcome(self, session_id: str) -> RunResult | None: ...@@ -56,6 +57,20 @@ def _default_chat() -> Any:return chat_service()+def final_message(events: list[dict[str, Any]], turn_id: str) -> str:+ """The last non-empty assistant message of ``turn_id`` (``""`` without one)."""+ for event in reversed(events):+ payload = event.get("payload") or {}+ if event.get("kind") != "assistant_text":+ continue+ if turn_id and str(payload.get("turn_id") or "") != turn_id:+ continue+ text = str(payload.get("text") or "").strip()+ if text:+ return text+ return ""++class ThreadRunner:""":class:`Runner` on the agent-chat service's coding threads."""@@ -72,7 +87,9 @@ class ThreadRunner:timeout_s: float,should_stop: Callable[[], bool],on_session: Callable[[str], Awaitable[None]] | None = None,+ drop_env: tuple[str, ...] = (),) -> RunResult:+ from dodaios.agent_chat.runner_cli import drop_child_env, release_child_envfrom dodaios.agent_chat.service import resolve_runnerfrom dodaios.society.coding_threads import THREAD_SURFACE, access_mode@@ -88,9 +105,26 @@ class ThreadRunner:surface=THREAD_SURFACE,)sid = session.session_id- if on_session is not None:- await on_session(sid)- turn_id = await service.send(sid, prompt, author=dict(AUTHOR))+ if drop_env:+ # The CLI bills its plan only without these (``seat``); the app's+ # own environment keeps them.+ drop_child_env(sid, drop_env)+ try:+ if on_session is not None:+ await on_session(sid)+ turn_id = await service.send(sid, prompt, author=dict(AUTHOR))+ return await self._wait(service, sid, turn_id, timeout_s, should_stop)+ finally:+ release_child_env(sid)++ async def _wait(+ self,+ service: Any,+ sid: str,+ turn_id: str,+ timeout_s: float,+ should_stop: Callable[[], bool],+ ) -> RunResult:deadline = time.monotonic() + timeout_swhile True:result = self._finished(service, sid, turn_id)@@ -144,6 +178,9 @@ class ThreadRunner:if not done:return Nonestatus, text, error = last_turn(events)+ # The pull request gets the agent's closing message, not every progress+ # note it wrote along the way (Codex narrates each step).+ text = final_message(events, str((done[-1].get("payload") or {}).get("turn_id") or ""))if status not in ("done", "complete", "completed", "ok", "success"):return RunResult(False, summary=text, error=error or status, session_id=sid)return RunResult(True, summary=text, session_id=sid)diff --git a/dodaios/self_build/code/seat.py b/dodaios/self_build/code/seat.pyindex 57cc1ce693..4ef27fb8ea 100644--- a/dodaios/self_build/code/seat.py+++ b/dodaios/self_build/code/seat.py@@ -5,8 +5,11 @@ bills a per-token key (``dodaios.brain.background_policy``). A coding run isthe most expensive background work there is, so the rule is strict here:* only a CLI whose plan login is confirmed signed in right now;-* never while that CLI's own API-key variable is in the environment, since- the CLI would bill that key instead of the plan;+* never while that CLI's own API-key variable reaches it, since the CLI would+ bill that key instead of the plan. Codex is run with those variables removed+ from its own child environment when its login is a ChatGPT plan (see+ :func:`codex_plan_login`); the app's environment is never changed. Claude+ Code with a key in the environment is skipped;* never inside a cooldown after the plan reported its usage limit, after adead login, or while a usage window is nearly spent.@@ -15,8 +18,11 @@ Anything else is an unknown and the answer is "wait".from __future__ import annotations+import jsonimport os+import refrom dataclasses import dataclass+from pathlib import Pathfrom typing import Any, Finalfrom loguru import logger@@ -27,8 +33,16 @@ SEATS: Final[dict[str, tuple[str, str, tuple[str, ...]]]] = {"claude-cli": ("claude-cli", "claude", ("ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN")),"codex-cli": ("codex", "codex", ("OPENAI_API_KEY", "CODEX_API_KEY")),}+#: Runners that may run with their key variables removed from the child+#: environment, because without them the CLI bills the plan login it holds.+#: Checked against Codex CLI 0.160: with a ChatGPT login in ``auth.json``,+#: ``codex exec`` ignores ``OPENAI_API_KEY`` but bills ``CODEX_API_KEY``.+STRIPPABLE: Final[frozenset[str]] = frozenset({"codex-cli"})#: A usage window this full leaves the plan to the person.FULL_PERCENT: Final[float] = 80.0+_FORCED_LOGIN: Final[re.Pattern[str]] = re.compile(+ r"""^\s*forced_login_method\s*=\s*["']([^"']*)["']""", re.MULTILINE+)@dataclass(frozen=True, slots=True)@@ -37,6 +51,60 @@ class Seat:provider: strrunner: strlabel: str+ #: Environment variables the coding CLI's child process must not see.+ drop_env: tuple[str, ...] = ()+++def _codex_home() -> Path:+ """The ``CODEX_HOME`` a thread's Codex runs with: the active account's, else the default."""+ env: dict[str, str] = dict(os.environ)+ try:+ from dodaios import agent_accounts++ account = agent_accounts.active_account("codex")+ env = agent_accounts.spawn_env("codex", account.id, base=os.environ)+ except Exception: # noqa: BLE001 - no account layer: the CLI's own default applies+ logger.opt(exception=True).debug("self-build code: codex account unreadable")+ return Path(env.get("CODEX_HOME") or Path.home() / ".codex")+++def _forced_login(config_toml: str) -> str:+ """``forced_login_method`` at the top level of a Codex ``config.toml`` ("" when unset)."""+ top = re.split(r"(?m)^\s*\[", config_toml, maxsplit=1)[0]+ match = _FORCED_LOGIN.search(top)+ return match.group(1).strip().lower() if match else ""+++def codex_plan_login(home: Path | None = None) -> bool:+ """Does this Codex home hold a ChatGPT plan login the CLI will use without a key?++ Strict on purpose, since a yes lets a run start while a key is in the app's+ environment: ``auth.json`` carries ChatGPT tokens, no stored API key and+ no other ``auth_mode``, and ``config.toml`` does not force the API login.+ """+ home = home or _codex_home()+ try:+ auth = json.loads((home / "auth.json").read_text(encoding="utf-8"))+ except (OSError, ValueError): # no readable login: not a plan login+ return False+ if not isinstance(auth, dict):+ return False+ tokens = auth.get("tokens")+ if not isinstance(tokens, dict) or not any(+ isinstance(tokens.get(k), str) and tokens.get(k)+ for k in ("access_token", "refresh_token", "id_token")+ ):+ return False+ if auth.get("OPENAI_API_KEY") or auth.get("openai_api_key"):+ return False+ mode = str(auth.get("auth_mode") or "chatgpt").lower()+ if not mode.startswith("chatgpt"):+ return False+ try:+ config = (home / "config.toml").read_text(encoding="utf-8")+ except OSError: # no config: nothing forces the API login+ config = ""+ return _forced_login(config) not in ("api", "apikey")def _cooling(runner: str) -> bool:@@ -94,7 +162,10 @@ def choose(installed: dict[str, bool] | None = None) -> tuple[Seat | None, str]:if installed is not None and not installed.get(row.agent, False):reasons.append(f"{row.label}: not installed")continue- if any(os.environ.get(name) for name in key_vars):+ drop: tuple[str, ...] = ()+ if runner in STRIPPABLE and codex_plan_login():+ drop = key_vars # always: a key set later must not reach the run either+ elif any(os.environ.get(name) for name in key_vars):reasons.append(f"{row.label}: an API key in the environment would be billed")continueif login_state(brain) is not True:@@ -106,7 +177,7 @@ def choose(installed: dict[str, bool] | None = None) -> tuple[Seat | None, str]:if _window_full(platform):reasons.append(f"{row.label}: usage window nearly spent")continue- return Seat(provider=row.id, runner=runner, label=row.label), ""+ return Seat(provider=row.id, runner=runner, label=row.label, drop_env=drop), ""return None, "; ".join(reasons) or "no subscription coding CLI"diff --git a/tests/unit/core/test_log_secret_redaction.py b/tests/unit/core/test_log_secret_redaction.pyindex fa11e62de0..b806984eda 100644--- a/tests/unit/core/test_log_secret_redaction.py+++ b/tests/unit/core/test_log_secret_redaction.py@@ -58,4 +58,4 @@ def test_github_api_never_shows_its_token(monkeypatch) -> None:assert "ghp_realtoken" not in repr(vars(api) if hasattr(api, "__dict__") else api._token)assert "ghp_realtoken" not in str(api._token)api.viewer()- assert seen == ["ghp_realtoken"]+ assert seen and set(seen) == {"ghp_realtoken"} # the login and the organisations querydiff --git a/tests/unit/self_build/test_self_build_code.py b/tests/unit/self_build/test_self_build_code.pyindex 22cbce542c..d6f8a6287c 100644--- a/tests/unit/self_build/test_self_build_code.py+++ b/tests/unit/self_build/test_self_build_code.py@@ -121,6 +121,7 @@ class FakeRunner:change: str = "good"prompts: list[str] = field(default_factory=list)stopped: list[str] = field(default_factory=list)+ dropped: list[tuple[str, ...]] = field(default_factory=list)async def run(self,@@ -132,8 +133,10 @@ class FakeRunner:timeout_s: float,should_stop: Any,on_session: Any = None,+ drop_env: tuple[str, ...] = (),) -> RunResult:self.prompts.append(prompt)+ self.dropped.append(drop_env)if on_session is not None:await on_session("thread-1")root = Path(folder)@@ -265,6 +268,8 @@ def test_issue_becomes_draft_pull_request_proven_by_ci_and_undoable(world: Worldassert record.artefact["id"] == "https://x/me/proj/pull/100"assert record.artefact["repo"] == "me/proj"assert record.artefact["draft"] is True+ # The coding thread stays linked from the build detail.+ assert record.artefact["thread"] == "thread-1"branch = record.undo["branch"]assert branch.startswith("dodaios/issue-1-")assert branch in world.remote_branches()@@ -277,6 +282,8 @@ def test_issue_becomes_draft_pull_request_proven_by_ci_and_undoable(world: Worldprompt = world.runner.prompts[0]assert "Use type hints in new code." in promptassert "pytest" in prompt and ISSUE_BODY in prompt+ # The agent is told the exact command the judge runs (the real interpreter).+ assert sys.executable.replace(chr(92), "/") in prompt.replace(chr(92), "/")world.github.pulls[100]["checks"] = "SUCCESS"world.tick()@@ -291,6 +298,7 @@ def test_issue_becomes_draft_pull_request_proven_by_ci_and_undoable(world: Worldassert world.github.pulls[100]["state"] == "CLOSED"assert branch not in world.remote_branches()assert not worktree.exists()+ assert not worktree.parent.exists() # no empty .worktrees folder left behindassert branch not in git(world.work, "branch", "--list", branch)diff --git a/tests/unit/self_build/test_self_build_code_seat_idle.py b/tests/unit/self_build/test_self_build_code_seat_idle.pynew file mode 100644index 0000000000..e041e613d6--- /dev/null+++ b/tests/unit/self_build/test_self_build_code_seat_idle.py@@ -0,0 +1,401 @@+"""The code builder's seat (which CLI may run on the plan) and idle detection."""++from __future__ import annotations++import asyncio+import json+from pathlib import Path+from types import SimpleNamespace+from typing import Any++import pytest++from dodaios.agent_chat import runner_cli+from dodaios.self_build.code import idle, seat++# ------------------------------------------------------------------ Codex on the plan+++def _codex_home(tmp_path: Path, auth: dict[str, Any], config: str = "") -> Path:+ home = tmp_path / ".codex"+ home.mkdir(parents=True)+ (home / "auth.json").write_text(json.dumps(auth), encoding="utf-8")+ if config:+ (home / "config.toml").write_text(config, encoding="utf-8")+ return home+++PLAN_AUTH: dict[str, Any] = {+ "auth_mode": "chatgpt",+ "OPENAI_API_KEY": None,+ "tokens": {"access_token": "a", "refresh_token": "r", "id_token": "x.y.z"},+}+++def test_codex_plan_login_is_strict(tmp_path: Path) -> None:+ assert seat.codex_plan_login(_codex_home(tmp_path / "a", PLAN_AUTH))+ # No auth_mode field (older CLIs) with ChatGPT tokens is still the plan.+ legacy = {k: v for k, v in PLAN_AUTH.items() if k != "auth_mode"}+ assert seat.codex_plan_login(_codex_home(tmp_path / "b", legacy))+ # A stored API key, an API auth mode, or no tokens: not the plan.+ assert not seat.codex_plan_login(+ _codex_home(tmp_path / "c", {**PLAN_AUTH, "OPENAI_API_KEY": "sk-stored"})+ )+ api_mode = {**PLAN_AUTH, "auth_mode": "apikey"}+ assert not seat.codex_plan_login(_codex_home(tmp_path / "d", api_mode))+ assert not seat.codex_plan_login(_codex_home(tmp_path / "e", {"auth_mode": "chatgpt"}))+ assert not seat.codex_plan_login(tmp_path / "missing")+ # config.toml forcing the API login at the top level wins; inside a profile it does not.+ assert not seat.codex_plan_login(+ _codex_home(tmp_path / "f", PLAN_AUTH, 'model = "x"\nforced_login_method = "api"\n')+ )+ assert seat.codex_plan_login(+ _codex_home(+ tmp_path / "g",+ PLAN_AUTH,+ 'model = "x"\n[profiles.local]\nforced_login_method = "api"\n',+ )+ )+++def _one_row(monkeypatch: pytest.MonkeyPatch, *, runner: str, agent: str, label: str) -> None:+ from dodaios.brain import background_policy++ row = SimpleNamespace(id=f"{agent}-row", agent=agent, label=label)+ monkeypatch.setattr(seat, "_rows", lambda: [row])+ monkeypatch.setattr(+ "dodaios.agent_chat.service.resolve_runner", lambda provider, surface="agent": runner+ )+ monkeypatch.setattr(seat, "_cooling", lambda r: False)+ monkeypatch.setattr(seat, "_window_full", lambda platform: False)+ monkeypatch.setattr(background_policy, "login_state", lambda provider: True)+++def test_codex_with_a_key_in_the_app_runs_on_the_plan_without_it(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ _one_row(monkeypatch, runner="codex-cli", agent="codex", label="Codex")+ home = _codex_home(tmp_path, PLAN_AUTH)+ monkeypatch.setattr(seat, "_codex_home", lambda: home)+ monkeypatch.setenv("OPENAI_API_KEY", "sk-app")+ monkeypatch.setenv("CODEX_API_KEY", "sk-codex")+ chosen, why = seat.choose({"codex": True})+ assert chosen is not None, why+ assert set(chosen.drop_env) == {"OPENAI_API_KEY", "CODEX_API_KEY"}+ # The app's own environment is untouched.+ import os++ assert os.environ["OPENAI_API_KEY"] == "sk-app"+++def test_codex_without_a_plan_login_is_still_skipped_while_a_key_is_set(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ _one_row(monkeypatch, runner="codex-cli", agent="codex", label="Codex")+ home = _codex_home(tmp_path, {**PLAN_AUTH, "OPENAI_API_KEY": "sk-stored"})+ monkeypatch.setattr(seat, "_codex_home", lambda: home)+ monkeypatch.setenv("CODEX_API_KEY", "sk-codex")+ chosen, why = seat.choose({"codex": True})+ assert chosen is None and "API key" in why+ monkeypatch.delenv("CODEX_API_KEY")+ monkeypatch.delenv("OPENAI_API_KEY", raising=False)+ chosen, _ = seat.choose({"codex": True})+ assert chosen is not None and chosen.drop_env == ()+++def test_claude_with_a_key_in_the_environment_is_still_skipped(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _one_row(monkeypatch, runner="claude-cli", agent="claude", label="Claude Code")+ monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-test")+ chosen, why = seat.choose({"claude": True})+ assert chosen is None and "API key" in why+++def test_child_env_drops_apply_to_that_session_only() -> None:+ runner_cli.drop_child_env("s1", ("OPENAI_API_KEY", "CODEX_API_KEY"))+ try:+ env = {"OPENAI_API_KEY": "k", "codex_api_key": "k2", "PATH": "/bin"}+ runner_cli.apply_child_env_drops("s1", env)+ assert env == {"PATH": "/bin"} # case-insensitive, like Windows' environment+ other = {"OPENAI_API_KEY": "k"}+ runner_cli.apply_child_env_drops("s2", other)+ assert other == {"OPENAI_API_KEY": "k"}+ finally:+ runner_cli.release_child_env("s1")+ env = {"OPENAI_API_KEY": "k"}+ runner_cli.apply_child_env_drops("s1", env)+ assert env == {"OPENAI_API_KEY": "k"}+++def test_thread_runner_strips_the_key_while_its_run_lasts(monkeypatch: pytest.MonkeyPatch) -> None:+ from dodaios.self_build.code.runner import ThreadRunner++ monkeypatch.setattr(+ "dodaios.agent_chat.service.resolve_runner", lambda provider, surface="agent": "codex-cli"+ )+ seen: dict[str, Any] = {}++ class Chat:+ store = SimpleNamespace(+ list_events=lambda sid, tail=None: [+ {"kind": "assistant_text", "payload": {"turn_id": "t1", "text": "done"}},+ {"kind": "turn_finished", "payload": {"turn_id": "t1", "status": "done"}},+ ]+ )++ def create_session(self, **kwargs: Any) -> Any:+ return SimpleNamespace(session_id="s7")++ async def send(self, sid: str, text: str, *, author: dict[str, str]) -> str:+ env = {"OPENAI_API_KEY": "sk-app", "HOME": "/h"}+ runner_cli.apply_child_env_drops(sid, env) # what the turn's planner does+ seen["env"] = env+ return "t1"++ def is_running(self, sid: str) -> bool:+ return False++ result = asyncio.run(+ ThreadRunner(lambda: Chat()).run(+ provider="codex",+ folder="/w",+ prompt="p",+ title="t",+ timeout_s=60,+ should_stop=lambda: False,+ drop_env=("OPENAI_API_KEY", "CODEX_API_KEY"),+ )+ )+ assert result.ok+ assert seen["env"] == {"HOME": "/h"}+ assert "s7" not in runner_cli._CHILD_ENV_DROPS # released after the run+++# ------------------------------------------------------------------ idle detection+++def _fake(outputs: dict[str, str | None]) -> Any:+ calls: list[list[str]] = []++ def run(argv: list[str]) -> str | None:+ calls.append(argv)+ joined = " ".join(argv)+ for needle, out in outputs.items():+ if needle in joined:+ return out+ return None++ run.calls = calls # type: ignore[attr-defined]+ return run+++def test_macos_reads_hid_idle_time_from_its_own_line() -> None:+ out = (+ "+-o Root <class IORegistryEntry, id 0x100000100, retain 26>\n"+ " +-o IOHIDSystem <class IOHIDSystem, id 0x100000465, registered, matched, "+ "active, busy 0 (0 ms), retain 39>\n"+ " {\n"+ ' "HIDIdleTime" = 1200000000000\n'+ " }\n"+ )+ run = _fake({"ioreg": out})+ assert idle.os_idle_s(platform="darwin", run=run) == 1200.0+ assert run.calls[0][:3] == ["ioreg", "-c", "IOHIDSystem"]+ assert idle.os_idle_s(platform="darwin", run=_fake({})) is None+++def test_linux_gnome_idle_monitor_over_gdbus_or_dbus_send() -> None:+ env = {"WAYLAND_DISPLAY": "wayland-0"}+ run = _fake({"gdbus call --session --dest org.gnome.Mutter.IdleMonitor": "(uint64 905000,)\n"})+ assert idle.os_idle_s(platform="linux", run=run, env=env) == 905.0+ run = _fake(+ {+ "dbus-send --session --print-reply --dest=org.gnome.Mutter.IdleMonitor": (+ "method return time=1.2 sender=:1.5 -> destination=:1.9 serial=7 "+ "reply_serial=2\n uint64 61000\n"+ )+ }+ )+ assert idle.os_idle_s(platform="linux", run=run, env=env) == 61.0+++def test_linux_xprintidle_only_outside_wayland() -> None:+ run = _fake({"xprintidle": "1800000\n"})+ assert idle.os_idle_s(platform="linux", run=run, env={"DISPLAY": ":0"}) == 1800.0+ # Under Wayland xprintidle sees only X clients: never asked.+ run = _fake({"xprintidle": "1800000\n"})+ env = {"DISPLAY": ":0", "XDG_SESSION_TYPE": "wayland"}+ assert idle.os_idle_s(platform="linux", run=run, env=env) is None+ assert not any(argv[0] == "xprintidle" for argv in run.calls)+++def test_linux_screensaver_active_time_is_a_lower_bound() -> None:+ run = _fake(+ {+ "ScreenSaver.GetActiveTime": "(uint32 1300,)\n",+ "ScreenSaver.GetActive": "(true,)\n",+ }+ )+ env = {"WAYLAND_DISPLAY": "wayland-0"}+ assert idle.os_idle_s(platform="linux", run=run, env=env) == 1300.0+ # Not active: no reading from the screen saver (the person may be typing).+ run = _fake({"ScreenSaver.GetActive": "(false,)\n"})+ assert idle.os_idle_s(platform="linux", run=run, env=env) is None+++def test_linux_logind_idle_hint() -> None:+ now = 2_000_000.0+ since_us = int((now - 1000.0) * 1e6)+ run = _fake({"loginctl": f"IdleHint=yes\nIdleSinceHint={since_us}\n"})+ env = {"XDG_SESSION_ID": "c2"}+ assert idle.os_idle_s(platform="linux", run=run, env=env, now=now) == pytest.approx(1000.0)+ assert run.calls[-1][:3] == ["loginctl", "show-session", "c2"]+ # "no" is what desktops that never set the hint say too: unknown, not "busy".+ run = _fake({"loginctl": "IdleHint=no\nIdleSinceHint=0\n"})+ assert idle.os_idle_s(platform="linux", run=run, env=env, now=now) is None+++def test_linux_without_any_reading_leaves_it_to_the_ide(monkeypatch: pytest.MonkeyPatch) -> None:+ assert idle.os_idle_s(platform="linux", run=_fake({}), env={}) is None+ monkeypatch.setattr(idle, "os_idle_s", lambda: None)+ monkeypatch.setattr(idle, "dodaios_idle_s", lambda: None)+ monkeypatch.setattr(idle, "ide_idle_s", lambda: None)+ assert idle.person_idle()+ monkeypatch.setattr(idle, "ide_idle_s", lambda: 30.0)+ assert not idle.person_idle()+++# ------------------------------------------------------------------ the GitHub account+++def test_viewer_without_read_org_still_knows_the_person(monkeypatch: pytest.MonkeyPatch) -> None:+ from dodaios.agentic_ide import github_link+ from dodaios.self_build.code.github import GitHubApi++ def graphql(token: str, query: str, variables: Any = None) -> dict[str, Any]:+ if "organizations" in query:+ # What GitHub answers a token from the in-app connection (no read:org).+ raise github_link.GitHubError("GitHub could not answer this request.")+ return {"data": {"viewer": {"login": "me"}}}++ monkeypatch.setattr(github_link, "graphql", graphql)+ who = GitHubApi("t").viewer()+ assert who.login == "me" and who.admin_orgs == frozenset()+ assert who.owns("me/proj") and not who.owns("some-org/proj")++ def with_orgs(token: str, query: str, variables: Any = None) -> dict[str, Any]:+ if "organizations" in query:+ nodes = [+ {"login": "Org", "viewerCanAdminister": True},+ {"login": "other", "viewerCanAdminister": False},+ ]+ return {"data": {"viewer": {"organizations": {"nodes": nodes}}}}+ return {"data": {"viewer": {"login": "me"}}}++ monkeypatch.setattr(github_link, "graphql", with_orgs)+ assert GitHubApi("t").viewer().admin_orgs == frozenset({"org"})+++# ------------------------------------------------------------------ the pull request text+++def test_pull_request_text_carries_no_local_paths() -> None:+ from dodaios.self_build.code.builder import scrub++ worktree = r"C:\Users\me\proj\.worktrees\dodaios-issue-1-x"+ text = (+ rf"Edited {worktree}\calc.py and ran (`C:\Program Files\Python311\python.exe -m pytest`)."+ "\nAlso see /home/me/proj/notes.txt and /Users/me/x.\nKept `tests/test_calc.py`."+ )+ out = scrub(text, worktree)+ assert "Edited calc.py" in out+ assert "Program Files" not in out and "Python311" not in out+ assert "/home/me" not in out and "/Users/me" not in out+ assert "`tests/test_calc.py`" in out # repository paths stay+++def test_leftover_worktree_folder_goes_only_when_it_holds_caches(tmp_path: Path) -> None:+ from dodaios.self_build.code.builder import _drop_if_empty, _sweep++ parent = tmp_path / ".worktrees"+ left = parent / "dodaios-issue-1-x"+ (left / "tests" / "__pycache__").mkdir(parents=True)+ (left / "tests" / "__pycache__" / "test_calc.pyc").write_bytes(b"x")+ (left / "__pycache__").mkdir()+ _sweep(left)+ _drop_if_empty(parent)+ assert not left.exists() and not parent.exists()++ kept = parent / "dodaios-issue-2-y"+ kept.mkdir(parents=True)+ (kept / "notes.txt").write_text("the person's", encoding="utf-8")+ _sweep(kept)+ _drop_if_empty(parent)+ assert (kept / "notes.txt").exists()+++def test_summary_is_the_agents_closing_message() -> None:+ from dodaios.self_build.code.runner import final_message++ events = [+ {"kind": "assistant_text", "payload": {"turn_id": "t0", "text": "old turn"}},+ {"kind": "assistant_text", "payload": {"turn_id": "t1", "text": "I'll inspect first."}},+ {"kind": "tool_call", "payload": {"turn_id": "t1", "name": "edit"}},+ {"kind": "assistant_text", "payload": {"turn_id": "t1", "text": "Added neg() and a test."}},+ {"kind": "assistant_text", "payload": {"turn_id": "t1", "text": " "}},+ {"kind": "turn_finished", "payload": {"turn_id": "t1", "status": "done"}},+ ]+ assert final_message(events, "t1") == "Added neg() and a test."+ assert final_message(events, "t9") == ""+++def test_sweep_retries_while_a_file_is_still_held(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ import shutil++ from dodaios.self_build.code.builder import _sweep++ left = tmp_path / ".worktrees" / "dodaios-issue-1-x"+ (left / "__pycache__").mkdir(parents=True)+ (left / "__pycache__" / "calc.pyc").write_bytes(b"x")+ real = shutil.rmtree+ calls: list[int] = []++ def flaky(path: Any, *args: Any, **kwargs: Any) -> None:+ calls.append(1)+ if len(calls) == 1:+ raise PermissionError("in use")+ real(path, *args, **kwargs)++ monkeypatch.setattr(shutil, "rmtree", flaky)+ _sweep(left, pause_s=0)+ assert not left.exists() and len(calls) == 2+++def test_git_calls_survive_deep_windows_paths(monkeypatch: pytest.MonkeyPatch) -> None:+ """Live: a worktree 213 characters deep made ``git diff base..HEAD`` fail with+ "Filename too long" (git also stats the range as a path) and left the worktree+ behind on removal. Every loop git call allows long paths, and the range is+ marked as a revision with ``--``."""+ from dodaios.self_build.code import builder, gitcmd++ seen: list[list[str]] = []++ def run(argv: list[str], cwd: Any, *, timeout: float = 0, env: Any = None) -> Any:+ seen.append(list(argv))+ if argv[-1] == "--abbrev-ref" or "--abbrev-ref" in argv:+ return gitcmd.Result(0, "dodaios/issue-1-x\n", "")+ if "--quiet" in argv:+ return gitcmd.Result(0, "", "")+ return gitcmd.Result(0, "calc.py\n", "")++ monkeypatch.setattr(gitcmd, "run", run)+ assert builder.collect("/w", "dodaios/issue-1-x", "abc", "fix: x") == ["calc.py"]+ assert all(+ argv[:5] == ["git", "-c", "core.quotepath=off", "-c", "core.longpaths=true"]+ for argv in seen+ )+ diff = next(argv for argv in seen if "--name-only" in argv)+ assert diff[-2:] == ["abc..HEAD", "--"]