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.

feat(channels): cache unified channel inventory

cyh4cd63a288db0
diff --git a/core/chat_discovery.py b/core/chat_discovery.py
new file mode 100644
index 000000000..ea0c8cf4a
--- /dev/null
+++ b/core/chat_discovery.py
@@ -0,0 +1,732 @@
+from __future__ import annotations
+
+import json
+import logging
+import tempfile
+import threading
+import time
+from dataclasses import asdict, dataclass, field
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any
+
+from sqlalchemy import Connection, and_, select
+
+from config import paths
+from storage.db import create_sqlite_engine
+from storage.migrations import run_migrations
+from storage.models import scope_settings, scopes, state_meta
+from storage.settings_service import make_scope_id, upsert_scope
+
+logger = logging.getLogger(__name__)
+
+CHANNEL_SCOPE_TYPE = "channel"
+GUILD_SCOPE_TYPE = "guild"
+VISIBILITY_VISIBLE = "visible"
+VISIBILITY_NOT_RETURNED = "not_returned"
+VISIBILITY_UNKNOWN = "unknown"
+
+METADATA_USERNAME = "username"
+METADATA_TOPIC = "topic"
+METADATA_PLATFORM_ARCHIVED = "platform_archived"
+METADATA_VISIBILITY_STATUS = "visibility_status"
+METADATA_IS_MEMBER = "is_member"
+METADATA_LAST_REFRESHED_AT = "last_refreshed_at"
+METADATA_LAST_MISSING_AT = "last_missing_at"
+METADATA_IS_FORUM = "is_forum"
+METADATA_SUPPORTS_TOPICS = "supports_topics"
+METADATA_CHANNEL_POSITION = "channel_position"
+METADATA_CHANNEL_CATEGORY_ID = "channel_category_id"
+METADATA_CHAT_MODE = "chat_mode"
+
+_STICKY_TRUE_KEYS = {METADATA_IS_FORUM, METADATA_SUPPORTS_TOPICS}
+_DEBOUNCE_SECONDS = 60.0
+_REFRESH_TTL_SECONDS = 300.0
+_MIN_REFRESH_INTERVAL_SECONDS = 30.0
+
+_debounce_lock = threading.Lock()
+_debounce_cache: dict[tuple[str, str], tuple[float, tuple[Any, ...]]] = {}
+
+_refresh_locks_lock = threading.Lock()
+_refresh_locks: dict[str, threading.Lock] = {}
+_migration_lock = threading.Lock()
+_migrated_db_paths: set[Path] = set()
+
+
+@dataclass
+class ChannelInfo:
+ platform: str
+ chat_id: str
+ name: str = ""
+ native_type: str = ""
+ is_private: bool = False
+ supports_threads: bool = False
+ platform_archived: bool = False
+ visibility_status: str = VISIBILITY_UNKNOWN
+ is_member: bool | None = None
+ parent_id: str | None = None
+ metadata: dict[str, Any] = field(default_factory=dict)
+ configured: bool = False
+ first_seen_at: str = ""
+ last_seen_at: str = ""
+
+ def to_channel_payload(self) -> dict[str, Any]:
+ payload = {
+ "id": self.chat_id,
+ "name": self.name or self.chat_id,
+ "type": self.native_type,
+ "native_type": self.native_type,
+ "is_private": self.is_private,
+ "supports_threads": self.supports_threads,
+ "platform_archived": self.platform_archived,
+ "visibility_status": self.visibility_status,
+ "is_member": self.is_member,
+ "parent_id": self.parent_id,
+ "metadata": self.metadata,
+ "configured": self.configured,
+ "first_seen_at": self.first_seen_at,
+ "last_seen_at": self.last_seen_at,
+ }
+ if METADATA_USERNAME in self.metadata:
+ payload["username"] = self.metadata.get(METADATA_USERNAME)
+ if METADATA_IS_FORUM in self.metadata:
+ payload["is_forum"] = bool(self.metadata.get(METADATA_IS_FORUM))
+ if METADATA_SUPPORTS_TOPICS in self.metadata:
+ payload["supports_topics"] = bool(self.metadata.get(METADATA_SUPPORTS_TOPICS))
+ return payload
+
+
+@dataclass
+class RefreshState:
+ last_attempt_at: str | None = None
+ last_success_at: str | None = None
+ last_error: str | None = None
+
+
+@dataclass
+class RefreshResult:
+ ok: bool
+ refresh_state: RefreshState
+ error: str | None = None
+
+
+def _utc_now_iso() -> str:
+ return datetime.now(timezone.utc).isoformat()
+
+
+def _json_dumps(value: Any) -> str:
+ return json.dumps(value, ensure_ascii=False, separators=(",", ":"))
+
+
+def _json_loads(value: str | None, default: Any) -> Any:
+ if not value:
+ return default
+ try:
+ parsed = json.loads(value)
+ except Exception:
+ return default
+ return parsed if isinstance(parsed, type(default)) else default
+
+
+def _json_load_any(value: str | None) -> Any:
+ if not value:
+ return None
+ try:
+ return json.loads(value)
+ except Exception:
+ return None
+
+
+def _db_path(db_path: Path | None = None) -> Path:
+ return (db_path or paths.get_sqlite_state_path()).expanduser().resolve()
+
+
+def _ensure_sqlite(db_path: Path | None = None) -> Path:
+ target = _db_path(db_path)
+ target.parent.mkdir(parents=True, exist_ok=True)
+ with _migration_lock:
+ if target not in _migrated_db_paths:
+ run_migrations(target)
+ _migrated_db_paths.add(target)
+ return target
+
+
+def _engine(db_path: Path | None = None):
+ return create_sqlite_engine(_ensure_sqlite(db_path))
+
+
+def _refresh_state_key(platform: str) -> str:
+ return f"channel_refresh.{platform}"
+
+
+def get_state_meta(key: str, *, db_path: Path | None = None) -> Any:
+ engine = _engine(db_path)
+ try:
+ with engine.connect() as conn:
+ value = conn.execute(select(state_meta.c.value_json).where(state_meta.c.key == key)).scalar_one_or_none()
+ return _json_load_any(value)
+ finally:
+ engine.dispose()
+
+
+def set_state_meta(key: str, value: Any, *, db_path: Path | None = None, now: str | None = None) -> None:
+ engine = _engine(db_path)
+ try:
+ with engine.begin() as conn:
+ _set_state_meta(conn, key, value, now=now or _utc_now_iso())
+ finally:
+ engine.dispose()
+
+
+def _set_state_meta(conn: Connection, key: str, value: Any, *, now: str) -> None:
+ conn.execute(state_meta.delete().where(state_meta.c.key == key))
+ conn.execute(state_meta.insert().values(key=key, value_json=_json_dumps(value), updated_at=now))
+
+
+def refresh_state(platform: str, *, db_path: Path | None = None) -> RefreshState:
+ payload = get_state_meta(_refresh_state_key(platform), db_path=db_path)
+ if not isinstance(payload, dict):
+ return RefreshState()
+ return RefreshState(
+ last_attempt_at=payload.get("last_attempt_at"),
+ last_success_at=payload.get("last_success_at"),
+ last_error=payload.get("last_error"),
+ )
+
+
+def _write_refresh_state(conn: Connection, platform: str, state: RefreshState, *, now: str) -> None:
+ _set_state_meta(
+ conn,
+ _refresh_state_key(platform),
+ asdict(state),
+ now=now,
+ )
+
+
+def normalize_metadata(metadata: dict[str, Any] | None) -> dict[str, Any]:
+ if not isinstance(metadata, dict):
+ return {}
+ return {str(key): value for key, value in metadata.items()}
+
+
+def merge_metadata(existing: dict[str, Any] | None, incoming: dict[str, Any] | None) -> dict[str, Any]:
+ merged = dict(existing or {})
+ for key, value in normalize_metadata(incoming).items():
+ if key in _STICKY_TRUE_KEYS and merged.get(key) is True and value is False:
+ continue
+ merged[key] = value
+ return merged
+
+
+def remember_chat(
+ platform: str,
+ chat_id: str,
+ *,
+ name: str = "",
+ native_type: str = "",
+ is_private: bool | None = None,
+ supports_threads: bool | None = None,
+ parent_id: str | None = None,
+ metadata: dict[str, Any] | None = None,
+ db_path: Path | None = None,
+) -> None:
+ platform = str(platform)
+ chat_id = str(chat_id).strip()
+ if not platform or not chat_id:
+ return
+
+ normalized_metadata = normalize_metadata(metadata)
+ normalized_metadata.setdefault(METADATA_VISIBILITY_STATUS, VISIBILITY_VISIBLE)
+ debounce_payload = (
+ name,
+ native_type,
+ is_private,
+ supports_threads,
+ parent_id,
+ tuple(sorted(normalized_metadata.items())),
+ )
+ debounce_key = (platform, chat_id)
+ monotonic_now = time.monotonic()
+ with _debounce_lock:
+ cached = _debounce_cache.get(debounce_key)
+ if cached is not None and monotonic_now - cached[0] < _DEBOUNCE_SECONDS and cached[1] == debounce_payload:
+ return
+ _debounce_cache[debounce_key] = (monotonic_now, debounce_payload)
+
+ now = _utc_now_iso()
+ engine = _engine(db_path)
+ try:
+ with engine.begin() as conn:
+ row = _scope_row(conn, platform, CHANNEL_SCOPE_TYPE, chat_id)
+ existing_metadata = _json_loads(row["metadata_json"], {}) if row else {}
+ merged_metadata = merge_metadata(existing_metadata, normalized_metadata)
+ if row is not None:
+ row_is_private = bool(row["is_private"])
+ row_supports_threads = bool(row["supports_threads"])
+ final_is_private = row_is_private or bool(is_private) if is_private is not None else row_is_private
+ final_supports_threads = (
+ row_supports_threads or bool(supports_threads)
+ if supports_threads is not None
+ else row_supports_threads
+ )
+ unchanged = (
+ (not name or row["display_name"] == name)
+ and (not native_type or row["native_type"] == native_type)
+ and row_is_private == final_is_private
+ and row_supports_threads == final_supports_threads
+ and existing_metadata == merged_metadata
+ and _seconds_since(row["last_seen_at"]) < _DEBOUNCE_SECONDS
+ )
+ if unchanged:
+ return
+ is_private = final_is_private
+ supports_threads = final_supports_threads
+
+ upsert_scope(
+ conn,
+ platform,
+ CHANNEL_SCOPE_TYPE,
+ chat_id,
+ parent_scope_id=parent_id,
+ display_name=name,
+ native_type=native_type,
+ is_private=is_private,
+ supports_threads=supports_threads,
+ metadata=merged_metadata,
+ now=now,
+ )
+ finally:
+ engine.dispose()
+
+
+def list_chats(
+ platform: str,
+ *,
+ include_private: bool = True,
+ include_not_returned: bool = True,
+ parent_scope_id: str | None = None,
+ db_path: Path | None = None,
+) -> list[ChannelInfo]:
+ engine = _engine(db_path)
+ try:
+ with engine.connect() as conn:
+ conditions = [scopes.c.platform == platform, scopes.c.scope_type == CHANNEL_SCOPE_TYPE]
+ if not include_private:
+ conditions.append(scopes.c.is_private == 0)
+ if parent_scope_id is not None:
+ conditions.append(scopes.c.parent_scope_id == parent_scope_id)
+ query = (
+ select(
+ scopes.c.platform,
+ scopes.c.native_id,
+ scopes.c.parent_scope_id,
+ scopes.c.display_name,
+ scopes.c.native_type,
+ scopes.c.is_private,
+ scopes.c.supports_threads,
+ scopes.c.metadata_json,
+ scopes.c.first_seen_at,
+ scopes.c.last_seen_at,
+ scope_settings.c.scope_id.label("settings_scope_id"),
+ )
+ .select_from(scopes.outerjoin(scope_settings, scope_settings.c.scope_id == scopes.c.id))
+ .where(and_(*conditions))
+ )
+ result: list[ChannelInfo] = []
+ for row in conn.execute(query).mappings():
+ metadata = _json_loads(row["metadata_json"], {})
+ visibility = str(metadata.get(METADATA_VISIBILITY_STATUS) or VISIBILITY_UNKNOWN)
+ if visibility == VISIBILITY_NOT_RETURNED and not include_not_returned:
+ continue
+ result.append(
+ ChannelInfo(
+ platform=str(row["platform"]),
+ chat_id=str(row["native_id"]),
+ name=str(row["display_name"] or ""),
+ native_type=str(row["native_type"] or ""),
+ is_private=bool(row["is_private"]),
+ supports_threads=bool(row["supports_threads"]),
+ platform_archived=bool(metadata.get(METADATA_PLATFORM_ARCHIVED, False)),
+ visibility_status=visibility,
+ is_member=metadata.get(METADATA_IS_MEMBER),
+ parent_id=row["parent_scope_id"],
+ metadata=metadata,
+ configured=row["settings_scope_id"] is not None,
+ first_seen_at=str(row["first_seen_at"] or ""),
+ last_seen_at=str(row["last_seen_at"] or ""),
+ )
+ )
+ return sorted(result, key=_channel_sort_key)
+ finally:
+ engine.dispose()
+
+
+def list_channel_payloads(platform: str, **kwargs: Any) -> list[dict[str, Any]]:
+ return [chat.to_channel_payload() for chat in list_chats(platform, **kwargs)]
+
+
+def refresh_platform(
+ platform: str,
+ *,
+ force: bool = False,
+ db_path: Path | None = None,
+ **kwargs: Any,
+) -> RefreshResult:
+ platform = str(platform)
+ lock = _refresh_lock(platform)
+ with lock:
+ existing_state = refresh_state(platform, db_path=db_path)
+ if not force and _seconds_since(existing_state.last_attempt_at) < _MIN_REFRESH_INTERVAL_SECONDS:
+ return RefreshResult(ok=True, refresh_state=existing_state)
+
+ now = _utc_now_iso()
+ engine = _engine(db_path)
+ try:
+ with engine.begin() as conn:
+ _write_refresh_state(
+ conn,
+ platform,
+ RefreshState(
+ last_attempt_at=now,
+ last_success_at=existing_state.last_success_at,
+ last_error=None,
+ ),
+ now=now,
+ )
+ finally:
+ engine.dispose()
+
+ try:
+ rows, refreshed_parent = _fetch_platform_channels(platform, db_path=db_path, **kwargs)
+ except Exception as exc:
+ error = str(exc)
+ logger.warning("Failed to refresh %s channel inventory: %s", platform, error, exc_info=True)
+ failed = RefreshState(
+ last_attempt_at=now,
+ last_success_at=existing_state.last_success_at,
+ last_error=error,
+ )
+ _store_refresh_state(platform, failed, db_path=db_path)
+ return RefreshResult(ok=False, refresh_state=failed, error=error)
+
+ success_at = _utc_now_iso()
+ engine = _engine(db_path)
+ try:
+ with engine.begin() as conn:
+ seen_ids: set[str] = set()
+ for row in rows:
+ native_id = str(row.get("id") or "").strip()
+ if not native_id:
+ continue
+ seen_ids.add(native_id)
+ parent_scope_id = row.get("parent_scope_id")
+ metadata = merge_metadata(
+ row.get("metadata") if isinstance(row.get("metadata"), dict) else {},
+ {
+ METADATA_VISIBILITY_STATUS: VISIBILITY_VISIBLE,
+ METADATA_LAST_REFRESHED_AT: success_at,
+ METADATA_LAST_MISSING_AT: None,
+ },
+ )
+ upsert_scope(
+ conn,
+ platform,
+ CHANNEL_SCOPE_TYPE,
+ native_id,
+ parent_scope_id=parent_scope_id,
+ display_name=str(row.get("name") or ""),
+ native_type=str(row.get("native_type") or row.get("type") or ""),
+ is_private=bool(row.get("is_private", False)),
+ supports_threads=bool(row.get("supports_threads", False)),
+ metadata=metadata,
+ now=success_at,
+ )
+ _mark_not_returned(
+ conn,
+ platform,
+ seen_ids,
+ refreshed_at=success_at,
+ parent_scope_id=refreshed_parent,
+ )
+ state = RefreshState(last_attempt_at=now, last_success_at=success_at, last_error=None)
+ _write_refresh_state(conn, platform, state, now=success_at)
+ return RefreshResult(ok=True, refresh_state=state)
+ finally:
+ engine.dispose()
+
+
+def should_refresh(platform: str, *, db_path: Path | None = None, ttl_seconds: float = _REFRESH_TTL_SECONDS) -> bool:
+ state = refresh_state(platform, db_path=db_path)
+ return _seconds_since(state.last_success_at) >= ttl_seconds
+
+
+def migrate_legacy_discovered_chats(*, db_path: Path | None = None, legacy_path: Path | None = None) -> None:
+ marker = "migrations.discovered_chats_to_scopes"
+ if get_state_meta(marker, db_path=db_path) == "done":
+ return
+
+ source = legacy_path or paths.get_discovered_chats_path()
+ if not source.exists():
+ set_state_meta(marker, "done", db_path=db_path)
+ return
+
+ payload = json.loads(source.read_text(encoding="utf-8"))
+ platforms = payload.get("platforms") if isinstance(payload, dict) else {}
+ if not isinstance(platforms, dict):
+ raise ValueError("discovered_chats.json platforms must be an object")
+
+ for platform, chats in platforms.items():
+ if not isinstance(chats, dict):
+ continue
+ for chat_id, chat in chats.items():
+ if not isinstance(chat, dict):
+ continue
+ remember_chat(
+ str(platform),
+ str(chat_id),
+ name=str(chat.get("name") or ""),
+ native_type=str(chat.get("chat_type") or ""),
+ is_private=bool(chat.get("is_private", False)),
+ supports_threads=bool(chat.get("supports_topics", False)),
+ metadata={
+ METADATA_USERNAME: chat.get("username"),
+ METADATA_IS_FORUM: bool(chat.get("is_forum", False)),
+ METADATA_SUPPORTS_TOPICS: bool(chat.get("supports_topics", False)),
+ },
+ db_path=db_path,
+ )
+
+ migrated_path = source.with_suffix(f"{source.suffix}.migrated")
+ _rename_preserving_existing(source, migrated_path)
+ set_state_meta(marker, "done", db_path=db_path)
+
+
+def channels_response(
+ platform: str,
+ *,
+ force: bool = False,
+ include_private: bool = True,
+ parent_scope_id: str | None = None,
+ db_path: Path | None = None,
+ **refresh_kwargs: Any,
+) -> dict[str, Any]:
+ migrate_legacy_discovered_chats(db_path=db_path)
+ all_chats = list_chats(platform, include_private=True, parent_scope_id=parent_scope_id, db_path=db_path)
+ chats = all_chats if include_private else [chat for chat in all_chats if not chat.is_private]
+ state = refresh_state(platform, db_path=db_path)
+ refreshing = False
+ error = state.last_error
+
+ can_refresh = platform in {"slack", "discord", "lark"}
+ if can_refresh and (force or not chats):
+ result = refresh_platform(platform, force=True, db_path=db_path, **refresh_kwargs)
+ state = result.refresh_state
+ error = result.error
+ all_chats = list_chats(platform, include_private=True, parent_scope_id=parent_scope_id, db_path=db_path)
+ chats = all_chats if include_private else [chat for chat in all_chats if not chat.is_private]
+ elif can_refresh and should_refresh(platform, db_path=db_path):
+ _schedule_refresh(platform, db_path=db_path, **refresh_kwargs)
+ refreshing = True
+
+ channels = [chat.to_channel_payload() for chat in chats]
+ return {
+ "ok": bool(channels) or error is None,
+ "channels": channels,
+ "chats": channels,
+ "refreshing": refreshing,
+ "last_attempt_at": state.last_attempt_at,
+ "last_success_at": state.last_success_at,
+ "error": error,
+ "summary": _summary(all_chats, chats, include_private=include_private),
+ }
+
+
+def _fetch_platform_channels(platform: str, **kwargs: Any) -> tuple[list[dict[str, Any]], str | None]:
+ from vibe import api
+
+ if platform == "slack":
+ result = api.list_channels_live(
+ kwargs.get("bot_token", ""),
+ browse_all=bool(kwargs.get("browse_all", False)),
+ )
+ if not result.get("ok"):
+ raise RuntimeError(str(result.get("error") or "Slack channel refresh failed"))
+ rows = []
+ for channel in result.get("channels") or []:
+ is_member = True if result.get("is_member_only") else channel.get("is_member")
+ rows.append(
+ {
+ "id": channel.get("id"),
+ "name": channel.get("name"),
+ "native_type": channel.get("type") or ("private_channel" if channel.get("is_private") else "public_channel"),
+ "is_private": bool(channel.get("is_private", False)),
+ "metadata": {
+ METADATA_USERNAME: channel.get("name"),
+ METADATA_IS_MEMBER: is_member,
+ },
+ }
+ )
+ return rows, None
+
+ if platform == "discord":
+ guild_id = str(kwargs.get("guild_id") or "").strip()
+ if not guild_id:
+ raise RuntimeError("Discord guild_id is required")
+ parent_scope_id = make_scope_id("discord", GUILD_SCOPE_TYPE, guild_id)
+ _remember_guild("discord", guild_id, db_path=kwargs.get("db_path"))
+ result = api.discord_list_channels_live(kwargs.get("bot_token", ""), guild_id)
+ if not result.get("ok"):
+ raise RuntimeError(str(result.get("error") or "Discord channel refresh failed"))
+ rows = []
+ for channel in result.get("channels") or []:
+ rows.append(
+ {
+ "id": channel.get("id"),
+ "name": channel.get("name"),
+ "native_type": str(channel.get("type") or ""),
+ "is_private": False,
+ "supports_threads": channel.get("type") in (0, 5),
+ "parent_scope_id": parent_scope_id,
+ "metadata": {
+ METADATA_CHANNEL_POSITION: channel.get("position"),
+ METADATA_CHANNEL_CATEGORY_ID: channel.get("parent_id"),
+ },
+ }
+ )
+ return rows, parent_scope_id
+
+ if platform == "lark":
+ result = api.lark_list_chats_live(
+ kwargs.get("app_id", ""),
+ kwargs.get("app_secret", ""),
+ kwargs.get("domain", "feishu"),
+ )
+ if not result.get("ok"):
+ raise RuntimeError(str(result.get("error") or "Lark chat refresh failed"))
+ rows = []
+ for chat in result.get("channels") or []:
+ rows.append(
+ {
+ "id": chat.get("id"),
+ "name": chat.get("name"),
+ "native_type": str(chat.get("chat_type") or ""),
+ "is_private": bool(chat.get("is_private", False)),
+ "metadata": {METADATA_CHAT_MODE: chat.get("chat_mode") or chat.get("chat_type")},
+ }
+ )
+ return rows, None
+
+ raise RuntimeError(f"Unsupported active refresh platform: {platform}")
+
+
+def _remember_guild(platform: str, guild_id: str, *, db_path: Path | None = None) -> None:
+ now = _utc_now_iso()
+ engine = _engine(db_path)
+ try:
+ with engine.begin() as conn:
+ upsert_scope(conn, platform, GUILD_SCOPE_TYPE, guild_id, now=now)
+ finally:
+ engine.dispose()
+
+
+def _mark_not_returned(
+ conn: Connection,
+ platform: str,
+ seen_ids: set[str],
+ *,
+ refreshed_at: str,
+ parent_scope_id: str | None,
+) -> None:
+ conditions = [scopes.c.platform == platform, scopes.c.scope_type == CHANNEL_SCOPE_TYPE]
+ if parent_scope_id is not None:
+ conditions.append(scopes.c.parent_scope_id == parent_scope_id)
+ rows = conn.execute(select(scopes).where(and_(*conditions))).mappings()
+ for row in rows:
+ native_id = str(row["native_id"])
+ if native_id in seen_ids:
+ continue
+ metadata = _json_loads(row["metadata_json"], {})
+ metadata[METADATA_VISIBILITY_STATUS] = VISIBILITY_NOT_RETURNED
+ metadata[METADATA_LAST_MISSING_AT] = refreshed_at
+ conn.execute(
+ scopes.update()
+ .where(scopes.c.id == row["id"])
+ .values(metadata_json=_json_dumps(metadata), updated_at=refreshed_at)
+ )
+
+
+def _scope_row(conn: Connection, platform: str, scope_type: str, native_id: str):
+ scope_id = make_scope_id(platform, scope_type, native_id)
+ return conn.execute(select(scopes).where(scopes.c.id == scope_id)).mappings().one_or_none()
+
+
+def _seconds_since(value: str | None) -> float:
+ if not value:
+ return float("inf")
+ try:
+ parsed = datetime.fromisoformat(value)
+ except ValueError:
+ return float("inf")
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=timezone.utc)
+ return max(0.0, (datetime.now(timezone.utc) - parsed).total_seconds())
+
+
+def _channel_sort_key(chat: ChannelInfo) -> tuple[int, int, str, str]:
+ visibility_rank = 0 if chat.visibility_status == VISIBILITY_VISIBLE else 1
+ configured_rank = 0 if chat.configured else 1
+ return (visibility_rank, configured_rank, (chat.name or chat.chat_id).lower(), chat.chat_id)
+
+
+def _refresh_lock(platform: str) -> threading.Lock:
+ with _refresh_locks_lock:
+ lock = _refresh_locks.get(platform)
+ if lock is None:
+ lock = threading.Lock()
+ _refresh_locks[platform] = lock
+ return lock
+
+
+def _store_refresh_state(platform: str, state: RefreshState, *, db_path: Path | None = None) -> None:
+ now = _utc_now_iso()
+ engine = _engine(db_path)
+ try:
+ with engine.begin() as conn:
+ _write_refresh_state(conn, platform, state, now=now)
+ finally:
+ engine.dispose()
+
+
+def _schedule_refresh(platform: str, *, db_path: Path | None = None, **kwargs: Any) -> None:
+ thread = threading.Thread(
+ target=refresh_platform,
+ kwargs={"platform": platform, "db_path": db_path, **kwargs},
+ daemon=True,
+ )
+ thread.start()
+
+
+def _summary(all_chats: list[ChannelInfo], visible_chats: list[ChannelInfo], *, include_private: bool) -> dict[str, int]:
+ return {
+ "discovered_count": len(all_chats),
+ "visible_count": len(visible_chats),
+ "hidden_private_count": 0 if include_private else sum(1 for chat in all_chats if chat.is_private),
+ "forum_count": sum(1 for chat in visible_chats if bool(chat.metadata.get(METADATA_SUPPORTS_TOPICS))),
+ }
+
+
+def _rename_preserving_existing(source: Path, target: Path) -> None:
+ if not target.exists():
+ source.rename(target)
+ return
+ with tempfile.NamedTemporaryFile(
+ mode="w",
+ dir=target.parent,
+ suffix=".migrated",
+ delete=False,
+ encoding="utf-8",
+ ) as handle:
+ handle.write(source.read_text(encoding="utf-8"))
+ temp_path = Path(handle.name)
+ source.unlink()
+ logger.info("Legacy discovered chats file already migrated; preserved duplicate at %s", temp_path)
diff --git a/docs/plans/unified-channel-inventory.md b/docs/plans/unified-channel-inventory.md
new file mode 100644
index 000000000..fe4896720
--- /dev/null
+++ b/docs/plans/unified-channel-inventory.md
@@ -0,0 +1,310 @@
+# Unified Channel Inventory Implementation Plan
+
+> Status: Implementation plan
+> Branch: `feature/unified-channel-inventory-impl`
+> Created: 2026-05-13
+
+## Problem
+
+The `/groups` page is slower than `/users` because Slack, Discord, and Lark
+fetch live platform APIs on every page open. Telegram has the opposite shape:
+it cannot actively list chats, so it keeps a legacy `discovered_chats.json`
+file populated from inbound messages.
+
+The repository already has the right persistent model:
+
+- `scopes`: all known runtime scopes, including channels, users, guilds, and
+ platform-level records.
+- `scope_settings`: optional user configuration for a scope.
+- `state_meta`: small key/value records for migration markers and runtime
+ bookkeeping.
+
+The implementation should finish that migration instead of adding a new cache
+table.
+
+## Product Goal
+
+Make `scopes` the single source of truth for channel inventory. The UI should
+load cached channels immediately, then refresh stale platform data in the
+background. User configuration remains in `scope_settings`.
+
+Expected behavior:
+
+1. `/groups` is fast after the first successful refresh.
+2. Telegram-discovered chats are stored in SQLite, not the legacy JSON store.
+3. Slack, Discord, and Lark refreshes update `scopes` rather than returning
+ live API results directly.
+4. Configured rows are never auto-deleted just because a platform refresh no
+ longer returns them.
+
+## Data Model
+
+No new tables and no schema-level columns.
+
+### `scopes`
+
+Use the existing columns as the canonical identity and inventory fields:
+
+- `id`: stable `"{platform}::{scope_type}::{native_id}"`.
+- `platform`: `slack`, `discord`, `telegram`, `lark`, etc.
+- `scope_type`: `channel`, `guild`, `user`, or `platform`.
+- `native_id`: platform-native identifier.
+- `parent_scope_id`: parent relationship, especially Discord guild -> channel.
+- `display_name`: best-known display name.
+- `native_type`: platform-native channel/chat type.
+- `is_private`: common privacy flag.
+- `supports_threads`: common thread/topic capability.
+- `metadata_json`: controlled platform-specific metadata.
+- `first_seen_at`, `last_seen_at`, `updated_at`: inventory timestamps.
+
+### `scope_settings`
+
+Keep this table strictly for user configuration:
+
+- enabled/disabled state
+- role/workdir/routing/model settings
+- require-mention behavior
+- opaque settings JSON for existing compatibility
+
+Do not add discovery, cache, refresh, or visibility fields here.
+
+### `metadata_json`
+
+Use `metadata_json` for channel inventory fields that are either
+platform-specific or not stable enough to deserve formal columns yet.
+
+Known keys for `scope_type = "channel"`:
+
+```jsonc
+{
+ "username": "string|null",
+ "topic": "string|null",
+ "platform_archived": "bool|null",
+ "visibility_status": "visible|not_returned|unknown",
+ "is_member": "bool|null",
+ "last_refreshed_at": "ISO 8601|null",
+ "last_missing_at": "ISO 8601|null",
+
+ "is_forum": "bool|null",
+ "supports_topics": "bool|null",
+
+ "channel_position": "number|null",
+ "channel_category_id": "string|null",
+
+ "chat_mode": "string|null"
+}
+```
+
+`visibility_status` is not the same as archive:
+
+- `visible`: the latest successful refresh for that refresh scope returned the
+ row.
+- `not_returned`: a successful refresh did not return a previously known row.
+- `unknown`: no active refresh has established current visibility.
+
+`platform_archived` is only true when the platform explicitly reports an
+archive/deleted state. Missing from a response is not enough evidence.
+
+All metadata writes go through the new inventory service. Adapters must not
+write arbitrary blobs directly.
+
+### `state_meta`
+
+Add conventional keys:
+
+```jsonc
+{
+ "channel_refresh.slack": {
+ "last_attempt_at": "ISO 8601|null",
+ "last_success_at": "ISO 8601|null",
+ "last_error": "string|null"
+ },
+ "channel_refresh.discord": {
+ "last_attempt_at": "ISO 8601|null",
+ "last_success_at": "ISO 8601|null",
+ "last_error": "string|null"
+ },
+ "channel_refresh.lark": {
+ "last_attempt_at": "ISO 8601|null",
+ "last_success_at": "ISO 8601|null",
+ "last_error": "string|null"
+ },
+ "migrations.discovered_chats_to_scopes": "done"
+}
+```
+
+Telegram has no active refresh state because the Bot API cannot list all chats.
+
+## Service Boundary
+
+Add `core/chat_discovery.py` as the only write/read service for channel
+inventory.
+
+Public surface:
+
+- `remember_chat(...)`: passive discovery path. Used by Telegram immediately
+ and optionally by Slack/Discord/Lark message handlers later.
+- `list_chats(platform, ...)`: cached read path. Returns `scopes` rows joined
+ with `scope_settings` so the UI can know whether a row is configured.
+- `refresh_platform(platform, force=False, ...)`: active refresh path for
+ Slack, Discord, and Lark.
+- `refresh_state(platform)`: returns `state_meta` refresh bookkeeping.
+- `migrate_legacy_discovered_chats()`: one-shot compatibility import from the
+ legacy JSON file into `scopes`.
+
+Important boundary: existing `upsert_scope()` is a low-level identity helper.
+It does not merge `metadata_json`. `chat_discovery` must read existing
+metadata, normalize incoming metadata, preserve unknown keys, then write the
+merged blob.
+
+## Refresh Behavior
+
+### Cached-first endpoints
+
+Change these endpoints to read from SQLite first:
+
+- `POST /slack/channels`
+- `POST /discord/channels`
+- `POST /lark/chats`
+- `POST /telegram/chats`
+
+Cold cache behavior:
+
+- If no cached rows exist for a requested active-refresh platform, do one
+ synchronous refresh so first-run behavior is no worse than today.
+
+Warm cache behavior:
+
+- Return cached rows immediately.
+- If stale or explicitly forced, schedule refresh in the background.
+- Return `refreshing: true` and the last known refresh state.
+
+Errors:
+
+- Keep returning stale cached rows when refresh fails.
+- Record `last_attempt_at` and `last_error`.
+- Do not update `last_success_at` on failure.
+
+### Slack
+
+Use existing Slack API helper behavior as the refresh source.
+
+On successful refresh:
+
+- Upsert returned channels as `scope_type = "channel"`.
+- Set `visibility_status = "visible"` and `last_refreshed_at`.
+- Preserve user settings by leaving `scope_settings` untouched.
+- Mark previously known Slack channel rows absent from the response as
+ `visibility_status = "not_returned"` and set `last_missing_at`.
+
+### Discord
+
+Discord refresh must be guild-aware.
+
+On successful refresh:
+
+1. Refresh guild scope rows where available.
+2. Determine refresh guild set from configured/allowed guilds and the current
+ endpoint request.
+3. Refresh channels for those guilds.
+4. Upsert channel rows with `parent_scope_id` pointing to the guild scope.
+5. Mark absent rows as `not_returned` only within the refreshed guild scope.
+
+Do not treat channels from unrefreshed guilds as missing.
+
+### Lark
+
+Use the joined chat list as the active refresh source.
+
+On successful refresh:
+
+- Upsert joined chats as channel scopes.
+- Set `visibility_status = "visible"`.
+- Mark previously known Lark rows absent from the response as `not_returned`.
+
+### Telegram
+
+Telegram has no active refresh.
+
+Replace the legacy `_remember_discovered_chat()` write path with
+`chat_discovery.remember_chat(platform="telegram", ...)`.
+
+Use a two-layer write mitigation:
+
+1. Process-local debounce keyed by `(platform, chat_id)` checks the normalized
+ payload before opening SQLite.
+2. After debounce expiry, read the existing row and skip the SQLite write if
+ only a too-recent `last_seen_at` would change.
+
+Target default: at most one write per unchanged chat per 60 seconds.
+
+## Legacy Migration
+
+The existing JSON-to-SQLite importer already imports `discovered_chats.json`
+when SQLite state is first created. Still add a compatibility migration because
+some users may have continued writing Telegram discoveries to the JSON file
+after SQLite was created.
+
+Migration rules:
+
+- Guard with `state_meta["migrations.discovered_chats_to_scopes"] == "done"`.
+- If the file is absent, mark done.
+- If present, import every valid chat into `scopes` through `remember_chat()`.
+- Rename the legacy file to `.json.migrated` after successful import.
+- Preserve the renamed file for one release as a fallback.
+
+## UI Behavior
+
+Update `ChannelList.tsx` to understand cached-first responses:
+
+- Render returned rows immediately.
+- Show last sync and refresh-in-progress state when present.
+- Manual refresh passes `force=1`.
+- After first paint, do one delayed re-fetch to pick up background refresh
+ results.
+- Keep current enable/disable and routing behavior backed by `scope_settings`.
+
+Existing response compatibility matters. If the UI currently expects
+`channels`, endpoints should either continue returning `channels` or return both
+`channels` and the new richer envelope during the transition.
+
+## Tests
+
+Add focused tests before broad regression:
+
+- Metadata normalization preserves unknown keys and merges known partial
+ updates.
+- `remember_chat()` creates rows, preserves existing settings, and debounces
+ unchanged payloads.
+- Legacy discovered chats migration is idempotent.
+- `list_chats()` returns configured state via LEFT JOIN.
+- Refresh state separates attempts, success, and errors.
+- Active refresh marks absent rows as `not_returned` without deleting settings.
+- Discord missing marking is scoped to refreshed guilds.
+- Endpoint cold-cache path performs synchronous refresh.
+- Endpoint warm-cache path returns cached rows and schedules refresh.
+
+Validation:
+
+- Focused pytest for storage/service/API paths.
+- `ruff check` on changed Python files.
+- `npm run build` for UI changes.
+- Docker regression only after core behavior is stable, preserving the selected
+ regression worktree state.
+
+## Implementation Order
+
+1. Add this plan.
+2. Add `core/chat_discovery.py` with metadata helpers, state_meta helpers,
+ `remember_chat()`, and `list_chats()`.
+3. Add unit tests for metadata merge, passive discovery, list join, and legacy
+ migration.
+4. Wire Telegram passive discovery to `chat_discovery`.
+5. Add active refresh functions for Slack, Discord, and Lark.
+6. Migrate channel endpoints to cached-first responses while preserving
+ frontend compatibility.
+7. Update `ChannelList.tsx` for refresh state and delayed re-fetch.
+8. Expand endpoint and refresh tests.
+9. Run focused backend tests, lint, and UI build.
+10. Review the final diff for cross-platform consistency before PR.
+
diff --git a/modules/im/telegram.py b/modules/im/telegram.py
index c872b2310..c327469e2 100644
--- a/modules/im/telegram.py
+++ b/modules/im/telegram.py
@@ -10,8 +10,8 @@ from datetime import datetime
from pathlib import Path
from typing import Any, Callable, Dict, Optional
-from config.discovered_chats import DiscoveredChatsStore
from config.v2_config import TelegramConfig
+from core import chat_discovery
from vibe.i18n import get_supported_languages, t as i18n_t
from vibe.proxy import resolve_proxy
from modules.agents.native_sessions import AgentNativeSessionService, NativeResumeSession
@@ -594,15 +594,18 @@ class TelegramBot(BaseIMClient):
chat_type = str(chat.get("type") or "")
is_topic_message = bool((message or {}).get("is_topic_message"))
is_forum = bool(chat.get("is_forum")) or is_topic_message
- DiscoveredChatsStore.get_instance().remember_chat(
+ chat_discovery.remember_chat(
platform="telegram",
chat_id=str(chat.get("id")),
name=name,
- username=str(chat.get("username") or ""),
- chat_type=chat_type,
+ native_type=chat_type,
is_private=chat_type == "private",
- is_forum=is_forum,
- supports_topics=chat_type == "supergroup" and is_forum,
+ supports_threads=chat_type == "supergroup" and is_forum,
+ metadata={
+ chat_discovery.METADATA_USERNAME: str(chat.get("username") or ""),
+ chat_discovery.METADATA_IS_FORUM: is_forum,
+ chat_discovery.METADATA_SUPPORTS_TOPICS: chat_type == "supergroup" and is_forum,
+ },
)
except Exception:
logger.debug("Failed to remember Telegram discovered chat", exc_info=True)
diff --git a/tests/test_chat_discovery.py b/tests/test_chat_discovery.py
new file mode 100644
index 000000000..279dd0142
--- /dev/null
+++ b/tests/test_chat_discovery.py
@@ -0,0 +1,155 @@
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+from config.v2_settings import ChannelSettings, SettingsState
+from core import chat_discovery
+from storage.migrations import run_migrations
+from storage.settings_service import SQLiteSettingsService
+
+
+def test_metadata_merge_preserves_unknown_keys_and_sticky_true_flags() -> None:
+ merged = chat_discovery.merge_metadata(
+ {
+ "custom": "keep",
+ chat_discovery.METADATA_IS_FORUM: True,
+ chat_discovery.METADATA_TOPIC: "old",
+ },
+ {
+ chat_discovery.METADATA_IS_FORUM: False,
+ chat_discovery.METADATA_TOPIC: "new",
+ chat_discovery.METADATA_VISIBILITY_STATUS: chat_discovery.VISIBILITY_VISIBLE,
+ },
+ )
+
+ assert merged["custom"] == "keep"
+ assert merged[chat_discovery.METADATA_IS_FORUM] is True
+ assert merged[chat_discovery.METADATA_TOPIC] == "new"
+ assert merged[chat_discovery.METADATA_VISIBILITY_STATUS] == chat_discovery.VISIBILITY_VISIBLE
+
+
+def test_remember_chat_lists_inventory_with_configured_state(tmp_path: Path) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path)
+
+ chat_discovery.remember_chat(
+ "telegram",
+ "123",
+ name="General",
+ native_type="supergroup",
+ is_private=False,
+ supports_threads=True,
+ metadata={
+ chat_discovery.METADATA_USERNAME: "general",
+ chat_discovery.METADATA_IS_FORUM: True,
+ },
+ db_path=db_path,
+ )
+
+ service = SQLiteSettingsService(db_path)
+ try:
+ service.save_state(SettingsState(channels={"telegram::123": ChannelSettings(enabled=True)}))
+ finally:
+ service.close()
+
+ chats = chat_discovery.list_chats("telegram", db_path=db_path)
+
+ assert len(chats) == 1
+ assert chats[0].chat_id == "123"
+ assert chats[0].name == "General"
+ assert chats[0].configured is True
+ assert chats[0].metadata[chat_discovery.METADATA_USERNAME] == "general"
+ assert chats[0].visibility_status == chat_discovery.VISIBILITY_VISIBLE
+
+
+def test_legacy_discovered_chats_migration_is_idempotent(tmp_path: Path) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path)
+ legacy_path = tmp_path / "discovered_chats.json"
+ legacy_path.write_text(
+ json.dumps(
+ {
+ "schema_version": 1,
+ "platforms": {
+ "telegram": {
+ "456": {
+ "name": "Ops",
+ "username": "ops",
+ "chat_type": "supergroup",
+ "is_private": False,
+ "is_forum": True,
+ "supports_topics": True,
+ }
+ }
+ },
+ }
+ ),
+ encoding="utf-8",
+ )
+
+ chat_discovery.migrate_legacy_discovered_chats(db_path=db_path, legacy_path=legacy_path)
+ chat_discovery.migrate_legacy_discovered_chats(db_path=db_path, legacy_path=legacy_path)
+
+ chats = chat_discovery.list_chats("telegram", db_path=db_path)
+
+ assert [chat.chat_id for chat in chats] == ["456"]
+ assert chats[0].supports_threads is True
+ assert legacy_path.exists() is False
+ assert legacy_path.with_suffix(".json.migrated").exists()
+ assert chat_discovery.get_state_meta("migrations.discovered_chats_to_scopes", db_path=db_path) == "done"
+
+
+def test_refresh_marks_absent_rows_not_returned_without_deleting_settings(tmp_path: Path, monkeypatch) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path)
+ chat_discovery.remember_chat("slack", "C_OLD", name="old", db_path=db_path)
+
+ service = SQLiteSettingsService(db_path)
+ try:
+ service.save_state(SettingsState(channels={"slack::C_OLD": ChannelSettings(enabled=True)}))
+ finally:
+ service.close()
+
+ from vibe import api
+
+ monkeypatch.setattr(
+ api,
+ "list_channels_live",
+ lambda _token, browse_all=False: {
+ "ok": True,
+ "channels": [{"id": "C_NEW", "name": "new", "is_private": False}],
+ "is_member_only": not browse_all,
+ },
+ )
+
+ result = chat_discovery.refresh_platform("slack", force=True, bot_token="x", db_path=db_path)
+ chats = {chat.chat_id: chat for chat in chat_discovery.list_chats("slack", db_path=db_path)}
+
+ assert result.ok is True
+ assert chats["C_NEW"].visibility_status == chat_discovery.VISIBILITY_VISIBLE
+ assert chats["C_OLD"].visibility_status == chat_discovery.VISIBILITY_NOT_RETURNED
+ assert chats["C_OLD"].configured is True
+
+
+def test_refresh_failure_keeps_stale_cache_and_records_error(tmp_path: Path, monkeypatch) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path)
+ chat_discovery.remember_chat("slack", "C_KEEP", name="keep", db_path=db_path)
+
+ from vibe import api
+
+ monkeypatch.setattr(api, "list_channels_live", lambda _token, browse_all=False: {"ok": False, "error": "boom"})
+
+ result = chat_discovery.refresh_platform("slack", force=True, bot_token="x", db_path=db_path)
+ chats = chat_discovery.list_chats("slack", db_path=db_path)
+ state = chat_discovery.refresh_state("slack", db_path=db_path)
+ response = chat_discovery.channels_response("slack", bot_token="x", db_path=db_path)
+
+ assert result.ok is False
+ assert result.refresh_state.last_error == "boom"
+ assert chats[0].chat_id == "C_KEEP"
+ assert state.last_error == "boom"
+ assert response["ok"] is True
+ assert response["channels"][0]["id"] == "C_KEEP"
+ assert response["error"] == "boom"
diff --git a/tests/test_telegram_bot.py b/tests/test_telegram_bot.py
index 023d39c7b..c9a6661b8 100644
--- a/tests/test_telegram_bot.py
+++ b/tests/test_telegram_bot.py
@@ -9,7 +9,7 @@ from unittest.mock import AsyncMock, patch
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from config import paths
-from config.discovered_chats import DiscoveredChatsStore
+from core import chat_discovery
from modules.agents.native_sessions import NativeResumeSession
from modules.im import MessageContext
from modules.im.telegram import TelegramBot
@@ -222,7 +222,6 @@ def test_start_new_topic_session_allows_forum_context_without_thread_id() -> Non
def test_build_message_context_records_discovered_chat(tmp_path, monkeypatch) -> None:
monkeypatch.setattr(paths, "get_vibe_remote_dir", lambda: tmp_path / ".vibe_remote")
- DiscoveredChatsStore.reset_instance()
bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))
context = bot._build_message_context(
@@ -236,11 +235,10 @@ def test_build_message_context_records_discovered_chat(tmp_path, monkeypatch) ->
)
assert context is not None
- chats = DiscoveredChatsStore.get_instance().list_chats("telegram", include_private=False)
+ chats = chat_discovery.list_chats("telegram", include_private=False)
assert len(chats) == 1
assert chats[0].chat_id == "-100123"
- assert chats[0].is_forum is True
- DiscoveredChatsStore.reset_instance()
+ assert chats[0].metadata[chat_discovery.METADATA_IS_FORUM] is True
def test_handle_message_ignores_foreign_bot_command() -> None:
diff --git a/tests/test_ui_api.py b/tests/test_ui_api.py
index 02776917a..dd5e971f1 100644
--- a/tests/test_ui_api.py
+++ b/tests/test_ui_api.py
@@ -5,7 +5,7 @@ from types import SimpleNamespace
import pytest
from config import paths
-from config.discovered_chats import DiscoveredChatsStore
+from core import chat_discovery
from vibe import api
from vibe.opencode_config import parse_jsonc_object
@@ -741,8 +741,9 @@ def test_parse_jsonc_object_rejects_invalid_jsonc():
def test_telegram_auth_test_returns_response(monkeypatch):
- async def fake_get_me(bot_token: str):
+ async def fake_get_me(bot_token: str, proxy_url: str | None = None):
assert bot_token == "123456:test-token"
+ assert proxy_url is None
return {"id": 1, "username": "vibe_remote_bot"}
monkeypatch.setattr(api, "_telegram_get_me", fake_get_me)
@@ -755,10 +756,8 @@ def test_telegram_auth_test_returns_response(monkeypatch):
def test_telegram_list_chats_returns_discovered_groups(tmp_path, monkeypatch):
monkeypatch.setattr(paths, "get_vibe_remote_dir", lambda: tmp_path / ".vibe_remote")
- DiscoveredChatsStore.reset_instance()
- store = DiscoveredChatsStore.get_instance()
- store.remember_chat(platform="telegram", chat_id="-1001", name="Core Group", chat_type="supergroup")
- store.remember_chat(platform="telegram", chat_id="42", name="Alex", chat_type="private", is_private=True)
+ chat_discovery.remember_chat("telegram", "-1001", name="Core Group", native_type="supergroup")
+ chat_discovery.remember_chat("telegram", "42", name="Alex", native_type="private", is_private=True)
result = api.telegram_list_chats()
@@ -766,4 +765,3 @@ def test_telegram_list_chats_returns_discovered_groups(tmp_path, monkeypatch):
assert [chat["id"] for chat in result["channels"]] == ["-1001"]
assert result["summary"]["visible_count"] == 1
assert result["summary"]["hidden_private_count"] == 1
- DiscoveredChatsStore.reset_instance()
diff --git a/ui/src/components/steps/ChannelList.tsx b/ui/src/components/steps/ChannelList.tsx
index 8b2c9a459..f60d8a9ec 100644
--- a/ui/src/components/steps/ChannelList.tsx
+++ b/ui/src/components/steps/ChannelList.tsx
@@ -75,6 +75,13 @@ interface TelegramDiscoverySummary {
forum_count: number;
}
+interface ChannelRefreshMeta {
+ refreshing?: boolean;
+ last_success_at?: string | null;
+ last_attempt_at?: string | null;
+ error?: string | null;
+}
+
const getDiscordGuildAllowlist = (source: any): string[] => {
const allowlist = source?.discordGuildAllowlist || source?.guild_allowlist || source?.discord?.guild_allowlist;
return Array.isArray(allowlist) ? allowlist : [];
@@ -126,6 +133,8 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
const configVersionRef = useRef(0);
const configRef = useRef<any>(data);
const [telegramSummary, setTelegramSummary] = useState<TelegramDiscoverySummary | null>(null);
+ const [refreshMetaByPlatform, setRefreshMetaByPlatform] = useState<Record<string, ChannelRefreshMeta>>({});
+ const refreshFollowupTimersRef = useRef<Record<string, ReturnType<typeof setTimeout>>>({});
// Directory browser state — tracks which channel's cwd picker is open
const [browsingCwdFor, setBrowsingCwdFor] = useState<string | null>(null);
// Page-mode tab/search/collapse state (only used when isPage is true)
@@ -138,6 +147,12 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
const [allConfigsByPlatform, setAllConfigsByPlatform] = useState<Record<string, Record<string, ChannelConfig>>>({});
const [allLoading, setAllLoading] = useState(false);
+ useEffect(() => {
+ return () => {
+ Object.values(refreshFollowupTimersRef.current).forEach((timer) => clearTimeout(timer));
+ };
+ }, []);
+
const applySelectedGuildIds = (allowlist: string[]) => {
const normalized = [...allowlist];
selectedGuildIdsRef.current = normalized;
@@ -340,7 +355,27 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
}
};
- const loadChannels = async (all?: boolean) => {
+ const recordRefreshMeta = (platformId: string, result: any) => {
+ setRefreshMetaByPlatform((prev) => ({
+ ...prev,
+ [platformId]: {
+ refreshing: Boolean(result.refreshing),
+ last_success_at: result.last_success_at || null,
+ last_attempt_at: result.last_attempt_at || null,
+ error: result.error || null,
+ },
+ }));
+ };
+
+ const scheduleRefreshFollowup = (platformId: string, all?: boolean) => {
+ const existing = refreshFollowupTimersRef.current[platformId];
+ if (existing) clearTimeout(existing);
+ refreshFollowupTimersRef.current[platformId] = setTimeout(() => {
+ void loadChannels(all, false);
+ }, 3000);
+ };
+
+ const loadChannels = async (all?: boolean, force = false) => {
if (platform === 'lark') {
if (!larkAppId || !larkAppSecret) return;
} else if (!botToken) {
@@ -354,12 +389,15 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
}
try {
if (platform === 'lark') {
- const result = await api.larkChats(larkAppId, larkAppSecret, larkDomain);
+ const result = await api.larkChats(larkAppId, larkAppSecret, larkDomain, force);
+ recordRefreshMeta(platform, result);
if (result.ok) {
setChannels(result.channels || []);
+ if (result.refreshing) scheduleRefreshFollowup(platform, isAll);
}
} else if (platform === 'telegram') {
const result = await api.telegramChats(false);
+ recordRefreshMeta(platform, result);
if (result.ok) {
setChannels(result.channels || []);
setTelegramSummary(result.summary || null);
@@ -369,16 +407,20 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
setLoading(false);
return;
}
- const result = await api.discordChannels(botToken, selectedGuild);
+ const result = await api.discordChannels(botToken, selectedGuild, force);
+ recordRefreshMeta(platform, result);
if (result.ok) {
const filtered = (result.channels || []).filter((c: any) => c.type === 0 || c.type === 5);
setChannels(filtered);
+ if (result.refreshing) scheduleRefreshFollowup(platform, isAll);
}
} else {
- const result = await api.slackChannels(botToken, isAll);
+ const result = await api.slackChannels(botToken, isAll, force);
+ recordRefreshMeta(platform, result);
if (result.ok) {
setChannels(result.channels || []);
if (isAll) setBrowseAll(true);
+ if (result.refreshing) scheduleRefreshFollowup(platform, isAll);
}
}
} catch (e) {
@@ -576,6 +618,18 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
});
const selectedCount = channels.filter((channel) => isChannelEnabled(channel.id)).length;
+ const currentRefreshMeta = refreshMetaByPlatform[platform] || {};
+ const refreshStatusText = React.useMemo(() => {
+ if (currentRefreshMeta.refreshing) return t('channelList.refreshingCache');
+ if (currentRefreshMeta.error) return t('channelList.refreshFailed');
+ if (currentRefreshMeta.last_success_at) {
+ const parsed = new Date(currentRefreshMeta.last_success_at);
+ if (!Number.isNaN(parsed.getTime())) {
+ return t('channelList.lastSynced', { time: parsed.toLocaleString() });
+ }
+ }
+ return '';
+ }, [currentRefreshMeta, t]);
// ---- Page-mode all-platforms aggregation ----
const updateConfigForPlatform = async (
@@ -609,7 +663,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
}
};
- const loadAllPlatformsData = async () => {
+ const loadAllPlatformsData = async (force = false) => {
if (!isPage) return;
const platforms = getEnabledPlatforms(config).filter((p) => platformSupportsChannels(config, p));
if (platforms.length === 0) return;
@@ -627,7 +681,8 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
const appSecret = config.lark?.app_secret || '';
const domain = config.lark?.domain || 'feishu';
if (appId && appSecret) {
- const result = await api.larkChats(appId, appSecret, domain);
+ const result = await api.larkChats(appId, appSecret, domain, force);
+ recordRefreshMeta(p, result);
if (result.ok) channelsList = result.channels || [];
}
} else if (p === 'telegram') {
@@ -640,14 +695,16 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
const guildId = allowlist[0] || selectedGuildIdsRef.current[0] || selectedGuild;
const token = config.discord?.bot_token || '';
if (guildId && token) {
- const result = await api.discordChannels(token, guildId);
+ const result = await api.discordChannels(token, guildId, force);
+ recordRefreshMeta(p, result);
if (result.ok) {
channelsList = (result.channels || []).filter((c: any) => c.type === 0 || c.type === 5);
}
}
} else if (p === 'slack') {
if (config.slack?.bot_token) {
- const result = await api.slackChannels(config.slack.bot_token, false);
+ const result = await api.slackChannels(config.slack.bot_token, false, force);
+ recordRefreshMeta(p, result);
if (result.ok) channelsList = result.channels || [];
}
}
@@ -880,9 +937,9 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
const handleRescan = () => {
if (pageTab === 'all') {
- void loadAllPlatformsData();
+ void loadAllPlatformsData(true);
} else {
- void loadChannels(false);
+ void loadChannels(false, true);
}
};
@@ -920,6 +977,9 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
<RefreshCw size={14} className={isRescanLoading ? 'animate-spin' : ''} />
{t('channelList.rescan')}
</Button>
+ {pageTab !== 'all' && refreshStatusText && (
+ <span className="text-xs text-muted">{refreshStatusText}</span>
+ )}
</div>
</div>
@@ -1051,7 +1111,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
type="button"
variant="secondary"
size="xs"
- onClick={() => loadChannels(true)}
+ onClick={() => loadChannels(true, true)}
disabled={loadingAll}
className="hover:border-cyan/40"
>
@@ -1378,7 +1438,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
type="button"
variant="secondary"
size="sm"
- onClick={() => loadChannels(browseAll)}
+ onClick={() => loadChannels(browseAll, true)}
className="hover:border-cyan/40"
>
<RefreshCw size={14} className={loading ? 'animate-spin' : ''} /> {t('channelList.refreshList')}
@@ -1388,7 +1448,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
type="button"
variant="secondary"
size="sm"
- onClick={() => loadChannels(true)}
+ onClick={() => loadChannels(true, true)}
disabled={loadingAll}
className="hover:border-cyan/40"
>
@@ -1399,6 +1459,9 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
{browseAll && (
<span className="text-xs text-muted">{t('channelList.showingAll')}</span>
)}
+ {refreshStatusText && (
+ <span className="text-xs text-muted">{refreshStatusText}</span>
+ )}
<span className="relative group">
<span className="flex items-center gap-1 text-sm text-muted cursor-help">
<HelpCircle size={14} />
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 554577669..575f01cfd 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -20,15 +20,15 @@ export type ApiContextType = {
detectCli: (binary: string) => Promise<any>;
installAgent: (name: string) => Promise<InstallResult>;
slackAuthTest: (botToken: string, proxyUrl?: string) => Promise<any>;
- slackChannels: (botToken: string, browseAll?: boolean) => Promise<any>;
+ slackChannels: (botToken: string, browseAll?: boolean, force?: boolean) => Promise<any>;
slackManifest: () => Promise<{ ok: boolean; manifest?: string; manifest_compact?: string; error?: string }>;
discordAuthTest: (botToken: string, proxyUrl?: string) => Promise<any>;
discordGuilds: (botToken: string) => Promise<any>;
- discordChannels: (botToken: string, guildId: string) => Promise<any>;
+ discordChannels: (botToken: string, guildId: string, force?: boolean) => Promise<any>;
telegramAuthTest: (botToken: string, proxyUrl?: string) => Promise<any>;
telegramChats: (includePrivate?: boolean) => Promise<any>;
larkAuthTest: (appId: string, appSecret: string, domain?: string, proxyUrl?: string) => Promise<any>;
- larkChats: (appId: string, appSecret: string, domain?: string) => Promise<any>;
+ larkChats: (appId: string, appSecret: string, domain?: string, force?: boolean) => Promise<any>;
larkTempWsStart: (appId: string, appSecret: string, domain?: string) => Promise<any>;
larkTempWsStop: () => Promise<any>;
wechatStartLogin: () => Promise<any>;
@@ -172,15 +172,15 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
detectCli: (binary) => getJson(`/cli/detect?binary=${encodeURIComponent(binary)}`),
installAgent: (name) => postJson(`/agent/${encodeURIComponent(name)}/install`, {}),
slackAuthTest: (botToken, proxyUrl) => postJson('/slack/auth_test', { bot_token: botToken, proxy_url: proxyUrl || undefined }),
- slackChannels: (botToken, browseAll) => postJson('/slack/channels', { bot_token: botToken, browse_all: browseAll || false }),
+ slackChannels: (botToken, browseAll, force) => postJson('/slack/channels', { bot_token: botToken, browse_all: browseAll || false, force: force || false }),
slackManifest: () => getJson('/slack/manifest'),
discordAuthTest: (botToken, proxyUrl) => postJson('/discord/auth_test', { bot_token: botToken, proxy_url: proxyUrl || undefined }),
discordGuilds: (botToken) => postJson('/discord/guilds', { bot_token: botToken }),
- discordChannels: (botToken, guildId) => postJson('/discord/channels', { bot_token: botToken, guild_id: guildId }),
+ discordChannels: (botToken, guildId, force) => postJson('/discord/channels', { bot_token: botToken, guild_id: guildId, force: force || false }),
telegramAuthTest: (botToken, proxyUrl) => postJson('/telegram/auth_test', { bot_token: botToken, proxy_url: proxyUrl || undefined }),
telegramChats: (includePrivate) => postJson('/telegram/chats', { include_private: includePrivate || false }),
larkAuthTest: (appId, appSecret, domain, proxyUrl) => postJson('/lark/auth_test', { app_id: appId, app_secret: appSecret, domain: domain || 'feishu', proxy_url: proxyUrl || undefined }),
- larkChats: (appId, appSecret, domain) => postJson('/lark/chats', { app_id: appId, app_secret: appSecret, domain: domain || 'feishu' }),
+ larkChats: (appId, appSecret, domain, force) => postJson('/lark/chats', { app_id: appId, app_secret: appSecret, domain: domain || 'feishu', force: force || false }),
larkTempWsStart: (appId, appSecret, domain) => postJson('/lark/temp_ws/start', { app_id: appId, app_secret: appSecret, domain: domain || 'feishu' }),
larkTempWsStop: () => postJson('/lark/temp_ws/stop', {}),
wechatStartLogin: () => postJson('/wechat/qr_login/start', {}),
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 0ad1d1291..adfdbdb29 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -525,6 +525,9 @@
"title": "Group Settings",
"subtitle": "Enable groups and configure routing for each group.",
"refreshList": "Refresh List",
+ "lastSynced": "Last synced {{time}}",
+ "refreshingCache": "Refreshing in background",
+ "refreshFailed": "Refresh failed; showing cached groups",
"browseAll": "Browse All Groups",
"showingAll": "Showing all workspace groups",
"cantFindChannel": "Can't find your group?",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index d7a6cba49..77fc00d71 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -525,6 +525,9 @@
"title": "群组设置",
"subtitle": "启用群组并配置每个群组的路由",
"refreshList": "刷新列表",
+ "lastSynced": "最近同步 {{time}}",
+ "refreshingCache": "正在后台刷新",
+ "refreshFailed": "刷新失败,正在显示缓存群组",
"browseAll": "浏览所有群组",
"showingAll": "已显示工作区所有群组",
"cantFindChannel": "找不到你想要的群组?",
diff --git a/vibe/api.py b/vibe/api.py
index b87fe54f0..e5b47ebf8 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -23,7 +23,6 @@ from config.v2_settings import (
_parse_routing,
_routing_to_dict,
)
-from config.discovered_chats import DiscoveredChatsStore
from config.v2_sessions import SessionsStore
from vibe.opencode_config import (
get_opencode_config_paths,
@@ -581,7 +580,18 @@ def slack_auth_test(bot_token: str, proxy_url: str | None = None) -> dict:
return {"ok": False, "error": str(exc)}
-def list_channels(bot_token: str, browse_all: bool = False) -> dict:
+def list_channels(bot_token: str, browse_all: bool = False, force: bool = False) -> dict:
+ from core import chat_discovery
+
+ return chat_discovery.channels_response(
+ "slack",
+ bot_token=bot_token,
+ browse_all=browse_all,
+ force=force,
+ )
+
+
+def list_channels_live(bot_token: str, browse_all: bool = False) -> dict:
"""List Slack channels.
When *browse_all* is False (default), only channels the bot has joined are
@@ -645,6 +655,7 @@ def list_channels(bot_token: str, browse_all: bool = False) -> dict:
"id": channel.get("id"),
"name": channel.get("name"),
"is_private": channel.get("is_private", False),
+ "is_member": channel.get("is_member"),
}
)
cursor = response.get("response_metadata", {}).get("next_cursor")
@@ -675,31 +686,12 @@ def telegram_auth_test(bot_token: str, proxy_url: str | None = None) -> dict:
def telegram_list_chats(include_private: bool = False) -> dict:
- store = DiscoveredChatsStore.get_instance()
- all_chats = store.list_chats("telegram", include_private=True)
- chats = all_chats if include_private else [chat for chat in all_chats if not chat.is_private]
- return {
- "ok": True,
- "channels": [
- {
- "id": chat.chat_id,
- "name": chat.name or chat.username or chat.chat_id,
- "username": chat.username,
- "type": chat.chat_type,
- "is_private": chat.is_private,
- "is_forum": chat.is_forum,
- "supports_topics": chat.supports_topics,
- "last_seen_at": chat.last_seen_at,
- }
- for chat in chats
- ],
- "summary": {
- "discovered_count": len(all_chats),
- "visible_count": len(chats),
- "hidden_private_count": sum(1 for chat in all_chats if chat.is_private) if not include_private else 0,
- "forum_count": sum(1 for chat in chats if chat.supports_topics),
- },
- }
+ from core import chat_discovery
+
+ return chat_discovery.channels_response(
+ "telegram",
+ include_private=include_private,
+ )
def discord_list_guilds(bot_token: str) -> dict:
@@ -710,7 +702,24 @@ def discord_list_guilds(bot_token: str) -> dict:
return {"ok": False, "error": str(exc)}
-def discord_list_channels(bot_token: str, guild_id: str) -> dict:
+def discord_list_channels(bot_token: str, guild_id: str, force: bool = False) -> dict:
+ from core import chat_discovery
+
+ parent_scope_id = None
+ if guild_id:
+ from storage.settings_service import make_scope_id
+
+ parent_scope_id = make_scope_id("discord", "guild", guild_id)
+ return chat_discovery.channels_response(
+ "discord",
+ bot_token=bot_token,
+ guild_id=guild_id,
+ parent_scope_id=parent_scope_id,
+ force=force,
+ )
+
+
+def discord_list_channels_live(bot_token: str, guild_id: str) -> dict:
try:
data = _discord_api_get(bot_token, f"guilds/{guild_id}/channels")
channels = []
@@ -720,6 +729,8 @@ def discord_list_channels(bot_token: str, guild_id: str) -> dict:
"id": channel.get("id"),
"name": channel.get("name"),
"type": channel.get("type"),
+ "position": channel.get("position"),
+ "parent_id": channel.get("parent_id"),
}
)
return {"ok": True, "channels": channels}
@@ -1649,7 +1660,19 @@ def lark_auth_test(
return {"ok": False, "error": str(exc)}
-def lark_list_chats(app_id: str, app_secret: str, domain: str = "feishu") -> dict:
+def lark_list_chats(app_id: str, app_secret: str, domain: str = "feishu", force: bool = False) -> dict:
+ from core import chat_discovery
+
+ return chat_discovery.channels_response(
+ "lark",
+ app_id=app_id,
+ app_secret=app_secret,
+ domain=domain,
+ force=force,
+ )
+
+
+def lark_list_chats_live(app_id: str, app_secret: str, domain: str = "feishu") -> dict:
"""List Lark/Feishu group chats the bot has joined (with pagination)."""
import urllib.request
@@ -1679,6 +1702,8 @@ def lark_list_chats(app_id: str, app_secret: str, domain: str = "feishu") -> dic
{
"id": c.get("chat_id"),
"name": c.get("name"),
+ "chat_type": c.get("chat_type"),
+ "chat_mode": c.get("chat_mode"),
"is_private": c.get("chat_type") == "private",
}
for c in items
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 60214e0c6..7e96775eb 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -1466,6 +1466,7 @@ def slack_channels():
api.list_channels(
payload.get("bot_token", ""),
browse_all=payload.get("browse_all", False),
+ force=payload.get("force", False) or request.args.get("force") == "1",
)
)
@@ -1495,7 +1496,13 @@ def discord_channels():
from vibe import api
payload = request.json or {}
- return jsonify(api.discord_list_channels(payload.get("bot_token", ""), payload.get("guild_id", "")))
+ return jsonify(
+ api.discord_list_channels(
+ payload.get("bot_token", ""),
+ payload.get("guild_id", ""),
+ force=payload.get("force", False) or request.args.get("force") == "1",
+ )
+ )
@app.route("/telegram/auth_test", methods=["POST"])
@@ -1538,7 +1545,12 @@ def lark_chats():
payload = request.json or {}
return jsonify(
- api.lark_list_chats(payload.get("app_id", ""), payload.get("app_secret", ""), payload.get("domain", "feishu"))
+ api.lark_list_chats(
+ payload.get("app_id", ""),
+ payload.get("app_secret", ""),
+ payload.get("domain", "feishu"),
+ force=payload.get("force", False) or request.args.get("force") == "1",
+ )
)