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): improve doctor logs and shutdown handling
cyhde2e50e15515
diff --git a/core/controller.py b/core/controller.pyindex 4c8b998a7..6e381a324 100644--- a/core/controller.py+++ b/core/controller.py@@ -548,7 +548,14 @@ class Controller:# Stop update checkertry:- self.update_checker.stop()+ update_task = self.update_checker.stop()+ if update_task and not update_task.done():+ loop = self._loop+ if loop and not loop.is_running() and not loop.is_closed():+ try:+ loop.run_until_complete(self.update_checker.wait_stopped(update_task))+ except Exception:+ passexcept Exception as e:logger.debug(f"Update checker cleanup skipped: {e}")diff --git a/core/update_checker.py b/core/update_checker.pyindex 74ebfe536..67ed66eed 100644--- a/core/update_checker.py+++ b/core/update_checker.py@@ -162,12 +162,26 @@ class UpdateChecker:f"auto_update={self.config.auto_update}, idle_minutes={self.config.idle_minutes})")- def stop(self) -> None:- """Stop the periodic update checker."""+ def stop(self) -> Optional[asyncio.Task]:+ """Stop the periodic update checker and return the cancelled task, if any."""self._running = False- if self._check_task:- self._check_task.cancel()- self._check_task = None+ task = self._check_task+ if task:+ task.cancel()+ return task++ async def wait_stopped(self, task: Optional[asyncio.Task] = None) -> None:+ """Wait for the periodic checker task to finish after cancellation."""+ task = task or self._check_task+ if not task:+ return+ try:+ await task+ except asyncio.CancelledError:+ pass+ finally:+ if self._check_task is task:+ self._check_task = Nonedef record_activity(self) -> None:"""Record user activity (called when a Slack message is received)."""diff --git a/scripts/docker-entrypoint.sh b/scripts/docker-entrypoint.shindex 0c85d18f8..e75b0fdfe 100755--- a/scripts/docker-entrypoint.sh+++ b/scripts/docker-entrypoint.sh@@ -57,6 +57,31 @@ read_runtime_service_pid() {echo "$runtime_pid"}+read_runtime_state() {+ local runtime_dir="$1"+ local status_file="$runtime_dir/status.json"++ if [ ! -f "$status_file" ]; then+ return 1+ fi++ python - "$status_file" <<'PY'+import json+import sys+from pathlib import Path++status_path = Path(sys.argv[1])+try:+ payload = json.loads(status_path.read_text(encoding="utf-8"))+except Exception:+ sys.exit(1)++state = payload.get("state")+if isinstance(state, str):+ print(state)+PY+}+wait_for_replacement_service_pid() {local runtime_dir="$1"local previous_pid="$2"@@ -76,6 +101,17 @@ wait_for_replacement_service_pid() {return 1}+is_intentional_service_stop_state() {+ case "$1" in+ stopped|stopping|restarting|starting)+ return 0+ ;;+ *)+ return 1+ ;;+ esac+}+ensure_service_pid() {local runtime_dir="$1"local service_pid="$2"@@ -102,6 +138,12 @@ ensure_service_pid() {return 0fi+ local runtime_state=""+ runtime_state="$(read_runtime_state "$runtime_dir" 2>/dev/null || true)"+ if is_intentional_service_stop_state "$runtime_state"; then+ return 0+ fi+local service_exit_code=1local wait_status=0if wait "$service_pid" 2>/dev/null; then@@ -159,17 +201,33 @@ run_ui_server('0.0.0.0', ${VIBE_UI_PORT:-5123})CURRENT_UI_PID="$(cat "$RUNTIME_DIR/vibe-ui.pid")"fi- SERVICE_PID="$(ensure_service_pid "$RUNTIME_DIR" "$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" ]; thenUI_PID="$(start_ui_process "$RUNTIME_DIR")"- write_runtime_status "running" "ui restarted" "$SERVICE_PID" "$UI_PID"+ CURRENT_STATE="$(read_runtime_state "$RUNTIME_DIR" 2>/dev/null || true)"+ if [ -z "$CURRENT_STATE" ]; then+ if [ -n "${SERVICE_PID:-}" ]; then+ CURRENT_STATE="running"+ else+ CURRENT_STATE="stopped"+ fi+ fi+ write_runtime_status "$CURRENT_STATE" "ui restarted" "${SERVICE_PID:-None}" "$UI_PID"elif ! kill -0 "$CURRENT_UI_PID" 2>/dev/null; thenUI_EXIT_CODE=0wait "$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")"- write_runtime_status "running" "ui restarted after crash" "$SERVICE_PID" "$UI_PID"+ CURRENT_STATE="$(read_runtime_state "$RUNTIME_DIR" 2>/dev/null || true)"+ if [ -z "$CURRENT_STATE" ]; then+ if [ -n "${SERVICE_PID:-}" ]; then+ CURRENT_STATE="running"+ else+ CURRENT_STATE="stopped"+ fi+ fi+ write_runtime_status "$CURRENT_STATE" "ui restarted after crash" "${SERVICE_PID:-None}" "$UI_PID"fisleep 1diff --git a/tests/e2e/test_settings.py b/tests/e2e/test_settings.pyindex 1a2c02b60..8d9622004 100644--- a/tests/e2e/test_settings.py+++ b/tests/e2e/test_settings.py@@ -54,7 +54,10 @@ class TestLogsAPI:"""POST /logs should return log lines and total count."""status, data = _post(f"{api_url}/logs", {"lines": 10})assert status == 200+ assert "source" in dataassert "logs" in data+ assert "sources" in dataassert "total" in dataassert isinstance(data["logs"], list)+ assert isinstance(data["sources"], list)assert isinstance(data["total"], int)diff --git a/tests/test_docker_entrypoint_supervisor.py b/tests/test_docker_entrypoint_supervisor.pyindex 54655b5b9..5639556b9 100644--- a/tests/test_docker_entrypoint_supervisor.py+++ b/tests/test_docker_entrypoint_supervisor.py@@ -1,4 +1,5 @@import os+import signalimport statimport subprocessimport sys@@ -119,21 +120,111 @@ class DockerEntrypointSupervisorTests(unittest.TestCase):stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True,+ start_new_session=True,)try:time.sleep(4)self.assertIsNone(proc.poll())finally:- proc.terminate()+ os.killpg(proc.pid, signal.SIGTERM)try:_stdout, stderr = proc.communicate(timeout=5)except subprocess.TimeoutExpired:- proc.kill()+ os.killpg(proc.pid, signal.SIGKILL)_stdout, stderr = proc.communicate(timeout=5)self.assertNotIn("Service exited unexpectedly", stderr)self.assertIn("Detected replacement service PID", stderr)+ def test_full_mode_keeps_ui_alive_when_service_is_stopped_intentionally(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 json+ import os+ 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)+ status_path = runtime_dir / "status.json"++ if args and args[0] == "main.py":+ time.sleep(1)+ sys.exit(0)++ if args and args[0] == "-":+ try:+ payload = json.loads(Path(args[1]).read_text(encoding="utf-8"))+ except Exception:+ sys.exit(1)+ state = payload.get("state")+ if isinstance(state, str):+ print(state)+ sys.exit(0)++ if len(args) >= 2 and args[0] == "-c":+ code = args[1]+ if "run_ui_server" in code:+ def stop_service_later():+ time.sleep(0.5)+ status_path.write_text(json.dumps({"state": "stopped"}), encoding="utf-8")++ threading.Thread(target=stop_service_later, daemon=True).start()+ time.sleep(30)+ sys.exit(0)+ if "write_status" in code:+ state = "running"+ if "stopping" in code:+ state = "stopping"+ elif "stopped" in code:+ state = "stopped"+ elif "restarting" in code:+ state = "restarting"+ status_path.write_text(json.dumps({"state": state}), encoding="utf-8")+ 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")++ proc = subprocess.Popen(+ ["bash", str(ENTRYPOINT), "full"],+ cwd=REPO_ROOT,+ env=env,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ text=True,+ start_new_session=True,+ )+ try:+ time.sleep(4)+ self.assertIsNone(proc.poll())+ finally:+ os.killpg(proc.pid, signal.SIGTERM)+ try:+ _stdout, stderr = proc.communicate(timeout=5)+ except subprocess.TimeoutExpired:+ os.killpg(proc.pid, signal.SIGKILL)+ _stdout, stderr = proc.communicate(timeout=5)++ self.assertNotIn("Service exited unexpectedly", stderr)+if __name__ == "__main__":unittest.main()diff --git a/tests/test_ui_server_logs.py b/tests/test_ui_server_logs.pynew file mode 100644index 000000000..50387920e--- /dev/null+++ b/tests/test_ui_server_logs.py@@ -0,0 +1,90 @@+from __future__ import annotations++from config import paths+from vibe.ui_server import app+++def test_logs_endpoint_returns_multiple_sources(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ paths.ensure_data_dirs()++ (paths.get_logs_dir() / "vibe_remote.log").write_text(+ "2026-03-25 15:51:17,428 - asyncio - ERROR - [base_events.py:1875] - Task was destroyed but it is pending!\n"+ "traceback line\n",+ encoding="utf-8",+ )+ (paths.get_runtime_dir() / "service_stderr.log").write_text("service stderr line\n", encoding="utf-8")+ (paths.get_runtime_dir() / "ui_stderr.log").write_text("UI boot failed\nTraceback line\n", encoding="utf-8")++ client = app.test_client()+ response = client.post("/logs", json={"lines": 20, "source": "ui_stderr"})++ assert response.status_code == 200+ payload = response.get_json()+ assert payload["source"] == "ui_stderr"+ assert payload["total"] == 2+ assert isinstance(payload["logs"], list)+ assert {source["key"] for source in payload["sources"]} == {+ "all",+ "service",+ "service_stdout",+ "service_stderr",+ "ui_stdout",+ "ui_stderr",+ }+ assert next(source for source in payload["sources"] if source["key"] == "service")["total"] == 2+ assert next(source for source in payload["sources"] if source["key"] == "all")["total"] == 5+ assert payload["logs"][0]["logger"] == "ui_stderr"+ assert payload["logs"][0]["message"] == "UI boot failed\nTraceback line"+ assert payload["logs"][0]["source"] == "ui_stderr"+++def test_logs_endpoint_returns_aggregated_all_view(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ paths.ensure_data_dirs()++ (paths.get_logs_dir() / "vibe_remote.log").write_text(+ "2026-03-25 15:51:17,428 - asyncio - ERROR - main service failed\n",+ encoding="utf-8",+ )+ (paths.get_runtime_dir() / "service_stderr.log").write_text(+ "service stderr line\n",+ encoding="utf-8",+ )+ (paths.get_runtime_dir() / "ui_stderr.log").write_text(+ "UI boot failed\n",+ encoding="utf-8",+ )++ client = app.test_client()+ response = client.post("/logs", json={"lines": 20, "source": "all"})++ assert response.status_code == 200+ payload = response.get_json()+ assert payload["source"] == "all"+ assert payload["total"] == 3+ assert [entry["source"] for entry in payload["logs"]] == [+ "service_stderr",+ "ui_stderr",+ "service",+ ]+ assert {entry["source"] for entry in payload["logs"]} == {"service", "service_stderr", "ui_stderr"}+++def test_logs_endpoint_falls_back_to_service_for_unknown_source(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ paths.ensure_data_dirs()++ (paths.get_logs_dir() / "vibe_remote.log").write_text(+ "2026-03-25 15:51:17,428 - asyncio - ERROR - [base_events.py:1875] - Task was destroyed but it is pending!\n",+ encoding="utf-8",+ )++ client = app.test_client()+ response = client.post("/logs", json={"lines": 20, "source": "unknown"})++ assert response.status_code == 200+ payload = response.get_json()+ assert payload["source"] == "all"+ assert payload["total"] == 1+ assert payload["logs"][0]["logger"] == "asyncio"diff --git a/tests/test_update_checker_platforms.py b/tests/test_update_checker_platforms.pyindex e991954c4..0aaf8046e 100644--- a/tests/test_update_checker_platforms.py+++ b/tests/test_update_checker_platforms.py@@ -1,5 +1,6 @@from __future__ import annotations+import asyncioimport sysfrom pathlib import Path@@ -38,3 +39,19 @@ def test_get_admin_user_ids_includes_all_platforms(monkeypatch, tmp_path):admin_ids = checker._get_admin_user_ids()assert set(admin_ids) == {"slack::U1", "discord::D1"}+++def test_stop_returns_cancellable_task(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ SettingsStore.reset_instance()++ async def run_test():+ checker = UpdateChecker(_StubController(SettingsStore.get_instance()), UpdateConfig(check_interval_minutes=1))+ checker.start()+ await asyncio.sleep(0)+ task = checker.stop()+ assert task is not None+ await checker.wait_stopped(task)+ assert task.done()++ asyncio.run(run_test())diff --git a/ui/src/components/steps/LogsPanel.tsx b/ui/src/components/steps/LogsPanel.tsxindex 9b315e249..9859a1ba9 100644--- a/ui/src/components/steps/LogsPanel.tsx+++ b/ui/src/components/steps/LogsPanel.tsx@@ -1,7 +1,7 @@import React, { useEffect, useState, useMemo, useRef } from 'react';import { FileText, RefreshCw, Search, Filter, ArrowDown, Pause, Play } from 'lucide-react';import { useTranslation } from 'react-i18next';-import { useApi, type LogEntry } from '../../context/ApiContext';+import { useApi, type LogEntry, type LogSource } from '../../context/ApiContext';import clsx from 'clsx';type LogLevel = 'DEBUG' | 'INFO' | 'WARNING' | 'ERROR' | 'ALL';@@ -26,6 +26,8 @@ export const LogsPanel: React.FC = () => {const { t } = useTranslation();const api = useApi();const [logs, setLogs] = useState<LogEntry[]>([]);+ const [sources, setSources] = useState<LogSource[]>([]);+ const [selectedSource, setSelectedSource] = useState('all');const [loading, setLoading] = useState(false);const [logsTotal, setLogsTotal] = useState(0);const [searchQuery, setSearchQuery] = useState('');@@ -34,25 +36,29 @@ export const LogsPanel: React.FC = () => {const logsContainerRef = useRef<HTMLDivElement>(null);const autoRefreshRef = useRef<ReturnType<typeof setInterval> | null>(null);- const loadLogs = async () => {+ const loadLogs = async (source = selectedSource) => {setLoading(true);try {- const res = await api.getLogs(2000);+ const res = await api.getLogs(2000, source);setLogs(res.logs);setLogsTotal(res.total);+ setSources(res.sources);+ setSelectedSource(res.source);} finally {setLoading(false);}};useEffect(() => {- loadLogs();+ void loadLogs();}, []);// Auto-refresh logicuseEffect(() => {if (autoRefresh) {- autoRefreshRef.current = setInterval(loadLogs, 5000);+ autoRefreshRef.current = setInterval(() => {+ void loadLogs(selectedSource);+ }, 5000);} else if (autoRefreshRef.current) {clearInterval(autoRefreshRef.current);autoRefreshRef.current = null;@@ -62,7 +68,7 @@ export const LogsPanel: React.FC = () => {clearInterval(autoRefreshRef.current);}};- }, [autoRefresh]);+ }, [autoRefresh, selectedSource]);// Auto-scroll to bottom when new logs arriveuseEffect(() => {@@ -94,6 +100,30 @@ export const LogsPanel: React.FC = () => {return counts;}, [logs]);+ const selectedSourceMeta = useMemo(+ () => sources.find((source) => source.key === selectedSource) ?? null,+ [selectedSource, sources]+ );++ const getSourceLabel = (sourceKey: string) => {+ switch (sourceKey) {+ case 'all':+ return t('logs.sources.all');+ case 'service':+ return t('logs.sources.service');+ case 'service_stdout':+ return t('logs.sources.serviceStdout');+ case 'service_stderr':+ return t('logs.sources.serviceStderr');+ case 'ui_stdout':+ return t('logs.sources.uiStdout');+ case 'ui_stderr':+ return t('logs.sources.uiStderr');+ default:+ return sourceKey;+ }+ };+const LogLevelBadge = ({ level }: { level: string }) => {const colors = LOG_LEVEL_COLORS[level] || LOG_LEVEL_COLORS.INFO;return (@@ -133,7 +163,7 @@ export const LogsPanel: React.FC = () => {{autoRefresh ? t('logs.autoRefreshOn') : t('logs.autoRefresh')}</button><button- onClick={loadLogs}+ onClick={() => void loadLogs(selectedSource)}disabled={loading}className="flex items-center gap-2 px-4 py-2 bg-accent text-white rounded-lg hover:bg-accent/90 disabled:opacity-50 transition-colors font-medium shadow-sm">@@ -173,6 +203,24 @@ export const LogsPanel: React.FC = () => {</div>{/* Level Quick Filters */}+ <div className="flex gap-2 flex-wrap">+ {sources.map((source) => (+ <button+ key={source.key}+ onClick={() => void loadLogs(source.key)}+ className={clsx(+ 'px-3 py-1.5 rounded-full text-xs font-medium border transition-colors',+ selectedSource === source.key+ ? 'bg-accent text-white border-accent'+ : 'bg-white text-muted border-border hover:border-accent/50'+ )}+ >+ {getSourceLabel(source.key)}+ {source.total > 0 && ` (${source.total})`}+ </button>+ ))}+ </div>+<div className="flex gap-2 flex-wrap">{(['ALL', 'ERROR', 'WARNING', 'INFO', 'DEBUG'] as LogLevel[]).map((level) => (<button@@ -206,7 +254,7 @@ export const LogsPanel: React.FC = () => {<ArrowDown size={12} /> {t('logs.jumpToLatest')}</button><code className="text-xs text-muted bg-neutral-100 px-2 py-1 rounded">- ~/.vibe_remote/logs/vibe_remote.log+ {selectedSourceMeta?.path || t('logs.allFiles')}</code></div></div>@@ -247,6 +295,9 @@ export const LogsPanel: React.FC = () => {<span className="text-muted text-xs truncate max-w-[200px]" title={log.logger}>{log.logger}</span>+ <span className="text-muted/60 text-xs font-normal">+ {getSourceLabel(log.source)}+ </span>{location && (<span className="text-muted/60 text-xs font-normal">[{location}]diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex a672cedea..7639f7442 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -34,7 +34,7 @@ export type ApiContextType = {claudeAgents: (cwd?: string) => Promise<{ ok: boolean; agents?: { id: string; name: string; path: string; source?: string }[]; error?: string }>;claudeModels: () => Promise<{ ok: boolean; models?: string[]; reasoning_options?: Record<string, { value: string; label: string }[]>; error?: string }>;codexModels: () => Promise<{ ok: boolean; models?: string[]; error?: string }>;- getLogs: (lines?: number) => Promise<{ logs: LogEntry[]; total: number }>;+ getLogs: (lines?: number, source?: string) => Promise<{ logs: LogEntry[]; total: number; source: string; sources: LogSource[] }>;getVersion: () => Promise<VersionInfo>;doUpgrade: () => Promise<UpgradeResult>;browseDirectory: (path: string, showHidden?: boolean) => Promise<{ ok: boolean; path?: string; parent?: string | null; dirs?: { name: string; path: string }[]; error?: string }>;@@ -45,6 +45,16 @@ export type LogEntry = {level: string;logger: string;message: string;+ source: string;+};++export type LogSource = {+ key: string;+ filename: string;+ path: string;+ exists: boolean;+ total: number;+ logs?: LogEntry[];};export type VersionInfo = {@@ -160,7 +170,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrenclaudeAgents: (cwd) => cwd ? getJson(`/claude/agents?cwd=${encodeURIComponent(cwd)}`) : getJson('/claude/agents'),claudeModels: () => getJson('/claude/models'),codexModels: () => getJson('/codex/models'),- getLogs: (lines = 500) => postJson('/logs', { lines }),+ getLogs: (lines = 500, source) => postJson('/logs', source ? { lines, source } : { lines }),getVersion: () => getJson('/version'),doUpgrade: () => postJson('/upgrade', {}),browseDirectory: (path, showHidden) => postJson('/browse', { path, show_hidden: showHidden || false }),diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 6829d2bd2..3d1e815e2 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -456,10 +456,19 @@"all": "All","entriesCount": "{{filtered}} of {{total}} entries","totalInFile": "({{total}} total in file)",+ "allFiles": "All log files","jumpToLatest": "Jump to latest","loadingLogs": "Loading logs...","noLogsAvailable": "No logs available",- "noLogsMatch": "No logs match your filter"+ "noLogsMatch": "No logs match your filter",+ "sources": {+ "all": "All",+ "service": "Main service log",+ "serviceStdout": "Main service stdout",+ "serviceStderr": "Main service stderr",+ "uiStdout": "UI stdout",+ "uiStderr": "UI stderr"+ }},"language": {"switchLanguage": "Language",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex bd0d38286..5bd4d10b0 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -456,10 +456,19 @@"all": "全部","entriesCount": "{{filtered}} / {{total}} 条","totalInFile": "(文件中共 {{total}} 条)",+ "allFiles": "全部日志文件","jumpToLatest": "跳转到最新","loadingLogs": "加载日志中...","noLogsAvailable": "暂无日志",- "noLogsMatch": "没有匹配的日志"+ "noLogsMatch": "没有匹配的日志",+ "sources": {+ "all": "全部",+ "service": "主服务日志",+ "serviceStdout": "主服务标准输出",+ "serviceStderr": "主服务错误输出",+ "uiStdout": "UI 标准输出",+ "uiStderr": "UI 错误输出"+ }},"language": {"switchLanguage": "语言",diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 4cd021e18..fff3da097 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -23,6 +23,16 @@ _server = Nonelog = logging.getLogger("werkzeug")log.setLevel(logging.WARNING)+STRUCTURED_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+(.*)$")+LEVEL_HINT_PATTERN = re.compile(r"\b(DEBUG|INFO|WARNING|ERROR|CRITICAL)\b")+LOG_SOURCES = (+ ("service", "vibe_remote.log", lambda: paths.get_logs_dir() / "vibe_remote.log"),+ ("service_stdout", "service_stdout.log", lambda: paths.get_runtime_dir() / "service_stdout.log"),+ ("service_stderr", "service_stderr.log", lambda: paths.get_runtime_dir() / "service_stderr.log"),+ ("ui_stdout", "ui_stdout.log", lambda: paths.get_runtime_dir() / "ui_stdout.log"),+ ("ui_stderr", "ui_stderr.log", lambda: paths.get_runtime_dir() / "ui_stderr.log"),+)+def _run_async(coro, timeout: float = 10.0) -> dict:"""Run async coroutine in a separate thread with timeout."""@@ -48,6 +58,90 @@ def _run_async(coro, timeout: float = 10.0) -> dict:return result+def _is_continuation_line(line: str) -> bool:+ stripped = line.lstrip()+ return (+ line[:1].isspace()+ or stripped.startswith("Traceback ")+ or stripped.startswith("During handling of the above exception")+ or stripped.startswith("File ")+ or stripped.startswith("task:")+ or stripped.startswith("^")+ )+++def _fallback_log_entry(line: str, source_key: str) -> dict[str, str]:+ level_match = LEVEL_HINT_PATTERN.search(line)+ level = level_match.group(1) if level_match else "INFO"+ if level == "CRITICAL":+ level = "ERROR"+ return {+ "timestamp": "",+ "logger": source_key,+ "level": level,+ "message": line,+ "source": source_key,+ }+++def _read_log_entries(log_path: Path, source_key: str, lines: int) -> tuple[list[dict[str, str]], int]:+ if not log_path.exists():+ return [], 0++ with log_path.open("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++ logs_list: list[dict[str, str]] = []+ for raw_line in recent_lines:+ line = raw_line.rstrip("\n")+ match = STRUCTURED_LOG_PATTERN.match(line)+ if match:+ logs_list.append(+ {+ "timestamp": match.group(1),+ "logger": match.group(2),+ "level": match.group(3),+ "message": match.group(4),+ "source": source_key,+ }+ )+ continue++ if not line:+ continue++ if logs_list and _is_continuation_line(line):+ logs_list[-1]["message"] += "\n" + line+ continue++ logs_list.append(_fallback_log_entry(line, source_key))++ return logs_list, len(all_lines)+++def _resolve_log_sources() -> list[dict[str, Any]]:+ resolved = [+ {+ "key": "all",+ "filename": "*",+ "path": "",+ "exists": True,+ }+ ]+ for key, filename, path_factory in LOG_SOURCES:+ path = path_factory()+ resolved.append(+ {+ "key": key,+ "filename": filename,+ "path": str(path),+ "exists": path.exists(),+ }+ )+ return resolved++# =============================================================================# Error Handler# =============================================================================@@ -163,12 +257,14 @@ def control():service_pid = runtime.start_service()runtime.write_status("running", "started", service_pid, status.get("ui_pid"))elif action == "stop":+ runtime.write_status("stopping", "stopping", status.get("service_pid"), status.get("ui_pid"))runtime.stop_service()_stop_opencode_server()- runtime.write_status("stopped")+ runtime.write_status("stopped", "stopped", None, status.get("ui_pid"))elif action == "restart":import time+ runtime.write_status("restarting", "restarting", status.get("service_pid"), status.get("ui_pid"))runtime.stop_service()_stop_opencode_server()time.sleep(3)@@ -423,31 +519,47 @@ def doctor_post():@app.route("/logs", methods=["POST"])def logs():payload = request.json or {}- lines = payload.get("lines", 500)- log_path = paths.get_logs_dir() / "vibe_remote.log"- if not log_path.exists():- return jsonify({"logs": [], "total": 0})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- 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_list = []- for line in recent_lines:- line = line.rstrip("\n")- match = log_pattern.match(line)- if match:- logs_list.append(- {- "timestamp": match.group(1),- "logger": match.group(2),- "level": match.group(3),- "message": match.group(4),- }- )- elif logs_list and line:- logs_list[-1]["message"] += "\n" + line- return jsonify({"logs": logs_list, "total": len(all_lines)})+ lines = max(int(payload.get("lines", 500)), 1)+ except (TypeError, ValueError):+ lines = 500+ selected_source = payload.get("source", "service")+ sources = _resolve_log_sources()+ source_map = {source["key"]: source for source in sources}+ active_source = source_map.get(selected_source) or source_map["all"]++ try:+ aggregated_logs: list[dict[str, str]] = []+ aggregated_total = 0+ for source in sources:+ if source["key"] == "all":+ continue+ source_logs, total = _read_log_entries(Path(source["path"]), source["key"], lines)+ source["total"] = total+ aggregated_logs.extend(source_logs)+ aggregated_total += total+ if source["key"] == active_source["key"]:+ source["logs"] = source_logs+ active_logs = source_logs+ active_total = total+ else:+ source["logs"] = []+ sources[0]["total"] = aggregated_total+ sources[0]["logs"] = []+ if active_source["key"] == "all":+ active_logs = sorted(+ aggregated_logs,+ key=lambda entry: (entry.get("timestamp") or "", entry.get("source") or "", entry.get("logger") or ""),+ )+ active_total = aggregated_total+ return jsonify(+ {+ "source": active_source["key"],+ "logs": active_logs,+ "total": active_total,+ "sources": sources,+ }+ )except Exception as e:return jsonify({"error": str(e)}), 500