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(search): backend message-content search + around-window

cyh7df70dcc8e24
diff --git a/storage/db.py b/storage/db.py
index 69777f7ab..9989957d0 100644
--- a/storage/db.py
+++ b/storage/db.py
@@ -8,6 +8,17 @@ from sqlalchemy.engine import URL
from config import paths
+def escape_sql_like(value: str) -> str:
+ """Escape the LIKE/ILIKE metacharacters in *value* for use with ``escape="\\"``.
+
+ Backslash first (so the escapes we add aren't re-escaped), then the two
+ wildcards ``%`` and ``_`` — a literal one in a user query must match itself,
+ not widen the pattern. Shared by every LIKE-based search (session title +
+ message content) so the escaping can't drift between call sites.
+ """
+ return str(value).replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
+
+
def sqlite_url(db_path: Path | None = None) -> str:
path = (db_path or paths.get_sqlite_state_path()).expanduser().resolve()
return URL.create("sqlite", database=str(path)).render_as_string(hide_password=False)
diff --git a/storage/messages_service.py b/storage/messages_service.py
index 2798b3d59..8759b8f80 100644
--- a/storage/messages_service.py
+++ b/storage/messages_service.py
@@ -11,6 +11,7 @@ land in one place.
from __future__ import annotations
import json
+import re
import time
import uuid
from datetime import datetime, timezone
@@ -19,6 +20,7 @@ from typing import Any, Iterable, Optional
from sqlalchemy import and_, delete, func, or_, select, update
from sqlalchemy.engine import Connection
+from storage.db import escape_sql_like
from storage.models import agent_sessions, messages, scopes
@@ -72,6 +74,153 @@ def _row_to_payload(row: dict[str, Any]) -> dict[str, Any]:
}
+_WS_RE = re.compile(r"\s+")
+
+# Snippet window radii (chars) either side of the matched term. Tuned for a
+# single-line result row: a little context before, a bit more after.
+_SNIPPET_BEFORE = 40
+_SNIPPET_AFTER = 50
+# Fallback head shown when the term isn't found in ``content_text`` (e.g. the
+# match lived in a non-text field) — keeps the row from rendering empty.
+_SNIPPET_FALLBACK_HEAD = 90
+
+
+def _collapse_ws(value: str) -> str:
+ """Collapse any run of whitespace/newlines to a single space (no strip)."""
+ return _WS_RE.sub(" ", value)
+
+
+def build_snippet(content_text: str, query: str) -> dict[str, str]:
+ """Split *content_text* into ``{prefix, match, suffix}`` around *query*.
+
+ The match is located case-insensitively but ``match`` carries the ORIGINAL
+ casing from the text. A window of ~``_SNIPPET_BEFORE`` chars before and
+ ~``_SNIPPET_AFTER`` after is kept; whitespace/newlines are collapsed to single
+ spaces so the row stays one line. A leading ``…`` marks a prefix truncated at
+ the start, a trailing ``…`` a suffix truncated at the end. When the query
+ isn't found, fall back to the first ~``_SNIPPET_FALLBACK_HEAD`` chars as the
+ prefix with an empty match (so the API contract — three string fields — holds
+ regardless of where the DB matched)."""
+ text = content_text or ""
+ idx = text.lower().find(query.lower())
+ if idx == -1:
+ head = text[:_SNIPPET_FALLBACK_HEAD]
+ prefix = _collapse_ws(head)
+ if len(text) > _SNIPPET_FALLBACK_HEAD:
+ prefix = f"{prefix}…"
+ return {"prefix": prefix, "match": "", "suffix": ""}
+
+ end = idx + len(query)
+ start = max(0, idx - _SNIPPET_BEFORE)
+ stop = min(len(text), end + _SNIPPET_AFTER)
+
+ prefix = _collapse_ws(text[start:idx])
+ match = text[idx:end] # original casing
+ suffix = _collapse_ws(text[end:stop])
+ if start > 0:
+ prefix = f"…{prefix}"
+ if stop < len(text):
+ suffix = f"{suffix}…"
+ return {"prefix": prefix, "match": match, "suffix": suffix}
+
+
+def search_messages(
+ conn: Connection,
+ *,
+ query: str,
+ platform: str = "avibe",
+ types: Iterable[str] = ("user", "result"),
+ limit: int = 50,
+) -> dict[str, Any]:
+ """Global message-content search, grouped by session.
+
+ Substring (case-insensitive) ``LIKE`` over ``messages.content_text``, scoped
+ to one ``platform`` (Workbench = ``avibe``) and a set of transcript-visible
+ ``types`` (the user's prompts + the agent's rendered ``result`` replies — both
+ land on a message the chat actually renders, so a clicked result is always
+ jumpable). Archived sessions are excluded. ``limit`` caps the number of
+ MATCHED messages scanned (newest first), so it bounds total work; the matches
+ are then grouped into sessions. The snippet is built in Python (see
+ :func:`build_snippet`) so the client renders ``match`` with a highlight and
+ needs no offset math.
+
+ Returns ``{"sessions": [...], "total": <#matches>, "session_count": <#sessions>}``
+ where each session is ``{session_id, title, project_id, project_name,
+ matches: [{id, author, source, type, created_at, snippet}]}``. Sessions are
+ ordered by their most-recent match; matches are newest-first within a session.
+ An empty / whitespace query short-circuits to an empty result.
+ """
+ cleaned = (query or "").strip()
+ if not cleaned:
+ return {"sessions": [], "total": 0, "session_count": 0}
+
+ like = escape_sql_like(cleaned)
+ type_list = list(types)
+ effective_limit = min(max(int(limit), 1), 200)
+
+ stmt = (
+ select(
+ messages.c.id,
+ messages.c.session_id,
+ messages.c.author,
+ messages.c.source,
+ messages.c.type,
+ messages.c.content_text,
+ messages.c.created_at,
+ agent_sessions.c.title,
+ scopes.c.native_id.label("project_id"),
+ scopes.c.display_name.label("project_name"),
+ )
+ .select_from(
+ messages.join(agent_sessions, agent_sessions.c.id == messages.c.session_id).join(
+ scopes, scopes.c.id == agent_sessions.c.scope_id, isouter=True
+ )
+ )
+ .where(messages.c.platform == platform)
+ .where(messages.c.type.in_(type_list))
+ .where(messages.c.content_text.is_not(None))
+ .where(messages.c.content_text.ilike(f"%{like}%", escape="\\"))
+ # Archived sessions are soft-deleted — never surface their messages.
+ .where(agent_sessions.c.status != "archived")
+ .order_by(messages.c.created_at.desc(), messages.c.id.desc())
+ .limit(effective_limit)
+ )
+
+ rows = conn.execute(stmt).mappings().all()
+
+ # Group by session, preserving the newest-match-first row order: the first
+ # time a session appears is its most-recent match, so insertion order already
+ # ranks sessions by recency and matches stay newest-first within each.
+ grouped: dict[str, dict[str, Any]] = {}
+ total = 0
+ for row in rows:
+ session_id = row["session_id"]
+ bucket = grouped.get(session_id)
+ if bucket is None:
+ bucket = {
+ "session_id": session_id,
+ "title": row["title"],
+ "project_id": row["project_id"],
+ "project_name": row["project_name"],
+ "matches": [],
+ }
+ grouped[session_id] = bucket
+ bucket["matches"].append(
+ {
+ "id": row["id"],
+ "author": row["author"],
+ "source": row["source"],
+ "type": row["type"],
+ "created_at": row["created_at"],
+ "snippet": build_snippet(row["content_text"], cleaned),
+ }
+ )
+ total += 1
+
+ sessions = list(grouped.values())
+ return {"sessions": sessions, "total": total, "session_count": len(sessions)}
+
+
def append(
conn: Connection,
*,
@@ -199,6 +348,7 @@ def list_session_messages(
session_id: str,
after_id: Optional[str] = None,
before_id: Optional[str] = None,
+ around_id: Optional[str] = None,
limit: int = 50,
types: Optional[Iterable[str]] = None,
include_metadata_sources: Iterable[str] = (),
@@ -219,6 +369,14 @@ def list_session_messages(
``before_id`` returns the page immediately older than that row, still in
chronological order. This powers upward history loading from the chat page.
+ ``around_id`` centers a window on a specific message (deep-link / search
+ jump): up to ``limit`` rows strictly older + the anchor + up to ``limit`` rows
+ strictly newer, merged chronologically. It takes precedence over
+ ``after_id`` / ``before_id`` / ``tail``. ``next_before_id`` is set when older
+ rows remain, ``next_after_id`` when newer rows remain, so the chat can page in
+ both directions from the centered window. An unknown ``around_id`` returns no
+ messages and null cursors.
+
``tail`` returns the most-recent ``limit`` rows (still chronological) instead
of the oldest page — used by the Chat page's reconnect/visibility gap
recovery, which needs the RECENT window (a long chat's oldest page would
@@ -237,6 +395,60 @@ def list_session_messages(
else:
query = query.where(type_filter)
effective_limit = min(max(int(limit), 1), 500)
+ if around_id:
+ # Window centered on a specific message (deep-link / search jump). Resolve
+ # the anchor's (created_at, id); an unknown id (or one in another session)
+ # yields an empty window. ``query`` already carries the type/metadata
+ # filter, so the older/anchor/newer sub-queries inherit it — the anchor
+ # only appears if it is itself transcript-visible.
+ anchor = conn.execute(
+ select(messages.c.created_at).where(
+ messages.c.id == around_id, messages.c.session_id == session_id
+ )
+ ).scalar_one_or_none()
+ if anchor is None:
+ return {"messages": [], "next_after_id": None, "next_before_id": None}
+
+ older_q = (
+ query.where(
+ or_(
+ messages.c.created_at < anchor,
+ and_(messages.c.created_at == anchor, messages.c.id < around_id),
+ )
+ )
+ .order_by(messages.c.created_at.desc(), messages.c.id.desc())
+ .limit(effective_limit + 1)
+ )
+ older = [_row_to_payload(dict(row)) for row in conn.execute(older_q).mappings().all()]
+ has_older = len(older) > effective_limit
+ older = older[:effective_limit]
+ older.reverse()
+
+ anchor_rows = [
+ _row_to_payload(dict(row))
+ for row in conn.execute(query.where(messages.c.id == around_id)).mappings().all()
+ ]
+
+ newer_q = (
+ query.where(
+ or_(
+ messages.c.created_at > anchor,
+ and_(messages.c.created_at == anchor, messages.c.id > around_id),
+ )
+ )
+ .order_by(messages.c.created_at.asc(), messages.c.id.asc())
+ .limit(effective_limit + 1)
+ )
+ newer = [_row_to_payload(dict(row)) for row in conn.execute(newer_q).mappings().all()]
+ has_newer = len(newer) > effective_limit
+ newer = newer[:effective_limit]
+
+ merged = older + anchor_rows + newer
+ return {
+ "messages": merged,
+ "next_after_id": newer[-1]["id"] if has_newer and newer else None,
+ "next_before_id": older[0]["id"] if has_older and older else None,
+ }
if tail:
# Newest ``limit`` rows, then flip back to chronological for the caller.
query = query.order_by(messages.c.created_at.desc(), messages.c.id.desc()).limit(effective_limit + 1)
diff --git a/storage/workbench_sessions_service.py b/storage/workbench_sessions_service.py
index 90d26208a..f6f1ad124 100644
--- a/storage/workbench_sessions_service.py
+++ b/storage/workbench_sessions_service.py
@@ -23,6 +23,7 @@ from sqlalchemy import and_, func, or_, select, update
from sqlalchemy.engine import Connection
from storage.agent_session_rows import create_agent_session_row
+from storage.db import escape_sql_like
from storage.pagination import PageRequest, PageResult, page_result_from_limit_plus_one
from storage.models import (
agent_runs,
@@ -131,7 +132,7 @@ def list_sessions(
if title_query:
# `#`-mention global search: case-insensitive title LIKE. Escape the LIKE
# metacharacters so a literal ``%`` / ``_`` in the query can't widen it.
- like = title_query.strip().replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
+ like = escape_sql_like(title_query.strip())
if like:
query = query.where(agent_sessions.c.title.ilike(f"%{like}%", escape="\\"))
if before_id is not None:
diff --git a/tests/test_message_search.py b/tests/test_message_search.py
new file mode 100644
index 000000000..3a1ed5bc3
--- /dev/null
+++ b/tests/test_message_search.py
@@ -0,0 +1,423 @@
+"""Tests for message-content search (``search_messages``) and the ``around_id``
+window mode on ``list_session_messages`` — Phase 1 of the message-search feature.
+
+Mirrors the fixture pattern in ``tests/test_messages_service.py``: an isolated
+``VIBE_REMOTE_HOME`` (so the live ``~/.avibe`` is never touched), a SQLite engine
+from ``create_sqlite_engine``, and direct inserts that control ``created_at`` /
+``type`` / ``platform`` / ``content_text``.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from storage import messages_service
+from storage.db import create_sqlite_engine
+from storage.importer import ensure_sqlite_state
+from storage.models import agent_sessions, messages, scopes
+from storage.settings_service import upsert_scope
+
+
+def isolated_state(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ yield tmp_path
+
+
+def _seed_scope(conn, native_id: str = "proj_test", display_name: str = "My Project") -> str:
+ now = messages_service._utc_now_iso()
+ scope_id = upsert_scope(conn, platform="avibe", scope_type="project", native_id=native_id, now=now)
+ conn.execute(scopes.update().where(scopes.c.id == scope_id).values(display_name=display_name))
+ return scope_id
+
+
+def _seed_session(conn, scope_id, session_id, title=None, *, status="active") -> None:
+ now = messages_service._utc_now_iso()
+ conn.execute(
+ agent_sessions.insert().values(
+ id=session_id,
+ scope_id=scope_id,
+ agent_backend="claude",
+ agent_variant="default",
+ session_anchor="anchor_" + session_id,
+ native_session_id="",
+ title=title,
+ status=status,
+ metadata_json="{}",
+ created_at=now,
+ updated_at=now,
+ last_active_at=now,
+ )
+ )
+
+
+def _insert_msg(
+ conn,
+ scope_id,
+ session_id,
+ author,
+ text,
+ created_at,
+ *,
+ platform="avibe",
+ msg_type=None,
+ source=None,
+ msg_id=None,
+):
+ """Direct insert so a test controls created_at / type / platform / text.
+
+ Agent rows default to ``result``, human rows to ``user`` — the two
+ transcript-visible types message search scans. ``text=None`` writes a NULL
+ ``content_text``."""
+ resolved_type = msg_type or ("user" if author == "user" else "result")
+ conn.execute(
+ messages.insert().values(
+ id=msg_id or f"msg_{session_id}_{created_at[-9:]}_{author}_{resolved_type}",
+ scope_id=scope_id,
+ session_id=session_id,
+ platform=platform,
+ author=author,
+ type=resolved_type,
+ source=source,
+ content_text=text,
+ content_json="{}",
+ metadata_json="{}",
+ created_at=created_at,
+ updated_at=created_at,
+ read_at=None,
+ )
+ )
+
+
+# --- search_messages --------------------------------------------------------
+
+
+def test_search_finds_latin_term_with_session_grouping_and_snippet(isolated_state):
+ """A Latin term is found across sessions, grouped by session (most-recent
+ match first), newest match first within a session, with a split snippet."""
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_scope(conn)
+ _seed_session(conn, scope_id, "ses_a", "Alpha")
+ _seed_session(conn, scope_id, "ses_b", "Beta")
+ # ses_a: two matches (older + newer) + a non-match.
+ _insert_msg(conn, scope_id, "ses_a", "user", "deploy the staging server", "2026-06-01T10:00:00Z")
+ _insert_msg(conn, scope_id, "ses_a", "agent", "unrelated reply", "2026-06-01T10:01:00Z")
+ _insert_msg(conn, scope_id, "ses_a", "agent", "I will DEPLOY it now", "2026-06-01T10:02:00Z")
+ # ses_b: a single, most-recent match → ranks first.
+ _insert_msg(conn, scope_id, "ses_b", "user", "can we deploy on friday", "2026-06-01T11:00:00Z")
+
+ with engine.connect() as conn:
+ result = messages_service.search_messages(conn, query="deploy")
+
+ assert result["total"] == 3
+ assert result["session_count"] == 2
+ # ses_b's match (11:00) is newer than any ses_a match → ses_b first.
+ assert [s["session_id"] for s in result["sessions"]] == ["ses_b", "ses_a"]
+
+ sb, sa = result["sessions"]
+ assert sb["title"] == "Beta" and sb["project_id"] == "proj_test" and sb["project_name"] == "My Project"
+ # Within ses_a: newest match first.
+ assert [m["created_at"] for m in sa["matches"]] == ["2026-06-01T10:02:00Z", "2026-06-01T10:00:00Z"]
+
+ # Snippet shape: three string fields; match carries ORIGINAL casing.
+ newest = sa["matches"][0]
+ assert set(newest["snippet"]) == {"prefix", "match", "suffix"}
+ assert newest["snippet"]["match"] == "DEPLOY" # original case preserved
+ # Each match exposes the row identity needed to deep-link + render.
+ assert set(newest) == {"id", "author", "source", "type", "created_at", "snippet"}
+
+
+def test_search_finds_cjk_term(isolated_state):
+ """Substring search is bilingual — a CJK term matches (LIKE, no tokenizer)."""
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_scope(conn)
+ _seed_session(conn, scope_id, "ses_cjk", "中文会话")
+ _insert_msg(conn, scope_id, "ses_cjk", "user", "请帮我部署测试服务器", "2026-06-01T10:00:00Z")
+ _insert_msg(conn, scope_id, "ses_cjk", "agent", "好的,正在处理", "2026-06-01T10:01:00Z")
+
+ with engine.connect() as conn:
+ result = messages_service.search_messages(conn, query="部署")
+
+ assert result["total"] == 1
+ match = result["sessions"][0]["matches"][0]
+ assert match["snippet"]["match"] == "部署"
+
+
+def test_search_excludes_im_platform_rows(isolated_state):
+ """A ``result`` row on a non-avibe (IM) platform is excluded for the default
+ platform='avibe' search — search is Workbench-scoped."""
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_scope(conn)
+ _seed_session(conn, scope_id, "ses_mix", "Mixed")
+ _insert_msg(conn, scope_id, "ses_mix", "agent", "deploy from avibe", "2026-06-01T10:00:00Z", platform="avibe")
+ _insert_msg(conn, scope_id, "ses_mix", "agent", "deploy from slack", "2026-06-01T10:01:00Z", platform="slack")
+
+ with engine.connect() as conn:
+ result = messages_service.search_messages(conn, query="deploy")
+
+ assert result["total"] == 1
+ assert result["sessions"][0]["matches"][0]["snippet"]["match"] == "deploy"
+ # The slack row's text must not appear.
+ texts = [m["snippet"] for s in result["sessions"] for m in s["matches"]]
+ assert all("slack" not in (sn["prefix"] + sn["suffix"]) for sn in texts)
+
+
+def test_search_excludes_assistant_and_null_content(isolated_state):
+ """Intermediate ``assistant`` process rows and NULL ``content_text`` rows are
+ excluded — only user/result rows with text are searchable."""
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_scope(conn)
+ _seed_session(conn, scope_id, "ses_t", "Types")
+ # assistant (intermediate) — excluded even though it matches.
+ _insert_msg(conn, scope_id, "ses_t", "agent", "deploy thinking", "2026-06-01T10:00:00Z", msg_type="assistant")
+ # NULL content_text — excluded (media-only row).
+ _insert_msg(conn, scope_id, "ses_t", "agent", None, "2026-06-01T10:01:00Z", msg_type="result")
+ # A real user/result match — kept.
+ _insert_msg(conn, scope_id, "ses_t", "user", "deploy please", "2026-06-01T10:02:00Z")
+
+ with engine.connect() as conn:
+ result = messages_service.search_messages(conn, query="deploy")
+
+ assert result["total"] == 1
+ assert result["sessions"][0]["matches"][0]["type"] == "user"
+
+
+def test_search_excludes_archived_session(isolated_state):
+ """Messages of an archived (soft-deleted) session never surface in search."""
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_scope(conn)
+ _seed_session(conn, scope_id, "ses_live", "Live", status="active")
+ _seed_session(conn, scope_id, "ses_arch", "Archived", status="archived")
+ _insert_msg(conn, scope_id, "ses_live", "user", "deploy here", "2026-06-01T10:00:00Z")
+ _insert_msg(conn, scope_id, "ses_arch", "user", "deploy there", "2026-06-01T10:01:00Z")
+
+ with engine.connect() as conn:
+ result = messages_service.search_messages(conn, query="deploy")
+
+ assert result["session_count"] == 1
+ assert result["sessions"][0]["session_id"] == "ses_live"
+
+
+def test_search_treats_like_metachars_literally(isolated_state):
+ """``%`` / ``_`` in the query are matched literally (escaped), not as LIKE
+ wildcards — a ``%`` query must not match a row lacking a literal ``%``."""
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_scope(conn)
+ _seed_session(conn, scope_id, "ses_pct", "Percent")
+ _insert_msg(conn, scope_id, "ses_pct", "user", "cpu at 50% load", "2026-06-01T10:00:00Z")
+ _insert_msg(conn, scope_id, "ses_pct", "user", "plain text no metachars", "2026-06-01T10:01:00Z")
+ _insert_msg(conn, scope_id, "ses_pct", "user", "value_x set", "2026-06-01T10:02:00Z")
+ _insert_msg(conn, scope_id, "ses_pct", "user", "valueXset other", "2026-06-01T10:03:00Z")
+
+ with engine.connect() as conn:
+ pct = messages_service.search_messages(conn, query="50%")
+ underscore = messages_service.search_messages(conn, query="value_x")
+
+ # '%' is literal: only the "50% load" row matches (not every row via wildcard).
+ assert pct["total"] == 1
+ assert pct["sessions"][0]["matches"][0]["snippet"]["match"] == "50%"
+ # '_' is literal: matches "value_x", not "valueXset".
+ assert underscore["total"] == 1
+ assert underscore["sessions"][0]["matches"][0]["snippet"]["match"] == "value_x"
+
+
+def test_search_empty_or_whitespace_query_is_empty(isolated_state):
+ """An empty / whitespace-only query short-circuits to an empty result."""
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_scope(conn)
+ _seed_session(conn, scope_id, "ses_e", "Empty")
+ _insert_msg(conn, scope_id, "ses_e", "user", "anything", "2026-06-01T10:00:00Z")
+
+ empty_shape = {"sessions": [], "total": 0, "session_count": 0}
+ with engine.connect() as conn:
+ assert messages_service.search_messages(conn, query="") == empty_shape
+ assert messages_service.search_messages(conn, query=" \n\t ") == empty_shape
+
+
+def test_search_snippet_windows_and_truncates(isolated_state):
+ """The snippet keeps ~40 chars before / ~50 after the match, collapses
+ whitespace+newlines to single spaces, and marks truncated ends with '…'."""
+ engine = create_sqlite_engine()
+ long_before = "x" * 100
+ long_after = "y" * 100
+ text = f"{long_before}\n\nNEEDLE\t here {long_after}"
+ with engine.begin() as conn:
+ scope_id = _seed_scope(conn)
+ _seed_session(conn, scope_id, "ses_snip", "Snip")
+ _insert_msg(conn, scope_id, "ses_snip", "user", text, "2026-06-01T10:00:00Z")
+ # Fallback case: query matches the title's column path but NOT content_text
+ # — we still get a head-of-text snippet with an empty match.
+ _insert_msg(conn, scope_id, "ses_snip", "user", "short body", "2026-06-01T10:01:00Z", msg_id="fallback_row")
+
+ with engine.connect() as conn:
+ result = messages_service.search_messages(conn, query="needle")
+
+ match = result["sessions"][0]["matches"][0]["snippet"]
+ assert match["match"] == "NEEDLE" # original case
+ # Prefix is truncated at the start (… leading) and windowed to ~40 chars.
+ assert match["prefix"].startswith("…")
+ assert len(match["prefix"]) <= 45
+ # Suffix truncated at the end (… trailing), whitespace collapsed (no tabs/nl).
+ assert match["suffix"].endswith("…")
+ assert "\n" not in match["prefix"] and "\t" not in match["suffix"]
+ # Whitespace right after the match was collapsed to a single space.
+ assert match["suffix"].startswith(" here ") or match["suffix"].startswith("here ")
+
+
+def test_search_snippet_fallback_when_term_not_in_content(isolated_state):
+ """If the matched substring can't be located (defensive: e.g. odd casing /
+ normalization), the snippet falls back to a head-of-text prefix + empty match.
+ Verified directly on the builder to exercise the not-found branch."""
+ snippet = messages_service.build_snippet("a" * 200, "zzz-not-present")
+ assert snippet["match"] == ""
+ assert snippet["suffix"] == ""
+ assert snippet["prefix"].endswith("…")
+ assert len(snippet["prefix"]) <= 91 # ~90 head + the ellipsis
+
+
+def test_search_limit_clamped_and_caps_matches(isolated_state):
+ """``limit`` caps the matched-message scan (newest first) and is clamped to
+ 1..200."""
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_scope(conn)
+ _seed_session(conn, scope_id, "ses_lim", "Limit")
+ for i in range(5):
+ _insert_msg(conn, scope_id, "ses_lim", "user", f"deploy {i}", f"2026-06-01T10:0{i}:00Z")
+
+ with engine.connect() as conn:
+ capped = messages_service.search_messages(conn, query="deploy", limit=2)
+ # limit<1 clamps up to 1.
+ floored = messages_service.search_messages(conn, query="deploy", limit=0)
+
+ assert capped["total"] == 2
+ # Newest first: deploy 4 then deploy 3.
+ assert [m["snippet"]["match"] for m in capped["sessions"][0]["matches"]] == ["deploy", "deploy"]
+ assert [m["created_at"] for m in capped["sessions"][0]["matches"]] == [
+ "2026-06-01T10:04:00Z",
+ "2026-06-01T10:03:00Z",
+ ]
+ assert floored["total"] == 1
+
+
+# --- list_session_messages around_id window ---------------------------------
+
+
+def _seed_linear_session(conn, scope_id, session_id, count):
+ """Insert ``count`` user messages m0..m{count-1} at increasing timestamps."""
+ _seed_session(conn, scope_id, session_id)
+ for i in range(count):
+ _insert_msg(conn, scope_id, session_id, "user", f"m{i}", f"2026-06-02T10:{i:02d}:00Z")
+
+
+def test_around_middle_target_returns_window_with_both_cursors(isolated_state):
+ """A middle anchor yields up to ``limit`` older + anchor + ``limit`` newer,
+ merged chronologically, with both cursors set when rows remain on each side."""
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_scope(conn)
+ _seed_linear_session(conn, scope_id, "ses_mid", 9) # m0..m8
+
+ with engine.connect() as conn:
+ anchor_id = f"msg_ses_mid_{'2026-06-02T10:04:00Z'[-9:]}_user_user"
+ page = messages_service.list_session_messages(
+ conn, session_id="ses_mid", around_id=anchor_id, limit=2, types=("user", "result")
+ )
+
+ # 2 older (m2, m3) + anchor (m4) + 2 newer (m5, m6), chronological.
+ assert [m["text"] for m in page["messages"]] == ["m2", "m3", "m4", "m5", "m6"]
+ # Older rows remain (m0, m1) → before cursor; newer remain (m7, m8) → after cursor.
+ assert page["next_before_id"] is not None
+ assert page["next_after_id"] is not None
+
+
+def test_around_newest_target_has_no_after_cursor(isolated_state):
+ """When the anchor is the newest message, the window has older rows but no
+ newer ones → ``next_after_id`` is None."""
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_scope(conn)
+ _seed_linear_session(conn, scope_id, "ses_new", 5) # m0..m4
+
+ with engine.connect() as conn:
+ anchor_id = f"msg_ses_new_{'2026-06-02T10:04:00Z'[-9:]}_user_user" # m4 = newest
+ page = messages_service.list_session_messages(
+ conn, session_id="ses_new", around_id=anchor_id, limit=2, types=("user", "result")
+ )
+
+ # m2, m3 older + m4 anchor; nothing newer.
+ assert [m["text"] for m in page["messages"]] == ["m2", "m3", "m4"]
+ assert page["next_after_id"] is None
+ assert page["next_before_id"] is not None # m0, m1 still older
+
+
+def test_around_oldest_target_has_no_before_cursor(isolated_state):
+ """When the anchor is the oldest message, there are no older rows →
+ ``next_before_id`` is None."""
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_scope(conn)
+ _seed_linear_session(conn, scope_id, "ses_old", 5) # m0..m4
+
+ with engine.connect() as conn:
+ anchor_id = f"msg_ses_old_{'2026-06-02T10:00:00Z'[-9:]}_user_user" # m0 = oldest
+ page = messages_service.list_session_messages(
+ conn, session_id="ses_old", around_id=anchor_id, limit=2, types=("user", "result")
+ )
+
+ # anchor m0 + m1, m2 newer; nothing older.
+ assert [m["text"] for m in page["messages"]] == ["m0", "m1", "m2"]
+ assert page["next_before_id"] is None
+ assert page["next_after_id"] is not None # m3, m4 still newer
+
+
+def test_around_unknown_id_returns_empty(isolated_state):
+ """An ``around_id`` that doesn't exist (or belongs to another session) returns
+ no messages and null cursors."""
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_scope(conn)
+ _seed_linear_session(conn, scope_id, "ses_unk", 3)
+
+ with engine.connect() as conn:
+ page = messages_service.list_session_messages(
+ conn, session_id="ses_unk", around_id="does-not-exist", limit=2, types=("user", "result")
+ )
+
+ assert page == {"messages": [], "next_after_id": None, "next_before_id": None}
+
+
+def test_around_takes_precedence_over_before_and_tail(isolated_state):
+ """``around_id`` wins over ``before_id`` / ``tail`` when several are passed."""
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_scope(conn)
+ _seed_linear_session(conn, scope_id, "ses_prec", 7) # m0..m6
+
+ with engine.connect() as conn:
+ anchor_id = f"msg_ses_prec_{'2026-06-02T10:03:00Z'[-9:]}_user_user" # m3
+ page = messages_service.list_session_messages(
+ conn,
+ session_id="ses_prec",
+ around_id=anchor_id,
+ before_id=anchor_id,
+ tail=True,
+ limit=1,
+ types=("user", "result"),
+ )
+
+ # Around window centered on m3 (1 older + anchor + 1 newer), not a tail/before page.
+ assert [m["text"] for m in page["messages"]] == ["m2", "m3", "m4"]
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 4eef546f1..66e74e03b 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -4489,6 +4489,9 @@ def sessions_messages_list(session_id: str):
except (TypeError, ValueError):
limit = 50
before_id = request.args.get("before_id") or None
+ # ``around_id`` centers the window on a specific message (search deep-link
+ # jump); it takes precedence over after/before/tail in the service.
+ around_id = request.args.get("around_id") or None
# ``tail=1`` returns the most-recent window (for the Chat page's gap recovery)
# instead of the oldest page.
tail = request.args.get("tail") == "1"
@@ -4511,6 +4514,7 @@ def sessions_messages_list(session_id: str):
session_id=session_id,
after_id=after_id,
before_id=before_id,
+ around_id=around_id,
limit=limit,
types=messages_service.TRANSCRIPT_TYPES,
include_metadata_sources=("show_page",),
@@ -4519,6 +4523,30 @@ def sessions_messages_list(session_id: str):
return jsonify(result)
[email protected]("/api/search/messages", methods=["GET"])
+def search_messages_list():
+ """Global message-content search across Workbench sessions, grouped by session.
+
+ Substring (case-insensitive) search over ``content_text`` for ``platform
+ ='avibe'`` user prompts + agent ``result`` replies, excluding archived
+ sessions. ``q`` is the query, ``limit`` caps the matched-message scan. The
+ remote-access host guard + auth run in the global ``before_request`` hooks
+ (same as the messages list), so this handler just delegates to the service.
+ """
+ from storage import messages_service
+
+ query = request.args.get("q") or ""
+ try:
+ limit = int(request.args.get("limit") or 50)
+ except (TypeError, ValueError):
+ limit = 50
+
+ engine = _projects_engine()
+ with engine.connect() as conn:
+ result = messages_service.search_messages(conn, query=query, limit=limit)
+ return jsonify(result)
+
+
# Content types the media proxy is willing to serve ``inline``. Anything else —
# text/html, image/svg+xml, xml, application/octet-stream, unknown — is forced to
# ``attachment`` so a preview-open of agent-produced ACTIVE content can't execute