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(thread): support silent agent replies

cyh783d5973b06c
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.py
index dfbf55852..4b874b628 100644
--- a/core/message_dispatcher.py
+++ b/core/message_dispatcher.py
@@ -12,7 +12,7 @@ from pathlib import Path
from typing import Optional
from modules.im import MessageContext
-from core.reply_enhancer import process_reply, strip_file_links
+from core.reply_enhancer import process_reply, strip_file_links, strip_silent_blocks
logger = logging.getLogger(__name__)
@@ -87,6 +87,13 @@ class ConsolidatedMessageDispatcher:
self._consolidated_message_locks[key] = asyncio.Lock()
return self._consolidated_message_locks[key]
+ async def _clear_consolidated_state(self, context: MessageContext) -> None:
+ consolidated_key = self._get_consolidated_message_key(context)
+ lock = self._get_consolidated_message_lock(consolidated_key)
+ async with lock:
+ self._consolidated_message_ids.pop(consolidated_key, None)
+ self._consolidated_message_buffers.pop(consolidated_key, None)
+
async def clear_consolidated_message_id(
self,
context: MessageContext,
@@ -256,14 +263,16 @@ class ConsolidatedMessageDispatcher:
- Result Message: final output, always sent immediately, not hideable.
- Notify Message: notifications, always sent immediately.
"""
- if not text or not text.strip():
- return None
-
settings_manager = self.controller.get_settings_manager_for_context(context)
im_client = self._get_im_client(context)
canonical_type = settings_manager._canonicalize_message_type(message_type or "")
settings_key = self._get_settings_key(context)
+ text = strip_silent_blocks(text)
+ if not text or not text.strip():
+ if canonical_type == "result":
+ await self._clear_consolidated_state(context)
+ return None
if canonical_type == "notify":
target_context = self._get_target_context(context)
@@ -362,11 +371,7 @@ class ConsolidatedMessageDispatcher:
# Final result closes the current turn: clear consolidated
# assistant/tool/system message state so the next user turn starts
# a fresh log message instead of appending to the previous one.
- consolidated_key = self._get_consolidated_message_key(context)
- lock = self._get_consolidated_message_lock(consolidated_key)
- async with lock:
- self._consolidated_message_ids.pop(consolidated_key, None)
- self._consolidated_message_buffers.pop(consolidated_key, None)
+ await self._clear_consolidated_state(context)
return primary_message_id
diff --git a/core/reply_enhancer.py b/core/reply_enhancer.py
index 6b5ac3d6c..a690f7728 100644
--- a/core/reply_enhancer.py
+++ b/core/reply_enhancer.py
@@ -1,11 +1,14 @@
"""Reply enhancer: parse agent responses for file attachments and quick-reply buttons.
-Extracts two special syntaxes from agent reply text:
+Extracts special syntaxes from agent reply text:
-1. **File links** – Markdown links whose URL starts with ``file://``
+1. **Silent blocks** – ``<silent>...</silent>`` sections that are never forwarded
+ to the IM user. If nothing remains after stripping them, no message is sent.
+
+2. **File links** – Markdown links whose URL starts with ``file://``
e.g. ``[screenshot](file:///tmp/shot.png)``
-2. **Quick-reply buttons** – A ``---`` separator followed by
+3. **Quick-reply buttons** – A ``---`` separator followed by
``[button text]`` tokens separated by ``|``
e.g. ``---\\n[👌好的] | [✅提交PR] | [先review一下]``
"""
@@ -75,6 +78,12 @@ _BUTTON_BLOCK_RE = re.compile(
# Individual button token: [button text]
_BUTTON_TOKEN_RE = re.compile(r"\[([^\]]+)\]")
+# Silent output blocks are intentionally simple and model-facing. They are
+# stripped before any reply enhancement parsing so hidden text cannot create
+# file uploads or quick replies.
+_SILENT_BLOCK_RE = re.compile(r"<silent\b[^>]*>.*?</silent\s*>", re.IGNORECASE | re.DOTALL)
+_UNTERMINATED_SILENT_RE = re.compile(r"<silent\b[^>]*>.*\Z", re.IGNORECASE | re.DOTALL)
+
# ---------------------------------------------------------------------------
# Public API
@@ -87,6 +96,7 @@ def process_reply(text: str) -> EnhancedReply:
The returned ``.text`` has file-link markup converted to plain labels and
the trailing button block (if any) stripped.
"""
+ text = strip_silent_blocks(text)
files = _extract_file_links(text)
text_no_files = _strip_file_links(text) if files else text
buttons, text_clean = _extract_buttons(text_no_files)
@@ -101,6 +111,16 @@ def strip_file_links(text: str) -> str:
return _strip_file_links(text)
+def strip_silent_blocks(text: str) -> str:
+ """Remove all ``<silent>...</silent>`` blocks from agent-visible output."""
+ if not text:
+ return text
+ if "<silent" not in text.lower():
+ return text
+ stripped = _SILENT_BLOCK_RE.sub("", text)
+ return _UNTERMINATED_SILENT_RE.sub("", stripped).strip()
+
+
# ---------------------------------------------------------------------------
# Internal helpers
# ---------------------------------------------------------------------------
@@ -171,6 +191,15 @@ If the user asks you to configure, repair, or operate Vibe Remote itself, read `
Vibe Remote provides optional capabilities:
+## Silent replies
+If you decide no user-facing response is needed, respond only with a silent block:
+`<silent>reason not shown to the user</silent>`
+
+Rules:
+- Vibe Remote strips all `<silent>...</silent>` blocks before sending messages.
+- If nothing remains after stripping silent blocks, Vibe Remote sends no message.
+- Use this for thread messages where you have received context but should not interrupt.
+
## 1. Send files
You can send a local file to the user by using a Markdown link with the `file://` protocol:
Example: [File 1](file:///tmp/result.pdf)
diff --git a/modules/agents/base.py b/modules/agents/base.py
index 5e2858659..af1f1d9ef 100644
--- a/modules/agents/base.py
+++ b/modules/agents/base.py
@@ -11,6 +11,7 @@ from typing import Any, Dict, List, Optional
from modules.im import MessageContext
from modules.im.base import FileAttachment
+from core.reply_enhancer import strip_silent_blocks
logger = logging.getLogger(__name__)
@@ -139,14 +140,26 @@ class BaseAgent(ABC):
if duration_ms is None:
duration_ms = self._calculate_duration_ms(started_at)
+ raw_result = result_text or ""
+ raw_suffix = suffix or ""
+ visible_result = strip_silent_blocks(raw_result)
+ visible_suffix = strip_silent_blocks(raw_suffix) if raw_suffix else None
+ has_silent_directive = "<silent" in raw_result.lower() or "<silent" in raw_suffix.lower()
+
+ if has_silent_directive and not visible_result.strip() and not (visible_suffix or "").strip():
+ await self.controller.emit_agent_message(context, "result", "", parse_mode=parse_mode)
+ if request:
+ await self._remove_ack_reaction(request)
+ return
+
# When show_duration is disabled, skip the entire result line
# unless there is actual result_text or suffix to deliver.
if not show_duration:
parts = []
- if result_text and result_text.strip():
- parts.append(result_text)
- if suffix:
- parts.append(suffix)
+ if visible_result and visible_result.strip():
+ parts.append(visible_result)
+ if visible_suffix:
+ parts.append(visible_suffix)
if parts:
formatted = "\n".join(parts)
await self.controller.emit_agent_message(context, "result", formatted, parse_mode=parse_mode)
@@ -154,11 +167,11 @@ class BaseAgent(ABC):
formatted = self._get_formatter(context).format_result_message(
subtype or "",
duration_ms,
- result_text,
+ visible_result,
show_duration=True,
)
- if suffix:
- formatted = f"{formatted}\n{suffix}"
+ if visible_suffix:
+ formatted = f"{formatted}\n{visible_suffix}"
await self.controller.emit_agent_message(context, "result", formatted, parse_mode=parse_mode)
# Remove ack reaction after result is sent
diff --git a/modules/sessions_facade.py b/modules/sessions_facade.py
index 8d89ca51b..fe641a0f3 100644
--- a/modules/sessions_facade.py
+++ b/modules/sessions_facade.py
@@ -241,7 +241,46 @@ class SessionsFacade:
user_key = self._normalize_user_id(user_id)
self._cleanup_expired_threads_for_channel(user_id, channel_id)
channel_map = self.sessions_store.get_thread_map(user_key, channel_id)
- return thread_ts in channel_map
+ if thread_ts in channel_map:
+ return True
+ return self._is_thread_active_for_any_user(channel_id, thread_ts)
+
+ def _is_thread_active_for_any_user(self, channel_id: str, thread_ts: str) -> bool:
+ """Return whether a channel thread is active for any participant.
+
+ Thread activation gates whether replies can be routed to the agent; once
+ the bot is invited into a thread, all participants should be able to
+ continue the conversation without mentioning the bot again.
+ """
+ cutoff = time.time() - (24 * 60 * 60)
+ changed = False
+
+ for user_key, channels in list(self.sessions_store.state.active_slack_threads.items()):
+ if not isinstance(channels, dict):
+ continue
+ channel_map = channels.get(channel_id)
+ if not isinstance(channel_map, dict):
+ continue
+
+ last_active = channel_map.get(thread_ts)
+ if last_active is None:
+ continue
+ if last_active < cutoff:
+ del channel_map[thread_ts]
+ if not channel_map:
+ channels.pop(channel_id, None)
+ if not channels:
+ self.sessions_store.state.active_slack_threads.pop(user_key, None)
+ changed = True
+ continue
+
+ if changed:
+ self.sessions_store.save()
+ return True
+
+ if changed:
+ self.sessions_store.save()
+ return False
def _cleanup_expired_threads_for_channel(self, user_id: Union[int, str], channel_id: str) -> None:
user_key = self._normalize_user_id(user_id)
diff --git a/tests/test_agent_silent_result.py b/tests/test_agent_silent_result.py
new file mode 100644
index 000000000..7cce07986
--- /dev/null
+++ b/tests/test_agent_silent_result.py
@@ -0,0 +1,49 @@
+from __future__ import annotations
+
+import sys
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from modules.agents.base import AgentRequest, BaseAgent
+from modules.im import MessageContext
+
+
+class _StubController:
+ def __init__(self):
+ self.config = SimpleNamespace(show_duration=True)
+ self.im_client = SimpleNamespace(formatter=None)
+ self.settings_manager = SimpleNamespace(sessions=None)
+ self.messages = []
+
+ async def emit_agent_message(self, context, message_type, text, parse_mode="markdown"):
+ self.messages.append((message_type, text, parse_mode))
+
+
+class _StubAgent(BaseAgent):
+ name = "stub"
+
+ async def handle_message(self, request: AgentRequest) -> None:
+ return None
+
+
+class AgentSilentResultTests(unittest.IsolatedAsyncioTestCase):
+ async def test_silent_only_result_suppresses_duration_wrapper(self):
+ controller = _StubController()
+ agent = _StubAgent(controller)
+ context = MessageContext(user_id="U1", channel_id="C1", platform="slack")
+
+ await agent.emit_result_message(
+ context,
+ "<silent>not relevant</silent>",
+ subtype="success",
+ duration_ms=1234,
+ )
+
+ self.assertEqual(controller.messages, [("result", "", "markdown")])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_message_dispatcher_scheduled.py b/tests/test_message_dispatcher_scheduled.py
index a9e3f3580..35cc9bf0e 100644
--- a/tests/test_message_dispatcher_scheduled.py
+++ b/tests/test_message_dispatcher_scheduled.py
@@ -86,6 +86,49 @@ class MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(controller.im_client.sent, [("C123", None, "hello")])
self.assertEqual(controller.session_handler.calls, [("C123", None, "bot-msg-1")])
+ async def test_result_message_strips_silent_blocks(self):
+ controller = _StubController()
+ dispatcher = ConsolidatedMessageDispatcher(controller)
+ context = MessageContext(user_id="U1", channel_id="C123", platform="slack")
+
+ message_id = await dispatcher.emit_agent_message(
+ context,
+ "result",
+ "<silent>internal decision</silent>\nVisible reply",
+ )
+
+ self.assertEqual(message_id, "bot-msg-1")
+ self.assertEqual(controller.im_client.sent, [("C123", None, "Visible reply")])
+
+ async def test_silent_only_result_sends_nothing(self):
+ controller = _StubController()
+ dispatcher = ConsolidatedMessageDispatcher(controller)
+ context = MessageContext(user_id="U1", channel_id="C123", platform="slack")
+
+ message_id = await dispatcher.emit_agent_message(
+ context,
+ "result",
+ "<silent>not relevant to the bot</silent>",
+ )
+
+ self.assertIsNone(message_id)
+ self.assertEqual(controller.im_client.sent, [])
+ self.assertEqual(controller.session_handler.calls, [])
+
+ async def test_silent_only_log_message_sends_nothing(self):
+ controller = _StubController()
+ dispatcher = ConsolidatedMessageDispatcher(controller)
+ context = MessageContext(user_id="U1", channel_id="C123", platform="slack")
+
+ message_id = await dispatcher.emit_agent_message(
+ context,
+ "assistant",
+ "<silent>only internal note</silent>",
+ )
+
+ self.assertIsNone(message_id)
+ self.assertEqual(controller.im_client.sent, [])
+
async def test_delivery_override_sends_result_to_parent_channel(self):
controller = _StubController()
dispatcher = ConsolidatedMessageDispatcher(controller)
diff --git a/tests/test_reply_enhancer_platform.py b/tests/test_reply_enhancer_platform.py
index 7919a2ae9..790b460e1 100644
--- a/tests/test_reply_enhancer_platform.py
+++ b/tests/test_reply_enhancer_platform.py
@@ -76,6 +76,8 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):
with patch.object(paths, "get_user_preferences_path", return_value=Path("/tmp/user_preferences.md")):
prompt = build_reply_enhancements_prompt(include_quick_replies=False)
+ self.assertIn("## Silent replies", prompt)
+ self.assertIn("<silent>reason not shown to the user</silent>", prompt)
self.assertIn(
"If the user asks you to configure, repair, or operate Vibe Remote itself, read `https://github.com/cyhhao/vibe-remote/raw/master/skills/use-vibe-remote/SKILL.md` before making changes.",
prompt,
@@ -87,6 +89,15 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):
self.assertIn("`/tmp/user_preferences.md`", prompt)
self.assertIn("`<platform>/<user_id>`", prompt)
+ def test_process_reply_strips_silent_blocks_before_enhancements(self):
+ reply = process_reply(
+ "Visible\n<silent>skip [secret](file:///tmp/secret.txt)\n---\n[Hidden]</silent>\nDone"
+ )
+
+ self.assertEqual(reply.text, "Visible\n\nDone")
+ self.assertEqual(reply.files, [])
+ self.assertEqual(reply.buttons, [])
+
def test_prompt_includes_task_watch_and_hook_usage_with_thread_default_session_key(self):
context = MessageContext(
user_id="U1",
diff --git a/tests/test_v2_sessions.py b/tests/test_v2_sessions.py
index 077bd47f0..2399912cd 100644
--- a/tests/test_v2_sessions.py
+++ b/tests/test_v2_sessions.py
@@ -5,6 +5,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from config import paths
from config.v2_sessions import SessionsStore
+from modules.sessions_facade import SessionsFacade
def test_sessions_store_roundtrip(tmp_path, monkeypatch):
@@ -33,6 +34,26 @@ def test_sessions_store_namespaces(tmp_path, monkeypatch):
assert "U2" in store.state.active_slack_threads
+def test_active_thread_is_shared_across_users(tmp_path, monkeypatch):
+ monkeypatch.setattr(paths, "get_vibe_remote_dir", lambda: tmp_path / ".vibe_remote")
+ store = SessionsStore()
+ sessions = SessionsFacade(store)
+
+ sessions.mark_thread_active("U1", "C1", "123.456")
+
+ assert sessions.is_thread_active("U2", "C1", "123.456")
+
+
+def test_shared_active_thread_ignores_expired_entries(tmp_path, monkeypatch):
+ monkeypatch.setattr(paths, "get_vibe_remote_dir", lambda: tmp_path / ".vibe_remote")
+ store = SessionsStore()
+ store.state.active_slack_threads = {"U1": {"C1": {"123.456": 1.0}}}
+ sessions = SessionsFacade(store)
+
+ assert not sessions.is_thread_active("U2", "C1", "123.456")
+ assert "U1" not in store.state.active_slack_threads
+
+
def test_migrate_active_polls_backfills_platform_and_scoped_key(tmp_path, monkeypatch):
"""Legacy active_polls lacking platform are migrated; unscoped keys stay raw."""
monkeypatch.setattr(paths, "get_vibe_remote_dir", lambda: tmp_path / ".vibe_remote")