fix(ai-vault): keep search results on screen while typing in Session History

This commit is contained in:
Kelvin Amoaba
2026-11-08 18:10:01 +00:00
parent ace74af490
commit 6bb8cd7cd7
7 changed files with 143 additions and 40 deletions
@@ -178,7 +178,10 @@ export default function AiVaultPanel({
() => withAiVaultHistoryPreviews(search.sessions, history),
[history, search.sessions]
)
const sessions = searching ? searchSessions : history
// Until this query's first reply, older hits stay dimmed or, with none, title matches fill the wait.
const waitingForHits = searching && search.loading && !search.answered
const searchTitles = waitingForHits && search.hits.length === 0
const sessions = searching && !searchTitles ? searchSessions : history
const requestedScanKey = aiVaultLocalScanKey({
scopePaths,
includeAntigravityIdeSessions: true,
@@ -225,7 +228,8 @@ export default function AiVaultPanel({
sessionLimit
})
const { filteredSessions, groups } = useAiVaultPanelSessions(sessions, searching, group, {
const listMode = searching ? (searchTitles ? 'search-titles' : 'search-hits') : 'browse'
const { filteredSessions, groups } = useAiVaultPanelSessions(sessions, listMode, group, {
query,
agents,
scope,
@@ -328,7 +332,9 @@ export default function AiVaultPanel({
)}
{(!searching || sessions.length > 0 || search.loading) && (
<AiVaultSessionVirtualList
key={searching ? search.resetKey : 'history'}
key={searching ? 'search' : 'history'}
resultsKey={searching ? search.resultsKey : undefined}
stale={waitingForHits && search.hits.length > 0}
searchHits={searching ? searchHits : undefined}
searchHitHostLabels={searchHitHostLabels}
groups={groups}
@@ -336,7 +342,7 @@ export default function AiVaultPanel({
loading={searching ? search.loading : loading}
scopePending={!searching && scopePending}
scanProgressShown={stripProgress !== null}
sessionsCount={sessions.length}
sessionsCount={searching ? filteredSessions.length : sessions.length}
filteredSessionsCount={filteredSessions.length}
noAgentsSelected={agents.length === 0}
error={error}
@@ -1,5 +1,5 @@
// @vitest-environment happy-dom
import { cleanup, render, screen, fireEvent } from '@testing-library/react'
import { act, cleanup, render, screen, fireEvent } from '@testing-library/react'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import type { ComponentProps } from 'react'
import { useAppStore } from '@/store/index'
@@ -14,6 +14,8 @@ import {
STRUCTURED_AGENT_SESSION_RESUME_HISTORY_RUNTIME_CAPABILITY,
STRUCTURED_AGENT_SESSION_RESUME_LINKED_CWD_RUNTIME_CAPABILITY
} from '../../../../../../shared/agent-session/structured-agent-session-surface-capabilities'
import { getDefaultSettings } from '../../../../../../shared/constants'
import { resolveAiVaultSearchSettings } from '../../../../../../shared/ai-vault/search/ai-vault-search-settings'
import { aiVaultSearchHitToSession } from '../search/ai-vault-search-session'
import type { AiVaultSessionVirtualList } from '../session-list/AiVaultSessionVirtualList'
import type { AiVaultResumeInChatEligibility } from '../session-actions/ai-vault-session-resume-in-chat'
@@ -148,3 +150,35 @@ it.each([false, true])(
expect(panelRows[0].session.sessionId).toBe(session.sessionId)
}
)
it('lists title matches from loaded history until full-text search answers', async () => {
useAppStore.setState({
settings: {
...getDefaultSettings('/tmp'),
aiVaultSearch: { ...resolveAiVaultSearchSettings({}), enabled: true }
}
})
const loaded = (sessionId: string, title: string) =>
aiVaultSearchHitToSession(
{ ...searchHit(), agent: 'claude', cwd: '/repo/wt', sessionId, title },
'local'
)
returned.sessions = [loaded('login', 'Fix login redirect'), loaded('parser', 'Refactor parser')]
const search = vi.mocked(window.api.aiVault.searchSessions).mockReturnValue(new Promise(() => {}))
const { default: AiVaultPanel } = await import('../panel/AiVaultPanel')
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
try {
render(<AiVaultPanel />)
fireEvent.change(screen.getByRole('textbox', { name: 'Search sessions' }), {
target: { value: 'login' }
})
expect(panelRows.map((row) => row.session.sessionId)).toEqual(['login'])
await act(async () => {
await vi.advanceTimersByTimeAsync(250)
})
expect(search).toHaveBeenCalled()
expect(panelRows.map((row) => row.session.sessionId)).toEqual(['login'])
} finally {
vi.useRealTimers()
}
})
@@ -230,3 +230,32 @@ it('revalidates active search without losing hits, accepting old pages, or touch
await act(async () => feeds.emit.get('a')?.({ type: 'snapshot', sessions: [] }))
expect(searchSessions).toHaveBeenCalledTimes(baseline + 2)
})
it('keeps the last hits on screen until a newer query answers, ignoring the older reply', async () => {
const hit = (sessionId: string) => ({ ...searchHit(), sessionId })
let answerOld = (_response: AiVaultSearchResponse): void => {}
searchSessions
.mockResolvedValueOnce({ ...searchResults(), hits: [hit('first')] })
.mockImplementationOnce(
() =>
new Promise((resolve) => {
answerOld = resolve
})
)
.mockResolvedValueOnce({ ...searchResults(), hits: [hit('newest')] })
const { result, rerender, unmount } = renderHook(
({ request }) => useAiVaultSearch(request, 'local', ''),
{ initialProps: { request: { query: 'n' } } }
)
await debounce()
rerender({ request: { query: 'ne' } })
await debounce()
rerender({ request: { query: 'nee' } })
expect(result.current.hits.map((entry) => entry.sessionId)).toEqual(['first'])
expect(result.current.answered).toBe(false)
await debounce()
await act(async () => answerOld({ ...searchResults(), hits: [hit('older')] }))
expect(result.current.hits.map((entry) => entry.sessionId)).toEqual(['newest'])
expect(result.current.answered).toBe(true)
unmount()
})
@@ -61,7 +61,7 @@ export function useAiVaultSearch(
let pending = false
let followUp = false
let started = false
async function run(cursor?: string, revalidate = false) {
async function run(cursor?: string) {
if (pending || cancelled || !request || !scope) {
return
}
@@ -69,13 +69,12 @@ export function useAiVaultSearch(
started = true
const revision = associations.getSnapshot()
const isCurrent = () => !cancelled && revision === associations.getSnapshot()
setPage((previous) => ({
identity,
hits: (cursor || revalidate) && previous?.identity === identity ? previous.hits : [],
response: null,
error: false,
loading: true
}))
// Only a rerun of the same request touches its page; a new request's page waits for its reply.
setPage((previous) =>
previous?.identity === identity
? { ...previous, response: null, error: false, loading: true }
: previous
)
try {
let response = await window.api.aiVault.searchSessions({ ...request, cursor }, scope)
let append = Boolean(cursor)
@@ -110,7 +109,7 @@ export function useAiVaultSearch(
pending = false
if (followUp && !cancelled) {
followUp = false
void run(undefined, true)
void run()
}
}
}
@@ -122,10 +121,10 @@ export function useAiVaultSearch(
if (pending) {
followUp = true
} else {
void run(undefined, true)
void run()
}
})
const timer = setTimeout(() => void run(undefined, true), 250)
const timer = setTimeout(() => void run(), 250)
return () => {
cancelled = true
followUp = false
@@ -135,17 +134,26 @@ export function useAiVaultSearch(
}
}, [identity, associations])
// Leaving search drops its hits so returning cannot revive another request's results or cursor.
if (page && !(request && scope)) {
setPage(null)
}
const current = page?.identity === identity ? page : null
// Same-host hits stay visible while a newer request is debounced or in flight.
const shown = current ?? (page?.identity.scope === scope ? page : null)
return {
hits: current?.hits ?? [],
hits: shown?.hits ?? [],
/** The hits answer this request; until then they are an older request's, or none. */
answered: current !== null,
/** Changes when hits for a different request land, never while one is pending. */
resultsKey: JSON.stringify(shown ? [shown.identity.scope, shown.identity.request] : null),
response: current?.response ?? null,
error: current?.error ?? false,
loading: Boolean(request && scope && (!current || current.loading)),
removeHit: (hit: AiVaultSearchHit) =>
setPage((previous) =>
previous?.identity === identity
? { ...previous, hits: previous.hits.filter((entry) => entry !== hit) }
: previous
setPage(
(previous) =>
previous && { ...previous, hits: previous.hits.filter((entry) => entry !== hit) }
),
retry: () => setRevision((value) => value + 1),
loadMore: () => {
@@ -235,7 +243,6 @@ export function useAiVaultPanelSearch(
hasQuery,
needsLocalConsent,
titleOnly: hasQuery && titleOnly,
host,
resetKey: JSON.stringify([scope, request])
host
}
}
@@ -1,6 +1,6 @@
import { SubagentExpansionProvider } from './ai-vault-subagent-expansion'
import { useVirtualizer } from '@tanstack/react-virtual'
import { useCallback, useMemo, useRef, useState, type Ref } from 'react'
import { useCallback, useLayoutEffect, useMemo, useRef, useState, type Ref } from 'react'
import type { AgentDotState } from '@/components/AgentStateDot'
import type {
AiVaultScope,
@@ -8,6 +8,7 @@ import type {
} from '../../../../../../shared/ai-vault/contracts/ai-vault-types'
import type { AiVaultResumeStartup } from '../../../../../../shared/ai-vault/resume/ai-vault-resume-startup'
import { useTranslate } from '@/i18n/use-translate'
import { cn } from '@/lib/utils'
import { measureVirtualRowRetainingHiddenSize } from '@/hooks/virtualized-hidden-row-measurement'
import { getActiveStickyHeaderIndexForScroll } from '../../../sidebar/worktree-list/viewport/virtual-rows'
import { EmptyState, SessionLoadingState } from './AiVaultSessionListStates'
@@ -45,6 +46,8 @@ export function AiVaultSessionVirtualList({
groups,
collapsedGroups,
loading,
stale = false,
resultsKey,
scopePending = false,
scanProgressShown = false,
sessionsCount,
@@ -84,6 +87,10 @@ export function AiVaultSessionVirtualList({
groups: readonly AiVaultSessionListGroup[]
collapsedGroups: ReadonlySet<string>
loading: boolean
/** Rows answer an older search while a newer one runs. */
stale?: boolean
/** Changes when a different result set lands, which returns the list to its top match. */
resultsKey?: string
scopePending?: boolean
/** The progress strip above names the scan, so the list does not repeat it. */
scanProgressShown?: boolean
@@ -130,6 +137,9 @@ export function AiVaultSessionVirtualList({
const stickyRangeStartIndexRef = useRef(0)
const activeStickyHeaderIndexRef = useRef<number | null>(null)
const [expandedSessionIds, setExpandedSessionIds] = useState<Set<string>>(() => new Set())
useLayoutEffect(() => {
listScrollRef.current?.scrollTo({ top: 0 })
}, [resultsKey])
const vaultRows = useMemo(() => {
const rows: AiVaultListRow[] = []
@@ -148,7 +158,11 @@ export function AiVaultSessionVirtualList({
}, [collapsedGroups, groups])
const stickyHeaderIndexes = useMemo(() => getVaultStickyHeaderIndexes(vaultRows), [vaultRows])
const selection = useAiVaultSessionSelection(vaultRows, keyboardRef !== undefined, query)
const selection = useAiVaultSessionSelection(
vaultRows,
keyboardRef !== undefined,
JSON.stringify([query, resultsKey ?? null])
)
const { selectedIndex } = selection
const virtualizer = useVirtualizer({
@@ -231,6 +245,10 @@ export function AiVaultSessionVirtualList({
}
// Enter resumes the row in the chat; a row that can't shows its details instead.
const activateSession = (session: AiVaultSession, index: number): void => {
// A stale row answers an older query, so Enter waits for the current one.
if (stale) {
return
}
if (!pickHere(session)) {
setExpandedSessionIds((current) => new Set(current).add(session.id))
virtualizer.scrollToIndex(index)
@@ -288,7 +306,11 @@ export function AiVaultSessionVirtualList({
) : null}
{vaultRows.length > 0 ? (
<div className="relative w-full" style={{ height: virtualizer.getTotalSize() }}>
<div
className={cn('relative w-full', stale && 'opacity-60')}
aria-busy={stale || undefined}
style={{ height: virtualizer.getTotalSize() }}
>
{virtualItems.map((virtualRow) => (
<AiVaultVirtualRow
key={virtualRow.key}
@@ -17,9 +17,12 @@ export type AiVaultSessionListGroup = {
sessions: AiVaultSession[]
}
/** Browse groups title-filtered sessions; search lists hits as given, or title matches until hits arrive. */
export type AiVaultPanelListMode = 'browse' | 'search-hits' | 'search-titles'
export function useAiVaultPanelSessions(
sessions: readonly AiVaultSession[],
searching: boolean,
mode: AiVaultPanelListMode,
group: AiVaultGroup,
{
query,
@@ -35,7 +38,7 @@ export function useAiVaultPanelSessions(
) {
const filteredSessions = useMemo(
() =>
searching
mode === 'search-hits'
? sessions
: filterAiVaultSessions(sessions, {
query,
@@ -49,7 +52,7 @@ export function useAiVaultPanelSessions(
hideEmptySessions
}),
[
searching,
mode,
sessions,
query,
agents,
@@ -64,13 +67,13 @@ export function useAiVaultPanelSessions(
)
const groups = useMemo<AiVaultSessionListGroup[]>(
() =>
searching
mode !== 'browse'
? filteredSessions.length === 0
? []
: // The results bar above the list carries the count, so this group only holds rows.
[{ key: 'search-results', label: null, sessions: [...filteredSessions] }]
: groupAiVaultSessions(filteredSessions, group, { sessionProjectById, projectLabelByKey }),
[searching, filteredSessions, group, projectLabelByKey, sessionProjectById]
[mode, filteredSessions, group, projectLabelByKey, sessionProjectById]
)
return { filteredSessions, groups }
}
@@ -22,20 +22,22 @@ export type AiVaultSessionSelection = {
move: (delta: 1 | -1) => number | null
}
/** Reconcile selected session/row after list changes; new queries reset to the top match. */
/** Reconcile selected session/row after list changes; a new `resetKey` (query or result set) resets to the top match. */
export function useAiVaultSessionSelection(
rows: readonly AiVaultListRow[],
enabled: boolean,
query: string
resetKey: string
): AiVaultSessionSelection {
const [stored, setStored] = useState<{ index: number; sessionId: string; query: string } | null>(
null
)
// Clear query-owned picks so reverting search text cannot revive them.
if (stored !== null && stored.query !== query) {
const [stored, setStored] = useState<{
index: number
sessionId: string
resetKey: string
} | null>(null)
// Clear picks owned by an older key so reverting search text cannot revive them.
if (stored !== null && stored.resetKey !== resetKey) {
setStored(null)
}
const chosen = stored?.query === query ? stored : null
const chosen = stored?.resetKey === resetKey ? stored : null
const sessionIndexes = useMemo(
() => rows.flatMap((row, index) => (row.type === 'session' ? [index] : [])),
[rows]
@@ -51,7 +53,7 @@ export function useAiVaultSessionSelection(
const select = (index: number): void => {
const sessionId = sessionIdAt(rows, index)
if (sessionId !== null) {
setStored({ index, sessionId, query })
setStored({ index, sessionId, resetKey })
}
}
return {