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.

fix(platform): handle restart pid handoff

cyhf0c02c2cb875
diff --git a/modules/im/feishu.py b/modules/im/feishu.py
index 995e34f3d..c2001d6b4 100644
--- a/modules/im/feishu.py
+++ b/modules/im/feishu.py
@@ -1499,13 +1499,22 @@ class FeishuBot(BaseIMClient):
# --- Dedup: prevent re-delivery of the same card action ---
# Include a hash of form values so that intentional re-submissions
# with different selections are not mistakenly deduplicated.
- form_hash = ""
+ interaction_hash = ""
if form_value:
try:
- form_hash = str(hash(json.dumps(form_value, sort_keys=True)))
+ interaction_hash = str(hash(json.dumps(form_value, sort_keys=True)))
except Exception:
- form_hash = str(id(form_value))
- dedup_key = f"card:{message_id}:{button_name or callback_data}:{user_id}:{form_hash}"
+ interaction_hash = str(id(form_value))
+ elif action.get("tag") in {"select_static", "multi_select_static"}:
+ select_state = {
+ "option": action.get("option"),
+ "options": action.get("options"),
+ }
+ try:
+ interaction_hash = str(hash(json.dumps(select_state, sort_keys=True)))
+ except Exception:
+ interaction_hash = str(id(select_state))
+ dedup_key = f"card:{message_id}:{button_name or callback_data}:{user_id}:{interaction_hash}"
if self._is_duplicate_event(dedup_key):
return
diff --git a/scripts/docker-entrypoint.sh b/scripts/docker-entrypoint.sh
index 136b6ba8f..0c85d18f8 100755
--- a/scripts/docker-entrypoint.sh
+++ b/scripts/docker-entrypoint.sh
@@ -40,16 +40,78 @@ runtime.write_status('${state}', '${detail}', ${service_pid}, ${ui_pid})
"
}
-exit_if_service_stopped() {
- local service_pid="$1"
- local ui_pid="$2"
+read_runtime_service_pid() {
+ local runtime_dir="$1"
+ local pid_file="$runtime_dir/vibe.pid"
+
+ if [ ! -f "$pid_file" ]; then
+ return 1
+ fi
+
+ local runtime_pid
+ runtime_pid="$(tr -d '[:space:]' < "$pid_file")"
+ if [[ ! "$runtime_pid" =~ ^[0-9]+$ ]]; then
+ return 1
+ fi
+
+ echo "$runtime_pid"
+}
+
+wait_for_replacement_service_pid() {
+ local runtime_dir="$1"
+ local previous_pid="$2"
+ local attempts=50
+
+ while [ "$attempts" -gt 0 ]; do
+ local runtime_pid=""
+ runtime_pid="$(read_runtime_service_pid "$runtime_dir" 2>/dev/null || true)"
+ if [ -n "$runtime_pid" ] && [ "$runtime_pid" != "$previous_pid" ] && kill -0 "$runtime_pid" 2>/dev/null; then
+ echo "$runtime_pid"
+ return 0
+ fi
+ sleep 0.1
+ attempts=$((attempts - 1))
+ done
+
+ return 1
+}
+
+ensure_service_pid() {
+ local runtime_dir="$1"
+ local service_pid="$2"
+ local ui_pid="$3"
+
+ local current_runtime_pid=""
+ current_runtime_pid="$(read_runtime_service_pid "$runtime_dir" 2>/dev/null || true)"
+ if [ -n "$current_runtime_pid" ] && [ "$current_runtime_pid" != "$service_pid" ] && kill -0 "$current_runtime_pid" 2>/dev/null; then
+ echo "$current_runtime_pid"
+ return 0
+ fi
if kill -0 "$service_pid" 2>/dev/null; then
+ echo "$service_pid"
return 0
fi
- local service_exit_code=0
- wait "$service_pid" 2>/dev/null || service_exit_code=$?
+ local replacement_pid=""
+ replacement_pid="$(wait_for_replacement_service_pid "$runtime_dir" "$service_pid" 2>/dev/null || true)"
+ if [ -n "$replacement_pid" ]; then
+ echo "Detected replacement service PID ${replacement_pid}, continuing supervisor loop." >&2
+ write_runtime_status "running" "service restarted in container" "$replacement_pid" "$ui_pid"
+ echo "$replacement_pid"
+ return 0
+ fi
+
+ local service_exit_code=1
+ local wait_status=0
+ if wait "$service_pid" 2>/dev/null; then
+ wait_status=0
+ else
+ wait_status=$?
+ fi
+ if [ "$wait_status" -ne 127 ]; then
+ service_exit_code="$wait_status"
+ fi
echo "Service exited unexpectedly (code: ${service_exit_code}), stopping container..." >&2
write_runtime_status "stopped" "service exited unexpectedly" "$service_pid" "$ui_pid"
exit "$service_exit_code"
@@ -97,7 +159,7 @@ run_ui_server('0.0.0.0', ${VIBE_UI_PORT:-5123})
CURRENT_UI_PID="$(cat "$RUNTIME_DIR/vibe-ui.pid")"
fi
- exit_if_service_stopped "$SERVICE_PID" "${CURRENT_UI_PID:-$UI_PID}"
+ SERVICE_PID="$(ensure_service_pid "$RUNTIME_DIR" "$SERVICE_PID" "${CURRENT_UI_PID:-$UI_PID}")"
if [ -z "$CURRENT_UI_PID" ]; then
UI_PID="$(start_ui_process "$RUNTIME_DIR")"
diff --git a/tests/test_docker_entrypoint_supervisor.py b/tests/test_docker_entrypoint_supervisor.py
index 116076387..54655b5b9 100644
--- a/tests/test_docker_entrypoint_supervisor.py
+++ b/tests/test_docker_entrypoint_supervisor.py
@@ -1,8 +1,10 @@
import os
import stat
import subprocess
+import sys
import tempfile
import textwrap
+import time
import unittest
from pathlib import Path
@@ -56,6 +58,82 @@ class DockerEntrypointSupervisorTests(unittest.TestCase):
self.assertEqual(result.returncode, 42, result.stdout + result.stderr)
self.assertIn("Service exited unexpectedly", result.stderr)
+ def test_full_mode_tracks_restarted_service_pid(self):
+ with tempfile.TemporaryDirectory() as tmpdir:
+ tmp_path = Path(tmpdir)
+ fake_python = tmp_path / "python"
+ fake_python.write_text(
+ textwrap.dedent(
+ """\
+ #!/usr/bin/env python3
+ import os
+ import subprocess
+ import sys
+ import threading
+ import time
+ from pathlib import Path
+
+ args = sys.argv[1:]
+ runtime_dir = Path(os.environ["VIBE_REMOTE_HOME"]) / "runtime"
+ runtime_dir.mkdir(parents=True, exist_ok=True)
+ real_python = os.environ["REAL_PYTHON"]
+
+ if args and args[0] == "main.py":
+ time.sleep(1)
+ sys.exit(42)
+
+ if len(args) >= 2 and args[0] == "-c":
+ code = args[1]
+ if "run_ui_server" in code:
+ def restart_service_later():
+ time.sleep(2)
+ proc = subprocess.Popen(
+ [real_python, "-c", "import time; time.sleep(30)"],
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ start_new_session=True,
+ )
+ (runtime_dir / "vibe.pid").write_text(str(proc.pid), encoding="utf-8")
+
+ threading.Thread(target=restart_service_later, daemon=True).start()
+ time.sleep(30)
+ sys.exit(0)
+ sys.exit(0)
+
+ sys.exit(0)
+ """
+ ),
+ encoding="utf-8",
+ )
+ fake_python.chmod(fake_python.stat().st_mode | stat.S_IEXEC)
+
+ env = os.environ.copy()
+ env["PATH"] = f"{tmp_path}{os.pathsep}{env.get('PATH', '')}"
+ env["VIBE_REMOTE_HOME"] = str(tmp_path / "home")
+ env["REAL_PYTHON"] = sys.executable
+
+ proc = subprocess.Popen(
+ ["bash", str(ENTRYPOINT), "full"],
+ cwd=REPO_ROOT,
+ env=env,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True,
+ )
+ try:
+ time.sleep(4)
+ self.assertIsNone(proc.poll())
+ finally:
+ proc.terminate()
+ try:
+ _stdout, stderr = proc.communicate(timeout=5)
+ except subprocess.TimeoutExpired:
+ proc.kill()
+ _stdout, stderr = proc.communicate(timeout=5)
+
+ self.assertNotIn("Service exited unexpectedly", stderr)
+ self.assertIn("Detected replacement service PID", stderr)
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_feishu_routing_card.py b/tests/test_feishu_routing_card.py
index 32669825e..f03ccf2eb 100644
--- a/tests/test_feishu_routing_card.py
+++ b/tests/test_feishu_routing_card.py
@@ -7,10 +7,14 @@ from types import SimpleNamespace
from unittest.mock import AsyncMock
from config.v2_config import LarkConfig
+from core.auth import AuthResult
from modules.im.base import MessageContext
def _install_opencode_utils_module() -> None:
+ if "aiohttp" not in sys.modules:
+ sys.modules["aiohttp"] = types.ModuleType("aiohttp")
+
if "modules.agents.opencode.utils" in sys.modules:
return
@@ -86,7 +90,9 @@ class FeishuRoutingCardTests(unittest.IsolatedAsyncioTestCase):
self.assertTrue(handled)
bot._patch_card_message.assert_awaited_once()
- _, card = bot._patch_card_message.await_args.args
+ first_call = bot._patch_card_message.await_args
+ assert first_call is not None
+ _, card = first_call.args
reasoning_select = self._find_select(card, "claude_reasoning")
reasoning_values = [option["value"] for option in reasoning_select["options"]]
@@ -100,6 +106,65 @@ class FeishuRoutingCardTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(draft["claude_model"], "claude-opus-4-6")
self.assertIsNone(draft["claude_reasoning_effort"])
+ async def test_select_changes_with_different_options_are_not_deduped(self):
+ bot = self._make_bot()
+ bot._patch_card_message = AsyncMock()
+ bot.check_authorization = lambda **kwargs: AuthResult(allowed=True)
+
+ current_routing = SimpleNamespace(
+ claude_agent="helper",
+ claude_model="claude-sonnet-4-5",
+ claude_reasoning_effort="high",
+ opencode_agent=None,
+ opencode_model=None,
+ opencode_reasoning_effort=None,
+ codex_model=None,
+ codex_reasoning_effort=None,
+ )
+ bot._routing_cache["chat:user"] = {
+ "current_routing": current_routing,
+ "draft_routing": bot._routing_draft_from_current(current_routing),
+ "_selected_backend": "claude",
+ "claude_agents": ["helper", "reviewer"],
+ "claude_models": ["claude-sonnet-4-5", "claude-sonnet-4-6", "claude-opus-4-6"],
+ "opencode_agents": [],
+ "opencode_models": {},
+ "opencode_default_config": {},
+ "codex_models": [],
+ }
+
+ first_event = {
+ "operator": {"open_id": "user"},
+ "context": {"open_message_id": "om_123", "open_chat_id": "chat"},
+ "action": {
+ "tag": "select_static",
+ "name": "claude_model",
+ "option": {"value": "claude-sonnet-4-6"},
+ },
+ }
+ second_event = {
+ "operator": {"open_id": "user"},
+ "context": {"open_message_id": "om_123", "open_chat_id": "chat"},
+ "action": {
+ "tag": "select_static",
+ "name": "claude_model",
+ "option": {"value": "claude-opus-4-6"},
+ },
+ }
+
+ await bot._async_handle_card_action(first_event)
+ await bot._async_handle_card_action(second_event)
+
+ self.assertEqual(bot._patch_card_message.await_count, 2)
+ draft = bot._routing_cache["chat:user"]["draft_routing"]
+ self.assertEqual(draft["claude_model"], "claude-opus-4-6")
+ latest_call = bot._patch_card_message.await_args
+ assert latest_call is not None
+ _, latest_card = latest_call.args
+ reasoning_select = self._find_select(latest_card, "claude_reasoning")
+ reasoning_values = [option["value"] for option in reasoning_select["options"]]
+ self.assertIn("max", reasoning_values)
+
if __name__ == "__main__":
unittest.main()