Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

feat(chat): search full conversation history (#1415)

AoHanBei00e2100adfd0
diff --git a/deeptutor/api/routers/sessions.py b/deeptutor/api/routers/sessions.py
index 53b3435c5..dca444da7 100644
--- a/deeptutor/api/routers/sessions.py
+++ b/deeptutor/api/routers/sessions.py
@@ -20,6 +20,7 @@ from deeptutor.services.session.organization import (
from deeptutor.services.session.provider_response_state import (
redact_private_message_metadata as _redact_provider_state_metadata,
)
+from deeptutor.services.session.search import MAX_SEARCH_QUERY_CHARS
from deeptutor.services.storage.attachment_store import get_attachment_store
logger = logging.getLogger(__name__)
@@ -106,6 +107,24 @@ async def list_sessions(
return {"sessions": sessions}
+async def search_sessions(
+ q: str = Query(..., min_length=1, max_length=MAX_SEARCH_QUERY_CHARS),
+ limit: int = Query(default=50, ge=1, le=100),
+ offset: int = Query(default=0, ge=0),
+):
+ """Search titles and persisted user/assistant messages for a literal term."""
+ if not q.strip():
+ raise HTTPException(status_code=400, detail="Search query cannot be empty")
+ result = await get_session_store().search_sessions(q, limit=limit, offset=offset)
+ return {
+ "sessions": result["sessions"],
+ "total": result["total"],
+ "limit": limit,
+ "offset": offset,
+ }
+
+
# Cap (in characters) for a single event payload returned to the UI. RAG
# tools can attach whole KB documents to ``tool_result``/``observation``
# events; the frontend TraceSurface only needs a preview, and the LLM context
diff --git a/deeptutor/services/session/pocketbase_store.py b/deeptutor/services/session/pocketbase_store.py
index ef277f4a0..c86e34486 100644
--- a/deeptutor/services/session/pocketbase_store.py
+++ b/deeptutor/services/session/pocketbase_store.py
@@ -31,6 +31,7 @@ from .ask_user_trace import filter_ask_user_events
from .event_preview import MAX_TRACE_PREVIEW_EVENTS, compact_trace_preview
from .provider_response_state import redact_private_message_metadata
from .scope import StoreScope
+from .search import bounded_search_excerpt, normalize_search_query
from .workspace_preferences import upgrade_workspace_preferences
logger = logging.getLogger(__name__)
@@ -412,6 +413,97 @@ class PocketBaseSessionStore:
logger.warning(f"list_sessions failed: {exc}")
return []
+ async def search_sessions(
+ self,
+ query: str,
+ limit: int = 50,
+ offset: int = 0,
+ ) -> dict[str, Any]:
+ """Search the current user's native sessions without loading transcripts."""
+ normalized = normalize_search_query(query)
+ if not normalized:
+ return {"sessions": [], "total": 0}
+ uid = _current_user_id()
+ bounded_limit = max(1, min(int(limit), 100))
+ bounded_offset = max(0, int(offset))
+
+ def _search() -> dict[str, Any]:
+ pb = _pb()
+ records = pb.collection("sessions").get_full_list(
+ query_params={"filter": f"user_id={json.dumps(uid)}"}
+ )
+ records = [
+ record
+ for record in records
+ if not str(getattr(record, "session_id", "") or "").startswith("imported_")
+ ]
+ records.sort(
+ key=lambda record: (
+ _to_float(getattr(record, "session_updated_at", None))
+ or _to_float(getattr(record, "updated", None))
+ ),
+ reverse=True,
+ )
+
+ matched: list[tuple[Any, Any | None]] = []
+ query_literal = json.dumps(normalized, ensure_ascii=False)
+ for record in records:
+ sid = _validate_id(str(getattr(record, "session_id", "")), "session_id")
+ message_page = pb.collection("messages").get_list(
+ 1,
+ 1,
+ query_params={
+ "filter": (
+ f"session_id={json.dumps(sid)} && "
+ '(role="user" || role="assistant") && '
+ f"content~{query_literal}"
+ ),
+ "sort": "-msg_created_at,-created",
+ },
+ )
+ matching_messages = self._page_items(message_page)
+ title = str(getattr(record, "title", "") or "")
+ if normalized.casefold() in title.casefold() or matching_messages:
+ matched.append((record, matching_messages[0] if matching_messages else None))
+
+ page = matched[bounded_offset : bounded_offset + bounded_limit]
+ sessions: list[dict[str, Any]] = []
+ for record, match in page:
+ session = self._session_record_to_dict(record)
+ sid = session["session_id"]
+ summary_page = pb.collection("messages").get_list(
+ 1,
+ 1,
+ query_params={
+ "filter": f'session_id={json.dumps(sid)} && role!="system"',
+ "sort": "-msg_created_at,-created",
+ },
+ )
+ summary_items = self._page_items(summary_page)
+ session["message_count"] = self._page_total(summary_page)
+ session["last_message"] = str(
+ getattr(summary_items[0], "content", "") if summary_items else ""
+ )
+ session["match_message_id"] = getattr(match, "id", None)
+ session["match_role"] = getattr(match, "role", None)
+ session["match_created_at"] = (
+ _to_float(getattr(match, "msg_created_at", None)) if match is not None else None
+ )
+ match_content = (
+ str(getattr(match, "content", "") or "")
+ if match is not None
+ else session["title"]
+ )
+ session["match_excerpt"] = bounded_search_excerpt(match_content, normalized)
+ sessions.append(session)
+ return {"sessions": sessions, "total": len(matched)}
+
+ try:
+ return await asyncio.to_thread(_search)
+ except Exception as exc:
+ logger.warning(f"search_sessions failed: {exc}")
+ return {"sessions": [], "total": 0}
+
async def get_session_summaries(
self,
session_ids: list[str],
@@ -451,7 +543,7 @@ class PocketBaseSessionStore:
1,
query_params={
"filter": f'session_id="{sid}" && role!="system"',
- "sort": "-msg_created_at",
+ "sort": "-msg_created_at,-created",
},
)
)
diff --git a/deeptutor/services/session/protocol.py b/deeptutor/services/session/protocol.py
index d13da4c4e..732f361e5 100644
--- a/deeptutor/services/session/protocol.py
+++ b/deeptutor/services/session/protocol.py
@@ -54,6 +54,10 @@ class SessionRepository(Protocol):
async def list_sessions(self, limit: int = 50, offset: int = 0) -> list[dict[str, Any]]: ...
+ async def search_sessions(
+ self, query: str, limit: int = 50, offset: int = 0
+ ) -> dict[str, Any]: ...
+
async def update_session_title(self, session_id: str, title: str) -> bool: ...
async def delete_session(self, session_id: str) -> bool: ...
@@ -194,6 +198,13 @@ class SessionStoreProtocol(SessionRepository, TurnRepository, MessageRepository,
offset: int = 0,
) -> list[dict[str, Any]]: ...
+ async def search_sessions(
+ self,
+ query: str,
+ limit: int = 50,
+ offset: int = 0,
+ ) -> dict[str, Any]: ...
+
async def get_session_summaries(
self,
session_ids: list[str],
diff --git a/deeptutor/services/session/search.py b/deeptutor/services/session/search.py
new file mode 100644
index 000000000..e40356e34
--- /dev/null
+++ b/deeptutor/services/session/search.py
@@ -0,0 +1,45 @@
+"""Shared result shaping for literal conversation-history search."""
+
+from __future__ import annotations
+
+import re
+
+MAX_SEARCH_QUERY_CHARS = 200
+MAX_SEARCH_EXCERPT_CHARS = 320
+
+
+def normalize_search_query(value: str) -> str:
+ """Trim and bound a user-entered literal history query."""
+ return str(value or "").strip()[:MAX_SEARCH_QUERY_CHARS]
+
+
+def bounded_search_excerpt(content: str, query: str) -> str:
+ """Return a short plain-text window around the first literal match."""
+ text = str(content or "").strip()
+ if not text:
+ return ""
+ match = re.search(re.escape(query), text, flags=re.IGNORECASE) if query else None
+ if match is None:
+ return text[:MAX_SEARCH_EXCERPT_CHARS]
+
+ context_before = 96
+ start = max(0, match.start() - context_before)
+ end = min(len(text), start + MAX_SEARCH_EXCERPT_CHARS)
+ if end - start < MAX_SEARCH_EXCERPT_CHARS:
+ start = max(0, end - MAX_SEARCH_EXCERPT_CHARS)
+ excerpt = text[start:end]
+ if start:
+ excerpt = f"…{excerpt}"
+ if end < len(text):
+ excerpt = f"{excerpt}…"
+ if len(excerpt) > MAX_SEARCH_EXCERPT_CHARS:
+ excerpt = f"{excerpt[: MAX_SEARCH_EXCERPT_CHARS - 1]}…"
+ return excerpt
+
+
+__all__ = [
+ "MAX_SEARCH_EXCERPT_CHARS",
+ "MAX_SEARCH_QUERY_CHARS",
+ "bounded_search_excerpt",
+ "normalize_search_query",
+]
diff --git a/deeptutor/services/session/sqlite_store.py b/deeptutor/services/session/sqlite_store.py
index ebb6fefaa..c914eb4d9 100644
--- a/deeptutor/services/session/sqlite_store.py
+++ b/deeptutor/services/session/sqlite_store.py
@@ -29,6 +29,7 @@ from deeptutor.utils.secret_files import ensure_private_directory, ensure_privat
from .ask_user_trace import select_ask_user_events
from .event_preview import MAX_TRACE_PREVIEW_EVENTS, compact_trace_preview
from .provider_response_state import redact_private_message_metadata
+from .search import bounded_search_excerpt, normalize_search_query
from .workspace_preferences import upgrade_workspace_preferences
@@ -2177,6 +2178,133 @@ class SQLiteSessionStore:
) -> list[dict[str, Any]]:
return await self._run(self._list_sessions_sync, limit, offset)
+ def _search_sessions_sync(
+ self,
+ query: str,
+ limit: int = 50,
+ offset: int = 0,
+ ) -> dict[str, Any]:
+ """Search native session titles and visible message text literally."""
+ normalized = normalize_search_query(query)
+ if not normalized:
+ return {"sessions": [], "total": 0}
+
+ match_condition = r"""
+ s.id NOT LIKE 'imported\_%' ESCAPE '\'
+ AND (
+ INSTR(LOWER(COALESCE(s.title, '')), LOWER(?)) > 0
+ OR EXISTS (
+ SELECT 1 FROM messages candidate
+ WHERE candidate.session_id = s.id
+ AND candidate.role IN ('user', 'assistant')
+ AND INSTR(LOWER(COALESCE(candidate.content, '')), LOWER(?)) > 0
+ )
+ )
+ """
+ with self._connect() as conn:
+ total = int(
+ conn.execute(
+ f"SELECT COUNT(*) FROM sessions s WHERE {match_condition}", # nosec B608
+ (normalized, normalized),
+ ).fetchone()[0]
+ )
+ rows = conn.execute(
+ f"""
+ WITH matched_sessions AS (
+ SELECT s.*
+ FROM sessions s
+ WHERE {match_condition}
+ ORDER BY s.updated_at DESC
+ LIMIT ? OFFSET ?
+ ),
+ best_messages AS (
+ SELECT m.session_id, m.id, m.role, m.created_at,
+ SUBSTR(
+ m.content,
+ MAX(1, INSTR(LOWER(m.content), LOWER(?)) - 160),
+ 520
+ ) AS content
+ FROM messages m
+ JOIN matched_sessions s ON s.id = m.session_id
+ WHERE m.role IN ('user', 'assistant')
+ AND INSTR(LOWER(COALESCE(m.content, '')), LOWER(?)) > 0
+ AND m.id = (
+ SELECT newest.id FROM messages newest
+ WHERE newest.session_id = m.session_id
+ AND newest.role IN ('user', 'assistant')
+ AND INSTR(
+ LOWER(COALESCE(newest.content, '')), LOWER(?)
+ ) > 0
+ ORDER BY newest.created_at DESC, newest.id DESC
+ LIMIT 1
+ )
+ )
+ SELECT
+ s.id, s.title, s.created_at, s.updated_at,
+ s.compressed_summary, s.summary_up_to_msg_id,
+ s.preferences_json,
+ COUNT(CASE WHEN m.role != 'system' THEN 1 END) AS message_count,
+ COALESCE(
+ (SELECT t.status FROM turns t WHERE t.session_id = s.id
+ ORDER BY t.updated_at DESC LIMIT 1),
+ 'idle'
+ ) AS status,
+ COALESCE(
+ (SELECT t.id FROM turns t WHERE t.session_id = s.id
+ AND t.status IN ('queued', 'running', 'waiting_input')
+ ORDER BY t.updated_at DESC LIMIT 1),
+ ''
+ ) AS active_turn_id,
+ COALESCE(
+ (SELECT t.capability FROM turns t WHERE t.session_id = s.id
+ ORDER BY t.updated_at DESC LIMIT 1),
+ ''
+ ) AS capability,
+ COALESCE(
+ (SELECT latest.content FROM messages latest
+ WHERE latest.session_id = s.id AND latest.role != 'system'
+ AND TRIM(COALESCE(latest.content, '')) != ''
+ ORDER BY latest.id DESC LIMIT 1),
+ ''
+ ) AS last_message,
+ bm.id AS match_message_id,
+ bm.role AS match_role,
+ bm.created_at AS match_created_at,
+ COALESCE(bm.content, s.title, '') AS match_content
+ FROM matched_sessions s
+ LEFT JOIN messages m ON m.session_id = s.id
+ LEFT JOIN best_messages bm ON bm.session_id = s.id
+ GROUP BY s.id
+ ORDER BY s.updated_at DESC
+ """, # nosec B608 - match_condition is a module-owned SQL literal
+ (
+ normalized,
+ normalized,
+ max(1, min(int(limit), 100)),
+ max(0, int(offset)),
+ normalized,
+ normalized,
+ normalized,
+ ),
+ ).fetchall()
+
+ sessions: list[dict[str, Any]] = []
+ for row in rows:
+ payload = self._session_summary_payload(row)
+ content = str(payload.pop("match_content", "") or "")
+ payload["match_excerpt"] = bounded_search_excerpt(content, normalized)
+ sessions.append(payload)
+ return {"sessions": sessions, "total": total}
+
+ async def search_sessions(
+ self,
+ query: str,
+ limit: int = 50,
+ offset: int = 0,
+ ) -> dict[str, Any]:
+ """Return a bounded page of native sessions matching a literal query."""
+ return await self._run(self._search_sessions_sync, query, limit, offset)
+
async def get_session_summaries(
self,
session_ids: list[str],
diff --git a/tests/api/test_session_search.py b/tests/api/test_session_search.py
new file mode 100644
index 000000000..7d54a8885
--- /dev/null
+++ b/tests/api/test_session_search.py
@@ -0,0 +1,34 @@
+from __future__ import annotations
+
+import asyncio
+
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from deeptutor.api.routers import sessions as sessions_router
+from deeptutor.services.session.sqlite_store import SQLiteSessionStore
+
+
+def test_session_search_route_precedes_dynamic_session_route(tmp_path, monkeypatch) -> None:
+ store = SQLiteSessionStore(tmp_path / "history.db")
+ session = asyncio.run(store.create_session(title="Older chat", session_id="native"))
+ message_id = asyncio.run(
+ store.add_message(session["id"], "user", "The remembered equation is x + y")
+ )
+ monkeypatch.setattr(sessions_router, "get_session_store", lambda: store)
+ app = FastAPI()
+ app.include_router(sessions_router.router, prefix="/api/sessions")
+
+ with TestClient(app) as client:
+ response = client.get("/api/sessions/search", params={"q": "equation", "limit": 5})
+ blank = client.get("/api/sessions/search", params={"q": " "})
+ too_long = client.get("/api/sessions/search", params={"q": "x" * 201})
+
+ assert response.status_code == 200
+ body = response.json()
+ assert body["total"] == 1
+ assert body["limit"] == 5
+ assert body["offset"] == 0
+ assert body["sessions"][0]["match_message_id"] == message_id
+ assert blank.status_code == 400
+ assert too_long.status_code == 422
diff --git a/tests/services/session/test_history_search.py b/tests/services/session/test_history_search.py
new file mode 100644
index 000000000..975ddbc00
--- /dev/null
+++ b/tests/services/session/test_history_search.py
@@ -0,0 +1,66 @@
+from __future__ import annotations
+
+import asyncio
+import sqlite3
+
+from deeptutor.services.session.sqlite_store import SQLiteSessionStore
+
+
+def run(coro):
+ return asyncio.run(coro)
+
+
+def test_searches_full_visible_transcript_and_returns_latest_match(tmp_path) -> None:
+ store = SQLiteSessionStore(tmp_path / "history.db")
+ session = run(store.create_session(title="Probability notes", session_id="native"))
+ first_id = run(store.add_message(session["id"], "user", "Explain Bayes theorem slowly"))
+ latest_id = run(store.add_message(session["id"], "assistant", "A later BAYES theorem recap"))
+ run(store.add_message(session["id"], "system", "Bayes provider metadata"))
+
+ result = run(store.search_sessions("bayes", limit=10, offset=0))
+
+ assert result["total"] == 1
+ [match] = result["sessions"]
+ assert match["session_id"] == "native"
+ assert match["match_message_id"] == latest_id
+ assert match["match_message_id"] != first_id
+ assert match["match_role"] == "assistant"
+ assert "BAYES theorem" in match["match_excerpt"]
+ assert len(match["match_excerpt"]) <= 320
+
+
+def test_search_is_literal_paginated_and_preserves_history_visibility(tmp_path) -> None:
+ store = SQLiteSessionStore(tmp_path / "history.db")
+ first = run(store.create_session(title="100%_literal", session_id="first"))
+ second = run(store.create_session(title="Second", session_id="second"))
+ archived = run(store.create_session(title="Archived", session_id="archived"))
+ imported = run(store.create_session(title="Imported", session_id="imported_codex_hidden"))
+ run(store.add_message(second["id"], "user", "also 100%_literal here"))
+ run(store.add_message(archived["id"], "assistant", "100%_literal archived match"))
+ run(store.update_session_preferences(archived["id"], {"archived": True}))
+ run(store.add_message(imported["id"], "user", "100%_literal imported match"))
+
+ with sqlite3.connect(store.db_path) as conn:
+ conn.executemany(
+ "UPDATE sessions SET updated_at = ? WHERE id = ?",
+ [(40, first["id"]), (30, second["id"]), (20, archived["id"])],
+ )
+
+ first_page = run(store.search_sessions("%_", limit=2, offset=0))
+ second_page = run(store.search_sessions("%_", limit=2, offset=2))
+
+ assert first_page["total"] == 3
+ assert [row["session_id"] for row in first_page["sessions"]] == ["first", "second"]
+ assert first_page["sessions"][0]["match_message_id"] is None
+ assert first_page["sessions"][0]["match_excerpt"] == "100%_literal"
+ assert [row["session_id"] for row in second_page["sessions"]] == ["archived"]
+ assert second_page["sessions"][0]["preferences"]["archived"] is True
+
+
+def test_search_ignores_system_only_matches_and_empty_queries(tmp_path) -> None:
+ store = SQLiteSessionStore(tmp_path / "history.db")
+ session = run(store.create_session(title="Unrelated", session_id="system-only"))
+ run(store.add_message(session["id"], "system", "private needle"))
+
+ assert run(store.search_sessions("needle")) == {"sessions": [], "total": 0}
+ assert run(store.search_sessions(" ")) == {"sessions": [], "total": 0}
diff --git a/tests/services/session/test_pocketbase_isolation.py b/tests/services/session/test_pocketbase_isolation.py
index 0cccb178a..907b3f540 100644
--- a/tests/services/session/test_pocketbase_isolation.py
+++ b/tests/services/session/test_pocketbase_isolation.py
@@ -11,6 +11,7 @@ user's sessions.
from __future__ import annotations
from contextlib import contextmanager
+import json
from pathlib import Path
import re
@@ -57,6 +58,17 @@ class _Collection:
def _matches(self, record: _Record, query_params: dict | None) -> bool:
flt = (query_params or {}).get("filter") or ""
+ role_pair = '(role="user" || role="assistant")'
+ if role_pair in flt:
+ if str(getattr(record, "role", "")) not in {"user", "assistant"}:
+ return False
+ flt = flt.replace(role_pair, "")
+ contains = re.search(r"content~(\"(?:\\.|[^\"])*\")", flt)
+ if contains is not None:
+ needle = json.loads(contains.group(1))
+ if needle.casefold() not in str(getattr(record, "content", "")).casefold():
+ return False
+ flt = flt.replace(contains.group(0), "")
for field, expected in _CLAUSE.findall(flt):
if str(getattr(record, field, "")) != expected:
return False
@@ -75,11 +87,14 @@ class _Collection:
matched = self.get_full_list(query_params)
sort = str((query_params or {}).get("sort") or "")
if sort:
- field = sort.lstrip("-")
- matched.sort(
- key=lambda record: getattr(record, field, 0),
- reverse=sort.startswith("-"),
- )
+ for part in reversed(sort.split(",")):
+ field = part.lstrip("-")
+ matched.sort(
+ key=lambda record: getattr(
+ record, field, record.id if field == "created" else 0
+ ),
+ reverse=part.startswith("-"),
+ )
start = (page - 1) * per_page
return _Result(matched[start : start + per_page], len(matched))
@@ -135,6 +150,29 @@ async def test_list_sessions_only_returns_own(fake_pb) -> None:
assert {s["session_id"] for s in alice_sessions} == {"s_a1", "s_a2"}
+async def test_search_sessions_is_owner_scoped_and_preserves_native_visibility(fake_pb) -> None:
+ store = PocketBaseSessionStore()
+ with as_user("alice"):
+ own = await store.create_session(title="Own", session_id="s_own")
+ archived = await store.create_session(title="Archive", session_id="s_archived")
+ imported = await store.create_session(title="Import", session_id="imported_codex_hidden")
+ await store.add_message(own["id"], "user", "private Bayes theorem")
+ await store.add_message(archived["id"], "assistant", "archived Bayes theorem")
+ await store.update_session_preferences(archived["id"], {"archived": True})
+ await store.add_message(imported["id"], "user", "imported Bayes theorem")
+ with as_user("bob"):
+ other = await store.create_session(title="Other", session_id="s_other")
+ await store.add_message(other["id"], "user", "other Bayes theorem")
+ bob = await store.search_sessions("bayes")
+ with as_user("alice"):
+ alice = await store.search_sessions("bayes")
+
+ assert [row["session_id"] for row in bob["sessions"]] == ["s_other"]
+ assert {row["session_id"] for row in alice["sessions"]} == {"s_own", "s_archived"}
+ archived_row = next(row for row in alice["sessions"] if row["session_id"] == "s_archived")
+ assert archived_row["preferences"]["archived"] is True
+
+
async def test_legacy_workspace_preferences_are_normalized_at_repository_boundary(
fake_pb,
) -> None:
diff --git a/web/components/chat/HistorySessionPicker.tsx b/web/components/chat/HistorySessionPicker.tsx
index 8f6a81723..df2d02454 100644
--- a/web/components/chat/HistorySessionPicker.tsx
+++ b/web/components/chat/HistorySessionPicker.tsx
@@ -16,7 +16,9 @@ import PickerHeader from "@/components/common/PickerHeader";
import {
getSession,
listSessions,
+ searchSessions,
type SessionDetail,
+ type SessionSearchResult,
type SessionSummary,
} from "@/lib/session-api";
import { normalizeMessageContent, truncateText } from "@/lib/message-content";
@@ -58,9 +60,19 @@ export default function HistorySessionPicker({
// title lands; mirror SessionList with a localized "New chat" label.
const placeholderLabel = t("New chat");
const [sessions, setSessions] = useState<SessionSummary[]>([]);
- const [selectedIds, setSelectedIds] = useState<string[]>([]);
+ const [selectedSessions, setSelectedSessions] = useState<
+ Record<string, SessionSummary>
+ >({});
const [query, setQuery] = useState("");
+ const queryRef = useRef(query);
const [loading, setLoading] = useState(false);
+ const [searchResults, setSearchResults] = useState<SessionSearchResult[]>([]);
+ const [searchTotal, setSearchTotal] = useState(0);
+ const [searchLoading, setSearchLoading] = useState(false);
+ const [loadingMore, setLoadingMore] = useState(false);
+ const searchGenerationRef = useRef(0);
+ const loadMoreAbortRef = useRef<AbortController | null>(null);
+ const selectedIds = Object.keys(selectedSessions);
// The session shown in the right-hand preview pane. Driven by hover/focus
// and click so the preview tracks wherever the user's attention is — the
@@ -84,6 +96,7 @@ export default function HistorySessionPicker({
const data = await listSessions(200, 0, { force: true });
if (!mounted) return;
setSessions(data);
+ if (queryRef.current.trim()) return;
// Default the preview to the most recent session so the right pane is
// never blank on open.
setActiveId((prev) => {
@@ -104,6 +117,51 @@ export default function HistorySessionPicker({
};
}, [open]);
+ useEffect(() => {
+ const generation = ++searchGenerationRef.current;
+ loadMoreAbortRef.current?.abort();
+ loadMoreAbortRef.current = null;
+ setLoadingMore(false);
+ const term = query.trim();
+ if (!open || !term) {
+ setSearchResults([]);
+ setSearchTotal(0);
+ setSearchLoading(false);
+ return;
+ }
+
+ setSearchResults([]);
+ setSearchTotal(0);
+ setSearchLoading(true);
+ let controller: AbortController | null = null;
+ const timer = window.setTimeout(() => {
+ controller = new AbortController();
+ searchSessions(term, 50, 0, controller.signal)
+ .then((page) => {
+ if (generation !== searchGenerationRef.current) return;
+ setSearchResults(page.sessions);
+ setSearchTotal(page.total);
+ setActiveId(page.sessions[0] ? sessionKey(page.sessions[0]) : null);
+ })
+ .catch((error: unknown) => {
+ if (error instanceof DOMException && error.name === "AbortError")
+ return;
+ if (generation !== searchGenerationRef.current) return;
+ setSearchResults([]);
+ setSearchTotal(0);
+ })
+ .finally(() => {
+ if (generation === searchGenerationRef.current)
+ setSearchLoading(false);
+ });
+ }, 300);
+
+ return () => {
+ window.clearTimeout(timer);
+ controller?.abort();
+ };
+ }, [open, query]);
+
// Lazily fetch the active session's transcript for the preview pane.
useEffect(() => {
if (!open || !activeId) return;
@@ -127,27 +185,25 @@ export default function HistorySessionPicker({
};
}, [activeId, open]);
- const filteredSessions = useMemo(() => {
- const keyword = query.trim().toLowerCase();
- if (!keyword) return sessions;
- return sessions.filter((session) => {
- const title = String(session.title || "").toLowerCase();
- const lastMessage = normalizeMessageContent(
- session.last_message,
- ).toLowerCase();
- return title.includes(keyword) || lastMessage.includes(keyword);
- });
- }, [query, sessions]);
+ const searching = query.trim().length > 0;
+ const visibleSessions: SessionSummary[] = searching
+ ? searchResults
+ : sessions;
- const toggleSession = (id: string) => {
- setSelectedIds((prev) =>
- prev.includes(id) ? prev.filter((item) => item !== id) : [...prev, id],
- );
+ const toggleSession = (session: SessionSummary) => {
+ const id = sessionKey(session);
+ setSelectedSessions((prev) => {
+ if (!prev[id]) return { ...prev, [id]: session };
+ const next = { ...prev };
+ delete next[id];
+ return next;
+ });
};
const handleApply = () => {
- const selected = sessions
- .filter((session) => selectedIds.includes(sessionKey(session)))
+ const selected = selectedIds
+ .map((id) => selectedSessions[id])
+ .filter((session): session is SessionSummary => Boolean(session))
.map((session) => ({
sessionId: sessionKey(session),
title: displaySessionTitle(session.title, placeholderLabel),
@@ -157,8 +213,12 @@ export default function HistorySessionPicker({
};
const activeSession = activeId
- ? sessions.find((s) => sessionKey(s) === activeId)
+ ? visibleSessions.find((s) => sessionKey(s) === activeId)
: undefined;
+ const activeSearchResult =
+ searching && activeId
+ ? searchResults.find((s) => sessionKey(s) === activeId)
+ : undefined;
const activeDetail = activeId ? details[activeId] : undefined;
const activeLoading =
previewLoadingId !== null && previewLoadingId === activeId;
@@ -190,14 +250,18 @@ export default function HistorySessionPicker({
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-[var(--muted-foreground)]" />
<input
value={query}
- onChange={(event) => setQuery(event.target.value)}
- placeholder={t("Search sessions by title or last message")}
+ onChange={(event) => {
+ queryRef.current = event.target.value;
+ setQuery(event.target.value);
+ }}
+ maxLength={200}
+ placeholder={t("Search full conversation history")}
className="w-full rounded-xl border border-[var(--border)] bg-[var(--card)] py-2.5 pl-9 pr-3 text-[13px] text-[var(--foreground)] outline-none transition focus:border-[var(--primary)]/50 focus:ring-2 focus:ring-[var(--primary)]/15"
/>
</div>
{selectedIds.length > 0 && (
<button
- onClick={() => setSelectedIds([])}
+ onClick={() => setSelectedSessions({})}
className="shrink-0 rounded-xl border border-[var(--border)] bg-[var(--card)] px-3 py-2.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
>
{t("Clear")}
@@ -206,21 +270,24 @@ export default function HistorySessionPicker({
</div>
<div className="min-h-0 flex-1 overflow-y-auto px-2 pb-2">
- {loading ? (
+ {(searching ? searchLoading : loading) ? (
<div className="flex min-h-[280px] items-center justify-center">
<Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />
</div>
- ) : filteredSessions.length ? (
+ ) : visibleSessions.length ? (
<div className="flex flex-col gap-0.5">
- {filteredSessions.map((session) => {
+ {visibleSessions.map((session) => {
const id = sessionKey(session);
const selected = selectedIds.includes(id);
const active = id === activeId;
+ const searchResult = searching
+ ? (session as SessionSearchResult)
+ : null;
return (
<button
key={id}
onClick={() => {
- toggleSession(id);
+ toggleSession(session);
setActiveId(id);
}}
onMouseEnter={() => setActiveId(id)}
@@ -259,10 +326,56 @@ export default function HistorySessionPicker({
<MessageSquare size={11} strokeWidth={1.8} />
{session.message_count ?? 0} {t("messages")}
</span>
+ {searchResult && (
+ <span className="mt-1 line-clamp-2 block text-[11px] leading-relaxed text-[var(--muted-foreground)]">
+ {searchResult.match_excerpt}
+ </span>
+ )}
</span>
</button>
);
})}
+ {searching && searchResults.length < searchTotal && (
+ <button
+ type="button"
+ disabled={loadingMore}
+ onClick={() => {
+ const term = query.trim();
+ if (!term || loadingMore) return;
+ const generation = searchGenerationRef.current;
+ const controller = new AbortController();
+ loadMoreAbortRef.current?.abort();
+ loadMoreAbortRef.current = controller;
+ setLoadingMore(true);
+ searchSessions(
+ term,
+ 50,
+ searchResults.length,
+ controller.signal,
+ )
+ .then((page) => {
+ if (generation !== searchGenerationRef.current)
+ return;
+ setSearchResults((prev) => [
+ ...prev,
+ ...page.sessions,
+ ]);
+ setSearchTotal(page.total);
+ })
+ .catch(() => {
+ /* keep the already loaded page */
+ })
+ .finally(() => {
+ if (generation === searchGenerationRef.current) {
+ setLoadingMore(false);
+ }
+ });
+ }}
+ className="mx-2 my-2 rounded-lg px-3 py-2 text-[12px] font-medium text-[var(--primary)] transition hover:bg-[var(--muted)] disabled:opacity-50"
+ >
+ {loadingMore ? t("Loading…") : t("Load more")}
+ </button>
+ )}
</div>
) : (
<div className="px-6 py-14 text-center text-[13px] text-[var(--muted-foreground)]">
@@ -315,7 +428,10 @@ export default function HistorySessionPicker({
{t("Loading preview…")}
</div>
) : activeDetail ? (
- <ConversationPreview detail={activeDetail} />
+ <ConversationPreview
+ detail={activeDetail}
+ focusMessageId={activeSearchResult?.match_message_id}
+ />
) : (
<div className="flex min-h-[200px] items-center justify-center text-[12px] text-[var(--muted-foreground)]">
{t("No messages in this session.")}
@@ -359,8 +475,15 @@ export default function HistorySessionPicker({
* role-labelled text — enough to recognize a conversation at a glance without
* pulling in the full markdown/KaTeX renderer.
*/
-function ConversationPreview({ detail }: { detail: SessionDetail }) {
+function ConversationPreview({
+ detail,
+ focusMessageId,
+}: {
+ detail: SessionDetail;
+ focusMessageId?: number | string | null;
+}) {
const { t } = useTranslation();
+ const messageRefs = useRef(new Map<string, HTMLDivElement>());
const turns = useMemo(
() =>
(detail.messages || [])
@@ -374,6 +497,13 @@ function ConversationPreview({ detail }: { detail: SessionDetail }) {
[detail.messages],
);
+ useEffect(() => {
+ if (focusMessageId === null || focusMessageId === undefined) return;
+ messageRefs.current
+ .get(String(focusMessageId))
+ ?.scrollIntoView?.({ block: "center" });
+ }, [focusMessageId, turns]);
+
if (turns.length === 0) {
return (
<div className="flex min-h-[200px] items-center justify-center text-[12px] text-[var(--muted-foreground)]">
@@ -387,7 +517,21 @@ function ConversationPreview({ detail }: { detail: SessionDetail }) {
{turns.map((turn) => {
const isUser = turn.role === "user";
return (
- <div key={turn.id}>
+ <div
+ key={turn.id}
+ ref={(node) => {
+ const key = String(turn.id);
+ if (node) messageRefs.current.set(key, node);
+ else messageRefs.current.delete(key);
+ }}
+ className={
+ focusMessageId !== null &&
+ focusMessageId !== undefined &&
+ String(turn.id) === String(focusMessageId)
+ ? "rounded-xl bg-[var(--primary)]/[0.06] p-3 ring-1 ring-[var(--primary)]/20"
+ : undefined
+ }
+ >
<div className="mb-1 flex items-center gap-1.5 text-[11px] font-medium text-[var(--muted-foreground)]">
{isUser ? (
<UserRound size={12} strokeWidth={1.9} />
diff --git a/web/contracts/generated/api.ts b/web/contracts/generated/api.ts
index c950b5168..4e0342db5 100644
--- a/web/contracts/generated/api.ts
+++ b/web/contracts/generated/api.ts
@@ -6414,6 +6414,26 @@ export interface paths {
readonly patch?: never;
readonly trace?: never;
};
+ readonly "/api/sessions/search": {
+ readonly parameters: {
+ readonly query?: never;
+ readonly header?: never;
+ readonly path?: never;
+ readonly cookie?: never;
+ };
+ /**
+ * Search Sessions
+ * @description Search titles and persisted user/assistant messages for a literal term.
+ */
+ readonly get: operations["search_sessions_api_sessions_search_get"];
+ readonly put?: never;
+ readonly post?: never;
+ readonly delete?: never;
+ readonly options?: never;
+ readonly head?: never;
+ readonly patch?: never;
+ readonly trace?: never;
+ };
readonly "/api/settings": {
readonly parameters: {
readonly query?: never;
@@ -28543,6 +28563,43 @@ export interface operations {
};
};
};
+ readonly search_sessions_api_sessions_search_get: {
+ readonly parameters: {
+ readonly query: {
+ readonly limit?: number;
+ readonly offset?: number;
+ readonly q: string;
+ };
+ readonly header?: {
+ readonly Authorization?: string | null;
+ };
+ readonly path?: never;
+ readonly cookie?: {
+ readonly dt_token?: string | null;
+ };
+ };
+ readonly requestBody?: never;
+ readonly responses: {
+ /** @description Successful Response */
+ readonly 200: {
+ headers: {
+ readonly [name: string]: unknown;
+ };
+ content: {
+ readonly "application/json": unknown;
+ };
+ };
+ /** @description Validation Error */
+ readonly 422: {
+ headers: {
+ readonly [name: string]: unknown;
+ };
+ content: {
+ readonly "application/json": components["schemas"]["HTTPValidationError"];
+ };
+ };
+ };
+ };
readonly get_settings_api_settings_get: {
readonly parameters: {
readonly query?: never;
diff --git a/web/contracts/schema/openapi.json b/web/contracts/schema/openapi.json
index 8685a2efe..9c2862f3e 100644
--- a/web/contracts/schema/openapi.json
+++ b/web/contracts/schema/openapi.json
@@ -39810,6 +39810,104 @@
]
}
},
+ "/api/sessions/search": {
+ "get": {
+ "description": "Search titles and persisted user/assistant messages for a literal term.",
+ "operationId": "search_sessions_api_sessions_search_get",
+ "parameters": [
+ {
+ "in": "query",
+ "name": "q",
+ "required": true,
+ "schema": {
+ "maxLength": 200,
+ "minLength": 1,
+ "title": "Q",
+ "type": "string"
+ }
+ },
+ {
+ "in": "query",
+ "name": "limit",
+ "required": false,
+ "schema": {
+ "default": 50,
+ "maximum": 100,
+ "minimum": 1,
+ "title": "Limit",
+ "type": "integer"
+ }
+ },
+ {
+ "in": "query",
+ "name": "offset",
+ "required": false,
+ "schema": {
+ "default": 0,
+ "minimum": 0,
+ "title": "Offset",
+ "type": "integer"
+ }
+ },
+ {
+ "in": "header",
+ "name": "Authorization",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Authorization"
+ }
+ },
+ {
+ "in": "cookie",
+ "name": "dt_token",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Dt Token"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {}
+ }
+ },
+ "description": "Successful Response"
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ "description": "Validation Error"
+ }
+ },
+ "summary": "Search Sessions",
+ "tags": [
+ "sessions"
+ ]
+ }
+ },
"/api/sessions/{session_id}": {
"delete": {
"operationId": "delete_session_api_sessions__session_id__delete",
@@ -49642,7 +49740,9 @@
}
},
"summary": "Browse Invidious",
- "tags": ["video-learning"]
+ "tags": [
+ "video-learning"
+ ]
}
},
"/api/video-learning/materials/resolve": {
diff --git a/web/lib/session-api.ts b/web/lib/session-api.ts
index 987022013..dc3a1a2c5 100644
--- a/web/lib/session-api.ts
+++ b/web/lib/session-api.ts
@@ -108,6 +108,20 @@ export interface SessionSummary {
preferences?: SessionPreferences;
}
+export interface SessionSearchResult extends SessionSummary {
+ match_excerpt: string;
+ match_role?: "user" | "assistant" | null;
+ match_message_id?: number | string | null;
+ match_created_at?: number | null;
+}
+
+export interface SessionSearchPage {
+ sessions: SessionSearchResult[];
+ total: number;
+ limit: number;
+ offset: number;
+}
+
export interface ActiveTurnSummary {
id: string;
turn_id: string;
@@ -201,6 +215,24 @@ export async function listAllSessions(options?: {
}
}
+export async function searchSessions(
+ query: string,
+ limit = 50,
+ offset = 0,
+ signal?: AbortSignal,
+): Promise<SessionSearchPage> {
+ const qs = new URLSearchParams({
+ q: query,
+ limit: String(limit),
+ offset: String(offset),
+ });
+ const response = await apiFetch(apiUrl(`/api/sessions/search?${qs}`), {
+ cache: "no-store",
+ signal,
+ });
+ return expectJson<SessionSearchPage>(response);
+}
+
export async function getSession(
sessionId: string,
signal?: AbortSignal,
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index ea72027d8..4895c76da 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -691,6 +691,7 @@
"No messages in this session.": "No messages in this session.",
"Select a session to preview it here.": "Select a session to preview it here.",
"Search sessions by title or last message": "Search sessions by title or last message",
+ "Search full conversation history": "Search full conversation history",
"No matching sessions found.": "No matching sessions found.",
"Untitled session": "Untitled session",
"1 session selected": "1 session selected",
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index 702df3f39..332f1f31e 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -706,6 +706,7 @@
"No messages in this session.": "该会话暂无消息。",
"Select a session to preview it here.": "选择一个会话,在此预览内容。",
"Search sessions by title or last message": "按标题或最后一条消息搜索会话",
+ "Search full conversation history": "搜索完整会话历史",
"No matching sessions found.": "未找到匹配的会话。",
"Untitled session": "未命名会话",
"1 session selected": "已选 1 个会话",
diff --git a/web/tests/history-session-search.spec.tsx b/web/tests/history-session-search.spec.tsx
new file mode 100644
index 000000000..24bf07691
--- /dev/null
+++ b/web/tests/history-session-search.spec.tsx
@@ -0,0 +1,122 @@
+import { act, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, expect, it, vi } from "vitest";
+import HistorySessionPicker from "@/components/chat/HistorySessionPicker";
+
+const fixture = vi.hoisted(() => ({
+ calls: [] as Array<{ query: string; signal?: AbortSignal }>,
+}));
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+vi.mock("@/components/common/PickerShell", () => ({
+ default: ({
+ open,
+ children,
+ }: {
+ open: boolean;
+ children: React.ReactNode;
+ }) => (open ? <div>{children}</div> : null),
+}));
+vi.mock("@/components/common/PickerHeader", () => ({
+ default: ({ title }: { title: string }) => <h2>{title}</h2>,
+}));
+vi.mock("@/lib/session-api", () => ({
+ listSessions: vi.fn(async () => [
+ {
+ id: "recent",
+ session_id: "recent",
+ title: "Recent chat",
+ created_at: 1,
+ updated_at: 1,
+ message_count: 1,
+ last_message: "latest only",
+ },
+ ]),
+ getSession: vi.fn(async (id: string) => ({
+ id,
+ session_id: id,
+ title: id,
+ created_at: 1,
+ updated_at: 1,
+ messages: [
+ {
+ id: 7,
+ session_id: id,
+ role: "user",
+ content: `Matched body in ${id}`,
+ events: [],
+ attachments: [],
+ created_at: 1,
+ },
+ ],
+ })),
+ searchSessions: vi.fn(
+ async (
+ query: string,
+ _limit: number,
+ _offset: number,
+ signal?: AbortSignal,
+ ) => {
+ fixture.calls.push({ query, signal });
+ return {
+ sessions: [
+ {
+ id: `match-${query}`,
+ session_id: `match-${query}`,
+ title: "Older conversation",
+ created_at: 1,
+ updated_at: 1,
+ message_count: 4,
+ last_message: "unrelated ending",
+ match_excerpt: `Earlier transcript contains ${query}`,
+ match_role: "user",
+ match_message_id: 7,
+ match_created_at: 1,
+ },
+ ],
+ total: 1,
+ limit: 50,
+ offset: 0,
+ };
+ },
+ ),
+}));
+
+afterEach(() => {
+ vi.useRealTimers();
+ fixture.calls.length = 0;
+});
+
+it("debounces full-history search and aborts stale requests", async () => {
+ vi.useFakeTimers();
+ render(<HistorySessionPicker open onClose={vi.fn()} onApply={vi.fn()} />);
+ await act(async () => undefined);
+ expect(screen.getAllByText("Recent chat").length).toBeGreaterThan(0);
+
+ const input = screen.getByPlaceholderText("Search full conversation history");
+ fireEvent.change(input, { target: { value: "Bayes" } });
+ await act(async () => {
+ vi.advanceTimersByTime(300);
+ });
+ expect(fixture.calls.map((call) => call.query)).toEqual(["Bayes"]);
+
+ fireEvent.change(input, { target: { value: "posterior" } });
+ expect(fixture.calls[0].signal?.aborted).toBe(true);
+ await act(async () => {
+ vi.advanceTimersByTime(300);
+ });
+
+ expect(fixture.calls.map((call) => call.query)).toEqual([
+ "Bayes",
+ "posterior",
+ ]);
+ expect(
+ screen.getByText("Earlier transcript contains posterior"),
+ ).toBeInTheDocument();
+ await act(async () => {
+ await Promise.resolve();
+ });
+ const focusedMessage = screen.getByText("Matched body in match-posterior");
+ expect(focusedMessage.parentElement).toHaveClass("ring-1");
+});
diff --git a/web/tests/session-search-api.test.ts b/web/tests/session-search-api.test.ts
new file mode 100644
index 000000000..08b6a8a7e
--- /dev/null
+++ b/web/tests/session-search-api.test.ts
@@ -0,0 +1,40 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import { searchSessions } from "../lib/session-api";
+
+test("session search sends a literal bounded query and pagination", async () => {
+ const original = globalThis.fetch;
+ let capturedUrl = "";
+ let capturedSignal: AbortSignal | null | undefined;
+ (globalThis as { fetch: typeof fetch }).fetch = async (input, init) => {
+ capturedUrl = String(input);
+ capturedSignal = init?.signal;
+ return new Response(
+ JSON.stringify({ sessions: [], total: 0, limit: 25, offset: 50 }),
+ {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ },
+ );
+ };
+ const controller = new AbortController();
+
+ try {
+ const page = await searchSessions(
+ "100%_literal",
+ 25,
+ 50,
+ controller.signal,
+ );
+ const url = new URL(capturedUrl, "http://deeptutor.local");
+ assert.equal(url.pathname, "/api/sessions/search");
+ assert.equal(url.searchParams.get("q"), "100%_literal");
+ assert.equal(url.searchParams.get("limit"), "25");
+ assert.equal(url.searchParams.get("offset"), "50");
+ assert.equal(capturedSignal, controller.signal);
+ assert.deepEqual(page.sessions, []);
+ } finally {
+ (globalThis as { fetch: typeof fetch }).fetch = original;
+ }
+});