Skip to content

armgit / avibe

Public Imported from GitHub
0

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

feat(opencode): attach long results for Slack

cyhhaobaf8904fb2d6
diff --git a/core/controller.py b/core/controller.py
index 6180822eb..d0ac9d81d 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -220,6 +220,21 @@ class Controller:
return 3200
return 8000
+ def _get_result_max_chars(self) -> int:
+ if self.config.platform == "slack":
+ return 30000
+ if self.config.platform == "telegram":
+ return 3200
+ return 8000
+
+ def _build_result_summary(self, text: str, max_chars: int) -> str:
+ if len(text) <= max_chars:
+ return text
+ prefix = "结果过长,以下为摘要:\n\n"
+ suffix = "\n\n…(已截断,完整内容见附件 result.md)"
+ keep = max(0, max_chars - len(prefix) - len(suffix))
+ return f"{prefix}{text[:keep]}{suffix}"
+
def _truncate_consolidated(self, text: str, max_chars: int) -> str:
if len(text) <= max_chars:
return text
@@ -305,9 +320,32 @@ class Controller:
if canonical_type == "result":
target_context = self._get_target_context(context)
+ if len(text) <= self._get_result_max_chars():
+ await self.im_client.send_message(
+ target_context, text, parse_mode=parse_mode
+ )
+ return
+
+ summary = self._build_result_summary(text, self._get_result_max_chars())
await self.im_client.send_message(
- target_context, text, parse_mode=parse_mode
+ target_context, summary, parse_mode=parse_mode
)
+
+ if self.config.platform == "slack" and hasattr(self.im_client, "upload_markdown"):
+ try:
+ await self.im_client.upload_markdown(
+ target_context,
+ title="result.md",
+ content=text,
+ filetype="markdown",
+ )
+ except Exception as err:
+ logger.warning(f"Failed to upload result attachment: {err}")
+ await self.im_client.send_message(
+ target_context,
+ "无法上传附件(缺少 files:write 权限或上传失败)。需要我改成分条发送吗?",
+ parse_mode=parse_mode,
+ )
return
if canonical_type not in {"system", "assistant", "toolcall"}:
diff --git a/modules/agents/opencode_agent.py b/modules/agents/opencode_agent.py
index 8cbcedef4..9b56ac08c 100644
--- a/modules/agents/opencode_agent.py
+++ b/modules/agents/opencode_agent.py
@@ -825,30 +825,67 @@ class OpenCodeAgent(BaseAgent):
self._session_locks[base_session_id] = asyncio.Lock()
return self._session_locks[base_session_id]
+ async def _wait_for_session_idle(
+ self,
+ server: OpenCodeServerManager,
+ session_id: str,
+ directory: str,
+ timeout_seconds: float = 15.0,
+ ) -> None:
+ deadline = time.monotonic() + timeout_seconds
+ while time.monotonic() < deadline:
+ try:
+ messages = await server.list_messages(session_id, directory)
+ except Exception as err:
+ logger.debug(f"Failed to poll OpenCode session {session_id} for idle: {err}")
+ await asyncio.sleep(1.0)
+ continue
+
+ in_progress = False
+ for message in messages:
+ info = message.get("info", {})
+ if info.get("role") != "assistant":
+ continue
+ time_info = info.get("time") or {}
+ if not time_info.get("completed"):
+ in_progress = True
+ break
+
+ if not in_progress:
+ return
+
+ await asyncio.sleep(1.0)
+
+ logger.warning(
+ "OpenCode session %s did not reach idle state within %.1fs",
+ session_id,
+ timeout_seconds,
+ )
+
async def handle_message(self, request: AgentRequest) -> None:
lock = self._get_session_lock(request.base_session_id)
async with lock:
existing_task = self._active_requests.get(request.base_session_id)
if existing_task and not existing_task.done():
- await self.controller.emit_agent_message(
- request.context,
- "notify",
- "OpenCode is already processing a task in this thread. "
- "Cancelling the previous run...",
+ logger.info(
+ "OpenCode session %s already running; cancelling before new request",
+ request.base_session_id,
)
req_info = self._request_sessions.get(request.base_session_id)
if req_info:
server = await self._get_server()
await server.abort_session(req_info[0], req_info[1])
+ await self._wait_for_session_idle(
+ server, req_info[0], req_info[1]
+ )
existing_task.cancel()
try:
await existing_task
except asyncio.CancelledError:
pass
- await self.controller.emit_agent_message(
- request.context,
- "notify",
- "Previous OpenCode task cancelled. Starting the new request...",
+ logger.info(
+ "OpenCode session %s cancelled; continuing with new request",
+ request.base_session_id,
)
pending = self._pending_questions.get(request.base_session_id)
diff --git a/modules/im/base.py b/modules/im/base.py
index 3d5e2cad5..6a7a159ce 100644
--- a/modules/im/base.py
+++ b/modules/im/base.py
@@ -154,6 +154,16 @@ class BaseIMClient(ABC):
Message ID of sent message
"""
pass
+
+ async def upload_markdown(
+ self,
+ context: MessageContext,
+ title: str,
+ content: str,
+ filetype: str = "markdown",
+ ) -> str:
+ """Upload markdown content as a file (optional per platform)."""
+ raise NotImplementedError
@abstractmethod
async def edit_message(
diff --git a/modules/im/slack.py b/modules/im/slack.py
index 7d39a2263..8a44d3218 100644
--- a/modules/im/slack.py
+++ b/modules/im/slack.py
@@ -117,6 +117,8 @@ class SlackBot(BaseIMClient):
"""Send a message to Slack"""
self._ensure_clients()
try:
+ if not text:
+ raise ValueError("Slack send_message requires non-empty text")
# Convert markdown to Slack mrkdwn if needed
if parse_mode == "markdown":
text = self._convert_markdown_to_slack_mrkdwn(text)
@@ -142,36 +144,16 @@ class SlackBot(BaseIMClient):
# Workaround: ensure multi-line content is preserved. Slack sometimes collapses
# rich_text rendering for bot messages; sending with blocks+mrkdwn forces line breaks.
- if "\n" in text and "blocks" not in kwargs:
- section_blocks = []
- for idx, line in enumerate(text.split("\n")):
- content = line if line.strip() else " "
- section_blocks.append(
- {
- "type": "section",
- "block_id": f"line_{idx}",
- "text": {
- "type": "mrkdwn" if parse_mode == "markdown" else "plain_text",
- "text": content,
- "verbatim": True,
- },
- }
- )
- if len(section_blocks) >= 45:
- break
- if len(section_blocks) < len(text.split("\n")):
- section_blocks.append(
- {
- "type": "context",
- "elements": [
- {
- "type": "plain_text",
- "text": "(内容过长,已截断部分行)",
- }
- ],
- }
- )
- kwargs["blocks"] = section_blocks
+ if "\n" in text and "blocks" not in kwargs and len(text) <= 3000:
+ kwargs["blocks"] = [
+ {
+ "type": "section",
+ "text": {
+ "type": "mrkdwn" if parse_mode == "markdown" else "plain_text",
+ "text": text,
+ },
+ }
+ ]
# Send message
response = await self.web_client.chat_postMessage(**kwargs)
@@ -190,6 +172,27 @@ class SlackBot(BaseIMClient):
logger.error(f"Error sending Slack message: {e}")
raise
+ async def upload_markdown(
+ self,
+ context: MessageContext,
+ title: str,
+ content: str,
+ filetype: str = "markdown",
+ ) -> str:
+ self._ensure_clients()
+ data = content or ""
+ result = await self.web_client.files_upload_v2(
+ channel=context.channel_id,
+ thread_ts=context.thread_id,
+ filename=title,
+ title=title,
+ content=data,
+ )
+ file_id = result.get("file", {}).get("id")
+ if not file_id:
+ file_id = result.get("files", [{}])[0].get("id")
+ return file_id or ""
+
async def add_reaction(self, context: MessageContext, message_id: str, emoji: str) -> bool:
"""Add a reaction emoji to a Slack message."""
self._ensure_clients()
diff --git a/scripts/send_long_result_test.py b/scripts/send_long_result_test.py
new file mode 100644
index 000000000..36026f225
--- /dev/null
+++ b/scripts/send_long_result_test.py
@@ -0,0 +1,35 @@
+import asyncio
+import os
+from dataclasses import dataclass
+
+from config.settings import AppConfig
+from core.controller import Controller
+from modules.im import MessageContext
+
+
+@dataclass
+class DummyRequest:
+ started_at: float = 0.0
+
+
+async def main() -> None:
+ channel_id = os.getenv("TEST_SLACK_CHANNEL_ID") or "C0A6U2GH6P5"
+ thread_id = os.getenv("TEST_SLACK_THREAD_TS")
+
+ config = AppConfig.from_env()
+ controller = Controller(config)
+
+ context = MessageContext(
+ user_id="test_user",
+ channel_id=channel_id,
+ thread_id=thread_id,
+ message_id=None,
+ platform_specific=None,
+ )
+
+ content = "".join([f"Line {idx:04d}: Lorem ipsum dolor sit amet.\n" for idx in range(1200)])
+ await controller.emit_agent_message(context, "result", content, parse_mode="markdown")
+
+
+if __name__ == "__main__":
+ asyncio.run(main())