Skip to content

armgit / avibe

Public Imported from GitHub
0

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

fix(sessions): derive titles from user messages (#1032)

Call White3baa3f6e5f13
diff --git a/core/handlers/command_handlers.py b/core/handlers/command_handlers.py
index de0731ec0..29e81acab 100644
--- a/core/handlers/command_handlers.py
+++ b/core/handlers/command_handlers.py
@@ -1045,6 +1045,7 @@ class CommandHandlers(BaseHandler):
request = AgentRequest(
context=context,
message="stop",
+ user_message="",
working_path=working_path,
base_session_id=base_session_id,
composite_session_id=composite_key,
diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.py
index d8ac53e9d..16ae0fcdf 100644
--- a/core/handlers/message_handler.py
+++ b/core/handlers/message_handler.py
@@ -462,9 +462,11 @@ class MessageHandler(BaseHandler):
if processed_files:
logger.info(f"Processed {len(processed_files)} file attachments for message")
+ user_message = self._get_user_message(context, message)
audio_transcripts = await self._transcribe_audio_attachments(context, processed_files or [])
if audio_transcripts:
message = append_audio_transcripts_to_message(message, audio_transcripts)
+ user_message = append_audio_transcripts_to_message(user_message, audio_transcripts)
await self._echo_audio_transcripts_if_enabled(context, audio_transcripts)
message = await self._prepend_message_metadata(context, message, include_user_info=is_human)
@@ -483,6 +485,7 @@ class MessageHandler(BaseHandler):
request = self._build_agent_request(
context=context,
message=message,
+ user_message=user_message,
working_path=working_path,
base_session_id=base_session_id,
composite_session_id=composite_key,
@@ -697,6 +700,14 @@ class MessageHandler(BaseHandler):
return control_text
return message
+ @staticmethod
+ def _get_user_message(context: MessageContext, message: str) -> str:
+ payload = context.platform_specific or {}
+ normalized_user_text = payload.get("normalized_user_text")
+ if isinstance(normalized_user_text, str):
+ return normalized_user_text
+ return message
+
async def handle_callback_query(self, context: MessageContext, callback_data: str):
"""Route callback queries to appropriate handlers"""
try:
@@ -799,6 +810,7 @@ class MessageHandler(BaseHandler):
request = AgentRequest(
context=context,
message=callback_data,
+ user_message="",
working_path=working_path,
base_session_id=base_session_id,
composite_session_id=composite_key,
@@ -891,6 +903,7 @@ class MessageHandler(BaseHandler):
request = AgentRequest(
context=context,
message="stop",
+ user_message="",
working_path=working_path,
base_session_id=base_session_id,
composite_session_id=composite_key,
diff --git a/modules/agents/base.py b/modules/agents/base.py
index db10685ae..207a13eb7 100644
--- a/modules/agents/base.py
+++ b/modules/agents/base.py
@@ -28,6 +28,8 @@ class AgentRequest:
context: MessageContext
message: str
+ # Originating content before Avibe adds prompt metadata or attachment errors.
+ user_message: str
working_path: str
base_session_id: str
composite_session_id: str
@@ -366,7 +368,7 @@ class BaseAgent(ABC):
agent_session_id=agent_session_id,
native_session_id=str(native_session_id),
working_path=working_path,
- fallback_first_user_message=getattr(request, "message", "") or "",
+ fallback_first_user_message=request.user_message,
)
if updated is None and delay is None and retry_delay_seconds:
asyncio.create_task(_run(retry_delay_seconds))
diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.py
index 553284cbe..4b545d825 100644
--- a/modules/agents/claude_agent.py
+++ b/modules/agents/claude_agent.py
@@ -594,6 +594,7 @@ class ClaudeAgent(BaseAgent):
request = AgentRequest(
context=context,
message="",
+ user_message="",
working_path=working_path,
base_session_id=base_session_id,
composite_session_id=composite_key,
@@ -2302,6 +2303,7 @@ class ClaudeAgent(BaseAgent):
request = AgentRequest(
context=context,
message="",
+ user_message="",
working_path=working_path,
base_session_id=base_session_id,
composite_session_id=composite_key,
diff --git a/modules/agents/opencode/poll_loop.py b/modules/agents/opencode/poll_loop.py
index ed3876a77..db668fb14 100644
--- a/modules/agents/opencode/poll_loop.py
+++ b/modules/agents/opencode/poll_loop.py
@@ -118,6 +118,7 @@ class OpenCodePollLoop:
return AgentRequest(
context=context,
message="",
+ user_message="",
working_path=poll_info.working_path,
base_session_id=poll_info.base_session_id,
composite_session_id=f"{poll_info.base_session_id}:{poll_info.working_path}",
diff --git a/modules/im/slack.py b/modules/im/slack.py
index 12c53a9c2..73a290aad 100644
--- a/modules/im/slack.py
+++ b/modules/im/slack.py
@@ -1956,6 +1956,11 @@ class SlackBot(BaseIMClient):
if not shared_text and not route_text and not file_attachments:
logger.debug("Ignoring shared message with no extractable content")
return
+ normalized_user_text = route_text
+ if shared_text:
+ normalized_user_text = (
+ f"{normalized_user_text}\n\n{shared_text}" if normalized_user_text else shared_text
+ )
# Extract context
# For Slack: if no thread_ts, use the message's own ts as thread_id (start of thread)
@@ -1973,6 +1978,7 @@ class SlackBot(BaseIMClient):
"bot_user_id": bot_user_id,
"bot_mention": bot_mention,
"control_text": route_text,
+ "normalized_user_text": normalized_user_text,
},
files=file_attachments,
)
@@ -2049,6 +2055,11 @@ class SlackBot(BaseIMClient):
# Extract shared/forwarded message content (defer appending until after command check)
shared_text = await self._extract_shared_message_content(event)
+ normalized_user_text = route_text
+ if shared_text:
+ normalized_user_text = (
+ f"{normalized_user_text}\n\n{shared_text}" if normalized_user_text else shared_text
+ )
had_mention_only = not route_text and not file_attachments and not shared_text
@@ -2064,6 +2075,7 @@ class SlackBot(BaseIMClient):
"bot_user_id": bot_user_id,
"bot_mention": bot_mention,
"control_text": route_text,
+ "normalized_user_text": normalized_user_text,
},
files=file_attachments,
)
diff --git a/tests/test_agent_silent_result.py b/tests/test_agent_silent_result.py
index c43899cbe..7e490642f 100644
--- a/tests/test_agent_silent_result.py
+++ b/tests/test_agent_silent_result.py
@@ -112,6 +112,7 @@ class AgentSessionIdContextTests(unittest.TestCase):
request = AgentRequest(
context=context,
message="hello",
+ user_message="hello",
working_path="/tmp/work",
base_session_id="slack_171717.123",
composite_session_id="slack_171717.123:/tmp/work",
@@ -151,6 +152,7 @@ class AgentSessionIdContextTests(unittest.TestCase):
request = AgentRequest(
context=context,
message="hello",
+ user_message="hello",
working_path="/tmp/test",
base_session_id="slack_171717.123",
composite_session_id="slack_171717.123:/repo/original",
@@ -193,6 +195,7 @@ class AgentSessionIdContextTests(unittest.TestCase):
request = AgentRequest(
context=context,
message="hello",
+ user_message="hello",
working_path="/tmp/work",
base_session_id="chat-1:reviewer",
composite_session_id="chat-1:reviewer:/tmp/work",
diff --git a/tests/test_backend_failure.py b/tests/test_backend_failure.py
index 32ca7a9aa..3d2f0c068 100644
--- a/tests/test_backend_failure.py
+++ b/tests/test_backend_failure.py
@@ -19,6 +19,7 @@ def _request() -> AgentRequest:
return AgentRequest(
context=context,
message="work",
+ user_message="work",
working_path="/tmp/work",
base_session_id="session-1",
composite_session_id="session-1:/tmp/work",
diff --git a/tests/test_message_handler_typing.py b/tests/test_message_handler_typing.py
index 368fc87c2..87feca25d 100644
--- a/tests/test_message_handler_typing.py
+++ b/tests/test_message_handler_typing.py
@@ -23,6 +23,7 @@ def _load_message_handler_class():
class _AgentRequest:
context: MessageContext
message: str
+ user_message: str
working_path: str
base_session_id: str
composite_session_id: str
@@ -982,7 +983,11 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):
channel_id="C1",
message_id="m1",
platform="slack",
- platform_specific={"bot_mention": "<@U_BOT>", "control_text": ""},
+ platform_specific={
+ "bot_mention": "<@U_BOT>",
+ "control_text": "",
+ "normalized_user_text": "shared content",
+ },
)
await handler.handle_user_message(context, "<@U_BOT>\n\nshared content")
@@ -990,6 +995,54 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):
controller.command_handler.handle_start.assert_not_awaited()
_, request = controller.agent_service.requests[0]
self.assertIn("shared content", request.message)
+ self.assertEqual(request.user_message, "shared content")
+
+ async def test_request_separates_user_message_from_prompt_decorations(self):
+ from core.audio_asr import AudioTranscript
+
+ controller = _StubController(platform="slack", ack_mode="reaction", typing_result=True)
+ controller.config.include_time_info = True
+ controller.config.include_user_info = True
+ handler = MessageHandler(controller)
+ handler.set_session_handler(_StubSessionHandler())
+ handler._build_current_time_line = lambda: "[Current Time: 2026-07-26 16:00:00 UTC+08:00]"
+ handler._process_file_attachments = AsyncMock(
+ return_value=([object()], ["report.pdf could not be downloaded"])
+ )
+ handler._transcribe_audio_attachments = AsyncMock(
+ return_value=[
+ AudioTranscript(
+ attachment_name="note.m4a",
+ local_path="/tmp/note.m4a",
+ text="Keep the user's words",
+ )
+ ]
+ )
+ handler._echo_audio_transcripts_if_enabled = AsyncMock()
+ context = MessageContext(
+ user_id="U1",
+ channel_id="C1",
+ message_id="m1",
+ platform="slack",
+ platform_specific={
+ "bot_mention": "<@U_BOT>",
+ "control_text": "Investigate session title fallback",
+ "normalized_user_text": "Investigate session title fallback",
+ },
+ files=[object()],
+ )
+
+ await handler.handle_user_message(context, "<@U_BOT> Investigate session title fallback")
+
+ _, request = controller.agent_service.requests[0]
+ prepended_lines = request.message.splitlines()[:2]
+ self.assertIn("<@U_BOT>", request.message)
+ self.assertNotIn("<@U_BOT>", request.user_message)
+ self.assertIn("[Audio Transcripts]", request.user_message)
+ self.assertIn("Keep the user's words", request.user_message)
+ self.assertFalse(set(prepended_lines) & set(request.user_message.splitlines()))
+ self.assertNotIn("[Attachment Download Errors]", request.user_message)
+ self.assertIn("[Attachment Download Errors]", request.message)
async def test_control_text_routes_mentioned_subagent_prefix(self):
controller = _StubController(platform="slack", ack_mode="reaction", typing_result=True)
diff --git a/tests/test_multi_platform_runtime.py b/tests/test_multi_platform_runtime.py
index 2461bc026..7692306b0 100644
--- a/tests/test_multi_platform_runtime.py
+++ b/tests/test_multi_platform_runtime.py
@@ -800,6 +800,7 @@ def test_opencode_prompt_disables_question_tool_for_all_platforms():
platform_specific={"agent_session_id": "ses_test"},
),
message="hello",
+ user_message="hello",
working_path="/tmp/work",
base_session_id="base",
composite_session_id="base:/tmp/work",
@@ -1163,6 +1164,7 @@ def test_opencode_fork_prompt_marks_target_session_id_authoritative():
},
),
message="hello",
+ user_message="hello",
working_path="/tmp/work",
base_session_id="ses-target",
composite_session_id="ses-target:/tmp/work",
@@ -1213,6 +1215,7 @@ def test_opencode_normal_text_matching_legacy_question_prefix_is_processed():
request = AgentRequest(
context=MessageContext(user_id="u", channel_id="c", platform="slack"),
message="opencode_question:choose:1",
+ user_message="",
working_path="/tmp/work",
base_session_id="base",
composite_session_id="base:/tmp/work",
@@ -1329,6 +1332,7 @@ def test_opencode_process_message_removes_active_poll_when_question_tool_aborts(
platform_specific={"agent_session_id": "ses_test"},
),
message="hello",
+ user_message="hello",
working_path="/tmp/work",
base_session_id="base",
composite_session_id="base:/tmp/work",
@@ -1403,6 +1407,7 @@ def test_opencode_poll_aborts_disabled_question_toolcall():
request = AgentRequest(
context=MessageContext(user_id="u", channel_id="c", platform="slack"),
message="hello",
+ user_message="hello",
working_path="/tmp/work",
base_session_id="base",
composite_session_id="base:/tmp/work",
@@ -1506,6 +1511,7 @@ def test_opencode_poll_notifies_and_settles_on_retry_exhaustion():
request = AgentRequest(
context=MessageContext(user_id="u", channel_id="c", platform="slack"),
message="hello",
+ user_message="hello",
working_path="/tmp/work",
base_session_id="base",
composite_session_id="base:/tmp/work",
@@ -1625,6 +1631,7 @@ def test_opencode_poll_keeps_explicit_empty_completion_on_success_path():
request = AgentRequest(
context=MessageContext(user_id="u", channel_id="c", platform="slack"),
message="hello",
+ user_message="hello",
working_path="/tmp/work",
base_session_id="base",
composite_session_id="base:/tmp/work",
@@ -2048,6 +2055,7 @@ async def _run_terminal_result_cleanup(platform: str, *, platform_specific=None)
request = AgentRequest(
context=context,
message="hello",
+ user_message="hello",
working_path="/tmp",
base_session_id="base",
composite_session_id="base:/tmp",
diff --git a/tests/test_opencode_session_manager.py b/tests/test_opencode_session_manager.py
index cada65112..7183a2089 100644
--- a/tests/test_opencode_session_manager.py
+++ b/tests/test_opencode_session_manager.py
@@ -18,6 +18,7 @@ def _request() -> AgentRequest:
return AgentRequest(
context=MessageContext(user_id="U1", channel_id="C1", platform_specific={}),
message="hello",
+ user_message="hello",
working_path="/repo",
base_session_id="base-1",
composite_session_id="base-1:/repo",
diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.py
index b0491b2f9..24c9dfb34 100644
--- a/tests/test_scheduled_tasks.py
+++ b/tests/test_scheduled_tasks.py
@@ -6862,6 +6862,7 @@ def test_dead_accepted_owner_converges_run_session_and_persisted_fifo(
AgentRequest(
context=context,
message=message,
+ user_message=message,
working_path=str(tmp_path),
base_session_id=session_id,
composite_session_id=f"{session_id}:{tmp_path}",
diff --git a/tests/test_session_titles.py b/tests/test_session_titles.py
index 27efbce04..2bacd67d0 100644
--- a/tests/test_session_titles.py
+++ b/tests/test_session_titles.py
@@ -1,13 +1,19 @@
from __future__ import annotations
+import asyncio
import sys
from pathlib import Path
+from types import SimpleNamespace
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from core import inbox_events
from core.session_titles import backfill_agent_session_title
from core.services import sessions as sessions_service
+from modules.agents.base import AgentRequest, BaseAgent
+from modules.agents.native_sessions.service import AgentNativeSessionService
+from modules.agents.native_sessions.types import BackendSessionTitle
+from modules.im import MessageContext
from storage import messages_service
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state
@@ -15,6 +21,13 @@ from storage.models import scope_settings
from storage.settings_service import upsert_scope
+class _TitleBackfillAgent(BaseAgent):
+ name = "claude"
+
+ async def handle_message(self, request: AgentRequest) -> None:
+ return None
+
+
def test_backfill_agent_session_title_uses_first_user_message_for_claude(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
ensure_sqlite_state()
@@ -94,3 +107,81 @@ def test_backfill_agent_session_title_uses_first_user_message_for_claude(monkeyp
assert published[1][1]["session_id"] == session["id"]
assert published[1][1]["title"] == "帮我 实现 sess"
assert published[1][1]["preview_text"] == "title backfill done"
+
+
+def test_request_title_fallback_uses_user_message_when_no_message_row(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = upsert_scope(
+ conn,
+ platform="avibe",
+ scope_type="project",
+ native_id="proj_title_fallback",
+ now="2026-07-26T08:00:00Z",
+ )
+ session = sessions_service.create_session(conn, scope_id=scope_id, agent_backend="claude")
+ assert messages_service.first_user_text(conn, session["id"]) == ""
+
+ user_message = "Investigate session title fallback\n\n[Audio Transcript: note.m4a]\nKeep the user's words"
+ prepended_lines = [
+ "[Current Time: 2026-07-26 16:00:00 UTC+08:00]",
+ "[Alex<U123>]",
+ ]
+ prompt = "\n".join(
+ [
+ *prepended_lines,
+ user_message,
+ "",
+ "[Attachment Download Errors]",
+ "- report.pdf could not be downloaded",
+ ]
+ )
+ captured: dict[str, str] = {}
+
+ def _get_title(
+ _service,
+ *,
+ working_path,
+ agent,
+ native_session_id,
+ first_user_message="",
+ ):
+ captured["first_user_message"] = first_user_message
+ return BackendSessionTitle(
+ title="Clean title input",
+ source="derived_first_prompt",
+ confidence="low",
+ )
+
+ monkeypatch.setattr(AgentNativeSessionService, "get_title", _get_title)
+ controller = SimpleNamespace(
+ config=SimpleNamespace(),
+ im_client=SimpleNamespace(),
+ settings_manager=SimpleNamespace(sessions=None),
+ )
+ request = AgentRequest(
+ context=MessageContext(
+ user_id="U123",
+ channel_id=session["id"],
+ platform="avibe",
+ platform_specific={"agent_session_id": session["id"]},
+ ),
+ message=prompt,
+ user_message=user_message,
+ working_path="/repo",
+ base_session_id=session["id"],
+ composite_session_id=f"{session['id']}:/repo",
+ session_key=f"avibe::{scope_id}",
+ )
+
+ async def _run() -> None:
+ _TitleBackfillAgent(controller)._maybe_backfill_session_title(request, "claude-native-2")
+ await asyncio.sleep(0)
+
+ asyncio.run(_run())
+
+ assert captured["first_user_message"] == user_message
+ assert not set(prepended_lines) & set(captured["first_user_message"].splitlines())
diff --git a/tests/test_slack_app_mention_empty.py b/tests/test_slack_app_mention_empty.py
index 94a017491..f8cae6593 100644
--- a/tests/test_slack_app_mention_empty.py
+++ b/tests/test_slack_app_mention_empty.py
@@ -155,6 +155,44 @@ class SlackAppMentionEmptyTests(unittest.IsolatedAsyncioTestCase):
)
slack.sessions.mark_thread_active.assert_called_once_with("U123", "C123", "1710000000.000700")
+ async def test_app_mention_normalized_user_text_retains_shared_content(self):
+ slack = SlackBot(SlackConfig(bot_token="xoxb-test"))
+ received = {}
+
+ async def _on_message(context, text):
+ received["text"] = text
+ received["normalized_user_text"] = (context.platform_specific or {}).get(
+ "normalized_user_text"
+ )
+
+ slack.register_callbacks(on_message=_on_message)
+ slack.settings_manager = object()
+ slack.sessions = SimpleNamespace(mark_thread_active=Mock())
+ slack._get_bot_user_id = AsyncMock(return_value="U_BOT")
+ slack._extract_shared_message_content = AsyncMock(return_value="Forwarded details")
+ payload = {
+ "event_id": "evt-app-mention-shared",
+ "team_id": "T1",
+ "authorizations": [{"user_id": "U_BOT"}],
+ "event": {
+ "type": "app_mention",
+ "channel": "C123",
+ "user": "U123",
+ "text": "<@U_BOT>",
+ "ts": "1710000000.000701",
+ },
+ }
+
+ await slack._handle_event(payload)
+
+ self.assertEqual(
+ received,
+ {
+ "text": "<@U_BOT>\n\nForwarded details",
+ "normalized_user_text": "Forwarded details",
+ },
+ )
+
class SlackFileAttachmentTests(unittest.IsolatedAsyncioTestCase):
async def test_extract_file_attachments_preserves_file_id_when_url_missing(self):
diff --git a/tests/test_slack_dm_mentions.py b/tests/test_slack_dm_mentions.py
index 714acedd8..c3e1d90cd 100644
--- a/tests/test_slack_dm_mentions.py
+++ b/tests/test_slack_dm_mentions.py
@@ -1826,8 +1826,11 @@ class SlackDmMentionTests(unittest.IsolatedAsyncioTestCase):
slack = SlackBot(SlackConfig(bot_token="xoxb-test"))
received = {}
- async def _on_message(_context, text):
+ async def _on_message(context, text):
received["text"] = text
+ received["normalized_user_text"] = (context.platform_specific or {}).get(
+ "normalized_user_text"
+ )
slack.register_callbacks(on_message=_on_message)
@@ -1846,7 +1849,13 @@ class SlackDmMentionTests(unittest.IsolatedAsyncioTestCase):
await slack._handle_event(payload)
- self.assertEqual(received, {"text": "<@U_BOT> summarize what <@U_OTHER> said"})
+ self.assertEqual(
+ received,
+ {
+ "text": "<@U_BOT> summarize what <@U_OTHER> said",
+ "normalized_user_text": "summarize what <@U_OTHER> said",
+ },
+ )
if __name__ == "__main__":