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(discovery): hide deleted channels in Group Settings + manual remove + fetch robustness (#726)

Qi Qi9dae091c9068
diff --git a/core/chat_discovery.py b/core/chat_discovery.py
index a42b4459a..a90d8b77c 100644
--- a/core/chat_discovery.py
+++ b/core/chat_discovery.py
@@ -16,7 +16,7 @@ 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.models import agent_events, media_objects, messages, scope_settings, scopes, state_meta
from storage.settings_service import make_scope_id, upsert_scope
logger = logging.getLogger(__name__)
@@ -40,6 +40,10 @@ METADATA_CHANNEL_POSITION = "channel_position"
METADATA_CHANNEL_CATEGORY_ID = "channel_category_id"
METADATA_CHAT_MODE = "chat_mode"
METADATA_AUTH_CONTEXT = "auth_context"
+# Set when a user removes a stale channel that still owns history (messages /
+# events / media). The scope row is kept so the CASCADE FKs do not wipe history;
+# this flag hides it from every discovery listing. Cleared on rediscovery.
+METADATA_DISMISSED_AT = "dismissed_at"
_STICKY_TRUE_KEYS = {METADATA_IS_FORUM, METADATA_SUPPORTS_TOPICS}
_DEBOUNCE_SECONDS = 60.0
@@ -282,6 +286,10 @@ def remember_chat(
normalized_metadata = normalize_metadata(metadata)
normalized_metadata.setdefault(METADATA_VISIBILITY_STATUS, VISIBILITY_VISIBLE)
+ # Seeing the chat again (e.g. Telegram passive rediscovery) un-dismisses it,
+ # so a removed-but-kept group reappears once it is active again. Without this,
+ # list_chats would hide it forever after a dismissal.
+ normalized_metadata.setdefault(METADATA_DISMISSED_AT, None)
debounce_payload = (
name,
native_type,
@@ -386,6 +394,10 @@ def list_chats(
metadata = _json_loads(row["metadata_json"], {})
if auth_context is not None and metadata.get(METADATA_AUTH_CONTEXT) != auth_context:
continue
+ if metadata.get(METADATA_DISMISSED_AT):
+ # User removed this stale entry but history kept the row alive;
+ # never surface it in any discovery listing.
+ continue
visibility = str(metadata.get(METADATA_VISIBILITY_STATUS) or VISIBILITY_UNKNOWN)
if visibility == VISIBILITY_NOT_RETURNED and not include_not_returned:
continue
@@ -451,7 +463,9 @@ def refresh_platform(
engine.dispose()
try:
- rows, refreshed_parent = _fetch_platform_channels(platform, db_path=db_path, **kwargs)
+ rows, refreshed_parent, fetch_complete = _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)
@@ -480,6 +494,9 @@ def refresh_platform(
METADATA_VISIBILITY_STATUS: VISIBILITY_VISIBLE,
METADATA_LAST_REFRESHED_AT: success_at,
METADATA_LAST_MISSING_AT: None,
+ # A channel that reappears on the platform is no longer
+ # dismissed — surface it again.
+ METADATA_DISMISSED_AT: None,
METADATA_AUTH_CONTEXT: auth_context,
},
)
@@ -496,15 +513,21 @@ def refresh_platform(
metadata=metadata,
now=success_at,
)
- _mark_not_returned(
- conn,
- platform,
- seen_ids,
- refreshed_at=success_at,
- parent_scope_id=refreshed_parent,
- auth_context=auth_context,
- require_member=platform == "slack" and not bool(kwargs.get("browse_all", False)),
- )
+ if fetch_complete:
+ _mark_not_returned(
+ conn,
+ platform,
+ seen_ids,
+ refreshed_at=success_at,
+ parent_scope_id=refreshed_parent,
+ auth_context=auth_context,
+ require_member=platform == "slack" and not bool(kwargs.get("browse_all", False)),
+ )
+ else:
+ logger.warning(
+ "Skipping not_returned marking for %s: live inventory was incomplete/truncated",
+ platform,
+ )
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)
if platform == "slack" and bool(kwargs.get("browse_all", False)) and auth_context:
@@ -588,6 +611,7 @@ def channels_response(
force: bool = False,
include_private: bool = True,
require_member: bool = False,
+ include_not_returned: bool = False,
parent_scope_id: str | None = None,
db_path: Path | None = None,
**refresh_kwargs: Any,
@@ -614,13 +638,22 @@ def channels_response(
auth_context=auth_context,
db_path=db_path,
)
- chats = _filter_response_chats(all_chats, include_private=include_private, require_member=require_member)
+ chats = _filter_response_chats(
+ all_chats,
+ include_private=include_private,
+ require_member=require_member,
+ include_not_returned=include_not_returned,
+ )
state = refresh_state(platform, refresh_scope=refresh_scope, db_path=db_path)
refreshing = False
error = state.last_error
cache_requires_refresh = _response_cache_requires_refresh(platform, state, refresh_kwargs)
- if can_refresh and (force or not chats or cache_requires_refresh):
+ # Trigger an initial refresh only when we have never successfully fetched.
+ # Do NOT key off an empty filtered ``chats`` list: once stale channels are
+ # hidden, an all-deleted install would otherwise refresh on every request and
+ # bypass the per-platform TTL guard (which lives inside ``refresh_platform``).
+ if can_refresh and (force or state.last_success_at is None or cache_requires_refresh):
result = refresh_platform(platform, force=force, db_path=db_path, **refresh_kwargs)
state = result.refresh_state
error = result.error or state.last_error
@@ -631,7 +664,12 @@ def channels_response(
auth_context=auth_context,
db_path=db_path,
)
- chats = _filter_response_chats(all_chats, include_private=include_private, require_member=require_member)
+ chats = _filter_response_chats(
+ all_chats,
+ include_private=include_private,
+ require_member=require_member,
+ include_not_returned=include_not_returned,
+ )
elif can_refresh and should_refresh(platform, refresh_scope=refresh_scope, db_path=db_path):
refreshing = _schedule_refresh(platform, db_path=db_path, **refresh_kwargs)
@@ -648,7 +686,15 @@ def channels_response(
}
-def _fetch_platform_channels(platform: str, **kwargs: Any) -> tuple[list[dict[str, Any]], str | None]:
+def _fetch_platform_channels(
+ platform: str, **kwargs: Any
+) -> tuple[list[dict[str, Any]], str | None, bool]:
+ """Fetch the live channel inventory for a platform.
+
+ Returns ``(rows, parent_scope_id, fetch_complete)``. ``fetch_complete`` is
+ ``False`` when the live list was truncated/partial (e.g. Lark page cap), in
+ which case the caller must NOT mark unseen channels ``not_returned``.
+ """
from vibe import api
if platform == "slack":
@@ -673,7 +719,7 @@ def _fetch_platform_channels(platform: str, **kwargs: Any) -> tuple[list[dict[st
},
}
)
- return rows, None
+ return rows, None, True
if platform == "discord":
guild_id = str(kwargs.get("guild_id") or "").strip()
@@ -701,7 +747,7 @@ def _fetch_platform_channels(platform: str, **kwargs: Any) -> tuple[list[dict[st
},
}
)
- return rows, parent_scope_id
+ return rows, parent_scope_id, True
if platform == "lark":
result = api.lark_list_chats_live(
@@ -722,7 +768,10 @@ def _fetch_platform_channels(platform: str, **kwargs: Any) -> tuple[list[dict[st
"metadata": {METADATA_CHAT_MODE: chat.get("chat_mode") or chat.get("chat_type")},
}
)
- return rows, None
+ # A truncated page-cap result is an incomplete inventory: never use it to
+ # mark unseen chats not_returned.
+ fetch_complete = not bool(result.get("truncated", False))
+ return rows, None, fetch_complete
raise RuntimeError(f"Unsupported active refresh platform: {platform}")
@@ -769,6 +818,68 @@ def _mark_not_returned(
)
+def _scope_has_history(conn: Connection, scope_id: str) -> bool:
+ """True if the scope owns rows whose FK to scopes is ON DELETE CASCADE.
+
+ ``messages``, ``agent_events`` and ``media_objects`` cascade-delete with the
+ scope row, so deleting a scope that owns any of them would destroy stored
+ chat history/traces/media — not just the discovery entry.
+ """
+ for table in (messages, agent_events, media_objects):
+ exists = conn.execute(
+ select(table.c.scope_id).where(table.c.scope_id == scope_id).limit(1)
+ ).first()
+ if exists is not None:
+ return True
+ return False
+
+
+def delete_scope(
+ platform: str,
+ native_id: str,
+ *,
+ scope_type: str = CHANNEL_SCOPE_TYPE,
+ db_path: Path | None = None,
+) -> dict[str, bool]:
+ """Remove a discovered scope and its settings without destroying history.
+
+ The user-facing intent is "clear this stale entry", not "purge all stored
+ messages". Because ``messages`` / ``agent_events`` / ``media_objects`` FK the
+ scope with ON DELETE CASCADE, a hard delete would wipe that history. So:
+
+ - the ``scope_settings`` row is always deleted (the user's config);
+ - if the scope owns no cascading history, the ``scopes`` row is physically
+ deleted (clean removal);
+ - otherwise the ``scopes`` row is kept and stamped ``dismissed_at`` so it is
+ hidden from every discovery listing while its history stays intact.
+
+ Returns ``{"removed": bool, "dismissed": bool}``.
+ """
+ scope_id = make_scope_id(platform, scope_type, native_id)
+ engine = _engine(db_path)
+ try:
+ with engine.begin() as conn:
+ row = conn.execute(select(scopes).where(scopes.c.id == scope_id)).mappings().one_or_none()
+ if row is None:
+ return {"removed": False, "dismissed": False}
+ conn.execute(scope_settings.delete().where(scope_settings.c.scope_id == scope_id))
+ if _scope_has_history(conn, scope_id):
+ metadata = _json_loads(row["metadata_json"], {})
+ metadata[METADATA_DISMISSED_AT] = _utc_now_iso()
+ conn.execute(
+ scopes.update()
+ .where(scopes.c.id == scope_id)
+ .values(metadata_json=_json_dumps(metadata), updated_at=_utc_now_iso())
+ )
+ return {"removed": False, "dismissed": True}
+ # No cascading history — safe to physically delete. Child scopes keep
+ # their rows (parent_scope_id is ON DELETE SET NULL).
+ result = conn.execute(scopes.delete().where(scopes.c.id == scope_id))
+ return {"removed": bool(result.rowcount), "dismissed": False}
+ finally:
+ engine.dispose()
+
+
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()
@@ -850,6 +961,9 @@ def _summary(all_chats: list[ChannelInfo], visible_chats: list[ChannelInfo], *,
return {
"discovered_count": len(all_chats),
"visible_count": len(visible_chats),
+ "not_returned_count": sum(
+ 1 for chat in all_chats if chat.visibility_status == VISIBILITY_NOT_RETURNED
+ ),
"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))),
}
@@ -860,16 +974,22 @@ def _filter_response_chats(
*,
include_private: bool,
require_member: bool,
+ include_not_returned: bool = False,
) -> list[ChannelInfo]:
result = chats
if not include_private:
result = [chat for chat in result if not chat.is_private]
+ if not include_not_returned:
+ # Hide channels that the platform no longer returns (deleted / inaccessible)
+ # by default, across all platforms. They remain in storage and are exposed
+ # only when a caller explicitly opts in (review / manual remove views).
+ result = [chat for chat in result if chat.visibility_status != VISIBILITY_NOT_RETURNED]
if require_member:
- result = [
- chat
- for chat in result
- if chat.is_member is True and chat.visibility_status != VISIBILITY_NOT_RETURNED
- ]
+ # Keep only member channels for the Slack member-only view. Do NOT re-drop
+ # not_returned here: when the caller opted in (include_not_returned), the
+ # stale member rows are exactly what the review/remove view needs; when
+ # they did not, those rows were already removed above.
+ result = [chat for chat in result if chat.is_member is True]
return result
diff --git a/docs/plans/stale-channel-discovery-fix.md b/docs/plans/stale-channel-discovery-fix.md
new file mode 100644
index 000000000..9c53e105a
--- /dev/null
+++ b/docs/plans/stale-channel-discovery-fix.md
@@ -0,0 +1,222 @@
+# Fix: Deleted/stale channels keep showing in Group Settings
+
+## Background
+
+A Discord channel that was deleted on the platform still appears in the Web UI
+**Group Settings → Groups** list. Investigation shows this is a shared-core gap,
+not a Discord-only bug.
+
+Data flow today (`core/chat_discovery.py`):
+
+1. On `refresh_platform()` (Rescan), live channels are fetched via
+ `_fetch_platform_channels()`. Every returned id goes into `seen_ids` and is
+ upserted with `visibility_status = "visible"` (lines 469–498).
+2. `_mark_not_returned()` (lines 740–769) walks the persisted `scopes` for that
+ platform and, for any row **not** in `seen_ids`, soft-marks it
+ `visibility_status = "not_returned"` plus `last_missing_at`. Rows are **never
+ physically deleted**.
+3. `channels_response()` (lines 585–648) calls `list_chats(..., include_not_returned=True)`
+ and `_filter_response_chats()`. That filter only drops `not_returned` when
+ `require_member=True`, which is **Slack-with-membership only**. For Discord and
+ Lark (`require_member=False`) `not_returned` rows are returned verbatim.
+4. The UI (`ui/src/components/steps/ChannelList.tsx`) never reads
+ `visibility_status`; its "Show inactive" toggle filters by `config.enabled`
+ (enabled/disabled), not by platform existence. So deleted channels always show
+ and there is no way to remove them.
+
+Per-platform audit:
+
+| Platform | Live list API | Pagination handled | 429/backoff | `_mark_not_returned` | Deleted-still-shows |
+| --- | --- | --- | --- | --- | --- |
+| Slack | `users_conversations` / `conversations_list` | yes (cursor loop) | yes (5x backoff) | yes, `require_member` gated | yes |
+| Discord | `GET /guilds/{id}/channels` (+ guild list) | channels: single call (complete); **guild list `users/@me/guilds` not paginated** | **no** | yes (`require_member=False`) | yes |
+| Lark/Feishu | `GET /im/v1/chats` | yes (`page_token`, `max_pages=50` cap → `truncated`) | **no** | yes (`require_member=False`) | yes |
+| Telegram | none (passive, message-driven) | n/a | n/a | **never called** | yes (cannot auto-detect deletion) |
+| WeChat | none (no channel concept) | n/a | n/a | n/a | n/a (UI short-circuits) |
+
+Key correctness coupling: hiding `not_returned` is only safe if we never
+`_mark_not_returned` on an **incomplete** fetch (transient 429, truncated page).
+`_mark_not_returned` already runs only after a fetch that did not raise — but it
+runs inside the same transaction that has already upserted the seen rows, so a
+fetch that *succeeds but is partial* (Lark `truncated`) will still mark the unseen
+(but actually-live) rows `not_returned`. So P0 (hide) and P1 (never false-mark)
+must ship together.
+
+Note: Discord's per-guild channel fetch (`GET /guilds/{id}/channels`) returns the
+whole channel set in one call, and `_fetch_platform_channels` for Discord already
+requires a `guild_id`. The paginated `users/@me/guilds` endpoint is only used by
+the setup-wizard guild picker and has **no** effect on `_mark_not_returned`
+correctness — it is a UX item, not a P1 correctness item.
+
+## Goal
+
+1. Deleted/inaccessible channels stop appearing in the Groups list by default
+ (the reported bug), across all active-refresh platforms (Slack, Discord, Lark).
+2. Users can still review and manually remove stale entries (covers Telegram /
+ WeChat and any soft-marked row), with a clear visual state.
+3. Eliminate false `not_returned` marking caused by partial/rate-limited fetches.
+
+Non-goals: redesigning discovery; automatic background physical deletion (left as
+an explicit, optional follow-up); changing the meaning of the existing
+"Show inactive" (enabled/disabled) toggle.
+
+## Solution
+
+### P0 — Hide `not_returned` from the Groups list by default (root-cause)
+
+Backend (`core/chat_discovery.py`):
+
+- Add `include_not_returned: bool = False` parameter to `channels_response()`.
+ **`all_chats` keeps `list_chats(..., include_not_returned=True)` unchanged** (it
+ must stay the full inventory for accurate counts). Apply the filter only to the
+ returned `chats` view — extend `_filter_response_chats()` to drop
+ `visibility_status == not_returned` whenever `include_not_returned` is `False`
+ (for all platforms, not just `require_member`). This is the central, platform-
+ agnostic fix, so every active-refresh platform inherits it.
+- `_summary()` derives counts from the unfiltered `all_chats`:
+ `discovered_count = len(all_chats)` (unchanged) and a new
+ `not_returned_count = len([c for c in all_chats if c.visibility_status ==
+ VISIBILITY_NOT_RETURNED])` — no extra DB query.
+- **Fix the refresh-trigger guard** at `channels_response()` line ~623. Today it
+ is `force or not chats or cache_requires_refresh`. After P0, `chats` excludes
+ `not_returned`, so an install whose channels were all deleted would have
+ `chats == []` on every request and re-refresh on every load (bypassing the TTL,
+ which only lives inside `refresh_platform`). Replace the `not chats` signal with
+ a "never successfully fetched" signal: `force or state.last_success_at is None or
+ cache_requires_refresh`. The background `should_refresh()`/`_schedule_refresh`
+ path (line ~635) already handles staleness via TTL and is unchanged.
+- Keep the existing `require_member` + `not_returned` check in
+ `_filter_response_chats()` as defense-in-depth (harmless once the new default
+ filter is in place; protects callers that pass an unfiltered list).
+- API surface: `vibe/api.py` `list_channels` / `discord_list_channels` /
+ `lark_*` / `telegram_list_chats` and the UI endpoint gain an opt-in
+ `include_not_returned` (default `False`) so a power-user view can still fetch
+ stale rows for review/removal.
+
+UI (`ui/src/components/steps/ChannelList.tsx`):
+
+- By default render only channels the backend returns (now excludes
+ `not_returned`). No behavior change needed if backend defaults to hiding.
+- Add a small affordance ("N unavailable — review") that, when toggled, requests
+ `include_not_returned=true` and renders those rows with a distinct
+ "Unavailable / removed on platform" badge derived from `visibility_status`
+ (+ `metadata.last_missing_at`), visually separate from Enabled/Disabled.
+
+### P0b — Manual remove (physical delete of a scope)
+
+- New API + UI action to permanently delete a discovered scope (the `scopes` row
+ plus its `scope_settings`). Reuses the existing scope-id helpers; add a focused
+ `delete_scope()` in the discovery/store layer.
+- This is the only deletion path that also works for Telegram (no live list) and
+ is the user-facing escape hatch. Confirm-before-delete in UI.
+- FK note: `scope_settings.scope_id` is `ON DELETE CASCADE` and
+ `scopes.parent_scope_id` is `ON DELETE SET NULL` (`storage/models.py`). SQLite
+ enforces cascade only when `PRAGMA foreign_keys = ON`. `delete_scope()` must
+ therefore explicitly delete the `scope_settings` row(s) first (do not rely on
+ the pragma), then the `scopes` row. Deleting a guild-type scope nulls the
+ `parent_scope_id` of its child channel scopes (SET NULL) — correct behavior.
+
+### P1 — Never false-mark on incomplete fetches (robustness)
+
+The single safety-critical change here is: **`refresh_platform()` must skip
+`_mark_not_returned()` when the fetch was incomplete**, while still upserting the
+rows it did get. Because both the foreground and background (`_schedule_refresh`)
+paths call `refresh_platform()`, changing it there covers both.
+
+`core/chat_discovery.py`:
+
+- Extend `_fetch_platform_channels()` return from
+ `tuple[list[dict], str | None]` to `tuple[list[dict], str | None, bool]` where
+ the new bool is `fetch_complete`. Update the single destructure at line ~454
+ (`rows, refreshed_parent = ...`). Values: Slack `True` (cursor loop exhausts),
+ Discord `True` (single complete call), Lark `not result.get("truncated", False)`.
+- In `refresh_platform()`, guard the `_mark_not_returned(...)` call (line ~499) on
+ `fetch_complete`; when incomplete, log and skip marking (rows still upserted).
+
+`vibe/api.py`:
+
+- Lark (highest priority): the `truncated` flag already exists in the
+ `lark_list_chats_live` return dict (line ~9148); `_fetch_platform_channels` just
+ reads `result.get("truncated", False)`. Add 429/5xx retry/backoff to the Lark
+ fetch so transient limits don't surface as partial success.
+- Discord (hygiene, lower priority): add 429/5xx retry with backoff to
+ `_discord_api_get` / `_discord_api_get_async` (honor `Retry-After`), mirroring
+ the Slack helper. Per-guild channel fetch rarely hits 429; this is defensive.
+
+(`users/@me/guilds` pagination is a UX item — see P4 below — not part of this
+correctness fix.)
+
+### P2 — Optional auto-GC (follow-up, gated on P1)
+
+- Physically delete rows that have been `not_returned` for a grace window
+ (e.g. ≥ N consecutive successful refreshes or ≥ X days via `last_missing_at`),
+ configurable and off by default. Documented as a separate PR; not implemented
+ in this change unless review requests it.
+
+### P3 — Telegram / WeChat
+
+- Telegram: no server list to diff, so deletion cannot be auto-detected. Rely on
+ P0b manual remove; optionally surface a "last seen" staleness hint. No
+ auto-marking.
+- WeChat: unchanged (no channel concept; UI already short-circuits).
+
+### P4 — Discord guild-list pagination (UX, separate follow-up)
+
+- Paginate `users/@me/guilds` with the `after` cursor in `discord_list_guilds*`
+ so the setup-wizard guild picker is complete for bots in >100–200 guilds. This
+ does **not** affect `_mark_not_returned` correctness and is out of scope for the
+ primary fix; documented here so it is not lost.
+
+## Testing
+
+- Unit (`tests/`): extend chat_discovery tests with a hermetic SQLite
+ `db_path` to assert:
+ - a row marked `not_returned` is excluded from `channels_response()` by default
+ and included when `include_not_returned=True`;
+ - `_summary()` still counts it under `discovered_count` + new
+ `not_returned_count`;
+ - a truncated/partial fetch upserts seen rows but does **not** mark missing rows
+ `not_returned` — covering **both** the foreground `refresh_platform()` call and
+ the background `_schedule_refresh()` → `refresh_platform()` path (mock a
+ truncated Lark result in each);
+ - after P0, an install whose channels are all `not_returned` does not trigger a
+ refresh on every `channels_response()` call (assert the `last_success_at`-based
+ guard, not `not chats`);
+ - `delete_scope()` removes the scope and its `scope_settings` (assert the
+ explicit child-delete works regardless of the SQLite FK pragma).
+- API: unit-test Discord 429 retry and guild-list pagination, and Lark `truncated`
+ propagation, with mocked HTTP (no live calls; keep hermetic per CLAUDE.md).
+- UI: `cd ui && npm run build`; add/extend a ChannelList test if a pattern exists
+ for the unavailable-rows view.
+- Manual: Incus regression for cross-platform sanity (Slack/Discord/Lark) per
+ CLAUDE.md, after CI-style local checks.
+
+## Rollout / risk
+
+- Behavior change: deleted channels disappear from the default list. Mitigated by
+ the opt-in "unavailable" view + manual remove, and by P1 preventing false hides.
+- No destructive DB migration; soft-mark semantics preserved. Physical deletion
+ only via explicit user action (P0b) or optional P2.
+- Scope of this PR: P0 + P0b + P1 (+ tests). P2 is a documented follow-up.
+
+## TODO
+
+- [ ] P0: `include_not_returned` param on `channels_response` (default `False`);
+ keep `all_chats` unfiltered, filter only `chats` via `_filter_response_chats`;
+ add `not_returned_count` to `_summary`; fix refresh-trigger guard to use
+ `state.last_success_at is None` instead of `not chats`; thread the opt-in
+ through `vibe/api.py` + UI endpoint.
+- [ ] P0b: `delete_scope()` store helper (explicit `scope_settings` delete then
+ `scopes`) + API endpoint + UI remove action with confirm.
+- [ ] P1: `_fetch_platform_channels` returns `fetch_complete` (3-tuple), update
+ destructure at line ~454; `refresh_platform` skips `_mark_not_returned` when
+ incomplete (covers foreground + background paths); Lark `truncated`
+ propagation + Lark 429 retry; Discord 429 retry (hygiene).
+- [ ] UI: unavailable-rows view + badge from `visibility_status`/`last_missing_at`.
+- [ ] i18n: add new UI strings to `ui/src/i18n/en.json` and `ui/src/i18n/zh.json`.
+- [ ] Tests: chat_discovery unit (filter default, summary counts, refresh-guard,
+ truncation skip in fore+background, delete_scope), API retry/truncation unit,
+ `cd ui && npm run build`.
+- [ ] Update user docs for the unavailable/remove behavior.
+- [ ] P4 (separate follow-up): `users/@me/guilds` cursor pagination for the guild
+ picker.
diff --git a/tests/test_chat_discovery.py b/tests/test_chat_discovery.py
index b525cb64a..3c1acbd44 100644
--- a/tests/test_chat_discovery.py
+++ b/tests/test_chat_discovery.py
@@ -349,6 +349,47 @@ def test_slack_member_only_response_excludes_not_returned_member_channels(tmp_pa
assert [channel["id"] for channel in response["channels"]] == ["C_PRESENT"]
+def test_slack_member_only_opt_in_exposes_not_returned_member_channels(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_GONE_OPTIN",
+ name="gone",
+ metadata={
+ chat_discovery.METADATA_IS_MEMBER: True,
+ chat_discovery.METADATA_VISIBILITY_STATUS: chat_discovery.VISIBILITY_NOT_RETURNED,
+ chat_discovery.METADATA_AUTH_CONTEXT: auth_context,
+ },
+ db_path=db_path,
+ )
+ chat_discovery.remember_chat(
+ "slack",
+ "C_PRESENT_OPTIN",
+ name="present",
+ metadata={
+ chat_discovery.METADATA_IS_MEMBER: True,
+ chat_discovery.METADATA_AUTH_CONTEXT: auth_context,
+ },
+ db_path=db_path,
+ )
+ chat_discovery.set_state_meta(
+ 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,
+ )
+
+ # Member-only view (Slack default) must still surface the stale member row
+ # when the caller opts in, so it can be reviewed/removed without browse-all.
+ response = chat_discovery.channels_response(
+ "slack", require_member=True, include_not_returned=True, bot_token="x", db_path=db_path
+ )
+
+ assert {c["id"] for c in response["channels"]} == {"C_GONE_OPTIN", "C_PRESENT_OPTIN"}
+ assert response["summary"]["not_returned_count"] == 1
+
+
def test_slack_browse_all_refreshes_after_member_only_cache_hit(tmp_path: Path, monkeypatch) -> None:
db_path = tmp_path / "vibe.sqlite"
run_migrations(db_path)
@@ -515,6 +556,354 @@ def test_discord_cached_payload_preserves_numeric_channel_type(tmp_path: Path, m
assert cached["channels"][0]["native_type"] == "0"
+def _seed_not_returned_discord(db_path: Path) -> None:
+ auth_context = _auth_context("discord", bot_token="x")
+ parent = chat_discovery.make_scope_id("discord", chat_discovery.GUILD_SCOPE_TYPE, "G1")
+ # Parent guild scope must exist before channels can reference it (FK).
+ chat_discovery._remember_guild("discord", "G1", db_path=db_path)
+ chat_discovery.remember_chat(
+ "discord",
+ "C_PRESENT",
+ name="present",
+ metadata={chat_discovery.METADATA_AUTH_CONTEXT: auth_context},
+ parent_id=parent,
+ db_path=db_path,
+ )
+ chat_discovery.remember_chat(
+ "discord",
+ "C_GONE",
+ name="gone",
+ metadata={
+ chat_discovery.METADATA_AUTH_CONTEXT: auth_context,
+ chat_discovery.METADATA_VISIBILITY_STATUS: chat_discovery.VISIBILITY_NOT_RETURNED,
+ chat_discovery.METADATA_LAST_MISSING_AT: "2026-01-01T00:00:00+00:00",
+ },
+ parent_id=parent,
+ db_path=db_path,
+ )
+
+
+def test_channels_response_hides_not_returned_by_default_and_opts_in(tmp_path: Path) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path)
+ _seed_not_returned_discord(db_path)
+ # Mark already fetched so no live refresh is attempted.
+ chat_discovery.set_state_meta(
+ f"channel_refresh.discord.guild.G1.{_auth_context('discord', bot_token='x')}",
+ {"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,
+ )
+
+ parent = chat_discovery.make_scope_id("discord", chat_discovery.GUILD_SCOPE_TYPE, "G1")
+ hidden = chat_discovery.channels_response(
+ "discord", bot_token="x", guild_id="G1", parent_scope_id=parent, db_path=db_path
+ )
+ shown = chat_discovery.channels_response(
+ "discord",
+ bot_token="x",
+ guild_id="G1",
+ parent_scope_id=parent,
+ include_not_returned=True,
+ db_path=db_path,
+ )
+
+ assert [c["id"] for c in hidden["channels"]] == ["C_PRESENT"]
+ assert {c["id"] for c in shown["channels"]} == {"C_PRESENT", "C_GONE"}
+ # Summary always counts the full inventory regardless of the view.
+ assert hidden["summary"]["discovered_count"] == 2
+ assert hidden["summary"]["not_returned_count"] == 1
+ assert shown["summary"]["not_returned_count"] == 1
+
+
+def test_all_not_returned_does_not_trigger_refresh_each_call(tmp_path: Path, monkeypatch) -> 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_STALE_GUARD",
+ name="gone",
+ metadata={
+ chat_discovery.METADATA_AUTH_CONTEXT: auth_context,
+ chat_discovery.METADATA_IS_MEMBER: True,
+ chat_discovery.METADATA_VISIBILITY_STATUS: chat_discovery.VISIBILITY_NOT_RETURNED,
+ },
+ db_path=db_path,
+ )
+ # last_success recent (TTL not elapsed) but last_attempt old (backoff would
+ # allow). Old `not chats` guard would refresh; the success-based guard must not.
+ chat_discovery.set_state_meta(
+ f"channel_refresh.slack.{auth_context}",
+ {"last_attempt_at": "2000-01-01T00:00:00+00:00", "last_success_at": "2999-01-01T00:00:00+00:00", "last_error": None},
+ db_path=db_path,
+ )
+
+ from vibe import api
+
+ calls = 0
+
+ def fake_live(_token: str, browse_all: bool = False) -> dict:
+ nonlocal calls
+ calls += 1
+ return {"ok": True, "channels": [], "is_member_only": not browse_all}
+
+ monkeypatch.setattr(api, "list_channels_live", fake_live)
+
+ first = chat_discovery.channels_response("slack", bot_token="x", db_path=db_path)
+ second = chat_discovery.channels_response("slack", bot_token="x", db_path=db_path)
+
+ assert calls == 0
+ assert first["channels"] == []
+ assert second["channels"] == []
+ assert first["summary"]["not_returned_count"] == 1
+
+
+def test_refresh_skips_not_returned_marking_when_lark_truncated(tmp_path: Path, monkeypatch) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path)
+ auth_context = _auth_context("lark", app_id="a", app_secret="s", domain="feishu")
+ chat_discovery.remember_chat(
+ "lark",
+ "oc_keep",
+ name="keep",
+ metadata={chat_discovery.METADATA_AUTH_CONTEXT: auth_context},
+ db_path=db_path,
+ )
+
+ from vibe import api
+
+ # Live result is truncated and does NOT include oc_keep — it must NOT be
+ # marked not_returned because the inventory is incomplete.
+ monkeypatch.setattr(
+ api,
+ "lark_list_chats_live",
+ lambda _app_id, _app_secret, _domain="feishu": {
+ "ok": True,
+ "channels": [{"id": "oc_new", "name": "new", "chat_type": "group"}],
+ "truncated": True,
+ },
+ )
+
+ result = chat_discovery.refresh_platform(
+ "lark", force=True, app_id="a", app_secret="s", domain="feishu", db_path=db_path
+ )
+ chats = {c.chat_id: c for c in chat_discovery.list_chats("lark", db_path=db_path)}
+
+ assert result.ok is True
+ assert chats["oc_keep"].visibility_status != chat_discovery.VISIBILITY_NOT_RETURNED
+ assert chats["oc_new"].visibility_status == chat_discovery.VISIBILITY_VISIBLE
+
+
+def test_background_refresh_skips_marking_when_lark_truncated(tmp_path: Path, monkeypatch) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path)
+ auth_context = _auth_context("lark", app_id="a", app_secret="s", domain="feishu")
+ chat_discovery.remember_chat(
+ "lark",
+ "oc_keepbg",
+ name="keep",
+ metadata={chat_discovery.METADATA_AUTH_CONTEXT: auth_context},
+ db_path=db_path,
+ )
+ # Stale cache so channels_response schedules a background refresh.
+ chat_discovery.set_state_meta(
+ f"channel_refresh.lark.{auth_context}",
+ {"last_attempt_at": "2000-01-01T00:00:00+00:00", "last_success_at": "2000-01-01T00:00:00+00:00", "last_error": None},
+ db_path=db_path,
+ )
+
+ from vibe import api
+
+ monkeypatch.setattr(
+ api,
+ "lark_list_chats_live",
+ lambda _app_id, _app_secret, _domain="feishu": {
+ "ok": True,
+ "channels": [{"id": "oc_newbg", "name": "new", "chat_type": "group"}],
+ "truncated": True,
+ },
+ )
+
+ class InlineThread:
+ def __init__(self, *args, target=None, **kwargs):
+ self._target = target
+
+ def start(self):
+ if self._target:
+ self._target()
+
+ monkeypatch.setattr(chat_discovery.threading, "Thread", InlineThread)
+
+ try:
+ chat_discovery.channels_response(
+ "lark", app_id="a", app_secret="s", domain="feishu", db_path=db_path
+ )
+ finally:
+ with chat_discovery._scheduled_refreshes_lock:
+ chat_discovery._scheduled_refreshes.clear()
+
+ chats = {c.chat_id: c for c in chat_discovery.list_chats("lark", db_path=db_path)}
+ assert chats["oc_keepbg"].visibility_status != chat_discovery.VISIBILITY_NOT_RETURNED
+
+
+def test_delete_scope_removes_scope_and_settings(tmp_path: Path) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path)
+ chat_discovery.remember_chat("telegram", "999", name="Gone", db_path=db_path)
+ service = SQLiteSettingsService(db_path)
+ try:
+ service.save_state(SettingsState(channels={"telegram::999": ChannelSettings(enabled=True)}))
+ finally:
+ service.close()
+
+ assert any(c.chat_id == "999" for c in chat_discovery.list_chats("telegram", db_path=db_path))
+
+ # No history → physical delete.
+ outcome = chat_discovery.delete_scope("telegram", "999", db_path=db_path)
+ assert outcome == {"removed": True, "dismissed": False}
+ assert chat_discovery.list_chats("telegram", db_path=db_path) == []
+ # Settings row is gone too (no orphan).
+ reloaded = SQLiteSettingsService(db_path)
+ try:
+ assert "telegram::999" not in reloaded.load_state().channels
+ finally:
+ reloaded.close()
+ # Deleting a missing scope is a no-op.
+ assert chat_discovery.delete_scope("telegram", "999", db_path=db_path) == {
+ "removed": False,
+ "dismissed": False,
+ }
+
+
+def test_delete_scope_with_history_dismisses_instead_of_deleting(tmp_path: Path) -> None:
+ from datetime import datetime, timezone
+
+ from storage.models import messages
+
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path)
+ chat_discovery.remember_chat("telegram", "777", name="HasHistory", db_path=db_path)
+ scope_id = chat_discovery.make_scope_id("telegram", chat_discovery.CHANNEL_SCOPE_TYPE, "777")
+
+ # Insert a message owned by the scope (CASCADE FK). A physical delete would
+ # destroy it, so removal must dismiss instead.
+ now = datetime.now(timezone.utc).isoformat()
+ engine = chat_discovery._engine(db_path)
+ try:
+ with engine.begin() as conn:
+ conn.execute(
+ messages.insert().values(
+ id="m1",
+ scope_id=scope_id,
+ platform="telegram",
+ author="user",
+ type="user",
+ content_json="{}",
+ metadata_json="{}",
+ created_at=now,
+ updated_at=now,
+ )
+ )
+ finally:
+ engine.dispose()
+
+ outcome = chat_discovery.delete_scope("telegram", "777", db_path=db_path)
+ assert outcome == {"removed": False, "dismissed": True}
+
+ # Hidden from every listing, including the unavailable view.
+ assert chat_discovery.list_chats("telegram", db_path=db_path) == []
+ assert chat_discovery.list_chats("telegram", include_not_returned=True, db_path=db_path) == []
+
+ # History preserved (the scope row was kept, not cascade-deleted).
+ engine = chat_discovery._engine(db_path)
+ try:
+ with engine.connect() as conn:
+ kept = conn.execute(messages.select().where(messages.c.scope_id == scope_id)).first()
+ finally:
+ engine.dispose()
+ assert kept is not None
+
+
+def test_remember_chat_clears_dismissed_on_passive_rediscovery(tmp_path: Path) -> None:
+ from datetime import datetime, timezone
+
+ from storage.models import messages
+
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path)
+ chat_discovery.remember_chat("telegram", "tg_redisc", name="Gone", db_path=db_path)
+ scope_id = chat_discovery.make_scope_id("telegram", chat_discovery.CHANNEL_SCOPE_TYPE, "tg_redisc")
+
+ now = datetime.now(timezone.utc).isoformat()
+ engine = chat_discovery._engine(db_path)
+ try:
+ with engine.begin() as conn:
+ conn.execute(
+ messages.insert().values(
+ id="m_redisc",
+ scope_id=scope_id,
+ platform="telegram",
+ author="user",
+ type="user",
+ content_json="{}",
+ metadata_json="{}",
+ created_at=now,
+ updated_at=now,
+ )
+ )
+ finally:
+ engine.dispose()
+
+ # History present → removal dismisses (keeps row hidden).
+ assert chat_discovery.delete_scope("telegram", "tg_redisc", db_path=db_path) == {
+ "removed": False,
+ "dismissed": True,
+ }
+ assert chat_discovery.list_chats("telegram", db_path=db_path) == []
+
+ # Telegram has no live list; a new message flows through remember_chat, which
+ # must clear the dismissal so the group reappears in Group Settings.
+ chat_discovery.remember_chat("telegram", "tg_redisc", name="Active Again", db_path=db_path)
+ assert [c.chat_id for c in chat_discovery.list_chats("telegram", db_path=db_path)] == ["tg_redisc"]
+
+
+def test_refresh_clears_dismissed_flag_on_rediscovery(tmp_path: Path, monkeypatch) -> 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_BACK",
+ name="back",
+ metadata={
+ chat_discovery.METADATA_AUTH_CONTEXT: auth_context,
+ chat_discovery.METADATA_IS_MEMBER: True,
+ chat_discovery.METADATA_DISMISSED_AT: "2026-01-01T00:00:00+00:00",
+ },
+ db_path=db_path,
+ )
+ # Dismissed → hidden everywhere initially.
+ assert chat_discovery.list_chats("slack", include_not_returned=True, db_path=db_path) == []
+
+ from vibe import api
+
+ monkeypatch.setattr(
+ api,
+ "list_channels_live",
+ lambda _token, browse_all=False: {
+ "ok": True,
+ "channels": [{"id": "C_BACK", "name": "back", "is_private": False, "is_member": True}],
+ "is_member_only": not browse_all,
+ },
+ )
+
+ chat_discovery.refresh_platform("slack", force=True, bot_token="x", db_path=db_path)
+
+ chats = chat_discovery.list_chats("slack", db_path=db_path)
+ assert [c.chat_id for c in chats] == ["C_BACK"]
+ assert chats[0].visibility_status == chat_discovery.VISIBILITY_VISIBLE
+
+
def test_malformed_legacy_discovered_chats_does_not_break_channel_response(tmp_path: Path, monkeypatch) -> None:
db_path = tmp_path / "vibe.sqlite"
run_migrations(db_path)
diff --git a/tests/test_delete_channel_scope.py b/tests/test_delete_channel_scope.py
new file mode 100644
index 000000000..3943c08d6
--- /dev/null
+++ b/tests/test_delete_channel_scope.py
@@ -0,0 +1,38 @@
+from __future__ import annotations
+
+from core import chat_discovery
+from vibe import api
+
+
+def test_delete_channel_scope_rejects_non_channel_scope(monkeypatch) -> None:
+ calls: list[tuple] = []
+
+ def fake_delete_scope(platform, native_id, *, scope_type="channel", db_path=None):
+ calls.append((platform, native_id, scope_type))
+ return {"removed": True, "dismissed": False}
+
+ monkeypatch.setattr(chat_discovery, "delete_scope", fake_delete_scope)
+
+ # Non-channel scope types must be rejected without touching the store.
+ result = api.delete_channel_scope("avibe", "p1", scope_type="project")
+ assert result["ok"] is False
+ assert calls == []
+
+
+def test_delete_channel_scope_allows_channel(monkeypatch) -> None:
+ calls: list[tuple] = []
+
+ def fake_delete_scope(platform, native_id, *, scope_type="channel", db_path=None):
+ calls.append((platform, native_id, scope_type))
+ return {"removed": True, "dismissed": False}
+
+ monkeypatch.setattr(chat_discovery, "delete_scope", fake_delete_scope)
+
+ result = api.delete_channel_scope("discord", "C1")
+ assert result == {"ok": True, "removed": True, "dismissed": False}
+ assert calls == [("discord", "C1", "channel")]
+
+
+def test_delete_channel_scope_requires_platform_and_id() -> None:
+ assert api.delete_channel_scope("", "C1")["ok"] is False
+ assert api.delete_channel_scope("discord", "")["ok"] is False
diff --git a/tests/test_discord_api_retry.py b/tests/test_discord_api_retry.py
new file mode 100644
index 000000000..105cfbd64
--- /dev/null
+++ b/tests/test_discord_api_retry.py
@@ -0,0 +1,100 @@
+from __future__ import annotations
+
+import urllib.error
+import urllib.request
+
+from vibe import api
+
+
+class _FakeResp:
+ def __init__(self, payload: str) -> None:
+ self._payload = payload
+
+ def __enter__(self) -> "_FakeResp":
+ return self
+
+ def __exit__(self, *exc) -> None:
+ return None
+
+ def read(self) -> bytes:
+ return self._payload.encode("utf-8")
+
+
+def test_discord_api_get_retries_on_429_then_succeeds(monkeypatch) -> None:
+ calls = {"n": 0}
+ sleeps: list[float] = []
+
+ class _FakeOpener:
+ def open(self, _req, timeout=10):
+ calls["n"] += 1
+ if calls["n"] == 1:
+ raise urllib.error.HTTPError(
+ "https://discord.com", 429, "Too Many Requests", {"Retry-After": "0"}, None
+ )
+ return _FakeResp('{"ok": true}')
+
+ monkeypatch.setattr(urllib.request, "build_opener", lambda *a, **k: _FakeOpener())
+ monkeypatch.setattr("time.sleep", lambda s: sleeps.append(s))
+
+ result = api._discord_api_get("bot-token", "guilds/1/channels")
+
+ assert result == {"ok": True}
+ assert calls["n"] == 2 # one 429, one success
+ assert sleeps # backoff slept at least once
+
+
+def test_lark_list_chats_live_marks_truncated_on_repeated_page_token(monkeypatch) -> None:
+ import json as _json
+
+ pages = [
+ {"code": 0, "data": {"items": [{"chat_id": "oc_1", "name": "one"}], "has_more": True, "page_token": "P1"}},
+ # Server repeats the same cursor while still claiming more pages.
+ {"code": 0, "data": {"items": [{"chat_id": "oc_2", "name": "two"}], "has_more": True, "page_token": "P1"}},
+ ]
+ idx = {"n": 0}
+
+ def fake_urlopen(_req, timeout=10):
+ payload = pages[min(idx["n"], len(pages) - 1)]
+ idx["n"] += 1
+ return _FakeResp(_json.dumps(payload))
+
+ monkeypatch.setattr(api, "_lark_tenant_token", lambda *a, **k: "tok")
+ monkeypatch.setattr(urllib.request, "urlopen", fake_urlopen)
+
+ result = api.lark_list_chats_live("app", "secret", "feishu")
+
+ assert result["ok"] is True
+ assert result["truncated"] is True
+ assert {c["id"] for c in result["channels"]} == {"oc_1", "oc_2"}
+
+
+def test_lark_list_chats_live_not_truncated_when_complete(monkeypatch) -> None:
+ import json as _json
+
+ page = {"code": 0, "data": {"items": [{"chat_id": "oc_1", "name": "one"}], "has_more": False, "page_token": ""}}
+
+ monkeypatch.setattr(api, "_lark_tenant_token", lambda *a, **k: "tok")
+ monkeypatch.setattr(urllib.request, "urlopen", lambda _req, timeout=10: _FakeResp(_json.dumps(page)))
+
+ result = api.lark_list_chats_live("app", "secret", "feishu")
+
+ assert result["ok"] is True
+ assert result["truncated"] is False
+ assert [c["id"] for c in result["channels"]] == ["oc_1"]
+
+
+def test_discord_api_get_raises_on_non_retryable(monkeypatch) -> None:
+ class _FakeOpener:
+ def open(self, _req, timeout=10):
+ raise urllib.error.HTTPError(
+ "https://discord.com", 401, "Unauthorized", {}, None
+ )
+
+ monkeypatch.setattr(urllib.request, "build_opener", lambda *a, **k: _FakeOpener())
+
+ try:
+ api._discord_api_get("bot-token", "guilds/1/channels")
+ except urllib.error.HTTPError as exc:
+ assert exc.code == 401
+ else: # pragma: no cover
+ raise AssertionError("expected HTTPError for 401")
diff --git a/ui/src/components/steps/ChannelList.tsx b/ui/src/components/steps/ChannelList.tsx
index 6c342c4f1..ba0d0b2ae 100644
--- a/ui/src/components/steps/ChannelList.tsx
+++ b/ui/src/components/steps/ChannelList.tsx
@@ -12,6 +12,7 @@ import {
MessageSquare,
RefreshCw,
Square,
+ Trash2,
Users,
} from 'lucide-react';
import { useTranslation } from 'react-i18next';
@@ -152,6 +153,10 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
const [searchQuery, setSearchQuery] = useState('');
const [expandedChannelId, setExpandedChannelId] = useState<string | null>(null);
const [showInactive, setShowInactive] = useState(true);
+ // When true, also fetch channels the platform no longer returns (deleted /
+ // inaccessible) so the user can review and remove them.
+ const [showUnavailable, setShowUnavailable] = useState(false);
+ const [removingChannelId, setRemovingChannelId] = useState<string | null>(null);
// All-channels aggregation: keyed by platform
const [allChannelsByPlatform, setAllChannelsByPlatform] = useState<Record<string, any[]>>({});
const [allConfigsByPlatform, setAllConfigsByPlatform] = useState<Record<string, Record<string, ChannelConfig>>>({});
@@ -486,7 +491,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
const loadingKey = beginChannelLoading(isAll);
try {
if (platform === 'lark') {
- const result = await api.larkChats(larkAppId, larkAppSecret, larkDomain, force);
+ const result = await api.larkChats(larkAppId, larkAppSecret, larkDomain, force, showUnavailable);
if (channelRequestVersionRef.current !== requestVersion) return;
recordRefreshMeta(platform, result);
if (result.ok) {
@@ -494,7 +499,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
if (result.refreshing) scheduleRefreshFollowup(platform, isAll);
}
} else if (platform === 'telegram') {
- const result = await api.telegramChats(false);
+ const result = await api.telegramChats(false, showUnavailable);
if (channelRequestVersionRef.current !== requestVersion) return;
recordRefreshMeta(platform, result);
if (result.ok) {
@@ -505,7 +510,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
if (!selectedGuild) {
return;
}
- const result = await api.discordChannels(botToken, selectedGuild, force);
+ const result = await api.discordChannels(botToken, selectedGuild, force, showUnavailable);
if (channelRequestVersionRef.current !== requestVersion) return;
recordRefreshMeta(platform, result);
if (result.ok) {
@@ -514,7 +519,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
if (result.refreshing) scheduleRefreshFollowup(platform, isAll);
}
} else {
- const result = await api.slackChannels(botToken, isAll, force);
+ const result = await api.slackChannels(botToken, isAll, force, showUnavailable);
if (channelRequestVersionRef.current !== requestVersion) return;
recordRefreshMeta(platform, result);
if (result.ok) {
@@ -615,6 +620,63 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
config.lark?.has_app_secret,
]);
+ // Reload the inventory shown by the current view. In the All tab the renderer
+ // uses the per-platform `channels` state for the currently selected platform
+ // and `allChannelsByPlatform` for the rest, so refresh both.
+ const reloadCurrentView = async () => {
+ if (isPage && pageTab === 'all') {
+ await Promise.all([loadAllPlatformsData(false), loadChannels(undefined, false)]);
+ } else {
+ await loadChannels(undefined, false);
+ }
+ };
+
+ // Reload when the user toggles "show unavailable" so the request carries the
+ // updated include_not_returned flag.
+ const showUnavailableInitRef = useRef(true);
+ useEffect(() => {
+ if (showUnavailableInitRef.current) {
+ showUnavailableInitRef.current = false;
+ return;
+ }
+ void reloadCurrentView();
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [showUnavailable]);
+
+ const handleRemoveChannel = async (rowPlatform: string, channelId: string, channelName?: string) => {
+ const confirmed = typeof window === 'undefined'
+ || window.confirm(t('channelList.removeChannelConfirm', { name: channelName || channelId }));
+ if (!confirmed) return;
+ setRemovingChannelId(channelId);
+ try {
+ const result = await api.deleteChannel(rowPlatform, channelId);
+ if (result?.ok) {
+ // Drop the removed channel's local settings so a later edit of another
+ // channel doesn't re-persist (and thus recreate) the deleted scope.
+ if (rowPlatform === platform) {
+ setConfigs((prev) => {
+ if (!(channelId in prev)) return prev;
+ const next = { ...prev };
+ delete next[channelId];
+ return next;
+ });
+ }
+ setAllConfigsByPlatform((prev) => {
+ const platformConfigs = prev[rowPlatform];
+ if (!platformConfigs || !(channelId in platformConfigs)) return prev;
+ const nextPlatform = { ...platformConfigs };
+ delete nextPlatform[channelId];
+ return { ...prev, [rowPlatform]: nextPlatform };
+ });
+ await reloadCurrentView();
+ }
+ } catch (e) {
+ console.error('Failed to remove channel:', e);
+ } finally {
+ setRemovingChannelId(null);
+ }
+ };
+
useEffect(() => {
if (config.agents?.claude?.enabled) {
loadClaudeModels();
@@ -798,14 +860,14 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
const appSecret = config.lark?.app_secret || '';
const domain = config.lark?.domain || 'feishu';
if (appId && hasChannelCredentials('lark')) {
- const result = await api.larkChats(appId, appSecret, domain, force);
+ const result = await api.larkChats(appId, appSecret, domain, force, showUnavailable);
recordRefreshMeta(p, result);
refreshing = Boolean(result.refreshing);
if (result.ok) channelsList = result.channels || [];
}
} else if (p === 'telegram') {
if (hasChannelCredentials('telegram')) {
- const result = await api.telegramChats(false);
+ const result = await api.telegramChats(false, showUnavailable);
if (result.ok) channelsList = result.channels || [];
}
} else if (p === 'discord') {
@@ -813,7 +875,7 @@ 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 && hasChannelCredentials('discord')) {
- const result = await api.discordChannels(token, guildId, force);
+ const result = await api.discordChannels(token, guildId, force, showUnavailable);
recordRefreshMeta(p, result);
refreshing = Boolean(result.refreshing);
if (result.ok) {
@@ -822,7 +884,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
}
} else if (p === 'slack') {
if (hasChannelCredentials('slack')) {
- const result = await api.slackChannels(config.slack?.bot_token || '', false, force);
+ const result = await api.slackChannels(config.slack?.bot_token || '', false, force, showUnavailable);
recordRefreshMeta(p, result);
refreshing = Boolean(result.refreshing);
if (result.ok) channelsList = result.channels || [];
@@ -1049,7 +1111,10 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
const visibleRows = rawRows
.filter((r) => {
const enabled = r.config.enabled === true;
- if (!showInactive && !enabled) return false;
+ const isUnavailable = r.channel.visibility_status === 'not_returned';
+ // "Show inactive" hides unconfigured rows, but never the unavailable
+ // rows the user explicitly opted to review via "Show unavailable".
+ if (!showInactive && !enabled && !isUnavailable) return false;
if (!lowerQuery) return true;
const name = String(r.channel.name || r.channel.id || '').toLowerCase();
const id = String(r.channel.id || '').toLowerCase();
@@ -1278,13 +1343,22 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
discovered: summary.total,
})}
</div>
- <label className="inline-flex cursor-pointer items-center gap-2">
- <span className="text-[12px] text-muted">{t('channelList.showInactive')}</span>
- <ToggleSwitch
- enabled={showInactive}
- onClick={() => setShowInactive(!showInactive)}
- />
- </label>
+ <div className="flex items-center gap-4">
+ <label className="inline-flex cursor-pointer items-center gap-2">
+ <span className="text-[12px] text-muted">{t('channelList.showUnavailable')}</span>
+ <ToggleSwitch
+ enabled={showUnavailable}
+ onClick={() => setShowUnavailable(!showUnavailable)}
+ />
+ </label>
+ <label className="inline-flex cursor-pointer items-center gap-2">
+ <span className="text-[12px] text-muted">{t('channelList.showInactive')}</span>
+ <ToggleSwitch
+ enabled={showInactive}
+ onClick={() => setShowInactive(!showInactive)}
+ />
+ </label>
+ </div>
</div>
{/* Channel rows — design.pen JrNBe / M8FRiG / KywfU */}
@@ -1305,6 +1379,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
const def = defaultConfig();
const defaultAgent = agentByName[defaultAgentName || ''] || null;
const channelEnabled = rawConfig.enabled === true;
+ const isUnavailable = channel.visibility_status === 'not_returned';
const channelConfig = {
...def,
...rawConfig,
@@ -1392,22 +1467,49 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
</span>
{/* Status badge */}
- <span
- className={clsx(
- 'inline-flex items-center gap-1.5 rounded-full border px-2 py-0.5 text-[11px] font-medium',
- channelEnabled
- ? 'border-mint/40 bg-mint-soft text-mint'
- : 'border-border bg-foreground/[0.04] text-muted'
- )}
- >
+ {isUnavailable ? (
+ <span
+ className="inline-flex items-center gap-1.5 rounded-full border border-amber-500/40 bg-amber-500/10 px-2 py-0.5 text-[11px] font-medium text-amber-500"
+ title={channel.metadata?.last_missing_at ? t('channelList.unavailableSince', { at: channel.metadata.last_missing_at }) : undefined}
+ >
+ <span className="size-1.5 rounded-full bg-amber-500" />
+ {t('channelList.unavailableBadge')}
+ </span>
+ ) : (
<span
className={clsx(
- 'size-1.5 rounded-full',
- channelEnabled ? 'bg-mint shadow-[0_0_6px_rgba(91,255,160,0.7)]' : 'bg-muted'
+ 'inline-flex items-center gap-1.5 rounded-full border px-2 py-0.5 text-[11px] font-medium',
+ channelEnabled
+ ? 'border-mint/40 bg-mint-soft text-mint'
+ : 'border-border bg-foreground/[0.04] text-muted'
)}
- />
- {channelEnabled ? t('common.enabled') : t('common.disabled')}
- </span>
+ >
+ <span
+ className={clsx(
+ 'size-1.5 rounded-full',
+ channelEnabled ? 'bg-mint shadow-[0_0_6px_rgba(91,255,160,0.7)]' : 'bg-muted'
+ )}
+ />
+ {channelEnabled ? t('common.enabled') : t('common.disabled')}
+ </span>
+ )}
+
+ {/* Remove (only for channels no longer on the platform) */}
+ {isUnavailable && (
+ <button
+ type="button"
+ onClick={(e) => {
+ e.stopPropagation();
+ void handleRemoveChannel(channelPlatform, channel.id, channel.name);
+ }}
+ disabled={removingChannelId === channel.id}
+ className="inline-flex items-center gap-1 rounded-full border border-border px-2 py-0.5 text-[11px] font-medium text-muted hover:border-red-500/50 hover:text-red-500 disabled:opacity-50"
+ title={t('channelList.removeChannel')}
+ >
+ <Trash2 size={12} />
+ {t('channelList.removeChannel')}
+ </button>
+ )}
{/* Chevron */}
{expanded ? (
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 78628813c..a7ca49c20 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -222,15 +222,16 @@ export type ApiContextType = {
modelId: string,
) => Promise<OpencodeMutationResult>;
slackAuthTest: (botToken?: string, proxyUrl?: string) => Promise<any>;
- slackChannels: (botToken?: string, browseAll?: boolean, force?: boolean) => Promise<any>;
+ slackChannels: (botToken?: string, browseAll?: boolean, force?: boolean, includeNotReturned?: 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 | undefined, guildId: string, force?: boolean) => Promise<any>;
+ discordChannels: (botToken: string | undefined, guildId: string, force?: boolean, includeNotReturned?: boolean) => Promise<any>;
telegramAuthTest: (botToken?: string, proxyUrl?: string) => Promise<any>;
- telegramChats: (includePrivate?: boolean) => Promise<any>;
+ telegramChats: (includePrivate?: boolean, includeNotReturned?: boolean) => Promise<any>;
larkAuthTest: (appId: string, appSecret?: string, domain?: string, proxyUrl?: string) => Promise<any>;
- larkChats: (appId: string, appSecret?: string, domain?: string, force?: boolean) => Promise<any>;
+ larkChats: (appId: string, appSecret?: string, domain?: string, force?: boolean, includeNotReturned?: boolean) => Promise<any>;
+ deleteChannel: (platform: string, id: string, scopeType?: string) => Promise<any>;
larkTempWsStart: (appId: string, appSecret?: string, domain?: string) => Promise<any>;
larkTempWsStop: () => Promise<any>;
wechatStartLogin: () => Promise<any>;
@@ -1834,15 +1835,16 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
`/api/backend/opencode/provider/${encodeURIComponent(providerId)}/models/${encodeURIComponent(modelId)}`,
),
slackAuthTest: (botToken, proxyUrl) => postJson('/api/slack/auth_test', { bot_token: botToken, proxy_url: proxyUrl || undefined }),
- slackChannels: (botToken, browseAll, force) => postJson('/api/slack/channels', { bot_token: botToken, browse_all: browseAll || false, force: force || false }),
+ slackChannels: (botToken, browseAll, force, includeNotReturned) => postJson('/api/slack/channels', { bot_token: botToken, browse_all: browseAll || false, force: force || false, include_not_returned: includeNotReturned || false }),
slackManifest: () => getJson('/api/slack/manifest'),
discordAuthTest: (botToken, proxyUrl) => postJson('/api/discord/auth_test', { bot_token: botToken, proxy_url: proxyUrl || undefined }),
discordGuilds: (botToken) => postJson('/api/discord/guilds', { bot_token: botToken }),
- discordChannels: (botToken, guildId, force) => postJson('/api/discord/channels', { bot_token: botToken, guild_id: guildId, force: force || false }),
+ discordChannels: (botToken, guildId, force, includeNotReturned) => postJson('/api/discord/channels', { bot_token: botToken, guild_id: guildId, force: force || false, include_not_returned: includeNotReturned || false }),
telegramAuthTest: (botToken, proxyUrl) => postJson('/api/telegram/auth_test', { bot_token: botToken, proxy_url: proxyUrl || undefined }),
- telegramChats: (includePrivate) => postJson('/api/telegram/chats', { include_private: includePrivate || false }),
+ telegramChats: (includePrivate, includeNotReturned) => postJson('/api/telegram/chats', { include_private: includePrivate || false, include_not_returned: includeNotReturned || false }),
larkAuthTest: (appId, appSecret, domain, proxyUrl) => postJson('/api/lark/auth_test', { app_id: appId, app_secret: appSecret, domain: domain || 'feishu', proxy_url: proxyUrl || undefined }),
- larkChats: (appId, appSecret, domain, force) => postJson('/api/lark/chats', { app_id: appId, app_secret: appSecret, domain: domain || 'feishu', force: force || false }),
+ larkChats: (appId, appSecret, domain, force, includeNotReturned) => postJson('/api/lark/chats', { app_id: appId, app_secret: appSecret, domain: domain || 'feishu', force: force || false, include_not_returned: includeNotReturned || false }),
+ deleteChannel: (platform, id, scopeType) => postJson('/api/channels/delete', { platform, id, scope_type: scopeType || 'channel' }),
larkTempWsStart: (appId, appSecret, domain) => postJson('/api/lark/temp_ws/start', { app_id: appId, app_secret: appSecret, domain: domain || 'feishu' }),
larkTempWsStop: () => postJson('/api/lark/temp_ws/stop', {}),
wechatStartLogin: () => postJson('/api/wechat/qr_login/start', {}),
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index ade9ff1e3..9a2c97e94 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -1435,6 +1435,11 @@
"filterPlaceholder": "Filter groups…",
"rescan": "Rescan",
"showInactive": "Show inactive",
+ "showUnavailable": "Show unavailable",
+ "unavailableBadge": "Unavailable",
+ "unavailableSince": "No longer returned by the platform since {{at}}",
+ "removeChannel": "Remove",
+ "removeChannelConfirm": "Permanently remove \"{{name}}\" and its settings? This cannot be undone.",
"headerSummary": "All groups · {{active}} active · {{discovered}} discovered",
"headerSummaryPlatform": "{{platform}} · {{active}} active · {{discovered}} discovered",
"noChannelsForSearch": "No groups match your search.",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 787c18828..fc09f8d3a 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -1435,6 +1435,11 @@
"filterPlaceholder": "搜索群组…",
"rescan": "重新扫描",
"showInactive": "显示未启用",
+ "showUnavailable": "显示已失效",
+ "unavailableBadge": "已失效",
+ "unavailableSince": "自 {{at}} 起平台不再返回此群组",
+ "removeChannel": "移除",
+ "removeChannelConfirm": "永久移除“{{name}}”及其设置?此操作无法撤销。",
"headerSummary": "全部群组 · {{active}} 已启用 · {{discovered}} 已发现",
"headerSummaryPlatform": "{{platform}} · {{active}} 已启用 · {{discovered}} 已发现",
"noChannelsForSearch": "没有群组匹配你的搜索。",
diff --git a/vibe/api.py b/vibe/api.py
index 99d88b469..918f65ac2 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -2788,7 +2788,12 @@ 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, force: bool = False) -> dict:
+def list_channels(
+ bot_token: str,
+ browse_all: bool = False,
+ force: bool = False,
+ include_not_returned: bool = False,
+) -> dict:
from core import chat_discovery
bot_token = bot_token or _stored_platform_secret("slack", "bot_token")
@@ -2798,6 +2803,7 @@ def list_channels(bot_token: str, browse_all: bool = False, force: bool = False)
browse_all=browse_all,
require_member=not browse_all,
force=force,
+ include_not_returned=include_not_returned,
)
@@ -2909,12 +2915,40 @@ async def telegram_auth_test_async(bot_token: str, proxy_url: str | None = None)
return {"ok": False, "error": str(exc)}
-def telegram_list_chats(include_private: bool = False) -> dict:
+def delete_channel_scope(platform: str, native_id: str, scope_type: str = "channel") -> dict:
+ """Permanently remove a discovered channel/chat scope and its settings.
+
+ Restricted to ``channel`` scopes: this endpoint exists only to clear stale
+ discovered chats. Deleting other scope types (e.g. ``project``) would bypass
+ their dedicated lifecycle (project archival preserves the scope for sessions),
+ so any non-channel scope type is rejected.
+ """
+ from core import chat_discovery
+
+ platform = str(platform or "").strip()
+ native_id = str(native_id or "").strip()
+ scope_type = str(scope_type or "channel").strip()
+ if not platform or not native_id:
+ return {"ok": False, "error": "platform and id are required"}
+ if scope_type != "channel":
+ return {"ok": False, "error": "only channel scopes can be removed here"}
+ try:
+ outcome = chat_discovery.delete_scope(platform, native_id, scope_type="channel")
+ except Exception as exc:
+ logger.warning("Failed to delete %s scope %s: %s", platform, native_id, exc, exc_info=True)
+ return {"ok": False, "error": str(exc)}
+ # ``dismissed`` means history was preserved and the entry was hidden instead
+ # of physically deleted; ``removed`` means the scope row was deleted outright.
+ return {"ok": True, **outcome}
+
+
+def telegram_list_chats(include_private: bool = False, include_not_returned: bool = False) -> dict:
from core import chat_discovery
return chat_discovery.channels_response(
"telegram",
include_private=include_private,
+ include_not_returned=include_not_returned,
)
@@ -2933,7 +2967,9 @@ async def discord_list_guilds_async(bot_token: str) -> dict:
return {"ok": False, "error": str(exc)}
-def discord_list_channels(bot_token: str, guild_id: str, force: bool = False) -> dict:
+def discord_list_channels(
+ bot_token: str, guild_id: str, force: bool = False, include_not_returned: bool = False
+) -> dict:
guild_id = str(guild_id or "").strip()
if not guild_id:
return {
@@ -2959,6 +2995,7 @@ def discord_list_channels(bot_token: str, guild_id: str, force: bool = False) ->
guild_id=guild_id,
parent_scope_id=parent_scope_id,
force=force,
+ include_not_returned=include_not_returned,
)
@@ -2991,7 +3028,16 @@ def opencode_options(cwd: str) -> dict:
return {"ok": False, "error": str(exc)}
+def _discord_retry_wait(exc: "urllib.error.HTTPError", attempt: int) -> float:
+ retry_after = exc.headers.get("Retry-After") if exc.headers else None
+ try:
+ return max(float(retry_after), float(2**attempt)) if retry_after else float(2**attempt)
+ except (TypeError, ValueError):
+ return float(2**attempt)
+
+
def _discord_api_get(bot_token: str, path: str, proxy_url: str | None = None) -> dict:
+ import urllib.error
import urllib.request
from vibe.proxy import is_socks_proxy, resolve_proxy
@@ -3002,22 +3048,43 @@ def _discord_api_get(bot_token: str, path: str, proxy_url: str | None = None) ->
headers = {"Authorization": f"Bot {bot_token}", "User-Agent": "avibe"}
proxy = resolve_proxy(proxy_url)
- if proxy and is_socks_proxy(proxy):
- return _https_json_request_via_socks(proxy, url, headers=headers)
- if proxy:
- opener = urllib.request.build_opener(
- urllib.request.ProxyHandler({"http": proxy, "https": proxy})
- )
- else:
- opener = urllib.request.build_opener()
- req = urllib.request.Request(url, headers=headers)
- with opener.open(req, timeout=10) as resp:
- payload = resp.read().decode("utf-8")
- return json.loads(payload)
+ def _request() -> dict:
+ if proxy and is_socks_proxy(proxy):
+ return _https_json_request_via_socks(proxy, url, headers=headers)
+ if proxy:
+ opener = urllib.request.build_opener(
+ urllib.request.ProxyHandler({"http": proxy, "https": proxy})
+ )
+ else:
+ opener = urllib.request.build_opener()
+ req = urllib.request.Request(url, headers=headers)
+ with opener.open(req, timeout=10) as resp:
+ payload = resp.read().decode("utf-8")
+ return json.loads(payload)
+
+ attempts = 5
+ for attempt in range(attempts):
+ try:
+ return _request()
+ except urllib.error.HTTPError as http_exc:
+ if http_exc.code in (429, 500, 502, 503, 504) and attempt < attempts - 1:
+ wait = _discord_retry_wait(http_exc, attempt)
+ logger.warning(
+ "Discord rate-limited/transient (%d), retrying after %ss (attempt %d/%d)",
+ http_exc.code,
+ wait,
+ attempt + 1,
+ attempts,
+ )
+ time.sleep(wait)
+ continue
+ raise
+ raise RuntimeError("Discord request exhausted retries") # pragma: no cover
async def _discord_api_get_async(bot_token: str, path: str, proxy_url: str | None = None) -> dict:
+ import urllib.error
import urllib.request
from vibe.proxy import is_socks_proxy, resolve_proxy
@@ -3028,23 +3095,57 @@ async def _discord_api_get_async(bot_token: str, path: str, proxy_url: str | Non
headers = {"Authorization": f"Bot {bot_token}", "User-Agent": "avibe"}
proxy = resolve_proxy(proxy_url)
- if proxy and is_socks_proxy(proxy):
- # urllib has no native SOCKS support; route via aiohttp + aiohttp_socks.
- return await _discord_api_get_via_aiohttp(url, headers, proxy)
+ use_socks = bool(proxy and is_socks_proxy(proxy))
- if proxy:
+ if proxy and not use_socks:
opener = urllib.request.build_opener(
urllib.request.ProxyHandler({"http": proxy, "https": proxy})
)
else:
opener = urllib.request.build_opener()
+
def _request() -> dict:
req = urllib.request.Request(url, headers=headers)
with opener.open(req, timeout=10) as resp:
payload = resp.read().decode("utf-8")
return json.loads(payload)
- return await asyncio.to_thread(_request)
+ attempts = 5
+ for attempt in range(attempts):
+ try:
+ if use_socks:
+ # urllib has no native SOCKS support; route via aiohttp + aiohttp_socks.
+ return await _discord_api_get_via_aiohttp(url, headers, proxy)
+ return await asyncio.to_thread(_request)
+ except urllib.error.HTTPError as http_exc:
+ if http_exc.code in (429, 500, 502, 503, 504) and attempt < attempts - 1:
+ wait = _discord_retry_wait(http_exc, attempt)
+ logger.warning(
+ "Discord rate-limited/transient (%d), retrying after %ss (attempt %d/%d)",
+ http_exc.code,
+ wait,
+ attempt + 1,
+ attempts,
+ )
+ await asyncio.sleep(wait)
+ continue
+ raise
+ except Exception as exc:
+ # aiohttp (SOCKS path) raises ClientResponseError with a `.status`.
+ status = getattr(exc, "status", None)
+ if status in (429, 500, 502, 503, 504) and attempt < attempts - 1:
+ wait = float(2**attempt)
+ logger.warning(
+ "Discord rate-limited/transient (%s) via proxy, retrying after %ss (attempt %d/%d)",
+ status,
+ wait,
+ attempt + 1,
+ attempts,
+ )
+ await asyncio.sleep(wait)
+ continue
+ raise
+ raise RuntimeError("Discord request exhausted retries") # pragma: no cover
def _https_json_request_via_socks(
@@ -9087,7 +9188,13 @@ async def lark_auth_test_async(
return {"ok": False, "error": str(exc)}
-def lark_list_chats(app_id: str, app_secret: str, domain: str = "feishu", force: bool = False) -> dict:
+def lark_list_chats(
+ app_id: str,
+ app_secret: str,
+ domain: str = "feishu",
+ force: bool = False,
+ include_not_returned: bool = False,
+) -> dict:
from core import chat_discovery
app_id = app_id or _stored_platform_field("lark", "app_id")
@@ -9099,13 +9206,41 @@ def lark_list_chats(app_id: str, app_secret: str, domain: str = "feishu", force:
app_secret=app_secret,
domain=domain,
force=force,
+ include_not_returned=include_not_returned,
)
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 time
+ import urllib.error
import urllib.request
+ def _get_with_retry(req: "urllib.request.Request", *, attempts: int = 5) -> dict:
+ for attempt in range(attempts):
+ try:
+ with urllib.request.urlopen(req, timeout=10) as resp:
+ return json.loads(resp.read().decode())
+ except urllib.error.HTTPError as http_exc:
+ # Retry on rate-limit / transient server errors with backoff.
+ if http_exc.code in (429, 500, 502, 503, 504) and attempt < attempts - 1:
+ retry_after = http_exc.headers.get("Retry-After") if http_exc.headers else None
+ try:
+ wait = max(int(retry_after), 2**attempt) if retry_after else 2**attempt
+ except (TypeError, ValueError):
+ wait = 2**attempt
+ logger.warning(
+ "Lark rate-limited/transient (%d), retrying after %ds (attempt %d/%d)",
+ http_exc.code,
+ wait,
+ attempt + 1,
+ attempts,
+ )
+ time.sleep(wait)
+ continue
+ raise
+ raise RuntimeError("Lark request exhausted retries")
+
try:
token = _lark_tenant_token(app_id, app_secret, domain)
if not token:
@@ -9117,13 +9252,19 @@ def lark_list_chats_live(app_id: str, app_secret: str, domain: str = "feishu") -
seen_page_tokens: set = set()
max_pages = 50 # safety cap to prevent infinite loop
page = 0
- while page < max_pages:
+ # `truncated` marks an INCOMPLETE inventory. Any early/abnormal exit while
+ # the server still reports more pages must set it, so the caller never
+ # marks the unseen chats not_returned from a partial list.
+ truncated = False
+ while True:
+ if page >= max_pages:
+ truncated = True
+ break
url = f"{base}/open-apis/im/v1/chats?page_size=100"
if page_token:
url = f"{url}&page_token={page_token}"
req = urllib.request.Request(url, headers={"Authorization": f"Bearer {token}"})
- with urllib.request.urlopen(req, timeout=10) as resp:
- result = json.loads(resp.read().decode())
+ result = _get_with_retry(req)
if result.get("code") != 0:
return {"ok": False, "error": result.get("msg", "Unknown error")}
data = result.get("data", {})
@@ -9138,14 +9279,21 @@ def lark_list_chats_live(app_id: str, app_secret: str, domain: str = "feishu") -
}
for c in items
)
+ has_more = bool(data.get("has_more"))
page_token = data.get("page_token") or ""
- if not data.get("has_more") or not page_token:
+ if not has_more:
+ break
+ if not page_token:
+ # Server claims more pages but gave no cursor — cannot continue.
+ truncated = True
break
if page_token in seen_page_tokens:
- break # server returned the same token — avoid loop
+ # Server returned a repeated cursor — avoid an infinite loop, but
+ # the remaining pages are unreachable, so the list is incomplete.
+ truncated = True
+ break
seen_page_tokens.add(page_token)
page += 1
- truncated = page >= max_pages
return {"ok": True, "channels": channels, "truncated": truncated}
except Exception as exc:
return {"ok": False, "error": str(exc)}
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 265303fdf..2a1b15872 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -3619,6 +3619,7 @@ def slack_channels():
payload.get("bot_token", ""),
browse_all=payload.get("browse_all", False),
force=payload.get("force", False) or request.args.get("force") == "1",
+ include_not_returned=bool(payload.get("include_not_returned", False)),
)
)
@@ -3653,6 +3654,25 @@ def discord_channels():
payload.get("bot_token", ""),
payload.get("guild_id", ""),
force=payload.get("force", False) or request.args.get("force") == "1",
+ include_not_returned=bool(payload.get("include_not_returned", False)),
+ )
+ )
+
+
[email protected]("/api/channels/delete", methods=["POST"])
+def channels_delete():
+ from vibe import api
+
+ payload = request.json or {}
+ # Channel-only by design: forward the requested scope_type so a non-channel
+ # request is explicitly rejected at this boundary (api.delete_channel_scope
+ # returns an error for anything other than "channel") rather than silently
+ # deleting the channel scope that happens to share the id.
+ return jsonify(
+ api.delete_channel_scope(
+ payload.get("platform", ""),
+ payload.get("id", ""),
+ scope_type=payload.get("scope_type", "channel"),
)
)
@@ -3674,7 +3694,12 @@ def telegram_chats():
from vibe import api
payload = request.json or {}
- return jsonify(api.telegram_list_chats(include_private=payload.get("include_private", False)))
+ return jsonify(
+ api.telegram_list_chats(
+ include_private=payload.get("include_private", False),
+ include_not_returned=bool(payload.get("include_not_returned", False)),
+ )
+ )
@app.route("/api/lark/auth_test", methods=["POST"])
@@ -3702,6 +3727,7 @@ def lark_chats():
payload.get("app_secret", ""),
payload.get("domain", "feishu"),
force=payload.get("force", False) or request.args.get("force") == "1",
+ include_not_returned=bool(payload.get("include_not_returned", False)),
)
)