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(runtime): harden windows support and slack recovery
cyh0e51b231561d
diff --git a/.agents/skills/use-sentry-cli-debug/SKILL.md b/.agents/skills/use-sentry-cli-debug/SKILL.mdnew file mode 100644index 000000000..d54eb793a--- /dev/null+++ b/.agents/skills/use-sentry-cli-debug/SKILL.md@@ -0,0 +1,134 @@+---+name: use-sentry-cli-debug+slug: use-sentry-cli-debug+description: Use the official Sentry CLI to investigate issues, events, traces, and logs for Vibe Remote without committing Sentry credentials into the repository.+version: 0.1.0+---++# Use Sentry CLI Debug++Use this skill when the user asks to inspect Sentry issues, events, traces, logs, or authenticated Sentry API responses from the command line while working in the Vibe Remote repository.++## Core Rules++1. Prefer `sentry` CLI subcommands over raw REST calls. Use `sentry issue`, `sentry event`, `sentry trace`, and `sentry log` first. Fall back to `sentry api` only when the dedicated command cannot expose the needed field.+2. Do not commit credentials. Prefer `sentry auth login` interactive auth. If token auth is required, use a shell-scoped `SENTRY_AUTH_TOKEN` or another untracked local secret source. Never write tokens into tracked repo files.+3. Keep output small. Prefer `--json --fields ...`, `--limit ...`, and `jq` when filtering.+4. Stay read-only by default. Do not resolve, mute, delete, or otherwise mutate Sentry state unless the user explicitly asks.+5. Verify CLI context before debugging. Run `sentry auth status`, then confirm the target org/project if auto-detection looks ambiguous.++## Prerequisites++If `sentry` is not installed:++```bash+curl https://cli.sentry.dev/install -fsS | bash+```++Then verify:++```bash+sentry --help+sentry auth status+```++Authentication options that do not require committing secrets:++```bash+# Preferred: interactive login managed by the CLI+sentry auth login++# Alternative: shell-scoped token+export SENTRY_AUTH_TOKEN=...+sentry auth login --token "$SENTRY_AUTH_TOKEN"+```++Never add the token to tracked files such as `.env`, `.envrc`, `config/*.json`, `settings.json`, or skill files.++## Repo-Specific Context++Before querying Sentry, read [vibe-remote.md](references/vibe-remote.md) for the tags and environment metadata currently attached by this repository.++Important current signals:++- `component=service` for the main service+- `component=ui` for the Flask UI+- `mode=<config.mode>`+- `primary_platform=<config.platforms.primary>`+- `deployment_environment=<resolved environment>`+- `release=vibe-remote@<version>`++These are useful narrowing dimensions when many unrelated issues exist in the same Sentry org/project.++## Debug Workflow++### 1. Confirm auth and scope++```bash+sentry auth status+sentry org list+sentry project list <org>+```++If auto-detection is unreliable, use explicit `<org>/<project>` in every command.++### 2. Triage recent issues++```bash+sentry issue list <org>/<project> \+ --query 'is:unresolved' \+ --limit 10 \+ --json \+ --fields shortId,title,count,userCount,lastSeen,level,status+```++Common filters:++```bash+sentry issue list <org>/<project> --query 'is:unresolved environment:regression'+sentry issue list <org>/<project> --query 'component:service'+sentry issue list <org>/<project> --query 'component:ui'+sentry issue list <org>/<project> --query 'primary_platform:slack'+sentry issue list <org>/<project> --query 'release:[email protected]'+```++### 3. Inspect one issue deeply++```bash+sentry issue view <short-id>+sentry issue explain <short-id>+```++Use `sentry issue explain` only after you have the raw issue details. Treat the AI explanation as a hint, not ground truth.++### 4. Inspect concrete event, trace, and logs++```bash+sentry event view <org>/<project>/<event-id>+sentry trace view <trace-id>+sentry trace logs <trace-id> --limit 100+sentry log list <org>/<project> --query 'level:error' --limit 100+```++Use trace and log commands when the issue points to timing, retries, upstream HTTP failures, or multi-step orchestration problems.++### 5. Use `sentry api` only as a fallback++```bash+sentry api /api/0/organizations/<org>/issues/+```++Prefer `--method`, `--data`, and `--header` only when the dedicated CLI command cannot express the operation.++## Vibe Remote Triage Hints++1. If the bug is user-visible in regression, first search `environment:regression`.+2. Split `component:service` and `component:ui` early. Do not mix backend startup errors with UI Flask failures.+3. When the report is platform-specific, try `primary_platform:<platform>` and cross-check local logs if Sentry detail is incomplete.+4. If no Sentry result appears, check whether the problem was only logged locally in `~/.vibe_remote/logs/vibe_remote.log`.+5. If Sentry output is too noisy, reduce fields instead of pasting full blobs back to the user.++## When Not to Use This Skill++- When the user wants release management or source map upload only, use generic `sentry` CLI commands directly without a full debug workflow.+- When the user explicitly wants dashboard/MCP-based investigation instead of CLI.diff --git a/.agents/skills/use-sentry-cli-debug/references/vibe-remote.md b/.agents/skills/use-sentry-cli-debug/references/vibe-remote.mdnew file mode 100644index 000000000..c68148d4b--- /dev/null+++ b/.agents/skills/use-sentry-cli-debug/references/vibe-remote.md@@ -0,0 +1,54 @@+# Vibe Remote Sentry Context++This repository already initializes the Python Sentry SDK in two entry points:++- `main.py` initializes Sentry for the main service+- `vibe/ui_server.py` initializes Sentry for the Flask UI++Current runtime metadata attached during initialization:++- `release = vibe-remote@<package-version>`+- tag `component = service|ui`+- tag `mode = <config.mode>`+- tag `primary_platform = <config.platforms.primary>`+- tag `deployment_environment = <resolved environment>`++Current structured contexts include:++- `runtime`+- `host`+- `deployment`++Environment resolution currently behaves like this:++1. Use `VIBE_SENTRY_ENVIRONMENT` or `SENTRY_ENVIRONMENT` if set.+2. Else use `VIBE_DEPLOYMENT_ENV` if set.+3. Else use `regression` when `VIBE_REMOTE_HOME` contains `three-regression`.+4. Else use `integration` when `E2E_TEST_MODE=true|1|yes`.+5. Else default to `local`.++Useful query ideas for this repo:++```bash+# Recent unresolved regression issues+sentry issue list <org>/<project> --query 'is:unresolved environment:regression'++# Service-only failures+sentry issue list <org>/<project> --query 'component:service'++# UI-only failures+sentry issue list <org>/<project> --query 'component:ui'++# Platform-focused drilldown+sentry issue list <org>/<project> --query 'primary_platform:slack'+sentry issue list <org>/<project> --query 'primary_platform:discord'+sentry issue list <org>/<project> --query 'primary_platform:lark'++# Deployment mode focused drilldown+sentry issue list <org>/<project> --query 'mode:self_host'+```++Operational note:++- Sentry is useful for grouped failures, stack traces, events, traces, and correlated logs.+- Local logs remain the fallback for configuration mistakes, startup failures before SDK init, and any problem that was only logged but never captured as an exception.diff --git a/core/handlers/command_handlers.py b/core/handlers/command_handlers.pyindex 2e0d6c7b4..55d068e3a 100644--- a/core/handlers/command_handlers.py+++ b/core/handlers/command_handlers.py@@ -367,6 +367,8 @@ class CommandHandlers(BaseHandler):platform = context.platform or (context.platform_specific or {}).get("platform") or self.config.platformplatform_name = str(platform).capitalize()+ is_dm = bool((context.platform_specific or {}).get("is_dm", False))+# Get user and channel infotry:user_info = await im_client.get_user_info(context.user_id)@@ -374,16 +376,25 @@ class CommandHandlers(BaseHandler):logger.warning(f"Failed to get user info: {e}")user_info = {"id": context.user_id}- try:- channel_info = await im_client.get_channel_info(context.channel_id)- except Exception as e:- logger.warning(f"Failed to get channel info: {e}")+ channel_info = None+ if platform == "slack" and is_dm:channel_info = {"id": context.channel_id,- "name": (- self._t("command.start.directMessage") if context.channel_id.startswith("D") else context.channel_id- ),+ "name": self._t("command.start.directMessage"),}+ else:+ try:+ channel_info = await im_client.get_channel_info(context.channel_id)+ except Exception as e:+ logger.warning(f"Failed to get channel info: {e}")+ channel_info = {+ "id": context.channel_id,+ "name": (+ self._t("command.start.directMessage")+ if context.channel_id.startswith("D")+ else context.channel_id+ ),+ }agent_name = self.controller.resolve_agent_for_context(context)default_agent = getattr(self.controller.agent_service, "default_agent", None)@@ -392,7 +403,6 @@ class CommandHandlers(BaseHandler):# Determine whether this conversation supports threads.# If it does, each new thread is already a fresh session, so the# "New Session" button/command is unnecessary.- is_dm = bool((context.platform_specific or {}).get("is_dm", False))supports_threads = (getattr(im_client, "should_use_thread_for_dm_session", lambda: False)()if is_dmdiff --git a/docs/WINDOWS_WSL_ZH.md b/docs/WINDOWS_WSL_ZH.mdnew file mode 100644index 000000000..5af90e16f--- /dev/null+++ b/docs/WINDOWS_WSL_ZH.md@@ -0,0 +1,214 @@+# 在 Windows 上通过 WSL 使用 Vibe Remote++这篇文档面向希望在 Windows 电脑上使用 Vibe Remote 的用户。++如果你发现原生 Windows 运行某些 Agent CLI 不够稳定,或者希望获得更接近 Linux/macOS 的命令行体验,推荐使用 WSL 运行 Vibe Remote。++## 什么是 WSL++WSL 是 `Windows Subsystem for Linux`。++简单说,它让你可以在 Windows 里运行一个 Linux 用户态环境。对 Vibe Remote 这类依赖命令行工具、Python、Node、Agent CLI 的程序来说,WSL 通常比原生 Windows 更顺畅。++## 什么时候推荐用 WSL++推荐优先使用 WSL 的情况:++- 你主要使用 OpenCode+- 你希望尽量减少 Windows 原生兼容性问题+- 你习惯 Linux 命令行+- 你的项目本身已经在 WSL 开发++如果你主要使用 Claude Code 或 Codex,WSL 同样是一个很稳妥的方案。++## 总体思路++推荐的运行方式是:++- Windows 负责浏览器和聊天工具+- WSL 负责运行 Vibe Remote+- Agent CLI 也安装在 WSL 里+- 项目代码放在 WSL 的 Linux 文件系统里++这样做的好处是:++- 环境更统一+- 大多数命令行工具行为更接近官方文档+- 避免一部分原生 Windows 的进程和路径兼容问题++## 先决条件++开始前请确认:++- 你已经安装 WSL2+- 你已经安装一个 Linux 发行版,例如 Ubuntu+- 你能打开 WSL 终端+- 你的 Windows 浏览器可以访问本机地址++## 推荐目录++建议把项目放在 WSL 自己的 Linux 文件系统里,例如:++```bash+~/work+```++不建议优先把项目放在 `/mnt/c/...` 下长期使用。++原因是:++- 一些工具在 `/mnt/c/...` 下会更慢+- 文件监听、权限和路径行为更容易出现边角问题+- Agent CLI 在原生 Linux 路径里通常更稳定++## 安装 Vibe Remote++在 WSL 终端中执行:++```bash+curl -fsSL https://raw.githubusercontent.com/cyhhao/vibe-remote/master/install.sh | bash+```++安装完成后启动:++```bash+vibe+```++## 打开 Web UI++Vibe Remote 默认会在运行它的那台机器上监听:++```text+http://127.0.0.1:5123+```++在现代 WSL2 环境里,通常可以直接在 Windows 浏览器里打开:++```text+http://127.0.0.1:5123+```++如果浏览器没有自动弹出,手动打开上面的地址即可。++## 安装 Agent CLI++重要:请把你要使用的 Agent CLI 也安装在 WSL 里,而不是只安装在 Windows 里。++例如:++- `claude`+- `codex`+- `opencode`++Vibe Remote 会从它自己的运行环境里调用这些命令。如果 Vibe Remote 跑在 WSL,那么这些 CLI 也应该能在 WSL 终端里直接执行。++你可以先在 WSL 里确认:++```bash+which claude+which codex+which opencode+```++如果某个命令找不到,请先在 WSL 内完成安装。++## 设置工作目录++在 Web UI 的设置向导或 Dashboard 中,把默认工作目录设置成 WSL 路径,例如:++```text+/home/<your-user>/work+```++不要把默认工作目录优先设成 Windows 风格路径,例如:++```text+C:\Users\...+```++也不要优先设成:++```text+/mnt/c/Users/...+```++如果你必须访问 Windows 文件,也可以临时使用 `/mnt/c/...`,但不建议把它作为长期默认工作目录。++## 推荐的使用方式++### 方案 A:全部跑在 WSL++这是最推荐的方式。++- Vibe Remote 跑在 WSL+- Agent CLI 跑在 WSL+- 项目代码放在 WSL+- 浏览器在 Windows 中访问 `http://127.0.0.1:5123`++### 方案 B:Windows 只负责界面++这也是推荐做法。++- Slack / Discord / 微信 / 飞书客户端照常装在 Windows+- 浏览器在 Windows 中打开 Web UI+- 所有实际执行代码的命令都在 WSL 内完成++## 常见问题++### 1. 浏览器没有自动打开++这是正常的。++直接在 Windows 浏览器中打开:++```text+http://127.0.0.1:5123+```++### 2. 在 Web UI 里点安装 Agent 失败++如果你在 WSL 中运行 Vibe Remote,而在 Windows 浏览器中操作,有时本地安全校验可能导致安装接口失败。++如果出现这种情况,不要卡在 UI 按钮里,直接在 WSL 终端里手动安装对应 CLI,然后回到 Web UI 填路径或重新检测即可。++### 3. OpenCode 在 Windows 原生环境里不够稳定++如果你主要使用 OpenCode,优先推荐在 WSL 中运行它。++这通常比原生 Windows 更稳定,也更接近 OpenCode 官方推荐的使用方式。++### 4. 可以在 WSL 里用 Docker 吗++可以,但前提是你的 Docker Desktop 已开启 WSL 集成,或者你自己在 WSL 里具备可用的 Docker 环境。++如果你只是在本机日常使用 Vibe Remote,本身并不要求必须用 Docker。++## 快速检查清单++在 WSL 中确认以下命令都正常:++```bash+vibe version+vibe doctor+which claude+which codex+which opencode+```++然后在 Windows 浏览器中确认:++```text+http://127.0.0.1:5123+```++可以正常打开。++## 一句话建议++如果你在 Windows 上想获得更稳定的 Vibe Remote 使用体验,推荐采用下面这套组合:++- Windows:浏览器 + 聊天工具+- WSL:Vibe Remote + Agent CLI + 代码仓库++这通常是当前最稳妥、最省心的方案。diff --git a/modules/agents/opencode/server.py b/modules/agents/opencode/server.pyindex 87a983423..0723e9642 100644--- a/modules/agents/opencode/server.py+++ b/modules/agents/opencode/server.py@@ -17,6 +17,7 @@ from typing import Any, Dict, List, Optionalimport aiohttpfrom config import paths+from vibe import runtimefrom vibe.opencode_config import load_first_opencode_user_configlogger = logging.getLogger(__name__)@@ -146,29 +147,11 @@ class OpenCodeServerManager:@staticmethoddef _pid_exists(pid: int) -> bool:- if not isinstance(pid, int) or pid <= 0:- return False- try:- os.kill(pid, 0)- return True- except ProcessLookupError:- return False- except PermissionError:- return True+ return runtime.pid_alive(pid)@staticmethoddef _get_pid_command(pid: int) -> Optional[str]:- try:- result = subprocess.run(- ["ps", "-p", str(pid), "-o", "command="],- capture_output=True,- text=True,- check=False,- )- except Exception:- return None- cmd = (result.stdout or "").strip()- return cmd or None+ return runtime.get_process_command(pid)@staticmethoddef _is_opencode_serve_cmd(command: str, port: int) -> bool:@@ -187,6 +170,36 @@ class OpenCodeServerManager:@staticmethoddef _find_opencode_serve_pids(port: int) -> List[int]:+ if os.name == "nt":+ try:+ result = subprocess.run(+ ["netstat", "-ano", "-p", "tcp"],+ capture_output=True,+ text=True,+ check=False,+ )+ except Exception:+ return []++ pids: List[int] = []+ for line in (result.stdout or "").splitlines():+ parts = line.split()+ if len(parts) < 5 or parts[0].upper() != "TCP":+ continue+ local_addr = parts[1]+ state = parts[3].upper()+ pid_str = parts[4]+ if state != "LISTENING" or local_addr.rsplit(":", 1)[-1] != str(port):+ continue+ try:+ pid = int(pid_str)+ except ValueError:+ continue+ command = runtime.get_process_command(pid)+ if command and OpenCodeServerManager._is_opencode_serve_cmd(command, port):+ pids.append(pid)+ return pids+try:result = subprocess.run(["ps", "-ax", "-o", "pid=,command="],@@ -216,24 +229,8 @@ class OpenCodeServerManager:async def _terminate_pid(self, pid: int, reason: str) -> None:logger.info(f"Stopping OpenCode server pid={pid} ({reason})")- try:- os.kill(pid, signal.SIGTERM)- except ProcessLookupError:- return- except Exception as e:- logger.debug(f"Failed to terminate OpenCode server pid={pid}: {e}")- return-- start_time = time.monotonic()- while time.monotonic() - start_time < 5:- if not self._pid_exists(pid):- return- await asyncio.sleep(0.25)-- try:- os.kill(pid, signal.SIGKILL)- except Exception:- pass+ if not runtime.stop_pid(pid, timeout=5) and self._pid_exists(pid):+ logger.debug("Failed to terminate OpenCode server pid=%s", pid)async def _cleanup_orphaned_managed_server(self) -> None:info = self._read_pid_file()diff --git a/modules/im/slack.py b/modules/im/slack.pyindex d00a968a3..283fc6811 100644--- a/modules/im/slack.py+++ b/modules/im/slack.py@@ -239,15 +239,53 @@ class SlackBot(BaseIMClient):# Fallback to original text if conversion failsreturn text+ @staticmethod+ def _is_dm_context(context: MessageContext) -> bool:+ if bool((context.platform_specific or {}).get("is_dm", False)):+ return True+ return isinstance(context.channel_id, str) and context.channel_id.startswith("D")++ async def _open_dm_channel(self, user_id: str) -> Optional[str]:+ self._ensure_clients()+ resp = await self.web_client.conversations_open(users=[user_id])+ if not resp.get("ok"):+ logger.warning("Failed to open DM channel with user %s", user_id)+ return None+ return resp.get("channel", {}).get("id")++ async def _post_message_with_dm_recovery(+ self,+ context: MessageContext,+ kwargs: Dict[str, Any],+ *,+ log_label: str,+ ):+ try:+ return await self.web_client.chat_postMessage(**kwargs)+ except SlackApiError as err:+ error_code = err.response.get("error") if getattr(err, "response", None) else None+ if error_code != "channel_not_found" or not self._is_dm_context(context) or not context.user_id:+ raise++ recovered_channel_id = await self._open_dm_channel(context.user_id)+ if not recovered_channel_id or recovered_channel_id == kwargs.get("channel"):+ raise++ logger.warning(+ "Retrying Slack %s in recovered DM channel %s for user %s",+ log_label,+ recovered_channel_id,+ context.user_id,+ )+ kwargs["channel"] = recovered_channel_id+ context.channel_id = recovered_channel_id+ return await self.web_client.chat_postMessage(**kwargs)+async def send_dm(self, user_id: str, text: str, **kwargs) -> Optional[str]:"""Send a direct message to a Slack user by opening a DM channel first."""self._ensure_clients()try:- resp = await self.web_client.conversations_open(users=[user_id])- if not resp.get("ok"):- logger.warning("Failed to open DM channel with user %s", user_id)- return None- dm_channel = resp.get("channel", {}).get("id")+ dm_channel = await self._open_dm_channel(user_id)if not dm_channel:return Nonemsg_kwargs = {"channel": dm_channel, "text": text}@@ -305,7 +343,11 @@ class SlackBot(BaseIMClient):]# Send message- response = await self.web_client.chat_postMessage(**kwargs)+ response = await self._post_message_with_dm_recovery(+ context,+ kwargs,+ log_label="message send",+ )# Mark thread as active if we sent a message to a threadif self.settings_manager and (context.thread_id or reply_to):@@ -934,7 +976,11 @@ class SlackBot(BaseIMClient):if context.thread_id:kwargs["thread_ts"] = context.thread_id- response = await self.web_client.chat_postMessage(**kwargs)+ response = await self._post_message_with_dm_recovery(+ context,+ kwargs,+ log_label="message-with-buttons send",+ )# Mark thread as active if we sent a message to a threadif self.settings_manager and context.thread_id:diff --git a/tests/test_command_handler_user_names.py b/tests/test_command_handler_user_names.pyindex f27990c74..648bb97ca 100644--- a/tests/test_command_handler_user_names.py+++ b/tests/test_command_handler_user_names.py@@ -52,15 +52,25 @@ class _StubIMClient:def __init__(self, user_info):self.user_info = user_infoself.sent_messages = []+ self.sent_button_messages = []+ self.channel_info_calls = []self.formatter = Noneasync def get_user_info(self, user_id):return self.user_info+ async def get_channel_info(self, channel_id):+ self.channel_info_calls.append(channel_id)+ return {"id": channel_id, "name": channel_id}+async def send_message(self, context, text, parse_mode=None):self.sent_messages.append((context.channel_id, text))return "T1"+ async def send_message_with_buttons(self, context, text, keyboard, parse_mode=None):+ self.sent_button_messages.append((context.channel_id, text, keyboard))+ return "T2"+class _StubSettingsManager:def __init__(self):@@ -152,6 +162,23 @@ class CommandHandlerUserNameTests(unittest.IsolatedAsyncioTestCase):[("wx-chat", "🆕 已开启新的会话。你下一条消息会从全新对话开始。")],)+ async def test_slack_dm_start_skips_channel_info_lookup(self):+ controller = _StubController({"display_name": "Alex"})+ handler = CommandHandlers(controller)+ context = MessageContext(+ user_id="U0E0FM3QT",+ channel_id="D123",+ platform="slack",+ platform_specific={"is_dm": True, "platform": "slack"},+ )++ await handler.handle_start(context)++ self.assertEqual(controller.im_client.channel_info_calls, [])+ self.assertEqual(len(controller.im_client.sent_button_messages), 1)+ _, text, _ = controller.im_client.sent_button_messages[0]+ self.assertIn("私信", text)+async def _clear_sessions(_settings_key):return {}diff --git a/tests/test_opencode_server.py b/tests/test_opencode_server.pyindex c727e6b13..1fb088e79 100644--- a/tests/test_opencode_server.py+++ b/tests/test_opencode_server.py@@ -106,6 +106,27 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):},)+ async def test_find_opencode_serve_pids_windows_uses_netstat_and_command_lookup(self):+ netstat_output = """+ TCP 127.0.0.1:4096 0.0.0.0:0 LISTENING 1234+ TCP 127.0.0.1:7777 0.0.0.0:0 LISTENING 7777+"""++ with patch.object(SERVER_MODULE.os, "name", "nt"):+ with patch.object(+ SERVER_MODULE.subprocess,+ "run",+ return_value=types.SimpleNamespace(stdout=netstat_output),+ ):+ with patch.object(+ SERVER_MODULE.runtime,+ "get_process_command",+ side_effect=lambda pid: "opencode serve --port=4096" if pid == 1234 else "python app.py",+ ):+ pids = OpenCodeServerManager._find_opencode_serve_pids(4096)++ self.assertEqual(pids, [1234])+if __name__ == "__main__":unittest.main()diff --git a/tests/test_slack_dm_mentions.py b/tests/test_slack_dm_mentions.pyindex ad01d6993..d297ec34f 100644--- a/tests/test_slack_dm_mentions.py+++ b/tests/test_slack_dm_mentions.py@@ -5,11 +5,28 @@ import typesfrom pathlib import Pathfrom config.v2_config import SlackConfig+from modules.im.base import InlineButton, InlineKeyboard, MessageContextdef _install_slack_stubs() -> None:if "aiohttp" not in sys.modules:- sys.modules["aiohttp"] = types.ModuleType("aiohttp")+ aiohttp_mod = types.ModuleType("aiohttp")++ class _ClientWebSocketResponse:+ closed = False++ class _ClientSession:+ async def close(self):+ return None++ class _ClientTimeout:+ def __init__(self, *args, **kwargs):+ pass++ aiohttp_mod.ClientWebSocketResponse = _ClientWebSocketResponse+ aiohttp_mod.ClientSession = _ClientSession+ aiohttp_mod.ClientTimeout = _ClientTimeout+ sys.modules["aiohttp"] = aiohttp_modif "markdown_to_mrkdwn" not in sys.modules:markdown_mod = types.ModuleType("markdown_to_mrkdwn")@@ -52,7 +69,9 @@ def _install_slack_stubs() -> None:passclass _SlackApiError(Exception):- pass+ def __init__(self, message="", response=None):+ super().__init__(message)+ self.response = responseweb_async_mod.AsyncWebClient = _AsyncWebClientsocket_mode_aiohttp_mod.SocketModeClient = _SocketModeClient@@ -97,6 +116,83 @@ from modules.im.slack import SlackBotclass SlackDmMentionTests(unittest.IsolatedAsyncioTestCase):+ async def test_send_message_recovers_dm_channel_after_channel_not_found(self):+ slack = SlackBot(SlackConfig(bot_token="xoxb-test"))+ sent_channels = []++ class _WebClient:+ def __init__(self):+ self.fail_once = True++ async def chat_postMessage(self, **kwargs):+ sent_channels.append(kwargs["channel"])+ if self.fail_once:+ self.fail_once = False+ raise sys.modules["slack_sdk.errors"].SlackApiError(+ "channel missing",+ response={"error": "channel_not_found"},+ )+ return {"ts": "1710000000.000001"}++ async def conversations_open(self, users):+ return {"ok": True, "channel": {"id": "D999"}}++ slack.web_client = _WebClient()+ context = MessageContext(+ user_id="U123",+ channel_id="D123",+ thread_id="1710000000.000100",+ platform_specific={"is_dm": True},+ )++ message_ts = await slack.send_message(context, "hello", parse_mode="markdown")++ self.assertEqual(message_ts, "1710000000.000001")+ self.assertEqual(sent_channels, ["D123", "D999"])+ self.assertEqual(context.channel_id, "D999")++ async def test_send_message_with_buttons_recovers_dm_channel_after_channel_not_found(self):+ slack = SlackBot(SlackConfig(bot_token="xoxb-test"))+ sent_channels = []++ class _WebClient:+ def __init__(self):+ self.fail_once = True++ async def chat_postMessage(self, **kwargs):+ sent_channels.append(kwargs["channel"])+ if self.fail_once:+ self.fail_once = False+ raise sys.modules["slack_sdk.errors"].SlackApiError(+ "channel missing",+ response={"error": "channel_not_found"},+ )+ return {"ts": "1710000000.000002"}++ async def conversations_open(self, users):+ return {"ok": True, "channel": {"id": "D999"}}++ slack.web_client = _WebClient()+ context = MessageContext(+ user_id="U123",+ channel_id="D123",+ thread_id="1710000000.000100",+ platform_specific={"is_dm": True},+ )+ keyboard = InlineKeyboard(+ buttons=[+ [+ InlineButton(text="One", callback_data="choose:1")+ ]+ ]+ )++ message_ts = await slack.send_message_with_buttons(context, "hello", keyboard, parse_mode="markdown")++ self.assertEqual(message_ts, "1710000000.000002")+ self.assertEqual(sent_channels, ["D123", "D999"])+ self.assertEqual(context.channel_id, "D999")+async def test_get_user_info_prefers_normalized_profile_names(self):slack = SlackBot(SlackConfig(bot_token="xoxb-test"))diff --git a/tests/test_ui_server_logs.py b/tests/test_ui_server_logs.pyindex 7ebe4342e..3ee6e9fca 100644--- a/tests/test_ui_server_logs.py+++ b/tests/test_ui_server_logs.py@@ -5,6 +5,7 @@ from datetime import datetimefrom config import pathsfrom vibe.ui_server import app+from vibe import runtimedef _set_mtime(path, timestamp: str) -> None:@@ -205,3 +206,24 @@ def test_logs_endpoint_falls_back_to_service_for_unknown_source(monkeypatch, tmpassert payload["source"] == "all"assert payload["total"] == 1assert payload["logs"][0]["logger"] == "asyncio"+++def test_status_endpoint_degrades_when_pid_probe_raises(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ paths.ensure_data_dirs()+ paths.get_runtime_pid_path().write_text("12345", encoding="utf-8")+ runtime.write_status("running", detail="pid=12345", service_pid=12345)++ def _raise(_pid):+ raise SystemError("boom")++ monkeypatch.setattr(runtime, "pid_alive", _raise)++ client = app.test_client()+ response = client.get("/status")++ assert response.status_code == 200+ payload = response.get_json()+ assert payload["running"] is False+ assert payload["pid"] is None+ assert payload["state"] == "stopped"diff --git a/tests/test_upgrade_flow.py b/tests/test_upgrade_flow.pyindex 1757854dc..f831b6064 100644--- a/tests/test_upgrade_flow.py+++ b/tests/test_upgrade_flow.py@@ -182,7 +182,7 @@ def test_do_upgrade_uses_upgrade_plan_env_and_restarts(monkeypatch):monkeypatch.setattr(api, "build_upgrade_plan", lambda **kwargs: plan)monkeypatch.setattr(api, "get_running_vibe_path", lambda: "/custom/bin/vibe")- monkeypatch.setattr(api, "get_restart_shell_command", lambda **kwargs: "/custom/bin/vibe")+ monkeypatch.setattr(api, "get_restart_command", lambda **kwargs: ["/custom/bin/vibe"])def fake_run(cmd, **kwargs):calls["run_cmd"] = cmd@@ -211,8 +211,10 @@ def test_do_upgrade_uses_upgrade_plan_env_and_restarts(monkeypatch):assert calls["run_kwargs"]["env"] == plan.envsafe_cwd = calls["run_kwargs"].get("cwd")assert safe_cwd and os.path.isabs(safe_cwd), f"subprocess.run cwd must be an absolute path, got {safe_cwd!r}"- assert calls["popen_cmd"] == "sleep 2 && /custom/bin/vibe"- assert calls["popen_kwargs"]["shell"] is True+ assert calls["popen_cmd"][0] == sys.executable+ assert calls["popen_cmd"][1] == "-c"+ assert "time.sleep(2.0)" in calls["popen_cmd"][2]+ assert "/custom/bin/vibe" in calls["popen_cmd"][2]assert calls["popen_kwargs"]["start_new_session"] is Truepopen_cwd = calls["popen_kwargs"].get("cwd")assert popen_cwd and os.path.isabs(popen_cwd), f"Popen cwd must be an absolute path, got {popen_cwd!r}"diff --git a/tests/test_vibe_cli.py b/tests/test_vibe_cli.pyindex d44821ceb..0e2b790b6 100644--- a/tests/test_vibe_cli.py+++ b/tests/test_vibe_cli.py@@ -3,9 +3,11 @@ import osimport signalimport sysfrom pathlib import Path+from unittest.mock import patchfrom config import pathsfrom vibe import runtime+from vibe import clidef test_default_config_written(tmp_path, monkeypatch):@@ -29,3 +31,62 @@ def test_stop_process_handles_missing_pid(tmp_path, monkeypatch):monkeypatch.setattr(paths, "get_vibe_remote_dir", lambda: tmp_path / ".vibe_remote")runtime.ensure_dirs()assert runtime.stop_process(paths.get_runtime_pid_path()) is False+++def test_pid_alive_returns_true_on_permission_error(monkeypatch):+ monkeypatch.setattr(runtime.os, "name", "posix", raising=False)++ def _raise_permission(_pid, _sig):+ raise PermissionError()++ monkeypatch.setattr(runtime.os, "kill", _raise_permission)++ assert runtime.pid_alive(12345) is True+++def test_pid_alive_delegates_to_windows_probe(monkeypatch):+ monkeypatch.setattr(runtime.os, "name", "nt", raising=False)+ monkeypatch.setattr(runtime, "_pid_alive_windows", lambda pid: pid == 4321)++ assert runtime.pid_alive(4321) is True+ assert runtime.pid_alive(1234) is False+++def test_cli_pid_alive_reuses_runtime_impl(monkeypatch):+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 99)++ assert cli._pid_alive(99) is True+ assert cli._pid_alive(100) is False+++def test_stop_process_delegates_to_windows_terminator(tmp_path, monkeypatch):+ pid_path = tmp_path / "service.pid"+ pid_path.write_text("4321", encoding="utf-8")++ monkeypatch.setattr(runtime.os, "name", "nt", raising=False)+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 4321)+ monkeypatch.setattr(runtime, "_terminate_process_windows", lambda pid, timeout=5: pid == 4321)++ assert runtime.stop_process(pid_path) is True+ assert not pid_path.exists()+++def test_cli_stop_process_reuses_runtime_impl(tmp_path, monkeypatch):+ pid_path = tmp_path / "service.pid"+ pid_path.write_text("123", encoding="utf-8")+ monkeypatch.setattr(runtime, "stop_process", lambda path: path == pid_path)++ assert cli._stop_process(pid_path) is True+++def test_cli_stop_opencode_server_uses_runtime_helpers(tmp_path, monkeypatch):+ pid_file = tmp_path / "opencode_server.json"+ pid_file.write_text('{"pid": 321}', encoding="utf-8")++ monkeypatch.setattr(paths, "get_logs_dir", lambda: tmp_path)+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 321)+ monkeypatch.setattr(runtime, "get_process_command", lambda pid: "C:\\opencode.exe serve --port=4096")+ monkeypatch.setattr(runtime, "stop_pid", lambda pid, timeout=5: pid == 321)++ assert cli._stop_opencode_server() is True+ assert not pid_file.exists()diff --git a/vibe/api.py b/vibe/api.pyindex 9b6cc7fc7..2d1dbf0e2 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -4,6 +4,7 @@ import loggingimport osimport shutilimport subprocess+import sysimport timeimport urllib.requestfrom pathlib import Path@@ -29,7 +30,7 @@ from vibe.opencode_config import (from vibe.upgrade import (build_upgrade_plan,get_latest_version_info,- get_restart_shell_command,+ get_restart_command,get_running_vibe_path,get_safe_cwd,)@@ -42,6 +43,23 @@ _OPENCODE_OPTIONS_CACHE: dict[str, dict] = {}_OPENCODE_OPTIONS_TTL_SECONDS = 30.0+def _spawn_delayed_restart(command: list[str], cwd: str, delay_seconds: float = 2.0) -> None:+ helper_code = (+ "import subprocess, time\n"+ f"time.sleep({delay_seconds!r})\n"+ f"subprocess.Popen({command!r}, cwd={cwd!r}, stdout=subprocess.DEVNULL, "+ "stderr=subprocess.DEVNULL, close_fds=True)\n"+ )+ subprocess.Popen(+ [sys.executable, "-c", helper_code],+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ start_new_session=True,+ close_fds=True,+ cwd=cwd,+ )++def _is_executable_file(path: Path) -> bool:return path.exists() and path.is_file() and os.access(path, os.X_OK)@@ -681,14 +699,9 @@ def do_upgrade(auto_restart: bool = True) -> dict:if result.returncode == 0:restarting = Falseif auto_restart:- restart_cmd = f"sleep 2 && {get_restart_shell_command(vibe_path=current_vibe_path)}"- subprocess.Popen(- restart_cmd,- shell=True,- stdout=subprocess.DEVNULL,- stderr=subprocess.DEVNULL,- start_new_session=True,- cwd=safe_cwd,+ _spawn_delayed_restart(+ get_restart_command(vibe_path=current_vibe_path),+ safe_cwd,)restarting = Truediff --git a/vibe/cli.py b/vibe/cli.pyindex 863677d1d..8b6486b7e 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -36,11 +36,7 @@ def _read_json(path):def _pid_alive(pid):- try:- os.kill(pid, 0)- return True- except OSError:- return False+ return runtime.pid_alive(pid)def _in_ssh_session() -> bool:@@ -134,15 +130,7 @@ def _spawn_background(def _stop_process(pid_path):- if not pid_path.exists():- return False- pid = int(pid_path.read_text(encoding="utf-8").strip())- if not _pid_alive(pid):- pid_path.unlink(missing_ok=True)- return False- os.kill(pid, signal.SIGTERM)- pid_path.unlink(missing_ok=True)- return True+ return runtime.stop_process(pid_path)def _render_status():@@ -519,28 +507,18 @@ def _stop_opencode_server():return False# Verify it's actually an opencode serve process- try:- import subprocess-- result = subprocess.run(- ["ps", "-p", str(pid), "-o", "command="],- capture_output=True,- text=True,- )- cmd = result.stdout.strip()- if "opencode" not in cmd or "serve" not in cmd:- return False- except Exception as e:- logger.debug("Failed to verify OpenCode process (pid=%s): %s", pid, e)+ cmd = runtime.get_process_command(pid)+ if not cmd:+ logger.debug("Failed to verify OpenCode process (pid=%s): command not available", pid)+ return False+ if "opencode" not in cmd or "serve" not in cmd:return False- try:- os.kill(pid, signal.SIGTERM)+ if runtime.stop_pid(pid, timeout=5):pid_file.unlink(missing_ok=True)return True- except Exception as e:- logger.warning("Failed to stop OpenCode server (pid=%s): %s", pid, e)- return False+ logger.warning("Failed to stop OpenCode server (pid=%s)", pid)+ return Falsedef cmd_stop():diff --git a/vibe/runtime.py b/vibe/runtime.pyindex d652bee8a..229942d93 100644--- a/vibe/runtime.py+++ b/vibe/runtime.py@@ -1,4 +1,5 @@import json+import loggingimport osimport signalimport subprocess@@ -19,6 +20,9 @@ from config.v2_config import ()+logger = logging.getLogger(__name__)++def get_package_root() -> Path:"""Get the root directory of the vibe package."""return Path(__file__).resolve().parent@@ -118,14 +122,151 @@ def read_json(path):return json.loads(path.read_text(encoding="utf-8"))+def _pid_alive_windows(pid: int) -> bool:+ if pid <= 0:+ return False++ try:+ import ctypes++ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)+ synchronize = 0x00100000+ query_limited_information = 0x1000+ still_active = 259++ handle = kernel32.OpenProcess(synchronize | query_limited_information, False, pid)+ if not handle:+ last_error = ctypes.get_last_error()+ # Access denied still means the process exists.+ if last_error == 5:+ return True+ return False++ try:+ exit_code = ctypes.c_ulong()+ if not kernel32.GetExitCodeProcess(handle, ctypes.byref(exit_code)):+ return False+ return exit_code.value == still_active+ finally:+ kernel32.CloseHandle(handle)+ except Exception:+ logger.debug("Windows pid_alive probe failed for pid=%s", pid, exc_info=True)+ return False+++def _terminate_process_windows(pid: int, timeout: float = 5) -> bool:+ if pid <= 0:+ return False++ try:+ import ctypes++ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)+ synchronize = 0x00100000+ query_limited_information = 0x1000+ process_terminate = 0x0001+ wait_object_0 = 0++ handle = kernel32.OpenProcess(+ synchronize | query_limited_information | process_terminate,+ False,+ pid,+ )+ if not handle:+ return not _pid_alive_windows(pid)++ try:+ if not kernel32.TerminateProcess(handle, 1):+ return False++ timeout_ms = max(0, int(timeout * 1000))+ wait_result = kernel32.WaitForSingleObject(handle, timeout_ms)+ return wait_result == wait_object_0+ finally:+ kernel32.CloseHandle(handle)+ except Exception:+ logger.debug("Windows process termination failed for pid=%s", pid, exc_info=True)+ return False+++def _get_process_command_windows(pid: int) -> str | None:+ script = f'$p = Get-CimInstance Win32_Process -Filter "ProcessId = {pid}"; if ($p) {{ $p.CommandLine }}'+ for shell in ("powershell", "pwsh"):+ try:+ result = subprocess.run(+ [shell, "-NoProfile", "-Command", script],+ capture_output=True,+ text=True,+ check=False,+ )+ except Exception:+ continue+ command = (result.stdout or "").strip()+ if command:+ return command+ return None+++def get_process_command(pid: int) -> str | None:+ if not isinstance(pid, int) or pid <= 0:+ return None++ if os.name == "nt":+ return _get_process_command_windows(pid)++ try:+ result = subprocess.run(+ ["ps", "-p", str(pid), "-o", "command="],+ capture_output=True,+ text=True,+ check=False,+ )+ except Exception:+ return None+ command = (result.stdout or "").strip()+ return command or None++def pid_alive(pid):+ if not isinstance(pid, int) or pid <= 0:+ return False++ if os.name == "nt":+ return _pid_alive_windows(pid)+try:os.kill(pid, 0)return True- except OSError:+ except ProcessLookupError:+ return False+ except PermissionError:+ return True+ except (OSError, ValueError, SystemError):return False+def stop_pid(pid: int, timeout: float = 5) -> bool:+ if not isinstance(pid, int) or pid <= 0:+ return False+ if not pid_alive(pid):+ return False++ if os.name == "nt":+ return _terminate_process_windows(pid, timeout=timeout)++ os.kill(pid, signal.SIGTERM)+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if not pid_alive(pid):+ return True+ time.sleep(0.2)+ try:+ os.kill(pid, signal.SIGKILL)+ except OSError:+ pass+ return True++def _log_path(name: str) -> Path:return paths.get_runtime_dir() / name@@ -158,20 +299,9 @@ def stop_process(pid_path, timeout=5):if not pid_alive(pid):pid_path.unlink(missing_ok=True)return False- os.kill(pid, signal.SIGTERM)+ stopped = stop_pid(pid, timeout=timeout)pid_path.unlink(missing_ok=True)- # Wait for the process to actually exit; SIGKILL if it doesn't- deadline = time.monotonic() + timeout- while time.monotonic() < deadline:- if not pid_alive(pid):- return True- time.sleep(0.2)- # Process didn't exit in time — force kill- try:- os.kill(pid, signal.SIGKILL)- except OSError:- pass- return True+ return stoppeddef write_status(state, detail=None, service_pid=None, ui_pid=None):diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 5d52d05c6..1ef0748ca 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -217,7 +217,11 @@ def status():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)))+ try:+ running = bool(pid and pid.isdigit() and runtime.pid_alive(int(pid)))+ except Exception as exc:+ logger.warning("Failed to inspect service pid %s: %s", pid, exc)+ running = Falsepayload["running"] = runningpayload["pid"] = int(pid) if pid and pid.isdigit() else Noneif running: