* 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.
227 lines
8.1 KiB
TypeScript
227 lines
8.1 KiB
TypeScript
import type {
|
|
DirectoryListResult,
|
|
FileSearchQuery,
|
|
FileSearchResult,
|
|
FilesAPI,
|
|
} from '@openchamber/ui/lib/api/types';
|
|
|
|
const normalizePath = (path: string): string => path.replace(/\\/g, '/');
|
|
|
|
type WebDirectoryEntry = {
|
|
name?: string;
|
|
path?: string;
|
|
isDirectory?: boolean;
|
|
isFile?: boolean;
|
|
isSymbolicLink?: boolean;
|
|
};
|
|
|
|
type WebDirectoryListResponse = {
|
|
directory?: string;
|
|
path?: string;
|
|
entries?: WebDirectoryEntry[];
|
|
};
|
|
|
|
const toDirectoryListResult = (fallbackDirectory: string, payload: WebDirectoryListResponse): DirectoryListResult => {
|
|
const directory = normalizePath(payload?.directory || payload?.path || fallbackDirectory);
|
|
const entries = Array.isArray(payload?.entries) ? payload.entries : [];
|
|
|
|
return {
|
|
directory,
|
|
entries: entries
|
|
.filter((entry): entry is Required<Pick<WebDirectoryEntry, 'name' | 'path'>> & { isDirectory?: boolean } =>
|
|
Boolean(entry && typeof entry.name === 'string' && typeof entry.path === 'string')
|
|
)
|
|
.map((entry) => ({
|
|
name: entry.name,
|
|
path: normalizePath(entry.path),
|
|
isDirectory: Boolean(entry.isDirectory),
|
|
})),
|
|
};
|
|
};
|
|
|
|
export const createWebFilesAPI = (): FilesAPI => ({
|
|
async listDirectory(path: string): Promise<DirectoryListResult> {
|
|
const target = normalizePath(path);
|
|
const params = new URLSearchParams();
|
|
if (target) {
|
|
params.set('path', target);
|
|
}
|
|
|
|
const response = await fetch(`/api/fs/list${params.toString() ? `?${params.toString()}` : ''}`);
|
|
|
|
if (!response.ok) {
|
|
const error = await response.json().catch(() => ({ error: response.statusText }));
|
|
throw new Error((error as { error?: string }).error || 'Failed to list directory');
|
|
}
|
|
|
|
const result = (await response.json()) as WebDirectoryListResponse;
|
|
return toDirectoryListResult(target, result);
|
|
},
|
|
|
|
async search(payload: FileSearchQuery): Promise<FileSearchResult[]> {
|
|
const params = new URLSearchParams();
|
|
|
|
const directory = normalizePath(payload.directory);
|
|
if (directory) {
|
|
params.set('directory', directory);
|
|
}
|
|
|
|
params.set('query', payload.query);
|
|
params.set('dirs', 'false');
|
|
params.set('type', 'file');
|
|
|
|
if (typeof payload.maxResults === 'number' && Number.isFinite(payload.maxResults)) {
|
|
params.set('limit', String(payload.maxResults));
|
|
}
|
|
|
|
const response = await fetch(`/api/find/file?${params.toString()}`);
|
|
|
|
if (!response.ok) {
|
|
const error = await response.json().catch(() => ({ error: response.statusText }));
|
|
throw new Error((error as { error?: string }).error || 'Failed to search files');
|
|
}
|
|
|
|
const result = (await response.json()) as string[];
|
|
const files = Array.isArray(result) ? result : [];
|
|
|
|
return files.map((relativePath) => ({
|
|
path: normalizePath(`${directory}/${relativePath}`),
|
|
preview: [normalizePath(relativePath)],
|
|
}));
|
|
},
|
|
|
|
async createDirectory(path: string): Promise<{ success: boolean; path: string }> {
|
|
const target = normalizePath(path);
|
|
const response = await fetch('/api/fs/mkdir', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ path: target }),
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const error = await response.json().catch(() => ({ error: response.statusText }));
|
|
throw new Error((error as { error?: string }).error || 'Failed to create directory');
|
|
}
|
|
|
|
const result = await response.json();
|
|
return {
|
|
success: Boolean(result?.success),
|
|
path: typeof result?.path === 'string' ? normalizePath(result.path) : target,
|
|
};
|
|
},
|
|
|
|
async statFile(path: string): Promise<{ path: string; isFile: boolean; size: number; mtimeMs?: number }> {
|
|
const target = normalizePath(path);
|
|
const response = await fetch(`/api/fs/stat?path=${encodeURIComponent(target)}`);
|
|
|
|
if (!response.ok) {
|
|
const error = await response.json().catch(() => ({ error: response.statusText }));
|
|
throw new Error((error as { error?: string }).error || 'Failed to stat file');
|
|
}
|
|
|
|
const result = await response.json().catch(() => ({}));
|
|
return {
|
|
path: typeof (result as { path?: string }).path === 'string' ? normalizePath((result as { path: string }).path) : target,
|
|
isFile: Boolean((result as { isFile?: boolean }).isFile),
|
|
size: typeof (result as { size?: number }).size === 'number' ? (result as { size: number }).size : 0,
|
|
mtimeMs: typeof (result as { mtimeMs?: number }).mtimeMs === 'number' ? (result as { mtimeMs: number }).mtimeMs : undefined,
|
|
};
|
|
},
|
|
|
|
async readFile(path: string): Promise<{ content: string; path: string }> {
|
|
const target = normalizePath(path);
|
|
const response = await fetch(`/api/fs/read?path=${encodeURIComponent(target)}`);
|
|
|
|
if (!response.ok) {
|
|
const error = await response.json().catch(() => ({ error: response.statusText }));
|
|
throw new Error((error as { error?: string }).error || 'Failed to read file');
|
|
}
|
|
|
|
const content = await response.text();
|
|
return { content, path: target };
|
|
},
|
|
|
|
async writeFile(path: string, content: string): Promise<{ success: boolean; path: string }> {
|
|
const target = normalizePath(path);
|
|
const response = await fetch('/api/fs/write', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ path: target, content }),
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const error = await response.json().catch(() => ({ error: response.statusText }));
|
|
throw new Error((error as { error?: string }).error || 'Failed to write file');
|
|
}
|
|
|
|
const result = await response.json().catch(() => ({}));
|
|
return {
|
|
success: Boolean((result as { success?: boolean }).success),
|
|
path: typeof (result as { path?: string }).path === 'string' ? normalizePath((result as { path: string }).path) : target,
|
|
};
|
|
},
|
|
|
|
async delete(path: string): Promise<{ success: boolean }> {
|
|
const target = normalizePath(path);
|
|
const response = await fetch('/api/fs/delete', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ path: target }),
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const error = await response.json().catch(() => ({ error: response.statusText }));
|
|
throw new Error((error as { error?: string }).error || 'Failed to delete file');
|
|
}
|
|
|
|
const result = await response.json().catch(() => ({}));
|
|
return { success: Boolean((result as { success?: boolean }).success) };
|
|
},
|
|
|
|
async rename(oldPath: string, newPath: string): Promise<{ success: boolean; path: string }> {
|
|
const response = await fetch('/api/fs/rename', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ oldPath, newPath }),
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const error = await response.json().catch(() => ({ error: response.statusText }));
|
|
throw new Error((error as { error?: string }).error || 'Failed to rename file');
|
|
}
|
|
|
|
const result = await response.json().catch(() => ({}));
|
|
return {
|
|
success: Boolean((result as { success?: boolean }).success),
|
|
path: typeof (result as { path?: string }).path === 'string' ? normalizePath((result as { path: string }).path) : newPath,
|
|
};
|
|
},
|
|
|
|
async revealPath(targetPath: string): Promise<{ success: boolean }> {
|
|
const response = await fetch('/api/fs/reveal', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ path: normalizePath(targetPath) }),
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const error = await response.json().catch(() => ({ error: response.statusText }));
|
|
throw new Error((error as { error?: string }).error || 'Failed to reveal path');
|
|
}
|
|
|
|
const result = await response.json().catch(() => ({}));
|
|
return { success: Boolean((result as { success?: boolean }).success) };
|
|
},
|
|
|
|
async downloadFile(path: string): Promise<void> {
|
|
const target = normalizePath(path);
|
|
const url = `/api/fs/raw?path=${encodeURIComponent(target)}&download=true`;
|
|
const a = document.createElement('a');
|
|
a.href = url;
|
|
a.download = target.split('/').pop() || 'file';
|
|
document.body.appendChild(a);
|
|
a.click();
|
|
document.body.removeChild(a);
|
|
},
|
|
});
|