feat: add Files tab for browsing workspace files (#154)
* feat: add Files tab for browsing workspace files - Add Files tab between Diff and Terminal in header - Implement hierarchical file tree with expand/collapse - Add fuzzy search with debouncing and relevance ranking - Support gitignore filtering via `git check-ignore` (web + desktop) - Add syntax highlighting for 150+ file types - Add image preview (SVG, PNG, JPG, etc.) - Add line numbers, wrap toggle, and copy button - Desktop: split-pane layout matching DiffView - Mobile: drill-in navigation with full-width sidebar - Update help dialog with Cmd+3 shortcut - Increase header breakpoint to 940px for new tab * feat: enhance context and session stores to track agent/model/variant choices for historical sessions * feat: implement line selection and commenting functionality in FilesView
This commit is contained in:
committed by
GitHub
parent
ecf81c901d
commit
1be5dfda05
@@ -4021,6 +4021,54 @@ async function main(options = {}) {
|
||||
}
|
||||
});
|
||||
|
||||
// Read file as raw bytes (images, etc.)
|
||||
app.get('/api/fs/raw', async (req, res) => {
|
||||
const filePath = typeof req.query.path === 'string' ? req.query.path.trim() : '';
|
||||
if (!filePath) {
|
||||
return res.status(400).json({ error: 'Path is required' });
|
||||
}
|
||||
|
||||
try {
|
||||
const resolvedPath = path.resolve(normalizeDirectoryPath(filePath));
|
||||
if (resolvedPath.includes('..')) {
|
||||
return res.status(400).json({ error: 'Invalid path: path traversal not allowed' });
|
||||
}
|
||||
|
||||
const stats = await fsPromises.stat(resolvedPath);
|
||||
if (!stats.isFile()) {
|
||||
return res.status(400).json({ error: 'Specified path is not a file' });
|
||||
}
|
||||
|
||||
const ext = path.extname(resolvedPath).toLowerCase();
|
||||
const mimeMap = {
|
||||
'.png': 'image/png',
|
||||
'.jpg': 'image/jpeg',
|
||||
'.jpeg': 'image/jpeg',
|
||||
'.gif': 'image/gif',
|
||||
'.svg': 'image/svg+xml',
|
||||
'.webp': 'image/webp',
|
||||
'.ico': 'image/x-icon',
|
||||
'.bmp': 'image/bmp',
|
||||
'.avif': 'image/avif',
|
||||
};
|
||||
const mimeType = mimeMap[ext] || 'application/octet-stream';
|
||||
|
||||
const content = await fsPromises.readFile(resolvedPath);
|
||||
res.setHeader('Cache-Control', 'no-store');
|
||||
res.type(mimeType).send(content);
|
||||
} catch (error) {
|
||||
const err = error;
|
||||
if (err && typeof err === 'object' && err.code === 'ENOENT') {
|
||||
return res.status(404).json({ error: 'File not found' });
|
||||
}
|
||||
if (err && typeof err === 'object' && err.code === 'EACCES') {
|
||||
return res.status(403).json({ error: 'Access to file denied' });
|
||||
}
|
||||
console.error('Failed to read raw file:', error);
|
||||
res.status(500).json({ error: (error && error.message) || 'Failed to read file' });
|
||||
}
|
||||
});
|
||||
|
||||
// Write file contents
|
||||
app.post('/api/fs/write', async (req, res) => {
|
||||
const { path: filePath, content } = req.body || {};
|
||||
@@ -4327,6 +4375,7 @@ async function main(options = {}) {
|
||||
const rawPath = typeof req.query.path === 'string' && req.query.path.trim().length > 0
|
||||
? req.query.path.trim()
|
||||
: os.homedir();
|
||||
const respectGitignore = req.query.respectGitignore === 'true';
|
||||
|
||||
try {
|
||||
const resolvedPath = path.resolve(normalizeDirectoryPath(rawPath));
|
||||
@@ -4337,16 +4386,57 @@ async function main(options = {}) {
|
||||
}
|
||||
|
||||
const dirents = await fsPromises.readdir(resolvedPath, { withFileTypes: true });
|
||||
|
||||
// Get gitignored paths if requested
|
||||
let ignoredPaths = new Set();
|
||||
if (respectGitignore) {
|
||||
try {
|
||||
// Get all entry paths to check (relative to resolvedPath for git check-ignore)
|
||||
const pathsToCheck = dirents.map((d) => d.name);
|
||||
|
||||
if (pathsToCheck.length > 0) {
|
||||
try {
|
||||
// Use git check-ignore with paths as arguments
|
||||
// Pass paths directly as arguments (works for reasonable directory sizes)
|
||||
const result = await new Promise((resolve) => {
|
||||
const child = spawn('git', ['check-ignore', '--', ...pathsToCheck], {
|
||||
cwd: resolvedPath,
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
});
|
||||
|
||||
let stdout = '';
|
||||
child.stdout.on('data', (data) => { stdout += data.toString(); });
|
||||
child.on('close', () => resolve(stdout));
|
||||
child.on('error', () => resolve(''));
|
||||
});
|
||||
|
||||
result.split('\n').filter(Boolean).forEach((name) => {
|
||||
const fullPath = path.join(resolvedPath, name.trim());
|
||||
ignoredPaths.add(fullPath);
|
||||
});
|
||||
} catch {
|
||||
// git check-ignore fails if not a git repo, continue without filtering
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// If git is not available, continue without gitignore filtering
|
||||
}
|
||||
}
|
||||
|
||||
const entries = await Promise.all(
|
||||
dirents.map(async (dirent) => {
|
||||
const entryPath = path.join(resolvedPath, dirent.name);
|
||||
|
||||
// Skip gitignored entries
|
||||
if (respectGitignore && ignoredPaths.has(entryPath)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let isDirectory = dirent.isDirectory();
|
||||
const isSymbolicLink = dirent.isSymbolicLink();
|
||||
|
||||
if (!isDirectory && isSymbolicLink) {
|
||||
|
||||
try {
|
||||
|
||||
try {
|
||||
const linkStats = await fsPromises.stat(entryPath);
|
||||
isDirectory = linkStats.isDirectory();
|
||||
} catch {
|
||||
@@ -4366,7 +4456,7 @@ async function main(options = {}) {
|
||||
|
||||
res.json({
|
||||
path: resolvedPath,
|
||||
entries
|
||||
entries: entries.filter(Boolean)
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Failed to list directory:', error);
|
||||
|
||||
+100
-29
@@ -1,50 +1,108 @@
|
||||
import type { DirectoryListResult, FileSearchQuery, FileSearchResult, FilesAPI } from '@openchamber/ui/lib/api/types';
|
||||
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[];
|
||||
};
|
||||
|
||||
type WebFileSearchResponse = {
|
||||
root?: string;
|
||||
directory?: string;
|
||||
count?: number;
|
||||
files?: Array<{
|
||||
name?: string;
|
||||
path?: string;
|
||||
relativePath?: string;
|
||||
extension?: string;
|
||||
}>;
|
||||
};
|
||||
|
||||
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 response = await fetch('/api/fs/list', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ path: target }),
|
||||
});
|
||||
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.error || 'Failed to list directory');
|
||||
throw new Error((error as { error?: string }).error || 'Failed to list directory');
|
||||
}
|
||||
|
||||
return response.json();
|
||||
const result = (await response.json()) as WebDirectoryListResponse;
|
||||
return toDirectoryListResult(target, result);
|
||||
},
|
||||
|
||||
async search(payload: FileSearchQuery): Promise<FileSearchResult[]> {
|
||||
const response = await fetch('/api/fs/search', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
directory: normalizePath(payload.directory),
|
||||
query: payload.query,
|
||||
maxResults: payload.maxResults,
|
||||
}),
|
||||
});
|
||||
const params = new URLSearchParams();
|
||||
|
||||
const directory = normalizePath(payload.directory);
|
||||
if (directory) {
|
||||
params.set('directory', directory);
|
||||
}
|
||||
|
||||
params.set('q', payload.query);
|
||||
|
||||
if (typeof payload.maxResults === 'number' && Number.isFinite(payload.maxResults)) {
|
||||
params.set('limit', String(payload.maxResults));
|
||||
}
|
||||
|
||||
const response = await fetch(`/api/fs/search?${params.toString()}`);
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: response.statusText }));
|
||||
throw new Error(error.error || 'Failed to search files');
|
||||
throw new Error((error as { error?: string }).error || 'Failed to search files');
|
||||
}
|
||||
|
||||
const results = (await response.json()) as unknown;
|
||||
if (!Array.isArray(results)) {
|
||||
return [];
|
||||
}
|
||||
return results
|
||||
.filter((item): item is FileSearchResult => !!item && typeof item === 'object' && typeof (item as { path?: string }).path === 'string')
|
||||
.map((item) => ({
|
||||
path: normalizePath((item as FileSearchResult).path),
|
||||
score: (item as FileSearchResult).score,
|
||||
preview: (item as FileSearchResult).preview,
|
||||
const result = (await response.json()) as WebFileSearchResponse;
|
||||
const files = Array.isArray(result?.files) ? result.files : [];
|
||||
|
||||
return files
|
||||
.filter((file): file is { path: string; relativePath?: string } =>
|
||||
Boolean(file && typeof file.path === 'string')
|
||||
)
|
||||
.map((file) => ({
|
||||
path: normalizePath(file.path),
|
||||
preview: typeof file.relativePath === 'string' && file.relativePath.length > 0
|
||||
? [normalizePath(file.relativePath)]
|
||||
: undefined,
|
||||
}));
|
||||
},
|
||||
|
||||
@@ -58,7 +116,7 @@ export const createWebFilesAPI = (): FilesAPI => ({
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: response.statusText }));
|
||||
throw new Error(error.error || 'Failed to create directory');
|
||||
throw new Error((error as { error?: string }).error || 'Failed to create directory');
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
@@ -67,4 +125,17 @@ export const createWebFilesAPI = (): FilesAPI => ({
|
||||
path: typeof result?.path === 'string' ? normalizePath(result.path) : target,
|
||||
};
|
||||
},
|
||||
|
||||
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 };
|
||||
},
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user