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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(resume): keep native resume scoped to cwd
cyh25f66452577a
diff --git a/config/v2_sessions.py b/config/v2_sessions.pyindex 3890dacd8..e8819b355 100644--- a/config/v2_sessions.py+++ b/config/v2_sessions.py@@ -94,9 +94,6 @@ class ActivePollInfo:class SessionState:# session_mappings: user_id -> agent_name -> thread_id -> session_idsession_mappings: Dict[str, Dict[str, Dict[str, str]]] = field(default_factory=dict)- # session_working_paths: user_id -> agent_name -> thread_id -> working_path- # Stores the original working_path for cross-project resumed sessions- session_working_paths: Dict[str, Dict[str, Dict[str, str]]] = field(default_factory=dict)active_slack_threads: Dict[str, Dict[str, Dict[str, float]]] = field(default_factory=dict)# active_polls: opencode_session_id -> ActivePollInfoactive_polls: Dict[str, Dict[str, Any]] = field(default_factory=dict)@@ -121,7 +118,6 @@ class SessionsStore:returnself.state = SessionState(session_mappings=payload.get("session_mappings", {}),- session_working_paths=payload.get("session_working_paths", {}),active_slack_threads=payload.get("active_slack_threads", {}),active_polls=payload.get("active_polls", {}),processed_message_ts=payload.get("processed_message_ts", {}),@@ -357,7 +353,6 @@ class SessionsStore:paths.ensure_data_dirs()payload = {"session_mappings": self.state.session_mappings,- "session_working_paths": self.state.session_working_paths,"active_slack_threads": self.state.active_slack_threads,"active_polls": self.state.active_polls,"processed_message_ts": self.state.processed_message_ts,diff --git a/core/handlers/command_handlers.py b/core/handlers/command_handlers.pyindex a2f247599..ad5d4a4c7 100644--- a/core/handlers/command_handlers.py+++ b/core/handlers/command_handlers.py@@ -119,6 +119,9 @@ class CommandHandlers(BaseHandler):if time.time() - float(snapshot.get("stored_at", 0.0)) > self._resume_snapshot_ttl_seconds:self._resume_snapshots.pop(self._get_resume_snapshot_key(context), None)return None+ if snapshot.get("working_path") != self.controller.get_cwd(context):+ self._resume_snapshots.pop(self._get_resume_snapshot_key(context), None)+ return Nonereturn snapshotdef _list_recent_native_sessions(@@ -135,7 +138,7 @@ class CommandHandlers(BaseHandler):native_session_service = getattr(self.controller, "native_session_service", None)if native_session_service is None:return working_path, []- sessions = native_session_service.list_all_recent_sessions(limit=limit)+ sessions = native_session_service.list_recent_sessions(working_path, limit=limit)agent_service = getattr(self.controller, "agent_service", None)registered_agents = getattr(agent_service, "agents", None)if isinstance(registered_agents, dict) and registered_agents:@@ -269,7 +272,6 @@ class CommandHandlers(BaseHandler):host_message_ts=context.message_id,is_dm=bool((context.platform_specific or {}).get("is_dm", False)),platform=context.platform or (context.platform_specific or {}).get("platform") or self.config.platform,- session_working_path=item.working_path,)async def _handle_wechat_resume_latest(self, context: MessageContext, *, agent: Optional[str] = None) -> None:@@ -296,7 +298,6 @@ class CommandHandlers(BaseHandler):host_message_ts=context.message_id,is_dm=bool((context.platform_specific or {}).get("is_dm", False)),platform=context.platform or (context.platform_specific or {}).get("platform") or self.config.platform,- session_working_path=item.working_path,)async def _handle_wechat_resume(self, context: MessageContext, args: str) -> None:@@ -456,9 +457,7 @@ class CommandHandlers(BaseHandler):InlineButton(text=f"🤖 {self._t('button.agentSettings')}", callback_data="cmd_routing"),],# Row 4: Features- [- InlineButton(text=f"✨ {self._t('button.howItWorks')}", callback_data="info_how_it_works"),- ],+ [InlineButton(text=f"✨ {self._t('button.howItWorks')}", callback_data="info_how_it_works")],]keyboard = InlineKeyboard(buttons=buttons)diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.pyindex f4d25c49f..edd7bbf5c 100644--- a/core/handlers/session_handler.py+++ b/core/handlers/session_handler.py@@ -404,13 +404,6 @@ class SessionHandler(BaseHandler):session_key = self._get_session_key(context)stored_claude_session_id = self.sessions.get_claude_session_id(session_key, base_session_id)- # For cross-project resumed sessions, use the stored working_path- # as cwd so Claude Code can find the session file.- stored_working_path = self.sessions.get_agent_session_working_path(session_key, base_session_id, agent_name="claude")- if stored_working_path and stored_claude_session_id:- logger.info(f"Using stored working_path for resumed session: {stored_working_path} (current: {working_path})")- working_path = stored_working_path-# Read routing overrides via get_channel_routing which correctly# resolves DM users from the users store (not the stale channels store).routing = self._get_settings_manager(context).get_channel_routing(settings_key)@@ -673,7 +666,6 @@ class SessionHandler(BaseHandler):host_message_ts: Optional[str] = None,is_dm: bool = False,platform: Optional[str] = None,- session_working_path: Optional[str] = None,) -> None:"""Bind a provided session_id to the current thread for the chosen agent."""from modules.settings_manager import ChannelRouting@@ -801,7 +793,7 @@ class SessionHandler(BaseHandler):if agent == "opencode":mapping_key = f"{base_session_id}:{working_path}"- self.sessions.set_agent_session_mapping(session_key, agent, mapping_key, session_id, session_working_path=session_working_path)+ self.sessions.set_agent_session_mapping(session_key, agent, mapping_key, session_id)self.sessions.mark_thread_active(user_id, context.channel_id, mapped_thread)except Exception as e:logger.error(f"Error resuming session: {e}", exc_info=True)diff --git a/modules/agents/native_sessions/claude.py b/modules/agents/native_sessions/claude.pyindex 615a4f980..829c6281b 100644--- a/modules/agents/native_sessions/claude.py+++ b/modules/agents/native_sessions/claude.py@@ -301,101 +301,6 @@ class ClaudeNativeSessionProvider(NativeSessionProvider):items.sort(key=lambda item: (-item.sort_ts, item.native_session_id))return items- def _merge_session_file_unfiltered(- self,- results: dict[str, NativeResumeSession],- *,- jsonl_path: Path,- ) -> bool:- """Merge a session file without filtering by working_path.- The session's working_path is inferred from the file's cwd/projectPath fields."""- rows = read_json_lines(jsonl_path)- if not rows:- return False- created_at = None- updated_at = None- first_prompt = ""- inferred_working_path = ""- for row in rows:- row_cwd = str(row.get("cwd") or row.get("projectPath") or "").strip()- if row_cwd:- inferred_working_path = row_cwd- if row.get("type") == "user" and not first_prompt:- first_prompt = str((row.get("message") or {}).get("content") or "")- timestamp = self._parse_iso(row.get("timestamp"))- if timestamp and created_at is None:- created_at = timestamp- if timestamp:- updated_at = timestamp- if not inferred_working_path:- return False- if not (created_at or updated_at):- stat = jsonl_path.stat()- created_at = datetime.fromtimestamp(stat.st_ctime)- updated_at = datetime.fromtimestamp(stat.st_mtime)- self._merge_session(- results,- NativeResumeSession(- agent="claude",- agent_prefix="cc",- native_session_id=jsonl_path.stem,- working_path=inferred_working_path,- created_at=created_at,- updated_at=updated_at,- sort_ts=(updated_at or created_at).timestamp() if (updated_at or created_at) else 0.0,- locator={"full_path": str(jsonl_path), "first_prompt": first_prompt},- ),- )- return True-- def list_all_metadata(self) -> list[NativeResumeSession]:- """List sessions across all project directories."""- results: dict[str, NativeResumeSession] = {}-- # Scan all project directories under ~/.claude/projects/- if not self.root.exists():- return []-- for project_dir in sorted(self.root.iterdir()):- if not project_dir.is_dir():- continue- # Scan all .jsonl session files in each project dir- for jsonl_path in sorted(project_dir.glob("*.jsonl")):- self._merge_session_file_unfiltered(results, jsonl_path=jsonl_path)-- # Also scan history.jsonl for sessions not found in files- if self.history_path.exists():- for row in read_json_lines(self.history_path):- session_id = str(row.get("sessionId") or "").strip()- project_path = str(row.get("project") or "").strip()- if not session_id or not project_path:- continue- if session_id in results:- # Already discovered from file; just enrich with display- display = str(row.get("display") or "").strip()- if display and not results[session_id].locator.get("history_display"):- results[session_id].locator["history_display"] = display- continue- updated_at = dt_from_ts(row.get("timestamp"), millis=True)- sort_ts = updated_at.timestamp() if updated_at else 0.0- self._merge_session(- results,- NativeResumeSession(- agent="claude",- agent_prefix="cc",- native_session_id=session_id,- working_path=project_path,- created_at=updated_at if isinstance(updated_at, datetime) else None,- updated_at=updated_at if isinstance(updated_at, datetime) else None,- sort_ts=sort_ts,- locator={"history_display": str(row.get("display") or "").strip()},- ),- )-- items = list(results.values())- items.sort(key=lambda item: (-item.sort_ts, item.native_session_id))- return items-def hydrate_preview(self, item: NativeResumeSession) -> NativeResumeSession:preview = ""full_path_raw = str(item.locator.get("full_path") or "").strip()diff --git a/modules/agents/native_sessions/codex.py b/modules/agents/native_sessions/codex.pyindex b26c36501..0758877b5 100644--- a/modules/agents/native_sessions/codex.py+++ b/modules/agents/native_sessions/codex.py@@ -57,47 +57,6 @@ class CodexNativeSessionProvider(NativeSessionProvider):logger.warning("Failed to list Codex sessions for %s: %s", working_path, exc)return items- def list_all_metadata(self) -> list[NativeResumeSession]:- """List sessions across all project directories."""- if not self.db_path.exists():- return []- items: list[NativeResumeSession] = []- try:- with self._connect() as conn:- cursor = conn.execute(- """- SELECT id, cwd, created_at, updated_at, title, first_user_message, rollout_path- FROM threads- WHERE archived = 0- ORDER BY updated_at DESC, id DESC- """,- )- for session_id, cwd, created_ts, updated_ts, title, first_user_message, rollout_path in cursor.fetchall():- if not cwd:- continue- created_at = dt_from_ts(created_ts)- updated_at = dt_from_ts(updated_ts)- items.append(- NativeResumeSession(- agent="codex",- agent_prefix="cx",- native_session_id=session_id,- working_path=cwd,- created_at=created_at,- updated_at=updated_at,- sort_ts=(updated_at or created_at).timestamp() if (updated_at or created_at) else 0.0,- locator={- "title": title or "",- "first_user_message": first_user_message or "",- "rollout_path": rollout_path or "",- },- )- )- except Exception as exc:- logger.warning("Failed to list all Codex sessions: %s", exc)- items.sort(key=lambda item: (-item.sort_ts, item.native_session_id))- return items-def hydrate_preview(self, item: NativeResumeSession) -> NativeResumeSession:preview = ""rollout_path_raw = str(item.locator.get("rollout_path") or "").strip()@@ -125,4 +84,4 @@ class CodexNativeSessionProvider(NativeSessionProvider):preview = str(item.locator.get("title") or item.locator.get("first_user_message") or "")item.last_agent_message = previewitem.last_agent_tail = build_tail_preview(preview or item.native_session_id)- return item\ No newline at end of file+ return itemdiff --git a/modules/agents/native_sessions/opencode.py b/modules/agents/native_sessions/opencode.pyindex 0fb584039..73142958a 100644--- a/modules/agents/native_sessions/opencode.py+++ b/modules/agents/native_sessions/opencode.py@@ -53,42 +53,6 @@ class OpenCodeNativeSessionProvider(NativeSessionProvider):logger.warning("Failed to list OpenCode sessions for %s: %s", working_path, exc)return rows- def list_all_metadata(self) -> list[NativeResumeSession]:- """List sessions across all project directories."""- if not self.db_path.exists():- return []- rows: list[NativeResumeSession] = []- try:- with self._connect() as conn:- cursor = conn.execute(- """- SELECT id, title, directory, time_created, time_updated- FROM session- ORDER BY time_updated DESC, id DESC- """,- )- for session_id, title, directory, created_ms, updated_ms in cursor.fetchall():- if not directory:- continue- created_at = dt_from_ts(created_ms, millis=True)- updated_at = dt_from_ts(updated_ms, millis=True)- rows.append(- NativeResumeSession(- agent="opencode",- agent_prefix="oc",- native_session_id=session_id,- working_path=directory,- created_at=created_at,- updated_at=updated_at,- sort_ts=(updated_at or created_at).timestamp() if (updated_at or created_at) else 0.0,- locator={"title": title or ""},- )- )- except Exception as exc:- logger.warning("Failed to list all OpenCode sessions: %s", exc)- rows.sort(key=lambda item: (-item.sort_ts, item.native_session_id))- return rows-def hydrate_preview(self, item: NativeResumeSession) -> NativeResumeSession:preview = ""if not self.db_path.exists():@@ -121,4 +85,4 @@ class OpenCodeNativeSessionProvider(NativeSessionProvider):item.last_agent_message = previewfallback = str(item.locator.get("title") or item.native_session_id)item.last_agent_tail = build_tail_preview(preview or fallback)- return item\ No newline at end of file+ return itemdiff --git a/modules/agents/native_sessions/service.py b/modules/agents/native_sessions/service.pyindex 50af919f8..223c5beca 100644--- a/modules/agents/native_sessions/service.py+++ b/modules/agents/native_sessions/service.py@@ -104,32 +104,6 @@ class AgentNativeSessionService:selected.sort(key=lambda item: (-item.sort_ts, item.agent_prefix, item.native_session_id))return selected- def list_all_recent_sessions(self, limit: int = 100) -> list[NativeResumeSession]:- """List recent sessions across all project directories."""- items: list[NativeResumeSession] = []- for provider in self.providers:- try:- items.extend(provider.list_all_metadata())- except Exception as exc:- logger.warning("Failed to list all %s sessions: %s", provider.agent_name, exc)-- items.sort(key=lambda item: (-item.sort_ts, item.agent_prefix, item.native_session_id))- items = self._apply_limit(items, max(limit, 0))-- provider_by_name = {provider.agent_name: provider for provider in self.providers}- hydrated: list[NativeResumeSession] = []- for item in items:- provider = provider_by_name.get(item.agent)- if not provider:- hydrated.append(item)- continue- try:- hydrated.append(provider.hydrate_preview(item))- except Exception as exc:- logger.warning("Failed to hydrate %s session %s: %s", item.agent, item.native_session_id, exc)- hydrated.append(item)- return hydrated-def get_session(self,working_path: str,diff --git a/modules/im/telegram.py b/modules/im/telegram.pyindex 55c086573..6eeb09723 100644--- a/modules/im/telegram.py+++ b/modules/im/telegram.py@@ -3,7 +3,6 @@ from __future__ import annotationsimport asyncioimport jsonimport logging-import osimport tempfileimport threadingfrom dataclasses import dataclass@@ -32,7 +31,7 @@ class _TelegramCwdPrompt:@dataclassclass _TelegramResumeSessionState:message_id: str- options: list[tuple[str, str, str]] # (agent, session_id, working_path)+ options: list[tuple[str, str]]is_dm: bool@@ -1053,26 +1052,16 @@ class TelegramBot(BaseIMClient):if context is None:raise ValueError("Telegram resume flow requires a message context")- options: list[tuple[str, str, str]] = [] # (agent, session_id, working_path)+ options: list[tuple[str, str]] = []rows: list[list[InlineButton]] = []summary_lines = [f"⏮️ {self._t('telegram.resumeTitle')}",self._t("telegram.resumeBody"),]- current_cwd = ""- if self._controller and hasattr(self._controller, "get_cwd"):- try:- current_cwd = self._controller.get_cwd(context)- except Exception:- passfor item in list(sessions)[:12]:idx = len(options)- options.append((item.agent, item.native_session_id, item.working_path))+ options.append((item.agent, item.native_session_id))label = AgentNativeSessionService.format_display_summary(item)- # Show project name when session is from a different project- if current_cwd and item.working_path and os.path.normcase(os.path.normpath(item.working_path)) != os.path.normcase(os.path.normpath(current_cwd)):- project_name = os.path.basename(item.working_path)- label = f"{label} [{project_name}]"rows.append([InlineButton(text=label[:40], callback_data=f"tg_resume:{idx}")])summary_lines.append(f"{idx + 1}. {label} ({AgentNativeSessionService.format_display_time(item)})"@@ -1108,7 +1097,7 @@ class TelegramBot(BaseIMClient):if option_index < 0 or option_index >= len(state.options):return- agent, session_id, working_path = state.options[option_index]+ agent, session_id = state.options[option_index]self._resume_states.pop(scope_key, None)if self._controller is None or not hasattr(self._controller, "session_handler"):await self.send_message(context, f"❌ {self._t('error.resumeFailed')}")@@ -1122,7 +1111,6 @@ class TelegramBot(BaseIMClient):session_id=session_id,is_dm=state.is_dm,platform="telegram",- session_working_path=working_path or None,)async def open_routing_modal(self, trigger_id: Any, channel_id: str, **kwargs):diff --git a/modules/sessions_facade.py b/modules/sessions_facade.pyindex 161ab45e7..d0707c1f6 100644--- a/modules/sessions_facade.py+++ b/modules/sessions_facade.py@@ -34,35 +34,11 @@ class SessionsFacade:agent_name: str,thread_id: str,session_id: str,- session_working_path: Optional[str] = None,) -> None:agent_map = self._ensure_agent_namespace(user_id, agent_name)agent_map[thread_id] = session_id- if session_working_path:- self._set_agent_session_working_path(user_id, agent_name, thread_id, session_working_path)self.sessions_store.save()- logger.info("Stored %s session mapping for %s: %s -> %s (working_path=%s)", agent_name, user_id, thread_id, session_id, session_working_path)-- def _set_agent_session_working_path(- self,- user_id: Union[int, str],- agent_name: str,- thread_id: str,- working_path: str,- ) -> None:- user_key = self._normalize_user_id(user_id)- wp_map = self.sessions_store.state.session_working_paths.setdefault(user_key, {}).setdefault(agent_name, {})- wp_map[thread_id] = working_path-- def get_agent_session_working_path(- self,- user_id: Union[int, str],- thread_id: str,- agent_name: str,- ) -> Optional[str]:- user_key = self._normalize_user_id(user_id)- wp_map = self.sessions_store.state.session_working_paths.get(user_key, {}).get(agent_name, {})- return wp_map.get(thread_id)+ logger.info("Stored %s session mapping for %s: %s -> %s", agent_name, user_id, thread_id, session_id)def get_agent_session_id(self,@@ -84,8 +60,6 @@ class SessionsFacade:agent_map = self.sessions_store.get_agent_map(user_key, agent_name)if thread_id in agent_map:del agent_map[thread_id]- wp_map = self.sessions_store.state.session_working_paths.get(user_key, {}).get(agent_name, {})- wp_map.pop(thread_id, None)self.sessions_store.save()logger.info("Cleared %s session mapping for user %s: %s", agent_name, user_id, thread_id)@@ -94,9 +68,6 @@ class SessionsFacade:agent_map = self.sessions_store.get_agent_map(user_key, agent_name)if agent_map:self.sessions_store.state.session_mappings[user_key][agent_name] = {}- wp_map = self.sessions_store.state.session_working_paths.get(user_key, {}).get(agent_name, {})- if wp_map:- wp_map.clear()self.sessions_store.save()logger.info("Cleared all %s session namespaces for user %s", agent_name, user_id)@@ -106,7 +77,6 @@ class SessionsFacade:if agent_maps:count = sum(len(agent_map) for agent_map in agent_maps.values())self.sessions_store.state.session_mappings[user_key] = {}- self.sessions_store.state.session_working_paths.pop(user_key, None)self.sessions_store.save()logger.info("Cleared all session mappings (%s bases) for user %s", count, user_id)@@ -230,8 +200,6 @@ class SessionsFacade:continuefor mapping_key in keys_to_remove:del agent_map[mapping_key]- wp_map = self.sessions_store.state.session_working_paths.get(user_key, {}).get(agent_name, {})- wp_map.pop(mapping_key, None)cleared += 1logger.info("Cleared %s session base for %s: %s (%s keys)",diff --git a/tests/test_native_session_providers.py b/tests/test_native_session_providers.pyindex da4713667..6eacfd8b7 100644--- a/tests/test_native_session_providers.py+++ b/tests/test_native_session_providers.py@@ -42,6 +42,40 @@ def test_claude_provider_falls_back_to_history_jsonl(tmp_path: Path) -> None:assert hydrated.last_agent_tail == "latest prompt"+def test_claude_project_path_encoding_handles_windows_paths() -> None:+ assert encode_project_path("C:\\Users\\cyh\\vibe-remote") == "C--Users-cyh-vibe-remote"+++def test_claude_provider_scans_candidate_jsonl_when_history_has_results(tmp_path: Path) -> None:+ projects_root = tmp_path / "projects"+ history_path = tmp_path / "history.jsonl"+ projects_root.mkdir(parents=True, exist_ok=True)++ working_path = "/Users/cyh/vibe-remote"+ history_path.write_text(+ '{"display":"history prompt","timestamp":1766079000000,"project":"/Users/cyh/vibe-remote","sessionId":"sess_history"}',+ encoding="utf-8",+ )++ candidate_dir = projects_root / encode_project_path(working_path)+ candidate_dir.mkdir(parents=True, exist_ok=True)+ (candidate_dir / "sess_sdk.jsonl").write_text(+ "\n".join(+ [+ '{"type":"user","timestamp":"2026-03-27T09:59:00Z","cwd":"/Users/cyh/vibe-remote","message":{"content":"sdk prompt"}}',+ '{"type":"assistant","timestamp":"2026-03-27T10:00:00Z","message":{"content":"sdk reply"}}',+ ]+ ),+ encoding="utf-8",+ )++ provider = ClaudeNativeSessionProvider(root=str(projects_root), history_path=str(history_path))++ items = provider.list_metadata(working_path)++ assert {item.native_session_id for item in items} == {"sess_history", "sess_sdk"}++def test_claude_provider_does_not_scan_unrelated_project_jsonl(tmp_path: Path, monkeypatch) -> None:projects_root = tmp_path / "projects"history_path = tmp_path / "history.jsonl"