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.

refactor(settings): rename hidden_message_types to show_message_types

cyhhao04c6af523df8
diff --git a/.gitignore b/.gitignore
index 56d96c0d9..8457d91a1 100644
--- a/.gitignore
+++ b/.gitignore
@@ -154,7 +154,6 @@ ui/dist/
tmp/
.bot.pid
user_settings.json
-agent_routes.yaml
# Config files with secrets
config/secrets.py
diff --git a/AGENTS.md b/AGENTS.md
index 2aaf18fbe..3c12eb861 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -54,7 +54,7 @@ This file defines how coding agents should work in this repository.
- IM transports: `modules/im/` (Slack-first; platform abstraction retained).
- Config:
- Defaults and validation: `config/` (see `config/v2_config.py`).
- - Agent routing: optional local `agent_routes.yaml` (gitignored).
+ - Agent routing: configured via Slack Agent Settings.
- Runtime data:
- Logs: `~/.vibe_remote/logs/vibe_remote.log`.
- Persisted state: `~/.vibe_remote/state/`.
@@ -93,11 +93,7 @@ This file defines how coding agents should work in this repository.
- OpenCode enablement: `OPENCODE_ENABLED=true` (default: false) and `OPENCODE_CLI_PATH` points to the CLI.
- Codex enablement: `CODEX_ENABLED=true` (default: true) and `CODEX_CLI_PATH` points to the CLI.
-- Routing file:
- - Create `agent_routes.yaml` (local) only if you prefer file-based routing (legacy).
- - Controlled by `AGENT_ROUTE_FILE` (defaults to repo-root `agent_routes.yaml`).
- - Keys are Slack channel IDs; values are agent names (e.g., `opencode`, `claude`, `codex`).
- - Missing entries fall back to platform default, then to global default.
+- Routing is configured per channel via Slack **Agent Settings**.
### Safety Notes
diff --git a/CLAUDE.md b/CLAUDE.md
index 250403c76..f17ec2647 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -47,7 +47,7 @@ This file defines how coding agents should work in this repository.
- IM transports: `modules/im/` (Slack-first; platform abstraction retained).
- Config:
- Defaults and validation: `config/` (see `config/v2_config.py`).
- - Agent routing: optional local `agent_routes.yaml` (gitignored).
+ - Agent routing: configured via Slack Agent Settings.
- Runtime data:
- Logs: `~/.vibe_remote/logs/vibe_remote.log`.
- Persisted state: `~/.vibe_remote/state/`.
@@ -81,11 +81,7 @@ This file defines how coding agents should work in this repository.
- OpenCode enablement: `OPENCODE_ENABLED=true` (default: false) and `OPENCODE_CLI_PATH` points to the CLI.
- Codex enablement: `CODEX_ENABLED=true` (default: true) and `CODEX_CLI_PATH` points to the CLI.
-- Routing file:
- - Create `agent_routes.yaml` (local) only if you prefer file-based routing (legacy).
- - Controlled by `AGENT_ROUTE_FILE` (defaults to repo-root `agent_routes.yaml`).
- - Keys are Slack channel IDs; values are agent names (e.g., `opencode`, `claude`, `codex`).
- - Missing entries fall back to platform default, then to global default.
+- Routing is configured per channel via Slack **Agent Settings**.
### Safety Notes
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 33d809bf5..f86f3f6c4 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -13,7 +13,7 @@ Thanks for your interest in contributing!
- Run locally: `python main.py`
- Lint before PR (add your linter if used)
- Write clear commit messages
-- Agent-specific changes: install the relevant CLI (recommended: OpenCode `opencode`; also supported: Codex), then route one Slack channel via Slack **Agent Settings**, or (legacy) create `agent_routes.yaml`, to manually test the backend (`opencode` or `codex`).
+- Agent-specific changes: install the relevant CLI (recommended: OpenCode `opencode`; also supported: Codex), then route one Slack channel via Slack **Agent Settings** to manually test the backend (`opencode` or `codex`).
## Pull Requests
diff --git a/README.md b/README.md
index 2032f97ca..8e517919f 100644
--- a/README.md
+++ b/README.md
@@ -26,7 +26,7 @@ Vibe Remote lets you operate coding agents via Slack. Type in Slack to start and
- **Vibe coding, not micromanaging**: Let AI drive based on your intent and constraints; focus on outcomes.
- **Work from anywhere**: Control coding sessions over Slack; no IDE tether.
- **Extensible by design**: OpenCode-first, and also supports Claude Code + Codex; built to support additional coding agents/CLIs.
-- **Multi-agent routing**: Route each Slack channel to OpenCode, Claude Code, or Codex via `agent_routes.yaml` (and Slack UI when enabled).
+- **Multi-agent routing**: Route each Slack channel to OpenCode, Claude Code, or Codex via Slack UI.
- **Session persistence by thread + path**: Each Slack thread maintains its own agent session and working dir; auto‑resume via saved mappings.
- **Interactive Slack UX**: `/start` menu + Settings/CWD modals; buttons over commands for faster flow.
@@ -39,7 +39,7 @@ Vibe Remote lets you operate coding agents via Slack. Type in Slack to start and
- **Persistent sessions**: Per chat/thread sessions, easy resume
- **Threaded Slack UX**: Clean, per‑conversation threads
- **Working dir control**: Inspect and change `cwd` on the fly
-- **Personalization**: Toggle which message types to display
+- **Personalization**: Toggle per-channel hidden message types (defaults hide system/toolcall)
## Architecture (Brief)
@@ -135,21 +135,9 @@ vibe
### Agent routing
- Slack: use the built-in **Agent Settings** dialog to select the backend per channel (recommended).
-- Legacy (for backward compatibility): file-based routing via `agent_routes.yaml`.
- - Place `agent_routes.yaml` in the repo root, or point `AGENT_ROUTE_FILE` to any YAML/JSON file.
- - File schema:
-
-```yaml
-default: opencode
-slack:
- default: opencode
- overrides:
- C01EXAMPLE: codex
-```
-
- Slack routes use channel IDs.
- See [docs/CODEX_SETUP.md](docs/CODEX_SETUP.md) for Codex install and routing notes.
-- No routing file? If OpenCode is enabled, the bot defaults to OpenCode; otherwise it falls back to Claude.
+- If OpenCode is enabled, the bot defaults to OpenCode; otherwise it falls back to Claude.
### App
diff --git a/README_ZH.md b/README_ZH.md
index c6d1be648..81f53271e 100644
--- a/README_ZH.md
+++ b/README_ZH.md
@@ -26,7 +26,7 @@ Vibe Remote 把 AI 写代码搬到聊天软件。你在 Slack 输入意图与约
- **专注 vibe coding**:基于你的意图与约束让 AI 自主推进,你只把控方向与结果。
- **随时随地**:不被 IDE 束缚,直接在 Slack 中远程操控编码会话。
- **为扩展而生**:OpenCode 优先,同时支持 Claude Code + Codex;并可扩展到更多 coding agents/CLIs。
-- **多 Agent 路由**:为不同 Slack Channel 指定 OpenCode / Claude Code / Codex,互不干扰。
+- **多 Agent 路由**:通过 Slack UI 为不同 Channel 选择 OpenCode / Claude Code / Codex。
- **按线程 + 路径持久化**:每个 Slack 线程维持独立 Agent 会话与工作目录,并通过持久化映射自动恢复。
- **Slack 交互式体验**:`/start` 菜单 + Settings/CWD 模态,按钮优先于命令,更快上手。
@@ -39,7 +39,7 @@ Vibe Remote 把 AI 写代码搬到聊天软件。你在 Slack 输入意图与约
- **持久会话**:按聊天/线程维度持久化,可随时恢复
- **Slack 线程化 UX**:每个会话独立线程,保持频道整洁
- **工作目录控制**:随时查看与更改 `cwd`
-- **个性化**:自定义隐藏的消息类型
+- **个性化**:按频道自定义隐藏消息类型(默认隐藏 system/toolcall)
## 架构(简述)
@@ -135,21 +135,9 @@ vibe
### Agent 路由
- Slack:推荐直接使用内置的 **Agent Settings** 弹窗,为每个 channel 选择 backend。
-- 兼容(为老用户保留):通过 `agent_routes.yaml` 进行文件路由。
- - 将 `agent_routes.yaml` 放在仓库根目录,或用 `AGENT_ROUTE_FILE` 指向任意 YAML/JSON 文件。
- - 示例:
-
-```yaml
-default: opencode
-slack:
- default: opencode
- overrides:
- C01EXAMPLE: codex
-```
-
- Slack 使用频道 ID。
- 参见 [docs/CODEX_SETUP.md](docs/CODEX_SETUP.md) 获取 Codex 安装与路由说明。
-- 未提供路由文件时:如果启用了 OpenCode,则默认使用 OpenCode;否则回退到 Claude。
+- 如果启用了 OpenCode,则默认使用 OpenCode;否则回退到 Claude。
### 应用
diff --git a/agent_routes.yaml b/agent_routes.yaml
new file mode 100644
index 000000000..b2d231d04
--- /dev/null
+++ b/agent_routes.yaml
@@ -0,0 +1,9 @@
+default: opencode
+slack:
+ default: opencode
+ overrides:
+ C09KX3GN118: codex
+telegram:
+ default: claude
+ overrides:
+ "123456789": codex
diff --git a/config/v2_compat.py b/config/v2_compat.py
index bd8c58e54..ba1f37e06 100644
--- a/config/v2_compat.py
+++ b/config/v2_compat.py
@@ -37,9 +37,7 @@ class AppCompatConfig:
codex: Optional[CodexCompatConfig]
opencode: Optional[OpenCodeCompatConfig]
log_level: str
- cleanup_enabled: bool
ack_mode: str
- agent_route_file: Optional[str]
def to_app_config(v2: V2Config) -> AppCompatConfig:
@@ -62,14 +60,13 @@ def to_app_config(v2: V2Config) -> AppCompatConfig:
port=4096,
request_timeout_seconds=60,
)
+ slack = SlackConfig(**v2.slack.__dict__)
return AppCompatConfig(
platform="slack",
- slack=v2.slack,
+ slack=slack,
claude=claude,
codex=codex,
opencode=opencode,
log_level=v2.runtime.log_level,
- cleanup_enabled=v2.cleanup_enabled,
ack_mode=v2.ack_mode,
- agent_route_file=v2.agent_route_file,
)
diff --git a/config/v2_config.py b/config/v2_config.py
index dea635a9c..fa4063686 100644
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@ -2,7 +2,7 @@ import json
import logging
from dataclasses import dataclass, field
from pathlib import Path
-from typing import List, Optional
+from typing import List, Optional, Union
from config import paths
from modules.im.base import BaseIMConfig
@@ -19,11 +19,6 @@ class SlackConfig(BaseIMConfig):
team_name: Optional[str] = None
app_id: Optional[str] = None
require_mention: bool = False
- target_channels: Optional[List[str]] = None
-
- @classmethod
- def from_env(cls):
- raise RuntimeError("V2 does not support env-based config")
def validate(self) -> None:
if not self.bot_token or not self.bot_token.startswith("xoxb-"):
@@ -45,8 +40,7 @@ class GatewayConfig:
class RuntimeConfig:
default_cwd: str
log_level: str = "INFO"
- require_mention: bool = False
- target_channels: Optional[List[str]] = None
+
@dataclass
@@ -82,6 +76,7 @@ class AgentsConfig:
@dataclass
class UiConfig:
+ setup_host: str = "127.0.0.1"
setup_port: int = 5123
open_browser: bool = True
@@ -96,8 +91,6 @@ class V2Config:
gateway: Optional[GatewayConfig] = None
ui: UiConfig = field(default_factory=UiConfig)
ack_mode: str = "reaction"
- cleanup_enabled: bool = False
- agent_route_file: Optional[str] = None
@classmethod
def load(cls, config_path: Optional[Path] = None) -> "V2Config":
@@ -111,10 +104,19 @@ class V2Config:
@classmethod
def from_payload(cls, payload: dict) -> "V2Config":
slack_payload = payload.get("slack") or {}
+ if "require_mention" not in slack_payload:
+ slack_payload = dict(slack_payload)
+ slack_payload["require_mention"] = False
+ if "target_channels" in slack_payload:
+ slack_payload = dict(slack_payload)
+ slack_payload.pop("target_channels", None)
slack = SlackConfig(**slack_payload)
gateway_payload = payload.get("gateway")
gateway = GatewayConfig(**gateway_payload) if gateway_payload else None
runtime_payload = payload.get("runtime") or {}
+ if "target_channels" in runtime_payload:
+ runtime_payload = dict(runtime_payload)
+ runtime_payload.pop("target_channels", None)
runtime = RuntimeConfig(**runtime_payload)
agents_payload = payload.get("agents") or {}
opencode = OpenCodeConfig(**(agents_payload.get("opencode") or {}))
@@ -136,8 +138,6 @@ class V2Config:
gateway=gateway,
ui=ui,
ack_mode=payload.get("ack_mode", "reaction"),
- cleanup_enabled=payload.get("cleanup_enabled", False),
- agent_route_file=payload.get("agent_route_file"),
)
def save(self, config_path: Optional[Path] = None) -> None:
@@ -150,8 +150,6 @@ class V2Config:
"runtime": {
"default_cwd": self.runtime.default_cwd,
"log_level": self.runtime.log_level,
- "require_mention": self.runtime.require_mention,
- "target_channels": self.runtime.target_channels,
},
"agents": {
"default_backend": self.agents.default_backend,
@@ -162,7 +160,5 @@ class V2Config:
"gateway": self.gateway.__dict__ if self.gateway else None,
"ui": self.ui.__dict__,
"ack_mode": self.ack_mode,
- "cleanup_enabled": self.cleanup_enabled,
- "agent_route_file": self.agent_route_file,
}
path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
diff --git a/config/v2_settings.py b/config/v2_settings.py
index ea1d319ca..bd37bfe4b 100644
--- a/config/v2_settings.py
+++ b/config/v2_settings.py
@@ -1,4 +1,5 @@
import json
+import json
import logging
from dataclasses import dataclass, field
from pathlib import Path
@@ -8,6 +9,15 @@ from config import paths
logger = logging.getLogger(__name__)
+DEFAULT_SHOW_MESSAGE_TYPES: List[str] = []
+ALLOWED_MESSAGE_TYPES = {"system", "assistant", "toolcall"}
+
+
+def normalize_show_message_types(show_message_types: Optional[List[str]]) -> List[str]:
+ if show_message_types is None:
+ return DEFAULT_SHOW_MESSAGE_TYPES.copy()
+ return [msg for msg in show_message_types if msg in ALLOWED_MESSAGE_TYPES]
+
@dataclass
class RoutingSettings:
@@ -19,9 +29,9 @@ class RoutingSettings:
@dataclass
class ChannelSettings:
- enabled: bool = True
- hidden_message_types: List[str] = field(
- default_factory=lambda: ["system", "assistant", "toolcall"]
+ enabled: bool = False
+ show_message_types: List[str] = field(
+ default_factory=lambda: DEFAULT_SHOW_MESSAGE_TYPES.copy()
)
custom_cwd: Optional[str] = None
routing: RoutingSettings = field(default_factory=RoutingSettings)
@@ -46,8 +56,17 @@ class SettingsStore:
except Exception as exc:
logger.error("Failed to load settings: %s", exc)
return
+ raw_channels = payload.get("channels") if isinstance(payload, dict) else None
+ if raw_channels is None:
+ logger.error("Failed to load settings: invalid format")
+ return
+ if not isinstance(raw_channels, dict):
+ logger.error("Failed to load settings: channels must be an object")
+ return
channels = {}
- for channel_id, channel_payload in (payload.get("channels") or {}).items():
+ for channel_id, channel_payload in raw_channels.items():
+ if not isinstance(channel_payload, dict):
+ continue
routing_payload = channel_payload.get("routing") or {}
routing = RoutingSettings(
agent_backend=routing_payload.get("agent_backend"),
@@ -56,9 +75,9 @@ class SettingsStore:
opencode_reasoning_effort=routing_payload.get("opencode_reasoning_effort"),
)
channels[channel_id] = ChannelSettings(
- enabled=channel_payload.get("enabled", True),
- hidden_message_types=channel_payload.get(
- "hidden_message_types", ["system", "assistant", "toolcall"]
+ enabled=channel_payload.get("enabled", False),
+ show_message_types=normalize_show_message_types(
+ channel_payload.get("show_message_types")
),
custom_cwd=channel_payload.get("custom_cwd"),
routing=routing,
@@ -71,7 +90,7 @@ class SettingsStore:
for channel_id, settings in self.settings.channels.items():
payload["channels"][channel_id] = {
"enabled": settings.enabled,
- "hidden_message_types": settings.hidden_message_types,
+ "show_message_types": settings.show_message_types,
"custom_cwd": settings.custom_cwd,
"routing": {
"agent_backend": settings.routing.agent_backend,
diff --git a/core/controller.py b/core/controller.py
index 9b7b08d85..b437c8a03 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -72,15 +72,12 @@ class Controller:
self.session_manager = SessionManager()
self.settings_manager = SettingsManager()
- # Agent routing (service initialized later after handlers)
- self.agent_router = AgentRouter.from_file(
- self.config.agent_route_file, platform=self.config.platform
- )
+ # Agent routing
+ self.agent_router = AgentRouter.from_file(None, platform=self.config.platform)
# Default backend preference:
- # If the user didn't provide an agent_routes.yaml, and OpenCode is enabled,
- # make OpenCode the implicit default backend.
- if self.config.opencode and not self.config.agent_route_file:
+ # If OpenCode is enabled, make it the implicit default backend.
+ if self.config.opencode:
self.agent_router.global_default = "opencode"
platform_route = self.agent_router.platform_routes.get(self.config.platform)
if platform_route:
@@ -154,7 +151,7 @@ class Controller:
# Get custom CWD from settings
custom_cwd = self.settings_manager.get_custom_cwd(settings_key)
- # Use custom CWD if available, otherwise use default from .env
+ # Use custom CWD if available, otherwise use default from config
if custom_cwd and os.path.exists(custom_cwd):
return os.path.abspath(custom_cwd)
elif custom_cwd:
@@ -221,11 +218,9 @@ class Controller:
"""Unified agent resolution with dynamic override support.
Priority:
- 1. channel_routing.agent_backend (from user_settings.json)
- 2. agent_routes.yaml overrides[channel_id]
- 3. agent_routes.yaml platform.default
- 4. agent_routes.yaml global default
- 5. AgentService.default_agent ("claude")
+ 1. channel_routing.agent_backend (from settings.json)
+ 2. AgentRouter platform default (configured in code)
+ 3. AgentService.default_agent ("claude")
"""
settings_key = self._get_settings_key(context)
@@ -375,7 +370,7 @@ class Controller:
# Settings update handler (for Slack modal)
async def handle_settings_update(
- self, user_id: str, hidden_message_types: list, channel_id: Optional[str] = None
+ self, user_id: str, show_message_types: list, channel_id: Optional[str] = None
):
"""Handle settings update (typically from Slack modal)"""
try:
@@ -389,13 +384,13 @@ class Controller:
# Update settings
user_settings = self.settings_manager.get_user_settings(settings_key)
- user_settings.hidden_message_types = hidden_message_types
+ user_settings.show_message_types = show_message_types
# Save settings - using the correct method name
self.settings_manager.update_user_settings(settings_key, user_settings)
logger.info(
- f"Updated settings for {settings_key}: hidden types = {hidden_message_types}"
+ f"Updated settings for {settings_key}: show types = {show_message_types}"
)
# Create context for sending confirmation (without 'message' field)
@@ -642,7 +637,6 @@ class Controller:
# 不再创建额外事件循环,避免与 IM 客户端的内部事件循环冲突
# 清理职责改为:
- # - 仅当收到消息且开启 cleanup_enabled 时,在消息入口清理已完成任务(见 MessageHandler)
# - 进程退出时做一次同步的 best-effort 取消(不跨循环 await)
try:
@@ -689,6 +683,22 @@ class Controller:
except Exception:
pass
+ # Best-effort async shutdown for IM clients
+ try:
+ shutdown_attr = getattr(self.im_client, "shutdown", None)
+ if callable(shutdown_attr):
+ import inspect
+
+ if inspect.iscoroutinefunction(shutdown_attr):
+ try:
+ asyncio.run(shutdown_attr())
+ except RuntimeError:
+ pass
+ else:
+ shutdown_attr()
+ except Exception:
+ pass
+
# Stop OpenCode server if running
try:
from modules.agents.opencode_agent import OpenCodeServerManager
diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.py
index 71bcaf774..66e6b34fe 100644
--- a/core/handlers/message_handler.py
+++ b/core/handlers/message_handler.py
@@ -47,21 +47,7 @@ class MessageHandler:
async def handle_user_message(self, context: MessageContext, message: str):
"""Process regular user messages and route to configured agent"""
try:
- # Safe cleanup: only remove completed receiver tasks when enabled
- if getattr(self.config, "cleanup_enabled", False):
- try:
- completed_keys = [
- key
- for key, task in list(self.receiver_tasks.items())
- if task.done()
- ]
- for key in completed_keys:
- del self.receiver_tasks[key]
- logger.info(
- f"Safely cleaned completed receiver task for session {key}"
- )
- except Exception as cleanup_err:
- logger.debug(f"Safe cleanup skipped due to error: {cleanup_err}")
+ # Skip automatic cleanup; receiver tasks are retained until shutdown
# Allow "stop" shortcut inside Slack threads
if context.thread_id and message.strip().lower() in ["stop", "/stop"]:
diff --git a/core/handlers/settings_handler.py b/core/handlers/settings_handler.py
index bccc61a1a..9f553754b 100644
--- a/core/handlers/settings_handler.py
+++ b/core/handlers/settings_handler.py
@@ -59,11 +59,11 @@ class SettingsHandler:
row = []
for i, msg_type in enumerate(message_types):
- is_hidden = msg_type in user_settings.hidden_message_types
- checkbox = "☑️" if is_hidden else "⬜"
+ is_shown = msg_type in user_settings.show_message_types
+ checkbox = "☑️" if is_shown else "⬜"
display_name = display_names.get(msg_type, msg_type)
button = InlineButton(
- text=f"{checkbox} Hide {display_name}",
+ text=f"{checkbox} Show {display_name}",
callback_data=f"toggle_msg_{msg_type}",
)
row.append(button)
@@ -140,7 +140,7 @@ class SettingsHandler:
try:
# Toggle message type visibility
settings_key = self._get_settings_key(context)
- is_hidden = self.settings_manager.toggle_hidden_message_type(
+ is_shown = self.settings_manager.toggle_show_message_type(
settings_key, msg_type
)
@@ -153,11 +153,11 @@ class SettingsHandler:
row = []
for i, mt in enumerate(message_types):
- is_hidden_now = mt in user_settings.hidden_message_types
- checkbox = "☑️" if is_hidden_now else "⬜"
+ is_shown_now = mt in user_settings.show_message_types
+ checkbox = "☑️" if is_shown_now else "⬜"
display_name = display_names.get(mt, mt)
button = InlineButton(
- text=f"{checkbox} Hide {display_name}",
+ text=f"{checkbox} Show {display_name}",
callback_data=f"toggle_msg_{mt}",
)
row.append(button)
@@ -181,7 +181,7 @@ class SettingsHandler:
# Answer callback (for Telegram)
display_name = display_names.get(msg_type, msg_type)
- action = "hidden" if is_hidden else "shown"
+ action = "shown" if is_shown else "hidden"
# Platform-specific callback answering
await self.im_client.send_message(
@@ -264,7 +264,7 @@ class SettingsHandler:
await self.im_client.send_message(
context,
"🤖 Agent switching is currently only available in Slack. "
- "Use agent_routes.yaml to configure routing.",
+ "Use Slack Agent Settings to configure routing.",
)
except Exception as e:
logger.error(f"Error showing routing settings: {e}", exc_info=True)
diff --git a/docs/CODEX_SETUP.md b/docs/CODEX_SETUP.md
index 71132943e..3587a8637 100644
--- a/docs/CODEX_SETUP.md
+++ b/docs/CODEX_SETUP.md
@@ -32,25 +32,9 @@ No additional flag is required to bypass approvals—the bot always adds `--dang
## 3. Route channels to Codex
-Configure routing (two options):
+Configure routing via Slack **Agent Settings**: pick Codex for the channel you want.
-1) Slack: use the **Agent Settings** dialog to switch a channel to Codex.
-
-2) Legacy (file-based): create `agent_routes.yaml` (repo root) or set `AGENT_ROUTE_FILE`.
-
-Example contents:
-
-```yaml
-default: claude
-slack:
- default: claude
- overrides:
- C01ABCD2EFG: codex # Slack channel ID
-```
-
-Each Slack channel ID (starts with `C`) gets its own agent. Routes fall back to the platform default, then to the global `default`.
-
-`agent_routes.yaml` is gitignored so you can maintain different mappings per environment. Alternatively, point `AGENT_ROUTE_FILE` to a custom path.
+Each Slack channel ID (starts with `C`) gets its own agent. Routes fall back to the configured default backend.
## 4. Restart the bot and test
@@ -64,4 +48,4 @@ In a routed Slack channel run `@VibeRemote status` or any question—you should
- **“Agent `codex` is not configured”**: ensure `codex` CLI is installed and on PATH; check `CODEX_ENABLED`.
- **`codex exec` errors**: inspect the Slack stderr snippet or tail the latest `~/.vibe_remote/logs/vibe_remote.log`.
-- **Routing not applied**: confirm the channel ID matches Slack’s `C...` value (copy from channel details), and restart the bot after editing `agent_routes.yaml`.
+- **Routing not applied**: confirm the channel ID matches Slack’s `C...` value and that the channel override is set in Slack **Agent Settings**.
diff --git a/docs/DYNAMIC_ROUTING_DESIGN.md b/docs/DYNAMIC_ROUTING_DESIGN.md
index a58a132f3..ce573ccca 100644
--- a/docs/DYNAMIC_ROUTING_DESIGN.md
+++ b/docs/DYNAMIC_ROUTING_DESIGN.md
@@ -2,7 +2,7 @@
## Overview
-Replace static `agent_routes.yaml` with dynamic per-channel routing configuration that users can change via Slack menus.
+Replace static file-based routing with dynamic per-channel routing configuration that users can change via Slack menus.
## Requirements
@@ -11,7 +11,7 @@ Replace static `agent_routes.yaml` with dynamic per-channel routing configuratio
- Agent selection (build, plan, etc.) - from `/agent` API
- Model selection - from `/config/providers` API
3. **Claude/Codex**: No model selection (use their defaults)
-4. **Fallback**: `agent_routes.yaml` remains as default; UI overrides are persisted in `~/.vibe_remote/state/settings.json`
+4. **Fallback**: channel routing overrides are persisted in `~/.vibe_remote/state/settings.json`
5. **Entry points**:
- Slack: `/start` button "Switch Agent" + `/settings` modal
@@ -28,7 +28,7 @@ class ChannelRouting:
@dataclass
class UserSettings:
- hidden_message_types: List[str] = ...
+ show_message_types: List[str] = ... # empty list means hide all
custom_cwd: Optional[str] = None
channel_routing: Optional[ChannelRouting] = None
@@ -39,7 +39,7 @@ class UserSettings:
```json
{
"C0A6U2GH6P5": {
- "hidden_message_types": ["system", "assistant", "user"],
+ "show_message_types": ["assistant"],
"custom_cwd": "/path/to/project",
"channel_routing": {
"agent_backend": "opencode",
@@ -55,13 +55,9 @@ class UserSettings:
```
1. channel_routing.agent_backend (from `~/.vibe_remote/state/settings.json`)
↓ if null
-2. agent_routes.yaml overrides[channel_id]
+2. AgentRouter platform default
↓ if not found
-3. agent_routes.yaml platform.default
- ↓ if not found
-4. agent_routes.yaml global default
- ↓ if not found
-5. AgentService.default_agent ("claude")
+3. AgentService.default_agent ("claude")
```
## API Design
@@ -250,51 +246,13 @@ view = {
## Implementation Steps
### Phase 1: Data & Routing
-1. [ ] Add `ChannelRouting` dataclass to `settings_manager.py`
-2. [ ] Add `channel_routing` field to `UserSettings`
-3. [ ] Add `get_channel_routing()` and `set_channel_routing()` methods
-4. [ ] Add `resolve_agent_for_context()` to Controller
-5. [ ] Update all callers of `agent_router.resolve()` to use new method
-
-### Phase 2: OpenCode Integration
-6. [ ] Add `get_available_agents()` to OpenCodeServerManager
-7. [ ] Add `get_available_models()` to OpenCodeServerManager
-8. [ ] Add `get_default_config()` to OpenCodeServerManager
-9. [ ] Modify `OpenCodeAgent._process_message()` to use per-channel overrides
-
-### Phase 3: Slack UI
-10. [ ] Add "Switch Agent" button to `/start` command
-11. [ ] Create `open_routing_modal()` in SlackBot
-12. [ ] Handle `routing_modal` submission in `_handle_view_submission()`
-13. [ ] Add `cmd_routing` callback handler
-
-### Phase 4: Future App UI (Optional)
-14. [ ] Add backend switching to the Vibe app UI
-15. [ ] (Future) Add OpenCode agent/model selection to the Vibe app UI
-
-## File Changes Summary
-
-| File | Changes |
-|------|---------|
+1. [x] Add `ChannelRouting` dataclass to `settings_manager.py`
+4. [x] Add `resolve_agent_for_context()` to Controller
+5. [x] Update all callers of `agent_router.resolve()` to use new method
+
| `modules/settings_manager.py` | Add `ChannelRouting`, routing methods |
| `core/controller.py` | Add `resolve_agent_for_context()`, `get_opencode_overrides()` |
-| `core/handlers/message_handler.py` | Use new resolve method |
-| `core/handlers/command_handlers.py` | Add Switch Agent button, routing callback |
-| `core/handlers/settings_handler.py` | Add routing modal handler |
-| `modules/im/slack.py` | Add `open_routing_modal()`, handle submission |
-| `modules/agents/opencode_agent.py` | Add API methods, use per-channel overrides |
-| `modules/agents/base.py` | Add opencode_agent/model fields to AgentRequest |
-
-## Testing Checklist
-
-- [ ] `/start` shows "Switch Agent" button
-- [ ] Clicking button opens routing modal
-- [ ] Modal shows only registered backends
-- [ ] Selecting OpenCode shows agent/model dropdowns
-- [ ] Selecting Claude/Codex hides OpenCode options
-- [ ] Default options are marked and pre-selected
-- [ ] Saving updates channel routing
-- [ ] Messages route to selected backend
-- [ ] OpenCode uses selected agent/model
-- [ ] Clearing routing falls back to agent_routes.yaml
+
+- [x] Clearing routing falls back to default backend
+
- [ ] Restart preserves routing settings
diff --git a/docs/plans/v2/04_v2_milestones.md b/docs/plans/v2/04_v2_milestones.md
index 85cf94fcb..87cbce237 100644
--- a/docs/plans/v2/04_v2_milestones.md
+++ b/docs/plans/v2/04_v2_milestones.md
@@ -18,11 +18,13 @@
## V2 Milestones
-### M1: Local Data Directory + Config Model (Status: In progress)
+### M1: Local Data Directory + Config Model (Status: Done)
- [x] Establish `~/.vibe_remote/` as the single home for config/state/logs.
- [x] Split settings and sessions into separate JSON files.
-- [~] Remove `.env` and legacy config paths from the V2 flow.
+- [x] Remove `.env` and legacy config paths from the V2 flow.
+- [~] Align defaults with `docs/plans/v2/05_config_model.md` (settings defaults and enablement).
+- [~] Drop V1 compatibility paths/aliases in settings and routing.
Proposed structure:
diff --git a/docs/plans/v2/05_config_model.md b/docs/plans/v2/05_config_model.md
index 0797ef6d7..a09beb152 100644
--- a/docs/plans/v2/05_config_model.md
+++ b/docs/plans/v2/05_config_model.md
@@ -37,8 +37,7 @@ V2 stores all user data under `~/.vibe_remote/` as JSON files. The model preserv
- `default_cwd`: default working directory
- `log_level`: `"DEBUG" | "INFO" | "WARNING" | "ERROR"`
-- `require_mention`: bool (channel messages require @mention)
-- `target_channels`: list of channel IDs or `"*"` for all
+- `require_mention`: bool (channel messages require @mention; stored under `slack`)
### agents
@@ -60,6 +59,7 @@ V2 stores all user data under `~/.vibe_remote/` as JSON files. The model preserv
### ui
+- `setup_host`: hostname/interface for local setup UI
- `setup_port`: port for local setup UI
- `open_browser`: bool
@@ -68,7 +68,7 @@ V2 stores all user data under `~/.vibe_remote/` as JSON files. The model preserv
Settings are stored per channel and preserve existing functionality.
- `channels`: map keyed by `channel_id`
- - `hidden_message_types`: list (default: `system`, `assistant`, `toolcall`)
+ - `show_message_types`: list (default: `[]` - hide all message types)
- `custom_cwd`: optional cwd override
- `routing`:
- `agent_backend`: `"opencode" | "claude" | "codex" | null`
diff --git a/docs/plans/v2/11_web_ui_spec.md b/docs/plans/v2/11_web_ui_spec.md
index 8ba2c4604..e50d2a340 100644
--- a/docs/plans/v2/11_web_ui_spec.md
+++ b/docs/plans/v2/11_web_ui_spec.md
@@ -295,626 +295,7 @@ Validation:
Collects:
-- `config.runtime.target_channels` (global allow-list, including `"*"`)
-- Per-channel settings in `settings.json`:
- - `settings.channels[channel_id].custom_cwd`
- - `settings.channels[channel_id].routing.*`
- - `settings.channels[channel_id].hidden_message_types`
+- `settings.channels[*].enabled` is the single source of truth for channel availability.
+- Channel list loads and user can enable/disable channels; resulting `settings.json` is persisted.
+- Confusing channel enable semantics are avoided by removing the global allow-list.
-UI requirements:
-
-- Fetch channel list:
- - SaaS: via cloud-backed endpoint using workspace token
- - Self-host: via Slack Web API using bot token
-
-Channel list table:
-
-- Columns:
- - Channel name (with privacy badge: Public/Private)
- - Enabled toggle
- - Working directory
- - Backend (effective)
- - Last activity (if available from `sessions.json`; otherwise omit)
-
-Enable/disable behavior (maps to `config.runtime.target_channels`):
-
-- If `target_channels == "*"`:
- - All channels show Enabled=true.
- - Turning a single channel off converts `target_channels` to an explicit list of all currently enabled channels except that one.
-- If `target_channels` is a list:
- - Enabled=true if channel id is in the list.
- - Enabled=false otherwise.
- - Provide a top-level action: “Enable all channels” that sets `target_channels` to `"*"`.
-
-Channel detail drawer/page (`/channels/:channel_id`):
-
-1) Working directory
-
-- Field: “Working directory for this channel”
- - Default: empty (uses `config.runtime.default_cwd`)
- - When set: writes to `settings.channels[channel_id].custom_cwd`
-- Validation:
- - Must be an absolute path.
- - Must exist and be a directory.
- - Must be readable and writable.
-
-2) Agent routing
-
-- Field: “Agent backend”
- - Options: “Use workspace default”, “OpenCode”, “ClaudeCode”, “Codex”
- - Writes to `settings.channels[channel_id].routing.agent_backend` where “Use workspace default” stores `null`.
-
-- Backend overrides (only shown when relevant):
- - OpenCode:
- - Agent (optional): `routing.opencode_agent`
- - Model (optional): `routing.opencode_model`
- - Reasoning effort (optional): `routing.opencode_reasoning_effort`
- - ClaudeCode:
- - Model override (optional): stored in `routing` only if supported in code; otherwise hidden in UI for V2.
- - Codex:
- - Model override (optional): stored in `routing` only if supported in code; otherwise hidden in UI for V2.
-
-Notes for frontend engineering:
-
-- The V2 config model explicitly defines OpenCode per-channel overrides in `settings.json`. For ClaudeCode/Codex, only global defaults are defined in `config.json`. The UI must not write undefined per-channel keys.
-
-3) Message visibility
-
-- Multi-select checkboxes: “Hide these message types in Slack”
- - System
- - Assistant
- - Tool calls
-- Writes to `settings.channels[channel_id].hidden_message_types`.
-- Default selection: `system`, `assistant`, `toolcall`.
-
-4) Effective settings preview
-
-- Read-only panel that shows resolved values:
- - Enabled (from `target_channels`)
- - Effective CWD (channel override or default)
- - Effective backend and model/agent (channel override or global default)
-
-#### Step 6: Validation + finish
-
-Purpose: run all checks before starting service.
-
-UI:
-
-- Button: “Run validation”
-- Results grouped:
- - Executors
- - Slack
- - Relay (SaaS only)
- - Filesystem
- - Configuration
-
-Each check shows:
-
-- Status: Pass / Warn / Fail
-- One-line explanation
-- Action link (if fixable in UI) or “Copy command” (if fix requires CLI)
-
-Rules:
-
-- “Finish setup” CTA is disabled until all Fail items are resolved.
-- Warn items do not block but are highlighted.
-
-#### Step 7: Start service
-
-UI:
-
-- Primary CTA: “Start Vibe Remote”
-- After successful start:
- - Show “Service running”
- - Button: “Go to dashboard”
-
-Constraints:
-
-- Start is idempotent. If already running, show “Already running” and navigate to Dashboard.
-
----
-
-## Dashboard requirements
-
-Dashboard is the default screen after setup.
-
-### Overview card
-
-- Service status pill: Running / Stopped / Error
-- Mode: SaaS / Self-host
-- Workspace: team name + team id
-- Gateway connection (SaaS): Online / Offline, last connected time (`config.gateway.last_connected_at`)
-
-### Controls
-
-- Buttons:
- - Start (if stopped)
- - Stop (if running)
- - Restart
-
-Rules:
-
-- Actions are idempotent and show inline progress.
-- Stop triggers a confirmation modal: “Stopping will pause Slack responses until restarted.”
-
-### Channels snapshot
-
-- Quick stats:
- - Enabled channels count
- - Total channels where bot is present (if available)
-- Table of up to 5 recently active channels (if sessions data available) with “View all” link.
-
-### Health snapshot
-
-- Inline Doctor summary:
- - “All systems go” or “2 issues need attention”
- - Link to Doctor panel
-
-### Footers / secondary
-
-- Config file locations (read-only):
- - `~/.vibe_remote/config/config.json`
- - `~/.vibe_remote/state/settings.json`
- - `~/.vibe_remote/logs/vibe_remote.log`
-
----
-
-## Doctor panel requirements
-
-Doctor panel must mirror the checks in `docs/plans/v2/09_cli_and_install.md` and present them in a UI that is:
-
-- Fast to scan (grouped, clear statuses)
-- Actionable (links to fix in-place)
-- Copy-friendly (export report)
-
-### Doctor checks
-
-The UI runs `POST /api/doctor/run` and displays the returned structured results.
-
-Required check groups:
-
-1) Config validation
-
-- Validate schema presence and required fields based on mode.
-- Validate file readability/writability.
-
-2) Slack validation
-
-- Self-host:
- - `auth.test` using `xoxb-` token
- - Validate required scopes from `docs/plans/v2/10_slack_permissions.md`.
-- SaaS:
- - Validate workspace binding exists (team_id)
- - Validate workspace token is present
- - Cloud-backed `auth.test` equivalent via relay/control plane
-
-3) Executors
-
-- For each enabled backend:
- - CLI exists and is executable
- - Version detection succeeds
-
-4) Relay connectivity (SaaS only)
-
-- Relay URL reachable
-- Successful hello/hello_ack handshake (see `docs/plans/v2/06_gateway_protocol.md`)
-- Time since last connected under a clear threshold (e.g., warn if > 10 minutes)
-
-5) Runtime
-
-- Service process running (PID) and responding
-- Ports in use / conflicts
-
-### Doctor UI behaviors
-
-- Button: “Run Doctor” (always visible)
-- Auto-run on page load if last run older than 5 minutes.
-- Expand/collapse per group; “Expand all” action.
-- Export:
- - “Copy report” copies a redacted JSON summary to clipboard.
- - Redaction rules: mask tokens, secrets, and any values matching `xoxb-`, `xapp-`, `workspace_token`, `client_secret`.
-
----
-
-## Layout / typography / color direction
-
-The UI should feel like a developer tool: calm, precise, and readable for long sessions, without default “generic dashboard” styling.
-
-### Typography
-
-- Headings: "Space Grotesk" (600)
-- Body: "IBM Plex Sans" (400/500)
-- Code / tokens / paths: "IBM Plex Mono" (400)
-
-Implementation notes:
-
-- Self-host fonts (bundle in app assets) to avoid relying on Google Fonts and to work offline in self-host mode.
-
-### Color system (CSS variables)
-
-Use a warm neutral base with a teal accent (no purple bias).
-
-```css
-:root {
- --bg: #F6F2EA; /* warm paper */
- --panel: #FFFFFF;
- --text: #1F2430; /* ink */
- --muted: #5B6475;
- --border: #E6DFD3;
-
- --accent: #0B7285; /* teal */
- --accent-2: #E29578; /* clay */
-
- --success: #2F9E44;
- --warning: #F08C00;
- --danger: #D9480F;
-}
-```
-
-Background direction:
-
-- Subtle gradient from `--bg` to a slightly cooler tint at the top.
-- Light grain/noise texture (very low opacity) is acceptable if it does not affect readability.
-
-### Layout
-
-- App shell uses a left sidebar (desktop) and bottom nav (mobile) with the same destinations.
-- Max content width: 1100px, centered, with generous whitespace.
-- Step wizard uses a sticky stepper header on desktop; collapses to “Step X of Y” on mobile.
-
-### Motion
-
-- Use one meaningful motion pattern:
- - Step transitions: 150–200ms fade + slide (reduced motion respected).
-- Avoid constant micro-animations.
-
-### Accessibility
-
-- Keyboard navigable; visible focus rings.
-- Color contrast meets WCAG AA.
-- All form fields have labels and error text tied via `aria-describedby`.
-
----
-
-## Component requirements
-
-The UI must be built from reusable components with consistent states.
-
-Required components:
-
-- AppShell (sidebar/topbar, workspace chip, service status pill)
-- Stepper (wizard steps with completion/validation state)
-- Card / SectionHeader
-- FormField (label, helper, validation error)
-- ToggleSwitch
-- Select / Combobox
-- CodeBlock (monospace, copy button, masked mode)
-- StatusPill (Running/Stopped/Error; Pass/Warn/Fail)
-- InlineAlert (info/warn/error)
-- Toast notifications (success/failure of save/start/stop)
-- ConfirmationModal (stop, reset)
-- ChannelTable (sortable by name, filter by enabled)
-- EmptyState (no channels, no private channel access, etc.)
-- Skeleton loaders for async data
-
----
-
-## API endpoints (local UI backend)
-
-All endpoints are served by the local gateway at:
-
-- `http://127.0.0.1:<config.ui.setup_port>`
-
-Conventions:
-
-- JSON request/response.
-- Errors use the same shape:
-
-```json
-{
- "error": {
- "code": "string",
- "message": "human readable",
- "details": {}
- }
-}
-```
-
-### Status + runtime
-
-- `GET /api/status`
- - Returns: mode, service_state, workspace summary, gateway connection summary.
-
-Response:
-
-```json
-{
- "service": {"state": "running", "pid": 12345, "started_at": "2026-01-18T12:00:00Z"},
- "config": {"mode": "saas", "version": "2"},
- "workspace": {"team_id": "T123", "team_name": "Acme"},
- "gateway": {"relay_url": "https://relay.vibe.remote", "last_connected_at": "2026-01-18T12:00:00Z", "connected": true}
-}
-```
-
-- `POST /api/service/start`
-- `POST /api/service/stop`
-- `POST /api/service/restart`
-
-All three are idempotent and return the same payload as `/api/status`.
-
-### Config + settings
-
-- `GET /api/config`
- - Returns current `config.json` contents.
-- `PUT /api/config`
- - Replaces allowed keys; server validates and persists.
-
-- `GET /api/settings`
- - Returns current `settings.json` contents.
-- `PUT /api/settings`
- - Replaces allowed keys; server validates and persists.
-
-Write rules:
-
-- Server rejects unknown top-level keys.
-- Server applies defaults defined in `docs/plans/v2/05_config_model.md` when fields are missing.
-
-### Executor detection
-
-- `POST /api/executors/detect`
-
-Request:
-
-```json
-{"backends": ["opencode", "claude", "codex"]}
-```
-
-Response:
-
-```json
-{
- "results": {
- "opencode": {"found": true, "cli_path": "/usr/local/bin/opencode", "version": "1.2.3"},
- "claude": {"found": false, "cli_path": null, "version": null},
- "codex": {"found": true, "cli_path": "/opt/homebrew/bin/codex", "version": "0.9.1"}
- }
-}
-```
-
-### Slack + channels
-
-- `POST /api/slack/validate`
-
-Runs Slack validation appropriate to mode.
-
-Response:
-
-```json
-{
- "ok": true,
- "team": {"id": "T123", "name": "Acme"},
- "bot_user_id": "U999",
- "missing_scopes": []
-}
-```
-
-- `GET /api/slack/channels`
-
-Returns channels where the bot is present and the user can configure.
-
-Response:
-
-```json
-{
- "channels": [
- {"id": "C123", "name": "dev", "is_private": false, "is_member": true},
- {"id": "G456", "name": "incident-room", "is_private": true, "is_member": true}
- ]
-}
-```
-
-### SaaS OAuth (mode == saas)
-
-- `POST /api/saas/oauth/start`
-
-Response:
-
-```json
-{"authorize_url": "https://vibe.remote/slack/oauth/start?state=..."}
-```
-
-- `GET /api/saas/oauth/status`
-
-Response states:
-
-```json
-{"state": "pending"}
-```
-
-```json
-{
- "state": "complete",
- "workspace": {"team_id": "T123", "team_name": "Acme", "app_id": "A111"},
- "gateway": {"relay_url": "https://relay.vibe.remote", "workspace_token": "***", "client_id": "gw-...", "client_secret": "***"}
-}
-```
-
-```json
-{"state": "error", "error": {"code": "oauth_failed", "message": "Slack authorization was cancelled."}}
-```
-
-### Doctor
-
-- `POST /api/doctor/run`
-
-Response:
-
-```json
-{
- "ran_at": "2026-01-18T12:00:00Z",
- "summary": {"pass": 12, "warn": 1, "fail": 0},
- "groups": [
- {
- "name": "Slack",
- "items": [
- {"id": "slack-auth-test", "status": "pass", "message": "auth.test succeeded", "action": null}
- ]
- }
- ]
-}
-```
-
----
-
-## Data & rules (validation, persistence, permissions)
-
-### Files written
-
-UI writes only these V2 files:
-
-- `~/.vibe_remote/config/config.json`
-- `~/.vibe_remote/state/settings.json`
-
-It must not write to:
-
-- `~/.vibe_remote/state/sessions.json` (runtime-owned)
-
-### Mode-dependent required fields
-
-From `docs/plans/v2/05_config_model.md`:
-
-- If `mode == "self_host"`:
- - `config.slack.bot_token` required
- - `config.slack.app_token` required
-- If `mode == "saas"`:
- - `config.gateway.relay_url` required
- - `config.gateway.workspace_token` required
- - `config.slack.team_id` required
-
-### Validation rules
-
-- Tokens:
- - Bot token must match `^xoxb-[A-Za-z0-9-]+$`
- - App token must match `^xapp-[A-Za-z0-9-]+$`
-- Relay URL:
- - Must be HTTPS
- - Must be a valid URL
-- Paths:
- - `runtime.default_cwd` and any `custom_cwd` must be absolute
- - Must exist, be a directory, and be readable/writable
-- Target channels:
- - Either `"*"` or a non-empty list of Slack channel IDs
- - When list: IDs must be unique
-
-### Channel settings resolution (effective behavior)
-
-- Enabled:
- - If `target_channels == "*"`: all channels are enabled.
- - Else: enabled iff channel id in list.
-
-- CWD:
- - If `settings.channels[channel_id].custom_cwd` is set, use it.
- - Else use `config.runtime.default_cwd`.
-
-- Routing:
- - If `settings.channels[channel_id].routing.agent_backend` is `null`, use `config.agents.default_backend`.
- - If backend is OpenCode:
- - use per-channel overrides if present, else OpenCode defaults.
-
-### Security constraints
-
-- Web server binds to `127.0.0.1` only.
-- UI must never display raw tokens by default.
- - Tokens are masked and require explicit “Reveal” per field.
-- “Copy” actions copy the full value, but only after user intent (button click).
-
----
-
-## Edge cases & failure modes
-
-- Slack OAuth cancelled (SaaS): show a clear error and allow retry.
-- Missing Slack scopes (self-host): doctor and validation show exact missing scopes; link to manifest.
-- Bot not in channel:
- - Channel list should still show channels (if API returns them) and mark “Bot not a member”; enable toggle disabled with instruction: “Invite the bot to this channel in Slack.”
-- No channels found:
- - Show empty state with steps: “Create a channel” + “Invite the bot” + “Refresh”.
-- Private channels not visible:
- - If `groups:*` scopes missing, show “Private channels unavailable” warning.
-- Executor CLI missing:
- - Block wizard progression if enabled backend has missing/non-executable path.
- - Provide a “Disable this backend” action.
-- Relay offline (SaaS):
- - Dashboard shows Offline with last_connected_at.
- - Doctor shows fail for relay connectivity with retry.
-- Port conflict for setup UI:
- - Backend chooses a free port and returns it; UI displays actual URL in header.
-- Service stop from dashboard:
- - UI navigates to a “Service stopped” page with a Start button; do not show broken state.
-
----
-
-## Acceptance criteria
-
-Setup wizard:
-
-- On first run with no config, UI opens to `/setup` and completes all steps without manual file editing.
-- SaaS flow:
- - “Connect Slack” starts OAuth, polling completes, and resulting workspace + relay values are persisted to `~/.vibe_remote/config/config.json`.
-- Self-host flow:
- - User can copy manifest, paste `xapp-` and `xoxb-` tokens, run `auth.test`, and persist tokens to `~/.vibe_remote/config/config.json`.
-- Channel settings step:
- - Channel list loads and user can enable/disable channels; resulting `runtime.target_channels` is persisted.
- - User can set a per-channel `custom_cwd` and routing values; persisted to `~/.vibe_remote/state/settings.json`.
-- Validation step:
- - “Run validation” produces pass/warn/fail statuses and blocks finish when any fail exists.
-
-Dashboard:
-
-- Dashboard shows current service state, mode, workspace, and relay connection state.
-- Start/Stop/Restart work and are idempotent (repeated clicks do not crash and return consistent state).
-- Dashboard links to Channels and Doctor and reflects updated settings without page reload (or via refresh).
-
-Doctor:
-
-- Doctor panel runs and shows results for: config, Slack, executors, relay (SaaS), runtime.
-- Doctor export is redacted and never includes raw tokens/secrets.
-
-UX + accessibility:
-
-- Works on mobile widths down to 360px.
-- Keyboard navigation covers wizard, tables, and modals.
-- All critical errors include a human-readable message and a next step.
-
----
-
-## Metrics / telemetry
-
-V2 focuses on local observability; do not log message contents.
-
-Local (in `~/.vibe_remote/logs/vibe_remote.log` and/or UI backend):
-
-- Setup completion event (mode, time-to-complete)
-- Doctor run counts + failing check IDs
-- Service start/stop/restart counts
-- Relay connection duration + reconnect counts (SaaS)
-
-Cloud (SaaS control plane; no message content):
-
-- Workspace install success/failure
-- Active gateway online/offline timestamps
-
----
-
-## Rollout plan & risks
-
-Rollout:
-
-- Ship Web UI as part of V2 CLI (`vibe`) and make it the default entrypoint.
-- Release behind a V2 version gate (`config.version`) to avoid interacting with V1 artifacts.
-
-Key risks and mitigations:
-
-- OAuth complexity (SaaS): mitigate with clear polling states and deterministic error codes.
-- Token leakage: mitigate with masking-by-default, redaction in logs/exports, localhost-only binding.
-- Slack scope drift: mitigate by embedding the exact scopes/events list in UI and validating missing scopes in Doctor.
-- Confusing channel enable semantics: mitigate by making `target_channels` behavior explicit and showing an “Enabled in Slack” preview per channel.
diff --git a/docs/plans/v2/12_webui_log_bugfixes.md b/docs/plans/v2/12_webui_log_bugfixes.md
new file mode 100644
index 000000000..ec4e61efd
--- /dev/null
+++ b/docs/plans/v2/12_webui_log_bugfixes.md
@@ -0,0 +1,21 @@
+# Web UI Log Bugfixes
+
+## Background
+Recent Web UI runs show repeated errors in `~/.vibe_remote/logs/vibe_remote.log`, notably settings load failures and unclosed aiohttp client sessions during shutdown.
+
+## Goals
+- Load channel-based settings without errors or data loss.
+- Eliminate aiohttp client session leaks on shutdown.
+- Keep Slack routing and settings behavior consistent with V2 channel settings.
+
+## Solution Outline
+- Make `SettingsManager` read/write the new `config.v2_settings.SettingsStore` format (channels map), while preserving current APIs used by handlers.
+- Provide a best-effort close path for Slack async clients and OpenCode HTTP sessions during controller shutdown.
+- Add lightweight migration/compat logic where needed to avoid breaking older settings payloads.
+
+## Todo
+- Update `SettingsManager` to wrap `SettingsStore` for channel settings (hidden types, custom CWD, routing).
+- Adjust `SettingsManager` serialization/deserialization to tolerate legacy payloads.
+- Add shutdown cleanup to close Slack `AsyncWebClient`/`SocketModeClient` sessions.
+- Verify OpenCode HTTP session is closed on shutdown.
+- Run minimal validation (launch service, check log for removed errors).
diff --git a/modules/agent_router.py b/modules/agent_router.py
index 89c66f306..c7e1a551a 100644
--- a/modules/agent_router.py
+++ b/modules/agent_router.py
@@ -31,32 +31,7 @@ class AgentRouter:
routes: Dict[str, PlatformRoute] = {}
global_default = "claude"
- if file_path and os.path.exists(file_path):
- try:
- data = cls._load_file(file_path)
- global_default = data.get("default", global_default)
- for key, value in data.items():
- if key == "default":
- continue
- if not isinstance(value, dict):
- continue
- routes[key] = PlatformRoute(
- default=value.get("default", global_default),
- overrides=value.get("overrides", {}) or {},
- )
- logger.info(
- f"Loaded agent routing config from {file_path} "
- f"(platforms: {list(routes.keys())})"
- )
- except Exception as e:
- logger.error(f"Failed to parse agent route config {file_path}: {e}")
- else:
- if file_path:
- logger.warning(
- f"Agent route config file not found at {file_path}, using defaults"
- )
-
- # Ensure platform entry exists
+ # File-based routing removed; keep defaults only.
routes.setdefault(platform, PlatformRoute(default=global_default))
return cls(routes, global_default=global_default)
diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.py
index a7b78cc2a..f3756db95 100644
--- a/modules/agents/claude_agent.py
+++ b/modules/agents/claude_agent.py
@@ -65,9 +65,10 @@ class ClaudeAgent(BaseAgent):
async def clear_sessions(self, settings_key: str) -> int:
"""Clear Claude sessions scoped to the provided settings key."""
- settings = self.settings_manager.get_user_settings(settings_key)
- claude_map = settings.session_mappings.get(self.name, {})
- session_bases_to_clear = set(claude_map.keys())
+ agent_map = self.settings_manager.sessions_store.get_agent_map(
+ settings_key, self.name
+ )
+ session_bases_to_clear = set(agent_map.keys())
self.settings_manager.clear_agent_sessions(settings_key, self.name)
diff --git a/modules/agents/opencode_agent.py b/modules/agents/opencode_agent.py
index 5e0c4d56d..6db7504a9 100644
--- a/modules/agents/opencode_agent.py
+++ b/modules/agents/opencode_agent.py
@@ -23,6 +23,99 @@ DEFAULT_OPENCODE_HOST = "127.0.0.1"
SERVER_START_TIMEOUT = 15
+_REASONING_FALLBACK_OPTIONS = [
+ {"value": "low", "label": "Low"},
+ {"value": "medium", "label": "Medium"},
+ {"value": "high", "label": "High"},
+]
+
+_REASONING_VARIANT_ORDER = ["none", "minimal", "low", "medium", "high", "xhigh", "max"]
+
+_REASONING_VARIANT_LABELS = {
+ "none": "None",
+ "minimal": "Minimal",
+ "low": "Low",
+ "medium": "Medium",
+ "high": "High",
+ "xhigh": "Extra High",
+ "max": "Max",
+}
+
+
+def _parse_model_key(model_key: Optional[str]) -> tuple[str, str]:
+ if not model_key:
+ return "", ""
+ parts = model_key.split("/", 1)
+ if len(parts) != 2:
+ return "", ""
+ return parts[0], parts[1]
+
+
+def _find_model_variants(opencode_models: dict, target_model: Optional[str]) -> Dict[str, Any]:
+ target_provider, target_model_id = _parse_model_key(target_model)
+ if not target_provider or not target_model_id or not isinstance(opencode_models, dict):
+ return {}
+ providers_data = opencode_models.get("providers", [])
+ for provider in providers_data:
+ provider_id = provider.get("id") or provider.get("provider_id") or provider.get("name")
+ if provider_id != target_provider:
+ continue
+
+ models = provider.get("models", {})
+ model_info: Optional[dict] = None
+ if isinstance(models, dict):
+ candidate = models.get(target_model_id)
+ if isinstance(candidate, dict):
+ model_info = candidate
+ elif isinstance(models, list):
+ for entry in models:
+ if isinstance(entry, dict) and entry.get("id") == target_model_id:
+ model_info = entry
+ break
+
+ if isinstance(model_info, dict):
+ variants = model_info.get("variants", {})
+ if isinstance(variants, dict):
+ return variants
+ break
+ return {}
+
+
+def _build_reasoning_options_from_variants(variants: Dict[str, Any]) -> List[Dict[str, str]]:
+ sorted_variants = sorted(
+ variants.keys(),
+ key=lambda variant: (
+ _REASONING_VARIANT_ORDER.index(variant)
+ if variant in _REASONING_VARIANT_ORDER
+ else len(_REASONING_VARIANT_ORDER),
+ variant,
+ ),
+ )
+ return [
+ {
+ "value": variant_key,
+ "label": _REASONING_VARIANT_LABELS.get(
+ variant_key, variant_key.capitalize()
+ ),
+ }
+ for variant_key in sorted_variants
+ ]
+
+
+def build_reasoning_effort_options(
+ opencode_models: dict,
+ target_model: Optional[str],
+) -> List[Dict[str, str]]:
+ """Build reasoning effort options from OpenCode model metadata."""
+ options = [{"value": "__default__", "label": "(Default)"}]
+ variants = _find_model_variants(opencode_models, target_model)
+ if variants:
+ options.extend(_build_reasoning_options_from_variants(variants))
+ return options
+ options.extend(_REASONING_FALLBACK_OPTIONS)
+ return options
+
+
class OpenCodeServerManager:
"""Manages a singleton OpenCode server process shared across all working directories."""
@@ -42,6 +135,7 @@ class OpenCodeServerManager:
self._process: Optional[Process] = None
self._base_url: Optional[str] = None
self._http_session: Optional[aiohttp.ClientSession] = None
+ self._http_session_loop: Optional[asyncio.AbstractEventLoop] = None
self._lock = asyncio.Lock()
self._pid_file = (
Path(__file__).resolve().parents[2] / "logs" / "opencode_server.json"
@@ -91,6 +185,7 @@ class OpenCodeServerManager:
self._http_session = aiohttp.ClientSession(
timeout=aiohttp.ClientTimeout(total=total_timeout)
)
+ self._http_session_loop = asyncio.get_running_loop()
return self._http_session
def _read_pid_file(self) -> Optional[Dict[str, Any]]:
@@ -344,6 +439,7 @@ class OpenCodeServerManager:
if self._http_session:
await self._http_session.close()
self._http_session = None
+ self._http_session_loop = None
if self._process and self._process.returncode is None:
self._process.terminate()
@@ -365,6 +461,18 @@ class OpenCodeServerManager:
self._process = None
def stop_sync(self) -> None:
+ if self._http_session and self._http_session_loop:
+ try:
+ future = asyncio.run_coroutine_threadsafe(
+ self._http_session.close(), self._http_session_loop
+ )
+ future.result(timeout=5)
+ except Exception as e:
+ logger.debug(f"Failed to close OpenCode HTTP session: {e}")
+ finally:
+ self._http_session = None
+ self._http_session_loop = None
+
if self._process and self._process.returncode is None:
self._process.terminate()
logger.info("OpenCode server terminated (sync)")
@@ -790,7 +898,7 @@ class OpenCodeServerManager:
Default agent name (e.g., "build", "plan"), or "build" as fallback.
"""
# OpenCode doesn't have an explicit "default agent" config field.
- # Users can override via channel settings or agent_routes.yaml.
+ # Users can override via channel settings.
# Default to "build" agent which uses the agent's configured model,
# avoiding fallback to global model which may use restricted credentials.
return "build"
@@ -1318,7 +1426,7 @@ class OpenCodeAgent(BaseAgent):
)
try:
- # Get per-channel overrides from user_settings.json
+ # Get per-channel overrides from settings.json
override_agent, override_model, override_reasoning = (
self.controller.get_opencode_overrides(request.context)
)
diff --git a/modules/im/base.py b/modules/im/base.py
index 9259b61ef..9568def67 100644
--- a/modules/im/base.py
+++ b/modules/im/base.py
@@ -222,6 +222,10 @@ class BaseIMClient(ABC):
def run(self):
"""Start the bot/client"""
pass
+
+ async def shutdown(self) -> None:
+ """Best-effort async shutdown for platform resources."""
+ return None
@abstractmethod
async def get_user_info(self, user_id: str) -> Dict[str, Any]:
diff --git a/modules/im/slack.py b/modules/im/slack.py
index 55126b07c..b803bcccb 100644
--- a/modules/im/slack.py
+++ b/modules/im/slack.py
@@ -1,4 +1,5 @@
import asyncio
+import asyncio
import hashlib
import logging
import time
@@ -25,8 +26,8 @@ class SlackBot(BaseIMClient):
def __init__(self, config: SlackConfig):
super().__init__(config)
self.config = config
- self.web_client = None
- self.socket_client = None
+ self.web_client: Optional[AsyncWebClient] = None
+ self.socket_client: Optional[SocketModeClient] = None
# Initialize Slack formatter
self.formatter = SlackFormatter()
@@ -46,6 +47,8 @@ class SlackBot(BaseIMClient):
# Settings manager for thread tracking (will be injected later)
self.settings_manager = None
self._recent_event_ids: Dict[str, float] = {}
+ self._stop_event: Optional[asyncio.Event] = None
+ self._loop: Optional[asyncio.AbstractEventLoop] = None
def set_settings_manager(self, settings_manager):
"""Set the settings manager for thread tracking"""
@@ -795,21 +798,21 @@ class SlackBot(BaseIMClient):
user_id = payload.get("user", {}).get("id")
values = view.get("state", {}).get("values", {})
- # Extract selected hidden message types
- hidden_types_data = values.get("hidden_message_types", {}).get(
- "hidden_types_select", {}
+ # Extract selected show message types
+ show_types_data = values.get("show_message_types", {}).get(
+ "show_types_select", {}
)
- selected_options = hidden_types_data.get("selected_options", [])
+ selected_options = show_types_data.get("selected_options", [])
# Get the values from selected options
- hidden_types = [opt.get("value") for opt in selected_options]
+ show_types = [opt.get("value") for opt in selected_options]
# Get channel_id from the view's private_metadata if available
channel_id = view.get("private_metadata")
# Update settings - need access to settings manager
if hasattr(self, "_on_settings_update"):
- await self._on_settings_update(user_id, hidden_types, channel_id)
+ await self._on_settings_update(user_id, show_types, channel_id)
elif callback_id == "change_cwd_modal":
# Handle change CWD modal submission
@@ -930,20 +933,82 @@ class SlackBot(BaseIMClient):
async def start():
self._ensure_clients()
self.register_handlers()
+ self._loop = asyncio.get_running_loop()
+ self._stop_event = asyncio.Event()
await self.socket_client.connect()
- await asyncio.sleep(float("inf"))
+ await self._stop_event.wait()
+ await self._async_close()
asyncio.run(start())
else:
# Web API only mode (for development/testing)
logger.warning("No app token provided, running in Web API only mode")
- # In this mode, you would typically run a web server to receive events
- # For now, just keep the program running
+
+ async def start():
+ self._ensure_clients()
+ self._loop = asyncio.get_running_loop()
+ self._stop_event = asyncio.Event()
+ await self._stop_event.wait()
+ await self._async_close()
+
try:
- asyncio.run(asyncio.sleep(float("inf")))
+ asyncio.run(start())
except KeyboardInterrupt:
logger.info("Shutting down...")
+ def stop(self) -> None:
+ if self._stop_event is None:
+ return
+ if self._loop and self._loop.is_running():
+ self._loop.call_soon_threadsafe(self._stop_event.set)
+ else:
+ self._stop_event.set()
+
+ async def shutdown(self) -> None:
+ """Best-effort async shutdown for Slack clients."""
+ if self._stop_event is not None:
+ self._stop_event.set()
+
+ try:
+ current_loop = asyncio.get_running_loop()
+ except RuntimeError:
+ current_loop = None
+
+ if self._loop and self._loop.is_running() and self._loop is not current_loop:
+ try:
+ future = asyncio.run_coroutine_threadsafe(self._async_close(), self._loop)
+ future.result(timeout=5)
+ except Exception as exc:
+ logger.debug(f"Slack shutdown dispatch failed: {exc}")
+ return
+
+ await self._async_close()
+
+ async def _async_close(self) -> None:
+ if self.socket_client is not None:
+ try:
+ disconnect = getattr(self.socket_client, "disconnect", None)
+ if callable(disconnect):
+ result = disconnect()
+ if asyncio.iscoroutine(result):
+ await result
+ except Exception as exc:
+ logger.debug(f"Socket mode disconnect failed: {exc}")
+ try:
+ close = getattr(self.socket_client, "close", None)
+ if callable(close):
+ result = close()
+ if asyncio.iscoroutine(result):
+ await result
+ except Exception as exc:
+ logger.debug(f"Socket mode close failed: {exc}")
+
+ if self.web_client is not None:
+ try:
+ await self.web_client.close()
+ except Exception as exc:
+ logger.debug(f"Slack web client close failed: {exc}")
+
async def get_user_info(self, user_id: str) -> Dict[str, Any]:
"""Get information about a Slack user"""
self._ensure_clients()
@@ -1024,14 +1089,14 @@ class SlackBot(BaseIMClient):
}
options.append(option)
- # If this type is hidden, add THE SAME option object to selected options
- if msg_type in user_settings.hidden_message_types:
+ # If this type is shown, add THE SAME option object to selected options
+ if msg_type in user_settings.show_message_types:
selected_options.append(option) # Same object reference!
logger.info(
f"Creating modal with {len(options)} options, {len(selected_options)} selected"
)
- logger.info(f"Hidden types: {user_settings.hidden_message_types}")
+ logger.info(f"Show types: {user_settings.show_message_types}")
# Debug: Log the actual data being sent
import json
@@ -1044,11 +1109,11 @@ class SlackBot(BaseIMClient):
"type": "multi_static_select",
"placeholder": {
"type": "plain_text",
- "text": "Select message types to hide",
+ "text": "Select message types to show",
"emoji": True,
},
"options": options,
- "action_id": "hidden_types_select",
+ "action_id": "show_types_select",
}
# Only add initial_options if there are selected options
@@ -1076,17 +1141,17 @@ class SlackBot(BaseIMClient):
"type": "section",
"text": {
"type": "mrkdwn",
- "text": "Choose which message types to *hide* from agent output. Hidden messages won't appear in your Slack workspace.",
+ "text": "Choose which message types to *show* from agent output. Unselected types won't appear in your Slack workspace.",
},
},
{"type": "divider"},
{
"type": "input",
- "block_id": "hidden_message_types",
+ "block_id": "show_message_types",
"element": multi_select_element,
"label": {
"type": "plain_text",
- "text": "Hide these message types:",
+ "text": "Show these message types:",
"emoji": True,
},
"optional": True,
@@ -1847,20 +1912,19 @@ class SlackBot(BaseIMClient):
async def _is_authorized_channel(self, channel_id: str) -> bool:
"""Check if a channel is authorized based on whitelist configuration"""
- target_channel = self.config.target_channels
+ if not self.settings_manager:
+ logger.warning("No settings_manager configured; rejecting by default")
+ return False
- # If None/null, accept all channels
- if target_channel is None:
- return True
+ settings = self.settings_manager.get_channel_settings(channel_id)
+ if settings is None:
+ logger.warning("No channel settings found; rejecting by default")
+ return False
- # If list with IDs, check whitelist
- if isinstance(target_channel, list):
- return channel_id in target_channel
+ if settings.enabled:
+ return True
- # Unexpected type: be conservative and reject
- logger.warning(
- f"Unexpected target_channel type: {type(target_channel)}; rejecting by default"
- )
+ logger.info("Channel not enabled in settings.json: %s", channel_id)
return False
async def _send_unauthorized_message(self, channel_id: str):
diff --git a/modules/settings_manager.py b/modules/settings_manager.py
index 98d0bb744..0ac2a4e44 100644
--- a/modules/settings_manager.py
+++ b/modules/settings_manager.py
@@ -1,19 +1,20 @@
-import json
import logging
-import os
+import hashlib
+import logging
import time
-from dataclasses import dataclass, asdict, field
+from dataclasses import asdict, dataclass, field
from typing import Any, Dict, List, Optional, Union
from pathlib import Path
from config import paths
from config.v2_sessions import SessionsStore
+from config.v2_settings import SettingsStore, ChannelSettings, RoutingSettings
logger = logging.getLogger(__name__)
-DEFAULT_HIDDEN_MESSAGE_TYPES = ["system", "assistant", "toolcall"]
+DEFAULT_SHOW_MESSAGE_TYPES: List[str] = []
@dataclass
@@ -44,27 +45,40 @@ class ChannelRouting:
@dataclass
class UserSettings:
- hidden_message_types: List[str] = field(
- default_factory=lambda: DEFAULT_HIDDEN_MESSAGE_TYPES.copy()
+ show_message_types: List[str] = field(
+ default_factory=lambda: DEFAULT_SHOW_MESSAGE_TYPES.copy()
)
custom_cwd: Optional[str] = None
channel_routing: Optional[ChannelRouting] = None
+ enabled: bool = True
def to_dict(self) -> dict:
"""Convert to dictionary for JSON serialization"""
- result = asdict(self)
- # Handle ChannelRouting serialization
+ result = {
+ "show_message_types": self.show_message_types,
+ "custom_cwd": self.custom_cwd,
+ }
if self.channel_routing is not None:
- result["channel_routing"] = self.channel_routing.to_dict()
+ result["routing"] = self.channel_routing.to_dict()
return result
@classmethod
def from_dict(cls, data: dict) -> "UserSettings":
"""Create from dictionary"""
- # Handle channel_routing deserialization
- routing_data = data.pop("channel_routing", None)
- settings = cls(**data)
- if routing_data:
+ if data is None:
+ return cls()
+ payload = dict(data)
+ routing_data = payload.pop("routing", None)
+ show_message_types = payload.get("show_message_types")
+ settings = cls(
+ show_message_types=(
+ show_message_types
+ if show_message_types is not None
+ else DEFAULT_SHOW_MESSAGE_TYPES.copy()
+ ),
+ custom_cwd=payload.get("custom_cwd"),
+ )
+ if routing_data is not None:
settings.channel_routing = ChannelRouting.from_dict(routing_data)
return settings
@@ -73,10 +87,6 @@ class SettingsManager:
"""Manages user personalization settings with JSON persistence"""
MESSAGE_TYPE_ALIASES = {
- # Legacy/compat aliases
- "response": "toolcall",
- "user": "toolcall",
- # Normalize common variants
"tool_call": "toolcall",
"tool": "toolcall",
}
@@ -84,7 +94,10 @@ class SettingsManager:
def __init__(self, settings_file: Optional[str] = None):
paths.ensure_data_dirs()
self.settings_file = Path(settings_file) if settings_file else paths.get_settings_path()
+ self._settings_mtime_ns: Optional[int] = None
+ self._settings_fingerprint: Optional[str] = None
self.settings: Dict[Union[int, str], UserSettings] = {}
+ self.store = SettingsStore(self.settings_file)
self.sessions_store = SessionsStore()
self.sessions_store.load()
self._load_settings()
@@ -100,37 +113,106 @@ class SettingsManager:
"""
return str(user_id)
+ def _from_channel_settings(self, channel_settings: ChannelSettings) -> UserSettings:
+ routing = ChannelRouting(
+ agent_backend=channel_settings.routing.agent_backend,
+ opencode_agent=channel_settings.routing.opencode_agent,
+ opencode_model=channel_settings.routing.opencode_model,
+ opencode_reasoning_effort=channel_settings.routing.opencode_reasoning_effort,
+ )
+ return UserSettings(
+ show_message_types=self._normalize_show_message_types(
+ channel_settings.show_message_types
+ ),
+ custom_cwd=channel_settings.custom_cwd,
+ channel_routing=routing,
+ enabled=channel_settings.enabled,
+ )
+
+ def _to_channel_settings(self, settings: UserSettings) -> ChannelSettings:
+ routing = settings.channel_routing or ChannelRouting()
+ return ChannelSettings(
+ enabled=settings.enabled,
+ show_message_types=self._normalize_show_message_types(
+ settings.show_message_types
+ ),
+ custom_cwd=settings.custom_cwd,
+ routing=RoutingSettings(
+ agent_backend=routing.agent_backend,
+ opencode_agent=routing.opencode_agent,
+ opencode_model=routing.opencode_model,
+ opencode_reasoning_effort=routing.opencode_reasoning_effort,
+ ),
+ )
+
def _load_settings(self):
"""Load settings from JSON file"""
+ self.store = SettingsStore(self.settings_file)
+ self.settings = {}
+
+ if not self.store.settings.channels:
+ logger.info("No settings file found, starting with empty settings")
+ return
+
+ for channel_id, channel_settings in self.store.settings.channels.items():
+ self.settings[str(channel_id)] = self._from_channel_settings(channel_settings)
+
try:
- if self.settings_file.exists():
- with open(self.settings_file, "r") as f:
- data = json.load(f)
- for user_id_str, user_data in data.items():
- user_id = user_id_str
- settings = UserSettings.from_dict(user_data)
- settings.hidden_message_types = self._normalize_hidden_message_types(
- settings.hidden_message_types
- )
- self.settings[user_id] = settings
-
- logger.info(f"Loaded settings for {len(self.settings)} users")
- else:
- logger.info("No settings file found, starting with empty settings")
- except Exception as e:
- logger.error(f"Error loading settings: {e}")
- self.settings = {}
+ self._settings_mtime_ns = self.settings_file.stat().st_mtime_ns
+ self._settings_fingerprint = self._compute_settings_fingerprint()
+ except FileNotFoundError:
+ self._settings_mtime_ns = None
+ self._settings_fingerprint = None
+
+ logger.info(f"Loaded settings for {len(self.settings)} channels")
+ def _compute_settings_fingerprint(self) -> Optional[str]:
+ try:
+ data = self.settings_file.read_bytes()
+ except FileNotFoundError:
+ return None
+ return hashlib.sha256(data).hexdigest()
+
+ def _reload_if_changed(self) -> None:
+ if not self.settings_file.exists():
+ return
+ try:
+ mtime_ns = self.settings_file.stat().st_mtime_ns
+ except FileNotFoundError:
+ return
+ fingerprint = None
+ if self._settings_mtime_ns is None or mtime_ns != self._settings_mtime_ns:
+ fingerprint = self._compute_settings_fingerprint()
+ elif self._settings_fingerprint is None:
+ fingerprint = self._compute_settings_fingerprint()
+ if fingerprint and fingerprint != self._settings_fingerprint:
+ logger.info("Settings file changed on disk, reloading")
+ self._load_settings()
+ elif fingerprint:
+ self._settings_fingerprint = fingerprint
+ self._settings_mtime_ns = mtime_ns
+ else:
+ self._settings_mtime_ns = mtime_ns
+
def _save_settings(self):
"""Save settings to JSON file"""
try:
- data = {
- str(user_id): settings.to_dict()
- for user_id, settings in self.settings.items()
- }
- with open(self.settings_file, "w") as f:
- json.dump(data, f, indent=2)
+ channels: Dict[str, ChannelSettings] = {}
+ for settings_key, settings in self.settings.items():
+ existing = self.store.settings.channels.get(str(settings_key))
+ channel_settings = self._to_channel_settings(settings)
+ if existing is not None:
+ channel_settings.enabled = existing.enabled
+ channels[str(settings_key)] = channel_settings
+ self.store.settings.channels = channels
+ self.store.save()
+ try:
+ self._settings_mtime_ns = self.settings_file.stat().st_mtime_ns
+ self._settings_fingerprint = self._compute_settings_fingerprint()
+ except FileNotFoundError:
+ self._settings_mtime_ns = None
+ self._settings_fingerprint = None
logger.info("Settings saved successfully")
except Exception as e:
logger.error(f"Error saving settings: {e}")
@@ -139,9 +221,16 @@ class SettingsManager:
"""Get settings for a specific user"""
normalized_id = self._normalize_user_id(user_id)
+ self._reload_if_changed()
+
# Return existing or create new
if normalized_id not in self.settings:
- self.settings[normalized_id] = UserSettings()
+ settings = UserSettings()
+ if normalized_id in self.store.settings.channels:
+ settings = self._from_channel_settings(
+ self.store.settings.channels[normalized_id]
+ )
+ self.settings[normalized_id] = settings
self._save_settings()
return self.settings[normalized_id]
@@ -149,29 +238,29 @@ class SettingsManager:
"""Update settings for a specific user"""
normalized_id = self._normalize_user_id(user_id)
- settings.hidden_message_types = self._normalize_hidden_message_types(
- settings.hidden_message_types
+ settings.show_message_types = self._normalize_show_message_types(
+ settings.show_message_types
)
self.settings[normalized_id] = settings
self._save_settings()
- def toggle_hidden_message_type(
+ def toggle_show_message_type(
self, user_id: Union[int, str], message_type: str
) -> bool:
- """Toggle a message type in hidden list, returns new state"""
+ """Toggle a message type in show list, returns new state (True if now shown)"""
message_type = self._canonicalize_message_type(message_type)
settings = self.get_user_settings(user_id)
- if message_type in settings.hidden_message_types:
- settings.hidden_message_types.remove(message_type)
- is_hidden = False
+ if message_type in settings.show_message_types:
+ settings.show_message_types.remove(message_type)
+ is_shown = False
else:
- settings.hidden_message_types.append(message_type)
- is_hidden = True
+ settings.show_message_types.append(message_type)
+ is_shown = True
self.update_user_settings(user_id, settings)
- return is_hidden
+ return is_shown
def set_custom_cwd(self, user_id: Union[int, str], cwd: str):
"""Set custom working directory for user"""
@@ -184,13 +273,20 @@ class SettingsManager:
settings = self.get_user_settings(user_id)
return settings.custom_cwd
+ def get_channel_settings(self, channel_id: Union[int, str]) -> Optional[ChannelSettings]:
+ """Get raw ChannelSettings for a channel without creating defaults."""
+ self._reload_if_changed()
+ key = str(channel_id)
+ return self.store.settings.channels.get(key)
+
def is_message_type_hidden(
self, user_id: Union[int, str], message_type: str
) -> bool:
- """Check if a message type is hidden for user"""
+ """Check if a message type is hidden for user (not in show_message_types)"""
+ self._reload_if_changed()
message_type = self._canonicalize_message_type(message_type)
settings = self.get_user_settings(user_id)
- return message_type in settings.hidden_message_types
+ return message_type not in settings.show_message_types
def save_user_settings(self, user_id: Union[int, str], settings: UserSettings):
"""Save settings for a specific user (alias for update_user_settings)"""
@@ -227,7 +323,7 @@ class SettingsManager:
agent_map[base_session_id][working_path] = session_id
self.sessions_store.save()
logger.info(
- f"Stored {agent_name} session mapping for user {user_id}: "
+ f"Stored {agent_name} session mapping for {user_id}: "
f"{base_session_id}[{working_path}] -> {session_id}"
)
@@ -249,13 +345,15 @@ class SettingsManager:
"""Normalize message type to canonical form to support aliases."""
return self.MESSAGE_TYPE_ALIASES.get(message_type, message_type)
- def _normalize_hidden_message_types(self, hidden_message_types: List[str]) -> List[str]:
- """Normalize and migrate hidden message types to current canonical schema."""
+ def _normalize_show_message_types(self, show_message_types: Optional[List[str]]) -> List[str]:
+ """Normalize and migrate show message types to current canonical schema."""
allowed = {"system", "assistant", "toolcall"}
+ if show_message_types is None:
+ return DEFAULT_SHOW_MESSAGE_TYPES.copy()
normalized: List[str] = []
seen = set()
- for msg_type in hidden_message_types or []:
+ for msg_type in show_message_types or []:
canonical = self._canonicalize_message_type(msg_type)
if canonical not in allowed:
continue
@@ -428,6 +526,7 @@ class SettingsManager:
self, settings_key: Union[int, str]
) -> Optional[ChannelRouting]:
"""Get channel routing override for the given settings key."""
+ self._reload_if_changed()
settings = self.get_user_settings(settings_key)
return settings.channel_routing
@@ -446,7 +545,7 @@ class SettingsManager:
)
def clear_channel_routing(self, settings_key: Union[int, str]):
- """Clear channel routing override (fall back to agent_routes.yaml)."""
+ """Clear channel routing override (fall back to default backend)."""
settings = self.get_user_settings(settings_key)
if settings.channel_routing:
settings.channel_routing = None
diff --git a/ui/index.html b/ui/index.html
index 1b71ee3fd..0ce4d2cb5 100644
--- a/ui/index.html
+++ b/ui/index.html
@@ -2,7 +2,7 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
- <link rel="icon" type="image/svg+xml" href="/vite.svg" />
+ <link rel="icon" type="image/png" href="/logo.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vibe Remote</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
diff --git a/ui/public/logo.png b/ui/public/logo.png
new file mode 100644
index 000000000..16d20f161
Binary files /dev/null and b/ui/public/logo.png differ
diff --git a/ui/src/App.tsx b/ui/src/App.tsx
index 1a1838602..c92fce1c6 100644
--- a/ui/src/App.tsx
+++ b/ui/src/App.tsx
@@ -4,8 +4,10 @@ import { AppShell } from './components/AppShell';
import { Dashboard } from './components/Dashboard';
import { ChannelList } from './components/steps/ChannelList';
import { DoctorPanel } from './components/steps/DoctorPanel';
+import { LogsPanel } from './components/steps/LogsPanel';
import { StatusProvider } from './context/StatusContext';
import { ApiProvider, useApi } from './context/ApiContext';
+import { ToastProvider } from './context/ToastContext';
import { useEffect, useState } from 'react';
// Wrapper to check if setup is needed
@@ -42,6 +44,7 @@ function AppRoutes() {
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/channels" element={<ChannelList isPage />} />
<Route path="/doctor" element={<DoctorPanel isPage />} />
+ <Route path="/doctor/logs" element={<LogsPanel />} />
<Route path="/" element={<Navigate to="/dashboard" replace />} />
</Route>
</Routes>
@@ -52,9 +55,11 @@ function App() {
return (
<StatusProvider>
<ApiProvider>
- <BrowserRouter>
- <AppRoutes />
- </BrowserRouter>
+ <ToastProvider>
+ <BrowserRouter>
+ <AppRoutes />
+ </BrowserRouter>
+ </ToastProvider>
</ApiProvider>
</StatusProvider>
);
diff --git a/ui/src/components/steps/ChannelList.tsx b/ui/src/components/steps/ChannelList.tsx
index f4d82f017..430e7c801 100644
--- a/ui/src/components/steps/ChannelList.tsx
+++ b/ui/src/components/steps/ChannelList.tsx
@@ -14,7 +14,7 @@ interface ChannelListProps {
interface ChannelConfig {
enabled: boolean;
- hidden_message_types: string[];
+ show_message_types: string[];
custom_cwd: string;
routing: {
agent_backend: string | null;
@@ -132,8 +132,8 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
const updateConfig = (channelId: string, patch: Partial<ChannelConfig>) => {
const base = configs[channelId] || defaultConfig();
const next = { ...base, ...patch };
- if (!next.hidden_message_types || next.hidden_message_types.length === 0) {
- next.hidden_message_types = defaultConfig().hidden_message_types;
+ if (!next.show_message_types) {
+ next.show_message_types = defaultConfig().show_message_types;
}
if (!next.routing || typeof next.routing !== 'object') {
next.routing = { agent_backend: config.agents?.default_backend || 'opencode' };
@@ -145,7 +145,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
const defaultConfig = (): ChannelConfig => ({
enabled: false,
- hidden_message_types: ['system', 'assistant', 'toolcall'],
+ show_message_types: [],
custom_cwd: '',
routing: {
agent_backend: config.agents?.default_backend || 'opencode',
@@ -212,7 +212,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
...def,
...rawConfig,
enabled: isChannelEnabled(channel.id),
- hidden_message_types: rawConfig.hidden_message_types || def.hidden_message_types,
+ show_message_types: rawConfig.show_message_types || def.show_message_types,
routing: {
...def.routing,
...(rawConfig.routing || {}),
@@ -280,12 +280,12 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
</div>
</div>
- {/* Hidden Message Types */}
+ {/* Show Message Types */}
<div className="space-y-2">
- <div className="text-xs font-medium text-muted uppercase">{t('channelList.hiddenMessageTypes')}</div>
+ <div className="text-xs font-medium text-muted uppercase">{t('channelList.showMessageTypes')}</div>
<div className="flex flex-wrap gap-3 text-sm">
{['system', 'assistant', 'toolcall'].map((msgType) => {
- const checked = channelConfig.hidden_message_types.includes(msgType);
+ const checked = channelConfig.show_message_types.includes(msgType);
return (
<label key={msgType} className="flex items-center gap-2 text-text">
<input
@@ -293,9 +293,9 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
checked={checked}
onChange={() => {
const next = checked
- ? channelConfig.hidden_message_types.filter((value) => value !== msgType)
- : [...channelConfig.hidden_message_types, msgType];
- updateConfig(channel.id, { hidden_message_types: next });
+ ? channelConfig.show_message_types.filter((value) => value !== msgType)
+ : [...channelConfig.show_message_types, msgType];
+ updateConfig(channel.id, { show_message_types: next });
}}
className="h-4 w-4 rounded border-border text-accent focus:ring-accent"
/>
diff --git a/ui/src/components/steps/Summary.tsx b/ui/src/components/steps/Summary.tsx
index bb42a23ac..f094617be 100644
--- a/ui/src/components/steps/Summary.tsx
+++ b/ui/src/components/steps/Summary.tsx
@@ -153,7 +153,7 @@ const buildSettingsPayload = (data: any) => {
id,
{
enabled: cfg.enabled,
- hidden_message_types: cfg.hidden_message_types || ['system', 'toolcall'],
+ show_message_types: cfg.show_message_types || [],
custom_cwd: cfg.custom_cwd || null,
routing: {
agent_backend: cfg.routing?.agent_backend || null,
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 6a740f170..426b81c01 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -10,6 +10,14 @@ export type ApiContextType = {
slackChannels: (botToken: string) => Promise<any>;
doctor: () => Promise<any>;
opencodeOptions: (cwd: string) => Promise<any>;
+ getLogs: (lines?: number) => Promise<{ logs: LogEntry[]; total: number }>;
+};
+
+export type LogEntry = {
+ timestamp: string;
+ level: string;
+ logger: string;
+ message: string;
};
const ApiContext = createContext<ApiContextType | undefined>(undefined);
@@ -49,6 +57,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
slackChannels: (botToken) => postJson('/slack/channels', { bot_token: botToken }),
doctor: () => postJson('/doctor', {}),
opencodeOptions: (cwd) => postJson('/opencode/options', { cwd }),
+ getLogs: (lines = 500) => postJson('/logs', { lines }),
};
return <ApiContext.Provider value={value}>{children}</ApiContext.Provider>;
diff --git a/ui/src/context/ToastContext.tsx b/ui/src/context/ToastContext.tsx
new file mode 100644
index 000000000..85f85d84c
--- /dev/null
+++ b/ui/src/context/ToastContext.tsx
@@ -0,0 +1,76 @@
+import React, { createContext, useContext, useState, useCallback } from 'react';
+import { CheckCircle, XCircle, X } from 'lucide-react';
+
+type ToastType = 'success' | 'error';
+
+interface Toast {
+ id: number;
+ message: string;
+ type: ToastType;
+}
+
+interface ToastContextType {
+ showToast: (message: string, type?: ToastType) => void;
+}
+
+const ToastContext = createContext<ToastContextType | null>(null);
+
+let toastId = 0;
+
+export const ToastProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
+ const [toasts, setToasts] = useState<Toast[]>([]);
+
+ const showToast = useCallback((message: string, type: ToastType = 'success') => {
+ const id = ++toastId;
+ setToasts((prev) => [...prev, { id, message, type }]);
+
+ // Auto dismiss after 3 seconds
+ setTimeout(() => {
+ setToasts((prev) => prev.filter((t) => t.id !== id));
+ }, 3000);
+ }, []);
+
+ const dismissToast = useCallback((id: number) => {
+ setToasts((prev) => prev.filter((t) => t.id !== id));
+ }, []);
+
+ return (
+ <ToastContext.Provider value={{ showToast }}>
+ {children}
+ {/* Toast container - fixed at bottom right */}
+ <div className="fixed bottom-4 right-4 z-50 flex flex-col gap-2">
+ {toasts.map((toast) => (
+ <div
+ key={toast.id}
+ className={`flex items-center gap-3 px-4 py-3 rounded-lg shadow-lg border animate-slide-in ${
+ toast.type === 'success'
+ ? 'bg-success/10 border-success/30 text-success'
+ : 'bg-error/10 border-error/30 text-error'
+ }`}
+ >
+ {toast.type === 'success' ? (
+ <CheckCircle size={18} />
+ ) : (
+ <XCircle size={18} />
+ )}
+ <span className="text-sm font-medium">{toast.message}</span>
+ <button
+ onClick={() => dismissToast(toast.id)}
+ className="ml-2 opacity-60 hover:opacity-100 transition-opacity"
+ >
+ <X size={14} />
+ </button>
+ </div>
+ ))}
+ </div>
+ </ToastContext.Provider>
+ );
+};
+
+export const useToast = () => {
+ const context = useContext(ToastContext);
+ if (!context) {
+ throw new Error('useToast must be used within a ToastProvider');
+ }
+ return context;
+};
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 25e9a24f7..ff1e44f34 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -98,7 +98,7 @@
"workingDirectory": "Working Directory",
"useGlobalDefault": "Use global default",
"backend": "Backend",
- "hiddenMessageTypes": "Hidden Message Types",
+ "showMessageTypes": "Show Message Types",
"opencodeSettings": "OpenCode Settings",
"agent": "Agent",
"model": "Model",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 97fe7783f..f6d3e7c22 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -98,7 +98,7 @@
"workingDirectory": "工作目录",
"useGlobalDefault": "使用全局默认值",
"backend": "后端",
- "hiddenMessageTypes": "隐藏的消息类型",
+ "showMessageTypes": "显示的消息类型",
"opencodeSettings": "OpenCode 设置",
"agent": "Agent",
"model": "模型",
diff --git a/ui/src/index.css b/ui/src/index.css
index 34bbbbfa0..4258b1017 100644
--- a/ui/src/index.css
+++ b/ui/src/index.css
@@ -43,3 +43,27 @@ body {
h1, h2, h3, h4, h5, h6 {
font-family: var(--font-display);
}
+
+button, [role="button"] {
+ cursor: pointer;
+}
+
+button:disabled {
+ cursor: not-allowed;
+}
+
+/* Toast animation */
+@keyframes slide-in {
+ from {
+ transform: translateX(100%);
+ opacity: 0;
+ }
+ to {
+ transform: translateX(0);
+ opacity: 1;
+ }
+}
+
+.animate-slide-in {
+ animation: slide-in 0.2s ease-out;
+}
diff --git a/vibe/api.py b/vibe/api.py
index a7007f35a..8572ac47b 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -1,16 +1,33 @@
import json
+import asyncio
+import logging
import os
import shutil
import subprocess
+import time
from pathlib import Path
-from typing import Dict, List
+from typing import Dict, List, Optional
from config import paths
from config.v2_config import V2Config
-from config.v2_settings import SettingsStore, ChannelSettings, RoutingSettings
+from config.v2_settings import (
+ SettingsStore,
+ ChannelSettings,
+ RoutingSettings,
+ normalize_show_message_types,
+)
from config.v2_sessions import SessionsStore
+logger = logging.getLogger(__name__)
+
+_OPENCODE_OPTIONS_CACHE: dict[str, Optional[object]] = {
+ "data": None,
+ "updated_at": 0.0,
+}
+_OPENCODE_OPTIONS_TTL_SECONDS = 30.0
+
+
def load_config() -> V2Config:
return V2Config.load()
@@ -25,12 +42,17 @@ def config_to_payload(config: V2Config) -> dict:
payload = {
"mode": config.mode,
"version": config.version,
- "slack": config.slack.__dict__,
+ "slack": {
+ **config.slack.__dict__,
+ "require_mention": config.slack.require_mention,
+ },
"runtime": {
"default_cwd": config.runtime.default_cwd,
"log_level": config.runtime.log_level,
- "require_mention": config.runtime.require_mention,
- "target_channels": config.runtime.target_channels,
+ },
+ "slack": {
+ **config.slack.__dict__,
+ "require_mention": config.slack.require_mention,
},
"agents": {
"default_backend": config.agents.default_backend,
@@ -41,8 +63,6 @@ def config_to_payload(config: V2Config) -> dict:
"gateway": config.gateway.__dict__ if config.gateway else None,
"ui": config.ui.__dict__,
"ack_mode": config.ack_mode,
- "cleanup_enabled": config.cleanup_enabled,
- "agent_route_file": config.agent_route_file,
}
return payload
@@ -65,8 +85,8 @@ def save_settings(payload: dict) -> dict:
)
channels[channel_id] = ChannelSettings(
enabled=channel_payload.get("enabled", True),
- hidden_message_types=channel_payload.get(
- "hidden_message_types", ["system", "assistant", "toolcall"]
+ show_message_types=normalize_show_message_types(
+ channel_payload.get("show_message_types")
),
custom_cwd=channel_payload.get("custom_cwd"),
routing=routing,
@@ -142,23 +162,84 @@ def list_channels(bot_token: str) -> dict:
def opencode_options(cwd: str) -> dict:
try:
- import asyncio
+ return asyncio.run(opencode_options_async(cwd))
+ except Exception as exc:
+ logger.warning("OpenCode options fetch failed: %s", exc, exc_info=True)
+ return {"ok": False, "error": str(exc)}
+
+
+async def opencode_options_async(cwd: str) -> dict:
+ cache_data = _OPENCODE_OPTIONS_CACHE.get("data")
+ updated_at = _OPENCODE_OPTIONS_CACHE.get("updated_at")
+ updated_at_value = updated_at if isinstance(updated_at, float) else 0.0
+ cache_age = time.monotonic() - updated_at_value
+ if cache_data and cache_age < _OPENCODE_OPTIONS_TTL_SECONDS:
+ return {"ok": True, "data": cache_data, "cached": True}
+
+ try:
from config.v2_compat import to_app_config
- from modules.agents.opencode_agent import OpenCodeAgent
+ from modules.agents.opencode_agent import (
+ OpenCodeServerManager,
+ build_reasoning_effort_options,
+ )
config = to_app_config(V2Config.load())
- agent = OpenCodeAgent(None, config.opencode)
+ if not config.opencode:
+ return {"ok": False, "error": "opencode disabled"}
+ opencode_config = config.opencode
+ timeout_seconds = min(10.0, float(opencode_config.request_timeout_seconds or 10))
- async def _fetch() -> dict:
- server = await agent._get_server()
- await server.ensure_running()
- agents = await server.get_available_agents(cwd)
- models = await server.get_available_models(cwd)
- defaults = await server.get_default_config(cwd)
- return {"agents": agents, "models": models, "defaults": defaults}
+ def _build_reasoning_options(
+ models: dict,
+ builder,
+ ) -> dict:
+ options: dict = {}
+ for provider in models.get("providers", []):
+ provider_id = (
+ provider.get("id")
+ or provider.get("provider_id")
+ or provider.get("name")
+ )
+ if not provider_id:
+ continue
+ model_ids = []
+ provider_models = provider.get("models", {})
+ if isinstance(provider_models, dict):
+ model_ids = list(provider_models.keys())
+ elif isinstance(provider_models, list):
+ model_ids = [
+ model.get("id")
+ for model in provider_models
+ if isinstance(model, dict) and model.get("id")
+ ]
+ for model_id in model_ids:
+ model_key = f"{provider_id}/{model_id}"
+ options[model_key] = builder(models, model_key)
+ return options
- return {"ok": True, "data": asyncio.run(_fetch())}
+ server = await OpenCodeServerManager.get_instance(
+ binary=opencode_config.binary,
+ port=opencode_config.port,
+ request_timeout_seconds=opencode_config.request_timeout_seconds,
+ )
+ await asyncio.wait_for(server.ensure_running(), timeout=timeout_seconds)
+ agents = await asyncio.wait_for(server.get_available_agents(cwd), timeout=timeout_seconds)
+ models = await asyncio.wait_for(server.get_available_models(cwd), timeout=timeout_seconds)
+ defaults = await asyncio.wait_for(server.get_default_config(cwd), timeout=timeout_seconds)
+ reasoning_options = _build_reasoning_options(models, build_reasoning_effort_options)
+ data = {
+ "agents": agents,
+ "models": models,
+ "defaults": defaults,
+ "reasoning_options": reasoning_options,
+ }
+ _OPENCODE_OPTIONS_CACHE["data"] = data
+ _OPENCODE_OPTIONS_CACHE["updated_at"] = time.monotonic()
+ return {"ok": True, "data": data}
except Exception as exc:
+ logger.warning("OpenCode options fetch failed: %s", exc, exc_info=True)
+ if cache_data:
+ return {"ok": True, "data": cache_data, "cached": True, "warning": str(exc)}
return {"ok": False, "error": str(exc)}
@@ -167,7 +248,9 @@ def _settings_to_payload(store: SettingsStore) -> dict:
for channel_id, settings in store.settings.channels.items():
payload["channels"][channel_id] = {
"enabled": settings.enabled,
- "hidden_message_types": settings.hidden_message_types,
+ "show_message_types": normalize_show_message_types(
+ settings.show_message_types
+ ),
"custom_cwd": settings.custom_cwd,
"routing": {
"agent_backend": settings.routing.agent_backend,
diff --git a/vibe/cli.py b/vibe/cli.py
index 2aebf9031..9037d1f33 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -77,13 +77,25 @@ def _write_status(state, detail=None):
_write_json(paths.get_runtime_status_path(), payload)
-def _spawn_background(args, pid_path):
+def _spawn_background(
+ args,
+ pid_path,
+ stdout_name: str = "service_stdout.log",
+ stderr_name: str = "service_stderr.log",
+):
+ stdout_path = paths.get_runtime_dir() / stdout_name
+ stderr_path = paths.get_runtime_dir() / stderr_name
+ stdout_path.parent.mkdir(parents=True, exist_ok=True)
+ stdout = stdout_path.open("ab")
+ stderr = stderr_path.open("ab")
process = subprocess.Popen(
args,
- stdout=subprocess.DEVNULL,
- stderr=subprocess.DEVNULL,
+ stdout=stdout,
+ stderr=stderr,
start_new_session=True,
)
+ stdout.close()
+ stderr.close()
pid_path.write_text(str(process.pid), encoding="utf-8")
return process.pid
@@ -157,7 +169,12 @@ def _doctor():
def _run_background_service():
python = sys.executable
command = "import runpy; runpy.run_path('main.py', run_name='__main__')"
- return _spawn_background([python, "-c", command], paths.get_runtime_pid_path())
+ return _spawn_background(
+ [python, "-c", command],
+ paths.get_runtime_pid_path(),
+ "service_stdout.log",
+ "service_stderr.log",
+ )
def cmd_vibe():
@@ -174,10 +191,10 @@ def cmd_vibe():
_write_status("starting")
service_pid = _run_background_service()
- ui_pid = runtime.start_ui(config.ui.setup_port)
+ ui_pid = runtime.start_ui(config.ui.setup_host, config.ui.setup_port)
runtime.write_status("running", "pid={}".format(service_pid), service_pid, ui_pid)
- ui_url = "http://127.0.0.1:{}".format(config.ui.setup_port)
+ ui_url = "http://{}:{}".format(config.ui.setup_host, config.ui.setup_port)
if config.ui.open_browser:
_open_browser(ui_url)
diff --git a/vibe/runtime.py b/vibe/runtime.py
index a30663250..c62ef357d 100644
--- a/vibe/runtime.py
+++ b/vibe/runtime.py
@@ -67,14 +67,26 @@ def pid_alive(pid):
return False
-def spawn_background(args, pid_path):
+def _log_path(name: str) -> Path:
+ return paths.get_runtime_dir() / name
+
+
+def spawn_background(args, pid_path, stdout_name: str, stderr_name: str):
+ stdout_path = _log_path(stdout_name)
+ stderr_path = _log_path(stderr_name)
+ stdout_path.parent.mkdir(parents=True, exist_ok=True)
+ stdout = stdout_path.open("ab")
+ stderr = stderr_path.open("ab")
process = subprocess.Popen(
args,
- stdout=subprocess.DEVNULL,
- stderr=subprocess.DEVNULL,
+ stdout=stdout,
+ stderr=stderr,
start_new_session=True,
cwd=str(ROOT_DIR),
+ close_fds=True,
)
+ stdout.close()
+ stderr.close()
pid_path.write_text(str(process.pid), encoding="utf-8")
return process.pid
@@ -118,15 +130,22 @@ def render_status():
def start_service():
return spawn_background(
- [sys.executable, str(MAIN_PATH)], paths.get_runtime_pid_path()
+ [sys.executable, str(MAIN_PATH)],
+ paths.get_runtime_pid_path(),
+ "service_stdout.log",
+ "service_stderr.log",
)
-def start_ui(port):
- command = "from vibe.ui_server import run_ui_server; run_ui_server({})".format(port)
+def start_ui(host, port):
+ command = "from vibe.ui_server import run_ui_server; run_ui_server('{}', {})".format(
+ host, port
+ )
return spawn_background(
[sys.executable, "-c", command],
paths.get_runtime_ui_pid_path(),
+ "ui_stdout.log",
+ "ui_stderr.log",
)
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 84de284db..981d708bf 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -2,12 +2,43 @@ import http.server
import json
import socketserver
import mimetypes
+import threading
from pathlib import Path
+from typing import Any
from config import paths
class UiHandler(http.server.BaseHTTPRequestHandler):
+ server_version = "VibeUI"
+
+ def log_message(self, format: str, *args):
+ return
+
+ def _run_async(self, coro, timeout: float = 10.0):
+ result: dict[str, Any] = {}
+ error: str | None = None
+ lock = threading.Event()
+
+ def _runner():
+ nonlocal result, error
+ try:
+ import asyncio
+
+ result = asyncio.run(coro)
+ except Exception as exc:
+ error = str(exc)
+ finally:
+ lock.set()
+
+ threading.Thread(target=_runner, daemon=True).start()
+ lock.wait(timeout=timeout)
+ if not lock.is_set():
+ return {"ok": False, "error": "OpenCode options request timed out"}
+ if error:
+ return {"ok": False, "error": error}
+ return result
+
def _send_json(self, payload: dict, status: int = 200) -> None:
body = json.dumps(payload).encode("utf-8")
self.send_response(status)
@@ -26,10 +57,21 @@ class UiHandler(http.server.BaseHTTPRequestHandler):
self._send_json({"status": "ok"})
return
if self.path == "/status":
- payload = {}
- status_path = paths.get_runtime_status_path()
- if status_path.exists():
- payload = json.loads(status_path.read_text(encoding="utf-8"))
+ from vibe import runtime
+
+ payload = runtime.read_status()
+ pid_path = paths.get_runtime_pid_path()
+ pid = pid_path.read_text(encoding="utf-8").strip() if pid_path.exists() else None
+ running = bool(pid and pid.isdigit() and runtime.pid_alive(int(pid)))
+ payload["running"] = running
+ payload["pid"] = int(pid) if pid and pid.isdigit() else None
+ if running:
+ payload["service_pid"] = payload.get("service_pid") or payload["pid"]
+ elif payload.get("state") == "running":
+ runtime.write_status("stopped", "process not running", None, payload.get("ui_pid"))
+ payload = runtime.read_status()
+ payload["running"] = False
+ payload["pid"] = None
self._send_json(payload)
return
if self.path == "/doctor":
@@ -129,6 +171,62 @@ class UiHandler(http.server.BaseHTTPRequestHandler):
api.init_sessions()
self._send_json(api.config_to_payload(config))
return
+ if self.path == "/ui/reload":
+ from vibe import runtime
+
+ payload = self._read_json()
+ host = payload.get("host")
+ port = payload.get("port")
+ if not host or not port:
+ self._send_json({"error": "host_and_port_required"}, status=400)
+ return
+ try:
+ port = int(port)
+ except (TypeError, ValueError):
+ self._send_json({"error": "invalid_port"}, status=400)
+ return
+ status = runtime.read_status()
+ self._send_json({"ok": True, "host": host, "port": port})
+
+ def _restart():
+ import subprocess
+ import sys
+ import time
+ from pathlib import Path
+ from config import paths as config_paths
+ root_dir = Path(__file__).resolve().parents[1]
+ # Start new UI server process first (it will retry until port is available)
+ command = f"from vibe.ui_server import run_ui_server; run_ui_server('{host}', {port})"
+ stdout_path = config_paths.get_runtime_dir() / "ui_stdout.log"
+ stderr_path = config_paths.get_runtime_dir() / "ui_stderr.log"
+ stdout = stdout_path.open("ab")
+ stderr = stderr_path.open("ab")
+ process = subprocess.Popen(
+ [sys.executable, "-c", command],
+ stdout=stdout,
+ stderr=stderr,
+ start_new_session=True,
+ cwd=str(root_dir),
+ close_fds=True,
+ )
+ stdout.close()
+ stderr.close()
+ # Write new PID
+ config_paths.get_runtime_ui_pid_path().write_text(str(process.pid), encoding="utf-8")
+ runtime.write_status(
+ status.get("state", "running"),
+ status.get("detail"),
+ status.get("service_pid"),
+ process.pid,
+ )
+ # Give the new process a moment to start attempting connection
+ time.sleep(0.2)
+ # Now shutdown current server - new process will retry until port is free
+ self.server.shutdown()
+ self.server.server_close()
+
+ threading.Thread(target=_restart).start()
+ return
if self.path == "/settings":
from vibe import api
@@ -154,18 +252,75 @@ class UiHandler(http.server.BaseHTTPRequestHandler):
result = _doctor()
self._send_json(result)
return
+ if self.path == "/logs":
+ from config import paths
+ import re
+
+ payload = self._read_json()
+ lines = payload.get("lines", 500)
+ log_path = paths.get_logs_dir() / "vibe_remote.log"
+ if not log_path.exists():
+ self._send_json({"logs": [], "total": 0})
+ return
+ # Read last N lines
+ try:
+ with open(log_path, "r", encoding="utf-8", errors="replace") as f:
+ all_lines = f.readlines()
+ recent_lines = all_lines[-lines:] if len(all_lines) > lines else all_lines
+ # Parse log lines
+ # Format: 2026-01-19 18:46:42,292 - slack_sdk.socket_mode.aiohttp - DEBUG - [__init__.py:246] - message
+ log_pattern = re.compile(
+ r"^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3})\s+-\s+([\w.]+)\s+-\s+(\w+)\s+-\s+(.*)$"
+ )
+ logs = []
+ for line in recent_lines:
+ line = line.rstrip("\n")
+ match = log_pattern.match(line)
+ if match:
+ logs.append({
+ "timestamp": match.group(1),
+ "logger": match.group(2),
+ "level": match.group(3),
+ "message": match.group(4),
+ })
+ elif logs and line:
+ # Continuation of previous log (multiline)
+ logs[-1]["message"] += "\n" + line
+ self._send_json({"logs": logs, "total": len(all_lines)})
+ except Exception as e:
+ self._send_json({"error": str(e)}, status=500)
+ return
if self.path == "/opencode/options":
from vibe import api
payload = self._read_json()
- self._send_json(api.opencode_options(payload.get("cwd", ".")))
+ result = self._run_async(
+ api.opencode_options_async(payload.get("cwd", ".")),
+ timeout=12.0,
+ )
+ self._send_json(result)
return
self._send_json({"error": "not_found"}, status=404)
-def run_ui_server(port: int) -> None:
+class ThreadingHTTPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
+ daemon_threads = True
+ allow_reuse_address = True
+
+
+def run_ui_server(host: str, port: int) -> None:
+ import time
paths.ensure_data_dirs()
- print(f"UI Server running at http://127.0.0.1:{port}")
- socketserver.TCPServer.allow_reuse_address = True
- with socketserver.TCPServer(("127.0.0.1", port), UiHandler) as httpd:
- httpd.serve_forever()
+ print(f"UI Server running at http://{host}:{port}")
+ # Retry binding in case of TIME_WAIT
+ for attempt in range(10):
+ try:
+ with ThreadingHTTPServer((host, port), UiHandler) as httpd:
+ httpd.serve_forever()
+ break
+ except OSError as e:
+ if e.errno == 48 and attempt < 9: # Address already in use
+ print(f"Port {port} in use, retrying in 1s... (attempt {attempt + 1})")
+ time.sleep(1)
+ else:
+ raise