Skip to content

armgit / avibe

Public Imported from GitHub
0

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

feat(discord): add Discord IM support

yh c36472bceae8e
diff --git a/README.md b/README.md
index 86f1b3c00..df12a7b27 100644
--- a/README.md
+++ b/README.md
@@ -4,7 +4,7 @@
# Vibe Remote
-### Your AI coding army, commanded from Slack.
+### Your AI coding army, commanded from Slack or Discord.
**No laptop. No IDE. Just vibes.**
@@ -26,7 +26,7 @@ You're at the beach. Phone buzzes — production's on fire.
**Old you:** Panic. Find WiFi. Open laptop. Wait for IDE. Lose your tan.
-**Vibe Remote you:** Open Slack. Type "Fix the auth bug in login.py". Watch Claude Code fix it in real-time. Approve. Sip margarita.
+**Vibe Remote you:** Open Slack or Discord. Type "Fix the auth bug in login.py". Watch Claude Code fix it in real-time. Approve. Sip margarita.
```
AI works. You live.
@@ -108,11 +108,11 @@ Get notified the moment your AI finishes. Like assigning tasks to employees —
### Thread = Session
-Each Slack thread is an isolated workspace. Open 5 threads, run 5 parallel tasks. Context stays separate.
+Each Slack/Discord thread is an isolated workspace. Open 5 threads, run 5 parallel tasks. Context stays separate.
### Interactive Prompts
-When your agent needs input — file selection, confirmation, options — Slack pops up buttons or a modal. Full CLI interactivity, zero terminal required.
+When your agent needs input — file selection, confirmation, options — Slack or Discord pops up buttons or a modal. Full CLI interactivity, zero terminal required.
![Interactive Prompts](assets/screenshots/question-en.jpg)
@@ -254,6 +254,7 @@ vibe stop && uv tool uninstall vibe-remote && rm -rf ~/.vibe_remote
- **[CLI Reference](docs/CLI.md)** — Command-line usage and service lifecycle
- **[Slack Setup Guide](docs/SLACK_SETUP.md)** — Detailed setup with screenshots
+- **[Discord Setup Guide](docs/DISCORD_SETUP.md)** — Detailed setup with screenshots
## Remote Server Tip (SSH)
diff --git a/README_ZH.md b/README_ZH.md
index fef695030..9b8efe8e3 100644
--- a/README_ZH.md
+++ b/README_ZH.md
@@ -4,7 +4,7 @@
# Vibe Remote
-### 你的 AI 编码军团,用 Slack 指挥。
+### 你的 AI 编码军团,用 Slack 或 Discord 指挥。
**不用笔记本电脑。不用 IDE。只需 vibe。**
@@ -26,7 +26,7 @@
**以前的你:** 慌了。找 WiFi。开电脑。等 IDE 加载。晒伤了。
-**用了 Vibe Remote:** 打开 Slack。输入「修一下 login.py 的认证 bug」。看着 Claude Code 实时修复。批准。继续喝玛格丽塔。
+**用了 Vibe Remote:** 打开 Slack 或 Discord。输入「修一下 login.py 的认证 bug」。看着 Claude Code 实时修复。批准。继续喝玛格丽塔。
```
让 AI 去忙,你去浪。
@@ -108,11 +108,11 @@ AI 完成任务的那一刻,你就能收到通知。就像老板给员工布
### Thread = 会话
-每个 Slack 线程是独立工作区。开 5 个线程,跑 5 个并行任务。上下文互不干扰。
+每个 Slack/Discord 线程是独立工作区。开 5 个线程,跑 5 个并行任务。上下文互不干扰。
### 交互式提示
-Agent 需要输入时 — 文件选择、确认、选项 — Slack 弹出按钮或模态框。完整 CLI 交互,零终端。
+Agent 需要输入时 — 文件选择、确认、选项 — Slack 或 Discord 弹出按钮或模态框。完整 CLI 交互,零终端。
![交互式提示](assets/screenshots/question-zh.jpg)
@@ -254,6 +254,7 @@ vibe stop && uv tool uninstall vibe-remote && rm -rf ~/.vibe_remote
- **[CLI 参考手册](docs/CLI_ZH.md)** — 命令行使用和服务生命周期
- **[Slack 配置指南](docs/SLACK_SETUP_ZH.md)** — 详细配置和截图
+- **[Discord 配置指南](docs/DISCORD_SETUP_ZH.md)** — 详细配置和截图
## 远端服务器提示(SSH)
diff --git a/config/v2_compat.py b/config/v2_compat.py
index 030b7c5cb..ea26d9afb 100644
--- a/config/v2_compat.py
+++ b/config/v2_compat.py
@@ -1,7 +1,7 @@
from dataclasses import dataclass
from typing import Optional
-from config.v2_config import V2Config, SlackConfig
+from config.v2_config import V2Config, SlackConfig, DiscordConfig
@dataclass
@@ -35,6 +35,7 @@ class OpenCodeCompatConfig:
class AppCompatConfig:
platform: str
slack: SlackConfig
+ discord: Optional[DiscordConfig]
claude: ClaudeCompatConfig
codex: Optional[CodexCompatConfig]
opencode: Optional[OpenCodeCompatConfig]
@@ -68,8 +69,9 @@ def to_app_config(v2: V2Config) -> AppCompatConfig:
)
slack = SlackConfig(**v2.slack.__dict__)
return AppCompatConfig(
- platform="slack",
+ platform=v2.platform,
slack=slack,
+ discord=v2.discord,
claude=claude,
codex=codex,
opencode=opencode,
diff --git a/config/v2_config.py b/config/v2_config.py
index 287ca53db..3289ed85a 100644
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@ -19,7 +19,7 @@ def _filter_dataclass_fields(dc_class, payload: dict) -> dict:
@dataclass
class SlackConfig(BaseIMConfig):
- bot_token: str
+ bot_token: str = ""
app_token: Optional[str] = None
signing_secret: Optional[str] = None
team_id: Optional[str] = None
@@ -35,6 +35,20 @@ class SlackConfig(BaseIMConfig):
raise ValueError("Invalid Slack app token format (should start with xapp-)")
+@dataclass
+class DiscordConfig(BaseIMConfig):
+ bot_token: str = ""
+ application_id: Optional[str] = None
+ guild_allowlist: Optional[List[str]] = None
+ guild_denylist: Optional[List[str]] = None
+ require_mention: bool = False
+
+ def validate(self) -> None:
+ # Allow empty token for initial setup
+ if self.bot_token and len(self.bot_token.strip()) < 10:
+ raise ValueError("Invalid Discord bot token format")
+
+
@dataclass
class GatewayConfig:
relay_url: Optional[str] = None
@@ -50,7 +64,6 @@ class RuntimeConfig:
log_level: str = "INFO"
-
@dataclass
class OpenCodeConfig:
enabled: bool = True
@@ -93,10 +106,11 @@ class UiConfig:
@dataclass
class UpdateConfig:
"""Configuration for automatic update checking and installation."""
+
auto_update: bool = True # Auto-install updates when idle
check_interval_minutes: int = 60 # How often to check for updates (0 = disable)
idle_minutes: int = 30 # Minutes of inactivity before auto-update
- notify_slack: bool = True # Send Slack notification when update is available
+ notify_slack: bool = True # Send update notification when update is available
@dataclass
@@ -106,6 +120,8 @@ class V2Config:
slack: SlackConfig
runtime: RuntimeConfig
agents: AgentsConfig
+ platform: str = "slack"
+ discord: Optional[DiscordConfig] = None
gateway: Optional[GatewayConfig] = None
ui: UiConfig = field(default_factory=UiConfig)
update: UpdateConfig = field(default_factory=UpdateConfig)
@@ -130,7 +146,11 @@ class V2Config:
if mode not in {"self_host", "saas"}:
raise ValueError("Config 'mode' must be 'self_host' or 'saas'")
- slack_payload = payload.get("slack")
+ platform = payload.get("platform") or "slack"
+ if platform not in {"slack", "discord"}:
+ raise ValueError("Config 'platform' must be 'slack' or 'discord'")
+
+ slack_payload = payload.get("slack") or {}
if not isinstance(slack_payload, dict):
raise ValueError("Config 'slack' must be an object")
@@ -140,6 +160,16 @@ class V2Config:
slack = SlackConfig(**_filter_dataclass_fields(SlackConfig, slack_payload))
slack.validate()
+
+ discord_payload = payload.get("discord") or None
+ if discord_payload is not None and not isinstance(discord_payload, dict):
+ raise ValueError("Config 'discord' must be an object")
+ discord = None
+ if discord_payload is not None:
+ discord = DiscordConfig(**_filter_dataclass_fields(DiscordConfig, discord_payload))
+ discord.validate()
+ if platform == "discord" and discord is None:
+ raise ValueError("Config 'discord' must be provided when platform is discord")
gateway_payload = payload.get("gateway")
if gateway_payload is not None and not isinstance(gateway_payload, dict):
raise ValueError("Config 'gateway' must be an object")
@@ -198,9 +228,11 @@ class V2Config:
language = normalize_language(payload.get("language"), default="en")
return cls(
+ platform=platform,
mode=mode,
version=payload.get("version", "v2"),
slack=slack,
+ discord=discord,
runtime=runtime,
agents=agents,
gateway=gateway,
@@ -214,9 +246,11 @@ class V2Config:
paths.ensure_data_dirs()
path = config_path or paths.get_config_path()
payload = {
+ "platform": self.platform,
"mode": self.mode,
"version": self.version,
"slack": self.slack.__dict__,
+ "discord": self.discord.__dict__ if self.discord else None,
"runtime": {
"default_cwd": self.runtime.default_cwd,
"log_level": self.runtime.log_level,
diff --git a/core/controller.py b/core/controller.py
index 7fc43bae6..4efbf1235 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -7,7 +7,7 @@ import logging
from typing import Optional, Dict, Any
from config import paths
from modules.im import BaseIMClient, MessageContext, IMFactory
-from modules.im.formatters import SlackFormatter
+from modules.im.formatters import SlackFormatter, DiscordFormatter
from modules.agent_router import AgentRouter
from modules.agents import AgentService, ClaudeAgent, CodexAgent, OpenCodeAgent
from modules.claude_client import ClaudeClient
@@ -79,7 +79,10 @@ class Controller:
self.im_client: BaseIMClient = IMFactory.create_client(self.config)
# Create platform-specific formatter
- formatter = SlackFormatter()
+ if self.config.platform == "discord":
+ formatter = DiscordFormatter()
+ else:
+ formatter = SlackFormatter()
# Inject formatter into clients
self.im_client.formatter = formatter
@@ -96,15 +99,21 @@ class Controller:
default_backend = getattr(self.config, "default_backend", "opencode")
self.agent_router = AgentRouter.from_file(None, platform=self.config.platform, default_backend=default_backend)
- # Inject settings_manager into SlackBot if it's Slack platform
+ # Inject settings_manager into IM client if supported
if self.config.platform == "slack":
- # Import here to avoid circular dependency
from modules.im.slack import SlackBot
if isinstance(self.im_client, SlackBot):
self.im_client.set_settings_manager(self.settings_manager)
self.im_client.set_controller(self)
logger.info("Injected settings_manager and controller into SlackBot")
+ elif self.config.platform == "discord":
+ from modules.im.discord import DiscordBot
+
+ if isinstance(self.im_client, DiscordBot):
+ self.im_client.set_settings_manager(self.settings_manager)
+ self.im_client.set_controller(self)
+ logger.info("Injected settings_manager and controller into DiscordBot")
def _get_lang(self) -> str:
self._refresh_language_from_config()
@@ -384,13 +393,17 @@ class Controller:
self._consolidated_message_buffers.pop(key, None)
def _get_consolidated_max_bytes(self) -> int:
+ if self.config.platform == "discord":
+ return 2000
# Slack API hard limit is exactly 4000 BYTES (not characters) for chat.update
# Chinese/emoji characters take 3-4 bytes each in UTF-8
return 4000
def _get_consolidated_split_threshold(self) -> int:
# When accumulated message exceeds this threshold (in bytes), start a new message
- # to avoid Slack edit failures. Use 90% of max to leave some buffer.
+ # to avoid edit failures. Use 90% of max to leave some buffer.
+ if self.config.platform == "discord":
+ return 1800
return 3600
def _get_text_byte_length(self, text: str) -> int:
@@ -398,6 +411,8 @@ class Controller:
return len(text.encode("utf-8"))
def _get_result_max_chars(self) -> int:
+ if self.config.platform == "discord":
+ return 1900
return 30000
def _build_result_summary(self, text: str, max_chars: int) -> str:
@@ -503,7 +518,7 @@ class Controller:
summary = self._build_result_summary(text, self._get_result_max_chars())
await self.im_client.send_message(target_context, summary, parse_mode=parse_mode)
- if self.config.platform == "slack" and hasattr(self.im_client, "upload_markdown"):
+ if self.config.platform in {"slack", "discord"} and hasattr(self.im_client, "upload_markdown"):
try:
await self.im_client.upload_markdown(
target_context,
@@ -515,7 +530,7 @@ class Controller:
logger.warning(f"Failed to upload result attachment: {err}")
await self.im_client.send_message(
target_context,
- "无法上传附件(缺少 files:write 权限或上传失败)。需要我改成分条发送吗?",
+ "Failed to upload attachment. Want me to split the result into multiple messages?",
parse_mode=parse_mode,
)
return
@@ -717,7 +732,6 @@ class Controller:
context,
f"❌ {self._t('error.settingsUpdateFailed', error=str(e))}",
)
-
# Working directory change handler (for Slack modal)
async def handle_change_cwd_submission(self, user_id: str, new_cwd: str, channel_id: Optional[str] = None):
@@ -1068,9 +1082,7 @@ class Controller:
if opencode_model:
parts.append(f"{self._t('routing.label.model')}: **{opencode_model}**")
if opencode_reasoning_effort:
- parts.append(
- f"{self._t('routing.label.reasoningEffort')}: **{opencode_reasoning_effort}**"
- )
+ parts.append(f"{self._t('routing.label.reasoningEffort')}: **{opencode_reasoning_effort}**")
elif backend == "claude":
if claude_agent:
parts.append(f"{self._t('routing.label.agent')}: **{claude_agent}**")
@@ -1080,9 +1092,7 @@ class Controller:
if codex_model:
parts.append(f"{self._t('routing.label.model')}: **{codex_model}**")
if codex_reasoning_effort:
- parts.append(
- f"{self._t('routing.label.reasoningEffort')}: **{codex_reasoning_effort}**"
- )
+ parts.append(f"{self._t('routing.label.reasoningEffort')}: **{codex_reasoning_effort}**")
# Create context for confirmation message
context = MessageContext(
diff --git a/core/handlers/command_handlers.py b/core/handlers/command_handlers.py
index 9ba31dee4..574884c12 100644
--- a/core/handlers/command_handlers.py
+++ b/core/handlers/command_handlers.py
@@ -33,8 +33,8 @@ class CommandHandlers:
def _get_channel_context(self, context: MessageContext) -> MessageContext:
"""Get context for channel messages (no thread)"""
- # For Slack: send command responses directly to channel, not in thread
- if self.config.platform == "slack":
+ # For Slack/Discord: send command responses directly to channel, not in thread
+ if self.config.platform in {"slack", "discord"}:
return MessageContext(
user_id=context.user_id,
channel_id=context.channel_id,
@@ -62,20 +62,16 @@ class CommandHandlers:
channel_info = {
"id": context.channel_id,
"name": (
- self._t("command.start.directMessage")
- if context.channel_id.startswith("D")
- else context.channel_id
+ self._t("command.start.directMessage") if context.channel_id.startswith("D") else context.channel_id
),
}
agent_name = self.controller.resolve_agent_for_context(context)
default_agent = getattr(self.controller.agent_service, "default_agent", None)
- agent_display_name = get_agent_display_name(
- agent_name, fallback=default_agent or "Unknown"
- )
+ agent_display_name = get_agent_display_name(agent_name, fallback=default_agent or "Unknown")
- # For non-Slack platforms, use traditional text message
- if self.config.platform != "slack":
+ # For non-Slack platforms without buttons, use traditional text message
+ if self.config.platform not in {"slack", "discord"}:
formatter = self.im_client.formatter
# Build welcome message using formatter to handle escaping properly
@@ -93,17 +89,11 @@ class CommandHandlers:
formatter.format_text("@Vibe Remote /cwd - Show current working directory"),
formatter.format_text("@Vibe Remote /set_cwd <path> - Set working directory"),
formatter.format_text("@Vibe Remote /settings - Personalization settings"),
- formatter.format_text(
- f"@Vibe Remote /stop - Interrupt {agent_display_name} execution"
- ),
+ formatter.format_text(f"@Vibe Remote /stop - Interrupt {agent_display_name} execution"),
"",
formatter.format_bold("How it works:"),
- formatter.format_text(
- f"• Send any message and it's immediately sent to {agent_display_name}"
- ),
- formatter.format_text(
- "• Each chat maintains its own conversation context"
- ),
+ formatter.format_text(f"• Send any message and it's immediately sent to {agent_display_name}"),
+ formatter.format_text("• Each chat maintains its own conversation context"),
formatter.format_text("• Use /clear to reset the conversation"),
]
@@ -112,7 +102,7 @@ class CommandHandlers:
await self.im_client.send_message(channel_context, message_text)
return
- # For Slack, create interactive buttons using Block Kit
+ # For Slack/Discord, create interactive buttons
user_name = user_info.get("real_name") or user_info.get("name") or "User"
# Create interactive buttons for commands
@@ -143,16 +133,14 @@ class CommandHandlers:
👋 {self._t("command.start.greeting", name=user_name)}
🔧 {self._t("command.start.platform", platform=platform_name)}
🤖 {self._t("command.start.agent", agent=agent_display_name)}
-📍 {self._t("command.start.channel", channel=channel_info.get('name', 'Unknown'))}
+📍 {self._t("command.start.channel", channel=channel_info.get("name", "Unknown"))}
**{self._t("command.start.quickActions")}**
{self._t("command.start.quickActionsDesc", agent=agent_display_name)}"""
# Send command response to channel (not in thread)
channel_context = self._get_channel_context(context)
- await self.im_client.send_message_with_buttons(
- channel_context, welcome_text, keyboard
- )
+ await self.im_client.send_message_with_buttons(channel_context, welcome_text, keyboard)
async def handle_clear(self, context: MessageContext, args: str = ""):
"""Handle clear command - clears all sessions across configured agents"""
@@ -178,13 +166,9 @@ class CommandHandlers:
logger.error(f"Error clearing session: {e}", exc_info=True)
try:
channel_context = self._get_channel_context(context)
- await self.im_client.send_message(
- channel_context, f"❌ {self._t('error.clearSession', error=str(e))}"
- )
+ await self.im_client.send_message(channel_context, f"❌ {self._t('error.clearSession', error=str(e))}")
except Exception as send_error:
- logger.error(
- f"Failed to send error message: {send_error}", exc_info=True
- )
+ logger.error(f"Failed to send error message: {send_error}", exc_info=True)
async def handle_cwd(self, context: MessageContext, args: str = ""):
"""Handle cwd command - show current working directory"""
@@ -215,18 +199,14 @@ class CommandHandlers:
except Exception as e:
logger.error(f"Error getting cwd: {e}")
channel_context = self._get_channel_context(context)
- await self.im_client.send_message(
- channel_context, f"❌ {self._t('error.cwdGetFailed', error=str(e))}"
- )
+ await self.im_client.send_message(channel_context, f"❌ {self._t('error.cwdGetFailed', error=str(e))}")
async def handle_set_cwd(self, context: MessageContext, args: str):
"""Handle set_cwd command - change working directory"""
try:
if not args:
channel_context = self._get_channel_context(context)
- await self.im_client.send_message(
- channel_context, self._t("command.cwd.usage")
- )
+ await self.im_client.send_message(channel_context, self._t("command.cwd.usage"))
return
new_path = args.strip()
@@ -269,14 +249,26 @@ class CommandHandlers:
except Exception as e:
logger.error(f"Error setting cwd: {e}")
channel_context = self._get_channel_context(context)
- await self.im_client.send_message(
- channel_context, f"❌ {self._t('error.cwdSetFailed', error=str(e))}"
- )
+ await self.im_client.send_message(channel_context, f"❌ {self._t('error.cwdSetFailed', error=str(e))}")
async def handle_change_cwd_modal(self, context: MessageContext):
"""Handle Change Work Dir button - open modal for Slack"""
+ if self.config.platform == "discord":
+ interaction = context.platform_specific.get("interaction") if context.platform_specific else None
+ if interaction and hasattr(self.im_client, "open_change_cwd_modal"):
+ try:
+ current_cwd = self.controller.get_cwd(context)
+ await self.im_client.open_change_cwd_modal(interaction, current_cwd, context.channel_id)
+ return
+ except Exception as e:
+ logger.error(f"Error opening change CWD modal: {e}")
+ channel_context = self._get_channel_context(context)
+ await self.im_client.send_message(
+ channel_context,
+ f"📂 {self._t('command.cwd.changeInstructions')}",
+ )
+ return
if self.config.platform != "slack":
- # For non-Slack platforms, just send instructions
channel_context = self._get_channel_context(context)
await self.im_client.send_message(
channel_context,
@@ -285,20 +277,14 @@ class CommandHandlers:
return
# For Slack, open a modal dialog
- trigger_id = (
- context.platform_specific.get("trigger_id")
- if context.platform_specific
- else None
- )
+ trigger_id = context.platform_specific.get("trigger_id") if context.platform_specific else None
if trigger_id and hasattr(self.im_client, "open_change_cwd_modal"):
try:
# Get current CWD based on context
current_cwd = self.controller.get_cwd(context)
- await self.im_client.open_change_cwd_modal(
- trigger_id, current_cwd, context.channel_id
- )
+ await self.im_client.open_change_cwd_modal(trigger_id, current_cwd, context.channel_id)
except Exception as e:
logger.error(f"Error opening change CWD modal: {e}")
channel_context = self._get_channel_context(context)
@@ -316,6 +302,35 @@ class CommandHandlers:
async def handle_resume(self, context: MessageContext):
"""Open resume-session modal (Slack) or explain availability."""
+ if self.config.platform == "discord":
+ interaction = context.platform_specific.get("interaction") if context.platform_specific else None
+ settings_key = self.controller._get_settings_key(context)
+ sessions_by_agent = self.settings_manager.list_all_agent_sessions(settings_key)
+ if not sessions_by_agent:
+ channel_context = self._get_channel_context(context)
+ await self.im_client.send_message(
+ channel_context,
+ f"ℹ️ {self._t('command.resume.noStoredSessions')}",
+ )
+ return
+ if interaction and hasattr(self.im_client, "open_resume_session_modal"):
+ try:
+ await self.im_client.open_resume_session_modal(
+ trigger_id=interaction,
+ sessions_by_agent=sessions_by_agent,
+ channel_id=context.channel_id,
+ thread_id=context.thread_id or context.message_id or "",
+ host_message_ts=context.message_id,
+ )
+ return
+ except Exception as e:
+ logger.error(f"Error opening resume modal: {e}")
+ channel_context = self._get_channel_context(context)
+ await self.im_client.send_message(
+ channel_context,
+ f"⏮️ {self._t('command.resume.clickButton')}",
+ )
+ return
if self.config.platform != "slack":
channel_context = self._get_channel_context(context)
await self.im_client.send_message(
@@ -324,11 +339,7 @@ class CommandHandlers:
)
return
- trigger_id = (
- context.platform_specific.get("trigger_id")
- if context.platform_specific
- else None
- )
+ trigger_id = context.platform_specific.get("trigger_id") if context.platform_specific else None
if not trigger_id:
channel_context = self._get_channel_context(context)
await self.im_client.send_message(
@@ -358,17 +369,13 @@ class CommandHandlers:
except Exception as e:
logger.error(f"Error opening resume modal: {e}")
channel_context = self._get_channel_context(context)
- await self.im_client.send_message(
- channel_context, f"❌ {self._t('error.resumeFailed')}"
- )
+ await self.im_client.send_message(channel_context, f"❌ {self._t('error.resumeFailed')}")
async def handle_stop(self, context: MessageContext, args: str = ""):
"""Handle /stop command - send interrupt message to the active agent"""
try:
session_handler = self.controller.session_handler
- base_session_id, working_path, composite_key = (
- session_handler.get_session_info(context)
- )
+ base_session_id, working_path, composite_key = session_handler.get_session_info(context)
settings_key = self.controller._get_settings_key(context)
agent_name = self.controller.resolve_agent_for_context(context)
request = AgentRequest(
@@ -380,14 +387,10 @@ class CommandHandlers:
settings_key=settings_key,
)
- handled = await self.controller.agent_service.handle_stop(
- agent_name, request
- )
+ handled = await self.controller.agent_service.handle_stop(agent_name, request)
if not handled:
channel_context = self._get_channel_context(context)
- await self.im_client.send_message(
- channel_context, f"ℹ️ {self._t('command.stop.noActiveSession')}"
- )
+ await self.im_client.send_message(channel_context, f"ℹ️ {self._t('command.stop.noActiveSession')}")
except Exception as e:
logger.error(f"Error sending stop command: {e}", exc_info=True)
diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.py
index bf852bd23..72895bff5 100644
--- a/core/handlers/message_handler.py
+++ b/core/handlers/message_handler.py
@@ -317,6 +317,19 @@ class MessageHandler:
elif callback_data == "cmd_routing":
await settings_handler.handle_routing(context)
+ elif callback_data.startswith("vibe_update_now"):
+ # Discord update button handler
+ target_version = None
+ if ":" in callback_data:
+ target_version = callback_data.split(":", 1)[1] or None
+ if hasattr(self.controller, "update_checker"):
+ await self.controller.update_checker.handle_update_button_click(context, target_version)
+ else:
+ await self.im_client.send_message(
+ context,
+ self.formatter.format_warning(self._t("error.updateUnavailable")),
+ )
+
elif callback_data.startswith("info_") and callback_data != "info_msg_types":
# Generic info handler
info_type = callback_data.replace("info_", "")
@@ -405,9 +418,7 @@ class MessageHandler:
async def _handle_missing_agent(self, context: MessageContext, agent_name: str):
"""Notify user when a requested agent backend is unavailable."""
target = agent_name or self.controller.agent_service.default_agent
- msg = (
- f"❌ {self._t('error.agentNotConfigured', agent=target)}"
- )
+ msg = f"❌ {self._t('error.agentNotConfigured', agent=target)}"
await self.im_client.send_message(context, msg)
async def _delete_ack(self, channel_id: str, request: AgentRequest):
diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.py
index bf285e555..5e13c8307 100644
--- a/core/handlers/session_handler.py
+++ b/core/handlers/session_handler.py
@@ -12,7 +12,7 @@ logger = logging.getLogger(__name__)
class SessionHandler:
"""Handles all session-related operations"""
-
+
def __init__(self, controller):
"""Initialize with reference to main controller"""
self.controller = controller
@@ -24,7 +24,7 @@ class SessionHandler:
self.claude_sessions = controller.claude_sessions
self.receiver_tasks = controller.receiver_tasks
self.stored_session_mappings = controller.stored_session_mappings
-
+
def _get_settings_key(self, context: MessageContext) -> str:
"""Get settings key - delegate to controller"""
return self.controller._get_settings_key(context)
@@ -36,36 +36,37 @@ class SessionHandler:
def _t(self, key: str, **kwargs) -> str:
return i18n_t(key, self._get_lang(), **kwargs)
-
+
def get_base_session_id(self, context: MessageContext) -> str:
"""Get base session ID based on platform and context (without path)"""
- # Slack only in V2; always use thread ID
- return f"slack_{context.thread_id}"
-
+ platform = getattr(self.config, "platform", "slack")
+ base_id = context.thread_id or context.message_id or context.channel_id
+ return f"{platform}_{base_id}"
+
def get_working_path(self, context: MessageContext) -> str:
"""Get working directory - delegate to controller's get_cwd"""
return self.controller.get_cwd(context)
-
+
def _load_agent_file(self, agent_name: str, working_path: str) -> Optional[Dict[str, Any]]:
"""Load an agent file and return its parsed content.
-
+
Searches for agent file in:
1. Project agents: <working_path>/.claude/agents/<agent_name>.md
2. Global agents: ~/.claude/agents/<agent_name>.md
-
+
Returns:
Dict with keys: name, description, prompt, tools, model
or None if not found/parse error.
"""
from pathlib import Path
from vibe.api import parse_claude_agent_file
-
+
# Search paths (project first, then global)
search_paths = [
Path(working_path) / ".claude" / "agents" / f"{agent_name}.md",
Path.home() / ".claude" / "agents" / f"{agent_name}.md",
]
-
+
for agent_path in search_paths:
if agent_path.exists() and agent_path.is_file():
parsed = parse_claude_agent_file(str(agent_path))
@@ -73,10 +74,10 @@ class SessionHandler:
return parsed
else:
logger.warning(f"Failed to parse agent file: {agent_path}")
-
+
logger.warning(f"Agent file not found for '{agent_name}' in {search_paths}")
return None
-
+
def get_session_info(self, context: MessageContext) -> Tuple[str, str, str]:
"""Get session info: base_session_id, working_path, and composite_key"""
base_session_id = self.get_base_session_id(context)
@@ -84,7 +85,7 @@ class SessionHandler:
# Create composite key for internal storage
composite_key = f"{base_session_id}:{working_path}"
return base_session_id, working_path, composite_key
-
+
async def get_or_create_claude_session(
self,
context: MessageContext,
@@ -96,14 +97,12 @@ class SessionHandler:
base_session_id, working_path, composite_key = self.get_session_info(context)
settings_key = self._get_settings_key(context)
- stored_claude_session_id = self.settings_manager.get_claude_session_id(
- settings_key, base_session_id
- )
+ stored_claude_session_id = self.settings_manager.get_claude_session_id(settings_key, base_session_id)
# Read channel-level configuration overrides
channel_settings = self.settings_manager.get_channel_settings(context.channel_id)
routing = channel_settings.routing if channel_settings else None
-
+
# Priority: subagent params > channel config > agent frontmatter > global default
# Note: agent frontmatter model is applied later after loading agent file
effective_agent = subagent_name or (routing.claude_agent if routing else None)
@@ -124,9 +123,7 @@ class SessionHandler:
agent_name="claude",
)
if cached_key in self.claude_sessions:
- logger.info(
- "Using Claude subagent session for %s at %s", cached_base, working_path
- )
+ logger.info("Using Claude subagent session for %s at %s", cached_base, working_path)
return self.claude_sessions[cached_key]
# Always use agent-specific key when effective_agent is set
# This ensures session continuity even on first use
@@ -143,7 +140,7 @@ class SessionHandler:
except Exception as e:
logger.error(f"Failed to create working directory {working_path}: {e}")
working_path = os.getcwd()
-
+
# Build system prompt from agent file if subagent is specified
# Claude Code has a bug where ~/.claude/agents/*.md files are not auto-discovered
# See: https://github.com/anthropics/claude-code/issues/11205
@@ -200,7 +197,7 @@ class SessionHandler:
disallowed_tools=["AskUserQuestion"],
env=claude_env, # Pass Anthropic/Claude env vars
)
-
+
# Log session creation details
logger.info(f"Creating Claude client for {base_session_id} at {working_path}")
logger.info(f" Working directory: {working_path}")
@@ -210,13 +207,13 @@ class SessionHandler:
logger.info(f" Subagent: {effective_agent}")
if effective_model:
logger.info(f" Model: {effective_model}")
-
+
# Log if we're resuming a session
if stored_claude_session_id:
logger.info(f"Attempting to resume Claude session {stored_claude_session_id}")
else:
logger.info(f"Creating new Claude session")
-
+
# Create new Claude client
client = ClaudeSDKClient(options=options)
@@ -235,9 +232,9 @@ class SessionHandler:
self.claude_sessions[composite_key] = client
logger.info(f"Created new Claude SDK client for {base_session_id} at {working_path}")
-
+
return client
-
+
async def cleanup_session(self, composite_key: str):
"""Clean up a specific session by composite key"""
# Cancel receiver task if exists
@@ -251,7 +248,7 @@ class SessionHandler:
pass
del self.receiver_tasks[composite_key]
logger.info(f"Cancelled receiver task for session {composite_key}")
-
+
# Cleanup Claude session
if composite_key in self.claude_sessions:
client = self.claude_sessions[composite_key]
@@ -261,53 +258,44 @@ class SessionHandler:
logger.error(f"Error disconnecting Claude session {composite_key}: {e}")
del self.claude_sessions[composite_key]
logger.info(f"Cleaned up Claude session {composite_key}")
-
+
async def handle_session_error(self, composite_key: str, context: MessageContext, error: Exception):
"""Handle session-related errors"""
error_msg = str(error)
-
+
# Check for specific error types
if "read() called while another coroutine" in error_msg:
logger.error(f"Session {composite_key} has concurrent read error - cleaning up")
await self.cleanup_session(composite_key)
-
+
# Notify user and suggest retry
- await self.im_client.send_message(
- context,
- self.formatter.format_error(
- self._t("error.sessionReset")
- )
- )
+ await self.im_client.send_message(context, self.formatter.format_error(self._t("error.sessionReset")))
elif "Session is broken" in error_msg or "Connection closed" in error_msg or "Connection lost" in error_msg:
logger.error(f"Session {composite_key} is broken - cleaning up")
await self.cleanup_session(composite_key)
-
+
# Notify user
await self.im_client.send_message(
- context,
- self.formatter.format_error(
- self._t("error.sessionConnectionLost")
- )
+ context, self.formatter.format_error(self._t("error.sessionConnectionLost"))
)
else:
# Generic error handling
logger.error(f"Error in session {composite_key}: {error}")
await self.im_client.send_message(
- context,
- self.formatter.format_error(self._t("error.sessionGeneric", error=error_msg))
+ context, self.formatter.format_error(self._t("error.sessionGeneric", error=error_msg))
)
-
+
def capture_session_id(self, base_session_id: str, claude_session_id: str, settings_key: str):
"""Capture and store Claude session ID mapping"""
# Persist to settings (settings_key is channel_id for Slack)
self.settings_manager.set_session_mapping(settings_key, base_session_id, claude_session_id)
-
+
logger.info(f"Captured Claude session_id: {claude_session_id} for {base_session_id}")
-
+
def restore_session_mappings(self):
"""Restore session mappings from settings on startup"""
logger.info("Initializing session mappings from saved settings...")
-
+
session_state = self.settings_manager.sessions_store.state.session_mappings
restored_count = 0
@@ -315,9 +303,7 @@ class SessionHandler:
claude_map = agent_map.get("claude", {}) if isinstance(agent_map, dict) else {}
for thread_id, claude_session_id in claude_map.items():
if isinstance(claude_session_id, str):
- logger.info(
- f" - {thread_id} -> {claude_session_id} (user {user_id})"
- )
+ logger.info(f" - {thread_id} -> {claude_session_id} (user {user_id})")
restored_count += 1
logger.info(f"Session restoration complete. Restored {restored_count} session mappings.")
diff --git a/core/handlers/settings_handler.py b/core/handlers/settings_handler.py
index 3c9d82a90..01ccda792 100644
--- a/core/handlers/settings_handler.py
+++ b/core/handlers/settings_handler.py
@@ -50,6 +50,8 @@ class SettingsHandler:
# For Slack, use modal dialog
if self.config.platform == "slack":
await self._handle_settings_slack(context)
+ elif self.config.platform == "discord":
+ await self._handle_settings_discord(context)
else:
# For other platforms, use inline keyboard
await self._handle_settings_traditional(context)
@@ -145,6 +147,31 @@ class SettingsHandler:
keyboard,
)
+ async def _handle_settings_discord(self, context: MessageContext):
+ interaction = context.platform_specific.get("interaction") if context.platform_specific else None
+ settings_key = self._get_settings_key(context)
+ user_settings = self.settings_manager.get_user_settings(settings_key)
+ message_types = self.settings_manager.get_available_message_types()
+ display_names = self._message_type_display_names()
+
+ current_require_mention = self.settings_manager.get_require_mention_override(settings_key)
+ global_require_mention = self.config.discord.require_mention if self.config.discord else False
+ current_language = self.config.language
+
+ if hasattr(self.im_client, "open_settings_modal"):
+ await self.im_client.open_settings_modal(
+ interaction,
+ user_settings,
+ message_types,
+ display_names,
+ context.channel_id,
+ current_require_mention=current_require_mention,
+ global_require_mention=global_require_mention,
+ current_language=current_language,
+ )
+ return
+ await self._handle_settings_traditional(context)
+
async def handle_toggle_message_type(self, context: MessageContext, msg_type: str):
"""Handle toggle for message type visibility"""
try:
@@ -237,7 +264,10 @@ class SettingsHandler:
title=self._t("info.howItWorksTitle"),
emoji="📚",
items=[
- (self._t("info.howItWorksRealtimeLabel"), self._t("info.howItWorksRealtimeDesc", agent=agent_label)),
+ (
+ self._t("info.howItWorksRealtimeLabel"),
+ self._t("info.howItWorksRealtimeDesc", agent=agent_label),
+ ),
(self._t("info.howItWorksPersistentLabel"), self._t("info.howItWorksPersistentDesc")),
(self._t("info.howItWorksCommandsLabel"), self._t("info.howItWorksCommandsDesc")),
(self._t("info.howItWorksWorkDirLabel"), self._t("info.howItWorksWorkDirDesc")),
@@ -260,6 +290,8 @@ class SettingsHandler:
# Only Slack has modal support for now
if self.config.platform == "slack":
await self._handle_routing_slack(context)
+ elif self.config.platform == "discord":
+ await self._handle_routing_discord(context)
else:
# For other platforms, show a simple message
await self.im_client.send_message(
@@ -372,3 +404,77 @@ class SettingsHandler:
except Exception as e:
logger.error(f"Error opening routing modal: {e}", exc_info=True)
await self.im_client.send_message(context, f"❌ {self._t('error.routingModalFailed')}")
+
+ async def _handle_routing_discord(self, context: MessageContext):
+ interaction = context.platform_specific.get("interaction") if context.platform_specific else None
+
+ settings_key = self._get_settings_key(context)
+ current_routing = self.settings_manager.get_channel_routing(settings_key)
+
+ all_backends = list(self.controller.agent_service.agents.keys())
+ registered_backends = sorted(all_backends, key=lambda x: (x != "opencode", x))
+ current_backend = self.controller.resolve_agent_for_context(context)
+
+ opencode_agents = []
+ opencode_models = {}
+ opencode_default_config = {}
+
+ if "opencode" in registered_backends:
+ try:
+ opencode_agent = self.controller.agent_service.agents.get("opencode")
+ if opencode_agent and hasattr(opencode_agent, "_get_server"):
+ server = await opencode_agent._get_server()
+ await server.ensure_running()
+
+ cwd = self.controller.get_cwd(context)
+ opencode_agents = await server.get_available_agents(cwd)
+ opencode_models = await server.get_available_models(cwd)
+ opencode_default_config = await server.get_default_config(cwd)
+ except Exception as e:
+ logger.warning(f"Failed to fetch OpenCode data: {e}")
+
+ claude_agents = []
+ claude_models = []
+
+ if "claude" in registered_backends:
+ try:
+ from vibe.api import claude_agents as get_claude_agents, claude_models as get_claude_models
+
+ cwd = self.controller.get_cwd(context)
+ agents_result = get_claude_agents(cwd)
+ if agents_result.get("ok"):
+ claude_agents = agents_result.get("agents", [])
+ models_result = get_claude_models()
+ if models_result.get("ok"):
+ claude_models = models_result.get("models", [])
+ except Exception as e:
+ logger.warning(f"Failed to fetch Claude data: {e}")
+
+ codex_models = []
+ if "codex" in registered_backends:
+ try:
+ from vibe.api import codex_models as get_codex_models
+
+ models_result = get_codex_models()
+ if models_result.get("ok"):
+ codex_models = models_result.get("models", [])
+ except Exception as e:
+ logger.warning(f"Failed to fetch Codex data: {e}")
+
+ try:
+ await self.im_client.open_routing_modal(
+ trigger_id=interaction or context,
+ channel_id=context.channel_id,
+ registered_backends=registered_backends,
+ current_backend=current_backend,
+ current_routing=current_routing,
+ opencode_agents=opencode_agents,
+ opencode_models=opencode_models,
+ opencode_default_config=opencode_default_config,
+ claude_agents=claude_agents,
+ claude_models=claude_models,
+ codex_models=codex_models,
+ )
+ except Exception as e:
+ logger.error(f"Error opening routing modal: {e}", exc_info=True)
+ await self.im_client.send_message(context, f"❌ {self._t('error.routingModalFailed')}")
diff --git a/core/update_checker.py b/core/update_checker.py
index 7f9e78b40..5078046bf 100644
--- a/core/update_checker.py
+++ b/core/update_checker.py
@@ -19,6 +19,7 @@ from typing import TYPE_CHECKING, Any, Dict, Optional
from config import paths
from config.v2_config import UpdateConfig
+from modules.im import MessageContext
if TYPE_CHECKING:
from core.controller import Controller
@@ -36,6 +37,7 @@ def _compare_versions(latest: str, current: str) -> bool:
"""Compare versions using packaging.version for PEP440 compliance."""
try:
from packaging.version import Version
+
return Version(latest) > Version(current)
except Exception:
# Fallback: simple comparison if packaging not available or version invalid
@@ -50,9 +52,10 @@ def _compare_versions(latest: str, current: str) -> bool:
def _fetch_pypi_version_sync() -> Dict[str, Any]:
"""Synchronous PyPI version fetch (to be run in thread)."""
from vibe import __version__
+
current = __version__
result = {"current": current, "latest": None, "has_update": False, "error": None}
-
+
try:
url = "https://pypi.org/pypi/vibe-remote/json"
req = urllib.request.Request(url, headers={"User-Agent": "vibe-remote"})
@@ -60,18 +63,19 @@ def _fetch_pypi_version_sync() -> Dict[str, Any]:
data = json.loads(resp.read().decode("utf-8"))
latest = data.get("info", {}).get("version", "")
result["latest"] = latest
-
+
if latest and latest != current:
result["has_update"] = _compare_versions(latest, current)
except Exception as e:
result["error"] = str(e)
-
+
return result
@dataclass
class UpdateState:
"""Persistent state for update tracking."""
+
notified_version: Optional[str] = None
notified_at: Optional[str] = None
last_check_at: Optional[str] = None
@@ -107,7 +111,7 @@ class UpdateState:
}
# Atomic write: write to temp file, then rename
with tempfile.NamedTemporaryFile(
- mode='w', dir=path.parent, suffix='.tmp', delete=False, encoding='utf-8'
+ mode="w", dir=path.parent, suffix=".tmp", delete=False, encoding="utf-8"
) as f:
json.dump(data, f, indent=2)
temp_path = Path(f.name)
@@ -139,12 +143,12 @@ class UpdateChecker:
if self.config.check_interval_minutes <= 0:
logger.info("Update checker disabled (check_interval_minutes=0)")
return
-
+
# Initialize last_activity_at if not set (for idle detection baseline)
if not self.state.last_activity_at:
self.state.last_activity_at = time.time()
self.state.save()
-
+
self._running = True
self._check_task = asyncio.create_task(self._check_loop())
logger.info(
@@ -179,7 +183,7 @@ class UpdateChecker:
"""Main loop for periodic update checking."""
# Initial delay to let the service fully start
await asyncio.sleep(30)
-
+
while self._running:
try:
await self._do_check()
@@ -187,11 +191,11 @@ class UpdateChecker:
break
except Exception as e:
logger.error(f"Update check failed: {e}", exc_info=True)
-
+
# Reload config and get interval (with minimum bound to prevent tight loop)
self._reload_config()
interval = max(self.config.check_interval_minutes, MIN_CHECK_INTERVAL_MINUTES)
-
+
# If interval is set to 0 (disabled), keep loop alive so hot-reload can re-enable
await asyncio.sleep(interval * 60)
@@ -200,36 +204,36 @@ class UpdateChecker:
try:
# Reload config for hot-reload support (e.g., user toggled auto_update in UI)
self._reload_config()
-
+
# Skip if disabled
if self.config.check_interval_minutes <= 0:
return
-
+
# Fetch version info in a thread to avoid blocking the event loop
version_info = await asyncio.to_thread(_fetch_pypi_version_sync)
-
+
self.state.last_check_at = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
self.state.save()
-
+
if version_info.get("error"):
logger.warning(f"Failed to check for updates: {version_info['error']}")
return
-
+
if not version_info.get("has_update"):
logger.debug(f"No update available (current={version_info['current']})")
return
-
+
latest = version_info["latest"]
current = version_info["current"]
logger.info(f"Update available: {current} -> {latest}")
-
+
# Notification flow (independent)
if self.config.notify_slack and self.state.notified_version != latest:
- await self._send_slack_notification(current, latest)
+ await self._send_update_notification(current, latest)
self.state.notified_version = latest
self.state.notified_at = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
self.state.save()
-
+
# Auto-update flow (independent)
if self.config.auto_update and self._is_idle():
logger.info("System is idle, performing auto-update...")
@@ -247,93 +251,93 @@ class UpdateChecker:
if self._has_active_sessions():
logger.debug("Not idle: has active sessions")
return False
-
+
# Check for recent activity
# If no activity recorded yet, consider it NOT idle (just started)
if not self.state.last_activity_at:
logger.debug("Not idle: no activity recorded yet (service just started)")
return False
-
+
idle_seconds = time.time() - self.state.last_activity_at
idle_minutes = idle_seconds / 60
if idle_minutes < self.config.idle_minutes:
logger.debug(f"Not idle: last activity {idle_minutes:.1f} minutes ago")
return False
-
+
return True
def _has_active_sessions(self) -> bool:
"""Check if any agent has active sessions."""
try:
# Check OpenCode active polls
- if hasattr(self.controller, 'settings_manager'):
+ if hasattr(self.controller, "settings_manager"):
active_polls = self.controller.settings_manager.get_all_active_polls()
if active_polls:
return True
-
+
# Check Claude sessions
- if hasattr(self.controller, 'claude_sessions') and self.controller.claude_sessions:
+ if hasattr(self.controller, "claude_sessions") and self.controller.claude_sessions:
return True
-
+
# Check Codex active processes
- if hasattr(self.controller, 'agent_service'):
+ if hasattr(self.controller, "agent_service"):
codex = self.controller.agent_service.agents.get("codex")
- if codex and hasattr(codex, 'active_processes') and codex.active_processes:
+ if codex and hasattr(codex, "active_processes") and codex.active_processes:
return True
except Exception as e:
logger.warning(f"Error checking active sessions: {e}")
-
+
return False
async def _get_workspace_owner_id(self) -> Optional[str]:
"""Get the Slack workspace primary owner's user ID."""
try:
im_client = self.controller.im_client
- if not im_client or not hasattr(im_client, 'web_client'):
+ if not im_client or not hasattr(im_client, "web_client"):
return None
-
+
# Paginate through users to handle large workspaces
cursor = None
while True:
kwargs = {"limit": 200}
if cursor:
kwargs["cursor"] = cursor
-
+
response = await im_client.web_client.users_list(**kwargs)
if not response.get("ok"):
return None
-
+
for member in response.get("members", []):
if member.get("is_primary_owner"):
return member.get("id")
-
+
# Check for next page
cursor = response.get("response_metadata", {}).get("next_cursor")
if not cursor:
break
-
+
# Second pass: fallback to any owner if no primary owner found
cursor = None
while True:
kwargs = {"limit": 200}
if cursor:
kwargs["cursor"] = cursor
-
+
response = await im_client.web_client.users_list(**kwargs)
if not response.get("ok"):
return None
-
+
for member in response.get("members", []):
if member.get("is_owner"):
return member.get("id")
-
+
cursor = response.get("response_metadata", {}).get("next_cursor")
if not cursor:
break
-
+
except Exception as e:
logger.warning(f"Failed to get workspace owner: {e}")
-
+
return None
async def _open_dm_channel(self, user_id: str) -> Optional[str]:
@@ -341,12 +345,12 @@ class UpdateChecker:
# Use cached channel if available
if self._cached_owner_dm_channel:
return self._cached_owner_dm_channel
-
+
try:
im_client = self.controller.im_client
- if not im_client or not hasattr(im_client, 'web_client'):
+ if not im_client or not hasattr(im_client, "web_client"):
return None
-
+
response = await im_client.web_client.conversations_open(users=[user_id])
if response.get("ok"):
channel_id = response.get("channel", {}).get("id")
@@ -354,22 +358,32 @@ class UpdateChecker:
return channel_id
except Exception as e:
logger.warning(f"Failed to open DM channel with user {user_id}: {e}")
-
+
return None
+ async def _send_update_notification(self, current: str, latest: str) -> None:
+ platform = getattr(self.controller.config, "platform", "slack")
+ if platform == "slack":
+ await self._send_slack_notification(current, latest)
+ return
+ if platform == "discord":
+ await self._send_discord_notification(current, latest)
+ return
+ logger.warning("Update notification skipped for unsupported platform: %s", platform)
+
async def _send_slack_notification(self, current: str, latest: str) -> None:
"""Send a Slack notification about the available update."""
owner_id = await self._get_workspace_owner_id()
if not owner_id:
logger.warning("Cannot send update notification: no workspace owner found")
return
-
+
# Open DM channel first (required for sending messages to users)
dm_channel = await self._open_dm_channel(owner_id)
if not dm_channel:
logger.warning(f"Cannot send update notification: failed to open DM with {owner_id}")
return
-
+
try:
im_client = self.controller.im_client
blocks = [
@@ -378,38 +392,105 @@ class UpdateChecker:
"text": {
"type": "mrkdwn",
"text": f":rocket: *Vibe Remote Update Available*\n\n"
- f"A new version is available: `{current}` → `{latest}`"
- }
+ f"A new version is available: `{current}` → `{latest}`",
+ },
},
{
"type": "actions",
"elements": [
{
"type": "button",
- "text": {
- "type": "plain_text",
- "text": "Update Now",
- "emoji": True
- },
+ "text": {"type": "plain_text", "text": "Update Now", "emoji": True},
"style": "primary",
"action_id": UPDATE_BUTTON_ACTION_ID,
- "value": latest
+ "value": latest,
}
- ]
- }
+ ],
+ },
]
-
+
await im_client.web_client.chat_postMessage(
- channel=dm_channel,
- text=f"Vibe Remote update available: {current} → {latest}",
- blocks=blocks
+ channel=dm_channel, text=f"Vibe Remote update available: {current} → {latest}", blocks=blocks
)
logger.info(f"Sent update notification to workspace owner {owner_id}")
except Exception as e:
logger.error(f"Failed to send update notification: {e}")
+ async def _send_discord_notification(self, current: str, latest: str) -> None:
+ """Send a Discord notification about the available update."""
+ channel_id = self._get_default_notification_channel_id()
+ if not channel_id:
+ logger.warning("Cannot send update notification: no enabled channel found")
+ return
+ try:
+ from modules.im import InlineButton, InlineKeyboard, MessageContext
+
+ text = f"🚀 **Vibe Remote Update Available**\n\nUpdate from `{current}` → `{latest}`"
+ keyboard = InlineKeyboard(
+ buttons=[[InlineButton(text="Update Now", callback_data=f"vibe_update_now:{latest}")]]
+ )
+ context = MessageContext(user_id="system", channel_id=channel_id)
+ await self.controller.im_client.send_message_with_buttons(context, text, keyboard, parse_mode="markdown")
+ logger.info("Sent update notification to Discord channel %s", channel_id)
+ except Exception as e:
+ logger.error(f"Failed to send Discord update notification: {e}")
+
+ def _get_default_notification_channel_id(self) -> Optional[str]:
+ if not hasattr(self.controller, "settings_manager"):
+ return None
+ store = getattr(self.controller.settings_manager, "store", None)
+ channels = getattr(store, "settings", None)
+ if not channels or not hasattr(channels, "channels"):
+ return None
+ for channel_id, settings in channels.channels.items():
+ if getattr(settings, "enabled", False):
+ return str(channel_id)
+ return None
+
+ async def handle_update_button_click(self, context: MessageContext, target_version: Optional[str] = None) -> None:
+ """Handle update button click for Discord (non-Slack)."""
+ im_client = self.controller.im_client
+ if self._upgrade_lock.locked():
+ await im_client.edit_message(
+ context,
+ context.message_id,
+ text="Upgrade already in progress. Please wait.",
+ )
+ return
+
+ if not target_version:
+ version_info = await self._get_version_info_async()
+ if not version_info.get("has_update"):
+ await im_client.edit_message(context, context.message_id, text="Already up to date.")
+ return
+ target_version = version_info.get("latest")
+ if not target_version:
+ await im_client.edit_message(
+ context,
+ context.message_id,
+ text="Update information unavailable. Please try again later.",
+ )
+ return
+
+ await im_client.edit_message(context, context.message_id, text="Updating Vibe Remote...")
+ result = await self._perform_update(
+ target_version, channel_id=context.channel_id, message_id=context.message_id
+ )
+ if not result.get("ok"):
+ await im_client.edit_message(
+ context,
+ context.message_id,
+ text="Upgrade failed. Please check logs.",
+ )
+ elif not result.get("restarting"):
+ await im_client.edit_message(
+ context,
+ context.message_id,
+ text="Upgrade complete. Please restart Vibe Remote.",
+ )
+
async def _perform_update(
- self, target_version: str, channel_id: Optional[str] = None, message_ts: Optional[str] = None
+ self, target_version: str, channel_id: Optional[str] = None, message_id: Optional[str] = None
) -> Dict[str, Any]:
"""Perform the actual update and restart. Returns do_upgrade result dict."""
# Prevent concurrent upgrades
@@ -421,21 +502,20 @@ class UpdateChecker:
"output": None,
"restarting": False,
}
-
+
async with self._upgrade_lock:
logger.info(f"Starting auto-update to version {target_version}")
-
+
# Run upgrade in thread to avoid blocking event loop
from vibe.api import do_upgrade
+
result = await asyncio.to_thread(do_upgrade, True)
-
+
if result["ok"]:
logger.info(f"Upgrade successful: {result['message']}")
if result.get("restarting"):
# Write marker only if restart is scheduled
- self._write_update_marker(
- target_version, channel_id=channel_id, message_ts=message_ts
- )
+ self._write_update_marker(target_version, channel_id=channel_id, message_id=message_id)
else:
logger.warning("Upgrade completed without restart; manual restart required")
return result
@@ -447,7 +527,7 @@ class UpdateChecker:
return result
def _write_update_marker(
- self, version: str, channel_id: Optional[str] = None, message_ts: Optional[str] = None
+ self, version: str, channel_id: Optional[str] = None, message_id: Optional[str] = None
) -> None:
"""Write a marker file to trigger post-update notification."""
try:
@@ -458,13 +538,13 @@ class UpdateChecker:
"updated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
}
# Store message coordinates for updating the original message after restart
- if channel_id and message_ts:
+ if channel_id and message_id:
data["channel_id"] = channel_id
- data["message_ts"] = message_ts
-
+ data["message_id"] = message_id
+
# Atomic write
with tempfile.NamedTemporaryFile(
- mode='w', dir=marker_path.parent, suffix='.tmp', delete=False, encoding='utf-8'
+ mode="w", dir=marker_path.parent, suffix=".tmp", delete=False, encoding="utf-8"
) as f:
json.dump(data, f)
temp_path = Path(f.name)
@@ -485,49 +565,63 @@ class UpdateChecker:
marker_path = paths.get_state_dir() / "pending_update_notification.json"
if not marker_path.exists():
return
-
+
try:
data = json.loads(marker_path.read_text(encoding="utf-8"))
channel_id = data.get("channel_id")
- message_ts = data.get("message_ts")
+ message_id = data.get("message_id")
# Use the target version from marker (more reliable than __version__ in edge cases)
target_version = data.get("version", "unknown")
-
+
im_client = self.controller.im_client
-
- success_text = f":white_check_mark: Vibe Remote has been updated to `{target_version}`"
+
+ platform = getattr(self.controller.config, "platform", "slack")
+ if platform == "discord":
+ success_text = f"✅ Vibe Remote has been updated to `{target_version}`"
+ else:
+ success_text = f":white_check_mark: Vibe Remote has been updated to `{target_version}`"
success_blocks = [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": f":white_check_mark: *Vibe Remote Updated Successfully*\n\n"
- f"Now running version `{target_version}`"
- }
+ f"Now running version `{target_version}`",
+ },
}
]
-
+
# If we have original message coordinates, update that message
- if channel_id and message_ts:
+ if channel_id and message_id and platform == "slack":
await im_client.web_client.chat_update(
channel=channel_id,
- ts=message_ts,
+ ts=message_id,
text=success_text,
- blocks=success_blocks
+ blocks=success_blocks,
)
logger.info("Updated original message with post-update notification")
+ elif channel_id and message_id and platform == "discord":
+ try:
+ from modules.im import MessageContext
+
+ context = MessageContext(user_id="system", channel_id=channel_id)
+ await im_client.edit_message(context, message_id, text=success_text)
+ logger.info("Updated Discord message with post-update notification")
+ except Exception as e:
+ logger.error("Failed to edit Discord update message: %s", e)
else:
# Fallback: send a new message to owner
- owner_id = await self._get_workspace_owner_id()
- if owner_id:
- dm_channel = await self._open_dm_channel(owner_id)
- if dm_channel:
- await im_client.web_client.chat_postMessage(
- channel=dm_channel,
- text=success_text,
- blocks=success_blocks
- )
- logger.info(f"Sent post-update notification to {owner_id}")
+ if platform == "slack":
+ owner_id = await self._get_workspace_owner_id()
+ if owner_id:
+ dm_channel = await self._open_dm_channel(owner_id)
+ if dm_channel:
+ await im_client.web_client.chat_postMessage(
+ channel=dm_channel,
+ text=success_text,
+ blocks=success_blocks,
+ )
+ logger.info(f"Sent post-update notification to {owner_id}")
except Exception as e:
logger.error(f"Failed to send post-update notification: {e}")
finally:
@@ -536,123 +630,120 @@ class UpdateChecker:
async def handle_update_button_click(controller: "Controller", payload: Dict[str, Any]) -> None:
"""Handle the 'Update Now' button click from Slack.
-
+
This function should return quickly to avoid Slack ack timeout.
The actual update is performed in a background task.
"""
channel_id = payload.get("channel", {}).get("id")
- message_ts = payload.get("message", {}).get("ts")
+ message_id = payload.get("message", {}).get("ts")
im_client = controller.im_client
-
+
# Check if upgrade is already in progress
- if hasattr(controller, 'update_checker') and controller.update_checker._upgrade_lock.locked():
+ if hasattr(controller, "update_checker") and controller.update_checker._upgrade_lock.locked():
try:
await im_client.web_client.chat_update(
channel=channel_id,
- ts=message_ts,
+ ts=message_id,
text="Upgrade already in progress",
blocks=[
{
"type": "section",
- "text": {
- "type": "mrkdwn",
- "text": ":warning: An upgrade is already in progress. Please wait."
- }
+ "text": {"type": "mrkdwn", "text": ":warning: An upgrade is already in progress. Please wait."},
}
- ]
+ ],
)
except Exception as e:
logger.error(f"Failed to update message: {e}")
return
-
+
# Update message immediately to acknowledge the click
try:
await im_client.web_client.chat_update(
channel=channel_id,
- ts=message_ts,
+ ts=message_id,
text="Updating Vibe Remote...",
blocks=[
{
"type": "section",
"text": {
"type": "mrkdwn",
- "text": ":hourglass_flowing_sand: *Updating Vibe Remote...*\n\nPlease wait, the service will restart shortly."
- }
+ "text": ":hourglass_flowing_sand: *Updating Vibe Remote...*\n\nPlease wait, the service will restart shortly.",
+ },
}
- ]
+ ],
)
except Exception as e:
logger.error(f"Failed to acknowledge button click: {e}")
return
-
+
# Schedule the actual update in a background task to avoid blocking
- asyncio.create_task(_do_update_from_button(controller, channel_id, message_ts))
+ asyncio.create_task(_do_update_from_button(controller, channel_id, message_id))
-async def _do_update_from_button(controller: "Controller", channel_id: str, message_ts: str) -> None:
+async def _do_update_from_button(controller: "Controller", channel_id: str, message_id: str) -> None:
"""Background task to perform update after button click."""
try:
- if not hasattr(controller, 'update_checker'):
+ if not hasattr(controller, "update_checker"):
return
-
+
update_checker = controller.update_checker
im_client = controller.im_client
-
+
# Check for updates
version_info = await update_checker._get_version_info_async()
-
+
if version_info.get("has_update"):
# Perform the update
result = await update_checker._perform_update(
- version_info["latest"], channel_id=channel_id, message_ts=message_ts
+ version_info["latest"], channel_id=channel_id, message_id=message_id
)
if not result.get("ok"):
# Update failed, show error
await im_client.web_client.chat_update(
channel=channel_id,
- ts=message_ts,
+ ts=message_id,
text="Upgrade failed",
blocks=[
{
"type": "section",
"text": {
"type": "mrkdwn",
- "text": ":x: *Upgrade Failed*\n\nPlease check the logs for details."
- }
+ "text": ":x: *Upgrade Failed*\n\nPlease check the logs for details.",
+ },
}
- ]
+ ],
)
elif not result.get("restarting"):
# Upgrade succeeded but restart not scheduled
await im_client.web_client.chat_update(
channel=channel_id,
- ts=message_ts,
+ ts=message_id,
text="Upgrade completed - restart required",
blocks=[
{
"type": "section",
"text": {
"type": "mrkdwn",
- "text": ":white_check_mark: *Upgrade complete*\n\nPlease restart Vibe Remote to apply the update."
- }
+ "text": ":white_check_mark: *Upgrade complete*\n\nPlease restart Vibe Remote to apply the update.",
+ },
}
- ]
+ ],
)
else:
# No update available
await im_client.web_client.chat_update(
channel=channel_id,
- ts=message_ts,
+ ts=message_id,
text="Already up to date",
blocks=[
{
"type": "section",
- "text": {
- "type": "mrkdwn",
- "text": ":white_check_mark: Already running the latest version."
- }
+ "text": {"type": "mrkdwn", "text": ":white_check_mark: Already running the latest version."},
}
- ]
+ ],
)
except Exception as e:
logger.error(f"Failed to perform update from button click: {e}", exc_info=True)
+
+
+from modules.im import MessageContext
diff --git a/docs/DISCORD_SETUP.md b/docs/DISCORD_SETUP.md
new file mode 100644
index 000000000..7b3656b69
--- /dev/null
+++ b/docs/DISCORD_SETUP.md
@@ -0,0 +1,57 @@
+## TL;DR
+
+```bash
+vibe
+```
+
+Choose **Discord** in the wizard, paste your bot token, validate, pick a guild, enable channels.
+
+---
+
+## Step 1: Create a Discord App
+
+1. Open the [Discord Developer Portal](https://discord.com/developers/applications)
+2. Click **New Application** and name it
+3. Go to **Bot** → **Add Bot**
+4. Copy the **Bot Token**
+
+---
+
+## Step 2: Enable Intents
+
+In **Bot → Privileged Gateway Intents**, enable:
+
+- Message Content Intent
+- Server Members Intent (optional)
+
+---
+
+## Step 3: Invite the Bot
+
+1. Go to **OAuth2 → URL Generator**
+2. Select **bot** scope
+3. Add permissions:
+ - Read Messages/View Channels
+ - Send Messages
+ - Create Public Threads
+ - Send Messages in Threads
+ - Add Reactions
+ - Attach Files
+4. Open the generated URL and invite the bot to your guild
+
+---
+
+## Step 4: Configure in Wizard
+
+1. Run `vibe`
+2. Select **Discord**
+3. Paste bot token → **Validate Token**
+4. Select your guild
+5. Enable channels in the **Channels** step
+
+---
+
+## Notes
+
+- Vibe Remote creates a new Discord thread for each new user message to match Slack session behavior.
+- For DMs, Discord does not support threads; sessions are still isolated per message.
diff --git a/docs/DISCORD_SETUP_ZH.md b/docs/DISCORD_SETUP_ZH.md
new file mode 100644
index 000000000..0647d6cfb
--- /dev/null
+++ b/docs/DISCORD_SETUP_ZH.md
@@ -0,0 +1,57 @@
+## TL;DR
+
+```bash
+vibe
+```
+
+在向导中选择 **Discord**,粘贴机器人令牌,验证后选择服务器并启用频道。
+
+---
+
+## 第一步:创建 Discord 应用
+
+1. 打开 [Discord Developer Portal](https://discord.com/developers/applications)
+2. 点击 **New Application** 并命名
+3. 进入 **Bot** → **Add Bot**
+4. 复制 **Bot Token**
+
+---
+
+## 第二步:启用 Intents
+
+在 **Bot → Privileged Gateway Intents** 中启用:
+
+- Message Content Intent
+- Server Members Intent(可选)
+
+---
+
+## 第三步:邀请机器人
+
+1. 进入 **OAuth2 → URL Generator**
+2. 勾选 **bot** scope
+3. 添加权限:
+ - Read Messages/View Channels
+ - Send Messages
+ - Create Public Threads
+ - Send Messages in Threads
+ - Add Reactions
+ - Attach Files
+4. 打开生成的 URL,把机器人加入服务器
+
+---
+
+## 第四步:向导配置
+
+1. 运行 `vibe`
+2. 选择 **Discord**
+3. 粘贴 Bot Token → **Validate Token**
+4. 选择服务器
+5. 在 **Channels** 步骤启用频道
+
+---
+
+## 说明
+
+- 为了对齐 Slack 的会话体验,每条新消息会创建一个 Discord 线程。
+- 在私信中,Discord 不支持线程,但会话仍按消息隔离。
diff --git a/docs/plans/discord-im.md b/docs/plans/discord-im.md
new file mode 100644
index 000000000..af5c5a747
--- /dev/null
+++ b/docs/plans/discord-im.md
@@ -0,0 +1,105 @@
+# Discord IM Support Plan
+
+## Background
+Vibe Remote currently supports Slack as the only IM transport. The goal is to add Discord as a first-class IM platform, matching Slack feature coverage while preserving existing Slack behavior. This includes full onboarding/configuration flow, UI copy, documentation, and operational parity.
+
+## Goals
+- Add Discord as a supported IM platform alongside Slack (no regression to Slack).
+- Align all Slack features in Discord with equivalent UX and behavior (commands, buttons, modals, reactions, file uploads, routing, settings, resume session, update notifications, etc.).
+- Provide end-to-end setup flow (wizard + docs + copy) for Discord, in both English and Chinese.
+- Keep configuration backward compatible and safe for existing Slack users.
+
+## Non-Goals
+- Voice, stage, or message threading beyond Discord's native capabilities.
+- Multi-workspace Slack redesign or SaaS mode.
+- New agent backends or new CLI commands unrelated to Discord.
+
+## Key Parity Surface (Slack -> Discord)
+- Message intake: mentions, direct messages, channel messages, and thread messages.
+- Commands: `/start`, `/clear`, `/cwd`, `/set_cwd`, `/settings`, `/stop`, `/resume`, `/routing`.
+- Interactive UI: buttons, select menus, and modals for settings/routing/change cwd/resume session.
+- Message formatting (markdown): bold/italic/links/code blocks/quotes/lists.
+- Ack mode: reaction (eyes) and ack message.
+- Inline actions: callback handling for buttons/menus and question modals.
+- File handling: upload result as markdown, download attachments, and persistent storage under `~/.vibe_remote/attachments`.
+- Update notifications and "update now" action.
+- Per-channel routing and settings storage.
+
+## Proposed Architecture Changes
+1) Config model
+ - Add `platform` to `V2Config` with allowed values: `slack` | `discord`.
+ - Introduce `DiscordConfig` in `config/v2_config.py` with required fields (bot token, app ID, public key if needed, guild allowlist/denylist, intents flags).
+ - Update `to_app_config` in `config/v2_compat.py` to pass platform and discord config into `AppCompatConfig`.
+
+2) IM abstraction
+ - Add `modules/im/discord.py` implementing `BaseIMClient` for Discord.
+ - Add `DiscordFormatter` in `modules/im/formatters/discord_formatter.py`.
+ - Update `IMFactory` to create Slack or Discord client based on `config.platform`.
+ - Extend optional IM client capabilities for:
+ - `open_settings_modal`, `open_change_cwd_modal`, `open_routing_modal`, `update_routing_modal`, `open_resume_session_modal`.
+ - `delete_message`, `download_file`, `upload_markdown`, reactions, and interaction handling.
+
+3) Controller & session semantics
+ - Replace Slack-only assumptions:
+ - `SessionHandler.get_base_session_id` should be platform-aware (`{platform}_{thread_or_channel_or_message_id}`).
+ - `Controller._get_settings_key` should remain channel-based but handle Discord DM/guild channel IDs.
+ - Update any Slack-only logic in handlers to branch on `config.platform`.
+
+4) Update notifications
+ - Generalize update checker to send notification via IM client, not Slack WebClient.
+ - Implement Discord equivalent of "Update Now" using a button interaction.
+
+5) API + Web UI
+ - Add Discord setup endpoints in `vibe/api.py`:
+ - token validation, bot identity, guild list, and channel list (where possible).
+ - Update Web UI wizard to include platform selection and a Discord configuration step.
+ - Update i18n keys in `ui/src/i18n/en.json` + `zh.json` and server i18n in `vibe/i18n/*`.
+
+## Discord Implementation Details (Proposed)
+- Library: `discord.py` 2.x (add dependency in `pyproject.toml`).
+- Connection: bot token + gateway; run with `discord.Client` or `commands.Bot` and `app_commands` for slash commands.
+- Intents: enable `GUILD_MESSAGES`, `DIRECT_MESSAGES`, `MESSAGE_CONTENT`, `GUILDS`, and `REACTIONS`.
+- Interactions:
+ - Buttons and select menus via `discord.ui.View`.
+ - Modals via `discord.ui.Modal` (text input only). Use follow-up menus to emulate Slack select in routing/settings.
+- Threading:
+ - Always create a real Discord thread per new user message (Slack parity: per-message session).
+ - Use the created thread ID as `thread_id` and bind the session to that thread.
+ - If message already arrives in a thread, reuse that thread.
+- Mentions:
+ - Respect `require_mention` by checking `bot.user.mentioned_in(message)` in guild channels.
+
+## Setup Flow & Copy
+- Wizard:
+ - Add platform selector (Slack/Discord) before platform-specific config.
+ - Discord config step: bot token, optional guild allowlist, and permissions/intents guidance.
+ - Channel list step should support Discord channels (guild selection + channel checkboxes).
+- Docs:
+ - Add `docs/DISCORD_SETUP.md` and `docs/DISCORD_SETUP_ZH.md`.
+ - Update `README.md` and `README_ZH.md` to mention Discord support and setup links.
+- Slack docs remain unchanged.
+
+## Data Model & Migration
+- Backward compatible: existing configs without `platform` default to `slack`.
+- Discord config section optional unless platform=discord.
+- Settings store remains channel-based; no migration needed beyond platform prefix in session IDs.
+
+## Testing Plan
+- Unit-style checks:
+ - Config load/validate for Discord and Slack.
+ - Formatter parity (markdown examples).
+- Manual E2E:
+ - Discord bot setup and OAuth invite flow.
+ - DM and channel interactions (commands, buttons, modals).
+ - File attachments upload/download.
+ - Routing + resume session flows.
+ - Update notification button flow.
+
+## Milestones
+1) Config + IM factory + formatter + minimal Discord client (send/receive messages).
+2) Commands + settings + routing + resume session interactions on Discord.
+3) Attachments, reactions, update notifications, and parity polish.
+4) Wizard + docs + i18n copy.
+
+## Open Questions
+- For routing/settings UI on Discord, do we accept multi-step ephemeral menus instead of a single modal (Discord limitation)?
diff --git a/modules/agents/opencode/question_handler.py b/modules/agents/opencode/question_handler.py
index 14bb4f4a4..ea5796833 100644
--- a/modules/agents/opencode/question_handler.py
+++ b/modules/agents/opencode/question_handler.py
@@ -116,9 +116,7 @@ class OpenCodeQuestionHandler:
)
return False
- logger.info(
- "Answer received for %s, resuming poll loop", request.base_session_id
- )
+ logger.info("Answer received for %s, resuming poll loop", request.base_session_id)
return True
except asyncio.TimeoutError:
logger.warning(
@@ -149,8 +147,7 @@ class OpenCodeQuestionHandler:
await self._im_client.remove_inline_keyboard(
request.context,
msg_id,
- text=(pending.get("prompt_text") or "")
- + "\n\n_(Timed out waiting for answer)_",
+ text=(pending.get("prompt_text") or "") + "\n\n_(Timed out waiting for answer)_",
parse_mode="markdown",
)
except Exception:
@@ -168,9 +165,7 @@ class OpenCodeQuestionHandler:
try:
server = await self._get_server()
await server.abort_session(session_id, directory)
- logger.info(
- "Aborted OpenCode session %s after question timeout", session_id
- )
+ logger.info("Aborted OpenCode session %s after question timeout", session_id)
except Exception as e:
logger.warning(f"Failed to abort session on timeout: {e}")
@@ -197,20 +192,22 @@ class OpenCodeQuestionHandler:
return ""
return "已选择:\n" + "\n".join(lines)
- async def open_question_modal(
- self, request: AgentRequest, pending: PendingQuestionPayload
- ) -> None:
+ async def open_question_modal(self, request: AgentRequest, pending: PendingQuestionPayload) -> None:
trigger_id = None
+ interaction = None
if request.context.platform_specific:
trigger_id = request.context.platform_specific.get("trigger_id")
- if not trigger_id:
+ interaction = request.context.platform_specific.get("interaction")
+ if not trigger_id and not interaction:
await self._im_client.send_message(
request.context,
- "Slack did not provide a trigger_id for the modal. Please reply with a custom message.",
+ "Modal UI is not available. Please reply with a custom message.",
)
return
- if not hasattr(self._im_client, "open_opencode_question_modal"):
+ if not hasattr(self._im_client, "open_opencode_question_modal") and not hasattr(
+ self._im_client, "open_question_modal"
+ ):
await self._im_client.send_message(
request.context,
"Modal UI is not available. Please reply with a custom message.",
@@ -218,11 +215,19 @@ class OpenCodeQuestionHandler:
return
try:
- await self._im_client.open_opencode_question_modal(
- trigger_id=trigger_id,
- context=request.context,
- pending=pending,
- )
+ if hasattr(self._im_client, "open_opencode_question_modal"):
+ await self._im_client.open_opencode_question_modal(
+ trigger_id=interaction or trigger_id,
+ context=request.context,
+ pending=pending,
+ )
+ else:
+ await self._im_client.open_question_modal(
+ trigger_id=interaction or trigger_id,
+ context=request.context,
+ pending=pending,
+ callback_prefix="opencode_question",
+ )
except Exception as err:
logger.error(f"Failed to open OpenCode question modal: {err}", exc_info=True)
await self._im_client.send_message(
@@ -321,11 +326,7 @@ class OpenCodeQuestionHandler:
questions = await server.list_questions()
for item in questions:
tool = item.get("tool") or {}
- item_session_id = (
- item.get("sessionID")
- or item.get("sessionId")
- or item.get("session_id")
- )
+ item_session_id = item.get("sessionID") or item.get("sessionId") or item.get("session_id")
if item_session_id != session_id:
continue
if call_id and tool.get("callID") != call_id:
@@ -410,13 +411,9 @@ class OpenCodeQuestionHandler:
if question_message_id and hasattr(self._im_client, "add_reaction"):
try:
emoji = "eyes"
- await self._im_client.add_reaction(
- request.context, question_message_id, emoji
- )
+ await self._im_client.add_reaction(request.context, question_message_id, emoji)
# Save for cleanup when request completes
- self._answer_reactions[request.base_session_id] = (
- request.context, question_message_id, emoji
- )
+ self._answer_reactions[request.base_session_id] = (request.context, question_message_id, emoji)
except Exception as err:
logger.debug(f"Failed to add reaction to question message: {err}")
@@ -427,13 +424,9 @@ class OpenCodeQuestionHandler:
evt = self._question_answer_events.get(request.base_session_id)
if evt:
evt.set()
- logger.info(
- "Answer submitted for %s, signaling main poll loop to resume", session_id
- )
+ logger.info("Answer submitted for %s, signaling main poll loop to resume", session_id)
else:
- logger.warning(
- "No wait event found for %s; cannot resume poll", request.base_session_id
- )
+ logger.warning("No wait event found for %s; cannot resume poll", request.base_session_id)
await self._controller.emit_agent_message(
request.context,
"notify",
@@ -503,9 +496,7 @@ class OpenCodeQuestionHandler:
await asyncio.sleep(delay)
if last_list_err and not questions_listing:
- logger.warning(
- f"Failed to fetch questions listing for prompt fallback: {last_list_err}"
- )
+ logger.warning(f"Failed to fetch questions listing for prompt fallback: {last_list_err}")
logger.info(
"Question list fetch for %s: dir=%s attempts=%s items=%s",
@@ -518,16 +509,10 @@ class OpenCodeQuestionHandler:
if questions_listing:
try:
item_sessions = [
- (
- item.get("sessionID")
- or item.get("sessionId")
- or item.get("session_id")
- )
+ (item.get("sessionID") or item.get("sessionId") or item.get("session_id"))
for item in questions_listing
]
- logger.info(
- "Question list sessions for %s: %s", opencode_session_id, item_sessions
- )
+ logger.info("Question list sessions for %s: %s", opencode_session_id, item_sessions)
except Exception:
pass
@@ -550,11 +535,7 @@ class OpenCodeQuestionHandler:
if questions_listing:
session_items: List[Dict[str, Any]] = []
for item in questions_listing:
- item_session_id = (
- item.get("sessionID")
- or item.get("sessionId")
- or item.get("session_id")
- )
+ item_session_id = item.get("sessionID") or item.get("sessionId") or item.get("session_id")
if item_session_id == opencode_session_id:
session_items.append(item)
@@ -622,9 +603,7 @@ class OpenCodeQuestionHandler:
continue
msg_state = msg_part.get("state") or {}
msg_input = msg_state.get("input") or {}
- msg_questions = (
- msg_input.get("questions") if isinstance(msg_input, dict) else None
- )
+ msg_questions = msg_input.get("questions") if isinstance(msg_input, dict) else None
if isinstance(msg_questions, list):
qlist = msg_questions
break
@@ -637,9 +616,7 @@ class OpenCodeQuestionHandler:
await asyncio.sleep(delay)
if last_msg_err and not qlist:
- logger.warning(
- f"Failed to fetch full question input from message {message_id}: {last_msg_err}"
- )
+ logger.warning(f"Failed to fetch full question input from message {message_id}: {last_msg_err}")
if full_message is not None:
parts = full_message.get("parts", []) or []
tool_parts = [p for p in parts if p.get("type") == "tool"]
@@ -753,9 +730,7 @@ class OpenCodeQuestionHandler:
pending_payload["prompt_message_id"] = question_message_id
seen_tool_calls.add(call_key)
- if await self.wait_for_question_answer(
- request, opencode_session_id, pending_payload
- ):
+ if await self.wait_for_question_answer(request, opencode_session_id, pending_payload):
return True
return False
except Exception as err:
@@ -764,9 +739,7 @@ class OpenCodeQuestionHandler:
exc_info=True,
)
- await self._im_client.send_message(
- request.context, text, parse_mode="markdown"
- )
+ await self._im_client.send_message(request.context, text, parse_mode="markdown")
seen_tool_calls.add(call_key)
if await self.wait_for_question_answer(request, opencode_session_id, pending_payload):
return True
@@ -809,9 +782,7 @@ class OpenCodeQuestionHandler:
if question_message_id:
pending_payload["prompt_message_id"] = question_message_id
seen_tool_calls.add(call_key)
- if await self.wait_for_question_answer(
- request, opencode_session_id, pending_payload
- ):
+ if await self.wait_for_question_answer(request, opencode_session_id, pending_payload):
return True
return False
except Exception as err:
diff --git a/modules/agents/question_ui.py b/modules/agents/question_ui.py
index 07958063b..b1be44b7d 100644
--- a/modules/agents/question_ui.py
+++ b/modules/agents/question_ui.py
@@ -204,9 +204,7 @@ class QuestionUIHandler:
)
return False
- logger.info(
- "Answer received for %s, resuming", request.base_session_id
- )
+ logger.info("Answer received for %s, resuming", request.base_session_id)
return True
except asyncio.TimeoutError:
logger.warning(
@@ -357,9 +355,7 @@ class QuestionUIHandler:
exc_info=True,
)
# Fallback to text-only
- await self._im_client.send_message(
- request.context, text, parse_mode="markdown"
- )
+ await self._im_client.send_message(request.context, text, parse_mode="markdown")
return None
async def _render_modal_trigger(
@@ -389,22 +385,20 @@ class QuestionUIHandler:
exc_info=True,
)
# Fallback to text-only
- await self._im_client.send_message(
- request.context, text, parse_mode="markdown"
- )
+ await self._im_client.send_message(request.context, text, parse_mode="markdown")
return None
- async def open_modal(
- self, request: AgentRequest, pending: PendingQuestion
- ) -> None:
+ async def open_modal(self, request: AgentRequest, pending: PendingQuestion) -> None:
"""Open the question modal."""
trigger_id = None
+ interaction = None
if request.context.platform_specific:
trigger_id = request.context.platform_specific.get("trigger_id")
- if not trigger_id:
+ interaction = request.context.platform_specific.get("interaction")
+ if not trigger_id and not interaction:
await self._im_client.send_message(
request.context,
- "Slack did not provide a trigger_id for the modal. Please reply with a custom message.",
+ "Modal UI is not available. Please reply with a custom message.",
)
return
@@ -417,7 +411,7 @@ class QuestionUIHandler:
try:
await self._im_client.open_question_modal(
- trigger_id=trigger_id,
+ trigger_id=interaction or trigger_id,
context=request.context,
pending=pending,
callback_prefix=self._callback_prefix,
@@ -495,12 +489,8 @@ class QuestionUIHandler:
try:
emoji = "eyes"
- await self._im_client.add_reaction(
- request.context, question_message_id, emoji
- )
+ await self._im_client.add_reaction(request.context, question_message_id, emoji)
# Save for cleanup when request completes
- self._answer_reactions[request.base_session_id] = (
- request.context, question_message_id, emoji
- )
+ self._answer_reactions[request.base_session_id] = (request.context, question_message_id, emoji)
except Exception as err:
logger.debug(f"Failed to add reaction to question message: {err}")
diff --git a/modules/im/discord.py b/modules/im/discord.py
new file mode 100644
index 000000000..b6b3608f1
--- /dev/null
+++ b/modules/im/discord.py
@@ -0,0 +1,1003 @@
+import asyncio
+import io
+import json
+import logging
+from typing import Dict, Any, Optional, Callable, List
+
+import aiohttp
+import discord
+
+from .base import BaseIMClient, MessageContext, InlineKeyboard, InlineButton, FileAttachment
+from config.v2_config import DiscordConfig
+from .formatters import DiscordFormatter
+from vibe.i18n import get_supported_languages, t as i18n_t
+
+logger = logging.getLogger(__name__)
+
+
+class DiscordBot(BaseIMClient):
+ """Discord implementation of the IM client."""
+
+ def __init__(self, config: DiscordConfig):
+ super().__init__(config)
+ self.config = config
+
+ intents = discord.Intents.default()
+ intents.message_content = True
+ intents.guilds = True
+ intents.messages = True
+ intents.dm_messages = True
+ intents.reactions = True
+
+ self.client = discord.Client(intents=intents)
+ self.formatter = DiscordFormatter()
+
+ self.settings_manager = None
+ self._controller = None
+ self._on_ready: Optional[Callable] = None
+
+ self.client.event(self._on_ready_event)
+ self.client.event(self._on_message_event)
+
+ def set_settings_manager(self, settings_manager):
+ self.settings_manager = settings_manager
+
+ def set_controller(self, controller):
+ self._controller = controller
+
+ def register_callbacks(
+ self,
+ on_message: Optional[Callable] = None,
+ on_command: Optional[Dict[str, Callable]] = None,
+ on_callback_query: Optional[Callable] = None,
+ **kwargs,
+ ):
+ super().register_callbacks(on_message, on_command, on_callback_query, **kwargs)
+ if "on_settings_update" in kwargs:
+ self._on_settings_update = kwargs["on_settings_update"]
+ if "on_change_cwd" in kwargs:
+ self._on_change_cwd = kwargs["on_change_cwd"]
+ if "on_routing_update" in kwargs:
+ self._on_routing_update = kwargs["on_routing_update"]
+ if "on_resume_session" in kwargs:
+ self._on_resume_session = kwargs["on_resume_session"]
+ if "on_ready" in kwargs:
+ self._on_ready = kwargs["on_ready"]
+
+ def _get_lang(self, channel_id: Optional[str] = None) -> str:
+ if self._controller and hasattr(self._controller, "config"):
+ if hasattr(self._controller, "_get_lang"):
+ return self._controller._get_lang()
+ return getattr(self._controller.config, "language", "en")
+ return "en"
+
+ def _t(self, key: str, channel_id: Optional[str] = None, **kwargs) -> str:
+ lang = self._get_lang(channel_id)
+ return i18n_t(key, lang, **kwargs)
+
+ def get_default_parse_mode(self) -> str:
+ return "markdown"
+
+ def should_use_thread_for_reply(self) -> bool:
+ return True
+
+ def format_markdown(self, text: str) -> str:
+ return text
+
+ def register_handlers(self):
+ return
+
+ 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 shutdown(self) -> None:
+ await self.client.close()
+
+ # ---------------------------------------------------------------------
+ # Message helpers
+ # ---------------------------------------------------------------------
+ def _to_int_id(self, value: Optional[str]) -> Optional[int]:
+ if not value:
+ return None
+ try:
+ return int(value)
+ except (TypeError, ValueError):
+ return None
+
+ async def _fetch_channel(self, channel_id: Optional[str]) -> Optional[discord.abc.Messageable]:
+ cid = self._to_int_id(channel_id)
+ if cid is None:
+ return None
+ channel = self.client.get_channel(cid)
+ if channel is not None:
+ return channel
+ try:
+ return await self.client.fetch_channel(cid)
+ except Exception as err:
+ logger.debug("Failed to fetch channel %s: %s", channel_id, err)
+ return None
+
+ def _extract_context_ids(self, channel: discord.abc.GuildChannel | discord.Thread) -> tuple[str, Optional[str]]:
+ if isinstance(channel, discord.Thread):
+ parent_id = str(channel.parent_id) if channel.parent_id else str(channel.id)
+ return parent_id, str(channel.id)
+ return str(channel.id), None
+
+ def _clean_message_text(self, text: str) -> str:
+ return (text or "").strip()
+
+ async def send_message(
+ self,
+ context: MessageContext,
+ text: str,
+ parse_mode: Optional[str] = None,
+ reply_to: Optional[str] = None,
+ ) -> str:
+ if not text:
+ raise ValueError("Discord send_message requires non-empty text")
+ target = None
+ if context.thread_id:
+ target = await self._fetch_channel(context.thread_id)
+ if not isinstance(target, discord.Thread):
+ target = None
+ if target is None:
+ target = await self._fetch_channel(context.channel_id)
+ if target is None:
+ raise RuntimeError("Discord channel not found")
+ message = await target.send(content=text)
+ if self.settings_manager and context.thread_id:
+ try:
+ self.settings_manager.mark_thread_active(context.user_id, context.channel_id, context.thread_id)
+ except Exception:
+ pass
+ return str(message.id)
+
+ async def send_message_with_buttons(
+ self,
+ context: MessageContext,
+ text: str,
+ keyboard: InlineKeyboard,
+ parse_mode: Optional[str] = None,
+ ) -> str:
+ target = None
+ if context.thread_id:
+ target = await self._fetch_channel(context.thread_id)
+ if not isinstance(target, discord.Thread):
+ target = None
+ if target is None:
+ target = await self._fetch_channel(context.channel_id)
+ if target is None:
+ raise RuntimeError("Discord channel not found")
+
+ view = _DiscordButtonView(self, context, keyboard)
+ message = await target.send(content=text, view=view)
+ if self.settings_manager and context.thread_id:
+ try:
+ self.settings_manager.mark_thread_active(context.user_id, context.channel_id, context.thread_id)
+ except Exception:
+ pass
+ return str(message.id)
+
+ async def edit_message(
+ self,
+ context: MessageContext,
+ message_id: str,
+ text: Optional[str] = None,
+ keyboard: Optional[InlineKeyboard] = None,
+ parse_mode: Optional[str] = None,
+ ) -> bool:
+ target = None
+ if context.thread_id:
+ target = await self._fetch_channel(context.thread_id)
+ if not isinstance(target, discord.Thread):
+ target = None
+ if target is None:
+ target = await self._fetch_channel(context.channel_id)
+ if target is None:
+ return False
+ try:
+ msg = await target.fetch_message(int(message_id))
+ view = _DiscordButtonView(self, context, keyboard) if keyboard else None
+ await msg.edit(content=text, view=view)
+ return True
+ except Exception as err:
+ logger.debug("Failed to edit Discord message: %s", err)
+ return False
+
+ async def remove_inline_keyboard(
+ self,
+ context: MessageContext,
+ message_id: str,
+ text: Optional[str] = None,
+ parse_mode: Optional[str] = None,
+ ) -> bool:
+ return 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:
+ return True
+
+ async def add_reaction(self, context: MessageContext, message_id: str, emoji: str) -> bool:
+ target = await self._fetch_channel(context.thread_id or context.channel_id)
+ if target is None:
+ return False
+ try:
+ msg = await target.fetch_message(int(message_id))
+ await msg.add_reaction(emoji)
+ return True
+ except Exception as err:
+ logger.debug("Failed to add Discord reaction: %s", err)
+ return False
+
+ async def remove_reaction(self, context: MessageContext, message_id: str, emoji: str) -> bool:
+ target = await self._fetch_channel(context.thread_id or context.channel_id)
+ if target is None:
+ return False
+ try:
+ msg = await target.fetch_message(int(message_id))
+ await msg.remove_reaction(emoji, self.client.user)
+ return True
+ except Exception as err:
+ logger.debug("Failed to remove Discord reaction: %s", err)
+ return False
+
+ async def upload_markdown(
+ self,
+ context: MessageContext,
+ title: str,
+ content: str,
+ filetype: str = "markdown",
+ ) -> str:
+ target = await self._fetch_channel(context.thread_id or context.channel_id)
+ if target is None:
+ raise RuntimeError("Discord channel not found")
+ data = (content or "").encode("utf-8")
+ file_obj = discord.File(io.BytesIO(data), filename=title)
+ message = await target.send(file=file_obj)
+ return str(message.id)
+
+ async def download_file(
+ self,
+ file_info: Dict[str, Any],
+ max_bytes: int = 20 * 1024 * 1024,
+ timeout_seconds: int = 30,
+ ) -> Optional[bytes]:
+ url = file_info.get("url") or file_info.get("url_private_download") or file_info.get("url_private")
+ if not url:
+ return None
+ try:
+ timeout = aiohttp.ClientTimeout(total=timeout_seconds)
+ async with aiohttp.ClientSession(timeout=timeout) as session:
+ async with session.get(url) as response:
+ if response.status != 200:
+ return None
+ content_length = response.headers.get("Content-Length")
+ if content_length and int(content_length) > max_bytes:
+ return None
+ chunks = []
+ total_size = 0
+ async for chunk in response.content.iter_chunked(64 * 1024):
+ total_size += len(chunk)
+ if total_size > max_bytes:
+ return None
+ chunks.append(chunk)
+ return b"".join(chunks)
+ except Exception as err:
+ logger.debug("Failed to download Discord file: %s", err)
+ return None
+
+ async def get_user_info(self, user_id: str) -> Dict[str, Any]:
+ uid = self._to_int_id(user_id)
+ if uid is None:
+ return {"id": user_id}
+ user = self.client.get_user(uid)
+ if user is None:
+ try:
+ user = await self.client.fetch_user(uid)
+ except Exception:
+ user = None
+ if user is None:
+ return {"id": user_id}
+ return {"id": str(user.id), "name": user.name, "display_name": user.display_name}
+
+ async def get_channel_info(self, channel_id: str) -> Dict[str, Any]:
+ channel = await self._fetch_channel(channel_id)
+ if channel is None:
+ return {"id": channel_id, "name": channel_id}
+ name = getattr(channel, "name", None) or channel_id
+ return {"id": str(channel.id), "name": name}
+
+ # ---------------------------------------------------------------------
+ # Discord-specific interaction helpers
+ # ---------------------------------------------------------------------
+ async def _on_ready_event(self):
+ logger.info("Discord client ready")
+ if self._on_ready:
+ await self._on_ready()
+
+ async def _is_authorized_channel(self, channel_id: str) -> bool:
+ if not self.settings_manager:
+ logger.warning("No settings_manager configured; rejecting by default")
+ return False
+ settings = self.settings_manager.get_channel_settings(channel_id)
+ if settings is None:
+ logger.warning("No channel settings found; rejecting by default")
+ return False
+ return settings.enabled
+
+ async def _send_unauthorized_message(self, channel_id: str):
+ try:
+ channel = await self._fetch_channel(channel_id)
+ if channel is None:
+ return
+ await channel.send(content=f"❌ {self._t('error.channelNotEnabled', channel_id)}")
+ except Exception as err:
+ logger.debug("Failed to send unauthorized message: %s", err)
+
+ async def _maybe_create_thread(self, message: discord.Message) -> Optional[discord.Thread]:
+ if isinstance(message.channel, discord.Thread):
+ return message.channel
+ if message.guild is None:
+ return None
+ try:
+ snippet = (message.content or "").strip()
+ if snippet:
+ snippet = snippet[:50]
+ name = snippet or "vibe-remote session"
+ thread = await message.create_thread(name=name, auto_archive_duration=60)
+ return thread
+ except Exception as err:
+ logger.warning("Failed to create thread: %s", err)
+ return None
+
+ async def _on_message_event(self, message: discord.Message):
+ if message.author and message.author.bot:
+ return
+
+ content = self._clean_message_text(message.content)
+
+ channel = message.channel
+ channel_id, thread_id = self._extract_context_ids(channel)
+
+ # File attachments
+ files = None
+ if message.attachments:
+ files = []
+ for attachment in message.attachments:
+ files.append(
+ FileAttachment(
+ name=attachment.filename,
+ mimetype=attachment.content_type or "application/octet-stream",
+ url=attachment.url,
+ size=attachment.size,
+ )
+ )
+
+ if not content and not files:
+ return
+
+ # Authorization
+ if not await self._is_authorized_channel(channel_id):
+ await self._send_unauthorized_message(channel_id)
+ return
+
+ # Mention logic for guild channels
+ is_dm = isinstance(channel, discord.DMChannel) or message.guild is None
+ effective_require_mention = self.config.require_mention
+ if self.settings_manager:
+ effective_require_mention = self.settings_manager.get_require_mention(
+ channel_id, global_default=self.config.require_mention
+ )
+
+ if effective_require_mention and not is_dm:
+ if isinstance(channel, discord.Thread):
+ if self.settings_manager:
+ if not self.settings_manager.is_thread_active(str(message.author.id), channel_id, str(channel.id)):
+ return
+ else:
+ return
+ else:
+ if not message.mentions or (self.client.user and self.client.user not in message.mentions):
+ return
+
+ # Strip bot mention from content
+ if self.client.user:
+ bot_id = str(self.client.user.id)
+ content = content.replace(f"<@{bot_id}>", "").replace(f"<@!{bot_id}>", "").strip()
+
+ # For non-thread guild messages, create a real thread
+ if not isinstance(channel, discord.Thread) and message.guild is not None:
+ thread = await self._maybe_create_thread(message)
+ if thread is not None:
+ thread_id = str(thread.id)
+
+ context = MessageContext(
+ user_id=str(message.author.id),
+ channel_id=channel_id,
+ thread_id=thread_id,
+ message_id=str(message.id),
+ platform_specific={"message": message},
+ files=files,
+ )
+
+ # Handle slash-like commands in plain messages
+ if content.startswith("/"):
+ parts = content.split(maxsplit=1)
+ command = parts[0][1:]
+ args = parts[1] if len(parts) > 1 else ""
+ if command in self.on_command_callbacks:
+ handler = self.on_command_callbacks[command]
+ await handler(context, args)
+ return
+
+ if self.on_message_callback:
+ await self.on_message_callback(context, content)
+
+ # ---------------------------------------------------------------------
+ # Discord UI helpers (modals and selects)
+ # ---------------------------------------------------------------------
+ async def open_change_cwd_modal(self, interaction: discord.Interaction, current_cwd: str, channel_id: str):
+ class ChangeCwdModal(discord.ui.Modal, title="Change Working Directory"):
+ new_cwd = discord.ui.TextInput(label="New working directory", default=current_cwd or "", required=True)
+
+ async def on_submit(self, submit_interaction: discord.Interaction):
+ if not hasattr(self, "_outer"):
+ return
+ outer: DiscordBot = getattr(self, "_outer")
+ if hasattr(outer, "_on_change_cwd"):
+ await outer._on_change_cwd(
+ str(submit_interaction.user.id),
+ str(self.new_cwd.value or ""),
+ channel_id,
+ )
+ await submit_interaction.response.send_message("✅ Working directory updated.", ephemeral=True)
+
+ modal = ChangeCwdModal()
+ modal._outer = self
+ await interaction.response.send_modal(modal)
+
+ async def open_settings_modal(
+ self,
+ trigger_id: Any,
+ user_settings: Any,
+ message_types: list,
+ display_names: dict,
+ channel_id: str = None,
+ current_require_mention: object = None,
+ global_require_mention: bool = False,
+ current_language: str = None,
+ ):
+ interaction = trigger_id if isinstance(trigger_id, discord.Interaction) else None
+
+ selected_types = set(user_settings.show_message_types or [])
+ type_options = [
+ discord.SelectOption(
+ label=display_names.get(mt, mt),
+ value=mt,
+ default=mt in selected_types,
+ )
+ for mt in message_types
+ ]
+ require_options = [
+ discord.SelectOption(label="Default", value="__default__", default=current_require_mention is None),
+ discord.SelectOption(label="Require mention", value="true", default=current_require_mention is True),
+ discord.SelectOption(label="No mention required", value="false", default=current_require_mention is False),
+ ]
+ language_options = [
+ discord.SelectOption(label=lang, value=lang, default=lang == current_language)
+ for lang in get_supported_languages()
+ ]
+
+ class SettingsView(discord.ui.View):
+ def __init__(self, outer: DiscordBot):
+ super().__init__(timeout=900)
+ self.outer = outer
+ self.types_select = discord.ui.Select(
+ placeholder="Visible message types",
+ options=type_options,
+ min_values=0,
+ max_values=len(type_options) if type_options else 1,
+ )
+ self.require_select = discord.ui.Select(
+ placeholder="Require mention",
+ options=require_options,
+ min_values=1,
+ max_values=1,
+ )
+ self.lang_select = discord.ui.Select(
+ placeholder="Language",
+ options=language_options,
+ min_values=1,
+ max_values=1,
+ )
+ self.add_item(self.types_select)
+ self.add_item(self.require_select)
+ self.add_item(self.lang_select)
+ self.add_item(discord.ui.Button(label="Save", style=discord.ButtonStyle.primary))
+
+ async def interaction_check(self, interaction: discord.Interaction) -> bool:
+ return True
+
+ async def on_error(self, interaction: discord.Interaction, error: Exception, item: discord.ui.Item) -> None:
+ logger.debug("SettingsView error: %s", error)
+
+ async def on_timeout(self) -> None:
+ return
+
+ view = SettingsView(self)
+
+ async def save_callback(save_interaction: discord.Interaction):
+ show_types = list(view.types_select.values or [])
+ require_value = view.require_select.values[0] if view.require_select.values else "__default__"
+ if require_value == "__default__":
+ require_mention = None
+ elif require_value == "true":
+ require_mention = True
+ else:
+ require_mention = False
+ language = view.lang_select.values[0] if view.lang_select.values else current_language
+ if hasattr(self, "_on_settings_update"):
+ await self._on_settings_update(
+ str(save_interaction.user.id),
+ show_types,
+ channel_id or str(save_interaction.channel_id or ""),
+ require_mention,
+ language,
+ )
+ await save_interaction.response.edit_message(content="✅ Settings updated.", view=None)
+
+ # Patch the save button callback
+ for item in view.children:
+ if isinstance(item, discord.ui.Button) and item.label == "Save":
+ item.callback = save_callback
+
+ if interaction:
+ await interaction.response.send_message(
+ "⚙️ Settings",
+ view=view,
+ ephemeral=True,
+ )
+ else:
+ channel = await self._fetch_channel(channel_id)
+ if channel is None:
+ raise RuntimeError("Discord channel not found")
+ await channel.send("⚙️ Settings", view=view)
+
+ async def open_resume_session_modal(
+ self,
+ trigger_id: Any,
+ sessions_by_agent: dict,
+ channel_id: str,
+ thread_id: str,
+ host_message_ts: Optional[str] = None,
+ ):
+ interaction = trigger_id if isinstance(trigger_id, discord.Interaction) else None
+ options = []
+ for agent, mapping in sessions_by_agent.items():
+ for thread_key, session_id in mapping.items():
+ label = f"{agent}:{session_id[:24]}"
+ options.append(discord.SelectOption(label=label, value=f"{agent}|{session_id}"))
+ if not options:
+ options = [discord.SelectOption(label="No stored sessions", value="__none__")]
+
+ agent_options = [discord.SelectOption(label=agent, value=agent) for agent in sorted(sessions_by_agent.keys())]
+ if not agent_options:
+ agent_options = [discord.SelectOption(label="default", value="opencode")]
+
+ class ManualSessionModal(discord.ui.Modal, title="Resume Session"):
+ session_id = discord.ui.TextInput(label="Session ID", required=True)
+
+ async def on_submit(self, submit_interaction: discord.Interaction):
+ if not hasattr(self, "_view"):
+ return
+ view: ResumeView = getattr(self, "_view")
+ view.manual_session = str(self.session_id.value)
+ await submit_interaction.response.send_message("✅ Session ID captured.", ephemeral=True)
+
+ class ResumeView(discord.ui.View):
+ def __init__(self, outer: DiscordBot):
+ super().__init__(timeout=900)
+ self.outer = outer
+ self.manual_session: Optional[str] = None
+ self.session_select = discord.ui.Select(
+ placeholder="Choose a stored session",
+ options=options,
+ min_values=1,
+ max_values=1,
+ )
+ self.agent_select = discord.ui.Select(
+ placeholder="Agent (for manual input)",
+ options=agent_options,
+ min_values=1,
+ max_values=1,
+ )
+ self.add_item(self.session_select)
+ self.add_item(self.agent_select)
+ self.add_item(discord.ui.Button(label="Enter session ID", style=discord.ButtonStyle.secondary))
+ self.add_item(discord.ui.Button(label="Resume", style=discord.ButtonStyle.primary))
+
+ view = ResumeView(self)
+
+ async def manual_callback(manual_interaction: discord.Interaction):
+ modal = ManualSessionModal()
+ modal._view = view
+ await manual_interaction.response.send_modal(modal)
+
+ async def resume_callback(resume_interaction: discord.Interaction):
+ selected = view.session_select.values[0] if view.session_select.values else None
+ chosen_agent = view.agent_select.values[0] if view.agent_select.values else None
+ chosen_session = None
+ if selected and selected != "__none__" and "|" in selected:
+ chosen_agent, chosen_session = selected.split("|", 1)
+ if view.manual_session:
+ chosen_session = view.manual_session
+ if hasattr(self, "_on_resume_session"):
+ await self._on_resume_session(
+ str(resume_interaction.user.id),
+ channel_id,
+ thread_id,
+ chosen_agent,
+ chosen_session,
+ host_message_ts,
+ )
+ await resume_interaction.response.edit_message(content="✅ Session resumed.", view=None)
+
+ for item in view.children:
+ if isinstance(item, discord.ui.Button) and item.label == "Enter session ID":
+ item.callback = manual_callback
+ if isinstance(item, discord.ui.Button) and item.label == "Resume":
+ item.callback = resume_callback
+
+ if interaction:
+ await interaction.response.send_message("⏮️ Resume session", view=view, ephemeral=True)
+ else:
+ channel = await self._fetch_channel(channel_id)
+ if channel is None:
+ raise RuntimeError("Discord channel not found")
+ await channel.send("⏮️ Resume session", view=view)
+
+ async def open_routing_modal(
+ self,
+ trigger_id: Any,
+ channel_id: str,
+ registered_backends: list,
+ current_backend: str,
+ current_routing: Any,
+ opencode_agents: list,
+ opencode_models: dict,
+ opencode_default_config: dict,
+ claude_agents: list,
+ claude_models: list,
+ codex_models: list,
+ ):
+ interaction = trigger_id if isinstance(trigger_id, discord.Interaction) else None
+
+ class RoutingView(discord.ui.View):
+ def __init__(self, outer: DiscordBot):
+ super().__init__(timeout=900)
+ self.outer = outer
+ self.step = "backend"
+ self.selected_backend = current_backend or (
+ registered_backends[0] if registered_backends else "opencode"
+ )
+ self.oc_agent = getattr(current_routing, "opencode_agent", None) if current_routing else None
+ self.oc_model = getattr(current_routing, "opencode_model", None) if current_routing else None
+ self.oc_reasoning = (
+ getattr(current_routing, "opencode_reasoning_effort", None) if current_routing else None
+ )
+ self.claude_agent = getattr(current_routing, "claude_agent", None) if current_routing else None
+ self.claude_model = getattr(current_routing, "claude_model", None) if current_routing else None
+ self.codex_model = getattr(current_routing, "codex_model", None) if current_routing else None
+ self.codex_reasoning = (
+ getattr(current_routing, "codex_reasoning_effort", None) if current_routing else None
+ )
+ self._render()
+
+ def _render(self):
+ self.clear_items()
+ if self.step == "backend":
+ options = [
+ discord.SelectOption(label=backend, value=backend, default=backend == self.selected_backend)
+ for backend in registered_backends
+ ]
+ backend_select = discord.ui.Select(
+ placeholder="Select backend",
+ options=options,
+ min_values=1,
+ max_values=1,
+ )
+
+ async def backend_callback(select_interaction: discord.Interaction):
+ self.selected_backend = backend_select.values[0]
+ await select_interaction.response.defer()
+
+ backend_select.callback = backend_callback
+ self.add_item(backend_select)
+ next_button = discord.ui.Button(label="Next", style=discord.ButtonStyle.primary)
+ next_button.callback = self._on_next
+ self.add_item(next_button)
+ return
+
+ if self.step == "opencode":
+ agent_options = [discord.SelectOption(label="Default", value="__default__")]
+ agent_options += [
+ discord.SelectOption(label=a, value=a, default=a == self.oc_agent) for a in opencode_agents
+ ]
+ model_options = [discord.SelectOption(label="Default", value="__default__")]
+ model_ids = []
+ for provider in opencode_models.get("providers", []):
+ provider_id = provider.get("id") or provider.get("name") or provider.get("provider_id")
+ if not provider_id:
+ continue
+ models = provider.get("models", {})
+ if isinstance(models, dict):
+ model_ids.extend([f"{provider_id}/{mid}" for mid in models.keys()])
+ model_options += [
+ discord.SelectOption(label=m, value=m, default=m == self.oc_model) for m in model_ids
+ ]
+ reasoning_options = [
+ discord.SelectOption(label="Default", value="__default__"),
+ discord.SelectOption(label="low", value="low", default=self.oc_reasoning == "low"),
+ discord.SelectOption(label="medium", value="medium", default=self.oc_reasoning == "medium"),
+ discord.SelectOption(label="high", value="high", default=self.oc_reasoning == "high"),
+ discord.SelectOption(label="xhigh", value="xhigh", default=self.oc_reasoning == "xhigh"),
+ ]
+
+ agent_select = discord.ui.Select(
+ placeholder="OpenCode agent", options=agent_options, min_values=1, max_values=1
+ )
+ model_select = discord.ui.Select(
+ placeholder="OpenCode model", options=model_options, min_values=1, max_values=1
+ )
+ reasoning_select = discord.ui.Select(
+ placeholder="Reasoning effort", options=reasoning_options, min_values=1, max_values=1
+ )
+
+ async def agent_callback(select_interaction: discord.Interaction):
+ self.oc_agent = agent_select.values[0]
+ await select_interaction.response.defer()
+
+ async def model_callback(select_interaction: discord.Interaction):
+ self.oc_model = model_select.values[0]
+ await select_interaction.response.defer()
+
+ async def reasoning_callback(select_interaction: discord.Interaction):
+ self.oc_reasoning = reasoning_select.values[0]
+ await select_interaction.response.defer()
+
+ agent_select.callback = agent_callback
+ model_select.callback = model_callback
+ reasoning_select.callback = reasoning_callback
+ self.add_item(agent_select)
+ self.add_item(model_select)
+ self.add_item(reasoning_select)
+ back_button = discord.ui.Button(label="Back", style=discord.ButtonStyle.secondary)
+ back_button.callback = self._on_back
+ save_button = discord.ui.Button(label="Save", style=discord.ButtonStyle.primary)
+ save_button.callback = self._on_save
+ self.add_item(back_button)
+ self.add_item(save_button)
+ return
+
+ if self.step == "claude":
+ agent_options = [discord.SelectOption(label="Default", value="__default__")]
+ agent_options += [
+ discord.SelectOption(label=a, value=a, default=a == self.claude_agent) for a in claude_agents
+ ]
+ model_options = [discord.SelectOption(label="Default", value="__default__")]
+ model_options += [
+ discord.SelectOption(label=m, value=m, default=m == self.claude_model) for m in claude_models
+ ]
+
+ agent_select = discord.ui.Select(
+ placeholder="Claude agent", options=agent_options, min_values=1, max_values=1
+ )
+ model_select = discord.ui.Select(
+ placeholder="Claude model", options=model_options, min_values=1, max_values=1
+ )
+
+ async def agent_callback(select_interaction: discord.Interaction):
+ self.claude_agent = agent_select.values[0]
+ await select_interaction.response.defer()
+
+ async def model_callback(select_interaction: discord.Interaction):
+ self.claude_model = model_select.values[0]
+ await select_interaction.response.defer()
+
+ agent_select.callback = agent_callback
+ model_select.callback = model_callback
+ self.add_item(agent_select)
+ self.add_item(model_select)
+ back_button = discord.ui.Button(label="Back", style=discord.ButtonStyle.secondary)
+ back_button.callback = self._on_back
+ save_button = discord.ui.Button(label="Save", style=discord.ButtonStyle.primary)
+ save_button.callback = self._on_save
+ self.add_item(back_button)
+ self.add_item(save_button)
+ return
+
+ if self.step == "codex":
+ model_options = [discord.SelectOption(label="Default", value="__default__")]
+ model_options += [
+ discord.SelectOption(label=m, value=m, default=m == self.codex_model) for m in codex_models
+ ]
+ reasoning_options = [
+ discord.SelectOption(label="Default", value="__default__"),
+ discord.SelectOption(
+ label="minimal", value="minimal", default=self.codex_reasoning == "minimal"
+ ),
+ discord.SelectOption(label="low", value="low", default=self.codex_reasoning == "low"),
+ discord.SelectOption(label="medium", value="medium", default=self.codex_reasoning == "medium"),
+ discord.SelectOption(label="high", value="high", default=self.codex_reasoning == "high"),
+ discord.SelectOption(label="xhigh", value="xhigh", default=self.codex_reasoning == "xhigh"),
+ ]
+ model_select = discord.ui.Select(
+ placeholder="Codex model", options=model_options, min_values=1, max_values=1
+ )
+ reasoning_select = discord.ui.Select(
+ placeholder="Reasoning effort", options=reasoning_options, min_values=1, max_values=1
+ )
+
+ async def model_callback(select_interaction: discord.Interaction):
+ self.codex_model = model_select.values[0]
+ await select_interaction.response.defer()
+
+ async def reasoning_callback(select_interaction: discord.Interaction):
+ self.codex_reasoning = reasoning_select.values[0]
+ await select_interaction.response.defer()
+
+ model_select.callback = model_callback
+ reasoning_select.callback = reasoning_callback
+ self.add_item(model_select)
+ self.add_item(reasoning_select)
+ back_button = discord.ui.Button(label="Back", style=discord.ButtonStyle.secondary)
+ back_button.callback = self._on_back
+ save_button = discord.ui.Button(label="Save", style=discord.ButtonStyle.primary)
+ save_button.callback = self._on_save
+ self.add_item(back_button)
+ self.add_item(save_button)
+ return
+
+ async def _on_next(self, interaction: discord.Interaction):
+ backend = self.selected_backend
+ self.step = backend
+ self._render()
+ await interaction.response.edit_message(content="🤖 Agent routing", view=self)
+
+ async def _on_back(self, interaction: discord.Interaction):
+ self.step = "backend"
+ self._render()
+ await interaction.response.edit_message(content="🤖 Agent routing", view=self)
+
+ async def _on_save(self, interaction: discord.Interaction):
+ def _normalize(value: Optional[str]) -> Optional[str]:
+ if value in (None, "__default__"):
+ return None
+ return value
+
+ if hasattr(self.outer, "_on_routing_update"):
+ await self.outer._on_routing_update(
+ str(interaction.user.id),
+ channel_id,
+ self.selected_backend,
+ _normalize(self.oc_agent),
+ _normalize(self.oc_model),
+ _normalize(self.oc_reasoning),
+ _normalize(self.claude_agent),
+ _normalize(self.claude_model),
+ _normalize(self.codex_model),
+ _normalize(self.codex_reasoning),
+ )
+ await interaction.response.edit_message(content="✅ Routing updated.", view=None)
+
+ view = RoutingView(self)
+
+ if interaction:
+ await interaction.response.send_message("🤖 Agent routing", view=view, ephemeral=True)
+ else:
+ channel = await self._fetch_channel(channel_id)
+ if channel is None:
+ raise RuntimeError("Discord channel not found")
+ await channel.send("🤖 Agent routing", view=view)
+
+ async def open_question_modal(
+ self,
+ trigger_id: Any,
+ context: MessageContext,
+ pending: Any,
+ callback_prefix: str = "opencode_question",
+ ):
+ interaction = trigger_id if isinstance(trigger_id, discord.Interaction) else None
+ questions = getattr(pending, "questions", None) or []
+ if not questions or len(questions) > 4:
+ await self.send_message(
+ context,
+ "Too many questions for Discord UI. Please reply with a custom message.",
+ )
+ return
+
+ class QuestionView(discord.ui.View):
+ def __init__(self, outer: DiscordBot):
+ super().__init__(timeout=900)
+ self.outer = outer
+ self.answers: list[list[str]] = [[] for _ in questions]
+ for idx, q in enumerate(questions):
+ options = [discord.SelectOption(label=o.label, value=o.label) for o in q.options]
+ max_values = len(options) if getattr(q, "multiple", False) else 1
+ select = discord.ui.Select(
+ placeholder=q.header or f"Question {idx + 1}",
+ options=options,
+ min_values=1,
+ max_values=max_values,
+ )
+
+ async def make_callback(select_interaction: discord.Interaction, i=idx, sel=select):
+ self.answers[i] = list(sel.values)
+ await select_interaction.response.defer()
+
+ select.callback = make_callback
+ self.add_item(select)
+ self.add_item(discord.ui.Button(label="Submit", style=discord.ButtonStyle.primary))
+
+ view = QuestionView(self)
+
+ async def submit_callback(submit_interaction: discord.Interaction):
+ payload = {"answers": view.answers}
+ if self.on_callback_query_callback:
+ callback_data = f"{callback_prefix}:modal:" + json.dumps(payload)
+ ctx = MessageContext(
+ user_id=str(submit_interaction.user.id),
+ channel_id=context.channel_id,
+ thread_id=context.thread_id,
+ message_id=context.message_id,
+ platform_specific={"interaction": submit_interaction},
+ )
+ await self.on_callback_query_callback(ctx, callback_data)
+ await submit_interaction.response.edit_message(content="✅ Answer submitted.", view=None)
+
+ for item in view.children:
+ if isinstance(item, discord.ui.Button) and item.label == "Submit":
+ item.callback = submit_callback
+
+ if interaction:
+ await interaction.response.send_message("Please answer:", view=view, ephemeral=True)
+ else:
+ channel = await self._fetch_channel(context.thread_id or context.channel_id)
+ if channel is None:
+ raise RuntimeError("Discord channel not found")
+ await channel.send("Please answer:", view=view)
+
+
+class _DiscordButtonView(discord.ui.View):
+ def __init__(self, outer: DiscordBot, base_context: MessageContext, keyboard: InlineKeyboard):
+ super().__init__(timeout=900)
+ self.outer = outer
+ self.base_context = base_context
+ for row_idx, row in enumerate(keyboard.buttons):
+ for button in row:
+ item = discord.ui.Button(
+ label=button.text,
+ style=discord.ButtonStyle.secondary,
+ custom_id=button.callback_data,
+ row=row_idx,
+ )
+
+ async def on_click(interaction: discord.Interaction, data=button.callback_data):
+ try:
+ await interaction.response.defer(ephemeral=True)
+ except Exception:
+ pass
+ channel_id, thread_id = self.outer._extract_context_ids(interaction.channel)
+ context = MessageContext(
+ user_id=str(interaction.user.id),
+ channel_id=channel_id,
+ thread_id=thread_id,
+ message_id=str(interaction.message.id) if interaction.message else None,
+ platform_specific={"interaction": interaction},
+ )
+ if self.outer.on_callback_query_callback:
+ await self.outer.on_callback_query_callback(context, data)
+
+ item.callback = on_click
+ self.add_item(item)
diff --git a/modules/im/factory.py b/modules/im/factory.py
index 5c4faa3f6..729b4ddb8 100644
--- a/modules/im/factory.py
+++ b/modules/im/factory.py
@@ -14,28 +14,37 @@ logger = logging.getLogger(__name__)
class IMFactory:
"""Factory class to create the appropriate IM client based on platform"""
-
+
@staticmethod
def create_client(config) -> BaseIMClient:
"""Create and return the appropriate IM client based on configuration
-
+
Args:
config: Application configuration
-
+
Returns:
Instance of platform-specific IM client
-
+
Raises:
ValueError: If platform is not supported
"""
# Dynamic imports to avoid circular dependency
from .slack import SlackBot
+ from .discord import DiscordBot
+
+ platform = getattr(config, "platform", "slack")
+ if platform == "slack":
+ if not config.slack:
+ raise ValueError("Slack configuration not found")
+ logger.info("Creating Slack client")
+ return SlackBot(config.slack)
+ if platform == "discord":
+ if not config.discord:
+ raise ValueError("Discord configuration not found")
+ logger.info("Creating Discord client")
+ return DiscordBot(config.discord)
+ raise ValueError(f"Unsupported platform: {platform}")
- if not config.slack:
- raise ValueError("Slack configuration not found")
- logger.info("Creating Slack client")
- return SlackBot(config.slack)
-
@staticmethod
def get_supported_platforms() -> list[str]:
"""Get list of supported platforms
@@ -43,18 +52,27 @@ class IMFactory:
Returns:
List of supported platform names
"""
- return ["slack"]
-
+ return ["slack", "discord"]
+
@staticmethod
def validate_platform_config(config) -> None:
"""Validate platform configuration before creating client
-
+
Args:
config: Application configuration
-
+
Raises:
ValueError: If configuration is invalid
"""
- if config.slack is None:
- raise ValueError("Missing configuration for platform: slack")
- config.slack.validate()
+ platform = getattr(config, "platform", "slack")
+ if platform == "slack":
+ if config.slack is None:
+ raise ValueError("Missing configuration for platform: slack")
+ config.slack.validate()
+ return
+ if platform == "discord":
+ if config.discord is None:
+ raise ValueError("Missing configuration for platform: discord")
+ config.discord.validate()
+ return
+ raise ValueError(f"Unsupported platform: {platform}")
diff --git a/modules/im/formatters/__init__.py b/modules/im/formatters/__init__.py
index da4bea291..17dbed2e2 100644
--- a/modules/im/formatters/__init__.py
+++ b/modules/im/formatters/__init__.py
@@ -1,4 +1,5 @@
from .base_formatter import BaseMarkdownFormatter
from .slack_formatter import SlackFormatter
+from .discord_formatter import DiscordFormatter
-__all__ = ['BaseMarkdownFormatter', 'SlackFormatter']
+__all__ = ["BaseMarkdownFormatter", "SlackFormatter", "DiscordFormatter"]
diff --git a/modules/im/formatters/discord_formatter.py b/modules/im/formatters/discord_formatter.py
new file mode 100644
index 000000000..8584dc052
--- /dev/null
+++ b/modules/im/formatters/discord_formatter.py
@@ -0,0 +1,32 @@
+from .base_formatter import BaseMarkdownFormatter
+
+
+class DiscordFormatter(BaseMarkdownFormatter):
+ """Discord markdown formatter.
+
+ Discord supports standard Markdown with a few extensions.
+ Reference: https://support.discord.com/hc/en-us/articles/210298617
+ """
+
+ def format_bold(self, text: str) -> str:
+ return f"**{text}**"
+
+ def format_italic(self, text: str) -> str:
+ return f"*{text}*"
+
+ def format_strikethrough(self, text: str) -> str:
+ return f"~~{text}~~"
+
+ def format_link(self, text: str, url: str) -> str:
+ return f"[{text}]({url})"
+
+ def escape_special_chars(self, text: str) -> str:
+ # Escape basic markdown characters to avoid unintended formatting.
+ for ch in ("\\", "*", "_", "~", "`", "|"):
+ text = text.replace(ch, f"\\{ch}")
+ return text
+
+ def format_code_block(self, code: str, language: str = "") -> str:
+ if language:
+ return f"```{language}\n{code}\n```"
+ return f"```\n{code}\n```"
diff --git a/pyproject.toml b/pyproject.toml
index ef9cd7d32..91bc09039 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -30,6 +30,7 @@ dependencies = [
"claude-agent-sdk>=0.1.23",
"anyio>=4.0.0",
"slack-sdk>=3.26.0",
+ "discord.py>=2.4.0",
"aiohttp>=3.8.0",
"markdown_to_mrkdwn>=0.2.0",
"typing_extensions>=4.12.2",
diff --git a/ui/src/App.tsx b/ui/src/App.tsx
index cb5f12212..4dd36dee0 100644
--- a/ui/src/App.tsx
+++ b/ui/src/App.tsx
@@ -18,9 +18,11 @@ const AuthGuard = ({ children }: { children: any }) => {
useEffect(() => {
getConfig().then(config => {
- // Check if minimal config exists
- // If no mode or no slack bot_token, setup is needed
- if (!config || !config.mode || !config.slack?.bot_token) {
+ const platform = config?.platform || 'slack';
+ const hasToken = platform === 'discord'
+ ? !!config?.discord?.bot_token
+ : !!config?.slack?.bot_token;
+ if (!config || !config.mode || !hasToken) {
setNeedsSetup(true);
}
setLoading(false);
diff --git a/ui/src/components/Dashboard.tsx b/ui/src/components/Dashboard.tsx
index 1a218c3a1..e4c6d5840 100644
--- a/ui/src/components/Dashboard.tsx
+++ b/ui/src/components/Dashboard.tsx
@@ -138,7 +138,7 @@ export const Dashboard: React.FC = () => {
return () => window.clearTimeout(timer);
}, [diagnosticsMessage]);
- const showWorkspaceGateway = config.mode !== 'self_host';
+ const showWorkspaceGateway = config.mode !== 'self_host' && (config.platform || 'slack') === 'slack';
return (
<div className="max-w-5xl mx-auto space-y-8">
@@ -233,15 +233,19 @@ export const Dashboard: React.FC = () => {
<h3 className="font-semibold flex items-center gap-2 text-text"><Settings size={18} /> {t('dashboard.globalPolicy')}</h3>
<Link to="/setup" className="text-sm text-accent hover:underline font-medium">{t('common.editSetup')}</Link>
</div>
- <div className="space-y-3 text-sm">
- <div className="flex justify-between items-center">
- <span className="text-muted">{t('dashboard.mode')}</span>
- <span className="font-mono text-xs text-text capitalize">{config.mode || '-'}</span>
- </div>
- <div className="flex justify-between items-center">
- <span className="text-muted">{t('dashboard.defaultBackend')}</span>
- <span className="font-mono text-xs text-text">{config.agents?.default_backend || 'opencode'}</span>
- </div>
+ <div className="space-y-3 text-sm">
+ <div className="flex justify-between items-center">
+ <span className="text-muted">{t('dashboard.mode')}</span>
+ <span className="font-mono text-xs text-text capitalize">{config.mode || '-'}</span>
+ </div>
+ <div className="flex justify-between items-center">
+ <span className="text-muted">{t('dashboard.platform')}</span>
+ <span className="font-mono text-xs text-text capitalize">{config.platform || 'slack'}</span>
+ </div>
+ <div className="flex justify-between items-center">
+ <span className="text-muted">{t('dashboard.defaultBackend')}</span>
+ <span className="font-mono text-xs text-text">{config.agents?.default_backend || 'opencode'}</span>
+ </div>
{showWorkspaceGateway && (
<div className="flex justify-between items-center">
<span className="text-muted">{t('dashboard.slackWorkspace')}</span>
@@ -272,27 +276,41 @@ export const Dashboard: React.FC = () => {
</span>
</span>
</span>
- <button
- onClick={() => {
- setSettingsMessage(null);
- const newConfig = {
- ...config,
- slack: {
- ...(config.slack || {}),
- require_mention: !config.slack?.require_mention,
- },
- };
- setConfig(newConfig);
- autoSaveMessageConfig(newConfig);
- }}
- className={`px-2 py-1 rounded text-xs font-semibold border ${
- config.slack?.require_mention
- ? 'bg-success/10 text-success border-success/20'
- : 'bg-neutral-100 text-muted border-border'
- }`}
- >
- {config.slack?.require_mention ? t('common.enabled') : t('common.disabled')}
- </button>
+ <button
+ onClick={() => {
+ setSettingsMessage(null);
+ const platform = config.platform || 'slack';
+ const toggleValue = platform === 'discord'
+ ? !config.discord?.require_mention
+ : !config.slack?.require_mention;
+ const newConfig = {
+ ...config,
+ discord: {
+ ...(config.discord || {}),
+ require_mention: platform === 'discord' ? toggleValue : config.discord?.require_mention,
+ },
+ slack: {
+ ...(config.slack || {}),
+ require_mention: platform === 'slack' ? toggleValue : config.slack?.require_mention,
+ },
+ };
+ setConfig(newConfig);
+ autoSaveMessageConfig(newConfig);
+ }}
+ className={`px-2 py-1 rounded text-xs font-semibold border ${
+ (config.platform === 'discord'
+ ? config.discord?.require_mention
+ : config.slack?.require_mention)
+ ? 'bg-success/10 text-success border-success/20'
+ : 'bg-neutral-100 text-muted border-border'
+ }`}
+ >
+ {(config.platform === 'discord'
+ ? config.discord?.require_mention
+ : config.slack?.require_mention)
+ ? t('common.enabled')
+ : t('common.disabled')}
+ </button>
</div>
<div className="flex justify-between items-center">
diff --git a/ui/src/components/Wizard.tsx b/ui/src/components/Wizard.tsx
index ace9b0df4..8c5812ba3 100644
--- a/ui/src/components/Wizard.tsx
+++ b/ui/src/components/Wizard.tsx
@@ -3,8 +3,10 @@ import { motion, AnimatePresence } from 'framer-motion';
import { useTranslation } from 'react-i18next';
import { Welcome } from './steps/Welcome';
import { ModeSelection } from './steps/ModeSelection';
+import { PlatformSelection } from './steps/PlatformSelection';
import { AgentDetection } from './steps/AgentDetection';
import { SlackConfig } from './steps/SlackConfig';
+import { DiscordConfig } from './steps/DiscordConfig';
import { ChannelList } from './steps/ChannelList';
import { Summary } from './steps/Summary';
import { useApi } from '../context/ApiContext';
@@ -12,6 +14,7 @@ import { LanguageSwitcher } from './LanguageSwitcher';
import clsx from 'clsx';
const buildConfigPayload = (data: any) => ({
+ platform: data.platform || 'slack',
mode: data.mode || 'self_host',
version: 'v2',
slack: {
@@ -22,6 +25,13 @@ const buildConfigPayload = (data: any) => ({
app_token: data.slack?.app_token || '',
require_mention: data.slack?.require_mention || false,
},
+ discord: {
+ ...data.discord,
+ bot_token: data.discord?.bot_token || '',
+ guild_allowlist: data.discord?.guild_allowlist || [],
+ guild_denylist: data.discord?.guild_denylist || [],
+ require_mention: data.discord?.require_mention || false,
+ },
runtime: {
// Preserve existing runtime config
...data.runtime,
@@ -69,15 +79,6 @@ const buildConfigPayload = (data: any) => ({
language: data.language,
});
-const steps = [
- { id: 'welcome', title: 'Welcome', component: Welcome },
- { id: 'mode', title: 'Mode', component: ModeSelection },
- { id: 'agents', title: 'Agents', component: AgentDetection },
- { id: 'slack', title: 'Slack', component: SlackConfig },
- { id: 'channels', title: 'Channels', component: ChannelList },
- { id: 'summary', title: 'Finish', component: Summary },
-];
-
export const Wizard: React.FC = () => {
const { t } = useTranslation();
const api = useApi();
@@ -85,6 +86,21 @@ export const Wizard: React.FC = () => {
const [data, setData] = useState<any>({});
const [loaded, setLoaded] = useState(false);
+ const steps = React.useMemo(() => {
+ const platform = data.platform || 'slack';
+ return [
+ { id: 'welcome', title: 'Welcome', component: Welcome },
+ { id: 'mode', title: 'Mode', component: ModeSelection },
+ { id: 'platform', title: 'Platform', component: PlatformSelection },
+ { id: 'agents', title: 'Agents', component: AgentDetection },
+ platform === 'discord'
+ ? { id: 'discord', title: 'Discord', component: DiscordConfig }
+ : { id: 'slack', title: 'Slack', component: SlackConfig },
+ { id: 'channels', title: 'Channels', component: ChannelList },
+ { id: 'summary', title: 'Finish', component: Summary },
+ ];
+ }, [data.platform]);
+
useEffect(() => {
const bootstrap = async () => {
try {
@@ -127,7 +143,7 @@ export const Wizard: React.FC = () => {
const persistStep = async (payload: any) => {
if (!payload) return;
- if (payload.agents || payload.slack || payload.mode || payload.channelConfigs) {
+ if (payload.agents || payload.slack || payload.discord || payload.mode || payload.platform || payload.channelConfigs) {
await api.saveConfig(buildConfigPayload(payload));
}
if (payload.channelConfigs) {
diff --git a/ui/src/components/steps/ChannelList.tsx b/ui/src/components/steps/ChannelList.tsx
index 75e06032f..b1ee64870 100644
--- a/ui/src/components/steps/ChannelList.tsx
+++ b/ui/src/components/steps/ChannelList.tsx
@@ -61,6 +61,8 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
const [claudeModels, setClaudeModels] = useState<string[]>([]);
const [codexModels, setCodexModels] = useState<string[]>([]);
const [selectedModels, setSelectedModels] = useState<Record<string, string>>({});
+ const [guilds, setGuilds] = useState<any[]>([]);
+ const [selectedGuild, setSelectedGuild] = useState<string>(data.discord?.guild_allowlist?.[0] || '');
useEffect(() => {
if (!isPage) {
@@ -68,6 +70,12 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
}
}, [data.channelConfigs, isPage]);
+ useEffect(() => {
+ if (!isPage) {
+ setSelectedGuild(data.discord?.guild_allowlist?.[0] || '');
+ }
+ }, [data.discord?.guild_allowlist, isPage]);
+
useEffect(() => {
if (isPage) {
api.getConfig().then(c => {
@@ -79,15 +87,42 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
}
}, [isPage]);
- const botToken = config.slack?.bot_token || config.slackBotToken || '';
+ const platform = config.platform || data.platform || 'slack';
+ const botToken = platform === 'discord'
+ ? (config.discord?.bot_token || data.discord?.bot_token || '')
+ : (config.slack?.bot_token || config.slackBotToken || '');
+
+ const loadGuilds = async () => {
+ if (!botToken) return;
+ try {
+ const result = await api.discordGuilds(botToken);
+ if (result.ok) {
+ setGuilds(result.guilds || []);
+ }
+ } catch (e) {
+ console.error('Failed to load guilds:', e);
+ }
+ };
const loadChannels = async () => {
if (!botToken) return;
setLoading(true);
try {
- const result = await api.slackChannels(botToken);
- if (result.ok) {
- setChannels(result.channels || []);
+ if (platform === 'discord') {
+ if (!selectedGuild) {
+ setLoading(false);
+ return;
+ }
+ const result = await api.discordChannels(botToken, selectedGuild);
+ if (result.ok) {
+ const filtered = (result.channels || []).filter((c: any) => c.type === 0 || c.type === 5);
+ setChannels(filtered);
+ }
+ } else {
+ const result = await api.slackChannels(botToken);
+ if (result.ok) {
+ setChannels(result.channels || []);
+ }
}
} catch (e) {
console.error('Failed to load channels:', e);
@@ -141,10 +176,16 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
};
useEffect(() => {
- if (botToken) {
+ if (!botToken) return;
+ if (platform === 'discord') {
+ loadGuilds();
+ if (selectedGuild) {
+ loadChannels();
+ }
+ } else {
loadChannels();
}
- }, [botToken]);
+ }, [botToken, platform, selectedGuild]);
useEffect(() => {
if (config.agents?.claude?.enabled) {
@@ -301,7 +342,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
{t('channelList.cantFindChannel')}
</span>
<span className="absolute bottom-full left-0 mb-2 px-3 py-2 bg-text text-bg text-xs rounded shadow-lg opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-10 w-64 whitespace-normal">
- {t('channelList.inviteBotHint')}
+ {platform === 'discord' ? t('channelList.discordInviteBotHint') : t('channelList.inviteBotHint')}
</span>
</span>
{channels.length === 0 && !loading && (
@@ -310,6 +351,21 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
</div>
<span className="text-sm text-muted font-mono">{t('channelList.enabledCount', { count: selectedCount })}</span>
</div>
+ {platform === 'discord' && (
+ <div className="flex flex-wrap items-center gap-3 text-sm">
+ <label className="text-muted">{t('channelList.guild')}</label>
+ <select
+ value={selectedGuild}
+ onChange={(e) => setSelectedGuild(e.target.value)}
+ className="bg-bg border border-border rounded px-3 py-2 text-sm focus:outline-none focus:border-accent text-text"
+ >
+ <option value="">{t('channelList.guildPlaceholder')}</option>
+ {guilds.map((g) => (
+ <option key={g.id} value={g.id}>{g.name}</option>
+ ))}
+ </select>
+ </div>
+ )}
{isPage && (
<div className="flex flex-wrap items-center gap-3 text-sm">
<span className="text-muted">{t('channelList.accessPolicy')}</span>
@@ -364,12 +420,16 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
<span
className={clsx(
'text-xs px-2 py-0.5 rounded-full border',
- channel.is_private
- ? 'bg-warning/10 text-warning border-warning/20'
- : 'bg-success/10 text-success border-success/20'
+ platform === 'discord'
+ ? 'bg-neutral-100 text-text border-border'
+ : channel.is_private
+ ? 'bg-warning/10 text-warning border-warning/20'
+ : 'bg-success/10 text-success border-success/20'
)}
>
- {channel.is_private ? t('common.private') : t('common.public')}
+ {platform === 'discord'
+ ? (channel.type === 5 ? t('channelList.discordNews') : t('channelList.discordText'))
+ : channel.is_private ? t('common.private') : t('common.public')}
</span>
</div>
@@ -415,7 +475,11 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
}}
className="w-full bg-bg border border-border rounded px-3 py-2 text-sm focus:outline-none focus:border-accent text-text"
>
- <option value="">{t('common.default')} ({config.slack?.require_mention ? t('common.enabled') : t('common.disabled')})</option>
+ <option value="">
+ {t('common.default')} ({platform === 'discord'
+ ? (config.discord?.require_mention ? t('common.enabled') : t('common.disabled'))
+ : (config.slack?.require_mention ? t('common.enabled') : t('common.disabled'))})
+ </option>
<option value="true">{t('channelList.requireMentionOn')}</option>
<option value="false">{t('channelList.requireMentionOff')}</option>
</select>
@@ -660,7 +724,10 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
{t('common.back')}
</button>
<button
- onClick={() => onNext && onNext({ channelConfigs: configs })}
+ onClick={() => onNext && onNext({
+ channelConfigs: configs,
+ ...(platform === 'discord' ? { discord: { ...config.discord, guild_allowlist: selectedGuild ? [selectedGuild] : [] } } : {}),
+ })}
className="px-6 py-2 bg-accent hover:bg-accent/90 text-white rounded-lg font-medium shadow-sm"
>
{t('common.continue')}
diff --git a/ui/src/components/steps/DiscordConfig.tsx b/ui/src/components/steps/DiscordConfig.tsx
new file mode 100644
index 000000000..114f2176a
--- /dev/null
+++ b/ui/src/components/steps/DiscordConfig.tsx
@@ -0,0 +1,148 @@
+import React, { useEffect, useMemo, useState } from 'react';
+import { Shield, RefreshCw, Check, Server, KeyRound } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import clsx from 'clsx';
+import { useApi } from '../../context/ApiContext';
+
+interface DiscordConfigProps {
+ data: any;
+ onNext: (data: any) => void;
+ onBack: () => void;
+}
+
+export const DiscordConfig: React.FC<DiscordConfigProps> = ({ data, onNext, onBack }) => {
+ const { t } = useTranslation();
+ const api = useApi();
+ const [botToken, setBotToken] = useState(data.discord?.bot_token || '');
+ const [checking, setChecking] = useState(false);
+ const [authResult, setAuthResult] = useState<any>(null);
+ const [guilds, setGuilds] = useState<any[]>([]);
+ const [selectedGuild, setSelectedGuild] = useState<string>(data.discord?.guild_allowlist?.[0] || '');
+
+ const isValid = useMemo(() => botToken.length > 0 && authResult?.ok, [botToken, authResult]);
+
+ const runAuthTest = async () => {
+ setChecking(true);
+ try {
+ const result = await api.discordAuthTest(botToken);
+ setAuthResult(result);
+ } catch (err: any) {
+ setAuthResult({ ok: false, error: err?.message || 'Request failed' });
+ } finally {
+ setChecking(false);
+ }
+ };
+
+ const loadGuilds = async () => {
+ if (!botToken) return;
+ try {
+ const result = await api.discordGuilds(botToken);
+ if (result.ok) {
+ setGuilds(result.guilds || []);
+ }
+ } catch {
+ // ignore
+ }
+ };
+
+ useEffect(() => {
+ if (authResult?.ok) {
+ loadGuilds();
+ }
+ }, [authResult?.ok]);
+
+ return (
+ <div className="flex flex-col h-full max-w-2xl mx-auto">
+ <div className="mb-4">
+ <h2 className="text-3xl font-display font-bold text-text">{t('discordConfig.title')}</h2>
+ <p className="text-muted mt-1">{t('discordConfig.subtitle')}</p>
+ </div>
+
+ <div className="space-y-6 flex-1">
+ <div className="space-y-2">
+ <label className="text-sm font-medium text-text flex items-center gap-2">
+ <KeyRound size={16} className="text-accent" /> {t('discordConfig.botToken')}
+ </label>
+ <input
+ type="password"
+ value={botToken}
+ onChange={(e) => setBotToken(e.target.value)}
+ placeholder={t('discordConfig.botTokenPlaceholder')}
+ className="w-full bg-bg border border-border rounded-lg p-3 text-text focus:outline-none focus:border-accent focus:ring-1 focus:ring-accent font-mono transition-colors"
+ />
+ <p className="text-xs text-muted">{t('discordConfig.botTokenHint')}</p>
+ </div>
+
+ <div className="flex items-center gap-3">
+ <button
+ onClick={runAuthTest}
+ disabled={!botToken || checking}
+ className="px-4 py-2 bg-accent text-white rounded-lg flex items-center gap-2 transition-colors font-medium shadow-sm hover:bg-accent/90 disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ {checking ? <RefreshCw size={16} className="animate-spin" /> : <Shield size={16} />}
+ {t('discordConfig.validateToken')}
+ </button>
+ {authResult && (
+ <span
+ className={clsx(
+ 'flex items-center gap-2 text-sm font-medium px-3 py-1.5 rounded-lg border',
+ authResult.ok ? 'text-success bg-success/10 border-success/20' : 'text-danger bg-danger/10 border-danger/20'
+ )}
+ >
+ {authResult.ok ? (
+ <>
+ <Check size={14} />
+ <span>{t('discordConfig.tokenValidated')}</span>
+ </>
+ ) : (
+ <span>{t('discordConfig.authFailed')}: {authResult.error}</span>
+ )}
+ </span>
+ )}
+ </div>
+
+ {authResult?.ok && (
+ <div className="space-y-2">
+ <label className="text-sm font-medium text-text flex items-center gap-2">
+ <Server size={16} className="text-accent" /> {t('discordConfig.guild')}
+ </label>
+ <select
+ value={selectedGuild}
+ onChange={(e) => setSelectedGuild(e.target.value)}
+ className="w-full bg-bg border border-border rounded-lg p-3 text-text focus:outline-none focus:border-accent focus:ring-1 focus:ring-accent"
+ >
+ <option value="">{t('discordConfig.guildPlaceholder')}</option>
+ {guilds.map((g) => (
+ <option key={g.id} value={g.id}>{g.name}</option>
+ ))}
+ </select>
+ <p className="text-xs text-muted">{t('discordConfig.guildHint')}</p>
+ </div>
+ )}
+ </div>
+
+ <div className="mt-auto flex justify-between pt-6 border-t border-border">
+ <button onClick={onBack} className="px-6 py-2 text-muted hover:text-text font-medium transition-colors">
+ {t('common.back')}
+ </button>
+ <button
+ onClick={() => onNext({
+ platform: 'discord',
+ discord: {
+ ...(data.discord || {}),
+ bot_token: botToken,
+ guild_allowlist: selectedGuild ? [selectedGuild] : [],
+ },
+ })}
+ disabled={!isValid}
+ className={clsx(
+ 'px-8 py-3 rounded-lg font-medium transition-colors shadow-sm',
+ isValid ? 'bg-accent hover:bg-accent/90 text-white' : 'bg-neutral-200 text-muted cursor-not-allowed'
+ )}
+ >
+ {t('common.continue')}
+ </button>
+ </div>
+ </div>
+ );
+};
diff --git a/ui/src/components/steps/PlatformSelection.tsx b/ui/src/components/steps/PlatformSelection.tsx
new file mode 100644
index 000000000..81b11e09d
--- /dev/null
+++ b/ui/src/components/steps/PlatformSelection.tsx
@@ -0,0 +1,53 @@
+import React from 'react';
+import { useTranslation } from 'react-i18next';
+import clsx from 'clsx';
+
+interface PlatformSelectionProps {
+ data: any;
+ onNext: (data: any) => void;
+ onBack: () => void;
+}
+
+export const PlatformSelection: React.FC<PlatformSelectionProps> = ({ data, onNext, onBack }) => {
+ const { t } = useTranslation();
+ const platform = data.platform || 'slack';
+
+ return (
+ <div className="flex flex-col h-full max-w-2xl mx-auto">
+ <div className="mb-6">
+ <h2 className="text-3xl font-display font-bold text-text">{t('platform.title')}</h2>
+ <p className="text-muted mt-1">{t('platform.subtitle')}</p>
+ </div>
+
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4 flex-1">
+ {['slack', 'discord'].map((option) => (
+ <button
+ key={option}
+ onClick={() => onNext({ platform: option })}
+ className={clsx(
+ 'text-left p-5 rounded-xl border transition-colors shadow-sm',
+ platform === option
+ ? 'border-accent bg-accent/5'
+ : 'border-border bg-panel hover:border-accent/60'
+ )}
+ >
+ <div className="text-lg font-semibold text-text">{t(`platform.${option}.title`)}</div>
+ <div className="text-sm text-muted mt-2">{t(`platform.${option}.desc`)}</div>
+ </button>
+ ))}
+ </div>
+
+ <div className="mt-auto flex justify-between pt-6 border-t border-border">
+ <button onClick={onBack} className="px-6 py-2 text-muted hover:text-text font-medium transition-colors">
+ {t('common.back')}
+ </button>
+ <button
+ onClick={() => onNext({ platform })}
+ className="px-8 py-3 rounded-lg font-medium transition-colors shadow-sm bg-accent hover:bg-accent/90 text-white"
+ >
+ {t('common.continue')}
+ </button>
+ </div>
+ </div>
+ );
+};
diff --git a/ui/src/components/steps/Summary.tsx b/ui/src/components/steps/Summary.tsx
index 27623ad2a..c92de2a02 100644
--- a/ui/src/components/steps/Summary.tsx
+++ b/ui/src/components/steps/Summary.tsx
@@ -19,7 +19,10 @@ export const Summary: React.FC<SummaryProps> = ({ data, onBack }) => {
const { control } = useStatus();
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
- const [requireMention, setRequireMention] = useState(data.slack?.require_mention || false);
+ const platform = data.platform || 'slack';
+ const [requireMention, setRequireMention] = useState(
+ platform === 'discord' ? (data.discord?.require_mention || false) : (data.slack?.require_mention || false)
+ );
const [autoUpdate, setAutoUpdate] = useState(data.update?.auto_update ?? true);
const navigate = useNavigate();
@@ -33,6 +36,10 @@ export const Summary: React.FC<SummaryProps> = ({ data, onBack }) => {
...data.slack,
require_mention: requireMention,
},
+ discord: {
+ ...data.discord,
+ require_mention: requireMention,
+ },
update: {
...data.update,
auto_update: autoUpdate,
@@ -71,8 +78,18 @@ export const Summary: React.FC<SummaryProps> = ({ data, onBack }) => {
<div className="flex-1 space-y-4 overflow-y-auto mb-6">
<Section title={t('summary.mode')} value={data.mode} />
- <Section title={t('summary.slackBotToken')} value={mask(data.slack?.bot_token || '')} />
- <Section title={t('summary.slackAppToken')} value={mask(data.slack?.app_token || '')} />
+ <Section title={t('summary.platform')} value={platform} />
+ {platform === 'discord' ? (
+ <>
+ <Section title={t('summary.discordBotToken')} value={mask(data.discord?.bot_token || '')} />
+ <Section title={t('summary.discordGuild')} value={(data.discord?.guild_allowlist || [])[0] || t('summary.notSet')} />
+ </>
+ ) : (
+ <>
+ <Section title={t('summary.slackBotToken')} value={mask(data.slack?.bot_token || '')} />
+ <Section title={t('summary.slackAppToken')} value={mask(data.slack?.app_token || '')} />
+ </>
+ )}
<Section title={t('summary.enabledAgents')} value={enabledAgents(data).join(', ')} />
<Section title={t('summary.channelsConfigured')} value={Object.keys(data.channelConfigs || {}).filter(k => data.channelConfigs[k]?.enabled).length} />
@@ -191,6 +208,7 @@ const enabledAgents = (data: any) => {
const buildConfigPayload = (data: any) => {
const agents = data.agents || {};
return {
+ platform: data.platform || 'slack',
mode: data.mode || 'self_host',
version: 'v2',
slack: {
@@ -201,6 +219,13 @@ const buildConfigPayload = (data: any) => {
app_token: data.slack?.app_token || '',
require_mention: data.slack?.require_mention || false,
},
+ discord: {
+ ...data.discord,
+ bot_token: data.discord?.bot_token || '',
+ guild_allowlist: data.discord?.guild_allowlist || [],
+ guild_denylist: data.discord?.guild_denylist || [],
+ require_mention: data.discord?.require_mention || false,
+ },
runtime: {
// Preserve existing runtime config
...data.runtime,
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 4cfa9e816..d1055d212 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -11,6 +11,9 @@ export type ApiContextType = {
slackAuthTest: (botToken: string) => Promise<any>;
slackChannels: (botToken: string) => Promise<any>;
slackManifest: () => Promise<{ ok: boolean; manifest?: string; manifest_compact?: string; error?: string }>;
+ discordAuthTest: (botToken: string) => Promise<any>;
+ discordGuilds: (botToken: string) => Promise<any>;
+ discordChannels: (botToken: string, guildId: string) => Promise<any>;
doctor: () => Promise<any>;
opencodeOptions: (cwd: string) => Promise<any>;
opencodeSetupPermission: () => Promise<{ ok: boolean; message: string; config_path: string }>;
@@ -118,6 +121,9 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
slackAuthTest: (botToken) => postJson('/slack/auth_test', { bot_token: botToken }),
slackChannels: (botToken) => postJson('/slack/channels', { bot_token: botToken }),
slackManifest: () => getJson('/slack/manifest'),
+ discordAuthTest: (botToken) => postJson('/discord/auth_test', { bot_token: botToken }),
+ discordGuilds: (botToken) => postJson('/discord/guilds', { bot_token: botToken }),
+ discordChannels: (botToken, guildId) => postJson('/discord/channels', { bot_token: botToken, guild_id: guildId }),
doctor: () => postJson('/doctor', {}),
opencodeOptions: (cwd) => postJson('/opencode/options', { cwd }),
opencodeSetupPermission: () => postJson('/opencode/setup-permission', {}),
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index bb2ecd7df..efe2d0899 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -49,7 +49,7 @@
},
"welcome": {
"title": "Set up Vibe Remote",
- "subtitle": "Your local AI coding assistant for Slack.",
+ "subtitle": "Your local AI coding assistant for Slack and Discord.",
"getStarted": "Get started",
"feature1": "Runs locally. Your code stays on your computer.",
"feature2": "SaaS mode uses a cloud relay for Slack delivery, but does not store message content.",
@@ -62,6 +62,31 @@
"selfHostMode": "Self-host Mode",
"selfHostDescription": "Use your own Slack app + Socket Mode tokens."
},
+ "platform": {
+ "title": "Choose a Platform",
+ "subtitle": "Select the chat platform to connect.",
+ "slack": {
+ "title": "Slack",
+ "desc": "Connect a Slack workspace and enable channels."
+ },
+ "discord": {
+ "title": "Discord",
+ "desc": "Connect a Discord bot and choose a guild."
+ }
+ },
+ "discordConfig": {
+ "title": "Discord Configuration",
+ "subtitle": "Add your bot token and validate access.",
+ "botToken": "Bot Token",
+ "botTokenPlaceholder": "Paste your Discord bot token",
+ "botTokenHint": "Use the token from the Discord Developer Portal.",
+ "validateToken": "Validate Token",
+ "tokenValidated": "Token validated",
+ "authFailed": "Validation failed",
+ "guild": "Guild",
+ "guildPlaceholder": "Select a guild",
+ "guildHint": "Choose the guild where the bot is installed."
+ },
"slackConfig": {
"title": "Slack Configuration",
"saasDescription": "Authorize the official Slack app and wait for workspace binding.",
@@ -130,12 +155,17 @@
"refreshList": "Refresh List",
"cantFindChannel": "Can't find your channel?",
"inviteBotHint": "Invite the bot to your channel first:\n1. Open the channel, click ⚙️ Settings → Integrations → Add apps\n2. Or type /invite @YourBotName in the channel",
+ "discordInviteBotHint": "Add the bot to your guild and grant access to the channel.",
+ "guild": "Guild",
+ "guildPlaceholder": "Select a guild",
+ "discordText": "Text",
+ "discordNews": "News",
"enabledCount": "{{count}} enabled",
"accessPolicy": "Access Policy",
"accessPolicyHint": "Channels are enabled only when checked below.",
"noChannelsFound": "No channels found. Check token or invite bot.",
"noChannelsLoaded": "No channels loaded.",
- "addTokenFirst": "Add a Slack bot token first to load channels.",
+ "addTokenFirst": "Add a bot token first to load channels.",
"workingDirectory": "Working Directory",
"useGlobalDefault": "Use global default",
"backend": "Backend",
@@ -164,8 +194,12 @@
"title": "Review & Finish",
"subtitle": "Confirm settings and start Vibe Remote.",
"mode": "Mode",
+ "platform": "Platform",
"slackBotToken": "Slack Bot Token",
"slackAppToken": "Slack App Token",
+ "discordBotToken": "Discord Bot Token",
+ "discordGuild": "Discord Guild",
+ "notSet": "Not set",
"enabledAgents": "Enabled Agents",
"channelsConfigured": "Channels Configured",
"requireMention": "Require @Mention",
@@ -186,6 +220,7 @@
"subtitle": "Manage your local Vibe Remote instance.",
"serviceStatus": "Service Status",
"mode": "Mode",
+ "platform": "Platform",
"workspace": "Workspace",
"gateway": "Gateway",
"health": "Health",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index ad167f387..85659575b 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -49,7 +49,7 @@
},
"welcome": {
"title": "设置 Vibe Remote",
- "subtitle": "为 Slack 打造的本地 AI 编程助手",
+ "subtitle": "为 Slack 与 Discord 打造的本地 AI 编程助手",
"getStarted": "开始设置",
"feature1": "本地运行,代码留在您的电脑上",
"feature2": "SaaS 模式使用云端中继进行 Slack 消息传输,但不会存储消息内容",
@@ -62,6 +62,31 @@
"selfHostMode": "自托管模式",
"selfHostDescription": "使用您自己的 Slack 应用 + Socket Mode 令牌"
},
+ "platform": {
+ "title": "选择平台",
+ "subtitle": "选择要连接的聊天平台。",
+ "slack": {
+ "title": "Slack",
+ "desc": "连接 Slack 工作区并启用频道。"
+ },
+ "discord": {
+ "title": "Discord",
+ "desc": "连接 Discord 机器人并选择服务器。"
+ }
+ },
+ "discordConfig": {
+ "title": "Discord 配置",
+ "subtitle": "填写机器人令牌并验证权限。",
+ "botToken": "机器人令牌",
+ "botTokenPlaceholder": "粘贴 Discord 机器人令牌",
+ "botTokenHint": "在 Discord Developer Portal 获取令牌。",
+ "validateToken": "验证令牌",
+ "tokenValidated": "令牌验证成功",
+ "authFailed": "验证失败",
+ "guild": "服务器",
+ "guildPlaceholder": "选择服务器",
+ "guildHint": "选择已安装机器人的服务器。"
+ },
"slackConfig": {
"title": "Slack 配置",
"saasDescription": "授权官方 Slack 应用并等待工作区绑定",
@@ -130,12 +155,17 @@
"refreshList": "刷新列表",
"cantFindChannel": "找不到你想要的频道?",
"inviteBotHint": "请先将 Bot 邀请到频道:\n1. 打开频道,点击 ⚙️ 设置 → 集成 → 添加应用\n2. 或在频道中输入 /invite @你的Bot名称",
+ "discordInviteBotHint": "请确保机器人已加入服务器并具备访问频道的权限。",
+ "guild": "服务器",
+ "guildPlaceholder": "选择服务器",
+ "discordText": "文本",
+ "discordNews": "公告",
"enabledCount": "已启用 {{count}} 个",
"accessPolicy": "访问策略",
"accessPolicyHint": "只有勾选的频道才会启用",
"noChannelsFound": "未找到频道,请检查令牌或邀请机器人",
"noChannelsLoaded": "未加载频道",
- "addTokenFirst": "请先添加 Slack Bot 令牌以加载频道",
+ "addTokenFirst": "请先添加机器人令牌以加载频道",
"workingDirectory": "工作目录",
"useGlobalDefault": "使用全局默认值",
"backend": "后端",
@@ -164,8 +194,12 @@
"title": "检查并完成",
"subtitle": "确认设置并启动 Vibe Remote",
"mode": "模式",
+ "platform": "平台",
"slackBotToken": "Slack Bot 令牌",
"slackAppToken": "Slack App 令牌",
+ "discordBotToken": "Discord 机器人令牌",
+ "discordGuild": "Discord 服务器",
+ "notSet": "未设置",
"enabledAgents": "已启用的 Agent",
"channelsConfigured": "已配置的频道",
"requireMention": "需要 @提及",
@@ -186,6 +220,7 @@
"subtitle": "管理您的本地 Vibe Remote 实例",
"serviceStatus": "服务状态",
"mode": "模式",
+ "platform": "平台",
"workspace": "工作区",
"gateway": "网关",
"health": "健康状态",
diff --git a/vibe/api.py b/vibe/api.py
index 20a326bf2..e3e823c63 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -38,12 +38,14 @@ def save_config(payload: dict) -> V2Config:
def config_to_payload(config: V2Config) -> dict:
payload = {
+ "platform": config.platform,
"mode": config.mode,
"version": config.version,
"slack": {
**config.slack.__dict__,
"require_mention": config.slack.require_mention,
},
+ "discord": config.discord.__dict__ if config.discord else None,
"runtime": {
"default_cwd": config.runtime.default_cwd,
"log_level": config.runtime.log_level,
@@ -161,6 +163,39 @@ def list_channels(bot_token: str) -> dict:
return {"ok": False, "error": str(exc)}
+def discord_auth_test(bot_token: str) -> dict:
+ try:
+ data = _discord_api_get(bot_token, "users/@me")
+ return {"ok": True, "response": data}
+ except Exception as exc:
+ return {"ok": False, "error": str(exc)}
+
+
+def discord_list_guilds(bot_token: str) -> dict:
+ try:
+ data = _discord_api_get(bot_token, "users/@me/guilds")
+ return {"ok": True, "guilds": data}
+ except Exception as exc:
+ return {"ok": False, "error": str(exc)}
+
+
+def discord_list_channels(bot_token: str, guild_id: str) -> dict:
+ try:
+ data = _discord_api_get(bot_token, f"guilds/{guild_id}/channels")
+ channels = []
+ for channel in data:
+ channels.append(
+ {
+ "id": channel.get("id"),
+ "name": channel.get("name"),
+ "type": channel.get("type"),
+ }
+ )
+ return {"ok": True, "channels": channels}
+ except Exception as exc:
+ return {"ok": False, "error": str(exc)}
+
+
def opencode_options(cwd: str) -> dict:
try:
return asyncio.run(opencode_options_async(cwd))
@@ -169,6 +204,21 @@ def opencode_options(cwd: str) -> dict:
return {"ok": False, "error": str(exc)}
+def _discord_api_get(bot_token: str, path: str) -> dict:
+ import urllib.request
+
+ if not bot_token:
+ raise ValueError("bot_token is required")
+ url = f"https://discord.com/api/v10/{path.lstrip('/')}"
+ req = urllib.request.Request(
+ url,
+ headers={"Authorization": f"Bot {bot_token}", "User-Agent": "vibe-remote"},
+ )
+ with urllib.request.urlopen(req, timeout=10) as resp:
+ payload = resp.read().decode("utf-8")
+ return json.loads(payload)
+
+
async def opencode_options_async(cwd: str) -> dict:
# Expand ~ to user home directory
expanded_cwd = os.path.expanduser(cwd)
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index ccb5815fe..575081077 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -34,6 +34,7 @@
"languageUpdateFailed": "Language update failed. Please try again.",
"resumeSubmitFailed": "Failed to resume session: {error}",
"routingUpdateFailed": "Failed to update routing: {error}",
+ "updateUnavailable": "Update action is not available right now.",
"unknownAction": "Unknown action: {action}",
"processActionFailed": "Error processing action: {error}",
"agentNotConfigured": "Agent `{agent}` is not configured. Make sure the Codex CLI is installed and environment variables are set if this channel is routed to Codex.",
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 6d87d2be9..62fcd097a 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -34,6 +34,7 @@
"languageUpdateFailed": "语言更新失败,请重试。",
"resumeSubmitFailed": "恢复会话失败:{error}",
"routingUpdateFailed": "更新路由失败:{error}",
+ "updateUnavailable": "当前无法执行更新操作。",
"unknownAction": "未知操作:{action}",
"processActionFailed": "处理操作时出错:{error}",
"agentNotConfigured": "Agent `{agent}` 未配置。若此频道路由到 Codex,请确保已安装 Codex CLI 并设置环境变量。",
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index e6983a6ea..d8642dc61 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -266,6 +266,31 @@ def slack_channels():
return jsonify(api.list_channels(payload.get("bot_token", "")))
[email protected]("/discord/auth_test", methods=["POST"])
+def discord_auth_test():
+ from vibe import api
+
+ payload = request.json or {}
+ result = api.discord_auth_test(payload.get("bot_token", ""))
+ return jsonify(result)
+
+
[email protected]("/discord/guilds", methods=["POST"])
+def discord_guilds():
+ from vibe import api
+
+ payload = request.json or {}
+ return jsonify(api.discord_list_guilds(payload.get("bot_token", "")))
+
+
[email protected]("/discord/channels", methods=["POST"])
+def discord_channels():
+ from vibe import api
+
+ payload = request.json or {}
+ return jsonify(api.discord_list_channels(payload.get("bot_token", ""), payload.get("guild_id", "")))
+
+
@app.route("/doctor", methods=["POST"])
def doctor_post():
from vibe.cli import _doctor