fix(files): refresh open file content after external changes (#967)

* fix(files): refresh open file content after external edits

Previously, opening a file in the Files view and then editing it externally
(e.g. via CLI or another editor) would show stale content. Even closing and
reopening the file returned cached content — a full page reload was required.

Root causes:
1. The in-memory readFile cache used path-only hits, with no metadata
   validation. External edits were invisible until the cache was evicted.
2. No polling mechanism existed to detect external changes to the open file.

Fix:
- Add mtimeMs to statFile across all runtimes (web, VS Code, desktop).
- Cache layer (RuntimeAPIProvider): validate cache hits against current stat
  metadata (mtimeMs + size). On miss, use stat→read→stat to avoid TOCTOU.
- UI layer (FilesView): poll the open file every 2s; on detected change, set
  loadedFilePath=null to trigger the existing load effect once (no double
  reload). Skip polling when tab is hidden or editor has unsaved changes.
- After save, refresh the stat ref so the next poll doesn't see a spurious
  change from the save itself.

Addresses review feedback from PR #827 (double reload + TOCTOU).

* fix(files): address P2 review findings

- readFreshFile retry now uses stat→read→stat to maintain TOCTOU
  protection during the retry path (not just the initial read).
- Replace isDirty in polling effect deps with isDirtyRef to avoid
  unnecessary interval teardown/restart on every edit/save cycle.
This commit is contained in:
jwcrystal
2026-04-21 18:04:24 +03:00
committed by GitHub
parent 5f3b57b5ed
commit 2f5912c287
7 changed files with 179 additions and 21 deletions
+95 -2
View File
@@ -92,6 +92,12 @@ type FileNode = {
relativePath?: string;
};
type FileStatSnapshot = {
path: string;
size: number;
mtimeMs?: number;
};
type SelectedLineRange = {
start: number;
end: number;
@@ -623,6 +629,7 @@ export const FilesView: React.FC<FilesViewProps> = ({ mode = 'full' }) => {
const [draftContent, setDraftContent] = React.useState('');
const [isSaving, setIsSaving] = React.useState(false);
const autoSaveTimerRef = React.useRef<ReturnType<typeof setTimeout> | null>(null);
const lastLoadedFileStatRef = React.useRef<FileStatSnapshot | null>(null);
const [autoSaveStatus, setAutoSaveStatus] = React.useState<'idle' | 'saved'>('idle');
const [confirmDiscardOpen, setConfirmDiscardOpen] = React.useState(false);
@@ -1213,6 +1220,18 @@ export const FilesView: React.FC<FilesViewProps> = ({ mode = 'full' }) => {
return response.text();
}, [files]);
const readFileStat = React.useCallback(async (path: string): Promise<FileStatSnapshot | null> => {
if (files.statFile) {
const result = await files.statFile(path);
return {
path: result.path,
size: result.size,
mtimeMs: result.mtimeMs,
};
}
return null;
}, [files]);
const displayedContent = React.useMemo(() => {
return fileContent.length > MAX_VIEW_CHARS
? `${fileContent.slice(0, MAX_VIEW_CHARS)}\n\n… truncated …`
@@ -1240,6 +1259,14 @@ export const FilesView: React.FC<FilesViewProps> = ({ mode = 'full' }) => {
return;
}
setFileContent(draftContent);
// Refresh stat after write so polling doesn't see a stale metadata change.
void readFileStat(selectedFile.path)
.then((stat) => {
if (stat) {
lastLoadedFileStatRef.current = stat;
}
})
.catch(() => {});
})
.catch((error) => {
toast.error(error instanceof Error ? error.message : 'Save failed');
@@ -1247,7 +1274,7 @@ export const FilesView: React.FC<FilesViewProps> = ({ mode = 'full' }) => {
.finally(() => {
setIsSaving(false);
});
}, [draftContent, files, isDirty, selectedFile]);
}, [draftContent, files, isDirty, readFileStat, selectedFile]);
React.useEffect(() => {
if (!isDirty) {
@@ -1371,6 +1398,13 @@ export const FilesView: React.FC<FilesViewProps> = ({ mode = 'full' }) => {
? `${content.slice(0, MAX_VIEW_CHARS)}\n\n… truncated …`
: content);
setLoadedFilePath(node.path);
void readFileStat(node.path)
.then((stat) => {
if (stat) {
lastLoadedFileStatRef.current = stat;
}
})
.catch(() => {});
})
.catch((error) => {
if (isDirectoryReadError(error)) {
@@ -1381,6 +1415,7 @@ export const FilesView: React.FC<FilesViewProps> = ({ mode = 'full' }) => {
setFileContent('');
setDraftContent('');
setLoadedFilePath(null);
lastLoadedFileStatRef.current = null;
if (searchQuery.trim().length > 0) {
setSearchQuery('');
}
@@ -1404,11 +1439,12 @@ export const FilesView: React.FC<FilesViewProps> = ({ mode = 'full' }) => {
setFileContent('');
setDraftContent('');
setFileError(error instanceof Error ? error.message : 'Failed to read file');
lastLoadedFileStatRef.current = null;
})
.finally(() => {
setFileLoading(false);
});
}, [expandPaths, isMobile, loadDirectory, readFile, root, runtime.isDesktop, searchQuery, setSelectedPath]);
}, [expandPaths, isMobile, loadDirectory, readFile, readFileStat, root, runtime.isDesktop, searchQuery, setSelectedPath]);
const ensurePathVisible = React.useCallback(async (targetPath: string, includeTarget: boolean) => {
if (!root) {
@@ -1483,6 +1519,63 @@ export const FilesView: React.FC<FilesViewProps> = ({ mode = 'full' }) => {
void loadSelectedFile(selectedFile);
}, [loadSelectedFile, loadedFilePath, selectedFile]);
// Sync isDirty to a ref so the polling interval can read the latest value
// without isDirty in its dependency array (avoids interval restart on every edit/save).
const isDirtyRef = React.useRef(isDirty);
isDirtyRef.current = isDirty;
// Poll open file for external changes.
// When a change is detected, reset loadedFilePath so the effect above
// triggers a single reload — no double-load.
React.useEffect(() => {
if (!selectedFile?.path || loadedFilePath !== selectedFile.path) {
return;
}
let cancelled = false;
const interval = window.setInterval(() => {
if (document.hidden) {
return;
}
void readFileStat(selectedFile.path)
.then((latestStat) => {
if (cancelled || !latestStat) {
return;
}
const previousStat = lastLoadedFileStatRef.current;
if (!previousStat || previousStat.path !== selectedFile.path) {
lastLoadedFileStatRef.current = latestStat;
return;
}
const changedByMtime = latestStat.mtimeMs !== undefined
&& previousStat.mtimeMs !== undefined
&& latestStat.mtimeMs !== previousStat.mtimeMs;
const changedBySize = latestStat.size !== previousStat.size;
if (!changedByMtime && !changedBySize) {
return;
}
if (isDirtyRef.current) {
return;
}
lastLoadedFileStatRef.current = latestStat;
// Reset loadedFilePath so the effect above triggers a single reload.
setLoadedFilePath(null);
})
.catch(() => {});
}, 2000);
return () => {
cancelled = true;
window.clearInterval(interval);
};
}, [loadedFilePath, readFileStat, selectedFile?.path]);
const discardAndContinue = React.useCallback(() => {
const nextFile = pendingSelectFileRef.current;
const nextTab = pendingTabRef.current;