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(claude): avoid scanning unrelated session logs
cyh8f1d714b25e4
diff --git a/modules/agents/native_sessions/claude.py b/modules/agents/native_sessions/claude.pyindex 88fda68da..bb265e7ba 100644--- a/modules/agents/native_sessions/claude.py+++ b/modules/agents/native_sessions/claude.py@@ -72,137 +72,212 @@ class ClaudeNativeSessionProvider(NativeSessionProvider):except Exception:return None- def list_metadata(self, working_path: str) -> list[NativeResumeSession]:- candidate_names = self._candidate_project_names(working_path)- results: dict[str, NativeResumeSession] = {}-- project_dirs: list[Path] = []- seen_dirs: set[Path] = set()- for name in candidate_names:+ def _existing_candidate_dirs(self, working_path: str) -> list[Path]:+ dirs: list[Path] = []+ seen: set[Path] = set()+ for name in self._candidate_project_names(working_path):path = self.root / name- if path.exists() and path.is_dir() and path not in seen_dirs:- project_dirs.append(path)- seen_dirs.add(path)- for path in sorted(self.root.iterdir()) if self.root.exists() else []:- if not path.is_dir() or path in seen_dirs:+ if path.exists() and path.is_dir() and path not in seen:+ dirs.append(path)+ seen.add(path)+ return dirs++ def _load_project_index(self, project_dir: Path) -> list[dict]:+ index_path = project_dir / "sessions-index.json"+ if not index_path.is_file():+ return []+ try:+ payload = json.loads(index_path.read_text(encoding="utf-8"))+ except Exception as exc:+ logger.warning("Failed to parse Claude sessions index %s: %s", index_path, exc)+ return []+ entries = payload.get("entries", []) if isinstance(payload, dict) else []+ return [entry for entry in entries if isinstance(entry, dict)]++ def _merge_index_entry(+ self,+ results: dict[str, NativeResumeSession],+ *,+ working_path: str,+ project_dir: Path,+ entry: dict,+ ) -> str | None:+ session_id = str(entry.get("sessionId") or "").strip()+ project_path = str(entry.get("projectPath") or "").strip()+ if not session_id or project_path != working_path:+ return None+ created_at = self._parse_iso(entry.get("created"))+ updated_at = self._parse_iso(entry.get("modified"))+ self._merge_session(+ results,+ NativeResumeSession(+ agent="claude",+ agent_prefix="cc",+ native_session_id=session_id,+ working_path=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": entry.get("fullPath") or str(project_dir / f"{session_id}.jsonl"),+ "first_prompt": str(entry.get("firstPrompt") or ""),+ },+ ),+ )+ return session_id++ def _history_sessions(+ self, working_path: str+ ) -> dict[str, dict[str, str | float | datetime | None]]:+ latest_history: dict[str, dict[str, str | float | datetime | None]] = {}+ if not self.history_path.exists():+ return latest_history+ for row in read_json_lines(self.history_path):+ project_path = str(row.get("project") or "").strip()+ session_id = str(row.get("sessionId") or "").strip()+ if project_path != working_path or not session_id:continue- project_dirs.append(path)- seen_dirs.add(path)-- for project_dir in project_dirs:- index_path = project_dir / "sessions-index.json"- if index_path.is_file():- try:- payload = json.loads(index_path.read_text(encoding="utf-8"))- except Exception as exc:- logger.warning("Failed to parse Claude sessions index %s: %s", index_path, exc)- payload = {}-- entries = payload.get("entries", []) if isinstance(payload, dict) else []- for entry in entries:- if not isinstance(entry, dict):- continue- session_id = str(entry.get("sessionId") or "").strip()- project_path = str(entry.get("projectPath") or "").strip()- if not session_id or project_path != working_path:- continue- created_at = self._parse_iso(entry.get("created"))- updated_at = self._parse_iso(entry.get("modified"))- self._merge_session(- results,- NativeResumeSession(- agent="claude",- agent_prefix="cc",- native_session_id=session_id,- working_path=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": entry.get("fullPath") or str(project_dir / f"{session_id}.jsonl"),- "first_prompt": str(entry.get("firstPrompt") or ""),- },- ),- )+ updated_at = dt_from_ts(row.get("timestamp"), millis=True)+ sort_ts = updated_at.timestamp() if updated_at else 0.0+ current = latest_history.get(session_id)+ if current and sort_ts <= float(current.get("sort_ts") or 0.0):+ continue+ latest_history[session_id] = {+ "updated_at": updated_at,+ "sort_ts": sort_ts,+ "display": str(row.get("display") or "").strip(),+ }+ return latest_history- for jsonl_path in sorted(project_dir.glob("*.jsonl")):- session_id = jsonl_path.stem- rows = read_json_lines(jsonl_path)- if not rows:- continue- created_at = None- updated_at = None- first_prompt = ""- matched_working_path = False- 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_cwd == working_path:- matched_working_path = True- 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 matched_working_path and inferred_working_path and inferred_working_path != working_path:- continue- if not matched_working_path and not inferred_working_path and project_dir.name not in candidate_names:- continue- 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=session_id,- working_path=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},- ),- )-- if self.history_path.exists():- latest_history: dict[str, dict[str, str | float | datetime | None]] = {}- for row in read_json_lines(self.history_path):- project_path = str(row.get("project") or "").strip()- session_id = str(row.get("sessionId") or "").strip()- if project_path != working_path or not session_id:+ def _merge_history_sessions(+ self,+ results: dict[str, NativeResumeSession],+ *,+ working_path: str,+ history_sessions: dict[str, dict[str, str | float | datetime | None]],+ ) -> None:+ for session_id, payload in history_sessions.items():+ updated_at = payload.get("updated_at")+ self._merge_session(+ results,+ NativeResumeSession(+ agent="claude",+ agent_prefix="cc",+ native_session_id=session_id,+ working_path=working_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=float(payload.get("sort_ts") or 0.0),+ locator={"history_display": str(payload.get("display") or "")},+ ),+ )++ def _merge_session_file(+ self,+ results: dict[str, NativeResumeSession],+ *,+ working_path: str,+ jsonl_path: Path,+ ) -> bool:+ rows = read_json_lines(jsonl_path)+ if not rows:+ return False+ created_at = None+ updated_at = None+ first_prompt = ""+ matched_working_path = False+ 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_cwd == working_path:+ matched_working_path = True+ 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 matched_working_path and inferred_working_path and inferred_working_path != 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=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_metadata(self, working_path: str) -> list[NativeResumeSession]:+ results: dict[str, NativeResumeSession] = {}+ candidate_dirs = self._existing_candidate_dirs(working_path)+ history_sessions = self._history_sessions(working_path)+ known_session_ids = set(history_sessions)+ session_file_paths: dict[str, Path] = {}++ for project_dir in candidate_dirs:+ for entry in self._load_project_index(project_dir):+ session_id = self._merge_index_entry(results, working_path=working_path, project_dir=project_dir, entry=entry)+ if not session_id:continue- updated_at = dt_from_ts(row.get("timestamp"), millis=True)- sort_ts = updated_at.timestamp() if updated_at else 0.0- current = latest_history.get(session_id)- if current and sort_ts <= float(current.get("sort_ts") or 0.0):+ known_session_ids.add(session_id)+ full_path = str(entry.get("fullPath") or "").strip()+ if full_path:+ session_file_paths[session_id] = Path(full_path)++ if not results and self.root.exists():+ for project_dir in sorted(self.root.iterdir()):+ if not project_dir.is_dir() or project_dir in candidate_dirs:continue- latest_history[session_id] = {- "updated_at": updated_at,- "sort_ts": sort_ts,- "display": str(row.get("display") or "").strip(),- }-- for session_id, payload in latest_history.items():- updated_at = payload.get("updated_at")- self._merge_session(- results,- NativeResumeSession(- agent="claude",- agent_prefix="cc",- native_session_id=session_id,- working_path=working_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=float(payload.get("sort_ts") or 0.0),- locator={"history_display": str(payload.get("display") or "")},- ),- )+ for entry in self._load_project_index(project_dir):+ session_id = self._merge_index_entry(+ results, working_path=working_path, project_dir=project_dir, entry=entry+ )+ if not session_id:+ continue+ known_session_ids.add(session_id)+ full_path = str(entry.get("fullPath") or "").strip()+ if full_path:+ session_file_paths[session_id] = Path(full_path)++ self._merge_history_sessions(results, working_path=working_path, history_sessions=history_sessions)++ for session_id, item in list(results.items()):+ full_path_raw = str(item.locator.get("full_path") or "").strip()+ if full_path_raw:+ session_file_paths.setdefault(session_id, Path(full_path_raw))++ for session_id in known_session_ids:+ if session_id in session_file_paths:+ continue+ for project_dir in candidate_dirs:+ candidate_path = project_dir / f"{session_id}.jsonl"+ if candidate_path.is_file():+ session_file_paths[session_id] = candidate_path+ break++ for session_id, jsonl_path in session_file_paths.items():+ if not jsonl_path.is_file():+ continue+ self._merge_session_file(results, working_path=working_path, jsonl_path=jsonl_path)++ if not results:+ for project_dir in candidate_dirs:+ for jsonl_path in sorted(project_dir.glob("*.jsonl")):+ self._merge_session_file(results, working_path=working_path, jsonl_path=jsonl_path)items = list(results.values())items.sort(key=lambda item: (-item.sort_ts, item.native_session_id))diff --git a/tests/test_native_session_providers.py b/tests/test_native_session_providers.pyindex c19a16157..4954d792e 100644--- a/tests/test_native_session_providers.py+++ b/tests/test_native_session_providers.py@@ -1,8 +1,10 @@from pathlib import Pathfrom types import SimpleNamespace+import jsonfrom modules.agents.native_sessions.base import build_resume_preview, build_tail_preview-from modules.agents.native_sessions.claude import ClaudeNativeSessionProvider+from modules.agents.native_sessions import claude as claude_module+from modules.agents.native_sessions.claude import ClaudeNativeSessionProvider, encode_project_pathfrom modules.agents.native_sessions.service import AgentNativeSessionServicefrom modules.agents.native_sessions.types import NativeResumeSession@@ -34,6 +36,95 @@ def test_claude_provider_falls_back_to_history_jsonl(tmp_path: Path) -> None:assert hydrated.last_agent_tail == "latest prompt"+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"+ projects_root.mkdir(parents=True, exist_ok=True)+ history_path.write_text("", encoding="utf-8")++ working_path = "/Users/cyh/vibe-remote"+ candidate_dir = projects_root / encode_project_path(working_path)+ candidate_dir.mkdir(parents=True, exist_ok=True)+ target_jsonl = candidate_dir / "sess_target.jsonl"+ target_jsonl.write_text(+ '{"type":"assistant","timestamp":"2026-03-27T10:00:00Z","message":{"content":"done"}}\n',+ encoding="utf-8",+ )++ unrelated_dir = projects_root / "-Users-cyh-other"+ unrelated_dir.mkdir(parents=True, exist_ok=True)+ unrelated_jsonl = unrelated_dir / "sess_other.jsonl"+ unrelated_jsonl.write_text(+ '{"type":"assistant","timestamp":"2026-03-27T10:00:00Z","message":{"content":"should not read"}}\n',+ encoding="utf-8",+ )++ read_paths: list[Path] = []+ original_read_json_lines = claude_module.read_json_lines++ def _tracking_read_json_lines(path: Path) -> list[dict]:+ read_paths.append(Path(path))+ return original_read_json_lines(path)++ monkeypatch.setattr(claude_module, "read_json_lines", _tracking_read_json_lines)+ 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_target"]+ assert target_jsonl in read_paths+ assert unrelated_jsonl not in read_paths+++def test_claude_provider_uses_global_index_fallback_without_scanning_all_jsonl(tmp_path: Path) -> None:+ projects_root = tmp_path / "projects"+ history_path = tmp_path / "history.jsonl"+ projects_root.mkdir(parents=True, exist_ok=True)+ history_path.write_text("", encoding="utf-8")++ working_path = "/Users/cyh/vibe-remote"+ indexed_dir = projects_root / "-Users-cyh"+ indexed_dir.mkdir(parents=True, exist_ok=True)+ session_jsonl = indexed_dir / "sess_idx.jsonl"+ session_jsonl.write_text(+ "\n".join(+ [+ '{"type":"user","timestamp":"2026-03-27T09:59:00Z","cwd":"/Users/cyh/vibe-remote","message":{"content":"hello"}}',+ '{"type":"assistant","timestamp":"2026-03-27T10:00:00Z","message":{"content":"reply from indexed session"}}',+ ]+ ),+ encoding="utf-8",+ )+ (indexed_dir / "sessions-index.json").write_text(+ json.dumps(+ {+ "version": 1,+ "entries": [+ {+ "sessionId": "sess_idx",+ "projectPath": "/Users/cyh/vibe-remote",+ "created": "2026-03-27T09:59:00Z",+ "modified": "2026-03-27T10:00:00Z",+ "firstPrompt": "hello",+ "fullPath": str(session_jsonl),+ }+ ],+ }+ ),+ 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_idx"]+ hydrated = provider.hydrate_preview(items[0])+ assert hydrated.last_agent_message == "reply from indexed session"+ assert hydrated.last_agent_tail.startswith("...")+ assert "indexed session" in hydrated.last_agent_tail++def test_native_session_service_preserves_agent_visibility_when_limited() -> None:def _item(agent: str, prefix: str, session_id: str, sort_ts: float) -> NativeResumeSession:return NativeResumeSession(