/** * Cross-session full-text search (services/search.ts + GET /web/search). * * FTS5 index fed by persistSessionEvent; backfill from session_events for * pre-FTS deployments; visibility filtering (ownership) on the way out. */ import { describe, test, expect, beforeEach, mock } from 'bun:test' import { mockConfigModule } from './helpers/mock-config' mock.module('../config', () => mockConfigModule({})) import { freshDb } from './helpers/db' import { createUserDirectly } from './helpers/fixtures' import { Hono } from 'hono' import { storeReset, storeCreateSession, storeBindSession } from '../store' import { getDb } from '../db/sqlite' import { publishSessionEvent } from '../services/transport' import { buildFtsMatchExpression, resetSearchBackfillState, searchSessions, } from '../services/search' import webSessions from '../routes/web/sessions' import { issueToken } from '../auth/token' beforeEach(() => { freshDb() storeReset() const owner = createUserDirectly(getDb(), { username: 'search-owner' }) storeBindSession issueToken('search-owner') // bind helper below uses the username directly }) function makeSession(title: string, owner = 'search-owner'): string { const session = storeCreateSession({ title }) storeBindSession(session.id, owner) return session.id } function seed(sessionId: string, texts: string[]): void { for (const [i, text] of texts.entries()) { publishSessionEvent( sessionId, i % 2 === 0 ? 'user' : 'assistant', { content: text, uuid: `u-${sessionId}-${i}` }, i % 2 === 0 ? 'outbound' : 'inbound', ) } } describe('buildFtsMatchExpression', () => { test('quotes each token and joins with implicit AND', () => { expect(buildFtsMatchExpression('login bug')).toBe('"login" "bug"') }) test('escapes embedded double quotes', () => { // FTS5 转义:字面双引号翻倍 — "hi" 片段 → ""hi"",再包引号成 """hi""" expect(buildFtsMatchExpression('say "hi"')).toBe('"say" """hi"""') }) test('empty/whitespace queries return null', () => { expect(buildFtsMatchExpression('')).toBeNull() expect(buildFtsMatchExpression(' ')).toBeNull() }) }) describe('searchSessions', () => { test('finds matches across sessions, grouped with counts and snippets', () => { const s1 = makeSession('登录修复') const s2 = makeSession('部署脚本') seed(s1, ['帮我修复 login 页面', '正在修复 login…', 'login 已修复']) seed(s2, ['写一个 deploy 脚本', 'deploy 完成']) const results = searchSessions('search-owner', 'login') expect(results.length).toBe(1) expect(results[0].session_id).toBe(s1) expect(results[0].match_count).toBe(3) expect(results[0].title).toBe('登录修复') expect(results[0].snippet).toContain('login') // 多词 AND const both = searchSessions('search-owner', 'deploy 脚本') expect(both.map(r => r.session_id)).toEqual([s2]) }) test('filters sessions invisible to the searching user', () => { const stranger = createUserDirectly(getDb(), { username: 'search-stranger', }) const s1 = makeSession('私有会话') seed(s1, ['secret keyword here']) expect(searchSessions('search-owner', 'secret').length).toBe(1) expect(searchSessions(stranger.id, 'secret').length).toBe(0) expect(searchSessions('search-stranger', 'secret').length).toBe(0) }) test('empty and whitespace queries return no results without throwing', () => { makeSession('空查询') expect(searchSessions('search-owner', '')).toEqual([]) expect(searchSessions('search-owner', ' ')).toEqual([]) }) test('backfill reindexes pre-FTS rows from session_events', () => { const s1 = makeSession('回填') seed(s1, ['legacy content for backfill']) // 模拟旧部署:清空 FTS + 重置进程级 once 标记,下一次 search 触发回填 getDb().exec('DELETE FROM session_events_fts') resetSearchBackfillState() const results = searchSessions('search-owner', 'backfill') expect(results.length).toBe(1) expect(results[0].session_id).toBe(s1) }) test('archived sessions are excluded', () => { const s1 = makeSession('归档会话') seed(s1, ['archived keyword']) // 直接归档(updateSessionStatus 的终态守卫绕过 store 层即可) getDb() .query('UPDATE sessions SET status = $status WHERE id = $id') .run({ $status: 'archived', $id: s1 }) expect(searchSessions('search-owner', 'archived').length).toBe(0) }) test('matches a session by its id (Dashboard search box)', () => { const s1 = makeSession('与内容无关的标题') const results = searchSessions('search-owner', s1) expect(results.length).toBe(1) expect(results[0].session_id).toBe(s1) expect(results[0].match_count).toBe(0) }) test('matches a session by its title, including Chinese titles', () => { const s1 = makeSession('登录修复专项') const results = searchSessions('search-owner', '登录修复') expect(results.length).toBe(1) expect(results[0].session_id).toBe(s1) expect(results[0].match_count).toBe(0) }) test('content hits outrank title-only hits and are not duplicated', () => { // FTS 命中内容 + 标题 LIKE 同样命中 — 只保留 content 结果,不重复 const s1 = makeSession('deploy the deploy script') seed(s1, ['deploy the service now']) const results = searchSessions('search-owner', 'deploy') expect(results.length).toBe(1) expect(results[0].session_id).toBe(s1) expect(results[0].match_count).toBe(1) expect(results[0].snippet).toContain('deploy') }) test('CJK content substring falls back to LIKE when FTS matches nothing', () => { // unicode61 把一串 CJK 合成单 token — 子串查询 FTS 恒空,LIKE 兜底命中 const s1 = makeSession('中文内容检索') seed(s1, ['帮我修复登录页面的报错']) const results = searchSessions('search-owner', '登录页面') expect(results.length).toBe(1) expect(results[0].session_id).toBe(s1) expect(results[0].match_count).toBe(1) expect(results[0].snippet).toContain('登录页面') }) }) describe('GET /web/search', () => { function createApp() { const app = new Hono() app.route('/web', webSessions) return app } test('returns grouped results for the authenticated user', async () => { const s1 = makeSession('API 测试') seed(s1, ['findme in the api test']) const token = issueToken('search-owner').token const res = await createApp().request( `/web/search?q=${encodeURIComponent('findme')}`, { headers: { Authorization: `Bearer ${token}` } }, ) expect(res.status).toBe(200) const body = (await res.json()) as { results: Array<{ session_id: string; match_count: number }> } expect(body.results.length).toBe(1) expect(body.results[0].session_id).toBe(s1) expect(body.results[0].match_count).toBe(1) }) test('requires authentication', async () => { makeSession('auth test') const res = await createApp().request('/web/search?q=x') expect(res.status).toBe(401) }) })