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.

feat(agentic-ide): resume, drop into and prompt the three new CLI panes

Ruben Lütke22ebbd71999b
diff --git a/jarvis/agentic_ide/agent_sessions.py b/jarvis/agentic_ide/agent_sessions.py
index f9ef98019f..e7f8cf69dc 100644
--- a/jarvis/agentic_ide/agent_sessions.py
+++ b/jarvis/agentic_ide/agent_sessions.py
@@ -139,6 +139,11 @@ def _codex_launch() -> tuple[tuple[str, ...], ResumeHandle | None]:
return ((), None)
+def _discovered_launch() -> tuple[tuple[str, ...], ResumeHandle | None]:
+ """Nothing can be passed: the id is the CLI's to choose and ours to find."""
+ return ((), None)
+
+
_ADAPTERS: dict[str, _Adapter] = {
"claude": _Adapter(
kind="claude_session",
@@ -160,21 +165,59 @@ _ADAPTERS: dict[str, _Adapter] = {
),
exists=lambda handle, home: _codex_conversation_exists(handle, home),
),
+ "opencode": _Adapter(
+ kind="opencode_session",
+ launch=_discovered_launch,
+ # Long form on purpose. The short flags of a TUI are the ones that get
+ # reused for something else between releases; `--session` has to keep
+ # meaning this or the CLI would break its own users.
+ resume=lambda session_id: ("--session", session_id),
+ discover=lambda cwd, started, taken, home: _discover_opencode(
+ cwd, started, taken, home
+ ),
+ exists=lambda handle, home: _opencode_conversation_exists(handle, home),
+ ),
+ "kimi": _Adapter(
+ kind="kimi_session",
+ launch=_discovered_launch,
+ # Long form again, and here it is not a preference: the two shipping
+ # generations disagree on the SHORT flag (-C versus -c), so a short one
+ # would mean something different depending on which is installed.
+ resume=lambda session_id: ("--session", session_id),
+ discover=lambda cwd, started, taken, home: _discover_kimi(
+ cwd, started, taken, home
+ ),
+ exists=lambda handle, home: _kimi_conversation_exists(handle, home),
+ ),
}
+def _adapter_for(agent: str) -> _Adapter | None:
+ """The adapter that reopens ``agent``'s conversations.
+
+ Goes through the registry so an entry may name ANOTHER entry's adapter. That
+ is what lets a launch profile over an existing binary — the same CLI pointed
+ at a different vendor — inherit resume exactly rather than owning a second
+ copy of it that can drift.
+ """
+ from jarvis.workspace import agents as workspace_agents
+
+ entry = workspace_agents.get_agent(agent)
+ return _ADAPTERS.get(entry.adapter_key if entry is not None else agent)
+
+
def can_resume(agent: str) -> bool:
"""True when this coding CLI can reopen one of its own conversations."""
- return agent in _ADAPTERS
+ return _adapter_for(agent) is not None
def launch_extra(agent: str) -> tuple[tuple[str, ...], ResumeHandle | None]:
"""Extra argv for a fresh start, plus the handle it will be reachable by.
- A ``None`` handle does not mean "not resumable" — Codex simply cannot be
- told its id, so the handle arrives later through :func:`discover`.
+ A ``None`` handle does not mean "not resumable" — most CLIs cannot be told
+ their id, so the handle arrives later through :func:`discover`.
"""
- adapter = _ADAPTERS.get(agent)
+ adapter = _adapter_for(agent)
if adapter is None:
return ((), None)
return adapter.launch()
@@ -189,7 +232,7 @@ def resume_argv(agent: str, handle: ResumeHandle | None) -> tuple[str, ...] | No
"""
if handle is None:
return None
- adapter = _ADAPTERS.get(agent)
+ adapter = _adapter_for(agent)
if adapter is None or adapter.kind != handle.kind:
return None
return adapter.resume(handle.id)
@@ -217,7 +260,7 @@ def has_conversation(
"""
if handle is None:
return False
- adapter = _ADAPTERS.get(agent)
+ adapter = _adapter_for(agent)
if adapter is None or adapter.kind != handle.kind:
return False
try:
@@ -250,7 +293,7 @@ def discover(
for every agent that does not need discovery (its handle already exists) and
whenever nothing convincing is found.
"""
- adapter = _ADAPTERS.get(agent)
+ adapter = _adapter_for(agent)
if adapter is None or adapter.discover is None:
return None
try:
@@ -480,6 +523,256 @@ def _discover_codex(
return ResumeHandle(kind="codex_rollout", id=best[1], captured_at=best[0])
+# ------------------------------------------------------------------ OpenCode
+def _opencode_data_dir(override: Path | None = None) -> Path:
+ """The directory holding this CLI's session database.
+
+ Follows the XDG data convention it actually uses, on every OS — it does not
+ switch to ``%APPDATA%`` on Windows, so hardcoding a Windows-shaped path here
+ would look right and find nothing.
+ """
+ if override is not None:
+ return Path(override).expanduser()
+ raw = os.environ.get("XDG_DATA_HOME")
+ base = Path(raw).expanduser() if raw else Path.home() / ".local" / "share"
+ return base / "opencode"
+
+
+def _opencode_db(home: Path | None = None) -> Path | None:
+ """The session database, or ``None`` when this CLI has never run here.
+
+ Globbed rather than named: the file name carries the release channel unless
+ that is switched off, so a user on a non-stable channel has a differently
+ named database and a hardcoded name would silently find no sessions at all —
+ which reads as "nothing to resume" rather than as the lookup bug it is.
+ """
+ root = _opencode_data_dir(home)
+ try:
+ candidates = [p for p in root.glob("opencode*.db") if p.is_file()]
+ except OSError:
+ return None
+ if not candidates:
+ return None
+ return max(candidates, key=lambda p: p.stat().st_mtime)
+
+
+def _opencode_rows(
+ home: Path | None, query: str, params: tuple[Any, ...]
+) -> list[tuple[Any, ...]]:
+ """Run a read-only query against the session database.
+
+ Read-only and never ``immutable``: the CLI may well be running and holding a
+ write-ahead log, and declaring the file immutable would hand back a stale
+ snapshot that is missing exactly the session just created — the one every
+ caller here is looking for.
+ """
+ db = _opencode_db(home)
+ if db is None:
+ return []
+ import sqlite3
+
+ try:
+ con = sqlite3.connect(f"file:{db.as_posix()}?mode=ro", uri=True, timeout=1.0)
+ except sqlite3.Error:
+ return []
+ try:
+ return list(con.execute(query, params))
+ except sqlite3.Error as exc:
+ # A schema this build does not recognise is not an error the user can
+ # act on; it costs a fresh conversation, which is the same degradation
+ # every other unreadable history gets.
+ logger.debug("Agentic IDE: opencode session query failed: {}", exc)
+ return []
+ finally:
+ con.close()
+
+
+def _epoch_seconds(value: Any) -> float | None:
+ """A stored timestamp as POSIX seconds, whether it was written in ms or s."""
+ try:
+ number = float(value)
+ except (TypeError, ValueError):
+ return None
+ if number <= 0:
+ return None
+ # Anything past ~5138 in seconds is milliseconds — no real timestamp lands
+ # between the two ranges, so this cannot mis-read a genuine value.
+ return number / 1000.0 if number > 1e11 else number
+
+
+def _opencode_conversation_exists(
+ handle: ResumeHandle, home: Path | None = None
+) -> bool:
+ rows = _opencode_rows(
+ home, "SELECT 1 FROM session WHERE id = ? LIMIT 1", (handle.id,)
+ )
+ return bool(rows)
+
+
+def _discover_opencode(
+ cwd: str,
+ started_at: float,
+ taken: Collection[str] = (),
+ home: Path | None = None,
+) -> ResumeHandle | None:
+ """The session a pane in ``cwd`` started at ``started_at`` created.
+
+ Same matching rule as every other discovered CLI — folder, not already
+ claimed, earliest moment at or after the pane launched — so several panes
+ opened together queue rather than all claiming the first session.
+
+ ``parent_id IS NULL`` is the one CLI-specific part: this agent files its
+ subagents' threads in the same table, and a pane that resumed one of those
+ would reopen a fragment of its own previous run instead of the conversation
+ the user was having.
+ """
+ claimed = {str(t) for t in taken}
+ rows = _opencode_rows(
+ home,
+ "SELECT id, directory, time_created FROM session "
+ "WHERE parent_id IS NULL ORDER BY time_created LIMIT ?",
+ (_MAX_CANDIDATES,),
+ )
+ for session_id, directory, created in rows:
+ session_id = str(session_id or "").strip()
+ if not session_id or session_id in claimed:
+ continue
+ if not isinstance(directory, str) or not _same_folder(directory, cwd):
+ continue
+ stamp = _epoch_seconds(created)
+ if stamp is None or stamp < started_at - _SKEW_S:
+ continue
+ return ResumeHandle(
+ kind="opencode_session", id=session_id, captured_at=stamp
+ )
+ return None
+
+
+# ---------------------------------------------------------------- Kimi Code
+def _kimi_root(home: Path | None = None) -> Path | None:
+ """The data root of whichever generation of this CLI is installed.
+
+ Two generations ship under one binary name and keep separate roots. Asking
+ the registry which one is present — rather than picking one — is what stops
+ a pane reading the other generation's history and reporting "nothing to
+ resume" on a machine that has plenty.
+ """
+ if home is not None:
+ return Path(home).expanduser()
+ from jarvis.workspace import agents as workspace_agents
+
+ generation = workspace_agents.generation_of("kimi")
+ if generation == workspace_agents.KIMI_LEGACY:
+ return Path.home() / ".kimi"
+ if generation == workspace_agents.KIMI_CURRENT:
+ return Path.home() / ".kimi-code"
+ return None
+
+
+def _kimi_folder_key(cwd: str) -> str | None:
+ """The per-working-directory folder name this CLI derives from a path.
+
+ MEASURED against a live install rather than taken from documentation: the
+ folder is the MD5 of the working directory exactly as the OS spells it
+ (``C:\\Users\\...`` on Windows), which is why the native string is hashed and
+ not a normalised or POSIX one.
+
+ This is the ONLY link between a session and the folder it belongs to — the
+ files inside record no working directory — so when the derived folder is
+ absent there is simply nothing to match against, and the caller starts a
+ fresh conversation instead of guessing.
+ """
+ import hashlib
+
+ try:
+ native = str(Path(cwd).expanduser().resolve())
+ except OSError:
+ return None
+ if not native:
+ return None
+ return hashlib.md5(native.encode("utf-8"), usedforsecurity=False).hexdigest()
+
+
+def _kimi_sessions_dir(cwd: str, home: Path | None) -> Path | None:
+ root = _kimi_root(home)
+ key = _kimi_folder_key(cwd)
+ if root is None or key is None:
+ return None
+ folder = root / "sessions" / key
+ return folder if folder.is_dir() else None
+
+
+def _kimi_conversation_exists(
+ handle: ResumeHandle, home: Path | None = None
+) -> bool:
+ """True when this CLI still holds a conversation behind the handle.
+
+ Searched by id across every working-directory folder, for the same reason
+ the Claude check is: the id is unique everywhere, while the folder name is
+ the CLI's own convention and could change without notice.
+ """
+ session_id = handle.id
+ if not session_id or "/" in session_id or "\\" in session_id:
+ return False
+ root = _kimi_root(home)
+ if root is None:
+ return False
+ sessions = root / "sessions"
+ if not sessions.is_dir():
+ return False
+ try:
+ return any(
+ child.is_dir() and any(child.iterdir())
+ for child in sessions.glob(f"*/{session_id}")
+ )
+ except OSError:
+ return False
+
+
+def _discover_kimi(
+ cwd: str,
+ started_at: float,
+ taken: Collection[str] = (),
+ home: Path | None = None,
+) -> ResumeHandle | None:
+ """The session a pane in ``cwd`` started at ``started_at`` created.
+
+ A session here is a DIRECTORY named after its id, so the moment it was
+ created is its own timestamp — no file has to be opened at all, which keeps
+ this the cheapest discovery of the three even for a heavy user.
+
+ An empty directory is skipped: this CLI creates the folder when the session
+ opens and writes into it once the conversation has content, so resuming an
+ empty one reopens nothing and costs the pane its launch.
+ """
+ folder = _kimi_sessions_dir(cwd, home)
+ if folder is None:
+ return None
+ claimed = {str(t) for t in taken}
+ best: tuple[float, str] | None = None
+ try:
+ children = list(folder.iterdir())
+ except OSError:
+ return None
+ for child in children[:_MAX_CANDIDATES]:
+ session_id = child.name
+ if session_id in claimed or not child.is_dir():
+ continue
+ try:
+ if not any(child.iterdir()):
+ continue
+ stamp = child.stat().st_mtime
+ except OSError:
+ continue
+ if stamp < started_at - _SKEW_S:
+ continue
+ if best is None or stamp < best[0]:
+ best = (stamp, session_id)
+ if best is None:
+ return None
+ return ResumeHandle(kind="kimi_session", id=best[1], captured_at=best[0])
+
+
__all__ = [
"ResumeHandle",
"can_resume",
diff --git a/jarvis/agentic_ide/drops.py b/jarvis/agentic_ide/drops.py
index a58f7177b3..e1bb4a86ed 100644
--- a/jarvis/agentic_ide/drops.py
+++ b/jarvis/agentic_ide/drops.py
@@ -210,14 +210,24 @@ def store(
def reference(path: str, *, agent: str) -> str:
"""How ``path`` should be written so ``agent`` picks the file up.
- Claude Code resolves ``@path`` into the file's contents — verified live, the
- file-picker popup does not eat an injected reference. Codex has no such
- syntax, so it gets a quoted path and reads it because the sentence asks it
- to. Quoting matters on both: workspace paths contain spaces far more often
+ Some CLIs resolve ``@path`` into the file's contents — verified live for the
+ ones that declare it, including that the file-picker popup does not eat an
+ injected reference. A CLI without that syntax gets a quoted path and reads
+ it because the sentence asks it to, which works everywhere and is therefore
+ the default a newly registered entry gets.
+
+ Which of the two a CLI wants is registry data, not a name test here: a
+ dropped file is one of the places a wrong guess is invisible — the path goes
+ in, the agent answers, and nobody notices it never opened the file.
+
+ Quoting matters in both forms: workspace paths contain spaces far more often
than people expect ("Personal Jarvis").
"""
+ from jarvis.workspace import agents as workspace_agents
+
posix = path.replace("\\", "/")
- if agent == "claude":
+ spec = workspace_agents.get_agent(agent)
+ if spec is not None and spec.file_reference == "at":
# An @reference containing a space would end at the space, so a path
# that needs quoting is passed plainly instead of half-referenced.
return f"@{posix}" if " " not in posix else f'"{posix}"'
diff --git a/jarvis/agentic_ide/fleet_actions.py b/jarvis/agentic_ide/fleet_actions.py
index 13e7ad7d16..ffe9340fcf 100644
--- a/jarvis/agentic_ide/fleet_actions.py
+++ b/jarvis/agentic_ide/fleet_actions.py
@@ -14,11 +14,26 @@ log = logging.getLogger(__name__)
def _ready_for_prompt(term: Any) -> bool:
+ """Is this pane far enough along to be typed into?
+
+ Every CLI observed so far swallows a prompt that arrives while it is still
+ booting — the keystrokes go nowhere and the user is told the work was sent.
+ So waiting for a real input line is the DEFAULT, and an entry only skips it
+ by declaring so: one CLI has a launch-and-prompt path measured to be stable
+ without the wait, and making it wait would slow down behaviour that already
+ works.
+
+ Getting that default the wrong way round is what a new provider cannot
+ afford. Opting in silently means every CLI registered later loses its first
+ prompt until somebody notices; opting out silently costs one CLI a little
+ speed. The cheap mistake is the one worth defaulting to.
+ """
if getattr(term, "status", "") != "live" or not getattr(term, "pty_id", None):
return False
- # Claude Code already has a stable launch-and-prompt path. Restrict the new
- # startup gate to Codex so that working behaviour stays byte-for-byte fast.
- if getattr(term, "agent", "") != "codex":
+ from jarvis.workspace import agents as workspace_agents
+
+ spec = workspace_agents.get_agent(getattr(term, "agent", ""))
+ if spec is not None and not spec.needs_input_line_wait:
return True
transcript = getattr(term, "transcript", None)
if transcript is None:
@@ -27,7 +42,8 @@ def _ready_for_prompt(term: Any) -> bool:
lines = transcript.tail(30)
except Exception: # noqa: BLE001 - a test double may expose no real buffer
return True
- return any(line.strip().startswith(_INPUT_MARKERS) for line in lines)
+ markers = (spec.input_markers if spec else ()) or _INPUT_MARKERS
+ return any(line.strip().startswith(markers) for line in lines)
async def wait_for_prompt_ready(
diff --git a/jarvis/agentic_ide/recap.py b/jarvis/agentic_ide/recap.py
index 726c0aebbf..6e588d4680 100644
--- a/jarvis/agentic_ide/recap.py
+++ b/jarvis/agentic_ide/recap.py
@@ -92,6 +92,28 @@ _CHROME_FRAGMENTS = (
"plan mode on",
)
+
+def _chrome_fragments() -> tuple[str, ...]:
+ """The shared set, plus whatever the registered CLIs add to it.
+
+ The list above is what every TUI observed so far draws, and it is shared
+ rather than per-CLI on purpose — these phrases are near-universal, and
+ splitting them per product would mean a new entry starting with none of
+ them and its recaps reading "? for shortcuts". An entry adds only its own
+ peculiarities.
+ """
+ try:
+ from jarvis.workspace import agents as workspace_agents
+
+ extra = tuple(
+ fragment.lower()
+ for agent in workspace_agents.coding_agents()
+ for fragment in agent.chrome_fragments
+ )
+ except Exception: # noqa: BLE001 - a recap must never fail on decoration
+ extra = ()
+ return (*_CHROME_FRAGMENTS, *extra)
+
# Leading decoration a TUI puts in front of a real line: bullets, tree glyphs,
# check marks, spinner frames. Stripped so the recap starts on a word. The
# allowed openers are kept out of the class deliberately — a path, a quote or an
@@ -194,7 +216,7 @@ def _informative(line: str) -> bool:
if len(text) < 4 or text.startswith(_INPUT_MARKERS):
return False
lowered = text.lower()
- if any(fragment in lowered for fragment in _CHROME_FRAGMENTS):
+ if any(fragment in lowered for fragment in _chrome_fragments()):
return False
# A row of numbers, punctuation or box residue is not a sentence.
return sum(1 for ch in text if ch.isalpha()) >= 3
diff --git a/tests/unit/agentic_ide/conftest.py b/tests/unit/agentic_ide/conftest.py
index 399707bc3e..8a96a0a4da 100644
--- a/tests/unit/agentic_ide/conftest.py
+++ b/tests/unit/agentic_ide/conftest.py
@@ -69,10 +69,31 @@ def _agent_history_in_tmp(
that history. Pointed at the real one they would inherit whatever the
developer happens to have on disk — a test could pass because an unrelated
conversation was lying around, or fail on a fresh machine.
+
+ The per-CLI variables are read from the registry rather than listed here, so
+ a CLI registered later is redirected without anybody remembering to add it.
+ The two that resolve their history from the home directory instead of a
+ variable are redirected at their own seam, for the same reason: a test that
+ can reach the developer's real history is a test that will, eventually.
"""
+ from jarvis.agentic_ide import agent_sessions
+ from jarvis.workspace import agents as workspace_agents
+
home = tmp_path_factory.mktemp("agent-history")
- monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(home / "claude"))
- monkeypatch.setenv("CODEX_HOME", str(home / "codex"))
+ for entry in workspace_agents.coding_agents():
+ for variable, template in (entry.account.env if entry.account else ()):
+ monkeypatch.setenv(variable, template.format(dir=home / entry.name))
+ # This CLI follows the XDG data convention on every OS, so one variable
+ # moves its whole session database.
+ monkeypatch.setenv("XDG_DATA_HOME", str(home / "xdg"))
+ # And this one derives its root from the home directory with no variable at
+ # all, so the seam is the only place to intercept it.
+ kimi_root = home / "kimi"
+ monkeypatch.setattr(
+ agent_sessions,
+ "_kimi_root",
+ lambda override=None: Path(override) if override else kimi_root,
+ )
return home
@@ -99,16 +120,37 @@ def existing_conversation() -> Any:
"""
from jarvis.agentic_ide import agent_sessions
+ def _claude(session_id: str) -> None:
+ folder = agent_sessions._claude_home() / "projects" / "a-project"
+ folder.mkdir(parents=True, exist_ok=True)
+ (folder / f"{session_id}.jsonl").write_text("{}\n", encoding="utf-8")
+
+ def _codex(session_id: str) -> None:
+ folder = agent_sessions._codex_home() / "sessions" / "2026" / "07" / "26"
+ folder.mkdir(parents=True, exist_ok=True)
+ (folder / f"rollout-2026-07-26T00-00-00-{session_id}.jsonl").write_text(
+ "{}\n", encoding="utf-8"
+ )
+
+ def _kimi(session_id: str) -> None:
+ # One directory per session, named after the id, under a folder named
+ # after the working directory — the layout measured on a live install.
+ folder = agent_sessions._kimi_root() / "sessions" / "a-project" / session_id
+ folder.mkdir(parents=True, exist_ok=True)
+ (folder / "context.jsonl").write_text("{}\n", encoding="utf-8")
+
+ # One writer per session STORE. A CLI whose store this table does not know
+ # falls to the last entry, which would quietly build a conversation the CLI
+ # under test never reads — so an unknown agent raises instead.
+ writers = {"claude": _claude, "codex": _codex, "kimi": _kimi}
+
def _make(session_id: str, *, agent: str = "claude") -> None:
- if agent == "claude":
- folder = agent_sessions._claude_home() / "projects" / "a-project"
- folder.mkdir(parents=True, exist_ok=True)
- (folder / f"{session_id}.jsonl").write_text("{}\n", encoding="utf-8")
- else:
- folder = agent_sessions._codex_home() / "sessions" / "2026" / "07" / "26"
- folder.mkdir(parents=True, exist_ok=True)
- (folder / f"rollout-2026-07-26T00-00-00-{session_id}.jsonl").write_text(
- "{}\n", encoding="utf-8"
+ writer = writers.get(agent)
+ if writer is None:
+ raise AssertionError(
+ f"No conversation writer for {agent!r} — add one here rather "
+ "than letting the test read another CLI's history."
)
+ writer(session_id)
return _make
diff --git a/tests/unit/agentic_ide/test_new_cli_providers.py b/tests/unit/agentic_ide/test_new_cli_providers.py
new file mode 100644
index 0000000000..f19d31136a
--- /dev/null
+++ b/tests/unit/agentic_ide/test_new_cli_providers.py
@@ -0,0 +1,315 @@
+"""The three CLI providers added alongside Claude Code and Codex.
+
+Each of them exercises a different half of the registry contract, which is why
+they are worth testing together rather than one file per product:
+
+* **OpenCode** is a plain standalone CLI whose sessions live in a database, so
+ it proves the discover-after-launch path works against something that is not
+ a directory of files.
+* **Kimi Code** ships as two generations under one binary name, so it proves the
+ generation probe reaches the launch and history paths.
+* **GLM** is not a CLI at all — it is the Claude Code binary pointed at another
+ vendor — so it proves a launch profile inherits behaviour without duplicating
+ it, and that the environment it depends on is never half-applied.
+"""
+
+from __future__ import annotations
+
+import sqlite3
+import time
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from jarvis.agentic_ide import agent_sessions, drops
+from jarvis.agentic_ide.fleet_actions import _ready_for_prompt
+from jarvis.workspace import agents as workspace_agents
+
+# --------------------------------------------------------------- the registry
+
+
+def test_every_new_provider_is_launchable_and_installable() -> None:
+ """A registered entry must answer the three questions a pane asks of it."""
+ for name in ("opencode", "kimi", "glm"):
+ entry = workspace_agents.get_agent(name)
+ assert entry is not None, f"{name} is not registered"
+ assert entry.is_coding_agent
+ assert entry.executable, f"{name} resolves to no binary"
+ assert workspace_agents.install_command(name)
+
+
+def test_a_two_part_version_string_is_not_read_as_no_version() -> None:
+ """"kimi, version 1.3" must parse — a blank version reads as a broken install."""
+ import re
+
+ entry = workspace_agents.get_agent("kimi")
+ assert entry is not None and entry.spec is not None
+ match = re.search(entry.spec.version_parse_regex, "kimi, version 1.3")
+ assert match is not None and match.group(1) == "1.3"
+ # The three-part form still works, so an upgrade does not lose the version.
+ three = re.search(entry.spec.version_parse_regex, "kimi, version 1.3.7")
+ assert three is not None and three.group(1) == "1.3.7"
+
+
+def test_a_product_name_can_never_become_a_pane_call_sign() -> None:
+ """Saying "Kimi" must address the CLI, not a pane that happens to be called that."""
+ reserved = workspace_agents.reserved_call_signs()
+ for spoken in ("kimi", "opencode", "glm", "claude", "codex"):
+ assert spoken in reserved
+ from jarvis.agentic_ide import names
+
+ assert not {n.lower() for n in names.NAME_POOL} & reserved
+
+
+# ------------------------------------------------------------------ OpenCode
+
+
+def _opencode_db(root: Path) -> Path:
+ """A database with the real schema's load-bearing columns."""
+ data = root / "xdg" / "opencode"
+ data.mkdir(parents=True, exist_ok=True)
+ db = data / "opencode.db"
+ con = sqlite3.connect(db)
+ con.execute(
+ "CREATE TABLE session (id TEXT PRIMARY KEY, project_id TEXT, "
+ "parent_id TEXT, directory TEXT NOT NULL, time_created INTEGER NOT NULL)"
+ )
+ con.commit()
+ con.close()
+ return db
+
+
+def _add_session(
+ db: Path, session_id: str, directory: str, created_s: float, parent: str | None = None
+) -> None:
+ con = sqlite3.connect(db)
+ con.execute(
+ "INSERT INTO session (id, project_id, parent_id, directory, time_created) "
+ "VALUES (?, 'p', ?, ?, ?)",
+ (session_id, parent, directory, int(created_s * 1000)),
+ )
+ con.commit()
+ con.close()
+
+
+def test_opencode_finds_the_session_its_own_pane_created(
+ _agent_history_in_tmp: Path, tmp_path: Path
+) -> None:
+ db = _opencode_db(_agent_history_in_tmp)
+ started = time.time()
+ _add_session(db, "ses_new", str(tmp_path), started + 1)
+ handle = agent_sessions.discover("opencode", str(tmp_path), started)
+ assert handle is not None
+ assert handle.kind == "opencode_session"
+ assert handle.id == "ses_new"
+ assert agent_sessions.resume_argv("opencode", handle) == ("--session", "ses_new")
+ assert agent_sessions.has_conversation("opencode", handle) is True
+
+
+def test_opencode_ignores_another_folder_and_an_older_session(
+ _agent_history_in_tmp: Path, tmp_path: Path
+) -> None:
+ db = _opencode_db(_agent_history_in_tmp)
+ started = time.time()
+ _add_session(db, "ses_elsewhere", str(tmp_path / "other"), started + 1)
+ _add_session(db, "ses_before", str(tmp_path), started - 600)
+ assert agent_sessions.discover("opencode", str(tmp_path), started) is None
+
+
+def test_opencode_never_resumes_a_subagents_own_thread(
+ _agent_history_in_tmp: Path, tmp_path: Path
+) -> None:
+ """A pane must reopen the conversation, not a fragment of its own last run."""
+ db = _opencode_db(_agent_history_in_tmp)
+ started = time.time()
+ _add_session(db, "ses_child", str(tmp_path), started + 1, parent="ses_parent")
+ assert agent_sessions.discover("opencode", str(tmp_path), started) is None
+
+
+def test_two_opencode_panes_in_one_folder_get_different_conversations(
+ _agent_history_in_tmp: Path, tmp_path: Path
+) -> None:
+ """The failure this claim check exists for: both panes taking session one."""
+ db = _opencode_db(_agent_history_in_tmp)
+ started = time.time()
+ _add_session(db, "ses_a", str(tmp_path), started + 1)
+ _add_session(db, "ses_b", str(tmp_path), started + 2)
+ first = agent_sessions.discover("opencode", str(tmp_path), started)
+ assert first is not None
+ second = agent_sessions.discover(
+ "opencode", str(tmp_path), started, taken=[first.id]
+ )
+ assert second is not None
+ assert second.id != first.id
+
+
+def test_a_missing_opencode_database_starts_fresh_instead_of_raising(
+ tmp_path: Path,
+) -> None:
+ assert agent_sessions.discover("opencode", str(tmp_path), time.time()) is None
+ handle = agent_sessions.ResumeHandle("opencode_session", "ses_x", time.time())
+ assert agent_sessions.has_conversation("opencode", handle) is False
+
+
+# ----------------------------------------------------------------- Kimi Code
+
+
+def test_kimi_finds_the_session_directory_its_pane_created(
+ _agent_history_in_tmp: Path, tmp_path: Path
+) -> None:
+ started = time.time()
+ key = agent_sessions._kimi_folder_key(str(tmp_path))
+ assert key is not None
+ folder = _agent_history_in_tmp / "kimi" / "sessions" / key / "sess-1"
+ folder.mkdir(parents=True)
+ (folder / "context.jsonl").write_text("{}\n", encoding="utf-8")
+ handle = agent_sessions.discover("kimi", str(tmp_path), started - 5)
+ assert handle is not None
+ assert handle.kind == "kimi_session"
+ assert handle.id == "sess-1"
+ assert agent_sessions.resume_argv("kimi", handle) == ("--session", "sess-1")
+
+
+def test_kimi_skips_a_session_folder_with_nothing_in_it(
+ _agent_history_in_tmp: Path, tmp_path: Path
+) -> None:
+ """An opened-but-never-used pane leaves an empty folder; resuming it kills the pane."""
+ key = agent_sessions._kimi_folder_key(str(tmp_path))
+ assert key is not None
+ (_agent_history_in_tmp / "kimi" / "sessions" / key / "sess-empty").mkdir(parents=True)
+ assert agent_sessions.discover("kimi", str(tmp_path), time.time() - 5) is None
+
+
+def test_kimi_folder_key_is_derived_from_the_native_path(tmp_path: Path) -> None:
+ """The only link between a session and its folder — so it must be stable."""
+ import hashlib
+
+ expected = hashlib.md5(
+ str(tmp_path.resolve()).encode("utf-8"), usedforsecurity=False
+ ).hexdigest()
+ assert agent_sessions._kimi_folder_key(str(tmp_path)) == expected
+
+
+def test_the_kimi_generation_probe_reads_the_data_root(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """Two generations, one binary name — and the wrong flags on the wrong one."""
+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path))
+ assert workspace_agents.kimi_generation() is None
+ (tmp_path / ".kimi").mkdir()
+ assert workspace_agents.kimi_generation() == workspace_agents.KIMI_LEGACY
+ (tmp_path / ".kimi-code").mkdir()
+ assert workspace_agents.kimi_generation() == workspace_agents.KIMI_CURRENT
+
+
+# ------------------------------------------------------------------- GLM
+
+
+def test_glm_runs_the_borrowed_binary_and_inherits_its_resume() -> None:
+ """It is a launch profile, not a CLI: nothing about it may be a second copy."""
+ entry = workspace_agents.get_agent("glm")
+ assert entry is not None
+ assert entry.executable == "claude"
+ assert entry.adapter_key == "claude"
+ argv, handle = agent_sessions.launch_extra("glm")
+ assert handle is not None and handle.kind == "claude_session"
+ assert argv[0] == "--session-id"
+ assert agent_sessions.resume_argv("glm", handle) == ("--resume", handle.id)
+ # A handle from a genuinely different CLI is still refused.
+ foreign = agent_sessions.ResumeHandle("codex_rollout", handle.id, time.time())
+ assert agent_sessions.resume_argv("glm", foreign) is None
+
+
+def test_a_glm_pane_without_a_key_refuses_to_open(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The wrong-vendor trap: a half-set environment answers, and bills, elsewhere."""
+ from jarvis.agentic_ide import session as ide_session
+
+ monkeypatch.setattr("jarvis.core.config.get_secret", lambda *_a, **_k: None)
+ with pytest.raises(ide_session.SessionError):
+ ide_session.agent_spawn_overlay("glm")
+
+
+def test_a_configured_glm_pane_carries_the_endpoint_and_hides_a_stray_key(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from jarvis.agentic_ide import session as ide_session
+
+ monkeypatch.setattr("jarvis.core.config.get_secret", lambda *_a, **_k: "tok")
+ overlay = ide_session.agent_spawn_overlay("glm")
+ assert overlay["ANTHROPIC_BASE_URL"].startswith("http")
+ assert overlay["ANTHROPIC_AUTH_TOKEN"] == "tok"
+ assert int(overlay["API_TIMEOUT_MS"]) >= 60_000
+ # Empty means "remove from the child": a host key would otherwise outrank
+ # the token and the pane would quietly answer from the other vendor.
+ assert overlay["ANTHROPIC_API_KEY"] == ""
+ # A plain Claude Code pane in the same workspace is untouched.
+ assert ide_session.agent_spawn_overlay("claude") == {}
+
+
+def test_the_glm_environment_factory_reports_not_configured_without_a_key(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ "jarvis.core.config.get_secret", lambda *_a, **_k: None
+ )
+ assert workspace_agents.glm_spawn_env() is None
+
+
+def test_the_glm_environment_pins_no_model_the_user_did_not_choose(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Vendor docs disagree on the ids, so a guessed default fails at request time."""
+ monkeypatch.setattr("jarvis.core.config.get_secret", lambda *_a, **_k: "tok")
+ env = workspace_agents.glm_spawn_env()
+ assert env is not None
+ assert env["ANTHROPIC_AUTH_TOKEN"] == "tok"
+ assert "ANTHROPIC_DEFAULT_SONNET_MODEL" not in env
+
+
+# ------------------------------------------------- per-CLI pane behaviour
+
+
+def test_a_dropped_file_is_written_the_way_each_cli_reads_it() -> None:
+ at_style = drops.reference("/w/a b.py", agent="claude")
+ assert at_style == '"/w/a b.py"' # a space would end the @reference early
+ assert drops.reference("/w/a.py", agent="claude") == "@/w/a.py"
+ assert drops.reference("/w/a.py", agent="opencode") == "@/w/a.py"
+ assert drops.reference("/w/a.py", agent="codex") == '"/w/a.py"'
+ # An entry nobody has registered gets the form that works everywhere.
+ assert drops.reference("/w/a.py", agent="nope") == '"/w/a.py"'
+
+
+class _Pane:
+ def __init__(self, agent: str, lines: tuple[str, ...] = ()) -> None:
+ self.agent = agent
+ self.status = "live"
+ self.pty_id = "pty-1"
+ self._lines = lines
+
+ @property
+ def transcript(self) -> Any:
+ lines = self._lines
+
+ class _T:
+ @staticmethod
+ def tail(_n: int) -> tuple[str, ...]:
+ return lines
+
+ return _T()
+
+
+def test_a_booting_pane_of_a_new_cli_is_not_prompted_yet() -> None:
+ """Waiting is the default; a CLI opts out, it does not opt in.
+
+ The cheap mistake and the expensive one are not symmetric: opting in
+ silently means every CLI registered later loses its first prompt with no
+ error anywhere, while opting out silently costs one CLI a little speed.
+ """
+ assert _ready_for_prompt(_Pane("opencode", ("Loading...",))) is False
+ assert _ready_for_prompt(_Pane("opencode", ("> ",))) is True
+ assert _ready_for_prompt(_Pane("kimi", ("starting",))) is False
+ # The one measured exception keeps its fast path.
+ assert _ready_for_prompt(_Pane("claude", ("anything",))) is True