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(question): remove 30-min timeout and fix restart recovery for pending questions
cyh467cc4ba2ec6
diff --git a/config/v2_sessions.py b/config/v2_sessions.pyindex db78de6c2..3adbce3e8 100644--- a/config/v2_sessions.py+++ b/config/v2_sessions.py@@ -26,6 +26,8 @@ class ActivePollInfo:# Ack reaction info for cleanup on restoreack_reaction_message_id: Optional[str] = Noneack_reaction_emoji: Optional[str] = None+ # User identity for restoring question UI context+ user_id: str = ""def to_dict(self) -> Dict[str, Any]:return {@@ -41,6 +43,7 @@ class ActivePollInfo:"started_at": self.started_at,"ack_reaction_message_id": self.ack_reaction_message_id,"ack_reaction_emoji": self.ack_reaction_emoji,+ "user_id": self.user_id,}@classmethod@@ -58,6 +61,7 @@ class ActivePollInfo:started_at=data.get("started_at", 0.0),ack_reaction_message_id=data.get("ack_reaction_message_id"),ack_reaction_emoji=data.get("ack_reaction_emoji"),+ user_id=data.get("user_id", ""),)diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.pyindex 2f184d0e5..ccefc2fa5 100644--- a/modules/agents/opencode/agent.py+++ b/modules/agents/opencode/agent.py@@ -133,7 +133,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):await taskexcept asyncio.CancelledError:logger.debug(f"OpenCode task cancelled for {request.base_session_id}")- await self._question_handler.clear(request.base_session_id)+ await self._question_handler.clear(request.base_session_id, request.context)finally:if self._active_requests.get(request.base_session_id) is task:self._active_requests.pop(request.base_session_id, None)@@ -262,6 +262,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):baseline_message_ids=list(baseline_message_ids),ack_reaction_message_id=request.ack_reaction_message_id,ack_reaction_emoji=request.ack_reaction_emoji,+ user_id=request.context.user_id or "",)final_text, should_emit = await self._poll_loop.run_prompt_poll(@@ -298,12 +299,12 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):)# Clean up answer reaction after result is sent- await self._question_handler.clear(request.base_session_id)+ await self._question_handler.clear(request.base_session_id, request.context)self.sessions.remove_active_poll(session_id)except asyncio.CancelledError:logger.info(f"OpenCode request cancelled for {request.base_session_id}")- await self._question_handler.clear(request.base_session_id)+ await self._question_handler.clear(request.base_session_id, request.context)await self._remove_ack_reaction(request)if session_id:self.sessions.remove_active_poll(session_id)@@ -320,7 +321,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):logger.warning(f"Failed to abort OpenCode session after error: {abort_err}")# Clean up answer reaction on error- await self._question_handler.clear(request.base_session_id)+ await self._question_handler.clear(request.base_session_id, request.context)await self._remove_ack_reaction(request)if session_id:self.sessions.remove_active_poll(session_id)diff --git a/modules/agents/opencode/poll_loop.py b/modules/agents/opencode/poll_loop.pyindex 94b2a61fe..a0da57e8b 100644--- a/modules/agents/opencode/poll_loop.py+++ b/modules/agents/opencode/poll_loop.py@@ -342,6 +342,7 @@ class OpenCodePollLoop:poll_iter = 0while True:poll_iter += 1+ restart_poll = Falsetry:messages = await server.list_messages(session_id=session_id,@@ -384,16 +385,51 @@ class OpenCodePollLoop:if tool_name == "question" and tool_state.get("status") != "completed":logger.info(- "Detected question in restored poll for %s, exiting poll loop",+ "Detected pending question in restored poll for %s, restoring question UI",session_id,)++ # Build a synthetic AgentRequest from poll_info so the+ # question handler can render the UI and wait for an answer+ # exactly like the normal poll loop does.+ from modules.agents.base import AgentRequest++ restored_request = AgentRequest(+ context=MessageContext(+ user_id=poll_info.user_id or "",+ channel_id=poll_info.channel_id,+ thread_id=poll_info.thread_id,+ ),+ message="",+ settings_key=poll_info.settings_key,+ working_path=poll_info.working_path,+ base_session_id=poll_info.base_session_id,+ composite_session_id=poll_info.base_session_id,+ )++ answered = await self._question_handler.handle_question_toolcall(+ request=restored_request,+ server=server,+ opencode_session_id=session_id,+ message_id=message_id,+ tool_part=part,+ tool_input=tool_input,+ call_key=call_key,+ seen_tool_calls=seen_tool_calls,+ )+ if answered:+ restart_poll = True+ # Persist seen_tool_calls immediately so a second+ # restart won't re-show the same question.+ seen_tool_calls.add(call_key)+ poll_info.seen_tool_calls = list(seen_tool_calls)+ self._agent.sessions.update_active_poll_state(+ session_id, seen_tool_calls=poll_info.seen_tool_calls+ )+ break+ # Answer failed or cancelled — exit gracefullyself._agent.sessions.remove_active_poll(session_id)await _remove_ack_reaction()- await self._agent.controller.emit_agent_message(- context,- "notify",- "OpenCode is waiting for input. Please check the session.",- )returnseen_tool_calls.add(call_key)@@ -424,6 +460,13 @@ class OpenCodePollLoop:await self._agent.controller.emit_agent_message(context, "tool_call", tool_summary)+ if restart_poll:+ break++ if restart_poll:+ logger.info("Restarting restored poll loop for %s after question answer", session_id)+ continue+if messages:last_message = messages[-1]last_info = last_message.get("info", {})@@ -487,13 +530,13 @@ class OpenCodePollLoop:# Clean up ack reaction after result is sentawait _remove_ack_reaction()# Clean up answer reaction after result is sent- await self._question_handler.clear(poll_info.base_session_id)+ await self._question_handler.clear(poll_info.base_session_id, context)self._agent.sessions.remove_active_poll(session_id)except asyncio.CancelledError:logger.info(f"Restored OpenCode poll cancelled for {poll_info.base_session_id}")await _remove_ack_reaction()- await self._question_handler.clear(poll_info.base_session_id)+ await self._question_handler.clear(poll_info.base_session_id, context)self._agent.sessions.remove_active_poll(session_id)raiseexcept Exception as e:diff --git a/modules/agents/opencode/question_handler.py b/modules/agents/opencode/question_handler.pyindex 445dd8fda..3f1aa3eb2 100644--- a/modules/agents/opencode/question_handler.py+++ b/modules/agents/opencode/question_handler.py@@ -24,9 +24,6 @@ logger = logging.getLogger(__name__)class OpenCodeQuestionHandler:- # Timeout for waiting on user to answer a question (30 minutes)- QUESTION_WAIT_TIMEOUT_SECONDS = 30 * 60-def __init__(self, controller, im_client, settings_manager, get_server=None):self._controller = controllerself._im_client = im_client@@ -35,7 +32,6 @@ class OpenCodeQuestionHandler:self._pending_questions: Dict[str, PendingQuestionPayload] = {}self._question_answer_events: Dict[str, asyncio.Event] = {}- self._timed_out_questions: set[str] = set()# Track reactions added after question answer for cleanup# Maps base_session_id -> (context, message_id, emoji)self._answer_reactions: Dict[str, tuple] = {}@@ -49,11 +45,31 @@ class OpenCodeQuestionHandler:def pop_pending(self, base_session_id: str) -> Optional[PendingQuestionPayload]:return self._pending_questions.pop(base_session_id, None)- async def clear(self, base_session_id: str) -> None:- """Clear all state for a session, including removing any answer reaction."""- self._pending_questions.pop(base_session_id, None)+ async def clear(self, base_session_id: str, context=None) -> None:+ """Clear all state for a session, including removing question UI and answer reaction.++ Args:+ base_session_id: The session identifier+ context: Optional MessageContext for removing the inline keyboard.+ When provided, stale question buttons will be cleaned up.+ """+ pending = self._pending_questions.pop(base_session_id, None)self._question_answer_events.pop(base_session_id, None)- self._timed_out_questions.discard(base_session_id)++ # Remove the inline keyboard / buttons so stale buttons can't be clicked+ if pending and context:+ msg_id = pending.get("prompt_message_id")+ if msg_id and hasattr(self._im_client, "remove_inline_keyboard"):+ try:+ await self._im_client.remove_inline_keyboard(+ context,+ msg_id,+ text=pending.get("prompt_text") or "",+ parse_mode="markdown",+ )+ except Exception as err:+ logger.debug(f"Failed to remove question UI for {base_session_id}: {err}")+await self._remove_answer_reaction(base_session_id)async def _remove_answer_reaction(self, base_session_id: str) -> None:@@ -70,12 +86,8 @@ class OpenCodeQuestionHandler:"""Get or create an event for question answer coordination.Clears the event if it already exists (important for nested questions).- Also clears any stale timeout marker from previous runs."""- # Clear stale timeout marker - this is a new question, not a late answer- self._timed_out_questions.discard(base_session_id)-evt = self._question_answer_events.get(base_session_id)if evt is None:evt = asyncio.Event()@@ -99,84 +111,25 @@ class OpenCodeQuestionHandler:) -> bool:"""Wait for user to answer the question.+ Waits indefinitely — the user can answer whenever they come back.+ The asyncio task is suspended (no CPU cost) until the event fires.+Returns:- True if answer was submitted successfully, False if timed out+ True if answer was submitted successfully, False if cancelled"""evt = self._get_or_create_question_event(request.base_session_id)try:- await asyncio.wait_for(evt.wait(), timeout=self.QUESTION_WAIT_TIMEOUT_SECONDS)-- # If a previous timed-out run left residue, clear it.- if request.base_session_id in self._timed_out_questions:- self._timed_out_questions.discard(request.base_session_id)- logger.warning(- "Answer received after timeout for %s, ignoring",- request.base_session_id,- )- return False-+ await evt.wait()logger.info("Answer received for %s, resuming poll loop", request.base_session_id)return True- except asyncio.TimeoutError:- logger.warning(- "Timeout waiting for answer for %s after %d seconds",- request.base_session_id,- self.QUESTION_WAIT_TIMEOUT_SECONDS,- )- self._timed_out_questions.add(request.base_session_id)- try:- await self._handle_question_timeout(request, session_id, pending_payload)- except Exception as e:- logger.error(f"Error in timeout handler: {e}", exc_info=True)- return False+ except asyncio.CancelledError:+ logger.info("Question wait cancelled for %s", request.base_session_id)+ raisefinally:self._clear_question_event(request.base_session_id, evt)- async def _handle_question_timeout(- self,- request: AgentRequest,- session_id: str,- pending: PendingQuestionPayload,- ) -> None:- """Handle timeout when user doesn't answer a question within timeout period."""-- msg_id = pending.get("prompt_message_id")- if msg_id and hasattr(self._im_client, "remove_inline_keyboard"):- try:- await self._im_client.remove_inline_keyboard(- request.context,- msg_id,- text=(pending.get("prompt_text") or "") + "\n\n_(Timed out waiting for answer)_",- parse_mode="markdown",- )- except Exception:- pass-- # Clear in-memory state- self._pending_questions.pop(request.base_session_id, None)-- # Stop restoring this on restart (since we're abandoning the run)- sessions = getattr(self._settings_manager, "sessions", self._settings_manager)- sessions.remove_active_poll(session_id)-- # Abort the OpenCode session so rerun starts fresh- directory = pending.get("directory")- if self._get_server and session_id and directory:- try:- server = await self._get_server()- await server.abort_session(session_id, directory)- logger.info("Aborted OpenCode session %s after question timeout", session_id)- except Exception as e:- logger.warning(f"Failed to abort session on timeout: {e}")-- await self._controller.emit_agent_message(- request.context,- "notify",- "Timed out waiting for your answer (30 minutes). Please re-run your request.",- )-async def _send_answer_receipt(self, request: AgentRequest, answers_payload: List[List[str]]) -> None:receipt_text = build_answer_receipt_text(self._controller, answers_payload)if not receipt_text:@@ -533,14 +486,32 @@ class OpenCodeQuestionHandler:breakif matched_item is None and session_items:- matched_item = session_items[0]- logger.warning(- "Question match for session %s: no callID/messageID match, "- "falling back to first item in same session (id=%s, callID=%s)",- opencode_session_id,- matched_item.get("id"),- (matched_item.get("tool") or {}).get("callID"),- )+ # Only fallback to the first item if we cannot verify staleness.+ # If both the current tool call and the listed item carry+ # callIDs and they differ, the listed item is stale (e.g. a+ # leftover from a pre-timeout question) — skip it.+ our_call_id = tool_part.get("callID")+ first_item = session_items[0]+ first_call_id = (first_item.get("tool") or {}).get("callID")++ if our_call_id and first_call_id and our_call_id != first_call_id:+ logger.warning(+ "Question match for session %s: callID mismatch, "+ "skipping stale fallback (expected=%s, found=%s, question_id=%s)",+ opencode_session_id,+ our_call_id,+ first_call_id,+ first_item.get("id"),+ )+ else:+ matched_item = first_item+ logger.warning(+ "Question match for session %s: no callID/messageID match, "+ "falling back to first item in same session (id=%s, callID=%s)",+ opencode_session_id,+ matched_item.get("id"),+ (matched_item.get("tool") or {}).get("callID"),+ )# Cross-session fallback by callID — only if exactly one item# matches the callID across all sessions (callID is unique perdiff --git a/modules/agents/question_ui.py b/modules/agents/question_ui.pyindex 7310a31bb..2bcc98bd4 100644--- a/modules/agents/question_ui.py+++ b/modules/agents/question_ui.py@@ -109,14 +109,10 @@ class QuestionUIHandler:This class handles:- Rendering question prompts with buttons or modal triggers- Waiting for user answers via asyncio.Event- - Timeout handling and cleanupAgent-specific logic should remain in agent handlers."""- # Timeout for waiting on user to answer a question (30 minutes)- QUESTION_WAIT_TIMEOUT_SECONDS = 30 * 60-def __init__(self,controller,@@ -139,7 +135,6 @@ class QuestionUIHandler:self._pending_questions: Dict[str, PendingQuestion] = {}self._question_answer_events: Dict[str, asyncio.Event] = {}- self._timed_out_questions: set[str] = set()# Track reactions added after question answer for cleanup# Maps base_session_id -> (context, message_id, emoji)self._answer_reactions: Dict[str, tuple] = {}@@ -161,7 +156,6 @@ class QuestionUIHandler:"""Clear all state for a session, including removing any answer reaction."""self._pending_questions.pop(base_session_id, None)self._question_answer_events.pop(base_session_id, None)- self._timed_out_questions.discard(base_session_id)await self._remove_answer_reaction(base_session_id)async def _remove_answer_reaction(self, base_session_id: str) -> None:@@ -182,11 +176,7 @@ class QuestionUIHandler:"""Get or create an event for question answer coordination.Clears the event if it already exists (important for nested questions).- Also clears any stale timeout marker from previous runs."""- # Clear stale timeout marker - this is a new question, not a late answer- self._timed_out_questions.discard(base_session_id)-evt = self._question_answer_events.get(base_session_id)if evt is None:evt = asyncio.Event()@@ -217,77 +207,29 @@ class QuestionUIHandler:) -> bool:"""Wait for user to answer the question.+ Waits indefinitely — the user can answer whenever they come back.+ The asyncio task is suspended (no CPU cost) until the event fires.+Args:request: The agent requestpending: Pending question state- on_timeout: Optional callback when timeout occurs+ on_timeout: Unused, kept for API compatibilityReturns:- True if answer was received, False if timed out+ True if answer was received, False if cancelled"""evt = self._get_or_create_question_event(request.base_session_id)try:- await asyncio.wait_for(evt.wait(), timeout=self.QUESTION_WAIT_TIMEOUT_SECONDS)-- # If a previous timed-out run left residue, clear it.- if request.base_session_id in self._timed_out_questions:- self._timed_out_questions.discard(request.base_session_id)- logger.warning(- "Answer received after timeout for %s, ignoring",- request.base_session_id,- )- return False-+ await evt.wait()logger.info("Answer received for %s, resuming", request.base_session_id)return True- except asyncio.TimeoutError:- logger.warning(- "Timeout waiting for answer for %s after %d seconds",- request.base_session_id,- self.QUESTION_WAIT_TIMEOUT_SECONDS,- )- self._timed_out_questions.add(request.base_session_id)- try:- await self._handle_timeout(request, pending, on_timeout)- except Exception as e:- logger.error(f"Error in timeout handler: {e}", exc_info=True)- return False+ except asyncio.CancelledError:+ logger.info("Question wait cancelled for %s", request.base_session_id)+ raisefinally:self._clear_question_event(request.base_session_id, evt)- async def _handle_timeout(- self,- request: AgentRequest,- pending: PendingQuestion,- on_timeout: Optional[Callable[[AgentRequest, PendingQuestion], Coroutine]] = None,- ) -> None:- """Handle timeout when user doesn't answer a question within timeout period."""- msg_id = pending.prompt_message_id- if msg_id and hasattr(self._im_client, "remove_inline_keyboard"):- try:- await self._im_client.remove_inline_keyboard(- request.context,- msg_id,- text=(pending.prompt_text or "") + "\n\n_(Timed out waiting for answer)_",- parse_mode="markdown",- )- except Exception:- pass-- # Clear in-memory state- self._pending_questions.pop(request.base_session_id, None)-- # Call agent-specific timeout handler- if on_timeout:- await on_timeout(request, pending)-- await self._controller.emit_agent_message(- request.context,- "notify",- "Timed out waiting for your answer (30 minutes). Please re-run your request.",- )-# -------------------------------------------------------------------------# UI Rendering# -------------------------------------------------------------------------diff --git a/modules/sessions_facade.py b/modules/sessions_facade.pyindex d07818874..59210e248 100644--- a/modules/sessions_facade.py+++ b/modules/sessions_facade.py@@ -171,6 +171,7 @@ class SessionsFacade:baseline_message_ids: List[str],ack_reaction_message_id: Optional[str] = None,ack_reaction_emoji: Optional[str] = None,+ user_id: str = "",) -> None:poll_info = ActivePollInfo(opencode_session_id=opencode_session_id,@@ -185,6 +186,7 @@ class SessionsFacade:started_at=time.time(),ack_reaction_message_id=ack_reaction_message_id,ack_reaction_emoji=ack_reaction_emoji,+ user_id=user_id,)self.sessions_store.add_active_poll(poll_info)logger.debug("Added active poll: session=%s, thread=%s", opencode_session_id, thread_id)