mirror of
https://github.com/wu736139669/hapi.git
synced 2026-11-26 05:27:06 +00:00
feat(web,hub): add opt-in search for session message content (#1598)
Adds an opt-in content search over session messages, alongside the existing metadata search. An FTS5 index covers visible user and assistant prose; the sidebar gains a scope toggle, and selecting a result opens the matching message rather than the session tail. Search scope is a two-state toggle rather than a dropdown: a 48x48 target matching the clear endcap, distinct glyphs for session details vs message text, tooltips naming the real scopes, and the active mode kept on the collapsed chip (tiann/hapi#2081). Dogfooded on a live 1178-session fleet. The scope toggle and reading forward from a search result were both click-tested on that install — the latter walking six bounded pages through a 1,507-message session and stopping correctly at the session head. The per-commit history does not survive this squash; the review trail — including which commit closed which finding — is on the PR threads. Fixes #1554 Fixes #2081
This commit is contained in:
@@ -357,6 +357,100 @@ describe('ApiClient error mapping', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('ApiClient session content search', () => {
|
||||
it('uses the opt-in content-search endpoint with encoded query, limit, and session scope', async () => {
|
||||
const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ results: [] }), { status: 200 })
|
||||
)
|
||||
try {
|
||||
const api = new ApiClient('test-token')
|
||||
await api.searchSessionContent(' cache search ', 12, undefined, ['session /?#', 'session /?#', 'other'])
|
||||
const request = fetchMock.mock.calls[0]?.[0]
|
||||
const init = fetchMock.mock.calls[0]?.[1]
|
||||
expect(String(request)).toBe('/api/sessions/content-search')
|
||||
expect(init?.method).toBe('POST')
|
||||
expect(init?.body).toBe(JSON.stringify({
|
||||
query: 'cache search',
|
||||
limit: 12,
|
||||
sessionIds: ['session /?#', 'other']
|
||||
}))
|
||||
} finally {
|
||||
fetchMock.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('chunks oversized session scopes and merges results before applying the limit', async () => {
|
||||
const requests: string[][] = []
|
||||
const fetchMock = vi.spyOn(globalThis, 'fetch').mockImplementation(async (_input, init) => {
|
||||
const body = JSON.parse(String(init?.body)) as { sessionIds: string[] }
|
||||
requests.push(body.sessionIds)
|
||||
const resultSessionId = body.sessionIds.at(-1) ?? ''
|
||||
const index = Number(resultSessionId.match(/session-(\d+)/)?.[1] ?? 0)
|
||||
return new Response(JSON.stringify({
|
||||
results: [{
|
||||
session: { id: resultSessionId, updatedAt: index },
|
||||
match: { messageId: `message-${index}`, role: 'user', seq: index, createdAt: index, snippet: `hit-${index}`, truncated: false }
|
||||
}],
|
||||
hasPotentiallyIncompleteResults: body.sessionIds.some(id => id.startsWith('session-0-'))
|
||||
}), { status: 200 })
|
||||
})
|
||||
|
||||
try {
|
||||
const sessionIds = Array.from({ length: 7_000 }, (_, index) =>
|
||||
`session-${index}-${'x'.repeat(32)}`
|
||||
)
|
||||
const api = new ApiClient('test-token')
|
||||
const response = await api.searchSessionContent('cache', 2, undefined, sessionIds)
|
||||
|
||||
expect(requests.length).toBeGreaterThan(1)
|
||||
expect(requests.flat()).toHaveLength(sessionIds.length)
|
||||
expect(Math.max(...requests.map(chunk => new TextEncoder().encode(JSON.stringify(chunk)).byteLength)))
|
||||
.toBeLessThan(192 * 1024)
|
||||
const expectedTopIds = requests
|
||||
.map(chunk => Number(chunk.at(-1)?.match(/session-(\d+)/)?.[1] ?? 0))
|
||||
.sort((a, b) => b - a)
|
||||
.slice(0, 2)
|
||||
expect(response.results.map(result => result.match.messageId)).toEqual([
|
||||
...expectedTopIds.map(index => `message-${index}`)
|
||||
])
|
||||
expect(response.hasPotentiallyIncompleteResults).toBe(true)
|
||||
} finally {
|
||||
fetchMock.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('requests an encoded message context endpoint', async () => {
|
||||
const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
|
||||
new Response(JSON.stringify(null), { status: 200 })
|
||||
)
|
||||
try {
|
||||
const api = new ApiClient('test-token')
|
||||
await expect(api.getMessageContext('session /?#', 'message /?#')).resolves.toBeNull()
|
||||
expect(fetchMock.mock.calls[0]?.[0]).toBe(
|
||||
'/api/sessions/session%20%2F%3F%23/messages/message%20%2F%3F%23/context'
|
||||
)
|
||||
} finally {
|
||||
fetchMock.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('loads all matching messages for an opened session', async () => {
|
||||
const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ matches: [], total: 0 }), { status: 200 })
|
||||
)
|
||||
try {
|
||||
const api = new ApiClient('test-token')
|
||||
await api.searchSessionContentMatches('session /?#', ' cache search ', 42)
|
||||
const request = fetchMock.mock.calls[0]?.[0]
|
||||
expect(String(request)).toContain(
|
||||
'/api/sessions/session%20%2F%3F%23/content-search?query=cache+search&limit=42'
|
||||
)
|
||||
} finally {
|
||||
fetchMock.mockRestore()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('ApiClient Kimi session model discovery', () => {
|
||||
let originalFetch: typeof globalThis.fetch
|
||||
let fetchMock: ReturnType<typeof vi.fn>
|
||||
|
||||
+121
-1
@@ -13,6 +13,7 @@ import type {
|
||||
CopilotAgentMode,
|
||||
FileSearchResponse,
|
||||
MachinesResponse,
|
||||
MessageContextResponse,
|
||||
MessagesResponse,
|
||||
OpencodeImportSessionsResponse,
|
||||
OpencodeLocalSessionsResponse,
|
||||
@@ -29,8 +30,10 @@ import type {
|
||||
HapiSessionExportResponse,
|
||||
HubHealthResponse,
|
||||
SessionResponse,
|
||||
SessionContentMatchesResponse,
|
||||
SessionTitleSuggestionResponse,
|
||||
SessionsResponse
|
||||
SessionsResponse,
|
||||
SessionContentSearchResponse
|
||||
} from '@/types/api'
|
||||
import type {
|
||||
AgyModelsResponse,
|
||||
@@ -126,6 +129,58 @@ export interface TranscriptionCredentialsUpdate {
|
||||
elevenLabsMaxDurationSeconds?: number | null
|
||||
}
|
||||
|
||||
// Keep scoped content-search bodies comfortably below the Hub's 256 KiB
|
||||
// request limit. The remaining space covers the query, limit, and JSON body
|
||||
// framing; callers still get one merged result set for large visible scopes.
|
||||
const CONTENT_SEARCH_SCOPE_CHUNK_BYTES = 192 * 1024
|
||||
|
||||
function chunkContentSearchSessionIds(sessionIds: readonly string[]): string[][] {
|
||||
if (sessionIds.length === 0) return []
|
||||
|
||||
const encoder = new TextEncoder()
|
||||
const chunks: string[][] = []
|
||||
let current: string[] = []
|
||||
let currentBytes = 2 // []
|
||||
|
||||
for (const sessionId of sessionIds) {
|
||||
const itemBytes = encoder.encode(JSON.stringify(sessionId)).byteLength
|
||||
const separatorBytes = current.length > 0 ? 1 : 0
|
||||
if (
|
||||
current.length > 0
|
||||
&& currentBytes + separatorBytes + itemBytes > CONTENT_SEARCH_SCOPE_CHUNK_BYTES
|
||||
) {
|
||||
chunks.push(current)
|
||||
current = []
|
||||
currentBytes = 2
|
||||
}
|
||||
|
||||
current.push(sessionId)
|
||||
currentBytes += (current.length > 1 ? 1 : 0) + itemBytes
|
||||
}
|
||||
|
||||
if (current.length > 0) chunks.push(current)
|
||||
return chunks
|
||||
}
|
||||
|
||||
function mergeContentSearchResponses(
|
||||
responses: SessionContentSearchResponse[],
|
||||
limit: number
|
||||
): SessionContentSearchResponse {
|
||||
const results = responses
|
||||
.flatMap(response => response.results)
|
||||
.sort((a, b) => (
|
||||
b.session.updatedAt - a.session.updatedAt
|
||||
|| b.match.seq - a.match.seq
|
||||
|| b.match.createdAt - a.match.createdAt
|
||||
|| a.session.id.localeCompare(b.session.id)
|
||||
))
|
||||
|
||||
return {
|
||||
results: results.slice(0, limit),
|
||||
hasPotentiallyIncompleteResults: responses.some(response => response.hasPotentiallyIncompleteResults)
|
||||
}
|
||||
}
|
||||
|
||||
type ApiClientOptions = {
|
||||
baseUrl?: string
|
||||
getToken?: () => string | null
|
||||
@@ -291,6 +346,65 @@ export class ApiClient {
|
||||
return await this.request<HubHealthResponse>('/health')
|
||||
}
|
||||
|
||||
async searchSessionContent(
|
||||
query: string,
|
||||
limit: number = 50,
|
||||
signal?: AbortSignal,
|
||||
sessionIds?: readonly string[]
|
||||
): Promise<SessionContentSearchResponse> {
|
||||
const normalizedQuery = query.trim()
|
||||
if (sessionIds !== undefined) {
|
||||
const normalizedSessionIds = [...new Set(sessionIds.map((sessionId) => sessionId.trim()).filter(Boolean))]
|
||||
const chunks = chunkContentSearchSessionIds(normalizedSessionIds)
|
||||
if (chunks.length <= 1) {
|
||||
return await this.request<SessionContentSearchResponse>(
|
||||
'/api/sessions/content-search',
|
||||
{
|
||||
method: 'POST',
|
||||
signal,
|
||||
body: JSON.stringify({
|
||||
query: normalizedQuery,
|
||||
limit,
|
||||
sessionIds: normalizedSessionIds
|
||||
})
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
const responses = await Promise.all(chunks.map((chunk) => this.request<SessionContentSearchResponse>(
|
||||
'/api/sessions/content-search',
|
||||
{
|
||||
method: 'POST',
|
||||
signal,
|
||||
body: JSON.stringify({
|
||||
query: normalizedQuery,
|
||||
limit,
|
||||
sessionIds: chunk
|
||||
})
|
||||
}
|
||||
)))
|
||||
return mergeContentSearchResponses(responses, limit)
|
||||
}
|
||||
const params = new URLSearchParams({ query: normalizedQuery, limit: String(limit) })
|
||||
return await this.request<SessionContentSearchResponse>(
|
||||
`/api/sessions/content-search?${params.toString()}`,
|
||||
{ signal }
|
||||
)
|
||||
}
|
||||
|
||||
async searchSessionContentMatches(
|
||||
sessionId: string,
|
||||
query: string,
|
||||
limit: number = 500,
|
||||
signal?: AbortSignal
|
||||
): Promise<SessionContentMatchesResponse> {
|
||||
const params = new URLSearchParams({ query: query.trim(), limit: String(limit) })
|
||||
return await this.request<SessionContentMatchesResponse>(
|
||||
`/api/sessions/${encodeURIComponent(sessionId)}/content-search?${params.toString()}`,
|
||||
{ signal }
|
||||
)
|
||||
}
|
||||
|
||||
async getPushVapidPublicKey(): Promise<PushVapidPublicKeyResponse> {
|
||||
return await this.request<PushVapidPublicKeyResponse>('/api/push/vapid-public-key')
|
||||
}
|
||||
@@ -454,6 +568,12 @@ export class ApiClient {
|
||||
return await this.request<MessagesResponse>(url)
|
||||
}
|
||||
|
||||
async getMessageContext(sessionId: string, messageId: string): Promise<MessageContextResponse | null> {
|
||||
return await this.request<MessageContextResponse | null>(
|
||||
`/api/sessions/${encodeURIComponent(sessionId)}/messages/${encodeURIComponent(messageId)}/context`
|
||||
)
|
||||
}
|
||||
|
||||
async getGitStatus(sessionId: string): Promise<GitCommandResponse> {
|
||||
return await this.request<GitCommandResponse>(`/api/sessions/${encodeURIComponent(sessionId)}/git-status`)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user