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
feat(claude): add AskUserQuestion support for Claude Code agent
cyhhao88fd675751ef
diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.pyindex 18723ea46..f32f60150 100644--- a/core/handlers/message_handler.py+++ b/core/handlers/message_handler.py@@ -339,6 +339,24 @@ class MessageHandler:)await self.controller.agent_service.handle_message("opencode", request)+ elif callback_data.startswith("claude_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)+ )+ settings_key = self._get_settings_key(context)+ request = AgentRequest(+ context=context,+ message=callback_data,+ working_path=working_path,+ base_session_id=base_session_id,+ composite_session_id=composite_key,+ settings_key=settings_key,+ )+ await self.controller.agent_service.handle_message("claude", request)+else:logger.warning(f"Unknown callback data: {callback_data}")await self.im_client.send_message(diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.pyindex 986233c88..51fd82006 100644--- a/modules/agents/claude_agent.py+++ b/modules/agents/claude_agent.py@@ -6,6 +6,7 @@ from typing import Callable, Optionalfrom claude_code_sdk import TextBlock, ToolUseBlockfrom modules.agents.base import AgentRequest, BaseAgent+from modules.agents.claude_question_handler import ClaudeQuestionHandlerfrom modules.im import MessageContextlogger = logging.getLogger(__name__)@@ -29,9 +30,22 @@ class ClaudeAgent(BaseAgent):# Each entry is (reaction_message_id, emoji)self._pending_reactions: dict[str, list[tuple[str, str]]] = {}+ # Question handler for AskUserQuestion support+ self._question_handler = ClaudeQuestionHandler(+ agent=self,+ controller=controller,+ im_client=controller.im_client,+ settings_manager=controller.settings_manager,+ )+async def handle_message(self, request: AgentRequest) -> None:context = request.context+ # Check if this is a question callback+ if request.message.startswith("claude_question:"):+ await self._handle_question_callback(request)+ return+try:client = await self.session_handler.get_or_create_claude_session(context,@@ -77,6 +91,35 @@ class ClaudeAgent(BaseAgent):finally:await self._delete_ack(context, request)+ async def _handle_question_callback(self, request: AgentRequest) -> None:+ """Handle question-related callbacks (button clicks, modal submissions)."""+ pending = self._question_handler.get_pending(request.base_session_id)+ if not pending:+ await self.controller.emit_agent_message(+ request.context,+ "notify",+ "No pending question found. The session may have timed out.",+ )+ return++ # Handle modal open request+ if request.message == "claude_question:open_modal":+ trigger_id = None+ if request.context.platform_specific:+ trigger_id = request.context.platform_specific.get("trigger_id")+ if trigger_id:+ await self._question_handler.open_modal(request, pending)+ else:+ await self.controller.emit_agent_message(+ request.context,+ "notify",+ "Cannot open modal without trigger_id. Please reply with text.",+ )+ return++ # Process answer+ await self._question_handler.process_answer(request, pending)+async def clear_sessions(self, settings_key: str) -> int:"""Clear Claude sessions scoped to the provided settings key."""agent_map = self.settings_manager.sessions_store.get_agent_map(@@ -149,6 +192,17 @@ class ClaudeAgent(BaseAgent):try:settings_key = self.controller._get_settings_key(context)composite_key = f"{base_session_id}:{working_path}"++ # Build a request object for question handler+ request = AgentRequest(+ context=context,+ message="",+ working_path=working_path,+ base_session_id=base_session_id,+ composite_session_id=composite_key,+ settings_key=settings_key,+ )+async for message in client.receive_messages():try:claude_session_id = self._maybe_capture_session_id(@@ -168,8 +222,16 @@ class ClaudeAgent(BaseAgent):if message_type == "assistant":toolcalls = []text_parts = []+ ask_user_question_block = None+for block in getattr(message, "content", []) or []:if isinstance(block, ToolUseBlock):+ # Check for AskUserQuestion+ if self._question_handler.is_ask_user_question(block):+ ask_user_question_block = block+ # Don't format as regular toolcall+ continue+toolcalls.append(formatter.format_toolcall(block.name,@@ -214,6 +276,32 @@ class ClaudeAgent(BaseAgent):self._pending_assistant_message[composite_key] = (formatted_assistant)++ # Handle AskUserQuestion if detected+ if ask_user_question_block:+ logger.info(+ "Detected AskUserQuestion for session %s",+ base_session_id,+ )+ answered = await self._question_handler.handle_ask_user_question(+ request=request,+ tool_use_block=ask_user_question_block,+ client=client,+ composite_session_id=composite_key,+ )+ if not answered:+ # Timed out - stop receiving messages+ logger.warning(+ "AskUserQuestion timed out for session %s",+ base_session_id,+ )+ return+ # Answer submitted - continue receiving messages+ logger.info(+ "AskUserQuestion answered for session %s, continuing",+ base_session_id,+ )+continueif message_type == "system":diff --git a/modules/agents/claude_question_handler.py b/modules/agents/claude_question_handler.pynew file mode 100644index 000000000..8b61c4e94--- /dev/null+++ b/modules/agents/claude_question_handler.py@@ -0,0 +1,403 @@+"""Question/answer coordination for the Claude Code agent.++This module handles:+- Detecting AskUserQuestion tool calls from Claude Code+- Presenting question UI to the user via the common QuestionUIHandler+- Submitting answers back to Claude Code via tool result+"""++from __future__ import annotations++import asyncio+import json+import logging+from typing import Any, Dict, List, Optional, TYPE_CHECKING++from modules.agents.base import AgentRequest+from modules.agents.question_ui import (+ Question,+ QuestionOption,+ QuestionUIHandler,+ PendingQuestion,+)++if TYPE_CHECKING:+ from modules.agents.claude_agent import ClaudeAgent++logger = logging.getLogger(__name__)+++class ClaudeQuestionHandler:+ """Handles AskUserQuestion tool calls for Claude Code agent.++ This class:+ - Detects AskUserQuestion ToolUseBlock+ - Converts Claude's question format to the common format+ - Uses QuestionUIHandler for UI rendering and answer waiting+ - Submits answers back as tool results+ """++ # Callback prefix for routing+ CALLBACK_PREFIX = "claude_question"++ def __init__(self, agent: "ClaudeAgent", controller, im_client, settings_manager):+ self._agent = agent+ self._controller = controller+ self._im_client = im_client+ self._settings_manager = settings_manager++ # The shared UI handler+ self._ui_handler = QuestionUIHandler(+ controller=controller,+ im_client=im_client,+ settings_manager=settings_manager,+ callback_prefix=self.CALLBACK_PREFIX,+ )++ # Map base_session_id -> tool_use_id for submitting answers+ self._pending_tool_use_ids: Dict[str, str] = {}+ # Map base_session_id -> SDK client for submitting answers+ self._pending_clients: Dict[str, Any] = {}+ # Map base_session_id -> composite_session_id for SDK query+ self._pending_composite_ids: Dict[str, str] = {}++ # -------------------------------------------------------------------------+ # Public API+ # -------------------------------------------------------------------------++ def get_pending(self, base_session_id: str) -> Optional[PendingQuestion]:+ """Get pending question for a session."""+ return self._ui_handler.get_pending(base_session_id)++ async def clear(self, base_session_id: str) -> None:+ """Clear all state for a session."""+ await self._ui_handler.clear(base_session_id)+ self._pending_tool_use_ids.pop(base_session_id, None)+ self._pending_clients.pop(base_session_id, None)+ self._pending_composite_ids.pop(base_session_id, None)++ def is_ask_user_question(self, tool_use_block) -> bool:+ """Check if a ToolUseBlock is an AskUserQuestion call."""+ return getattr(tool_use_block, "name", None) == "AskUserQuestion"++ async def handle_ask_user_question(+ self,+ request: AgentRequest,+ tool_use_block,+ client,+ composite_session_id: str,+ ) -> bool:+ """Handle an AskUserQuestion tool call.++ Args:+ request: The agent request+ tool_use_block: The ToolUseBlock with AskUserQuestion+ client: The Claude SDK client for submitting answers+ composite_session_id: Session ID for SDK query++ Returns:+ True if answer was received, False if timed out+ """+ tool_use_id = getattr(tool_use_block, "id", None)+ tool_input = getattr(tool_use_block, "input", {})++ if not tool_use_id:+ logger.error("AskUserQuestion tool call missing id")+ return False++ logger.info(+ "Handling AskUserQuestion for session %s, tool_use_id=%s",+ request.base_session_id,+ tool_use_id,+ )++ # Convert Claude's question format to common format+ questions = self._convert_questions(tool_input)+ if not questions:+ logger.warning("AskUserQuestion had no valid questions")+ return False++ # Build prompt text+ prompt_text = self._ui_handler.build_prompt_text(questions)++ # Extract option labels from first question for simple button case+ option_labels = [opt.label for opt in questions[0].options] if questions else []++ # Create pending question+ pending = PendingQuestion(+ questions=questions,+ prompt_text=prompt_text,+ option_labels=option_labels,+ base_session_id=request.base_session_id,+ thread_id=request.context.thread_id,+ agent_data={+ "tool_use_id": tool_use_id,+ },+ )++ # Store state for answer submission+ self._pending_tool_use_ids[request.base_session_id] = tool_use_id+ self._pending_clients[request.base_session_id] = client+ self._pending_composite_ids[request.base_session_id] = composite_session_id+ self._ui_handler.set_pending(request.base_session_id, pending)++ # Render question UI+ message_id = await self._ui_handler.render_question_ui(request, pending)+ if message_id:+ pending.prompt_message_id = message_id++ # Wait for answer+ answered = await self._ui_handler.wait_for_answer(+ request,+ pending,+ on_timeout=self._on_timeout,+ )++ return answered++ async def process_answer(+ self,+ request: AgentRequest,+ pending: PendingQuestion,+ ) -> bool:+ """Process user's answer and submit to Claude Code.++ Args:+ request: Agent request with answer in message field+ pending: Pending question state++ Returns:+ True if answer was submitted successfully+ """+ base_session_id = request.base_session_id+ tool_use_id = self._pending_tool_use_ids.get(base_session_id)+ client = self._pending_clients.get(base_session_id)+ composite_session_id = self._pending_composite_ids.get(base_session_id)++ if not tool_use_id or not client or not composite_session_id:+ logger.error(+ "Missing state for answer submission: tool_use_id=%s, client=%s, composite=%s",+ tool_use_id,+ client is not None,+ composite_session_id,+ )+ await self._controller.emit_agent_message(+ request.context,+ "notify",+ "Claude question context is missing. Please retry your request.",+ )+ return False++ # Parse answer from callback data+ answers_payload = self._parse_answer(request.message, pending)+ if answers_payload is None:+ await self._controller.emit_agent_message(+ request.context,+ "notify",+ "Please provide an answer.",+ )+ return False++ # Update UI to show selection+ await self._ui_handler.update_prompt_after_answer(+ request, pending, answers_payload+ )++ # Build answer text for Claude+ answer_text = self._build_answer_text(answers_payload, pending)++ # Submit tool result to Claude+ try:+ await self._submit_tool_result(+ client, composite_session_id, tool_use_id, answer_text+ )+ except Exception as err:+ logger.error(f"Failed to submit answer to Claude: {err}", exc_info=True)+ await self._controller.emit_agent_message(+ request.context,+ "notify",+ f"Failed to submit answer to Claude: {err}. Please retry.",+ )+ return False++ # Add reaction to indicate answer received+ await self._ui_handler.add_answer_reaction(request, pending)++ # Clean up and signal+ self._pending_tool_use_ids.pop(base_session_id, None)+ self._pending_clients.pop(base_session_id, None)+ self._pending_composite_ids.pop(base_session_id, None)+ self._ui_handler.pop_pending(base_session_id)+ self._ui_handler.signal_answer_received(base_session_id)++ logger.info("Answer submitted for session %s", base_session_id)+ return True++ async def open_modal(self, request: AgentRequest, pending: PendingQuestion) -> None:+ """Open the question modal."""+ await self._ui_handler.open_modal(request, pending)++ # -------------------------------------------------------------------------+ # Internal helpers+ # -------------------------------------------------------------------------++ def _convert_questions(self, tool_input: Dict[str, Any]) -> List[Question]:+ """Convert Claude's AskUserQuestion format to common Question format.++ Claude format:+ {+ "questions": [+ {+ "question": "Which library?",+ "header": "Library",+ "options": [{"label": "axios", "description": "HTTP client"}],+ "multiSelect": false+ }+ ]+ }+ """+ questions_raw = tool_input.get("questions", [])+ if not isinstance(questions_raw, list):+ return []++ questions = []+ for q in questions_raw:+ if not isinstance(q, dict):+ continue++ options_raw = q.get("options", [])+ options = []+ for opt in options_raw:+ if not isinstance(opt, dict):+ continue+ label = opt.get("label", "")+ desc = opt.get("description", "")+ if label:+ options.append(QuestionOption(label=str(label), description=str(desc)))++ question = Question(+ question=str(q.get("question", "")),+ header=str(q.get("header", "")),+ options=options,+ # Claude uses "multiSelect", our common format uses "multiple"+ multiple=bool(q.get("multiSelect", False)),+ )+ questions.append(question)++ return questions++ def _parse_answer(+ self, message: str, pending: PendingQuestion+ ) -> Optional[List[List[str]]]:+ """Parse answer from callback data or user message.++ Returns answers_payload in format [[answer1], [answer2], ...]+ """+ prefix = f"{self.CALLBACK_PREFIX}:"++ # Button click: "claude_question:choose:1"+ if message.startswith(f"{prefix}choose:"):+ try:+ choice_idx = int(message.rsplit(":", 1)[-1]) - 1+ if 0 <= choice_idx < len(pending.option_labels):+ answer = pending.option_labels[choice_idx]+ return [[answer] for _ in range(pending.question_count)]+ except Exception:+ pass+ return None++ # Modal submission: "claude_question:modal:{...}"+ if message.startswith(f"{prefix}modal:"):+ try:+ payload = json.loads(message.split(":", 2)[-1])+ answers = payload.get("answers", [])+ if isinstance(answers, list) and answers:+ # Normalize to List[List[str]]+ normalized = []+ 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([])+ return normalized+ except Exception:+ logger.debug("Failed to parse modal answers")+ return None++ # Plain text answer+ text = message.strip()+ if text and not message.startswith(prefix):+ return [[text] for _ in range(pending.question_count)]++ return None++ def _build_answer_text(+ self, answers_payload: List[List[str]], pending: PendingQuestion+ ) -> str:+ """Build answer text to send back to Claude.++ Format: "User has answered your questions: Q1=answer1, Q2=answer2"+ """+ parts = []+ for idx, answers in enumerate(answers_payload):+ if not answers:+ continue+ joined = ", ".join(answers)+ if len(answers_payload) > 1:+ parts.append(f"Q{idx + 1}={joined}")+ else:+ parts.append(joined)++ if not parts:+ return "User provided no answer"++ return f"User has answered your questions: {'; '.join(parts)}"++ async def _submit_tool_result(+ self,+ client,+ composite_session_id: str,+ tool_use_id: str,+ answer_text: str,+ ) -> None:+ """Submit tool result to Claude Code SDK.++ Claude expects a user message with tool_result content block.+ """+ message = {+ "type": "user",+ "message": {+ "role": "user",+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": tool_use_id,+ "content": answer_text,+ }+ ],+ },+ "parent_tool_use_id": None,+ "session_id": composite_session_id,+ }++ # Use transport.write directly since query() may not support this format+ if hasattr(client, "_transport") and client._transport:+ await client._transport.write(json.dumps(message) + "\n")+ logger.info(+ "Submitted tool result for %s: %s",+ tool_use_id,+ answer_text[:100],+ )+ else:+ raise RuntimeError("Claude SDK client transport not available")++ async def _on_timeout(+ self, request: AgentRequest, pending: PendingQuestion+ ) -> None:+ """Handle timeout when user doesn't answer."""+ # Clean up our state+ self._pending_tool_use_ids.pop(request.base_session_id, None)+ self._pending_clients.pop(request.base_session_id, None)+ self._pending_composite_ids.pop(request.base_session_id, None)diff --git a/modules/agents/question_ui.py b/modules/agents/question_ui.pynew file mode 100644index 000000000..07958063b--- /dev/null+++ b/modules/agents/question_ui.py@@ -0,0 +1,506 @@+"""Common question UI rendering and answer coordination for all agent backends.++This module provides shared infrastructure for:+- Rendering question prompts (text, buttons, modals)+- Waiting for user answers (event-based coordination)+- Timeout handling++Agent-specific logic (detecting question tools, submitting answers) should+remain in each agent's own handler.+"""++from __future__ import annotations++import asyncio+import logging+from dataclasses import dataclass, field+from typing import Any, Callable, Coroutine, Dict, List, Optional++from modules.agents.base import AgentRequest++logger = logging.getLogger(__name__)+++@dataclass+class QuestionOption:+ """A single option in a question."""++ label: str+ description: str = ""+++@dataclass+class Question:+ """A single question with its options."""++ question: str+ header: str = ""+ options: List[QuestionOption] = field(default_factory=list)+ multiple: bool = False # multiSelect / multiple+++@dataclass+class PendingQuestion:+ """Common pending question state shared across agents."""++ # Question content+ questions: List[Question]+ prompt_text: str+ option_labels: List[str] # First question's option labels for simple cases++ # Session info+ base_session_id: str+ thread_id: Optional[str] = None++ # UI state+ prompt_message_id: Optional[str] = None++ # Agent-specific data (opaque to this module)+ agent_data: Dict[str, Any] = field(default_factory=dict)++ @property+ def question_count(self) -> int:+ return len(self.questions)++ @property+ def is_multiple(self) -> bool:+ """Check if any question allows multiple selection."""+ return any(q.multiple for q in self.questions)+++class QuestionUIHandler:+ """Shared question UI rendering and answer coordination.++ This class handles:+ - Rendering question prompts with buttons or modal triggers+ - Waiting for user answers via asyncio.Event+ - Timeout handling and cleanup++ Agent-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,+ im_client,+ settings_manager,+ callback_prefix: str,+ ):+ """Initialize the question UI handler.++ Args:+ controller: Main controller for emitting messages+ im_client: IM client for sending messages+ settings_manager: Settings manager for state persistence+ callback_prefix: Prefix for callback data (e.g., "opencode_question", "claude_question")+ """+ self._controller = controller+ self._im_client = im_client+ self._settings_manager = settings_manager+ self._callback_prefix = callback_prefix++ 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] = {}++ # -------------------------------------------------------------------------+ # Pending state management+ # -------------------------------------------------------------------------++ def get_pending(self, base_session_id: str) -> Optional[PendingQuestion]:+ return self._pending_questions.get(base_session_id)++ def set_pending(self, base_session_id: str, pending: PendingQuestion) -> None:+ self._pending_questions[base_session_id] = pending++ def pop_pending(self, base_session_id: str) -> Optional[PendingQuestion]:+ 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)+ 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:+ """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}")++ # -------------------------------------------------------------------------+ # Event coordination+ # -------------------------------------------------------------------------++ 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).+ 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()+ 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)++ def signal_answer_received(self, base_session_id: str) -> bool:+ """Signal that an answer has been received. Returns True if event was set."""+ evt = self._question_answer_events.get(base_session_id)+ if evt:+ evt.set()+ return True+ return False++ async def wait_for_answer(+ self,+ request: AgentRequest,+ pending: PendingQuestion,+ on_timeout: Optional[Callable[[AgentRequest, PendingQuestion], Coroutine]] = None,+ ) -> bool:+ """Wait for user to answer the question.++ Args:+ request: The agent request+ pending: Pending question state+ on_timeout: Optional callback when timeout occurs++ Returns:+ True if answer was received, False if timed out+ """+ 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++ 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+ finally:+ 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+ # -------------------------------------------------------------------------++ def build_prompt_text(self, questions: List[Question]) -> str:+ """Build formatted prompt text from questions."""+ lines: list[str] = []+ for q_idx, q in enumerate(questions):+ title = (q.header or f"Question {q_idx + 1}").strip()+ prompt = (q.question or "").strip()++ lines.append(f"**{title}**")+ if prompt:+ lines.append(prompt)++ for idx, opt in enumerate(q.options, start=1):+ label = opt.label.strip()+ desc = opt.description.strip()+ if desc:+ lines.append(f"{idx}. *{label}* - {desc}")+ else:+ lines.append(f"{idx}. *{label}*")++ if q_idx < len(questions) - 1:+ lines.append("")++ return "\n".join(lines)++ async def render_question_ui(+ self,+ request: AgentRequest,+ pending: PendingQuestion,+ ) -> Optional[str]:+ """Render question UI (buttons or modal trigger).++ Returns the message ID of the prompt message, or None if failed.+ """+ text = pending.prompt_text+ questions = pending.questions+ option_labels = pending.option_labels+ question_count = pending.question_count+ is_multiple = pending.is_multiple++ # Multi-select or multi-question or too many options: show modal button+ if is_multiple or question_count != 1 or len(option_labels) > 10:+ return await self._render_modal_trigger(request, text, pending)++ # Single question + single select + <=10 options: show inline buttons+ if (+ question_count == 1+ and not is_multiple+ and len(option_labels) <= 10+ and hasattr(self._im_client, "send_message_with_buttons")+ ):+ return await self._render_inline_buttons(request, text, option_labels)++ # 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: {err}", exc_info=True)+ return None++ async def _render_inline_buttons(+ self,+ request: AgentRequest,+ text: str,+ option_labels: List[str],+ ) -> Optional[str]:+ """Render question with inline 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"{self._callback_prefix}: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:+ message_id = await self._im_client.send_message_with_buttons(+ request.context,+ text,+ keyboard,+ parse_mode="markdown",+ )+ return message_id+ except Exception as err:+ logger.warning(+ f"Failed to send buttons, falling back to text: {err}",+ exc_info=True,+ )+ # Fallback to text-only+ await self._im_client.send_message(+ request.context, text, parse_mode="markdown"+ )+ return None++ async def _render_modal_trigger(+ self,+ request: AgentRequest,+ text: str,+ pending: PendingQuestion,+ ) -> Optional[str]:+ """Render question with modal trigger button."""+ from modules.im import InlineButton, InlineKeyboard++ modal_keyboard = InlineKeyboard(+ buttons=[[InlineButton(text="Choose…", callback_data=f"{self._callback_prefix}:open_modal")]]+ )++ try:+ message_id = await self._im_client.send_message_with_buttons(+ request.context,+ text,+ modal_keyboard,+ parse_mode="markdown",+ )+ return message_id+ except Exception as err:+ logger.warning(+ f"Failed to send modal button, falling back to text: {err}",+ exc_info=True,+ )+ # Fallback to text-only+ await self._im_client.send_message(+ request.context, text, parse_mode="markdown"+ )+ return None++ async def open_modal(+ self, request: AgentRequest, pending: PendingQuestion+ ) -> None:+ """Open the question modal."""+ trigger_id = None+ if request.context.platform_specific:+ trigger_id = request.context.platform_specific.get("trigger_id")+ if not trigger_id:+ await self._im_client.send_message(+ request.context,+ "Slack did not provide a trigger_id for the modal. Please reply with a custom message.",+ )+ return++ if 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:+ await self._im_client.open_question_modal(+ trigger_id=trigger_id,+ context=request.context,+ pending=pending,+ callback_prefix=self._callback_prefix,+ )+ except Exception as err:+ logger.error(f"Failed to open 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.",+ )++ # -------------------------------------------------------------------------+ # Answer processing helpers+ # -------------------------------------------------------------------------++ def build_selection_note(self, answers_payload: List[List[str]]) -> str:+ """Build a note showing what the user selected."""+ if not answers_payload:+ return ""++ if len(answers_payload) == 1:+ joined = ", ".join([value for value in answers_payload[0] if value])+ return f"已选择:{joined}" if joined else ""++ lines = []+ for idx, answers in enumerate(answers_payload, start=1):+ joined = ", ".join([value for value in answers if value])+ if joined:+ lines.append(f"Q{idx}: {joined}")+ if not lines:+ return ""+ return "已选择:\n" + "\n".join(lines)++ async def update_prompt_after_answer(+ self,+ request: AgentRequest,+ pending: PendingQuestion,+ answers_payload: List[List[str]],+ ) -> None:+ """Update the prompt message after answer is submitted."""+ question_message_id = pending.prompt_message_id+ if not question_message_id or not hasattr(self._im_client, "remove_inline_keyboard"):+ return++ note = self.build_selection_note(answers_payload)+ fallback_text = pending.prompt_text+ try:+ if note:+ updated_text = f"{fallback_text}\n\n{note}" if fallback_text else note+ await self._im_client.remove_inline_keyboard(+ request.context,+ question_message_id,+ text=updated_text,+ parse_mode="markdown",+ )+ else:+ 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 update question message: {err}")++ async def add_answer_reaction(+ self,+ request: AgentRequest,+ pending: PendingQuestion,+ ) -> None:+ """Add 👀 reaction to question message to indicate answer received."""+ question_message_id = pending.prompt_message_id+ if not question_message_id or not hasattr(self._im_client, "add_reaction"):+ return++ 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}")diff --git a/modules/im/slack.py b/modules/im/slack.pyindex 8c7ed9043..3285d33a8 100644--- a/modules/im/slack.py+++ b/modules/im/slack.py@@ -884,7 +884,8 @@ class SlackBot(BaseIMClient):# We need to find the right channel to send the message# For now, we'll rely on the controller to handle this- elif callback_id == "opencode_question_modal":+ elif callback_id == "opencode_question_modal" or callback_id == "claude_question_modal":+ # Generic question modal handling for both OpenCode and Claudeuser_id = payload.get("user", {}).get("id")values = view.get("state", {}).get("values", {})metadata_raw = view.get("private_metadata")@@ -898,6 +899,10 @@ class SlackBot(BaseIMClient):channel_id = metadata.get("channel_id")thread_id = metadata.get("thread_id")+ # Get callback_prefix from metadata, fallback to deriving from callback_id+ callback_prefix = metadata.get("callback_prefix")+ if not callback_prefix:+ callback_prefix = callback_id.replace("_modal", "")answers = []q_count = int(metadata.get("question_count") or 1)@@ -922,9 +927,10 @@ class SlackBot(BaseIMClient):thread_id=str(thread_id) if thread_id else None,platform_specific={"payload": payload},)+ # Use callback_prefix to route to correct agentawait self.on_callback_query_callback(context,- "opencode_question:modal:" + json.dumps({"answers": answers}),+ f"{callback_prefix}:modal:" + json.dumps({"answers": answers}),)elif callback_id == "routing_modal":@@ -1962,6 +1968,149 @@ class SlackBot(BaseIMClient):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",+ ):+ """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.++ Args:+ trigger_id: Slack trigger ID for opening the modal+ context: Message context+ pending: PendingQuestion instance with questions data+ callback_prefix: Prefix for callback routing (e.g., "opencode_question", "claude_question")+ """+ self._ensure_clients()++ # Support both PendingQuestion dataclass and dict format+ if hasattr(pending, "questions"):+ questions = pending.questions+ else:+ questions = pending.get("questions") if isinstance(pending, dict) 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),+ "callback_prefix": callback_prefix,+ }+ )++ blocks: list[Dict[str, Any]] = []+ for idx, q in enumerate(questions):+ # Support both Question dataclass and dict format+ if hasattr(q, "header"):+ header = (q.header or f"Question {idx + 1}").strip()+ prompt = (q.question or "").strip()+ multiple = bool(q.multiple)+ options = q.options+ elif isinstance(q, dict):+ header = (q.get("header") or f"Question {idx + 1}").strip()+ prompt = (q.get("question") or "").strip()+ multiple = bool(q.get("multiple") or q.get("multiSelect"))+ options = q.get("options") if isinstance(q.get("options"), list) else []+ else:+ continue++ option_items = []+ for opt in options:+ # Support both QuestionOption dataclass and dict format+ if hasattr(opt, "label"):+ label = opt.label+ desc = opt.description+ elif isinstance(opt, dict):+ label = opt.get("label")+ desc = opt.get("description")+ else:+ continue++ if label is None:+ continue+ 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": "Select one or more",+ "emoji": True,+ },+ }+ else:+ element = {+ "type": "static_select",+ "action_id": "select",+ "options": option_items,+ "placeholder": {+ "type": "plain_text",+ "text": "Select one",+ "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,+ }+ )++ # Use callback_prefix to generate callback_id+ callback_id = f"{callback_prefix}_modal"+ title = "Claude Code" if callback_prefix.startswith("claude") else "OpenCode"++ view = {+ "type": "modal",+ "callback_id": callback_id,+ "private_metadata": private_metadata,+ "title": {"type": "plain_text", "text": title, "emoji": True},+ "submit": {"type": "plain_text", "text": "Submit", "emoji": True},+ "close": {"type": "plain_text", "text": "Cancel", "emoji": True},+ "blocks": blocks,+ }++ await self.web_client.views_open(trigger_id=trigger_id, view=view)+async def open_routing_modal(self,trigger_id: str,