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
Disable OpenCode question tool
cyhbc7982a3f57d
diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.pyindex 273b595df..742cfe255 100644--- a/core/handlers/message_handler.py+++ b/core/handlers/message_handler.py@@ -561,20 +561,7 @@ class MessageHandler(BaseHandler):)elif callback_data.startswith("opencode_question:"):- if not self.session_handler:- raise RuntimeError("Session handler not initialized")-- base_session_id, working_path, composite_key = self.session_handler.get_session_info(context)- session_key = self._get_session_key(context)- request = AgentRequest(- context=context,- message=callback_data,- working_path=working_path,- base_session_id=base_session_id,- composite_session_id=composite_key,- session_key=session_key,- )- await self.controller.agent_service.handle_message("opencode", request)+ logger.info("Ignoring legacy OpenCode question callback because the question tool is disabled")elif callback_data.startswith("claude_question:"):if not self.session_handler:diff --git a/docs/plans/disable-opencode-question.md b/docs/plans/disable-opencode-question.mdnew file mode 100644index 000000000..5204b7358--- /dev/null+++ b/docs/plans/disable-opencode-question.md@@ -0,0 +1,42 @@+# Disable OpenCode Question Tool++## Background++OpenCode exposes interactive user questions through its built-in `question`+tool. Vibe Remote currently adapts that tool into IM buttons/modals and keeps a+poll loop waiting for answers. That bridge is expensive to maintain across IM+platforms and is not needed for the preferred chat workflow: if the agent needs+clarification, it should ask in normal assistant text and let the user reply in+the next turn.++## Goal++Disable OpenCode `question` tool calls for all Vibe Remote-started OpenCode+turns and remove the OpenCode-specific question polling / answer submission+path.++## Scope++- Always send the per-prompt OpenCode `tools={"question": False}` override.+- Remove OpenCode-specific `opencode_question:*` callback handling from the+ agent coordinator.+- Remove question-tool branches from normal and restored OpenCode poll loops.+- Remove OpenCode `/question` list/reply client methods and tests.+- Delete the OpenCode-specific question handler/tests.++## Non-Goals++- Do not remove the shared question UI primitives yet; Claude's disabled+ AskUserQuestion code still imports them and platform modal methods are shared+ surface area.+- Do not alter Claude Code `AskUserQuestion` policy in this change.+- Do not change user-facing IM routing or general tool-call rendering.++## Safety Notes++- Existing restored polls that still contain an unfinished `question` tool call+ should no longer try to re-open UI. They will be treated as a regular tool+ call in the poll stream, and new OpenCode turns should not produce new+ `question` calls because the tool is denied at prompt start.+- Error retry prompts must use the same `tools={"question": False}` override so+ retries do not re-enable the question tool.diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.pyindex 510cdff44..dca1f1df7 100644--- a/modules/agents/opencode/agent.py+++ b/modules/agents/opencode/agent.py@@ -2,7 +2,6 @@Most heavy lifting lives in:- server.py: OpenCodeServerManager-- question_handler.py: question UI + answer submission- poll_loop.py: unified poll loop- session.py: session mapping + concurrency guards"""@@ -21,7 +20,6 @@ from modules.agents.base import AgentRequest, BaseAgentfrom .client_manager import OpenCodeClientManagerfrom .message_processor import OpenCodeMessageProcessorMixinfrom .poll_loop import OpenCodePollLoop-from .question_handler import OpenCodeQuestionHandlerfrom .server import OpenCodeServerManagerfrom .session import OpenCodeSessionManager@@ -40,13 +38,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):self._client_manager = OpenCodeClientManager(opencode_config)self._session_manager = OpenCodeSessionManager(self.settings_manager, self.name)- self._question_handler = OpenCodeQuestionHandler(- self.controller,- self.im_client,- self.settings_manager,- get_server=self._get_server,- )- self._poll_loop = OpenCodePollLoop(self, self._question_handler)+ self._poll_loop = OpenCodePollLoop(self)self._active_requests: Dict[str, asyncio.Task] = {}@@ -73,79 +65,43 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):)async def handle_message(self, request: AgentRequest) -> None:+ if request.message.startswith("opencode_question:"):+ logger.info(+ "Ignoring legacy OpenCode question callback for %s because the question tool is disabled",+ request.base_session_id,+ )+ await self._remove_ack_reaction(request)+ return+lock = self._session_manager.get_session_lock(request.base_session_id)- open_modal_task: Optional[asyncio.Task] = Nonetask: Optional[asyncio.Task] = Noneasync with lock:- pending = self._question_handler.get_pending(request.base_session_id)- is_modal_open = pending and request.message == "opencode_question:open_modal"- is_answer_submission = pending and not is_modal_open-existing_task = self._active_requests.get(request.base_session_id)if existing_task and not existing_task.done():- if is_modal_open:- logger.info(- "OpenCode session %s running; opening modal without cancel",- request.base_session_id,- )- elif is_answer_submission:- logger.info(- "OpenCode session %s running; submitting answer without cancel",- request.base_session_id,- )- else:- logger.info(- "OpenCode session %s already running; cancelling before new request",- request.base_session_id,- )- req_info = self._session_manager.get_request_session(request.base_session_id)- if req_info:- server = await self._get_server()- await server.abort_session(req_info[0], req_info[1])- await self._session_manager.wait_for_session_idle(server, req_info[0], req_info[1])-- existing_task.cancel()- try:- await existing_task- except asyncio.CancelledError:- pass-- logger.info(- "OpenCode session %s cancelled; continuing with new request",- request.base_session_id,- )-- if is_modal_open:- if hasattr(self.im_client, "open_opencode_question_modal"):- open_modal_task = asyncio.create_task(- self._question_handler.open_question_modal(request, pending) # type: ignore[arg-type]- )- # Clean up reaction for modal open request- await self._remove_ack_reaction(request)- else:- task = asyncio.create_task(self._process_message(request))- self._active_requests[request.base_session_id] = task- elif is_answer_submission:- server = await self._get_server()- await self._question_handler.process_question_answer(- request,- pending,- server, # type: ignore[arg-type]+ logger.info(+ "OpenCode session %s already running; cancelling before new request",+ request.base_session_id,+ )+ req_info = self._session_manager.get_request_session(request.base_session_id)+ if req_info:+ server = await self._get_server()+ await server.abort_session(req_info[0], req_info[1])+ await self._session_manager.wait_for_session_idle(server, req_info[0], req_info[1])++ existing_task.cancel()+ try:+ await existing_task+ except asyncio.CancelledError:+ pass++ logger.info(+ "OpenCode session %s cancelled; continuing with new request",+ request.base_session_id,)- # Do NOT remove ack reaction here.- # The OpenCode run is still in progress after answer submission,- # so early cleanup makes users think the task has finished.- # Prefer stale reactions over premature removal; terminal cleanup- # happens on result/error/cancel paths.- return- else:- task = asyncio.create_task(self._process_message(request))- self._active_requests[request.base_session_id] = task- if open_modal_task:- await open_modal_task- return+ task = asyncio.create_task(self._process_message(request))+ self._active_requests[request.base_session_id] = taskif not task:return@@ -154,7 +110,6 @@ 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, request.context)finally:if self._active_requests.get(request.base_session_id) is task:self._active_requests.pop(request.base_session_id, None)@@ -282,8 +237,6 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):if request.vibe_agent_system_prompt:system_prompt_injection = f"{request.vibe_agent_system_prompt}\n\n{system_prompt_injection}"- request_tools = {"question": False} if platform == "wechat" else None-await server.prompt_async(session_id=session_id,directory=request.working_path,@@ -292,7 +245,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):model=model_dict,reasoning_effort=reasoning_effort,system=system_prompt_injection,- tools=request_tools,+ tools={"question": False},)await server.mark_run_active(session_id)run_registered = True@@ -362,13 +315,10 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):request=request,)- # Clean up answer reaction after result is sent- 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, request.context)await self._remove_ack_reaction(request)if session_id:self.sessions.remove_active_poll(session_id)@@ -384,8 +334,6 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):except Exception as abort_err: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, 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 3517b58ba..ca5431d0c 100644--- a/modules/agents/opencode/poll_loop.py+++ b/modules/agents/opencode/poll_loop.py@@ -9,17 +9,25 @@ from typing import Any, Dict, Optionalfrom config.v2_config import DEFAULT_OPENCODE_ERROR_RETRY_LIMITfrom modules.agents.base import AgentRequest+from vibe.i18n import t as i18n_t-from .question_handler import OpenCodeQuestionHandlerfrom .server import OpenCodeServerManagerlogger = logging.getLogger(__name__)class OpenCodePollLoop:- def __init__(self, agent, question_handler: OpenCodeQuestionHandler):+ def __init__(self, agent):self._agent = agent- self._question_handler = question_handler++ def _t(self, key: str) -> str:+ controller = getattr(self._agent, "controller", None)+ translate = getattr(controller, "_t", None)+ if callable(translate):+ return str(translate(key))+ config = getattr(controller, "config", None)+ lang = getattr(config, "language", "en")+ return str(i18n_t(key, lang))def _build_restored_handle(self, poll_info):snapshot = poll_info.processing_indicator or {@@ -68,12 +76,10 @@ class OpenCodePollLoop:"""Walk backward through messages to find response text.When the last completed message has no text parts (e.g. it only- contains tool calls or step markers), search earlier messages for- the actual assistant response text.-- Messages in *emitted_message_ids* are skipped so that text already- sent to the user (e.g. question preface text) is not re-sent as the- final result.+ contains tool calls or step markers), search earlier messages for the+ actual assistant response text. Messages in *emitted_message_ids* are+ skipped so text already sent to the user is not re-sent as the final+ result."""skip_ids: set[str] = set()if last_message_id:@@ -117,7 +123,7 @@ class OpenCodePollLoop:(final_text, should_emit_final_result)If `should_emit_final_result` is False, the caller should exit without- emitting a final result message (e.g. timed out waiting for question).+ emitting a final result message."""seen_tool_calls: set[str] = set()@@ -139,7 +145,6 @@ class OpenCodePollLoop:poll_iter = 0while True:poll_iter += 1- restart_poll = Falsetry:messages = await server.list_messages(session_id=session_id,@@ -181,37 +186,13 @@ class OpenCodePollLoop:tool_input = tool_state.get("input") or {}if tool_name == "question" and tool_state.get("status") != "completed":- # Emit any assistant text from this message BEFORE the- # question form, so the user sees the context first.- # Without this, the form/buttons appear first and the- # assistant's explanatory text only shows up after the- # user answers (because the parts loop breaks on the- # question and lines below never run).- if message_id not in emitted_assistant_messages:- pre_text = self._agent._extract_response_text(message)- if pre_text:- await self._agent.controller.emit_agent_message(- request.context,- "assistant",- pre_text,- parse_mode="markdown",- )- emitted_assistant_messages.add(message_id)-- answered = await self._question_handler.handle_question_toolcall(- request=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- break- # Timeout -> end request without final result message+ message = self._t("error.opencodeQuestionToolDisabled")+ logger.warning("Aborting OpenCode session %s after disabled question tool call", session_id)+ await self._agent.controller.emit_agent_message(request.context, "notify", message)+ try:+ await server.abort_session(session_id, request.working_path)+ except Exception as abort_err:+ logger.warning("Failed to abort disabled question session %s: %s", session_id, abort_err)return None, Falsetoolcall = self._agent._get_formatter(request.context).format_toolcall(@@ -227,9 +208,6 @@ class OpenCodePollLoop:)seen_tool_calls.add(call_key)- if restart_poll:- break-if (info.get("time", {}).get("completed")and message_id not in emitted_assistant_messages@@ -245,10 +223,6 @@ class OpenCodePollLoop:)emitted_assistant_messages.add(message_id)- if restart_poll:- logger.info("Restarting poll loop for %s after question answer", session_id)- continue-if messages:last_message = messages[-1]last_info = last_message.get("info", {})@@ -293,6 +267,7 @@ class OpenCodePollLoop:agent=agent_to_use,model=model_dict,reasoning_effort=reasoning_effort,+ tools={"question": False},)await asyncio.sleep(poll_interval_seconds)continue@@ -377,7 +352,6 @@ class OpenCodePollLoop:poll_iter = 0while True:poll_iter += 1- restart_poll = Falsetry:messages = await server.list_messages(session_id=session_id,@@ -419,48 +393,16 @@ class OpenCodePollLoop:tool_input = tool_state.get("input") or {}if tool_name == "question" and tool_state.get("status") != "completed":- logger.info(- "Detected pending question in restored poll for %s, restoring question UI",+ message = self._t("error.opencodeQuestionToolDisabledRestored")+ logger.warning(+ "Aborting restored OpenCode session %s after disabled question tool call",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=context,- message="",- session_key=f"{poll_info.platform}::{poll_info.settings_key}"- if poll_info.platform- else 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 gracefully+ await self._agent.controller.emit_agent_message(context, "notify", message)+ try:+ await server.abort_session(session_id, poll_info.working_path)+ except Exception as abort_err:+ logger.warning("Failed to abort disabled question session %s: %s", session_id, abort_err)self._agent.sessions.remove_active_poll(session_id)await self.remove_restored_ack(poll_info)return@@ -493,13 +435,6 @@ 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", {})@@ -569,14 +504,11 @@ class OpenCodePollLoop:# Clean up ack reaction after result is sentawait self.remove_restored_ack(poll_info)- # Clean up answer reaction after result is sent- 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 self.remove_restored_ack(poll_info)- 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.pydeleted file mode 100644index 5d8c2da68..000000000--- a/modules/agents/opencode/question_handler.py+++ /dev/null@@ -1,836 +0,0 @@-"""Question/answer coordination for the OpenCode agent.--This encapsulates:-- Detecting question toolcalls and presenting UI to the user-- Waiting for an answer (event-based)-- Submitting answers back to OpenCode-"""--from __future__ import annotations--import asyncio-import json-import logging-import time-from typing import Any, Dict, List, Optional--from modules.agents.base import AgentRequest--from ..question_ui import build_answer_receipt_text-from .server import OpenCodeServerManager-from .types import PendingQuestionPayload--logger = logging.getLogger(__name__)---class OpenCodeQuestionHandler:- def __init__(self, controller, im_client, settings_manager, get_server=None):- self._controller = controller- self._im_client = im_client- self._settings_manager = settings_manager- self._get_server = get_server # Callback to get server instance for abort-- self._pending_questions: Dict[str, PendingQuestionPayload] = {}- self._question_answer_events: Dict[str, asyncio.Event] = {}- # Track reactions added after question answer for cleanup- # Maps base_session_id -> (context, message_id, emoji)- self._answer_reactions: Dict[str, tuple] = {}-- def _platform_supports_question_tool(self, request: AgentRequest) -> bool:- platform = request.context.platform or (request.context.platform_specific or {}).get("platform")- if not platform:- platform = getattr(self._controller.config, "platform", "")- return platform != "wechat"-- def _question_tool_disabled_text(self) -> str:- translator = getattr(self._controller, "_t", None)- if callable(translator):- return translator("error.opencodeQuestionUnsupportedWechat")- return "OpenCode interactive questions are temporarily disabled on WeChat. Please send a follow-up message instead."-- def get_pending(self, base_session_id: str) -> Optional[PendingQuestionPayload]:- return self._pending_questions.get(base_session_id)-- def set_pending(self, base_session_id: str, payload: PendingQuestionPayload) -> None:- self._pending_questions[base_session_id] = payload-- 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, 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)-- # 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:- """Remove the 👀 reaction added after question answer."""- reaction_info = self._answer_reactions.pop(base_session_id, None)- if reaction_info and hasattr(self._im_client, "remove_reaction"):- context, message_id, emoji = reaction_info- try:- await self._im_client.remove_reaction(context, message_id, emoji)- except Exception as err:- logger.debug(f"Failed to remove answer reaction: {err}")-- def _get_or_create_question_event(self, base_session_id: str) -> asyncio.Event:- """Get or create an event for question answer coordination.-- Clears the event if it already exists (important for nested questions).- """-- evt = self._question_answer_events.get(base_session_id)- if evt is None:- evt = asyncio.Event()- self._question_answer_events[base_session_id] = evt- else:- evt.clear()- return evt-- def _clear_question_event(self, base_session_id: str, evt: asyncio.Event) -> None:- """Clear question event, but only if it's still the same object (avoid races)."""-- current = self._question_answer_events.get(base_session_id)- if current is evt:- self._question_answer_events.pop(base_session_id, None)-- async def wait_for_question_answer(- self,- request: AgentRequest,- session_id: str,- pending_payload: PendingQuestionPayload,- ) -> 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 cancelled- """-- evt = self._get_or_create_question_event(request.base_session_id)-- try:- await evt.wait()- logger.info("Answer received for %s, resuming poll loop", request.base_session_id)- return True- except asyncio.CancelledError:- logger.info("Question wait cancelled for %s", request.base_session_id)- raise- finally:- self._clear_question_event(request.base_session_id, evt)-- 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:- return-- try:- await self._im_client.send_message(request.context, receipt_text)- except Exception as err:- logger.debug(f"Failed to send answer receipt: {err}")-- async def open_question_modal(self, request: AgentRequest, pending: PendingQuestionPayload) -> None:- trigger_id = None- interaction = None- platform = getattr(request.context, "platform", None) or (request.context.platform_specific or {}).get("platform")- if request.context.platform_specific:- trigger_id = request.context.platform_specific.get("trigger_id")- interaction = request.context.platform_specific.get("interaction")- if not trigger_id and not interaction and platform == "telegram":- trigger_id = request.context- if not trigger_id and not interaction:- await self._im_client.send_message(- request.context,- "Modal UI is not available. Please reply with a custom message.",- )- return-- if not hasattr(self._im_client, "open_opencode_question_modal") and not hasattr(- self._im_client, "open_question_modal"- ):- await self._im_client.send_message(- request.context,- "Modal UI is not available. Please reply with a custom message.",- )- return-- try:- if hasattr(self._im_client, "open_opencode_question_modal"):- await self._im_client.run_on_client_loop(- self._im_client.open_opencode_question_modal(- trigger_id=interaction or trigger_id,- context=request.context,- pending=pending,- )- )- else:- await self._im_client.run_on_client_loop(- self._im_client.open_question_modal(- trigger_id=interaction or trigger_id,- context=request.context,- pending=pending,- callback_prefix="opencode_question",- )- )- except Exception as err:- logger.error(f"Failed to open OpenCode question modal: {err}", exc_info=True)- await self._im_client.send_message(- request.context,- f"Failed to open modal: {err}. Please reply with a custom message.",- )-- async def process_question_answer(- self,- request: AgentRequest,- pending: PendingQuestionPayload,- server: OpenCodeServerManager,- ) -> None:- session_id = pending.get("session_id")- directory = pending.get("directory")- question_id = pending.get("question_id")- option_labels = pending.get("option_labels")- option_labels = option_labels if isinstance(option_labels, list) else []- question_count = pending.get("question_count")- pending_thread_id = pending.get("thread_id")- question_message_id = pending.get("prompt_message_id")- trigger_message_id = pending.get("trigger_message_id") # Original request msg_id-- if pending_thread_id and not request.context.thread_id:- request.context.thread_id = pending_thread_id-- try:- question_count_int = int(question_count) if question_count is not None else 1- except Exception:- question_count_int = 1- question_count_int = max(1, question_count_int)-- if not session_id or not directory:- await self._controller.emit_agent_message(- request.context,- "notify",- "OpenCode question context is missing; please reply with a custom message.",- )- return-- answer_text = None- if request.message.startswith("opencode_question:choose:"):- try:- choice_idx = int(request.message.rsplit(":", 1)[-1]) - 1- if 0 <= choice_idx < len(option_labels):- answer_text = str(option_labels[choice_idx]).strip()- except Exception:- pass-- is_modal_payload = False- answers_payload: Optional[List[List[str]]] = None- if request.message.startswith("opencode_question:modal:"):- is_modal_payload = True- try:- payload = json.loads(request.message.split(":", 2)[-1])- answers = payload.get("answers") if isinstance(payload, dict) else None- if isinstance(answers, list) and answers:- normalized: List[List[str]] = []- for answer in answers:- if isinstance(answer, list):- normalized.append([str(x) for x in answer if x])- elif answer:- normalized.append([str(answer)])- else:- normalized.append([])- answers_payload = normalized- if normalized:- answer_text = " ".join(normalized[0])- except Exception:- logger.debug("Failed to parse modal answers payload")-- if answer_text is None and request.message.startswith("opencode_question:"):- raw_payload = request.message.split(":", 2)[-1]- answer_text = raw_payload.strip() if raw_payload else ""-- if not answer_text:- answer_text = (request.message or "").strip()-- if not answer_text:- await self._controller.emit_agent_message(- request.context,- "notify",- "Please reply with an answer.",- )- return-- # Consume pending state now; we'll put it back on failure.- self._pending_questions.pop(request.base_session_id, None)-- if not question_id:- call_id = pending.get("call_id")- message_id = pending.get("message_id")- try:- questions = await server.list_questions(directory)- if not questions:- questions = await server.list_questions()- for item in questions:- tool = item.get("tool") or {}- item_session_id = item.get("sessionID") or item.get("sessionId") or item.get("session_id")- if item_session_id != session_id:- continue- if call_id and tool.get("callID") != call_id:- continue- if message_id and tool.get("messageID") != message_id:- continue- question_id = item.get("id")- questions_obj = item.get("questions")- if isinstance(questions_obj, list):- question_count_int = max(1, len(questions_obj))- break- except Exception as err:- logger.warning(f"Failed to resolve OpenCode question id: {err}")-- if not question_id:- self._pending_questions[request.base_session_id] = pending- await self._controller.emit_agent_message(- request.context,- "notify",- "OpenCode is waiting for input, but the question id could not be resolved. Please retry.",- )- return-- if is_modal_payload and answers_payload is not None:- padded = answers_payload[:question_count_int]- if len(padded) < question_count_int:- padded.extend([[] for _ in range(question_count_int - len(padded))])- answers_payload = padded- else:- answers_payload = [[answer_text] for _ in range(question_count_int)]-- if question_message_id and hasattr(self._im_client, "remove_inline_keyboard"):- fallback_text = pending.get("prompt_text") if isinstance(pending, dict) else None- try:- await self._im_client.remove_inline_keyboard(- request.context,- question_message_id,- text=fallback_text,- parse_mode="markdown",- )- except Exception as err:- logger.debug(f"Failed to remove question buttons: {err}")-- try:- ok = await server.reply_question(question_id, directory, answers_payload)- except Exception as err:- logger.warning(f"Failed to reply OpenCode question: {err}")- self._pending_questions[request.base_session_id] = pending- # Do NOT set event here - let user retry, poll loop keeps waiting- await self._controller.emit_agent_message(- request.context,- "notify",- f"Failed to submit answer to OpenCode: {err}. Please retry.",- )- return-- if not ok:- self._pending_questions[request.base_session_id] = pending- # Do NOT set event here - let user retry, poll loop keeps waiting- await self._controller.emit_agent_message(- request.context,- "notify",- "OpenCode did not accept the answer. Please retry.",- )- return-- await self._send_answer_receipt(request, answers_payload)-- # Add 👀 reaction to question message to indicate answer received- # Track it for cleanup when the request completes- if question_message_id and hasattr(self._im_client, "add_reaction"):- try:- emoji = "eyes"- await self._im_client.add_reaction(request.context, question_message_id, emoji)- # Save for cleanup when request completes- self._answer_reactions[request.base_session_id] = (request.context, question_message_id, emoji)- except Exception as err:- logger.debug(f"Failed to add reaction to question message: {err}")-- # Clear consolidated message ID so subsequent log messages appear after user's reply- # instead of editing the old consolidated message from before the question- await self._controller.clear_consolidated_message_id(request.context, trigger_message_id)-- evt = self._question_answer_events.get(request.base_session_id)- if evt:- evt.set()- logger.info("Answer submitted for %s, signaling main poll loop to resume", session_id)- else:- logger.warning("No wait event found for %s; cannot resume poll", request.base_session_id)- await self._controller.emit_agent_message(- request.context,- "notify",- "Answer submitted, but I no longer have an active poll loop for this session. "- "Please send a new message to continue.",- )-- async def handle_question_toolcall(- self,- request: AgentRequest,- server: OpenCodeServerManager,- opencode_session_id: str,- message_id: str,- tool_part: Dict[str, Any],- tool_input: Dict[str, Any],- call_key: str,- seen_tool_calls: set[str],- ) -> bool:- """Render question UI and wait for answer.-- Returns:- True if answer received (caller should restart poll), False if timed out.- """-- logger.info(- "Detected question toolcall for %s message=%s callID=%s",- opencode_session_id,- message_id,- tool_part.get("callID"),- )-- if not self._platform_supports_question_tool(request):- logger.warning(- "Blocking OpenCode question toolcall on unsupported platform %s for session %s",- getattr(self._controller.config, "platform", ""),- opencode_session_id,- )- seen_tool_calls.add(call_key)- try:- await server.abort_session(opencode_session_id, request.working_path)- except Exception as err:- logger.warning("Failed to abort OpenCode session after blocked question toolcall: %s", err)- await self._controller.emit_agent_message(- request.context,- "notify",- self._question_tool_disabled_text(),- )- return False-- qlist = tool_input.get("questions") if isinstance(tool_input, dict) else None- qlist = qlist if isinstance(qlist, list) else []-- question_fetch_deadline = time.monotonic() + 60.0- question_fetch_delays = [1.0, 2.0, 3.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0]- max_question_attempts = 10-- def _question_delay(attempt_index: int) -> float:- if attempt_index >= len(question_fetch_delays):- return 0.0- remaining = question_fetch_deadline - time.monotonic()- if remaining <= 0:- return 0.0- return min(question_fetch_delays[attempt_index], remaining)-- question_id = None- questions_listing: List[Dict[str, Any]] = []- list_attempts = 0- last_list_err: Optional[Exception] = None- for attempt in range(max_question_attempts):- list_attempts = attempt + 1- try:- questions_listing = await server.list_questions(request.working_path)- if not questions_listing:- questions_listing = await server.list_questions()- last_list_err = None- except Exception as err:- last_list_err = err- questions_listing = []- if questions_listing:- break- if attempt < max_question_attempts - 1:- delay = _question_delay(attempt)- if delay <= 0:- break- await asyncio.sleep(delay)-- if last_list_err and not questions_listing:- logger.warning(f"Failed to fetch questions listing for prompt fallback: {last_list_err}")-- logger.info(- "Question list fetch for %s: dir=%s attempts=%s items=%s",- opencode_session_id,- request.working_path,- list_attempts,- len(questions_listing),- )-- if questions_listing:- try:- item_sessions = [- (item.get("sessionID") or item.get("sessionId") or item.get("session_id"))- for item in questions_listing- ]- logger.info("Question list sessions for %s: %s", opencode_session_id, item_sessions)- except Exception:- pass-- if questions_listing and not qlist:- try:- first_questions = questions_listing[0].get("questions")- if not isinstance(first_questions, list):- first_questions = []- listing_preview = {- "id": questions_listing[0].get("id"),- "sessionID": questions_listing[0].get("sessionID"),- "tool": questions_listing[0].get("tool"),- "questions_len": len(first_questions),- }- logger.info("Question list preview for %s: %s", opencode_session_id, listing_preview)- except Exception:- pass-- matched_item = None- if questions_listing:- session_items: List[Dict[str, Any]] = []- for item in questions_listing:- item_session_id = item.get("sessionID") or item.get("sessionId") or item.get("session_id")- if item_session_id == opencode_session_id:- session_items.append(item)-- for item in session_items:- tool_meta = item.get("tool") or {}- if tool_part.get("callID") and tool_meta.get("callID") == tool_part.get("callID"):- matched_item = item- break- if message_id and tool_meta.get("messageID") == message_id:- matched_item = item- break-- if matched_item is None and session_items:- # 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 per- # tool invocation, so a single match is reliable).- if matched_item is None and tool_part.get("callID"):- call_matches = [- item- for item in questions_listing- if (item.get("tool") or {}).get("callID") == tool_part.get("callID")- ]- if len(call_matches) == 1:- matched_item = call_matches[0]- item_sid = (- matched_item.get("sessionID") or matched_item.get("sessionId") or matched_item.get("session_id")- )- logger.warning(- "Question match: cross-session callID fallback "- "(current=%s, matched=%s, question_id=%s, callID=%s)",- opencode_session_id,- item_sid,- matched_item.get("id"),- tool_part.get("callID"),- )- elif len(call_matches) > 1:- logger.warning(- "Question match ambiguous by callID; skip fallback (session=%s, callID=%s, matches=%s)",- opencode_session_id,- tool_part.get("callID"),- len(call_matches),- )-- # REMOVED: cross-session messageID fallback — messageID is NOT- # unique across sessions and can bind question_id to the wrong- # session, causing the current session to hang forever.-- # REMOVED: blind len==1 fallback — grabbed questions from- # unrelated sessions.-- if matched_item is None:- logger.warning(- "Question match failed for session=%s (callID=%s, messageID=%s, listed=%s, session_items=%s)",- opencode_session_id,- tool_part.get("callID"),- message_id,- len(questions_listing),- len(session_items),- )-- if matched_item:- question_id = matched_item.get("id")- if not qlist:- q_obj = matched_item.get("questions")- if isinstance(q_obj, list):- qlist = q_obj-- if not qlist and message_id:- msg_attempts = 0- last_msg_err: Optional[Exception] = None- full_message: Optional[Dict[str, Any]] = None- for attempt in range(max_question_attempts):- msg_attempts = attempt + 1- try:- full_message = await server.get_message(- session_id=opencode_session_id,- message_id=message_id,- directory=request.working_path,- )- last_msg_err = None- except Exception as err:- last_msg_err = err- full_message = None-- if full_message:- for msg_part in full_message.get("parts", []) or []:- if msg_part.get("type") != "tool":- continue- if msg_part.get("tool") != "question":- continue- msg_call_id = msg_part.get("callID") or msg_part.get("id")- if call_key and msg_call_id and msg_call_id != call_key:- continue- msg_state = msg_part.get("state") or {}- msg_input = msg_state.get("input") or {}- msg_questions = msg_input.get("questions") if isinstance(msg_input, dict) else None- if isinstance(msg_questions, list):- qlist = msg_questions- break- if qlist:- break- if attempt < max_question_attempts - 1:- delay = _question_delay(attempt)- if delay <= 0:- break- await asyncio.sleep(delay)-- if last_msg_err and not qlist:- logger.warning(f"Failed to fetch full question input from message {message_id}: {last_msg_err}")- if full_message is not None:- parts = full_message.get("parts", []) or []- tool_parts = [p for p in parts if p.get("type") == "tool"]- logger.info(- "Question message fetch for %s: attempts=%s parts=%s tool_parts=%s",- opencode_session_id,- msg_attempts,- len(parts),- len(tool_parts),- )-- option_labels: list[str] = []- lines: list[str] = []- for q_idx, q in enumerate(qlist or []):- if not isinstance(q, dict):- continue- title = (q.get("header") or f"Question {q_idx + 1}").strip()- prompt = (q.get("question") or "").strip()- options_raw = q.get("options")- options: List[Dict[str, Any]] = options_raw if isinstance(options_raw, list) else []-- lines.append(f"**{title}**")- if prompt:- lines.append(prompt)-- for idx, opt in enumerate(options, start=1):- if not isinstance(opt, dict):- continue- label = (opt.get("label") or f"Option {idx}").strip()- desc = (opt.get("description") or "").strip()- if q_idx == 0:- option_labels.append(label)- if desc:- lines.append(f"{idx}. *{label}* - {desc}")- else:- lines.append(f"{idx}. *{label}*")-- if q_idx < len(qlist) - 1:- lines.append("")-- first_q = qlist[0] if qlist and isinstance(qlist[0], dict) else {}- text = "\n".join(lines)- logger.info(- "Question prompt built for %s: len=%s preview=%r",- opencode_session_id,- len(text),- text[:200],- )-- logger.info(- "Question prompt data for %s: qlist=%s options=%s question_id=%s call_id=%s",- opencode_session_id,- len(qlist),- len(option_labels),- question_id,- tool_part.get("callID"),- )-- if not option_labels:- logger.warning(- "Question toolcall had no options in tool_input; session=%s question_id=%s",- opencode_session_id,- question_id,- )-- question_count = len(qlist) if qlist else 1- multiple = bool(first_q.get("multiple"))-- pending_payload: PendingQuestionPayload = {- "session_id": opencode_session_id,- "directory": request.working_path,- "question_id": question_id,- "call_id": tool_part.get("callID"),- "message_id": message_id,- "prompt_message_id": None,- "prompt_text": text,- "option_labels": option_labels,- "question_count": question_count,- "multiple": multiple,- "questions": qlist,- "thread_id": request.context.thread_id,- "trigger_message_id": request.context.message_id, # For consolidated key- }- self._pending_questions[request.base_session_id] = pending_payload-- # Multi-select or multi-question: show full text + modal button- if multiple or question_count != 1 or len(option_labels) > 10:- modal_keyboard = None- if hasattr(self._im_client, "send_message_with_buttons"):- from modules.im import InlineButton, InlineKeyboard-- modal_keyboard = InlineKeyboard(- buttons=[[InlineButton(text="Choose…", callback_data="opencode_question:open_modal")]]- )-- if modal_keyboard:- try:- logger.info(- "Sending modal open button for %s (multiple=%s questions=%s)",- opencode_session_id,- multiple,- question_count,- )- question_message_id = await self._im_client.send_message_with_buttons(- request.context,- text,- modal_keyboard,- parse_mode="markdown",- )- if question_message_id:- pending_payload["prompt_message_id"] = question_message_id-- seen_tool_calls.add(call_key)- if await self.wait_for_question_answer(request, opencode_session_id, pending_payload):- return True- return False- except Exception as err:- logger.warning(- f"Failed to send modal button, falling back to text: {err}",- exc_info=True,- )-- await self._im_client.send_message(request.context, text, parse_mode="markdown")- seen_tool_calls.add(call_key)- if await self.wait_for_question_answer(request, opencode_session_id, pending_payload):- return True- return False-- # single question + single select + <=10 options -> buttons- if (- question_count == 1- and isinstance(first_q, dict)- and not multiple- and len(option_labels) <= 10- and hasattr(self._im_client, "send_message_with_buttons")- ):- from modules.im import InlineButton, InlineKeyboard-- buttons: list[list[InlineButton]] = []- row: list[InlineButton] = []- for idx, label in enumerate(option_labels, start=1):- callback = f"opencode_question:choose:{idx}"- row.append(InlineButton(text=label, callback_data=callback))- if len(row) == 5:- buttons.append(row)- row = []- if row:- buttons.append(row)-- keyboard = InlineKeyboard(buttons=buttons)- try:- logger.info(- "Sending single-select buttons for %s (options=%s)",- opencode_session_id,- len(option_labels),- )- question_message_id = await self._im_client.send_message_with_buttons(- request.context,- text,- keyboard,- parse_mode="markdown",- )- if question_message_id:- pending_payload["prompt_message_id"] = question_message_id- seen_tool_calls.add(call_key)- if await self.wait_for_question_answer(request, opencode_session_id, pending_payload):- return True- return False- except Exception as err:- logger.warning(- f"Failed to send Slack buttons, falling back to text: {err}",- exc_info=True,- )-- # fallback: text-only- try:- await self._im_client.send_message(- request.context,- text,- parse_mode="markdown",- )- except Exception as err:- logger.error(f"Failed to send question prompt to Slack: {err}", exc_info=True)-- seen_tool_calls.add(call_key)- if await self.wait_for_question_answer(request, opencode_session_id, pending_payload):- return True- return Falsediff --git a/modules/agents/opencode/server.py b/modules/agents/opencode/server.pyindex ae2a7f459..7feb1041f 100644--- a/modules/agents/opencode/server.py+++ b/modules/agents/opencode/server.py@@ -765,34 +765,6 @@ class OpenCodeServerManager:raise RuntimeError(f"Failed to get message: {resp.status} {error_text}")return await resp.json()- async def list_questions(self, directory: Optional[str] = None) -> List[Dict[str, Any]]:- async with self._request_scope():- session = await self._get_http_session()- params = {"directory": directory} if directory else None- async with session.get(- f"{self.base_url}/question",- params=params,- ) as resp:- if resp.status != 200:- error_text = await resp.text()- raise RuntimeError(f"Failed to list questions: {resp.status} {error_text}")- data = await resp.json()- return data if isinstance(data, list) else []-- async def reply_question(self, question_id: str, directory: str, answers: List[List[str]]) -> bool:- async with self._request_scope():- session = await self._get_http_session()- async with session.post(- f"{self.base_url}/question/{question_id}/reply",- params={"directory": directory},- json={"answers": answers},- ) as resp:- if resp.status != 200:- error_text = await resp.text()- raise RuntimeError(f"Failed to reply question: {resp.status} {error_text}")- data = await resp.json()- return bool(data)-async def abort_session(self, session_id: str, directory: str) -> bool:async with self._request_scope():session = await self._get_http_session()diff --git a/modules/agents/opencode/types.py b/modules/agents/opencode/types.pyindex ad3c8a4bb..70c45ee76 100644--- a/modules/agents/opencode/types.py+++ b/modules/agents/opencode/types.py@@ -3,7 +3,7 @@from __future__ import annotationsfrom dataclasses import dataclass-from typing import Any, Dict, List, Optional, TypedDict+from typing import TypedDictclass ModelDict(TypedDict):@@ -11,22 +11,6 @@ class ModelDict(TypedDict):modelID: str-class PendingQuestionPayload(TypedDict, total=False):- session_id: str- directory: str- question_id: Optional[str]- call_id: Optional[str]- message_id: Optional[str]- prompt_message_id: Optional[str]- prompt_text: str- option_labels: List[str]- question_count: int- multiple: bool- questions: List[Dict[str, Any]]- thread_id: Optional[str]- trigger_message_id: Optional[str] # Original request message_id for consolidated key--@dataclass(frozen=True)class RequestSessionInfo:opencode_session_id: strdiff --git a/modules/agents/question_ui.py b/modules/agents/question_ui.pyindex ba78ad7a2..25aaa85e2 100644--- a/modules/agents/question_ui.py+++ b/modules/agents/question_ui.py@@ -126,7 +126,7 @@ class QuestionUIHandler:controller: Main controller for emitting messagesim_client: IM client for sending messagessettings_manager: Settings manager for state persistence- callback_prefix: Prefix for callback data (e.g., "opencode_question", "claude_question")+ callback_prefix: Prefix for callback data (e.g., "claude_question")"""self._controller = controllerself._im_client = im_clientdiff --git a/modules/im/discord.py b/modules/im/discord.pyindex 5ed340506..12dce1e41 100644--- a/modules/im/discord.py+++ b/modules/im/discord.py@@ -1919,7 +1919,7 @@ class DiscordBot(BaseIMClient):trigger_id: Any,context: MessageContext,pending: Any,- callback_prefix: str = "opencode_question",+ callback_prefix: str = "claude_question",):interaction = trigger_id if isinstance(trigger_id, discord.Interaction) else Noneif isinstance(pending, dict):@@ -2013,20 +2013,6 @@ class DiscordBot(BaseIMClient):raise RuntimeError("Discord channel not found")await channel.send("Please answer:", view=view)- async def open_opencode_question_modal(- self,- trigger_id: Any,- context: MessageContext,- pending: Any,- ):- await self.open_question_modal(- trigger_id=trigger_id,- context=context,- pending=pending,- callback_prefix="opencode_question",- )--class _PersistentStartView(discord.ui.View):"""Persistent view for /start menu buttons.@@ -2157,12 +2143,7 @@ class _DiscordButtonView(discord.ui.View):"cmd_routing","cmd_resume",}- if data == "opencode_question:open_modal":- try:- await interaction.response.defer(ephemeral=True)- except Exception:- pass- elif not needs_modal:+ if data.startswith("opencode_question:") or not needs_modal:try:await interaction.response.defer(ephemeral=True)except Exception:diff --git a/modules/im/feishu.py b/modules/im/feishu.pyindex 1415629ca..5d938f735 100644--- a/modules/im/feishu.py+++ b/modules/im/feishu.py@@ -2034,9 +2034,9 @@ class FeishuBot(BaseIMClient):The button name encodes metadata as``question_submit:{callback_prefix}:{question_count}:{thread_id}``."""- # Parse metadata from button name: question_submit:opencode_question:2:om_xxx+ # Parse metadata from button name: question_submit:<callback_prefix>:2:om_xxxparts = button_name.split(":")- callback_prefix = parts[1] if len(parts) > 1 else "opencode_question"+ callback_prefix = parts[1] if len(parts) > 1 else "claude_question"question_count = int(parts[2]) if len(parts) > 2 else 1embedded_thread_id = parts[3] if len(parts) > 3 else ""@@ -2895,16 +2895,16 @@ class FeishuBot(BaseIMClient):trigger_id: Any,context: MessageContext = None,pending: Any = None,- callback_prefix: str = "opencode_question",+ callback_prefix: str = "claude_question",**kwargs,):"""Send a JSON 2.0 form card with question select fields.Aligns with the Slack/Discord ``open_question_modal`` signature so that- ``question_handler.py`` can call it identically across platforms.+ agent question handlers can call it identically across platforms.``pending`` can be:- - A dict with ``"questions"`` key (OpenCode question handler format).+ - A dict with ``"questions"`` key.- A ``PendingQuestion`` dataclass with ``.questions`` attribute.Each question has ``header``, ``question``, ``multiple``, and ``options``@@ -3024,7 +3024,7 @@ class FeishuBot(BaseIMClient):})- title = t("modal.question.claudeCode") if callback_prefix.startswith("claude") else t("modal.question.opencode")+ title = t("modal.question.claudeCode")card = {"schema": "2.0",@@ -3054,20 +3054,6 @@ class FeishuBot(BaseIMClient):except Exception as exc:logger.error("Failed to send question card: %s", exc)- async def open_opencode_question_modal(- self,- trigger_id: Any,- context: MessageContext = None,- pending: Any = None,- ):- """Convenience wrapper matching the preferred OpenCode question handler call."""- await self.open_question_modal(- trigger_id=trigger_id,- context=context,- pending=pending,- callback_prefix="opencode_question",- )-async def _send_card_to_channel(self, context: MessageContext, card: dict) -> str:"""Send a raw card JSON to a channel."""self._ensure_client()diff --git a/modules/im/slack.py b/modules/im/slack.pyindex 4c9657df4..9d0e71601 100644--- a/modules/im/slack.py+++ b/modules/im/slack.py@@ -2256,8 +2256,8 @@ class SlackBot(BaseIMClient):# Backward compatibility: older callback signature omitted is_dm.await callback(user_id, channel_id, thread_id, chosen_agent, chosen_session, host_message_ts)- elif callback_id == "opencode_question_modal" or callback_id == "claude_question_modal":- # Generic question modal handling for both OpenCode and Claude+ elif callback_id == "claude_question_modal":+ # Generic question modal handling for Claudeuser_id = payload.get("user", {}).get("id")values = view.get("state", {}).get("values", {})metadata_raw = view.get("private_metadata")@@ -3753,132 +3753,22 @@ class SlackBot(BaseIMClient):"blocks": blocks,}- async def open_opencode_question_modal(- self,- trigger_id: str,- context: MessageContext,- pending: Dict[str, Any],- ):- self._ensure_clients()-- questions = pending.get("questions")- questions = questions if isinstance(questions, list) else []- if not questions:- raise ValueError("No questions available")-- import json-- private_metadata = json.dumps(- {- "channel_id": context.channel_id,- "thread_id": context.thread_id,- "question_count": len(questions),- }- )-- blocks: list[Dict[str, Any]] = []- for idx, q in enumerate(questions):- if not isinstance(q, dict):- continue- header = (q.get("header") or f"Question {idx + 1}").strip()- prompt = (q.get("question") or "").strip()- multiple = bool(q.get("multiple"))- options = q.get("options") if isinstance(q.get("options"), list) else []-- option_items = []- for opt in options:- if not isinstance(opt, dict):- continue- label = opt.get("label")- if label is None:- continue- desc = opt.get("description")- item: Dict[str, Any] = {- "text": {- "type": "plain_text",- "text": str(label)[:75],- "emoji": True,- },- "value": str(label),- }- if desc:- item["description"] = {- "type": "plain_text",- "text": str(desc)[:75],- "emoji": True,- }- option_items.append(item)-- element: Dict[str, Any]- if multiple:- element = {- "type": "multi_static_select",- "action_id": "select",- "options": option_items,- "placeholder": {- "type": "plain_text",- "text": self._t("common.selectOneOrMore"),- "emoji": True,- },- }- else:- element = {- "type": "static_select",- "action_id": "select",- "options": option_items,- "placeholder": {- "type": "plain_text",- "text": self._t("common.selectOne"),- "emoji": True,- },- }-- label_text = header- if prompt:- label_text = f"{header}: {prompt}"[:150]-- blocks.append(- {- "type": "input",- "block_id": f"q{idx}",- "label": {- "type": "plain_text",- "text": label_text,- "emoji": True,- },- "element": element,- }- )-- view = {- "type": "modal",- "callback_id": "opencode_question_modal",- "private_metadata": private_metadata,- "title": {"type": "plain_text", "text": self._t("modal.question.opencode"), "emoji": True},- "submit": {"type": "plain_text", "text": self._t("common.submit"), "emoji": True},- "close": {"type": "plain_text", "text": self._t("common.cancel"), "emoji": True},- "blocks": blocks,- }-- await self.web_client.views_open(trigger_id=trigger_id, view=view)-async def open_question_modal(self,trigger_id: str,context: MessageContext,pending: Any, # PendingQuestion from question_ui module- callback_prefix: str = "opencode_question",+ callback_prefix: str = "claude_question",):"""Open a question modal for any agent backend.- This is a generalized version of open_opencode_question_modal that- supports different callback prefixes for different agents.+ This supports different callback prefixes for agent question flows.Args:trigger_id: Slack trigger ID for opening the modalcontext: Message contextpending: PendingQuestion instance with questions data- callback_prefix: Prefix for callback routing (e.g., "opencode_question", "claude_question")+ callback_prefix: Prefix for callback routing (e.g., "claude_question")"""self._ensure_clients()@@ -3994,7 +3884,7 @@ class SlackBot(BaseIMClient):title = (self._t("modal.question.claudeCode")if callback_prefix.startswith("claude")- else self._t("modal.question.opencode")+ else self._t("modal.question.claudeCode"))view = {diff --git a/modules/im/telegram.py b/modules/im/telegram.pyindex 9574d2b7e..99823eefa 100644--- a/modules/im/telegram.py+++ b/modules/im/telegram.py@@ -1205,9 +1205,6 @@ class TelegramBot(BaseIMClient):else:state.message_id = await self.send_message_with_buttons(target_context, text, keyboard)- async def open_opencode_question_modal(self, trigger_id: Any, context: MessageContext, pending: Any):- await self.open_question_modal(trigger_id, context, pending, callback_prefix="opencode_question")-def _get_backend_label(self, backend: str) -> str:translated = self._t(f"backend.{backend}")return translated if translated != f"backend.{backend}" else backenddiff --git a/tests/test_message_handler_typing.py b/tests/test_message_handler_typing.pyindex ef801829b..a1d5393fa 100644--- a/tests/test_message_handler_typing.py+++ b/tests/test_message_handler_typing.py@@ -574,6 +574,16 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):platform="lark",)+ async def test_legacy_opencode_question_callback_is_ignored(self):+ controller = _StubController(platform="slack", ack_mode="reaction", typing_result=True)+ handler = MessageHandler(controller)+ handler.set_session_handler(_StubSessionHandler())+ context = MessageContext(user_id="u1", channel_id="c1", platform="slack")++ await handler.handle_callback_query(context, "opencode_question:choose:1")++ self.assertEqual(controller.agent_service.requests, [])+async def test_quick_reply_callback_preserves_platform(self):controller = _StubController(platform="slack", ack_mode="reaction", typing_result=True)handler = MessageHandler(controller)diff --git a/tests/test_multi_platform_runtime.py b/tests/test_multi_platform_runtime.pyindex 549a792dc..fd9daf34d 100644--- a/tests/test_multi_platform_runtime.py+++ b/tests/test_multi_platform_runtime.py@@ -12,6 +12,8 @@ from modules.im.multi import MultiIMClientfrom modules.settings_manager import MultiSettingsManagerfrom config.v2_sessions import ActivePollInfofrom core.processing_indicator import ProcessingIndicatorService+from modules.agents.base import AgentRequest+from modules.agents.opencode.agent import OpenCodeAgentfrom modules.agents.opencode.poll_loop import OpenCodePollLoop@@ -228,7 +230,7 @@ def test_opencode_restored_ack_preserves_wechat_typing_context():"typing_indicator_active": True,},)- loop = OpenCodePollLoop(_StubAgent(), question_handler=None)+ loop = OpenCodePollLoop(_StubAgent())asyncio.run(loop.remove_restored_ack(poll))@@ -239,6 +241,234 @@ def test_opencode_restored_ack_preserves_wechat_typing_context():assert wechat.sent == [("clear_typing", "wechat", "user-1", "ctx-1")]+def test_opencode_prompt_disables_question_tool_for_all_platforms():+ calls = []++ class _Server:+ async def ensure_running(self):+ return None++ async def list_messages(self, session_id, directory):+ return []++ async def prompt_async(self, **kwargs):+ calls.append(kwargs)++ async def mark_run_active(self, session_id):+ return None++ async def mark_run_inactive(self, session_id):+ return None++ def get_default_agent_from_config(self):+ return None++ def get_agent_model_from_config(self, _agent):+ return None++ def get_agent_reasoning_effort_from_config(self, _agent):+ return None++ class _SessionManager:+ async def ensure_working_dir(self, path):+ return None++ async def get_or_create_session_id(self, request, server):+ return "oc-session"++ def set_request_session(self, *args):+ return None++ def mark_initialized(self, session_id):+ return False++ class _Sessions:+ def add_active_poll(self, **kwargs):+ return None++ def remove_active_poll(self, session_id):+ return None++ class _PollLoop:+ async def run_prompt_poll(self, *args, **kwargs):+ return "done", True++ async def _get_server():+ return _Server()++ async def _async_noop():+ return None++ class _Controller:+ def __init__(self):+ self.config = type(+ "Config",+ (),+ {+ "platform": "slack",+ "reply_enhancements": True,+ "show_pages_prompt": True,+ "remote_access": None,+ "language": "en",+ },+ )()+ self.im_client = _StubClient("slack")+ self.settings_manager = type("Settings", (), {"sessions": _Sessions()})()+ self.sessions = self.settings_manager.sessions+ self.processing_indicator = type("Processing", (), {"snapshot_request": lambda self, request: {}})()++ def get_opencode_overrides(self, context):+ return None, None, None++ agent = OpenCodeAgent.__new__(OpenCodeAgent)+ agent.controller = _Controller()+ agent.config = agent.controller.config+ agent.im_client = agent.controller.im_client+ agent.settings_manager = agent.controller.settings_manager+ agent.sessions = agent.controller.sessions+ agent.opencode_config = type("OpenCodeConfig", (), {"error_retry_limit": 0})()+ agent._session_manager = _SessionManager()+ agent._poll_loop = _PollLoop()+ agent._get_server = _get_server+ agent._delete_ack = lambda request: _async_noop()+ agent._remove_ack_reaction = lambda request: _async_noop()+ agent.emit_result_message = lambda *args, **kwargs: _async_noop()++ async def _run():+ request = AgentRequest(+ context=MessageContext(+ user_id="u",+ channel_id="c",+ platform="slack",+ platform_specific={"agent_session_id": "ses_test"},+ ),+ message="hello",+ working_path="/tmp/work",+ base_session_id="base",+ composite_session_id="base:/tmp/work",+ session_key="slack::c",+ )+ await agent._process_message(request)++ asyncio.run(_run())++ assert calls+ assert calls[0]["tools"] == {"question": False}+++def test_opencode_legacy_question_callback_is_ignored():+ removed = []++ class _Controller:+ def __init__(self):+ self.config = type("Config", (), {})()+ self.im_client = _StubClient("slack")+ self.settings_manager = type("Settings", (), {"sessions": object()})()++ async def _remove_ack(request):+ removed.append(request.message)++ agent = OpenCodeAgent.__new__(OpenCodeAgent)+ agent.controller = _Controller()+ agent.config = agent.controller.config+ agent.im_client = agent.controller.im_client+ agent.settings_manager = agent.controller.settings_manager+ agent._remove_ack_reaction = _remove_ack++ async def _run():+ request = AgentRequest(+ context=MessageContext(user_id="u", channel_id="c", platform="slack"),+ message="opencode_question:choose:1",+ working_path="/tmp/work",+ base_session_id="base",+ composite_session_id="base:/tmp/work",+ session_key="slack::c",+ )+ await agent.handle_message(request)++ asyncio.run(_run())++ assert removed == ["opencode_question:choose:1"]+++def test_opencode_poll_aborts_disabled_question_toolcall():+ emitted = []+ aborted = []++ class _Formatter:+ def format_toolcall(self, *args, **kwargs):+ return "tool"++ class _Controller:+ def _t(self, key):+ return f"translated:{key}"++ async def emit_agent_message(self, context, message_type, text, parse_mode=None):+ emitted.append((message_type, text))++ class _Agent:+ opencode_config = type("OpenCodeConfig", (), {"error_retry_limit": 0})()+ controller = _Controller()+ im_client = type("IM", (), {"formatter": _Formatter()})()++ def _get_formatter(self, context):+ return _Formatter()++ def _to_relative_path(self, path, working_path):+ return path++ def _extract_response_text(self, message):+ return ""++ class _Server:+ async def list_messages(self, session_id, directory):+ return [+ {+ "info": {"id": "msg-1", "role": "assistant"},+ "parts": [+ {+ "type": "tool",+ "id": "part-1",+ "tool": "question",+ "state": {"status": "pending", "input": {"questions": []}},+ }+ ],+ }+ ]++ async def abort_session(self, session_id, directory):+ aborted.append((session_id, directory))+ return True++ request = AgentRequest(+ context=MessageContext(user_id="u", channel_id="c", platform="slack"),+ message="hello",+ working_path="/tmp/work",+ base_session_id="base",+ composite_session_id="base:/tmp/work",+ session_key="slack::c",+ )++ loop = OpenCodePollLoop(_Agent())+ final_text, should_emit = asyncio.run(+ loop.run_prompt_poll(+ request,+ _Server(),+ "oc-session",+ agent_to_use=None,+ model_dict=None,+ reasoning_effort=None,+ baseline_message_ids=set(),+ )+ )++ assert final_text is None+ assert should_emit is False+ assert aborted == [("oc-session", "/tmp/work")]+ assert emitted[0][0] == "notify"+ assert emitted[0][1] == "translated:error.opencodeQuestionToolDisabled"++def test_processing_indicator_handle_is_source_of_truth_for_backend_cleanup():wechat = _StubClient("wechat")diff --git a/tests/test_opencode_question_handler.py b/tests/test_opencode_question_handler.pydeleted file mode 100644index e1f1f4c64..000000000--- a/tests/test_opencode_question_handler.py+++ /dev/null@@ -1,247 +0,0 @@-import asyncio-import importlib.util-from pathlib import Path-import sys-import types-import unittest--from modules.im import MessageContext-from vibe.i18n import t as i18n_t--REPO_ROOT = Path(__file__).resolve().parents[1]---def _ensure_package(name: str, path: Path) -> None:- module = sys.modules.get(name)- if module is None:- module = types.ModuleType(name)- module.__path__ = [str(path)]- sys.modules[name] = module---def _load_module(name: str, relative_path: str):- module = sys.modules.get(name)- if module is not None:- return module-- spec = importlib.util.spec_from_file_location(name, REPO_ROOT / relative_path)- if spec is None or spec.loader is None:- raise RuntimeError(f"Failed to load module {name} from {relative_path}")-- module = importlib.util.module_from_spec(spec)- sys.modules[name] = module- spec.loader.exec_module(module)- return module---_ensure_package("modules", REPO_ROOT / "modules")-_ensure_package("modules.agents", REPO_ROOT / "modules/agents")-_ensure_package("modules.agents.opencode", REPO_ROOT / "modules/agents/opencode")-_ensure_package("modules.im", REPO_ROOT / "modules/im")--server_stub = types.ModuleType("modules.agents.opencode.server")-setattr(server_stub, "OpenCodeServerManager", type("OpenCodeServerManager", (), {}))-sys.modules.setdefault("modules.agents.opencode.server", server_stub)--base_module = _load_module("modules.agents.base", "modules/agents/base.py")-question_ui_module = _load_module("modules.agents.question_ui", "modules/agents/question_ui.py")-_load_module("modules.agents.opencode.types", "modules/agents/opencode/types.py")-question_handler_module = _load_module(- "modules.agents.opencode.question_handler",- "modules/agents/opencode/question_handler.py",-)--AgentRequest = base_module.AgentRequest-QuestionUIHandler = question_ui_module.QuestionUIHandler-PendingQuestion = question_ui_module.PendingQuestion-OpenCodeQuestionHandler = question_handler_module.OpenCodeQuestionHandler---class _StubIMClient:- def __init__(self):- self.sent_messages = []- self.removed_keyboards = []- self.reactions = []-- async def send_message(self, context, text, parse_mode=None, reply_to=None):- message_id = f"M{len(self.sent_messages) + 1}"- self.sent_messages.append((context.channel_id, context.thread_id, text, parse_mode, reply_to))- return message_id-- async def remove_inline_keyboard(self, context, message_id, text=None, parse_mode=None):- self.removed_keyboards.append((context.channel_id, context.thread_id, message_id, text, parse_mode))- return True-- async def add_reaction(self, context, message_id, emoji):- self.reactions.append((context.channel_id, context.thread_id, message_id, emoji))- return True---class _StubConfig:- def __init__(self, language="zh"):- self.language = language---class _StubController:- def __init__(self, lang="zh", platform="slack"):- self.config = _StubConfig(language=lang)- self.config.platform = platform- self.emitted_messages = []- self.cleared_consolidated_ids = []-- def _t(self, key, **kwargs):- return i18n_t(key, self.config.language, **kwargs)-- async def emit_agent_message(self, context, message_type, text, parse_mode=None):- self.emitted_messages.append((context.channel_id, message_type, text, parse_mode))-- async def clear_consolidated_message_id(self, context, trigger_message_id=None):- self.cleared_consolidated_ids.append((context.channel_id, context.thread_id, trigger_message_id))---class _StubServer:- def __init__(self, ok=True):- self.ok = ok- self.reply_calls = []- self.abort_calls = []-- async def reply_question(self, question_id, directory, answers_payload):- self.reply_calls.append((question_id, directory, answers_payload))- return self.ok-- async def abort_session(self, session_id, directory):- self.abort_calls.append((session_id, directory))- return True---def _build_request(message: str) -> AgentRequest:- return AgentRequest(- context=MessageContext(- user_id="U123",- channel_id="C123",- thread_id="T123",- message_id="USER1",- ),- message=message,- working_path="/tmp/work",- base_session_id="base-session",- composite_session_id="base-session:/tmp/work",- session_key="C123",- )---class OpenCodeQuestionHandlerTests(unittest.IsolatedAsyncioTestCase):- async def test_process_question_answer_sends_visible_reply_echo(self):- controller = _StubController(lang="zh")- im_client = _StubIMClient()- handler = OpenCodeQuestionHandler(controller, im_client, object())- server = _StubServer(ok=True)- request = _build_request("opencode_question:choose:2")- handler._question_answer_events[request.base_session_id] = asyncio.Event()-- pending = {- "session_id": "oc-session",- "directory": "/tmp/work",- "question_id": "q-1",- "option_labels": ["Alpha", "Beta"],- "prompt_message_id": "PROMPT1",- "prompt_text": "Pick an option",- "trigger_message_id": "TRIGGER1",- }-- await handler.process_question_answer(request, pending, server)-- self.assertEqual(server.reply_calls, [("q-1", "/tmp/work", [["Beta"]])])- self.assertEqual(- im_client.removed_keyboards,- [("C123", "T123", "PROMPT1", "Pick an option", "markdown")],- )- self.assertEqual(im_client.sent_messages[0][2], "回复:Beta")- self.assertEqual(controller.cleared_consolidated_ids, [("C123", "T123", "TRIGGER1")])- self.assertTrue(handler._question_answer_events[request.base_session_id].is_set())-- async def test_handle_question_toolcall_is_blocked_on_wechat(self):- controller = _StubController(lang="zh", platform="wechat")- im_client = _StubIMClient()- handler = OpenCodeQuestionHandler(controller, im_client, object())- server = _StubServer(ok=True)- request = _build_request("ask")- seen_tool_calls = set()-- answered = await handler.handle_question_toolcall(- request=request,- server=server,- opencode_session_id="oc-session",- message_id="msg-1",- tool_part={"callID": "call-1"},- tool_input={"questions": [{"question": "Need input?"}]},- call_key="call-1",- seen_tool_calls=seen_tool_calls,- )-- self.assertFalse(answered)- self.assertEqual(server.abort_calls, [("oc-session", "/tmp/work")])- self.assertEqual(- controller.emitted_messages,- [("C123", "notify", "微信平台暂时不支持 OpenCode 的交互式提问。请直接再发一条消息继续。", None)],- )- self.assertEqual(im_client.sent_messages, [])- self.assertIn("call-1", seen_tool_calls)-- async def test_handle_question_toolcall_uses_request_context_platform(self):- controller = _StubController(lang="zh", platform="slack")- im_client = _StubIMClient()- handler = OpenCodeQuestionHandler(controller, im_client, object())- server = _StubServer(ok=True)- request = _build_request("ask")- request.context.platform = "wechat"- request.context.platform_specific = {"platform": "wechat"}- seen_tool_calls = set()-- answered = await handler.handle_question_toolcall(- request=request,- server=server,- opencode_session_id="oc-session",- message_id="msg-1",- tool_part={"callID": "call-1"},- tool_input={"questions": [{"question": "Need input?"}]},- call_key="call-1",- seen_tool_calls=seen_tool_calls,- )-- self.assertFalse(answered)- self.assertEqual(server.abort_calls, [("oc-session", "/tmp/work")])---class QuestionUIHandlerTests(unittest.IsolatedAsyncioTestCase):- async def test_send_answer_receipt_formats_multi_question_answers(self):- controller = _StubController(lang="en")- im_client = _StubIMClient()- ui_handler = QuestionUIHandler(controller, im_client, object(), "opencode_question")- request = _build_request("unused")-- await ui_handler.send_answer_receipt(request, [["Alpha", "Beta"], ["Gamma"]])-- self.assertEqual(im_client.sent_messages[0][2], "Reply: \nQ1: Alpha, Beta\nQ2: Gamma")-- async def test_update_prompt_after_answer_does_not_append_selection_text(self):- controller = _StubController(lang="zh")- im_client = _StubIMClient()- ui_handler = QuestionUIHandler(controller, im_client, object(), "opencode_question")- request = _build_request("freeform answer")- pending = PendingQuestion(- questions=[],- prompt_text="请选择一个答案",- option_labels=[],- base_session_id=request.base_session_id,- thread_id=request.context.thread_id,- prompt_message_id="PROMPT2",- )-- await ui_handler.update_prompt_after_answer(request, pending)-- self.assertEqual(- im_client.removed_keyboards,- [("C123", "T123", "PROMPT2", "请选择一个答案", "markdown")],- )- self.assertNotIn("已选择", im_client.removed_keyboards[0][3])diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex 1bbc92f53..dffde69cc 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -42,13 +42,14 @@"processActionFailed": "Error processing action: {error}","agentNotConfigured": "Agent `{agent}` is not configured. Make sure the Codex CLI is installed and environment variables are set if this channel is routed to Codex.","processMessageFailed": "Error: {error}",- "opencodeQuestionUnsupportedWechat": "OpenCode interactive questions are temporarily disabled on WeChat. Please send a follow-up message instead.","sessionReset": "Session error detected. Session has been reset. Please try your message again.","sessionConnectionLost": "Connection to Claude was lost. Please try your message again.","claudeSessionNotFound": "Claude Code could not find the historical session `{sessionId}` in the current working directory:\n`{path}`\n\nClaude Code sessions are scoped to a working directory. This usually means the conversation was resumed after switching workdirs, or the local Claude Code session data changed. Switch back to the original working directory to continue that session, or start a new Claude Code session from the current directory.","sessionGeneric": "An error occurred: {error}","resultAttachmentUploadFailed": "Failed to upload attachment. Want me to split the result into multiple messages?",- "resultDeliveryFailed": "⚠️ Message delivery failed. The content may be too long or incompatible. Ask me to resend it."+ "resultDeliveryFailed": "⚠️ Message delivery failed. The content may be too long or incompatible. Ask me to resend it.",+ "opencodeQuestionToolDisabled": "OpenCode asked an interactive question, but Vibe Remote disables the OpenCode question tool. Please send a new follow-up message with your answer or direction.",+ "opencodeQuestionToolDisabledRestored": "Restored OpenCode session asked an interactive question, but Vibe Remote disables the OpenCode question tool. Please send a new follow-up message with your answer or direction."},"success": {"settingsUpdated": "Settings updated successfully!",diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex 590153b91..6b8ce673c 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -42,13 +42,14 @@"processActionFailed": "处理操作时出错:{error}","agentNotConfigured": "Agent `{agent}` 未配置。若此频道路由到 Codex,请确保已安装 Codex CLI 并设置环境变量。","processMessageFailed": "出错:{error}",- "opencodeQuestionUnsupportedWechat": "微信平台暂时不支持 OpenCode 的交互式提问。请直接再发一条消息继续。","sessionReset": "检测到会话错误。会话已重置,请重试。","sessionConnectionLost": "与 Claude 的连接已断开,请重试。","claudeSessionNotFound": "Claude Code 在当前工作目录下找不到历史会话 `{sessionId}`:\n`{path}`\n\nClaude Code 的会话和工作目录相关。通常是恢复会话后切换了工作目录,或本地 Claude Code 会话数据发生变化。请切回原来的工作目录继续该会话,或在当前目录开始一个新的 Claude Code 会话。","sessionGeneric": "发生错误:{error}","resultAttachmentUploadFailed": "附件上传失败。要我改成拆分成多条消息发送吗?",- "resultDeliveryFailed": "⚠️ 消息投递失败,内容可能过长或格式不兼容。你可以让我重新发送一次。"+ "resultDeliveryFailed": "⚠️ 消息投递失败,内容可能过长或格式不兼容。你可以让我重新发送一次。",+ "opencodeQuestionToolDisabled": "OpenCode 发起了交互式提问,但 Vibe Remote 已禁用 OpenCode 的 question 工具。请直接发送一条新消息,告诉我你的答案或下一步方向。",+ "opencodeQuestionToolDisabledRestored": "恢复中的 OpenCode 会话发起了交互式提问,但 Vibe Remote 已禁用 OpenCode 的 question 工具。请直接发送一条新消息,告诉我你的答案或下一步方向。"},"success": {"settingsUpdated": "设置更新成功!",