Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(e2e): stabilize three-end regression runtime
cyhhao682b6db0c21a
diff --git a/.env.three-regression.example b/.env.three-regression.exampleindex 9b2daf949..71589fd10 100644--- a/.env.three-regression.example+++ b/.env.three-regression.example@@ -22,11 +22,12 @@ THREE_REGRESSION_CODEX_MODEL=gpt-5.4THREE_REGRESSION_CODEX_REVIEW_MODEL=gpt-5.4THREE_REGRESSION_CODEX_REASONING_EFFORT=xhighTHREE_REGRESSION_CODEX_DISABLE_RESPONSE_STORAGE=true-THREE_REGRESSION_CODEX_RESPONSES_WEBSOCKETS_V2=true+THREE_REGRESSION_CODEX_RESPONSES_WEBSOCKETS_V2=falseTHREE_REGRESSION_CODEX_CONTEXT_WINDOW=1000000THREE_REGRESSION_CODEX_AUTO_COMPACT_TOKEN_LIMIT=900000THREE_REGRESSION_CODEX_BASE_URL=THREE_REGRESSION_CODEX_OPENAI_API_KEY=+THREE_REGRESSION_CODEX_SUPPRESS_UNSTABLE_WARNING=trueTHREE_REGRESSION_OPENCODE_OPENAI_BASE_URL=THREE_REGRESSION_OPENCODE_OPENAI_API_KEY=diff --git a/Dockerfile b/Dockerfileindex e265ddf10..e9487630d 100644--- a/Dockerfile+++ b/Dockerfile@@ -62,7 +62,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \# Install agent CLIs (failures are non-fatal: not all may be needed)RUN npm install -g @anthropic-ai/claude-code 2>/dev/null || echo "WARN: claude-code install failed (optional)"RUN npm install -g @openai/codex 2>/dev/null || echo "WARN: codex install failed (optional)"-# OpenCode: try npm, fall back to noting it's unavailable-RUN npm install -g opencode 2>/dev/null || echo "WARN: opencode install failed (optional)"+# OpenCode: use the official installer and expose the binary on PATH+RUN bash -lc 'set -euo pipefail; curl -fsSL https://opencode.ai/install | bash && ln -sf /root/.opencode/bin/opencode /usr/local/bin/opencode && opencode --version'ENTRYPOINT ["/docker-entrypoint.sh"]diff --git a/config/v2_config.py b/config/v2_config.pyindex b87e7365b..4b9e4023b 100644--- a/config/v2_config.py+++ b/config/v2_config.py@@ -1,5 +1,8 @@import jsonimport logging+import os+import tempfile+import threadingfrom dataclasses import dataclass, field, fieldsfrom pathlib import Pathfrom typing import List, Optional, Union@@ -10,6 +13,8 @@ from vibe.i18n import normalize_languagelogger = logging.getLogger(__name__)+CONFIG_LOCK = threading.RLock()+def _filter_dataclass_fields(dc_class, payload: dict) -> dict:"""Filter payload to only include fields defined in dataclass."""@@ -155,9 +160,10 @@ class V2Config:def load(cls, config_path: Optional[Path] = None) -> "V2Config":paths.ensure_data_dirs()path = config_path or paths.get_config_path()- if not path.exists():- raise FileNotFoundError(f"Config not found: {path}")- payload = json.loads(path.read_text(encoding="utf-8"))+ with CONFIG_LOCK:+ if not path.exists():+ raise FileNotFoundError(f"Config not found: {path}")+ payload = json.loads(path.read_text(encoding="utf-8"))return cls.from_payload(payload)@classmethod@@ -321,4 +327,12 @@ class V2Config:"reply_enhancements": self.reply_enhancements,"language": self.language,}- path.write_text(json.dumps(payload, indent=2), encoding="utf-8")+ content = json.dumps(payload, indent=2)+ path.parent.mkdir(parents=True, exist_ok=True)+ with CONFIG_LOCK:+ with tempfile.NamedTemporaryFile("w", encoding="utf-8", dir=path.parent, delete=False) as tmp:+ tmp.write(content)+ tmp.flush()+ os.fsync(tmp.fileno())+ temp_name = tmp.name+ os.replace(temp_name, path)diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.pyindex c79af6327..4cce9b2cd 100644--- a/core/handlers/session_handler.py+++ b/core/handlers/session_handler.py@@ -25,7 +25,11 @@ class SessionHandler(BaseHandler):def get_base_session_id(self, context: MessageContext) -> str:"""Get base session ID based on platform and context (without path)"""platform = getattr(self.config, "platform", "slack")- base_id = context.thread_id or context.message_id or context.channel_id+ is_dm = bool((context.platform_specific or {}).get("is_dm", False))+ if is_dm:+ base_id = context.channel_id or context.user_id+ else:+ base_id = context.thread_id or context.message_id or context.channel_idreturn f"{platform}_{base_id}"def get_working_path(self, context: MessageContext) -> str:diff --git a/docker-compose.three-regression.yml b/docker-compose.three-regression.ymlindex 45b877255..4e5b9df30 100644--- a/docker-compose.three-regression.yml+++ b/docker-compose.three-regression.yml@@ -14,12 +14,6 @@ x-vibe-regression: &vibe-regressionANTHROPIC_AUTH_TOKEN: ${THREE_REGRESSION_CLAUDE_AUTH_TOKEN:-}CLAUDE_CODE_ATTRIBUTION_HEADER: ${THREE_REGRESSION_CLAUDE_ATTRIBUTION_HEADER:-0}OPENAI_API_KEY: ${OPENAI_API_KEY:-}- OPENAI_BASE_URL: ${OPENAI_BASE_URL:-}- OPENAI_API_BASE: ${OPENAI_API_BASE:-}- volumes:- - ./_tmp/three-regression/shared-home/.claude:/root/.claude:ro- - ./_tmp/three-regression/shared-home/.codex:/root/.codex:ro- - ./_tmp/three-regression/shared-home/.config/opencode:/root/.config/opencode:rohealthcheck:test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:5123/health', timeout=3)"]interval: 3s@@ -34,6 +28,10 @@ services:- "${THREE_REGRESSION_SLACK_PORT:-15131}:5123"volumes:- ./_tmp/three-regression/slack:/data/vibe_remote+ - ./_tmp/three-regression/shared-home/.claude/settings.json:/root/.claude/settings.json:ro+ - ./_tmp/three-regression/shared-home/.codex/config.toml:/root/.codex/config.toml:ro+ - ./_tmp/three-regression/shared-home/.codex/auth.json:/root/.codex/auth.json:ro+ - ./_tmp/three-regression/shared-home/.config/opencode/opencode.json:/root/.config/opencode/opencode.json:rodiscord:<<: *vibe-regression@@ -41,6 +39,10 @@ services:- "${THREE_REGRESSION_DISCORD_PORT:-15132}:5123"volumes:- ./_tmp/three-regression/discord:/data/vibe_remote+ - ./_tmp/three-regression/shared-home/.claude/settings.json:/root/.claude/settings.json:ro+ - ./_tmp/three-regression/shared-home/.codex/config.toml:/root/.codex/config.toml:ro+ - ./_tmp/three-regression/shared-home/.codex/auth.json:/root/.codex/auth.json:ro+ - ./_tmp/three-regression/shared-home/.config/opencode/opencode.json:/root/.config/opencode/opencode.json:rofeishu:<<: *vibe-regression@@ -48,3 +50,7 @@ services:- "${THREE_REGRESSION_FEISHU_PORT:-15133}:5123"volumes:- ./_tmp/three-regression/feishu:/data/vibe_remote+ - ./_tmp/three-regression/shared-home/.claude/settings.json:/root/.claude/settings.json:ro+ - ./_tmp/three-regression/shared-home/.codex/config.toml:/root/.codex/config.toml:ro+ - ./_tmp/three-regression/shared-home/.codex/auth.json:/root/.codex/auth.json:ro+ - ./_tmp/three-regression/shared-home/.config/opencode/opencode.json:/root/.config/opencode/opencode.json:rodiff --git a/docs/plans/three-regression-followup-fixes.md b/docs/plans/three-regression-followup-fixes.mdnew file mode 100644index 000000000..06bf77ae0--- /dev/null+++ b/docs/plans/three-regression-followup-fixes.md@@ -0,0 +1,28 @@+# Three Regression Follow-up Fixes++> Status: In Progress++## Background++The three-end regression workflow is running, but two UX issues remain:++1. The Discord container is configured for Codex, yet some Web UI surfaces still show OpenCode, creating inconsistent routing feedback.+2. The Web UI health/status polling appears overly chatty, and likely uses multiple endpoints more often than needed.++## Goal++Make backend display consistent across the Web UI and reduce polling overhead by simplifying the runtime status checks.++## Solution++1. Trace the backend shown in dashboard/pages to determine whether it is reading global defaults, stale local state, or per-channel routing.+2. Fix the UI/API contract so the effective backend shown for the current platform reflects the actual runtime routing the service will use.+3. Inspect the status polling implementation, collapse redundant endpoint polling where possible, and reduce the polling interval without breaking responsiveness.+4. Validate in the running three-end regression environment and cover the behavior with tests where practical.++## Todo++- [ ] Find the source of the incorrect OpenCode display in the Discord Web UI.+- [ ] Fix effective backend display so it matches the actual Discord runtime backend.+- [ ] Simplify and reduce status polling.+- [ ] Validate via tests/build and live container checks.diff --git a/install.sh b/install.shindex a56d1550b..d98b9a657 100755--- a/install.sh+++ b/install.sh@@ -16,6 +16,7 @@ NC='\033[0m' # No Color# ConfigurationREPO="cyhhao/vibe-remote"PACKAGE_NAME="vibe-remote"+VIBE_BIN_PATH=""print_banner() {echo -e "${BLUE}"@@ -133,9 +134,10 @@ verify_installation() {export PATH="$HOME/.local/bin:$HOME/.cargo/bin:$PATH"if command_exists vibe; then+ VIBE_BIN_PATH="$(command -v vibe)"success "vibe command is available"echo ""- vibe --help 2>/dev/null || true+ "$VIBE_BIN_PATH" --help 2>/dev/null || truereturn 0fi@@ -147,6 +149,7 @@ verify_installation() {for loc in "${vibe_locations[@]}"; doif [ -f "$loc" ]; then+ VIBE_BIN_PATH="$loc"warn "vibe installed at $loc but not in PATH"echo ""echo -e "${YELLOW}Add this to your shell config (.bashrc, .zshrc, etc.):${NC}"@@ -161,13 +164,17 @@ verify_installation() {# Print next stepsprint_next_steps() {+ local vibe_dir+ vibe_dir="$(dirname "${VIBE_BIN_PATH:-$HOME/.local/bin/vibe}")"+echo ""echo -e "${GREEN}Installation complete!${NC}"echo ""echo -e "${BLUE}Next steps:${NC}"- echo " 1. Run 'vibe' to start the setup wizard"- echo " 2. Configure your Slack app tokens in the web UI"- echo " 3. Enable channels and start chatting with AI agents"+ echo " 1. Run 'source ${vibe_dir}/env' (or restart your shell)"+ echo " 2. Run 'vibe' to start the setup wizard"+ echo " 3. Configure your Slack app tokens in the web UI"+ echo " 4. Enable channels and start chatting with AI agents"echo ""echo -e "${BLUE}Quick commands:${NC}"echo " vibe - Start Vibe Remote (service + web UI)"@@ -180,6 +187,9 @@ print_next_steps() {echo " pip uninstall vibe-remote # if installed with pip"echo " rm -rf ~/.vibe_remote # remove config and data"echo ""+ echo -e "${BLUE}If 'vibe' is still not found:${NC}"+ echo " ${VIBE_BIN_PATH:-$HOME/.local/bin/vibe}"+ echo ""echo -e "${BLUE}Documentation:${NC}"echo " https://github.com/${REPO}#readme"echo ""diff --git a/modules/im/discord.py b/modules/im/discord.pyindex 96a4c939f..6d6566b98 100644--- a/modules/im/discord.py+++ b/modules/im/discord.py@@ -3,6 +3,7 @@ import ioimport jsonimport loggingimport os+import timefrom typing import Dict, Any, Optional, Callable, Listfrom urllib.parse import urlsplit@@ -47,6 +48,9 @@ class DiscordBot(BaseIMClient):self._controller = Noneself._on_ready: Optional[Callable] = Noneself._user_info_cache: Dict[str, Dict[str, Any]] = {}+ self._recent_interaction_ids: Dict[str, float] = {}+ self._recent_callback_keys: Dict[str, float] = {}+ self._callback_dedupe_ttl_seconds = 3.0self.client.on_ready = self._on_ready_eventself.client.on_message = self._on_message_event@@ -88,6 +92,56 @@ class DiscordBot(BaseIMClient):lang = self._get_lang(channel_id)return i18n_t(key, lang, **kwargs)+ def _prune_recent_interactions(self) -> None:+ cutoff = time.monotonic() - self._callback_dedupe_ttl_seconds+ self._recent_interaction_ids = {key: ts for key, ts in self._recent_interaction_ids.items() if ts >= cutoff}+ self._recent_callback_keys = {key: ts for key, ts in self._recent_callback_keys.items() if ts >= cutoff}++ def _mark_interaction_seen(self, interaction: discord.Interaction, callback_data: str) -> bool:+ self._prune_recent_interactions()++ now = time.monotonic()+ interaction_id = str(interaction.id)+ if interaction_id in self._recent_interaction_ids:+ return False++ message_id = str(interaction.message.id) if interaction.message else ""+ callback_key = f"{interaction.user.id}:{message_id}:{callback_data}"+ last_seen = self._recent_callback_keys.get(callback_key)+ self._recent_interaction_ids[interaction_id] = now+ self._recent_callback_keys[callback_key] = now+ return last_seen is None or (now - last_seen) > self._callback_dedupe_ttl_seconds++ def _build_interaction_context(self, interaction: discord.Interaction) -> MessageContext | None:+ channel_id, thread_id = self._extract_context_ids(interaction.channel)+ guild_id = str(interaction.guild_id) if interaction.guild_id else None+ if guild_id and not self._is_allowed_guild(guild_id):+ return None++ is_dm = interaction.guild is None or isinstance(interaction.channel, discord.DMChannel)+ return MessageContext(+ user_id=str(interaction.user.id),+ channel_id=channel_id,+ thread_id=thread_id,+ message_id=str(interaction.message.id) if interaction.message else None,+ platform_specific={"interaction": interaction, "is_dm": is_dm},+ )++ async def _dispatch_callback_query(self, context: MessageContext, data: str) -> None:+ if self.on_callback_query_callback:+ await self.on_callback_query_callback(context, data)++ def _spawn_callback_query_task(self, context: MessageContext, data: str) -> None:+ task = asyncio.create_task(self._dispatch_callback_query(context, data))++ def _log_task_result(done_task: asyncio.Task) -> None:+ try:+ done_task.result()+ except Exception:+ logger.exception("Discord callback task failed: %s", data)++ task.add_done_callback(_log_task_result)+def get_default_parse_mode(self) -> str:return "markdown"@@ -1614,32 +1668,31 @@ class _PersistentStartView(discord.ui.View):await interaction.response.defer(ephemeral=True)except Exception:pass- channel_id, thread_id = self.outer._extract_context_ids(interaction.channel)- guild_id = str(interaction.guild_id) if interaction.guild_id else None- if guild_id and not self.outer._is_allowed_guild(guild_id):++ if not self.outer._mark_interaction_seen(interaction, data):+ logger.info("Ignoring duplicate Discord interaction: %s", data)+ return++ context = self.outer._build_interaction_context(interaction)+ if context is None:return- is_dm = interaction.guild is None or isinstance(interaction.channel, discord.DMChannel)auth_result = self.outer.check_authorization(- user_id=str(interaction.user.id),- channel_id=channel_id,- is_dm=is_dm,+ user_id=context.user_id,+ channel_id=context.channel_id,+ is_dm=bool((context.platform_specific or {}).get("is_dm", False)),action=data,settings_manager=self.outer.settings_manager,)if not auth_result.allowed:await self.outer._send_auth_denial(- channel_id, str(interaction.user.id), auth_result, interaction=interaction+ context.channel_id, context.user_id, auth_result, interaction=interaction)return- context = MessageContext(- user_id=str(interaction.user.id),- channel_id=channel_id,- thread_id=thread_id,- message_id=str(interaction.message.id) if interaction.message else None,- platform_specific={"interaction": interaction, "is_dm": is_dm},- )- if self.outer.on_callback_query_callback:- await self.outer.on_callback_query_callback(context, data)++ if needs_modal:+ await self.outer._dispatch_callback_query(context, data)+ else:+ self.outer._spawn_callback_query_task(context, data)return on_click@@ -1693,32 +1746,31 @@ class _DiscordButtonView(discord.ui.View):await interaction.response.defer(ephemeral=True)except Exception:pass- channel_id, thread_id = self.outer._extract_context_ids(interaction.channel)- guild_id = str(interaction.guild_id) if interaction.guild_id else None- if guild_id and not self.outer._is_allowed_guild(guild_id):++ if not self.outer._mark_interaction_seen(interaction, data):+ logger.info("Ignoring duplicate Discord interaction: %s", data)+ return++ context = self.outer._build_interaction_context(interaction)+ if context is None:return- is_dm = interaction.guild is None or isinstance(interaction.channel, discord.DMChannel)auth_result = self.outer.check_authorization(- user_id=str(interaction.user.id),- channel_id=channel_id,- is_dm=is_dm,+ user_id=context.user_id,+ channel_id=context.channel_id,+ is_dm=bool((context.platform_specific or {}).get("is_dm", False)),action=data,settings_manager=self.outer.settings_manager,)if not auth_result.allowed:await self.outer._send_auth_denial(- channel_id, str(interaction.user.id), auth_result, interaction=interaction+ context.channel_id, context.user_id, auth_result, interaction=interaction)return- context = MessageContext(- user_id=str(interaction.user.id),- channel_id=channel_id,- thread_id=thread_id,- message_id=str(interaction.message.id) if interaction.message else None,- platform_specific={"interaction": interaction, "is_dm": is_dm},- )- if self.outer.on_callback_query_callback:- await self.outer.on_callback_query_callback(context, data)++ if needs_modal:+ await self.outer._dispatch_callback_query(context, data)+ else:+ self.outer._spawn_callback_query_task(context, data)item.callback = on_clickself.add_item(item)diff --git a/scripts/docker-entrypoint.sh b/scripts/docker-entrypoint.shindex 841f161c6..6658fdf9b 100755--- a/scripts/docker-entrypoint.sh+++ b/scripts/docker-entrypoint.sh@@ -1,6 +1,33 @@#!/bin/bashset -e+cleanup() {+ python -c "+from vibe import runtime+runtime.stop_service()+runtime.stop_ui()+runtime.write_status('stopped', 'container shutdown')+"+}++trap cleanup EXIT INT TERM++start_ui_process() {+ local runtime_dir="$1"+ local ui_stdout="$runtime_dir/ui_stdout.log"+ local ui_stderr="$runtime_dir/ui_stderr.log"++ echo "Starting UI server on 0.0.0.0:${VIBE_UI_PORT:-5123}..." >&2+ python -c "+from vibe.ui_server import run_ui_server+run_ui_server('0.0.0.0', ${VIBE_UI_PORT:-5123})+" >>"$ui_stdout" 2>>"$ui_stderr" &++ local ui_pid=$!+ echo "$ui_pid" > "$runtime_dir/vibe-ui.pid"+ echo "$ui_pid"+}+# Ensure runtime directories exist and seed default config if missingpython -c "from config.paths import ensure_data_dirs, get_config_path@@ -23,7 +50,7 @@ run_ui_server('0.0.0.0', ${VIBE_UI_PORT:-5123})";;full)- # Start service in background + UI server in foreground+ # Start service + UI server under a lightweight supervisor loopecho "Starting service..."python main.py &SERVICE_PID=$!@@ -33,23 +60,37 @@ run_ui_server('0.0.0.0', ${VIBE_UI_PORT:-5123})mkdir -p "$RUNTIME_DIR"echo "$SERVICE_PID" > "$RUNTIME_DIR/vibe.pid"- echo "Starting UI server on 0.0.0.0:${VIBE_UI_PORT:-5123}..."+ UI_PID="$(start_ui_process "$RUNTIME_DIR")"+python -c "-from vibe.ui_server import run_ui_server-run_ui_server('0.0.0.0', ${VIBE_UI_PORT:-5123})-" &- UI_PID=$!- echo "$UI_PID" > "$RUNTIME_DIR/vibe-ui.pid"+from vibe import runtime+runtime.write_status('running', 'started', ${SERVICE_PID}, ${UI_PID})+"++ while true; do+ CURRENT_UI_PID=""+ if [ -f "$RUNTIME_DIR/vibe-ui.pid" ]; then+ CURRENT_UI_PID="$(cat "$RUNTIME_DIR/vibe-ui.pid")"+ fi++ if [ -z "$CURRENT_UI_PID" ]; then+ UI_PID="$(start_ui_process "$RUNTIME_DIR")"+ python -c "+from vibe import runtime+runtime.write_status('running', 'ui restarted', ${SERVICE_PID}, ${UI_PID})+"+ elif ! kill -0 "$CURRENT_UI_PID" 2>/dev/null; then+ wait "$CURRENT_UI_PID" 2>/dev/null || UI_EXIT_CODE=$?+ echo "UI server exited unexpectedly (code: ${UI_EXIT_CODE:-unknown}), restarting..."+ UI_PID="$(start_ui_process "$RUNTIME_DIR")"+ python -c "+from vibe import runtime+runtime.write_status('running', 'ui restarted after crash', ${SERVICE_PID}, ${UI_PID})+"+ fi- # Wait for either process to exit; propagate its exit code- set +e- wait -n "$SERVICE_PID" "$UI_PID" 2>/dev/null- EXIT_CODE=$?- set -e- # Terminate the sibling process- kill "$SERVICE_PID" "$UI_PID" 2>/dev/null || true- wait "$SERVICE_PID" "$UI_PID" 2>/dev/null || true- exit "$EXIT_CODE"+ sleep 1+ done;;cli)# Run a vibe CLI command (e.g., docker run ... cli doctor)diff --git a/scripts/prepare_three_regression.py b/scripts/prepare_three_regression.pyindex 2baa21df0..5df038918 100755--- a/scripts/prepare_three_regression.py+++ b/scripts/prepare_three_regression.py@@ -267,7 +267,10 @@ def _build_codex_config_toml() -> str:_parse_bool(_optional("THREE_REGRESSION_CODEX_DISABLE_RESPONSE_STORAGE"), default=True)).lower()responses_websockets_v2 = str(- _parse_bool(_optional("THREE_REGRESSION_CODEX_RESPONSES_WEBSOCKETS_V2"), default=True)+ _parse_bool(_optional("THREE_REGRESSION_CODEX_RESPONSES_WEBSOCKETS_V2"), default=False)+ ).lower()+ suppress_unstable_warning = str(+ _parse_bool(_optional("THREE_REGRESSION_CODEX_SUPPRESS_UNSTABLE_WARNING"), default=True)).lower()return (f'model_provider = "{model_provider}"\n'@@ -275,6 +278,7 @@ def _build_codex_config_toml() -> str:f'review_model = "{review_model}"\n'f'model_reasoning_effort = "{reasoning_effort}"\n'f"disable_response_storage = {disable_storage}\n"+ f"suppress_unstable_features_warning = {suppress_unstable_warning}\n"'network_access = "enabled"\n'"windows_wsl_setup_acknowledged = true\n"f"model_context_window = {_env('THREE_REGRESSION_CODEX_CONTEXT_WINDOW', '1000000')}\n"diff --git a/tests/test_api_save_config_merge.py b/tests/test_api_save_config_merge.pynew file mode 100644index 000000000..521742ef9--- /dev/null+++ b/tests/test_api_save_config_merge.py@@ -0,0 +1,97 @@+from __future__ import annotations++import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from vibe import api+++def _full_config_payload() -> dict:+ return {+ "platform": "discord",+ "mode": "self_host",+ "version": "v2",+ "slack": {+ "bot_token": "",+ "app_token": None,+ "signing_secret": None,+ "team_id": None,+ "team_name": None,+ "app_id": None,+ "require_mention": False,+ },+ "discord": {+ "bot_token": "discord-token-1234567890",+ "application_id": None,+ "guild_allowlist": ["754776951587340359"],+ "guild_denylist": [],+ "require_mention": False,+ },+ "lark": {+ "app_id": "",+ "app_secret": "",+ "require_mention": False,+ "domain": "feishu",+ },+ "runtime": {+ "default_cwd": "/tmp/workdir",+ "log_level": "INFO",+ },+ "agents": {+ "default_backend": "codex",+ "opencode": {+ "enabled": True,+ "cli_path": "opencode",+ "default_agent": None,+ "default_model": None,+ "default_reasoning_effort": None,+ "error_retry_limit": 1,+ },+ "claude": {+ "enabled": True,+ "cli_path": "claude",+ "default_model": None,+ },+ "codex": {+ "enabled": True,+ "cli_path": "codex",+ "default_model": "gpt-5.4",+ },+ },+ "gateway": None,+ "ui": {+ "setup_host": "127.0.0.1",+ "setup_port": 5123,+ "open_browser": False,+ },+ "update": {+ "auto_update": False,+ "check_interval_minutes": 0,+ "idle_minutes": 30,+ "notify_slack": False,+ },+ "ack_mode": "reaction",+ "show_duration": True,+ "include_user_info": True,+ "reply_enhancements": True,+ "language": "en",+ }+++def test_save_config_merges_partial_payload(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))++ original = api.save_config(_full_config_payload())+ assert original.show_duration is True+ assert original.update.auto_update is False++ updated = api.save_config({"show_duration": False, "update": {"auto_update": True}})++ assert updated.show_duration is False+ assert updated.update.auto_update is True+ assert updated.platform == "discord"+ assert updated.discord is not None+ assert updated.discord.bot_token == "discord-token-1234567890"+ assert updated.runtime.default_cwd == "/tmp/workdir"diff --git a/tests/test_prepare_three_regression.py b/tests/test_prepare_three_regression.pyindex 3fbec23a2..ea946e917 100644--- a/tests/test_prepare_three_regression.py+++ b/tests/test_prepare_three_regression.py@@ -81,6 +81,8 @@ def test_prepare_generates_three_isolated_states(tmp_path: Path, monkeypatch: py)codex_config = (tmp_path / "shared-home" / ".codex" / "config.toml").read_text(encoding="utf-8")assert 'model = "gpt-5.4"' in codex_config+ assert "responses_websockets_v2 = false" in codex_config+ assert "suppress_unstable_features_warning = true" in codex_configopencode_config = json.loads((tmp_path / "shared-home" / ".config" / "opencode" / "opencode.json").read_text(encoding="utf-8"))diff --git a/tests/test_session_handler_base_id.py b/tests/test_session_handler_base_id.pynew file mode 100644index 000000000..f6a97c805--- /dev/null+++ b/tests/test_session_handler_base_id.py@@ -0,0 +1,56 @@+from __future__ import annotations++from dataclasses import dataclass+import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from core.handlers.session_handler import SessionHandler+from modules.im import MessageContext+++@dataclass+class _Config:+ platform: str = "discord"+++class _Controller:+ def __init__(self) -> None:+ self.config = _Config()+ self.im_client = type("IM", (), {"formatter": None})()+ self.settings_manager = type("Settings", (), {"sessions": None})()+ self.session_manager = object()+ self.claude_sessions = {}+ self.receiver_tasks = {}+ self.stored_session_mappings = {}++ def get_cwd(self, context: MessageContext) -> str:+ return "/tmp/workdir"++ def _get_settings_key(self, context: MessageContext) -> str:+ return context.user_id if (context.platform_specific or {}).get("is_dm") else context.channel_id+++def test_dm_session_base_id_uses_stable_channel_id() -> None:+ handler = SessionHandler(_Controller())+ context = MessageContext(+ user_id="u-1",+ channel_id="dm-123",+ message_id="msg-999",+ platform_specific={"is_dm": True},+ )++ assert handler.get_base_session_id(context) == "discord_dm-123"+++def test_channel_session_base_id_keeps_thread_or_message_behavior() -> None:+ handler = SessionHandler(_Controller())+ context = MessageContext(+ user_id="u-1",+ channel_id="chan-123",+ message_id="msg-999",+ platform_specific={"is_dm": False},+ )++ assert handler.get_base_session_id(context) == "discord_msg-999"diff --git a/ui/src/components/Dashboard.tsx b/ui/src/components/Dashboard.tsxindex ec0fbdbbc..2e7b9bc8f 100644--- a/ui/src/components/Dashboard.tsx+++ b/ui/src/components/Dashboard.tsx@@ -28,10 +28,16 @@ export const Dashboard: React.FC = () => {// Auto-save Message Handling config (no restart needed)const autoSaveMessageConfig = async (newConfig: any) => {try {+ const patch = {+ ack_mode: newConfig.ack_mode,+ show_duration: newConfig.show_duration,+ include_user_info: newConfig.include_user_info,+ reply_enhancements: newConfig.reply_enhancements,+ };await fetch('/config', {method: 'POST',headers: { 'Content-Type': 'application/json' },- body: JSON.stringify(newConfig),+ body: JSON.stringify(patch),});setSettingsMessage(t('common.saved'));} catch {@@ -49,7 +55,6 @@ export const Dashboard: React.FC = () => {setup_port: config.ui?.setup_port || 5123,};const configPayload = {- ...config,ui: { ...(config.ui || {}), ...uiPayload },};// Save config first@@ -85,8 +90,7 @@ export const Dashboard: React.FC = () => {log_level: config.runtime?.log_level || 'INFO',};const configPayload = {- ...config,- runtime: { ...(config.runtime || {}), ...runtimePayload },+ runtime: runtimePayload,};await fetch('/config', {method: 'POST',@@ -244,7 +248,7 @@ export const Dashboard: React.FC = () => {</div><div className="flex justify-between items-center"><span className="text-muted">{t('dashboard.defaultBackend')}</span>- <span className="font-mono text-xs text-text">{config.agents?.default_backend || 'opencode'}</span>+ <span className="font-mono text-xs text-text">{config.agents?.default_backend || '-'}</span></div>{showWorkspaceGateway && (<div className="flex justify-between items-center">diff --git a/ui/src/components/LanguageSwitcher.tsx b/ui/src/components/LanguageSwitcher.tsxindex 4f9d9d736..0746be818 100644--- a/ui/src/components/LanguageSwitcher.tsx+++ b/ui/src/components/LanguageSwitcher.tsx@@ -1,4 +1,4 @@-import React, { useEffect, useState } from 'react';+import React, { useEffect } from 'react';import { useTranslation } from 'react-i18next';import { Languages } from 'lucide-react';import { useApi } from '../context/ApiContext';@@ -6,14 +6,12 @@ import { useApi } from '../context/ApiContext';export const LanguageSwitcher: React.FC = () => {const { i18n, t } = useTranslation();const { getConfig, saveConfig } = useApi();- const [config, setConfig] = useState<any>(null);// Load config and sync language on mountuseEffect(() => {const loadConfig = async () => {try {const cfg = await getConfig();- setConfig(cfg);// Sync i18n with config languageif (cfg.language && cfg.language !== i18n.language) {i18n.changeLanguage(cfg.language);@@ -39,10 +37,7 @@ export const LanguageSwitcher: React.FC = () => {// Save to configtry {- const baseConfig = config ?? await getConfig();- const updatedConfig = { ...baseConfig, language: newLang };- await saveConfig(updatedConfig);- setConfig(updatedConfig);+ await saveConfig({ language: newLang });} catch {// Ignore save errors - language change already applied locally}diff --git a/ui/src/components/VersionBadge.tsx b/ui/src/components/VersionBadge.tsxindex cff1e9c7f..b1f8a901e 100644--- a/ui/src/components/VersionBadge.tsx+++ b/ui/src/components/VersionBadge.tsx@@ -48,15 +48,7 @@ export const VersionBadge: React.FC = () => {const handleAutoUpdateToggle = async (enabled: boolean) => {setSavingAutoUpdate(true);try {- const config = await api.getConfig();- const updatedConfig = {- ...config,- update: {- ...config.update,- auto_update: enabled,- },- };- await api.saveConfig(updatedConfig);+ await api.saveConfig({ update: { auto_update: enabled } });setAutoUpdate(enabled);} catch (e) {console.error('Failed to save auto-update setting:', e);diff --git a/ui/src/components/steps/ChannelList.tsx b/ui/src/components/steps/ChannelList.tsxindex d7420457a..d275a7781 100644--- a/ui/src/components/steps/ChannelList.tsx+++ b/ui/src/components/steps/ChannelList.tsx@@ -349,7 +349,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onBshow_message_types: [],custom_cwd: '',routing: {- agent_backend: 'opencode',+ agent_backend: null,opencode_agent: null,opencode_model: null,opencode_reasoning_effort: null,@@ -457,6 +457,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB{sortedChannels.map((channel) => {const rawConfig = configs[channel.id] || {};const def = defaultConfig();+ const defaultBackend = config.agents?.default_backend || 'opencode';const channelConfig = {...def,...rawConfig,@@ -470,6 +471,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB// Preserve require_mention from rawConfig (can be null, true, or false)require_mention: rawConfig.require_mention !== undefined ? rawConfig.require_mention : def.require_mention,};+ const effectiveBackend = channelConfig.routing.agent_backend || defaultBackend;const effectiveCwd = channelConfig.custom_cwd || config.runtime?.default_cwd || '~/work';const opencodeOptions = opencodeOptionsByCwd[effectiveCwd];@@ -534,7 +536,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB<div className="space-y-1"><label className="text-xs font-medium text-muted uppercase">{t('channelList.backend')}</label><select- value={channelConfig.routing.agent_backend || 'opencode'}+ value={effectiveBackend}onChange={(e) =>updateConfig(channel.id, {routing: { ...channelConfig.routing, agent_backend: e.target.value },@@ -607,7 +609,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB</div>{/* OpenCode Settings */}- {(!channelConfig.routing.agent_backend || channelConfig.routing.agent_backend === 'opencode') && (+ {effectiveBackend === 'opencode' && (<div className="space-y-3"><div className="text-xs font-medium text-muted uppercase">{t('channelList.opencodeSettings')}</div><div className="grid grid-cols-1 md:grid-cols-3 gap-3 bg-bg/50 p-3 rounded border border-border">@@ -702,7 +704,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB)}{/* Claude Settings */}- {channelConfig.routing.agent_backend === 'claude' && (+ {effectiveBackend === 'claude' && (<div className="space-y-3"><div className="text-xs font-medium text-muted uppercase">{t('channelList.claudeSettings')}</div><div className="grid grid-cols-1 md:grid-cols-2 gap-3 bg-bg/50 p-3 rounded border border-border">@@ -746,7 +748,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB)}{/* Codex Settings */}- {channelConfig.routing.agent_backend === 'codex' && (+ {effectiveBackend === 'codex' && (<div className="space-y-3"><div className="text-xs font-medium text-muted uppercase">{t('channelList.codexSettings')}</div><div className="grid grid-cols-1 md:grid-cols-2 gap-3 bg-bg/50 p-3 rounded border border-border">diff --git a/ui/src/components/steps/UserList.tsx b/ui/src/components/steps/UserList.tsxindex 25a322e80..1e7d71523 100644--- a/ui/src/components/steps/UserList.tsx+++ b/ui/src/components/steps/UserList.tsx@@ -420,7 +420,7 @@ export const UserList: React.FC = () => {enabled: true,show_message_types: [],custom_cwd: '',- routing: { agent_backend: 'opencode' },+ routing: { agent_backend: null },});const getReasoningOptions = (cwd: string, modelKey: string) => {@@ -450,6 +450,7 @@ export const UserList: React.FC = () => {) : (userEntries.map(([userId, userConfig]) => {const effectiveCwd = userConfig.custom_cwd || config.runtime?.default_cwd || '~/work';+ const effectiveBackend = userConfig.routing?.agent_backend || config.agents?.default_backend || 'opencode';const opencodeOptions = opencodeOptionsByCwd[effectiveCwd];const claudeAgents = claudeAgentsByCwd[effectiveCwd] || [];return (@@ -527,7 +528,7 @@ export const UserList: React.FC = () => {<div className="space-y-1"><label className="text-xs font-medium text-muted uppercase">{t('channelList.backend')}</label><select- value={userConfig.routing.agent_backend || 'opencode'}+ value={effectiveBackend}onChange={(e) => updateUser(userId, { routing: { ...userConfig.routing, agent_backend: e.target.value } })}className="w-full bg-bg border border-border rounded px-3 py-2 text-sm focus:outline-none focus:border-accent text-text">@@ -573,7 +574,7 @@ export const UserList: React.FC = () => {</div>{/* OpenCode Settings */}- {(!userConfig.routing.agent_backend || userConfig.routing.agent_backend === 'opencode') && (+ {effectiveBackend === 'opencode' && (<div className="space-y-3"><div className="text-xs font-medium text-muted uppercase">{t('channelList.opencodeSettings')}</div><div className="grid grid-cols-1 md:grid-cols-3 gap-3 bg-bg/50 p-3 rounded border border-border">@@ -633,7 +634,7 @@ export const UserList: React.FC = () => {)}{/* Claude Settings */}- {userConfig.routing.agent_backend === 'claude' && (+ {effectiveBackend === 'claude' && (<div className="space-y-3"><div className="text-xs font-medium text-muted uppercase">{t('channelList.claudeSettings')}</div><div className="grid grid-cols-1 md:grid-cols-2 gap-3 bg-bg/50 p-3 rounded border border-border">@@ -664,7 +665,7 @@ export const UserList: React.FC = () => {)}{/* Codex Settings */}- {userConfig.routing.agent_backend === 'codex' && (+ {effectiveBackend === 'codex' && (<div className="space-y-3"><div className="text-xs font-medium text-muted uppercase">{t('channelList.codexSettings')}</div><div className="grid grid-cols-1 md:grid-cols-2 gap-3 bg-bg/50 p-3 rounded border border-border">diff --git a/ui/src/context/StatusContext.tsx b/ui/src/context/StatusContext.tsxindex 03b9664c5..13b5099fe 100644--- a/ui/src/context/StatusContext.tsx+++ b/ui/src/context/StatusContext.tsx@@ -26,27 +26,18 @@ export const StatusProvider: React.FC<{ children: React.ReactNode }> = ({ childrconst [status, setStatus] = useState<RuntimeStatus>({});const [health, setHealth] = useState(false);- const checkHealth = async () => {- try {- const res = await fetch('/health');- if (res.ok) {- setHealth(true);- } else {- setHealth(false);- }- } catch (e) {- setHealth(false);- }- };-const refreshStatus = async () => {try {const res = await fetch('/status');if (res.ok) {const data = await res.json();setStatus(data);+ setHealth(true);+ } else {+ setHealth(false);}} catch (e) {+ setHealth(false);console.error('Failed to fetch status', e);}};@@ -69,13 +60,28 @@ export const StatusProvider: React.FC<{ children: React.ReactNode }> = ({ childr};useEffect(() => {- checkHealth();- refreshStatus();- const interval = setInterval(() => {- checkHealth();- refreshStatus();- }, 2000);- return () => clearInterval(interval);+ void refreshStatus();++ const poll = () => {+ void refreshStatus();+ };++ const interval = window.setInterval(poll, 5000);+ const handleVisibilityChange = () => {+ if (document.visibilityState === 'visible') {+ poll();+ }+ };+ const handleFocus = () => poll();++ document.addEventListener('visibilitychange', handleVisibilityChange);+ window.addEventListener('focus', handleFocus);++ return () => {+ window.clearInterval(interval);+ document.removeEventListener('visibilitychange', handleVisibilityChange);+ window.removeEventListener('focus', handleFocus);+ };}, []);return (diff --git a/vibe/api.py b/vibe/api.pyindex 0705d6e29..c3bfae898 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -9,7 +9,7 @@ from pathlib import Pathfrom typing import Dict, List, Optionalfrom config import paths-from config.v2_config import V2Config+from config.v2_config import CONFIG_LOCK, V2Configfrom config.v2_settings import (SettingsStore,ChannelSettings,@@ -65,10 +65,31 @@ def load_config() -> V2Config:return V2Config.load()+def _deep_merge_dicts(base: dict, patch: dict) -> dict:+ merged = dict(base)+ for key, value in patch.items():+ if isinstance(value, dict) and isinstance(merged.get(key), dict):+ merged[key] = _deep_merge_dicts(merged[key], value)+ else:+ merged[key] = value+ return merged++def save_config(payload: dict) -> V2Config:- config = V2Config.from_payload(payload)- config.save()- return config+ if not isinstance(payload, dict):+ raise ValueError("Config payload must be an object")++ with CONFIG_LOCK:+ base_payload: dict = {}+ try:+ base_payload = config_to_payload(load_config())+ except FileNotFoundError:+ base_payload = {}++ merged_payload = _deep_merge_dicts(base_payload, payload) if base_payload else payload+ config = V2Config.from_payload(merged_payload)+ config.save()+ return configdef config_to_payload(config: V2Config) -> dict: