Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(platform): unify IM behavior and scope settings
cyhhao6db9d5bf4299
diff --git a/AGENTS.md b/AGENTS.mdindex 7d19bc9e2..5c08b2201 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -110,6 +110,39 @@ For complex features or bug fixes that may take extended time and block the main## 2) Project-Specific (Vibe Remote)+### Architecture & Layering++Vibe Remote is a **multi-platform, multi-backend** system. Every feature and bug fix must be evaluated from this perspective.++```+┌─────────────────────────────────────┐+│ core/controller.py │ Orchestration — platform/backend agnostic+│ core/handlers/ │ Business logic — platform/backend agnostic+│ core/message_dispatcher.py │ Message routing — platform/backend agnostic+├─────────────────────────────────────┤+│ modules/im/base.py │ IM abstraction (BaseIMClient)+│ modules/agents/base.py │ Agent abstraction (BaseAgentBackend)+│ modules/im/formatters/base_formatter.py │ Formatter abstraction+├─────────────────────────────────────┤+│ modules/im/slack.py, feishu.py, discord.py │ IM implementations+│ modules/agents/claude_agent.py, codex/, opencode/ │ Agent implementations+│ modules/im/formatters/slack_formatter.py, ... │ Formatter implementations+└─────────────────────────────────────┘+```++**Key rule: fix at the highest appropriate layer.**++- A bug triggered on Feishu is often a common issue. Check: does the same logic path exist for Slack/Discord? If yes, fix in the handler/base layer, not the platform layer.+- A feature for one agent backend likely applies to all. Check: should the behavior be in `base.py` or `controller.py` rather than `claude_agent.py`?+- User-facing text must go through `vibe/i18n/` — never hardcode strings in handler or platform code.++**Decision checklist before writing code:**++1. **Scope**: Does this affect one platform/backend, or all? → If all, fix in the common layer.+2. **Abstraction**: Can the base class provide a default? → Add to base, override only where platforms genuinely differ.+3. **Callers**: Who calls this code? → If it's called from common code (handlers/controller), the fix belongs in common code.+4. **Future platforms**: If we add a new IM platform tomorrow, would it inherit correct behavior automatically? → If not, the abstraction is wrong.+### Structure- Entry point: `main.py` wires `config.V2Config` into `core/controller.py`.diff --git a/config/v2_compat.py b/config/v2_compat.pyindex dd3339a2b..5de3ea8e3 100644--- a/config/v2_compat.py+++ b/config/v2_compat.py@@ -44,6 +44,8 @@ class AppCompatConfig:ack_mode: strlanguage: strshow_duration: bool = True+ include_user_info: bool = True+ reply_enhancements: bool = Truedefault_backend: str = "opencode"@@ -82,5 +84,7 @@ def to_app_config(v2: V2Config) -> AppCompatConfig:ack_mode=v2.ack_mode,language=v2.language,show_duration=v2.show_duration,+ include_user_info=v2.include_user_info,+ reply_enhancements=v2.reply_enhancements,default_backend=v2.agents.default_backend,)diff --git a/config/v2_settings.py b/config/v2_settings.pyindex f793f44b7..3658b867b 100644--- a/config/v2_settings.py+++ b/config/v2_settings.py@@ -14,6 +14,8 @@ logger = logging.getLogger(__name__)DEFAULT_SHOW_MESSAGE_TYPES: List[str] = []ALLOWED_MESSAGE_TYPES = {"system", "assistant", "toolcall"}+SCHEMA_VERSION = 3+SCOPED_KEY_SEP = "::"# Bind code prefix and length_BIND_CODE_PREFIX = "vr-"@@ -38,6 +40,40 @@ def _now_iso() -> str:return datetime.now(timezone.utc).isoformat()+def _make_scoped_key(platform: str, item_id: str) -> str:+ return f"{platform}{SCOPED_KEY_SEP}{item_id}"+++def _split_scoped_key(scoped_key: str) -> Tuple[Optional[str], str]:+ if SCOPED_KEY_SEP in scoped_key:+ platform, raw_id = scoped_key.split(SCOPED_KEY_SEP, 1)+ if platform:+ return platform, raw_id+ return None, scoped_key+++def _infer_channel_platform(channel_id: str) -> str:+ cid = str(channel_id)+ if cid.startswith("oc_"):+ return "lark"+ if cid and cid[0] in {"C", "G", "D"}:+ return "slack"+ if cid.isdigit() and len(cid) >= 15:+ return "discord"+ return "unknown"+++def _infer_user_platform(user_id: str) -> str:+ uid = str(user_id)+ if uid.startswith("ou_"):+ return "lark"+ if uid and uid[0] in {"U", "W"}:+ return "slack"+ if uid.isdigit() and len(uid) >= 15:+ return "discord"+ return "unknown"++@dataclassclass RoutingSettings:agent_backend: Optional[str] = None@@ -180,43 +216,86 @@ class SettingsStore:logger.error("Failed to load settings: invalid format")return- # --- Channels ---- raw_channels = payload.get("channels")- if raw_channels is None:- # Legacy format or empty — tolerate missing channels key- raw_channels = {}- if not isinstance(raw_channels, dict):- logger.error("Failed to load settings: channels must be an object")- raw_channels = {}channels: Dict[str, ChannelSettings] = {}- for channel_id, cp in raw_channels.items():- if not isinstance(cp, dict):- continue- channels[channel_id] = ChannelSettings(- enabled=cp.get("enabled", False),- show_message_types=normalize_show_message_types(cp.get("show_message_types")),- custom_cwd=cp.get("custom_cwd"),- routing=_parse_routing(cp.get("routing") or {}),- require_mention=cp.get("require_mention"),- )-- # --- Users ---- raw_users = payload.get("users") or {}users: Dict[str, UserSettings] = {}- if isinstance(raw_users, dict):- for user_id, up in raw_users.items():- if not isinstance(up, dict):+ migrated_legacy_channels = False++ # --- New schema (v3): payload["scopes"]["channel"|"user"][platform][id] ---+ scopes = payload.get("scopes")+ if isinstance(scopes, dict):+ raw_channel_scopes = scopes.get("channel") or {}+ if isinstance(raw_channel_scopes, dict):+ for platform, items in raw_channel_scopes.items():+ if not isinstance(items, dict):+ continue+ for channel_id, cp in items.items():+ if not isinstance(cp, dict):+ continue+ key = _make_scoped_key(str(platform), str(channel_id))+ channels[key] = ChannelSettings(+ enabled=cp.get("enabled", False),+ show_message_types=normalize_show_message_types(cp.get("show_message_types")),+ custom_cwd=cp.get("custom_cwd"),+ routing=_parse_routing(cp.get("routing") or {}),+ require_mention=cp.get("require_mention"),+ )++ raw_user_scopes = scopes.get("user") or {}+ if isinstance(raw_user_scopes, dict):+ for platform, items in raw_user_scopes.items():+ if not isinstance(items, dict):+ continue+ for user_id, up in items.items():+ if not isinstance(up, dict):+ continue+ key = _make_scoped_key(str(platform), str(user_id))+ users[key] = UserSettings(+ display_name=up.get("display_name", ""),+ is_admin=up.get("is_admin", False),+ bound_at=up.get("bound_at", ""),+ enabled=up.get("enabled", True),+ show_message_types=normalize_show_message_types(up.get("show_message_types")),+ custom_cwd=up.get("custom_cwd"),+ routing=_parse_routing(up.get("routing") or {}),+ dm_chat_id=up.get("dm_chat_id", ""),+ )+ else:+ # --- Legacy schema: flat payload["channels"] / payload["users"] ---+ raw_channels = payload.get("channels") or {}+ if not isinstance(raw_channels, dict):+ logger.error("Failed to load settings: channels must be an object")+ raw_channels = {}+ for channel_id, cp in raw_channels.items():+ if not isinstance(cp, dict):continue- users[user_id] = UserSettings(- display_name=up.get("display_name", ""),- is_admin=up.get("is_admin", False),- bound_at=up.get("bound_at", ""),- enabled=up.get("enabled", True),- show_message_types=normalize_show_message_types(up.get("show_message_types")),- custom_cwd=up.get("custom_cwd"),- routing=_parse_routing(up.get("routing") or {}),- dm_chat_id=up.get("dm_chat_id", ""),+ platform = _infer_channel_platform(str(channel_id))+ scoped_key = _make_scoped_key(platform, str(channel_id))+ channels[scoped_key] = ChannelSettings(+ enabled=cp.get("enabled", False),+ show_message_types=normalize_show_message_types(cp.get("show_message_types")),+ custom_cwd=cp.get("custom_cwd"),+ routing=_parse_routing(cp.get("routing") or {}),+ require_mention=cp.get("require_mention"),)+ migrated_legacy_channels = True++ raw_users = payload.get("users") or {}+ if isinstance(raw_users, dict):+ for user_id, up in raw_users.items():+ if not isinstance(up, dict):+ continue+ platform = _infer_user_platform(str(user_id))+ scoped_key = _make_scoped_key(platform, str(user_id))+ users[scoped_key] = UserSettings(+ display_name=up.get("display_name", ""),+ is_admin=up.get("is_admin", False),+ bound_at=up.get("bound_at", ""),+ enabled=up.get("enabled", True),+ show_message_types=normalize_show_message_types(up.get("show_message_types")),+ custom_cwd=up.get("custom_cwd"),+ routing=_parse_routing(up.get("routing") or {}),+ dm_chat_id=up.get("dm_chat_id", ""),+ )# --- Bind Codes ---raw_codes = payload.get("bind_codes") or []@@ -237,6 +316,11 @@ class SettingsStore:)self.settings = SettingsState(channels=channels, users=users, bind_codes=bind_codes)++ if migrated_legacy_channels:+ logger.info("Migrating legacy channel settings to platform-scoped schema")+ self.save()+try:self._file_mtime = self.settings_path.stat().st_mtimeexcept FileNotFoundError:@@ -244,11 +328,18 @@ class SettingsStore:def save(self) -> None:paths.ensure_data_dirs()- payload: dict = {"channels": {}, "users": {}, "bind_codes": []}-- # Channels- for channel_id, s in self.settings.channels.items():- payload["channels"][channel_id] = {+ payload: dict = {+ "schema_version": SCHEMA_VERSION,+ "scopes": {"channel": {}, "user": {}},+ "bind_codes": [],+ }++ # Channels (platform-scoped)+ for scoped_key, s in self.settings.channels.items():+ platform, channel_id = _split_scoped_key(scoped_key)+ if not platform:+ platform = _infer_channel_platform(channel_id)+ payload["scopes"]["channel"].setdefault(platform, {})[channel_id] = {"enabled": s.enabled,"show_message_types": s.show_message_types,"custom_cwd": s.custom_cwd,@@ -256,9 +347,12 @@ class SettingsStore:"require_mention": s.require_mention,}- # Users- for user_id, u in self.settings.users.items():- payload["users"][user_id] = {+ # Users (platform-scoped)+ for scoped_key, u in self.settings.users.items():+ platform, user_id = _split_scoped_key(scoped_key)+ if not platform:+ platform = _infer_user_platform(user_id)+ payload["scopes"]["user"].setdefault(platform, {})[user_id] = {"display_name": u.display_name,"is_admin": u.is_admin,"bound_at": u.bound_at,@@ -290,37 +384,118 @@ class SettingsStore:# --- Channel helpers ---- def get_channel(self, channel_id: str) -> ChannelSettings:- if channel_id not in self.settings.channels:- self.settings.channels[channel_id] = ChannelSettings()- return self.settings.channels[channel_id]+ 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 _user_key(self, user_id: str, platform: Optional[str] = None) -> str:+ return _make_scoped_key(platform, user_id) if platform else user_id++ def get_channels_for_platform(self, platform: str) -> Dict[str, ChannelSettings]:+ result: Dict[str, ChannelSettings] = {}+ prefix = f"{platform}{SCOPED_KEY_SEP}"+ for key, settings in self.settings.channels.items():+ if key.startswith(prefix):+ result[key[len(prefix) :]] = settings+ return result++ def set_channels_for_platform(self, platform: str, channels: Dict[str, ChannelSettings]) -> None:+ prefix = f"{platform}{SCOPED_KEY_SEP}"+ self.settings.channels = {k: v for k, v in self.settings.channels.items() if not k.startswith(prefix)}+ for channel_id, settings in channels.items():+ self.settings.channels[self._channel_key(str(channel_id), platform)] = settings++ def get_users_for_platform(self, platform: str) -> Dict[str, UserSettings]:+ result: Dict[str, UserSettings] = {}+ prefix = f"{platform}{SCOPED_KEY_SEP}"+ for key, settings in self.settings.users.items():+ if key.startswith(prefix):+ result[key[len(prefix) :]] = settings+ return result++ def set_users_for_platform(self, platform: str, users: Dict[str, UserSettings]) -> None:+ prefix = f"{platform}{SCOPED_KEY_SEP}"+ self.settings.users = {k: v for k, v in self.settings.users.items() if not k.startswith(prefix)}+ for user_id, settings in users.items():+ self.settings.users[self._user_key(str(user_id), platform)] = settings++ def get_channel(self, channel_id: str, platform: Optional[str] = None) -> ChannelSettings:+ key = self._channel_key(channel_id, platform)+ if platform is None and key not in self.settings.channels:+ suffix = f"{SCOPED_KEY_SEP}{channel_id}"+ for scoped_key, settings in self.settings.channels.items():+ if scoped_key.endswith(suffix):+ return settings+ if key not in self.settings.channels:+ self.settings.channels[key] = ChannelSettings()+ return self.settings.channels[key]++ def find_channel(self, channel_id: str, platform: Optional[str] = None) -> Optional[ChannelSettings]:+ key = self._channel_key(channel_id, platform)+ if key in self.settings.channels:+ return self.settings.channels[key]+ if platform is None:+ suffix = f"{SCOPED_KEY_SEP}{channel_id}"+ for scoped_key, settings in self.settings.channels.items():+ if scoped_key.endswith(suffix):+ return settings+ return None- def update_channel(self, channel_id: str, settings: ChannelSettings) -> None:- self.settings.channels[channel_id] = settings+ def update_channel(self, channel_id: str, settings: ChannelSettings, platform: Optional[str] = None) -> None:+ key = self._channel_key(channel_id, platform)+ self.settings.channels[key] = settingsself.save()# --- User helpers ---- def get_user(self, user_id: str) -> Optional[UserSettings]:+ def get_user(self, user_id: str, platform: Optional[str] = None) -> Optional[UserSettings]:"""Get user settings, or None if user is not bound."""- return self.settings.users.get(user_id)+ key = self._user_key(user_id, platform)+ user = self.settings.users.get(key)+ if user is not None or platform:+ return user+ suffix = f"{SCOPED_KEY_SEP}{user_id}"+ for scoped_key, value in self.settings.users.items():+ if scoped_key.endswith(suffix):+ return value+ return None- def is_bound_user(self, user_id: str) -> bool:- return user_id in self.settings.users+ def is_bound_user(self, user_id: str, platform: Optional[str] = None) -> bool:+ if platform:+ return self._user_key(user_id, platform) in self.settings.users+ if user_id in self.settings.users:+ return True+ suffix = f"{SCOPED_KEY_SEP}{user_id}"+ return any(key.endswith(suffix) for key in self.settings.users.keys())- def is_admin(self, user_id: str) -> bool:- user = self.settings.users.get(user_id)- return user is not None and user.is_admin+ def is_admin(self, user_id: str, platform: Optional[str] = None) -> bool:+ if platform:+ user = self.settings.users.get(self._user_key(user_id, platform))+ return user is not None and user.is_admin+ if user_id in self.settings.users:+ return self.settings.users[user_id].is_admin+ suffix = f"{SCOPED_KEY_SEP}{user_id}"+ for key, value in self.settings.users.items():+ if key.endswith(suffix):+ return value.is_admin+ return False- def has_any_admin(self) -> bool:+ def has_any_admin(self, platform: Optional[str] = None) -> bool:"""Return True if at least one admin exists."""+ if platform:+ prefix = f"{platform}{SCOPED_KEY_SEP}"+ return any(u.is_admin for key, u in self.settings.users.items() if key.startswith(prefix))return any(u.is_admin for u in self.settings.users.values())- def get_admins(self) -> Dict[str, UserSettings]:+ def get_admins(self, platform: Optional[str] = None) -> Dict[str, UserSettings]:"""Return all admin users."""+ if platform:+ prefix = f"{platform}{SCOPED_KEY_SEP}"+ return {uid: u for uid, u in self.settings.users.items() if uid.startswith(prefix) and u.is_admin}return {uid: u for uid, u in self.settings.users.items() if u.is_admin}- def add_user(self, user_id: str, display_name: str, is_admin: bool = False) -> UserSettings:+ def add_user(+ self, user_id: str, display_name: str, is_admin: bool = False, platform: Optional[str] = None+ ) -> UserSettings:"""Add a new bound user. Returns the created UserSettings."""user = UserSettings(display_name=display_name,@@ -328,12 +503,12 @@ class SettingsStore:bound_at=_now_iso(),enabled=True,)- self.settings.users[user_id] = user+ self.settings.users[self._user_key(user_id, platform)] = userself.save()return userdef bind_user_with_code(- self, user_id: str, display_name: str, code: str, dm_chat_id: str = ""+ self, user_id: str, display_name: str, code: str, dm_chat_id: str = "", platform: Optional[str] = None) -> Tuple[bool, bool]:"""Atomically validate code, create user, and consume code.@@ -346,7 +521,7 @@ class SettingsStore:self.maybe_reload()# Check already bound- if self.is_bound_user(user_id):+ if self.is_bound_user(user_id, platform=platform):return False, False# Validate code@@ -355,7 +530,7 @@ class SettingsStore:return False, False# Auto-admin for first user- is_admin = not self.has_any_admin()+ is_admin = not self.has_any_admin(platform=platform)# Create useruser = UserSettings(@@ -365,37 +540,35 @@ class SettingsStore:enabled=True,dm_chat_id=dm_chat_id,)- self.settings.users[user_id] = user+ scoped_user_id = self._user_key(user_id, platform)+ self.settings.users[scoped_user_id] = user# Consume code- bc.used_by.append(user_id)+ bc.used_by.append(scoped_user_id)if bc.type == "one_time":bc.is_active = Falseself.save()return True, is_admin- def update_user(self, user_id: str, settings: UserSettings) -> None:- self.settings.users[user_id] = settings+ def update_user(self, user_id: str, settings: UserSettings, platform: Optional[str] = None) -> None:+ self.settings.users[self._user_key(user_id, platform)] = settingsself.save()- def remove_user(self, user_id: str) -> bool:- if user_id in self.settings.users:- del self.settings.users[user_id]+ def remove_user(self, user_id: str, platform: Optional[str] = None) -> bool:+ key = self._user_key(user_id, platform)+ if key in self.settings.users:+ del self.settings.users[key]self.save()return Truereturn False- def set_admin(self, user_id: str, is_admin: bool) -> bool:- """Set admin flag for a user. Returns False if user not found or trying to remove last admin."""- user = self.settings.users.get(user_id)+ def set_admin(self, user_id: str, is_admin: bool, platform: Optional[str] = None) -> bool:+ """Set admin flag for a user. Returns False if user not found."""+ key = self._user_key(user_id, platform)+ user = self.settings.users.get(key)if user is None:return False- if not is_admin:- # Prevent removing the last admin- admin_count = sum(1 for u in self.settings.users.values() if u.is_admin)- if admin_count <= 1 and user.is_admin:- return Falseuser.is_admin = is_adminself.save()return Truediff --git a/core/auth.py b/core/auth.pyindex f9d091ec2..68c8c0ce6 100644--- a/core/auth.py+++ b/core/auth.py@@ -62,6 +62,7 @@ def check_auth(user_id: str,channel_id: str,is_dm: bool,+ platform: str | None = None,action: str = "",settings_manager: object | None = None,store: "SettingsStore | None" = None,@@ -100,18 +101,36 @@ def check_auth(if is_dm:if action in BIND_EXEMPT_COMMANDS:return AuthResult(allowed=True, is_dm=True)- if not store.is_bound_user(user_id):+ try:+ is_bound = store.is_bound_user(user_id, platform=platform)+ except TypeError:+ is_bound = store.is_bound_user(user_id)+ if not is_bound:return AuthResult(allowed=False, denial="unbound_dm", is_dm=True)# DM users skip channel authorizationelse:# 2. Channel authorization- ch = store.settings.channels.get(channel_id)+ if hasattr(store, "find_channel"):+ try:+ ch = store.find_channel(channel_id, platform=platform)+ except TypeError:+ ch = store.find_channel(channel_id)+ else:+ ch = getattr(getattr(store, "settings", None), "channels", {}).get(channel_id)if not ch or not ch.enabled:return AuthResult(allowed=False, denial="unauthorized_channel", is_dm=False)# 3. Admin check for protected actionsif _is_admin_protected(action):- if store.has_any_admin() and not store.is_admin(user_id):+ try:+ has_admin = store.has_any_admin(platform=platform)+ except TypeError:+ has_admin = store.has_any_admin()+ try:+ is_admin = store.is_admin(user_id, platform=platform)+ except TypeError:+ is_admin = store.is_admin(user_id)+ if has_admin and not is_admin:return AuthResult(allowed=False, denial="not_admin", is_dm=is_dm)return AuthResult(allowed=True, is_dm=is_dm)diff --git a/core/controller.py b/core/controller.pyindex e0481cb83..b7c98ec03 100644--- a/core/controller.py+++ b/core/controller.py@@ -90,7 +90,7 @@ class Controller:# Initialize managersself.session_manager = SessionManager()- self.settings_manager = SettingsManager()+ self.settings_manager = SettingsManager(platform=self.config.platform)self.sessions = self.settings_manager.sessions# Migrate legacy per-channel language into global configdiff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.pyindex 3d392069f..122c7c0b3 100644--- a/core/handlers/message_handler.py+++ b/core/handlers/message_handler.py@@ -266,10 +266,10 @@ class MessageHandler(BaseHandler):"""Prepend user identity as [username<user_id>] to the message."""try:user_info = await self.im_client.get_user_info(context.user_id)- raw_name = user_info.get("display_name") or user_info.get("name") or "unknown"+ raw_name = user_info.get("display_name") or user_info.get("name") or context.user_idexcept Exception as e:logger.debug(f"Failed to fetch user info for {context.user_id}: {e}")- raw_name = "unknown"+ raw_name = context.user_idname = self._sanitize_identity(raw_name)uid = self._sanitize_identity(context.user_id)return f"[{name}<{uid}>] {message}"@@ -395,14 +395,30 @@ class MessageHandler(BaseHandler):# Quick-reply button: treat the button text as a new user messagereply_text = callback_data[len("quick_reply:") :]if reply_text:- # Remove buttons from the original message+ # Update the card: preserve original text, append user+ # action, and strip the buttons.if context.message_id:try:- await self.im_client.remove_inline_keyboard(context, context.message_id)+ original = self.controller.message_dispatcher.pop_quick_reply_text(context.message_id)+ if original is not None:+ note = self._t("message.quickReplyNote", text=reply_text)+ updated = f"{original}\n\n---\n{note}"+ else:+ updated = None+ await self.im_client.remove_inline_keyboard(context, context.message_id, text=updated)except Exception as err:logger.debug(f"Failed to remove quick-reply buttons: {err}")- # Dispatch as a normal user message+ # Add ack reaction on the card message before dispatching+ if context.message_id:+ try:+ await self.im_client.add_reaction(context, context.message_id, ":eyes:")+ except Exception as err:+ logger.debug(f"Failed to add quick-reply ack reaction: {err}")++ # Dispatch as a normal user message (message_id=None to+ # bypass dedup — this is a synthetic message, not a real+ # platform message that could be replayed).context_for_reply = MessageContext(user_id=context.user_id,channel_id=context.channel_id,diff --git a/core/handlers/settings_handler.py b/core/handlers/settings_handler.pyindex 125320528..1f7bd8e0e 100644--- a/core/handlers/settings_handler.py+++ b/core/handlers/settings_handler.py@@ -26,6 +26,39 @@ class SettingsHandler(BaseHandler):"toolcall": self._t("messageType.toolcall"),}+ def _format_settings_update_message(+ self,+ show_message_types: list,+ require_mention: Optional[bool],+ language: Optional[str],+ language_saved: bool,+ ) -> str:+ display_names = self._message_type_display_names()+ selected_names = [display_names.get(msg_type, msg_type) for msg_type in show_message_types]+ selected_text = ", ".join(selected_names) if selected_names else "-"++ if require_mention is None:+ slack_cfg = getattr(self.config, "slack", None)+ default_require = bool(getattr(slack_cfg, "require_mention", False))+ default_state = self._t("common.on") if default_require else self._t("common.off")+ mention_text = f"{self._t('common.default')} {default_state}"+ else:+ mention_text = self._t("common.on") if require_mention else self._t("common.off")++ language_text = self._t(f"language.{language}") if language else self._t("language.systemDefault")+ if language and language_text == f"language.{language}":+ language_text = language++ lines = [+ f"✅ {self._t('success.settingsUpdated')}",+ f"{self._t('modal.settings.showMessageTypes')} **{selected_text}**",+ f"{self._t('modal.settings.requireMention')} **{mention_text}**",+ f"{self._t('modal.settings.language')} **{language_text}**",+ ]+ if not language_saved:+ lines.append(f"⚠️ {self._t('error.languageUpdateFailed')}")+ return "\n".join(lines)+def _get_agent_display_name(self, context: MessageContext) -> str:"""Return a friendly agent name for the current context."""agent_name = self.controller.resolve_agent_for_context(context)@@ -503,12 +536,13 @@ class SettingsHandler(BaseHandler):)if notify_user:- await self.im_client.send_message(context, f"✅ {self._t('success.settingsUpdated')}")- if not language_saved:- await self.im_client.send_message(- context,- f"⚠️ {self._t('error.languageUpdateFailed')}",- )+ message = self._format_settings_update_message(+ show_message_types=show_message_types,+ require_mention=require_mention,+ language=language,+ language_saved=language_saved,+ )+ await self.im_client.send_message(context, message, parse_mode="markdown")except Exception as e:logger.error(f"Error updating settings: {e}")diff --git a/core/message_dispatcher.py b/core/message_dispatcher.pyindex c24869e95..e4b57b5c7 100644--- a/core/message_dispatcher.py+++ b/core/message_dispatcher.py@@ -25,6 +25,9 @@ class ConsolidatedMessageDispatcher:self._consolidated_message_buffers: dict[str, str] = {}self._consolidated_message_locks: dict[str, asyncio.Lock] = {}self._thread_current_message_id: dict[str, str] = {}+ # Cache the body text of quick-reply card messages so the callback+ # handler can retrieve the original text when updating the card.+ self._quick_reply_text_cache: dict[str, str] = {}def _get_settings_key(self, context: MessageContext) -> str:return self.controller._get_settings_key(context)@@ -190,6 +193,15 @@ class ConsolidatedMessageDispatcher:if enhanced and enhanced.files:await self._upload_file_links(im_client, target_context, enhanced.files)+ # Final result closes the current turn: clear consolidated+ # assistant/tool/system message state so the next user turn starts+ # a fresh log message instead of appending to the previous one.+ consolidated_key = self._get_consolidated_message_key(context)+ lock = self._get_consolidated_message_lock(consolidated_key)+ async with lock:+ self._consolidated_message_ids.pop(consolidated_key, None)+ self._consolidated_message_buffers.pop(consolidated_key, None)+returnif canonical_type not in {"system", "assistant", "toolcall"}:@@ -327,12 +339,18 @@ class ConsolidatedMessageDispatcher:row.append(InlineButton(text=btn.text, callback_data=callback))keyboard = InlineKeyboard(buttons=[row])- await im_client.send_message_with_buttons(+ msg_id = await im_client.send_message_with_buttons(context,text,keyboard,parse_mode=parse_mode,)+ if msg_id:+ self._quick_reply_text_cache[msg_id] = text++ def pop_quick_reply_text(self, message_id: str) -> str | None:+ """Pop and return the cached text for a quick-reply card message."""+ return self._quick_reply_text_cache.pop(message_id, None)async def _upload_file_links(self,@@ -369,11 +387,41 @@ class ConsolidatedMessageDispatcher:if not any(resolved == root or resolved.is_relative_to(root) for root in allowed_roots):logger.warning("File outside allowed roots, skipping: %s", fl.path)continue++ # Use link label as title, but preserve file extension so users can+ # download/open files correctly on all platforms.+ upload_title = (fl.label or "").strip() or os.path.basename(fl.path)+ src_ext = resolved.suffix+ if src_ext and not Path(upload_title).suffix:+ upload_title = f"{upload_title}{src_ext}"+try:- await im_client.upload_file_from_path(- context,- file_path=str(resolved),- title=fl.label or os.path.basename(fl.path),- )+ if getattr(fl, "is_image", False):+ try:+ await im_client.upload_image_from_path(+ context,+ file_path=str(resolved),+ title=upload_title,+ )+ except Exception as image_err:+ logger.warning(+ "Image upload failed for %s, fallback to file upload: %r",+ fl.path,+ image_err,+ )+ await im_client.upload_file_from_path(+ context,+ file_path=str(resolved),+ title=upload_title,+ )+ else:+ await im_client.upload_file_from_path(+ context,+ file_path=str(resolved),+ title=upload_title,+ )+ except NotImplementedError:+ logger.debug("IM client does not implement file uploads; skipping")+ returnexcept Exception as err:- logger.warning("Failed to upload file %s: %s", fl.path, err)+ logger.warning("Failed to upload file %s: %r", fl.path, err)diff --git a/core/reply_enhancer.py b/core/reply_enhancer.pyindex e3a4a32e8..3807d2fc8 100644--- a/core/reply_enhancer.py+++ b/core/reply_enhancer.py@@ -32,6 +32,7 @@ class FileLink:label: str # Markdown link text (e.g. "screenshot")path: str # Absolute local path (e.g. "/tmp/shot.png")+ is_image: bool = False # True when parsed from @dataclass@@ -54,8 +55,10 @@ class EnhancedReply:# Regex patterns# ----------------------------------------------------------------------------# Matches markdown links with file:// URLs: [label](file:///path)-_FILE_LINK_RE = re.compile(r"\[([^\]]*)\]\((file://[^)]+)\)")+# Matches markdown links with file:// URLs, including image links:+# [label](file:///path)+# +_FILE_LINK_RE = re.compile(r"(!?)\[([^\]]*)\]\((file://[^)]+)\)")# Matches the quick-reply button block at the end of the text.# A horizontal rule (``---``) on its own line, followed by one or more@@ -95,7 +98,7 @@ def process_reply(text: str) -> EnhancedReply:def _extract_file_links(text: str) -> List[FileLink]:"""Return all ``FileLink`` instances found in *text*."""results: List[FileLink] = []- for label, url in _FILE_LINK_RE.findall(text):+ for bang, label, url in _FILE_LINK_RE.findall(text):parsed = urlparse(url)if parsed.scheme != "file":continue@@ -103,7 +106,7 @@ def _extract_file_links(text: str) -> List[FileLink]:if not os.path.isabs(path):logger.warning("Skipping non-absolute file link: %s", url)continue- results.append(FileLink(label=label, path=path))+ results.append(FileLink(label=label, path=path, is_image=(bang == "!")))return results@@ -111,8 +114,8 @@ def _strip_file_links(text: str) -> str:"""Replace ``[label](file://…)`` with just the label."""def _replacer(m: re.Match) -> str:- label = m.group(1)- url = m.group(2)+ label = m.group(2)+ url = m.group(3)if url.startswith("file://"):return label # keep the label text, drop the linkreturn m.group(0)@@ -148,25 +151,30 @@ def _extract_buttons(text: str) -> Tuple[List[QuickReplyButton], str]:# ---------------------------------------------------------------------------REPLY_ENHANCEMENTS_PROMPT = """\-# Vibe Remote 增强回复+# Vibe Remote++Vibe Remote 是一个将 AI Agent 接入 Slack 等 IM 平台的中间层,\+用户正使用 IM 软件通过 Vibe Remote 的转发与你进行交互。-用户正在通过 Vibe Remote 与你交互——Vibe Remote 是一个将 AI Agent 接入 Slack 等 IM 平台的中间层,\-用户在聊天窗口中向你发送消息,你的回复经由 Vibe Remote 转发给用户。\你有两个可选的回复增强能力:## 1. 发送文件用 Markdown 链接 + `file://` 协议即可将本地文件发送给用户:-[描述](file:///绝对路径)-示例:[截图](file:///tmp/result.png)+示例:[文件1](file:///tmp/result.pdf)Vibe Remote 会自动将文件作为附件发送。+### 图片语法+如果你希望按“图片附件”发送(而不是普通文件),请使用 Markdown 图片语法:+示例:+## 2. 快捷回复按钮在消息最末尾,用 `---` 分隔线后跟 `[按钮文字]` 提供可点击的快捷回复,示例:----[👌好的] | [✅提交PR] | [先review一下]+[👌 继续吧] | [✅ 提交PR] | [👀 先review一下]规则:+- 根据对话上下文和用户习惯推测用户可能的回复意图,仅在确实对用户有帮助时添加+- 不要添加与用户下一步意图无关的废话,如:知道了、收到、谢谢- 必须放在消息最末尾,`---` 分隔线之后-- 每个按钮用 `[文字]` 包裹,用 `|` 分隔,文字中可包含 emoji-- 根据对话上下文和用户习惯推测用户可能的回复,仅在确实有帮助时添加-- 最多 2-4 个按钮,每个不超过 20 字符\+- 每个按钮用 `[文字]` 包裹,用 `|` 分隔,可用 emoji 开头优化表达+- 最多 2-4 个按钮,每个不超过 20 字符"""diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.pyindex e3c576d23..059be268d 100644--- a/modules/agents/claude_agent.py+++ b/modules/agents/claude_agent.py@@ -293,22 +293,19 @@ class ClaudeAgent(BaseAgent):continueif message_type == "result":- pending = self._pending_assistant_message.pop(composite_key, None)+ self._pending_assistant_message.pop(composite_key, None)result_text = getattr(message, "result", None)- used_fallback = Falseif not result_text:+ # ResultMessage had no text; use the last assistant+ # text as a fallback so the user still sees output.fallback = self._last_assistant_text.get(composite_key)if fallback:result_text = fallback- used_fallback = True- if pending and not used_fallback:- await self.controller.emit_agent_message(- context,- "assistant",- pending,- parse_mode="markdown",- )+ # NOTE: The pending assistant message is intentionally+ # NOT emitted here. ResultMessage.result already+ # contains the same text as the last AssistantMessage,+ # so sending both would duplicate the content.await self.emit_result_message(context,diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.pyindex af975a832..b3b40b686 100644--- a/modules/agents/codex/agent.py+++ b/modules/agents/codex/agent.py@@ -96,11 +96,6 @@ class CodexAgent(BaseAgent):# If a turn is active, interrupt it firstactive_turn = self._session_mgr.get_active_turn(request.base_session_id)if active_turn:- await self.controller.emit_agent_message(- request.context,- "notify",- "⚠️ Interrupting previous Codex task...",- )try:await transport.send_request("turn/interrupt",@@ -125,6 +120,9 @@ class CodexAgent(BaseAgent):turn_params: Dict[str, Any] = {"threadId": thread_id,"input": input_items,+ # Enforce non-interactive execution for Codex backend.+ "approvalPolicy": "never",+ "sandbox": "danger-full-access",}if effective_model:turn_params["model"] = effective_modeldiff --git a/modules/im/base.py b/modules/im/base.pyindex e2212665a..0bfdc48b6 100644--- a/modules/im/base.py+++ b/modules/im/base.py@@ -192,10 +192,37 @@ class BaseIMClient(ABC):user_id=user_id,channel_id=channel_id,is_dm=is_dm,+ platform=getattr(settings_manager, "platform", None),action=resolved_action,settings_manager=settings_manager,)+ def build_auth_denial_text(self, denial: str, channel_id: Optional[str] = None) -> Optional[str]:+ """Build a localized denial message from centralized auth result.++ Keeps denial copy in one place so IM implementations only handle+ delivery mechanics (how to send), not message wording/branching.+ """++ def _translate(key: str, **kwargs) -> str:+ translator = getattr(self, "_t", None)+ if callable(translator):+ try:+ return translator(key, channel_id, **kwargs)+ except TypeError:+ return translator(key, **kwargs)+ from vibe.i18n import t as i18n_t++ return i18n_t(key, "en", **kwargs)++ if denial == "unbound_dm":+ return _translate("bind.dmNotBound")+ if denial == "unauthorized_channel":+ return f"❌ {_translate('error.channelNotEnabled')}"+ if denial == "not_admin":+ return _translate("permission.adminOnly")+ return None+@abstractmethodasync def send_message(self, context: MessageContext, text: str, parse_mode: Optional[str] = None, reply_to: Optional[str] = None@@ -258,6 +285,19 @@ class BaseIMClient(ABC):"""raise NotImplementedError+ async def upload_image_from_path(+ self,+ context: MessageContext,+ file_path: str,+ title: Optional[str] = None,+ ) -> str:+ """Upload a local image to the conversation (optional per platform).++ Default behavior falls back to ``upload_file_from_path`` so platforms+ without native image upload support still deliver the attachment.+ """+ return await self.upload_file_from_path(context, file_path, title=title)+@abstractmethodasync def edit_message(self,@@ -299,6 +339,16 @@ class BaseIMClient(ABC):parse_mode=parse_mode,)+ async def dismiss_form_message(self, context: MessageContext) -> None:+ """Dismiss a form card message after successful submission.++ Platforms that render forms as persistent chat messages (Feishu,+ Discord) should override this to delete or replace the card so+ it doesn't remain interactive. Platforms whose forms are+ ephemeral modals (Slack) can keep the default no-op.+ """+ pass+@abstractmethodasync def answer_callback(self, callback_id: str, text: Optional[str] = None, show_alert: bool = False) -> bool:"""Answer a callback query from inline buttondiff --git a/modules/im/discord.py b/modules/im/discord.pyindex baa97e4a1..6f9d11739 100644--- a/modules/im/discord.py+++ b/modules/im/discord.py@@ -2,6 +2,7 @@ import asyncioimport ioimport jsonimport logging+import osfrom typing import Dict, Any, Optional, Callable, Listimport aiohttp@@ -101,7 +102,29 @@ class DiscordBot(BaseIMClient):def run(self):if not self.config.bot_token:raise ValueError("Discord bot token is required")- self.client.run(self.config.bot_token)++ async def _run():+ # Inject SOCKS proxy connector inside the event loop (required+ # by aiohttp). Must happen before login() creates the session.+ from vibe.proxy import get_system_socks_proxy++ socks_url = get_system_socks_proxy()+ if socks_url:+ try:+ from aiohttp_socks import ProxyConnector++ self.client.http.connector = ProxyConnector.from_url(socks_url, rdns=True)+ logger.info("Discord using SOCKS proxy: %s", socks_url)+ except ImportError:+ logger.warning("SOCKS proxy detected but aiohttp_socks not installed")++ async with self.client:+ await self.client.start(self.config.bot_token)++ try:+ asyncio.run(_run())+ except KeyboardInterrupt:+ returnasync def shutdown(self) -> None:await self.client.close()@@ -263,6 +286,19 @@ class DiscordBot(BaseIMClient):text: Optional[str] = None,parse_mode: Optional[str] = None,) -> bool:+ # When called from a button callback, use the interaction's message+ # object to edit directly (the interaction response is already deferred).+ interaction = (context.platform_specific or {}).get("interaction") if context.platform_specific else None+ if interaction is not None and interaction.message is not None:+ try:+ kwargs: dict = {"view": None}+ if text is not None:+ kwargs["content"] = text+ await interaction.message.edit(**kwargs)+ return True+ except Exception as err:+ logger.info("Failed to remove Discord keyboard via interaction.message: %s", err)+ return Falsereturn await self.edit_message(context, message_id, text=text, keyboard=None, parse_mode=parse_mode)async def answer_callback(self, callback_id: str, text: Optional[str] = None, show_alert: bool = False) -> bool:@@ -313,6 +349,23 @@ class DiscordBot(BaseIMClient):message = await target.send(file=file_obj)return str(message.id)+ async def upload_file_from_path(+ self,+ context: MessageContext,+ file_path: str,+ title: Optional[str] = None,+ ) -> str:+ """Upload a local file to the Discord conversation."""+ target = await self._fetch_channel(context.thread_id or context.channel_id)+ if target is None:+ raise RuntimeError("Discord channel not found")++ # Keep original extension for proper Discord preview handling.+ filename = os.path.basename(file_path)+ file_obj = discord.File(file_path, filename=filename)+ message = await target.send(file=file_obj)+ return str(message.id)+async def download_file(self,file_info: Dict[str, Any],@@ -406,26 +459,27 @@ class DiscordBot(BaseIMClient):async def _send_auth_denial(self, channel_id: str, user_id: str, auth_result, interaction=None):"""Send denial message for failed auth check."""- if auth_result.denial == "unbound_dm":- hint = self._t("bind.dmNotBound", channel_id)- if interaction:- try:- await interaction.response.send_message(hint, ephemeral=True)- except Exception:- pass- else:- channel = self.client.get_channel(int(channel_id))- if channel:- await channel.send(content=hint)- elif auth_result.denial == "unauthorized_channel":- await self._send_unauthorized_message(channel_id)- elif auth_result.denial == "not_admin":- msg = i18n_t("permission.adminOnly")- if interaction:- try:+ msg = self.build_auth_denial_text(auth_result.denial, channel_id)+ if not msg:+ return++ if interaction:+ try:+ if not interaction.response.is_done():await interaction.response.send_message(msg, ephemeral=True)- except Exception:- pass+ else:+ await interaction.followup.send(msg, ephemeral=True)+ except Exception as err:+ logger.debug("Failed to send interaction auth denial: %s", err)+ return++ channel = await self._fetch_channel(channel_id)+ if channel is None:+ return+ try:+ await channel.send(content=msg)+ except Exception as err:+ logger.debug("Failed to send channel auth denial: %s", err)async def _maybe_create_thread(self, message: discord.Message) -> Optional[discord.Thread]:if isinstance(message.channel, discord.Thread):@@ -583,7 +637,7 @@ class DiscordBot(BaseIMClient):channel_id,_is_dm,)- await submit_interaction.response.send_message("✅ Working directory updated.", ephemeral=True)+ await submit_interaction.response.defer(ephemeral=True)modal = ChangeCwdModal()modal._outer = self@@ -773,11 +827,11 @@ class DiscordBot(BaseIMClient):channel_id or str(save_interaction.channel_id or ""),require_mention,language,- notify_user=False,+ notify_user=True,is_dm=save_interaction.guild is None,)await save_interaction.edit_original_response(- content=f"✅ {self._t('success.settingsUpdated')}",+ content=f"✅ {self._t('common.submitted')}",embed=None,view=None,)@@ -1339,11 +1393,11 @@ class DiscordBot(BaseIMClient):_normalize(self.claude_model),_normalize(self.codex_model),_normalize(self.codex_reasoning),- notify_user=False,+ notify_user=True,is_dm=interaction.guild is None,)await interaction.edit_original_response(- content=f"✅ {self.outer._t('success.routingUpdated')}",+ content=f"✅ {self.outer._t('common.submitted')}",embed=None,view=None,)@@ -1643,8 +1697,7 @@ class _DiscordButtonView(discord.ui.View):user_id=str(interaction.user.id),channel_id=channel_id,thread_id=thread_id,- message_id=self.base_context.message_id- or (str(interaction.message.id) if interaction.message else None),+ message_id=str(interaction.message.id) if interaction.message else None,platform_specific={"interaction": interaction, "is_dm": is_dm},)if self.outer.on_callback_query_callback:diff --git a/modules/im/feishu.py b/modules/im/feishu.pyindex 6c6ac4f28..333b2f156 100644--- a/modules/im/feishu.py+++ b/modules/im/feishu.py@@ -4,6 +4,7 @@ import asyncioimport ioimport jsonimport logging+import osimport timefrom typing import Any, Callable, Dict, List, Optional@@ -263,13 +264,8 @@ class FeishuBot(BaseIMClient):async def _send_auth_denial(self, chat_id: str, user_id: str, auth_result):"""Send denial message for failed auth check."""ctx = MessageContext(user_id="system", channel_id=chat_id)- if auth_result.denial == "unbound_dm":- hint = self._t("bind.dmNotBound", chat_id)- await self.send_message(ctx, hint)- elif auth_result.denial == "unauthorized_channel":- await self._send_unauthorized_message(chat_id)- elif auth_result.denial == "not_admin":- msg = i18n_t("permission.adminOnly")+ msg = self.build_auth_denial_text(auth_result.denial, chat_id)+ if msg:await self.send_message(ctx, msg)# ------------------------------------------------------------------@@ -627,9 +623,13 @@ class FeishuBot(BaseIMClient):text: Optional[str] = None,parse_mode: Optional[str] = None,) -> bool:- """Remove interactive buttons from a Feishu message."""- # Re-patch the card with only markdown content (no actions)- display_text = text or ""+ """Remove interactive buttons from a Feishu message.++ Feishu cards must be rebuilt entirely, so *text* should contain+ the desired card body. When *text* is ``None`` the card is+ re-sent with an empty body (callers should pass text explicitly).+ """+ display_text = text if text is not None else ""return await self.edit_message(context, message_id, text=display_text, keyboard=None, parse_mode=parse_mode)# ------------------------------------------------------------------@@ -800,6 +800,165 @@ class FeishuBot(BaseIMClient):logger.error("Error uploading markdown to Feishu: %s", exc)raise+ async def upload_file_from_path(+ self,+ context: MessageContext,+ file_path: str,+ title: Optional[str] = None,+ ) -> str:+ """Upload a local file to Feishu chat/thread."""+ self._ensure_client()+ try:+ token = await self._get_tenant_token()+ if not token:+ raise RuntimeError("Failed to obtain tenant token for file upload")++ filename = os.path.basename(file_path)+ with open(file_path, "rb") as f:+ file_bytes = f.read()++ url = f"{self.config.api_base_url}/open-apis/im/v1/files"+ form = aiohttp.FormData()+ form.add_field("file_type", "stream")+ form.add_field("file_name", title or filename)+ form.add_field(+ "file",+ io.BytesIO(file_bytes),+ filename=filename,+ content_type="application/octet-stream",+ )++ async with aiohttp.ClientSession() as session:+ async with session.post(+ url,+ data=form,+ headers={"Authorization": f"Bearer {token}"},+ ) as resp:+ result = await resp.json()+ if result.get("code") != 0:+ raise RuntimeError(f"Feishu file upload failed: {result.get('msg')}")+ file_key = result.get("data", {}).get("file_key", "")++ from lark_oapi.api.im.v1 import CreateMessageRequest, CreateMessageRequestBody++ file_content = json.dumps({"file_key": file_key})+ if context.thread_id:+ from lark_oapi.api.im.v1 import ReplyMessageRequest, ReplyMessageRequestBody++ request = (+ ReplyMessageRequest.builder()+ .message_id(context.thread_id)+ .request_body(+ ReplyMessageRequestBody.builder()+ .msg_type("file")+ .content(file_content)+ .reply_in_thread(True)+ .build()+ )+ .build()+ )+ response = await self._lark_client.im.v1.message.areply(request)+ else:+ request = (+ CreateMessageRequest.builder()+ .receive_id_type("chat_id")+ .request_body(+ CreateMessageRequestBody.builder()+ .receive_id(context.channel_id)+ .msg_type("file")+ .content(file_content)+ .build()+ )+ .build()+ )+ response = await self._lark_client.im.v1.message.acreate(request)++ if not response.success():+ raise RuntimeError(f"Feishu file message failed: {response.msg}")+ return response.data.message_id+ except Exception as exc:+ logger.error("Error uploading file to Feishu: %s", exc)+ raise++ async def upload_image_from_path(+ self,+ context: MessageContext,+ file_path: str,+ title: Optional[str] = None,+ ) -> str:+ """Upload a local image to Feishu as an image message."""+ self._ensure_client()+ try:+ token = await self._get_tenant_token()+ if not token:+ raise RuntimeError("Failed to obtain tenant token for image upload")++ filename = os.path.basename(file_path)+ with open(file_path, "rb") as f:+ image_bytes = f.read()++ url = f"{self.config.api_base_url}/open-apis/im/v1/images"+ form = aiohttp.FormData()+ form.add_field("image_type", "message")+ form.add_field(+ "image",+ io.BytesIO(image_bytes),+ filename=filename,+ content_type="application/octet-stream",+ )++ async with aiohttp.ClientSession() as session:+ async with session.post(+ url,+ data=form,+ headers={"Authorization": f"Bearer {token}"},+ ) as resp:+ result = await resp.json()+ if result.get("code") != 0:+ raise RuntimeError(f"Feishu image upload failed: {result.get('msg')}")+ image_key = result.get("data", {}).get("image_key", "")++ from lark_oapi.api.im.v1 import CreateMessageRequest, CreateMessageRequestBody++ image_content = json.dumps({"image_key": image_key})+ if context.thread_id:+ from lark_oapi.api.im.v1 import ReplyMessageRequest, ReplyMessageRequestBody++ request = (+ ReplyMessageRequest.builder()+ .message_id(context.thread_id)+ .request_body(+ ReplyMessageRequestBody.builder()+ .msg_type("image")+ .content(image_content)+ .reply_in_thread(True)+ .build()+ )+ .build()+ )+ response = await self._lark_client.im.v1.message.areply(request)+ else:+ request = (+ CreateMessageRequest.builder()+ .receive_id_type("chat_id")+ .request_body(+ CreateMessageRequestBody.builder()+ .receive_id(context.channel_id)+ .msg_type("image")+ .content(image_content)+ .build()+ )+ .build()+ )+ response = await self._lark_client.im.v1.message.acreate(request)++ if not response.success():+ raise RuntimeError(f"Feishu image message failed: {response.msg}")+ return response.data.message_id+ except Exception as exc:+ logger.error("Error uploading image to Feishu: %s", exc)+ raise+async def download_file(self,file_info: Dict[str, Any],@@ -966,7 +1125,15 @@ class FeishuBot(BaseIMClient):async with session.get(url, headers={"Authorization": f"Bearer {token}"}) as resp:result = await resp.json()if result.get("code") != 0:- return {"id": user_id}+ logger.warning(+ "Feishu get_user_info failed for %s: code=%s msg=%s",+ user_id,+ result.get("code"),+ result.get("msg"),+ )+ info = {"id": user_id}+ self._user_info_cache[user_id] = info+ return infouser = result.get("data", {}).get("user", {})info = {"id": user_id,@@ -978,7 +1145,9 @@ class FeishuBot(BaseIMClient):return infoexcept Exception as exc:logger.error("Error getting Feishu user info: %s", exc)- return {"id": user_id}+ info = {"id": user_id}+ self._user_info_cache[user_id] = info+ return infoasync def get_channel_info(self, channel_id: str) -> Dict[str, Any]:"""Get information about a Feishu chat."""@@ -1287,6 +1456,8 @@ class FeishuBot(BaseIMClient):await self._handle_question_form_submit(context, form_value, button_name)else:logger.warning("Unknown form submit button: %s", button_name)+ # Dismiss the form card after any successful submission+ await self.dismiss_form_message(context)return# --- Regular button callbacks ---@@ -1301,6 +1472,23 @@ class FeishuBot(BaseIMClient):except Exception as exc:logger.error("Error handling Feishu card action: %s", exc, exc_info=True)+ # ------------------------------------------------------------------+ # Form submission helpers+ # ------------------------------------------------------------------+ async def dismiss_form_message(self, context: MessageContext) -> None:+ """Delete (recall) the interactive form card after submission."""+ if not context.message_id:+ return+ try:+ from lark_oapi.api.im.v1 import DeleteMessageRequest++ req = DeleteMessageRequest.builder().message_id(context.message_id).build()+ resp = await self._lark_client.im.v1.message.adelete(req)+ if not resp.success():+ logger.warning("Failed to recall form card: %s", resp.msg)+ except Exception as exc:+ logger.warning("Could not recall form card: %s", exc)+# ------------------------------------------------------------------# Form submission handlers (JSON 2.0 form container)# ------------------------------------------------------------------@@ -1460,42 +1648,6 @@ class FeishuBot(BaseIMClient):payload = json.dumps({"answers": answers})callback_data = f"{callback_prefix}:modal:{payload}"- # Replace the interactive form card with a static confirmation so it- # doesn't stay clickable after submission (Feishu cards persist by default).- if context.message_id:- flat = ", ".join(a for group in answers for a in group) or "-"- done_card = json.dumps(- {- "schema": "2.0",- "header": {- "title": {- "tag": "plain_text",- "content": "✅ " + self._t("common.submitted", context.channel_id),- },- "template": "green",- },- "body": {- "direction": "vertical",- "elements": [{"tag": "markdown", "content": flat}],- },- },- ensure_ascii=False,- )- try:- from lark_oapi.api.im.v1 import PatchMessageRequest, PatchMessageRequestBody-- req = (- PatchMessageRequest.builder()- .message_id(context.message_id)- .request_body(PatchMessageRequestBody.builder().content(done_card).build())- .build()- )- resp = await self._lark_client.im.v1.message.apatch(req)- if not resp.success():- logger.warning("Failed to update question card after submit: %s", resp.msg)- except Exception as exc:- logger.warning("Could not update question card: %s", exc)-if self.on_callback_query_callback:await self.on_callback_query_callback(context, callback_data)@@ -1558,46 +1710,6 @@ class FeishuBot(BaseIMClient):await self.send_message(context, f"⚠️ {t('modal.resume.description')}")return- # Replace the form card with a confirmation- if context.message_id:- agent_label = (chosen_agent or "").capitalize()- done_card = json.dumps(- {- "schema": "2.0",- "header": {- "title": {- "tag": "plain_text",- "content": "✅ " + self._t("common.submitted", context.channel_id),- },- "template": "green",- },- "body": {- "direction": "vertical",- "elements": [- {- "tag": "markdown",- "content": f"Agent: **{agent_label}**\nSession: `{chosen_session[:60]}`",- }- ],- },- },- ensure_ascii=False,- )- try:- from lark_oapi.api.im.v1 import PatchMessageRequest, PatchMessageRequestBody-- req = (- PatchMessageRequest.builder()- .message_id(context.message_id)- .request_body(PatchMessageRequestBody.builder().content(done_card).build())- .build()- )- resp = await self._lark_client.im.v1.message.apatch(req)- if not resp.success():- logger.warning("Failed to update resume card after submit: %s", resp.msg)- except Exception as exc:- logger.warning("Could not update resume card: %s", exc)-# Delegate to the resume session callback (same as Slack/Discord)if hasattr(self, "_on_resume_session") and self._on_resume_session:is_dm = context.platform_specific.get("is_dm", False) if context.platform_specific else Falsediff --git a/modules/im/formatters/base_formatter.py b/modules/im/formatters/base_formatter.pyindex bde2b2467..40e435b43 100644--- a/modules/im/formatters/base_formatter.py+++ b/modules/im/formatters/base_formatter.py@@ -263,7 +263,6 @@ class BaseMarkdownFormatter(ABC):def format_assistant_message(self, content_parts: List[str]) -> str:"""Format assistant message"""- header = self.format_section_header("Assistant", "🤖")# Escape content parts that are plain textescaped_parts = []for part in content_parts:@@ -291,8 +290,7 @@ class BaseMarkdownFormatter(ABC):else:# Already formatted tool output, don't escapeescaped_parts.append(part)- parts = [header] + escaped_parts- return "\n\n".join(parts)+ return "\n\n".join(escaped_parts)def format_user_message(self, content_parts: List[str]) -> str:"""Format user/response message"""diff --git a/modules/im/slack.py b/modules/im/slack.pyindex ecf0d09e3..7d8f25d4c 100644--- a/modules/im/slack.py+++ b/modules/im/slack.py@@ -3215,31 +3215,19 @@ class SlackBot(BaseIMClient):async def _send_auth_denial(self, channel_id: str, user_id: str, auth: AuthResult, response_url: str = None):"""Send appropriate denial message based on auth result."""- if auth.denial == "unbound_dm":- hint = self._t("bind.dmNotBound", channel_id)- if response_url:- await self.send_slash_response(response_url, f"🔑 {hint}")- else:- try:- self._ensure_clients()- await self.web_client.chat_postMessage(channel=channel_id, text=hint)- except Exception as e:- logger.error(f"Failed to send DM bind hint: {e}")- elif auth.denial == "unauthorized_channel":- if response_url:- await self.send_slash_response(response_url, f"❌ {self._t('error.channelNotEnabled', channel_id)}")- else:- await self._send_unauthorized_message(channel_id)- elif auth.denial == "not_admin":- msg = i18n_t("permission.adminOnly")- if response_url:- await self.send_slash_response(response_url, msg)- else:- try:- self._ensure_clients()- await self.web_client.chat_postMessage(channel=channel_id, text=msg)- except Exception as e:- logger.error(f"Failed to send admin denial: {e}")+ msg = self.build_auth_denial_text(auth.denial, channel_id)+ if not msg:+ return++ if response_url:+ await self.send_slash_response(response_url, msg)+ return++ try:+ self._ensure_clients()+ await self.web_client.chat_postMessage(channel=channel_id, text=msg)+ except Exception as e:+ logger.error(f"Failed to send auth denial message: {e}")async def _send_unauthorized_message(self, channel_id: str):"""Send unauthorized access message to channel"""diff --git a/modules/settings_manager.py b/modules/settings_manager.pyindex ab279f5af..0550a8414 100644--- a/modules/settings_manager.py+++ b/modules/settings_manager.py@@ -87,9 +87,10 @@ class SettingsManager:"tool": "toolcall",}- def __init__(self, settings_file: Optional[str] = None):+ def __init__(self, settings_file: Optional[str] = None, platform: str = "slack"):paths.ensure_data_dirs()self.settings_file = Path(settings_file) if settings_file else paths.get_settings_path()+ self.platform = platformself.channel_settings: Dict[str, UserSettings] = {}self.dm_user_settings: Dict[str, UserSettings] = {}self.store = SettingsStore.get_instance(self.settings_file)@@ -121,11 +122,11 @@ class SettingsManager:def iter_bound_users(self):"""Iterate over bound users from persisted settings."""self._reload_if_changed()- return self.store.settings.users.items()+ return self.store.get_users_for_platform(self.platform).items()def is_bound_user(self, user_id: Union[int, str]) -> bool:"""Check whether a user is already bound."""- return self.store.is_bound_user(str(user_id))+ return self.store.is_bound_user(str(user_id), platform=self.platform)def bind_user_with_code(self,@@ -135,7 +136,13 @@ class SettingsManager:dm_chat_id: str = "",) -> tuple[bool, bool]:"""Atomically validate bind code and create user binding."""- return self.store.bind_user_with_code(str(user_id), display_name, code, dm_chat_id=dm_chat_id)+ return self.store.bind_user_with_code(+ str(user_id),+ display_name,+ code,+ dm_chat_id=dm_chat_id,+ platform=self.platform,+ )def _from_channel_settings(self, channel_settings: ChannelSettings) -> UserSettings:return UserSettings(@@ -165,7 +172,7 @@ class SettingsManager:def _sync_to_bound_user(self, user_id: str, settings: UserSettings) -> None:"""Sync runtime UserSettings back to the bound-user record in store.settings.users."""- bound = self.store.settings.users.get(user_id)+ bound = self.store.get_user(user_id, platform=self.platform)if not bound:returnbound.enabled = settings.enabled@@ -195,9 +202,9 @@ class SettingsManager:"""Rebuild the in-memory settings dicts from the store."""self.channel_settings = {}self.dm_user_settings = {}- for cid, cs in self.store.settings.channels.items():+ for cid, cs in self.store.get_channels_for_platform(self.platform).items():self.channel_settings[str(cid)] = self._from_channel_settings(cs)- for uid, us in self.store.settings.users.items():+ for uid, us in self.store.get_users_for_platform(self.platform).items():self.dm_user_settings[str(uid)] = self._from_bound_user_settings(us)logger.info(f"Rebuilt runtime settings for {len(self.channel_settings)} channels, {len(self.dm_user_settings)} DM users"@@ -212,14 +219,15 @@ class SettingsManager:"""try:channels: Dict[str, ChannelSettings] = {}+ existing_platform_channels = self.store.get_channels_for_platform(self.platform)for cid, s in self.channel_settings.items():- existing = self.store.settings.channels.get(cid)+ existing = existing_platform_channels.get(cid)cs = self._to_channel_settings(s)if existing is not None:cs.enabled = existing.enabledcs.require_mention = existing.require_mentionchannels[cid] = cs- self.store.settings.channels = channels+ self.store.set_channels_for_platform(self.platform, channels)for uid, s in self.dm_user_settings.items():self._sync_to_bound_user(uid, s)self.store.save()@@ -246,12 +254,14 @@ class SettingsManager:return self.channel_settings[normalized_id]# New key — check store- if normalized_id in self.store.settings.users:- settings = self._from_bound_user_settings(self.store.settings.users[normalized_id])+ platform_users = self.store.get_users_for_platform(self.platform)+ platform_channels = self.store.get_channels_for_platform(self.platform)+ if normalized_id in platform_users:+ settings = self._from_bound_user_settings(platform_users[normalized_id])self.dm_user_settings[normalized_id] = settingsreturn settings- if normalized_id in self.store.settings.channels:- settings = self._from_channel_settings(self.store.settings.channels[normalized_id])+ if normalized_id in platform_channels:+ settings = self._from_channel_settings(platform_channels[normalized_id])self.channel_settings[normalized_id] = settingsreturn settings@@ -271,7 +281,7 @@ class SettingsManager:self.dm_user_settings[normalized_id] = settingselif normalized_id in self.channel_settings:self.channel_settings[normalized_id] = settings- elif normalized_id in self.store.settings.users:+ elif normalized_id in self.store.get_users_for_platform(self.platform):self.dm_user_settings[normalized_id] = settingselse:self.channel_settings[normalized_id] = settings@@ -307,7 +317,7 @@ class SettingsManager:"""Get raw ChannelSettings for a channel without creating defaults."""self._reload_if_changed()key = str(channel_id)- return self.store.settings.channels.get(key)+ return self.store.get_channels_for_platform(self.platform).get(key)def is_message_type_hidden(self, user_id: Union[int, str], message_type: str) -> bool:"""Check if a message type is hidden for user (not in show_message_types)"""@@ -400,7 +410,7 @@ class SettingsManager:"""self._reload_if_changed()key = str(channel_id)- channel_settings = self.store.settings.channels.get(key)+ 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@@ -415,16 +425,16 @@ class SettingsManager:value: True=require mention, False=don't require, None=use global default"""key = str(channel_id)- channel_settings = self.store.get_channel(key)+ channel_settings = self.store.get_channel(key, platform=self.platform)channel_settings.require_mention = value- self.store.update_channel(key, channel_settings)+ self.store.update_channel(key, channel_settings, platform=self.platform)logger.info(f"Updated require_mention for channel {key}: {value}")def get_require_mention_override(self, channel_id: Union[int, str]) -> Optional[bool]:"""Get the raw per-channel require_mention override (may be None)."""self._reload_if_changed()key = str(channel_id)- channel_settings = self.store.settings.channels.get(key)+ channel_settings = self.store.get_channels_for_platform(self.platform).get(key)if channel_settings is not None:return channel_settings.require_mentionreturn Nonediff --git a/pyproject.toml b/pyproject.tomlindex 28d1b1820..196e81f8e 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -37,6 +37,8 @@ dependencies = ["PyYAML>=6.0","flask>=3.0.0","lark-oapi>=1.4.0",+ "python-socks[asyncio]>=2.0.0",+ "aiohttp-socks>=0.8.0",][project.urls]diff --git a/ui/src/components/Wizard.tsx b/ui/src/components/Wizard.tsxindex 9a1014095..69ce6d126 100644--- a/ui/src/components/Wizard.tsx+++ b/ui/src/components/Wizard.tsx@@ -137,9 +137,18 @@ export const Wizard: React.FC = () => {}, []);const next = async (stepData: any) => {- const nextData = { ...data, ...stepData };+ const platformChanged =+ typeof stepData?.platform === 'string' &&+ !!data?.platform &&+ stepData.platform !== data.platform;++ const nextData = {+ ...data,+ ...(platformChanged ? { channelConfigs: {} } : {}),+ ...stepData,+ };setData(nextData);- await persistStep(nextData);+ await persistStep(stepData, nextData);if (currentStep < steps.length - 1) {setCurrentStep(currentStep + 1);}@@ -151,13 +160,22 @@ export const Wizard: React.FC = () => {}};- const persistStep = async (payload: any) => {- if (!payload) return;- if (payload.agents || payload.slack || payload.discord || payload.lark || payload.mode || payload.platform || payload.channelConfigs) {- await api.saveConfig(buildConfigPayload(payload));+ const persistStep = async (stepData: any, mergedData: any) => {+ if (!mergedData) return;+ if (+ mergedData.agents ||+ mergedData.slack ||+ mergedData.discord ||+ mergedData.lark ||+ mergedData.mode ||+ mergedData.platform ||+ mergedData.channelConfigs+ ) {+ await api.saveConfig(buildConfigPayload(mergedData));}- if (payload.channelConfigs) {- await api.saveSettings({ channels: payload.channelConfigs });+ // Only persist channel settings when this step actually updated them.+ if (stepData && Object.prototype.hasOwnProperty.call(stepData, 'channelConfigs')) {+ await api.saveSettings({ channels: stepData.channelConfigs || {} });}};diff --git a/ui/src/components/steps/ChannelList.tsx b/ui/src/components/steps/ChannelList.tsxindex 47bb3813a..d7420457a 100644--- a/ui/src/components/steps/ChannelList.tsx+++ b/ui/src/components/steps/ChannelList.tsx@@ -70,10 +70,28 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onBconst [browsingCwdFor, setBrowsingCwdFor] = useState<string | null>(null);useEffect(() => {- if (!isPage) {- setConfigs(data.channelConfigs || {});- }- }, [data.channelConfigs, isPage]);+ if (isPage) return;+ let cancelled = false;++ const loadWizardPlatformSettings = async () => {+ try {+ const settings = await api.getSettings();+ if (!cancelled) {+ setConfigs(settings.channels || {});+ }+ } catch {+ if (!cancelled) {+ // Fallback to wizard-local state if API fetch fails.+ setConfigs(data.channelConfigs || {});+ }+ }+ };++ loadWizardPlatformSettings();+ return () => {+ cancelled = true;+ };+ }, [isPage, data.platform]);useEffect(() => {if (!isPage) {diff --git a/ui/src/components/steps/DiscordConfig.tsx b/ui/src/components/steps/DiscordConfig.tsxindex bad7cccdd..8ef88c587 100644--- a/ui/src/components/steps/DiscordConfig.tsx+++ b/ui/src/components/steps/DiscordConfig.tsx@@ -1,5 +1,5 @@import React, { useEffect, useMemo, useState } from 'react';-import { Shield, RefreshCw, Check, Server, KeyRound, Plus, ExternalLink, Settings, ChevronDown, ChevronUp, Copy } from 'lucide-react';+import { Shield, RefreshCw, Check, Server, KeyRound, Plus, ExternalLink, Settings, ChevronDown, ChevronUp, Copy, AlertTriangle } from 'lucide-react';import { useTranslation } from 'react-i18next';import clsx from 'clsx';import { useApi } from '../../context/ApiContext';@@ -229,6 +229,18 @@ export const DiscordConfig: React.FC<DiscordConfigProps> = ({ data, onNext, onBa{t('discordConfig.openInviteUrl')}</button></div>++ <div className="bg-amber-50 border border-amber-200 rounded-lg p-3 space-y-2">+ <div className="flex items-center gap-2 text-sm font-medium text-amber-800">+ <AlertTriangle size={14} className="text-amber-700" />+ {t('discordConfig.dmTroubleshootTitle')}+ </div>+ <ol className="list-decimal list-inside space-y-1 text-xs text-amber-900 pl-1">+ <li>{t('discordConfig.dmTroubleshoot1')}</li>+ <li>{t('discordConfig.dmTroubleshoot2')}</li>+ <li>{t('discordConfig.dmTroubleshoot3')}</li>+ </ol>+ </div></div>)}</div>diff --git a/ui/src/components/steps/LarkConfig.tsx b/ui/src/components/steps/LarkConfig.tsxindex 28bdf8e19..fd6566abf 100644--- a/ui/src/components/steps/LarkConfig.tsx+++ b/ui/src/components/steps/LarkConfig.tsx@@ -7,6 +7,7 @@ import { useApi } from '../../context/ApiContext';const LARK_PERMISSIONS_JSON = `{"scopes": {"tenant": [+ "contact:contact.base:readonly","contact:user.base:readonly","im:chat","im:message",@@ -352,7 +353,7 @@ export const LarkConfig: React.FC<LarkConfigProps> = ({ data, onNext, onBack })<details className="text-sm text-muted"><summary className="cursor-pointer font-medium text-text hover:text-accent transition-colors">{t('larkConfig.step3ManualList')}</summary><ul className="space-y-1.5 mt-2 pl-1">- {[1,2,3,4,5,6,7,8,9,10,11,12,13].map(i => (+ {[1,2,3,4,5,6,7,8,9,10,11,12,13,14].map(i => (<li key={i} className="flex items-start gap-2"><code className="text-xs bg-neutral-100 px-1.5 py-0.5 rounded font-mono shrink-0">{i}</code>{t(`larkConfig.step3Item${i}`)}diff --git a/ui/src/components/steps/Summary.tsx b/ui/src/components/steps/Summary.tsxindex aeae19179..0e770a42e 100644--- a/ui/src/components/steps/Summary.tsx+++ b/ui/src/components/steps/Summary.tsx@@ -133,7 +133,7 @@ export const Summary: React.FC<SummaryProps> = ({ data, onBack }) => {<buttononClick={() => navigate('/dashboard')}- className="mt-8 px-8 py-3 bg-primary hover:bg-primary/90 text-white rounded-lg font-bold transition-colors shadow-sm"+ className="mt-8 px-8 py-3 bg-accent hover:bg-accent/90 text-white rounded-lg font-bold transition-colors shadow-sm">{t('summary.goToDashboard')}</button>@@ -213,7 +213,7 @@ export const Summary: React.FC<SummaryProps> = ({ data, onBack }) => {<h3 className="text-sm font-medium text-text mb-3">{t('summary.usageTips')}</h3><div className="space-y-3"><div className="flex items-start gap-3">- <div className="w-8 h-8 bg-primary/10 text-primary rounded-lg flex items-center justify-center flex-shrink-0">+ <div className="w-8 h-8 bg-accent/10 text-accent rounded-lg flex items-center justify-center flex-shrink-0"><Terminal size={16} /></div><div>diff --git a/ui/src/components/steps/UserList.tsx b/ui/src/components/steps/UserList.tsxindex 3d864a782..25a322e80 100644--- a/ui/src/components/steps/UserList.tsx+++ b/ui/src/components/steps/UserList.tsx@@ -1,5 +1,5 @@import React, { useEffect, useState } from 'react';-import { User, Shield, ShieldOff, Copy, Check, Plus, Trash2, FolderOpen, HelpCircle } from 'lucide-react';+import { User, Shield, ShieldOff, Copy, Check, Plus, Trash2, FolderOpen, HelpCircle, X } from 'lucide-react';import { useTranslation } from 'react-i18next';import { useApi } from '../../context/ApiContext';import { useToast } from '../../context/ToastContext';@@ -65,6 +65,7 @@ const BindCodeSection: React.FC = () => {const [newExpiry, setNewExpiry] = useState('');const [copiedCode, setCopiedCode] = useState<string | null>(null);const [loading, setLoading] = useState(false);+ const [showUnavailableModal, setShowUnavailableModal] = useState(false);const loadCodes = async () => {try {@@ -130,102 +131,161 @@ const BindCodeSection: React.FC = () => {inactive: 'bg-neutral-100 text-muted border-border',};- return (- <div className="mb-6 bg-panel border border-border rounded-xl p-4 shadow-sm">- <div className="flex items-center justify-between mb-3">- <h3 className="text-lg font-semibold font-display">{t('bindCode.title')}</h3>- <button- onClick={() => setShowForm(!showForm)}- className="flex items-center gap-1.5 px-3 py-1.5 bg-accent hover:bg-accent/90 text-white rounded text-sm font-medium transition-colors"- >- <Plus size={14} /> {t('bindCode.newCode')}- </button>- </div>-- {showForm && (- <div className="mb-4 p-3 bg-bg border border-border rounded-lg space-y-3">- <div className="flex items-center gap-4">- <label className="text-sm text-muted">{t('bindCode.codeType')}</label>- <label className="flex items-center gap-1.5 text-sm">- <input type="radio" checked={newType === 'one_time'} onChange={() => setNewType('one_time')} className="text-accent" />- {t('bindCode.oneTime')}- </label>- <label className="flex items-center gap-1.5 text-sm">- <input type="radio" checked={newType === 'expiring'} onChange={() => setNewType('expiring')} className="text-accent" />- {t('bindCode.expiring')}- </label>- </div>- {newType === 'expiring' && (- <div className="flex items-center gap-3">- <label className="text-sm text-muted">{t('bindCode.expirationDate')}</label>- <input- type="date"- value={newExpiry}- onChange={(e) => setNewExpiry(e.target.value)}- min={new Date().toISOString().split('T')[0]}- className="bg-bg border border-border rounded px-3 py-1.5 text-sm focus:outline-none focus:border-accent text-text"- />- </div>+ const activeCodes = codes.filter((bc) => getCodeStatus(bc) === 'active');+ const unavailableCodes = codes.filter((bc) => getCodeStatus(bc) !== 'active');++ const renderCodeRow = (bc: BindCodeItem) => {+ const status = getCodeStatus(bc);+ return (+ <div key={bc.code} className="flex items-center justify-between py-2.5">+ <div className="flex items-center gap-3 flex-wrap">+ <code className="font-mono text-sm bg-bg px-2 py-0.5 rounded border border-border">{bc.code}</code>+ <span className={clsx('text-xs px-2 py-0.5 rounded-full border', statusColors[status])}>+ {t(`bindCode.${status}`)}+ </span>+ <span className="text-xs text-muted">+ {bc.type === 'one_time' ? t('bindCode.oneTime') : t('bindCode.expiring')}+ </span>+ {bc.used_by.length > 0 && (+ <span className="text-xs text-muted">{t('bindCode.usedBy', { count: bc.used_by.length })}</span>)}+ {bc.type === 'expiring' && bc.expires_at && (+ <span className="text-xs text-muted">+ {t('bindCode.expiresAt', { date: new Date(bc.expires_at).toLocaleDateString() })}+ </span>+ )}+ </div>+ <div className="flex items-center gap-2"><button- onClick={handleCreate}- disabled={loading || (newType === 'expiring' && !newExpiry)}- className="px-4 py-1.5 bg-accent hover:bg-accent/90 text-white rounded text-sm font-medium disabled:opacity-50 transition-colors"+ onClick={() => handleCopy(bc.code)}+ className="p-1.5 text-muted hover:text-text transition-colors"+ title={t('bindCode.copy')}>- {t('bindCode.generate')}+ {copiedCode === bc.code ? <Check size={14} className="text-success" /> : <Copy size={14} />}</button>+ {bc.is_active && (+ <button+ onClick={() => handleDelete(bc.code)}+ className="p-1.5 text-muted hover:text-danger transition-colors"+ title={t('bindCode.delete')}+ >+ <Trash2 size={14} />+ </button>+ )}</div>- )}+ </div>+ );+ };- {codes.length === 0 ? (- <p className="text-sm text-muted">{t('bindCode.noCodes')}</p>- ) : (- <div className="divide-y divide-border">- {codes.map((bc) => {- const status = getCodeStatus(bc);- return (- <div key={bc.code} className="flex items-center justify-between py-2.5">- <div className="flex items-center gap-3">- <code className="font-mono text-sm bg-bg px-2 py-0.5 rounded border border-border">{bc.code}</code>- <span className={clsx('text-xs px-2 py-0.5 rounded-full border', statusColors[status])}>- {t(`bindCode.${status}`)}- </span>- <span className="text-xs text-muted">- {bc.type === 'one_time' ? t('bindCode.oneTime') : t('bindCode.expiring')}- </span>- {bc.used_by.length > 0 && (- <span className="text-xs text-muted">{t('bindCode.usedBy', { count: bc.used_by.length })}</span>- )}- {bc.type === 'expiring' && bc.expires_at && (- <span className="text-xs text-muted">- {t('bindCode.expiresAt', { date: new Date(bc.expires_at).toLocaleDateString() })}- </span>- )}- </div>- <div className="flex items-center gap-2">- <button- onClick={() => handleCopy(bc.code)}- className="p-1.5 text-muted hover:text-text transition-colors"- title={t('bindCode.copy')}- >- {copiedCode === bc.code ? <Check size={14} className="text-success" /> : <Copy size={14} />}- </button>- {bc.is_active && (- <button- onClick={() => handleDelete(bc.code)}- className="p-1.5 text-muted hover:text-danger transition-colors"- title={t('bindCode.delete')}- >- <Trash2 size={14} />- </button>- )}- </div>+ return (+ <>+ <div className="mb-6 bg-panel border border-border rounded-xl p-4 shadow-sm">+ <div className="flex items-center justify-between mb-3 gap-2">+ <h3 className="text-lg font-semibold font-display">{t('bindCode.title')}</h3>+ <div className="flex items-center gap-2">+ {unavailableCodes.length > 0 && (+ <button+ onClick={() => setShowUnavailableModal(true)}+ className="px-3 py-1.5 bg-neutral-100 hover:bg-neutral-200 text-text rounded text-sm font-medium transition-colors"+ >+ {t('bindCode.viewUnavailable', { count: unavailableCodes.length })}+ </button>+ )}+ <button+ onClick={() => setShowForm(!showForm)}+ className="flex items-center gap-1.5 px-3 py-1.5 bg-accent hover:bg-accent/90 text-white rounded text-sm font-medium transition-colors"+ >+ <Plus size={14} /> {t('bindCode.newCode')}+ </button>+ </div>+ </div>++ <div className="mb-4 rounded-lg border border-blue-200 bg-blue-50 p-3 text-sm text-blue-900">+ <div className="flex items-center gap-2 font-medium text-blue-800">+ <HelpCircle size={14} /> {t('bindCode.usageTitle')}+ </div>+ <p className="mt-1 text-blue-900">{t('bindCode.usageHint')}</p>+ </div>++ {showForm && (+ <div className="mb-4 p-3 bg-bg border border-border rounded-lg space-y-3">+ <div className="flex items-center gap-4">+ <label className="text-sm text-muted">{t('bindCode.codeType')}</label>+ <label className="flex items-center gap-1.5 text-sm">+ <input type="radio" checked={newType === 'one_time'} onChange={() => setNewType('one_time')} className="text-accent" />+ {t('bindCode.oneTime')}+ </label>+ <label className="flex items-center gap-1.5 text-sm">+ <input type="radio" checked={newType === 'expiring'} onChange={() => setNewType('expiring')} className="text-accent" />+ {t('bindCode.expiring')}+ </label>+ </div>+ {newType === 'expiring' && (+ <div className="flex items-center gap-3">+ <label className="text-sm text-muted">{t('bindCode.expirationDate')}</label>+ <input+ type="date"+ value={newExpiry}+ onChange={(e) => setNewExpiry(e.target.value)}+ min={new Date().toISOString().split('T')[0]}+ className="bg-bg border border-border rounded px-3 py-1.5 text-sm focus:outline-none focus:border-accent text-text"+ /></div>- );- })}+ )}+ <button+ onClick={handleCreate}+ disabled={loading || (newType === 'expiring' && !newExpiry)}+ className="px-4 py-1.5 bg-accent hover:bg-accent/90 text-white rounded text-sm font-medium disabled:opacity-50 transition-colors"+ >+ {t('bindCode.generate')}+ </button>+ </div>+ )}++ {codes.length === 0 ? (+ <p className="text-sm text-muted">{t('bindCode.noCodes')}</p>+ ) : activeCodes.length === 0 ? (+ <p className="text-sm text-muted">{t('bindCode.noAvailableCodes')}</p>+ ) : (+ <div className="divide-y divide-border">+ {activeCodes.map(renderCodeRow)}+ </div>+ )}+ </div>++ {showUnavailableModal && (+ <div+ className="fixed inset-0 z-50 flex items-center justify-center bg-black/40"+ role="dialog"+ aria-modal="true"+ aria-label={t('bindCode.unavailableTitle')}+ onClick={() => setShowUnavailableModal(false)}+ >+ <div+ className="bg-panel border border-border rounded-xl shadow-xl w-full max-w-2xl max-h-[75vh] flex flex-col"+ onClick={(e) => e.stopPropagation()}+ >+ <div className="flex items-center justify-between px-4 py-3 border-b border-border">+ <h4 className="text-base font-semibold text-text">{t('bindCode.unavailableTitle')}</h4>+ <button+ onClick={() => setShowUnavailableModal(false)}+ className="text-muted hover:text-text transition-colors"+ title={t('bindCode.close')}+ >+ <X size={16} />+ </button>+ </div>+ <div className="px-4 py-2 overflow-y-auto">+ {unavailableCodes.length === 0 ? (+ <p className="text-sm text-muted py-4">{t('bindCode.noUnavailableCodes')}</p>+ ) : (+ <div className="divide-y divide-border">{unavailableCodes.map(renderCodeRow)}</div>+ )}+ </div>+ </div></div>)}- </div>+ </>);};@@ -317,6 +377,11 @@ export const UserList: React.FC = () => {};const handleToggleAdmin = async (userId: string, isAdmin: boolean) => {+ const current = users[userId];+ const currentAdminCount = Object.values(users).filter((u) => u.is_admin).length;+ if (current?.is_admin && !isAdmin && currentAdminCount <= 1) {+ if (!confirm(t('userList.lastAdminDemoteWarning'))) return;+ }try {const result = await api.toggleAdmin(userId, isAdmin);if (result.ok) {@@ -331,7 +396,10 @@ export const UserList: React.FC = () => {};const handleRemoveUser = async (userId: string) => {- if (!confirm(t('userList.removeConfirm'))) return;+ const current = users[userId];+ const currentAdminCount = Object.values(users).filter((u) => u.is_admin).length;+ const warningKey = current?.is_admin && currentAdminCount <= 1 ? 'userList.lastAdminRemoveWarning' : 'userList.removeConfirm';+ if (!confirm(t(warningKey))) return;try {const result = await api.removeUser(userId);if (result.ok) {diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 84aa84c2f..8b550d997 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -122,7 +122,11 @@"step4Description": "Copy the bot token and validate access.","step4Item1": "In the Bot tab, click \"Reset Token\" or \"View Token\"","step4Item2": "Copy the token and paste it here",- "step4Item3": "Validate the token and choose a guild"+ "step4Item3": "Validate the token and choose a guild",+ "dmTroubleshootTitle": "DM Troubleshooting",+ "dmTroubleshoot1": "Make sure your account and the bot are in at least one common server.",+ "dmTroubleshoot2": "In server Privacy Settings, enable \"Allow direct messages from server members\".",+ "dmTroubleshoot3": "Ensure you didn't block the bot account."},"larkConfig": {"title": "Configure Lark",@@ -162,11 +166,12 @@"step3Item6": "im:resource — Upload/download files and images","step3Item7": "im:chat — Access chat/group information","step3Item8": "im:message.reactions — Read/write emoji reactions",- "step3Item9": "contact:user.base:readonly — Read user basic info",+ "step3Item9": "contact:contact.base:readonly — Read user basic info","step3Item10": "im:message:update — Edit/update sent messages and cards","step3Item11": "im:message:recall — Recall (delete) bot messages","step3Item12": "cardkit:card:write — Create and manage card templates","step3Item13": "cardkit:card:read — Read card templates",+ "step3Item14": "contact:user.base:readonly — Read user basic info (legacy scope)","step3BatchImport": "Quick setup: Copy JSON and use \"Batch Import/Export Permissions\"","step3CopyJson": "Copy JSON","step3Copied": "Copied!",@@ -439,6 +444,8 @@"boundAt": "Bound","removeUser": "Remove","removeConfirm": "Remove this user? This cannot be undone.",+ "lastAdminDemoteWarning": "You are removing the last admin role. Continuing will put the bot into an 'unrestricted admin' state, where any bound user can access admin menus. Continue?",+ "lastAdminRemoveWarning": "You are removing the last admin user. Continuing will put the bot into an 'unrestricted admin' state, where any bound user can access admin menus. Continue?","cannotRemoveLastAdmin": "Cannot remove the last admin","adminToggled": "Admin status updated","userRemoved": "User removed"@@ -462,6 +469,13 @@"expirationDate": "Expiration date","created": "Bind code created","deleted": "Bind code deleted",- "noCodes": "No bind codes yet. Create one to get started."+ "noCodes": "No bind codes yet. Create one to get started.",+ "usageTitle": "How to use a bind code",+ "usageHint": "Share an active code with the user, then ask them to DM the bot with `/bind <code>`.",+ "viewUnavailable": "Unavailable ({{count}})",+ "unavailableTitle": "Unavailable Bind Codes",+ "noAvailableCodes": "No active bind codes. Create a new code to start binding users.",+ "noUnavailableCodes": "No unavailable bind codes.",+ "close": "Close"}}diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex cffbdc79d..13e6b3723 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -62,7 +62,7 @@"saasMode": "SaaS 模式","saasDescription": "OAuth 安装 + 云端中继 + 本地执行(即将推出)","selfHostMode": "自托管模式",- "selfHostDescription": "使用您自己的 Slack 应用 + Socket Mode 令牌"+ "selfHostDescription": "使用您自己的聊天应用 + Socket Mode 令牌"},"platform": {"title": "选择平台",@@ -122,7 +122,11 @@"step4Description": "复制机器人令牌并验证访问。","step4Item1": "在「Bot」中点击「Reset Token」或「View Token」","step4Item2": "复制令牌并粘贴到此处",- "step4Item3": "验证令牌并选择服务器"+ "step4Item3": "验证令牌并选择服务器",+ "dmTroubleshootTitle": "私信失败排查",+ "dmTroubleshoot1": "确认你的账号和机器人至少在同一个服务器中。",+ "dmTroubleshoot2": "在服务器隐私设置中开启「允许来自服务器成员的私信」。",+ "dmTroubleshoot3": "确认你没有屏蔽该机器人账号。"},"larkConfig": {"title": "配置飞书",@@ -162,11 +166,12 @@"step3Item6": "im:resource — 上传/下载文件和图片","step3Item7": "im:chat — 访问群聊信息","step3Item8": "im:message.reactions — 读写表情回复",- "step3Item9": "contact:user.base:readonly — 读取用户基本信息",+ "step3Item9": "contact:contact.base:readonly — 读取用户基本信息","step3Item10": "im:message:update — 编辑/更新已发送的消息和卡片","step3Item11": "im:message:recall — 撤回机器人消息","step3Item12": "cardkit:card:write — 创建和管理卡片模板","step3Item13": "cardkit:card:read — 读取卡片模板",+ "step3Item14": "contact:user.base:readonly — 读取用户基本信息(旧权限)","step3BatchImport": "快捷配置:复制 JSON 后使用「批量导入/导出权限」","step3CopyJson": "复制 JSON","step3Copied": "已复制!",@@ -439,6 +444,8 @@"boundAt": "绑定于","removeUser": "移除","removeConfirm": "确定要移除此用户吗?此操作不可撤销。",+ "lastAdminDemoteWarning": "你正在取消最后一个管理员身份。继续后将进入“无管理员约束”状态,任何已绑定用户都可操作管理员菜单。是否继续?",+ "lastAdminRemoveWarning": "你正在移除最后一个管理员。继续后将进入“无管理员约束”状态,任何已绑定用户都可操作管理员菜单。是否继续?","cannotRemoveLastAdmin": "无法移除最后一个管理员","adminToggled": "管理员状态已更新","userRemoved": "用户已移除"@@ -462,6 +469,13 @@"expirationDate": "到期日期","created": "绑定码已创建","deleted": "绑定码已删除",- "noCodes": "暂无绑定码,创建一个开始使用。"+ "noCodes": "暂无绑定码,创建一个开始使用。",+ "usageTitle": "绑定码如何使用",+ "usageHint": "把可用绑定码发给用户,并让用户私信机器人发送 `/bind <code>`。用户必须先完成绑定才可和bot私聊。仅管理员用户才可操作bot菜单进行设置。",+ "viewUnavailable": "不可用({{count}})",+ "unavailableTitle": "不可用的绑定码",+ "noAvailableCodes": "暂无可用绑定码,请先创建新的绑定码。",+ "noUnavailableCodes": "暂无不可用绑定码。",+ "close": "关闭"}}diff --git a/vibe/api.py b/vibe/api.pyindex 9f1f41a7e..0705d6e29 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -106,11 +106,12 @@ def config_to_payload(config: V2Config) -> dict:def get_settings() -> dict:store = SettingsStore.get_instance()- return _settings_to_payload(store)+ return _settings_to_payload(store, platform=_current_platform())def save_settings(payload: dict) -> dict:store = SettingsStore.get_instance()+ platform = _current_platform()channels = {}for channel_id, channel_payload in (payload.get("channels") or {}).items():channels[channel_id] = ChannelSettings(@@ -120,9 +121,9 @@ def save_settings(payload: dict) -> dict:routing=_parse_routing(channel_payload.get("routing") or {}),require_mention=channel_payload.get("require_mention"),)- store.settings.channels = channels+ store.set_channels_for_platform(platform, channels)store.save()- return _settings_to_payload(store)+ return _settings_to_payload(store, platform=platform)def init_sessions() -> None:@@ -366,9 +367,13 @@ async def opencode_options_async(cwd: str) -> dict:return {"ok": False, "error": str(exc)}-def _settings_to_payload(store: SettingsStore) -> dict:+def _current_platform() -> str:+ return load_config().platform+++def _settings_to_payload(store: SettingsStore, platform: str) -> dict:payload: dict = {"channels": {}, "users": {}, "bind_codes": []}- for channel_id, settings in store.settings.channels.items():+ 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(settings.show_message_types),@@ -376,7 +381,7 @@ def _settings_to_payload(store: SettingsStore) -> dict:"require_mention": settings.require_mention,"routing": _routing_to_dict(settings.routing),}- for user_id, u in store.settings.users.items():+ for user_id, u in store.get_users_for_platform(platform).items():payload["users"][user_id] = {"display_name": u.display_name,"is_admin": u.is_admin,@@ -1100,8 +1105,9 @@ def lark_list_chats(app_id: str, app_secret: str, domain: str = "feishu") -> dicdef get_users() -> dict:"""Get all bound users."""store = SettingsStore.get_instance()+ platform = _current_platform()users = {}- for user_id, u in store.settings.users.items():+ for user_id, u in store.get_users_for_platform(platform).items():users[user_id] = {"display_name": u.display_name,"is_admin": u.is_admin,@@ -1115,19 +1121,16 @@ def get_users() -> dict:def save_users(payload: dict) -> dict:- """Save user settings (bulk update from UI).-- Preserves admin invariant: if there were admins before, at least one must remain.- """+ """Save user settings (bulk update from UI)."""store = SettingsStore.get_instance()- had_admins = store.has_any_admin()+ platform = _current_platform()users = {}for user_id, up in (payload.get("users") or {}).items():if not isinstance(up, dict):continue# Preserve dm_chat_id from existing user (not editable via UI)- existing = store.settings.users.get(user_id)+ existing = store.get_user(user_id, platform=platform)users[user_id] = UserSettings(display_name=up.get("display_name", ""),is_admin=up.get("is_admin", False),@@ -1139,16 +1142,12 @@ def save_users(payload: dict) -> dict:dm_chat_id=existing.dm_chat_id if existing else "",)- # Enforce admin invariant: if admins existed before, at least one must remain- if had_admins:- new_admin_count = sum(1 for u in users.values() if u.is_admin)- if new_admin_count == 0:- return {"ok": False, "error": "Cannot remove all admins"}-# Merge instead of replace: update existing users and add new ones,# but preserve users not included in the payload (e.g. concurrently bound)+ current_users = store.get_users_for_platform(platform)for uid, user_settings in users.items():- store.settings.users[uid] = user_settings+ current_users[uid] = user_settings+ store.set_users_for_platform(platform, current_users)store.save()return get_users()@@ -1156,25 +1155,22 @@ def save_users(payload: dict) -> dict:def toggle_admin(user_id: str, is_admin: bool) -> dict:"""Toggle admin status for a user."""store = SettingsStore.get_instance()- if not store.set_admin(user_id, is_admin):- if not store.is_bound_user(user_id):+ platform = _current_platform()+ if not store.set_admin(user_id, is_admin, platform=platform):+ if not store.is_bound_user(user_id, platform=platform):return {"ok": False, "error": "User not found"}- return {"ok": False, "error": "Cannot remove the last admin"}+ return {"ok": False, "error": "Failed to update admin status"}return {"ok": True}def remove_user(user_id: str) -> dict:"""Remove a bound user."""store = SettingsStore.get_instance()- user = store.get_user(user_id)+ platform = _current_platform()+ user = store.get_user(user_id, platform=platform)if user is None:return {"ok": False, "error": "User not found"}- # Prevent removing the last admin- if user.is_admin:- admin_count = sum(1 for u in store.settings.users.values() if u.is_admin)- if admin_count <= 1:- return {"ok": False, "error": "Cannot remove the last admin"}- store.remove_user(user_id)+ store.remove_user(user_id, platform=platform)return {"ok": True}diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex dd0682e3a..1acc56b5d 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -227,7 +227,8 @@}},"message": {- "ack": "{agent} received, processing..."+ "ack": "{agent} received, processing...",+ "quickReplyNote": "Reply: {text}"},"backend": {"claude": "ClaudeCode",diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex 7bc445a9f..605611b70 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -52,7 +52,7 @@"sessionResumed": "已恢复 {agent} 会话。\n会话ID:`{sessionId}`","sessionResumedTip1": "💬 *点击此消息并在右侧线程中回复* 以继续该会话。","sessionResumedTip2": "_(在频道中发送新消息将开始新的会话。)_",- "routingUpdated": "Agent 路由已更新!"+ "routingUpdated": "Agent设置已更新!"},"settings": {"personalizationTitle": "个性化设置",@@ -227,7 +227,8 @@}},"message": {- "ack": "{agent} 已收到,正在处理..."+ "ack": "{agent} 已收到,正在处理...",+ "quickReplyNote": "回复:{text}"},"backend": {"claude": "ClaudeCode",diff --git a/vibe/proxy.py b/vibe/proxy.pynew file mode 100644index 000000000..d0468c821--- /dev/null+++ b/vibe/proxy.py@@ -0,0 +1,52 @@+"""System proxy detection utilities.++Provides helpers that detect the OS-level proxy configuration and return+values usable by Python networking libraries (aiohttp, websockets, etc.).+"""++import logging+import os+import subprocess+from typing import Optional++logger = logging.getLogger(__name__)+++def get_system_socks_proxy() -> Optional[str]:+ """Return the system SOCKS proxy URL, or ``None`` if not configured.++ Checks, in order:+ 1. ``ALL_PROXY`` / ``all_proxy`` environment variable.+ 2. ``HTTPS_PROXY`` / ``https_proxy`` (if it's a socks URL).+ 3. macOS ``networksetup -getsocksfirewallproxy Wi-Fi``.+ """+ for var in ("ALL_PROXY", "all_proxy", "HTTPS_PROXY", "https_proxy"):+ val = os.environ.get(var, "")+ if val and "socks" in val.lower():+ return val++ # macOS: query system SOCKS proxy+ try:+ out = subprocess.run(+ ["networksetup", "-getsocksfirewallproxy", "Wi-Fi"],+ capture_output=True,+ text=True,+ timeout=3,+ )+ if out.returncode == 0:+ lines = {+ k.strip().lower(): v.strip()+ for line in out.stdout.splitlines()+ if ":" in line+ for k, v in [line.split(":", 1)]+ }+ if lines.get("enabled") == "Yes":+ host = lines.get("server", "127.0.0.1")+ port = lines.get("port", "1080")+ url = f"socks5://{host}:{port}"+ logger.debug("Detected macOS SOCKS proxy: %s", url)+ return url+ except Exception:+ pass++ return Nonediff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 5b4e0dbe9..d16e84a0f 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -606,6 +606,7 @@ if _os.environ.get("E2E_TEST_MODE", "").lower() in ("true", "1", "yes"):# Merge settings into existing store (not wholesale replace)from config.v2_settings import SettingsStore, ChannelSettings, normalize_show_message_typesfrom vibe.api import _parse_routing+ from vibe.api import _current_platformsettings_key = modal_values.get("settings_key") or modal_values.get("channel_id")if not settings_key:@@ -613,10 +614,11 @@ if _os.environ.get("E2E_TEST_MODE", "").lower() in ("true", "1", "yes"):store = SettingsStore.get_instance()store.maybe_reload()- ch = store.settings.channels.get(settings_key)+ platform = _current_platform()+ ch = store.find_channel(settings_key, platform=platform)if not ch:ch = ChannelSettings(enabled=True)- store.settings.channels[settings_key] = ch+ store.update_channel(settings_key, ch, platform=platform)if "show_message_types" in modal_values:ch.show_message_types = normalize_show_message_types(modal_values["show_message_types"])@@ -638,7 +640,10 @@ if _os.environ.get("E2E_TEST_MODE", "").lower() in ("true", "1", "yes"):store = SettingsStore.get_instance()store.maybe_reload()- ch = store.settings.channels.get(channel_id)+ from vibe.api import _current_platform++ platform = _current_platform()+ ch = store.find_channel(channel_id, platform=platform)if ch:from config.v2_settings import RoutingSettings@@ -675,7 +680,10 @@ if _os.environ.get("E2E_TEST_MODE", "").lower() in ("true", "1", "yes"):store = SettingsStore.get_instance()store.maybe_reload()- ch = store.settings.channels.get(channel_id)+ from vibe.api import _current_platform++ platform = _current_platform()+ ch = store.find_channel(channel_id, platform=platform)if ch:from config.v2_settings import RoutingSettings