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(telegram): add per-topic settings (#961)

Haichao7f984e5c7981
diff --git a/config/v2_settings.py b/config/v2_settings.py
index 4b7b3c5a5..434b46faf 100644
--- a/config/v2_settings.py
+++ b/config/v2_settings.py
@@ -20,6 +20,7 @@ DEFAULT_SHOW_MESSAGE_TYPES: List[str] = ["assistant"]
ALLOWED_MESSAGE_TYPES = {"assistant", "toolcall"}
SCHEMA_VERSION = 5
SCOPED_KEY_SEP = "::"
+THREAD_SETTINGS_PREFIX = "thread"
# Bind code prefix and length
_BIND_CODE_PREFIX = "vr-"
@@ -81,6 +82,30 @@ def _split_scoped_key(scoped_key: str) -> Tuple[Optional[str], str]:
return None, scoped_key
+def make_thread_native_id(channel_id: str, thread_id: str) -> str:
+ """Build a platform-native thread key that stays unique across channels."""
+ return f"{channel_id}/{thread_id}"
+
+
+def split_thread_native_id(native_id: str) -> Tuple[str, str]:
+ channel_id, separator, thread_id = str(native_id).rpartition("/")
+ if not separator or not channel_id or not thread_id:
+ raise ValueError("thread native id must be '<channel_id>/<thread_id>'")
+ return channel_id, thread_id
+
+
+def make_thread_settings_key(channel_id: str, thread_id: str) -> str:
+ """Build the runtime-only key used to route operations to thread settings."""
+ return SCOPED_KEY_SEP.join((THREAD_SETTINGS_PREFIX, str(channel_id), str(thread_id)))
+
+
+def split_thread_settings_key(settings_key: str) -> Optional[Tuple[str, str]]:
+ parts = str(settings_key).split(SCOPED_KEY_SEP)
+ if len(parts) == 3 and parts[0] == THREAD_SETTINGS_PREFIX and parts[1] and parts[2]:
+ return parts[1], parts[2]
+ return None
+
+
def _infer_channel_platform(channel_id: str) -> str:
cid = str(channel_id)
if cid.startswith("oc_"):
@@ -231,6 +256,7 @@ class BindCode:
@dataclass
class SettingsState:
channels: Dict[str, ChannelSettings] = field(default_factory=dict)
+ threads: Dict[str, ChannelSettings] = field(default_factory=dict)
guilds: Dict[str, GuildSettings] = field(default_factory=dict)
guild_scope_platforms: set[str] = field(default_factory=set)
guild_default_enabled: Dict[str, bool] = field(default_factory=dict)
@@ -505,6 +531,10 @@ class SettingsStore:
def _channel_key(self, channel_id: str, platform: Optional[str] = None) -> str:
return _make_scoped_key(platform, channel_id) if platform else channel_id
+ def _thread_key(self, channel_id: str, thread_id: str, platform: Optional[str] = None) -> str:
+ native_id = make_thread_native_id(channel_id, thread_id)
+ return _make_scoped_key(platform, native_id) if platform else native_id
+
def _user_key(self, user_id: str, platform: Optional[str] = None) -> str:
return _make_scoped_key(platform, user_id) if platform else user_id
@@ -522,6 +552,62 @@ class SettingsStore:
for channel_id, settings in channels.items():
self.settings.channels[self._channel_key(str(channel_id), platform)] = settings
+ def get_threads_for_platform(self, platform: str) -> Dict[str, Dict[str, ChannelSettings]]:
+ result: Dict[str, Dict[str, ChannelSettings]] = {}
+ prefix = f"{platform}{SCOPED_KEY_SEP}"
+ for key, settings in self.settings.threads.items():
+ if not key.startswith(prefix):
+ continue
+ try:
+ channel_id, thread_id = split_thread_native_id(key[len(prefix) :])
+ except ValueError:
+ continue
+ result.setdefault(channel_id, {})[thread_id] = settings
+ return result
+
+ def find_thread(
+ self,
+ channel_id: str,
+ thread_id: str,
+ platform: Optional[str] = None,
+ ) -> Optional[ChannelSettings]:
+ return self.settings.threads.get(self._thread_key(channel_id, thread_id, platform))
+
+ def find_effective_channel(
+ self,
+ channel_id: str,
+ *,
+ thread_id: Optional[str] = None,
+ platform: Optional[str] = None,
+ ) -> Optional[ChannelSettings]:
+ if thread_id:
+ thread = self.find_thread(channel_id, thread_id, platform=platform)
+ if thread is not None:
+ return thread
+ return self.find_channel(channel_id, platform=platform)
+
+ def update_thread(
+ self,
+ channel_id: str,
+ thread_id: str,
+ settings: ChannelSettings,
+ platform: Optional[str] = None,
+ ) -> None:
+ self.settings.threads[self._thread_key(channel_id, thread_id, platform)] = settings
+ self.save()
+
+ def delete_thread(
+ self,
+ channel_id: str,
+ thread_id: str,
+ platform: Optional[str] = None,
+ ) -> bool:
+ removed = self.settings.threads.pop(self._thread_key(channel_id, thread_id, platform), None)
+ if removed is not None:
+ self.save()
+ return True
+ return False
+
def get_guilds_for_platform(self, platform: str) -> Dict[str, GuildSettings]:
result: Dict[str, GuildSettings] = {}
prefix = f"{platform}{SCOPED_KEY_SEP}"
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.py
index 5182712fb..fe699b5ff 100644
--- a/core/agent_auth_service.py
+++ b/core/agent_auth_service.py
@@ -462,6 +462,12 @@ class AgentAuthService:
def _get_settings_key(self, context: MessageContext) -> str:
return self.controller._get_settings_key(context)
+ def _get_session_key(self, context: MessageContext) -> str:
+ getter = getattr(self.controller, "_get_session_key", None)
+ if callable(getter):
+ return getter(context)
+ return self._get_settings_key(context)
+
def _make_flow_key(self, context: MessageContext, backend: str) -> str:
return f"{self._get_settings_key(context)}:{backend}"
@@ -570,7 +576,7 @@ class AgentAuthService:
logger.debug("Failed to derive OpenCode session info for provider resolution: %s", err)
return None
- session_key = self._get_settings_key(context)
+ session_key = self._get_session_key(context)
get_session_id = getattr(sessions, "get_agent_session_id", None)
if not callable(get_session_id):
return None
@@ -1735,14 +1741,15 @@ class AgentAuthService:
async def _clear_backend_sessions_for_context(self, backend: str, context: MessageContext) -> None:
agent_service = getattr(self.controller, "agent_service", None)
clear_backend_sessions = getattr(agent_service, "clear_backend_sessions", None)
+ session_key = self._get_session_key(context)
if callable(clear_backend_sessions):
- await clear_backend_sessions(backend, self._get_settings_key(context))
+ await clear_backend_sessions(backend, session_key)
return
agent = getattr(agent_service, "agents", {}).get(backend) if agent_service else None
clear_sessions = getattr(agent, "clear_sessions", None)
if not callable(clear_sessions):
return
- await clear_sessions(self._get_settings_key(context))
+ await clear_sessions(session_key)
def _find_flow_for_submission(self, context: MessageContext, backend_hint: str | None) -> AgentAuthFlow | None:
settings_key = self._get_settings_key(context)
diff --git a/core/agent_session_context.py b/core/agent_session_context.py
new file mode 100644
index 000000000..9fa559ff1
--- /dev/null
+++ b/core/agent_session_context.py
@@ -0,0 +1,17 @@
+"""Helpers for resolving Agent Session metadata carried by message contexts."""
+
+from __future__ import annotations
+
+from typing import Any, Optional
+
+
+def resolve_context_agent_session_target(context: Any) -> Optional[dict[str, Any]]:
+ """Return the persisted Agent Session row selected for this context."""
+ payload = getattr(context, "platform_specific", None) or {}
+ explicit_target = payload.get("agent_session_target")
+ if isinstance(explicit_target, dict):
+ return explicit_target
+ run_target = payload.get("agent_run_target")
+ if not isinstance(run_target, dict) or not run_target.get("agent_session_id"):
+ return None
+ return {**run_target, "id": run_target["agent_session_id"]}
diff --git a/core/auth.py b/core/auth.py
index 5c2c69691..adfdb53a8 100644
--- a/core/auth.py
+++ b/core/auth.py
@@ -77,6 +77,7 @@ def check_auth(
*,
user_id: str,
channel_id: str,
+ thread_id: str | None = None,
is_dm: bool,
platform: str | None = None,
action: str = "",
@@ -122,7 +123,16 @@ def check_auth(
# DM users skip channel authorization
else:
# 2. Channel authorization
- if hasattr(store, "find_channel"):
+ if thread_id and hasattr(store, "find_effective_channel"):
+ try:
+ ch = store.find_effective_channel(
+ channel_id,
+ thread_id=thread_id,
+ platform=platform,
+ )
+ except TypeError:
+ ch = store.find_channel(channel_id, platform=platform)
+ elif hasattr(store, "find_channel"):
try:
ch = store.find_channel(channel_id, platform=platform)
except TypeError:
diff --git a/core/chat_discovery.py b/core/chat_discovery.py
index e7697a839..68b16e774 100644
--- a/core/chat_discovery.py
+++ b/core/chat_discovery.py
@@ -18,10 +18,12 @@ from storage.db import create_sqlite_engine
from storage.migrations import guard_source_checkout_default_state_migration, run_migrations
from storage.models import agent_events, media_objects, messages, scope_settings, scopes, state_meta
from storage.settings_service import make_scope_id, upsert_scope
+from config.v2_settings import make_thread_native_id, split_thread_native_id
logger = logging.getLogger(__name__)
CHANNEL_SCOPE_TYPE = "channel"
+THREAD_SCOPE_TYPE = "thread"
GUILD_SCOPE_TYPE = "guild"
VISIBILITY_VISIBLE = "visible"
VISIBILITY_NOT_RETURNED = "not_returned"
@@ -51,7 +53,7 @@ _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, ...]]] = {}
+_debounce_cache: dict[tuple[str, ...], tuple[float, tuple[Any, ...]]] = {}
_refresh_locks_lock = threading.Lock()
_refresh_locks: dict[str, threading.Lock] = {}
@@ -299,7 +301,7 @@ def remember_chat(
parent_id,
tuple(sorted(normalized_metadata.items())),
)
- debounce_key = (platform, chat_id)
+ debounce_key = (str(_db_path(db_path)), platform, chat_id)
monotonic_now = time.monotonic()
with _debounce_lock:
cached = _debounce_cache.get(debounce_key)
@@ -356,6 +358,130 @@ def remember_chat(
_debounce_cache[debounce_key] = (monotonic_now, debounce_payload)
+def remember_thread(
+ platform: str,
+ channel_id: str,
+ thread_id: str,
+ *,
+ name: str = "",
+ native_type: str = "thread",
+ metadata: dict[str, Any] | None = None,
+ db_path: Path | None = None,
+) -> None:
+ """Remember a passively discovered child thread without changing settings."""
+ platform = str(platform)
+ channel_id = str(channel_id).strip()
+ thread_id = str(thread_id).strip()
+ if not platform or not channel_id or not thread_id:
+ return
+
+ native_id = make_thread_native_id(channel_id, thread_id)
+ normalized_metadata = normalize_metadata(metadata)
+ normalized_metadata.update({"channel_id": channel_id, "thread_id": thread_id})
+ normalized_metadata.setdefault(METADATA_VISIBILITY_STATUS, VISIBILITY_VISIBLE)
+ # A newly observed topic is active again even if its scope row was retained
+ # only to preserve history after the parent forum was removed.
+ normalized_metadata.setdefault(METADATA_DISMISSED_AT, None)
+ debounce_payload = (name, native_type, tuple(sorted(normalized_metadata.items())))
+ debounce_key = (str(_db_path(db_path)), platform, f"thread:{native_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
+
+ now = _utc_now_iso()
+ engine = _engine(db_path)
+ try:
+ with engine.begin() as conn:
+ parent_scope_id = upsert_scope(
+ conn,
+ platform,
+ CHANNEL_SCOPE_TYPE,
+ channel_id,
+ now=now,
+ )
+ row = _scope_row(conn, platform, THREAD_SCOPE_TYPE, native_id)
+ existing_metadata = _json_loads(row["metadata_json"], {}) if row else {}
+ upsert_scope(
+ conn,
+ platform,
+ THREAD_SCOPE_TYPE,
+ native_id,
+ parent_scope_id=parent_scope_id,
+ display_name=name,
+ native_type=native_type,
+ is_private=False,
+ supports_threads=False,
+ metadata=merge_metadata(existing_metadata, normalized_metadata),
+ now=now,
+ )
+ finally:
+ engine.dispose()
+ with _debounce_lock:
+ _debounce_cache[debounce_key] = (monotonic_now, debounce_payload)
+
+
+def list_thread_payloads(
+ platform: str,
+ channel_id: str,
+ *,
+ db_path: Path | None = None,
+) -> list[dict[str, Any]]:
+ parent_scope_id = make_scope_id(platform, CHANNEL_SCOPE_TYPE, str(channel_id))
+ engine = _engine(db_path)
+ try:
+ with engine.connect() as conn:
+ query = (
+ select(
+ scopes.c.native_id,
+ scopes.c.display_name,
+ scopes.c.native_type,
+ 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(
+ scopes.c.platform == platform,
+ scopes.c.scope_type == THREAD_SCOPE_TYPE,
+ scopes.c.parent_scope_id == parent_scope_id,
+ )
+ )
+ result: list[dict[str, Any]] = []
+ for row in conn.execute(query).mappings():
+ try:
+ _, thread_id = split_thread_native_id(str(row["native_id"]))
+ except ValueError:
+ continue
+ metadata = _json_loads(row["metadata_json"], {})
+ if metadata.get(METADATA_DISMISSED_AT):
+ continue
+ result.append(
+ {
+ "id": thread_id,
+ "name": str(row["display_name"] or ""),
+ "native_type": str(row["native_type"] or "thread"),
+ "configured": row["settings_scope_id"] is not None,
+ "metadata": metadata,
+ "first_seen_at": str(row["first_seen_at"] or ""),
+ "last_seen_at": str(row["last_seen_at"] or ""),
+ }
+ )
+ return sorted(
+ result,
+ key=lambda item: (
+ item["id"] != "1",
+ not item["configured"],
+ item["name"].lower(),
+ item["id"],
+ ),
+ )
+ finally:
+ engine.dispose()
+
+
def list_chats(
platform: str,
*,
@@ -835,6 +961,58 @@ def _scope_has_history(conn: Connection, scope_id: str) -> bool:
return False
+def _descendant_scope_rows(conn: Connection, scope_id: str) -> list[dict[str, Any]]:
+ """Return descendant scope rows in parent-before-child order."""
+ descendants: list[dict[str, Any]] = []
+ pending = [scope_id]
+ visited = {scope_id}
+ while pending:
+ rows = (
+ conn.execute(select(scopes).where(scopes.c.parent_scope_id.in_(pending)))
+ .mappings()
+ .all()
+ )
+ pending = []
+ for row in rows:
+ child_id = str(row["id"])
+ if child_id in visited:
+ continue
+ visited.add(child_id)
+ descendants.append(dict(row))
+ pending.append(child_id)
+ return descendants
+
+
+def _remove_scope_row_preserving_history(conn: Connection, row: dict[str, Any]) -> dict[str, bool]:
+ """Delete one scope's settings, then delete or dismiss its scope row."""
+ scope_id = str(row["id"])
+ conn.execute(scope_settings.delete().where(scope_settings.c.scope_id == scope_id))
+ if _scope_has_history(conn, scope_id):
+ now = _utc_now_iso()
+ metadata = _json_loads(row["metadata_json"], {})
+ metadata[METADATA_DISMISSED_AT] = now
+ conn.execute(
+ scopes.update()
+ .where(scopes.c.id == scope_id)
+ .values(metadata_json=_json_dumps(metadata), updated_at=now)
+ )
+ return {"removed": False, "dismissed": True}
+ result = conn.execute(scopes.delete().where(scopes.c.id == scope_id))
+ return {"removed": bool(result.rowcount), "dismissed": False}
+
+
+def _clear_scope_debounce_entries(db_path: Path | None, rows: list[dict[str, Any]]) -> None:
+ """Allow deleted or dismissed scopes to be persisted on rediscovery."""
+ database_key = str(_db_path(db_path))
+ with _debounce_lock:
+ for row in rows:
+ scope_type = str(row["scope_type"])
+ native_id = str(row["native_id"])
+ if scope_type == THREAD_SCOPE_TYPE:
+ native_id = f"thread:{native_id}"
+ _debounce_cache.pop((database_key, str(row["platform"]), native_id), None)
+
+
def delete_scope(
platform: str,
native_id: str,
@@ -849,6 +1027,8 @@ def delete_scope(
scope with ON DELETE CASCADE, a hard delete would wipe that history. So:
- the ``scope_settings`` row is always deleted (the user's config);
+ - descendant scopes and settings are removed by the same history-preserving
+ rules so a deleted parent cannot leave active child overrides behind;
- 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
@@ -863,20 +1043,12 @@ def delete_scope(
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}
+ descendants = _descendant_scope_rows(conn, scope_id)
+ for descendant in reversed(descendants):
+ _remove_scope_row_preserving_history(conn, descendant)
+ outcome = _remove_scope_row_preserving_history(conn, dict(row))
+ _clear_scope_debounce_entries(db_path, [dict(row), *descendants])
+ return outcome
finally:
engine.dispose()
diff --git a/core/controller.py b/core/controller.py
index de7ffdbae..97485cae2 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -527,6 +527,9 @@ class Controller:
def _inject_runtime_dependencies(self, platform: str, client: BaseIMClient) -> None:
settings_manager = self.platform_settings_managers[platform]
+ settings_manager.require_mention_default = lambda: bool(
+ getattr(getattr(client, "config", None), "require_mention", False)
+ )
setter = getattr(client, "set_settings_manager", None)
if callable(setter):
setter(settings_manager)
@@ -941,13 +944,16 @@ class Controller:
"""Get settings key based on context.
For DM contexts, returns user_id so per-user settings apply.
- For channel contexts, returns channel_id for per-channel settings.
+ For channel contexts, returns channel_id for per-channel settings. A
+ Telegram forum topic returns a runtime thread key so its explicit
+ override can win before the parent channel fallback.
Relies on the ``is_dm`` flag set by the IM layer in
``context.platform_specific`` (see Phase 2 of the refactoring).
"""
- is_dm = (context.platform_specific or {}).get("is_dm", False)
- return context.user_id if is_dm else context.channel_id
+ from core.message_context import resolve_context_scope_settings_key
+
+ return resolve_context_scope_settings_key(context)
def _get_session_key(self, context: MessageContext) -> str:
"""Get a globally unique session-scope key.
@@ -958,7 +964,9 @@ class Controller:
tracking never collide.
"""
platform = context.platform or (context.platform_specific or {}).get("platform") or self.primary_platform
- settings_key = self._get_settings_key(context)
+ from core.message_context import resolve_context_settings_key
+
+ settings_key = resolve_context_settings_key(context)
return build_context_session_key(context, platform=platform, settings_key=settings_key)
def backend_alive(self, context: MessageContext) -> Optional[bool]:
diff --git a/core/handlers/command_handlers.py b/core/handlers/command_handlers.py
index 76de0e3c1..de0731ec0 100644
--- a/core/handlers/command_handlers.py
+++ b/core/handlers/command_handlers.py
@@ -6,7 +6,11 @@ import time
from typing import Any, Optional
from config.platform_registry import get_platform_descriptor
from core.bind_security import BindAttemptLimiter
-from core.message_context import requires_typed_user_session_key
+from core.message_context import (
+ build_thread_session_anchor,
+ requires_typed_user_session_key,
+ resolve_context_thread_id,
+)
from modules.agents import get_agent_display_name
from modules.agents.native_sessions.types import NativeResumeSession
from modules.agents.base import AgentRequest
@@ -119,10 +123,13 @@ class CommandHandlers(BaseHandler):
logger.debug("Failed to resolve session anchor for /new", exc_info=True)
platform = context.platform or (context.platform_specific or {}).get("platform") or self.config.platform
payload = context.platform_specific or {}
+ thread_id = resolve_context_thread_id(context) or context.thread_id
if payload.get("is_dm", False):
base_id = context.thread_id or context.channel_id or context.user_id
else:
- base_id = context.thread_id or context.message_id or context.channel_id or context.user_id
+ if thread_id:
+ return build_thread_session_anchor(platform, context.channel_id, thread_id)
+ base_id = context.message_id or context.channel_id or context.user_id
return f"{platform}_{base_id}"
def _compat_session_keys_for_new(self, context: MessageContext, session_key: str) -> list[str]:
@@ -777,7 +784,8 @@ class CommandHandlers(BaseHandler):
# mutating an existing record. Reject in-thread invocations so resume always
# opens a FRESH scope-level session (maintainer decision; preserves the
# native_session_id write-once invariant). WeChat above has no threads.
- if context.thread_id and context.thread_id != context.message_id:
+ thread_id = resolve_context_thread_id(context) or context.thread_id
+ if thread_id and thread_id != context.message_id:
channel_context = self._get_channel_context(context)
await im_client.send_message(channel_context, self._t("command.resume.scopeOnly"))
return
diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.py
index 346fce83d..d8ac53e9d 100644
--- a/core/handlers/message_handler.py
+++ b/core/handlers/message_handler.py
@@ -13,6 +13,7 @@ from core.audio_asr import (
format_audio_transcript_echo,
)
from core.message_output import terminal_output_for, terminal_turn_output
+from core.message_context import resolve_context_thread_id
from modules.agents.base import AgentRequest
from modules.agents.catalog import display_name_for_backend, is_agent_backend
from modules.im import MessageContext
@@ -138,7 +139,8 @@ class MessageHandler(BaseHandler):
# Skip automatic cleanup; receiver tasks are retained until shutdown
# Allow "stop" shortcut inside Slack threads
- if is_human and context.thread_id and control_message.strip().lower() in ["stop", "/stop"]:
+ active_thread_id = resolve_context_thread_id(context) or context.thread_id
+ if is_human and active_thread_id and control_message.strip().lower() in ["stop", "/stop"]:
if await self._handle_inline_stop(context):
return None
diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.py
index 88c850ece..6eaf8ede7 100644
--- a/core/handlers/session_handler.py
+++ b/core/handlers/session_handler.py
@@ -30,7 +30,9 @@ from config.v2_config import (
DEFAULT_STUCK_ACTIVE_IDLE_EVICTION_MULTIPLIER,
)
from core.avibe_cloud import avibe_cloud_url_available
+from core.agent_session_context import resolve_context_agent_session_target
from core.caller_context import caller_env_for_platform_payload
+from core.message_context import build_thread_session_anchor, resolve_context_thread_id
from core.resource_governance import governor_from_controller
from core.services.session_fork import pending_native_fork_source
from core.system_prompt_injection import build_system_prompt_injection, get_enabled_agents_for_prompt
@@ -306,9 +308,8 @@ class SessionHandler(BaseHandler):
def get_base_session_id(self, context: MessageContext, source: str = "human") -> str:
"""Get base session ID based on platform and context (without path)"""
platform = self._get_context_platform(context)
- payload = context.platform_specific or {}
- session_target = payload.get("agent_session_target")
- if isinstance(session_target, dict):
+ session_target = resolve_context_agent_session_target(context)
+ if session_target:
reserved_anchor = str(session_target.get("session_anchor") or "").strip()
if reserved_anchor:
return reserved_anchor
@@ -323,7 +324,10 @@ class SessionHandler(BaseHandler):
else:
base_id = context.channel_id or context.user_id
else:
- base_id = context.thread_id
+ resolved_thread_id = resolve_context_thread_id(context)
+ base_id = resolved_thread_id or context.thread_id
+ if platform == "telegram" and base_id:
+ return build_thread_session_anchor(platform, context.channel_id, base_id)
if not base_id:
use_message_id = True
getter = getattr(self.controller, "get_im_client_for_context", None)
@@ -341,20 +345,13 @@ class SessionHandler(BaseHandler):
@staticmethod
def _reserved_native_session_id(context: MessageContext) -> Optional[str]:
- """Native session id bound to the RESERVED workbench row (by PK).
-
- avibe dispatch carries it in
- ``platform_specific['agent_session_target']['native_session_id']`` (read
- from the ``agent_sessions`` row). Resuming from this keeps the resume READ
- on the same key as the by-PK bind WRITE, so a restart resumes the same
- native session instead of forking a fresh one. ``None`` for IM/CLI turns
- or before the first native is captured. Only returns the native when the
- reserved row's ``agent_backend`` is Claude — after a header backend switch
- the row still carries the previous backend's native, which Claude can't
- resume. Mirrors ``BaseAgent._reserved_native_session_id``."""
- payload = getattr(context, "platform_specific", None) or {}
- target = payload.get("agent_session_target")
- if not isinstance(target, dict):
+ """Native session id bound to the selected persisted row (by PK).
+
+ This includes explicit Workbench targets and rows selected for IM turns.
+ Only returns the native when the row's backend is Claude; after a backend
+ switch, the previous backend's native id must not be resumed."""
+ target = resolve_context_agent_session_target(context)
+ if not target:
return None
native = str(target.get("native_session_id") or "").strip()
if not native:
@@ -684,8 +681,8 @@ class SessionHandler(BaseHandler):
explicit_model = subagent_model or routing_model_for_backend(routing, "claude")
explicit_effort = subagent_reasoning_effort or routing_reasoning_effort_for_backend(routing, "claude")
- session_target = payload.get("agent_session_target")
- if isinstance(session_target, dict):
+ session_target = resolve_context_agent_session_target(context)
+ if session_target:
explicit_model = subagent_model or session_target.get("model") or explicit_model
explicit_effort = subagent_reasoning_effort or session_target.get("reasoning_effort") or explicit_effort
@@ -1571,8 +1568,8 @@ class SessionHandler(BaseHandler):
# (mirrors BaseAgent.ensure_agent_session_id) so a pre-bind setup/query
# failure persists the terminal notify under the OPEN Chat session rather
# than a freshly-minted hidden row the page never sees (Codex P2).
- target = (getattr(context, "platform_specific", None) or {}).get("agent_session_target")
- if isinstance(target, dict) and target.get("id"):
+ target = resolve_context_agent_session_target(context)
+ if target and target.get("id"):
reserved_id = str(target["id"]).strip()
if reserved_id:
payload = dict(context.platform_specific or {})
diff --git a/core/handlers/settings_handler.py b/core/handlers/settings_handler.py
index 2a88d3e72..78d8a93a2 100644
--- a/core/handlers/settings_handler.py
+++ b/core/handlers/settings_handler.py
@@ -675,6 +675,7 @@ class SettingsHandler(BaseHandler):
user_id: str,
show_message_types: list,
channel_id: Optional[str] = None,
+ thread_id: Optional[str] = None,
require_mention: Optional[bool] = None,
language: Optional[str] = None,
notify_user: bool = True,
@@ -686,6 +687,7 @@ class SettingsHandler(BaseHandler):
context = MessageContext(
user_id=user_id,
channel_id=channel_id if channel_id else user_id,
+ thread_id=thread_id,
platform=platform or self.config.platform,
platform_specific={"is_dm": is_dm, "platform": platform or self.config.platform},
)
@@ -693,13 +695,13 @@ class SettingsHandler(BaseHandler):
im_client = self._get_im_client(context)
settings_manager = self._get_settings_manager(context)
+ if not is_dm:
+ settings_manager.set_require_mention(settings_key, require_mention)
+
user_settings = settings_manager.get_user_settings(settings_key)
user_settings.show_message_types = show_message_types
settings_manager.update_user_settings(settings_key, user_settings)
- if not is_dm:
- settings_manager.set_require_mention(settings_key, require_mention)
-
language_saved = True
if language is not None and language != self.config.language:
try:
@@ -750,6 +752,7 @@ class SettingsHandler(BaseHandler):
view_id: str,
view_hash: str,
selection: RoutingModalSelection,
+ thread_id: Optional[str] = None,
is_dm: bool = False,
platform: Optional[str] = None,
) -> None:
@@ -763,6 +766,7 @@ class SettingsHandler(BaseHandler):
context = MessageContext(
user_id=user_id,
channel_id=resolved_channel_id,
+ thread_id=thread_id,
platform=platform or self.config.platform,
platform_specific={"is_dm": is_dm, "platform": platform or self.config.platform},
)
@@ -815,6 +819,7 @@ class SettingsHandler(BaseHandler):
backend: str,
opencode_agent: Optional[str],
opencode_model: Optional[str],
+ thread_id: Optional[str] = None,
opencode_reasoning_effort: Optional[str] = None,
claude_agent: Optional[str] = None,
claude_model: Optional[str] = None,
@@ -834,6 +839,7 @@ class SettingsHandler(BaseHandler):
context = MessageContext(
user_id=user_id,
channel_id=channel_id if channel_id else user_id,
+ thread_id=thread_id,
platform=platform or self.config.platform,
platform_specific={"is_dm": is_dm, "platform": platform or self.config.platform},
)
diff --git a/core/message_context.py b/core/message_context.py
index cfe3bf6ab..c5d207d8e 100644
--- a/core/message_context.py
+++ b/core/message_context.py
@@ -4,6 +4,7 @@ from __future__ import annotations
from typing import Optional
+from config.v2_settings import make_thread_settings_key
from modules.im import MessageContext
@@ -27,6 +28,70 @@ def resolve_context_settings_key(context: MessageContext) -> str:
return str(value or "")
+def resolve_context_thread_id(context: MessageContext) -> Optional[str]:
+ """Return the canonical configurable thread ID for a message context."""
+ platform = resolve_context_platform(context)
+ payload = context.platform_specific or {}
+ if platform != "telegram" or payload.get("is_dm", False):
+ return None
+ if context.thread_id:
+ return str(context.thread_id)
+ if payload.get("is_forum") or payload.get("is_topic_message"):
+ return "1"
+ return None
+
+
+def build_thread_session_anchor(platform: str, channel_id: str, thread_id: str) -> str:
+ """Build a backend session anchor unique at the platform's thread scope."""
+ if platform == "telegram":
+ return f"{platform}_{channel_id}_{thread_id}"
+ return f"{platform}_{thread_id}"
+
+
+def build_thread_session_anchor_candidates(
+ platform: str,
+ channel_id: str,
+ thread_id: str,
+) -> tuple[str, ...]:
+ """Return the canonical anchor followed by any compatible legacy anchor."""
+ canonical = build_thread_session_anchor(platform, channel_id, thread_id)
+ legacy = f"{platform}_{thread_id}"
+ return (canonical, legacy) if legacy != canonical else (canonical,)
+
+
+def thread_id_from_session_anchor(
+ anchor: str,
+ *,
+ platform: str,
+ channel_id: str,
+) -> Optional[str]:
+ """Recover a thread ID from canonical and pre-scoped session anchors."""
+ base_anchor = str(anchor or "").split(":", 1)[0]
+ if not base_anchor:
+ return None
+
+ if platform == "telegram":
+ canonical_prefix = f"{platform}_{channel_id}_"
+ if base_anchor.startswith(canonical_prefix):
+ thread_id = base_anchor[len(canonical_prefix) :]
+ return thread_id or None
+
+ legacy_prefix = f"{platform}_"
+ if not base_anchor.startswith(legacy_prefix):
+ return None
+ thread_id = base_anchor[len(legacy_prefix) :]
+ return thread_id if thread_id and thread_id != str(channel_id) else None
+
+
+def resolve_context_scope_settings_key(context: MessageContext) -> str:
+ """Resolve the context-aware settings key without changing session identity."""
+ base = resolve_context_settings_key(context)
+ thread_id = resolve_context_thread_id(context)
+ if thread_id and not (context.platform_specific or {}).get("is_dm", False):
+ return make_thread_settings_key(base, thread_id)
+ return base
+
+
def requires_typed_user_session_key(context: MessageContext) -> bool:
payload = context.platform_specific or {}
return bool(payload.get("is_dm", False) and context.user_id and context.channel_id == context.user_id)
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.py
index fa14c07bc..1376aecee 100644
--- a/core/scheduled_tasks.py
+++ b/core/scheduled_tasks.py
@@ -20,7 +20,13 @@ from sqlalchemy import select
from sqlalchemy.exc import SQLAlchemyError
from config import paths
-from core.message_context import resolve_context_platform
+from config.v2_settings import split_thread_native_id
+from core.message_context import (
+ build_thread_session_anchor,
+ resolve_context_platform,
+ resolve_context_thread_id,
+ thread_id_from_session_anchor,
+)
from core.reply_enhancer import strip_silent_blocks
from core.session_activities import activity_completion_output
from modules.im import MessageContext
@@ -173,8 +179,9 @@ def parse_scope_id(value: str) -> ParsedSessionKey:
def session_anchor_for_target(target: ParsedSessionKey) -> str:
- anchor_id = target.thread_id or target.scope_id
- return f"{target.platform}_{anchor_id}"
+ if target.thread_id:
+ return build_thread_session_anchor(target.platform, target.scope_id, target.thread_id)
+ return f"{target.platform}_{target.scope_id}"
@dataclass(frozen=True)
@@ -266,19 +273,27 @@ def resolve_session_id_target(session_id: str, *, db_path: Optional[Path] = None
# the reply to that reserved session via ``agent_session_target`` — so a
# project-scoped row IS a valid task target. (``--session-key`` targeting stays
# channel/user-only: a bare project key wouldn't identify a single session.)
+ scoped_thread_id: Optional[str] = None
if persisted_scope_id is None:
platform = "avibe"
scope_type = "project"
native_scope_id = raw
- elif not platform or scope_type not in {"channel", "user", "project"} or not native_scope_id:
- raise ValueError(f"agent session id cannot be used as a task target: {raw}")
+ else:
+ if not platform or not native_scope_id:
+ raise ValueError(f"agent session id cannot be used as a task target: {raw}")
+ if scope_type == "thread":
+ try:
+ native_scope_id, scoped_thread_id = split_thread_native_id(native_scope_id)
+ except ValueError as exc:
+ raise ValueError(f"agent session id cannot be used as a task target: {raw}") from exc
+ scope_type = "channel"
+ elif scope_type not in {"channel", "user", "project"}:
+ raise ValueError(f"agent session id cannot be used as a task target: {raw}")
anchor = str(row["session_anchor"] or "")
- thread_id = (
- None
- if persisted_scope_id is None or anchor == raw
- else _thread_id_from_session_anchor(anchor, platform=platform, scope_id=native_scope_id)
- )
+ thread_id = scoped_thread_id
+ if thread_id is None and persisted_scope_id is not None and anchor != raw:
+ thread_id = _thread_id_from_session_anchor(anchor, platform=platform, scope_id=native_scope_id)
session_metadata = _json_loads(row["session_metadata_json"], {})
visibility = str(row["visibility"] or "foreground")
return ResolvedSessionIdTarget(
@@ -348,17 +363,7 @@ def enqueue_session_callback(
def _thread_id_from_session_anchor(anchor: str, *, platform: str, scope_id: str) -> Optional[str]:
- if not anchor:
- return None
- base_anchor = anchor
- if ":" in base_anchor:
- base_anchor = base_anchor.split(":", 1)[0]
- prefix = f"{platform}_"
- if base_anchor.startswith(prefix):
- base_anchor = base_anchor[len(prefix) :]
- if base_anchor and base_anchor != scope_id:
- return base_anchor
- return None
+ return thread_id_from_session_anchor(anchor, platform=platform, channel_id=scope_id)
def build_session_key_for_context(
@@ -376,7 +381,7 @@ def build_session_key_for_context(
platform=platform,
scope_type=scope_type,
scope_id=scope_id,
- thread_id=context.thread_id if include_thread else None,
+ thread_id=(resolve_context_thread_id(context) or context.thread_id) if include_thread else None,
)
@@ -2941,8 +2946,21 @@ class ScheduledTaskService:
clear_provisional_source = session_target.thread_id is None and self._supports_threaded_delivery(session_target)
if delivery_target.thread_id:
- alias_base = f"{delivery_target.platform}_{delivery_target.thread_id}"
- if same_scope and alias_base == f"{session_target.platform}_{session_target.thread_id}":
+ alias_base = build_thread_session_anchor(
+ delivery_target.platform,
+ delivery_target.scope_id,
+ delivery_target.thread_id,
+ )
+ source_alias_base = (
+ build_thread_session_anchor(
+ session_target.platform,
+ session_target.scope_id,
+ session_target.thread_id,
+ )
+ if session_target.thread_id
+ else None
+ )
+ if same_scope and alias_base == source_alias_base:
return {"mode": "none"}
return {
"mode": "fixed_base",
diff --git a/core/services/agent_run_target.py b/core/services/agent_run_target.py
index 0301d6540..3b8c1cab3 100644
--- a/core/services/agent_run_target.py
+++ b/core/services/agent_run_target.py
@@ -15,11 +15,18 @@ from dataclasses import dataclass
from pathlib import Path
from typing import Any, Optional
-from sqlalchemy import Engine, select
-
-from core.message_context import build_context_session_key, resolve_context_settings_key
+from sqlalchemy import Engine, select, update
+
+from core.message_context import (
+ build_context_session_key,
+ build_thread_session_anchor,
+ build_thread_session_anchor_candidates,
+ resolve_context_settings_key,
+ resolve_context_thread_id,
+)
+from config.v2_settings import make_thread_native_id
from modules.im import MessageContext
-from storage.agent_session_rows import create_agent_session_row
+from storage.agent_session_rows import create_agent_session_row, utc_now_iso
from storage.models import agent_sessions, scope_settings, scopes
logger = logging.getLogger(__name__)
@@ -146,41 +153,70 @@ def resolve_agent_run_target(
scope_row = _scope_for_context(conn, context, platform, settings_key)
scope_id = scope_row.get("scope_id") if scope_row else None
- if scope_id:
- existing = conn.execute(
- select(
- agent_sessions,
- scopes.c.scope_type.label("_scope_type"),
+ anchor_candidates = (anchor,)
+ thread_id = resolve_context_thread_id(context) or context.thread_id
+ if platform == "telegram" and thread_id:
+ canonical_anchor = build_thread_session_anchor(platform, context.channel_id, thread_id)
+ if anchor == canonical_anchor:
+ anchor_candidates = build_thread_session_anchor_candidates(
+ platform,
+ context.channel_id,
+ thread_id,
)
- .select_from(agent_sessions.outerjoin(scopes, scopes.c.id == agent_sessions.c.scope_id))
- .where(agent_sessions.c.scope_id == scope_id)
- .where(agent_sessions.c.session_anchor == anchor)
- # Never resolve a turn onto an archived row. The archived row's
- # anchor is vacated on archive (so it won't match a live thread
- # anyway); this is the explicit guard, matching the bind path.
- .where(agent_sessions.c.status != "archived")
- .order_by(agent_sessions.c.last_active_at.desc(), agent_sessions.c.id.desc())
- .limit(1)
- ).mappings().first()
+
+ existing = None
+ for candidate_scope_id in _session_scope_ids_for_context(
+ context,
+ platform=platform,
+ preferred_scope_id=_optional_str(scope_id),
+ ):
+ for candidate_anchor in anchor_candidates:
+ existing = conn.execute(
+ select(
+ agent_sessions,
+ scopes.c.scope_type.label("_scope_type"),
+ )
+ .select_from(agent_sessions.outerjoin(scopes, scopes.c.id == agent_sessions.c.scope_id))
+ .where(agent_sessions.c.scope_id == candidate_scope_id)
+ .where(agent_sessions.c.session_anchor == candidate_anchor)
+ # Never resolve a turn onto an archived row. The archived row's
+ # anchor is vacated on archive (so it won't match a live thread
+ # anyway); this is the explicit guard, matching the bind path.
+ .where(agent_sessions.c.status != "archived")
+ .order_by(agent_sessions.c.last_active_at.desc(), agent_sessions.c.id.desc())
+ .limit(1)
+ ).mappings().first()
+ if existing is not None:
+ if candidate_anchor != anchor:
+ conn.execute(
+ update(agent_sessions)
+ .where(agent_sessions.c.id == existing["id"])
+ .values(session_anchor=anchor, updated_at=utc_now_iso())
+ )
+ existing = dict(existing)
+ existing["session_anchor"] = anchor
+ break
if existing is not None:
- return _cache_target(
- context,
- _target_from_session_row(
+ break
+ if existing is not None:
+ return _cache_target(
+ context,
+ _target_from_session_row(
+ existing,
+ platform=platform,
+ settings_key=settings_key,
+ session_key=session_key,
+ fallback_anchor=anchor,
+ workdir=_authoritative_session_workdir(
existing,
platform=platform,
settings_key=settings_key,
session_key=session_key,
- fallback_anchor=anchor,
- workdir=_authoritative_session_workdir(
- existing,
- platform=platform,
- settings_key=settings_key,
- session_key=session_key,
- source="existing_session",
- ),
- source=source,
+ source="existing_session",
),
- )
+ source=source,
+ ),
+ )
if not scope_id:
agent_target = _resolve_agent_target(
@@ -353,7 +389,10 @@ def _fallback_anchor(context: MessageContext, platform: str) -> str:
target = payload.get("agent_session_target")
if isinstance(target, dict) and target.get("session_anchor"):
return str(target["session_anchor"])
- return f"{platform}_{context.thread_id or context.message_id or context.channel_id or context.user_id}"
+ thread_id = resolve_context_thread_id(context) or context.thread_id
+ if platform == "telegram" and thread_id:
+ return build_thread_session_anchor(platform, context.channel_id, thread_id)
+ return f"{platform}_{thread_id or context.message_id or context.channel_id or context.user_id}"
def _target_payload(context: MessageContext) -> dict[str, Any]:
@@ -507,6 +546,11 @@ def _scope_for_context(conn, context: MessageContext, platform: str, settings_ke
if (payload.get("is_dm", False)):
candidates.append((platform, "user", str(context.user_id)))
else:
+ thread_id = resolve_context_thread_id(context)
+ if thread_id:
+ candidates.append(
+ (platform, "thread", make_thread_native_id(str(context.channel_id), thread_id))
+ )
candidates.append((platform, "channel", str(settings_key)))
candidates.append((platform, "user", str(settings_key)))
if platform == "avibe":
@@ -515,11 +559,41 @@ def _scope_for_context(conn, context: MessageContext, platform: str, settings_ke
for candidate_platform, scope_type, native_id in candidates:
scope_id = f"{candidate_platform}::{scope_type}::{native_id}"
row = _scope_row(conn, scope_id)
+ if row is not None and scope_type == "thread" and not row.get("settings_scope_id"):
+ continue
if row is not None:
return row
return None
+def _session_scope_ids_for_context(
+ context: MessageContext,
+ *,
+ platform: str,
+ preferred_scope_id: Optional[str],
+) -> list[str]:
+ """Return stable session lookup scopes for a context.
+
+ Telegram topic settings can be added or removed independently of the
+ topic's conversation. Search both the currently preferred settings scope
+ and its parent/child counterpart so that changing the override does not
+ fork the existing Agent Session.
+ """
+
+ scope_ids = [preferred_scope_id] if preferred_scope_id else []
+ thread_id = resolve_context_thread_id(context)
+ if not thread_id:
+ return scope_ids
+
+ for scope_id in (
+ f"{platform}::thread::{make_thread_native_id(str(context.channel_id), thread_id)}",
+ f"{platform}::channel::{context.channel_id}",
+ ):
+ if scope_id not in scope_ids:
+ scope_ids.append(scope_id)
+ return scope_ids
+
+
def _scope_row(conn, scope_id: str) -> Optional[dict[str, Any]]:
row = conn.execute(
select(
@@ -533,6 +607,7 @@ def _scope_row(conn, scope_id: str) -> Optional[dict[str, Any]]:
scope_settings.c.model,
scope_settings.c.reasoning_effort,
scope_settings.c.settings_json,
+ scope_settings.c.scope_id.label("settings_scope_id"),
)
.select_from(scopes.outerjoin(scope_settings, scope_settings.c.scope_id == scopes.c.id))
.where(scopes.c.id == scope_id)
diff --git a/docs/TELEGRAM_SETUP.md b/docs/TELEGRAM_SETUP.md
index c7bd0027f..12398e837 100644
--- a/docs/TELEGRAM_SETUP.md
+++ b/docs/TELEGRAM_SETUP.md
@@ -55,7 +55,18 @@ The most common Telegram setup issue is leaving privacy mode enabled. In that st
Avibe discovers Telegram chats from inbound messages. Telegram does not provide a generic "list every chat the bot is in" API.
-Important: Telegram DMs are usable, but they stay hidden in the wizard chat-selection UI. The selectable list is for discovered groups and forum chats, not individual topics.
+Important: Telegram DMs are usable, but they stay hidden in the wizard chat-selection UI. The wizard selects discovered groups and forum chats. After setup, the dashboard's **Group Settings** page also lists forum topics that the bot has seen.
+
+### Configure individual forum topics
+
+Open **Dashboard → Group Settings → Telegram**, then expand a forum group. Every discovered topic initially inherits the group settings. Choose **Customize** to give that topic its own:
+
+- enabled state and `@mention` requirement
+- bound-user-only access policy
+- Vibe Agent, model, reasoning, and working directory
+- visible message types
+
+Choose **Use group settings** to delete the override and resume inheritance. Telegram does not provide a complete topic-list API, so a topic appears after the bot receives a message there. The General topic is treated as topic ID `1`.
On first setup, do this in order:
diff --git a/docs/TELEGRAM_SETUP_ZH.md b/docs/TELEGRAM_SETUP_ZH.md
index 550d41239..1497b8e49 100644
--- a/docs/TELEGRAM_SETUP_ZH.md
+++ b/docs/TELEGRAM_SETUP_ZH.md
@@ -55,7 +55,18 @@ Telegram 最常见的初始化问题,就是忘了把隐私模式关掉。隐
Avibe 是通过入站消息来发现 Telegram 会话的。Telegram 没有提供“列出 bot 所在全部群聊”的通用 API。
-注意:Telegram 私聊本身可以正常使用,但不会显示在向导里的会话选择列表中。列表里只会展示已发现的群组和 forum chat,不会单独展示某个 topic。
+注意:Telegram 私聊本身可以正常使用,但不会显示在向导里的会话选择列表中。向导只选择已发现的群组和 forum chat;完成设置后,Dashboard 的**群组设置**页面还会列出 Bot 已经见过的 forum topic。
+
+### 单独配置 Forum Topic
+
+打开 **Dashboard → 群组设置 → Telegram**,展开一个 forum 群组。每个已发现的 topic 一开始都会继承群组设置。点击**单独配置**后,可以为该 topic 分别设置:
+
+- 是否启用以及是否要求 `@提及`
+- 是否仅允许已绑定用户
+- Vibe Agent、模型、推理强度和工作目录
+- 要显示的消息类型
+
+点击**恢复群组设置**会删除 topic 覆盖并重新继承群组。Telegram 没有提供完整的 topic 列表 API,因此 Bot 在某个 topic 收到消息后,它才会出现在页面中。General topic 统一按 topic ID `1` 处理。
第一次配置时,请按这个顺序来:
diff --git a/docs/plans/telegram-topic-settings.md b/docs/plans/telegram-topic-settings.md
new file mode 100644
index 000000000..57b9ff34a
--- /dev/null
+++ b/docs/plans/telegram-topic-settings.md
@@ -0,0 +1,87 @@
+# Telegram Topic Settings
+
+## Background
+
+Telegram forum messages already carry `message_thread_id` through
+`MessageContext.thread_id`, so replies and Agent Sessions are isolated by topic.
+Persistent settings, authorization, routing, and the Web UI still resolve only
+the parent chat, which prevents operators from enabling and configuring selected
+topics independently.
+
+## Goal
+
+Make a Telegram forum topic a first-class child settings scope. An explicitly
+configured topic must be able to override the parent group's access, mention,
+binding, Agent routing, working directory, and message visibility settings.
+Topics without an override continue to inherit the group unchanged.
+
+## Design
+
+### Scope model
+
+- Persist topics as `scopes.scope_type = "thread"`.
+- Use `<chat_id>/<message_thread_id>` as the thread scope's native ID because a
+ Telegram topic ID is unique only inside its chat.
+- Set `parent_scope_id` to the Telegram channel scope.
+- Store discovered topic names and Telegram IDs in scope metadata.
+- Treat Telegram General as topic ID `1` for settings resolution without
+ changing the existing outbound/session behavior when Telegram omits the ID.
+
+### Precedence
+
+1. DMs continue to use bound-user settings.
+2. A forum topic with an explicit thread setting uses that complete setting.
+3. A forum topic without an explicit setting uses its parent channel setting.
+4. Non-forum groups continue to use channel settings.
+
+Creating an override snapshots the parent's effective channel settings. Removing
+the override restores inheritance. This makes `group disabled + selected topic
+enabled` and `group enabled + selected topic disabled` both possible without
+introducing field-level inheritance ambiguity.
+
+### Runtime resolution
+
+Use one context-aware settings key/resolver for mention policy, authorization,
+message visibility, cwd, and Agent routing. Keep the existing channel-based
+session key stable; topic identity remains the session anchor.
+
+### Topic identity contract
+
+The logical topic identity is always `(chat_id, topic_id)`. Telegram General is
+topic `1` even when inbound and outbound Bot API payloads omit
+`message_thread_id`.
+
+- persisted thread scope native ID: `<chat_id>/<topic_id>`
+- runtime settings key: `thread::<chat_id>::<topic_id>`
+- explicit delivery key: `telegram::channel::<chat_id>::thread::<topic_id>`
+- runtime session anchor: `telegram_<chat_id>_<topic_id>`
+
+Session-ID targeting must map a persisted thread scope back to its parent
+channel plus topic delivery key. Existing `telegram_<topic_id>` session anchors
+are compatibility inputs only and migrate to the scoped anchor on first use so
+native backend history is preserved without retaining cross-chat collisions.
+
+### Discovery and API
+
+Telegram cannot list all forum topics. Discover topics passively from inbound
+messages and topic service events, and include them under forum chats returned by
+the Telegram discovery API. Add focused thread-setting mutation endpoints so a
+single topic save never replaces the platform's full channel map.
+
+### UI
+
+Forum group rows expose a nested Topics section. Each topic shows whether it
+inherits the group or has a custom override. Operators can customize, disable,
+or reset a topic while reusing the existing routing configuration panel.
+
+## Tracker
+
+- [x] Add thread scope state and SQLite round-trip support.
+- [x] Add Telegram topic discovery and General-topic normalization.
+- [x] Add context-aware effective settings resolution.
+- [x] Apply thread settings to mention, auth, routing, cwd, and visibility.
+- [x] Add topic settings API endpoints.
+- [x] Add nested topic settings UI and translations.
+- [x] Add unit, API, scenario, and UI coverage.
+- [x] Update Telegram setup documentation.
+- [x] Capture a browser-verified screenshot.
diff --git a/modules/agents/base.py b/modules/agents/base.py
index fbb13a85b..34364cb34 100644
--- a/modules/agents/base.py
+++ b/modules/agents/base.py
@@ -11,6 +11,7 @@ from typing import Any, Callable, Dict, List, Optional
from modules.im import MessageContext
from modules.im.base import FileAttachment
+from core.agent_session_context import resolve_context_agent_session_target
from core.message_output import MessageOutput, terminal_turn_output
from core.reply_enhancer import strip_silent_blocks
@@ -211,40 +212,34 @@ class BaseAgent(ABC):
@staticmethod
def _reserved_agent_session_id(context: Any) -> Optional[str]:
- """The open Chat session's ``agent_sessions`` PK reserved for an avibe turn.
-
- avibe dispatch stamps ``platform_specific['agent_session_target']['id']``;
- IM/CLI turns have no target. Used to keep Claude/Codex replies attributed to
- the open Chat session instead of a freshly-minted hidden row (Codex P1)."""
- payload = getattr(context, "platform_specific", None) or {}
- target = payload.get("agent_session_target")
- if isinstance(target, dict) and target.get("id"):
+ """Return the persisted ``agent_sessions`` row selected for this turn.
+
+ Workbench dispatch carries an explicit ``agent_session_target`` while
+ ordinary IM turns carry the row selected by ``agent_run_target``. Both
+ must bind by primary key so backend state and mirrored replies stay on
+ the same row."""
+ target = resolve_context_agent_session_target(context)
+ if target and target.get("id"):
reserved = str(target["id"]).strip()
return reserved or None
return None
@staticmethod
def _reserved_native_session_id(context: Any, backend: Optional[str] = None) -> Optional[str]:
- """The backend-native session id last bound to the RESERVED workbench row.
-
- avibe dispatch carries it in
- ``platform_specific['agent_session_target']['native_session_id']`` (read
- from the ``agent_sessions`` row by its PK). Resuming from THIS — rather
- than the ``(session_key, anchor)`` projection — keeps the resume READ on
- the same key as the by-PK bind WRITE (``_bind_reserved_workbench_session``),
- so a controller restart resumes the SAME native session instead of forking
- a fresh one and losing context. Empty until the first turn captures a
- native; ``None`` for IM/CLI turns (no reserved target). Mirrors
- ``_reserved_agent_session_id``.
+ """The backend-native session id last bound to the selected session row.
+
+ The selected row may be an explicit Workbench target or an IM/CLI run
+ target. Resuming from its native id keeps the resume read on the same key
+ as the by-PK bind write, so a controller restart does not fork a fresh
+ backend session.
``backend``: when given, only return the native if the reserved row's
``agent_backend`` matches — after a header backend switch the row still
carries the previous backend's native, and handing e.g. a Claude id to
Codex would fail to resume; in that case return ``None`` so the newly
selected backend starts its own first thread for this Chat."""
- payload = getattr(context, "platform_specific", None) or {}
- target = payload.get("agent_session_target")
- if not isinstance(target, dict):
+ target = resolve_context_agent_session_target(context)
+ if not target:
return None
native = str(target.get("native_session_id") or "").strip()
if not native:
@@ -282,15 +277,11 @@ class BaseAgent(ABC):
vibe_agent_name: Optional[str] = None,
vibe_agent_backend: Optional[str] = None,
) -> Optional[str]:
- """Bind the backend-native id to the RESERVED workbench session row, by id.
-
- Claude/Codex must bind the native session to the reserved workbench row
- (like OpenCode's ``bind_agent_session_by_id``) instead of letting the
- generic ``bind_agent_session`` mint a fresh row and overwrite
- ``agent_session_id`` — otherwise ``persist_agent_message`` would publish
- ``message.new`` under the new hidden id and the reply would never reach the
- open Chat page (Codex P1). Returns the reserved id when this is an avibe
- turn (so the caller skips its normal binder), else ``None``.
+ """Bind the backend-native id to the selected persisted session row.
+
+ Claude/Codex use the same by-ID binding path for explicit Workbench
+ targets and resolved IM run targets. This prevents the generic
+ ``(session_key, anchor)`` binder from creating a second row.
"""
if self._uses_namespaced_backend_session(context):
return None
diff --git a/modules/agents/opencode/session.py b/modules/agents/opencode/session.py
index cbfc4282d..3f447f1bd 100644
--- a/modules/agents/opencode/session.py
+++ b/modules/agents/opencode/session.py
@@ -94,13 +94,7 @@ class OpenCodeSessionManager:
request.context.platform_specific = payload
def _reserved_agent_session_id(self, request: AgentRequest) -> Optional[str]:
- payload = request.context.platform_specific or {}
- session_target = payload.get("agent_session_target")
- if isinstance(session_target, dict):
- target_id = str(session_target.get("id") or "").strip()
- if target_id:
- return target_id
- return None
+ return BaseAgent._reserved_agent_session_id(request.context)
async def _resolve_running_fork_point(
self,
diff --git a/modules/im/base.py b/modules/im/base.py
index ed1fd0e45..465dbcb92 100644
--- a/modules/im/base.py
+++ b/modules/im/base.py
@@ -271,6 +271,7 @@ class BaseIMClient(ABC):
*,
user_id: str,
channel_id: str,
+ thread_id: Optional[str] = None,
is_dm: bool,
text: str = "",
action: str = "",
@@ -288,6 +289,7 @@ class BaseIMClient(ABC):
return check_auth(
user_id=user_id,
channel_id=channel_id,
+ thread_id=thread_id,
is_dm=is_dm,
platform=getattr(settings_manager, "platform", None),
action=resolved_action,
diff --git a/modules/im/telegram.py b/modules/im/telegram.py
index dce2d894a..6e5553c30 100644
--- a/modules/im/telegram.py
+++ b/modules/im/telegram.py
@@ -13,6 +13,7 @@ from typing import Any, Callable, Dict, Optional
from config.v2_config import TelegramConfig
from core import chat_discovery
+from core.message_context import resolve_context_scope_settings_key, resolve_context_thread_id
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
@@ -36,12 +37,14 @@ class _TelegramResumeSessionState:
message_id: str
options: list[tuple[str, str]]
is_dm: bool
+ thread_id: Optional[str]
@dataclass
class _TelegramRoutingState:
message_id: str
channel_id: str
+ thread_id: Optional[str]
user_id: str
is_dm: bool
registered_backends: list[str]
@@ -82,6 +85,7 @@ class _TelegramSettingsState:
global_require_mention: bool
current_language: str
is_dm: bool
+ thread_id: Optional[str]
@dataclass
@@ -421,15 +425,7 @@ class TelegramBot(BaseIMClient):
explicitly_addressed = self._is_explicitly_addressed(message, text)
- effective_require_mention = self.config.require_mention
- if self.settings_manager is not None and not context.platform_specific.get("is_dm", False):
- try:
- effective_require_mention = self.settings_manager.get_require_mention(
- context.channel_id,
- global_default=self.config.require_mention,
- )
- except Exception:
- logger.debug("Failed to resolve Telegram effective require_mention", exc_info=True)
+ effective_require_mention = self._effective_require_mention(context)
text = self._strip_leading_bot_mention(message, text)
@@ -443,6 +439,7 @@ class TelegramBot(BaseIMClient):
denial = self.check_authorization(
user_id=context.user_id,
channel_id=context.channel_id,
+ thread_id=resolve_context_thread_id(context),
is_dm=bool(context.platform_specific.get("is_dm")),
text=text,
settings_manager=self.settings_manager,
@@ -461,10 +458,46 @@ class TelegramBot(BaseIMClient):
if await self.dispatch_text_command(context, text, allow_plain_bind=allow_plain_bind):
return
+ original_thread_id = resolve_context_thread_id(context)
context = await self._maybe_route_to_forum_topic(context, message, text)
+ if resolve_context_thread_id(context) != original_thread_id:
+ if (
+ self._effective_require_mention(context)
+ and not context.platform_specific.get("is_dm", False)
+ and not explicitly_addressed
+ ):
+ return
+ denial = self.check_authorization(
+ user_id=context.user_id,
+ channel_id=context.channel_id,
+ thread_id=resolve_context_thread_id(context),
+ is_dm=bool(context.platform_specific.get("is_dm")),
+ text=text,
+ settings_manager=self.settings_manager,
+ )
+ if not denial.allowed:
+ denial_text = self.build_auth_denial_text(denial.denial, context.channel_id)
+ if denial_text:
+ await self.send_message(context, denial_text)
+ return
await self._spawn_message_callback_task(context, text)
+ def _effective_require_mention(self, context: MessageContext) -> bool:
+ effective = self.config.require_mention
+ if self.settings_manager is None or context.platform_specific.get("is_dm", False):
+ return bool(effective)
+ try:
+ return bool(
+ self.settings_manager.get_require_mention(
+ resolve_context_scope_settings_key(context),
+ global_default=self.config.require_mention,
+ )
+ )
+ except Exception:
+ logger.debug("Failed to resolve Telegram effective require_mention", exc_info=True)
+ return bool(effective)
+
async def _maybe_route_to_forum_topic(
self,
context: MessageContext,
@@ -551,6 +584,15 @@ class TelegramBot(BaseIMClient):
if topic_id is None:
raise RuntimeError("Telegram createForumTopic returned no message_thread_id")
+ chat_discovery.remember_thread(
+ "telegram",
+ context.channel_id,
+ str(topic_id),
+ name=topic_name,
+ native_type="forum_topic",
+ metadata={"auto_created": True, "is_general": False},
+ )
+
topic_context = MessageContext(
user_id=context.user_id,
channel_id=context.channel_id,
@@ -597,6 +639,7 @@ class TelegramBot(BaseIMClient):
"is_dm": chat.get("type") == "private",
"chat_type": chat.get("type"),
"chat_title": chat.get("title") or chat.get("username"),
+ "is_forum": bool(chat.get("is_forum")) or bool(message.get("is_topic_message")),
"is_topic_message": bool(message.get("is_topic_message")),
"raw_message": message,
},
@@ -614,6 +657,7 @@ class TelegramBot(BaseIMClient):
auth_result = self.check_authorization(
user_id=context.user_id,
channel_id=context.channel_id,
+ thread_id=resolve_context_thread_id(context),
is_dm=bool(context.platform_specific.get("is_dm")),
action=primary_action,
settings_manager=self.settings_manager,
@@ -633,6 +677,7 @@ class TelegramBot(BaseIMClient):
auth_result = self.check_authorization(
user_id=context.user_id,
channel_id=context.channel_id,
+ thread_id=resolve_context_thread_id(context),
is_dm=bool(context.platform_specific.get("is_dm")),
action=primary_action,
settings_manager=self.settings_manager,
@@ -716,6 +761,21 @@ class TelegramBot(BaseIMClient):
chat_discovery.METADATA_SUPPORTS_TOPICS: chat_type == "supergroup" and is_forum,
},
)
+ topic_id = (message or {}).get("message_thread_id")
+ if topic_id is None and is_forum:
+ topic_id = 1
+ if topic_id is not None and is_forum:
+ created = (message or {}).get("forum_topic_created") or {}
+ edited = (message or {}).get("forum_topic_edited") or {}
+ topic_name = created.get("name") or edited.get("name") or ""
+ chat_discovery.remember_thread(
+ "telegram",
+ str(chat.get("id")),
+ str(topic_id),
+ name=str(topic_name or ""),
+ native_type="forum_topic",
+ metadata={"is_general": str(topic_id) == "1"},
+ )
except Exception:
logger.debug("Failed to remember Telegram discovered chat", exc_info=True)
@@ -832,7 +892,9 @@ class TelegramBot(BaseIMClient):
payload = context.platform_specific or {}
is_dm = bool(payload.get("is_dm"))
scope = context.user_id if is_dm else context.channel_id
- return f"{scope}:{context.user_id}"
+ thread_id = resolve_context_thread_id(context)
+ thread_suffix = f":{thread_id}" if not is_dm and thread_id is not None else ""
+ return f"{scope}:{context.user_id}{thread_suffix}"
async def _consume_cwd_prompt(self, context: MessageContext, text: str) -> bool:
prompt = self._cwd_prompts.get(self._interaction_scope_key(context))
@@ -1498,6 +1560,7 @@ class TelegramBot(BaseIMClient):
message_id=message_id,
options=options,
is_dm=bool((context.platform_specific or {}).get("is_dm")),
+ thread_id=resolve_context_thread_id(context),
)
async def _handle_resume_callback(self, context: MessageContext, callback_data: str) -> None:
@@ -1526,7 +1589,7 @@ class TelegramBot(BaseIMClient):
await self._controller.session_handler.handle_resume_session_submission(
user_id=context.user_id,
channel_id=context.channel_id,
- thread_id=context.thread_id,
+ thread_id=getattr(state, "thread_id", resolve_context_thread_id(context)),
agent=agent,
session_id=session_id,
is_dm=state.is_dm,
@@ -1545,6 +1608,7 @@ class TelegramBot(BaseIMClient):
state = _TelegramRoutingState(
message_id="",
channel_id=channel_id,
+ thread_id=resolve_context_thread_id(context),
user_id=context.user_id,
is_dm=bool((context.platform_specific or {}).get("is_dm")),
registered_backends=list(kwargs.get("registered_backends") or []),
@@ -1762,6 +1826,7 @@ class TelegramBot(BaseIMClient):
auth_result = self.check_authorization(
user_id=context.user_id,
channel_id=context.channel_id,
+ thread_id=resolve_context_thread_id(context),
is_dm=bool((context.platform_specific or {}).get("is_dm")),
action=state.callback_prefix,
settings_manager=self.settings_manager,
@@ -2082,21 +2147,25 @@ class TelegramBot(BaseIMClient):
await self.send_message(context, f"❌ {self._t('error.routingModalFailed')}")
return
await self._delete_interaction_message(context, state.message_id)
- await self._controller.settings_handler.handle_routing_update(
- user_id=state.user_id,
- channel_id=state.channel_id,
- backend=state.backend,
- opencode_agent=state.opencode_agent,
- opencode_model=state.opencode_model,
- opencode_reasoning_effort=state.opencode_reasoning_effort,
- claude_agent=state.claude_agent,
- claude_model=state.claude_model,
- claude_reasoning_effort=state.claude_reasoning_effort,
- codex_model=state.codex_model,
- codex_reasoning_effort=state.codex_reasoning_effort,
- is_dm=state.is_dm,
- platform="telegram",
- )
+ routing_update = {
+ "user_id": state.user_id,
+ "channel_id": state.channel_id,
+ "backend": state.backend,
+ "opencode_agent": state.opencode_agent,
+ "opencode_model": state.opencode_model,
+ "opencode_reasoning_effort": state.opencode_reasoning_effort,
+ "claude_agent": state.claude_agent,
+ "claude_model": state.claude_model,
+ "claude_reasoning_effort": state.claude_reasoning_effort,
+ "codex_model": state.codex_model,
+ "codex_reasoning_effort": state.codex_reasoning_effort,
+ "is_dm": state.is_dm,
+ "platform": "telegram",
+ }
+ state_thread_id = getattr(state, "thread_id", None)
+ if state_thread_id is not None:
+ routing_update["thread_id"] = state_thread_id
+ await self._controller.settings_handler.handle_routing_update(**routing_update)
return
if action == "back":
state.picker_field = None
@@ -2158,6 +2227,7 @@ class TelegramBot(BaseIMClient):
global_require_mention=global_require_mention,
current_language=current_language or self._get_lang(),
is_dm=bool((context.platform_specific or {}).get("is_dm")),
+ thread_id=resolve_context_thread_id(context),
)
text, keyboard = self._render_settings_state(state, list(message_types or []))
message_id = await self.send_message_with_buttons(context, text, keyboard)
@@ -2274,16 +2344,20 @@ class TelegramBot(BaseIMClient):
await self.send_message(context, f"❌ {self._t('error.settingsFailed')}")
return
await self._delete_interaction_message(context, state.message_id)
- await self._controller.settings_handler.handle_settings_update(
- user_id=context.user_id,
- show_message_types=state.show_message_types,
- channel_id=context.channel_id,
- require_mention=state.current_require_mention,
- language=state.current_language,
- notify_user=True,
- is_dm=state.is_dm,
- platform="telegram",
- )
+ settings_update = {
+ "user_id": context.user_id,
+ "show_message_types": state.show_message_types,
+ "channel_id": context.channel_id,
+ "require_mention": state.current_require_mention,
+ "language": state.current_language,
+ "notify_user": True,
+ "is_dm": state.is_dm,
+ "platform": "telegram",
+ }
+ state_thread_id = getattr(state, "thread_id", None)
+ if state_thread_id is not None:
+ settings_update["thread_id"] = state_thread_id
+ await self._controller.settings_handler.handle_settings_update(**settings_update)
return
if action == "toggle" and len(parts) > 2:
diff --git a/modules/settings_manager.py b/modules/settings_manager.py
index 0f8d2facf..bc2980313 100644
--- a/modules/settings_manager.py
+++ b/modules/settings_manager.py
@@ -7,7 +7,7 @@ from config import paths
from config.platform_registry import get_platform_descriptor
from config.v2_sessions import SessionsStore
from config.v2_settings import SettingsStore, ChannelSettings, GuildSettings, RoutingSettings, SCOPED_KEY_SEP
-from config.v2_settings import normalize_routing_settings
+from config.v2_settings import normalize_routing_settings, split_thread_settings_key
from config.v2_settings import UserSettings as BoundUserSettings
from modules.sessions_facade import SessionsFacade
@@ -103,6 +103,10 @@ class SettingsManager:
paths.ensure_data_dirs()
self.settings_file = Path(settings_file) if settings_file else paths.get_settings_path()
self.platform = platform
+ # The controller replaces this with the live platform config during
+ # dependency injection. Keep standalone managers aligned with the
+ # built-in defaults before that happens.
+ self.require_mention_default = lambda: platform == "telegram"
self.channel_settings: Dict[str, UserSettings] = {}
self.dm_user_settings: Dict[str, UserSettings] = {}
self.store = SettingsStore.get_instance(self.settings_file)
@@ -266,6 +270,15 @@ class SettingsManager:
self._reload_if_changed()
+ thread_ref = split_thread_settings_key(normalized_id)
+ if thread_ref is not None:
+ channel_id, thread_id = thread_ref
+ thread = self.store.find_thread(channel_id, thread_id, platform=self.platform)
+ if thread is not None:
+ return self._from_channel_settings(thread)
+ parent = self.store.find_channel(channel_id, platform=self.platform)
+ return self._from_channel_settings(parent or ChannelSettings())
+
if normalized_id in self.dm_user_settings:
return self.dm_user_settings[normalized_id]
if normalized_id in self.channel_settings:
@@ -295,6 +308,23 @@ class SettingsManager:
settings.show_message_types = self._normalize_show_message_types(settings.show_message_types)
+ thread_ref = split_thread_settings_key(normalized_id)
+ if thread_ref is not None:
+ channel_id, thread_id = thread_ref
+ existing_thread = self.store.find_thread(channel_id, thread_id, platform=self.platform)
+ existing = existing_thread
+ if existing_thread is None:
+ existing = self.store.find_channel(channel_id, platform=self.platform)
+ updated = self._to_channel_settings(settings)
+ if existing is not None:
+ updated.require_mention = existing.require_mention
+ updated.require_bind = existing.require_bind
+ if existing_thread is None and updated.require_mention is None:
+ updated.require_mention = bool(self.require_mention_default())
+ self.store.update_thread(channel_id, thread_id, updated, platform=self.platform)
+ self._last_seen_store_mtime = self.store._file_mtime
+ return
+
if normalized_id in self.dm_user_settings:
self.dm_user_settings[normalized_id] = settings
elif normalized_id in self.channel_settings:
@@ -335,6 +365,14 @@ class SettingsManager:
"""Get raw ChannelSettings for a channel without creating defaults."""
self._reload_if_changed()
key = str(channel_id)
+ thread_ref = split_thread_settings_key(key)
+ if thread_ref is not None:
+ parent_id, thread_id = thread_ref
+ return self.store.find_effective_channel(
+ parent_id,
+ thread_id=thread_id,
+ platform=self.platform,
+ )
return self.store.get_channels_for_platform(self.platform).get(key)
def has_guild_scope(self) -> bool:
@@ -466,7 +504,16 @@ class SettingsManager:
"""
self._reload_if_changed()
key = str(channel_id)
- channel_settings = self.store.get_channels_for_platform(self.platform).get(key)
+ thread_ref = split_thread_settings_key(key)
+ if thread_ref is not None:
+ parent_id, thread_id = thread_ref
+ channel_settings = self.store.find_effective_channel(
+ parent_id,
+ thread_id=thread_id,
+ platform=self.platform,
+ )
+ else:
+ channel_settings = self.store.get_channels_for_platform(self.platform).get(key)
if channel_settings is not None and channel_settings.require_mention is not None:
return channel_settings.require_mention
@@ -481,6 +528,24 @@ class SettingsManager:
value: True=require mention, False=don't require, None=use global default
"""
key = str(channel_id)
+ thread_ref = split_thread_settings_key(key)
+ if thread_ref is not None:
+ parent_id, thread_id = thread_ref
+ channel_settings = self.store.find_thread(parent_id, thread_id, platform=self.platform)
+ if channel_settings is None:
+ parent = self.store.find_channel(parent_id, platform=self.platform)
+ channel_settings = ChannelSettings(**vars(parent)) if parent is not None else ChannelSettings()
+ if value is None:
+ value = (
+ parent.require_mention
+ if parent is not None and parent.require_mention is not None
+ else bool(self.require_mention_default())
+ )
+ channel_settings.require_mention = value
+ self.store.update_thread(parent_id, thread_id, channel_settings, platform=self.platform)
+ self._last_seen_store_mtime = self.store._file_mtime
+ logger.info("Updated require_mention for thread %s/%s: %s", parent_id, thread_id, value)
+ return
channel_settings = self.store.get_channel(key, platform=self.platform)
channel_settings.require_mention = value
self.store.update_channel(key, channel_settings, platform=self.platform)
@@ -490,7 +555,14 @@ class SettingsManager:
"""Get the raw per-channel require_mention override (may be None)."""
self._reload_if_changed()
key = str(channel_id)
- channel_settings = self.store.get_channels_for_platform(self.platform).get(key)
+ thread_ref = split_thread_settings_key(key)
+ if thread_ref is not None:
+ parent_id, thread_id = thread_ref
+ channel_settings = self.store.find_thread(parent_id, thread_id, platform=self.platform)
+ if channel_settings is None:
+ channel_settings = self.store.find_channel(parent_id, platform=self.platform)
+ else:
+ channel_settings = self.store.get_channels_for_platform(self.platform).get(key)
if channel_settings is not None:
return channel_settings.require_mention
return None
diff --git a/output/playwright/telegram-topic-settings.png b/output/playwright/telegram-topic-settings.png
new file mode 100644
index 000000000..1c3466b41
Binary files /dev/null and b/output/playwright/telegram-topic-settings.png differ
diff --git a/storage/settings_service.py b/storage/settings_service.py
index 2bcf4d82a..098c2f31e 100644
--- a/storage/settings_service.py
+++ b/storage/settings_service.py
@@ -18,8 +18,10 @@ from config.v2_settings import (
UserSettings,
_make_scoped_key,
_split_scoped_key,
+ make_thread_native_id,
normalize_routing_settings,
normalize_show_message_types,
+ split_thread_native_id,
)
from storage.db import SqliteInvalidationProbe, create_sqlite_engine
from storage.models import auth_codes, scope_settings, scopes
@@ -29,7 +31,7 @@ GUILD_POLICY_KIND = "guild_policy"
# Scope types whose settings this store owns. avibe project scopes
# (storage.projects_service) share the scope_settings table but are NOT managed
# here, so save_state must never delete or overwrite their rows.
-_MANAGED_SCOPE_TYPES = ("channel", "platform", "guild", "user")
+_MANAGED_SCOPE_TYPES = ("channel", "thread", "platform", "guild", "user")
class SQLiteSettingsService:
@@ -49,6 +51,7 @@ class SQLiteSettingsService:
with self.engine.connect() as conn:
return SettingsState(
channels=self._load_channels(conn),
+ threads=self._load_threads(conn),
guilds=self._load_guilds(conn),
guild_scope_platforms=self._load_guild_scope_platforms(conn),
guild_default_enabled=self._load_guild_policies(conn),
@@ -91,6 +94,48 @@ class SQLiteSettingsService:
)
kept.add(scope_id)
+ for scoped_key, item in state.threads.items():
+ platform, native_id = _split_scoped_key(scoped_key)
+ channel_id, thread_id = split_thread_native_id(native_id)
+ resolved_platform = platform or "unknown"
+ parent_scope_id = upsert_scope(
+ conn,
+ resolved_platform,
+ "channel",
+ channel_id,
+ now=now,
+ )
+ scope_id = upsert_scope(
+ conn,
+ resolved_platform,
+ "thread",
+ make_thread_native_id(channel_id, thread_id),
+ parent_scope_id=parent_scope_id,
+ native_type="forum_topic" if resolved_platform == "telegram" else "thread",
+ now=now,
+ )
+ routing = asdict(item.routing)
+ self._upsert_scope_settings(
+ conn,
+ scope_id=scope_id,
+ enabled=_bool_int(item.enabled),
+ role=None,
+ workdir=item.custom_cwd,
+ require_mention=_nullable_bool_int(item.require_mention),
+ settings_json=_json_dumps(
+ {
+ "show_message_types": normalize_show_message_types(item.show_message_types),
+ "routing": routing,
+ "require_bind": item.require_bind,
+ }
+ ),
+ created_at=now,
+ updated_at=now,
+ settings_version=SETTINGS_VERSION,
+ **_routing_columns(item.routing),
+ )
+ kept.add(scope_id)
+
for platform in sorted(state.guild_scope_platforms):
scope_id = upsert_scope(conn, platform, "platform", platform, now=now)
self._upsert_scope_settings(
@@ -242,6 +287,27 @@ class SQLiteSettingsService:
)
return result
+ def _load_threads(self, conn: Connection) -> dict[str, ChannelSettings]:
+ rows = _settings_rows(conn, "thread")
+ result: dict[str, ChannelSettings] = {}
+ for row in rows:
+ payload = _json_loads(row["settings_json"], {})
+ native_id = str(row["native_id"])
+ try:
+ split_thread_native_id(native_id)
+ except ValueError:
+ continue
+ key = _make_scoped_key(str(row["platform"]), native_id)
+ result[key] = ChannelSettings(
+ enabled=bool(row["enabled"]),
+ show_message_types=normalize_show_message_types(_json_list(payload.get("show_message_types"))),
+ custom_cwd=row["workdir"],
+ routing=_routing_from_row(row, payload),
+ require_mention=_nullable_bool(row["require_mention"]),
+ require_bind=payload.get("require_bind"),
+ )
+ return result
+
def _load_guilds(self, conn: Connection) -> dict[str, GuildSettings]:
rows = _settings_rows(conn, "guild")
result: dict[str, GuildSettings] = {}
diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yaml
index 6c7b1373b..0411dae30 100644
--- a/tests/scenarios/INDEX.yaml
+++ b/tests/scenarios/INDEX.yaml
@@ -60,3 +60,15 @@ capabilities:
- tests/test_tunnel_recovery.py
unit_or_contract_tests:
- tests/test_remote_access_vibe_cloud.py
+ - id: telegram_topic_routing
+ name: Telegram forum topic settings and routing
+ status: active
+ catalog: tests/scenarios/telegram_topic_routing/catalog.yaml
+ observations: tests/scenarios/telegram_topic_routing/observations.yaml
+ scenario_tests:
+ - tests/test_ui_api.py
+ - tests/test_auth_pipeline.py
+ - tests/test_agent_run_target.py
+ unit_or_contract_tests:
+ - tests/test_sqlite_settings_store.py
+ - tests/test_chat_discovery.py
diff --git a/tests/scenarios/telegram_topic_routing/catalog.yaml b/tests/scenarios/telegram_topic_routing/catalog.yaml
new file mode 100644
index 000000000..91d23b4ec
--- /dev/null
+++ b/tests/scenarios/telegram_topic_routing/catalog.yaml
@@ -0,0 +1,36 @@
+version: 1
+capability:
+ id: telegram_topic_routing
+ name: Telegram forum topic settings and routing
+ canonical_tests:
+ - tests/test_ui_api.py
+ - tests/test_auth_pipeline.py
+ - tests/test_agent_run_target.py
+status_legend:
+ covered: automated scenario or contract coverage exists
+ manual: currently validated by human regression
+scenarios:
+ - id: TELEGRAM-TOPIC-001
+ name: A topic override controls mention, bound-only, agent, and message-type settings
+ status: covered
+ kind: happy_path
+ layer: contract
+ test: tests/test_ui_api.py::test_telegram_topic_settings_api_and_discovery_payload
+ - id: TELEGRAM-TOPIC-002
+ name: An unconfigured topic inherits its parent group while a configured topic wins
+ status: covered
+ kind: fallback
+ layer: contract
+ test: tests/test_auth_pipeline.py::test_telegram_thread_auth_uses_topic_override_before_parent
+ - id: TELEGRAM-TOPIC-003
+ name: Agent workdir and routing resolve from the topic scope before the group scope
+ status: covered
+ kind: routing
+ layer: contract
+ test: tests/test_agent_run_target.py::test_telegram_topic_scope_workdir_wins_over_group
+ - id: TELEGRAM-TOPIC-004
+ name: Discovered forum topics can be customized and reset from Group Settings
+ status: manual
+ kind: ui
+ layer: manual
+ evidence: output/playwright/telegram-topic-settings.png
diff --git a/tests/scenarios/telegram_topic_routing/observations.yaml b/tests/scenarios/telegram_topic_routing/observations.yaml
new file mode 100644
index 000000000..b2c6a8ad4
--- /dev/null
+++ b/tests/scenarios/telegram_topic_routing/observations.yaml
@@ -0,0 +1,22 @@
+version: 1
+capability: telegram_topic_routing
+observations:
+ - id: OBS-TELEGRAM-TOPIC-001
+ source: telegram_bot_api_contract
+ related_scenarios:
+ - TELEGRAM-TOPIC-001
+ - TELEGRAM-TOPIC-004
+ summary: Telegram does not expose a complete list of forum topics to bots.
+ required_updates:
+ - discover topics passively from inbound messages
+ - keep undiscovered topics on the parent group fallback
+ - represent General as topic ID 1 when Telegram omits message_thread_id
+ - id: OBS-TELEGRAM-TOPIC-002
+ source: architecture_review
+ related_scenarios:
+ - TELEGRAM-TOPIC-002
+ - TELEGRAM-TOPIC-003
+ summary: Topic settings and conversation identity are separate concerns.
+ required_updates:
+ - resolve settings from thread then channel
+ - preserve the existing group session key and Telegram reply anchor
diff --git a/tests/test_agent_auth_service.py b/tests/test_agent_auth_service.py
index d63ab969a..91628b5fa 100644
--- a/tests/test_agent_auth_service.py
+++ b/tests/test_agent_auth_service.py
@@ -550,6 +550,43 @@ class AgentAuthServiceTests(_IsolatedClaudeConfigDirMixin, unittest.IsolatedAsyn
self.assertEqual(provider, "openai")
mock_server.list_messages.assert_awaited_once_with("ses-existing", "/tmp/workdir")
+ async def test_resolve_opencode_provider_in_topic_uses_runtime_session_key(self):
+ controller = _StubController()
+ controller._get_settings_key = Mock(return_value="thread::-1001::42")
+ controller._get_session_key = Mock(return_value="telegram::-1001")
+ controller.sessions = SimpleNamespace(get_agent_session_id=Mock(return_value="ses-existing"))
+ mock_server = SimpleNamespace(
+ list_messages=AsyncMock(
+ return_value=[
+ {"info": {"role": "assistant", "providerID": "openai", "modelID": "gpt-5.3-chat-latest"}}
+ ]
+ ),
+ get_default_agent_from_config=lambda: "build",
+ get_agent_model_from_config=lambda agent_name: None,
+ )
+ controller.agent_service = SimpleNamespace(
+ agents={"opencode": SimpleNamespace(_get_server=AsyncMock(return_value=mock_server))}
+ )
+ service = AgentAuthService(controller)
+ context = MessageContext(
+ user_id="7",
+ channel_id="-1001",
+ thread_id="42",
+ platform="telegram",
+ platform_specific={"is_forum": True, "is_topic_message": True},
+ )
+
+ provider = await service._resolve_opencode_provider(context)
+
+ self.assertEqual(provider, "openai")
+ controller._get_session_key.assert_called_once_with(context)
+ controller.sessions.get_agent_session_id.assert_called_once_with(
+ "telegram::-1001",
+ "base-1:/tmp/workdir",
+ "opencode",
+ )
+ controller._get_settings_key.assert_not_called()
+
async def test_handle_process_text_emits_opencode_device_flow_for_openai(self):
controller = _StubController()
service = AgentAuthService(controller)
@@ -1232,6 +1269,27 @@ class AgentAuthServiceTests(_IsolatedClaudeConfigDirMixin, unittest.IsolatedAsyn
controller.agent_service.clear_backend_sessions.assert_awaited_once_with("codex", "C1")
controller.agent_service.agents["codex"].clear_sessions.assert_not_awaited()
+ async def test_clear_backend_sessions_for_topic_uses_runtime_session_key(self):
+ controller = _StubController()
+ controller._get_session_key = Mock(return_value="telegram::-1001")
+ controller.agent_service.clear_backend_sessions = AsyncMock(return_value=1)
+ service = AgentAuthService(controller)
+ context = MessageContext(
+ user_id="7",
+ channel_id="-1001",
+ thread_id="42",
+ platform="telegram",
+ platform_specific={"is_forum": True, "is_topic_message": True},
+ )
+
+ await service._clear_backend_sessions_for_context("opencode", context)
+
+ controller._get_session_key.assert_called_once_with(context)
+ controller.agent_service.clear_backend_sessions.assert_awaited_once_with(
+ "opencode",
+ "telegram::-1001",
+ )
+
async def test_refresh_backend_runtime_registers_codex_when_enabled_after_startup(self):
from config.v2_compat import CodexCompatConfig
from modules.agents.service import AgentService
diff --git a/tests/test_agent_run_target.py b/tests/test_agent_run_target.py
index a29341e8e..f87df5869 100644
--- a/tests/test_agent_run_target.py
+++ b/tests/test_agent_run_target.py
@@ -5,6 +5,7 @@ from pathlib import Path
from types import SimpleNamespace
import pytest
+from sqlalchemy import select
from core.services import sessions as sessions_service
from core.services.agent_run_target import resolve_agent_run_target
@@ -15,6 +16,7 @@ from storage.importer import ensure_sqlite_state
from storage.models import agent_sessions, scope_settings
from storage.sessions_service import SQLiteSessionsService
from storage.settings_service import upsert_scope
+from config.v2_settings import make_thread_native_id
def _controller(tmp_path):
@@ -148,6 +150,222 @@ def test_im_channel_scope_workdir_creates_session_snapshot(tmp_path):
assert session["agent_variant"] == "codex"
+def test_telegram_topic_scope_workdir_wins_over_group(tmp_path):
+ # Scenario: TELEGRAM-TOPIC-003
+ controller = _controller(tmp_path)
+ group_workdir = tmp_path / "group"
+ topic_workdir = tmp_path / "topic"
+ with controller.sqlite_engine.begin() as conn:
+ group_scope_id = upsert_scope(
+ conn,
+ platform="telegram",
+ scope_type="channel",
+ native_id="-1001",
+ now="2026-06-04T05:00:00Z",
+ )
+ _seed_scope_settings(conn, group_scope_id, workdir=str(group_workdir))
+ topic_scope_id = upsert_scope(
+ conn,
+ platform="telegram",
+ scope_type="thread",
+ native_id=make_thread_native_id("-1001", "42"),
+ parent_scope_id=group_scope_id,
+ now="2026-06-04T05:00:00Z",
+ )
+ _seed_scope_settings(conn, topic_scope_id, workdir=str(topic_workdir))
+
+ ctx = MessageContext(
+ user_id="7",
+ channel_id="-1001",
+ thread_id="42",
+ platform="telegram",
+ platform_specific={"is_forum": True, "is_topic_message": True},
+ )
+ target = resolve_agent_run_target(ctx, controller=controller, base_session_id="telegram_topic_42")
+
+ assert target.scope_id == "telegram::thread::-1001/42"
+ assert target.workdir == str(topic_workdir)
+ assert target.agent_session_id
+ with controller.sqlite_engine.connect() as conn:
+ session = sessions_service.get_session(conn, target.agent_session_id)
+ assert session["workdir"] == str(topic_workdir)
+ assert session["agent_id"] == "agent-codex-default"
+ assert session["agent_name"] == "codex"
+ assert session["agent_backend"] == "codex"
+ assert session["agent_variant"] == "codex"
+
+
+def test_telegram_topic_override_reuses_parent_scoped_session(tmp_path):
+ # Scenario: TELEGRAM-TOPIC-003
+ controller = _controller(tmp_path)
+ group_workdir = tmp_path / "group"
+ topic_workdir = tmp_path / "topic"
+ with controller.sqlite_engine.begin() as conn:
+ group_scope_id = upsert_scope(
+ conn,
+ platform="telegram",
+ scope_type="channel",
+ native_id="-1001",
+ now="2026-06-04T05:00:00Z",
+ )
+ _seed_scope_settings(conn, group_scope_id, workdir=str(group_workdir))
+ topic_scope_id = upsert_scope(
+ conn,
+ platform="telegram",
+ scope_type="thread",
+ native_id=make_thread_native_id("-1001", "42"),
+ parent_scope_id=group_scope_id,
+ now="2026-06-04T05:00:00Z",
+ )
+ _seed_scope_settings(conn, topic_scope_id, workdir=str(topic_workdir))
+ session_id = create_agent_session_row(
+ conn,
+ scope_id=group_scope_id,
+ agent_backend="codex",
+ agent_variant="codex",
+ session_anchor="telegram_topic_42",
+ native_session_id="native-topic-session",
+ workdir=str(group_workdir),
+ )
+
+ ctx = MessageContext(
+ user_id="7",
+ channel_id="-1001",
+ thread_id="42",
+ platform="telegram",
+ platform_specific={"is_forum": True, "is_topic_message": True},
+ )
+ target = resolve_agent_run_target(ctx, controller=controller, base_session_id="telegram_topic_42")
+
+ assert target.agent_session_id == session_id
+ assert target.scope_id == "telegram::channel::-1001"
+ assert target.native_session_id == "native-topic-session"
+ assert target.workdir == str(group_workdir)
+
+
+def test_telegram_topic_override_removal_reuses_topic_scoped_session(tmp_path):
+ # Scenario: TELEGRAM-TOPIC-003
+ controller = _controller(tmp_path)
+ group_workdir = tmp_path / "group"
+ topic_workdir = tmp_path / "topic"
+ with controller.sqlite_engine.begin() as conn:
+ group_scope_id = upsert_scope(
+ conn,
+ platform="telegram",
+ scope_type="channel",
+ native_id="-1001",
+ now="2026-06-04T05:00:00Z",
+ )
+ _seed_scope_settings(conn, group_scope_id, workdir=str(group_workdir))
+ topic_scope_id = upsert_scope(
+ conn,
+ platform="telegram",
+ scope_type="thread",
+ native_id=make_thread_native_id("-1001", "42"),
+ parent_scope_id=group_scope_id,
+ now="2026-06-04T05:00:00Z",
+ )
+ session_id = create_agent_session_row(
+ conn,
+ scope_id=topic_scope_id,
+ agent_backend="codex",
+ agent_variant="codex",
+ session_anchor="telegram_topic_42",
+ native_session_id="native-topic-session",
+ workdir=str(topic_workdir),
+ )
+
+ ctx = MessageContext(
+ user_id="7",
+ channel_id="-1001",
+ thread_id="42",
+ platform="telegram",
+ platform_specific={"is_forum": True, "is_topic_message": True},
+ )
+ target = resolve_agent_run_target(ctx, controller=controller, base_session_id="telegram_topic_42")
+
+ assert target.agent_session_id == session_id
+ assert target.scope_id == "telegram::thread::-1001/42"
+ assert target.native_session_id == "native-topic-session"
+ assert target.workdir == str(topic_workdir)
+
+
+def test_telegram_general_topic_fallback_anchor_reuses_session(tmp_path):
+ # Scenario: TELEGRAM-TOPIC-003
+ controller = _controller(tmp_path)
+ group_workdir = tmp_path / "group"
+ with controller.sqlite_engine.begin() as conn:
+ group_scope_id = upsert_scope(
+ conn,
+ platform="telegram",
+ scope_type="channel",
+ native_id="-1001",
+ now="2026-06-04T05:00:00Z",
+ )
+ _seed_scope_settings(conn, group_scope_id, workdir=str(group_workdir))
+
+ def general_context(message_id: str) -> MessageContext:
+ return MessageContext(
+ user_id="7",
+ channel_id="-1001",
+ message_id=message_id,
+ platform="telegram",
+ platform_specific={"is_forum": True, "is_topic_message": True},
+ )
+
+ first = resolve_agent_run_target(general_context("100"), controller=controller)
+ follow_up = resolve_agent_run_target(general_context("101"), controller=controller)
+
+ assert first.session_anchor == "telegram_-1001_1"
+ assert follow_up.session_anchor == "telegram_-1001_1"
+ assert follow_up.agent_session_id == first.agent_session_id
+
+
+def test_telegram_topic_migrates_legacy_anchor_without_losing_native_session(tmp_path):
+ controller = _controller(tmp_path)
+ group_workdir = tmp_path / "group"
+ with controller.sqlite_engine.begin() as conn:
+ group_scope_id = upsert_scope(
+ conn,
+ platform="telegram",
+ scope_type="channel",
+ native_id="-1001",
+ now="2026-06-04T05:00:00Z",
+ )
+ _seed_scope_settings(conn, group_scope_id, workdir=str(group_workdir))
+ session_id = create_agent_session_row(
+ conn,
+ scope_id=group_scope_id,
+ agent_backend="codex",
+ agent_variant="codex",
+ session_anchor="telegram_42",
+ native_session_id="native-topic-session",
+ workdir=str(group_workdir),
+ )
+
+ context = MessageContext(
+ user_id="7",
+ channel_id="-1001",
+ thread_id="42",
+ platform="telegram",
+ platform_specific={"is_forum": True, "is_topic_message": True},
+ )
+ target = resolve_agent_run_target(
+ context,
+ controller=controller,
+ base_session_id="telegram_-1001_42",
+ )
+
+ assert target.agent_session_id == session_id
+ assert target.session_anchor == "telegram_-1001_42"
+ assert target.native_session_id == "native-topic-session"
+ with controller.sqlite_engine.connect() as conn:
+ migrated_anchor = conn.execute(
+ select(agent_sessions.c.session_anchor).where(agent_sessions.c.id == session_id)
+ ).scalar_one()
+ assert migrated_anchor == "telegram_-1001_42"
+
+
def test_existing_background_im_target_carries_visibility(tmp_path):
workdir = tmp_path / "channel"
controller = _controller(tmp_path)
diff --git a/tests/test_auth_pipeline.py b/tests/test_auth_pipeline.py
index d8604523b..7d45f29dd 100644
--- a/tests/test_auth_pipeline.py
+++ b/tests/test_auth_pipeline.py
@@ -180,6 +180,37 @@ def test_require_bind_off_allows_any_channel_member():
assert result.allowed is True
+def test_telegram_thread_auth_uses_topic_override_before_parent():
+ # Scenario: TELEGRAM-TOPIC-002
+ store = _Store()
+ parent = SimpleNamespace(enabled=True, require_bind=False)
+ topic = SimpleNamespace(enabled=True, require_bind=True)
+ store.settings.channels["-1001"] = parent
+ store.find_effective_channel = lambda channel_id, thread_id=None, platform=None: (
+ topic if channel_id == "-1001" and thread_id == "42" else parent
+ )
+
+ denied = check_auth(
+ user_id="U-stranger",
+ channel_id="-1001",
+ thread_id="42",
+ is_dm=False,
+ platform="telegram",
+ store=store,
+ )
+ inherited = check_auth(
+ user_id="U-stranger",
+ channel_id="-1001",
+ thread_id="99",
+ is_dm=False,
+ platform="telegram",
+ store=store,
+ )
+
+ assert denied.denial == "not_bound_channel"
+ assert inherited.allowed is True
+
+
def test_require_bind_null_allows_any_member_regardless_of_platform_default():
# Legacy channels store require_bind=None ("Anyone" in the old UI). The
# platform default is a copy-on-enable seed, NOT a runtime fallback, so a
diff --git a/tests/test_chat_discovery.py b/tests/test_chat_discovery.py
index 3c1acbd44..04759b117 100644
--- a/tests/test_chat_discovery.py
+++ b/tests/test_chat_discovery.py
@@ -69,6 +69,80 @@ def test_remember_chat_lists_inventory_with_configured_state(tmp_path: Path) ->
assert chats[0].visibility_status == chat_discovery.VISIBILITY_VISIBLE
+def test_remember_thread_lists_discovered_and_configured_topics(tmp_path: Path) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path)
+ chat_discovery.remember_chat(
+ "telegram",
+ "-1001",
+ name="Engineering",
+ native_type="supergroup",
+ supports_threads=True,
+ db_path=db_path,
+ )
+ chat_discovery.remember_thread(
+ "telegram",
+ "-1001",
+ "42",
+ name="Releases",
+ native_type="forum_topic",
+ db_path=db_path,
+ )
+
+ topics = chat_discovery.list_thread_payloads("telegram", "-1001", db_path=db_path)
+ assert [(topic["id"], topic["name"], topic["configured"]) for topic in topics] == [
+ ("42", "Releases", False)
+ ]
+
+ service = SQLiteSettingsService(db_path)
+ try:
+ service.save_state(
+ SettingsState(
+ threads={
+ "telegram::-1001/42": ChannelSettings(enabled=True, require_mention=False),
+ }
+ )
+ )
+ finally:
+ service.close()
+
+ topics = chat_discovery.list_thread_payloads("telegram", "-1001", db_path=db_path)
+ assert topics[0]["configured"] is True
+ assert topics[0]["name"] == "Releases"
+
+
+def test_passively_discovered_topics_leave_fallback_names_to_ui(tmp_path: Path) -> None:
+ # Scenario: TELEGRAM-TOPIC-004
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path)
+ chat_discovery.remember_chat(
+ "telegram",
+ "-1001",
+ name="Engineering",
+ native_type="supergroup",
+ supports_threads=True,
+ db_path=db_path,
+ )
+ chat_discovery.remember_thread(
+ "telegram",
+ "-1001",
+ "1",
+ native_type="forum_topic",
+ db_path=db_path,
+ )
+ chat_discovery.remember_thread(
+ "telegram",
+ "-1001",
+ "42",
+ native_type="forum_topic",
+ db_path=db_path,
+ )
+
+ topics = chat_discovery.list_thread_payloads("telegram", "-1001", db_path=db_path)
+
+ assert [(topic["id"], topic["name"]) for topic in topics] == [("1", ""), ("42", "")]
+
+
def test_remember_chat_debounce_does_not_suppress_retry_after_persist_failure(tmp_path: Path, monkeypatch) -> None:
db_path = tmp_path / "vibe.sqlite"
run_migrations(db_path)
@@ -775,6 +849,152 @@ def test_delete_scope_removes_scope_and_settings(tmp_path: Path) -> None:
}
+def test_delete_scope_cascades_child_thread_settings(tmp_path: Path) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path)
+ chat_discovery.remember_chat("telegram", "-1001", name="Forum", db_path=db_path)
+ chat_discovery.remember_thread(
+ "telegram",
+ "-1001",
+ "42",
+ name="Releases",
+ native_type="forum_topic",
+ db_path=db_path,
+ )
+ service = SQLiteSettingsService(db_path)
+ try:
+ service.save_state(
+ SettingsState(
+ channels={"telegram::-1001": ChannelSettings(enabled=True)},
+ threads={
+ "telegram::-1001/42": ChannelSettings(
+ enabled=True,
+ require_mention=False,
+ )
+ },
+ )
+ )
+ finally:
+ service.close()
+
+ outcome = chat_discovery.delete_scope("telegram", "-1001", db_path=db_path)
+
+ assert outcome == {"removed": True, "dismissed": False}
+ assert chat_discovery.list_chats("telegram", db_path=db_path) == []
+ assert chat_discovery.list_thread_payloads("telegram", "-1001", db_path=db_path) == []
+ reloaded = SQLiteSettingsService(db_path)
+ try:
+ state = reloaded.load_state()
+ assert "telegram::-1001" not in state.channels
+ assert "telegram::-1001/42" not in state.threads
+ finally:
+ reloaded.close()
+
+
+def test_delete_scope_preserves_child_thread_history(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", "-1001", name="Forum", db_path=db_path)
+ chat_discovery.remember_thread(
+ "telegram",
+ "-1001",
+ "42",
+ name="Releases",
+ native_type="forum_topic",
+ db_path=db_path,
+ )
+ service = SQLiteSettingsService(db_path)
+ try:
+ service.save_state(
+ SettingsState(
+ threads={
+ "telegram::-1001/42": ChannelSettings(enabled=True),
+ }
+ )
+ )
+ finally:
+ service.close()
+
+ thread_scope_id = chat_discovery.make_scope_id(
+ "telegram",
+ chat_discovery.THREAD_SCOPE_TYPE,
+ "-1001/42",
+ )
+ parent_scope_id = chat_discovery.make_scope_id(
+ "telegram",
+ chat_discovery.CHANNEL_SCOPE_TYPE,
+ "-1001",
+ )
+ now = datetime.now(timezone.utc).isoformat()
+ engine = chat_discovery._engine(db_path)
+ try:
+ with engine.begin() as conn:
+ conn.execute(
+ messages.insert(),
+ [
+ {
+ "id": "parent-message",
+ "scope_id": parent_scope_id,
+ "platform": "telegram",
+ "author": "user",
+ "type": "user",
+ "content_json": "{}",
+ "metadata_json": "{}",
+ "created_at": now,
+ "updated_at": now,
+ },
+ {
+ "id": "topic-message",
+ "scope_id": thread_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", "-1001", db_path=db_path)
+
+ assert outcome == {"removed": False, "dismissed": True}
+ assert chat_discovery.list_thread_payloads("telegram", "-1001", db_path=db_path) == []
+ chat_discovery.remember_chat("telegram", "-1001", name="Forum", db_path=db_path)
+ assert chat_discovery.list_thread_payloads("telegram", "-1001", db_path=db_path) == []
+ chat_discovery.remember_thread(
+ "telegram",
+ "-1001",
+ "42",
+ name="Releases",
+ native_type="forum_topic",
+ db_path=db_path,
+ )
+ assert [
+ topic["id"]
+ for topic in chat_discovery.list_thread_payloads("telegram", "-1001", db_path=db_path)
+ ] == ["42"]
+ engine = chat_discovery._engine(db_path)
+ try:
+ with engine.connect() as conn:
+ kept = conn.execute(messages.select().where(messages.c.id == "topic-message")).first()
+ finally:
+ engine.dispose()
+ assert kept is not None
+ reloaded = SQLiteSettingsService(db_path)
+ try:
+ assert "telegram::-1001/42" not in reloaded.load_state().threads
+ finally:
+ reloaded.close()
+
+
def test_delete_scope_with_history_dismisses_instead_of_deleting(tmp_path: Path) -> None:
from datetime import datetime, timezone
diff --git a/tests/test_claude_agent_sessions.py b/tests/test_claude_agent_sessions.py
index b763918c3..5ac0398b8 100644
--- a/tests/test_claude_agent_sessions.py
+++ b/tests/test_claude_agent_sessions.py
@@ -2802,6 +2802,33 @@ class BindReservedWorkbenchSessionTests(unittest.TestCase):
self.assertEqual(ret, "ses_workbench")
self.assertEqual(calls["workdir"], "/Users/alice/vibe-remote-project")
+ def test_im_run_target_binds_native_session_by_resolved_row_id(self):
+ calls = {}
+
+ def bind_by_id(agent_session_id, native_session_id, workdir=None, **kwargs):
+ calls.update(session_id=agent_session_id, native=native_session_id, workdir=workdir)
+ return agent_session_id
+
+ agent = _FakeBaseAgent(SimpleNamespace(bind_agent_session_by_id=bind_by_id))
+ ctx = self._ctx(None)
+ ctx.platform_specific["agent_run_target"] = {
+ "agent_session_id": "ses_topic",
+ "workdir": "/repo/topic",
+ }
+
+ ret = agent._bind_reserved_workbench_session(ctx, "native-topic", working_path="/repo/group")
+
+ self.assertEqual(ret, "ses_topic")
+ self.assertEqual(ctx.platform_specific["agent_session_id"], "ses_topic")
+ self.assertEqual(
+ calls,
+ {
+ "session_id": "ses_topic",
+ "native": "native-topic",
+ "workdir": "/repo/topic",
+ },
+ )
+
def test_routing_subagent_does_not_bind_native_to_reserved_row(self):
agent = _FakeBaseAgent(SimpleNamespace(bind_agent_session_by_id=lambda *a, **k: "ses_wb"))
ctx = self._ctx("ses_wb")
diff --git a/tests/test_message_context_helpers.py b/tests/test_message_context_helpers.py
index 9f02fefe1..8e3bbf52d 100644
--- a/tests/test_message_context_helpers.py
+++ b/tests/test_message_context_helpers.py
@@ -1,4 +1,10 @@
-from core.message_context import build_context_session_key, resolve_context_settings_key
+from core.message_context import (
+ build_context_session_key,
+ build_thread_session_anchor,
+ build_thread_session_anchor_candidates,
+ resolve_context_settings_key,
+ thread_id_from_session_anchor,
+)
from modules.im import MessageContext
@@ -24,3 +30,35 @@ def test_distinct_dm_channel_keeps_legacy_session_key():
assert resolve_context_settings_key(context) == "U123"
assert build_context_session_key(context, settings_key="U123") == "slack::U123"
+
+
+def test_telegram_thread_anchor_includes_chat_id():
+ assert build_thread_session_anchor("telegram", "-100123", "42") == "telegram_-100123_42"
+ assert build_thread_session_anchor("telegram", "-100456", "42") == "telegram_-100456_42"
+
+
+def test_non_telegram_thread_anchor_keeps_existing_shape():
+ assert build_thread_session_anchor("slack", "C123", "171717.999") == "slack_171717.999"
+
+
+def test_telegram_thread_anchor_candidates_include_legacy_shape():
+ assert build_thread_session_anchor_candidates("telegram", "-100123", "42") == (
+ "telegram_-100123_42",
+ "telegram_42",
+ )
+ assert build_thread_session_anchor_candidates("slack", "C123", "171717.999") == (
+ "slack_171717.999",
+ )
+
+
+def test_thread_id_from_session_anchor_accepts_canonical_and_legacy_shapes():
+ assert (
+ thread_id_from_session_anchor(
+ "telegram_-100123_42:runtime_abc",
+ platform="telegram",
+ channel_id="-100123",
+ )
+ == "42"
+ )
+ assert thread_id_from_session_anchor("telegram_42", platform="telegram", channel_id="-100123") == "42"
+ assert thread_id_from_session_anchor("telegram_-100123", platform="telegram", channel_id="-100123") is None
diff --git a/tests/test_message_handler_typing.py b/tests/test_message_handler_typing.py
index 517deec8e..368fc87c2 100644
--- a/tests/test_message_handler_typing.py
+++ b/tests/test_message_handler_typing.py
@@ -877,6 +877,29 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(len(controller.agent_service.stop_requests), 1)
self.assertEqual(controller.agent_service.requests, [])
+ async def test_control_text_handles_inline_stop_in_telegram_general_topic(self):
+ controller = _StubController(platform="telegram", ack_mode="reaction", typing_result=True)
+ handler = MessageHandler(controller)
+ handler.set_session_handler(_StubSessionHandler())
+ context = MessageContext(
+ user_id="U1",
+ channel_id="-1001",
+ thread_id=None,
+ message_id="m1",
+ platform="telegram",
+ platform_specific={
+ "control_text": "stop",
+ "is_dm": False,
+ "is_forum": True,
+ "is_topic_message": True,
+ },
+ )
+
+ await handler.handle_user_message(context, "stop")
+
+ self.assertEqual(len(controller.agent_service.stop_requests), 1)
+ self.assertEqual(controller.agent_service.requests, [])
+
async def test_target_routing_subagent_preserves_backend_runtime_key_for_stop(self):
from core.handlers.command_handlers import CommandHandlers
diff --git a/tests/test_opencode_session_manager.py b/tests/test_opencode_session_manager.py
index 104438824..cada65112 100644
--- a/tests/test_opencode_session_manager.py
+++ b/tests/test_opencode_session_manager.py
@@ -126,6 +126,34 @@ def test_opencode_reused_session_attaches_agent_session_id() -> None:
)
+def test_opencode_topic_run_target_binds_by_resolved_row_id() -> None:
+ sessions = SimpleNamespace(
+ bind_agent_session_by_id=Mock(return_value="ses-topic"),
+ bind_agent_session=Mock(return_value="ses-parent"),
+ )
+ manager = OpenCodeSessionManager(SimpleNamespace(sessions=sessions), "opencode")
+ request = _request()
+ request.context.platform_specific = {
+ "agent_run_target": {
+ "agent_session_id": "ses-topic",
+ "workdir": "/repo",
+ }
+ }
+
+ result = manager.bind_agent_session_id(request, "base-1", "oc-topic")
+
+ assert result == "ses-topic"
+ sessions.bind_agent_session_by_id.assert_called_once_with(
+ "ses-topic",
+ "oc-topic",
+ workdir="/repo",
+ vibe_agent_id=None,
+ vibe_agent_name=None,
+ vibe_agent_backend=None,
+ )
+ sessions.bind_agent_session.assert_not_called()
+
+
def test_opencode_create_session_does_not_pass_vibe_title() -> None:
sessions = SimpleNamespace(
get_agent_session_id=Mock(return_value=None),
diff --git a/tests/test_reserved_native_session_id.py b/tests/test_reserved_native_session_id.py
index a40922965..c64018b5e 100644
--- a/tests/test_reserved_native_session_id.py
+++ b/tests/test_reserved_native_session_id.py
@@ -1,10 +1,9 @@
-"""Contract for the reserved-native resume helper across backends.
+"""Contract for the selected-row native resume helper across backends.
Claude (``SessionHandler``) and Codex (``BaseAgent``) resume from the native
-session bound to the RESERVED workbench row (by PK) via
-``_reserved_native_session_id``. This pins the helper's behavior so the resume
-READ stays on the same key as the by-PK bind WRITE — the fix for "restart loses
-context". Both are static, so no heavy SDK/controller setup is needed.
+session bound to the selected persisted row (by PK), whether selected explicitly
+by Workbench or resolved for an IM run. Both helpers are static, so no heavy
+SDK/controller setup is needed.
"""
from __future__ import annotations
@@ -34,6 +33,20 @@ def test_returns_reserved_native_when_present(helper):
assert helper(ctx) == "native-abc"
[email protected]("helper", HELPERS)
+def test_returns_resolved_im_run_native_when_present(helper):
+ ctx = _ctx(
+ {
+ "agent_run_target": {
+ "agent_session_id": "ses-topic",
+ "native_session_id": "native-topic",
+ "agent_backend": "claude",
+ }
+ }
+ )
+ assert helper(ctx) == "native-topic"
+
+
@pytest.mark.parametrize("helper", HELPERS)
def test_strips_whitespace(helper):
ctx = _ctx({"agent_session_target": {"id": "ses-1", "native_session_id": " native-abc "}})
@@ -42,7 +55,7 @@ def test_strips_whitespace(helper):
@pytest.mark.parametrize("helper", HELPERS)
def test_none_when_no_reserved_target(helper):
- # IM/CLI turns carry no reserved target → fall back to the projection lookup.
+ # A context with no selected row falls back to the projection lookup.
assert helper(_ctx({})) is None
assert helper(_ctx(None)) is None
assert helper(SimpleNamespace(platform_specific=None)) is None
diff --git a/tests/test_resume_session.py b/tests/test_resume_session.py
index 2d2355b7f..d44aa5f7a 100644
--- a/tests/test_resume_session.py
+++ b/tests/test_resume_session.py
@@ -455,7 +455,7 @@ class ResumeSessionTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(
settings.set_calls,
- [("telegram::-100123", "codex", "telegram_99", "sess_telegram_topic")],
+ [("telegram::-100123", "codex", "telegram_-100123_99", "sess_telegram_topic")],
)
self.assertEqual(settings.mark_calls, [("U777", "-100123", "99")])
self.assertEqual(len(im_client.messages), 2)
@@ -527,6 +527,27 @@ class ResumeSessionTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(len(im_client.messages), 1)
self.assertIn("channel level", im_client.messages[0][2])
+ async def test_handle_resume_in_telegram_general_topic_is_rejected(self):
+ settings = _StubSettingsManager()
+ im_client = _StubIMClient()
+ ctrl = _StubController()
+ ctrl.init_minimal(im_client, settings, _StubConfig(platform="telegram"))
+
+ context = MessageContext(
+ user_id="U1",
+ channel_id="-100123",
+ thread_id=None,
+ message_id="MSG1",
+ platform="telegram",
+ platform_specific={"is_dm": False, "is_forum": True, "is_topic_message": True},
+ )
+
+ await ctrl.command_handler.handle_resume(context)
+
+ self.assertEqual(im_client.resume_calls, [])
+ self.assertEqual(len(im_client.messages), 1)
+ self.assertIn("channel level", im_client.messages[0][2])
+
async def test_command_handlers_handle_resume_filters_disabled_backends_before_modal(self):
settings = _StubSettingsManager()
im_client = _StubIMClient()
diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.py
index b6eec8130..e0717a81e 100644
--- a/tests/test_scheduled_tasks.py
+++ b/tests/test_scheduled_tasks.py
@@ -13,6 +13,7 @@ from sqlalchemy import select
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from config import paths
+from config.v2_settings import make_thread_native_id
from core.session_activities import SessionActivityRegistry
from core.scheduled_tasks import (
ParsedSessionKey,
@@ -31,6 +32,8 @@ from storage.db import create_sqlite_engine
from storage.background import SQLiteBackgroundTaskStore
from storage.pagination import PageRequest
from storage.session_activities import SQLiteSessionActivityStore
+from storage.agent_session_rows import create_agent_session_row
+from storage.settings_service import upsert_scope
class _StubScheduler:
@@ -75,6 +78,14 @@ def test_session_anchor_for_target_uses_scope_until_thread_is_explicit() -> None
assert session_anchor_for_target(thread) == "slack_171717.123"
+def test_session_anchor_for_telegram_topic_includes_chat_id() -> None:
+ first = parse_session_key("telegram::channel::-1001::thread::42")
+ second = parse_session_key("telegram::channel::-1002::thread::42")
+
+ assert session_anchor_for_target(first) == "telegram_-1001_42"
+ assert session_anchor_for_target(second) == "telegram_-1002_42"
+
+
def test_resolve_session_id_target_keeps_scope_anchor_threadless(tmp_path: Path) -> None:
from storage.sessions_service import SQLiteSessionsService
@@ -119,6 +130,64 @@ def test_resolve_session_id_target_preserves_reserved_user_scope(tmp_path: Path)
assert resolved.session_key.is_dm is True
[email protected]("anchor", ["telegram_-1001_42", "telegram_42"])
+def test_resolve_session_id_target_maps_telegram_topic_scope_to_delivery_key(
+ tmp_path: Path,
+ anchor: str,
+) -> None:
+ from storage.sessions_service import SQLiteSessionsService
+
+ db_path = tmp_path / "vibe.sqlite"
+ SQLiteSessionsService(db_path).close()
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.begin() as conn:
+ group_scope_id = upsert_scope(
+ conn,
+ platform="telegram",
+ scope_type="channel",
+ native_id="-1001",
+ now="2026-05-31T00:00:00Z",
+ )
+ topic_scope_id = upsert_scope(
+ conn,
+ platform="telegram",
+ scope_type="thread",
+ native_id=make_thread_native_id("-1001", "42"),
+ parent_scope_id=group_scope_id,
+ now="2026-05-31T00:00:00Z",
+ )
+ session_id = create_agent_session_row(
+ conn,
+ scope_id=topic_scope_id,
+ agent_backend="codex",
+ agent_variant="codex",
+ session_anchor=anchor,
+ native_session_id="native-topic-session",
+ workdir=str(tmp_path),
+ )
+ finally:
+ engine.dispose()
+
+ resolved = resolve_session_id_target(session_id, db_path=db_path)
+
+ assert resolved.scope_id == topic_scope_id
+ assert resolved.session_key.to_key() == "telegram::channel::-1001::thread::42"
+
+
+def test_build_session_key_for_general_topic_uses_canonical_thread_id() -> None:
+ context = MessageContext(
+ user_id="7",
+ channel_id="-1001",
+ platform="telegram",
+ platform_specific={"is_dm": False, "is_forum": True},
+ )
+
+ parsed = build_session_key_for_context(context, include_thread=True)
+
+ assert parsed.to_key() == "telegram::channel::-1001::thread::1"
+
+
def test_resolve_session_id_target_accepts_avibe_project_session(tmp_path: Path) -> None:
"""avibe workbench sessions live under ``avibe::project::proj_<hex>``. A
``--session-id`` task target must resolve them (the dispatch binds the reply
@@ -640,6 +709,25 @@ def test_build_context_separates_delivery_target_from_session_target() -> None:
assert context.platform_specific["scheduled_delivery_alias"]["clear_source"] is False
+def test_telegram_delivery_alias_includes_chat_id() -> None:
+ service = ScheduledTaskService(
+ controller=SimpleNamespace(),
+ store=ScheduledTaskStore(Path("/tmp/nonexistent-scheduled.json")),
+ )
+ session_target = parse_session_key("telegram::channel::-100123::thread::42")
+ delivery_target = parse_session_key("telegram::channel::-100456::thread::42")
+
+ strategy = service._build_delivery_alias_strategy(
+ session_target=session_target,
+ delivery_target=delivery_target,
+ session_context={"channel_id": "-100123"},
+ delivery_context={"channel_id": "-100456"},
+ )
+
+ assert strategy["mode"] == "fixed_base"
+ assert strategy["base_session_id"] == "telegram_-100456_42"
+
+
def test_build_context_avibe_keys_on_session_id_not_project() -> None:
# An avibe project holds many independent sessions. The scheduled context's
# identity (channel_id) must be the concrete session, not the project scope,
diff --git a/tests/test_session_handler_base_id.py b/tests/test_session_handler_base_id.py
index 910c2dcf3..5d83187bf 100644
--- a/tests/test_session_handler_base_id.py
+++ b/tests/test_session_handler_base_id.py
@@ -194,6 +194,36 @@ def test_telegram_plain_group_session_base_id_uses_stable_channel_id() -> None:
assert handler.get_base_session_id(context) == "telegram_-100123"
+def test_telegram_general_topic_session_base_id_includes_chat_and_canonical_topic() -> None:
+ handler = SessionHandler(_Controller(platform="telegram", channel_message_sessions=False))
+ first = MessageContext(
+ user_id="u-1",
+ channel_id="-100123",
+ message_id="42",
+ platform="telegram",
+ platform_specific={"is_dm": False, "is_forum": True, "is_topic_message": True},
+ )
+ follow_up = MessageContext(
+ user_id="u-1",
+ channel_id="-100123",
+ message_id="43",
+ platform="telegram",
+ platform_specific={"is_dm": False, "is_forum": True, "is_topic_message": True},
+ )
+
+ other_forum = MessageContext(
+ user_id="u-1",
+ channel_id="-100999",
+ message_id="42",
+ platform="telegram",
+ platform_specific={"is_dm": False, "is_forum": True, "is_topic_message": True},
+ )
+
+ assert handler.get_base_session_id(first) == "telegram_-100123_1"
+ assert handler.get_base_session_id(follow_up) == "telegram_-100123_1"
+ assert handler.get_base_session_id(other_forum) == "telegram_-100999_1"
+
+
def test_scheduled_channel_session_uses_provisional_anchor_on_threaded_surfaces() -> None:
controller = _Controller(platform="slack", dm_threads=False)
handler = SessionHandler(controller)
diff --git a/tests/test_settings_handler.py b/tests/test_settings_handler.py
index e74616729..a64560d99 100644
--- a/tests/test_settings_handler.py
+++ b/tests/test_settings_handler.py
@@ -37,6 +37,53 @@ def _make_handler(settings_manager: _StubSettingsManager) -> tuple[SettingsHandl
return SettingsHandler(controller), send_message
+def test_settings_update_materializes_topic_mention_before_saving_other_fields() -> None:
+ calls: list[str] = []
+ user_settings = SimpleNamespace(show_message_types=[])
+
+ class TopicSettingsManager:
+ sessions = object()
+
+ def set_require_mention(self, settings_key: str, value: bool | None) -> None:
+ assert settings_key == "thread::-100123::1"
+ assert value is None
+ calls.append("mention")
+
+ def get_user_settings(self, settings_key: str):
+ assert settings_key == "thread::-100123::1"
+ calls.append("read")
+ return user_settings
+
+ def update_user_settings(self, settings_key: str, settings) -> None:
+ assert settings_key == "thread::-100123::1"
+ assert settings.show_message_types == ["assistant"]
+ calls.append("save")
+
+ manager = TopicSettingsManager()
+ controller = SimpleNamespace(
+ config=SimpleNamespace(platform="telegram", language="en"),
+ im_client=SimpleNamespace(send_message=AsyncMock()),
+ settings_manager=manager,
+ _get_settings_key=lambda _context: "thread::-100123::1",
+ _get_lang=lambda: "en",
+ )
+ handler = SettingsHandler(controller)
+
+ asyncio.run(
+ handler.handle_settings_update(
+ user_id="42",
+ channel_id="-100123",
+ thread_id="1",
+ show_message_types=["assistant"],
+ require_mention=None,
+ notify_user=False,
+ platform="telegram",
+ )
+ )
+
+ assert calls == ["mention", "read", "save"]
+
+
class _FlatScopeSessions:
def __init__(self, row: dict | None):
self.row = row
diff --git a/tests/test_sqlite_settings_store.py b/tests/test_sqlite_settings_store.py
index bc5677ffa..f03992cd8 100644
--- a/tests/test_sqlite_settings_store.py
+++ b/tests/test_sqlite_settings_store.py
@@ -61,6 +61,42 @@ def test_channel_require_bind_persists(tmp_path: Path) -> None:
reloaded.close()
+def test_telegram_thread_settings_round_trip_and_parent_fallback(tmp_path: Path) -> None:
+ settings_path = tmp_path / "settings.json"
+ store = SettingsStore(settings_path)
+ parent = ChannelSettings(enabled=True, require_mention=True, require_bind=False)
+ topic = ChannelSettings(
+ enabled=True,
+ show_message_types=["assistant", "toolcall"],
+ custom_cwd="/topics/release",
+ routing=RoutingSettings(agent_name="reviewer", model="gpt-5.4"),
+ require_mention=False,
+ require_bind=True,
+ )
+ store.update_channel("-1001", parent, platform="telegram")
+ store.update_thread("-1001", "42", topic, platform="telegram")
+ store.close()
+
+ reloaded = SettingsStore(settings_path)
+ try:
+ effective = reloaded.find_effective_channel("-1001", thread_id="42", platform="telegram")
+ inherited = reloaded.find_effective_channel("-1001", thread_id="99", platform="telegram")
+ assert effective is not None
+ assert effective.require_mention is False
+ assert effective.require_bind is True
+ assert effective.show_message_types == ["assistant", "toolcall"]
+ assert effective.routing.agent_name == "reviewer"
+ assert effective.custom_cwd == "/topics/release"
+ assert inherited is not None
+ assert inherited.require_mention is True
+ assert reloaded.get_threads_for_platform("telegram")["-1001"]["42"] == effective
+
+ assert reloaded.delete_thread("-1001", "42", platform="telegram") is True
+ assert reloaded.find_effective_channel("-1001", thread_id="42", platform="telegram").require_mention is True
+ finally:
+ reloaded.close()
+
+
def test_bound_and_enabled_user_checks_are_separate(tmp_path: Path) -> None:
settings_path = tmp_path / "settings.json"
store = SettingsStore(settings_path)
@@ -225,6 +261,64 @@ def test_settings_manager_runtime_save_preserves_require_bind(tmp_path: Path, mo
manager.store.close()
+def test_settings_manager_topic_override_materializes_inherited_mention_default(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ settings_path = tmp_path / "settings.json"
+ monkeypatch.setattr(paths, "ensure_data_dirs", lambda: None)
+
+ manager = SettingsManager(settings_file=str(settings_path), platform="telegram")
+ manager.require_mention_default = lambda: False
+ try:
+ manager.store.update_channel(
+ "-1001",
+ ChannelSettings(enabled=True, require_mention=None),
+ platform="telegram",
+ )
+ settings_key = v2_settings.make_thread_settings_key("-1001", "42")
+ settings = manager.get_user_settings(settings_key)
+ settings.custom_cwd = "/topic"
+
+ manager.update_user_settings(settings_key, settings)
+
+ topic = manager.store.find_thread("-1001", "42", platform="telegram")
+ assert topic is not None
+ assert topic.custom_cwd == "/topic"
+ assert topic.require_mention is False
+ finally:
+ manager.store.close()
+
+
+def test_settings_manager_topic_mention_inherit_materializes_live_default(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ # Scenario: TELEGRAM-TOPIC-001
+ settings_path = tmp_path / "settings.json"
+ monkeypatch.setattr(paths, "ensure_data_dirs", lambda: None)
+
+ manager = SettingsManager(settings_file=str(settings_path), platform="telegram")
+ current_default = {"value": False}
+ manager.require_mention_default = lambda: current_default["value"]
+ try:
+ manager.store.update_channel(
+ "-1001",
+ ChannelSettings(enabled=True, require_mention=None),
+ platform="telegram",
+ )
+ manager.set_require_mention(v2_settings.make_thread_settings_key("-1001", "42"), None)
+ current_default["value"] = True
+ manager.set_require_mention(v2_settings.make_thread_settings_key("-1001", "43"), None)
+
+ first = manager.store.find_thread("-1001", "42", platform="telegram")
+ second = manager.store.find_thread("-1001", "43", platform="telegram")
+ assert first is not None and first.require_mention is False
+ assert second is not None and second.require_mention is True
+ finally:
+ manager.store.close()
+
+
def test_settings_store_reloads_external_sqlite_writes(tmp_path: Path) -> None:
settings_path = tmp_path / "settings.json"
store = SettingsStore(settings_path)
diff --git a/tests/test_telegram_bot.py b/tests/test_telegram_bot.py
index 84a249cce..904d5ae8c 100644
--- a/tests/test_telegram_bot.py
+++ b/tests/test_telegram_bot.py
@@ -14,6 +14,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from config import paths
from core import chat_discovery
+from core.message_context import resolve_context_thread_id
from modules.agents.native_sessions import NativeResumeSession
from modules.im import InlineButton, InlineKeyboard, MessageContext
from modules.im.multi import MultiIMClient
@@ -51,6 +52,32 @@ def test_strip_leading_bot_mention_returns_empty_for_mention_only() -> None:
assert bot._strip_leading_bot_mention(message, "@vibe_remote_bot") == ""
+def test_discovered_general_topic_leaves_name_for_ui_localization() -> None:
+ bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))
+ chat = {
+ "id": -100123,
+ "type": "supergroup",
+ "title": "Forum",
+ "is_forum": True,
+ }
+ message = {"is_topic_message": True}
+
+ with (
+ patch.object(chat_discovery, "remember_chat"),
+ patch.object(chat_discovery, "remember_thread") as remember_thread,
+ ):
+ bot._remember_discovered_chat(chat, message)
+
+ remember_thread.assert_called_once_with(
+ "telegram",
+ "-100123",
+ "1",
+ name="",
+ native_type="forum_topic",
+ metadata={"is_general": True},
+ )
+
+
def test_strip_leading_bot_mention_keeps_message_body() -> None:
bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))
bot._bot_user = {"id": 1, "username": "vibe_remote_bot"}
@@ -83,6 +110,35 @@ def test_group_message_uses_channel_require_mention_override() -> None:
assert bot.on_message_callback.await_args.args[1] == "hello team"
+def test_forum_message_uses_topic_require_mention_override() -> None:
+ bot = TelegramBot(TelegramConfig(bot_token="123456:test-token", require_mention=True))
+ bot._bot_user = {"id": 1, "username": "vibe_remote_bot"}
+ settings_keys: list[str] = []
+
+ def get_require_mention(settings_key, global_default=False):
+ settings_keys.append(settings_key)
+ return False
+
+ bot.settings_manager = SimpleNamespace(get_require_mention=get_require_mention)
+ bot.on_message_callback = AsyncMock()
+
+ asyncio.run(
+ bot._handle_message(
+ {
+ "message_id": 78,
+ "message_thread_id": 42,
+ "is_topic_message": True,
+ "chat": {"id": -100123, "type": "supergroup", "title": "Core Forum", "is_forum": True},
+ "from": {"id": 42},
+ "text": "hello topic",
+ }
+ )
+ )
+
+ assert settings_keys == ["thread::-100123::42"]
+ bot.on_message_callback.assert_awaited_once()
+
+
def test_inbound_message_refreshes_config_before_reading_options() -> None:
bot = TelegramBot(TelegramConfig(bot_token="123456:test-token", require_mention=True))
bot._bot_user = {"id": 1, "username": "vibe_remote_bot"}
@@ -285,6 +341,118 @@ def test_start_new_topic_session_allows_forum_context_without_thread_id() -> Non
assert send_mock.await_args.args[0] == context
+def test_auto_topic_handoff_rechecks_authorization_before_dispatch() -> None:
+ bot = TelegramBot(
+ TelegramConfig(
+ bot_token="123456:test-token",
+ forum_auto_topic=True,
+ require_mention=False,
+ )
+ )
+ auth_thread_ids: list[str | None] = []
+
+ def check_authorization(**kwargs):
+ auth_thread_ids.append(kwargs.get("thread_id"))
+ if len(auth_thread_ids) == 1:
+ return SimpleNamespace(allowed=True, denial="")
+ return SimpleNamespace(allowed=False, denial="unauthorized_channel")
+
+ bot.check_authorization = check_authorization
+ bot.build_auth_denial_text = lambda denial, channel_id=None: None
+ bot._maybe_route_to_forum_topic = AsyncMock(
+ return_value=MessageContext(
+ user_id="42",
+ channel_id="-100123",
+ thread_id="88",
+ message_id="77",
+ platform="telegram",
+ platform_specific={
+ "is_dm": False,
+ "chat_type": "supergroup",
+ "is_forum": True,
+ "is_topic_message": True,
+ },
+ )
+ )
+ bot._spawn_message_callback_task = AsyncMock()
+
+ asyncio.run(
+ bot._handle_message(
+ {
+ "message_id": 77,
+ "message_thread_id": 1,
+ "is_topic_message": True,
+ "chat": {
+ "id": -100123,
+ "type": "supergroup",
+ "title": "Core Forum",
+ "is_forum": True,
+ },
+ "from": {"id": 42},
+ "text": "start a session",
+ }
+ )
+ )
+
+ assert auth_thread_ids == ["1", "88"]
+ bot._spawn_message_callback_task.assert_not_awaited()
+
+
+def test_auto_topic_handoff_rechecks_destination_mention_policy() -> None:
+ bot = TelegramBot(
+ TelegramConfig(
+ bot_token="123456:test-token",
+ forum_auto_topic=True,
+ require_mention=True,
+ )
+ )
+ settings_keys: list[str] = []
+
+ def get_require_mention(settings_key, global_default=False):
+ settings_keys.append(settings_key)
+ return settings_key != "thread::-100123::1"
+
+ bot.settings_manager = SimpleNamespace(get_require_mention=get_require_mention)
+ bot.check_authorization = lambda **kwargs: SimpleNamespace(allowed=True, denial="")
+ bot._maybe_route_to_forum_topic = AsyncMock(
+ return_value=MessageContext(
+ user_id="42",
+ channel_id="-100123",
+ thread_id="88",
+ message_id="77",
+ platform="telegram",
+ platform_specific={
+ "is_dm": False,
+ "chat_type": "supergroup",
+ "is_forum": True,
+ "is_topic_message": True,
+ },
+ )
+ )
+ bot._spawn_message_callback_task = AsyncMock()
+
+ asyncio.run(
+ bot._handle_message(
+ {
+ "message_id": 77,
+ "message_thread_id": 1,
+ "is_topic_message": True,
+ "chat": {
+ "id": -100123,
+ "type": "supergroup",
+ "title": "Core Forum",
+ "is_forum": True,
+ },
+ "from": {"id": 42},
+ "text": "start a session",
+ }
+ )
+ )
+
+ assert settings_keys == ["thread::-100123::1", "thread::-100123::88"]
+ bot._spawn_message_callback_task.assert_not_awaited()
+
+
def test_build_message_context_records_discovered_chat(tmp_path, monkeypatch) -> None:
monkeypatch.setattr(paths, "get_vibe_remote_dir", lambda: tmp_path / ".vibe_remote")
bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))
@@ -649,6 +817,34 @@ def test_pending_cwd_prompt_consumes_next_plain_message() -> None:
assert bot._interaction_scope_key(context) not in bot._cwd_prompts
+def test_interaction_scope_key_separates_forum_topics() -> None:
+ bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))
+ topic_42 = MessageContext(
+ user_id="42",
+ channel_id="-100123",
+ thread_id="42",
+ platform="telegram",
+ platform_specific={"is_dm": False},
+ )
+ topic_43 = MessageContext(
+ user_id="42",
+ channel_id="-100123",
+ thread_id="43",
+ platform="telegram",
+ platform_specific={"is_dm": False},
+ )
+ general = MessageContext(
+ user_id="42",
+ channel_id="-100123",
+ platform="telegram",
+ platform_specific={"is_dm": False, "is_forum": True},
+ )
+
+ assert bot._interaction_scope_key(topic_42) == "-100123:42:42"
+ assert bot._interaction_scope_key(topic_43) == "-100123:42:43"
+ assert bot._interaction_scope_key(general) == "-100123:42:1"
+
+
def test_pending_cwd_prompt_bypasses_slash_command_with_args() -> None:
bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))
context = MessageContext(
@@ -959,6 +1155,7 @@ def test_resume_menu_uses_short_callback_ids() -> None:
assert keyboard.buttons[0][0].callback_data == "tg_resume:0"
state = bot._resume_states[bot._interaction_scope_key(context)]
assert state.options == [("codex", "session_abcdefghijklmnopqrstuvwxyz")]
+ assert state.thread_id == "1"
assert "cx...Latest answer" in text
@@ -967,15 +1164,15 @@ def test_resume_callback_submits_selected_session() -> None:
context = MessageContext(
user_id="42",
channel_id="-100123",
- thread_id="1",
message_id="55",
platform="telegram",
- platform_specific={"is_dm": False},
+ platform_specific={"is_dm": False, "is_forum": True},
)
bot._resume_states[bot._interaction_scope_key(context)] = SimpleNamespace(
message_id="55",
options=[("claude", "sess_123")],
is_dm=False,
+ thread_id="1",
)
bot._controller = SimpleNamespace(
session_handler=SimpleNamespace(handle_resume_session_submission=AsyncMock()),
@@ -984,7 +1181,15 @@ def test_resume_callback_submits_selected_session() -> None:
with patch.object(bot, "edit_message", new=AsyncMock(return_value=True)):
asyncio.run(bot._handle_resume_callback(context, "tg_resume:0"))
- bot._controller.session_handler.handle_resume_session_submission.assert_awaited_once()
+ bot._controller.session_handler.handle_resume_session_submission.assert_awaited_once_with(
+ user_id="42",
+ channel_id="-100123",
+ thread_id="1",
+ agent="claude",
+ session_id="sess_123",
+ is_dm=False,
+ platform="telegram",
+ )
def test_routing_callback_save_persists_selected_backend() -> None:
@@ -1278,6 +1483,7 @@ def test_settings_callback_save_updates_language_and_deletes_menu() -> None:
global_require_mention=True,
current_language="zh",
is_dm=False,
+ thread_id="1",
)
bot._controller = SimpleNamespace(
settings_handler=SimpleNamespace(handle_settings_update=AsyncMock()),
@@ -1296,9 +1502,47 @@ def test_settings_callback_save_updates_language_and_deletes_menu() -> None:
notify_user=True,
is_dm=False,
platform="telegram",
+ thread_id="1",
)
+def test_callback_context_preserves_general_forum_identity() -> None:
+ bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))
+ bot.check_authorization = lambda **kwargs: SimpleNamespace(allowed=True, denial=None)
+ captured_contexts: list[MessageContext] = []
+
+ async def handle_internal(context: MessageContext, callback_data: str) -> bool:
+ captured_contexts.append(context)
+ return True
+
+ bot._handle_internal_callback = handle_internal
+
+ with patch.object(bot, "answer_callback", new=AsyncMock(return_value=True)):
+ asyncio.run(
+ bot._handle_callback_query(
+ {
+ "id": "cb-general",
+ "data": "tg_settings:save",
+ "from": {"id": 42},
+ "message": {
+ "message_id": 66,
+ "is_topic_message": True,
+ "chat": {
+ "id": -100123,
+ "type": "supergroup",
+ "title": "Core Forum",
+ "is_forum": True,
+ },
+ },
+ }
+ )
+ )
+
+ assert len(captured_contexts) == 1
+ assert resolve_context_thread_id(captured_contexts[0]) == "1"
+ assert bot._interaction_scope_key(captured_contexts[0]) == "-100123:42:1"
+
+
def test_open_question_modal_edits_message_with_telegram_buttons() -> None:
bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))
context = MessageContext(
diff --git a/tests/test_ui_api.py b/tests/test_ui_api.py
index e6d06b52a..1c7e03486 100644
--- a/tests/test_ui_api.py
+++ b/tests/test_ui_api.py
@@ -17,6 +17,7 @@ from config.v2_config import (
V2Config,
)
from config import paths
+from config.v2_settings import ChannelSettings, SettingsStore
from core.vibe_agents import VibeAgentStore
from core import chat_discovery
from vibe import api, backend_model_catalog
@@ -2696,6 +2697,79 @@ def test_telegram_list_chats_returns_discovered_groups(tmp_path, monkeypatch):
assert result["summary"]["hidden_private_count"] == 1
+def test_telegram_topic_settings_api_and_discovery_payload(tmp_path, monkeypatch):
+ # Scenario: TELEGRAM-TOPIC-001
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / ".avibe"))
+ SettingsStore.reset_instance()
+ try:
+ store = SettingsStore.get_instance()
+ store.update_channel("-1001", ChannelSettings(enabled=True, require_mention=True), platform="telegram")
+ chat_discovery.remember_chat(
+ "telegram", "-1001", name="Engineering", native_type="supergroup", supports_threads=True
+ )
+ chat_discovery.remember_thread(
+ "telegram", "-1001", "42", name="Releases", native_type="forum_topic"
+ )
+
+ saved = api.save_thread_settings(
+ {
+ "platform": "telegram",
+ "channel_id": "-1001",
+ "thread_id": "42",
+ "settings": {
+ "enabled": True,
+ "require_mention": False,
+ "require_bind": True,
+ "show_message_types": ["assistant", "toolcall"],
+ "routing": {"agent_name": "reviewer", "model": "gpt-5.4"},
+ },
+ }
+ )
+ settings = api.get_settings("telegram")
+ chats = api.telegram_list_chats()
+
+ assert saved["ok"] is True
+ assert settings["threads"]["-1001"]["42"]["require_mention"] is False
+ assert settings["threads"]["-1001"]["42"]["require_bind"] is True
+ group = next(channel for channel in chats["channels"] if channel["id"] == "-1001")
+ assert group["topics"][0]["name"] == "Releases"
+ assert group["topics"][0]["configured"] is True
+
+ deleted = api.delete_thread_settings("telegram", "-1001", "42")
+ assert deleted["removed"] is True
+ assert api.get_settings("telegram")["threads"] == {}
+ finally:
+ SettingsStore.reset_instance()
+
+
+def test_telegram_topic_settings_materialize_inherited_mention_default(tmp_path, monkeypatch):
+ # Scenario: TELEGRAM-TOPIC-001
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / ".avibe"))
+ monkeypatch.setattr(api, "_stored_platform_config", lambda _platform: SimpleNamespace(require_mention=False))
+ SettingsStore.reset_instance()
+ try:
+ store = SettingsStore.get_instance()
+ store.update_channel("-1001", ChannelSettings(enabled=True, require_mention=None), platform="telegram")
+
+ saved = api.save_thread_settings(
+ {
+ "platform": "telegram",
+ "channel_id": "-1001",
+ "thread_id": "42",
+ "settings": {
+ "enabled": True,
+ "require_mention": None,
+ },
+ }
+ )
+
+ assert saved["ok"] is True
+ assert saved["settings"]["require_mention"] is False
+ assert store.find_thread("-1001", "42", platform="telegram").require_mention is False
+ finally:
+ SettingsStore.reset_instance()
+
+
def test_vibe_agent_api_crud_and_settings_catalog(tmp_path, monkeypatch):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path / ".vibe_remote"))
diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.py
index ad53fbc69..862005e38 100644
--- a/tests/test_ui_server_fastapi.py
+++ b/tests/test_ui_server_fastapi.py
@@ -59,6 +59,62 @@ def test_fastapi_schema_routes_are_not_exposed():
assert client.get("/openapi.json").status_code != 200
+def test_thread_settings_routes_use_native_fastapi(monkeypatch):
+ from vibe import api
+
+ saved_payloads = []
+ deleted_scopes = []
+ monkeypatch.setattr(
+ api,
+ "save_thread_settings",
+ lambda payload: saved_payloads.append(payload) or {"ok": True, "settings": payload["settings"]},
+ )
+ monkeypatch.setattr(
+ api,
+ "delete_thread_settings",
+ lambda platform, channel_id, thread_id: deleted_scopes.append(
+ (platform, channel_id, thread_id)
+ )
+ or {"ok": True, "removed": True},
+ )
+
+ post_route = next(
+ route
+ for route in app.routes
+ if getattr(route, "path", None) == "/api/settings/thread" and "POST" in route.methods
+ )
+ delete_route = next(
+ route
+ for route in app.routes
+ if getattr(route, "path", None) == "/api/settings/thread" and "DELETE" in route.methods
+ )
+ assert post_route.endpoint.__name__ == "thread_settings_post"
+ assert delete_route.endpoint.__name__ == "thread_settings_delete"
+
+ client = app.test_client()
+ saved = client.post(
+ "/api/settings/thread",
+ json={
+ "platform": "telegram",
+ "channel_id": "-1001",
+ "thread_id": "42",
+ "settings": {"enabled": True},
+ },
+ headers=csrf_headers(client),
+ )
+ deleted = client.delete(
+ "/api/settings/thread?platform=telegram&channel_id=-1001&thread_id=42",
+ headers=csrf_headers(client),
+ )
+
+ assert saved.status_code == 200
+ assert saved.get_json()["settings"] == {"enabled": True}
+ assert saved_payloads[0]["thread_id"] == "42"
+ assert deleted.status_code == 200
+ assert deleted.get_json() == {"ok": True, "removed": True}
+ assert deleted_scopes == [("telegram", "-1001", "42")]
+
+
def test_status_endpoint_uses_fast_runtime_status(monkeypatch):
from vibe import runtime
diff --git a/ui/src/components/steps/ChannelList.tsx b/ui/src/components/steps/ChannelList.tsx
index 09675b6f4..506cfbf24 100644
--- a/ui/src/components/steps/ChannelList.tsx
+++ b/ui/src/components/steps/ChannelList.tsx
@@ -26,6 +26,7 @@ import { EyebrowBadge, PlatformIcon, WizardCard } from '../visual';
import { RoutingConfigPanel } from '../shared/RoutingConfigPanel';
import { CompactSelect, SearchField, ToggleSwitch } from '../settings/SettingsPrimitives';
import { Button } from '../ui/button';
+import { TelegramTopicList } from './TelegramTopicList';
const PLATFORM_BRAND_COLORS: Record<string, string> = {
slack: '#4A154B',
@@ -50,7 +51,7 @@ interface ChannelListProps {
wizardPlatforms?: string[];
}
-interface ChannelConfig {
+export interface ChannelConfig {
enabled: boolean;
show_message_types: string[];
custom_cwd: string;
@@ -120,6 +121,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
const [configs, setConfigs] = useState<Record<string, ChannelConfig>>(
data.channelConfigsByPlatform?.[scopedInitialPlatform] || data.channelConfigs || {}
);
+ const [threadConfigs, setThreadConfigs] = useState<Record<string, Record<string, ChannelConfig>>>({});
const [config, setConfig] = useState<any>(data);
const [pagePlatform, setPagePlatform] = useState<string>(forcedPlatform || data.platform || 'slack');
const [opencodeOptionsByCwd, setOpencodeOptionsByCwd] = useState<Record<string, any>>({});
@@ -151,6 +153,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
const [pageTab, setPageTab] = useState<string>('all');
const [searchQuery, setSearchQuery] = useState('');
const [expandedChannelId, setExpandedChannelId] = useState<string | null>(null);
+ const [expandedTopicKey, setExpandedTopicKey] = 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.
@@ -219,6 +222,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
if (!cancelled) {
setConfig((current: any) => ({ ...current, agent_catalog: settings.agent_catalog || current.agent_catalog }));
setConfigs(settings.channels || {});
+ if (targetPlatform === 'telegram') setThreadConfigs(settings.threads || {});
}
} catch {
if (!cancelled) {
@@ -257,6 +261,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
api.getSettings(defaultPlatform).then(s => {
setConfig((current: any) => ({ ...current, agent_catalog: s.agent_catalog || current.agent_catalog }));
setConfigs(s.channels || {});
+ if (defaultPlatform === 'telegram') setThreadConfigs(s.threads || {});
if (defaultPlatform === 'discord') {
const allowlist = getDiscordGuildAllowlist(s);
confirmedGuildAllowlistRef.current = allowlist;
@@ -298,6 +303,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
if (!platform) return;
api.getSettings(platform).then((settings) => {
setConfigs(settings.channels || {});
+ if (platform === 'telegram') setThreadConfigs(settings.threads || {});
if (platform === 'discord') {
const allowlist = getDiscordGuildAllowlist(settings);
confirmedGuildAllowlistRef.current = allowlist;
@@ -702,8 +708,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
const neededClaudeCwds = new Set<string>();
const neededCodexCwds = new Set<string>();
- channels.forEach((channel) => {
- const raw = configs[channel.id];
+ const collectBackendCwd = (raw: ChannelConfig | undefined) => {
if (!raw || raw.enabled === false) return;
const effectiveCwd = (raw.custom_cwd ?? '') || defaultCwd;
const routing = raw.routing || {};
@@ -719,6 +724,13 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
if (backend === 'codex' && config.agents?.codex?.enabled) {
neededCodexCwds.add(effectiveCwd);
}
+ };
+
+ channels.forEach((channel) => {
+ collectBackendCwd(configs[channel.id]);
+ });
+ Object.values(threadConfigs).forEach((topics) => {
+ Object.values(topics).forEach(collectBackendCwd);
});
neededOpenCodeCwds.forEach((cwd) => {
@@ -738,7 +750,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
void loadCodexAgents(cwd);
}
});
- }, [channels, configs, config.runtime?.default_cwd, config.agents?.opencode?.enabled, config.agents?.claude?.enabled, config.agents?.codex?.enabled, agentByName, defaultAgentName]);
+ }, [channels, configs, threadConfigs, config.runtime?.default_cwd, config.agents?.opencode?.enabled, config.agents?.claude?.enabled, config.agents?.codex?.enabled, agentByName, defaultAgentName]);
const isChannelEnabled = (channelId: string) => {
const channel = configs[channelId];
@@ -847,6 +859,45 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
}
};
+ const saveTelegramTopicConfig = async (
+ channelId: string,
+ topicId: string,
+ next: ChannelConfig,
+ ) => {
+ setThreadConfigs((current) => ({
+ ...current,
+ [channelId]: { ...(current[channelId] || {}), [topicId]: next },
+ }));
+ try {
+ const result = await api.saveThreadSettings('telegram', channelId, topicId, next);
+ const saved = (result.settings || next) as ChannelConfig;
+ setThreadConfigs((current) => ({
+ ...current,
+ [channelId]: { ...(current[channelId] || {}), [topicId]: saved },
+ }));
+ showToast(t('channelList.settingsSaved'));
+ } catch {
+ const settings = await api.getSettings('telegram').catch(() => null);
+ if (settings) setThreadConfigs(settings.threads || {});
+ showToast(t('channelList.settingsSaveFailed'), 'error');
+ }
+ };
+
+ const resetTelegramTopicConfig = async (channelId: string, topicId: string) => {
+ try {
+ await api.deleteThreadSettings('telegram', channelId, topicId);
+ setThreadConfigs((current) => {
+ const nextChannel = { ...(current[channelId] || {}) };
+ delete nextChannel[topicId];
+ return { ...current, [channelId]: nextChannel };
+ });
+ setExpandedTopicKey((current) => current === `${channelId}::${topicId}` ? null : current);
+ showToast(t('channelList.settingsSaved'));
+ } catch {
+ showToast(t('channelList.settingsSaveFailed'), 'error');
+ }
+ };
+
const loadAllPlatformsData = async (force = false) => {
if (!isPage) return;
const platforms = getEnabledPlatforms(config).filter((p) => platformSupportsChannels(config, p));
@@ -858,10 +909,14 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
platforms.map(async (p) => {
let channelsList: any[] = [];
let configsMap: Record<string, ChannelConfig> = {};
+ let threadConfigsMap: Record<string, Record<string, ChannelConfig>> = {};
let refreshing = false;
try {
const settings = await api.getSettings(p);
configsMap = (settings.channels || {}) as Record<string, ChannelConfig>;
+ if (p === 'telegram') {
+ threadConfigsMap = (settings.threads || {}) as Record<string, Record<string, ChannelConfig>>;
+ }
if (p === 'lark') {
const appId = config.lark?.app_id || '';
const appSecret = config.lark?.app_secret || '';
@@ -900,7 +955,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
} catch {
// ignore individual platform failures
}
- return { platform: p, channels: channelsList, configs: configsMap, refreshing };
+ return { platform: p, channels: channelsList, configs: configsMap, threadConfigs: threadConfigsMap, refreshing };
})
);
if (allPlatformsRequestVersionRef.current !== requestVersion) return;
@@ -912,6 +967,8 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
}
setAllChannelsByPlatform(channelsByPlatform);
setAllConfigsByPlatform(configsByPlatform);
+ const telegramResult = results.find((result) => result.platform === 'telegram');
+ if (telegramResult) setThreadConfigs(telegramResult.threadConfigs);
if (results.some((r) => r.refreshing)) scheduleAllPlatformsRefreshFollowup();
} finally {
endAllPlatformsLoading();
@@ -1643,24 +1700,79 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
{/* Expanded body — design.pen asPXu (VR/RoutingConfig) — shared with /users */}
{expanded && (
- <RoutingConfigPanel
- value={channelConfig}
- onChange={(patch) => updateRow(patch)}
- onBrowseDirectory={() => setBrowsingCwdFor(rowKey)}
- globalConfig={config}
- vibeAgents={vibeAgents}
- defaultAgentName={defaultAgentName}
- availableMessageTypes={availableMessageTypes(channelPlatform)}
- showRequireMention={true}
- inheritsFromKey={channelPlatform}
- opencodeOptions={opencodeOptions}
- claudeAgents={claudeAgents}
- claudeModels={claudeModels}
- claudeModelLabels={claudeModelLabels}
- claudeReasoningOptions={claudeReasoningOptions}
- codexAgents={codexAgents}
- codexModels={codexModels}
- />
+ <>
+ <RoutingConfigPanel
+ value={channelConfig}
+ onChange={(patch) => updateRow(patch)}
+ onBrowseDirectory={() => setBrowsingCwdFor(rowKey)}
+ globalConfig={config}
+ vibeAgents={vibeAgents}
+ defaultAgentName={defaultAgentName}
+ availableMessageTypes={availableMessageTypes(channelPlatform)}
+ showRequireMention={true}
+ inheritsFromKey={channelPlatform}
+ opencodeOptions={opencodeOptions}
+ claudeAgents={claudeAgents}
+ claudeModels={claudeModels}
+ claudeModelLabels={claudeModelLabels}
+ claudeReasoningOptions={claudeReasoningOptions}
+ codexAgents={codexAgents}
+ codexModels={codexModels}
+ />
+ {channelPlatform === 'telegram' && channel.supports_topics && (
+ <TelegramTopicList<ChannelConfig>
+ topics={channel.topics || []}
+ configs={threadConfigs[channel.id] || {}}
+ expandedTopicId={
+ expandedTopicKey?.startsWith(`${channel.id}::`)
+ ? expandedTopicKey.slice(channel.id.length + 2)
+ : null
+ }
+ onToggleExpanded={(topicId) => {
+ const key = `${channel.id}::${topicId}`;
+ setExpandedTopicKey((current) => current === key ? null : key);
+ }}
+ onCustomize={(topicId) => {
+ const snapshot: ChannelConfig = {
+ ...channelConfig,
+ show_message_types: [...channelConfig.show_message_types],
+ routing: { ...channelConfig.routing },
+ };
+ void saveTelegramTopicConfig(channel.id, topicId, snapshot);
+ setExpandedTopicKey(`${channel.id}::${topicId}`);
+ }}
+ onReset={(topicId) => void resetTelegramTopicConfig(channel.id, topicId)}
+ onSetEnabled={(topicId, enabled) => {
+ const topicConfig = threadConfigs[channel.id]?.[topicId];
+ if (topicConfig) void saveTelegramTopicConfig(channel.id, topicId, { ...topicConfig, enabled });
+ }}
+ renderEditor={(topicId, topicConfig) => {
+ const topicCwd = topicConfig.custom_cwd || config.runtime?.default_cwd || '~/work';
+ return (
+ <RoutingConfigPanel
+ value={topicConfig}
+ onChange={(patch) => void saveTelegramTopicConfig(channel.id, topicId, { ...topicConfig, ...patch })}
+ onBrowseDirectory={() => setBrowsingCwdFor(`telegram::${channel.id}::${topicId}`)}
+ globalConfig={config}
+ vibeAgents={vibeAgents}
+ defaultAgentName={defaultAgentName}
+ availableMessageTypes={availableMessageTypes('telegram')}
+ showRequireMention={true}
+ inheritsFromKey="telegram"
+ opencodeOptions={opencodeOptionsByCwd[topicCwd]}
+ claudeAgents={claudeAgentsByCwd[topicCwd] || []}
+ claudeModels={claudeModels}
+ claudeModelLabels={claudeModelLabels}
+ claudeReasoningOptions={claudeReasoningOptions}
+ codexAgents={codexAgentsByCwd[topicCwd] || []}
+ codexModels={codexModels}
+ containerClass="border-t border-cyan/20 bg-background/35"
+ />
+ );
+ }}
+ />
+ )}
+ </>
)}
</div>
);
@@ -1670,16 +1782,21 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
{/* Directory browser modal — page mode keys by `${platform}::${channelId}` */}
{browsingCwdFor && (() => {
- const sep = browsingCwdFor.indexOf('::');
- if (sep < 0) return null;
- const browsePlatform = browsingCwdFor.slice(0, sep);
- const browseChannelId = browsingCwdFor.slice(sep + 2);
+ const [browsePlatform, browseChannelId, browseTopicId] = browsingCwdFor.split('::');
+ if (!browsePlatform || !browseChannelId) return null;
const platformConfigs = browsePlatform === platform ? configs : (allConfigsByPlatform[browsePlatform] || {});
+ const selectedConfig = browseTopicId
+ ? threadConfigs[browseChannelId]?.[browseTopicId]
+ : platformConfigs[browseChannelId];
return (
<DirectoryBrowser
- initialPath={platformConfigs[browseChannelId]?.custom_cwd || config.runtime?.default_cwd || '~/work'}
+ initialPath={selectedConfig?.custom_cwd || config.runtime?.default_cwd || '~/work'}
onSelect={(path) => {
- void updateConfigForPlatform(browsePlatform, browseChannelId, { custom_cwd: path });
+ if (browseTopicId && selectedConfig) {
+ void saveTelegramTopicConfig(browseChannelId, browseTopicId, { ...selectedConfig, custom_cwd: path });
+ } else {
+ void updateConfigForPlatform(browsePlatform, browseChannelId, { custom_cwd: path });
+ }
setBrowsingCwdFor(null);
}}
onClose={() => setBrowsingCwdFor(null)}
diff --git a/ui/src/components/steps/TelegramTopicList.tsx b/ui/src/components/steps/TelegramTopicList.tsx
new file mode 100644
index 000000000..3d1e07fa4
--- /dev/null
+++ b/ui/src/components/steps/TelegramTopicList.tsx
@@ -0,0 +1,144 @@
+import React from 'react';
+import { ChevronDown, ChevronUp, GitBranch, RotateCcw, SlidersHorizontal } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import clsx from 'clsx';
+import { Button } from '../ui/button';
+import { ToggleSwitch } from '../settings/SettingsPrimitives';
+
+export interface TelegramTopic {
+ id: string;
+ name?: string;
+ configured?: boolean;
+ last_seen_at?: string;
+}
+
+interface TelegramTopicListProps<T extends { enabled: boolean }> {
+ topics: TelegramTopic[];
+ configs: Record<string, T>;
+ expandedTopicId: string | null;
+ onToggleExpanded: (topicId: string) => void;
+ onCustomize: (topicId: string) => void;
+ onReset: (topicId: string) => void;
+ onSetEnabled: (topicId: string, enabled: boolean) => void;
+ renderEditor: (topicId: string, value: T) => React.ReactNode;
+}
+
+export function TelegramTopicList<T extends { enabled: boolean }>({
+ topics,
+ configs,
+ expandedTopicId,
+ onToggleExpanded,
+ onCustomize,
+ onReset,
+ onSetEnabled,
+ renderEditor,
+}: TelegramTopicListProps<T>) {
+ const { t } = useTranslation();
+
+ if (topics.length === 0) {
+ return (
+ <div className="border-t border-border px-5 py-4">
+ <div className="rounded-lg border border-dashed border-border bg-background/60 px-4 py-5 text-center">
+ <div className="text-sm font-medium text-foreground">{t('channelList.topicEmptyTitle')}</div>
+ <div className="mt-1 text-xs text-muted">{t('channelList.topicEmptyDesc')}</div>
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <section className="border-t border-border bg-background/35 px-5 py-4">
+ <div className="mb-3 flex items-start justify-between gap-4">
+ <div>
+ <div className="flex items-center gap-2 text-sm font-semibold text-foreground">
+ <GitBranch size={15} className="text-cyan" />
+ {t('channelList.topicSettingsTitle')}
+ <span className="rounded-full border border-border bg-foreground/[0.04] px-2 py-0.5 text-[10px] font-medium text-muted">
+ {topics.length}
+ </span>
+ </div>
+ <p className="mt-1 text-xs text-muted">{t('channelList.topicSettingsDesc')}</p>
+ </div>
+ </div>
+
+ <div className="space-y-2">
+ {topics.map((topic) => {
+ const value = configs[topic.id];
+ const customized = Boolean(value);
+ const expanded = expandedTopicId === topic.id;
+ return (
+ <div
+ key={topic.id}
+ className={clsx(
+ 'overflow-hidden rounded-lg border transition-colors',
+ customized ? 'border-cyan/30 bg-cyan-soft/10' : 'border-border bg-surface-2/45',
+ )}
+ >
+ <div className="flex items-center gap-3 px-3.5 py-3">
+ <span className="flex size-7 shrink-0 items-center justify-center rounded-md border border-cyan/25 bg-cyan-soft/20 text-cyan">
+ <GitBranch size={14} />
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-[13px] font-medium text-foreground">
+ {topic.name ||
+ (topic.id === '1'
+ ? t('channelList.topicGeneralName')
+ : t('channelList.topicFallbackName', { id: topic.id }))}
+ </span>
+ <span className="block truncate font-mono text-[10px] text-muted">
+ {t('channelList.topicIdLabel', { id: topic.id })}
+ </span>
+ </span>
+ <span
+ className={clsx(
+ 'rounded-full border px-2 py-0.5 text-[10px] font-medium',
+ customized
+ ? 'border-cyan/30 bg-cyan-soft/25 text-cyan'
+ : 'border-border bg-foreground/[0.04] text-muted',
+ )}
+ >
+ {customized ? t('channelList.topicCustomBadge') : t('channelList.topicInheritedBadge')}
+ </span>
+ {customized ? (
+ <>
+ <span className="inline-flex items-center gap-2 text-[11px] text-muted">
+ {value.enabled ? t('common.enabled') : t('common.disabled')}
+ <ToggleSwitch
+ enabled={value.enabled}
+ onClick={() => onSetEnabled(topic.id, !value.enabled)}
+ />
+ </span>
+ <Button
+ type="button"
+ variant="ghost"
+ size="xs"
+ onClick={() => onReset(topic.id)}
+ title={t('channelList.topicReset') as string}
+ >
+ <RotateCcw size={13} />
+ {t('channelList.topicReset')}
+ </Button>
+ <button
+ type="button"
+ onClick={() => onToggleExpanded(topic.id)}
+ className="rounded-md p-1.5 text-muted transition-colors hover:bg-foreground/[0.06] hover:text-foreground"
+ aria-label={expanded ? t('channelList.topicCollapse') : t('channelList.topicExpand')}
+ >
+ {expanded ? <ChevronUp size={16} /> : <ChevronDown size={16} />}
+ </button>
+ </>
+ ) : (
+ <Button type="button" variant="secondary" size="xs" onClick={() => onCustomize(topic.id)}>
+ <SlidersHorizontal size={13} />
+ {t('channelList.topicCustomize')}
+ </Button>
+ )}
+ </div>
+ {customized && expanded && renderEditor(topic.id, value)}
+ </div>
+ );
+ })}
+ </div>
+ </section>
+ );
+}
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index db02ffb3f..7ba9fcca4 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -398,6 +398,8 @@ export type ApiContextType = {
saveConfig: (payload: any) => Promise<any>;
getSettings: (platform?: string) => Promise<any>;
saveSettings: (payload: any, platform?: string) => Promise<any>;
+ saveThreadSettings: (platform: string, channelId: string, threadId: string, settings: any) => Promise<any>;
+ deleteThreadSettings: (platform: string, channelId: string, threadId: string) => Promise<any>;
getUsers: (platform?: string) => Promise<any>;
saveUsers: (payload: any, platform?: string) => Promise<any>;
toggleAdmin: (userId: string, isAdmin: boolean, platform?: string) => Promise<any>;
@@ -2322,6 +2324,15 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
saveConfig: (payload) => postJson('/api/config', payload),
getSettings: (platform) => getJson(platform ? `/api/settings?platform=${encodeURIComponent(platform)}` : '/api/settings'),
saveSettings: (payload, platform) => postJson('/api/settings', platform ? { ...payload, platform } : payload),
+ saveThreadSettings: (platform, channelId, threadId, settings) => postJson('/api/settings/thread', {
+ platform,
+ channel_id: channelId,
+ thread_id: threadId,
+ settings,
+ }),
+ deleteThreadSettings: (platform, channelId, threadId) => deleteJson(
+ `/api/settings/thread?platform=${encodeURIComponent(platform)}&channel_id=${encodeURIComponent(channelId)}&thread_id=${encodeURIComponent(threadId)}`,
+ ),
getUsers: (platform) => getJson(platform ? `/api/users?platform=${encodeURIComponent(platform)}` : '/api/users'),
saveUsers: (payload, platform) => postJson('/api/users', platform ? { ...payload, platform } : payload),
toggleAdmin: (userId, isAdmin, platform) => postJson(`/api/users/${encodeURIComponent(userId)}/admin`, platform ? { is_admin: isAdmin, platform } : { is_admin: isAdmin }),
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 4753060eb..0e3954711 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -1735,6 +1735,19 @@
"telegramDiscoveryEmptyTitle": "No Telegram chats discovered yet",
"telegramDiscoveryEmptyDesc": "Send a message in any Telegram group or forum where the bot is present, then refresh this page.",
"telegramLastSeen": "Last seen {{time}}",
+ "topicSettingsTitle": "Forum topic overrides",
+ "topicSettingsDesc": "Topics inherit the group until you create an override. New topics appear here after the bot sees a message.",
+ "topicEmptyTitle": "No topics discovered yet",
+ "topicEmptyDesc": "Send a message in a forum topic, then refresh the group list.",
+ "topicGeneralName": "General",
+ "topicFallbackName": "Topic {{id}}",
+ "topicIdLabel": "Topic ID: {{id}}",
+ "topicCustomBadge": "Custom",
+ "topicInheritedBadge": "Inherits group",
+ "topicCustomize": "Customize",
+ "topicReset": "Use group settings",
+ "topicExpand": "Expand topic settings",
+ "topicCollapse": "Collapse topic settings",
"enabledCount": "{{count}} enabled",
"accessPolicy": "Access Policy",
"accessPolicyHint": "Groups are enabled only when checked below.",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 56d6352fb..1d0d60cf9 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -1735,6 +1735,19 @@
"telegramDiscoveryEmptyTitle": "还没有发现任何 Telegram 会话",
"telegramDiscoveryEmptyDesc": "先在 bot 已加入的 Telegram 群组或 forum 里发一条消息,再回来刷新这个页面。",
"telegramLastSeen": "最近出现于 {{time}}",
+ "topicSettingsTitle": "Forum Topic 单独设置",
+ "topicSettingsDesc": "Topic 默认继承群组设置;创建覆盖后可单独控制。Bot 收到 topic 消息后会自动发现并显示在这里。",
+ "topicEmptyTitle": "还没有发现 Topic",
+ "topicEmptyDesc": "先在 forum topic 中发送一条消息,然后刷新群组列表。",
+ "topicGeneralName": "常规",
+ "topicFallbackName": "Topic {{id}}",
+ "topicIdLabel": "话题 ID:{{id}}",
+ "topicCustomBadge": "单独设置",
+ "topicInheritedBadge": "继承群组",
+ "topicCustomize": "单独配置",
+ "topicReset": "恢复群组设置",
+ "topicExpand": "展开 Topic 设置",
+ "topicCollapse": "收起 Topic 设置",
"enabledCount": "已启用 {{count}} 个",
"accessPolicy": "访问策略",
"accessPolicyHint": "只有勾选的群组才会启用",
diff --git a/ui/vite.config.ts b/ui/vite.config.ts
index 4e2c2ba06..d4e554ecb 100644
--- a/ui/vite.config.ts
+++ b/ui/vite.config.ts
@@ -2,6 +2,28 @@ import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
+const backendTarget = 'http://localhost:5100'
+
+const backendProxy = () => ({
+ target: backendTarget,
+ changeOrigin: true,
+ configure(proxy: {
+ on: (
+ event: 'proxyReq',
+ handler: (proxyReq: { setHeader: (name: string, value: string) => void }) => void,
+ ) => void
+ }) {
+ // Codex's in-app browser maps the Vite port to a temporary localhost
+ // origin. Rewrite the development proxy headers so Avibe's same-origin
+ // CSRF validation sees the isolated backend origin, while production keeps
+ // using the normal browser origin unchanged.
+ proxy.on('proxyReq', (proxyReq) => {
+ proxyReq.setHeader('origin', backendTarget)
+ proxyReq.setHeader('referer', `${backendTarget}/`)
+ })
+ },
+})
+
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
@@ -12,16 +34,16 @@ export default defineConfig({
},
server: {
proxy: {
- '/config': 'http://localhost:5100',
- '/session': 'http://localhost:5100',
- '/status': 'http://localhost:5100',
- '/settings': 'http://localhost:5100',
- '/logs': 'http://localhost:5100',
- '/doctor': 'http://localhost:5100',
- '/remote-access': 'http://localhost:5100',
- '/control': 'http://localhost:5100',
- '/upgrade': 'http://localhost:5100',
- '/api': 'http://localhost:5100',
+ '/config': backendProxy(),
+ '/session': backendProxy(),
+ '/status': backendProxy(),
+ '/settings': backendProxy(),
+ '/logs': backendProxy(),
+ '/doctor': backendProxy(),
+ '/remote-access': backendProxy(),
+ '/control': backendProxy(),
+ '/upgrade': backendProxy(),
+ '/api': backendProxy(),
},
},
})
diff --git a/vibe/api.py b/vibe/api.py
index d36cbeb9f..704982a3e 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -4181,6 +4181,66 @@ def save_settings(payload: dict) -> dict:
return _settings_to_payload(store, platform=platform)
+def save_thread_settings(payload: dict) -> dict:
+ """Create or replace one child-thread settings override."""
+ store = SettingsStore.get_instance()
+ platform = str(payload.get("platform") or _current_platform())
+ channel_id = str(payload.get("channel_id") or "").strip()
+ thread_id = str(payload.get("thread_id") or "").strip()
+ settings_payload = payload.get("settings")
+ if platform != "telegram":
+ return {"ok": False, "error": "thread settings currently support Telegram only"}
+ if not channel_id or not thread_id or not isinstance(settings_payload, dict):
+ return {"ok": False, "error": "channel_id, thread_id, and settings are required"}
+
+ existing = store.find_thread(channel_id, thread_id, platform=platform)
+ base = existing
+ if base is None:
+ base = store.find_channel(channel_id, platform=platform) or ChannelSettings()
+ routing_payload = settings_payload.get("routing")
+ routing = (
+ _parse_routing(_normalize_backend_routing_payload(routing_payload))
+ if isinstance(routing_payload, dict)
+ else base.routing
+ )
+ require_mention = settings_payload.get("require_mention", base.require_mention)
+ if existing is None and require_mention is None:
+ platform_config = _stored_platform_config(platform)
+ require_mention = bool(getattr(platform_config, "require_mention", True))
+ settings = ChannelSettings(
+ enabled=bool(settings_payload.get("enabled", base.enabled)),
+ show_message_types=_normalize_show_message_types_for_platform(
+ settings_payload.get("show_message_types", base.show_message_types),
+ platform,
+ ),
+ custom_cwd=settings_payload.get("custom_cwd", base.custom_cwd),
+ routing=routing,
+ require_mention=require_mention,
+ require_bind=settings_payload.get("require_bind", base.require_bind),
+ )
+ store.update_thread(channel_id, thread_id, settings, platform=platform)
+ return {
+ "ok": True,
+ "channel_id": channel_id,
+ "thread_id": thread_id,
+ "settings": _scope_settings_payload(settings, platform),
+ }
+
+
+def delete_thread_settings(platform: str, channel_id: str, thread_id: str) -> dict:
+ """Remove one child-thread override so it inherits its parent channel again."""
+ platform = str(platform or "").strip()
+ channel_id = str(channel_id or "").strip()
+ thread_id = str(thread_id or "").strip()
+ if platform != "telegram":
+ return {"ok": False, "error": "thread settings currently support Telegram only"}
+ if not channel_id or not thread_id:
+ return {"ok": False, "error": "channel_id and thread_id are required"}
+ store = SettingsStore.get_instance()
+ removed = store.delete_thread(channel_id, thread_id, platform=platform)
+ return {"ok": True, "removed": removed, "channel_id": channel_id, "thread_id": thread_id}
+
+
def _guild_scope_update_from_settings_payload(
store: SettingsStore,
platform: str,
@@ -4506,11 +4566,18 @@ def delete_channel_scope(platform: str, native_id: str, scope_type: str = "chann
def telegram_list_chats(include_private: bool = False, include_not_returned: bool = False) -> dict:
from core import chat_discovery
- return chat_discovery.channels_response(
+ result = chat_discovery.channels_response(
"telegram",
include_private=include_private,
include_not_returned=include_not_returned,
)
+ for channel in result.get("channels") or []:
+ supports_topics = bool(channel.get("supports_topics") or channel.get("supports_threads"))
+ channel["supports_topics"] = supports_topics
+ if supports_topics:
+ channel["topics"] = chat_discovery.list_thread_payloads("telegram", str(channel.get("id") or ""))
+ result["chats"] = result.get("channels") or []
+ return result
def discord_list_guilds(bot_token: str) -> dict:
@@ -4893,9 +4960,21 @@ def _current_platform() -> str:
return load_config().platform
+def _scope_settings_payload(settings: ChannelSettings, platform: str) -> dict:
+ return {
+ "enabled": settings.enabled,
+ "show_message_types": _normalize_show_message_types_for_platform(settings.show_message_types, platform),
+ "custom_cwd": settings.custom_cwd,
+ "require_mention": settings.require_mention,
+ "require_bind": settings.require_bind,
+ "routing": routing_to_compat_dict(settings.routing),
+ }
+
+
def _settings_to_payload(store: SettingsStore, platform: str) -> dict:
payload: dict = {
"channels": {},
+ "threads": {},
"guilds": {},
"guild_allowlist": [],
"guild_scope_configured": False,
@@ -4904,13 +4983,11 @@ def _settings_to_payload(store: SettingsStore, platform: str) -> dict:
"bind_codes": [],
}
for channel_id, settings in store.get_channels_for_platform(platform).items():
- payload["channels"][channel_id] = {
- "enabled": settings.enabled,
- "show_message_types": _normalize_show_message_types_for_platform(settings.show_message_types, platform),
- "custom_cwd": settings.custom_cwd,
- "require_mention": settings.require_mention,
- "require_bind": settings.require_bind,
- "routing": routing_to_compat_dict(settings.routing),
+ payload["channels"][channel_id] = _scope_settings_payload(settings, platform)
+ for channel_id, threads in store.get_threads_for_platform(platform).items():
+ payload["threads"][channel_id] = {
+ thread_id: _scope_settings_payload(settings, platform)
+ for thread_id, settings in threads.items()
}
payload["guild_scope_configured"] = store.has_guild_scope_for_platform(platform)
payload["guild_default_enabled"] = store.get_guild_default_enabled_for_platform(platform)
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index b26f44097..f356f7203 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -4783,6 +4783,33 @@ def settings_post():
return jsonify(api.save_settings(payload))
[email protected]("/api/settings/thread", include_in_schema=False)
+async def thread_settings_post(starlette_request: FastAPIRequest):
+ async def handler():
+ from vibe import api
+
+ body = await starlette_request.body()
+ payload = await starlette_request.json() if body else {}
+ return api.save_thread_settings(payload if isinstance(payload, dict) else {})
+
+ return await _dispatch_native_ui_request(starlette_request, handler)
+
+
[email protected]("/api/settings/thread", include_in_schema=False)
+async def thread_settings_delete(starlette_request: FastAPIRequest):
+ async def handler():
+ from vibe import api
+
+ query = starlette_request.query_params
+ return api.delete_thread_settings(
+ query.get("platform", ""),
+ query.get("channel_id", ""),
+ query.get("thread_id", ""),
+ )
+
+ return await _dispatch_native_ui_request(starlette_request, handler)
+
+
@app.route("/api/slack/auth_test", methods=["POST"])
def slack_auth_test():
from vibe import api