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): apply a pane's own CLI environment, and stop losing its session

Ruben Lütkefed145c10c59
diff --git a/jarvis/agentic_ide/agent_sessions.py b/jarvis/agentic_ide/agent_sessions.py
index e7f8cf69dc..82442f601a 100644
--- a/jarvis/agentic_ide/agent_sessions.py
+++ b/jarvis/agentic_ide/agent_sessions.py
@@ -627,13 +627,31 @@ def _discover_opencode(
the user was having.
"""
claimed = {str(t) for t in taken}
+ # DESC, and that single word is the whole correctness of the cap. This
+ # database is ONE global store for every project on the machine, so the
+ # limit bites long before a single project has many sessions — and a plain
+ # `LIMIT` sorts ASCENDING, which keeps the OLDEST rows and throws away the
+ # pane's own, newest one. Every pane would then come back as a fresh
+ # conversation, silently, once the machine had accumulated enough history.
+ #
+ # The bound is deliberately a row count and not a timestamp: the column's
+ # unit is not guaranteed (see `_epoch_seconds`, which reads both seconds and
+ # milliseconds), and a WHERE clause in the wrong unit filters everything out
+ # just as silently as the wrong sort order did.
+ #
+ # `parent_id IS NULL` is the CLI-specific half: it files its subagents'
+ # threads in the same table, and resuming one of those reopens a fragment of
+ # the pane's own previous run instead of the conversation.
rows = _opencode_rows(
home,
"SELECT id, directory, time_created FROM session "
- "WHERE parent_id IS NULL ORDER BY time_created LIMIT ?",
+ "WHERE parent_id IS NULL ORDER BY time_created DESC LIMIT ?",
(_MAX_CANDIDATES,),
)
- for session_id, directory, created in rows:
+ # Back to oldest-first, because the rule is "the EARLIEST session at or
+ # after the pane started" — that is what lets several panes opened together
+ # queue instead of all claiming the first one.
+ for session_id, directory, created in reversed(rows):
session_id = str(session_id or "").strip()
if not session_id or session_id in claimed:
continue
@@ -754,6 +772,19 @@ def _discover_kimi(
children = list(folder.iterdir())
except OSError:
return None
+
+ def _mtime(path: Path) -> float:
+ try:
+ return path.stat().st_mtime
+ except OSError:
+ return 0.0
+
+ # Newest first BEFORE the cap. Session folders are named with random ids, so
+ # directory order carries no recency at all — truncating it would drop the
+ # pane's own folder for an arbitrary 400 others, and the pane would come
+ # back as a fresh conversation with nothing to explain why. A pane's own
+ # session is by construction among the newest.
+ children.sort(key=_mtime, reverse=True)
for child in children[:_MAX_CANDIDATES]:
session_id = child.name
if session_id in claimed or not child.is_dir():
diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.py
index eb53621731..537541e0a9 100644
--- a/jarvis/agentic_ide/session.py
+++ b/jarvis/agentic_ide/session.py
@@ -572,8 +572,8 @@ def agent_spawn_overlay(agent: str) -> dict[str, str]:
resolved = spec.spawn_env_factory()
if resolved is None:
raise SessionError(
- f"{spec.display_name} is not configured yet — add its API key in "
- "Settings, then open the pane again."
+ f"{spec.display_name} is not configured yet — add its API key on "
+ "the API Keys page, then open the pane again."
)
overlay.update(resolved)
return overlay
@@ -2127,9 +2127,14 @@ class Registry:
"""
home = _redirected_home(term)
if home is None:
- # Nothing was redirected: this pane already inherits the machine's
- # own configuration, which is exactly what a terminal does.
- return None
+ # Nothing was REDIRECTED — but that is not the same as "nothing to
+ # do". A pane still carries whatever its CLI declares for every one
+ # of its panes, and skipping the environment here is how a launch
+ # profile silently becomes the CLI it borrows: a GLM pane would open
+ # as plain Claude Code on the user's own Anthropic login, answer
+ # perfectly, and bill the wrong vendor with nothing anywhere saying
+ # so. Only the account work below needs a redirected directory.
+ return _spawn_env(term)
from jarvis import agent_config_parity
with agent_config_parity.setup_lock(home):
diff --git a/jarvis/setup/wizard.py b/jarvis/setup/wizard.py
index 4bb29dac16..3a4acf3aa6 100644
--- a/jarvis/setup/wizard.py
+++ b/jarvis/setup/wizard.py
@@ -157,6 +157,18 @@ SECRETS: list[SecretSpec] = [
required_for="OpenAI Codex API-key mode (separate from the OpenAI Brain provider)",
section="brain",
),
+ SecretSpec(
+ key="zai_api_key",
+ env_fallback="ZAI_API_KEY",
+ label="Z.ai API Key (GLM Coding Plan)",
+ help_url="https://z.ai/model-api",
+ required_for=(
+ "GLM panes in the Agentic IDE — they run the Claude Code CLI "
+ "against Z.ai's endpoint, so this key is what makes them GLM "
+ "rather than Anthropic"
+ ),
+ section="brain",
+ ),
SecretSpec(
key="gemini_api_key",
env_fallback="GEMINI_API_KEY",
diff --git a/jarvis/workspace/agents.py b/jarvis/workspace/agents.py
index 34851acd36..a217e9f738 100644
--- a/jarvis/workspace/agents.py
+++ b/jarvis/workspace/agents.py
@@ -576,6 +576,11 @@ _AGENTS: dict[str, WorkspaceAgent] = {
kind="shell",
needs_trust=False,
description="This machine's own shell — no agent, just a prompt.",
+ # A shell draws no TUI input line, so waiting for one would wait
+ # forever. It is never prompted programmatically anyway (see
+ # ``accepts_prompts``), but "ready" is asked about it, and the honest
+ # answer is that a live shell is ready the moment it exists.
+ needs_input_line_wait=False,
),
}
diff --git a/tests/unit/agentic_ide/test_new_cli_providers.py b/tests/unit/agentic_ide/test_new_cli_providers.py
index 476416c27b..0aa3fac165 100644
--- a/tests/unit/agentic_ide/test_new_cli_providers.py
+++ b/tests/unit/agentic_ide/test_new_cli_providers.py
@@ -144,6 +144,55 @@ def test_two_opencode_panes_in_one_folder_get_different_conversations(
assert second.id != first.id
+def test_opencode_still_finds_its_session_behind_a_long_history(
+ _agent_history_in_tmp: Path, tmp_path: Path
+) -> None:
+ """The cap must keep the NEWEST sessions, not the oldest.
+
+ This database is one global store for every project on the machine, so the
+ candidate limit bites long before a single project has many sessions. Sorted
+ the wrong way it kept the oldest rows and threw away the pane's own — and
+ the symptom was silent: every pane came back as a fresh conversation, with
+ nothing anywhere to say why.
+ """
+ db = _opencode_db(_agent_history_in_tmp)
+ started = time.time()
+ for index in range(500):
+ _add_session(db, f"ses_old_{index}", str(tmp_path / "elsewhere"), started - 9_000)
+ _add_session(db, "ses_mine", str(tmp_path), started + 1)
+ handle = agent_sessions.discover("opencode", str(tmp_path), started)
+ assert handle is not None and handle.id == "ses_mine"
+
+
+def test_kimi_still_finds_its_session_behind_a_long_history(
+ _agent_history_in_tmp: Path, tmp_path: Path
+) -> None:
+ """Same cap, same trap: session folders carry no recency in their names.
+
+ Their ids are random, so directory order is arbitrary — truncating it
+ before sorting drops the pane's own folder for 400 unrelated ones.
+ """
+ import os
+
+ key = agent_sessions._kimi_folder_key(str(tmp_path))
+ assert key is not None
+ root = _agent_history_in_tmp / "kimi" / "sessions" / key
+ root.mkdir(parents=True)
+ started = time.time()
+ for index in range(500):
+ old = root / f"{index:04d}-old-session"
+ old.mkdir()
+ (old / "context.jsonl").write_text("{}\n", encoding="utf-8")
+ os.utime(old, (started - 9_000, started - 9_000))
+ mine = root / "zzz-mine"
+ mine.mkdir()
+ (mine / "context.jsonl").write_text("{}\n", encoding="utf-8")
+ os.utime(mine, (started + 1, started + 1))
+
+ handle = agent_sessions.discover("kimi", str(tmp_path), started)
+ assert handle is not None and handle.id == "zzz-mine"
+
+
def test_a_missing_opencode_database_starts_fresh_instead_of_raising(
tmp_path: Path,
) -> None:
@@ -249,6 +298,72 @@ def test_a_configured_glm_pane_carries_the_endpoint_and_hides_a_stray_key(
assert ide_session.agent_spawn_overlay("claude") == {}
+def _stub_pane(agent: str) -> Any:
+ """The smallest object the spawn path reads — no PTY, no registry."""
+ from jarvis.agentic_ide.session import Terminal
+
+ return Terminal(
+ key=agent,
+ name="Alex",
+ agent=agent,
+ display_name=agent,
+ index=0,
+ )
+
+
+def test_the_environment_reaches_a_pane_through_the_real_spawn_path(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """The gap the direct-overlay tests above could not see.
+
+ Every assertion in this file up to here calls ``agent_spawn_overlay``
+ directly — and the spawn path reached it through a guard that returned
+ early for any pane without an ADDED SUBSCRIPTION, which is every pane of
+ every CLI that has no account switcher. So the overlay was correct, tested,
+ and never applied: a GLM pane opened as plain Claude Code on the user's own
+ Anthropic login, answered perfectly, and billed the wrong vendor. This test
+ exists so that gap cannot reopen.
+ """
+ from jarvis.agentic_ide import session as ide_session
+
+ registry = ide_session.Registry()
+ monkeypatch.setattr("jarvis.core.config.get_secret", lambda *_a, **_k: "tok") # noqa: S105
+
+ env = registry._prepare_spawn(_stub_pane("glm"), str(tmp_path))
+ assert env is not None, "the GLM pane launched with no environment at all"
+ assert env["ANTHROPIC_AUTH_TOKEN"] == "tok" # noqa: S105
+ assert env["ANTHROPIC_BASE_URL"].startswith("http")
+ # Removed, not blanked — a host key here outranks the token.
+ assert "ANTHROPIC_API_KEY" not in env
+ # PATH survives: the child environment is inherited, not replaced.
+ assert env.get("PATH")
+
+ # The updater kill-switches reach their panes too, or a CLI can swap its
+ # own binary out from under a live conversation.
+ opencode_env = registry._prepare_spawn(_stub_pane("opencode"), str(tmp_path))
+ assert opencode_env is not None
+ assert opencode_env["OPENCODE_DISABLE_AUTOUPDATE"] == "1"
+ kimi_env = registry._prepare_spawn(_stub_pane("kimi"), str(tmp_path))
+ assert kimi_env is not None
+ assert kimi_env["KIMI_CODE_NO_AUTO_UPDATE"] == "1"
+
+ # A CLI that declares nothing still inherits the machine's environment
+ # untouched — the behaviour every pane had before any of this existed.
+ assert registry._prepare_spawn(_stub_pane("claude"), str(tmp_path)) is None
+
+
+def test_an_unconfigured_glm_pane_refuses_on_the_real_spawn_path(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """Refusing is the safety property; it has to hold where panes actually open."""
+ from jarvis.agentic_ide import session as ide_session
+
+ registry = ide_session.Registry()
+ monkeypatch.setattr("jarvis.core.config.get_secret", lambda *_a, **_k: None)
+ with pytest.raises(ide_session.SessionError):
+ registry._prepare_spawn(_stub_pane("glm"), str(tmp_path))
+
+
def test_the_glm_environment_factory_reports_not_configured_without_a_key(
monkeypatch: pytest.MonkeyPatch,
) -> None: