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.

feat(opencode): add active polls restoration on restart

cyhhaoe767fc469b15
diff --git a/README.md b/README.md
index 03f2b32ac..289035303 100644
--- a/README.md
+++ b/README.md
@@ -29,7 +29,7 @@ You're at the beach. Phone buzzes — production's on fire.
**Vibe Remote you:** Open Slack. Type "Fix the auth bug in login.py". Watch Claude Code fix it in real-time. Approve. Sip margarita.
```
-That's it. That's the product.
+AI works. You live.
```
---
diff --git a/README_ZH.md b/README_ZH.md
index 904254aa9..6f048f080 100644
--- a/README_ZH.md
+++ b/README_ZH.md
@@ -29,7 +29,7 @@
**用了 Vibe Remote:** 打开 Slack。输入「修一下 login.py 的认证 bug」。看着 Claude Code 实时修复。批准。继续喝玛格丽塔。
```
-就这样。这就是产品。
+让 AI 去忙,你去浪。
```
---
diff --git a/config/v2_sessions.py b/config/v2_sessions.py
index 568894dc0..c62552d2c 100644
--- a/config/v2_sessions.py
+++ b/config/v2_sessions.py
@@ -2,13 +2,57 @@ import json
import logging
from dataclasses import dataclass, field
from pathlib import Path
-from typing import Dict, Optional
+from typing import Any, Dict, List, Optional
from config import paths
logger = logging.getLogger(__name__)
+@dataclass
+class ActivePollInfo:
+ """Information about an active poll that needs to be restored on restart."""
+ opencode_session_id: str
+ base_session_id: str
+ channel_id: str
+ thread_id: str
+ settings_key: str
+ working_path: str
+ baseline_message_ids: List[str] = field(default_factory=list)
+ seen_tool_calls: List[str] = field(default_factory=list)
+ emitted_assistant_messages: List[str] = field(default_factory=list)
+ started_at: float = 0.0
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "opencode_session_id": self.opencode_session_id,
+ "base_session_id": self.base_session_id,
+ "channel_id": self.channel_id,
+ "thread_id": self.thread_id,
+ "settings_key": self.settings_key,
+ "working_path": self.working_path,
+ "baseline_message_ids": self.baseline_message_ids,
+ "seen_tool_calls": self.seen_tool_calls,
+ "emitted_assistant_messages": self.emitted_assistant_messages,
+ "started_at": self.started_at,
+ }
+
+ @classmethod
+ def from_dict(cls, data: Dict[str, Any]) -> "ActivePollInfo":
+ return cls(
+ opencode_session_id=data.get("opencode_session_id", ""),
+ base_session_id=data.get("base_session_id", ""),
+ channel_id=data.get("channel_id", ""),
+ thread_id=data.get("thread_id", ""),
+ settings_key=data.get("settings_key", ""),
+ working_path=data.get("working_path", ""),
+ baseline_message_ids=data.get("baseline_message_ids", []),
+ seen_tool_calls=data.get("seen_tool_calls", []),
+ emitted_assistant_messages=data.get("emitted_assistant_messages", []),
+ started_at=data.get("started_at", 0.0),
+ )
+
+
@dataclass
class SessionState:
# session_mappings: user_id -> agent_name -> thread_id -> session_id
@@ -18,6 +62,8 @@ class SessionState:
active_slack_threads: Dict[str, Dict[str, Dict[str, float]]] = field(
default_factory=dict
)
+ # active_polls: opencode_session_id -> ActivePollInfo
+ active_polls: Dict[str, Dict[str, Any]] = field(default_factory=dict)
last_activity: Optional[str] = None
@@ -37,6 +83,7 @@ class SessionsStore:
self.state = SessionState(
session_mappings=payload.get("session_mappings", {}),
active_slack_threads=payload.get("active_slack_threads", {}),
+ active_polls=payload.get("active_polls", {}),
last_activity=payload.get("last_activity"),
)
@@ -63,11 +110,43 @@ class SessionsStore:
self.state.active_slack_threads[user_id][channel_id] = channel_map
return channel_map
+ def add_active_poll(self, poll_info: ActivePollInfo) -> None:
+ """Add an active poll to track."""
+ self.state.active_polls[poll_info.opencode_session_id] = poll_info.to_dict()
+ self.save()
+
+ def remove_active_poll(self, opencode_session_id: str) -> None:
+ """Remove an active poll."""
+ if opencode_session_id in self.state.active_polls:
+ del self.state.active_polls[opencode_session_id]
+ self.save()
+
+ def get_active_poll(self, opencode_session_id: str) -> Optional[ActivePollInfo]:
+ """Get active poll info by session ID."""
+ data = self.state.active_polls.get(opencode_session_id)
+ if data:
+ return ActivePollInfo.from_dict(data)
+ return None
+
+ def get_all_active_polls(self) -> Dict[str, ActivePollInfo]:
+ """Get all active polls."""
+ return {
+ sid: ActivePollInfo.from_dict(data)
+ for sid, data in self.state.active_polls.items()
+ }
+
+ def update_active_poll(self, poll_info: ActivePollInfo) -> None:
+ """Update an existing active poll."""
+ if poll_info.opencode_session_id in self.state.active_polls:
+ self.state.active_polls[poll_info.opencode_session_id] = poll_info.to_dict()
+ self.save()
+
def save(self) -> None:
paths.ensure_data_dirs()
payload = {
"session_mappings": self.state.session_mappings,
"active_slack_threads": self.state.active_slack_threads,
+ "active_polls": self.state.active_polls,
"last_activity": self.state.last_activity,
}
self.sessions_path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
diff --git a/core/controller.py b/core/controller.py
index c31a9008a..3644f4f4e 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -137,8 +137,24 @@ class Controller:
on_change_cwd=self.handle_change_cwd_submission,
on_routing_update=self.handle_routing_update,
on_routing_modal_update=self.handle_routing_modal_update,
+ on_ready=self._on_im_ready,
)
+ async def _on_im_ready(self):
+ """Called when IM client is connected and ready.
+
+ Used to restore active poll loops that were interrupted by restart.
+ """
+ logger.info("IM client ready, checking for active polls to restore...")
+ opencode_agent = self.agent_service.agents.get("opencode")
+ if opencode_agent and hasattr(opencode_agent, "restore_active_polls"):
+ try:
+ restored = await opencode_agent.restore_active_polls()
+ if restored > 0:
+ logger.info(f"Restored {restored} active OpenCode poll(s)")
+ except Exception as e:
+ logger.error(f"Failed to restore active polls: {e}", exc_info=True)
+
# Utility methods used by handlers
def get_cwd(self, context: MessageContext) -> str:
diff --git a/modules/agents/opencode_agent.py b/modules/agents/opencode_agent.py
index 79b940bc8..4d3b91f40 100644
--- a/modules/agents/opencode_agent.py
+++ b/modules/agents/opencode_agent.py
@@ -1457,6 +1457,17 @@ class OpenCodeAgent(BaseAgent):
request.working_path,
)
+ # Record active poll for restoration on restart
+ self.settings_manager.add_active_poll(
+ opencode_session_id=session_id,
+ base_session_id=request.base_session_id,
+ channel_id=request.context.channel_id,
+ thread_id=request.context.thread_id,
+ settings_key=request.settings_key,
+ working_path=request.working_path,
+ baseline_message_ids=list(baseline_message_ids),
+ )
+
seen_tool_calls: set[str] = set()
emitted_assistant_messages: set[str] = set()
poll_interval_seconds = 2.0
@@ -1834,6 +1845,8 @@ class OpenCodeAgent(BaseAgent):
)
if question_message_id:
pending_payload["prompt_message_id"] = question_message_id
+ # Remove active poll when waiting for question response
+ self.settings_manager.remove_active_poll(session_id)
return
except Exception as err:
logger.warning(
@@ -1846,6 +1859,8 @@ class OpenCodeAgent(BaseAgent):
text,
parse_mode="markdown",
)
+ # Remove active poll when waiting for question response
+ self.settings_manager.remove_active_poll(session_id)
return
# single question + single select + <=10 options -> buttons
@@ -1884,6 +1899,8 @@ class OpenCodeAgent(BaseAgent):
)
if question_message_id:
pending_payload["prompt_message_id"] = question_message_id
+ # Remove active poll when waiting for question response
+ self.settings_manager.remove_active_poll(session_id)
return
except Exception as err:
logger.warning(
@@ -1903,6 +1920,8 @@ class OpenCodeAgent(BaseAgent):
f"Failed to send question prompt to Slack: {err}",
exc_info=True,
)
+ # Remove active poll when waiting for question response
+ self.settings_manager.remove_active_poll(session_id)
return
toolcall = self.im_client.formatter.format_toolcall(
@@ -2027,8 +2046,14 @@ class OpenCodeAgent(BaseAgent):
started_at=request.started_at,
)
+ # Remove active poll on normal completion
+ self.settings_manager.remove_active_poll(session_id)
+
except asyncio.CancelledError:
logger.info(f"OpenCode request cancelled for {request.base_session_id}")
+ # Remove active poll on cancellation
+ if session_id:
+ self.settings_manager.remove_active_poll(session_id)
raise
except Exception as e:
error_name = type(e).__name__
@@ -2043,6 +2068,10 @@ class OpenCodeAgent(BaseAgent):
f"Failed to abort OpenCode session after error: {abort_err}"
)
+ # Remove active poll on error
+ if session_id:
+ self.settings_manager.remove_active_poll(session_id)
+
await self.controller.emit_agent_message(
request.context,
"notify",
@@ -2088,7 +2117,9 @@ class OpenCodeAgent(BaseAgent):
return False
req_info = self._request_sessions.get(request.base_session_id)
+ opencode_session_id = None
if req_info:
+ opencode_session_id = req_info[0]
try:
server = await self._get_server()
await server.abort_session(req_info[0], req_info[1])
@@ -2101,6 +2132,10 @@ class OpenCodeAgent(BaseAgent):
except asyncio.CancelledError:
pass
+ # Remove from active_polls since we're stopping
+ if opencode_session_id:
+ self.settings_manager.remove_active_poll(opencode_session_id)
+
await self.controller.emit_agent_message(
request.context, "notify", "Terminated OpenCode execution."
)
@@ -2113,6 +2148,7 @@ class OpenCodeAgent(BaseAgent):
for base_id, task in list(self._active_requests.items()):
req_info = self._request_sessions.get(base_id)
if req_info and len(req_info) >= 3 and req_info[2] == settings_key:
+ opencode_session_id = req_info[0]
if not task.done():
try:
server = await self._get_server()
@@ -2125,6 +2161,8 @@ class OpenCodeAgent(BaseAgent):
except asyncio.CancelledError:
pass
terminated += 1
+ # Remove from active_polls
+ self.settings_manager.remove_active_poll(opencode_session_id)
return terminated
async def _delete_ack(self, request: AgentRequest):
@@ -2136,3 +2174,281 @@ class OpenCodeAgent(BaseAgent):
logger.debug(f"Could not delete ack message: {err}")
finally:
request.ack_message_id = None
+
+ async def restore_active_polls(self) -> int:
+ """Restore active poll loops that were interrupted by vibe-remote restart.
+
+ Returns:
+ Number of polls successfully restored.
+ """
+ from modules.im import MessageContext
+ from config.v2_sessions import ActivePollInfo
+
+ active_polls = self.settings_manager.get_all_active_polls()
+ if not active_polls:
+ logger.debug("No active polls to restore")
+ return 0
+
+ restored_count = 0
+ stale_poll_ids = []
+
+ for session_id, poll_info in active_polls.items():
+ # Validate the OpenCode session is still alive
+ try:
+ server = await self._get_server()
+ messages = await server.list_messages(
+ session_id=poll_info.opencode_session_id,
+ directory=poll_info.working_path,
+ )
+ except Exception as err:
+ logger.warning(
+ f"Failed to verify OpenCode session {session_id} for restoration: {err}"
+ )
+ stale_poll_ids.append(session_id)
+ continue
+
+ # Check if the session has any in-progress assistant message
+ has_in_progress = False
+ for message in messages:
+ info = message.get("info", {})
+ if info.get("role") != "assistant":
+ continue
+ time_info = info.get("time") or {}
+ if not time_info.get("completed"):
+ has_in_progress = True
+ break
+
+ if not has_in_progress:
+ # Session has completed, no need to restore
+ logger.info(
+ f"OpenCode session {session_id} has completed, removing from active polls"
+ )
+ stale_poll_ids.append(session_id)
+ continue
+
+ # Create a restoration task
+ logger.info(
+ f"Restoring poll loop for OpenCode session {session_id} "
+ f"(thread={poll_info.base_session_id}, cwd={poll_info.working_path})"
+ )
+
+ task = asyncio.create_task(
+ self._restored_poll_loop(poll_info)
+ )
+ self._active_requests[poll_info.base_session_id] = task
+ self._request_sessions[poll_info.base_session_id] = (
+ poll_info.opencode_session_id,
+ poll_info.working_path,
+ poll_info.settings_key,
+ )
+ restored_count += 1
+
+ # Clean up stale polls
+ for session_id in stale_poll_ids:
+ self.settings_manager.remove_active_poll(session_id)
+
+ if restored_count > 0:
+ logger.info(f"Restored {restored_count} active poll loop(s)")
+ if stale_poll_ids:
+ logger.info(f"Removed {len(stale_poll_ids)} stale active poll(s)")
+
+ return restored_count
+
+ async def _restored_poll_loop(self, poll_info) -> None:
+ """Continue a poll loop that was interrupted by restart.
+
+ This is similar to the main poll loop in handle_message but starts from
+ saved state instead of sending a new prompt.
+ """
+ from modules.im import MessageContext
+
+ session_id = poll_info.opencode_session_id
+ context = MessageContext(
+ user_id="", # Not needed for poll loop
+ channel_id=poll_info.channel_id,
+ thread_id=poll_info.thread_id,
+ )
+
+ # Notify user that we're resuming
+ await self.controller.emit_agent_message(
+ context,
+ "notify",
+ "Resuming interrupted OpenCode session after restart...",
+ )
+
+ server = await self._get_server()
+ baseline_message_ids = set(poll_info.baseline_message_ids)
+ seen_tool_calls = set(poll_info.seen_tool_calls)
+ emitted_assistant_messages = set(poll_info.emitted_assistant_messages)
+ poll_interval_seconds = 2.0
+ final_text: Optional[str] = None
+
+ # Error retry tracking
+ error_retry_count = 0
+ error_retry_limit = getattr(self.opencode_config, "error_retry_limit", 1)
+ last_error_message_id: Optional[str] = None
+
+ started_at = time.monotonic()
+
+ def _relative_path(path: str) -> str:
+ return self._to_relative_path(path, poll_info.working_path)
+
+ try:
+ poll_iter = 0
+ while True:
+ poll_iter += 1
+ try:
+ messages = await server.list_messages(
+ session_id=session_id,
+ directory=poll_info.working_path,
+ )
+ if poll_iter % 5 == 0:
+ last_info = messages[-1].get("info", {}) if messages else {}
+ logger.info(
+ "OpenCode restored poll heartbeat %s iter=%s last=%s role=%s completed=%s finish=%s error=%s",
+ session_id,
+ poll_iter,
+ last_info.get("id"),
+ last_info.get("role"),
+ bool(last_info.get("time", {}).get("completed")),
+ last_info.get("finish"),
+ bool(last_info.get("error")),
+ )
+ except Exception as poll_err:
+ logger.warning(f"Failed to poll OpenCode messages (restored): {poll_err}")
+ await asyncio.sleep(poll_interval_seconds)
+ continue
+
+ for message in messages:
+ info = message.get("info", {})
+ message_id = info.get("id")
+ if not message_id or message_id in baseline_message_ids:
+ continue
+ if info.get("role") != "assistant":
+ continue
+
+ for part in message.get("parts", []) or []:
+ if part.get("type") != "tool":
+ continue
+ call_key = part.get("callID") or part.get("id")
+ if not call_key or call_key in seen_tool_calls:
+ continue
+ tool_name = part.get("tool") or "tool"
+ tool_state = part.get("state") or {}
+ tool_input = tool_state.get("input") or {}
+
+ if tool_name == "question" and tool_state.get("status") != "completed":
+ # Question detected - need user input, exit poll loop
+ logger.info(
+ "Detected question in restored poll for %s, exiting poll loop",
+ session_id,
+ )
+ # Remove from active polls since we need user input
+ self.settings_manager.remove_active_poll(session_id)
+
+ # TODO: Emit question UI to user
+ await self.controller.emit_agent_message(
+ context,
+ "notify",
+ "OpenCode is waiting for input. Please check the session.",
+ )
+ return
+
+ seen_tool_calls.add(call_key)
+
+ # Update persisted state
+ poll_info.seen_tool_calls = list(seen_tool_calls)
+ self.settings_manager.update_active_poll_state(
+ session_id,
+ seen_tool_calls=poll_info.seen_tool_calls,
+ )
+
+ # Emit tool call summary (simplified for restored polls)
+ if tool_name in ("read", "write", "edit", "bash", "glob", "grep"):
+ tool_summary = f"`{tool_name}`"
+ if tool_name == "bash":
+ cmd = tool_input.get("command", "")
+ if cmd:
+ cmd_preview = cmd[:50] + "..." if len(cmd) > 50 else cmd
+ tool_summary = f"`bash`: `{cmd_preview}`"
+ elif tool_name in ("read", "write", "edit"):
+ path = tool_input.get("file_path") or tool_input.get("path", "")
+ if path:
+ tool_summary = f"`{tool_name}`: `{_relative_path(path)}`"
+
+ await self.controller.emit_agent_message(
+ context, "tool_call", tool_summary
+ )
+
+ # Check completion status
+ if messages:
+ last_message = messages[-1]
+ last_info = last_message.get("info", {})
+ if last_info.get("role") == "assistant":
+ time_info = last_info.get("time") or {}
+ if time_info.get("completed"):
+ msg_error = last_info.get("error")
+ if msg_error:
+ error_text = str(msg_error)
+ if last_info.get("id") != last_error_message_id:
+ error_retry_count = 0
+ last_error_message_id = last_info.get("id")
+ error_retry_count += 1
+ if error_retry_count > error_retry_limit:
+ await self.controller.emit_agent_message(
+ context, "notify", f"OpenCode error: {error_text}"
+ )
+ self.settings_manager.remove_active_poll(session_id)
+ return
+
+ if last_info.get("finish") != "tool-calls":
+ if not msg_error:
+ error_retry_count = 0
+ final_text = self._extract_response_text(last_message)
+ break
+
+ await asyncio.sleep(poll_interval_seconds)
+
+ if final_text:
+ await self.emit_result_message(
+ context,
+ final_text,
+ subtype="success",
+ started_at=started_at,
+ parse_mode="markdown",
+ )
+ else:
+ await self.emit_result_message(
+ context,
+ "(No response from OpenCode)",
+ subtype="warning",
+ started_at=started_at,
+ )
+
+ # Remove active poll on normal completion
+ self.settings_manager.remove_active_poll(session_id)
+
+ except asyncio.CancelledError:
+ logger.info(f"Restored OpenCode poll cancelled for {poll_info.base_session_id}")
+ self.settings_manager.remove_active_poll(session_id)
+ raise
+ except Exception as e:
+ error_name = type(e).__name__
+ error_details = str(e).strip()
+ error_text = f"{error_name}: {error_details}" if error_details else error_name
+
+ logger.error(f"Restored OpenCode poll failed: {error_text}", exc_info=True)
+ try:
+ await server.abort_session(session_id, poll_info.working_path)
+ except Exception as abort_err:
+ logger.warning(
+ f"Failed to abort OpenCode session after error: {abort_err}"
+ )
+
+ self.settings_manager.remove_active_poll(session_id)
+
+ await self.controller.emit_agent_message(
+ context,
+ "notify",
+ f"Restored OpenCode session failed: {error_text}",
+ )
diff --git a/modules/im/slack.py b/modules/im/slack.py
index a8cd18739..44ed2c911 100644
--- a/modules/im/slack.py
+++ b/modules/im/slack.py
@@ -49,6 +49,7 @@ class SlackBot(BaseIMClient):
self._recent_event_ids: Dict[str, float] = {}
self._stop_event: Optional[asyncio.Event] = None
self._loop: Optional[asyncio.AbstractEventLoop] = None
+ self._on_ready: Optional[Callable] = None
def set_settings_manager(self, settings_manager):
"""Set the settings manager for thread tracking"""
@@ -973,6 +974,12 @@ class SlackBot(BaseIMClient):
self._loop = asyncio.get_running_loop()
self._stop_event = asyncio.Event()
await self.socket_client.connect()
+ # Call on_ready callback after successful connection
+ if self._on_ready:
+ try:
+ await self._on_ready()
+ except Exception as e:
+ logger.error(f"on_ready callback failed: {e}", exc_info=True)
await self._stop_event.wait()
await self._async_close()
@@ -985,6 +992,12 @@ class SlackBot(BaseIMClient):
self._ensure_clients()
self._loop = asyncio.get_running_loop()
self._stop_event = asyncio.Event()
+ # Call on_ready callback (even in Web API only mode)
+ if self._on_ready:
+ try:
+ await self._on_ready()
+ except Exception as e:
+ logger.error(f"on_ready callback failed: {e}", exc_info=True)
await self._stop_event.wait()
await self._async_close()
@@ -2035,6 +2048,10 @@ class SlackBot(BaseIMClient):
if "on_routing_modal_update" in kwargs:
self._on_routing_modal_update = kwargs["on_routing_modal_update"]
+ # Register on_ready handler (called when connected)
+ if "on_ready" in kwargs:
+ self._on_ready = kwargs["on_ready"]
+
async def get_or_create_thread(
self, channel_id: str, user_id: str
) -> Optional[str]:
diff --git a/modules/settings_manager.py b/modules/settings_manager.py
index c124a4277..6983bb7bd 100644
--- a/modules/settings_manager.py
+++ b/modules/settings_manager.py
@@ -585,3 +585,64 @@ class SettingsManager:
if channel_settings is not None:
return channel_settings.require_mention
return None
+
+ # ---------------------------------------------
+ # Active polls management (for poll restoration on restart)
+ # ---------------------------------------------
+ def add_active_poll(
+ self,
+ opencode_session_id: str,
+ base_session_id: str,
+ channel_id: str,
+ thread_id: str,
+ settings_key: str,
+ working_path: str,
+ baseline_message_ids: List[str],
+ ) -> None:
+ """Record an active poll for potential restoration on restart."""
+ from config.v2_sessions import ActivePollInfo
+
+ poll_info = ActivePollInfo(
+ opencode_session_id=opencode_session_id,
+ base_session_id=base_session_id,
+ channel_id=channel_id,
+ thread_id=thread_id,
+ settings_key=settings_key,
+ working_path=working_path,
+ baseline_message_ids=baseline_message_ids,
+ seen_tool_calls=[],
+ emitted_assistant_messages=[],
+ started_at=time.time(),
+ )
+ self.sessions_store.add_active_poll(poll_info)
+ logger.debug(
+ f"Added active poll: session={opencode_session_id}, thread={thread_id}"
+ )
+
+ def remove_active_poll(self, opencode_session_id: str) -> None:
+ """Remove an active poll record."""
+ self.sessions_store.remove_active_poll(opencode_session_id)
+ logger.debug(f"Removed active poll: session={opencode_session_id}")
+
+ def update_active_poll_state(
+ self,
+ opencode_session_id: str,
+ seen_tool_calls: Optional[List[str]] = None,
+ emitted_assistant_messages: Optional[List[str]] = None,
+ ) -> None:
+ """Update the state of an active poll (for restoration accuracy)."""
+ from config.v2_sessions import ActivePollInfo
+
+ poll_info = self.sessions_store.get_active_poll(opencode_session_id)
+ if poll_info:
+ if seen_tool_calls is not None:
+ poll_info.seen_tool_calls = seen_tool_calls
+ if emitted_assistant_messages is not None:
+ poll_info.emitted_assistant_messages = emitted_assistant_messages
+ self.sessions_store.update_active_poll(poll_info)
+
+ def get_all_active_polls(self) -> Dict[str, Any]:
+ """Get all active polls for restoration."""
+ from config.v2_sessions import ActivePollInfo
+
+ return self.sessions_store.get_all_active_polls()