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(resume): unify native session recovery flow
cyh029db0662c6d
diff --git a/core/controller.py b/core/controller.pyindex 6e381a324..2d8a99138 100644--- a/core/controller.py+++ b/core/controller.py@@ -11,8 +11,9 @@ from modules.im import BaseIMClient, MessageContext, IMFactoryfrom modules.im.multi import MultiIMClientfrom modules.im.formatters import SlackFormatter, DiscordFormatterfrom modules.agent_router import AgentRouter-from modules.agents import AgentService, ClaudeAgent, CodexAgent, OpenCodeAgent+from modules.agents.service import AgentServicefrom modules.claude_client import ClaudeClient+from modules.agents.native_sessions import AgentNativeSessionServicefrom modules.session_manager import SessionManagerfrom modules.settings_manager import SettingsManager, MultiSettingsManagerfrom core.handlers import (@@ -95,6 +96,7 @@ class Controller:self.settings_manager = MultiSettingsManager(self.enabled_platforms, primary_platform=self.primary_platform)self.platform_settings_managers = self.settings_manager.managersself.sessions = self.settings_manager.sessions+ self.native_session_service = AgentNativeSessionService()# Migrate legacy per-channel language into global configself._migrate_language_from_settings()@@ -240,6 +242,10 @@ class Controller:self.message_handler.set_session_handler(self.session_handler)def _init_agents(self):+ from modules.agents.claude_agent import ClaudeAgent+ from modules.agents.codex import CodexAgent+ from modules.agents.opencode import OpenCodeAgent+self.agent_service = AgentService(self)self.agent_service.register(ClaudeAgent(self))if self.config.codex:diff --git a/core/handlers/command_handlers.py b/core/handlers/command_handlers.pyindex 6a45f40ac..3e6dc6eb0 100644--- a/core/handlers/command_handlers.py+++ b/core/handlers/command_handlers.py@@ -3,7 +3,8 @@import osimport loggingfrom typing import Optional-from modules.agents import AgentRequest, get_agent_display_name+from modules.agents import get_agent_display_name+from modules.agents.base import AgentRequestfrom modules.im import MessageContext, InlineKeyboard, InlineButtonfrom .base import BaseHandler@@ -382,23 +383,18 @@ class CommandHandlers(BaseHandler):"""Open resume-session modal (Slack) or explain availability."""platform = context.platform or (context.platform_specific or {}).get("platform") or self.config.platformim_client = self._get_im_client(context)+ working_path = self.controller.get_cwd(context)+ native_session_service = getattr(self.controller, "native_session_service", None)+ limit = 25 if platform == "discord" else 100+ sessions = native_session_service.list_recent_sessions(working_path, limit=limit) if native_session_service else []if platform == "discord":interaction = context.platform_specific.get("interaction") if context.platform_specific else None- session_key = self._get_session_key(context)- sessions_by_agent = self.sessions.list_all_agent_sessions(session_key)- if not sessions_by_agent:- channel_context = self._get_channel_context(context)- await im_client.send_message(- channel_context,- f"ℹ️ {self._t('command.resume.noStoredSessions')}",- )- returnif interaction and hasattr(im_client, "open_resume_session_modal"):try:await im_client.run_on_client_loop(im_client.open_resume_session_modal(trigger_id=interaction,- sessions_by_agent=sessions_by_agent,+ sessions=sessions,channel_id=context.channel_id,thread_id=context.thread_id or context.message_id or "",host_message_ts=context.message_id,@@ -414,15 +410,12 @@ class CommandHandlers(BaseHandler):)returnif platform == "lark":- session_key = self._get_session_key(context)- sessions_by_agent = self.sessions.list_all_agent_sessions(session_key)- # Allow opening modal even with no sessions (user can paste manually)if hasattr(im_client, "open_resume_session_modal"):try:await im_client.run_on_client_loop(im_client.open_resume_session_modal(trigger_id=context,- sessions_by_agent=sessions_by_agent or {},+ sessions=sessions,channel_id=context.channel_id,thread_id=context.thread_id or context.message_id or "",host_message_ts=context.message_id,@@ -455,21 +448,11 @@ class CommandHandlers(BaseHandler):)return- session_key = self._get_session_key(context)- sessions_by_agent = self.sessions.list_all_agent_sessions(session_key)-- if not sessions_by_agent:- channel_context = self._get_channel_context(context)- await im_client.send_message(- channel_context,- f"ℹ️ {self._t('command.resume.noStoredSessions')}",- )-try:await im_client.run_on_client_loop(im_client.open_resume_session_modal(trigger_id=trigger_id,- sessions_by_agent=sessions_by_agent,+ sessions=sessions,channel_id=context.channel_id,thread_id=context.thread_id or context.message_id or "",host_message_ts=context.message_id,diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.pyindex d71d615c5..aaa2b70df 100644--- a/core/handlers/message_handler.py+++ b/core/handlers/message_handler.py@@ -4,7 +4,7 @@ import asyncioimport loggingfrom typing import List, Optional, Tuple-from modules.agents import AgentRequest+from modules.agents.base import AgentRequestfrom modules.im import MessageContextfrom modules.im.base import FileAttachment@@ -521,6 +521,7 @@ class MessageHandler(BaseHandler):context_for_reply = MessageContext(user_id=context.user_id,channel_id=context.channel_id,+ platform=context.platform or (context.platform_specific or {}).get("platform"),thread_id=context.thread_id,message_id=None,platform_specific=context.platform_specific,diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.pyindex ef40b497f..53a0bec8b 100644--- a/core/handlers/session_handler.py+++ b/core/handlers/session_handler.py@@ -4,7 +4,8 @@ import loggingimport osfrom typing import Optional, Dict, Any, Tuplefrom modules.im import MessageContext-from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions+from modules.claude_sdk_compat import ClaudeSDKClient, ClaudeAgentOptions+from modules.agents.native_sessions.base import build_resume_previewfrom .base import BaseHandler@@ -118,6 +119,82 @@ class SessionHandler(BaseHandler):composite_key = f"{base_session_id}:{working_path}"return base_session_id, working_path, composite_key+ async def _prepare_resume_context(+ self,+ context: MessageContext,+ host_message_ts: Optional[str],+ is_dm: bool,+ ) -> MessageContext:+ im_client = self._get_im_client(context)+ prepare = getattr(im_client, "prepare_resume_context", None)+ if not callable(prepare):+ return context+ try:+ prepared = await prepare(context, host_message_ts=host_message_ts, is_dm=is_dm)+ except Exception as exc:+ logger.warning("Failed to prepare resume context for %s: %s", context.platform, exc)+ return context+ return prepared if isinstance(prepared, MessageContext) else context++ def _supports_resume_threading(self, context: MessageContext, *, is_dm: bool) -> bool:+ im_client = self._get_im_client(context)+ if is_dm:+ return bool(getattr(im_client, "should_use_thread_for_dm_session", lambda: False)())+ return bool(getattr(im_client, "should_use_thread_for_reply", lambda: False)())++ def _build_resume_confirmation(+ self,+ *,+ agent_label: str,+ session_id: str,+ preview: str = "",+ ) -> str:+ lines = [f"✅ {self._t('success.sessionResumed', agent=agent_label, sessionId=session_id)}"]+ if preview:+ lines.extend(["", preview])+ return "\n".join(lines)++ def _build_resume_followup(+ self,+ context: MessageContext,+ *,+ is_dm: bool,+ ) -> str:+ lines: list[str] = []+ platform = context.platform or self.config.platform+ if context.thread_id:+ if platform == "discord":+ lines.append(self._t("success.sessionResumedContinueDiscordThread"))+ elif platform == "lark":+ lines.append(self._t("success.sessionResumedContinueFeishuThread"))+ else:+ lines.append(self._t("success.sessionResumedContinueThread"))+ if not is_dm:+ lines.append(self._t("success.sessionResumedThreadFreshTip"))+ else:+ lines.append(self._t("success.sessionResumedContinueDirect"))+ return "\n".join(line for line in lines if line)++ def _get_resume_preview(+ self,+ context: MessageContext,+ *,+ agent: str,+ session_id: str,+ ) -> str:+ native_session_service = getattr(self.controller, "native_session_service", None)+ if native_session_service is None:+ return ""+ try:+ working_path = self.get_working_path(context)+ item = native_session_service.get_session(working_path, agent, session_id)+ except Exception as exc:+ logger.warning("Failed to resolve resume preview for %s session %s: %s", agent, session_id, exc)+ return ""+ if item is None:+ return ""+ return build_resume_preview(item.last_agent_message or item.last_agent_tail)+async def get_or_create_claude_session(self,context: MessageContext,@@ -367,8 +444,10 @@ class SessionHandler(BaseHandler):channel_id=channel_id or user_id,platform=platform or self.config.platform,thread_id=target_thread or None,+ message_id=host_message_ts or None,platform_specific={"is_dm": is_dm},)+ thread_capable = self._supports_resume_threading(context, is_dm=is_dm)settings_key = self._get_settings_key(context)session_key = self._get_session_key(context)@@ -389,23 +468,55 @@ class SessionHandler(BaseHandler):settings_manager.set_channel_routing(settings_key, routing)agent_label = agent.capitalize()- confirmation = "\n".join(- [- f"✅ {self._t('success.sessionResumed', agent=agent_label, sessionId=session_id)}",- self._t("success.sessionResumedTip1"),- self._t("success.sessionResumedTip2"),- ]+ preview = self._get_resume_preview(context, agent=agent, session_id=session_id)+ confirmation = self._build_resume_confirmation(+ agent_label=agent_label,+ session_id=session_id,+ preview=preview,)- confirmation_ts = await self._get_im_client(context).send_message(- context, confirmation, parse_mode="markdown"+ initial_context = context+ if thread_capable and not target_thread:+ initial_context = MessageContext(+ user_id=context.user_id,+ channel_id=context.channel_id,+ platform=context.platform,+ thread_id=None,+ message_id=context.message_id,+ platform_specific=context.platform_specific,+ files=context.files,+ )++ confirmation_ts = await self._get_im_client(initial_context).send_message(+ initial_context, confirmation, parse_mode="markdown")- mapped_thread = target_thread or confirmation_ts+ followup_context = context+ if thread_capable and not target_thread:+ anchor_context = MessageContext(+ user_id=context.user_id,+ channel_id=context.channel_id,+ platform=context.platform,+ thread_id=None,+ message_id=confirmation_ts,+ platform_specific=context.platform_specific,+ files=context.files,+ )+ followup_context = await self._prepare_resume_context(anchor_context, confirmation_ts, is_dm)++ followup = self._build_resume_followup(followup_context, is_dm=is_dm)+ if followup:+ await self._get_im_client(followup_context).send_message(+ followup_context,+ followup,+ parse_mode="markdown",+ )++ mapped_thread = followup_context.thread_id or confirmation_tsmapping_context = MessageContext(user_id=user_id,- channel_id=context.channel_id,- platform=context.platform,+ channel_id=followup_context.channel_id,+ platform=followup_context.platform,thread_id=mapped_thread,message_id=confirmation_ts,platform_specific={"is_dm": is_dm},diff --git a/core/message_dispatcher.py b/core/message_dispatcher.pyindex f1fd2447a..fb006980b 100644--- a/core/message_dispatcher.py+++ b/core/message_dispatcher.py@@ -379,7 +379,9 @@ class ConsolidatedMessageDispatcher:callback = f"quick_reply:{btn.text}"row.append(InlineButton(text=btn.text, callback_data=callback))- keyboard = InlineKeyboard(buttons=[row])+ platform = context.platform or (context.platform_specific or {}).get("platform") or self.controller.config.platform+ rows = [[button] for button in row] if platform == "lark" else [row]+ keyboard = InlineKeyboard(buttons=rows)await im_client.send_message_with_buttons(context,text,diff --git a/docs/plans/agent-native-resume-session-list.md b/docs/plans/agent-native-resume-session-list.mdnew file mode 100644index 000000000..fa8c26dad--- /dev/null+++ b/docs/plans/agent-native-resume-session-list.md@@ -0,0 +1,511 @@+# Agent-Native Resume Session List++## Background++The current `/resume` flow reads Vibe Remote's own persisted session bindings from `SessionsStore`.+That is sufficient for "resume the session previously bound to this thread", but it does not solve the+actual user problem:++- users want to browse the real session history from the agent backend itself+- the list should reflect the current effective working directory+- sessions created outside the current IM thread should still be recoverable+- the list should be visually obvious across multiple agent backends++This design replaces the current resume picker source with an agent-native session catalog.++## Goal++When the user opens Resume Session, Vibe Remote should:++1. Resolve the current effective working directory via the existing controller/session handler logic.+2. Read the real session history for OpenCode, Claude Code, and Codex for that directory.+3. Merge all sessions into one list.+4. Sort the merged list by time descending, newest first.+5. Show each row with:+ - session time+ - agent prefix: `oc-`, `cc-`, `cx-`+ - the tail of the agent's last message, truncated to about 10 characters+6. On selection, bind the chosen native session ID to the current thread using the existing resume submission flow.++## Non-Goals++- Do not change the actual resume behavior per backend.+- Do not remove manual session ID input.+- Do not change automatic same-thread resume.+- Do not introduce new dependencies.++## Product Rules++### Source of truth++The resume list must no longer come from `SessionsFacade.list_all_agent_sessions(...)`.++That mapping remains useful only as the runtime binding target after the user explicitly chooses a session.++### Working directory++The list must use the real effective working directory for the current context:++- source: `SessionHandler.get_working_path(context)`+- not the process cwd+- not the repository root unless that is the actual effective cwd++### Unified row format++Each displayed item should represent one native backend session and expose:++- `agent`: `opencode` | `claude` | `codex`+- `agent_prefix`: `oc` | `cc` | `cx`+- `native_session_id`: backend-native resume identifier+- `sort_ts`: primary timestamp used for global sorting+- `display_time`: localized short timestamp+- `last_agent_tail`: tail of the backend's latest assistant message+- `display_label`: platform-formatted label++Important: `display_id` is only for UI. Resume submission must still pass the real native identifier:++- OpenCode: session ID such as `ses_xxx`+- Claude Code: session ID UUID+- Codex: thread ID++## Architecture++### New module++Add a new backend-facing session catalog layer under `modules/agents/native_sessions/`:++- `types.py`+- `base.py`+- `opencode.py`+- `claude.py`+- `codex.py`+- `service.py`++This keeps backend-specific session discovery in `modules/agents/` and keeps platform-agnostic orchestration in handlers.++### Core types++```python+@dataclass+class NativeResumeSession:+ agent: Literal["opencode", "claude", "codex"]+ agent_prefix: Literal["oc", "cc", "cx"]+ native_session_id: str+ working_path: str+ created_at: Optional[datetime]+ updated_at: Optional[datetime]+ sort_ts: float+ last_agent_message: str+ last_agent_tail: str+ locator: dict[str, Any]+```++```python+class NativeSessionProvider(Protocol):+ agent_name: str++ def list_metadata(self, working_path: str) -> list[NativeResumeSession]:+ ...++ def hydrate_preview(self, item: NativeResumeSession) -> NativeResumeSession:+ ...+```++```python+class AgentNativeSessionService:+ def list_recent_sessions(+ self,+ working_path: str,+ limit: int,+ ) -> list[NativeResumeSession]:+ ...+```++### Two-phase loading++To avoid slow picker opens:++1. Each provider first returns lightweight metadata only.+2. The service merges all metadata and sorts by `sort_ts desc`.+3. Only the top `limit` items are hydrated to compute `last_agent_tail`.++This is especially important for Claude Code and Codex, where preview extraction requires reading session files.++## Backend Providers++### OpenCode provider++#### Source++- database: `${XDG_DATA_HOME:-~/.local/share}/opencode/opencode.db`+- read via Python `sqlite3` in read-only mode++#### Metadata query++Read from `session`:++- filter: `directory = working_path`+- fields:+ - `id`+ - `title`+ - `time_created`+ - `time_updated`++Use `time_updated` as the primary sort timestamp.++#### Preview query++Read from `part`:++- filter by `session_id`+- order by `time_created desc`+- find the latest assistant text part++The `part.data` payload already contains structured text parts, so OpenCode does not need `opencode export` for picker rendering.++#### Native resume identifier++- `native_session_id = session.id`++### Claude Code provider++#### Source++- project index: `~/.claude/projects/<encoded-working-path>/sessions-index.json`+- session files: `~/.claude/projects/<encoded-working-path>/<session_id>.jsonl`++Directory encoding rule:++- absolute path with `/` replaced by `-`+- example:+ - `/Users/cyh/vibe-remote`+ - `-Users-cyh-vibe-remote`++#### Metadata source++Primary source: `sessions-index.json`++Useful fields:++- `sessionId`+- `created`+- `modified`+- `projectPath`+- `firstPrompt`+- `fullPath`++Fallback if the index is missing or stale:++- scan `*.jsonl` files in the encoded project directory+- derive timestamps from file metadata and/or JSONL content++#### Preview extraction++Read the referenced `.jsonl` and scan for the latest assistant message with textual content.++Preferred order:++1. latest assistant text+2. fallback to session name if present in future index schema+3. fallback to `firstPrompt`++#### Native resume identifier++- `native_session_id = sessionId`++### Codex provider++#### Source++- metadata DB: `~/.codex/state_5.sqlite`+- message log file: `threads.rollout_path`++#### Metadata query++Read from `threads`:++- filter: `cwd = working_path`+- fields:+ - `id`+ - `created_at`+ - `updated_at`+ - `title`+ - `first_user_message`+ - `rollout_path`++Use `updated_at` as the primary sort timestamp.++#### Preview extraction++Parse `rollout_path` JSONL and scan backwards for the latest assistant-visible text.++Acceptable sources include:++- `response_item` assistant messages+- `event_msg` assistant commentary if that is the last visible assistant content++For picker preview, use the latest assistant text that a user would recognize as the session's final reply.++#### Native resume identifier++- `native_session_id = thread.id`++This matches the current Codex resume path, which calls `thread/resume` with the stored thread ID.++## Preview Text Rules++The picker preview should show the tail of the last assistant message, not the title.++### Normalization++For all providers:++1. keep only assistant-authored text+2. normalize newlines to spaces+3. trim whitespace+4. remove trailing quick-reply button block after `\n---\n`+5. drop empty output++### Tail extraction++Use the last non-empty line after normalization.++If the line is too long:++- keep the last ~10 characters+- prepend `...`++Example:++- full: `请帮我调研清楚这三种 agent 是否具备获取session list及详情的这样的能力。`+- tail: `...详情的这样的能力。`++### Empty fallback++If no assistant text exists yet:++- OpenCode: fallback to session title+- Claude Code: fallback to `firstPrompt`+- Codex: fallback to `title` or `first_user_message`++## Sorting and Merge Rules++### Global ordering++Merge all provider items into one flat list and sort by:++1. `sort_ts desc`+2. `agent_prefix asc`+3. `native_session_id asc`++This guarantees deterministic output.++### Time source++- prefer `updated_at`+- fallback to `created_at`++### Display time++Use a compact localized format suitable for IM pickers, for example:++- same year: `03-25 22:54`+- older year: `2025-11-10`++The exact formatter can stay shared and platform-agnostic.++## UI Design++### Required visual signal++Users must be able to tell backend type immediately.++Use explicit prefixes:++- OpenCode: `oc-`+- Claude Code: `cc-`+- Codex: `cx-`++### Canonical row content++Canonical display payload:++- prefix+- time+- last tail++Example logical row:++- `oc- 03-25 22:54 ...提交到master`++### Platform-specific formatting++#### Slack++Use a single flat `static_select` list, not grouped-by-agent option groups.++- option text: `oc- 03-25 22:54`+- option description: `...提交到master`+- option value: `opencode|ses_xxx`++This preserves global time ordering while still showing the preview text.++#### Discord++Use one flat select:++- label: `oc- 03-25 22:54`+- description: `...提交到master`+- value: `opencode|ses_xxx`++Because Discord caps select options at 25:++- show the newest 25 merged sessions+- keep manual session ID input as the escape hatch++#### Feishu++Feishu `select_static` is more constrained, so encode everything into one visible line:++- text: `oc- 03-25 22:54 · ...提交到master`+- value: `opencode|ses_xxx`++Show the newest 100 merged sessions.++## Handler Changes++### `CommandHandlers.handle_resume`++Current behavior:++- reads `self.sessions.list_all_agent_sessions(session_key)`++New behavior:++1. resolve `working_path = self.controller.get_cwd(context)`+2. call `agent_native_session_service.list_recent_sessions(working_path, platform_limit)`+3. pass the flat merged list into the platform modal/card renderer+4. if empty, still open the modal when manual paste is supported++### IM modal signatures++Change the modal/card methods from:++```python+open_resume_session_modal(..., sessions_by_agent: Dict[str, Dict[str, str]], ...)+```++to:++```python+open_resume_session_modal(..., sessions: list[NativeResumeSession], ...)+```++All three IM implementations should render from the same flat list.++### Resume submission++No behavioral rewrite is required.++Keep the existing submission contract:++- parse selected value as `agent|native_session_id`+- call `handle_resume_session_submission(...)`+- persist the chosen backend-native identifier via the existing session binding flow++This means:++- OpenCode still stores the chosen `ses_xxx`+- Claude still stores the chosen session UUID+- Codex still stores the chosen thread ID++## Copy Changes++The old copy says "stored sessions", which will become inaccurate.++Update copy to reflect the new source:++- "Recent sessions in the current working directory"+- "No recent agent sessions found for this working directory"+- manual paste remains available++## File Touchpoints++Expected implementation touchpoints:++- `core/handlers/command_handlers.py`+- `modules/im/slack.py`+- `modules/im/discord.py`+- `modules/im/feishu.py`+- `core/handlers/session_handler.py`+- `modules/agents/native_sessions/*`+- `vibe/i18n/en.json`+- `vibe/i18n/zh.json`++The existing `SessionsFacade` remains in place for thread-to-session bindings after selection.++## Edge Cases++### Missing backend data++If a backend is not installed, not enabled, or its local state files are missing:++- skip that backend+- do not fail the whole picker+- log at `info` or `warning`++### Corrupt session entries++If one session file or row fails to parse:++- skip that item+- continue rendering the rest++### Duplicate-looking IDs++Because the display prefix is explicit and the value carries `agent|native_id`, collisions are harmless.++### Sessions with no assistant reply yet++Still list them if they have valid metadata.++Their preview should fallback as described above.++## Testing Plan++### Unit tests++Add provider-level tests for:++- OpenCode metadata filtering by exact `working_path`+- Claude project path encoding and index parsing+- Codex thread filtering by exact `cwd`+- tail extraction and truncation rules+- merged global sorting++### Handler tests++Update `/resume` tests to verify:++- list source is agent-native, not session map+- merged order is newest first across backends+- selected value still resumes correctly++### Manual checks++Verify in Slack, Discord, and Feishu:++1. sessions from all three backends appear in one merged list+2. prefixes are visible and correct+3. newest items are first+4. preview shows the tail of the last agent message+5. selecting an item binds and resumes correctly++## Rollout Strategy++Implement in two steps:++1. introduce the new native session service and swap the picker source+2. keep the existing manual session ID path and binding logic untouched++This keeps the change focused and lowers regression risk.diff --git a/modules/agents/__init__.py b/modules/agents/__init__.pyindex d9aadf8a6..b99c41f2c 100644--- a/modules/agents/__init__.py+++ b/modules/agents/__init__.py@@ -1,9 +1,6 @@from typing import Optionalfrom .base import BaseAgent, AgentRequest, AgentMessage-from .claude_agent import ClaudeAgent-from .codex import CodexAgent-from .opencode import OpenCodeAgentfrom .service import AgentService@@ -30,9 +27,6 @@ __all__ = ["AgentMessage","AgentRequest","BaseAgent",- "ClaudeAgent",- "CodexAgent",- "OpenCodeAgent","AgentService","get_agent_display_name",]diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.pyindex 0f64cf192..43817d3c0 100644--- a/modules/agents/claude_agent.py+++ b/modules/agents/claude_agent.py@@ -3,7 +3,7 @@ import loggingimport osfrom typing import Callable, Optional-from claude_agent_sdk import TextBlock, ToolUseBlock+from modules.claude_sdk_compat import TextBlock, ToolUseBlockfrom modules.agents.base import AgentRequest, BaseAgentdiff --git a/modules/agents/native_sessions/__init__.py b/modules/agents/native_sessions/__init__.pynew file mode 100644index 000000000..2003c311c--- /dev/null+++ b/modules/agents/native_sessions/__init__.py@@ -0,0 +1,6 @@+"""Backend-native session catalog helpers for the resume picker."""++from .service import AgentNativeSessionService+from .types import NativeResumeSession++__all__ = ["AgentNativeSessionService", "NativeResumeSession"]diff --git a/modules/agents/native_sessions/base.py b/modules/agents/native_sessions/base.pynew file mode 100644index 000000000..a29da6edb--- /dev/null+++ b/modules/agents/native_sessions/base.py@@ -0,0 +1,137 @@+from __future__ import annotations++import json+import logging+from datetime import datetime+from pathlib import Path+from typing import Protocol++from .types import NativeResumeSession++logger = logging.getLogger(__name__)+EDGE_SYMBOLS = " \t\r\n`*_~'\"“”‘’.,!?!?。,、::;;-—…()()[]【】<>《》「」『』{}|/\\"+++class NativeSessionProvider(Protocol):+ agent_name: str++ def list_metadata(self, working_path: str) -> list[NativeResumeSession]:+ """Return lightweight session metadata for a working path."""++ def hydrate_preview(self, item: NativeResumeSession) -> NativeResumeSession:+ """Fill in the assistant preview text for one item."""+++def normalize_preview_text(text: str) -> str:+ if not text:+ return ""+ cleaned = text.replace("\r\n", "\n").replace("\r", "\n")+ if "\n---\n" in cleaned:+ cleaned = cleaned.split("\n---\n", 1)[0]+ lines = [line.strip() for line in cleaned.split("\n") if line.strip()]+ return " ".join(lines).strip()+++def normalize_multiline_preview_text(text: str) -> str:+ if not text:+ return ""+ cleaned = text.replace("\r\n", "\n").replace("\r", "\n")+ if "\n---\n" in cleaned:+ cleaned = cleaned.split("\n---\n", 1)[0]++ normalized_lines: list[str] = []+ previous_blank = False+ for raw_line in cleaned.split("\n"):+ line = raw_line.strip()+ if not line:+ if normalized_lines and not previous_blank:+ normalized_lines.append("")+ previous_blank = True+ continue+ normalized_lines.append(line)+ previous_blank = False++ while normalized_lines and not normalized_lines[0]:+ normalized_lines.pop(0)+ while normalized_lines and not normalized_lines[-1]:+ normalized_lines.pop()++ return "\n".join(normalized_lines).strip()+++def trim_edge_symbols(text: str) -> str:+ return (text or "").strip(EDGE_SYMBOLS)+++def build_trailing_excerpt(text: str, limit: int, *, prefix_ellipsis: bool = True) -> str:+ cleaned = normalize_preview_text(text)+ if not cleaned:+ return ""+ excerpt = cleaned if len(cleaned) <= limit else cleaned[-limit:]+ excerpt = trim_edge_symbols(excerpt) or excerpt.strip()+ if not excerpt:+ return ""+ if len(cleaned) <= limit:+ return excerpt+ return f"...{excerpt}" if prefix_ellipsis else excerpt+++def build_tail_preview(text: str, limit: int = 15) -> str:+ return build_trailing_excerpt(text, limit, prefix_ellipsis=True)+++def build_resume_preview(text: str, limit: int = 200) -> str:+ cleaned = normalize_multiline_preview_text(text)+ if not cleaned:+ return ""+ excerpt = cleaned if len(cleaned) <= limit else cleaned[-limit:]+ excerpt = excerpt.strip()+ if len(cleaned) > limit:+ excerpt = excerpt.lstrip()+ return f"...{excerpt}" if excerpt else ""+ return excerpt+++def parse_json_blob(blob: str) -> dict:+ try:+ value = json.loads(blob)+ return value if isinstance(value, dict) else {}+ except Exception:+ return {}+++def ts_seconds(value: int | float | str | None, *, millis: bool = False) -> float:+ if value in (None, ""):+ return 0.0+ try:+ number = float(value)+ except (TypeError, ValueError):+ return 0.0+ return number / 1000.0 if millis else number+++def dt_from_ts(value: int | float | str | None, *, millis: bool = False) -> datetime | None:+ seconds = ts_seconds(value, millis=millis)+ if seconds <= 0:+ return None+ return datetime.fromtimestamp(seconds)+++def read_json_lines(path: Path) -> list[dict]:+ rows: list[dict] = []+ try:+ for line in path.read_text(encoding="utf-8").splitlines():+ line = line.strip()+ if not line:+ continue+ try:+ value = json.loads(line)+ except Exception:+ continue+ if isinstance(value, dict):+ rows.append(value)+ except FileNotFoundError:+ return []+ except Exception as exc:+ logger.warning("Failed to read jsonl %s: %s", path, exc)+ return rowsdiff --git a/modules/agents/native_sessions/claude.py b/modules/agents/native_sessions/claude.pynew file mode 100644index 000000000..88fda68da--- /dev/null+++ b/modules/agents/native_sessions/claude.py@@ -0,0 +1,241 @@+from __future__ import annotations++import json+import logging+import re+from datetime import datetime+from pathlib import Path++from .base import (+ NativeSessionProvider,+ build_tail_preview,+ dt_from_ts,+ normalize_preview_text,+ read_json_lines,+)+from .types import NativeResumeSession++logger = logging.getLogger(__name__)+++def encode_project_path(working_path: str) -> str:+ return working_path.replace("/", "-")+++class ClaudeNativeSessionProvider(NativeSessionProvider):+ agent_name = "claude"++ def __init__(self, root: str | None = None, history_path: str | None = None):+ self.root = Path(root or Path.home() / ".claude" / "projects")+ self.history_path = Path(history_path or Path.home() / ".claude" / "history.jsonl")++ def _project_dir(self, working_path: str) -> Path:+ return self.root / encode_project_path(working_path)++ @staticmethod+ def _candidate_project_names(working_path: str) -> set[str]:+ collapsed = re.sub(r"[^A-Za-z0-9]+", "-", working_path).strip("-")+ names = {+ encode_project_path(working_path),+ encode_project_path(working_path).replace("_", "-"),+ }+ if collapsed:+ names.add(f"-{collapsed}")+ return names++ @staticmethod+ def _merge_session(+ results: dict[str, NativeResumeSession],+ item: NativeResumeSession,+ ) -> None:+ existing = results.get(item.native_session_id)+ if existing is None:+ results[item.native_session_id] = item+ return++ if item.created_at and (existing.created_at is None or item.created_at < existing.created_at):+ existing.created_at = item.created_at+ if item.updated_at and (existing.updated_at is None or item.updated_at > existing.updated_at):+ existing.updated_at = item.updated_at+ existing.sort_ts = max(existing.sort_ts, item.sort_ts)++ for key, value in item.locator.items():+ if value and not existing.locator.get(key):+ existing.locator[key] = value++ @staticmethod+ def _parse_iso(value: str | None) -> datetime | None:+ if not value:+ return None+ try:+ return datetime.fromisoformat(value.replace("Z", "+00:00")).astimezone().replace(tzinfo=None)+ except Exception:+ return None++ def list_metadata(self, working_path: str) -> list[NativeResumeSession]:+ candidate_names = self._candidate_project_names(working_path)+ results: dict[str, NativeResumeSession] = {}++ project_dirs: list[Path] = []+ seen_dirs: set[Path] = set()+ for name in candidate_names:+ path = self.root / name+ if path.exists() and path.is_dir() and path not in seen_dirs:+ project_dirs.append(path)+ seen_dirs.add(path)+ for path in sorted(self.root.iterdir()) if self.root.exists() else []:+ if not path.is_dir() or path in seen_dirs:+ continue+ project_dirs.append(path)+ seen_dirs.add(path)++ for project_dir in project_dirs:+ index_path = project_dir / "sessions-index.json"+ if index_path.is_file():+ try:+ payload = json.loads(index_path.read_text(encoding="utf-8"))+ except Exception as exc:+ logger.warning("Failed to parse Claude sessions index %s: %s", index_path, exc)+ payload = {}++ entries = payload.get("entries", []) if isinstance(payload, dict) else []+ for entry in entries:+ if not isinstance(entry, dict):+ continue+ session_id = str(entry.get("sessionId") or "").strip()+ project_path = str(entry.get("projectPath") or "").strip()+ if not session_id or project_path != working_path:+ continue+ created_at = self._parse_iso(entry.get("created"))+ updated_at = self._parse_iso(entry.get("modified"))+ self._merge_session(+ results,+ NativeResumeSession(+ agent="claude",+ agent_prefix="cc",+ native_session_id=session_id,+ working_path=working_path,+ created_at=created_at,+ updated_at=updated_at,+ sort_ts=(updated_at or created_at).timestamp() if (updated_at or created_at) else 0.0,+ locator={+ "full_path": entry.get("fullPath") or str(project_dir / f"{session_id}.jsonl"),+ "first_prompt": str(entry.get("firstPrompt") or ""),+ },+ ),+ )++ for jsonl_path in sorted(project_dir.glob("*.jsonl")):+ session_id = jsonl_path.stem+ rows = read_json_lines(jsonl_path)+ if not rows:+ continue+ created_at = None+ updated_at = None+ first_prompt = ""+ matched_working_path = False+ inferred_working_path = ""+ for row in rows:+ row_cwd = str(row.get("cwd") or row.get("projectPath") or "").strip()+ if row_cwd:+ inferred_working_path = row_cwd+ if row_cwd == working_path:+ matched_working_path = True+ if row.get("type") == "user" and not first_prompt:+ first_prompt = str((row.get("message") or {}).get("content") or "")+ timestamp = self._parse_iso(row.get("timestamp"))+ if timestamp and created_at is None:+ created_at = timestamp+ if timestamp:+ updated_at = timestamp+ if not matched_working_path and inferred_working_path and inferred_working_path != working_path:+ continue+ if not matched_working_path and not inferred_working_path and project_dir.name not in candidate_names:+ continue+ if not (created_at or updated_at):+ stat = jsonl_path.stat()+ created_at = datetime.fromtimestamp(stat.st_ctime)+ updated_at = datetime.fromtimestamp(stat.st_mtime)+ self._merge_session(+ results,+ NativeResumeSession(+ agent="claude",+ agent_prefix="cc",+ native_session_id=session_id,+ working_path=working_path,+ created_at=created_at,+ updated_at=updated_at,+ sort_ts=(updated_at or created_at).timestamp() if (updated_at or created_at) else 0.0,+ locator={"full_path": str(jsonl_path), "first_prompt": first_prompt},+ ),+ )++ if self.history_path.exists():+ latest_history: dict[str, dict[str, str | float | datetime | None]] = {}+ for row in read_json_lines(self.history_path):+ project_path = str(row.get("project") or "").strip()+ session_id = str(row.get("sessionId") or "").strip()+ if project_path != working_path or not session_id:+ continue+ updated_at = dt_from_ts(row.get("timestamp"), millis=True)+ sort_ts = updated_at.timestamp() if updated_at else 0.0+ current = latest_history.get(session_id)+ if current and sort_ts <= float(current.get("sort_ts") or 0.0):+ continue+ latest_history[session_id] = {+ "updated_at": updated_at,+ "sort_ts": sort_ts,+ "display": str(row.get("display") or "").strip(),+ }++ for session_id, payload in latest_history.items():+ updated_at = payload.get("updated_at")+ self._merge_session(+ results,+ NativeResumeSession(+ agent="claude",+ agent_prefix="cc",+ native_session_id=session_id,+ working_path=working_path,+ created_at=updated_at if isinstance(updated_at, datetime) else None,+ updated_at=updated_at if isinstance(updated_at, datetime) else None,+ sort_ts=float(payload.get("sort_ts") or 0.0),+ locator={"history_display": str(payload.get("display") or "")},+ ),+ )++ items = list(results.values())+ items.sort(key=lambda item: (-item.sort_ts, item.native_session_id))+ return items++ def hydrate_preview(self, item: NativeResumeSession) -> NativeResumeSession:+ preview = ""+ full_path_raw = str(item.locator.get("full_path") or "").strip()+ full_path = Path(full_path_raw) if full_path_raw else None+ if full_path and full_path.exists():+ rows = read_json_lines(full_path)+ for row in reversed(rows):+ if row.get("type") != "assistant":+ continue+ message = row.get("message") or {}+ content = message.get("content")+ if isinstance(content, str):+ preview = content+ break+ if isinstance(content, list):+ parts: list[str] = []+ for part in content:+ if isinstance(part, dict) and part.get("type") == "text":+ text = str(part.get("text") or "").strip()+ if text:+ parts.append(text)+ if parts:+ preview = "\n".join(parts)+ break+ if not preview:+ preview = str(+ item.locator.get("first_prompt") or item.locator.get("history_display") or ""+ )+ item.last_agent_message = normalize_preview_text(preview)+ item.last_agent_tail = build_tail_preview(item.last_agent_message or preview or item.native_session_id)+ return itemdiff --git a/modules/agents/native_sessions/codex.py b/modules/agents/native_sessions/codex.pynew file mode 100644index 000000000..8686be0a0--- /dev/null+++ b/modules/agents/native_sessions/codex.py@@ -0,0 +1,86 @@+from __future__ import annotations++import logging+import sqlite3+from pathlib import Path++from .base import NativeSessionProvider, build_tail_preview, dt_from_ts, read_json_lines+from .types import NativeResumeSession++logger = logging.getLogger(__name__)+++class CodexNativeSessionProvider(NativeSessionProvider):+ agent_name = "codex"++ def __init__(self, db_path: str | None = None):+ self.db_path = Path(db_path or Path.home() / ".codex" / "state_5.sqlite")++ def _connect(self) -> sqlite3.Connection:+ return sqlite3.connect(f"file:{self.db_path}?mode=ro", uri=True)++ def list_metadata(self, working_path: str) -> list[NativeResumeSession]:+ if not self.db_path.exists():+ return []+ items: list[NativeResumeSession] = []+ try:+ with self._connect() as conn:+ cursor = conn.execute(+ """+ SELECT id, created_at, updated_at, title, first_user_message, rollout_path+ FROM threads+ WHERE cwd = ? AND archived = 0+ ORDER BY updated_at DESC, id DESC+ """,+ (working_path,),+ )+ for session_id, created_ts, updated_ts, title, first_user_message, rollout_path in cursor.fetchall():+ created_at = dt_from_ts(created_ts)+ updated_at = dt_from_ts(updated_ts)+ items.append(+ NativeResumeSession(+ agent="codex",+ agent_prefix="cx",+ native_session_id=session_id,+ working_path=working_path,+ created_at=created_at,+ updated_at=updated_at,+ sort_ts=(updated_at or created_at).timestamp() if (updated_at or created_at) else 0.0,+ locator={+ "title": title or "",+ "first_user_message": first_user_message or "",+ "rollout_path": rollout_path or "",+ },+ )+ )+ except Exception as exc:+ logger.warning("Failed to list Codex sessions for %s: %s", working_path, exc)+ return items++ def hydrate_preview(self, item: NativeResumeSession) -> NativeResumeSession:+ preview = ""+ rollout_path = Path(str(item.locator.get("rollout_path") or ""))+ if rollout_path.exists():+ rows = read_json_lines(rollout_path)+ for row in reversed(rows):+ if row.get("type") != "response_item":+ continue+ payload = row.get("payload") or {}+ if payload.get("type") != "message" or payload.get("role") != "assistant":+ continue+ parts = payload.get("content") or []+ texts: list[str] = []+ if isinstance(parts, list):+ for part in parts:+ if isinstance(part, dict) and part.get("type") == "output_text":+ text = str(part.get("text") or "").strip()+ if text:+ texts.append(text)+ if texts:+ preview = "\n".join(texts)+ break+ if not preview:+ preview = str(item.locator.get("title") or item.locator.get("first_user_message") or "")+ item.last_agent_message = preview+ item.last_agent_tail = build_tail_preview(preview or item.native_session_id)+ return itemdiff --git a/modules/agents/native_sessions/opencode.py b/modules/agents/native_sessions/opencode.pynew file mode 100644index 000000000..73142958a--- /dev/null+++ b/modules/agents/native_sessions/opencode.py@@ -0,0 +1,88 @@+from __future__ import annotations++import logging+import sqlite3+from pathlib import Path++from .base import NativeSessionProvider, build_tail_preview, dt_from_ts, parse_json_blob+from .types import NativeResumeSession++logger = logging.getLogger(__name__)+++class OpenCodeNativeSessionProvider(NativeSessionProvider):+ agent_name = "opencode"++ def __init__(self, db_path: str | None = None):+ self.db_path = Path(db_path or Path.home() / ".local" / "share" / "opencode" / "opencode.db")++ def _connect(self) -> sqlite3.Connection:+ return sqlite3.connect(f"file:{self.db_path}?mode=ro", uri=True)++ def list_metadata(self, working_path: str) -> list[NativeResumeSession]:+ if not self.db_path.exists():+ return []+ rows: list[NativeResumeSession] = []+ try:+ with self._connect() as conn:+ cursor = conn.execute(+ """+ SELECT id, title, time_created, time_updated+ FROM session+ WHERE directory = ?+ ORDER BY time_updated DESC, id DESC+ """,+ (working_path,),+ )+ for session_id, title, created_ms, updated_ms in cursor.fetchall():+ created_at = dt_from_ts(created_ms, millis=True)+ updated_at = dt_from_ts(updated_ms, millis=True)+ rows.append(+ NativeResumeSession(+ agent="opencode",+ agent_prefix="oc",+ native_session_id=session_id,+ working_path=working_path,+ created_at=created_at,+ updated_at=updated_at,+ sort_ts=(updated_at or created_at).timestamp() if (updated_at or created_at) else 0.0,+ locator={"title": title or ""},+ )+ )+ except Exception as exc:+ logger.warning("Failed to list OpenCode sessions for %s: %s", working_path, exc)+ return rows++ def hydrate_preview(self, item: NativeResumeSession) -> NativeResumeSession:+ preview = ""+ if not self.db_path.exists():+ return item+ try:+ with self._connect() as conn:+ cursor = conn.execute(+ """+ SELECT m.data, p.data+ FROM part p+ JOIN message m ON m.id = p.message_id+ WHERE p.session_id = ?+ ORDER BY p.time_created DESC, p.id DESC+ """,+ (item.native_session_id,),+ )+ for message_blob, part_blob in cursor.fetchall():+ message_data = parse_json_blob(message_blob)+ if message_data.get("role") != "assistant":+ continue+ part_data = parse_json_blob(part_blob)+ if part_data.get("type") != "text":+ continue+ text = str(part_data.get("text") or "").strip()+ if text:+ preview = text+ break+ except Exception as exc:+ logger.warning("Failed to hydrate OpenCode session %s: %s", item.native_session_id, exc)+ item.last_agent_message = preview+ fallback = str(item.locator.get("title") or item.native_session_id)+ item.last_agent_tail = build_tail_preview(preview or fallback)+ return itemdiff --git a/modules/agents/native_sessions/service.py b/modules/agents/native_sessions/service.pynew file mode 100644index 000000000..42af1e09a--- /dev/null+++ b/modules/agents/native_sessions/service.py@@ -0,0 +1,126 @@+from __future__ import annotations++import logging+from collections import Counter+from datetime import datetime++from .base import NativeSessionProvider, build_tail_preview+from .claude import ClaudeNativeSessionProvider+from .codex import CodexNativeSessionProvider+from .opencode import OpenCodeNativeSessionProvider+from .types import NativeResumeSession++logger = logging.getLogger(__name__)+++class AgentNativeSessionService:+ def __init__(self, providers: list[NativeSessionProvider] | None = None):+ self.providers = providers or [+ OpenCodeNativeSessionProvider(),+ ClaudeNativeSessionProvider(),+ CodexNativeSessionProvider(),+ ]++ def list_recent_sessions(self, working_path: str, limit: int = 100) -> list[NativeResumeSession]:+ items: list[NativeResumeSession] = []+ for provider in self.providers:+ try:+ items.extend(provider.list_metadata(working_path))+ except Exception as exc:+ logger.warning("Failed to list %s sessions for %s: %s", provider.agent_name, working_path, exc)++ items.sort(key=lambda item: (-item.sort_ts, item.agent_prefix, item.native_session_id))+ items = self._apply_limit(items, max(limit, 0))++ provider_by_name = {provider.agent_name: provider for provider in self.providers}+ hydrated: list[NativeResumeSession] = []+ for item in items:+ provider = provider_by_name.get(item.agent)+ if not provider:+ hydrated.append(item)+ continue+ try:+ hydrated.append(provider.hydrate_preview(item))+ except Exception as exc:+ logger.warning("Failed to hydrate %s session %s: %s", item.agent, item.native_session_id, exc)+ hydrated.append(item)+ return hydrated++ @staticmethod+ def _apply_limit(items: list[NativeResumeSession], limit: int) -> list[NativeResumeSession]:+ if limit <= 0:+ return []+ if len(items) <= limit:+ return items++ selected = list(items[:limit])+ present_agents = {item.agent for item in selected}+ missing_agents = []+ seen_missing = set()+ for item in items[limit:]:+ if item.agent in present_agents or item.agent in seen_missing:+ continue+ missing_agents.append(item)+ seen_missing.add(item.agent)++ if not missing_agents:+ return selected++ counts = Counter(item.agent for item in selected)+ for replacement in missing_agents:+ removable_index = None+ for index in range(len(selected) - 1, -1, -1):+ candidate = selected[index]+ if counts[candidate.agent] > 1:+ removable_index = index+ break+ if removable_index is None:+ removable_index = len(selected) - 1+ removed = selected[removable_index]+ counts[removed.agent] -= 1+ selected[removable_index] = replacement+ counts[replacement.agent] += 1++ selected.sort(key=lambda item: (-item.sort_ts, item.agent_prefix, item.native_session_id))+ return selected++ @staticmethod+ def format_display_time(item: NativeResumeSession) -> str:+ dt = item.updated_at or item.created_at+ if not dt:+ return "--"+ now = datetime.now()+ if dt.year == now.year:+ return dt.strftime("%m-%d %H:%M")+ return dt.strftime("%Y-%m-%d")++ @staticmethod+ def format_display_summary(item: NativeResumeSession) -> str:+ tail = item.last_agent_tail or build_tail_preview(item.native_session_id)+ suffix = tail.lstrip(".") or item.native_session_id[-10:]+ return f"{item.agent_prefix}...{suffix}"++ def get_session(+ self,+ working_path: str,+ agent: str,+ native_session_id: str,+ ) -> NativeResumeSession | None:+ provider_by_name = {provider.agent_name: provider for provider in self.providers}+ provider = provider_by_name.get(agent)+ if not provider:+ return None+ try:+ items = provider.list_metadata(working_path)+ except Exception as exc:+ logger.warning("Failed to list %s sessions for preview lookup: %s", agent, exc)+ return None+ for item in items:+ if item.native_session_id != native_session_id:+ continue+ try:+ return provider.hydrate_preview(item)+ except Exception as exc:+ logger.warning("Failed to hydrate %s session %s: %s", agent, native_session_id, exc)+ return item+ return Nonediff --git a/modules/agents/native_sessions/types.py b/modules/agents/native_sessions/types.pynew file mode 100644index 000000000..ed5a233fb--- /dev/null+++ b/modules/agents/native_sessions/types.py@@ -0,0 +1,23 @@+from __future__ import annotations++from dataclasses import dataclass, field+from datetime import datetime+from typing import Any, Literal+++AgentName = Literal["opencode", "claude", "codex"]+AgentPrefix = Literal["oc", "cc", "cx"]+++@dataclass(slots=True)+class NativeResumeSession:+ agent: AgentName+ agent_prefix: AgentPrefix+ native_session_id: str+ working_path: str+ created_at: datetime | None+ updated_at: datetime | None+ sort_ts: float+ last_agent_message: str = ""+ last_agent_tail: str = ""+ locator: dict[str, Any] = field(default_factory=dict)diff --git a/modules/claude_client.py b/modules/claude_client.pyindex efd3c332d..09ed7d8b9 100644--- a/modules/claude_client.py+++ b/modules/claude_client.py@@ -1,7 +1,7 @@import loggingimport osfrom typing import Optional, Callable-from claude_agent_sdk import (+from modules.claude_sdk_compat import (ClaudeAgentOptions,SystemMessage,AssistantMessage,diff --git a/modules/claude_sdk_compat.py b/modules/claude_sdk_compat.pynew file mode 100644index 000000000..3fdad4920--- /dev/null+++ b/modules/claude_sdk_compat.py@@ -0,0 +1,52 @@+"""Compatibility helpers for environments without claude_agent_sdk installed."""++from __future__ import annotations+++try:+ from claude_agent_sdk import ( # type: ignore[import-not-found]+ AssistantMessage,+ ClaudeAgentOptions,+ ClaudeSDKClient,+ ResultMessage,+ SystemMessage,+ TextBlock,+ ToolResultBlock,+ ToolUseBlock,+ UserMessage,+ )+ CLAUDE_SDK_AVAILABLE = True+except ModuleNotFoundError: # pragma: no cover - exercised only in minimal test envs+ CLAUDE_SDK_AVAILABLE = False++ class _MissingClaudeSDK:+ def __init__(self, *args, **kwargs):+ raise ModuleNotFoundError("claude_agent_sdk is required for Claude backend functionality")++ class ClaudeAgentOptions(_MissingClaudeSDK):+ pass++ class ClaudeSDKClient(_MissingClaudeSDK):+ pass++ class SystemMessage: # minimal placeholders for isinstance checks+ pass++ class AssistantMessage:+ pass++ class UserMessage:+ pass++ class ResultMessage:+ pass++ class TextBlock:+ pass++ class ToolUseBlock:+ pass++ class ToolResultBlock:+ pass+diff --git a/modules/im/discord.py b/modules/im/discord.pyindex 12300989c..9b2f7ac5c 100644--- a/modules/im/discord.py+++ b/modules/im/discord.py@@ -30,6 +30,7 @@ from modules.agents.opencode.utils import (resolve_opencode_default_model,resolve_opencode_provider_preferences,)+from modules.agents.native_sessions import AgentNativeSessionService, NativeResumeSessionlogger = logging.getLogger(__name__)@@ -159,6 +160,44 @@ class DiscordBot(BaseIMClient):def should_use_thread_for_dm_session(self) -> bool:return False+ async def prepare_resume_context(+ self,+ context: MessageContext,+ *,+ host_message_ts: Optional[str] = None,+ is_dm: bool = False,+ ) -> MessageContext:+ if context.thread_id or is_dm or not host_message_ts:+ return context++ async def _impl() -> MessageContext:+ channel = await self._fetch_channel(context.channel_id)+ if channel is None or not hasattr(channel, "fetch_message"):+ return context+ try:+ message = await channel.fetch_message(int(host_message_ts))+ except Exception as err:+ logger.warning("Failed to fetch Discord host message %s: %s", host_message_ts, err)+ return context++ thread = getattr(message, "thread", None)+ if thread is None:+ thread = await self._maybe_create_thread(message)+ if thread is None:+ return context++ return MessageContext(+ user_id=context.user_id,+ channel_id=context.channel_id,+ platform=context.platform,+ thread_id=str(thread.id),+ message_id=context.message_id,+ platform_specific=context.platform_specific,+ files=context.files,+ )++ return await self._run_on_client_loop(_impl())+def format_markdown(self, text: str) -> str:return text@@ -1097,37 +1136,59 @@ class DiscordBot(BaseIMClient):async def open_resume_session_modal(self,trigger_id: Any,- sessions_by_agent: dict,+ sessions: List[NativeResumeSession],channel_id: str,thread_id: str,host_message_ts: Optional[str] = None,):interaction = trigger_id if isinstance(trigger_id, discord.Interaction) else None+ t = lambda key, **kw: self._t(key, channel_id, **kw)options = []- for agent, mapping in sessions_by_agent.items():- for thread_key, session_id in mapping.items():- label = f"{agent}:{session_id[:24]}"- options.append(discord.SelectOption(label=label, value=f"{agent}|{session_id}"))+ for item in sessions:+ label = AgentNativeSessionService.format_display_summary(item)+ options.append(+ discord.SelectOption(+ label=label[:100],+ value=f"{item.agent}|{item.native_session_id}",+ description=AgentNativeSessionService.format_display_time(item)[:100],+ )+ )if len(options) > 25:options = options[:25]+ has_recent_sessions = bool(options)if not options:- options = [discord.SelectOption(label="No stored sessions", value="__none__")]-- agent_options = [discord.SelectOption(label=agent, value=agent) for agent in sorted(sessions_by_agent.keys())]+ options = [discord.SelectOption(label=t("modal.resume.noRecentSessionsOption"), value="__none__")]++ 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 = registered_backends or common_agents+ agent_options = [discord.SelectOption(label=agent, value=agent) for agent in allowed_agents]if len(agent_options) > 25:agent_options = agent_options[:25]if not agent_options:agent_options = [discord.SelectOption(label="default", value="opencode")]- class ManualSessionModal(discord.ui.Modal, title="Resume Session"):- session_id = discord.ui.TextInput(label="Session ID", required=True)+ class ManualSessionModal(discord.ui.Modal):+ def __init__(self):+ super().__init__(title=t("modal.resume.manualInputTitle"))+ self.session_id = discord.ui.TextInput(+ label=t("modal.resume.sessionIdLabel"),+ placeholder=t("modal.resume.pasteIdPlaceholder"),+ required=True,+ )+ self.add_item(self.session_id)async def on_submit(self, submit_interaction: discord.Interaction):if not hasattr(self, "_view"):returnview: ResumeView = getattr(self, "_view")view.manual_session = str(self.session_id.value)- await submit_interaction.response.send_message("✅ Session ID captured.", ephemeral=True)+ await submit_interaction.response.send_message(+ f"✅ {t('modal.resume.manualCaptured')}",+ ephemeral=True,+ )class ResumeView(discord.ui.View):def __init__(self, outer: DiscordBot, owner_id: Optional[str]):@@ -1136,17 +1197,22 @@ class DiscordBot(BaseIMClient):self.owner_id = owner_idself.manual_session: Optional[str] = Noneself.session_select = discord.ui.Select(- placeholder="Choose a stored session",+ placeholder=t("modal.resume.selectSession"),options=options,min_values=1,max_values=1,)self.agent_select = discord.ui.Select(- placeholder="Agent (for manual input)",+ placeholder=t("modal.resume.selectAgentBackend"),options=agent_options,min_values=1,max_values=1,)+ self.manual_button = discord.ui.Button(+ label=t("modal.resume.manualInputButton"),+ style=discord.ButtonStyle.secondary,+ )+ self.resume_button = discord.ui.Button(label=t("common.resume"), style=discord.ButtonStyle.primary)async def _defer(interaction: discord.Interaction):await interaction.response.defer()@@ -1155,8 +1221,8 @@ class DiscordBot(BaseIMClient):self.agent_select.callback = _deferself.add_item(self.session_select)self.add_item(self.agent_select)- self.add_item(discord.ui.Button(label="Enter session ID", style=discord.ButtonStyle.secondary))- self.add_item(discord.ui.Button(label="Resume", style=discord.ButtonStyle.primary))+ self.add_item(self.manual_button)+ self.add_item(self.resume_button)owner_id = str(interaction.user.id) if interaction else Noneview = ResumeView(self, owner_id)@@ -1167,6 +1233,12 @@ class DiscordBot(BaseIMClient):await manual_interaction.response.send_modal(modal)async def resume_callback(resume_interaction: discord.Interaction):+ try:+ if not resume_interaction.response.is_done():+ await resume_interaction.response.defer(ephemeral=True)+ except Exception as err:+ logger.debug("Failed to defer Discord resume interaction: %s", err)+selected = view.session_select.values[0] if view.session_select.values else Nonechosen_agent = view.agent_select.values[0] if view.agent_select.values else Nonechosen_session = None@@ -1184,21 +1256,33 @@ class DiscordBot(BaseIMClient):host_message_ts,resume_interaction.guild is None,)- await resume_interaction.response.edit_message(content="✅ Session resumed.", view=None)-- for item in view.children:- if isinstance(item, discord.ui.Button) and item.label == "Enter session ID":- item.callback = manual_callback- if isinstance(item, discord.ui.Button) and item.label == "Resume":- item.callback = resume_callback+ try:+ await self._dismiss_interaction_message(resume_interaction, " ")+ except Exception as err:+ logger.debug("Failed to dismiss Discord resume message: %s", err)++ view.manual_button.callback = manual_callback+ view.resume_button.callback = resume_callback++ intro_text = "\n".join(+ [+ f"⏮️ {t('modal.resume.title')}",+ t("modal.resume.chooseOneOf"),+ (+ t("modal.resume.discordPickOrPaste")+ if has_recent_sessions+ else t("modal.resume.noSessionsFound")+ ),+ ]+ )if interaction:- await interaction.response.send_message("⏮️ Resume session", view=view, ephemeral=True)+ await interaction.response.send_message(intro_text, view=view, ephemeral=True)else:channel = await self._fetch_channel(channel_id)if channel is None:raise RuntimeError("Discord channel not found")- await channel.send("⏮️ Resume session", view=view)+ await channel.send(intro_text, view=view)async def open_routing_modal(self,diff --git a/modules/im/feishu.py b/modules/im/feishu.pyindex d0424e036..fca6f84bc 100644--- a/modules/im/feishu.py+++ b/modules/im/feishu.py@@ -29,6 +29,7 @@ from modules.agents.opencode.utils import (resolve_opencode_allowed_providers,resolve_opencode_provider_preferences,)+from modules.agents.native_sessions import AgentNativeSessionService, NativeResumeSessionlogger = logging.getLogger(__name__)@@ -113,6 +114,7 @@ class FeishuBot(BaseIMClient):self._token_expires_at: Optional[float] = Noneself._user_info_cache: Dict[str, Dict[str, Any]] = {}self._dm_chat_ids: set = set()+ self._message_text_cache: Dict[str, str] = {}# ------------------------------------------------------------------# Lifecycle / injection@@ -159,6 +161,25 @@ class FeishuBot(BaseIMClient):def should_use_thread_for_dm_session(self) -> bool:return True+ async def prepare_resume_context(+ self,+ context: MessageContext,+ *,+ host_message_ts: Optional[str] = None,+ is_dm: bool = False,+ ) -> MessageContext:+ if context.thread_id or not host_message_ts:+ return context+ return MessageContext(+ user_id=context.user_id,+ channel_id=context.channel_id,+ platform=context.platform,+ thread_id=host_message_ts,+ message_id=context.message_id,+ platform_specific=context.platform_specific,+ files=context.files,+ )+def _get_sdk_domain(self) -> str:"""Return the lark-oapi SDK domain constant based on config."""import lark_oapi as lark@@ -513,6 +534,7 @@ class FeishuBot(BaseIMClient):root_id = context.thread_idif root_id:message_id = await self._reply_message_with_card(root_id, card_json)+ self._remember_message_text(message_id, text)if self.settings_manager:if self.sessions:self.sessions.mark_thread_active(context.user_id, context.channel_id, root_id)@@ -541,6 +563,7 @@ class FeishuBot(BaseIMClient):raise RuntimeError(f"Feishu send card failed: {response.msg}")message_id = response.data.message_id+ self._remember_message_text(message_id, text)if self.settings_manager and context.thread_id:if self.sessions:self.sessions.mark_thread_active(context.user_id, context.channel_id, context.thread_id)@@ -623,11 +646,21 @@ class FeishuBot(BaseIMClient):response.msg,)return False+ if text is not None:+ self._remember_message_text(message_id, text)return Trueexcept Exception as exc:logger.error("Error editing Feishu message %s: %s", message_id, exc)return False+ def _remember_message_text(self, message_id: Optional[str], text: Optional[str]) -> None:+ if not message_id or text is None:+ return+ self._message_text_cache[message_id] = text+ while len(self._message_text_cache) > 200:+ oldest_key = next(iter(self._message_text_cache))+ self._message_text_cache.pop(oldest_key, None)+async def _fetch_message_card_content(self, message_id: str) -> Optional[Dict[str, Any]]:"""Fetch and parse card content JSON for an existing message."""try:@@ -728,6 +761,8 @@ class FeishuBot(BaseIMClient):card text before updating the card without buttons."""display_text = text+ if display_text is None:+ display_text = self._message_text_cache.get(message_id)if display_text is None:card_content = await self._fetch_message_card_content(message_id)if card_content is None:@@ -1490,9 +1525,11 @@ class FeishuBot(BaseIMClient):context = MessageContext(user_id=user_id,channel_id=chat_id,+ platform="lark",thread_id=thread_id,message_id=message_id,platform_specific={+ "platform": "lark","event": event_data,"msg_type": msg_type,"mentions": mentions,@@ -1616,9 +1653,11 @@ class FeishuBot(BaseIMClient):context = MessageContext(user_id=user_id,channel_id=chat_id,+ platform="lark",message_id=message_id,thread_id=callback_thread_id or None,platform_specific={+ "platform": "lark","event": event_data,"action": action,"is_dm": is_dm,@@ -1925,6 +1964,7 @@ class FeishuBot(BaseIMClient):context = MessageContext(user_id=context.user_id,channel_id=context.channel_id,+ platform=context.platform,message_id=context.message_id,thread_id=embedded_thread_id,platform_specific=context.platform_specific,@@ -1977,6 +2017,7 @@ class FeishuBot(BaseIMClient):context = MessageContext(user_id=context.user_id,channel_id=context.channel_id,+ platform=context.platform,message_id=context.message_id,thread_id=embedded_thread_id,platform_specific=context.platform_specific,@@ -2587,8 +2628,8 @@ class FeishuBot(BaseIMClient):channel_id: str = None,thread_id: str = None,host_message_ts: str = None,- # Legacy compat — ignored; use sessions_by_agent instead- sessions: list = None,+ # Legacy compat — ignored; use sessions instead+ sessions: List[NativeResumeSession] | None = None,**kwargs,):"""Send an interactive JSON 2.0 form card for session resume.@@ -2598,6 +2639,8 @@ class FeishuBot(BaseIMClient):"""t = lambda key, **kw: self._t(key, channel_id, **kw)+ if sessions is None:+ sessions = []if sessions_by_agent is None:sessions_by_agent = {}@@ -2615,26 +2658,42 @@ class FeishuBot(BaseIMClient):session_options = []total = 0max_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 sessions:+ for item in sessions: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]}"+ if item.agent not in allowed_agents:+ continue+ label = (+ f"{AgentNativeSessionService.format_display_summary(item)}"+ f" · {AgentNativeSessionService.format_display_time(item)}"+ )session_options.append({- "text": {"tag": "plain_text", "content": label},- "value": f"{agent_name}|{session_id}",+ "text": {"tag": "plain_text", "content": label[:120]},+ "value": f"{item.agent}|{item.native_session_id}",})total += 1- if total >= max_options:- break+ else:+ 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+ label = f"[{agent_name}] {session_id[:24]}"+ session_options.append(+ {+ "text": {"tag": "plain_text", "content": label},+ "value": f"{agent_name}|{session_id}",+ }+ )+ total += 1+ if total >= max_options:+ break# --- Build form elements ---form_elements: list = []diff --git a/modules/im/multi.py b/modules/im/multi.pyindex ef1e7db70..302c508c5 100644--- a/modules/im/multi.py+++ b/modules/im/multi.py@@ -250,6 +250,23 @@ class MultiIMClient(BaseIMClient):parse_mode=parse_mode,)+ async def remove_inline_keyboard(+ self,+ context: MessageContext,+ message_id: str,+ text: Optional[str] = None,+ parse_mode: Optional[str] = None,+ ) -> bool:+ return await self.get_client_for_context(context).remove_inline_keyboard(+ context,+ message_id,+ text=text,+ parse_mode=parse_mode,+ )++ async def dismiss_form_message(self, context: MessageContext) -> None:+ await self.get_client_for_context(context).dismiss_form_message(context)+async def answer_callback(self, callback_id: str, text: Optional[str] = None, show_alert: bool = False) -> bool:return await self.clients[self.primary_platform].answer_callback(callback_id, text=text, show_alert=show_alert)diff --git a/modules/im/slack.py b/modules/im/slack.pyindex e5cc5d366..d00a968a3 100644--- a/modules/im/slack.py+++ b/modules/im/slack.py@@ -1,5 +1,6 @@import asyncioimport hashlib+import jsonimport loggingimport reimport time@@ -33,6 +34,7 @@ from modules.agents.opencode.utils import (resolve_opencode_allowed_providers,resolve_opencode_provider_preferences,)+from modules.agents.native_sessions import AgentNativeSessionService, NativeResumeSessionlogger = logging.getLogger(__name__)@@ -132,6 +134,25 @@ class SlackBot(BaseIMClient):"""Slack DMs also support thread-based replies."""return True+ async def prepare_resume_context(+ self,+ context: MessageContext,+ *,+ host_message_ts: Optional[str] = None,+ is_dm: bool = False,+ ) -> MessageContext:+ if context.thread_id or not host_message_ts:+ return context+ return MessageContext(+ user_id=context.user_id,+ channel_id=context.channel_id,+ platform=context.platform,+ thread_id=host_message_ts,+ message_id=context.message_id,+ platform_specific=context.platform_specific,+ files=context.files,+ )+def _ensure_clients(self):"""Ensure web and socket clients are initialized"""if self.web_client is None:@@ -2279,7 +2300,7 @@ class SlackBot(BaseIMClient):async def open_resume_session_modal(self,trigger_id: str,- sessions_by_agent: Dict[str, Dict[str, str]],+ sessions: List[NativeResumeSession],channel_id: Optional[str],thread_id: Optional[str],host_message_ts: Optional[str],@@ -2303,38 +2324,24 @@ class SlackBot(BaseIMClient):})- session_option_groups = []+ session_options = []total_session_options = 0max_session_options = 100- for agent, mapping in sessions_by_agent.items():- if agent not in allowed_agents:- continue- if not mapping:- continue- options = []- for thread, session_id in mapping.items():- if total_session_options >= max_session_options:- break- 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},- }- )- total_session_options += 1- if options:- session_option_groups.append(- {- "label": {"type": "plain_text", "text": agent.capitalize(), "emoji": True},- "options": options,- }- )+ for item in sessions:if total_session_options >= max_session_options:break+ if item.agent not in allowed_agents:+ continue+ label = AgentNativeSessionService.format_display_summary(item)+ desc = AgentNativeSessionService.format_display_time(item)+ session_options.append(+ {+ "text": {"type": "plain_text", "text": label[:75], "emoji": True},+ "value": f"{item.agent}|{item.native_session_id}",+ "description": {"type": "plain_text", "text": desc[:75], "emoji": True},+ }+ )+ total_session_options += 1blocks: list = [{@@ -2346,7 +2353,7 @@ class SlackBot(BaseIMClient):},]- if session_option_groups:+ if session_options:blocks.append({"type": "input",@@ -2356,7 +2363,7 @@ class SlackBot(BaseIMClient):"element": {"type": "static_select","action_id": "session_select",- "option_groups": session_option_groups,+ "options": session_options,"placeholder": {"type": "plain_text","text": self._t("modal.resume.selectSession"),@@ -2422,7 +2429,6 @@ class SlackBot(BaseIMClient):"default_agent": agent_options[0]["value"] if agent_options else "opencode","agent_options": agent_options, # Store for dynamic update}- import jsonview = {"type": "modal",@@ -2442,8 +2448,6 @@ class SlackBot(BaseIMClient):async def _handle_resume_modal_manual_input(self, view: Dict[str, Any], action: Dict[str, Any]):"""Handle manual_input changes in resume_session_modal - dynamically show/hide agent_block."""- import json-self._ensure_clients()view_id = view.get("id")diff --git a/modules/session_manager.py b/modules/session_manager.pyindex 35141a4d5..0b23374c2 100644--- a/modules/session_manager.py+++ b/modules/session_manager.py@@ -3,7 +3,7 @@ import loggingfrom dataclasses import dataclass, fieldfrom typing import Dict, List, Optional, Union, Anyfrom datetime import datetime-from claude_agent_sdk import ClaudeSDKClient+from modules.claude_sdk_compat import ClaudeSDKClientlogger = logging.getLogger(__name__)@@ -135,4 +135,4 @@ class SessionManager:del self.sessions[user_id]logger.info(f"Cleaned up inactive session for user {user_id}")- return len(to_remove)\ No newline at end of file+ return len(to_remove)diff --git a/tests/test_feishu_routing_card.py b/tests/test_feishu_routing_card.pyindex f03ccf2eb..b5244008d 100644--- a/tests/test_feishu_routing_card.py+++ b/tests/test_feishu_routing_card.py@@ -165,6 +165,46 @@ class FeishuRoutingCardTests(unittest.IsolatedAsyncioTestCase):reasoning_values = [option["value"] for option in reasoning_select["options"]]self.assertIn("max", reasoning_values)+ async def test_quick_reply_card_action_sets_lark_platform(self):+ bot = self._make_bot()+ bot.check_authorization = lambda **kwargs: AuthResult(allowed=True)+ bot.on_callback_query_callback = AsyncMock()++ event = {+ "operator": {"open_id": "user"},+ "context": {"open_message_id": "om_123", "open_chat_id": "chat"},+ "action": {+ "tag": "button",+ "value": {"key": "quick_reply:继续"},+ },+ }++ await bot._async_handle_card_action(event)++ bot.on_callback_query_callback.assert_awaited_once()+ callback_context, callback_data = bot.on_callback_query_callback.await_args.args+ self.assertEqual(callback_data, "quick_reply:继续")+ self.assertEqual(callback_context.platform, "lark")+ self.assertEqual(callback_context.platform_specific["platform"], "lark")++ async def test_remove_inline_keyboard_prefers_cached_text(self):+ bot = self._make_bot()+ bot.edit_message = AsyncMock(return_value=True)+ bot._fetch_message_card_content = AsyncMock(return_value=None)+ bot._message_text_cache["om_123"] = "Original body"++ ok = await bot.remove_inline_keyboard(+ MessageContext(user_id="user", channel_id="chat", platform="lark"),+ "om_123",+ )++ self.assertTrue(ok)+ bot.edit_message.assert_awaited_once()+ _, kwargs = bot.edit_message.await_args+ self.assertEqual(kwargs["text"], "Original body")+ self.assertIsNone(kwargs["keyboard"])+ bot._fetch_message_card_content.assert_not_awaited()+if __name__ == "__main__":unittest.main()diff --git a/tests/test_message_handler_typing.py b/tests/test_message_handler_typing.pyindex cc1b49700..dc7926d76 100644--- a/tests/test_message_handler_typing.py+++ b/tests/test_message_handler_typing.py@@ -16,6 +16,7 @@ from modules.im import MessageContextdef _load_message_handler_class():with patch.dict(sys.modules, {}, clear=False):agents_module = types.ModuleType("modules.agents")+ agents_module.__path__ = [str(ROOT / "modules" / "agents")]@dataclassclass _AgentRequest:@@ -38,6 +39,9 @@ def _load_message_handler_class():setattr(agents_module, "AgentRequest", _AgentRequest)sys.modules["modules.agents"] = agents_module+ agents_base_module = types.ModuleType("modules.agents.base")+ setattr(agents_base_module, "AgentRequest", _AgentRequest)+ sys.modules["modules.agents.base"] = agents_base_modulecore_pkg = types.ModuleType("core")core_pkg.__path__ = [str(ROOT / "core")]@@ -91,6 +95,7 @@ class _StubIMClient:self.clear_calls = []self.reactions = []self.sent_messages = []+ self.removed_keyboards = []self.formatter = Nonedef should_use_thread_for_reply(self):@@ -125,6 +130,10 @@ class _StubIMClient:self.sent_messages.append((context.channel_id, text))return "msg-1"+ async def remove_inline_keyboard(self, context, message_id, text=None, parse_mode=None):+ self.removed_keyboards.append((context.channel_id, context.platform, message_id))+ return True+class _StubAgentService:def __init__(self):@@ -272,6 +281,26 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):platform="lark",)+ async def test_quick_reply_callback_preserves_platform(self):+ controller = _StubController(platform="slack", ack_mode="reaction", typing_result=True)+ handler = MessageHandler(controller)+ handler.handle_user_message = AsyncMock() # type: ignore[method-assign]+ context = MessageContext(+ user_id="u1",+ channel_id="chat1",+ message_id="om_123",+ platform="lark",+ platform_specific={"platform": "lark", "is_dm": False},+ )++ await handler.handle_callback_query(context, "quick_reply:继续")++ self.assertEqual(controller.im_client.removed_keyboards, [("chat1", "lark", "om_123")])+ handler.handle_user_message.assert_awaited_once()+ forwarded_context, forwarded_text = handler.handle_user_message.await_args.args+ self.assertEqual(forwarded_text, "继续")+ self.assertEqual(forwarded_context.platform, "lark")+if __name__ == "__main__":unittest.main()diff --git a/tests/test_multi_platform_runtime.py b/tests/test_multi_platform_runtime.pyindex 1a85102f3..cff91065a 100644--- a/tests/test_multi_platform_runtime.py+++ b/tests/test_multi_platform_runtime.py@@ -24,6 +24,8 @@ class _StubClient(BaseIMClient):super().__init__(_StubConfig())self.name = nameself.sent = []+ self.removed = []+ self.dismissed = []async def send_message(self, context, text, parse_mode=None, reply_to=None):self.sent.append((context.platform, context.channel_id, text))@@ -35,6 +37,13 @@ class _StubClient(BaseIMClient):async def edit_message(self, context, message_id, text=None, keyboard=None, parse_mode=None):return True+ async def remove_inline_keyboard(self, context, message_id, text=None, parse_mode=None):+ self.removed.append((context.platform, message_id, text))+ return True++ async def dismiss_form_message(self, context):+ self.dismissed.append((context.platform, context.message_id))+async def answer_callback(self, callback_id, text=None, show_alert=False):return True@@ -153,6 +162,37 @@ def test_multi_im_client_routes_download_by_file_info_platform():assert wechat.sent == [("download_to_path", "wechat", "/tmp/a.jpg")]+def test_multi_im_client_routes_remove_inline_keyboard_by_context_platform():+ slack = _StubClient("slack")+ lark = _StubClient("lark")+ client = MultiIMClient({"slack": slack, "lark": lark}, primary_platform="slack")++ asyncio.run(+ client.remove_inline_keyboard(+ MessageContext(user_id="u", channel_id="c", platform="lark"),+ "om_123",+ )+ )++ assert slack.removed == []+ assert lark.removed == [("lark", "om_123", None)]+++def test_multi_im_client_routes_dismiss_form_message_by_context_platform():+ slack = _StubClient("slack")+ lark = _StubClient("lark")+ client = MultiIMClient({"slack": slack, "lark": lark}, primary_platform="slack")++ asyncio.run(+ client.dismiss_form_message(+ MessageContext(user_id="u", channel_id="c", platform="lark", message_id="om_456")+ )+ )++ assert slack.dismissed == []+ assert lark.dismissed == [("lark", "om_456")]++def test_multi_im_client_on_ready_fires_only_after_all_platforms():"""on_ready callback must wait for all platform clients to be ready."""slack = _StubClient("slack")diff --git a/tests/test_native_session_providers.py b/tests/test_native_session_providers.pynew file mode 100644index 000000000..c19a16157--- /dev/null+++ b/tests/test_native_session_providers.py@@ -0,0 +1,82 @@+from pathlib import Path+from types import SimpleNamespace++from modules.agents.native_sessions.base import build_resume_preview, build_tail_preview+from modules.agents.native_sessions.claude import ClaudeNativeSessionProvider+from modules.agents.native_sessions.service import AgentNativeSessionService+from modules.agents.native_sessions.types import NativeResumeSession+++def test_claude_provider_falls_back_to_history_jsonl(tmp_path: Path) -> None:+ projects_root = tmp_path / "projects"+ history_path = tmp_path / "history.jsonl"+ projects_root.mkdir(parents=True, exist_ok=True)++ working_path = "/Users/cyh/vibe-remote"+ history_path.write_text(+ "\n".join(+ [+ '{"display":"old prompt","timestamp":1766078000000,"project":"/Users/cyh/vibe-remote","sessionId":"sess_a"}',+ '{"display":"latest prompt","timestamp":1766079000000,"project":"/Users/cyh/vibe-remote","sessionId":"sess_a"}',+ '{"display":"other project","timestamp":1766079100000,"project":"/Users/cyh/other","sessionId":"sess_b"}',+ ]+ ),+ encoding="utf-8",+ )++ provider = ClaudeNativeSessionProvider(root=str(projects_root), history_path=str(history_path))++ items = provider.list_metadata(working_path)++ assert [item.native_session_id for item in items] == ["sess_a"]+ hydrated = provider.hydrate_preview(items[0])+ assert hydrated.last_agent_message == "latest prompt"+ assert hydrated.last_agent_tail == "latest prompt"+++def test_native_session_service_preserves_agent_visibility_when_limited() -> None:+ def _item(agent: str, prefix: str, session_id: str, sort_ts: float) -> NativeResumeSession:+ return NativeResumeSession(+ agent=agent,+ agent_prefix=prefix,+ native_session_id=session_id,+ working_path="/tmp/project",+ created_at=None,+ updated_at=None,+ sort_ts=sort_ts,+ last_agent_message=session_id,+ last_agent_tail=f"...{session_id[-4:]}",+ )++ oc_provider = SimpleNamespace(+ agent_name="opencode",+ list_metadata=lambda working_path: [_item("opencode", "oc", f"oc_{i}", 200 - i) for i in range(5)],+ hydrate_preview=lambda item: item,+ )+ cc_provider = SimpleNamespace(+ agent_name="claude",+ list_metadata=lambda working_path: [_item("claude", "cc", "cc_1", 50)],+ hydrate_preview=lambda item: item,+ )+ cx_provider = SimpleNamespace(+ agent_name="codex",+ list_metadata=lambda working_path: [_item("codex", "cx", f"cx_{i}", 100 - i) for i in range(5)],+ hydrate_preview=lambda item: item,+ )++ service = AgentNativeSessionService(providers=[oc_provider, cc_provider, cx_provider])++ items = service.list_recent_sessions("/tmp/project", limit=5)++ assert len(items) == 5+ assert {item.agent for item in items} == {"opencode", "claude", "codex"}+++def test_build_tail_preview_strips_edge_symbols() -> None:+ assert build_tail_preview("前文很多很多很多。**最后一句话???**") == "...很多。**最后一句话"+++def test_build_resume_preview_preserves_line_breaks() -> None:+ text = "第一段第一行\n第二行\n\n第三行\n---\n[button]"++ assert build_resume_preview(text, limit=200) == "第一段第一行\n第二行\n\n第三行"diff --git a/tests/test_reply_enhancer_platform.py b/tests/test_reply_enhancer_platform.pyindex 26a6010ac..6cac79218 100644--- a/tests/test_reply_enhancer_platform.py+++ b/tests/test_reply_enhancer_platform.py@@ -92,6 +92,21 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):[("C1", "Done.", "markdown")],)+ async def test_lark_quick_reply_buttons_use_vertical_layout(self):+ controller = _StubController("lark")+ dispatcher = ConsolidatedMessageDispatcher(controller)+ context = MessageContext(user_id="U1", channel_id="C1", platform="lark")++ await dispatcher.emit_agent_message(+ context,+ "result",+ "Done.\n---\n[继续] | [提交PR]",+ )++ self.assertEqual(len(controller.im_client.sent_button_messages), 1)+ keyboard = controller.im_client.sent_button_messages[0][3]+ self.assertEqual([[button.text for button in row] for row in keyboard.buttons], [["继续"], ["提交PR"]])+if __name__ == "__main__":unittest.main()diff --git a/tests/test_resume_session.py b/tests/test_resume_session.pyindex a68699e08..c0ae9dfb3 100644--- a/tests/test_resume_session.py+++ b/tests/test_resume_session.py@@ -3,10 +3,15 @@ import unittestfrom core.controller import Controllerfrom core.handlers.command_handlers import CommandHandlersfrom core.handlers.session_handler import SessionHandler+from modules.agents.native_sessions import NativeResumeSessionfrom modules.im import MessageContext-from modules.im.slack import SlackBotfrom config.v2_config import SlackConfig+try:+ from modules.im.slack import SlackBot+except ModuleNotFoundError:+ SlackBot = None+class _StubSettingsManager:def __init__(self):@@ -34,19 +39,44 @@ class _StubIMClient:def __init__(self):self.messages = []self.resume_calls = []+ self.prepared_context = Noneasync def send_message(self, context, text, parse_mode=None):ts = f"T{len(self.messages) + 1}"self.messages.append((context.channel_id, context.thread_id, text, ts))return ts- async def open_resume_session_modal(self, trigger_id, sessions_by_agent, channel_id, thread_id, host_message_ts):- self.resume_calls.append((trigger_id, sessions_by_agent, channel_id, thread_id, host_message_ts))+ async def open_resume_session_modal(self, trigger_id, sessions, channel_id, thread_id, host_message_ts):+ self.resume_calls.append((trigger_id, sessions, channel_id, thread_id, host_message_ts))++ async def run_on_client_loop(self, coro):+ return await coro++ async def prepare_resume_context(self, context, host_message_ts=None, is_dm=False):+ return self.prepared_context or context+++class _StubNativeSessionService:+ def __init__(self, sessions=None):+ self.sessions = sessions or []+ self.calls = []++ def list_recent_sessions(self, working_path: str, limit: int = 100):+ self.calls.append((working_path, limit))+ return list(self.sessions)++ def get_session(self, working_path: str, agent: str, native_session_id: str):+ for item in self.sessions:+ if item.agent == agent and item.native_session_id == native_session_id:+ return item+ return Noneclass _StubConfig:def __init__(self, platform="slack"):self.platform = platform+ self.language = "en"+ self.claude = type("ClaudeCfg", (), {"cwd": "/tmp"})()class _StubController(Controller):@@ -64,6 +94,7 @@ class _StubController(Controller):self.receiver_tasks = {}self.stored_session_mappings = {}self.agent_service = type("A", (), {"agents": {"claude": object(), "codex": object()}})()+ self.native_session_service = _StubNativeSessionService()self.command_handler = CommandHandlers(self)self.session_handler = SessionHandler(self)@@ -73,6 +104,9 @@ class _StubController(Controller):def _get_session_key(self, context: MessageContext) -> str:return f"{getattr(context, 'platform', None) or 'test'}::{self._get_settings_key(context)}"+ def get_cwd(self, context: MessageContext) -> str:+ return "/Users/cyh/vibe-remote"+class ResumeSessionTests(unittest.IsolatedAsyncioTestCase):async def test_handle_resume_session_submission_threads(self):@@ -80,6 +114,21 @@ class ResumeSessionTests(unittest.IsolatedAsyncioTestCase):im_client = _StubIMClient()ctrl = _StubController()ctrl.init_minimal(im_client, settings, _StubConfig())+ ctrl.native_session_service = _StubNativeSessionService(+ [+ NativeResumeSession(+ agent="claude",+ agent_prefix="cc",+ native_session_id="sess_abc",+ working_path="/Users/cyh/vibe-remote",+ created_at=None,+ updated_at=None,+ sort_ts=10.0,+ last_agent_message="The latest Claude answer ends with a concise handoff.",+ last_agent_tail="...concise handoff",+ )+ ]+ )await ctrl.session_handler.handle_resume_session_submission(user_id="U123",@@ -91,10 +140,13 @@ class ResumeSessionTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(settings.set_calls,- [("C111", "claude", "slack_169999.123", "sess_abc")],+ [("slack::C111", "claude", "slack_169999.123", "sess_abc")],)self.assertEqual(settings.mark_calls, [("U123", "C111", "169999.123")])+ self.assertEqual(len(im_client.messages), 2)self.assertIn("sess_abc", im_client.messages[0][2])+ self.assertIn("The latest Claude answer ends with a concise handoff", im_client.messages[0][2])+ self.assertIn("Reply in this thread", im_client.messages[1][2])async def test_handle_resume_session_submission_dm_falls_back_to_channel(self):settings = _StubSettingsManager()@@ -111,8 +163,11 @@ class ResumeSessionTests(unittest.IsolatedAsyncioTestCase):)# No thread provided -> new confirmation message anchor used- self.assertEqual(settings.set_calls, [("DXYZ", "codex", "slack_T1", "sess_dm")])+ self.assertEqual(settings.set_calls, [("slack::DXYZ", "codex", "slack_T1", "sess_dm")])self.assertEqual(settings.mark_calls, [("U999", "DXYZ", "T1")])+ self.assertEqual(len(im_client.messages), 2)+ self.assertIn("sess_dm", im_client.messages[0][2])+ self.assertIn("Send your next message directly", im_client.messages[1][2])async def test_handle_resume_session_submission_discord_dm_uses_channel_session_key(self):settings = _StubSettingsManager()@@ -130,7 +185,7 @@ class ResumeSessionTests(unittest.IsolatedAsyncioTestCase):is_dm=True,)- self.assertEqual(settings.set_calls, [("U999", "codex", "discord_DMCHAN", "sess_dm")])+ self.assertEqual(settings.set_calls, [("discord::U999", "codex", "discord_DMCHAN", "sess_dm")])self.assertEqual(settings.mark_calls, [("U999", "DMCHAN", "T1")])async def test_handle_resume_session_submission_lark_dm_uses_thread_session_key(self):@@ -149,14 +204,64 @@ class ResumeSessionTests(unittest.IsolatedAsyncioTestCase):is_dm=True,)- self.assertEqual(settings.set_calls, [("U888", "claude", "lark_root_123", "sess_lark_dm")])+ self.assertEqual(settings.set_calls, [("lark::U888", "claude", "lark_root_123", "sess_lark_dm")])self.assertEqual(settings.mark_calls, [("U888", "DMCHAT", "root_123")])+ self.assertEqual(len(im_client.messages), 2)+ self.assertIn("Reply to this message", im_client.messages[1][2])++ async def test_handle_resume_session_submission_uses_prepared_thread_context(self):+ settings = _StubSettingsManager()+ im_client = _StubIMClient()+ ctrl = _StubController()+ ctrl.init_minimal(im_client, settings, _StubConfig(platform="discord"))+ ctrl.im_client.should_use_thread_for_reply = lambda: True+ im_client.prepared_context = MessageContext(+ user_id="U777",+ channel_id="C777",+ platform="discord",+ thread_id="SUB123",+ message_id="HOST1",+ platform_specific={"is_dm": False},+ )++ await ctrl.session_handler.handle_resume_session_submission(+ user_id="U777",+ channel_id="C777",+ thread_id=None,+ agent="codex",+ session_id="sess_sub",+ host_message_ts="HOST1",+ is_dm=False,+ platform="discord",+ )++ self.assertEqual(settings.set_calls, [("discord::C777", "codex", "discord_SUB123", "sess_sub")])+ self.assertEqual(settings.mark_calls, [("U777", "C777", "SUB123")])+ self.assertEqual(len(im_client.messages), 2)+ self.assertEqual(im_client.messages[0][1], None)+ self.assertEqual(im_client.messages[1][1], "SUB123")+ self.assertIn("Reply in the subchannel", im_client.messages[1][2])async def test_command_handlers_handle_resume_opens_modal(self):settings = _StubSettingsManager()im_client = _StubIMClient()ctrl = _StubController()ctrl.init_minimal(im_client, settings, _StubConfig(platform="slack"))+ ctrl.native_session_service = _StubNativeSessionService(+ [+ NativeResumeSession(+ agent="codex",+ agent_prefix="cx",+ native_session_id="thread_123",+ working_path="/Users/cyh/vibe-remote",+ created_at=None,+ updated_at=None,+ sort_ts=100.0,+ last_agent_message="done",+ last_agent_tail="...done",+ )+ ]+ )ctx = MessageContext(user_id="U1",@@ -168,13 +273,16 @@ class ResumeSessionTests(unittest.IsolatedAsyncioTestCase):await ctrl.command_handler.handle_resume(ctx)- # One info message about missing sessions- self.assertEqual(len(im_client.messages), 1)- self.assertIn("No stored sessions", im_client.messages[0][2])- # Modal opened with empty sessions map and host ts- self.assertEqual(im_client.resume_calls, [("TRIG", {}, "CCHAN", "TH1", "TS1")])+ self.assertEqual(im_client.messages, [])+ self.assertEqual(len(im_client.resume_calls), 1)+ trigger_id, sessions, channel_id, thread_id, host_ts = im_client.resume_calls[0]+ self.assertEqual((trigger_id, channel_id, thread_id, host_ts), ("TRIG", "CCHAN", "TH1", "TS1"))+ self.assertEqual([item.native_session_id for item in sessions], ["thread_123"])+ self.assertEqual(ctrl.native_session_service.calls, [("/Users/cyh/vibe-remote", 100)])async def test_resume_modal_manual_session_uses_manual_agent(self):+ if SlackBot is None:+ self.skipTest("Slack dependencies not installed in this environment")cfg = SlackConfig(bot_token="xoxb-test")slack = SlackBot(cfg)received = {}diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex 82dbccc22..ee1db06c0 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -51,8 +51,11 @@"settingsUpdated": "Settings updated successfully!","cwdChanged": "Working directory changed to:\n`{path}`","sessionResumed": "Resumed {agent} session.\nSession ID: `{sessionId}`",- "sessionResumedTip1": "💬 *Click this message and reply in the thread sidebar* to continue with this session.",- "sessionResumedTip2": "_(Sending a new message in the channel will start a fresh session.)_",+ "sessionResumedContinueThread": "💬 *Reply in this thread* to continue with this session.",+ "sessionResumedContinueFeishuThread": "💬 *Reply to this message* to continue with this session.",+ "sessionResumedContinueDiscordThread": "💬 *Reply in the subchannel to this message* to continue with this session.",+ "sessionResumedContinueDirect": "💬 *Send your next message directly* to continue with this session.",+ "sessionResumedThreadFreshTip": "_(Sending a new message in the main channel will start a fresh session.)_","routingUpdated": "Agent routing updated!"},"settings": {@@ -128,15 +131,22 @@},"resume": {"title": "Resume Session",- "description": "Select a saved session or paste a session ID to resume work in this thread.",- "pickExisting": "Pick an existing session",+ "description": "Select a recent agent session from the current working directory, or paste a session ID to resume work in this thread.",+ "chooseOneOf": "Choose one of the two options below:",+ "discordPickOrPaste": "Select a recent session below, or use the OR button to paste a Session ID manually.",+ "pickExisting": "Pick a recent session","selectSession": "Select a session","pasteId": "Or paste a session ID","pasteIdPlaceholder": "e.g., ses_12345",+ "sessionIdLabel": "Session ID",+ "manualInputTitle": "Paste Session ID",+ "manualInputButton": "OR: Paste Session ID",+ "manualCaptured": "Session ID captured. Click Resume to continue.","agentBackend": "Agent backend","selectAgentBackend": "Select agent backend",- "showingFirst100": "Showing the first 100 saved sessions. Paste a session ID below for others.",- "noSessionsFound": "No stored sessions found. Paste a session ID below to resume."+ "showingFirst100": "Showing the first 100 recent sessions for this working directory. Paste a session ID below for others.",+ "noSessionsFound": "No recent agent sessions found for this working directory. Use the OR button below to paste a session ID and resume manually.",+ "noRecentSessionsOption": "No recent sessions"},"routing": {"title": "Agent Settings",@@ -200,7 +210,7 @@"resume": {"slackOnly": "Resume is currently available only on Slack. Continue in the same thread to auto-resume.","clickButton": "Please click the Resume button inside Slack to open the picker.",- "noStoredSessions": "No stored sessions found. You can still paste a session ID manually in the resume modal."+ "noStoredSessions": "No recent agent sessions found for this working directory. You can still paste a session ID manually in the resume modal."},"stop": {"noActiveSession": "No active session to stop for this channel."diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex 01aae9d71..e1f894f81 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -51,8 +51,11 @@"settingsUpdated": "设置更新成功!","cwdChanged": "工作目录已更改为:\n`{path}`","sessionResumed": "已恢复 {agent} 会话。\n会话ID:`{sessionId}`",- "sessionResumedTip1": "💬 *点击此消息并在右侧线程中回复* 以继续该会话。",- "sessionResumedTip2": "_(在频道中发送新消息将开始新的会话。)_",+ "sessionResumedContinueThread": "💬 *请直接在这个线程里继续回复* 以继续该会话。",+ "sessionResumedContinueFeishuThread": "💬 *请直接回复这条消息* 以继续该会话。",+ "sessionResumedContinueDiscordThread": "💬 *请在子区回复这条消息* 以继续该会话。",+ "sessionResumedContinueDirect": "💬 *接下来直接发送消息* 即可继续该会话。",+ "sessionResumedThreadFreshTip": "_(在主会话中发送新消息将开始新的会话。)_","routingUpdated": "Agent设置已更新!"},"settings": {@@ -128,15 +131,22 @@},"resume": {"title": "恢复会话",- "description": "选择一个已保存的会话或粘贴会话 ID 以在此线程中继续工作。",- "pickExisting": "选择一个已有会话",+ "description": "选择当前工作目录下最近的 Agent 会话,或粘贴会话 ID 以在此线程中继续工作。",+ "chooseOneOf": "请从下面两种方式中二选一:",+ "discordPickOrPaste": "可以直接选择一个最近会话,或点击带 OR 的按钮手动粘贴 Session ID。",+ "pickExisting": "选择一个最近会话","selectSession": "选择一个会话","pasteId": "或粘贴会话 ID","pasteIdPlaceholder": "例如 ses_12345",+ "sessionIdLabel": "会话 ID",+ "manualInputTitle": "粘贴会话 ID",+ "manualInputButton": "OR:粘贴 Session ID",+ "manualCaptured": "已记录 Session ID,请点击“恢复”继续。","agentBackend": "Agent 后端","selectAgentBackend": "选择 Agent 后端",- "showingFirst100": "显示前 100 个已保存的会话。如需其他会话,请在下方粘贴会话 ID。",- "noSessionsFound": "未找到已存储的会话。请在下方粘贴会话 ID 以恢复。"+ "showingFirst100": "显示当前工作目录下最近的前 100 个会话。如需其他会话,请在下方粘贴会话 ID。",+ "noSessionsFound": "当前工作目录下未找到最近的 Agent 会话。请点击下方带 OR 的按钮,手动粘贴 Session ID 进行恢复。",+ "noRecentSessionsOption": "没有最近会话"},"routing": {"title": "Agent 设置",@@ -200,7 +210,7 @@"resume": {"slackOnly": "恢复功能目前仅在 Slack 上可用。在同一线程中继续可自动恢复。","clickButton": "请在 Slack 中点击“恢复”按钮打开选择器。",- "noStoredSessions": "未找到已存储的会话。您仍可以在恢复对话框中手动粘贴会话 ID。"+ "noStoredSessions": "当前工作目录下未找到最近的 Agent 会话。您仍可以在恢复对话框中手动粘贴会话 ID。"},"stop": {"noActiveSession": "此频道没有要停止的活动会话。"