Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(opencode): prevent cross-session question_id mismatch and improve Feishu UX

cyhhao56b84a277b0c
diff --git a/core/handlers/command_handlers.py b/core/handlers/command_handlers.py
index f091bfa40..83c14fbad 100644
--- a/core/handlers/command_handlers.py
+++ b/core/handlers/command_handlers.py
@@ -353,31 +353,15 @@ class CommandHandlers:
if self.config.platform == "lark":
settings_key = self.controller._get_settings_key(context)
sessions_by_agent = self.settings_manager.list_all_agent_sessions(settings_key)
- if not sessions_by_agent:
- channel_context = self._get_channel_context(context)
- await self.im_client.send_message(
- channel_context,
- f"ℹ️ {self._t('command.resume.noStoredSessions')}",
- )
- return
- # Flatten sessions_by_agent dict into a list for Feishu card
- # list_all_agent_sessions returns {agent: {thread_id: session_id}}
- flat_sessions = []
- for agent_name, agent_sessions in sessions_by_agent.items():
- for thread_id, session_id in agent_sessions.items():
- flat_sessions.append(
- {
- "id": session_id,
- "agent": agent_name,
- "label": f"[{agent_name}] {session_id[:12]}",
- }
- )
+ # Allow opening modal even with no sessions (user can paste manually)
if hasattr(self.im_client, "open_resume_session_modal"):
try:
await self.im_client.open_resume_session_modal(
trigger_id=context,
- sessions=flat_sessions,
+ sessions_by_agent=sessions_by_agent or {},
channel_id=context.channel_id,
+ thread_id=context.thread_id or context.message_id or "",
+ host_message_ts=context.message_id,
)
return
except Exception as e:
diff --git a/modules/agents/opencode/poll_loop.py b/modules/agents/opencode/poll_loop.py
index ff5a630aa..0fac5b770 100644
--- a/modules/agents/opencode/poll_loop.py
+++ b/modules/agents/opencode/poll_loop.py
@@ -96,21 +96,33 @@ class OpenCodePollLoop:
tool_state = part.get("state") or {}
tool_input = tool_state.get("input") or {}
- if (
- tool_name == "question"
- and tool_state.get("status") != "completed"
- ):
- 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 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
@@ -150,9 +162,7 @@ class OpenCodePollLoop:
emitted_assistant_messages.add(message_id)
if restart_poll:
- logger.info(
- "Restarting poll loop for %s after question answer", session_id
- )
+ logger.info("Restarting poll loop for %s after question answer", session_id)
continue
if messages:
@@ -171,11 +181,7 @@ class OpenCodePollLoop:
last_error_message_id = last_id
error_name = msg_error.get("name", "UnknownError")
error_data = msg_error.get("data", {})
- error_msg = (
- error_data.get("message", "")
- if isinstance(error_data, dict)
- else str(error_data)
- )
+ error_msg = error_data.get("message", "") if isinstance(error_data, dict) else str(error_data)
logger.warning(
"OpenCode message error detected for %s: %s - %s (retry %d/%d)",
@@ -299,9 +305,7 @@ class OpenCodePollLoop:
bool(last_info.get("error")),
)
except Exception as poll_err:
- logger.warning(
- f"Failed to poll OpenCode messages (restored): {poll_err}"
- )
+ logger.warning(f"Failed to poll OpenCode messages (restored): {poll_err}")
await asyncio.sleep(poll_interval_seconds)
continue
@@ -323,10 +327,7 @@ class OpenCodePollLoop:
tool_state = part.get("state") or {}
tool_input = tool_state.get("input") or {}
- if (
- tool_name == "question"
- and tool_state.get("status") != "completed"
- ):
+ if tool_name == "question" and tool_state.get("status") != "completed":
logger.info(
"Detected question in restored poll for %s, exiting poll loop",
session_id,
@@ -359,22 +360,14 @@ class OpenCodePollLoop:
if tool_name == "bash":
cmd = tool_input.get("command", "")
if cmd:
- cmd_preview = (
- cmd[:50] + "..." if len(cmd) > 50 else cmd
- )
+ cmd_preview = cmd[:50] + "..." if len(cmd) > 50 else cmd
tool_summary = f"`bash`: `{cmd_preview}`"
elif tool_name in ("read", "write", "edit"):
- path = tool_input.get("file_path") or tool_input.get(
- "path", ""
- )
+ path = tool_input.get("file_path") or tool_input.get("path", "")
if path:
- tool_summary = (
- f"`{tool_name}`: `{_relative_path(path)}`"
- )
+ tool_summary = f"`{tool_name}`: `{_relative_path(path)}`"
- await self._agent.controller.emit_agent_message(
- context, "tool_call", tool_summary
- )
+ await self._agent.controller.emit_agent_message(context, "tool_call", tool_summary)
if messages:
last_message = messages[-1]
@@ -395,18 +388,14 @@ class OpenCodePollLoop:
"notify",
f"OpenCode error: {error_text}",
)
- self._agent.settings_manager.remove_active_poll(
- session_id
- )
+ self._agent.settings_manager.remove_active_poll(session_id)
await _remove_ack_reaction()
return
if last_info.get("finish") != "tool-calls":
if not msg_error:
error_retry_count = 0
- final_text = self._agent._extract_response_text(
- last_message
- )
+ final_text = self._agent._extract_response_text(last_message)
break
await asyncio.sleep(poll_interval_seconds)
@@ -434,9 +423,7 @@ class OpenCodePollLoop:
self._agent.settings_manager.remove_active_poll(session_id)
except asyncio.CancelledError:
- logger.info(
- f"Restored OpenCode poll cancelled for {poll_info.base_session_id}"
- )
+ logger.info(f"Restored OpenCode poll cancelled for {poll_info.base_session_id}")
await _remove_ack_reaction()
await self._question_handler.clear(poll_info.base_session_id)
self._agent.settings_manager.remove_active_poll(session_id)
@@ -444,17 +431,13 @@ class OpenCodePollLoop:
except Exception as e:
error_name = type(e).__name__
error_details = str(e).strip()
- error_text = (
- f"{error_name}: {error_details}" if error_details else error_name
- )
+ error_text = f"{error_name}: {error_details}" if error_details else error_name
logger.error(f"Restored OpenCode poll failed: {error_text}", exc_info=True)
try:
await server.abort_session(session_id, poll_info.working_path)
except Exception as abort_err:
- logger.warning(
- f"Failed to abort OpenCode session after error: {abort_err}"
- )
+ logger.warning(f"Failed to abort OpenCode session after error: {abort_err}")
self._agent.settings_manager.remove_active_poll(session_id)
await _remove_ack_reaction()
diff --git a/modules/agents/opencode/question_handler.py b/modules/agents/opencode/question_handler.py
index ea5796833..1eb9c0d28 100644
--- a/modules/agents/opencode/question_handler.py
+++ b/modules/agents/opencode/question_handler.py
@@ -550,23 +550,60 @@ class OpenCodeQuestionHandler:
if matched_item is None and session_items:
matched_item = session_items[0]
+ logger.warning(
+ "Question match for session %s: no callID/messageID match, "
+ "falling back to first item in same session (id=%s, callID=%s)",
+ opencode_session_id,
+ matched_item.get("id"),
+ (matched_item.get("tool") or {}).get("callID"),
+ )
+ # 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"):
- for item in questions_listing:
- tool_meta = item.get("tool") or {}
- if tool_meta.get("callID") == tool_part.get("callID"):
- matched_item = item
- break
+ 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),
+ )
- if matched_item is None and message_id:
- for item in questions_listing:
- tool_meta = item.get("tool") or {}
- if tool_meta.get("messageID") == message_id:
- matched_item = item
- break
+ # 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.
- if matched_item is None and len(questions_listing) == 1:
- matched_item = questions_listing[0]
+ # 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")
diff --git a/modules/im/feishu.py b/modules/im/feishu.py
index fa4446fbd..bb29f01d0 100644
--- a/modules/im/feishu.py
+++ b/modules/im/feishu.py
@@ -1188,6 +1188,8 @@ class FeishuBot(BaseIMClient):
await self._handle_routing_backend_select(context, form_value)
elif button_name == "routing_submit":
await self._handle_routing_form_submit(context, form_value)
+ elif button_name.startswith("resume_submit"):
+ await self._handle_resume_form_submit(context, form_value, button_name)
elif button_name.startswith("question_submit"):
await self._handle_question_form_submit(context, form_value, button_name)
else:
@@ -1401,6 +1403,116 @@ class FeishuBot(BaseIMClient):
if self.on_callback_query_callback:
await self.on_callback_query_callback(context, callback_data)
+ # ------------------------------------------------------------------
+ # Resume session form submission handler
+ # ------------------------------------------------------------------
+ async def _handle_resume_form_submit(self, context: MessageContext, form_value: Dict[str, Any], button_name: str):
+ """Handle resume session form submission.
+
+ Extracts the selected or manually entered session ID and agent,
+ then delegates to ``_on_resume_session`` (same as Slack/Discord).
+
+ Button name encodes metadata as ``resume_submit:{thread_id}:{host_message_ts}``.
+ """
+ # Parse metadata from button name
+ parts = button_name.split(":")
+ embedded_thread_id = parts[1] if len(parts) > 1 and parts[1] else None
+ host_message_ts = parts[2] if len(parts) > 2 and parts[2] else None
+
+ # Restore thread_id on context if available from embedded metadata
+ if embedded_thread_id and not context.thread_id:
+ context = MessageContext(
+ user_id=context.user_id,
+ channel_id=context.channel_id,
+ message_id=context.message_id,
+ thread_id=embedded_thread_id,
+ platform_specific=context.platform_specific,
+ )
+
+ # Extract form values
+ session_select = form_value.get("session_select", "") # "agent|session_id"
+ manual_session_id = (form_value.get("manual_session_id") or "").strip()
+ agent_select = form_value.get("agent_select", "")
+
+ chosen_agent = None
+ chosen_session = None
+
+ # Manual input takes precedence (same logic as Slack/Discord)
+ if manual_session_id:
+ chosen_session = manual_session_id
+ chosen_agent = agent_select or "opencode"
+ elif session_select and "|" in session_select:
+ chosen_agent, chosen_session = session_select.split("|", 1)
+ elif session_select:
+ # No pipe — treat as session_id with agent from selector
+ chosen_session = session_select
+ chosen_agent = agent_select or "opencode"
+
+ logger.info(
+ "Resume form submitted: agent=%s, session=%s, manual=%s, select=%s",
+ chosen_agent,
+ chosen_session,
+ manual_session_id,
+ session_select,
+ )
+
+ if not chosen_session:
+ # Nothing selected or entered — send hint
+ t = lambda key, **kw: self._t(key, context.channel_id, **kw)
+ await self.send_message(context, f"⚠️ {t('modal.resume.description')}")
+ return
+
+ # Replace the form card with a confirmation
+ if context.message_id:
+ agent_label = (chosen_agent or "").capitalize()
+ done_card = json.dumps(
+ {
+ "schema": "2.0",
+ "header": {
+ "title": {
+ "tag": "plain_text",
+ "content": "✅ " + self._t("common.submitted", context.channel_id),
+ },
+ "template": "green",
+ },
+ "body": {
+ "direction": "vertical",
+ "elements": [
+ {
+ "tag": "markdown",
+ "content": f"Agent: **{agent_label}**\nSession: `{chosen_session[:60]}`",
+ }
+ ],
+ },
+ },
+ ensure_ascii=False,
+ )
+ try:
+ from lark_oapi.api.im.v1 import PatchMessageRequest, PatchMessageRequestBody
+
+ req = (
+ PatchMessageRequest.builder()
+ .message_id(context.message_id)
+ .request_body(PatchMessageRequestBody.builder().content(done_card).build())
+ .build()
+ )
+ resp = await self._lark_client.im.v1.message.apatch(req)
+ if not resp.success():
+ logger.warning("Failed to update resume card after submit: %s", resp.msg)
+ except Exception as exc:
+ logger.warning("Could not update resume card: %s", exc)
+
+ # Delegate to the resume session callback (same as Slack/Discord)
+ if hasattr(self, "_on_resume_session") and self._on_resume_session:
+ await self._on_resume_session(
+ context.user_id,
+ context.channel_id,
+ context.thread_id,
+ chosen_agent,
+ chosen_session,
+ host_message_ts,
+ )
+
# ------------------------------------------------------------------
# Modal-equivalent: interactive cards sent as messages
# ------------------------------------------------------------------
@@ -1926,36 +2038,129 @@ class FeishuBot(BaseIMClient):
async def open_resume_session_modal(
self,
trigger_id: Any,
- sessions: list = None,
+ sessions_by_agent: Dict[str, Dict[str, str]] = None,
channel_id: str = None,
+ thread_id: str = None,
+ host_message_ts: str = None,
+ # Legacy compat — ignored; use sessions_by_agent instead
+ sessions: list = None,
**kwargs,
):
- """Send an interactive card (v2) for session resume selection."""
- t = lambda key, **kw: self._t(key, channel_id, **kw)
+ """Send an interactive JSON 2.0 form card for session resume.
- elements = [
- {"tag": "markdown", "content": f"**{t('modal.resume.title')}**"},
- ]
+ Aligned with Slack/Discord: session selector dropdown (grouped by agent),
+ manual session ID text input, agent backend selector, and a submit button.
+ """
+ t = lambda key, **kw: self._t(key, channel_id, **kw)
- if sessions:
- for session in sessions[:10]: # Limit to 10 sessions
- session_id = session.get("id", "")
- agent = session.get("agent", "opencode")
- label = session.get("label", session_id[:8])
- # Encode agent|session_id so the callback handler can extract both
- elements.append(
+ if sessions_by_agent is None:
+ sessions_by_agent = {}
+
+ # --- Build agent options (from registered backends or fallback) ---
+ common_agents = ["claude", "codex", "opencode"]
+ registered_backends = None
+ if getattr(self, "_controller", None) and getattr(self._controller, "agent_service", None):
+ registered_backends = list(self._controller.agent_service.agents.keys())
+ allowed_agents = set(registered_backends) if registered_backends else set(common_agents)
+ agent_options = []
+ for agent in sorted(allowed_agents):
+ agent_options.append({"text": {"tag": "plain_text", "content": agent.capitalize()}, "value": agent})
+
+ # --- Build session options for select_static ---
+ session_options = []
+ total = 0
+ max_options = 100
+ for agent_name, mapping in sessions_by_agent.items():
+ if agent_name not in allowed_agents:
+ continue
+ if not mapping:
+ continue
+ for thread_key, session_id in mapping.items():
+ if total >= max_options:
+ break
+ thread_label = thread_key.replace("lark_", "", 1) if thread_key.startswith("lark_") else thread_key
+ label = f"[{agent_name}] {session_id[:24]}"
+ desc = f"thread {thread_label[:30]}"
+ session_options.append(
{
- "tag": "button",
"text": {"tag": "plain_text", "content": label},
- "type": "default",
- "width": "fill",
- "behaviors": [
- {"type": "callback", "value": {"key": f"resume_session:{agent}:{session_id}"}},
- ],
+ "value": f"{agent_name}|{session_id}",
}
)
+ total += 1
+ if total >= max_options:
+ break
+
+ # --- Build form elements ---
+ form_elements: list = []
+
+ # Description
+ form_elements.append({"tag": "markdown", "content": t("modal.resume.description")})
+
+ # 1) Session selector (optional — only if sessions exist)
+ if session_options:
+ form_elements.append({"tag": "markdown", "content": f"**{t('modal.resume.pickExisting')}**"})
+ form_elements.append(
+ {
+ "tag": "select_static",
+ "name": "session_select",
+ "placeholder": {"tag": "plain_text", "content": t("modal.resume.selectSession")},
+ "options": session_options,
+ }
+ )
+ if total >= max_options:
+ form_elements.append({"tag": "markdown", "content": f"_{t('modal.resume.showingFirst100')}_"})
+ else:
+ form_elements.append({"tag": "markdown", "content": f"_{t('modal.resume.noSessionsFound')}_"})
+
+ # Divider
+ form_elements.append({"tag": "column_set", "flex_mode": "none", "columns": []})
+
+ # 2) Manual session ID input
+ form_elements.append({"tag": "markdown", "content": f"**{t('modal.resume.pasteId')}**"})
+ form_elements.append(
+ {
+ "tag": "input",
+ "name": "manual_session_id",
+ "placeholder": {"tag": "plain_text", "content": t("modal.resume.pasteIdPlaceholder")},
+ "label": {"tag": "plain_text", "content": " "},
+ }
+ )
+
+ # 3) Agent backend selector (always shown — needed when using manual input)
+ form_elements.append({"tag": "markdown", "content": f"**{t('modal.resume.agentBackend')}**"})
+ if agent_options:
+ form_elements.append(
+ {
+ "tag": "select_static",
+ "name": "agent_select",
+ "placeholder": {"tag": "plain_text", "content": t("modal.resume.selectAgentBackend")},
+ "options": agent_options,
+ "value": {"value": agent_options[0]["value"]} if agent_options else None,
+ }
+ )
else:
- elements.append({"tag": "markdown", "content": f"_{t('command.resume.noStoredSessions')}_"})
+ form_elements.append({"tag": "markdown", "content": "_No agent backends available_"})
+
+ # Submit button — encode thread context in name field
+ # (form_value loses behaviors.value, so we encode metadata in button name)
+ meta_parts = [
+ "resume_submit",
+ thread_id or "",
+ host_message_ts or "",
+ ]
+ submit_button_name = ":".join(meta_parts)
+
+ form_elements.append(
+ {
+ "tag": "button",
+ "text": {"tag": "plain_text", "content": t("common.resume")},
+ "type": "primary",
+ "width": "fill",
+ "action_type": "form_submit",
+ "name": submit_button_name,
+ }
+ )
card = {
"schema": "2.0",
@@ -1965,7 +2170,13 @@ class FeishuBot(BaseIMClient):
},
"body": {
"direction": "vertical",
- "elements": elements,
+ "elements": [
+ {
+ "tag": "form",
+ "name": "resume_form",
+ "elements": form_elements,
+ },
+ ],
},
}
ctx = MessageContext(user_id="system", channel_id=channel_id or "")
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 1eb7734b7..5299271f9 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -291,9 +291,9 @@
"searchModel": "搜索模型...",
"settingsSaved": "设置已保存",
"settingsSaveFailed": "保存设置失败",
- "requireMention": "需要 @提及",
- "requireMentionOn": "需要 @提及",
- "requireMentionOff": "不需要 @提及",
+ "requireMention": "需要 @",
+ "requireMentionOn": "需要 @",
+ "requireMentionOff": "不需要 @",
"mentionStatusOn": "需要 @",
"mentionStatusOff": "不需要 @"
},
@@ -309,8 +309,8 @@
"notSet": "未设置",
"enabledAgents": "已启用的 Agent",
"channelsConfigured": "已配置的频道",
- "requireMention": "需要 @提及",
- "requireMentionHint": "机器人仅在被 @提及时响应",
+ "requireMention": "需要 @",
+ "requireMentionHint": "机器人仅在被 @ 时响应",
"autoUpdate": "自动更新",
"autoUpdateHint": "系统空闲时自动安装更新",
"usageTips": "快速上手",
@@ -337,8 +337,8 @@
"defaultBackend": "默认后端",
"slackWorkspace": "Slack 工作区",
"messageHandling": "消息处理",
- "requireMention": "需要 @提及",
- "requireMentionHint": "机器人仅在被 @提及时响应",
+ "requireMention": "需要 @",
+ "requireMentionHint": "机器人仅在被 @ 时响应",
"ackMode": "确认模式",
"ackModeHint": "机器人如何确认收到的消息",
"ackReaction": "👀 表情回应",