Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(agents): share public session lifecycle

cyh92289cd47961
diff --git a/AGENTS.md b/AGENTS.md
index 4551b5083..07854bbb8 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -78,6 +78,13 @@ Hard rule:
- **Never restart the local `vibe` service for routine verification.**
- The local `vibe` process may be the coding agent runtime itself; restarting it can interrupt the session.
+- **Tests and probes must never mutate the current local environment or live user state.**
+ Do not run commands, setup flows, migrations, installers, config writes, or
+ agent detection/install tests against `~/.vibe_remote`, the user's shell
+ environment, or the running local service unless the user explicitly asks for
+ that exact local operation. Use an isolated `VIBE_REMOTE_HOME`, a temporary
+ fixture directory, the Docker regression container, or the existing regression
+ environment instead.
- Unless the user explicitly asks otherwise, use the Docker regression environment for user-facing verification.
### Regression Testing (Docker)
diff --git a/config/v2_sessions.py b/config/v2_sessions.py
index a227b4985..3424a156e 100644
--- a/config/v2_sessions.py
+++ b/config/v2_sessions.py
@@ -324,6 +324,33 @@ class SessionsStore:
session_anchor=thread_id,
)
+ def ensure_agent_session_id(self, user_id: str, agent_name: str, thread_id: str) -> Optional[str]:
+ self._ensure_service()
+ agent_session_id = self._service.ensure_agent_session_id(
+ scope_key=user_id,
+ agent_name=agent_name,
+ session_anchor=thread_id,
+ )
+ self.get_agent_map(user_id, agent_name).setdefault(thread_id, "")
+ return agent_session_id
+
+ def bind_agent_session(
+ self,
+ user_id: str,
+ agent_name: str,
+ thread_id: str,
+ session_id: Any,
+ ) -> Optional[str]:
+ self._ensure_service()
+ agent_session_id = self._service.bind_agent_session(
+ scope_key=user_id,
+ agent_name=agent_name,
+ session_anchor=thread_id,
+ native_session_id=session_id,
+ )
+ self.get_agent_map(user_id, agent_name)[thread_id] = session_id
+ return agent_session_id
+
def get_thread_map(self, user_id: str, channel_id: str) -> Dict[str, float]:
self._ensure_user_namespace(user_id)
channel_map = self.state.active_slack_threads[user_id].get(channel_id)
diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.py
index b46348f1d..26213ee07 100644
--- a/core/handlers/session_handler.py
+++ b/core/handlers/session_handler.py
@@ -525,7 +525,7 @@ class SessionHandler(BaseHandler):
from core.system_prompt_injection import build_system_prompt_injection
platform = context.platform or (context.platform_specific or {}).get("platform") or self.config.platform
- self.attach_agent_session_id(
+ self.ensure_agent_session_id(
context,
session_key=session_key,
agent_name="claude",
@@ -992,12 +992,16 @@ class SessionHandler(BaseHandler):
def capture_session_id(self, base_session_id: str, claude_session_id: str, session_key: str):
"""Capture and store Claude session ID mapping"""
- self.sessions.set_session_mapping(session_key, base_session_id, claude_session_id)
-
+ agent_session_id = self.bind_agent_session_id(
+ session_key=session_key,
+ agent_name="claude",
+ session_anchor=base_session_id,
+ native_session_id=claude_session_id,
+ )
logger.info(f"Captured Claude session_id: {claude_session_id} for {base_session_id}")
- return self.sessions.get_agent_session_row_id(session_key, base_session_id, "claude")
+ return agent_session_id
- def attach_agent_session_id(
+ def ensure_agent_session_id(
self,
context: MessageContext,
*,
@@ -1005,10 +1009,12 @@ class SessionHandler(BaseHandler):
agent_name: str,
session_anchor: str,
) -> Optional[str]:
- getter = getattr(self.sessions, "get_agent_session_row_id", None)
- if not callable(getter):
- return None
- agent_session_id = getter(session_key, session_anchor, agent_name)
+ ensure = getattr(self.sessions, "ensure_agent_session_id", None)
+ if callable(ensure):
+ agent_session_id = ensure(session_key, agent_name, session_anchor)
+ else:
+ getter = getattr(self.sessions, "get_agent_session_row_id", None)
+ agent_session_id = getter(session_key, session_anchor, agent_name) if callable(getter) else None
if not agent_session_id:
return None
payload = dict(context.platform_specific or {})
@@ -1016,6 +1022,36 @@ class SessionHandler(BaseHandler):
context.platform_specific = payload
return agent_session_id
+ def bind_agent_session_id(
+ self,
+ *,
+ session_key: str,
+ agent_name: str,
+ session_anchor: str,
+ native_session_id: str,
+ ) -> Optional[str]:
+ binder = getattr(self.sessions, "bind_agent_session", None)
+ if callable(binder):
+ return binder(session_key, agent_name, session_anchor, native_session_id)
+ self.sessions.set_agent_session_mapping(session_key, agent_name, session_anchor, native_session_id)
+ getter = getattr(self.sessions, "get_agent_session_row_id", None)
+ return getter(session_key, session_anchor, agent_name) if callable(getter) else None
+
+ def attach_agent_session_id(
+ self,
+ context: MessageContext,
+ *,
+ session_key: str,
+ agent_name: str,
+ session_anchor: str,
+ ) -> Optional[str]:
+ return self.ensure_agent_session_id(
+ context,
+ session_key=session_key,
+ agent_name=agent_name,
+ session_anchor=session_anchor,
+ )
+
def restore_session_mappings(self):
"""Restore session mappings from settings on startup"""
logger.info("Initializing session mappings from saved settings...")
diff --git a/docs/plans/shared-agent-session-lifecycle.md b/docs/plans/shared-agent-session-lifecycle.md
new file mode 100644
index 000000000..3182f3097
--- /dev/null
+++ b/docs/plans/shared-agent-session-lifecycle.md
@@ -0,0 +1,33 @@
+# Shared Agent Session Lifecycle
+
+## Background
+
+Vibe Remote exposes a public `ses...` agent-session id to AI backends so they
+can create tasks, watches, and hooks targeting the current conversation. That
+id is Vibe-owned and should not depend on whether a backend has already created
+its native session.
+
+Today each backend handles this sequence locally. OpenCode usually creates its
+native session before prompt injection, while Claude Code and Codex can build
+their first prompt before the native session id exists. That leaves
+`Current session id` unavailable on first turn for some backends.
+
+## Goal
+
+Make the Vibe-owned agent-session lifecycle shared:
+
+1. Ensure a stable Vibe agent-session row before prompt injection.
+2. Put the `ses...` id into `MessageContext.platform_specific`.
+3. Bind the backend native session id into the same row once it exists.
+4. Keep backend-specific code responsible only for native session creation and
+ resume behavior.
+
+## Plan
+
+- Add shared storage/facade APIs for `ensure_agent_session_id` and
+ `bind_agent_session`.
+- Add a shared `BaseAgent` helper that writes the resolved `ses...` id into the
+ request context.
+- Use the helper from Codex, Claude Code, and OpenCode before their prompt
+ injection points and after native session creation.
+- Cover first-turn prompt injection for all three backend paths.
diff --git a/modules/agents/base.py b/modules/agents/base.py
index a788d766f..f363e0480 100644
--- a/modules/agents/base.py
+++ b/modules/agents/base.py
@@ -84,6 +84,52 @@ class BaseAgent(ABC):
def _get_formatter(self, context: MessageContext):
return getattr(self._get_im_client(context), "formatter", self.im_client.formatter)
+ def ensure_agent_session_id(
+ self,
+ request: AgentRequest,
+ *,
+ session_anchor: Optional[str] = None,
+ ) -> Optional[str]:
+ """Ensure the Vibe-owned public session id exists on the request context."""
+ anchor = session_anchor or request.base_session_id
+ sessions = getattr(self, "sessions", None)
+ ensure = getattr(sessions, "ensure_agent_session_id", None)
+ if callable(ensure):
+ agent_session_id = ensure(request.session_key, self.name, anchor)
+ else:
+ getter = getattr(sessions, "get_agent_session_row_id", None)
+ agent_session_id = (
+ getter(request.session_key, anchor, self.name)
+ if callable(getter)
+ else None
+ )
+ if not agent_session_id:
+ return None
+ payload = dict(request.context.platform_specific or {})
+ payload["agent_session_id"] = agent_session_id
+ request.context.platform_specific = payload
+ return agent_session_id
+
+ def bind_agent_session_id(
+ self,
+ request: AgentRequest,
+ native_session_id: Any,
+ *,
+ session_anchor: Optional[str] = None,
+ ) -> Optional[str]:
+ """Bind a backend-native session id to the existing Vibe session row."""
+ anchor = session_anchor or request.base_session_id
+ sessions = getattr(self, "sessions", None)
+ binder = getattr(sessions, "bind_agent_session", None)
+ if callable(binder):
+ agent_session_id = binder(request.session_key, self.name, anchor, native_session_id)
+ else:
+ setter = getattr(sessions, "set_agent_session_mapping", None)
+ if callable(setter):
+ setter(request.session_key, self.name, anchor, native_session_id)
+ agent_session_id = None
+ return agent_session_id or self.ensure_agent_session_id(request, session_anchor=anchor)
+
async def _remove_ack_reaction(self, request: AgentRequest) -> None:
"""Remove the acknowledgement reaction / typing indicator.
diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.py
index 89543c62b..bf9929b19 100644
--- a/modules/agents/claude_agent.py
+++ b/modules/agents/claude_agent.py
@@ -707,7 +707,16 @@ class ClaudeAgent(BaseAgent):
):
session_id = message.data.get("session_id")
if session_id:
- agent_session_id = self.session_handler.capture_session_id(base_session_id, session_id, session_key)
+ binder = getattr(self.session_handler, "bind_agent_session_id", None)
+ if callable(binder):
+ agent_session_id = binder(
+ session_key=session_key,
+ agent_name=self.name,
+ session_anchor=base_session_id,
+ native_session_id=session_id,
+ )
+ else:
+ agent_session_id = self.session_handler.capture_session_id(base_session_id, session_id, session_key)
if agent_session_id:
payload = dict(context.platform_specific or {})
payload["agent_session_id"] = agent_session_id
diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.py
index ed2991256..87c48a5ee 100644
--- a/modules/agents/codex/agent.py
+++ b/modules/agents/codex/agent.py
@@ -480,6 +480,7 @@ class CodexAgent(BaseAgent):
"approvalPolicy": "never",
"sandbox": "danger-full-access",
}
+ self.ensure_agent_session_id(request)
developer_instructions = self._build_thread_developer_instructions(request)
if developer_instructions:
params["developerInstructions"] = developer_instructions
@@ -496,27 +497,9 @@ class CodexAgent(BaseAgent):
self._session_mgr.set_thread_id(request.base_session_id, thread_id)
# Also persist for resume support
- self.sessions.set_agent_session_mapping(
- request.session_key,
- self.name,
- request.base_session_id,
- thread_id,
- )
- self._attach_agent_session_id(request)
+ self.bind_agent_session_id(request, thread_id)
return thread_id
- def _attach_agent_session_id(self, request: AgentRequest) -> Optional[str]:
- getter = getattr(self.sessions, "get_agent_session_row_id", None)
- if not callable(getter):
- return None
- agent_session_id = getter(request.session_key, request.base_session_id, self.name)
- if not agent_session_id:
- return None
- payload = dict(request.context.platform_specific or {})
- payload["agent_session_id"] = agent_session_id
- request.context.platform_specific = payload
- return agent_session_id
-
def _resolve_codex_agent_settings(
self,
request: AgentRequest,
@@ -575,7 +558,7 @@ class CodexAgent(BaseAgent):
)
if persisted:
try:
- self._attach_agent_session_id(request)
+ self.bind_agent_session_id(request, persisted)
resume_params: Dict[str, Any] = {
"threadId": persisted,
"developerInstructions": self._build_thread_developer_instructions(request),
diff --git a/modules/agents/codex/event_handler.py b/modules/agents/codex/event_handler.py
index b8e3a5ff8..ad3d41441 100644
--- a/modules/agents/codex/event_handler.py
+++ b/modules/agents/codex/event_handler.py
@@ -87,22 +87,7 @@ class CodexEventHandler:
thread_id = thread_obj.get("id", "") if isinstance(thread_obj, dict) else ""
if thread_id:
self._agent._session_mgr.set_thread_id(request.base_session_id, thread_id)
- # Persist thread_id in settings_manager for /clear resume
- self._agent.sessions.set_agent_session_mapping(
- request.session_key,
- self._agent.name,
- request.base_session_id,
- thread_id,
- )
- agent_session_id = self._agent.sessions.get_agent_session_row_id(
- request.session_key,
- request.base_session_id,
- self._agent.name,
- )
- if agent_session_id:
- payload = dict(request.context.platform_specific or {})
- payload["agent_session_id"] = agent_session_id
- request.context.platform_specific = payload
+ self._agent.bind_agent_session_id(request, thread_id)
system_text = self._agent._get_formatter(request.context).format_system_message(
request.working_path,
diff --git a/modules/agents/opencode/session.py b/modules/agents/opencode/session.py
index cb6fa5897..34df7a0e4 100644
--- a/modules/agents/opencode/session.py
+++ b/modules/agents/opencode/session.py
@@ -59,17 +59,55 @@ class OpenCodeSessionManager:
matches[base_id] = info
return matches
- def _attach_agent_session_id(self, request: AgentRequest, composite_session_key: str) -> Optional[str]:
- sessions = getattr(self._settings_manager, "sessions", self._settings_manager)
- getter = getattr(sessions, "get_agent_session_row_id", None)
- if not callable(getter):
- return None
- agent_session_id = getter(request.session_key, composite_session_key, self._agent_name)
+ def _set_request_agent_session_id(self, request: AgentRequest, agent_session_id: Optional[str]) -> None:
if not agent_session_id:
- return None
+ return
payload = dict(request.context.platform_specific or {})
payload["agent_session_id"] = agent_session_id
request.context.platform_specific = payload
+
+ def ensure_agent_session_id(self, request: AgentRequest, composite_session_key: str) -> Optional[str]:
+ sessions = getattr(self._settings_manager, "sessions", self._settings_manager)
+ ensure = getattr(sessions, "ensure_agent_session_id", None)
+ if callable(ensure):
+ agent_session_id = ensure(request.session_key, self._agent_name, composite_session_key)
+ else:
+ getter = getattr(sessions, "get_agent_session_row_id", None)
+ agent_session_id = (
+ getter(request.session_key, composite_session_key, self._agent_name)
+ if callable(getter)
+ else None
+ )
+ self._set_request_agent_session_id(request, agent_session_id)
+ return agent_session_id
+
+ def bind_agent_session_id(
+ self,
+ request: AgentRequest,
+ composite_session_key: str,
+ opencode_session_id: str,
+ ) -> Optional[str]:
+ sessions = getattr(self._settings_manager, "sessions", self._settings_manager)
+ binder = getattr(sessions, "bind_agent_session", None)
+ if callable(binder):
+ agent_session_id = binder(
+ request.session_key,
+ self._agent_name,
+ composite_session_key,
+ opencode_session_id,
+ )
+ else:
+ sessions.set_agent_session_mapping(
+ request.session_key,
+ self._agent_name,
+ composite_session_key,
+ opencode_session_id,
+ )
+ agent_session_id = None
+ if not agent_session_id:
+ agent_session_id = self.ensure_agent_session_id(request, composite_session_key)
+ else:
+ self._set_request_agent_session_id(request, agent_session_id)
return agent_session_id
def mark_initialized(self, opencode_session_id: str) -> bool:
@@ -139,6 +177,7 @@ class OpenCodeSessionManager:
# Include working_path in the mapping key so cwd changes create new sessions
composite_session_key = f"{request.base_session_id}:{request.working_path}"
+ self.ensure_agent_session_id(request, composite_session_key)
session_id = sessions.get_agent_session_id(
request.session_key,
@@ -157,18 +196,12 @@ class OpenCodeSessionManager:
)
if legacy_id:
if await server.get_session(legacy_id, request.working_path):
- sessions.set_agent_session_mapping(
- request.session_key,
- self._agent_name,
- composite_session_key,
- legacy_id,
- )
+ self.bind_agent_session_id(request, composite_session_key, legacy_id)
logger.info(
"Migrated legacy OpenCode session %s to composite key for %s",
legacy_id,
request.base_session_id,
)
- self._attach_agent_session_id(request, composite_session_key)
return legacy_id
else:
logger.info(
@@ -184,13 +217,7 @@ class OpenCodeSessionManager:
)
session_id = session_data.get("id")
if session_id:
- sessions.set_agent_session_mapping(
- request.session_key,
- self._agent_name,
- composite_session_key,
- session_id,
- )
- self._attach_agent_session_id(request, composite_session_key)
+ self.bind_agent_session_id(request, composite_session_key, session_id)
logger.info(f"Created OpenCode session {session_id} for {request.base_session_id}")
except Exception as e:
logger.error(f"Failed to create OpenCode session: {e}", exc_info=True)
@@ -199,7 +226,7 @@ class OpenCodeSessionManager:
existing = await server.get_session(session_id, request.working_path)
if existing:
- self._attach_agent_session_id(request, composite_session_key)
+ self.bind_agent_session_id(request, composite_session_key, session_id)
return session_id
try:
@@ -209,13 +236,7 @@ class OpenCodeSessionManager:
)
new_session_id = session_data.get("id")
if new_session_id:
- sessions.set_agent_session_mapping(
- request.session_key,
- self._agent_name,
- composite_session_key,
- new_session_id,
- )
- self._attach_agent_session_id(request, composite_session_key)
+ self.bind_agent_session_id(request, composite_session_key, new_session_id)
logger.info(f"Recreated OpenCode session {new_session_id} for {request.base_session_id}")
return new_session_id
except Exception as e:
diff --git a/modules/sessions_facade.py b/modules/sessions_facade.py
index 937268bd5..6e92bdbdf 100644
--- a/modules/sessions_facade.py
+++ b/modules/sessions_facade.py
@@ -35,6 +35,11 @@ class SessionsFacade:
thread_id: str,
session_id: str,
) -> None:
+ binder = getattr(self.sessions_store, "bind_agent_session", None)
+ if callable(binder):
+ binder(self._normalize_user_id(user_id), agent_name, thread_id, session_id)
+ logger.info("Stored %s session mapping for %s: %s -> %s", agent_name, user_id, thread_id, session_id)
+ return
agent_map = self._ensure_agent_namespace(user_id, agent_name)
agent_map[thread_id] = session_id
self.sessions_store.save()
@@ -62,6 +67,32 @@ class SessionsFacade:
return None
return getter(user_key, agent_name, thread_id)
+ def ensure_agent_session_id(
+ self,
+ user_id: Union[int, str],
+ agent_name: str,
+ thread_id: str,
+ ) -> Optional[str]:
+ user_key = self._normalize_user_id(user_id)
+ ensure = getattr(self.sessions_store, "ensure_agent_session_id", None)
+ if callable(ensure):
+ return ensure(user_key, agent_name, thread_id)
+ return self.get_agent_session_row_id(user_key, thread_id, agent_name)
+
+ def bind_agent_session(
+ self,
+ user_id: Union[int, str],
+ agent_name: str,
+ thread_id: str,
+ session_id: Any,
+ ) -> Optional[str]:
+ user_key = self._normalize_user_id(user_id)
+ binder = getattr(self.sessions_store, "bind_agent_session", None)
+ if callable(binder):
+ return binder(user_key, agent_name, thread_id, session_id)
+ self.set_agent_session_mapping(user_key, agent_name, thread_id, session_id)
+ return self.get_agent_session_row_id(user_key, thread_id, agent_name)
+
def clear_agent_session_mapping(
self,
user_id: Union[int, str],
diff --git a/storage/sessions_service.py b/storage/sessions_service.py
index 34feaf8f8..c5d8cf8ad 100644
--- a/storage/sessions_service.py
+++ b/storage/sessions_service.py
@@ -52,6 +52,81 @@ class SQLiteSessionsService:
.limit(1)
).scalar_one_or_none()
+ def ensure_agent_session_id(
+ self,
+ *,
+ scope_key: str,
+ agent_name: str,
+ session_anchor: str,
+ ) -> str | None:
+ """Ensure a Vibe-owned agent-session row exists before native binding."""
+ now = _utc_now_iso()
+ with self.engine.begin() as conn:
+ scope_id = resolve_scope_from_legacy_key(conn, str(scope_key), now=now)
+ if scope_id is None:
+ return None
+ row_id = _find_agent_session_row_id(
+ conn,
+ scope_id=scope_id,
+ agent_name=agent_name,
+ session_anchor=session_anchor,
+ )
+ if row_id:
+ return row_id
+ return _insert_agent_session_row(
+ conn,
+ scope_id=scope_id,
+ scope_key=str(scope_key),
+ agent_name=agent_name,
+ session_anchor=session_anchor,
+ native_session_id="",
+ now=now,
+ )
+
+ def bind_agent_session(
+ self,
+ *,
+ scope_key: str,
+ agent_name: str,
+ session_anchor: str,
+ native_session_id: Any,
+ ) -> str | None:
+ """Bind a backend-native session id to the stable Vibe session row."""
+ now = _utc_now_iso()
+ with self.engine.begin() as conn:
+ scope_id = resolve_scope_from_legacy_key(conn, str(scope_key), now=now)
+ if scope_id is None:
+ return None
+ row_id = _find_agent_session_row_id(
+ conn,
+ scope_id=scope_id,
+ agent_name=agent_name,
+ session_anchor=session_anchor,
+ )
+ encoded_session_id = encode_session_value(native_session_id)
+ if not row_id:
+ return _insert_agent_session_row(
+ conn,
+ scope_id=scope_id,
+ scope_key=str(scope_key),
+ agent_name=agent_name,
+ session_anchor=session_anchor,
+ native_session_id=encoded_session_id,
+ now=now,
+ )
+ conn.execute(
+ agent_sessions.update()
+ .where(agent_sessions.c.id == row_id)
+ .values(
+ native_session_id=encoded_session_id,
+ workdir=_workdir_from_anchor(str(session_anchor)),
+ status="active",
+ updated_at=now,
+ last_active_at=now,
+ )
+ )
+ return row_id
+
def load_state(self) -> SessionState:
with self.engine.connect() as conn:
return SessionState(
@@ -378,6 +453,61 @@ def _new_session_id(used: set[str]) -> str:
return value
+def _find_agent_session_row_id(
+ conn: Connection,
+ *,
+ scope_id: str | None,
+ agent_name: str,
+ session_anchor: str,
+) -> str | None:
+ return conn.execute(
+ select(agent_sessions.c.id)
+ .where(agent_sessions.c.scope_id == scope_id)
+ .where(agent_sessions.c.agent_variant == (str(agent_name) or "default"))
+ .where(agent_sessions.c.session_anchor == str(session_anchor))
+ .limit(1)
+ ).scalar_one_or_none()
+
+
+def _insert_agent_session_row(
+ conn: Connection,
+ *,
+ scope_id: str | None,
+ scope_key: str,
+ agent_name: str,
+ session_anchor: str,
+ native_session_id: Any,
+ now: str,
+) -> str:
+ used_session_ids = {
+ str(existing_id)
+ for existing_id in conn.execute(select(agent_sessions.c.id)).scalars()
+ }
+ row_id = _new_session_id(used_session_ids)
+ agent_variant = str(agent_name) or "default"
+ anchor = str(session_anchor)
+ conn.execute(
+ agent_sessions.insert().values(
+ id=row_id,
+ scope_id=scope_id,
+ agent_backend=_agent_backend(agent_variant),
+ agent_variant=agent_variant,
+ model=None,
+ reasoning_effort=None,
+ session_anchor=anchor,
+ workdir=_workdir_from_anchor(anchor),
+ native_session_id=encode_session_value(native_session_id),
+ title=None,
+ status="active",
+ metadata_json=_json_dumps({"legacy_scope_key": scope_key}),
+ created_at=now,
+ updated_at=now,
+ last_active_at=now,
+ )
+ )
+ return row_id
+
+
def _session_row_key(
*,
scope_id: str | None,
diff --git a/tests/test_claude_agent_sessions.py b/tests/test_claude_agent_sessions.py
index ac2e996cc..861ff4abb 100644
--- a/tests/test_claude_agent_sessions.py
+++ b/tests/test_claude_agent_sessions.py
@@ -579,6 +579,41 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
self.assertNotIn(composite_key, controller.claude_sessions)
agent.emit_result_message.assert_not_awaited()
+ async def test_init_message_binds_native_session_to_existing_agent_session(self):
+ controller = _StubController()
+ binds = []
+ controller.session_handler = SimpleNamespace(
+ bind_agent_session_id=lambda **kwargs: binds.append(kwargs) or "sesk8m4q2p7x"
+ )
+ agent = ClaudeAgent(controller)
+ context = SimpleNamespace(platform_specific={})
+ init_message = type(
+ "SystemMessage",
+ (),
+ {"subtype": "init", "data": {"session_id": "session-sdk"}},
+ )()
+
+ session_id = agent._maybe_capture_session_id(
+ init_message,
+ "session-1",
+ "slack::channel::C1",
+ context,
+ )
+
+ self.assertEqual(session_id, "session-sdk")
+ self.assertEqual(context.platform_specific["agent_session_id"], "sesk8m4q2p7x")
+ self.assertEqual(
+ binds,
+ [
+ {
+ "session_key": "slack::channel::C1",
+ "agent_name": "claude",
+ "session_anchor": "session-1",
+ "native_session_id": "session-sdk",
+ }
+ ],
+ )
+
async def test_result_auth_error_exits_receiver_and_disconnects_client(self):
controller = _StubController()
controller.agent_auth_service.maybe_emit_auth_recovery_message = AsyncMock(return_value=True)
diff --git a/tests/test_claude_cli_path.py b/tests/test_claude_cli_path.py
index 0ae73733a..25dad9599 100644
--- a/tests/test_claude_cli_path.py
+++ b/tests/test_claude_cli_path.py
@@ -45,6 +45,10 @@ class _Sessions:
def get_agent_session_id(settings_key, base_session_id, agent_name):
return None
+ @staticmethod
+ def ensure_agent_session_id(settings_key, agent_name, base_session_id):
+ return None
+
class _SettingsManager:
def __init__(self) -> None:
@@ -188,17 +192,17 @@ def test_session_handler_disallows_remote_unsafe_claude_tools(monkeypatch, tmp_p
assert captured["options"].disallowed_tools == ["AskUserQuestion", "EnterPlanMode", "ExitPlanMode"]
-def test_session_handler_attaches_persisted_agent_session_id_before_prompt(
+def test_session_handler_ensures_agent_session_id_before_prompt(
monkeypatch, tmp_path: Path
) -> None:
captured: dict[str, Any] = {}
class _PromptSessions(_Sessions):
@staticmethod
- def get_agent_session_row_id(settings_key, base_session_id, agent_name):
+ def ensure_agent_session_id(settings_key, agent_name, base_session_id):
assert settings_key == "test::C123"
- assert base_session_id == "slack_C123"
assert agent_name == "claude"
+ assert base_session_id == "slack_C123"
return "sesk8m4q2p7x"
class _StubClaudeSDKClient:
diff --git a/tests/test_codex_agent.py b/tests/test_codex_agent.py
index ab1929f7c..c8361e9d7 100644
--- a/tests/test_codex_agent.py
+++ b/tests/test_codex_agent.py
@@ -24,6 +24,30 @@ class _BaseAgent:
def __init__(self, controller):
self.controller = controller
+ def ensure_agent_session_id(self, request, *, session_anchor=None):
+ anchor = session_anchor or request.base_session_id
+ ensure = getattr(self.sessions, "ensure_agent_session_id", None)
+ if callable(ensure):
+ session_id = ensure(request.session_key, self.name, anchor)
+ else:
+ getter = getattr(self.sessions, "get_agent_session_row_id", None)
+ session_id = getter(request.session_key, anchor, self.name) if callable(getter) else None
+ if session_id:
+ request.context.platform_specific["agent_session_id"] = session_id
+ return session_id
+
+ def bind_agent_session_id(self, request, native_session_id, *, session_anchor=None):
+ anchor = session_anchor or request.base_session_id
+ binder = getattr(self.sessions, "bind_agent_session", None)
+ if callable(binder):
+ session_id = binder(request.session_key, self.name, anchor, native_session_id)
+ else:
+ setter = getattr(self.sessions, "set_agent_session_mapping", None)
+ if callable(setter):
+ setter(request.session_key, self.name, anchor, native_session_id)
+ session_id = None
+ return session_id or self.ensure_agent_session_id(request, session_anchor=anchor)
+
setattr(_base_module, "BaseAgent", _BaseAgent)
@@ -756,7 +780,10 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
agent.controller = SimpleNamespace(config=SimpleNamespace(platform="slack", reply_enhancements=False))
agent.codex_config = SimpleNamespace(default_model=None)
agent._session_mgr = SimpleNamespace(set_thread_id=Mock())
- agent.sessions = SimpleNamespace(set_agent_session_mapping=Mock())
+ agent.sessions = SimpleNamespace(
+ ensure_agent_session_id=Mock(return_value="sesk8m4q2p7x"),
+ bind_agent_session=Mock(return_value="sesk8m4q2p7x"),
+ )
request = SimpleNamespace(
working_path="/tmp/work",
context=SimpleNamespace(
@@ -785,6 +812,9 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(params["sandbox"], "danger-full-access")
self.assertIn("# Vibe Remote", params["developerInstructions"])
self.assertNotIn("## 2. Quick-reply buttons", params["developerInstructions"])
+ self.assertIn("Current session id: `sesk8m4q2p7x`", params["developerInstructions"])
+ agent.sessions.ensure_agent_session_id.assert_called_once_with("channel-1", "codex", "session-1")
+ agent.sessions.bind_agent_session.assert_called_once_with("channel-1", "codex", "session-1", "thread-1")
async def test_start_thread_includes_codex_agent_developer_instructions(self):
agent = object.__new__(CodexAgent)
diff --git a/tests/test_codex_event_handler.py b/tests/test_codex_event_handler.py
index 347a9963e..1c2387aba 100644
--- a/tests/test_codex_event_handler.py
+++ b/tests/test_codex_event_handler.py
@@ -5,7 +5,7 @@ import tempfile
import unittest
from pathlib import Path
from types import SimpleNamespace
-from unittest.mock import AsyncMock, patch
+from unittest.mock import AsyncMock, Mock, patch
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
@@ -85,6 +85,7 @@ class _StubTurnRegistry:
class _StubAgent:
def __init__(self):
self._turn_registry = _StubTurnRegistry()
+ self._session_mgr = SimpleNamespace(set_thread_id=Mock())
self.controller = SimpleNamespace(
config=SimpleNamespace(reply_enhancements=True),
emit_agent_message=AsyncMock(),
@@ -93,8 +94,40 @@ class _StubAgent:
self.emit_result_message = AsyncMock()
self._remove_ack_reaction = AsyncMock()
+ def bind_agent_session_id(self, request, native_session_id):
+ payload = dict(request.context.platform_specific or {})
+ payload["agent_session_id"] = "sesk8m4q2p7x"
+ request.context.platform_specific = payload
+ return "sesk8m4q2p7x"
+
+ def _get_formatter(self, context):
+ return SimpleNamespace(format_system_message=lambda *args: "system message")
+
class CodexEventHandlerTests(unittest.IsolatedAsyncioTestCase):
+ async def test_thread_started_binds_native_session_through_shared_lifecycle(self):
+ agent = _StubAgent()
+ agent.bind_agent_session_id = Mock(wraps=agent.bind_agent_session_id)
+ handler = CodexEventHandler(agent)
+ request = SimpleNamespace(
+ base_session_id="session-1",
+ session_key="slack::channel::C1",
+ working_path="/repo",
+ context=SimpleNamespace(platform_specific={}),
+ )
+
+ await handler._on_thread_started({"thread": {"id": "thread-1"}}, request)
+
+ agent._session_mgr.set_thread_id.assert_called_once_with("session-1", "thread-1")
+ agent.bind_agent_session_id.assert_called_once_with(request, "thread-1")
+ self.assertEqual(request.context.platform_specific["agent_session_id"], "sesk8m4q2p7x")
+ agent.controller.emit_agent_message.assert_awaited_once_with(
+ request.context,
+ "system",
+ "system message",
+ parse_mode="markdown",
+ )
+
async def test_retrying_error_is_suppressed(self):
agent = _StubAgent()
handler = CodexEventHandler(agent)
diff --git a/tests/test_opencode_session_manager.py b/tests/test_opencode_session_manager.py
index 4db6e3333..a3aa4eeff 100644
--- a/tests/test_opencode_session_manager.py
+++ b/tests/test_opencode_session_manager.py
@@ -7,6 +7,7 @@ from unittest.mock import AsyncMock, Mock
from modules.agents.base import AgentRequest
from modules.agents.opencode.session import OpenCodeSessionManager
from modules.im import MessageContext
+from modules.sessions_facade import SessionsFacade
def _request() -> AgentRequest:
@@ -23,7 +24,8 @@ def _request() -> AgentRequest:
def test_opencode_reused_session_attaches_agent_session_id() -> None:
sessions = SimpleNamespace(
get_agent_session_id=Mock(return_value="oc-session-1"),
- get_agent_session_row_id=Mock(return_value="sesk8m4q2p7x"),
+ ensure_agent_session_id=Mock(return_value="sesk8m4q2p7x"),
+ bind_agent_session=Mock(return_value="sesk8m4q2p7x"),
)
manager = OpenCodeSessionManager(SimpleNamespace(sessions=sessions), "opencode")
server = SimpleNamespace(get_session=AsyncMock(return_value={"id": "oc-session-1"}))
@@ -33,8 +35,28 @@ def test_opencode_reused_session_attaches_agent_session_id() -> None:
assert session_id == "oc-session-1"
assert request.context.platform_specific["agent_session_id"] == "sesk8m4q2p7x"
- sessions.get_agent_session_row_id.assert_called_once_with(
+ sessions.ensure_agent_session_id.assert_called_once_with(
"slack::channel::C1",
+ "opencode",
"base-1:/repo",
+ )
+ sessions.bind_agent_session.assert_called_once_with(
+ "slack::channel::C1",
"opencode",
+ "base-1:/repo",
+ "oc-session-1",
)
+
+
+def test_session_facade_ensure_fallback_does_not_clear_existing_native_session() -> None:
+ class _LegacyStore:
+ def __init__(self):
+ self.maps = {"slack::channel::C1": {"codex": {"base-1": "thread-old"}}}
+
+ def get_agent_map(self, user_id, agent_name):
+ return self.maps.setdefault(user_id, {}).setdefault(agent_name, {})
+
+ facade = SessionsFacade(_LegacyStore())
+
+ assert facade.ensure_agent_session_id("slack::channel::C1", "codex", "base-1") is None
+ assert facade.get_agent_session_id("slack::channel::C1", "base-1", "codex") == "thread-old"
diff --git a/tests/test_sqlite_sessions_store.py b/tests/test_sqlite_sessions_store.py
index 6fc8a5dea..8e934b950 100644
--- a/tests/test_sqlite_sessions_store.py
+++ b/tests/test_sqlite_sessions_store.py
@@ -158,6 +158,88 @@ def test_sqlite_sessions_service_preserves_agent_session_ids_on_save(tmp_path: P
service.close()
+def test_sqlite_sessions_service_reserves_then_binds_agent_session_id(tmp_path: Path) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ service = SQLiteSessionsService(db_path)
+ try:
+ reserved_id = service.ensure_agent_session_id(
+ scope_key="slack::C123",
+ agent_name="codex",
+ session_anchor="slack_171717.123",
+ )
+ assert reserved_id is not None
+ assert service.load_state().session_mappings["slack::C123"]["codex"]["slack_171717.123"] == ""
+
+ bound_id = service.bind_agent_session(
+ scope_key="slack::C123",
+ agent_name="codex",
+ session_anchor="slack_171717.123",
+ native_session_id="thread-native-1",
+ )
+
+ assert bound_id == reserved_id
+ assert service.get_agent_session_row_id(
+ scope_key="slack::C123",
+ agent_name="codex",
+ session_anchor="slack_171717.123",
+ ) == reserved_id
+ assert service.load_state().session_mappings["slack::C123"]["codex"]["slack_171717.123"] == "thread-native-1"
+ finally:
+ service.close()
+
+
+def test_sessions_store_lifecycle_updates_in_memory_state(tmp_path: Path) -> None:
+ sessions_path = tmp_path / "sessions.json"
+ store = SessionsStore(sessions_path)
+ try:
+ reserved_id = store.ensure_agent_session_id("slack::C123", "codex", "slack_171717.123")
+ assert reserved_id is not None
+ assert store.state.session_mappings["slack::C123"]["codex"]["slack_171717.123"] == ""
+
+ bound_id = store.bind_agent_session("slack::C123", "codex", "slack_171717.123", "thread-native-1")
+
+ assert bound_id == reserved_id
+ assert store.state.session_mappings["slack::C123"]["codex"]["slack_171717.123"] == "thread-native-1"
+ assert store.get_agent_session_row_id("slack::C123", "codex", "slack_171717.123") == reserved_id
+ finally:
+ store.close()
+
+
+def test_sessions_store_lifecycle_survives_followup_save(tmp_path: Path) -> None:
+ sessions_path = tmp_path / "sessions.json"
+ store = SessionsStore(sessions_path)
+ try:
+ reserved_id = store.ensure_agent_session_id("slack::C123", "opencode", "slack_171717.123:/repo")
+ bound_id = store.bind_agent_session("slack::C123", "opencode", "slack_171717.123:/repo", "oc-session-1")
+ store.add_active_poll(
+ ActivePollInfo(
+ opencode_session_id="oc-session-1",
+ base_session_id="slack_171717.123",
+ channel_id="C123",
+ thread_id="171717.123",
+ settings_key="C123",
+ working_path="/repo",
+ platform="slack",
+ )
+ )
+
+ assert bound_id == reserved_id
+ assert store.state.session_mappings["slack::C123"]["opencode"]["slack_171717.123:/repo"] == "oc-session-1"
+ finally:
+ store.close()
+
+ reloaded = SessionsStore(sessions_path)
+ try:
+ assert (
+ reloaded.state.session_mappings["slack::C123"]["opencode"]["slack_171717.123:/repo"] == "oc-session-1"
+ )
+ assert (
+ reloaded.get_agent_session_row_id("slack::C123", "opencode", "slack_171717.123:/repo") == reserved_id
+ )
+ finally:
+ reloaded.close()
+
+
def test_sessions_store_bootstrap_uses_config_primary_platform(tmp_path: Path, monkeypatch) -> None:
monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
paths.ensure_data_dirs()