Skip to content

armgit / avibe

Public Imported from GitHub
0

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

fix(channels): scope cache by auth context

cyhb149fd6ce453
diff --git a/core/chat_discovery.py b/core/chat_discovery.py
index aded97ff9..fbccbce62 100644
--- a/core/chat_discovery.py
+++ b/core/chat_discovery.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import hashlib
import json
import logging
import tempfile
@@ -38,6 +39,7 @@ METADATA_SUPPORTS_TOPICS = "supports_topics"
METADATA_CHANNEL_POSITION = "channel_position"
METADATA_CHANNEL_CATEGORY_ID = "channel_category_id"
METADATA_CHAT_MODE = "chat_mode"
+METADATA_AUTH_CONTEXT = "auth_context"
_STICKY_TRUE_KEYS = {METADATA_IS_FORUM, METADATA_SUPPORTS_TOPICS}
_DEBOUNCE_SECONDS = 60.0
@@ -161,13 +163,35 @@ def _refresh_state_key(platform: str, refresh_scope: str | None = None) -> str:
def _refresh_scope_for(platform: str, kwargs: dict[str, Any]) -> str | None:
+ parts: list[str] = []
if platform == "discord":
guild_id = str(kwargs.get("guild_id") or "").strip()
if guild_id:
- return f"guild.{guild_id}"
+ parts.append(f"guild.{guild_id}")
+ auth_context = _auth_context_for(platform, kwargs)
+ if auth_context:
+ parts.append(auth_context)
+ return ".".join(parts) or None
+
+
+def _auth_context_for(platform: str, kwargs: dict[str, Any]) -> str | None:
+ if platform in {"slack", "discord"}:
+ bot_token = str(kwargs.get("bot_token") or "").strip()
+ if bot_token:
+ return f"auth.{_stable_secret_hash(bot_token)}"
+ if platform == "lark":
+ app_id = str(kwargs.get("app_id") or "").strip()
+ app_secret = str(kwargs.get("app_secret") or "").strip()
+ domain = str(kwargs.get("domain") or "feishu").strip()
+ if app_id and app_secret:
+ return f"auth.{_stable_secret_hash(chr(0).join([domain, app_id, app_secret]))}"
return None
+def _stable_secret_hash(value: str) -> str:
+ return hashlib.sha256(value.encode("utf-8")).hexdigest()[:16]
+
+
def get_state_meta(key: str, *, db_path: Path | None = None) -> Any:
engine = _engine(db_path)
try:
@@ -321,6 +345,7 @@ def list_chats(
include_private: bool = True,
include_not_returned: bool = True,
parent_scope_id: str | None = None,
+ auth_context: str | None = None,
db_path: Path | None = None,
) -> list[ChannelInfo]:
engine = _engine(db_path)
@@ -351,6 +376,8 @@ def list_chats(
result: list[ChannelInfo] = []
for row in conn.execute(query).mappings():
metadata = _json_loads(row["metadata_json"], {})
+ if auth_context is not None and metadata.get(METADATA_AUTH_CONTEXT) != auth_context:
+ continue
visibility = str(metadata.get(METADATA_VISIBILITY_STATUS) or VISIBILITY_UNKNOWN)
if visibility == VISIBILITY_NOT_RETURNED and not include_not_returned:
continue
@@ -390,6 +417,7 @@ def refresh_platform(
) -> RefreshResult:
platform = str(platform)
refresh_scope = _refresh_scope_for(platform, kwargs)
+ auth_context = _auth_context_for(platform, kwargs)
lock = _refresh_lock(platform, refresh_scope)
with lock:
existing_state = refresh_state(platform, refresh_scope=refresh_scope, db_path=db_path)
@@ -444,6 +472,7 @@ def refresh_platform(
METADATA_VISIBILITY_STATUS: VISIBILITY_VISIBLE,
METADATA_LAST_REFRESHED_AT: success_at,
METADATA_LAST_MISSING_AT: None,
+ METADATA_AUTH_CONTEXT: auth_context,
},
)
upsert_scope(
@@ -465,6 +494,7 @@ def refresh_platform(
seen_ids,
refreshed_at=success_at,
parent_scope_id=refreshed_parent,
+ auth_context=auth_context,
)
state = RefreshState(last_attempt_at=now, last_success_at=success_at, last_error=None)
_write_refresh_state(conn, platform, state, now=success_at, refresh_scope=refresh_scope)
@@ -542,7 +572,14 @@ def channels_response(
) -> dict[str, Any]:
migrate_legacy_discovered_chats(db_path=db_path)
refresh_scope = _refresh_scope_for(platform, refresh_kwargs)
- all_chats = list_chats(platform, include_private=True, parent_scope_id=parent_scope_id, db_path=db_path)
+ auth_context = _auth_context_for(platform, refresh_kwargs)
+ all_chats = list_chats(
+ platform,
+ include_private=True,
+ parent_scope_id=parent_scope_id,
+ auth_context=auth_context,
+ db_path=db_path,
+ )
chats = _filter_response_chats(all_chats, include_private=include_private, require_member=require_member)
state = refresh_state(platform, refresh_scope=refresh_scope, db_path=db_path)
refreshing = False
@@ -553,7 +590,13 @@ def channels_response(
result = refresh_platform(platform, force=force, db_path=db_path, **refresh_kwargs)
state = result.refresh_state
error = result.error or state.last_error
- all_chats = list_chats(platform, include_private=True, parent_scope_id=parent_scope_id, db_path=db_path)
+ all_chats = list_chats(
+ platform,
+ include_private=True,
+ parent_scope_id=parent_scope_id,
+ auth_context=auth_context,
+ db_path=db_path,
+ )
chats = _filter_response_chats(all_chats, include_private=include_private, require_member=require_member)
elif can_refresh and should_refresh(platform, refresh_scope=refresh_scope, db_path=db_path):
_schedule_refresh(platform, db_path=db_path, **refresh_kwargs)
@@ -668,6 +711,7 @@ def _mark_not_returned(
*,
refreshed_at: str,
parent_scope_id: str | None,
+ auth_context: str | None,
) -> None:
conditions = [scopes.c.platform == platform, scopes.c.scope_type == CHANNEL_SCOPE_TYPE]
if parent_scope_id is not None:
@@ -678,6 +722,8 @@ def _mark_not_returned(
if native_id in seen_ids:
continue
metadata = _json_loads(row["metadata_json"], {})
+ if auth_context is not None and metadata.get(METADATA_AUTH_CONTEXT) != auth_context:
+ continue
metadata[METADATA_VISIBILITY_STATUS] = VISIBILITY_NOT_RETURNED
metadata[METADATA_LAST_MISSING_AT] = refreshed_at
conn.execute(
diff --git a/tests/test_chat_discovery.py b/tests/test_chat_discovery.py
index 45310cd73..b1f490be5 100644
--- a/tests/test_chat_discovery.py
+++ b/tests/test_chat_discovery.py
@@ -9,6 +9,12 @@ from storage.migrations import run_migrations
from storage.settings_service import SQLiteSettingsService
+def _auth_context(platform: str, **kwargs) -> str:
+ value = chat_discovery._auth_context_for(platform, kwargs)
+ assert value is not None
+ return value
+
+
def test_metadata_merge_preserves_unknown_keys_and_sticky_true_flags() -> None:
merged = chat_discovery.merge_metadata(
{
@@ -103,7 +109,13 @@ def test_legacy_discovered_chats_migration_is_idempotent(tmp_path: Path) -> None
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)
+ chat_discovery.remember_chat(
+ "slack",
+ "C_OLD",
+ name="old",
+ metadata={chat_discovery.METADATA_AUTH_CONTEXT: _auth_context("slack", bot_token="x")},
+ db_path=db_path,
+ )
service = SQLiteSettingsService(db_path)
try:
@@ -135,7 +147,13 @@ def test_refresh_marks_absent_rows_not_returned_without_deleting_settings(tmp_pa
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)
+ chat_discovery.remember_chat(
+ "slack",
+ "C_KEEP",
+ name="keep",
+ metadata={chat_discovery.METADATA_AUTH_CONTEXT: _auth_context("slack", bot_token="x")},
+ db_path=db_path,
+ )
from vibe import api
@@ -143,7 +161,7 @@ def test_refresh_failure_keeps_stale_cache_and_records_error(tmp_path: Path, mon
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)
+ state = chat_discovery.refresh_state("slack", refresh_scope=_auth_context("slack", bot_token="x"), db_path=db_path)
response = chat_discovery.channels_response("slack", bot_token="x", db_path=db_path)
assert result.ok is False
@@ -182,22 +200,23 @@ def test_empty_cache_channel_response_respects_refresh_backoff(tmp_path: Path, m
def test_slack_cached_response_respects_member_only_browse_mode(tmp_path: Path) -> None:
db_path = tmp_path / "vibe.sqlite"
run_migrations(db_path)
+ auth_context = _auth_context("slack", bot_token="x")
chat_discovery.remember_chat(
"slack",
"C_MEMBER",
name="member",
- metadata={chat_discovery.METADATA_IS_MEMBER: True},
+ metadata={chat_discovery.METADATA_IS_MEMBER: True, chat_discovery.METADATA_AUTH_CONTEXT: auth_context},
db_path=db_path,
)
chat_discovery.remember_chat(
"slack",
"C_OTHER",
name="other",
- metadata={chat_discovery.METADATA_IS_MEMBER: False},
+ metadata={chat_discovery.METADATA_IS_MEMBER: False, chat_discovery.METADATA_AUTH_CONTEXT: auth_context},
db_path=db_path,
)
chat_discovery.set_state_meta(
- "channel_refresh.slack",
+ f"channel_refresh.slack.{auth_context}",
{"last_attempt_at": "2999-01-01T00:00:00+00:00", "last_success_at": "2999-01-01T00:00:00+00:00", "last_error": None},
db_path=db_path,
)
@@ -209,6 +228,34 @@ def test_slack_cached_response_respects_member_only_browse_mode(tmp_path: Path)
assert {channel["id"] for channel in browse_all["channels"]} == {"C_MEMBER", "C_OTHER"}
+def test_slack_channel_cache_is_scoped_by_auth_context(tmp_path: Path, monkeypatch) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path)
+ calls: list[str] = []
+
+ from vibe import api
+
+ def fake_list_channels_live(token: str, browse_all: bool = False) -> dict:
+ calls.append(token)
+ suffix = token[-1].upper()
+ return {
+ "ok": True,
+ "channels": [{"id": f"C_{suffix}", "name": f"workspace-{suffix}", "is_private": False, "is_member": True}],
+ "is_member_only": not browse_all,
+ }
+
+ monkeypatch.setattr(api, "list_channels_live", fake_list_channels_live)
+
+ first = chat_discovery.channels_response("slack", bot_token="token-a", db_path=db_path)
+ second = chat_discovery.channels_response("slack", bot_token="token-b", db_path=db_path)
+ cached_first = chat_discovery.channels_response("slack", bot_token="token-a", db_path=db_path)
+
+ assert calls == ["token-a", "token-b"]
+ assert [channel["id"] for channel in first["channels"]] == ["C_A"]
+ assert [channel["id"] for channel in second["channels"]] == ["C_B"]
+ assert [channel["id"] for channel in cached_first["channels"]] == ["C_A"]
+
+
def test_discord_refresh_state_is_scoped_by_guild(tmp_path: Path, monkeypatch) -> None:
db_path = tmp_path / "vibe.sqlite"
run_migrations(db_path)
@@ -231,8 +278,22 @@ def test_discord_refresh_state_is_scoped_by_guild(tmp_path: Path, monkeypatch) -
assert first.ok is True
assert second.ok is True
assert calls == ["G1", "G2"]
- assert chat_discovery.refresh_state("discord", refresh_scope="guild.G1", db_path=db_path).last_success_at is not None
- assert chat_discovery.refresh_state("discord", refresh_scope="guild.G2", db_path=db_path).last_success_at is not None
+ assert (
+ chat_discovery.refresh_state(
+ "discord",
+ refresh_scope=f"guild.G1.{_auth_context('discord', bot_token='x')}",
+ db_path=db_path,
+ ).last_success_at
+ is not None
+ )
+ assert (
+ chat_discovery.refresh_state(
+ "discord",
+ refresh_scope=f"guild.G2.{_auth_context('discord', bot_token='x')}",
+ db_path=db_path,
+ ).last_success_at
+ is not None
+ )
assert chat_discovery.refresh_state("discord", db_path=db_path).last_success_at is None
diff --git a/ui/src/components/steps/ChannelList.tsx b/ui/src/components/steps/ChannelList.tsx
index a795e4e4f..d6df7f580 100644
--- a/ui/src/components/steps/ChannelList.tsx
+++ b/ui/src/components/steps/ChannelList.tsx
@@ -302,7 +302,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
Object.values(refreshFollowupTimersRef.current).forEach((timer) => clearTimeout(timer));
refreshFollowupTimersRef.current = {};
};
- }, [platform, selectedGuild, pageTab]);
+ }, [platform, selectedGuild, pageTab, botToken, larkAppId, larkAppSecret, larkDomain]);
useEffect(() => {
if (platform !== 'discord') return;