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.

feat(slack): add resume session picker

Wang Siyuanecf5f0ff3831
diff --git a/core/controller.py b/core/controller.py
index 6def865d9..fbf229936 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -144,6 +144,7 @@ class Controller:
on_change_cwd=self.handle_change_cwd_submission,
on_routing_update=self.handle_routing_update,
on_routing_modal_update=self.handle_routing_modal_update,
+ on_resume_session=self.handle_resume_session_submission,
on_ready=self._on_im_ready,
)
@@ -616,6 +617,61 @@ class Controller:
context, f"❌ Failed to change working directory: {str(e)}"
)
+ async def handle_resume_session_submission(
+ self,
+ user_id: str,
+ channel_id: Optional[str],
+ thread_id: Optional[str],
+ agent: Optional[str],
+ session_id: Optional[str],
+ ) -> None:
+ """Bind a provided session_id to the current thread for the chosen agent."""
+ try:
+ if not agent or not session_id:
+ raise ValueError("Agent and session ID are required to resume.")
+
+ target_thread = (
+ thread_id
+ or (channel_id if channel_id and channel_id.startswith("D") else None)
+ )
+ # Build context for replies (use thread_id if provided)
+ context = MessageContext(
+ user_id=user_id,
+ channel_id=channel_id or user_id,
+ thread_id=target_thread or None,
+ platform_specific={},
+ )
+
+ settings_key = self._get_settings_key(context)
+ base_session_id = f"slack_{target_thread or context.channel_id}"
+
+ # Persist mapping
+ self.settings_manager.set_agent_session_mapping(
+ settings_key, agent, base_session_id, session_id
+ )
+ # Mark thread active for visibility/cleanup semantics
+ if target_thread:
+ self.settings_manager.mark_thread_active(user_id, context.channel_id, target_thread)
+
+ agent_label = agent.capitalize()
+ confirmation = (
+ f"✅ Resumed {agent_label} session.\n"
+ f"Session ID: `{session_id}`\n"
+ "You can now continue the conversation in this thread."
+ )
+ await self.im_client.send_message(context, confirmation)
+ except Exception as e:
+ logger.error(f"Error resuming session: {e}", exc_info=True)
+ context = MessageContext(
+ user_id=user_id,
+ channel_id=channel_id or user_id,
+ thread_id=thread_id or None,
+ platform_specific={},
+ )
+ await self.im_client.send_message(
+ context, f"❌ Failed to resume session: {str(e)}"
+ )
+
async def handle_routing_modal_update(
self,
user_id: str,
diff --git a/core/handlers/command_handlers.py b/core/handlers/command_handlers.py
index 82308905a..589b07d38 100644
--- a/core/handlers/command_handlers.py
+++ b/core/handlers/command_handlers.py
@@ -116,8 +116,11 @@ class CommandHandlers:
InlineButton(text="🔄 Clear All Session", callback_data="cmd_clear"),
InlineButton(text="⚙️ Settings", callback_data="cmd_settings"),
],
- # Row 3: Agent/Model switching
- [InlineButton(text="🤖 Agent Settings", callback_data="cmd_routing")],
+ # Row 3: Resume + Agent/Model switching
+ [
+ InlineButton(text="⏮️ Resume Session", callback_data="cmd_resume"),
+ InlineButton(text="🤖 Agent Settings", callback_data="cmd_routing"),
+ ],
# Row 4: Help
[InlineButton(text="ℹ️ How it Works", callback_data="info_how_it_works")],
]
@@ -306,6 +309,53 @@ Use the buttons below to manage your {agent_display_name} sessions, or simply ty
"📂 Click the 'Change Work Dir' button in the @Vibe Remote /start menu to change working directory.",
)
+ async def handle_resume(self, context: MessageContext):
+ """Open resume-session modal (Slack) or explain availability."""
+ if self.config.platform != "slack":
+ channel_context = self._get_channel_context(context)
+ await self.im_client.send_message(
+ channel_context,
+ "⏮️ Resume is currently available only on Slack. Continue in the same thread to auto-resume.",
+ )
+ return
+
+ trigger_id = (
+ context.platform_specific.get("trigger_id")
+ if context.platform_specific
+ else None
+ )
+ if not trigger_id:
+ channel_context = self._get_channel_context(context)
+ await self.im_client.send_message(
+ channel_context,
+ "⏮️ Please click the Resume button inside Slack to open the picker.",
+ )
+ return
+
+ 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,
+ "ℹ️ No stored sessions found. You can still paste a session ID manually in the resume modal.",
+ )
+
+ try:
+ await self.im_client.open_resume_session_modal(
+ trigger_id=trigger_id,
+ sessions_by_agent=sessions_by_agent,
+ channel_id=context.channel_id,
+ thread_id=context.thread_id or context.message_id or "",
+ )
+ except Exception as e:
+ logger.error(f"Error opening resume modal: {e}")
+ channel_context = self._get_channel_context(context)
+ await self.im_client.send_message(
+ channel_context, "❌ Failed to open resume dialog. Please try again."
+ )
+
async def handle_stop(self, context: MessageContext, args: str = ""):
"""Handle /stop command - send interrupt message to the active agent"""
try:
diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.py
index bf1ffddab..c0f2db131 100644
--- a/core/handlers/message_handler.py
+++ b/core/handlers/message_handler.py
@@ -278,6 +278,9 @@ class MessageHandler:
elif callback_data == "cmd_clear":
await command_handlers.handle_clear(context)
+ elif callback_data == "cmd_resume":
+ await command_handlers.handle_resume(context)
+
elif callback_data == "cmd_settings":
await settings_handler.handle_settings(context)
diff --git a/docs/plans/resume-session.md b/docs/plans/resume-session.md
index 77b96c99b..9ac37f9cd 100644
--- a/docs/plans/resume-session.md
+++ b/docs/plans/resume-session.md
@@ -26,10 +26,10 @@ Add a user-facing resume entry point in Slack (/start menu) to let users pick or
- Reply in thread confirming resume and reminding how to start talking.
## Implementation Todos
-- [ ] Extend /start buttons to include "Resume Session".
-- [ ] Add modal schema + open handler for `cmd_resume` callback.
-- [ ] Implement modal submission handler: resolve session_id (manual input wins), persist via SettingsManager, mark thread active, send confirmation.
-- [ ] Add helper(s) in SettingsManager to list stored session mappings per agent with metadata for display.
+- [x] Extend /start buttons to include "Resume Session".
+- [x] Add modal schema + open handler for `cmd_resume` callback.
+- [x] Implement modal submission handler: resolve session_id (manual input wins), persist via SettingsManager, mark thread active, send confirmation.
+- [x] Add helper(s) in SettingsManager to list stored session mappings per agent with metadata for display.
- [ ] Add tests / manual check notes (if no test harness, include sanity steps).
## Open Questions
diff --git a/modules/im/slack.py b/modules/im/slack.py
index 8c7ed9043..ddae54048 100644
--- a/modules/im/slack.py
+++ b/modules/im/slack.py
@@ -884,6 +884,47 @@ 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 == "resume_session_modal":
+ user_id = payload.get("user", {}).get("id")
+ values = view.get("state", {}).get("values", {})
+
+ agent_data = values.get("agent_block", {}).get("agent_select", {})
+ agent = agent_data.get("selected_option", {}).get("value")
+
+ manual_data = values.get("manual_block", {}).get("manual_input", {})
+ manual_session = (manual_data.get("value") or "").strip()
+
+ session_data = values.get("session_block", {}).get("session_select", {}) if values else {}
+ selected_option = session_data.get("selected_option") or {}
+ selected_value = selected_option.get("value") if isinstance(selected_option, dict) else None
+ selected_session = None
+ selected_agent = None
+ if selected_value and "|" in selected_value:
+ selected_agent, selected_session = selected_value.split("|", 1)
+
+ # manual input takes precedence
+ chosen_session = manual_session or selected_session
+ chosen_agent = selected_agent or agent
+ if manual_session and not chosen_agent:
+ # fallback to agent select when manual filled
+ chosen_agent = agent
+ metadata_raw = view.get("private_metadata")
+ channel_id = None
+ thread_id = None
+ try:
+ import json
+
+ md = json.loads(metadata_raw) if metadata_raw else {}
+ channel_id = md.get("channel_id")
+ thread_id = md.get("thread_id")
+ except Exception:
+ pass
+
+ if hasattr(self, "_on_resume_session"):
+ await self._on_resume_session(
+ user_id, channel_id, thread_id, chosen_agent, chosen_session
+ )
+
elif callback_id == "opencode_question_modal":
user_id = payload.get("user", {}).get("id")
values = view.get("state", {}).get("values", {})
@@ -1392,6 +1433,133 @@ class SlackBot(BaseIMClient):
logger.error(f"Error opening change CWD modal: {e}")
raise
+ async def open_resume_session_modal(
+ self,
+ trigger_id: str,
+ sessions_by_agent: Dict[str, Dict[str, str]],
+ channel_id: Optional[str],
+ thread_id: Optional[str],
+ ):
+ """Open a modal to let users select or input a session to resume."""
+ self._ensure_clients()
+
+ # Build agent options (fallback to common backends)
+ agent_keys = list(sessions_by_agent.keys()) or ["claude", "codex", "opencode"]
+ agent_options = []
+ for agent in sorted(set(agent_keys)):
+ agent_options.append(
+ {
+ "text": {"type": "plain_text", "text": agent.capitalize(), "emoji": True},
+ "value": agent,
+ }
+ )
+
+ session_option_groups = []
+ for agent, mapping in sessions_by_agent.items():
+ if not mapping:
+ continue
+ options = []
+ for thread, session_id in mapping.items():
+ thread_label = thread.replace("slack_", "", 1) if thread.startswith("slack_") else thread
+ truncated = session_id[:60]
+ desc = f"thread {thread_label}"
+ options.append(
+ {
+ "text": {"type": "plain_text", "text": truncated, "emoji": True},
+ "value": f"{agent}|{session_id}",
+ "description": {"type": "plain_text", "text": desc[:75], "emoji": True},
+ }
+ )
+ if options:
+ session_option_groups.append(
+ {
+ "label": {"type": "plain_text", "text": agent.capitalize(), "emoji": True},
+ "options": options,
+ }
+ )
+
+ blocks: list = [
+ {
+ "type": "section",
+ "text": {
+ "type": "mrkdwn",
+ "text": "Select a saved session or paste a session ID to resume work in this thread.",
+ },
+ },
+ {
+ "type": "input",
+ "block_id": "agent_block",
+ "label": {"type": "plain_text", "text": "Agent backend", "emoji": True},
+ "element": {
+ "type": "static_select",
+ "action_id": "agent_select",
+ "options": agent_options,
+ "initial_option": agent_options[0],
+ },
+ },
+ ]
+
+ if session_option_groups:
+ blocks.append(
+ {
+ "type": "input",
+ "block_id": "session_block",
+ "optional": True,
+ "label": {"type": "plain_text", "text": "Pick an existing session", "emoji": True},
+ "element": {
+ "type": "static_select",
+ "action_id": "session_select",
+ "option_groups": session_option_groups,
+ "placeholder": {"type": "plain_text", "text": "Select a session", "emoji": True},
+ },
+ }
+ )
+ else:
+ blocks.append(
+ {
+ "type": "context",
+ "elements": [
+ {
+ "type": "mrkdwn",
+ "text": "_No stored sessions found. Paste a session ID below to resume._",
+ }
+ ],
+ }
+ )
+
+ blocks.append(
+ {
+ "type": "input",
+ "block_id": "manual_block",
+ "optional": True,
+ "label": {"type": "plain_text", "text": "Or paste a session ID", "emoji": True},
+ "element": {
+ "type": "plain_text_input",
+ "action_id": "manual_input",
+ "placeholder": {"type": "plain_text", "text": "e.g., sess_12345", "emoji": True},
+ },
+ }
+ )
+
+ metadata = {"channel_id": channel_id, "thread_id": thread_id}
+ import json
+
+ view = {
+ "type": "modal",
+ "callback_id": "resume_session_modal",
+ "private_metadata": json.dumps(metadata),
+ "title": {"type": "plain_text", "text": "Resume Session", "emoji": True},
+ "submit": {"type": "plain_text", "text": "Resume", "emoji": True},
+ "close": {"type": "plain_text", "text": "Cancel", "emoji": True},
+ "blocks": blocks,
+ }
+
+ try:
+ await self.web_client.views_open(trigger_id=trigger_id, view=view)
+ except SlackApiError as e:
+ logger.error(f"Error opening resume modal: {e}")
+ raise
+
def _get_default_opencode_agent_name(self, opencode_agents: list) -> Optional[str]:
"""Resolve the default OpenCode agent name."""
for agent in opencode_agents:
@@ -2075,6 +2243,10 @@ class SlackBot(BaseIMClient):
if "on_routing_modal_update" in kwargs:
self._on_routing_modal_update = kwargs["on_routing_modal_update"]
+ # Register resume session handler
+ if "on_resume_session" in kwargs:
+ self._on_resume_session = kwargs["on_resume_session"]
+
# Register on_ready handler (called when connected)
if "on_ready" in kwargs:
self._on_ready = kwargs["on_ready"]
diff --git a/modules/settings_manager.py b/modules/settings_manager.py
index 76cf39894..afe1549ab 100644
--- a/modules/settings_manager.py
+++ b/modules/settings_manager.py
@@ -405,6 +405,32 @@ class SettingsManager:
agent_map = self.sessions_store.get_agent_map(user_key, agent_name)
return dict(agent_map)
+ def list_all_agent_sessions(
+ self, user_id: Union[int, str]
+ ) -> Dict[str, Dict[str, str]]:
+ """Return all stored session mappings for the user, grouped by agent.
+
+ Structure: {agent_name: {thread_id: session_id}}
+ """
+ user_key = self._normalize_user_id(user_id)
+ # Ensure namespaces exist
+ self.sessions_store._ensure_user_namespace(user_key)
+ agent_maps = self.sessions_store.state.session_mappings.get(user_key, {})
+ # Shallow copies to avoid accidental mutation
+ return {agent: dict(mapping) for agent, mapping in agent_maps.items()}
+
+ def list_all_agent_sessions(self, user_id: Union[int, str]) -> Dict[str, Dict[str, str]]:
+ """Return all stored session mappings for the user, grouped by agent.
+
+ Returns: {agent_name: {thread_id: session_id}}
+ """
+ user_key = self._normalize_user_id(user_id)
+ # Ensure namespace exists to avoid KeyError
+ self.sessions_store._ensure_user_namespace(user_key)
+ agent_maps = self.sessions_store.state.session_mappings.get(user_key, {})
+ # Return shallow copies to prevent accidental mutation
+ return {agent: dict(mapping) for agent, mapping in agent_maps.items()}
+
# Backwards-compatible helpers for Claude-specific call sites
def set_session_mapping(
self,