()
| 705 | */ |
| 706 | const REFRESH_THROTTLE_MS = 5_000 |
| 707 | export function startBackgroundCacheRefresh(): void { |
| 708 | if (fileListRefreshPromise) return |
| 709 | |
| 710 | // Throttle only when a cache exists — cold start must always populate. |
| 711 | // Refresh immediately when .git/index mtime changed (tracked files). |
| 712 | // Otherwise refresh at most once per 5s — this floor picks up new UNTRACKED |
| 713 | // files, which don't bump .git/index. The signature checks downstream skip |
| 714 | // the rebuild when the 5s refresh finds nothing actually changed. |
| 715 | const indexMtime = getGitIndexMtime() |
| 716 | if (fileIndex) { |
| 717 | const gitStateChanged = |
| 718 | indexMtime !== null && indexMtime !== lastGitIndexMtime |
| 719 | if (!gitStateChanged && Date.now() - lastRefreshMs < REFRESH_THROTTLE_MS) { |
| 720 | return |
| 721 | } |
| 722 | } |
| 723 | |
| 724 | const generation = cacheGeneration |
| 725 | const refreshStart = Date.now() |
| 726 | // Ensure the FileIndex singleton exists — it's progressively queryable |
| 727 | // via readyCount while the build runs. Callers searching early get partial |
| 728 | // results; indexBuildComplete fires after .done so they can re-search. |
| 729 | getFileIndex() |
| 730 | fileListRefreshPromise = getPathsForSuggestions() |
| 731 | .then(result => { |
| 732 | if (generation !== cacheGeneration) { |
| 733 | return result // Cache was cleared; don't overwrite with stale data |
| 734 | } |
| 735 | fileListRefreshPromise = null |
| 736 | indexBuildComplete.emit() |
| 737 | // Commit the start-time mtime observation on success. If git state |
| 738 | // changed mid-refresh, the next call will see the newer mtime and |
| 739 | // correctly refresh again. |
| 740 | lastGitIndexMtime = indexMtime |
| 741 | lastRefreshMs = Date.now() |
| 742 | logForDebugging( |
| 743 | `[FileIndex] cache refresh completed in ${Date.now() - refreshStart}ms`, |
| 744 | ) |
| 745 | return result |
| 746 | }) |
| 747 | .catch(error => { |
| 748 | logForDebugging( |
| 749 | `[FileIndex] Cache refresh failed: ${errorMessage(error)}`, |
| 750 | ) |
| 751 | logError(error) |
| 752 | if (generation === cacheGeneration) { |
| 753 | fileListRefreshPromise = null // Allow retry on next call |
| 754 | } |
| 755 | return getFileIndex() |
| 756 | }) |
| 757 | } |
| 758 | |
| 759 | /** |
| 760 | * Gets the top-level files and directories in the current working directory |
no test coverage detected