Skip to content

An always-on second brain you talk to. Voice notes in Telegram → typed, linked knowledge in your Obsidian vault. Runs 24/7 on the Claude subscription you already have.

feat(session): interactive tmux ClaudeSession driver

smixsc78c424eef76
diff --git a/src/d_brain/services/claude_session.py b/src/d_brain/services/claude_session.py
new file mode 100644
index 0000000..dc81172
--- /dev/null
+++ b/src/d_brain/services/claude_session.py
@@ -0,0 +1,356 @@
+"""Drive a persistent INTERACTIVE Claude Code session inside a tmux pane.
+
+This is the core of the post-2026-06-15 design: instead of spawning
+`claude -p` per request (which moves to a paid Agent SDK credit), we keep
+one long-lived interactive `claude` alive in tmux and "type" prompts into
+it. Interactive usage stays on the subscription.
+
+All access to the pane goes through a single cross-process file lock
+(`pane.lock`) so the bot, the daily pipeline and the watchdog never talk to
+the pane at once. The watchdog recovers a wedged session via
+``force_recover()`` (non-blocking lock), and ``ask()`` self-detects a stall
+(no new bytes in pane.log) so it releases the lock quickly instead of
+holding it for the full timeout.
+
+Pure text parsing lives in tmux_parse; this module only orchestrates tmux
+and timing, so it is tested with a fake runner + injected clock/sleep/rid.
+
+NOTE: runtime_dir must be on a LOCAL filesystem — fcntl.flock is unreliable
+on NFS/9p and would silently degrade to no serialization.
+"""
+
+import fcntl
+import logging
+import os
+import shlex
+import subprocess
+import time
+import uuid
+from collections.abc import Callable
+from contextlib import contextmanager
+from dataclasses import dataclass
+from pathlib import Path
+
+from d_brain.services.tmux_parse import (
+ PaneState,
+ classify_state,
+ extract_reply,
+ is_complete,
+)
+
+logger = logging.getLogger(__name__)
+
+Runner = Callable[..., subprocess.CompletedProcess]
+
+DEFAULT_TIMEOUT = 1200 # 20 min, matches the old subprocess pipeline
+DEFAULT_STALL_TIMEOUT = 180 # no new pane bytes for this long ⇒ wedged
+_PANE_WIDTH = "200"
+# Height 50 (not taller): the TUI draws its footer (idle ❯ / bypass line)
+# just below content, so on a tall pane the footer lands mid-screen with a
+# blank bottom — and chrome-region state detection misses it. At 50 the
+# footer sits near the bottom. Long replies are still captured via scrollback.
+_PANE_HEIGHT = "50"
+# Scrollback lines to capture. NOTE (verified live on tmux 3.6b): `-S -` and
+# large counts like `-S -2000` return EMPTY on this TUI; a modest concrete
+# count works and includes scrollback (pane history ~2000 lines).
+_CAPTURE_SCROLLBACK = "-200"
+
+
+@dataclass
+class AskResult:
+ """Outcome of a single ask() round."""
+
+ status: str # "ok" | "rate_limited" | "logged_out" | "timeout" | "error"
+ reply: str | None = None
+ detail: str | None = None
+
+ @property
+ def ok(self) -> bool:
+ return self.status == "ok"
+
+
+class ClaudeSession:
+ """A single interactive Claude Code session in a named tmux session."""
+
+ def __init__(
+ self,
+ session_name: str,
+ work_dir: Path,
+ runtime_dir: Path,
+ *,
+ mcp_config: Path | None = None,
+ system_prompt_file: Path | None = None,
+ model: str | None = None,
+ claude_bin: str = "claude",
+ runner: Runner = subprocess.run,
+ sleep_fn: Callable[[float], None] = time.sleep,
+ clock_fn: Callable[[], float] = time.monotonic,
+ rid_factory: Callable[[], str] | None = None,
+ liveness_fn: Callable[[], float] | None = None,
+ poll_interval: float = 1.0,
+ paste_settle: float = 0.3,
+ startup_timeout: float = 90.0,
+ stall_timeout: float = DEFAULT_STALL_TIMEOUT,
+ ) -> None:
+ self.session_name = session_name
+ self.work_dir = Path(work_dir)
+ self.runtime_dir = Path(runtime_dir)
+ self.runtime_dir.mkdir(parents=True, exist_ok=True)
+ self.mcp_config = Path(mcp_config) if mcp_config else None
+ self.system_prompt_file = (
+ Path(system_prompt_file) if system_prompt_file else None
+ )
+ self.model = model
+ self.claude_bin = claude_bin
+ self._runner = runner
+ self._sleep = sleep_fn
+ self._clock = clock_fn
+ self._rid_factory = rid_factory or (lambda: uuid.uuid4().hex[:8])
+ self._liveness_fn = liveness_fn or self._pane_log_mtime
+ self._poll_interval = poll_interval
+ self._paste_settle = paste_settle
+ self._startup_timeout = startup_timeout
+ self._stall_timeout = stall_timeout
+
+ # Address the session's active window/pane by name. A fixed ":0.0"
+ # breaks under `base-index 1` (window 0 won't exist) → empty capture.
+ self._target = session_name
+ self._pane_log = self.runtime_dir / "pane.log"
+ self._ready_flag = self.runtime_dir / "ready"
+ self._inflight = self.runtime_dir / "inflight"
+ self._pane_lock = self.runtime_dir / "pane.lock"
+
+ # ── tmux helpers ─────────────────────────────────────────────────
+
+ def _tmux(self, *args: str) -> subprocess.CompletedProcess:
+ proc = self._runner(
+ ["tmux", *args], capture_output=True, text=True, check=False
+ )
+ if proc.returncode != 0:
+ logger.warning(
+ "tmux %s failed (rc=%s): %s",
+ args[0],
+ proc.returncode,
+ (proc.stderr or "").strip(),
+ )
+ return proc
+
+ def _capture(self) -> str:
+ return self._tmux(
+ "capture-pane", "-t", self._target, "-p", "-S", _CAPTURE_SCROLLBACK
+ ).stdout
+
+ def _session_exists(self) -> bool:
+ return self._tmux("has-session", "-t", self.session_name).returncode == 0
+
+ def _send_enter(self) -> None:
+ self._tmux("send-keys", "-t", self._target, "Enter")
+
+ def _interrupt(self) -> None:
+ self._tmux("send-keys", "-t", self._target, "C-c")
+
+ def _pane_log_mtime(self) -> float:
+ try:
+ return self._pane_log.stat().st_mtime
+ except OSError:
+ return 0.0
+
+ # ── file lock (single lock; see module docstring) ────────────────
+
+ @contextmanager
+ def _locked(self, *, blocking: bool = True):
+ fd = os.open(self._pane_lock, os.O_CREAT | os.O_RDWR, 0o644)
+ acquired = False
+ try:
+ flags = fcntl.LOCK_EX | (0 if blocking else fcntl.LOCK_NB)
+ fcntl.flock(fd, flags)
+ acquired = True
+ yield True
+ except BlockingIOError:
+ yield False
+ finally:
+ if acquired:
+ fcntl.flock(fd, fcntl.LOCK_UN)
+ os.close(fd)
+
+ # ── lifecycle ────────────────────────────────────────────────────
+
+ def _start_command(self) -> str:
+ parts = [shlex.quote(self.claude_bin), "--dangerously-skip-permissions"]
+ if self.mcp_config:
+ parts += ["--mcp-config", shlex.quote(str(self.mcp_config))]
+ if self.system_prompt_file:
+ parts += [
+ "--append-system-prompt",
+ f'"$(cat {shlex.quote(str(self.system_prompt_file))})"',
+ ]
+ if self.model:
+ parts += ["--model", shlex.quote(self.model)]
+ return f"cd {shlex.quote(str(self.work_dir))} && " + " ".join(parts)
+
+ def _ensure_locked(self) -> None:
+ """Create + ready the session if needed. Caller must hold the lock."""
+ if self._session_exists():
+ return
+ self._ready_flag.unlink(missing_ok=True)
+ self._tmux(
+ "new-session",
+ "-d",
+ "-s",
+ self.session_name,
+ "-x",
+ _PANE_WIDTH,
+ "-y",
+ _PANE_HEIGHT,
+ self._start_command(),
+ )
+ self._tmux(
+ "pipe-pane",
+ "-t",
+ self._target,
+ f"cat >> {shlex.quote(str(self._pane_log))}",
+ )
+
+ deadline = self._clock() + self._startup_timeout
+ last_state: PaneState | None = None
+ while self._clock() < deadline:
+ cap = self._capture()
+ state = classify_state(cap)
+ # Debounce: only Enter on the transition INTO the trust prompt,
+ # never on every poll (avoids stray blank submissions).
+ if state == PaneState.TRUST_PROMPT:
+ if last_state != PaneState.TRUST_PROMPT:
+ self._send_enter()
+ last_state = state
+ self._sleep(self._poll_interval)
+ continue
+ if state == PaneState.READY:
+ self._ready_flag.write_text("ready\n")
+ logger.info("Claude session %s is ready", self.session_name)
+ return
+ last_state = state
+ self._sleep(self._poll_interval)
+ raise RuntimeError(
+ f"session {self.session_name} not ready in {self._startup_timeout}s; "
+ f"last state={last_state}; pane tail:\n"
+ + "\n".join(self._capture().splitlines()[-8:])
+ )
+
+ def ensure_session(self) -> None:
+ with self._locked() as got:
+ if got:
+ self._ensure_locked()
+
+ def is_healthy(self) -> bool:
+ return self._session_exists()
+
+ def force_recover(self) -> bool:
+ """Watchdog entry point: take the lock non-blocking; if free, kill and
+ recreate. Returns False if a live ask() currently holds the lock."""
+ with self._locked(blocking=False) as got:
+ if not got:
+ return False
+ self._tmux("kill-session", "-t", self.session_name)
+ self._ready_flag.unlink(missing_ok=True)
+ self._inflight.unlink(missing_ok=True)
+ self._ensure_locked()
+ return True
+
+ def kill(self) -> None:
+ """Tear down the session (lock-guarded). For CLI/teardown use."""
+ with self._locked() as got:
+ if got:
+ self._tmux("kill-session", "-t", self.session_name)
+ self._ready_flag.unlink(missing_ok=True)
+ self._inflight.unlink(missing_ok=True)
+
+ def clear(self) -> None:
+ """Manual recovery only (durable-state-first: no scheduled clear)."""
+ with self._locked() as got:
+ if got:
+ self._send_text("/clear")
+ self._send_enter()
+
+ # ── sending ──────────────────────────────────────────────────────
+
+ def _send_text(self, text: str) -> None:
+ buf = f"dbrain_{uuid.uuid4().hex[:6]}"
+ self._tmux("set-buffer", "-b", buf, text)
+ self._tmux("paste-buffer", "-t", self._target, "-b", buf, "-d")
+ self._sleep(self._paste_settle)
+
+ def _send_prompt(self, prompt: str, rid: str) -> None:
+ # Markers are written INLINE (mid-sentence) so the input echo never
+ # forms a line-anchored pair; only the model's answer does.
+ payload = (
+ f"{prompt}\n\n"
+ f"When done, wrap your ENTIRE reply between a line containing only "
+ f"<<<R:{rid}>>> and a line containing only <<<E:{rid}>>>."
+ )
+ self._send_text(payload)
+ self._send_enter()
+
+ # ── ask ──────────────────────────────────────────────────────────
+
+ def ask(
+ self,
+ prompt: str,
+ *,
+ timeout: float = DEFAULT_TIMEOUT,
+ request_id: str | None = None,
+ ) -> AskResult:
+ """Send a prompt, return the model's reply (or a non-ok status).
+
+ Lock-guarded so concurrent callers serialize on the pane. Never
+ raises and never blocks forever: ensure failure → error, rate-limit /
+ logged-out short-circuit, a frozen pane (stall) is interrupted, and a
+ hard timeout returns a timeout status. request_id is for logging only;
+ the marker rid is always freshly generated to avoid stale answers.
+ """
+ rid = self._rid_factory()
+ log_id = request_id or rid
+ with self._locked() as got:
+ if not got: # only happens with non-blocking; blocking=True here
+ return AskResult("error", detail="could not acquire pane lock")
+ try:
+ self._ensure_locked()
+ except Exception as exc: # noqa: BLE001 — must never escape ask()
+ logger.error("ensure_session failed for %s: %s", log_id, exc)
+ return AskResult("error", detail=f"session start failed: {exc}")
+
+ pre = classify_state(self._capture())
+ if pre == PaneState.RATE_LIMITED:
+ return AskResult("rate_limited")
+ if pre == PaneState.LOGGED_OUT:
+ return AskResult("logged_out")
+
+ self._inflight.write_text(f"{log_id}\n{self._clock()}\n")
+ self._send_prompt(prompt, rid)
+
+ last_live = self._liveness_fn()
+ last_change = self._clock()
+ deadline = self._clock() + timeout
+ while self._clock() < deadline:
+ cap = self._capture()
+ state = classify_state(cap)
+ if state == PaneState.RATE_LIMITED:
+ self._inflight.unlink(missing_ok=True)
+ return AskResult("rate_limited")
+ if state == PaneState.LOGGED_OUT:
+ self._inflight.unlink(missing_ok=True)
+ return AskResult("logged_out")
+ if is_complete(cap, rid):
+ self._inflight.unlink(missing_ok=True)
+ return AskResult("ok", reply=extract_reply(cap, rid))
+
+ live = self._liveness_fn()
+ if live != last_live:
+ last_live, last_change = live, self._clock()
+ elif self._clock() - last_change > self._stall_timeout:
+ self._interrupt()
+ # leave inflight as an orphan/stuck signal for the watchdog
+ return AskResult("error", detail="session stalled (no output)")
+ self._sleep(self._poll_interval)
+
+ # timed out: prompt is still physically in the pane → keep inflight
+ return AskResult("timeout", detail=f"no reply in {timeout}s")
diff --git a/src/d_brain/services/tmux_parse.py b/src/d_brain/services/tmux_parse.py
index 0e70dbf..e41d833 100644
--- a/src/d_brain/services/tmux_parse.py
+++ b/src/d_brain/services/tmux_parse.py
@@ -43,8 +43,11 @@ def _require_rid(rid: str) -> None:
def _line_anchored(rid: str, kind: str) -> re.Pattern[str]:
- # Own line, tolerating leading/trailing whitespace and a trailing CR.
- return re.compile(rf"(?m)^[ \t]*<<<{kind}:{re.escape(rid)}>>>[ \t]*\r?$")
+ # The marker must be at the END of its line (only whitespace after it).
+ # Any prefix is allowed — Claude Code prefixes the first answer line with
+ # "⏺ " and indents the rest. The input echo has TEXT after the marker
+ # ("<<<R:id>>> and a line..."), so it never matches end-of-line.
+ return re.compile(rf"(?m)^.*?<<<{kind}:{re.escape(rid)}>>>[ \t]*\r?$")
def extract_reply(text: str, rid: str) -> str | None:
@@ -104,8 +107,12 @@ _LOGGED_OUT_RE = re.compile(
r"authentication (failed|required|expired)|session expired",
re.I,
)
-# READY: idle prompt (allow ghost suggestions after ❯) or the bypass footer.
-_READY_RE = re.compile(r"(?m)^\s*❯|bypass permissions on")
+# READY signals. The bypass footer is our always-present anchor (we launch
+# with --dangerously-skip-permissions); it can sit above a blank bottom, so
+# it is matched over the WHOLE pane. The idle ❯ is a secondary signal matched
+# only in chrome (a bare ❯ elsewhere could be model output).
+_FOOTER_RE = re.compile(r"bypass permissions on")
+_IDLE_RE = re.compile(r"(?m)^\s*❯")
_STARTING_RE = re.compile(r"Claude Code v\d", re.I)
@@ -122,14 +129,18 @@ def classify_state(text: str) -> PaneState:
"""
if not text.strip():
return PaneState.UNKNOWN
- chrome = _chrome(text)
- if _TRUST_MENU_RE.search(chrome):
+ # TRUST is a full-screen modal whose menu sits at the TOP; on a tall pane
+ # the chrome (bottom) is blank, so match it over the WHOLE pane. Safe
+ # because it anchors on the numbered menu line, which the model cannot
+ # reproduce verbatim in a reply.
+ if _TRUST_MENU_RE.search(text):
return PaneState.TRUST_PROMPT
+ chrome = _chrome(text)
if _RATE_RE.search(chrome):
return PaneState.RATE_LIMITED
if _LOGGED_OUT_RE.search(chrome):
return PaneState.LOGGED_OUT
- if _READY_RE.search(chrome):
+ if _FOOTER_RE.search(text) or _IDLE_RE.search(chrome):
return PaneState.READY
if _STARTING_RE.search(text):
return PaneState.STARTING
diff --git a/tests/test_claude_session.py b/tests/test_claude_session.py
new file mode 100644
index 0000000..80c54a0
--- /dev/null
+++ b/tests/test_claude_session.py
@@ -0,0 +1,257 @@
+"""Tests for ClaudeSession orchestration.
+
+The real tmux/subprocess layer is replaced by FakeTmux, which models the
+pane as a small state machine and returns scripted capture-pane output.
+Clock, sleep, rid generation and liveness are injected so polling, timeout
+and stall detection are deterministic and fast.
+"""
+
+import subprocess
+from pathlib import Path
+
+import pytest
+
+from d_brain.services.claude_session import AskResult, ClaudeSession
+
+READY = (
+ "────────────────────\n❯\n────────────────────\n"
+ " hello | Opus 4.8 (1M context) | ~/p\n"
+ " ⏵⏵ bypass permissions on (shift+tab to cycle)\n"
+)
+TRUST = (
+ " Quick safety check: Is this a project you created or one you trust?\n"
+ " ❯ 1. Yes, I trust this folder\n 2. No, exit\n"
+)
+THINKING = " ✻ Working… (esc to interrupt)\n"
+RATE = " You've reached your usage limit. Your limit resets at 3:00 PM.\n❯\n"
+LOGGED_OUT = " Invalid API key · Please run /login to authenticate.\n❯\n"
+
+
+def _complete(rid: str, reply: str = "PONG") -> str:
+ return f"some echo <<<R:{rid}>>> inline\n<<<R:{rid}>>>\n{reply}\n<<<E:{rid}>>>\n❯\n"
+
+
+def _inline_echo(rid: str) -> str:
+ """Echo of the typed prompt: markers appear INLINE (mid-sentence)."""
+ return f"> reply, wrap between <<<R:{rid}>>> and <<<E:{rid}>>> markers\n{THINKING}"
+
+
+class FakeTmux:
+ """Callable stand-in for subprocess.run over `tmux ...`."""
+
+ def __init__(self, capture_script: list[str], exists: bool = False) -> None:
+ self._captures = list(capture_script)
+ self.exists = exists
+ self.calls: list[list[str]] = []
+
+ def __call__(self, args, **kwargs): # noqa: ANN001
+ self.calls.append(args)
+ sub = args[1] if args and args[0] == "tmux" else args[0]
+ out, rc = "", 0
+ if sub == "has-session":
+ rc = 0 if self.exists else 1
+ elif sub == "new-session":
+ self.exists = True
+ elif sub == "capture-pane":
+ out = (
+ self._captures.pop(0)
+ if len(self._captures) > 1
+ else (self._captures[0] if self._captures else "")
+ )
+ return subprocess.CompletedProcess(args, rc, stdout=out, stderr="")
+
+ def sent_subcommands(self) -> list[str]:
+ return [c[1] for c in self.calls if c and c[0] == "tmux"]
+
+ def sent_keys(self) -> list[list[str]]:
+ return [c for c in self.calls if len(c) > 1 and c[1] == "send-keys"]
+
+ def enter_count(self) -> int:
+ return sum(1 for c in self.sent_keys() if c[-1] == "Enter")
+
+
+def clock():
+ return {"now": 0.0}
+
+
+def make_session(
+ tmp_path: Path,
+ fake: FakeTmux,
+ clock: dict,
+ *,
+ rid: str = "rid00001",
+ liveness=None,
+) -> ClaudeSession:
+ def sleep_fn(seconds: float) -> None:
+ clock["now"] += seconds
+
+ return ClaudeSession(
+ session_name="dbrain_test",
+ work_dir=tmp_path / "vault",
+ runtime_dir=tmp_path / ".dbrain",
+ runner=fake,
+ sleep_fn=sleep_fn,
+ clock_fn=lambda: clock["now"],
+ rid_factory=lambda: rid,
+ liveness_fn=liveness or (lambda: clock["now"]), # default: always "fresh"
+ poll_interval=1.0,
+ startup_timeout=30.0,
+ stall_timeout=10.0,
+ )
+
+
+# ── ensure_session ──────────────────────────────────────────────────────
+
+
+def test_ensure_session_creates_when_absent(tmp_path, clock):
+ fake = FakeTmux([READY], exists=False)
+ s = make_session(tmp_path, fake, clock)
+ s.ensure_session()
+ assert "new-session" in fake.sent_subcommands()
+ assert "pipe-pane" in fake.sent_subcommands()
+ assert (tmp_path / ".dbrain" / "ready").exists()
+
+
+def test_ensure_session_noop_when_present(tmp_path, clock):
+ fake = FakeTmux([READY], exists=True)
+ s = make_session(tmp_path, fake, clock)
+ s.ensure_session()
+ assert "new-session" not in fake.sent_subcommands()
+
+
+def test_ensure_session_handles_trust_prompt(tmp_path, clock):
+ fake = FakeTmux([TRUST, READY], exists=False)
+ s = make_session(tmp_path, fake, clock)
+ s.ensure_session()
+ assert fake.enter_count() >= 1
+
+
+def test_ensure_session_does_not_enter_spam_on_trust(tmp_path, clock):
+ """Trust persists for several captures; Enter must be debounced to the
+ transition, not sent on every poll (M2)."""
+ fake = FakeTmux([TRUST, TRUST, TRUST, READY], exists=False)
+ s = make_session(tmp_path, fake, clock)
+ s.ensure_session()
+ assert fake.enter_count() == 1
+
+
+def test_ensure_session_raises_if_never_ready(tmp_path, clock):
+ fake = FakeTmux([THINKING], exists=False)
+ s = make_session(tmp_path, fake, clock)
+ with pytest.raises(RuntimeError):
+ s.ensure_session()
+
+
+# ── ask ─────────────────────────────────────────────────────────────────
+
+
+def test_ask_returns_reply_on_completion(tmp_path, clock):
+ rid = "abcd0001"
+ fake = FakeTmux([READY, THINKING, _complete(rid)], exists=True)
+ s = make_session(tmp_path, fake, clock, rid=rid)
+ res = s.ask("ping", timeout=60)
+ assert isinstance(res, AskResult)
+ assert res.ok
+ assert res.reply == "PONG"
+
+
+def test_ask_ignores_inline_echo_contamination(tmp_path, clock):
+ """The echoed prompt has inline markers; ask must NOT complete on it,
+ only on the real line-anchored answer (H1 at session level)."""
+ rid = "echo0001"
+ fake = FakeTmux([READY, _inline_echo(rid), _complete(rid)], exists=True)
+ s = make_session(tmp_path, fake, clock, rid=rid)
+ res = s.ask("ping", timeout=60)
+ assert res.reply == "PONG"
+
+
+def test_ask_detects_rate_limit_without_hanging(tmp_path, clock):
+ fake = FakeTmux([RATE], exists=True)
+ s = make_session(tmp_path, fake, clock)
+ res = s.ask("ping", timeout=60)
+ assert res.status == "rate_limited"
+ assert not res.ok
+
+
+def test_ask_detects_logged_out(tmp_path, clock):
+ fake = FakeTmux([LOGGED_OUT], exists=True)
+ s = make_session(tmp_path, fake, clock)
+ res = s.ask("ping", timeout=60)
+ assert res.status == "logged_out"
+
+
+def test_ask_times_out_when_no_reply(tmp_path, clock):
+ fake = FakeTmux([READY, THINKING], exists=True)
+ # liveness keeps advancing (output flowing) so it's a timeout, not a stall
+ s = make_session(tmp_path, fake, clock, liveness=lambda: clock["now"])
+ res = s.ask("ping", timeout=3)
+ assert res.status == "timeout"
+
+
+def test_ask_detects_stall_and_interrupts(tmp_path, clock):
+ """No new bytes (frozen liveness) longer than stall_timeout → stall, not
+ a 20-min hang. Must interrupt and return promptly (C1)."""
+ fake = FakeTmux([READY, THINKING], exists=True)
+ s = make_session(tmp_path, fake, clock, liveness=lambda: 42.0) # frozen
+ res = s.ask("ping", timeout=600)
+ assert res.status == "error"
+ assert "stall" in (res.detail or "").lower()
+ assert any(c[-1] == "C-c" for c in fake.sent_keys())
+
+
+def test_ask_returns_error_when_ensure_fails(tmp_path, clock):
+ """ensure_session failing must surface as AskResult('error'), never an
+ exception out of ask() (C2)."""
+ fake = FakeTmux([THINKING], exists=False) # never becomes READY
+ s = make_session(tmp_path, fake, clock)
+ res = s.ask("ping", timeout=60)
+ assert res.status == "error"
+
+
+def test_ask_leaves_inflight_orphan_on_timeout(tmp_path, clock):
+ """A timed-out prompt is still physically in the pane; inflight marker
+ must persist as a stuck-signal (M6)."""
+ fake = FakeTmux([READY, THINKING], exists=True)
+ s = make_session(tmp_path, fake, clock, liveness=lambda: clock["now"])
+ s.ask("ping", timeout=3)
+ assert (tmp_path / ".dbrain" / "inflight").exists()
+
+
+def test_ask_clears_inflight_on_success(tmp_path, clock):
+ rid = "abcd0005"
+ fake = FakeTmux([READY, _complete(rid)], exists=True)
+ s = make_session(tmp_path, fake, clock, rid=rid)
+ s.ask("ping", timeout=60)
+ assert not (tmp_path / ".dbrain" / "inflight").exists()
+
+
+def test_ask_sends_prompt_via_buffer_then_enter(tmp_path, clock):
+ rid = "abcd0006"
+ fake = FakeTmux([READY, _complete(rid)], exists=True)
+ s = make_session(tmp_path, fake, clock, rid=rid)
+ s.ask("do the thing", timeout=60)
+ assert "paste-buffer" in fake.sent_subcommands()
+ assert any(c[-1] == "Enter" for c in fake.sent_keys())
+
+
+# ── health ──────────────────────────────────────────────────────────────
+
+
+def test_is_healthy_true_when_session_exists(tmp_path, clock):
+ fake = FakeTmux([READY], exists=True)
+ s = make_session(tmp_path, fake, clock)
+ assert s.is_healthy() is True
+
+
+def test_is_healthy_false_when_absent(tmp_path, clock):
+ fake = FakeTmux([READY], exists=False)
+ s = make_session(tmp_path, fake, clock)
+ assert s.is_healthy() is False
+
+
+def test_kill_sends_kill_session(tmp_path, clock):
+ fake = FakeTmux([READY], exists=True)
+ s = make_session(tmp_path, fake, clock)
+ s.kill()
+ assert "kill-session" in fake.sent_subcommands()
diff --git a/tests/test_tmux_parse.py b/tests/test_tmux_parse.py
index 2d2681d..8266baa 100644
--- a/tests/test_tmux_parse.py
+++ b/tests/test_tmux_parse.py
@@ -89,6 +89,15 @@ def test_extract_reply_takes_line_anchored_pair_not_inline_echo():
assert extract_reply(text, rid) == "PONG"
+def test_extract_reply_with_tui_bullet_prefix():
+ """Regression (live): Claude Code prefixes the first answer line with
+ '⏺ ' and indents the rest. The marker is at the END of its line; that,
+ not 'starts the line', is what distinguishes answer from inline echo."""
+ rid = "bull1234"
+ text = f"⏺ <<<R:{rid}>>>\n PONG\n <<<E:{rid}>>>\n❯\n"
+ assert extract_reply(text, rid) == "PONG"
+
+
def test_extract_reply_multiline_answer():
rid = "abc12345"
text = f"<<<R:{rid}>>>\nline one\nline two\n<<<E:{rid}>>>\n"
@@ -184,6 +193,14 @@ def test_classify_ready_without_bypass_footer():
assert classify_state(READY_NO_BYPASS_CAPTURE) == PaneState.READY
+def test_classify_ready_when_footer_above_empty_bottom():
+ """Regression (live): the TUI draws content at the top and leaves the
+ bottom of the screen blank, so the footer (bypass/idle) is NOT in the
+ chrome region. READY must still be detected via the footer anchor."""
+ text = READY_CAPTURE + "\n" * 30
+ assert classify_state(text) == PaneState.READY
+
+
def test_classify_starting():
assert classify_state(STARTING_CAPTURE) == PaneState.STARTING
@@ -246,6 +263,14 @@ def test_classify_no_false_positive_trust_in_body():
)
+def test_classify_trust_when_menu_above_empty_chrome():
+ """Regression (found in live integration): the trust dialog is a
+ full-screen modal drawn at the TOP; on a tall pane the bottom 18 lines
+ (chrome) are blank. Trust must still be detected over the whole pane."""
+ text = TRUST_CAPTURE + "\n" * 40
+ assert classify_state(text) == PaneState.TRUST_PROMPT
+
+
def test_classify_priority_stack_trust_first():
"""When several signatures co-occur in the chrome, TRUST wins (it must be
answered before anything else is meaningful)."""