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): persist ack reaction info for poll restoration

yh c10d6b7c1f350
diff --git a/config/v2_sessions.py b/config/v2_sessions.py
index b3dcb0176..aade5eb68 100644
--- a/config/v2_sessions.py
+++ b/config/v2_sessions.py
@@ -12,6 +12,7 @@ logger = logging.getLogger(__name__)
@dataclass
class ActivePollInfo:
"""Information about an active poll that needs to be restored on restart."""
+
opencode_session_id: str
base_session_id: str
channel_id: str
@@ -22,6 +23,9 @@ class ActivePollInfo:
seen_tool_calls: List[str] = field(default_factory=list)
emitted_assistant_messages: List[str] = field(default_factory=list)
started_at: float = 0.0
+ # Ack reaction info for cleanup on restore
+ ack_reaction_message_id: Optional[str] = None
+ ack_reaction_emoji: Optional[str] = None
def to_dict(self) -> Dict[str, Any]:
return {
@@ -35,6 +39,8 @@ class ActivePollInfo:
"seen_tool_calls": self.seen_tool_calls,
"emitted_assistant_messages": self.emitted_assistant_messages,
"started_at": self.started_at,
+ "ack_reaction_message_id": self.ack_reaction_message_id,
+ "ack_reaction_emoji": self.ack_reaction_emoji,
}
@classmethod
@@ -50,15 +56,15 @@ class ActivePollInfo:
seen_tool_calls=data.get("seen_tool_calls", []),
emitted_assistant_messages=data.get("emitted_assistant_messages", []),
started_at=data.get("started_at", 0.0),
+ ack_reaction_message_id=data.get("ack_reaction_message_id"),
+ ack_reaction_emoji=data.get("ack_reaction_emoji"),
)
@dataclass
class SessionState:
# session_mappings: user_id -> agent_name -> thread_id -> session_id
- session_mappings: Dict[str, Dict[str, Dict[str, str]]] = field(
- default_factory=dict
- )
+ session_mappings: Dict[str, Dict[str, Dict[str, str]]] = field(default_factory=dict)
active_slack_threads: Dict[str, Dict[str, Dict[str, float]]] = field(
default_factory=dict
)
@@ -113,14 +119,18 @@ class SessionsStore:
self.state.active_slack_threads[user_id][channel_id] = channel_map
return channel_map
- def get_last_processed_message_ts(self, channel_id: str, thread_ts: str) -> Optional[str]:
+ def get_last_processed_message_ts(
+ self, channel_id: str, thread_ts: str
+ ) -> Optional[str]:
"""Get the last processed message ts for a thread."""
channel_map = self.state.processed_message_ts.get(channel_id)
if channel_map:
return channel_map.get(thread_ts)
return None
- def set_last_processed_message_ts(self, channel_id: str, thread_ts: str, message_ts: str) -> None:
+ def set_last_processed_message_ts(
+ self, channel_id: str, thread_ts: str, message_ts: str
+ ) -> None:
"""Set the last processed message ts for a thread."""
if channel_id not in self.state.processed_message_ts:
self.state.processed_message_ts[channel_id] = {}
diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.py
index c586ae5bc..e6daf7ec2 100644
--- a/modules/agents/opencode/agent.py
+++ b/modules/agents/opencode/agent.py
@@ -266,6 +266,8 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
settings_key=request.settings_key,
working_path=request.working_path,
baseline_message_ids=list(baseline_message_ids),
+ ack_reaction_message_id=request.ack_reaction_message_id,
+ ack_reaction_emoji=request.ack_reaction_emoji,
)
final_text, should_emit = await self._poll_loop.run_prompt_poll(
diff --git a/modules/agents/opencode/poll_loop.py b/modules/agents/opencode/poll_loop.py
index 8c93af8a7..e6c33d59f 100644
--- a/modules/agents/opencode/poll_loop.py
+++ b/modules/agents/opencode/poll_loop.py
@@ -96,16 +96,21 @@ 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"
+ ):
+ 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
@@ -238,6 +243,18 @@ class OpenCodePollLoop:
thread_id=poll_info.thread_id,
)
+ async def _remove_ack_reaction() -> None:
+ """Remove ack reaction from the original message."""
+ if poll_info.ack_reaction_message_id and poll_info.ack_reaction_emoji:
+ try:
+ await self._agent.im_client.remove_reaction(
+ channel_id=poll_info.channel_id,
+ message_ts=poll_info.ack_reaction_message_id,
+ emoji=poll_info.ack_reaction_emoji,
+ )
+ except Exception as e:
+ logger.debug(f"Failed to remove ack reaction: {e}")
+
await self._agent.controller.emit_agent_message(
context,
"notify",
@@ -306,12 +323,16 @@ 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,
)
self._agent.settings_manager.remove_active_poll(session_id)
+ await _remove_ack_reaction()
await self._agent.controller.emit_agent_message(
context,
"notify",
@@ -338,14 +359,18 @@ 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", ""
)
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
@@ -370,13 +395,18 @@ 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)
@@ -397,6 +427,8 @@ class OpenCodePollLoop:
started_at=started_at,
)
+ # Clean up ack reaction after result is sent
+ await _remove_ack_reaction()
# Clean up answer reaction after result is sent
await self._question_handler.clear(poll_info.base_session_id)
self._agent.settings_manager.remove_active_poll(session_id)
@@ -405,13 +437,16 @@ class OpenCodePollLoop:
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)
raise
except Exception as e:
error_name = type(e).__name__
error_details = str(e).strip()
- error_text = f"{error_name}: {error_details}" if error_details else error_name
+ 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:
@@ -422,6 +457,7 @@ class OpenCodePollLoop:
)
self._agent.settings_manager.remove_active_poll(session_id)
+ await _remove_ack_reaction()
await self._agent.controller.emit_agent_message(
context,
diff --git a/modules/settings_manager.py b/modules/settings_manager.py
index 76cf39894..fbd3ff8eb 100644
--- a/modules/settings_manager.py
+++ b/modules/settings_manager.py
@@ -24,7 +24,9 @@ class ChannelRouting:
agent_backend: Optional[str] = None # "claude" | "codex" | "opencode" | None
opencode_agent: Optional[str] = None # "build" | "plan" | ... | None
opencode_model: Optional[str] = None # "provider/model" | None
- opencode_reasoning_effort: Optional[str] = None # "low" | "medium" | "high" | "xhigh" | None
+ opencode_reasoning_effort: Optional[str] = (
+ None # "low" | "medium" | "high" | "xhigh" | None
+ )
def to_dict(self) -> dict:
"""Convert to dictionary for JSON serialization"""
@@ -93,7 +95,9 @@ class SettingsManager:
def __init__(self, settings_file: Optional[str] = None):
paths.ensure_data_dirs()
- self.settings_file = Path(settings_file) if settings_file else paths.get_settings_path()
+ self.settings_file = (
+ Path(settings_file) if settings_file else paths.get_settings_path()
+ )
self._settings_mtime_ns: Optional[int] = None
self._settings_fingerprint: Optional[str] = None
self.settings: Dict[Union[int, str], UserSettings] = {}
@@ -155,7 +159,9 @@ class SettingsManager:
return
for channel_id, channel_settings in self.store.settings.channels.items():
- self.settings[str(channel_id)] = self._from_channel_settings(channel_settings)
+ self.settings[str(channel_id)] = self._from_channel_settings(
+ channel_settings
+ )
try:
self._settings_mtime_ns = self.settings_file.stat().st_mtime_ns
@@ -166,7 +172,6 @@ class SettingsManager:
logger.info(f"Loaded settings for {len(self.settings)} channels")
-
def _compute_settings_fingerprint(self) -> Optional[str]:
try:
data = self.settings_file.read_bytes()
@@ -273,7 +278,9 @@ class SettingsManager:
settings = self.get_user_settings(user_id)
return settings.custom_cwd
- def get_channel_settings(self, channel_id: Union[int, str]) -> Optional[ChannelSettings]:
+ def get_channel_settings(
+ self, channel_id: Union[int, str]
+ ) -> Optional[ChannelSettings]:
"""Get raw ChannelSettings for a channel without creating defaults."""
self._reload_if_changed()
key = str(channel_id)
@@ -304,7 +311,9 @@ class SettingsManager:
"toolcall": "Toolcall",
}
- def _ensure_agent_namespace(self, user_id: Union[int, str], agent_name: str) -> Dict[str, str]:
+ def _ensure_agent_namespace(
+ self, user_id: Union[int, str], agent_name: str
+ ) -> Dict[str, str]:
user_key = self._normalize_user_id(user_id)
return self.sessions_store.get_agent_map(user_key, agent_name)
@@ -339,7 +348,9 @@ class SettingsManager:
"""Normalize message type to canonical form to support aliases."""
return self.MESSAGE_TYPE_ALIASES.get(message_type, message_type)
- def _normalize_show_message_types(self, show_message_types: Optional[List[str]]) -> List[str]:
+ def _normalize_show_message_types(
+ self, show_message_types: Optional[List[str]]
+ ) -> List[str]:
"""Normalize and migrate show message types to current canonical schema."""
allowed = {"system", "assistant", "toolcall"}
if show_message_types is None:
@@ -412,25 +423,19 @@ class SettingsManager:
thread_id: str,
claude_session_id: str,
):
- self.set_agent_session_mapping(
- user_id, "claude", thread_id, claude_session_id
- )
+ self.set_agent_session_mapping(user_id, "claude", thread_id, claude_session_id)
def get_claude_session_id(
self, user_id: Union[int, str], thread_id: str
) -> Optional[str]:
- return self.get_agent_session_id(
- user_id, thread_id, agent_name="claude"
- )
+ return self.get_agent_session_id(user_id, thread_id, agent_name="claude")
def clear_session_mapping(
self,
user_id: Union[int, str],
thread_id: str,
):
- self.clear_agent_session_mapping(
- user_id, "claude", thread_id
- )
+ self.clear_agent_session_mapping(user_id, "claude", thread_id)
# ---------------------------------------------
# Slack thread management
@@ -483,7 +488,9 @@ class SettingsManager:
del channel_map[thread_ts]
if not channel_map:
- self.sessions_store.state.active_slack_threads[user_key].pop(channel_id, None)
+ self.sessions_store.state.active_slack_threads[user_key].pop(
+ channel_id, None
+ )
self.sessions_store.save()
logger.info(
@@ -509,11 +516,13 @@ class SettingsManager:
self, channel_id: str, thread_ts: str, message_ts: str
) -> bool:
"""Check if a message has already been processed.
-
+
Compares the message_ts with the last processed message ts for the thread.
Returns True if message_ts <= last_processed_ts (i.e., already processed).
"""
- last_ts = self.sessions_store.get_last_processed_message_ts(channel_id, thread_ts)
+ last_ts = self.sessions_store.get_last_processed_message_ts(
+ channel_id, thread_ts
+ )
if not last_ts:
return False
# Slack ts format is "epoch.sequence", can be compared as strings
@@ -523,7 +532,9 @@ class SettingsManager:
self, channel_id: str, thread_ts: str, message_ts: str
) -> None:
"""Record that a message has been processed."""
- self.sessions_store.set_last_processed_message_ts(channel_id, thread_ts, message_ts)
+ self.sessions_store.set_last_processed_message_ts(
+ channel_id, thread_ts, message_ts
+ )
logger.debug(
f"Recorded processed message: channel={channel_id}, thread={thread_ts}, message={message_ts}"
)
@@ -581,14 +592,15 @@ class SettingsManager:
key = str(channel_id)
channel_settings = self.store.settings.channels.get(key)
- if channel_settings is not None and channel_settings.require_mention is not None:
+ if (
+ channel_settings is not None
+ and channel_settings.require_mention is not None
+ ):
return channel_settings.require_mention
return global_default
- def set_require_mention(
- self, channel_id: Union[int, str], value: Optional[bool]
- ):
+ def set_require_mention(self, channel_id: Union[int, str], value: Optional[bool]):
"""Set per-channel require_mention override.
Args:
@@ -624,6 +636,8 @@ class SettingsManager:
settings_key: str,
working_path: str,
baseline_message_ids: List[str],
+ ack_reaction_message_id: Optional[str] = None,
+ ack_reaction_emoji: Optional[str] = None,
) -> None:
"""Record an active poll for potential restoration on restart."""
from config.v2_sessions import ActivePollInfo
@@ -639,6 +653,8 @@ class SettingsManager:
seen_tool_calls=[],
emitted_assistant_messages=[],
started_at=time.time(),
+ ack_reaction_message_id=ack_reaction_message_id,
+ ack_reaction_emoji=ack_reaction_emoji,
)
self.sessions_store.add_active_poll(poll_info)
logger.debug(