Skip to content

Reason Network: your team's coding agents, talking to each other. The engine behind `reason network`.

A Gemini session is one session, its MCP server's and its hooks' (#145)

Lars Taliana8086b6a02de
diff --git a/DESIGN.md b/DESIGN.md
index b1b89dc..eecc43d 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -259,9 +259,13 @@ session connection also receives pushed `deliver` events for its sessions.
**Session registration**, by priority:
1. Per-call `_meta`: Codex `sessionId` (the root thread, same id its hooks see), opencode V2 `ai.opencode/sessionID`.
2. Env: `REASON_NETWORK_SESSION` (set by our pi extension), else the agent's own: `CLAUDE_CODE_SESSION_ID` (Claude),
- `CODEX_THREAD_ID` (Codex), `OPENCODE_SESSION_ID` (opencode), `GEMINI_SESSION_ID` (Gemini), `COPILOT_AGENT_SESSION_ID`
- (Copilot), `GROK_SESSION_ID` (Grok).
-3. Hook stdin `session_id` (`SessionStart`), correlated to the MCP process by agent PID ancestry.
+ `CODEX_THREAD_ID` (Codex), `OPENCODE_SESSION_ID` (opencode), `COPILOT_AGENT_SESSION_ID` (Copilot),
+ `GROK_SESSION_ID` (Grok).
+3. Hook stdin `session_id` (`SessionStart`), for Gemini, which gives its MCP servers no id (`GEMINI_SESSION_ID` is in its
+ hooks' env only): the one session the hooks of the MCP server's agent process (its parent, past a shell) registered,
+ asked on each call so `/clear` is followed. At start the MCP server waits up to 20 s for those hooks; registered by
+ process after all, it moves to their session once they come. A new conversation's `SessionStart` ends the one
+ before in the same process, and `SessionEnd` ends one though its MCP server is still connected.
4. Fallback: one session per MCP process.
The key is `<agent>:<id>`, and it is what a name is kept for (above). Where each agent's id comes from:
@@ -273,7 +277,7 @@ The key is `<agent>:<id>`, and it is what a name is kept for (above). Where each
| opencode | session id | `_meta["ai.opencode/sessionID"]`, `OPENCODE_SESSION_ID`, the plugin's `--session` |
| pi | session id | the extension's `REASON_NETWORK_SESSION` and `--session` |
| Cursor | conversation id | hooks' `conversation_id` (its shared MCP server takes the session its hooks registered) |
-| Gemini CLI | session id | `GEMINI_SESSION_ID`, hooks' `session_id` |
+| Gemini CLI | session id | hooks' `session_id` (its MCP server takes the session its process's hooks registered) |
| Copilot CLI | session id | `COPILOT_AGENT_SESSION_ID`, hooks' `sessionId` |
| Grok CLI | session id | `GROK_SESSION_ID`, hooks' `session_id` |
| Reason | session id | `reason session list` |
diff --git a/src/agent.rs b/src/agent.rs
index 9d0b154..4657e76 100644
--- a/src/agent.rs
+++ b/src/agent.rs
@@ -199,6 +199,18 @@ fn executable(p: &Path) -> bool {
p.is_file()
}
+/// Agents that give their MCP servers no session id, only their hooks: their MCP server goes by the session the hooks
+/// of its own agent process registered. Gemini (`GEMINI_SESSION_ID` is in its hooks' env only).
+pub fn session_from_hooks(agent: &str) -> bool {
+ agent == "gemini"
+}
+
+/// The agent process we serve, as [`hook_agent_pid`] finds it for a hook: found once (each step up can run `ps`).
+pub fn agent_process() -> Option<u32> {
+ static PID: std::sync::OnceLock<Option<u32>> = std::sync::OnceLock::new();
+ *PID.get_or_init(hook_agent_pid)
+}
+
/// The agent process behind a hook: our parent, skipping the shell some agents run hooks through.
pub fn hook_agent_pid() -> Option<u32> {
let mut pid = util::parent_pid();
@@ -441,6 +453,14 @@ mod tests {
std::fs::remove_dir_all(&dir).unwrap();
}
+ #[test]
+ fn only_geminis_mcp_server_goes_by_its_hooks_session() {
+ assert!(session_from_hooks("gemini"));
+ for a in [CLAUDE_CODE, "codex", "cursor", "opencode", "copilot", "grok", "pi", "zed", ""] {
+ assert!(!session_from_hooks(a), "{a}");
+ }
+ }
+
#[test]
fn the_claude_process_is_the_nearest_ancestor_with_a_registry_entry() {
// 900 (us) ← 800 (a shell) ← 700 (Claude Code, with an entry) ← 600 (another Claude Code, with one) ← 1.
diff --git a/src/daemon/mod.rs b/src/daemon/mod.rs
index 6f9c11c..e318a86 100644
--- a/src/daemon/mod.rs
+++ b/src/daemon/mod.rs
@@ -343,6 +343,7 @@ impl Daemon {
}
Request::Hook(h) => json!(self.hook(h).await?),
Request::Attach { agent, cwd } => json!(self.attach(&agent, &cwd)?),
+ Request::Linked { agent, pid } => json!(self.linked(&agent, pid)),
Request::CreateTeam { name, person, relay, proof } => {
json!(self.create_team(&name, &person, relay, proof).await?)
}
diff --git a/src/daemon/sessions.rs b/src/daemon/sessions.rs
index ad9174d..156aab0 100644
--- a/src/daemon/sessions.rs
+++ b/src/daemon/sessions.rs
@@ -80,6 +80,18 @@ impl Daemon {
.collect();
self.moved_on(g, before, now);
}
+ // A Gemini window is in one conversation at a time: its hooks starting another (`/clear`, `/new`) end the one
+ // before, which its MCP server, outliving it, may still have. Never one registered by process (an older MCP
+ // server's).
+ if conn.is_none() && agent::session_from_hooks(&reg.agent) && reg.pid.is_some() && !g.live.contains_key(&key) {
+ let before: Vec<String> = g
+ .live
+ .iter()
+ .filter(|(k, l)| l.reg.agent == reg.agent && l.reg.pid == reg.pid && !k.starts_with("proc:"))
+ .map(|(k, _)| k.clone())
+ .collect();
+ self.moved_on(g, before, now);
+ }
if let Some(l) = g.live.get_mut(&key) {
// Known already (e.g. from a hook, now the MCP server connects, or a reconnect).
if conn.is_some() {
@@ -330,7 +342,8 @@ impl Daemon {
self.inner.lock().unwrap().off.remove(&key);
if event == "end" {
let mut g = self.inner.lock().unwrap();
- if g.live.get(&key).is_some_and(|l| l.conn.is_none())
+ // Gemini's MCP server outlives a conversation (`/clear`): its hooks say when one ends.
+ if g.live.get(&key).is_some_and(|l| l.conn.is_none() || agent::session_from_hooks(agent))
&& let Some(l) = g.live.remove(&key)
{
let _ = g.store.touch_session(&l.name, now);
@@ -449,6 +462,25 @@ impl Daemon {
Ok(key)
}
+ /// The session id `agent`'s live process `pid` is in, as its hooks registered it: for its MCP server, which the
+ /// agent gives no session id (Gemini). None unless exactly one session is its process's.
+ pub(super) fn linked(&self, agent: &str, pid: u32) -> Option<String> {
+ if !agent::session_from_hooks(agent) || !util::pid_alive(pid) {
+ return None;
+ }
+ let mut g = self.inner.lock().unwrap();
+ self.prune(&mut g);
+ let mut ids = g
+ .live
+ .values()
+ .filter(|l| l.reg.agent == agent && l.reg.pid == Some(pid) && !l.reg.key.starts_with("proc:"))
+ .map(|l| l.reg.agent_session_id.clone());
+ match (ids.next(), ids.next()) {
+ (Some(id), None) => id,
+ _ => None,
+ }
+ }
+
pub(super) fn drop_conn(&self, conn: u64) {
let now = util::now_ms();
let mut g = self.inner.lock().unwrap();
@@ -1099,6 +1131,103 @@ mod tests {
}
}
+ /// A Gemini hook from process `pid`, and its MCP server registering `key` over its connection `conn`.
+ fn gemini_hook(id: &str, event: &str, pid: u32) -> HookCall {
+ HookCall { pid: Some(pid), ..gemini(id, event) }
+ }
+
+ fn gemini_mcp(d: &Daemon, conn: u64, key: &str, pid: u32) {
+ let id = key.strip_prefix("gemini:").map(str::to_string);
+ let reg = SessionReg { agent_session_id: id, pid: Some(pid), ..named(key, "gemini", None) };
+ d.register_quiet(Some(conn), reg, GitInfo::default()).unwrap();
+ }
+
+ fn live_sessions(d: &Daemon) -> Vec<(String, String, Tier)> {
+ let g = d.inner.lock().unwrap();
+ let mut v: Vec<_> = g.live.iter().map(|(k, l)| (k.clone(), l.name.clone(), l.reg.tier)).collect();
+ v.sort();
+ v
+ }
+
+ /// A process that has exited.
+ fn gone_pid() -> u32 {
+ let mut child = std::process::Command::new(std::env::current_exe().unwrap())
+ .arg("--list")
+ .stdout(std::process::Stdio::null())
+ .spawn()
+ .unwrap();
+ child.wait().unwrap();
+ child.id()
+ }
+
+ #[tokio::test]
+ async fn geminis_mcp_server_goes_by_the_session_its_hooks_registered() {
+ // Gemini gives its MCP servers no session id, only its hooks: its MCP server asks for the session the hooks of
+ // its own process registered, and registers that, which keeps its hooks' tier.
+ let d = Arc::new(super::super::test_daemon(Default::default()));
+ let (me, other) = (std::process::id(), util::parent_pid());
+ d.hook(gemini_hook("g1", "start", me)).await.unwrap();
+ assert_eq!(d.linked("gemini", me).as_deref(), Some("g1"));
+ assert_eq!(d.linked("gemini", other), None);
+ gemini_mcp(&d, 1, "gemini:g1", me);
+ assert_eq!(live_sessions(&d), [("gemini:g1".into(), "api-gemini".into(), Tier::Turn)]);
+ // Only Gemini's: agents whose MCP calls name the session, or that share one MCP server, never ask.
+ let mut cursor = gemini_hook("c1", "start", me);
+ cursor.agent = "cursor".into();
+ d.hook(cursor).await.unwrap();
+ assert_eq!((d.linked("cursor", me), d.linked("claude-code", me), d.linked("codex", me)), (None, None, None));
+ }
+
+ #[tokio::test]
+ async fn an_older_gemini_mcp_server_keeps_the_session_it_registered_by_process() {
+ // An MCP server from before (or one whose hooks were late) registered by its process: its hooks coming never
+ // take that key away, so it keeps working across an upgrade.
+ let d = Arc::new(super::super::test_daemon(Default::default()));
+ let me = std::process::id();
+ gemini_mcp(&d, 7, "proc:7", me);
+ d.hook(gemini_hook("g2", "start", me)).await.unwrap();
+ let keys: Vec<String> = live_sessions(&d).into_iter().map(|(k, ..)| k).collect();
+ assert_eq!(keys, ["gemini:g2", "proc:7"]);
+ // A current one goes by its hooks' session from then on: over the same connection, that ends its own.
+ gemini_mcp(&d, 7, "gemini:g2", me);
+ assert_eq!(live_sessions(&d), [("gemini:g2".into(), "api-gemini-2".into(), Tier::Turn)]);
+ }
+
+ #[tokio::test]
+ async fn a_new_conversation_in_a_gemini_window_ends_the_one_before() {
+ let d = Arc::new(super::super::test_daemon(Default::default()));
+ let me = std::process::id();
+ d.hook(gemini_hook("g1", "start", me)).await.unwrap();
+ gemini_mcp(&d, 3, "gemini:g1", me);
+ // `/clear`: SessionEnd, then SessionStart with a new id, the same MCP server throughout.
+ d.hook(gemini_hook("g1", "end", me)).await.unwrap();
+ assert_eq!(live_sessions(&d), []);
+ d.hook(gemini_hook("g2", "start", me)).await.unwrap();
+ assert_eq!(d.linked("gemini", me).as_deref(), Some("g2"));
+ gemini_mcp(&d, 3, "gemini:g2", me);
+ assert_eq!(live_sessions(&d).len(), 1);
+ // A SessionEnd that never came: the next conversation's start ends this one all the same. An older MCP
+ // server's session, registered by process, stays.
+ gemini_mcp(&d, 9, "proc:9", me);
+ d.hook(gemini_hook("g3", "start", me)).await.unwrap();
+ let keys: Vec<String> = live_sessions(&d).into_iter().map(|(k, ..)| k).collect();
+ assert_eq!(keys, ["gemini:g3", "proc:9"]);
+ }
+
+ #[tokio::test]
+ async fn no_session_is_linked_when_it_is_unclear_or_its_process_is_gone() {
+ let d = Arc::new(super::super::test_daemon(Default::default()));
+ let me = std::process::id();
+ // Two of its process's sessions: neither is taken for the other.
+ d.hook(gemini_hook("g1", "start", me)).await.unwrap();
+ gemini_mcp(&d, 5, "gemini:g9", me);
+ assert_eq!(d.linked("gemini", me), None);
+ // A process that has exited (its id may be some other process's soon).
+ let gone = gone_pid();
+ d.hook(gemini_hook("g4", "start", gone)).await.unwrap();
+ assert_eq!(d.linked("gemini", gone), None);
+ }
+
#[tokio::test]
async fn a_session_its_hooks_hand_mail_to_keeps_its_name() {
// Gemini is reached through its hooks only: no MCP connection or push channel ever.
diff --git a/src/mcp.rs b/src/mcp.rs
index 1f86fb4..9560db4 100644
--- a/src/mcp.rs
+++ b/src/mcp.rs
@@ -23,7 +23,10 @@ use schemars::JsonSchema;
use serde::Deserialize;
use serde_json::Value;
use std::{
- sync::{Arc, Mutex},
+ sync::{
+ Arc, Mutex,
+ atomic::{AtomicBool, Ordering},
+ },
time::Duration,
};
use tokio::sync::mpsc;
@@ -91,6 +94,8 @@ pub struct ReasonNetworkMcp {
claude: Arc<Mutex<Option<Arc<ClaudeSocket>>>>,
/// The agent named by the client's `clientInfo`, once known.
client_agent: Arc<Mutex<Option<&'static str>>>,
+ /// Gemini: it has gone by its hooks' session (so between two conversations, the next is waited for).
+ hooks_linked: Arc<AtomicBool>,
tool_router: ToolRouter<Self>,
}
@@ -101,6 +106,7 @@ pub async fn run() -> Result<()> {
env_agent: agent::detect_env(),
claude: Default::default(),
client_agent: Default::default(),
+ hooks_linked: Default::default(),
tool_router: ReasonNetworkMcp::tool_router(),
};
let service = server.clone().serve(stdio()).await?;
@@ -118,11 +124,31 @@ pub async fn run() -> Result<()> {
tokio::spawn(async move {
tokio::time::sleep(Duration::from_secs(3)).await;
let agent = s.agent(&peer, None);
- if !agent::multiplexed(agent)
- && !off_here()
- && let Err(e) = s.session(agent, None).await
- {
- eprintln!("reason-network: registering session: {e:#}");
+ if agent::multiplexed(agent) || off_here() {
+ return;
+ }
+ // Gemini's hooks name its session, and can take seconds to run (PowerShell on Windows): they are waited for
+ // a while before it is registered by process.
+ let hooks = agent::session_from_hooks(agent);
+ for _ in 0..if hooks { 40 } else { 0 } {
+ if s.linked(agent).await.is_some() {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ }
+ match s.session(agent, None).await {
+ Err(e) => eprintln!("reason-network: registering session: {e:#}"),
+ // Registered by process after all: once its hooks turn up, it goes by their session.
+ Ok(key) if hooks && key.starts_with("proc:") => {
+ for _ in 0..60 {
+ tokio::time::sleep(Duration::from_secs(2)).await;
+ if s.linked(agent).await.is_some() {
+ let _ = s.session(agent, None).await;
+ break;
+ }
+ }
+ }
+ Ok(_) => {}
}
});
@@ -317,7 +343,22 @@ impl ReasonNetworkMcp {
_ => {}
}
}
- let id = meta_id.or_else(|| agent::env_session_id(agent));
+ let mut id = meta_id.or_else(|| agent::env_session_id(agent));
+ // Gemini gives its MCP servers no session id, only its hooks: the session they registered for its process.
+ // Asked each time, so a new conversation in the same window (`/clear`) is followed.
+ if id.is_none() && agent::session_from_hooks(agent) {
+ id = self.linked(agent).await;
+ // Between one conversation's end and the next one's start (`/clear`): the next, a moment.
+ for _ in 0..if self.hooks_linked.load(Ordering::Relaxed) { 10 } else { 0 } {
+ if id.is_some() {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ id = self.linked(agent).await;
+ }
+ // Waited for once per gap: a next conversation that never starts doesn't slow every later call.
+ self.hooks_linked.store(id.is_some(), Ordering::Relaxed);
+ }
let key = match &id {
Some(id) => format!("{agent}:{id}"),
None => format!("proc:{}", std::process::id()),
@@ -334,7 +375,14 @@ impl ReasonNetworkMcp {
agent_session_id: id,
// Claude Code's own process, as its registry names it: the daemon's scan of the registry matches it. None
// when that isn't known: any other process (a parent's) would get this session ended as that one moves on.
- pid: if agent == agent::CLAUDE_CODE { agent::claude_pid() } else { Some(agent::agent_pid()) },
+ pid: if agent == agent::CLAUDE_CODE {
+ agent::claude_pid()
+ } else if agent::session_from_hooks(agent) {
+ // The process its hooks name (past a shell), so the two are told to be one.
+ agent::agent_process()
+ } else {
+ Some(agent::agent_pid())
+ },
tier,
name: None,
};
@@ -342,6 +390,12 @@ impl ReasonNetworkMcp {
Ok(key)
}
+ /// The session id the hooks of our agent process registered, if any (an older daemon doesn't know the request).
+ async fn linked(&self, agent: &str) -> Option<String> {
+ let pid = agent::agent_process()?;
+ self.link.call::<Option<String>>(Request::Linked { agent: agent.into(), pid }).await.ok().flatten()
+ }
+
/// Tool result text, plus a note about unread mail so pull-only agents notice it, and how to join a team on a
/// machine that isn't in one.
async fn finish(&self, key: &str, res: Result<String>, notice: bool) -> CallToolResult {
diff --git a/src/proto.rs b/src/proto.rs
index 988396e..d59809a 100644
--- a/src/proto.rs
+++ b/src/proto.rs
@@ -169,6 +169,12 @@ pub enum Request {
agent: String,
cwd: String,
},
+ /// For agents that give their MCP servers no session id, only their hooks (Gemini): the session id the hooks of
+ /// agent process `pid` registered, if any.
+ Linked {
+ agent: String,
+ pid: u32,
+ },
CreateTeam {
name: String,
person: String,
diff --git a/tests/e2e/gemini.py b/tests/e2e/gemini.py
new file mode 100644
index 0000000..9ab2d65
--- /dev/null
+++ b/tests/e2e/gemini.py
@@ -0,0 +1,161 @@
+"""Gemini CLI windows against one isolated daemon, launched the way Gemini 0.65 does it: each window is its own process
+(standing in for Gemini's node), which runs its hooks through a shell (`powershell -NoProfile -Command` on Windows,
+`sh -c` elsewhere) with GEMINI_SESSION_ID in the hooks' env only, and starts `reason-network mcp` directly with no
+session id. A window is one session, at its hooks' tier, and the one its agent speaks as.
+
+ cargo build && python3 tests/e2e/gemini.py
+"""
+import json, os, subprocess, sys, tempfile, threading, time
+
+ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+EXE = ".exe" if os.name == "nt" else ""
+BIN = os.path.join(ROOT, "target", "debug", "reason-network" + EXE)
+UTF8 = dict(text=True, encoding="utf-8", errors="replace")
+
+
+def window(proj, base):
+ """The stand-in Gemini process: one command per line on stdin (mcp, start <id>, end <id>, call, call-bg and
+ call-join for a call left running meanwhile, close), one JSON answer line each."""
+ def hook(event, sid, name):
+ payload = json.dumps({"session_id": sid, "cwd": proj, "hook_event_name": name})
+ env = dict(base, GEMINI_CLI="1", GEMINI_PROJECT_DIR=proj, GEMINI_CWD=proj, GEMINI_SESSION_ID=sid)
+ cmd = f'& "{BIN}" hook gemini {event}' if os.name == "nt" else f'"{BIN}" hook gemini {event}'
+ shell = ["powershell", "-NoProfile", "-Command", cmd] if os.name == "nt" else ["sh", "-c", cmd]
+ subprocess.run(shell, input=payload, env=env, cwd=proj, capture_output=True, timeout=60, **UTF8)
+
+ def rpc(msg):
+ mcp.stdin.write(json.dumps(msg) + "\n")
+ mcp.stdin.flush()
+ while "id" in msg:
+ r = json.loads(mcp.stdout.readline())
+ if r.get("id") == msg["id"]:
+ return r
+
+ def you():
+ r = rpc({"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "list_team", "arguments": {}}})
+ return " | ".join(l for l in r["result"]["content"][0]["text"].splitlines() if "← you" in l)
+
+ mcp, bg = None, {}
+ for line in sys.stdin:
+ cmd, _, arg = line.strip().partition(" ")
+ out = ""
+ if cmd == "mcp":
+ mcp = subprocess.Popen([BIN, "mcp"], env=dict(base, GEMINI_CLI="1", REASON_NETWORK_AGENT="gemini"),
+ cwd=proj, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
+ stderr=subprocess.DEVNULL, **UTF8)
+ rpc({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {
+ "protocolVersion": "2025-06-18", "capabilities": {},
+ "clientInfo": {"name": "gemini-cli-mcp-client", "version": "0.65.0"}}})
+ rpc({"jsonrpc": "2.0", "method": "notifications/initialized"})
+ elif cmd in ("start", "end"):
+ hook(f"session-{cmd}", arg, "SessionStart" if cmd == "start" else "SessionEnd")
+ elif cmd == "call":
+ out = you()
+ elif cmd == "call-bg":
+ bg["t"] = threading.Thread(target=lambda: bg.update(out=you()))
+ bg["t"].start()
+ elif cmd == "call-join":
+ bg["t"].join(timeout=60)
+ out = bg.get("out", "")
+ elif cmd == "close":
+ mcp.stdin.close()
+ mcp.wait(timeout=30)
+ print(json.dumps(out), flush=True)
+
+
+def main():
+ d = tempfile.mkdtemp(prefix="reason-network-gemini-")
+ proj = os.path.join(d, "app")
+ os.makedirs(proj)
+ base = {k: v for k, v in os.environ.items() if not k.startswith(("CLAUDE", "CODEX", "GEMINI", "REASON_NETWORK", "TINCAN"))}
+ base.update(REASON_NETWORK_HOME=os.path.join(d, "home"), REASON_NETWORK_NO_MDNS="1", REASON_NETWORK_NO_SERVICE="1",
+ REASON_NETWORK_NO_TRAY="1", REASON_NETWORK_NO_UPDATE="1", REASON_NETWORK_MACHINE="box")
+ results = []
+
+ def check(name, ok, detail=""):
+ results.append(ok)
+ print(f"{'PASS' if ok else 'FAIL'}: {name}" + ("" if ok else f"\n {detail}"), flush=True)
+
+ def cli(*args):
+ r = subprocess.run([BIN, *args], env=base, capture_output=True, timeout=60, **UTF8)
+ return (r.stdout + r.stderr).strip()
+
+ def sessions():
+ rows = json.loads(cli("who", "--json") or "{}")
+ rows = rows.get("sessions", rows) if isinstance(rows, dict) else rows
+ return sorted((s.get("name"), s.get("tier")) for s in rows if isinstance(s, dict) and s.get("agent") == "gemini")
+
+ def watch(secs):
+ """What `who` lists over `secs`: every change, in order."""
+ seen, end = [], time.time() + secs
+ while time.time() < end:
+ now = sessions()
+ if not seen or now != seen[-1]:
+ seen.append(now)
+ time.sleep(0.25)
+ return seen
+
+ def open_window():
+ g = subprocess.Popen([sys.executable, os.path.abspath(__file__), "--window", proj, json.dumps(base)],
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, **UTF8)
+
+ def do(cmd):
+ g.stdin.write(cmd + "\n")
+ g.stdin.flush()
+ return json.loads(g.stdout.readline())
+
+ return g, do
+
+ cli("init", "gemini", "--as", "alex", "--no-setup")
+
+ # Its hooks soon after its MCP server starts, as Gemini goes.
+ g, do = open_window()
+ do("mcp")
+ do("start s-1")
+ seen = watch(5)
+ check("a window is one session, at its hooks' tier", seen[-1] == [("app-gemini", "turn")] and all(len(s) <= 1 for s in seen), seen)
+ check("…and the one its agent speaks as", " app-gemini " in f" {do('call')} ", do("call"))
+ # `/clear`: SessionEnd, a new id, SessionStart, the same MCP server throughout; a call made in between waits for
+ # the new conversation.
+ do("end s-1")
+ do("call-bg")
+ time.sleep(1)
+ do("start s-2")
+ between = do("call-join")
+ seen = watch(2)
+ check("/clear: the window is one session again, the new conversation", len(seen[-1]) == 1 and seen[-1][0][1] == "turn", seen)
+ me = do("call")
+ check("…which its agent now speaks as, also in a call made in between",
+ bool(seen[-1]) and f" {seen[-1][0][0]} " in f" {me} " and f" {seen[-1][0][0]} " in f" {between} ", (me, between))
+ do("close")
+ do("end s-2")
+ g.stdin.close()
+ g.wait(timeout=30)
+ check("closing the window leaves no session", watch(1)[-1] == [], sessions())
+
+ # Hooks that take seconds (PowerShell on Windows): its MCP server waits for them, never a second session.
+ g, do = open_window()
+ do("mcp")
+ time.sleep(6)
+ check("before its hooks, no session by process yet", sessions() == [], sessions())
+ do("start s-3")
+ seen = watch(3)
+ check("slow hooks: one session, at its hooks' tier", len(seen[-1]) == 1 and seen[-1][0][1] == "turn" and all(len(s) <= 1 for s in seen), seen)
+ me = do("call")
+ check("…which its agent speaks as", bool(seen[-1]) and f" {seen[-1][0][0]} " in f" {me} ", me)
+ do("close")
+ do("end s-3")
+ g.stdin.close()
+ g.wait(timeout=30)
+ check("closing it leaves no session", watch(1)[-1] == [], sessions())
+
+ cli("stop")
+ print(f"\n{sum(results)}/{len(results)} gemini checks passed (state in {d})")
+ sys.exit(0 if all(results) else 1)
+
+
+if __name__ == "__main__":
+ if sys.argv[1:2] == ["--window"]:
+ window(sys.argv[2], json.loads(sys.argv[3]))
+ else:
+ main()