Skip to content

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.

fix(agentic-ide): let one pane renew an expired login before the others start (#665)

Ruben Lütkeb75d4599f11c
diff --git a/jarvis/agent_accounts.py b/jarvis/agent_accounts.py
index 35d5813d4b..3425c68dd7 100644
--- a/jarvis/agent_accounts.py
+++ b/jarvis/agent_accounts.py
@@ -1056,6 +1056,52 @@ def _describe_claude(account: AgentAccount) -> AccountSnapshot:
)
+def stale_login_marker(platform: Platform, account_id: str | None) -> float | None:
+ """The expiry of a login that its CLI will renew on its next start, else ``None``.
+
+ Claude Code keeps an access token and a refresh token in its config dir and
+ swaps the refresh token for a new pair the first time it runs after the
+ access token has expired. Every process on that directory races for one
+ lock to do it, and a process that cannot get the lock within a few seconds
+ gives up and tells the user to sign in again. A restored workspace starts a
+ dozen of those processes at once on the morning after the token expired
+ overnight, so most of them lost that race and showed the sign-in message
+ (2026-10-14: "logged out of every coding account after a reboot").
+
+ The returned value identifies WHICH stale login this is, so a caller that
+ already waited for this exact renewal once does not wait for it again.
+ Only the Claude reader can tell a stale-but-renewable login apart; every
+ other platform answers ``None``. Never raises, never returns a token.
+ """
+ if platform != "claude":
+ return None
+ from jarvis.claude_credentials import claude_login_in
+
+ snapshot = claude_login_in(config_dir_for(platform, account_id))
+ if snapshot.status != "expired" or not snapshot.refresh_token_present:
+ return None
+ return snapshot.expires_s
+
+
+def login_renewed_since(platform: Platform, account_id: str | None, marker: float) -> bool:
+ """Whether the stale login named by *marker* has been replaced by a live one.
+
+ Deliberately not "is :func:`stale_login_marker` ``None`` now": a credentials
+ file read while the CLI is rewriting it parses as absent, and taking that
+ for a renewal would release every waiting pane into the very race the
+ wait exists to avoid. Only a live token, or a different stale one (the user
+ signed in again in between), counts. Never raises.
+ """
+ if platform != "claude":
+ return True
+ from jarvis.claude_credentials import claude_login_in
+
+ snapshot = claude_login_in(config_dir_for(platform, account_id))
+ if snapshot.status == "valid":
+ return True
+ return snapshot.status == "expired" and snapshot.expires_s != marker
+
+
def _describe_codex(account: AgentAccount) -> AccountSnapshot:
from jarvis.codex_auth import codex_login_in
@@ -1294,6 +1340,7 @@ __all__ = [
"inherit_default_mode",
"list_accounts",
"login_command",
+ "login_renewed_since",
"mode_file_name",
"native_dir",
"platforms",
@@ -1303,5 +1350,6 @@ __all__ = [
"set_auto_switch",
"snapshots",
"spawn_env",
+ "stale_login_marker",
"start_login",
]
diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.py
index e6d61e1638..2daf888d9c 100644
--- a/jarvis/agentic_ide/session.py
+++ b/jarvis/agentic_ide/session.py
@@ -471,6 +471,18 @@ COLD_START_LIMIT = max(2, (os.cpu_count() or 4) // 4)
COLD_START_SETTLE_S = 1.2
COLD_START_HOLD_MAX_S = 15.0
+# How long the other panes of one login wait while the first one renews it.
+#
+# A coding CLI whose access token expired renews it on its next start, and every
+# process on that login races for one lock to do so. Claude Code gives up after
+# about eight seconds and prints "sign in again with /login" — so a restored
+# workspace of a dozen panes, started the morning after the token expired
+# overnight, came back looking logged out everywhere (2026-10-14). One pane goes
+# first; the rest start once the credentials file holds a live token again, or
+# once this ceiling runs out, after which they start as they did before.
+LOGIN_RENEWAL_WAIT_S = 45.0
+LOGIN_RENEWAL_POLL_S = 0.5
+
# How long the nudged window size is held before it is put back (see
# ``_nudge_repaint``). A PTY carries one size, not a queue of them: set twice
# within the same event-loop tick, the agent may only ever observe the second
@@ -2127,6 +2139,13 @@ class Registry:
# limit; separate accounts get separate gates, and CLIs with no limit
# never touch this path.
self._agent_cold_starts: dict[tuple[str, str], asyncio.Semaphore] = {}
+ # One lock per login directory while its expired token is being renewed
+ # (see LOGIN_RENEWAL_WAIT_S), and the stale expiry each directory was
+ # already waited on once — a renewal that never came is not waited for
+ # a second time by every pane behind it.
+ self._login_renewals: dict[str, asyncio.Lock] = {}
+ self._login_renewal_waited: dict[str, float] = {}
+ self._login_renewal_holds: set[asyncio.Task[None]] = set()
# The tasks holding a cold-start slot open until a pane's input line
# appears (see ``_cold_start_slot``). asyncio keeps only weak
# references to tasks; without this set a hold could be collected
@@ -4001,6 +4020,95 @@ class Registry:
await gate.acquire()
return gate
+ async def _login_renewal_turn(self, term: Terminal) -> Callable[[bool], None] | None:
+ """Wait while another pane renews this pane's expired login.
+
+ ``None`` when the login is live, or when this pane's CLI has no login a
+ reader can judge: the pane starts at once, exactly as before. Otherwise
+ the pane queues on its login directory's lock. The first one through
+ becomes the renewer — the returned callback, called with whether its
+ spawn succeeded, keeps the lock until the credentials file holds a live
+ token again (bounded by LOGIN_RENEWAL_WAIT_S). The panes behind it find
+ the login fresh once they get the lock and start without holding it.
+
+ Before the slots, not inside them: a pane queued here occupies no
+ cold-start slot another login's pane could use.
+ """
+ if term.computer_id or not has_accounts(term.agent):
+ return None
+ from jarvis import agent_accounts
+
+ agent = cast("agent_accounts.Platform", term.agent)
+
+ def _probe() -> tuple[str, float | None]:
+ directory = agent_accounts.config_dir_for(agent, term.account)
+ stale = agent_accounts.stale_login_marker(agent, term.account)
+ return os.path.normcase(str(directory)), stale
+
+ key, stale = await asyncio.to_thread(_probe)
+ if stale is None or self._login_renewal_waited.get(key) == stale:
+ return None
+ lock = self._login_renewals.setdefault(key, asyncio.Lock())
+ await lock.acquire()
+ try:
+ _key, stale = await asyncio.to_thread(_probe)
+ except BaseException:
+ lock.release()
+ raise
+ if stale is None or self._login_renewal_waited.get(key) == stale:
+ lock.release()
+ return None
+ renewing = stale
+
+ def _finish(started: bool) -> None:
+ if not started:
+ # Nothing is renewing anything; the next pane in line tries.
+ lock.release()
+ return
+
+ async def _hold() -> None:
+ try:
+ loop = asyncio.get_running_loop()
+ deadline = loop.time() + LOGIN_RENEWAL_WAIT_S
+ while loop.time() < deadline:
+ await asyncio.sleep(LOGIN_RENEWAL_POLL_S)
+ if term.status != "live":
+ # The renewer is gone; the next pane in line tries.
+ return
+ if await asyncio.to_thread(
+ agent_accounts.login_renewed_since, agent, term.account, renewing
+ ):
+ return
+ # The CLI did not renew it in time. Starting the others is
+ # still right; waiting for this renewal again is not.
+ self._login_renewal_waited[key] = renewing
+ logger.warning(
+ "Agentic IDE: {} did not renew its expired {} login within "
+ "{:.0f}s; starting the remaining panes anyway",
+ term.name,
+ term.display_name,
+ LOGIN_RENEWAL_WAIT_S,
+ )
+ except Exception: # noqa: BLE001 - a probe failure must not strand the queue
+ logger.opt(exception=True).warning(
+ "Agentic IDE: checking {}'s login renewal failed; releasing the panes "
+ "behind it",
+ term.name,
+ )
+ finally:
+ lock.release()
+
+ task = asyncio.get_running_loop().create_task(_hold(), name="login-renewal-hold")
+ self._login_renewal_holds.add(task)
+ task.add_done_callback(self._login_renewal_holds.discard)
+
+ logger.info(
+ "Agentic IDE: {} renews the expired {} login before the other panes on it start",
+ term.name,
+ term.display_name,
+ )
+ return _finish
+
async def attach(
self,
key: str,
@@ -4577,9 +4685,13 @@ class Registry:
"RESUMED" if term.resumed else "fresh",
" ".join(argv),
)
- agent_start_gate = await self._acquire_agent_cold_start(term)
+ # First of all the gates: a pane waiting for another pane to renew their
+ # shared login must hold none of the slots below while it waits.
+ login_renewal = await self._login_renewal_turn(term)
+ agent_start_gate = None
spawn_succeeded = False
try:
+ agent_start_gate = await self._acquire_agent_cold_start(term)
# One of a few starts at a time (see COLD_START_LIMIT), and the
# slot stays taken until this pane's input line appears.
async with self._cold_start_slot(
@@ -4638,6 +4750,8 @@ class Registry:
finally:
if not spawn_succeeded and agent_start_gate is not None:
agent_start_gate.release()
+ if login_renewal is not None:
+ login_renewal(spawn_succeeded)
term.pty_id = pty_session.terminal_id
# The size the child was actually born with — `spawn` was handed these
diff --git a/tests/unit/agentic_ide/test_login_renewal_gate.py b/tests/unit/agentic_ide/test_login_renewal_gate.py
new file mode 100644
index 0000000000..6d4d7c6dfa
--- /dev/null
+++ b/tests/unit/agentic_ide/test_login_renewal_gate.py
@@ -0,0 +1,159 @@
+"""Panes that share an expired login let one of them renew it first.
+
+The defect these pin down (2026-10-14): after a reboot, a restored workspace
+started a dozen Claude Code panes within seconds, all on one config directory
+whose access token had expired overnight. Each of them raced for the CLI's
+refresh lock, and every one that did not win it within a few seconds printed
+"Could not refresh your login ... sign in again with /login" — so the user saw
+every coding pane logged out, although the login itself was fine.
+
+What must hold:
+
+* on an expired-but-renewable login, ONE pane starts and the rest wait until
+ the credentials file holds a live token again,
+* a renewal that never comes holds the others only up to the ceiling, and is
+ not waited for a second time,
+* a live login never makes anybody wait.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import os
+import time
+from pathlib import Path
+
+import pytest
+
+from jarvis import agent_accounts
+from jarvis.agentic_ide import session as ide
+from tests.fakes.fake_pty_manager import FakePtyManager
+
+#: A credentials file in the CLI's shape, holding placeholders rather than real
+#: tokens. Kept as finished text so nothing here reads as a secret being stored.
+_LOGIN_FILE = (
+ '{{"claudeAiOauth": {{"accessToken": "sk-ant-oat01-test", '
+ '"expiresAt": {expires_ms}, "subscriptionType": "max"{renewal}}}}}'
+)
+_RENEWAL_FIELD = ', "refreshToken": "sk-ant-ort01-test"'
+
+
+def _write_login(directory: Path, *, expires_in_s: float, refresh: bool = True) -> None:
+ directory.mkdir(parents=True, exist_ok=True)
+ text = _LOGIN_FILE.format(
+ expires_ms=int((time.time() + expires_in_s) * 1000),
+ renewal=_RENEWAL_FIELD if refresh else "",
+ )
+ (directory / ".credentials.json").write_text(text, encoding="utf-8")
+
+
+def _claude_home() -> Path:
+ # The autouse fixture points CLAUDE_CONFIG_DIR at a temporary directory, so
+ # the built-in account's login lives there.
+ return Path(os.environ["CLAUDE_CONFIG_DIR"])
+
+
+def pool(monkeypatch: pytest.MonkeyPatch) -> FakePtyManager:
+ monkeypatch.setattr(ide, "agent_argv", lambda name: (f"/usr/bin/{name}",))
+ monkeypatch.setattr(ide, "COLD_START_LIMIT", 16)
+ monkeypatch.setattr(ide, "COLD_START_SETTLE_S", 0.0)
+ monkeypatch.setattr(ide, "COLD_START_HOLD_MAX_S", 0.0)
+ monkeypatch.setattr(ide, "LOGIN_RENEWAL_POLL_S", 0.01)
+ return FakePtyManager()
+
+
+async def _attach_all(registry: ide.Registry, session) -> None: # noqa: ANN001
+ async def sink(_text: str) -> None:
+ return None
+
+ async def gone(_code: int) -> None:
+ return None
+
+ await asyncio.gather(
+ *(
+ registry.attach(term.key, 80, 24, sink, gone, workspace_id=session.id)
+ for term in session.terminals
+ )
+ )
+
+
+async def _wait_for_spawns(pool: FakePtyManager, count: int) -> None:
+ for _ in range(200):
+ if len(pool.spawns) >= count:
+ return
+ await asyncio.sleep(0.01)
+
+
+async def test_one_pane_renews_an_expired_login_before_the_others_start(
+ pool: FakePtyManager, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(ide, "LOGIN_RENEWAL_WAIT_S", 10.0)
+ _write_login(_claude_home(), expires_in_s=-3600)
+ registry = ide.Registry(pty_manager=pool)
+ session = await registry.start(str(tmp_path), [{"agent": "claude"} for _ in range(4)])
+
+ mounting = asyncio.create_task(_attach_all(registry, session))
+ await _wait_for_spawns(pool, 1)
+ await asyncio.sleep(0.1)
+ assert len(pool.spawns) == 1, "the other panes raced the renewal"
+
+ # A file caught mid-rewrite reads as no login at all; that is not a renewal.
+ (_claude_home() / ".credentials.json").write_text("{", encoding="utf-8")
+ await asyncio.sleep(0.1)
+ assert len(pool.spawns) == 1, "a half-written credentials file released the queue"
+
+ # The first CLI renews the token in place, as Claude Code does.
+ _write_login(_claude_home(), expires_in_s=8 * 3600)
+ await asyncio.wait_for(mounting, timeout=5.0)
+ assert len(pool.spawns) == 4, "every pane starts once the login is live again"
+
+
+async def test_a_renewal_that_never_comes_holds_the_others_only_to_the_ceiling(
+ pool: FakePtyManager, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(ide, "LOGIN_RENEWAL_WAIT_S", 0.2)
+ _write_login(_claude_home(), expires_in_s=-3600)
+ registry = ide.Registry(pty_manager=pool)
+ session = await registry.start(str(tmp_path), [{"agent": "claude"} for _ in range(3)])
+
+ await asyncio.wait_for(_attach_all(registry, session), timeout=5.0)
+ assert len(pool.spawns) == 3
+
+ # The same stale login was already waited for once: a second workspace on
+ # it starts at once instead of paying the ceiling again.
+ monkeypatch.setattr(ide, "LOGIN_RENEWAL_WAIT_S", 30.0)
+ other = tmp_path / "other"
+ other.mkdir()
+ second = await registry.start(str(other), [{"agent": "claude"} for _ in range(2)])
+ await asyncio.wait_for(_attach_all(registry, second), timeout=5.0)
+ assert len(pool.spawns) == 5
+
+
+async def test_a_live_login_makes_nobody_wait(
+ pool: FakePtyManager, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(ide, "LOGIN_RENEWAL_WAIT_S", 30.0)
+ _write_login(_claude_home(), expires_in_s=8 * 3600)
+ registry = ide.Registry(pty_manager=pool)
+ session = await registry.start(str(tmp_path), [{"agent": "claude"} for _ in range(4)])
+
+ await asyncio.wait_for(_attach_all(registry, session), timeout=5.0)
+ assert len(pool.spawns) == 4
+
+
+def test_stale_login_marker_names_only_a_renewable_expired_claude_login() -> None:
+ home = _claude_home()
+
+ _write_login(home, expires_in_s=-60)
+ marker = agent_accounts.stale_login_marker("claude", None)
+ assert marker is not None and marker < time.time()
+
+ _write_login(home, expires_in_s=3600)
+ assert agent_accounts.stale_login_marker("claude", None) is None
+
+ # Without a refresh token the CLI cannot renew anything; waiting is useless.
+ _write_login(home, expires_in_s=-60, refresh=False)
+ assert agent_accounts.stale_login_marker("claude", None) is None
+
+ assert agent_accounts.stale_login_marker("codex", None) is None