Skip to content

An AI-powered search engine with a generative UI

feat(history): search chat history from the sidebar (#1086)

Nathan Pride5052f2c74ac2
diff --git a/app/api/search/__tests__/route.test.ts b/app/api/search/__tests__/route.test.ts
new file mode 100644
index 00000000..be10900b
--- /dev/null
+++ b/app/api/search/__tests__/route.test.ts
@@ -0,0 +1,165 @@
+import { NextRequest } from 'next/server'
+
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { getCurrentUserId } from '@/lib/auth/get-current-user'
+import * as dbActions from '@/lib/db/actions'
+import { HL_START, HL_STOP } from '@/lib/render/highlight-markers'
+
+import { GET } from '../route'
+
+vi.mock('@/lib/auth/get-current-user')
+vi.mock('@/lib/db/actions')
+
+function makeRequest(query: string, include?: string) {
+ const url = new URL('http://localhost:3000/api/search')
+ url.searchParams.set('q', query)
+ if (include) {
+ url.searchParams.set('include', include)
+ }
+ return new NextRequest(url.toString())
+}
+
+const titleChat = {
+ id: 'chat-1',
+ createdAt: new Date(),
+ title: 'Robert Frost Readings',
+ userId: 'user-1',
+ visibility: 'private' as const
+}
+
+const contentMatch = {
+ chatId: 'chat-2',
+ title: 'Poetry class',
+ snippet: `Stopping by ${HL_START}woods${HL_STOP}`
+}
+
+describe('Search API Route', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ vi.mocked(getCurrentUserId).mockResolvedValue('user-1')
+ vi.mocked(dbActions.searchChatTitles).mockResolvedValue([])
+ vi.mocked(dbActions.searchChatContent).mockResolvedValue([])
+ vi.mocked(dbActions.searchChatReasoning).mockResolvedValue([])
+ })
+
+ it('returns empty groups for unauthenticated requests', async () => {
+ vi.mocked(getCurrentUserId).mockResolvedValue(undefined as never)
+
+ const response = await GET(makeRequest('frost'))
+
+ expect(response.status).toBe(200)
+ await expect(response.json()).resolves.toEqual({
+ title: [],
+ content: []
+ })
+ expect(dbActions.searchChatTitles).not.toHaveBeenCalled()
+ expect(dbActions.searchChatContent).not.toHaveBeenCalled()
+ })
+
+ it('returns empty groups for queries shorter than 2 characters', async () => {
+ const response = await GET(makeRequest('f'))
+
+ await expect(response.json()).resolves.toEqual({ title: [], content: [] })
+ expect(dbActions.searchChatTitles).not.toHaveBeenCalled()
+ })
+
+ it('counts code points, not UTF-16 code units, for the minimum', async () => {
+ // 'πŸ˜€' is two code units but one character: it must not smuggle a
+ // broad single-character search past the minimum
+ const response = await GET(makeRequest('πŸ˜€'))
+
+ await expect(response.json()).resolves.toEqual({ title: [], content: [] })
+ expect(dbActions.searchChatTitles).not.toHaveBeenCalled()
+ expect(dbActions.searchChatContent).not.toHaveBeenCalled()
+
+ // two characters do run the search
+ await GET(makeRequest('πŸ˜€a'))
+ expect(dbActions.searchChatTitles).toHaveBeenCalled()
+ })
+
+ it('returns empty groups when the normalized query falls below the minimum', async () => {
+ // 'a ' plus a token crossing the cap normalizes to a single character;
+ // the raw length must not smuggle a broad one-character search through
+ const response = await GET(makeRequest('a ' + 'x'.repeat(300)))
+
+ await expect(response.json()).resolves.toEqual({ title: [], content: [] })
+ expect(dbActions.searchChatTitles).not.toHaveBeenCalled()
+ expect(dbActions.searchChatContent).not.toHaveBeenCalled()
+ })
+
+ it('groups title and content matches with caps 20/20', async () => {
+ vi.mocked(dbActions.searchChatTitles).mockResolvedValue([titleChat])
+ vi.mocked(dbActions.searchChatContent).mockResolvedValue([contentMatch])
+
+ const response = await GET(makeRequest('frost'))
+
+ expect(dbActions.searchChatTitles).toHaveBeenCalledWith(
+ 'user-1',
+ 'frost',
+ 20
+ )
+ expect(dbActions.searchChatContent).toHaveBeenCalledWith(
+ 'user-1',
+ 'frost',
+ 20
+ )
+ await expect(response.json()).resolves.toEqual({
+ title: [{ chatId: 'chat-1', title: 'Robert Frost Readings' }],
+ content: [
+ {
+ chatId: 'chat-2',
+ title: 'Poetry class',
+ snippet: 'Stopping by woods',
+ highlight: `Stopping by ${HL_START}woods${HL_STOP}`
+ }
+ ]
+ })
+ })
+
+ it('omits thinking unless include=reasoning is set', async () => {
+ const response = await GET(makeRequest('frost'))
+ const body = await response.json()
+
+ expect('thinking' in body).toBe(false)
+ expect(dbActions.searchChatReasoning).not.toHaveBeenCalled()
+ })
+
+ it('adds thinking results when include=reasoning with cap 10', async () => {
+ vi.mocked(dbActions.searchChatReasoning).mockResolvedValue([
+ {
+ chatId: 'chat-3',
+ title: 'Deep chat',
+ snippet: `about ${HL_START}frost${HL_STOP}`
+ }
+ ])
+
+ const response = await GET(makeRequest('frost', 'reasoning'))
+
+ expect(dbActions.searchChatReasoning).toHaveBeenCalledWith(
+ 'user-1',
+ 'frost',
+ 10
+ )
+ const body = await response.json()
+ expect(body.thinking).toEqual([
+ {
+ chatId: 'chat-3',
+ title: 'Deep chat',
+ snippet: 'about frost',
+ highlight: `about ${HL_START}frost${HL_STOP}`
+ }
+ ])
+ })
+
+ it('returns 500 with empty groups when the search fails', async () => {
+ vi.mocked(dbActions.searchChatContent).mockRejectedValue(
+ new Error('db down')
+ )
+
+ const response = await GET(makeRequest('frost'))
+
+ expect(response.status).toBe(500)
+ await expect(response.json()).resolves.toEqual({ title: [], content: [] })
+ })
+})
diff --git a/app/api/search/route.ts b/app/api/search/route.ts
new file mode 100644
index 00000000..cd200403
--- /dev/null
+++ b/app/api/search/route.ts
@@ -0,0 +1,93 @@
+import { NextRequest, NextResponse } from 'next/server'
+
+import { getCurrentUserId } from '@/lib/auth/get-current-user'
+import {
+ searchChatContent,
+ searchChatReasoning,
+ searchChatTitles
+} from '@/lib/db/actions'
+import { stripHighlightMarkers } from '@/lib/render/highlight-markers'
+import {
+ effectiveQueryLength,
+ MIN_QUERY_LENGTH,
+ normalizeSearchQuery
+} from '@/lib/utils/search-query'
+const TITLE_LIMIT = 20
+const CONTENT_LIMIT = 20
+const REASONING_LIMIT = 10
+
+type ContentSearchItem = {
+ chatId: string
+ title: string
+ snippet: string
+ highlight: string
+}
+
+interface SearchResponse {
+ title: { chatId: string; title: string }[]
+ content: ContentSearchItem[]
+ thinking?: ContentSearchItem[]
+}
+
+// ts_headline wraps matched terms in HL_START/HL_STOP control characters;
+// keep them for the `highlight` field and strip them for the plain `snippet`
+// field. Literal HTML in message text is therefore never altered or emphasized.
+function toContentItem(result: {
+ chatId: string
+ title: string
+ snippet: string
+}): ContentSearchItem {
+ return {
+ chatId: result.chatId,
+ title: result.title,
+ snippet: stripHighlightMarkers(result.snippet),
+ highlight: result.snippet
+ }
+}
+
+export async function GET(request: NextRequest) {
+ const emptyResponse: SearchResponse = { title: [], content: [] }
+
+ const userId = await getCurrentUserId()
+ if (!userId) {
+ return NextResponse.json<SearchResponse>(emptyResponse)
+ }
+
+ const { searchParams } = new URL(request.url)
+ // Normalize once here so the minimum applies to the query the search
+ // actually runs: a long paste can normalize below the minimum (e.g. 'a '
+ // plus a token crossing the cap), and the actions would then run a very
+ // broad single-character search despite the advertised minimum.
+ const query = normalizeSearchQuery(searchParams.get('q') ?? '')
+ // Counted in code points: a single non-BMP character is one character
+ // for the user and for Postgres' parser, even though it is two UTF-16
+ // code units in JS.
+ if (effectiveQueryLength(query) < MIN_QUERY_LENGTH) {
+ return NextResponse.json<SearchResponse>(emptyResponse)
+ }
+
+ try {
+ const includeReasoning = searchParams.get('include') === 'reasoning'
+
+ const [titleChats, contentMatches, reasoningMatches] = await Promise.all([
+ searchChatTitles(userId, query, TITLE_LIMIT),
+ searchChatContent(userId, query, CONTENT_LIMIT),
+ includeReasoning
+ ? searchChatReasoning(userId, query, REASONING_LIMIT)
+ : Promise.resolve(null)
+ ])
+
+ const payload: SearchResponse = {
+ title: titleChats.map(chat => ({ chatId: chat.id, title: chat.title })),
+ content: contentMatches.map(toContentItem)
+ }
+ if (reasoningMatches) {
+ payload.thinking = reasoningMatches.map(toContentItem)
+ }
+
+ return NextResponse.json<SearchResponse>(payload)
+ } catch (error) {
+ console.error('API route error searching chats:', error)
+ return NextResponse.json<SearchResponse>(emptyResponse, { status: 500 })
+ }
+}
diff --git a/components/sidebar/__tests__/chat-history-client.test.tsx b/components/sidebar/__tests__/chat-history-client.test.tsx
new file mode 100644
index 00000000..4fa89062
--- /dev/null
+++ b/components/sidebar/__tests__/chat-history-client.test.tsx
@@ -0,0 +1,827 @@
+import { act, fireEvent, render, screen } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { ChatHistoryClient } from '../chat-history-client'
+
+const pushMock = vi.hoisted(() => vi.fn())
+
+vi.mock('next/navigation', () => ({
+ useRouter: () => ({ push: pushMock })
+}))
+
+vi.mock('../chat-menu-item', () => ({
+ ChatMenuItem: ({ chat }: { chat: { id: string; title: string } }) => (
+ <div data-testid="chat-item">{chat.title}</div>
+ )
+}))
+
+vi.mock('../clear-history-action', () => ({
+ ClearHistoryAction: () => <button type="button">Clear history</button>
+}))
+
+let lastObserver: IntersectionObserverStub | null = null
+class IntersectionObserverStub {
+ constructor(private callback: IntersectionObserverCallback) {
+ lastObserver = this
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ // Simulate the sentinel entering the viewport
+ intersect() {
+ this.callback(
+ [{ isIntersecting: true } as IntersectionObserverEntry],
+ this as unknown as IntersectionObserver
+ )
+ }
+}
+globalThis.IntersectionObserver =
+ IntersectionObserverStub as unknown as typeof IntersectionObserver
+
+// jsdom lacks ResizeObserver, which cmdk requires
+class ResizeObserverStub {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+}
+globalThis.ResizeObserver =
+ ResizeObserverStub as unknown as typeof ResizeObserver
+
+const chat = {
+ id: 'chat-1',
+ title: 'Existing chat',
+ userId: 'user-1',
+ visibility: 'private' as const,
+ createdAt: new Date('2026-01-01T00:00:00Z')
+}
+
+function mockFetch() {
+ const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
+ const url = String(input)
+ if (url.startsWith('/api/chats')) {
+ return {
+ ok: true,
+ json: async () => ({ chats: [chat], nextOffset: null })
+ }
+ }
+ if (url.startsWith('/api/search')) {
+ if (url.includes('include=reasoning')) {
+ return {
+ ok: true,
+ json: async () => ({
+ title: [],
+ content: [],
+ thinking: [
+ {
+ chatId: 'chat-9',
+ title: 'Thinking match',
+ snippet: 'pondering',
+ highlight: 'pondering'
+ }
+ ]
+ })
+ }
+ }
+ return {
+ ok: true,
+ json: async () => ({
+ title: [{ chatId: 'chat-9', title: 'Matched chat' }],
+ content: []
+ })
+ }
+ }
+ throw new Error(`Unexpected fetch: ${url}`)
+ })
+ vi.stubGlobal('fetch', fetchMock)
+ return fetchMock
+}
+
+async function flush(ms = 0) {
+ await act(async () => {
+ if (ms > 0) {
+ await vi.advanceTimersByTimeAsync(ms)
+ } else {
+ await Promise.resolve()
+ }
+ })
+}
+
+function calledWith(fetchMock: ReturnType<typeof mockFetch>, prefix: string) {
+ return fetchMock.mock.calls.some(([url]) => String(url).startsWith(prefix))
+}
+
+async function typeInSearch(query: string) {
+ const input = screen.getByLabelText('Search history')
+ await act(async () => {
+ fireEvent.change(input, { target: { value: query } })
+ })
+ await flush(300)
+}
+
+describe('ChatHistoryClient search mode', () => {
+ beforeEach(() => {
+ vi.useFakeTimers()
+ vi.clearAllMocks()
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ vi.unstubAllGlobals()
+ })
+
+ it('swaps the list for results while searching and restores it on Escape', async () => {
+ mockFetch()
+ render(<ChatHistoryClient />)
+ await flush(50)
+
+ expect(screen.getByText('Existing chat')).toBeInTheDocument()
+
+ await typeInSearch('mat')
+ expect(screen.queryByText('Existing chat')).not.toBeInTheDocument()
+ expect(screen.getByText('Matched chat')).toBeInTheDocument()
+
+ await act(async () => {
+ fireEvent.keyDown(screen.getByLabelText('Search history'), {
+ key: 'Escape'
+ })
+ })
+ expect(screen.getByText('Existing chat')).toBeInTheDocument()
+ expect(screen.queryByText('Matched chat')).not.toBeInTheDocument()
+ })
+
+ it('keeps the list visible for queries shorter than 2 characters', async () => {
+ const fetchMock = mockFetch()
+ render(<ChatHistoryClient />)
+ await flush(50)
+
+ await typeInSearch('m')
+ expect(screen.getByText('Existing chat')).toBeInTheDocument()
+ expect(calledWith(fetchMock, '/api/search')).toBe(false)
+ })
+
+ it('counts code points, not UTF-16 code units, for the minimum', async () => {
+ const fetchMock = mockFetch()
+ render(<ChatHistoryClient />)
+ await flush(50)
+ fetchMock.mockClear()
+
+ // 'πŸ˜€' is two code units but one character: like any single-character
+ // query it must keep the chronological list instead of a broad search.
+ await typeInSearch('πŸ˜€')
+ expect(screen.getByText('Existing chat')).toBeInTheDocument()
+ expect(calledWith(fetchMock, '/api/search')).toBe(false)
+
+ // two characters (even both non-BMP) do enter search mode
+ await typeInSearch('πŸ˜€πŸ˜€')
+ expect(screen.getByText('Matched chat')).toBeInTheDocument()
+ })
+
+ it('refreshes the hidden list immediately when chat data changes while searching', async () => {
+ const fetchMock = mockFetch()
+ render(<ChatHistoryClient />)
+ await flush(50)
+ fetchMock.mockClear()
+
+ await typeInSearch('mat')
+
+ // A chat completes (or Clear History) while the user is searching: the
+ // hidden list refetches right away, so deleted chats can never be
+ // revealed as clickable items when the user leaves search mode.
+ await act(async () => {
+ window.dispatchEvent(new CustomEvent('chat-history-updated'))
+ })
+ await flush(50)
+ expect(calledWith(fetchMock, '/api/chats')).toBe(true)
+
+ // Leaving the search shows the refreshed list, not stale items.
+ await act(async () => {
+ fireEvent.click(screen.getByLabelText('Clear search'))
+ })
+ await flush(50)
+ expect(screen.getByText('Existing chat')).toBeInTheDocument()
+ })
+
+ it('retries a failed hidden refresh when search mode ends', async () => {
+ const fetchMock = mockFetch()
+ render(<ChatHistoryClient />)
+ await flush(50)
+
+ await typeInSearch('mat')
+ fetchMock.mockClear()
+
+ // Clear History while searching, but the hidden list refresh fails:
+ // the deleted chats must not simply be revealed when the user exits.
+ fetchMock.mockImplementationOnce(async (input: RequestInfo | URL) => {
+ if (String(input).startsWith('/api/chats')) {
+ return {
+ ok: false,
+ json: async () => ({ chats: [], nextOffset: null })
+ }
+ }
+ return { ok: true, json: async () => ({ title: [], content: [] }) }
+ })
+ await act(async () => {
+ window.dispatchEvent(new CustomEvent('chat-history-updated'))
+ })
+ await flush(50)
+ const chatsCalls = () =>
+ fetchMock.mock.calls.filter(([url]) =>
+ String(url).startsWith('/api/chats')
+ ).length
+ expect(chatsCalls()).toBe(1)
+
+ // Exiting search retries the failed refresh; the retry succeeds here,
+ // so the fresh list replaces the stale (deleted) items.
+ await act(async () => {
+ fireEvent.click(screen.getByLabelText('Clear search'))
+ })
+ await flush(50)
+ expect(chatsCalls()).toBe(2)
+ expect(screen.getByText('Existing chat')).toBeInTheDocument()
+ })
+
+ it('marks the list stale when a hidden refresh fails after the query is cleared', async () => {
+ const fetchMock = mockFetch()
+ render(<ChatHistoryClient />)
+ await flush(50)
+
+ await typeInSearch('mat')
+ fetchMock.mockClear()
+
+ // The refresh starts while search mode hides the list, but the user
+ // clears the query before the failing response lands: the failure
+ // counts as a hidden-refresh failure (mode at request start, not at
+ // completion) and must still be retried.
+ fetchMock.mockImplementationOnce(async () => {
+ await new Promise(resolve => setTimeout(resolve, 100))
+ return { ok: false, json: async () => ({ chats: [], nextOffset: null }) }
+ })
+ await act(async () => {
+ window.dispatchEvent(new CustomEvent('chat-history-updated'))
+ })
+ await act(async () => {
+ fireEvent.click(screen.getByLabelText('Clear search'))
+ })
+ await flush(200)
+ const chatsCalls = fetchMock.mock.calls.filter(([url]) =>
+ String(url).startsWith('/api/chats')
+ ).length
+ expect(chatsCalls).toBe(2)
+ expect(screen.getByText('Existing chat')).toBeInTheDocument()
+ })
+
+ it('keeps the list suppressed while a hidden refresh is still pending on exit', async () => {
+ const fetchMock = mockFetch()
+ render(<ChatHistoryClient />)
+ await flush(50)
+
+ await typeInSearch('mat')
+ fetchMock.mockClear()
+
+ // Clear History while searching; the hidden refresh stays pending
+ // (slow response) and the user exits search before it settles. The
+ // list is already stale from the deletion, so the old links must not
+ // be clickable until a refresh succeeds.
+ fetchMock.mockImplementation(async (input: RequestInfo | URL) => {
+ if (String(input).startsWith('/api/chats')) {
+ await new Promise(resolve => setTimeout(resolve, 100))
+ return {
+ ok: true,
+ json: async () => ({ chats: [chat], nextOffset: null })
+ }
+ }
+ return { ok: true, json: async () => ({ title: [], content: [] }) }
+ })
+ await act(async () => {
+ window.dispatchEvent(new CustomEvent('chat-history-updated'))
+ })
+ await act(async () => {
+ fireEvent.click(screen.getByLabelText('Clear search'))
+ })
+ await flush(50) // still pending
+ expect(screen.queryByText('Existing chat')).not.toBeInTheDocument()
+
+ await flush(150)
+ expect(screen.getByText('Existing chat')).toBeInTheDocument()
+ })
+
+ it('offers a retry instead of stale chats when the exit retry also fails', async () => {
+ const fetchMock = mockFetch()
+ render(<ChatHistoryClient />)
+ await flush(50)
+
+ await typeInSearch('mat')
+ fetchMock.mockClear()
+
+ const failChats = async () => ({
+ ok: false,
+ json: async () => ({ chats: [], nextOffset: null })
+ })
+ fetchMock.mockImplementationOnce(failChats)
+ await act(async () => {
+ window.dispatchEvent(new CustomEvent('chat-history-updated'))
+ })
+ await flush(50)
+
+ // The retry issued on leaving search mode fails too (outage spanning
+ // both requests): the deleted chats must stay hidden behind an
+ // actionable retry instead of reappearing.
+ fetchMock.mockImplementationOnce(failChats)
+ await act(async () => {
+ fireEvent.click(screen.getByLabelText('Clear search'))
+ })
+ await flush(50)
+ expect(screen.queryByText('Existing chat')).not.toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'Retry' })).toBeInTheDocument()
+
+ // Recovering now, the manual retry shows the fresh list.
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }))
+ })
+ await flush(50)
+ expect(screen.getByText('Existing chat')).toBeInTheDocument()
+ })
+
+ it('ignores a superseded refresh when a newer one fails', async () => {
+ const fetchMock = mockFetch()
+ render(<ChatHistoryClient />)
+ await flush(50)
+
+ await typeInSearch('mat')
+ fetchMock.mockClear()
+
+ // Two data changes while the list is hidden. The first refresh is slow
+ // and would succeed with a response captured before the second change;
+ // the second refresh fails. Only the latest request may apply its data
+ // or move the suppression flags.
+ let chatsCalls = 0
+ fetchMock.mockImplementation(async (input: RequestInfo | URL) => {
+ if (String(input).startsWith('/api/chats')) {
+ chatsCalls++
+ if (chatsCalls === 1) {
+ await new Promise(resolve => setTimeout(resolve, 100))
+ return {
+ ok: true,
+ json: async () => ({ chats: [chat], nextOffset: null })
+ }
+ }
+ return {
+ ok: false,
+ json: async () => ({ chats: [], nextOffset: null })
+ }
+ }
+ return { ok: true, json: async () => ({ title: [], content: [] }) }
+ })
+ await act(async () => {
+ window.dispatchEvent(new CustomEvent('chat-history-updated'))
+ })
+ await act(async () => {
+ window.dispatchEvent(new CustomEvent('chat-history-updated'))
+ })
+ await flush(50) // the newer refresh has failed; the older is pending
+
+ // Leaving search retries the failed refresh (which fails here too).
+ await act(async () => {
+ fireEvent.click(screen.getByLabelText('Clear search'))
+ })
+ await flush(50)
+ expect(screen.queryByText('Existing chat')).not.toBeInTheDocument()
+
+ // The older response lands: it predates the second change, so it must
+ // not clear the suppression or reveal its (stale) items.
+ await flush(100)
+ expect(screen.queryByText('Existing chat')).not.toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'Retry' })).toBeInTheDocument()
+ })
+
+ it('surfaces a visible-mode failure that supersedes a pending hidden refresh', async () => {
+ const fetchMock = mockFetch()
+ render(<ChatHistoryClient />)
+ await flush(50)
+
+ await typeInSearch('mat')
+ fetchMock.mockClear()
+
+ // The hidden refresh and the exit retry are both slow and still
+ // pending when a chat finishes in normal mode; that third request
+ // supersedes both and fails. The failure must surface as the retry
+ // error state, not leave an endless skeleton.
+ let chatsCalls = 0
+ fetchMock.mockImplementation(async (input: RequestInfo | URL) => {
+ if (String(input).startsWith('/api/chats')) {
+ chatsCalls++
+ if (chatsCalls <= 2) {
+ await new Promise(resolve => setTimeout(resolve, 100))
+ return {
+ ok: true,
+ json: async () => ({ chats: [chat], nextOffset: null })
+ }
+ }
+ if (chatsCalls === 3) {
+ return {
+ ok: false,
+ json: async () => ({ chats: [], nextOffset: null })
+ }
+ }
+ return {
+ ok: true,
+ json: async () => ({ chats: [chat], nextOffset: null })
+ }
+ }
+ return { ok: true, json: async () => ({ title: [], content: [] }) }
+ })
+ await act(async () => {
+ window.dispatchEvent(new CustomEvent('chat-history-updated'))
+ })
+ // Leaving search starts the exit retry (still pending)...
+ await act(async () => {
+ fireEvent.click(screen.getByLabelText('Clear search'))
+ })
+ // ...and a chat finishing in normal mode supersedes both, then fails.
+ await act(async () => {
+ window.dispatchEvent(new CustomEvent('chat-history-updated'))
+ })
+ await flush(50)
+ expect(screen.queryByText('Existing chat')).not.toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'Retry' })).toBeInTheDocument()
+
+ // The two superseded successes land; they must not clear the error.
+ await flush(100)
+ expect(screen.queryByText('Existing chat')).not.toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'Retry' })).toBeInTheDocument()
+
+ // The manual retry recovers.
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }))
+ })
+ await flush(50)
+ expect(screen.getByText('Existing chat')).toBeInTheDocument()
+ })
+
+ it('discards a load-more page superseded by a refresh', async () => {
+ const deletedChat = {
+ id: 'chat-old',
+ title: 'Deleted chat',
+ userId: 'user-1',
+ visibility: 'private' as const,
+ createdAt: new Date('2026-01-01T00:00:00Z')
+ }
+ const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
+ const url = String(input)
+ if (url.startsWith('/api/chats?offset=0')) {
+ return {
+ ok: true,
+ json: async () => ({ chats: [chat], nextOffset: 20 })
+ }
+ }
+ if (url.startsWith('/api/chats')) {
+ await new Promise(resolve => setTimeout(resolve, 400))
+ return {
+ ok: true,
+ json: async () => ({ chats: [deletedChat], nextOffset: null })
+ }
+ }
+ return { ok: true, json: async () => ({ title: [], content: [] }) }
+ })
+ vi.stubGlobal('fetch', fetchMock)
+ render(<ChatHistoryClient />)
+ await flush(50)
+ expect(screen.getByText('Existing chat')).toBeInTheDocument()
+
+ // Start infinite scroll (its page is slow), then enter search mode:
+ // the observer disconnects but the request stays in flight.
+ lastObserver!.intersect()
+ await typeInSearch('mat')
+
+ // Clear History while hidden: the refresh succeeds and replaces the
+ // list; the stale load-more page must not append to it afterwards.
+ await act(async () => {
+ window.dispatchEvent(new CustomEvent('chat-history-updated'))
+ })
+ await flush(50)
+ await flush(400) // the stale page lands while the list is hidden
+
+ await act(async () => {
+ fireEvent.click(screen.getByLabelText('Clear search'))
+ })
+ await flush(50)
+ expect(screen.getByText('Existing chat')).toBeInTheDocument()
+ expect(screen.queryByText('Deleted chat')).not.toBeInTheDocument()
+ })
+
+ it('does not let a queued load-more callback supersede a running refresh', async () => {
+ const deletedChat = {
+ id: 'chat-old',
+ title: 'Deleted chat',
+ userId: 'user-1',
+ visibility: 'private' as const,
+ createdAt: new Date('2026-01-01T00:00:00Z')
+ }
+ const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
+ const url = String(input)
+ if (url.startsWith('/api/chats?offset=0')) {
+ return {
+ ok: true,
+ json: async () => ({ chats: [chat], nextOffset: 20 })
+ }
+ }
+ if (url.startsWith('/api/chats')) {
+ await new Promise(resolve => setTimeout(resolve, 100))
+ return {
+ ok: true,
+ json: async () => ({ chats: [deletedChat], nextOffset: null })
+ }
+ }
+ return { ok: true, json: async () => ({ title: [], content: [] }) }
+ })
+ vi.stubGlobal('fetch', fetchMock)
+ render(<ChatHistoryClient />)
+ await flush(50)
+
+ // The observer notification is queued just before the data change:
+ // the refresh starts first, but the callback still closes over the
+ // pre-refresh state (isLoading === false) and runs right after.
+ await act(async () => {
+ window.dispatchEvent(new CustomEvent('chat-history-updated'))
+ lastObserver!.intersect()
+ })
+ await flush(200)
+
+ // The refresh owns the list: the stale offset page must not append
+ // to (or replace) its result.
+ expect(screen.getByText('Existing chat')).toBeInTheDocument()
+ expect(screen.queryByText('Deleted chat')).not.toBeInTheDocument()
+ })
+
+ it('refetches search results when chat data changes during search', async () => {
+ const fetchMock = mockFetch()
+ render(<ChatHistoryClient />)
+ await flush(50)
+
+ await typeInSearch('mat')
+ fetchMock.mockClear()
+
+ // Clear History (or any chat-data change) while searching: stale results
+ // must not remain, so the search view refetches immediately.
+ await act(async () => {
+ window.dispatchEvent(new CustomEvent('chat-history-updated'))
+ })
+ await flush(300)
+
+ expect(calledWith(fetchMock, '/api/search')).toBe(true)
+ // the hidden chronological list refreshes alongside the results
+ expect(calledWith(fetchMock, '/api/chats')).toBe(true)
+ })
+
+ it('forwards ArrowDown and Enter from the input to the result list', async () => {
+ mockFetch()
+ render(<ChatHistoryClient />)
+ await flush(50)
+
+ await typeInSearch('mat')
+
+ const input = screen.getByLabelText('Search history')
+ // cmdk tracks the active item via aria-selected instead of DOM focus
+ await act(async () => {
+ fireEvent.keyDown(input, { key: 'ArrowDown' })
+ })
+ expect(screen.getAllByRole('option')[0]).toHaveAttribute(
+ 'aria-selected',
+ 'true'
+ )
+
+ await act(async () => {
+ fireEvent.keyDown(input, { key: 'Enter' })
+ })
+ expect(pushMock).toHaveBeenCalledWith('/search/chat-9')
+ })
+
+ it('mirrors the result list onto the input with combobox ARIA', async () => {
+ mockFetch()
+ render(<ChatHistoryClient />)
+ await flush(50)
+
+ const input = screen.getByLabelText('Search history')
+ // Outside search mode there is no popup list to point at.
+ expect(input).toHaveAttribute('role', 'combobox')
+ expect(input).toHaveAttribute('aria-expanded', 'false')
+ expect(input).not.toHaveAttribute('aria-controls')
+
+ await typeInSearch('mat')
+ expect(input).toHaveAttribute('aria-expanded', 'true')
+ const list = document.querySelector('[cmdk-list]') as HTMLElement
+ expect(list).toBeTruthy()
+ expect(input.getAttribute('aria-controls')).toBe(list.id)
+
+ // After keyboard navigation the active option is referenced so screen
+ // readers announce it while DOM focus stays on the input.
+ await act(async () => {
+ fireEvent.keyDown(input, { key: 'ArrowDown' })
+ })
+ const active = document.querySelector(
+ '[cmdk-item][data-selected="true"]'
+ ) as HTMLElement
+ expect(active).toBeTruthy()
+ expect(input.getAttribute('aria-activedescendant')).toBe(active.id)
+
+ // Leaving search mode removes the relationships again.
+ await act(async () => {
+ fireEvent.keyDown(input, { key: 'Escape' })
+ })
+ expect(input).not.toHaveAttribute('aria-controls')
+ expect(input).not.toHaveAttribute('aria-activedescendant')
+ })
+
+ it('lets Enter activate the thinking button instead of the selected result', async () => {
+ const fetchMock = mockFetch()
+ render(<ChatHistoryClient />)
+ await flush(50)
+
+ await typeInSearch('mat')
+ const input = screen.getByLabelText('Search history')
+ await act(async () => {
+ fireEvent.keyDown(input, { key: 'ArrowDown' })
+ })
+ expect(screen.getAllByRole('option')[0]).toHaveAttribute(
+ 'aria-selected',
+ 'true'
+ )
+
+ // The button lives inside the cmdk root; its Enter must press the button,
+ // not activate the selected result through cmdk's root handler. cmdk's
+ // handler cancels the keydown (preventDefault) to suppress the native
+ // click, so a non-cancelled event proves a real browser would press the
+ // button instead of opening the selected result.
+ let notCancelled = false
+ await act(async () => {
+ notCancelled = fireEvent.keyDown(
+ screen.getByRole('button', { name: /Search thinking/ }),
+ {
+ key: 'Enter'
+ }
+ )
+ })
+ expect(notCancelled).toBe(true)
+ expect(pushMock).not.toHaveBeenCalled()
+
+ // jsdom does not run the keydown's default action, so fire the click a
+ // real browser would produce and assert the thinking search starts.
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: /Search thinking/ }))
+ })
+ await flush(50)
+ expect(
+ fetchMock.mock.calls.some(([url]) =>
+ String(url).includes('include=reasoning')
+ )
+ ).toBe(true)
+ expect(pushMock).not.toHaveBeenCalled()
+ })
+
+ it('drops the mirrored active option when results are invalidated', async () => {
+ mockFetch()
+ render(<ChatHistoryClient />)
+ await flush(50)
+
+ await typeInSearch('mat')
+ const input = screen.getByLabelText('Search history')
+ await act(async () => {
+ fireEvent.keyDown(input, { key: 'ArrowDown' })
+ })
+ expect(input.getAttribute('aria-activedescendant')).toBeTruthy()
+
+ // Clear History invalidates the results; the removed option must not
+ // stay referenced by the input, even if the refetch fails or is empty.
+ await act(async () => {
+ window.dispatchEvent(new CustomEvent('chat-history-updated'))
+ })
+ await flush(50) // still inside the debounce window: options are gone
+ expect(input).not.toHaveAttribute('aria-activedescendant')
+ })
+
+ it('drops the mirrored active option when the query changes', async () => {
+ mockFetch()
+ render(<ChatHistoryClient />)
+ await flush(50)
+
+ await typeInSearch('mat')
+ const input = screen.getByLabelText('Search history')
+ await act(async () => {
+ fireEvent.keyDown(input, { key: 'ArrowDown' })
+ })
+ expect(input.getAttribute('aria-activedescendant')).toBeTruthy()
+
+ // Editing to a new query unmounts the options; the removed option must
+ // not stay referenced during the debounce window (or indefinitely if
+ // the new search returns nothing).
+ await act(async () => {
+ fireEvent.change(input, { target: { value: 'mat2' } })
+ })
+ await flush(50) // still inside the debounce window: no new options yet
+ expect(input).not.toHaveAttribute('aria-activedescendant')
+ })
+
+ it('bounds a pasted query before putting it in the search URL', async () => {
+ const fetchMock = mockFetch()
+ render(<ChatHistoryClient />)
+ await flush(50)
+
+ // 204 characters: the URL must carry the same bounded query the backend
+ // would apply, so oversized pastes cannot exceed the request-target limit
+ await typeInSearch('note '.repeat(40) + 'kiwi')
+
+ const url = fetchMock.mock.calls
+ .map(([u]) => String(u))
+ .find(u => u.startsWith('/api/search'))
+ expect(url).toBeTruthy()
+ expect(
+ new URL(url as string, 'http://localhost').searchParams.get('q')
+ ).toBe('note '.repeat(40).trim())
+ })
+
+ it('keeps the chronological list when normalization drops the query below the minimum', async () => {
+ mockFetch()
+ render(<ChatHistoryClient />)
+ await flush(50)
+
+ // 'a ' + a 300-char token: the bound drops the partial second token,
+ // leaving one character β€” too short to search, so the list stays
+ await typeInSearch('a ' + 'x'.repeat(300))
+
+ expect(screen.getByText('Existing chat')).toBeInTheDocument()
+ })
+
+ it('searches a paste whose cap split falls inside a surrogate pair', async () => {
+ const fetchMock = mockFetch()
+ render(<ChatHistoryClient />)
+ await flush(50)
+
+ // the 200-code-unit cut lands inside an emoji; without the surrogate
+ // backoff, encodeURIComponent throws and no request is ever issued
+ await typeInSearch('a' + 'πŸ˜€'.repeat(100))
+
+ expect(calledWith(fetchMock, '/api/search')).toBe(true)
+ })
+
+ it('does not forward Enter or Escape while an IME composition is active', async () => {
+ mockFetch()
+ render(<ChatHistoryClient />)
+ await flush(50)
+
+ await typeInSearch('mat')
+
+ const input = screen.getByLabelText('Search history')
+ await act(async () => {
+ fireEvent.keyDown(input, { key: 'ArrowDown' })
+ })
+ expect(screen.getAllByRole('option')[0]).toHaveAttribute(
+ 'aria-selected',
+ 'true'
+ )
+
+ // Enter confirms an IME candidate and Escape cancels it; neither may
+ // reach the result list or clear the query while composing.
+ await act(async () => {
+ fireEvent.keyDown(input, { key: 'Enter', isComposing: true })
+ })
+ expect(pushMock).not.toHaveBeenCalled()
+
+ // Some browser/IME combinations only signal composition via keyCode 229.
+ await act(async () => {
+ fireEvent.keyDown(input, { key: 'Enter', keyCode: 229 })
+ })
+ expect(pushMock).not.toHaveBeenCalled()
+
+ await act(async () => {
+ fireEvent.keyDown(input, { key: 'Escape', isComposing: true })
+ })
+ expect(screen.getByLabelText('Search history')).toHaveValue('mat')
+ })
+
+ it('keeps thinking results when chat data changes during search', async () => {
+ const fetchMock = mockFetch()
+ render(<ChatHistoryClient />)
+ await flush(50)
+
+ await typeInSearch('mat')
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: /Search thinking/ }))
+ })
+ await flush(50)
+ expect(screen.getByText('Thinking match')).toBeInTheDocument()
+
+ // A chat finishing (or Clear History) must not drop the thinking
+ // section: both result sets are refetched in place.
+ fetchMock.mockClear()
+ await act(async () => {
+ window.dispatchEvent(new CustomEvent('chat-history-updated'))
+ })
+ await flush(300)
+
+ expect(screen.getByText('Thinking match')).toBeInTheDocument()
+ expect(calledWith(fetchMock, '/api/search?q=mat&include=reasoning')).toBe(
+ true
+ )
+ })
+})
diff --git a/components/sidebar/__tests__/chat-history-search.test.tsx b/components/sidebar/__tests__/chat-history-search.test.tsx
new file mode 100644
index 00000000..e6eeb7a9
--- /dev/null
+++ b/components/sidebar/__tests__/chat-history-search.test.tsx
@@ -0,0 +1,471 @@
+import { act, fireEvent, render, screen } from '@testing-library/react'
+import { toast } from 'sonner'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { HL_START, HL_STOP } from '@/lib/render/highlight-markers'
+
+import { ChatHistorySearch } from '../chat-history-search'
+
+const pushMock = vi.hoisted(() => vi.fn())
+
+// jsdom lacks ResizeObserver, which cmdk requires
+class ResizeObserverStub {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+}
+globalThis.ResizeObserver =
+ ResizeObserverStub as unknown as typeof ResizeObserver
+
+vi.mock('next/navigation', () => ({
+ useRouter: () => ({ push: pushMock })
+}))
+
+vi.mock('sonner', () => ({
+ toast: { error: vi.fn() }
+}))
+
+function jsonResponse(body: unknown, ok = true, status = 200) {
+ return Promise.resolve({ ok, status, json: async () => body })
+}
+
+const emptyResponse = { title: [], content: [] }
+
+function deferred<T>() {
+ let resolve!: (value: T) => void
+ const promise = new Promise<T>(res => {
+ resolve = res
+ })
+ return { promise, resolve }
+}
+
+// Advance fake timers inside act() so React flushes state updates that
+// happen in promise continuations started by the timers.
+async function flush(ms: number) {
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(ms)
+ })
+}
+
+async function typeQuery(ui: ReturnType<typeof render>, query: string) {
+ await act(async () => {
+ ui.rerender(<ChatHistorySearch query={query} />)
+ })
+ await flush(300)
+}
+
+describe('ChatHistorySearch', () => {
+ beforeEach(() => {
+ vi.useFakeTimers()
+ vi.clearAllMocks()
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ vi.unstubAllGlobals()
+ })
+
+ it('does not search for queries shorter than 2 characters', async () => {
+ const fetchMock = vi.fn().mockReturnValue(jsonResponse(emptyResponse))
+ vi.stubGlobal('fetch', fetchMock)
+
+ render(<ChatHistorySearch query="r" />)
+ await flush(500)
+
+ expect(fetchMock).not.toHaveBeenCalled()
+ })
+
+ it('debounces the request by ~250ms', async () => {
+ const fetchMock = vi.fn().mockReturnValue(jsonResponse(emptyResponse))
+ vi.stubGlobal('fetch', fetchMock)
+
+ render(<ChatHistorySearch query="ro" />)
+ await flush(200)
+ expect(fetchMock).not.toHaveBeenCalled()
+
+ await flush(100)
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ expect(fetchMock.mock.calls[0][0]).toContain('/api/search?q=ro')
+ })
+
+ it('drops a stale response that arrives after a newer query resolved', async () => {
+ const robResponse = deferred<unknown>()
+ const robertResponse = deferred<unknown>()
+ const fetchMock = vi
+ .fn()
+ .mockReturnValueOnce(robResponse.promise)
+ .mockReturnValueOnce(robertResponse.promise)
+ vi.stubGlobal('fetch', fetchMock)
+
+ const ui = render(<ChatHistorySearch query="rob" />)
+ await flush(300)
+
+ await typeQuery(ui, 'robert')
+
+ await act(async () => {
+ robertResponse.resolve({
+ ok: true,
+ status: 200,
+ json: async () => ({
+ title: [],
+ content: [
+ {
+ chatId: 'c2',
+ title: 'Robert Frost',
+ snippet: 'robert',
+ highlight: `${HL_START}robert${HL_STOP}`
+ }
+ ]
+ })
+ })
+ })
+ expect(screen.getByText('Robert Frost')).toBeInTheDocument()
+
+ // The superseded "rob" response arrives late and must not overwrite.
+ await act(async () => {
+ robResponse.resolve({
+ ok: true,
+ status: 200,
+ json: async () => ({
+ title: [],
+ content: [
+ {
+ chatId: 'c1',
+ title: 'Rob Reiner',
+ snippet: 'rob',
+ highlight: `${HL_START}rob${HL_STOP}`
+ }
+ ]
+ })
+ })
+ })
+
+ expect(screen.queryByText('Rob Reiner')).not.toBeInTheDocument()
+ expect(screen.getByText('Robert Frost')).toBeInTheDocument()
+ })
+
+ it('renders By title and In chats sections with highlighted snippets', async () => {
+ const fetchMock = vi.fn().mockReturnValue(
+ jsonResponse({
+ title: [{ chatId: 'c1', title: 'Robert Frost Readings' }],
+ content: [
+ {
+ chatId: 'c2',
+ title: 'Poetry class',
+ snippet: 'Stopping by woods',
+ highlight: `Stopping by ${HL_START}woods${HL_STOP}`
+ }
+ ]
+ })
+ )
+ vi.stubGlobal('fetch', fetchMock)
+
+ render(<ChatHistorySearch query="woods" />)
+ await flush(300)
+
+ expect(screen.getByText('By title')).toBeInTheDocument()
+ expect(screen.getByText('In chats')).toBeInTheDocument()
+ expect(screen.getByText('Robert Frost Readings')).toBeInTheDocument()
+ const bold = screen.getByText('woods')
+ expect(bold.tagName).toBe('B')
+ })
+
+ it('opens the chat when a result is activated', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockReturnValue(
+ jsonResponse({
+ title: [{ chatId: 'c1', title: 'Robert Frost Readings' }],
+ content: []
+ })
+ )
+ )
+
+ render(<ChatHistorySearch query="frost" />)
+ await flush(300)
+
+ fireEvent.click(screen.getByText('Robert Frost Readings'))
+
+ expect(pushMock).toHaveBeenCalledWith('/search/c1')
+ })
+
+ it('shows a No matches empty state', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockReturnValue(jsonResponse(emptyResponse)))
+
+ render(<ChatHistorySearch query="zzz" />)
+ await flush(300)
+
+ expect(screen.getByText('No matches')).toBeInTheDocument()
+ })
+
+ it('shows an error toast when the request fails', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockReturnValue(jsonResponse({}, false, 500))
+ )
+
+ render(<ChatHistorySearch query="frost" />)
+ await flush(300)
+
+ expect(toast.error).toHaveBeenCalled()
+ })
+
+ it('appends an In thinking section on opt-in and resets it on a new query', async () => {
+ const fetchMock = vi
+ .fn()
+ .mockReturnValueOnce(
+ jsonResponse({
+ title: [],
+ content: [
+ { chatId: 'c1', title: 'Chat A', snippet: 'x', highlight: 'x' }
+ ]
+ })
+ )
+ .mockReturnValueOnce(
+ jsonResponse({
+ title: [],
+ content: [],
+ thinking: [
+ {
+ chatId: 'c9',
+ title: 'Deep chat',
+ snippet: 'pondering quasars',
+ highlight: `pondering ${HL_START}quasars${HL_STOP}`
+ }
+ ]
+ })
+ )
+ vi.stubGlobal('fetch', fetchMock)
+
+ const ui = render(<ChatHistorySearch query="quasars" />)
+ await flush(300)
+ expect(screen.getByText('Chat A')).toBeInTheDocument()
+ expect(screen.queryByText('In thinking')).not.toBeInTheDocument()
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: /Search thinking/ }))
+ })
+ await flush(50)
+
+ expect(fetchMock).toHaveBeenLastCalledWith(
+ expect.stringContaining('include=reasoning'),
+ expect.anything()
+ )
+ expect(screen.getByText('In thinking')).toBeInTheDocument()
+ expect(screen.getByText('Deep chat')).toBeInTheDocument()
+
+ // A new query resets the thinking scope: section gone, button back.
+ await typeQuery(ui, 'quasars again')
+ expect(screen.queryByText('In thinking')).not.toBeInTheDocument()
+ expect(
+ screen.getByRole('button', { name: /Search thinking/ })
+ ).toBeInTheDocument()
+ })
+
+ it('keeps thinking results when the main response resolves after them', async () => {
+ const mainResponse = deferred<unknown>()
+ const thinkingResponse = deferred<unknown>()
+ const fetchMock = vi
+ .fn()
+ .mockReturnValueOnce(mainResponse.promise)
+ .mockReturnValueOnce(thinkingResponse.promise)
+ vi.stubGlobal('fetch', fetchMock)
+
+ render(<ChatHistorySearch query="quasars" />)
+ await flush(300)
+
+ // The user opts in before the main response has resolved.
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: /Search thinking/ }))
+ })
+
+ await act(async () => {
+ thinkingResponse.resolve({
+ ok: true,
+ status: 200,
+ json: async () => ({
+ title: [],
+ content: [],
+ thinking: [
+ {
+ chatId: 'c9',
+ title: 'Deep chat',
+ snippet: 'pondering quasars',
+ highlight: `pondering ${HL_START}quasars${HL_STOP}`
+ }
+ ]
+ })
+ })
+ })
+ expect(screen.getByText('In thinking')).toBeInTheDocument()
+
+ // The main response arrives late and must not drop the thinking section.
+ await act(async () => {
+ mainResponse.resolve({
+ ok: true,
+ status: 200,
+ json: async () => ({
+ title: [],
+ content: [
+ { chatId: 'c1', title: 'Chat A', snippet: 'x', highlight: 'x' }
+ ]
+ })
+ })
+ })
+
+ expect(screen.getByText('Chat A')).toBeInTheDocument()
+ expect(screen.getByText('In thinking')).toBeInTheDocument()
+ expect(screen.getByText('Deep chat')).toBeInTheDocument()
+ })
+
+ it('aborts an in-flight thinking request on unmount', async () => {
+ const thinkingResponse = deferred<unknown>()
+ const fetchMock = vi
+ .fn()
+ .mockReturnValueOnce(jsonResponse(emptyResponse))
+ .mockReturnValueOnce(thinkingResponse.promise)
+ vi.stubGlobal('fetch', fetchMock)
+
+ const ui = render(<ChatHistorySearch query="quasars" />)
+ await flush(300)
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: /Search thinking/ }))
+ })
+ const thinkingSignal = (
+ fetchMock.mock.calls[1][1] as { signal: AbortSignal }
+ ).signal
+ expect(thinkingSignal.aborted).toBe(false)
+
+ ui.unmount()
+
+ expect(thinkingSignal.aborted).toBe(true)
+ })
+
+ it('re-enables the thinking button when the query changes mid-request', async () => {
+ const thinkingResponse = deferred<unknown>()
+ const fetchMock = vi
+ .fn()
+ .mockReturnValueOnce(jsonResponse(emptyResponse))
+ .mockReturnValueOnce(thinkingResponse.promise)
+ .mockReturnValue(jsonResponse(emptyResponse))
+ vi.stubGlobal('fetch', fetchMock)
+
+ const ui = render(<ChatHistorySearch query="quasars" />)
+ await flush(300)
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: /Search thinking/ }))
+ })
+ expect(
+ screen.getByRole('button', { name: /Search thinking/ })
+ ).toBeDisabled()
+
+ // Changing the query aborts the thinking request; the stale response
+ // must not leave the button stuck in the loading state.
+ await typeQuery(ui, 'quasars again')
+
+ expect(
+ screen.getByRole('button', { name: /Search thinking/ })
+ ).toBeEnabled()
+ })
+
+ it('renders literal HTML in snippets as plain text', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockReturnValue(
+ jsonResponse({
+ title: [],
+ content: [
+ {
+ chatId: 'c1',
+ title: 'HTML chat',
+ snippet: 'use <b>bold</b> tags',
+ highlight: `use <b>bold</b> ${HL_START}tags${HL_STOP}`
+ }
+ ]
+ })
+ )
+ )
+
+ render(<ChatHistorySearch query="tags" />)
+ await flush(300)
+
+ expect(screen.getByText('tags').tagName).toBe('B')
+ expect(screen.getByText(/use <b>bold<\/b>/)).toBeInTheDocument()
+ })
+
+ it('does not rerun the thinking search when the epoch bump lands with a query change', async () => {
+ const fetchMock = vi.fn().mockReturnValue(
+ jsonResponse({
+ title: [{ chatId: 'c1', title: 'Chat A' }],
+ content: []
+ })
+ )
+ vi.stubGlobal('fetch', fetchMock)
+
+ const ui = render(<ChatHistorySearch query="quasars" refreshKey={0} />)
+ await flush(300)
+
+ // Opt in to thinking search for the current query.
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: /Search thinking/ }))
+ })
+ await flush(50)
+ const thinkingCalls = () =>
+ fetchMock.mock.calls.filter(([url]) =>
+ String(url).includes('include=reasoning')
+ ).length
+ expect(thinkingCalls()).toBe(1)
+
+ // The epoch bump lands in the same render as a query change. The opt-in
+ // belongs to the previous query (its reset has not applied yet), so the
+ // refresh must not carry it over to the new query.
+ await act(async () => {
+ ui.rerender(<ChatHistorySearch query="quasars!" refreshKey={1} />)
+ })
+ await flush(300)
+
+ expect(thinkingCalls()).toBe(1)
+ expect(screen.queryByText('In thinking')).not.toBeInTheDocument()
+ })
+
+ it('invalidates stale results on refresh and does not restore them on failure', async () => {
+ const fetchMock = vi.fn().mockReturnValue(
+ jsonResponse({
+ title: [{ chatId: 'c1', title: 'Budget chat' }],
+ content: []
+ })
+ )
+ vi.stubGlobal('fetch', fetchMock)
+
+ const ui = render(<ChatHistorySearch query="budget" refreshKey={0} />)
+ await flush(300)
+ expect(screen.getByText('Budget chat')).toBeInTheDocument()
+
+ // A refreshKey bump (e.g. Clear History) must invalidate the displayed
+ // matches immediately; a failed refetch must not bring them back.
+ fetchMock.mockReturnValue(jsonResponse({}, false, 500))
+ await act(async () => {
+ ui.rerender(<ChatHistorySearch query="budget" refreshKey={1} />)
+ })
+ await flush(50) // still inside the debounce window
+ expect(screen.queryByText('Budget chat')).not.toBeInTheDocument()
+
+ await flush(300) // debounce fires and the fetch fails
+ expect(screen.queryByText('Budget chat')).not.toBeInTheDocument()
+
+ // A later successful refresh repopulates the results.
+ fetchMock.mockReturnValue(
+ jsonResponse({
+ title: [{ chatId: 'c2', title: 'Fresh chat' }],
+ content: []
+ })
+ )
+ await act(async () => {
+ ui.rerender(<ChatHistorySearch query="budget" refreshKey={2} />)
+ })
+ await flush(300)
+ expect(screen.getByText('Fresh chat')).toBeInTheDocument()
+ })
+})
diff --git a/components/sidebar/chat-history-client.tsx b/components/sidebar/chat-history-client.tsx
index 86ecfa2a..b7735a99 100644
--- a/components/sidebar/chat-history-client.tsx
+++ b/components/sidebar/chat-history-client.tsx
@@ -2,16 +2,23 @@
import { useCallback, useEffect, useRef, useState, useTransition } from 'react'
+import { IconX as X } from '@tabler/icons-react'
import { toast } from 'sonner'
import { Chat as DBChat } from '@/lib/db/schema'
+import {
+ effectiveQueryLength,
+ MIN_QUERY_LENGTH
+} from '@/lib/utils/search-query'
+import { Input } from '@/components/ui/input'
import {
SidebarGroup,
SidebarGroupLabel,
SidebarMenu
} from '@/components/ui/sidebar'
+import { ChatHistorySearch } from './chat-history-search'
import { ChatHistorySkeleton } from './chat-history-skeleton'
import { ChatMenuItem } from './chat-menu-item'
import { ClearHistoryAction } from './clear-history-action'
@@ -21,14 +28,94 @@ interface ChatPageResponse {
nextOffset: number | null
}
+// The API's minimum query length (shared constant), counted in code
+// points: a shorter query keeps the chronological list visible instead of
+// the results view.
+
export function ChatHistoryClient() {
const [chats, setChats] = useState<DBChat[]>([])
const [nextOffset, setNextOffset] = useState<number | null>(null)
const [isLoading, setIsLoading] = useState(true)
+ const [query, setQuery] = useState('')
const loadMoreRef = useRef<HTMLDivElement>(null)
+ const resultsRef = useRef<HTMLDivElement>(null)
+ const inputRef = useRef<HTMLInputElement>(null)
+ // Incremented per list request; lets fetchInitialChats/fetchMoreChats
+ // detect when a later request has superseded their in-flight response.
+ const listRequestSeqRef = useRef(0)
+ // Set synchronously while a full refresh is in flight. A queued
+ // IntersectionObserver callback closes over pre-refresh state, so
+ // pagination must not advance the generation past a running refresh.
+ const refreshInFlightRef = useRef(false)
const [isPending, startTransition] = useTransition()
+ // Based on the normalized query (what the search actually runs), counted
+ // in code points: a paste whose bounded form falls below the minimum
+ // keeps the chronological list, and a single non-BMP character (two code
+ // units, one character) does not trigger a broad single-character search.
+ const searchMode = effectiveQueryLength(query) >= MIN_QUERY_LENGTH
+ const searchModeRef = useRef(searchMode)
+ // A list refresh that started while search mode hid the list: the items
+ // (possibly deleted chats) must not be revealed until a refresh
+ // succeeds. Set at request start - the list is already stale the moment
+ // the change lands, before the refetch settles - and cleared only by a
+ // successful fetch.
+ const [staleHiddenRefresh, setStaleHiddenRefresh] = useState(false)
+ // Mirror for the event handler, which must read the flag without
+ // re-subscribing on every change.
+ const staleHiddenRefreshRef = useRef(false)
+ // The exit-from-search retry also failed: show an actionable error
+ // instead of an endless skeleton or the stale items.
+ const [listRetryFailed, setListRetryFailed] = useState(false)
+ // Bumped when chat data changes during search mode, telling the results
+ // view to refetch so stale matches (e.g. after Clear History) cannot be
+ // opened.
+ const [searchEpoch, setSearchEpoch] = useState(0)
+ // cmdk's active option; only used as a change signal for the ARIA mirror.
+ const [activeResult, setActiveResult] = useState<string | undefined>()
+
+ // Mirror cmdk's listbox state onto the search input for assistive tech:
+ // the input sits outside the Command scope and cmdk generates the list and
+ // option ids internally, so the combobox relationships (aria-controls,
+ // aria-activedescendant) are resolved from the rendered cmdk DOM.
+ useEffect(() => {
+ const input = inputRef.current
+ if (!input) return
+ const list = searchMode
+ ? resultsRef.current?.querySelector<HTMLElement>('[cmdk-list]')
+ : undefined
+ if (!list) {
+ input.removeAttribute('aria-controls')
+ input.removeAttribute('aria-activedescendant')
+ return
+ }
+ input.setAttribute('aria-controls', list.id)
+ const active = list.querySelector<HTMLElement>(
+ '[cmdk-item][data-selected="true"]'
+ )
+ if (active?.id) {
+ input.setAttribute('aria-activedescendant', active.id)
+ } else {
+ input.removeAttribute('aria-activedescendant')
+ }
+ }, [activeResult, searchMode])
+
+ useEffect(() => {
+ searchModeRef.current = searchMode
+ }, [searchMode])
+
+ useEffect(() => {
+ staleHiddenRefreshRef.current = staleHiddenRefresh
+ }, [staleHiddenRefresh])
- const fetchInitialChats = useCallback(async () => {
+ const fetchInitialChats = useCallback(async (): Promise<
+ 'ok' | 'failed' | 'superseded'
+ > => {
+ // Generation guard (same pattern as the results view): overlapping
+ // refreshes must not interleave. A superseded response may predate the
+ // data change that started the newer request, so only the latest
+ // request may apply its data or move the suppression flags.
+ const seq = ++listRequestSeqRef.current
+ refreshInFlightRef.current = true
setIsLoading(true)
try {
const response = await fetch(`/api/chats?offset=0&limit=20`)
@@ -38,14 +125,21 @@ export function ChatHistoryClient() {
const { chats: dbChats, nextOffset: newNextOffset } =
(await response.json()) as ChatPageResponse
+ if (seq !== listRequestSeqRef.current) return 'superseded'
setChats(dbChats)
setNextOffset(newNextOffset)
+ return 'ok'
} catch (error) {
+ if (seq !== listRequestSeqRef.current) return 'superseded'
console.error('Failed to load initial chats:', error)
toast.error('Failed to load chat history.')
setNextOffset(null)
+ return 'failed'
} finally {
- setIsLoading(false)
+ if (seq === listRequestSeqRef.current) {
+ refreshInFlightRef.current = false
+ setIsLoading(false)
+ }
}
}, [])
@@ -55,8 +149,37 @@ export function ChatHistoryClient() {
useEffect(() => {
const handleHistoryUpdate = () => {
+ // Capture the mode at request start: the user may leave search mode
+ // before the request settles, and a refresh that began while the list
+ // was hidden must be treated as hidden regardless of the mode at
+ // completion.
+ const startedHidden = searchModeRef.current
+ if (startedHidden) {
+ setSearchEpoch(epoch => epoch + 1)
+ // Suppress from the start: the list is stale the moment the data
+ // changed, not only once the refetch proves it by failing.
+ setStaleHiddenRefresh(true)
+ setListRetryFailed(false)
+ }
startTransition(async () => {
- await fetchInitialChats()
+ const result = await fetchInitialChats()
+ // A superseded request has no say: the newer request owns the
+ // suppression state, so an older success must not clear the marker
+ // a newer failure may still set (and an older failure must not
+ // mark a retry that a newer success has already resolved).
+ if (result === 'ok') {
+ setStaleHiddenRefresh(false)
+ setListRetryFailed(false)
+ } else if (
+ result === 'failed' &&
+ (startedHidden || staleHiddenRefreshRef.current)
+ ) {
+ // Any latest failure while the stale suppression is active is a
+ // retry failure: a visible-mode refresh that superseded the
+ // hidden one must surface the error, or the suppressed branch
+ // would render an endless skeleton with no Retry action.
+ setListRetryFailed(true)
+ }
})
}
window.addEventListener('chat-history-updated', handleHistoryUpdate)
@@ -65,9 +188,39 @@ export function ChatHistoryClient() {
}
}, [fetchInitialChats, startTransition])
+ // Retry a refresh that failed while the list was hidden. The stale items
+ // (possibly deleted chats) stay suppressed until a refresh succeeds:
+ // skeleton while a retry is in flight, an actionable error once one
+ // fails. The marker clears only on success.
+ const retryStaleList = useCallback(() => {
+ setListRetryFailed(false)
+ startTransition(async () => {
+ const result = await fetchInitialChats()
+ if (result === 'ok') {
+ setStaleHiddenRefresh(false)
+ } else if (result === 'failed') {
+ setListRetryFailed(true)
+ }
+ })
+ }, [fetchInitialChats, startTransition])
+
+ useEffect(() => {
+ if (!searchMode && staleHiddenRefresh) {
+ retryStaleList()
+ }
+ }, [searchMode, staleHiddenRefresh, retryStaleList])
+
const fetchMoreChats = useCallback(async () => {
if (isLoading || nextOffset === null) return
+ // A full refresh in flight always wins: a queued observer callback
+ // sees stale closure state, so pagination must never supersede it.
+ if (refreshInFlightRef.current) return
+ // Same generation guard as fetchInitialChats: a page fetched before a
+ // data change (e.g. Clear History) must not append its pre-deletion
+ // chats after the refresh that superseded this request replaced the
+ // list.
+ const seq = ++listRequestSeqRef.current
setIsLoading(true)
try {
const response = await fetch(`/api/chats?offset=${nextOffset}&limit=20`)
@@ -77,20 +230,24 @@ export function ChatHistoryClient() {
const { chats: dbChats, nextOffset: newNextOffset } =
(await response.json()) as ChatPageResponse
+ if (seq !== listRequestSeqRef.current) return
setChats(prevChats => [...prevChats, ...dbChats])
setNextOffset(newNextOffset)
} catch (error) {
+ if (seq !== listRequestSeqRef.current) return
console.error('Failed to load more chats:', error)
toast.error('Failed to load more chat history.')
setNextOffset(null)
} finally {
- setIsLoading(false)
+ if (seq === listRequestSeqRef.current) setIsLoading(false)
}
}, [nextOffset, isLoading])
useEffect(() => {
const observerRefValue = loadMoreRef.current
if (!observerRefValue || nextOffset === null || isPending) return
+ // Pause infinite scroll while the results view replaces the list.
+ if (searchMode) return
const observer = new IntersectionObserver(
([entry]) => {
@@ -108,7 +265,7 @@ export function ChatHistoryClient() {
observer.unobserve(observerRefValue)
}
}
- }, [fetchMoreChats, nextOffset, isLoading, isPending])
+ }, [fetchMoreChats, nextOffset, isLoading, isPending, searchMode])
const isHistoryEmpty = !isLoading && !chats.length && nextOffset === null
@@ -119,11 +276,92 @@ export function ChatHistoryClient() {
<SidebarGroupLabel className="p-0">History</SidebarGroupLabel>
<ClearHistoryAction empty={isHistoryEmpty} />
</div>
+ <div className="relative mt-1.5">
+ <Input
+ ref={inputRef}
+ value={query}
+ onChange={event => setQuery(event.target.value)}
+ role="combobox"
+ aria-expanded={searchMode}
+ aria-autocomplete="list"
+ onKeyDown={event => {
+ // While an IME composition is active, Enter confirms a
+ // candidate and Escape cancels it; those keystrokes belong to
+ // the IME, not to the search field or the result list. Some
+ // browser/IME combinations signal composition via keyCode 229
+ // without setting isComposing (same guard cmdk applies).
+ if (event.nativeEvent.isComposing || event.keyCode === 229) return
+ if (event.key === 'Escape') {
+ setQuery('')
+ return
+ }
+ if (!searchMode) return
+ // The input lives outside the Command scope, so cmdk never sees
+ // these keys. Re-dispatch them on the cmdk root so its own
+ // navigation (ArrowUp/ArrowDown) and activation (Enter) apply.
+ if (
+ event.key === 'ArrowDown' ||
+ event.key === 'ArrowUp' ||
+ event.key === 'Enter'
+ ) {
+ const commandRoot =
+ resultsRef.current?.querySelector<HTMLElement>('[cmdk-root]')
+ if (!commandRoot) return
+ event.preventDefault()
+ commandRoot.dispatchEvent(
+ new KeyboardEvent('keydown', {
+ key: event.key,
+ bubbles: true,
+ cancelable: true
+ })
+ )
+ }
+ }}
+ placeholder="Search history"
+ aria-label="Search history"
+ className="h-8 text-xs pr-7"
+ />
+ {query && (
+ <button
+ type="button"
+ onClick={() => setQuery('')}
+ aria-label="Clear search"
+ className="text-muted-foreground hover:text-foreground absolute right-1.5 top-1/2 -translate-y-1/2 p-0.5"
+ >
+ <X size={14} />
+ </button>
+ )}
+ </div>
</SidebarGroup>
- <div className="flex-1 overflow-y-auto mb-2 relative">
- {isHistoryEmpty && !isPending ? (
+ <div ref={resultsRef} className="flex-1 overflow-y-auto mb-2 relative">
+ {searchMode ? (
+ <ChatHistorySearch
+ refreshKey={searchEpoch}
+ query={query}
+ onActiveValueChange={setActiveResult}
+ />
+ ) : staleHiddenRefresh ? (
+ listRetryFailed ? (
+ <div className="px-2 py-4 text-center">
+ <p className="text-muted-foreground text-sm">
+ Failed to load chat history.
+ </p>
+ <button
+ type="button"
+ onClick={retryStaleList}
+ className="text-muted-foreground hover:text-foreground hover:bg-accent mt-1 rounded-sm px-2 py-1 text-xs transition-colors"
+ >
+ Retry
+ </button>
+ </div>
+ ) : (
+ <div className="py-2">
+ <ChatHistorySkeleton />
+ </div>
+ )
+ ) : isHistoryEmpty && !isPending ? (
<div className="px-2 text-foreground/30 text-sm text-center py-4">
- No search history
+ No chats yet
</div>
) : (
<SidebarMenu>
@@ -133,8 +371,8 @@ export function ChatHistoryClient() {
)}
</SidebarMenu>
)}
- <div ref={loadMoreRef} style={{ height: '1px' }} />
- {(isLoading || isPending) && (
+ {!searchMode && <div ref={loadMoreRef} style={{ height: '1px' }} />}
+ {!searchMode && !staleHiddenRefresh && (isLoading || isPending) && (
<div className="py-2">
<ChatHistorySkeleton />
</div>
diff --git a/components/sidebar/chat-history-search.tsx b/components/sidebar/chat-history-search.tsx
new file mode 100644
index 00000000..559575f2
--- /dev/null
+++ b/components/sidebar/chat-history-search.tsx
@@ -0,0 +1,365 @@
+'use client'
+
+import { useCallback, useEffect, useRef, useState } from 'react'
+import { useRouter } from 'next/navigation'
+
+import {
+ IconLoader2 as Loader2,
+ IconSparkles as Sparkles
+} from '@tabler/icons-react'
+import { toast } from 'sonner'
+
+import { HL_START, HL_STOP } from '@/lib/render/highlight-markers'
+import {
+ effectiveQueryLength,
+ MIN_QUERY_LENGTH,
+ normalizeSearchQuery
+} from '@/lib/utils/search-query'
+
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandItem,
+ CommandList
+} from '@/components/ui/command'
+
+import { ChatHistorySkeleton } from './chat-history-skeleton'
+
+const DEBOUNCE_MS = 250
+
+export interface SearchResultItem {
+ chatId: string
+ title: string
+ snippet?: string
+ highlight?: string
+}
+
+interface SearchResponse {
+ title: SearchResultItem[]
+ content: SearchResultItem[]
+ thinking?: SearchResultItem[]
+}
+
+// Renders a ts_headline snippet, emphasizing the terms delimited by
+// HL_START/HL_STOP control characters. The delimiters are parsed into
+// elements (never injected as HTML), so literal HTML in message text stays
+// plain text.
+function HighlightedSnippet({ highlight }: { highlight: string }) {
+ const segments = highlight.split(
+ new RegExp(`(${HL_START}[\\s\\S]*?${HL_STOP})`, 'g')
+ )
+ return (
+ <p className="text-muted-foreground text-xs leading-snug break-words line-clamp-2 w-full">
+ {segments.map((segment, index) =>
+ segment.startsWith(HL_START) && segment.endsWith(HL_STOP) ? (
+ <b key={index} className="font-semibold text-foreground">
+ {segment.slice(HL_START.length, -HL_STOP.length)}
+ </b>
+ ) : (
+ <span key={index}>{segment}</span>
+ )
+ )}
+ </p>
+ )
+}
+
+interface ChatHistorySearchProps {
+ query: string
+ // Bumped by the parent when chat data changes (e.g. Clear History) so
+ // results referencing deleted chats are refetched. Unlike remounting, this
+ // preserves the thinking opt-in and refreshes thinking matches as well.
+ refreshKey?: number
+ // Reports cmdk's active option so the parent can mirror the combobox
+ // ARIA (aria-activedescendant) onto the search input, which lives outside
+ // the Command scope and therefore cannot use cmdk's own CommandInput.
+ onActiveValueChange?: (value: string) => void
+}
+
+export function ChatHistorySearch({
+ query,
+ refreshKey,
+ onActiveValueChange
+}: ChatHistorySearchProps) {
+ const router = useRouter()
+ const [results, setResults] = useState<SearchResponse | null>(null)
+ const [isSearching, setIsSearching] = useState(false)
+ const [thinkingRequested, setThinkingRequested] = useState(false)
+ const [isSearchingThinking, setIsSearchingThinking] = useState(false)
+ // cmdk only reports value changes in controlled mode, so the active option
+ // is held here and mirrored to the parent for its combobox ARIA.
+ const [activeValue, setActiveValue] = useState('')
+ // Monotonic request sequence: responses from superseded queries are dropped
+ // so stale results never overwrite the current query's results.
+ const requestSeqRef = useRef(0)
+ const thinkingAbortRef = useRef<AbortController | null>(null)
+ // Distinguishes a refreshKey bump (same query) from a query change, so
+ // only refreshes invalidate the currently displayed results.
+ const lastQueryRef = useRef(query)
+
+ // The thinking opt-in is scoped to a single search: it resets whenever the
+ // query changes, and unmounting discards it entirely (no persistence).
+ useEffect(() => {
+ setThinkingRequested(false)
+ setResults(null)
+ setActiveValue('')
+ // The options unmount with the query change; notify the parent too or
+ // its aria-activedescendant keeps pointing at a removed option (its
+ // mirror effect only reruns when the reported value changes).
+ onActiveValueChange?.('')
+ // An aborted thinking request can no longer update state (its sequence is
+ // stale), so the button state must be reset here or it stays stuck.
+ setIsSearchingThinking(false)
+ return () => {
+ thinkingAbortRef.current?.abort()
+ thinkingAbortRef.current = null
+ }
+ // The parent passes a stable state setter, so this dependency never
+ // re-triggers the reset.
+ }, [query, onActiveValueChange])
+
+ useEffect(() => {
+ // Bounded client-side so a pasted passage cannot exceed the request
+ // target limit before the server bound takes effect (same normalization
+ // as the backend, so results match the same effective query).
+ const trimmed = normalizeSearchQuery(query)
+ if (effectiveQueryLength(trimmed) < MIN_QUERY_LENGTH) {
+ return
+ }
+
+ // A refreshKey bump (chat data changed, e.g. Clear History) must not
+ // leave stale matches clickable while the refetch is in flight, and a
+ // failed refetch must not restore them: invalidate up front and let the
+ // refetch repopulate. A query change is already cleared by the reset
+ // effect above.
+ if (query === lastQueryRef.current) {
+ setResults(null)
+ // The options are about to unmount; drop the mirrored active option so
+ // the parent's aria-activedescendant cannot keep pointing at a removed
+ // element (indefinitely if the refetch fails or returns nothing).
+ // Notifying with '' when nothing is active is a no-op for the parent.
+ setActiveValue('')
+ onActiveValueChange?.('')
+ }
+ lastQueryRef.current = query
+
+ const seq = ++requestSeqRef.current
+ const controller = new AbortController()
+ setIsSearching(true)
+
+ const timer = setTimeout(async () => {
+ try {
+ const response = await fetch(
+ `/api/search?q=${encodeURIComponent(trimmed)}`,
+ { signal: controller.signal }
+ )
+ if (!response.ok) {
+ throw new Error(`Search failed with status ${response.status}`)
+ }
+ const data = (await response.json()) as SearchResponse
+ if (seq === requestSeqRef.current) {
+ // A thinking response may resolve before this main response;
+ // merging keeps the requested thinking section from vanishing.
+ setResults(prev =>
+ prev?.thinking !== undefined && data.thinking === undefined
+ ? { ...data, thinking: prev.thinking }
+ : data
+ )
+ }
+ } catch (error) {
+ if (controller.signal.aborted) {
+ return
+ }
+ console.error('History search failed:', error)
+ if (seq === requestSeqRef.current) {
+ toast.error('Search failed. Please try again.')
+ }
+ } finally {
+ if (seq === requestSeqRef.current) {
+ setIsSearching(false)
+ }
+ }
+ }, DEBOUNCE_MS)
+
+ return () => {
+ clearTimeout(timer)
+ controller.abort()
+ }
+ }, [query, refreshKey, onActiveValueChange])
+
+ const handleSearchThinking = useCallback(async () => {
+ const trimmed = normalizeSearchQuery(query)
+ if (effectiveQueryLength(trimmed) < MIN_QUERY_LENGTH) {
+ return
+ }
+
+ const seq = requestSeqRef.current
+ setThinkingRequested(true)
+ setIsSearchingThinking(true)
+ thinkingAbortRef.current?.abort()
+ const controller = new AbortController()
+ thinkingAbortRef.current = controller
+
+ try {
+ const response = await fetch(
+ `/api/search?q=${encodeURIComponent(trimmed)}&include=reasoning`,
+ { signal: controller.signal }
+ )
+ if (!response.ok) {
+ throw new Error(`Thinking search failed with status ${response.status}`)
+ }
+ const data = (await response.json()) as SearchResponse
+ if (seq === requestSeqRef.current) {
+ setResults(prev =>
+ prev ? { ...prev, thinking: data.thinking ?? [] } : data
+ )
+ }
+ } catch (error) {
+ if (controller.signal.aborted) {
+ return
+ }
+ console.error('Thinking search failed:', error)
+ if (seq === requestSeqRef.current) {
+ setThinkingRequested(false)
+ toast.error('Thinking search failed. Please try again.')
+ }
+ } finally {
+ if (seq === requestSeqRef.current) {
+ setIsSearchingThinking(false)
+ }
+ }
+ }, [query])
+
+ // When the parent signals that chat data changed, refresh thinking matches
+ // too if the opt-in is active (the main fetch effect refreshes title and
+ // content and merges the thinking section in). The refs keep a query change
+ // - which resets the opt-in in a separate effect - from re-triggering the
+ // thinking search: when the epoch bump lands in the same render as a query
+ // edit, `thinkingRequested` still holds the previous query's value here
+ // (the reset effect's state update has not applied yet), so the query is
+ // compared against the one this refresh was last run for.
+ const lastRefreshRef = useRef({ key: refreshKey, query })
+ useEffect(() => {
+ const prev = lastRefreshRef.current
+ const sameQuery = prev.query === query
+ lastRefreshRef.current = { key: refreshKey, query }
+ if (refreshKey !== prev.key && sameQuery && thinkingRequested) {
+ void handleSearchThinking()
+ }
+ }, [refreshKey, thinkingRequested, handleSearchThinking, query])
+
+ const openChat = useCallback(
+ (chatId: string) => {
+ router.push(`/search/${chatId}`)
+ },
+ [router]
+ )
+
+ const hasAnyResults =
+ !!results &&
+ (results.title.length > 0 ||
+ results.content.length > 0 ||
+ (results.thinking?.length ?? 0) > 0)
+ const showEmpty = !isSearching && !!results && !hasAnyResults
+ const thinkingItems = results?.thinking
+ const showThinkingSection = thinkingRequested && thinkingItems !== undefined
+
+ return (
+ <Command
+ shouldFilter={false}
+ value={activeValue}
+ onValueChange={value => {
+ setActiveValue(value)
+ onActiveValueChange?.(value)
+ }}
+ className="bg-transparent p-0"
+ >
+ <CommandList className="max-h-full">
+ {isSearching && !results && (
+ <div className="py-2">
+ <ChatHistorySkeleton />
+ </div>
+ )}
+ {showEmpty && <CommandEmpty>No matches</CommandEmpty>}
+ {results && results.title.length > 0 && (
+ <CommandGroup heading="By title">
+ {results.title.map(item => (
+ <CommandItem
+ key={`title-${item.chatId}`}
+ value={`title-${item.chatId}`}
+ onSelect={() => openChat(item.chatId)}
+ >
+ <span className="text-xs truncate">{item.title}</span>
+ </CommandItem>
+ ))}
+ </CommandGroup>
+ )}
+ {results && results.content.length > 0 && (
+ <CommandGroup heading="In chats">
+ {results.content.map(item => (
+ <CommandItem
+ key={`content-${item.chatId}`}
+ value={`content-${item.chatId}`}
+ onSelect={() => openChat(item.chatId)}
+ className="flex-col items-start gap-0.5"
+ >
+ <span className="text-xs font-medium truncate w-full">
+ {item.title}
+ </span>
+ {item.highlight && (
+ <HighlightedSnippet highlight={item.highlight} />
+ )}
+ </CommandItem>
+ ))}
+ </CommandGroup>
+ )}
+ {showThinkingSection && (
+ <CommandGroup heading="In thinking">
+ {results!.thinking!.length === 0 ? (
+ <div className="text-muted-foreground px-2 py-1.5 text-xs">
+ No thinking matches
+ </div>
+ ) : (
+ results!.thinking!.map(item => (
+ <CommandItem
+ key={`thinking-${item.chatId}`}
+ value={`thinking-${item.chatId}`}
+ onSelect={() => openChat(item.chatId)}
+ className="flex-col items-start gap-0.5"
+ >
+ <span className="text-xs font-medium truncate w-full">
+ {item.title}
+ </span>
+ {item.highlight && (
+ <HighlightedSnippet highlight={item.highlight} />
+ )}
+ </CommandItem>
+ ))
+ )}
+ </CommandGroup>
+ )}
+ </CommandList>
+ {!showThinkingSection && (
+ <button
+ type="button"
+ onClick={handleSearchThinking}
+ onKeyDown={event => {
+ // cmdk's root Enter handler would activate the selected result
+ // instead of pressing this button; keep the keydown out of the
+ // command scope so native button activation applies.
+ if (event.key === 'Enter') event.stopPropagation()
+ }}
+ disabled={isSearchingThinking}
+ className="text-muted-foreground hover:text-foreground hover:bg-accent flex items-center gap-2 rounded-sm px-2 py-1.5 text-xs transition-colors disabled:opacity-60"
+ >
+ {isSearchingThinking ? (
+ <Loader2 size={14} className="animate-spin" />
+ ) : (
+ <Sparkles size={14} />
+ )}
+ Search thinking
+ </button>
+ )}
+ </Command>
+ )
+}
diff --git a/drizzle/0020_add_parts_search_fts.sql b/drizzle/0020_add_parts_search_fts.sql
new file mode 100644
index 00000000..1606546f
--- /dev/null
+++ b/drizzle/0020_add_parts_search_fts.sql
@@ -0,0 +1,4 @@
+ALTER TABLE "parts" ADD COLUMN "search" "tsvector" GENERATED ALWAYS AS (to_tsvector('simple', left(coalesce(text_text, ''), 100000))) STORED;--> statement-breakpoint
+ALTER TABLE "parts" ADD COLUMN "search_reasoning" "tsvector" GENERATED ALWAYS AS (to_tsvector('simple', left(coalesce(reasoning_text, ''), 100000))) STORED;--> statement-breakpoint
+CREATE INDEX "parts_search_idx" ON "parts" USING gin ("search");--> statement-breakpoint
+CREATE INDEX "parts_search_reasoning_idx" ON "parts" USING gin ("search_reasoning");
\ No newline at end of file
diff --git a/drizzle/meta/0020_snapshot.json b/drizzle/meta/0020_snapshot.json
new file mode 100644
index 00000000..475edb3a
--- /dev/null
+++ b/drizzle/meta/0020_snapshot.json
@@ -0,0 +1,1782 @@
+{
+ "id": "6117a258-7087-4641-aa88-3d01746ff3e7",
+ "prevId": "6d6db4de-99ff-4a6b-8657-4ab00ce53c3b",
+ "version": "7",
+ "dialect": "postgresql",
+ "tables": {
+ "public.additional_usage_interest": {
+ "name": "additional_usage_interest",
+ "schema": "",
+ "columns": {
+ "user_id": {
+ "name": "user_id",
+ "type": "varchar(255)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "count": {
+ "name": "count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 1
+ },
+ "first_clicked_at": {
+ "name": "first_clicked_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "last_clicked_at": {
+ "name": "last_clicked_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {
+ "users_write_own_additional_usage_interest": {
+ "name": "users_write_own_additional_usage_interest",
+ "as": "PERMISSIVE",
+ "for": "ALL",
+ "to": ["public"],
+ "using": "user_id = (select current_setting('app.current_user_id', true))",
+ "withCheck": "user_id = (select current_setting('app.current_user_id', true))"
+ }
+ },
+ "checkConstraints": {},
+ "isRLSEnabled": true
+ },
+ "public.chats": {
+ "name": "chats",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(191)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "visibility": {
+ "name": "visibility",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'private'"
+ }
+ },
+ "indexes": {
+ "chats_user_id_idx": {
+ "name": "chats_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "chats_user_id_created_at_idx": {
+ "name": "chats_user_id_created_at_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "chats_created_at_idx": {
+ "name": "chats_created_at_idx",
+ "columns": [
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "chats_id_user_id_idx": {
+ "name": "chats_id_user_id_idx",
+ "columns": [
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {
+ "users_manage_own_chats": {
+ "name": "users_manage_own_chats",
+ "as": "PERMISSIVE",
+ "for": "ALL",
+ "to": ["public"],
+ "using": "user_id = (select current_setting('app.current_user_id', true))",
+ "withCheck": "user_id = (select current_setting('app.current_user_id', true))"
+ },
+ "public_chats_readable": {
+ "name": "public_chats_readable",
+ "as": "PERMISSIVE",
+ "for": "SELECT",
+ "to": ["public"],
+ "using": "visibility = 'public'"
+ }
+ },
+ "checkConstraints": {},
+ "isRLSEnabled": true
+ },
+ "public.feedback": {
+ "name": "feedback",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(191)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "sentiment": {
+ "name": "sentiment",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "message": {
+ "name": "message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "page_url": {
+ "name": "page_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_agent": {
+ "name": "user_agent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "feedback_user_id_idx": {
+ "name": "feedback_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "feedback_created_at_idx": {
+ "name": "feedback_created_at_idx",
+ "columns": [
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {
+ "feedback_select_policy": {
+ "name": "feedback_select_policy",
+ "as": "PERMISSIVE",
+ "for": "SELECT",
+ "to": ["public"],
+ "using": "true"
+ },
+ "anyone_can_insert_feedback": {
+ "name": "anyone_can_insert_feedback",
+ "as": "PERMISSIVE",
+ "for": "INSERT",
+ "to": ["public"],
+ "withCheck": "true"
+ },
+ "users_anonymize_own_feedback": {
+ "name": "users_anonymize_own_feedback",
+ "as": "PERMISSIVE",
+ "for": "UPDATE",
+ "to": ["public"],
+ "using": "user_id = (select current_setting('app.current_user_id', true))",
+ "withCheck": "user_id IS NULL"
+ }
+ },
+ "checkConstraints": {},
+ "isRLSEnabled": true
+ },
+ "public.files": {
+ "name": "files",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(191)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "chat_id": {
+ "name": "chat_id",
+ "type": "varchar(191)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "filename": {
+ "name": "filename",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "object_key": {
+ "name": "object_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "media_type": {
+ "name": "media_type",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "size": {
+ "name": "size",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "files_user_id_idx": {
+ "name": "files_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "files_user_id_updated_at_idx": {
+ "name": "files_user_id_updated_at_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "updated_at",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "files_chat_id_idx": {
+ "name": "files_chat_id_idx",
+ "columns": [
+ {
+ "expression": "chat_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "files_media_type_idx": {
+ "name": "files_media_type_idx",
+ "columns": [
+ {
+ "expression": "media_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "files_object_key_idx": {
+ "name": "files_object_key_idx",
+ "columns": [
+ {
+ "expression": "object_key",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "files_chat_id_chats_id_fk": {
+ "name": "files_chat_id_chats_id_fk",
+ "tableFrom": "files",
+ "tableTo": "chats",
+ "columnsFrom": ["chat_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {
+ "users_manage_own_files": {
+ "name": "users_manage_own_files",
+ "as": "PERMISSIVE",
+ "for": "ALL",
+ "to": ["public"],
+ "using": "user_id = (select current_setting('app.current_user_id', true))",
+ "withCheck": "user_id = (select current_setting('app.current_user_id', true))"
+ }
+ },
+ "checkConstraints": {},
+ "isRLSEnabled": true
+ },
+ "public.messages": {
+ "name": "messages",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(191)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "chat_id": {
+ "name": "chat_id",
+ "type": "varchar(191)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "messages_chat_id_idx": {
+ "name": "messages_chat_id_idx",
+ "columns": [
+ {
+ "expression": "chat_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "messages_chat_id_created_at_idx": {
+ "name": "messages_chat_id_created_at_idx",
+ "columns": [
+ {
+ "expression": "chat_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "messages_chat_id_chats_id_fk": {
+ "name": "messages_chat_id_chats_id_fk",
+ "tableFrom": "messages",
+ "tableTo": "chats",
+ "columnsFrom": ["chat_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {
+ "users_manage_chat_messages": {
+ "name": "users_manage_chat_messages",
+ "as": "PERMISSIVE",
+ "for": "ALL",
+ "to": ["public"],
+ "using": "EXISTS (\n SELECT 1 FROM \"chats\"\n WHERE \"chats\".id = chat_id\n AND \"chats\".user_id = current_setting('app.current_user_id', true)\n )",
+ "withCheck": "EXISTS (\n SELECT 1 FROM \"chats\"\n WHERE \"chats\".id = chat_id\n AND \"chats\".user_id = current_setting('app.current_user_id', true)\n )"
+ },
+ "public_chat_messages_readable": {
+ "name": "public_chat_messages_readable",
+ "as": "PERMISSIVE",
+ "for": "SELECT",
+ "to": ["public"],
+ "using": "EXISTS (\n SELECT 1 FROM \"chats\"\n WHERE \"chats\".id = chat_id\n AND \"chats\".visibility = 'public'\n )"
+ }
+ },
+ "checkConstraints": {},
+ "isRLSEnabled": true
+ },
+ "public.notes": {
+ "name": "notes",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(191)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "chat_id": {
+ "name": "chat_id",
+ "type": "varchar(191)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_message_id": {
+ "name": "source_message_id",
+ "type": "varchar(191)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "notes_user_id_idx": {
+ "name": "notes_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "notes_user_id_updated_at_idx": {
+ "name": "notes_user_id_updated_at_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "updated_at",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "notes_chat_id_idx": {
+ "name": "notes_chat_id_idx",
+ "columns": [
+ {
+ "expression": "chat_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "notes_source_message_id_idx": {
+ "name": "notes_source_message_id_idx",
+ "columns": [
+ {
+ "expression": "source_message_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "notes_chat_id_chats_id_fk": {
+ "name": "notes_chat_id_chats_id_fk",
+ "tableFrom": "notes",
+ "tableTo": "chats",
+ "columnsFrom": ["chat_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {
+ "users_manage_own_notes": {
+ "name": "users_manage_own_notes",
+ "as": "PERMISSIVE",
+ "for": "ALL",
+ "to": ["public"],
+ "using": "user_id = (select current_setting('app.current_user_id', true))",
+ "withCheck": "user_id = (select current_setting('app.current_user_id', true))"
+ }
+ },
+ "checkConstraints": {},
+ "isRLSEnabled": true
+ },
+ "public.parts": {
+ "name": "parts",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(191)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "message_id": {
+ "name": "message_id",
+ "type": "varchar(191)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "order": {
+ "name": "order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "type": {
+ "name": "type",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "text_text": {
+ "name": "text_text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "reasoning_text": {
+ "name": "reasoning_text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "file_media_type": {
+ "name": "file_media_type",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "file_filename": {
+ "name": "file_filename",
+ "type": "varchar(1024)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "file_url": {
+ "name": "file_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "file_key": {
+ "name": "file_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_url_source_id": {
+ "name": "source_url_source_id",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_url_url": {
+ "name": "source_url_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_url_title": {
+ "name": "source_url_title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_document_source_id": {
+ "name": "source_document_source_id",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_document_media_type": {
+ "name": "source_document_media_type",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_document_title": {
+ "name": "source_document_title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_document_filename": {
+ "name": "source_document_filename",
+ "type": "varchar(1024)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_document_url": {
+ "name": "source_document_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_document_snippet": {
+ "name": "source_document_snippet",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_tool_call_id": {
+ "name": "tool_tool_call_id",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_state": {
+ "name": "tool_state",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_error_text": {
+ "name": "tool_error_text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_search_input": {
+ "name": "tool_search_input",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_search_output": {
+ "name": "tool_search_output",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_fetch_input": {
+ "name": "tool_fetch_input",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_fetch_output": {
+ "name": "tool_fetch_output",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_question_input": {
+ "name": "tool_question_input",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_question_output": {
+ "name": "tool_question_output",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_todoWrite_input": {
+ "name": "tool_todoWrite_input",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_todoWrite_output": {
+ "name": "tool_todoWrite_output",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_todoRead_input": {
+ "name": "tool_todoRead_input",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_todoRead_output": {
+ "name": "tool_todoRead_output",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_dynamic_input": {
+ "name": "tool_dynamic_input",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_dynamic_output": {
+ "name": "tool_dynamic_output",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_dynamic_name": {
+ "name": "tool_dynamic_name",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_dynamic_type": {
+ "name": "tool_dynamic_type",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "data_prefix": {
+ "name": "data_prefix",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "data_content": {
+ "name": "data_content",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "data_id": {
+ "name": "data_id",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "provider_metadata": {
+ "name": "provider_metadata",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "search": {
+ "name": "search",
+ "type": "tsvector",
+ "primaryKey": false,
+ "notNull": false,
+ "generated": {
+ "as": "to_tsvector('simple', left(coalesce(text_text, ''), 100000))",
+ "type": "stored"
+ }
+ },
+ "search_reasoning": {
+ "name": "search_reasoning",
+ "type": "tsvector",
+ "primaryKey": false,
+ "notNull": false,
+ "generated": {
+ "as": "to_tsvector('simple', left(coalesce(reasoning_text, ''), 100000))",
+ "type": "stored"
+ }
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "parts_message_id_idx": {
+ "name": "parts_message_id_idx",
+ "columns": [
+ {
+ "expression": "message_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "parts_message_id_order_idx": {
+ "name": "parts_message_id_order_idx",
+ "columns": [
+ {
+ "expression": "message_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "order",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "parts_search_idx": {
+ "name": "parts_search_idx",
+ "columns": [
+ {
+ "expression": "search",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "gin",
+ "with": {}
+ },
+ "parts_search_reasoning_idx": {
+ "name": "parts_search_reasoning_idx",
+ "columns": [
+ {
+ "expression": "search_reasoning",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "gin",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "parts_message_id_messages_id_fk": {
+ "name": "parts_message_id_messages_id_fk",
+ "tableFrom": "parts",
+ "tableTo": "messages",
+ "columnsFrom": ["message_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {
+ "users_manage_message_parts": {
+ "name": "users_manage_message_parts",
+ "as": "PERMISSIVE",
+ "for": "ALL",
+ "to": ["public"],
+ "using": "EXISTS (\n SELECT 1 FROM \"messages\"\n INNER JOIN \"chats\" ON \"chats\".id = \"messages\".chat_id\n WHERE \"messages\".id = message_id\n AND \"chats\".user_id = current_setting('app.current_user_id', true)\n )",
+ "withCheck": "EXISTS (\n SELECT 1 FROM \"messages\"\n INNER JOIN \"chats\" ON \"chats\".id = \"messages\".chat_id\n WHERE \"messages\".id = message_id\n AND \"chats\".user_id = current_setting('app.current_user_id', true)\n )"
+ },
+ "public_chat_parts_readable": {
+ "name": "public_chat_parts_readable",
+ "as": "PERMISSIVE",
+ "for": "SELECT",
+ "to": ["public"],
+ "using": "EXISTS (\n SELECT 1 FROM \"messages\"\n INNER JOIN \"chats\" ON \"chats\".id = \"messages\".chat_id\n WHERE \"messages\".id = message_id\n AND \"chats\".visibility = 'public'\n )"
+ }
+ },
+ "checkConstraints": {
+ "text_text_required": {
+ "name": "text_text_required",
+ "value": "(type != 'text' OR text_text IS NOT NULL)"
+ },
+ "reasoning_text_required": {
+ "name": "reasoning_text_required",
+ "value": "(type != 'reasoning' OR reasoning_text IS NOT NULL)"
+ },
+ "file_fields_required": {
+ "name": "file_fields_required",
+ "value": "(type != 'file' OR (file_media_type IS NOT NULL AND file_filename IS NOT NULL AND (file_key IS NOT NULL OR file_url IS NOT NULL)))"
+ },
+ "tool_state_valid": {
+ "name": "tool_state_valid",
+ "value": "(tool_state IS NULL OR tool_state IN ('input-streaming', 'input-available', 'output-available', 'output-error'))"
+ },
+ "tool_fields_required": {
+ "name": "tool_fields_required",
+ "value": "(type NOT LIKE 'tool-%' OR (tool_tool_call_id IS NOT NULL AND tool_state IS NOT NULL))"
+ }
+ },
+ "isRLSEnabled": true
+ },
+ "public.usage_events": {
+ "name": "usage_events",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(191)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "event_type": {
+ "name": "event_type",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "amount": {
+ "name": "amount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "mode": {
+ "name": "mode",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "attempt_id": {
+ "name": "attempt_id",
+ "type": "varchar(191)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "message_id": {
+ "name": "message_id",
+ "type": "varchar(191)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "remaining": {
+ "name": "remaining",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "usage_events_user_type_attempt_idx": {
+ "name": "usage_events_user_type_attempt_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "event_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "attempt_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "usage_events_user_created_idx": {
+ "name": "usage_events_user_created_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {
+ "users_read_own_usage_events": {
+ "name": "users_read_own_usage_events",
+ "as": "PERMISSIVE",
+ "for": "SELECT",
+ "to": ["public"],
+ "using": "user_id = (select current_setting('app.current_user_id', true))"
+ },
+ "users_insert_own_usage_events": {
+ "name": "users_insert_own_usage_events",
+ "as": "PERMISSIVE",
+ "for": "INSERT",
+ "to": ["public"],
+ "withCheck": "user_id = (select current_setting('app.current_user_id', true))"
+ }
+ },
+ "checkConstraints": {},
+ "isRLSEnabled": true
+ },
+ "public.usage_grants": {
+ "name": "usage_grants",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(191)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "idempotency_key": {
+ "name": "idempotency_key",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "kind": {
+ "name": "kind",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "amount": {
+ "name": "amount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "granted_at": {
+ "name": "granted_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "usage_grants_user_idempotency_idx": {
+ "name": "usage_grants_user_idempotency_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "idempotency_key",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "usage_grants_user_expires_idx": {
+ "name": "usage_grants_user_expires_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "expires_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {
+ "users_read_own_usage_grants": {
+ "name": "users_read_own_usage_grants",
+ "as": "PERMISSIVE",
+ "for": "SELECT",
+ "to": ["public"],
+ "using": "user_id = (select current_setting('app.current_user_id', true))"
+ },
+ "users_insert_own_usage_grants": {
+ "name": "users_insert_own_usage_grants",
+ "as": "PERMISSIVE",
+ "for": "INSERT",
+ "to": ["public"],
+ "withCheck": "user_id = (select current_setting('app.current_user_id', true))"
+ }
+ },
+ "checkConstraints": {},
+ "isRLSEnabled": true
+ },
+ "public.account": {
+ "name": "account",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "account_id": {
+ "name": "account_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "provider_id": {
+ "name": "provider_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "access_token": {
+ "name": "access_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refresh_token": {
+ "name": "refresh_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "id_token": {
+ "name": "id_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "access_token_expires_at": {
+ "name": "access_token_expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refresh_token_expires_at": {
+ "name": "refresh_token_expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "password": {
+ "name": "password",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "account_user_id_user_id_fk": {
+ "name": "account_user_id_user_id_fk",
+ "tableFrom": "account",
+ "tableTo": "user",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.invitations": {
+ "name": "invitations",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "invited_by": {
+ "name": "invited_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "revoked_at": {
+ "name": "revoked_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "used_at": {
+ "name": "used_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "invitations_token_unique": {
+ "name": "invitations_token_unique",
+ "nullsNotDistinct": false,
+ "columns": ["token"]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.session": {
+ "name": "session",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "ip_address": {
+ "name": "ip_address",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_agent": {
+ "name": "user_agent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "impersonated_by": {
+ "name": "impersonated_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "session_user_id_user_id_fk": {
+ "name": "session_user_id_user_id_fk",
+ "tableFrom": "session",
+ "tableTo": "user",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "session_token_unique": {
+ "name": "session_token_unique",
+ "nullsNotDistinct": false,
+ "columns": ["token"]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user": {
+ "name": "user",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "email_verified": {
+ "name": "email_verified",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "image": {
+ "name": "image",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'user'"
+ },
+ "banned": {
+ "name": "banned",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "ban_reason": {
+ "name": "ban_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "ban_expires": {
+ "name": "ban_expires",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "user_email_unique": {
+ "name": "user_email_unique",
+ "nullsNotDistinct": false,
+ "columns": ["email"]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.verification": {
+ "name": "verification",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "identifier": {
+ "name": "identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ }
+ },
+ "enums": {},
+ "schemas": {},
+ "sequences": {},
+ "roles": {},
+ "policies": {},
+ "views": {},
+ "_meta": {
+ "columns": {},
+ "schemas": {},
+ "tables": {}
+ }
+}
diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json
index f1c40d5d..7b0e0b1c 100644
--- a/drizzle/meta/_journal.json
+++ b/drizzle/meta/_journal.json
@@ -141,6 +141,13 @@
"when": 1791284859864,
"tag": "0019_rainy_jack_flag",
"breakpoints": true
+ },
+ {
+ "idx": 20,
+ "version": "7",
+ "when": 1792863042496,
+ "tag": "0020_add_parts_search_fts",
+ "breakpoints": true
}
]
}
diff --git a/lib/db/__tests__/chat-search.test.ts b/lib/db/__tests__/chat-search.test.ts
new file mode 100644
index 00000000..0205c2f1
--- /dev/null
+++ b/lib/db/__tests__/chat-search.test.ts
@@ -0,0 +1,317 @@
+import { PgDialect } from 'drizzle-orm/pg-core'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { withRLS } from '@/lib/db/with-rls'
+import { HL_START, HL_STOP } from '@/lib/render/highlight-markers'
+
+import {
+ searchChatContent,
+ searchChatReasoning,
+ searchChatTitles
+} from '../actions'
+
+vi.mock('@/lib/db/with-rls', () => ({
+ withOptionalRLS: vi.fn(),
+ withRLS: vi.fn()
+}))
+
+const dialect = new PgDialect()
+
+function mockTitleQuery(rows: unknown[] = []) {
+ const limit = vi.fn().mockResolvedValue(rows)
+ const orderBy = vi.fn().mockReturnValue({ limit })
+ const where = vi.fn().mockReturnValue({ orderBy })
+ const from = vi.fn().mockReturnValue({ where })
+ const select = vi.fn().mockReturnValue({ from })
+
+ vi.mocked(withRLS).mockImplementation(async (_userId, callback) =>
+ callback({ select } as never)
+ )
+
+ return { select, where, orderBy, limit }
+}
+
+function mockExecute(rows: unknown[] = []) {
+ const execute = vi.fn().mockResolvedValue(rows)
+
+ vi.mocked(withRLS).mockImplementation(async (_userId, callback) =>
+ callback({ execute } as never)
+ )
+
+ return execute
+}
+
+describe('searchChatTitles', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('returns an empty list without querying for a blank query', async () => {
+ const result = await searchChatTitles('user-1', ' ')
+
+ expect(result).toEqual([])
+ expect(withRLS).not.toHaveBeenCalled()
+ })
+
+ it('matches titles case-insensitively under the user RLS scope', async () => {
+ const chat = { id: 'chat-1', title: 'Robert Frost Readings' }
+ const { where } = mockTitleQuery([chat])
+
+ const result = await searchChatTitles('user-1', 'frost')
+
+ expect(result).toEqual([chat])
+ expect(withRLS).toHaveBeenCalledWith('user-1', expect.any(Function))
+
+ const rendered = dialect.sqlToQuery(where.mock.calls[0][0])
+ expect(rendered.sql).toContain('ilike')
+ expect(rendered.sql).toContain('"title"')
+ expect(rendered.params).toContain('%frost%')
+ // user scoping: only the requesting user's chats
+ expect(rendered.sql).toContain('"user_id"')
+ expect(rendered.params).toContain('user-1')
+ })
+
+ it('orders newest first and applies the limit', async () => {
+ const { orderBy, limit } = mockTitleQuery([])
+
+ await searchChatTitles('user-1', 'frost', 20)
+
+ const rendered = dialect.sqlToQuery(orderBy.mock.calls[0][0])
+ expect(rendered.sql).toContain('desc')
+ expect(rendered.sql).toContain('"created_at"')
+ expect(limit).toHaveBeenCalledWith(20)
+ })
+
+ it('escapes ILIKE wildcards so the query matches literally', async () => {
+ const { where } = mockTitleQuery([])
+
+ await searchChatTitles('user-1', '100%')
+
+ const rendered = dialect.sqlToQuery(where.mock.calls[0][0])
+ // "%" is backslash-escaped, so it cannot act as a wildcard
+ expect(rendered.params).toContain('%100\\%%')
+ })
+
+ it('caps the query at the shared bound on a word boundary', async () => {
+ const { where } = mockTitleQuery([])
+
+ await searchChatTitles('user-1', 'note '.repeat(40) + 'kiwi')
+
+ // 204 characters: the bound keeps the first 40 whole tokens and drops
+ // 'kiwi', so title and content groups match the same effective query
+ const rendered = dialect.sqlToQuery(where.mock.calls[0][0])
+ expect(rendered.params).toContain(`%${'note '.repeat(40).trim()}%`)
+ })
+})
+
+describe('searchChatContent', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('returns an empty list without querying for a blank query', async () => {
+ const result = await searchChatContent('user-1', '')
+
+ expect(result).toEqual([])
+ expect(withRLS).not.toHaveBeenCalled()
+ })
+
+ it('runs a tsquery match scoped to the user and maps rows', async () => {
+ const execute = mockExecute([
+ {
+ chat_id: 'chat-2',
+ title: 'Poetry',
+ snippet: `Stopping by ${HL_START}woods${HL_STOP} on a snowy evening`
+ }
+ ])
+
+ const result = await searchChatContent('user-1', 'woods')
+
+ expect(result).toEqual([
+ {
+ chatId: 'chat-2',
+ title: 'Poetry',
+ snippet: `Stopping by ${HL_START}woods${HL_STOP} on a snowy evening`
+ }
+ ])
+ expect(withRLS).toHaveBeenCalledWith('user-1', expect.any(Function))
+
+ const rendered = dialect.sqlToQuery(execute.mock.calls[0][0])
+ // full-text match on the message-text column only (not reasoning)
+ expect(rendered.sql).toContain("to_tsvector('simple'")
+ expect(rendered.sql).toContain('::tsquery')
+ expect(rendered.sql).toContain('quote_nullable')
+ expect(rendered.sql).not.toContain('plainto_tsquery')
+ expect(rendered.sql).not.toContain("'english'")
+ expect(rendered.sql).toMatch(/ts_headline\(\s*'simple'/)
+ expect(rendered.sql).toContain('"search" @@')
+ expect(rendered.sql).toContain('ts_rank')
+ expect(rendered.sql).toContain('ts_headline')
+ // the headline is generated from the same bounded document the
+ // generated tsvector column indexes, so oversized parts cannot make
+ // ts_headline tokenize text that can never match
+ expect(rendered.sql).toMatch(/ts_headline\(\s*'simple',\s*left\(coalesce\(/)
+ expect(rendered.params).toContain(100000)
+ // highlight delimiters are control characters, not HTML
+ expect(rendered.params).toEqual(
+ expect.arrayContaining([
+ expect.stringContaining(`StartSel=${HL_START}, StopSel=${HL_STOP}`)
+ ])
+ )
+ expect(rendered.sql).toContain('"text_text"')
+ expect(rendered.sql).not.toContain('"search_reasoning"')
+ // user scoping: excludes other users' chats even when public
+ expect(rendered.sql).toContain('c.user_id')
+ expect(rendered.params).toContain('user-1')
+ expect(rendered.params).toContain('woods')
+ // matches both user questions and assistant answers: no role filter
+ expect(rendered.sql).not.toContain('role')
+ })
+
+ it('keeps the best-scoring part per chat, newest-first tie-break, capped', async () => {
+ const execute = mockExecute([])
+
+ await searchChatContent('user-1', 'woods', 20)
+
+ const rendered = dialect.sqlToQuery(execute.mock.calls[0][0])
+ expect(rendered.sql).toContain('DISTINCT ON (c.id)')
+ // per-chat best score first, then overall ranking with newest chats first
+ expect(rendered.sql).toContain('ORDER BY c.id, match_rank DESC')
+ expect(rendered.sql).toContain(
+ 'ORDER BY match_rank DESC, chat_created_at DESC'
+ )
+ expect(rendered.params).toContain(20)
+ })
+
+ it('builds per-word groups with forward prefix and reverse prefixes', async () => {
+ const execute = mockExecute([])
+
+ await searchChatContent('user-1', 'chats')
+
+ const rendered = dialect.sqlToQuery(execute.mock.calls[0][0])
+ // forward prefix (word:*) plus exact proper prefixes of >= 3 chars,
+ // AND-joined across words, so "chats" also finds "chat"
+ expect(rendered.sql).toContain("quote_nullable(l) || ':*'")
+ expect(rendered.sql).toContain('generate_series(3, length(l) - 1)')
+ expect(rendered.sql).toContain("' & '")
+ })
+
+ it('passes operator characters through as bound parameters, never SQL', async () => {
+ const execute = mockExecute([])
+
+ await searchChatContent('user-1', 'Rust & Go | notes!')
+
+ const rendered = dialect.sqlToQuery(execute.mock.calls[0][0])
+ // the raw query reaches Postgres only as a parameter; the FTS parser
+ // quotes it into inert lexemes (verified against PG 17)
+ expect(rendered.params).toContain('Rust & Go | notes!')
+ expect(rendered.sql).not.toContain('Rust')
+ })
+
+ it('returns empty for a punctuation-only query without erroring', async () => {
+ const execute = mockExecute([])
+
+ const result = await searchChatContent('user-1', '!!! ???')
+
+ // the NULL-tsquery path is handled in SQL; no special case in TS
+ expect(result).toEqual([])
+ expect(execute).toHaveBeenCalledTimes(1)
+ })
+
+ it('caps the query length before the prefix expansion', async () => {
+ const execute = mockExecute([])
+
+ await searchChatContent('user-1', 'x'.repeat(500))
+
+ // a long single token would expand into hundreds of prefix alternatives;
+ // the bound query keeps the generated tsquery small
+ const rendered = dialect.sqlToQuery(execute.mock.calls[0][0])
+ const queryParam = rendered.params.find(
+ p => typeof p === 'string' && p.includes('x')
+ )
+ expect(queryParam).toHaveLength(200)
+ })
+
+ it('requires a parsed lexeme of the minimum length before scanning', async () => {
+ const execute = mockExecute([])
+
+ await searchChatContent('user-1', 'a!')
+
+ // the parser drops '!', leaving only the 'a' lexeme; the HAVING guard
+ // must null the tsquery instead of running a broad 'a:*' prefix scan
+ const rendered = dialect.sqlToQuery(execute.mock.calls[0][0])
+ expect(rendered.sql).toContain('HAVING bool_or(length(l) >=')
+ expect(rendered.params).toContain(2)
+ })
+
+ it('truncates at a word boundary so no partial token broadens the match', async () => {
+ const execute = mockExecute([])
+
+ await searchChatContent('user-1', 'note '.repeat(40) + 'kiwi')
+
+ // 'kiwi' falls past the cap and is dropped whole; the retained tokens are
+ // all complete, so none acts as a broad prefix match
+ const rendered = dialect.sqlToQuery(execute.mock.calls[0][0])
+ const queryParam = rendered.params.find(
+ p => typeof p === 'string' && p.includes('note')
+ )
+ expect(queryParam).toBe('note '.repeat(40).trim())
+ })
+
+ it('treats newlines and tabs as word boundaries when truncating', async () => {
+ const execute = mockExecute([])
+
+ // pasted multiline query: 39 whole 'note' lines plus 'golden' crossing
+ // the cap; 'golden' must be dropped whole, not sliced into 'golde'
+ await searchChatContent('user-1', 'note\n'.repeat(39) + 'golden')
+
+ const rendered = dialect.sqlToQuery(execute.mock.calls[0][0])
+ const queryParam = rendered.params.find(
+ p => typeof p === 'string' && p.includes('note')
+ )
+ expect(queryParam).toBe('note\n'.repeat(38) + 'note')
+ })
+})
+
+describe('searchChatReasoning', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('returns an empty list without querying for a blank query', async () => {
+ const result = await searchChatReasoning('user-1', ' ')
+
+ expect(result).toEqual([])
+ expect(withRLS).not.toHaveBeenCalled()
+ })
+
+ it('matches the reasoning column only and maps rows', async () => {
+ const execute = mockExecute([
+ {
+ chat_id: 'chat-3',
+ title: 'Thinking chat',
+ snippet: `reasoning about ${HL_START}quasars${HL_STOP}`
+ }
+ ])
+
+ const result = await searchChatReasoning('user-1', 'quasars')
+
+ expect(result).toEqual([
+ {
+ chatId: 'chat-3',
+ title: 'Thinking chat',
+ snippet: `reasoning about ${HL_START}quasars${HL_STOP}`
+ }
+ ])
+
+ const rendered = dialect.sqlToQuery(execute.mock.calls[0][0])
+ expect(rendered.sql).toContain('"search_reasoning" @@')
+ expect(rendered.sql).toContain('"reasoning_text"')
+ expect(rendered.sql).not.toMatch(/"text_text"/)
+ expect(rendered.sql).toContain("to_tsvector('simple'")
+ expect(rendered.sql).toContain('::tsquery')
+ expect(rendered.sql).not.toContain("'english'")
+ expect(rendered.sql).toContain('c.user_id')
+ expect(rendered.params).toContain('user-1')
+ })
+})
diff --git a/lib/db/actions.ts b/lib/db/actions.ts
index 4f69e83a..9339048e 100644
--- a/lib/db/actions.ts
+++ b/lib/db/actions.ts
@@ -13,6 +13,7 @@ import {
sql
} from 'drizzle-orm'
+import { HL_START, HL_STOP } from '@/lib/render/highlight-markers'
import type { UIMessage } from '@/lib/types/ai'
import type { PersistableUIMessage } from '@/lib/types/message-persistence'
import {
@@ -22,6 +23,10 @@ import {
} from '@/lib/utils/message-mapping'
import { perfLog, perfTime } from '@/lib/utils/perf-logging'
import { incrementDbOperationCount } from '@/lib/utils/perf-tracking'
+import {
+ MIN_QUERY_LENGTH,
+ normalizeSearchQuery
+} from '@/lib/utils/search-query'
import type {
Chat,
@@ -159,11 +164,17 @@ export async function loadChat(
userId?: string
): Promise<UIMessage[]> {
return withOptionalRLS(userId || null, async tx => {
- // Use Drizzle's query API with relations
+ // Use Drizzle's query API with relations. The tsvector columns are
+ // projected out: they are only used by the search SQL and would
+ // otherwise be transported on every chat open.
const result = await tx.query.messages.findMany({
where: eq(messages.chatId, chatId),
with: {
parts: {
+ columns: {
+ search: false,
+ searchReasoning: false
+ },
orderBy: [asc(parts.order)]
}
},
@@ -193,6 +204,10 @@ export async function loadChatWithMessages(
where: eq(messages.chatId, chatId),
with: {
parts: {
+ columns: {
+ search: false,
+ searchReasoning: false
+ },
orderBy: [asc(parts.order)]
}
},
@@ -370,6 +385,155 @@ export async function getChatsPage(
}
}
+/**
+ * Search chat titles for a user (case-insensitive substring match), newest first.
+ */
+export async function searchChatTitles(
+ userId: string,
+ query: string,
+ limit = 20
+): Promise<Chat[]> {
+ const trimmed = normalizeSearchQuery(query)
+ if (!trimmed) {
+ return []
+ }
+ // Escape ILIKE wildcards so user input matches literally
+ const pattern = `%${escapeLikePattern(trimmed)}%`
+
+ return withRLS(userId, async tx => {
+ return tx
+ .select()
+ .from(chats)
+ .where(and(eq(chats.userId, userId), ilike(chats.title, pattern)))
+ .orderBy(desc(chats.createdAt))
+ .limit(Math.max(1, Math.min(limit, 50)))
+ })
+}
+
+export type ChatContentSearchResult = {
+ chatId: string
+ title: string
+ snippet: string
+}
+
+// Whitelisted column pairs for the full-text search scopes (never user input)
+const FTS_SCOPES = {
+ content: { tsvectorColumn: 'search', textColumn: 'text_text' },
+ reasoning: {
+ tsvectorColumn: 'search_reasoning',
+ textColumn: 'reasoning_text'
+ }
+} as const
+
+// Keep in sync with the generated tsvector columns in lib/db/schema.ts:
+// only the first 100k characters of a part are indexed, so matches can
+// only exist inside that prefix. ts_headline must tokenize the same
+// bounded document, or oversized parts make every search pay CPU and
+// memory in proportion to text that can never match.
+const FTS_TEXT_CAP = 100_000
+
+type FtsSearchScope = keyof typeof FTS_SCOPES
+
+/**
+ * Full-text search over message parts of the user's chats.
+ * The tsquery is built from the FTS parser's own lexemes (language-neutral
+ * `simple` config): each query word becomes an OR group of a forward prefix
+ * (`word:*`) plus its exact proper prefixes of at least 3 characters, so
+ * "chats" also finds "chat". Keeps the best-scoring part per chat (DISTINCT ON
+ * + ts_rank), with a ts_headline snippet containing <b></b> highlight markers.
+ * Ties on rank are broken by newest chat first.
+ */
+async function searchChatParts(
+ userId: string,
+ query: string,
+ limit: number,
+ scope: FtsSearchScope
+): Promise<ChatContentSearchResult[]> {
+ const trimmed = normalizeSearchQuery(query)
+ if (!trimmed) {
+ return []
+ }
+
+ const { tsvectorColumn, textColumn } = FTS_SCOPES[scope]
+ const tsvectorCol = sql.identifier(tsvectorColumn)
+ const textCol = sql.identifier(textColumn)
+ const pageLimit = Math.max(1, Math.min(limit, 50))
+
+ return withRLS(userId, async tx => {
+ const rows = await tx.execute<{
+ chat_id: string
+ title: string
+ snippet: string
+ }>(sql`
+ WITH fts_query AS (
+ SELECT ('(' || string_agg(
+ '(' || quote_nullable(l) || ':*' ||
+ coalesce((SELECT string_agg(' | ' || quote_nullable(left(l, g)), '' ORDER BY g)
+ FROM generate_series(3, length(l) - 1) g), '') || ')',
+ ' & ') || ')')::tsquery AS q
+ FROM unnest(tsvector_to_array(to_tsvector('simple', ${trimmed}))) l
+ -- The parser can drop punctuation, so the raw-length minimum does
+ -- not bound the parsed lexemes: require at least one lexeme of the
+ -- minimum length or the query becomes a broad single-character
+ -- prefix scan (empty lexeme set yields NULL q via the aggregate).
+ HAVING bool_or(length(l) >= ${MIN_QUERY_LENGTH})
+ ),
+ ranked AS (
+ SELECT DISTINCT ON (c.id)
+ c.id AS chat_id,
+ c.title AS title,
+ c.created_at AS chat_created_at,
+ ts_rank(p.${tsvectorCol}, fts_query.q) AS match_rank,
+ ts_headline(
+ 'simple',
+ left(coalesce(p.${textCol}, ''), ${FTS_TEXT_CAP}),
+ fts_query.q,
+ ${`MaxWords=14, MinWords=7, StartSel=${HL_START}, StopSel=${HL_STOP}`}
+ ) AS snippet
+ FROM fts_query
+ CROSS JOIN ${parts} p
+ JOIN ${messages} msg ON msg.id = p.message_id
+ JOIN ${chats} c ON c.id = msg.chat_id
+ WHERE c.user_id = ${userId}
+ AND p.${tsvectorCol} @@ fts_query.q
+ ORDER BY c.id, match_rank DESC, p.id
+ )
+ SELECT chat_id, title, snippet
+ FROM ranked
+ ORDER BY match_rank DESC, chat_created_at DESC
+ LIMIT ${pageLimit}
+ `)
+
+ return (rows as unknown as Array<Record<string, string>>).map(row => ({
+ chatId: row.chat_id,
+ title: row.title,
+ snippet: row.snippet
+ }))
+ })
+}
+
+/**
+ * Full-text search over user/assistant message text of the user's chats.
+ */
+export async function searchChatContent(
+ userId: string,
+ query: string,
+ limit = 20
+): Promise<ChatContentSearchResult[]> {
+ return searchChatParts(userId, query, limit, 'content')
+}
+
+/**
+ * Full-text search over stored reasoning output of the user's chats.
+ */
+export async function searchChatReasoning(
+ userId: string,
+ query: string,
+ limit = 10
+): Promise<ChatContentSearchResult[]> {
+ return searchChatParts(userId, query, limit, 'reasoning')
+}
+
/**
* Delete a chat
*/
diff --git a/lib/db/schema.ts b/lib/db/schema.ts
index ce1282fa..90cf8265 100644
--- a/lib/db/schema.ts
+++ b/lib/db/schema.ts
@@ -2,6 +2,7 @@ import { createId } from '@paralleldrive/cuid2'
import { InferSelectModel, sql } from 'drizzle-orm'
import {
check,
+ customType,
index,
integer,
json,
@@ -20,6 +21,13 @@ const USER_ID_LENGTH = 255
const VARCHAR_LENGTH = 256
const FILENAME_LENGTH = 1024
+// Postgres tsvector type (no built-in drizzle type)
+const tsvector = customType<{ data: string }>({
+ dataType() {
+ return 'tsvector'
+ }
+})
+
// ID generation function
export const generateId = () => createId()
@@ -199,12 +207,26 @@ export const parts = pgTable(
// Provider metadata
providerMetadata: json('provider_metadata').$type<Record<string, any>>(),
+ // Full-text search columns (maintained by Postgres, used by history
+ // search). Input is capped at 100k characters: Postgres errors on any
+ // tsvector over 1MB ("string is too long for tsvector"), which would
+ // otherwise abort migration 0020 on existing rows and fail inserts of
+ // oversized parts. Worst-case vector size at this cap is ~220KB.
+ search: tsvector('search').generatedAlwaysAs(
+ sql`to_tsvector('simple', left(coalesce(text_text, ''), 100000))`
+ ),
+ searchReasoning: tsvector('search_reasoning').generatedAlwaysAs(
+ sql`to_tsvector('simple', left(coalesce(reasoning_text, ''), 100000))`
+ ),
+
createdAt: timestamp('created_at').notNull().defaultNow()
},
table => [
// Indexes
index('parts_message_id_idx').on(table.messageId),
index('parts_message_id_order_idx').on(table.messageId, table.order),
+ index('parts_search_idx').using('gin', table.search),
+ index('parts_search_reasoning_idx').using('gin', table.searchReasoning),
// Constraints
check('text_text_required', sql`(type != 'text' OR text_text IS NOT NULL)`),
diff --git a/lib/render/highlight-markers.ts b/lib/render/highlight-markers.ts
new file mode 100644
index 00000000..e11fc383
--- /dev/null
+++ b/lib/render/highlight-markers.ts
@@ -0,0 +1,9 @@
+// Delimiters that ts_headline wraps matched terms in (see searchChatParts).
+// Control characters (U+0001, U+0002) are used so literal HTML or markdown
+// in chat text can never be mistaken for a highlight marker.
+export const HL_START = String.fromCharCode(1)
+export const HL_STOP = String.fromCharCode(2)
+
+export function stripHighlightMarkers(text: string): string {
+ return text.split(HL_START).join('').split(HL_STOP).join('')
+}
diff --git a/lib/utils/__tests__/search-query.test.ts b/lib/utils/__tests__/search-query.test.ts
new file mode 100644
index 00000000..44a61f45
--- /dev/null
+++ b/lib/utils/__tests__/search-query.test.ts
@@ -0,0 +1,129 @@
+import { describe, expect, it } from 'vitest'
+
+import {
+ effectiveQueryLength,
+ MAX_QUERY_LENGTH,
+ normalizeSearchQuery
+} from '../search-query'
+
+describe('normalizeSearchQuery', () => {
+ it('trims and passes short queries through unchanged', () => {
+ expect(normalizeSearchQuery(' frost ')).toBe('frost')
+ })
+
+ it('returns empty for blank input', () => {
+ expect(normalizeSearchQuery(' \n\t ')).toBe('')
+ })
+
+ it('caps a whitespace-free token at the bound', () => {
+ expect(normalizeSearchQuery('x'.repeat(500))).toHaveLength(MAX_QUERY_LENGTH)
+ })
+
+ it('truncates at a whitespace boundary, dropping the partial token', () => {
+ expect(normalizeSearchQuery('note '.repeat(40) + 'kiwi')).toBe(
+ 'note '.repeat(40).trim()
+ )
+ expect(normalizeSearchQuery('note\n'.repeat(39) + 'golden')).toBe(
+ 'note\n'.repeat(38) + 'note'
+ )
+ })
+
+ it('keeps a token that ends exactly at the cap', () => {
+ // the 200th code unit is the last 'x' and the original continues with
+ // whitespace: the token is complete and must survive
+ expect(normalizeSearchQuery('a ' + 'x'.repeat(198) + ' y')).toBe(
+ 'a ' + 'x'.repeat(198)
+ )
+ })
+
+ it('drops the whole fragment when the cap splits a hyphenated token', () => {
+ const prefix = 'note '.repeat(39) // 195 characters
+ // cut immediately after the hyphen: the retained 'foo-' parses to the
+ // 'foo' component and would match chats without foo-bar
+ expect(normalizeSearchQuery(prefix + 'xfoo-bar')).toBe(prefix.trim())
+ // cut immediately before the hyphen: the hyphen continues the hword,
+ // but the complete 'x' before the compound token is kept
+ expect(normalizeSearchQuery(prefix + 'x foo-bar')).toBe(
+ (prefix + 'x').trim()
+ )
+ })
+
+ it('drops the whole fragment when the cap splits a numeric token', () => {
+ const prefix = 'note '.repeat(39) // 195 characters
+ // cap lands between '1' and '.': 'wxyz1' is a numword the parser could
+ // continue into a compound token, so the whole fragment goes
+ expect(normalizeSearchQuery(prefix + 'wxyz1.23')).toBe(prefix.trim())
+ // cap lands between 'z' and '1': 'vwxyz1' would parse as one numword
+ expect(normalizeSearchQuery(prefix + 'vwxyz1.23')).toBe(prefix.trim())
+ // Codex's example shape: the cap cuts 'x1.23' after the digit, leaving
+ // a retained '1' that would suppress otherwise-matching histories
+ expect(normalizeSearchQuery(prefix + 'w x1.23')).toBe(prefix + 'w')
+ })
+
+ it('drops the whole fragment when the cap splits an email token', () => {
+ const prefix = 'note '.repeat(39) // 195 characters
+ expect(normalizeSearchQuery(prefix + '[email protected]')).toBe(
+ prefix.trim()
+ )
+ })
+
+ it('drops the trailing word when the cap lands on an underscore', () => {
+ const prefix = 'note '.repeat(39) // 195 characters
+ // cap immediately after '_': the unfinished word goes with the fragment
+ expect(normalizeSearchQuery(prefix + 'foob_bar')).toBe(prefix.trim())
+ // cap inside the segment following '_': 'xfo_o' + 'bar' would leave a
+ // capped word ending in the underscore
+ expect(normalizeSearchQuery(prefix + 'xfo_obar')).toBe(prefix.trim())
+ // cap immediately before '_': the underscore splits tokens, so the
+ // preceding word is complete and stays
+ expect(normalizeSearchQuery(prefix + 'foobx_bar')).toBe(prefix + 'foobx')
+ })
+
+ it('treats punctuation after the cap as a token boundary, like the parser', () => {
+ // Postgres ends a word token at '!' just as it does at a space, so the
+ // 198-character token is complete at the cap and must survive; only a
+ // word character after the cap means the cap split a token.
+ expect(normalizeSearchQuery('a ' + 'x'.repeat(198) + '! y')).toBe(
+ 'a ' + 'x'.repeat(198)
+ )
+ })
+
+ it('drops a token sliced by the cap at a punctuation boundary', () => {
+ // no whitespace anywhere, but '!' ends the first token; the second
+ // token is sliced by the cap and must be dropped rather than act as a
+ // broad prefix match
+ expect(normalizeSearchQuery('aaa!' + 'b'.repeat(200))).toBe('aaa!')
+ })
+
+ it('never leaves a lone surrogate behind when the cap splits a pair', () => {
+ const result = normalizeSearchQuery('a' + 'πŸ˜€'.repeat(100))
+
+ // the 200-code-unit cut lands inside the 100th emoji; the dangling
+ // high surrogate would make encodeURIComponent throw
+ expect(result).toBe('a' + 'πŸ˜€'.repeat(99))
+ expect(() => encodeURIComponent(result)).not.toThrow()
+ })
+
+ it('strips lone surrogates present in the raw input', () => {
+ const result = normalizeSearchQuery('a\uD800b\uDC00c')
+
+ expect(result).toBe('abc')
+ expect(() => encodeURIComponent(result)).not.toThrow()
+ })
+})
+
+describe('effectiveQueryLength', () => {
+ it('counts characters, not UTF-16 code units', () => {
+ // a single non-BMP character is two code units but one character for
+ // the user and for Postgres' parser
+ expect(effectiveQueryLength('πŸ˜€')).toBe(1)
+ expect(effectiveQueryLength('πŸ˜€πŸ˜€')).toBe(2)
+ expect(effectiveQueryLength('πŸ˜€a')).toBe(2)
+ })
+
+ it('measures the normalized query', () => {
+ expect(effectiveQueryLength(' a ')).toBe(1)
+ expect(effectiveQueryLength(' \n ')).toBe(0)
+ expect(effectiveQueryLength('ab')).toBe(2)
+ })
+})
diff --git a/lib/utils/message-mapping.ts b/lib/utils/message-mapping.ts
index 907e39bf..29ea5fcf 100644
--- a/lib/utils/message-mapping.ts
+++ b/lib/utils/message-mapping.ts
@@ -13,6 +13,14 @@ import type {
ToolState
} from '@/lib/types/message-persistence'
+// The tsvector search columns are projected out of normal chat loads
+// (loadChat / loadChatWithMessages) so stored vectors are not transported on
+// every chat open. Mapping only needs the remaining columns.
+export type DBMessagePartWithoutVectors = Omit<
+ DBMessagePartSelect,
+ 'search' | 'searchReasoning'
+>
+
// Define local types for message parts that are compatible with the AI SDK
type TextUIPart = { type: 'text'; text: string; providerMetadata?: any }
type ReasoningUIPart = {
@@ -364,7 +372,7 @@ export function mapUIMessagePartsToDBParts(
* Convert DB message parts to UI format
*/
export function mapDBPartToUIMessagePart(
- part: DBMessagePartSelect
+ part: DBMessagePartWithoutVectors
): UIMessagePart {
switch (part.type) {
case 'text':
@@ -413,9 +421,9 @@ export function mapDBPartToUIMessagePart(
if (part.type.startsWith('tool-')) {
const toolName = part.type.substring(5) // Remove 'tool-' prefix
const inputColumn =
- `tool_${toolName}_input` as keyof DBMessagePartSelect
+ `tool_${toolName}_input` as keyof DBMessagePartWithoutVectors
const outputColumn =
- `tool_${toolName}_output` as keyof DBMessagePartSelect
+ `tool_${toolName}_output` as keyof DBMessagePartWithoutVectors
// Special handling for dynamic tools
if (toolName === 'dynamic' && part.tool_dynamic_type === 'draft') {
@@ -805,7 +813,7 @@ export function buildUIMessageFromDB(
metadata?: UIMessageMetadata | null
createdAt?: Date | string
},
- dbParts: DBMessagePartSelect[]
+ dbParts: DBMessagePartWithoutVectors[]
): UIMessage {
// Merge metadata from DB with createdAt
const metadata: UIMessageMetadata = {
diff --git a/lib/utils/search-query.ts b/lib/utils/search-query.ts
new file mode 100644
index 00000000..bc01dfc6
--- /dev/null
+++ b/lib/utils/search-query.ts
@@ -0,0 +1,79 @@
+/**
+ * Shared query bound for history search, applied on the client before a
+ * query goes into a GET URL and again in the database actions so every
+ * result group matches the same effective query.
+ *
+ * Content/reasoning tokens expand into an OR group of their proper
+ * prefixes, so the generated tsquery grows quadratically with token
+ * length; bounding the query keeps it (and Postgres' parse of it) small no
+ * matter the input. Client-side bounding also keeps a pasted passage from
+ * exceeding the deployment's request-target limit before the server bound
+ * can take effect. Truncation happens at the last parser-token boundary
+ * before the cap so a partially sliced token cannot act as a broad prefix
+ * match.
+ */
+export const MAX_QUERY_LENGTH = 200
+
+// Minimum length of the effective query. Enforced on the normalized query
+// in the route and client, and on the lexemes the FTS parser produces in
+// searchChatParts (punctuation can be dropped by the parser, leaving a
+// single-character lexeme whose prefix match would scan broadly).
+export const MIN_QUERY_LENGTH = 2
+
+// Length of the effective query in characters (code points), not UTF-16
+// code units: a single non-BMP character such as an emoji is two code
+// units but one character for the user and for Postgres' parser, so the
+// minimum must be checked in code points. Normalization is idempotent,
+// so callers may pass an already-normalized query.
+export function effectiveQueryLength(query: string): number {
+ return [...normalizeSearchQuery(query)].length
+}
+
+// Slicing can split a surrogate pair, and lone surrogates are rejected by
+// encodeURIComponent (URIError) and by Postgres' UTF-8 validation. Strip
+// them so the normalized query is always encodable.
+function stripLoneSurrogates(value: string): string {
+ return value.replace(
+ /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,
+ ''
+ )
+}
+
+// Which characters can continue the token a cap landed inside, verified
+// against Postgres 17's default text-search parser: hyphens (foo-bar ->
+// {foo, bar, foo-bar}), dots (a.b, 1.23, 192.168.1.1), slashes (a/b/c.d),
+// @ ([email protected]), and colons (example.com:80) all produce compound
+// tokens; underscores (x1_2 -> {x1, 2}), apostrophes (don't -> {don, t}),
+// and other punctuation split tokens instead. Reimplementing every token
+// rule in JS is a rabbit hole, so the cap is conservative: when the
+// character after the cap could continue a compound token, the whole
+// trailing fragment is dropped. Over-dropping a complete token is a minor
+// precision loss; keeping a fragment changes the query, which is the bug.
+// The fragment matcher also includes '_': although an underscore splits
+// tokens (so a cap before one keeps a complete word), a capped word left
+// ending in '_' reads as unfinished text and goes with the fragment.
+const TOKEN_CONT = /[\p{L}\p{N}.\-/@:]/u
+const TRAILING_FRAGMENT = /[\p{L}\p{N}.\-/@:_]+$/u
+
+export function normalizeSearchQuery(query: string): string {
+ const trimmed = query.trim()
+ if (trimmed.length <= MAX_QUERY_LENGTH) {
+ return stripLoneSurrogates(trimmed)
+ }
+ const capped = trimmed.slice(0, MAX_QUERY_LENGTH)
+ // The retained text is complete unless the cap landed inside a token the
+ // parser could continue: whitespace and plain punctuation ('!' as much as
+ // ' ') both end every token type, so only a continuation character after
+ // the cap means a token was split.
+ const next = trimmed[MAX_QUERY_LENGTH]
+ if (next === undefined || !TOKEN_CONT.test(next)) {
+ return stripLoneSurrogates(capped.trim())
+ }
+ // Drop the trailing fragment (everything since the last whitespace) so a
+ // partial token cannot act as a broad prefix match. When the whole capped
+ // range is a single fragment there is nothing to drop, and a long
+ // specific prefix is not broad, so keep it.
+ const fragment = capped.match(TRAILING_FRAGMENT)
+ const cut = fragment ? capped.slice(0, fragment.index) : capped
+ return stripLoneSurrogates((cut.trim() || capped).trim())
+}