fix: stream file search results and cancel stale searches (#99)

This commit is contained in:
Jinjing
2026-03-24 21:30:35 -07:00
committed by GitHub
parent 9c5a1f48bb
commit 624786d4cd
2 changed files with 115 additions and 61 deletions
+74 -51
View File
@@ -1,7 +1,7 @@
import { ipcMain } from 'electron'
import { readdir, readFile, writeFile, stat } from 'fs/promises'
import { resolve, relative } from 'path'
import { execFile } from 'child_process'
import { spawn } from 'child_process'
import type { Store } from '../persistence'
import type {
DirEntry,
@@ -150,7 +150,7 @@ export function registerFilesystemHandlers(store: Store): void {
'--max-count',
'200', // max matches per file
'--max-filesize',
'1M'
`${Math.floor(MAX_FILE_SIZE / 1024 / 1024)}M`
]
if (!args.caseSensitive) {
@@ -184,63 +184,86 @@ export function registerFilesystemHandlers(store: Store): void {
const fileMap = new Map<string, SearchFileResult>()
let totalMatches = 0
let truncated = false
let stdoutBuffer = ''
let resolved = false
const child = execFile('rg', rgArgs, { maxBuffer: 50 * 1024 * 1024 }, (error, stdout) => {
clearTimeout(killTimeout)
// rg exit code 1 = no matches, exit code 2 = error.
// If there's no stdout and a real error, return empty.
if (error && !stdout) {
resolvePromise({ files: [], totalMatches: 0, truncated: false })
const resolveOnce = (): void => {
if (resolved) {
return
}
const lines = stdout.split('\n').filter(Boolean)
for (const line of lines) {
if (totalMatches >= maxResults) {
truncated = true
break
}
try {
const msg = JSON.parse(line)
if (msg.type !== 'match') {
continue
}
const data = msg.data
const absPath: string = data.path.text
const relPath = relative(args.rootPath, absPath)
let fileResult = fileMap.get(absPath)
if (!fileResult) {
fileResult = { filePath: absPath, relativePath: relPath, matches: [] }
fileMap.set(absPath, fileResult)
}
for (const sub of data.submatches) {
fileResult.matches.push({
line: data.line_number,
column: sub.start + 1,
matchLength: sub.end - sub.start,
lineContent: data.lines.text.replace(/\n$/, '')
})
totalMatches++
if (totalMatches >= maxResults) {
truncated = true
break
}
}
} catch {
// skip malformed JSON lines
}
}
resolved = true
clearTimeout(killTimeout)
resolvePromise({
files: Array.from(fileMap.values()),
totalMatches,
truncated
})
}
const processLine = (line: string): void => {
if (!line || totalMatches >= maxResults) {
return
}
try {
const msg = JSON.parse(line)
if (msg.type !== 'match') {
return
}
const data = msg.data
const absPath: string = data.path.text
const relPath = relative(args.rootPath, absPath)
let fileResult = fileMap.get(absPath)
if (!fileResult) {
fileResult = { filePath: absPath, relativePath: relPath, matches: [] }
fileMap.set(absPath, fileResult)
}
for (const sub of data.submatches) {
fileResult.matches.push({
line: data.line_number,
column: sub.start + 1,
matchLength: sub.end - sub.start,
lineContent: data.lines.text.replace(/\n$/, '')
})
totalMatches++
if (totalMatches >= maxResults) {
truncated = true
child.kill()
break
}
}
} catch {
// skip malformed JSON lines
}
}
const child = spawn('rg', rgArgs, { stdio: ['ignore', 'pipe', 'pipe'] })
child.stdout.setEncoding('utf-8')
child.stdout.on('data', (chunk: string) => {
stdoutBuffer += chunk
const lines = stdoutBuffer.split('\n')
stdoutBuffer = lines.pop() ?? ''
for (const line of lines) {
processLine(line)
}
})
child.stderr.on('data', () => {
// Drain stderr so rg cannot block on a full pipe.
})
child.once('error', () => {
resolveOnce()
})
child.once('close', () => {
if (stdoutBuffer) {
processLine(stdoutBuffer)
}
resolveOnce()
})
// Kill after 30s if still running
@@ -44,6 +44,16 @@ export default function Search(): React.JSX.Element {
const inputRef = useRef<HTMLInputElement>(null)
const [showFilters, setShowFilters] = useState(false)
const searchTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const latestSearchIdRef = useRef(0)
const cancelPendingSearch = useCallback(() => {
latestSearchIdRef.current += 1
if (searchTimerRef.current) {
clearTimeout(searchTimerRef.current)
searchTimerRef.current = null
}
setFileSearchLoading(false)
}, [setFileSearchLoading])
// Find active worktree path
const worktreePath = useMemo(() => {
@@ -67,18 +77,27 @@ export default function Search(): React.JSX.Element {
// Cleanup debounce timer on unmount
useEffect(() => {
return () => {
if (searchTimerRef.current) {
clearTimeout(searchTimerRef.current)
}
cancelPendingSearch()
}
}, [])
}, [cancelPendingSearch])
useEffect(() => {
if (!worktreePath) {
cancelPendingSearch()
setFileSearchResults(null)
}
}, [worktreePath, cancelPendingSearch, setFileSearchResults])
// Execute search with debounce — reads fresh state inside setTimeout
// to avoid stale closures when options change during debounce
const executeSearch = useCallback(
(query: string) => {
latestSearchIdRef.current += 1
const searchId = latestSearchIdRef.current
if (searchTimerRef.current) {
clearTimeout(searchTimerRef.current)
searchTimerRef.current = null
}
if (!query.trim() || !worktreePath) {
@@ -89,6 +108,7 @@ export default function Search(): React.JSX.Element {
setFileSearchLoading(true)
searchTimerRef.current = setTimeout(async () => {
searchTimerRef.current = null
try {
const state = useAppStore.getState()
const results = await window.api.fs.search({
@@ -101,18 +121,29 @@ export default function Search(): React.JSX.Element {
excludePattern: state.fileSearchExcludePattern || undefined,
maxResults: 10000
})
setFileSearchResults(results)
if (latestSearchIdRef.current === searchId) {
setFileSearchResults(results)
}
} catch (err) {
console.error('Search failed:', err)
setFileSearchResults({ files: [], totalMatches: 0, truncated: false })
if (latestSearchIdRef.current === searchId) {
setFileSearchResults({ files: [], totalMatches: 0, truncated: false })
}
} finally {
setFileSearchLoading(false)
if (latestSearchIdRef.current === searchId) {
setFileSearchLoading(false)
}
}
}, 300)
},
[worktreePath, setFileSearchResults, setFileSearchLoading]
)
const handleClearSearch = useCallback(() => {
cancelPendingSearch()
clearFileSearch()
}, [cancelPendingSearch, clearFileSearch])
// Re-execute search from event handlers when options change
const rerunSearch = useCallback(() => {
const q = useAppStore.getState().fileSearchQuery
@@ -134,14 +165,14 @@ export default function Search(): React.JSX.Element {
(e: React.KeyboardEvent) => {
if (e.key === 'Escape') {
if (fileSearchQuery) {
clearFileSearch()
handleClearSearch()
}
}
if (e.key === 'Enter') {
executeSearch(fileSearchQuery)
}
},
[fileSearchQuery, clearFileSearch, executeSearch]
[fileSearchQuery, handleClearSearch, executeSearch]
)
const handleMatchClick = useCallback(
@@ -199,7 +230,7 @@ export default function Search(): React.JSX.Element {
{fileSearchQuery && (
<button
className="p-0.5 rounded-sm hover:bg-muted text-muted-foreground hover:text-foreground"
onClick={clearFileSearch}
onClick={handleClearSearch}
>
<X size={12} />
</button>