Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

refactor: split File Manager state and views with regression guards

Juan Denisb534ee2bafff
diff --git a/frontend/scripts/check-file-manager-boundaries.mjs b/frontend/scripts/check-file-manager-boundaries.mjs
new file mode 100644
index 00000000..14d69393
--- /dev/null
+++ b/frontend/scripts/check-file-manager-boundaries.mjs
@@ -0,0 +1,62 @@
+import { readFileSync, readdirSync } from 'node:fs';
+import { dirname, join, relative, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { parse } from 'espree';
+
+const src = resolve(dirname(fileURLToPath(import.meta.url)), '../src');
+const feature = 'components/file-manager/';
+const apiOwners = new Set(['pages/FileManager.jsx', `${feature}hooks/useFileTargets.js`,
+ `${feature}hooks/useFileVolumes.js`]);
+
+export function inspectFileManagerSource(path, source) {
+ const errors = [];
+ const ast = parse(source, { ecmaVersion: 'latest', sourceType: 'module', ecmaFeatures: { jsx: true } });
+ const page = path === 'pages/FileManager.jsx';
+ const hook = path.startsWith(`${feature}hooks/`);
+ const view = path.startsWith(feature) && path.endsWith('.jsx');
+ const imports = ast.body.filter(node => node.type === 'ImportDeclaration');
+ for (const node of imports) {
+ const target = node.source.value;
+ if (/services\//.test(target) && !apiOwners.has(path)) {
+ errors.push(`${path}: transport imports belong to the adapter composition or metadata hooks`);
+ }
+ if (path.startsWith(feature) && /(?:^|\/)pages\//.test(target)) {
+ errors.push(`${path}: a feature cannot depend on route pages`);
+ }
+ if (view && /(?:^|\/)hooks\/use(?:File|Directory)/.test(target)) {
+ errors.push(`${path}: views receive feature state through props`);
+ }
+ }
+ function visit(node) {
+ if (!node || typeof node !== 'object') return;
+ if (page && node.type === 'AwaitExpression') errors.push(`${path}: asynchronous work belongs in hooks`);
+ if ((page || view) && node.type === 'CallExpression' && node.callee?.object?.name === 'api') {
+ errors.push(`${path}: views must not call API methods`);
+ }
+ if (view && node.type === 'CallExpression' && node.callee?.name === 'fetch') {
+ errors.push(`${path}: views must not fetch`);
+ }
+ for (const value of Object.values(node)) {
+ if (Array.isArray(value)) value.forEach(visit);
+ else if (value && typeof value === 'object') visit(value);
+ }
+ }
+ visit(ast);
+ // Backstops for accidental recombination, in addition to dependency rules.
+ const lines = source.split('\n').filter(line => line.trim()).length;
+ if (page && lines > 650) errors.push(`${path}: keep the route focused on composition (650 nonblank lines)`);
+ if (hook && lines > 300) errors.push(`${path}: split unrelated hook responsibilities (300 nonblank lines)`);
+ return errors;
+}
+
+export function checkFileManagerBoundaries() {
+ const walk = dir => readdirSync(dir, { withFileTypes: true }).flatMap(entry => {
+ if (entry.name === '__tests__') return [];
+ const path = join(dir, entry.name);
+ return entry.isDirectory() ? walk(path) : /\.[jt]sx?$/.test(path) ? [path] : [];
+ });
+ const files = [join(src, 'pages/FileManager.jsx'), ...walk(join(src, feature))];
+ const errors = files.flatMap(path => inspectFileManagerSource(
+ relative(src, path).replaceAll('\\', '/'), readFileSync(path, 'utf8')));
+ if (errors.length) throw new Error(errors.join('\n'));
+}
diff --git a/frontend/scripts/check-frontend-boundaries.mjs b/frontend/scripts/check-frontend-boundaries.mjs
index 28f7785c..2a5c325c 100644
--- a/frontend/scripts/check-frontend-boundaries.mjs
+++ b/frontend/scripts/check-frontend-boundaries.mjs
@@ -9,6 +9,9 @@
import { existsSync, readFileSync, readdirSync } from 'node:fs';
import { dirname, extname, join, relative, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { checkFileManagerBoundaries } from './check-file-manager-boundaries.mjs';
+
+checkFileManagerBoundaries();
const here = dirname(fileURLToPath(import.meta.url));
const root = resolve(here, '..');
diff --git a/frontend/scripts/file-manager-browser.mjs b/frontend/scripts/file-manager-browser.mjs
index f1039b94..330de817 100644
--- a/frontend/scripts/file-manager-browser.mjs
+++ b/frontend/scripts/file-manager-browser.mjs
@@ -15,6 +15,7 @@ import React from 'react';
import {createRoot} from 'react-dom/client';
import {MemoryRouter} from 'react-router-dom';
import FileManager from '/src/pages/FileManager.jsx';
+import {ConfirmProvider} from '/src/contexts/ConfirmContext.jsx';
window.pending=[];
const listing=(p)=>({path:p,parent:p==='/'?null:p.replace(/\\/[^/]+$/,'')||'/',entries:p==='/home'?[{name:'projects',path:'/home/projects',is_dir:true,type:'directory',size:0,permissions:'drwxr-xr-x',permissions_octal:'750'}]:[{name:'inside-'+p.split('/').pop()+'.txt',path:p+'/x.txt',is_dir:false,type:'file',size:1}]});
window.release=(p)=>{const i=window.pending.findIndex(x=>x.path===p);const x=window.pending.splice(i,1)[0];x.resolve(listing(p));};
@@ -26,7 +27,7 @@ window.testApi={
renameFile:(p,n)=>{(window.ops=window.ops||[]).push(['rename',p,n]);return Promise.resolve({});},
changeFilePermissions:(p,m)=>{(window.ops=window.ops||[]).push(['chmod',p,m]);return Promise.resolve({});},
};
-createRoot(document.getElementById('root')).render(<MemoryRouter initialEntries={['/files']}><FileManager/></MemoryRouter>);
+createRoot(document.getElementById('root')).render(<MemoryRouter initialEntries={['/files']}><ConfirmProvider><FileManager/></ConfirmProvider></MemoryRouter>);
`;
const server = await createServer({
root, configFile: false, logLevel: 'error', resolve: { alias: { '@': path.join(root, 'src') } },
@@ -150,6 +151,155 @@ try {
assert.equal(await sw.getByText('projects', { exact: true }).count(), 0, 'the panel host listing is still shown');
assert.deepEqual(swErrors, []);
console.log('PASS switching to a remote agent reloads the listing from that agent');
+
+ // A local request still in flight must not replace the agent's listing.
+ const late = await browser.newPage();
+ await late.goto(`http://127.0.0.1:${server.httpServer.address().port}/fm-check`);
+ await late.getByText('projects', { exact: true }).first().waitFor();
+ await late.getByText('projects', { exact: true }).first().dblclick();
+ await late.waitForFunction(() => window.pending.some(x => x.path === '/home/projects'));
+ await late.getByRole('button', { name: 'pick-agent' }).click();
+ await late.getByText('on-agent.txt').first().waitFor();
+ await late.evaluate(() => window.release('/home/projects'));
+ await late.waitForTimeout(100);
+ assert.equal(await late.getByText('inside-projects.txt').count(), 0);
+ assert.equal(await late.getByTitle('Back', { exact: true }).isDisabled(), true,
+ 'navigation history must not cross storage targets');
+ console.log('PASS late local responses and history cannot cross a target switch');
+
+ // Search responses and canceled searches must not overwrite navigation.
+ const search = await browser.newPage();
+ await search.goto(`http://127.0.0.1:${server.httpServer.address().port}/fm-check`);
+ await search.getByText('projects', { exact: true }).first().waitFor();
+ await search.evaluate(() => {
+ window.testApi.searchFiles = () => new Promise(resolve => { window.finishSearch = resolve; });
+ });
+ await search.getByPlaceholder('Search files…').fill('old');
+ await search.getByPlaceholder('Search files…').press('Enter');
+ await search.waitForFunction(() => Boolean(window.finishSearch));
+ await search.getByTitle('Home', { exact: true }).click();
+ // Home is already the current folder, so explicitly refresh it.
+ await search.locator('.file-manager-toolbar').getByTitle('Refresh', { exact: true }).click();
+ await search.getByText('projects', { exact: true }).first().waitFor();
+ await search.evaluate(() => window.finishSearch({ results: [{ name: 'stale-result.txt', path: '/old', is_dir: false }] }));
+ await search.waitForTimeout(100);
+ assert.equal(await search.getByText('stale-result.txt').count(), 0);
+ console.log('PASS a late search cannot overwrite a refreshed directory');
+ await search.getByPlaceholder('Search files…').fill('cancel me');
+ await search.getByPlaceholder('Search files…').press('Enter');
+ await search.locator('.search-field-clear').click();
+ await search.evaluate(() => window.finishSearch({ results: [{ name: 'canceled-result.txt', path: '/old', is_dir: false }] }));
+ await search.waitForTimeout(100);
+ assert.equal(await search.getByText('canceled-result.txt').count(), 0);
+ console.log('PASS clearing search invalidates its pending response');
+
+ // Read A, then B; A arriving last must not become B's editable contents.
+ const editor = await browser.newPage();
+ const editorErrors = [];
+ editor.on('pageerror', error => editorErrors.push(error.message));
+ await editor.goto(`http://127.0.0.1:${server.httpServer.address().port}/fm-check`);
+ await editor.getByText('projects', { exact: true }).first().waitFor();
+ await editor.evaluate(() => {
+ window.reads = {};
+ window.testApi.browseFiles = p => Promise.resolve({ path: p, parent: '/', entries:
+ ['a.txt', 'b.txt'].map(name => ({ name, path: p + '/' + name, is_dir: false, is_editable: true, size: 1 })) });
+ window.testApi.readFile = p => new Promise(resolve => { window.reads[p] = resolve; });
+ window.testApi.writeFile = () => Promise.reject(new Error('disk full'));
+ });
+ await editor.locator('.file-manager-toolbar').getByTitle('Refresh', { exact: true }).click();
+ await editor.getByText('a.txt', { exact: true }).first().dblclick();
+ await editor.waitForFunction(() => Boolean(window.reads['/home/a.txt']));
+ await editor.getByText('b.txt', { exact: true }).first().dblclick();
+ await editor.waitForFunction(() => Boolean(window.reads['/home/b.txt']));
+ await editor.evaluate(() => window.reads['/home/b.txt']({ content: 'new-content' }));
+ await editor.getByLabel('File contents').getByText('new-content', { exact: true }).waitFor();
+ await editor.evaluate(() => window.reads['/home/a.txt']({ content: 'old-content' }));
+ await editor.waitForTimeout(100);
+ assert.equal(await editor.getByText('old-content', { exact: true }).count(), 0);
+ const preview = editor.getByRole('complementary', { name: 'File preview' });
+ await preview.getByRole('button', { name: 'Edit', exact: true }).click();
+ await preview.locator('textarea').fill('unsaved draft');
+ await preview.getByRole('button', { name: 'Save', exact: true }).click();
+ await editor.waitForFunction(() => (window.toasts || []).length > 0);
+ assert.equal(await preview.locator('textarea').inputValue(), 'unsaved draft');
+ await editor.getByRole('button', { name: 'pick-agent' }).click();
+ await editor.getByText('on-agent.txt').first().waitFor();
+ assert.equal(await preview.count(), 0, 'the previous target preview stayed open');
+ assert.deepEqual(editorErrors, []);
+ console.log('PASS preview read races, failed-save draft retention and target reset');
+
+ // Shared confirmation must preserve cancel semantics and partial failures.
+ const deletion = await browser.newPage();
+ await deletion.goto(`http://127.0.0.1:${server.httpServer.address().port}/fm-check`);
+ await deletion.getByText('projects', { exact: true }).first().waitFor();
+ await deletion.evaluate(() => {
+ window.deleted = [];
+ window.testApi.deleteFile = p => { window.deleted.push(p); return Promise.resolve({}); };
+ });
+ await deletion.getByTitle('Delete', { exact: true }).first().click();
+ await deletion.getByRole('alertdialog').getByRole('button', { name: 'Cancel', exact: true }).click();
+ assert.deepEqual(await deletion.evaluate(() => window.deleted), []);
+ await deletion.getByTitle('Delete', { exact: true }).first().click();
+ await deletion.getByRole('alertdialog').getByRole('button', { name: 'Delete', exact: true }).click();
+ await deletion.waitForFunction(() => window.deleted.length === 1);
+ assert.deepEqual(await deletion.evaluate(() => window.deleted), ['/home/projects']);
+ console.log('PASS shared delete confirmation cancels or executes the intended path');
+
+ // Back/forward still works after moving the toolbar into its own component.
+ const nav = await browser.newPage();
+ await nav.goto(`http://127.0.0.1:${server.httpServer.address().port}/fm-check`);
+ await nav.getByText('projects', { exact: true }).first().waitFor();
+ await nav.getByText('projects', { exact: true }).first().dblclick();
+ await nav.waitForFunction(() => window.pending.some(x => x.path === '/home/projects'));
+ await nav.evaluate(() => window.release('/home/projects'));
+ await nav.getByText('inside-projects.txt').waitFor();
+ await nav.getByTitle('Back', { exact: true }).click();
+ await nav.getByText('projects', { exact: true }).first().waitFor();
+ assert.equal(await nav.getByTitle('Forward', { exact: true }).isDisabled(), false);
+ await nav.getByTitle('Forward', { exact: true }).click();
+ await nav.waitForFunction(() => window.pending.some(x => x.path === '/home/projects'));
+ await nav.evaluate(() => window.release('/home/projects'));
+ await nav.getByText('inside-projects.txt').waitFor();
+ console.log('PASS directory back and forward navigation');
+
+ const transfer = await browser.newPage();
+ await transfer.goto(`http://127.0.0.1:${server.httpServer.address().port}/fm-check`);
+ await transfer.getByText('projects', { exact: true }).first().waitFor();
+ await transfer.evaluate(() => {
+ window.uploadPaths = [];
+ window.testApi.uploadFile = (p, file, progress) => {
+ window.uploadPaths.push([p, file.name]);
+ progress(50);
+ return new Promise(resolve => { window.finishUpload = resolve; });
+ };
+ });
+ await transfer.locator('input[type="file"]').setInputFiles({ name: 'upload.txt', mimeType: 'text/plain', buffer: Buffer.from('test') });
+ await transfer.waitForFunction(() => Boolean(window.finishUpload));
+ await transfer.getByText('projects', { exact: true }).first().dblclick();
+ await transfer.waitForFunction(() => window.pending.some(x => x.path === '/home/projects'));
+ await transfer.evaluate(() => window.release('/home/projects'));
+ await transfer.getByText('inside-projects.txt').waitFor();
+ const callsBeforeUpload = await transfer.evaluate(() => window.calls.length);
+ await transfer.evaluate(() => window.finishUpload({}));
+ await transfer.getByText('Uploads complete', { exact: true }).waitFor();
+ assert.deepEqual(await transfer.evaluate(() => window.uploadPaths), [['/home', 'upload.txt']]);
+ assert.equal(await transfer.evaluate(() => window.calls.length), callsBeforeUpload,
+ 'finishing an upload must not reload or navigate to the previous directory');
+ console.log('PASS uploads retain their destination without disrupting later navigation');
+
+ const images = await browser.newPage();
+ await images.goto(`http://127.0.0.1:${server.httpServer.address().port}/fm-check`);
+ await images.getByText('projects', { exact: true }).first().waitFor();
+ await images.evaluate(() => {
+ window.blobCalls = [];
+ window.testApi.getFileBlob = p => { window.blobCalls.push(p); return Promise.resolve(new Blob(['x'])); };
+ window.testApi.browseRemoteFiles = (_id, p) => Promise.resolve({ path: p, entries: [{ name: 'remote.png', path: p + '/remote.png', is_dir: false }] });
+ });
+ await images.getByRole('button', { name: 'pick-agent' }).click();
+ await images.getByText('remote.png', { exact: true }).first().dblclick();
+ await images.getByText('Image preview unavailable', { exact: true }).waitFor();
+ assert.deepEqual(await images.evaluate(() => window.blobCalls), []);
+ console.log('PASS agent image previews never fetch files from the panel host');
} finally {
await browser?.close();
await server.close();
diff --git a/frontend/src/components/file-manager/FileCard.jsx b/frontend/src/components/file-manager/FileCard.jsx
index e32ab265..3695a30e 100644
--- a/frontend/src/components/file-manager/FileCard.jsx
+++ b/frontend/src/components/file-manager/FileCard.jsx
@@ -13,7 +13,7 @@ function FileCard({
onOpen,
onToggleSelect,
onContext,
- isS3 = false,
+ fileApi,
}) {
const { t } = useTranslation();
const ext = getFileExt(entry);
@@ -51,7 +51,7 @@ function FileCard({
<div className="file-card-thumb">
{showThumb ? (
- <ImageThumb path={entry.path} isS3={isS3} fallback={<FileIcon entry={entry} size={36} />} />
+ <ImageThumb path={entry.path} fileApi={fileApi} fallback={<FileIcon entry={entry} size={36} />} />
) : (
<FileIcon entry={entry} size={36} />
)}
diff --git a/frontend/src/components/file-manager/FileManagerDialogs.jsx b/frontend/src/components/file-manager/FileManagerDialogs.jsx
new file mode 100644
index 00000000..03de1dd0
--- /dev/null
+++ b/frontend/src/components/file-manager/FileManagerDialogs.jsx
@@ -0,0 +1,55 @@
+import { NamePromptModal, PermissionsModal } from './FileDialogs';
+
+import { useTranslation } from 'react-i18next';
+
+export default function FileManagerDialogs({
+ dialog,
+ currentPath,
+ handleCreateFolder,
+ closeDialog,
+ handleRename,
+ handleChangePermissions,
+}) {
+ const { t } = useTranslation();
+ return (
+ <>
+ {dialog?.kind === 'newFolder' && (
+ <NamePromptModal
+ title={t('app.fileManager.createNewFolder', 'Create new folder')}
+ label={t('app.fileManager.folderName', 'Folder name')}
+ placeholder="new-folder"
+ hint={
+ <p className="text-muted">
+ {t('app.fileManager.willBeCreatedIn', 'Will be created in:')}{' '}
+ <code>{currentPath}</code>
+ </p>
+ }
+ submitLabel={t('app.fileManager.createFolder', 'Create folder')}
+ onSubmit={handleCreateFolder}
+ onClose={closeDialog}
+ />
+ )}
+ {dialog?.kind === 'rename' && (
+ <NamePromptModal
+ key={dialog.entry.path}
+ title={t('app.fileManager.rename2', 'Rename {{value}}', {
+ value: dialog.entry.is_dir ? 'Folder' : 'File',
+ })}
+ label={t('app.fileManager.newName', 'New name')}
+ initialValue={dialog.entry.name}
+ submitLabel={t('app.fileManager.rename', 'Rename')}
+ onSubmit={(name) => handleRename(dialog.entry, name)}
+ onClose={closeDialog}
+ />
+ )}
+ {dialog?.kind === 'permissions' && (
+ <PermissionsModal
+ key={dialog.entry.path}
+ entry={dialog.entry}
+ onSubmit={(mode) => handleChangePermissions(dialog.entry, mode)}
+ onClose={closeDialog}
+ />
+ )}
+ </>
+ );
+}
diff --git a/frontend/src/components/file-manager/FileManagerListing.jsx b/frontend/src/components/file-manager/FileManagerListing.jsx
new file mode 100644
index 00000000..b4524d76
--- /dev/null
+++ b/frontend/src/components/file-manager/FileManagerListing.jsx
@@ -0,0 +1,171 @@
+import EmptyState from '@/components/EmptyState';
+import ErrorState from '@/components/ErrorState';
+import { FolderOpen, CloudUpload, Check } from 'lucide-react';
+
+import { Button } from '@/components/ui/button';
+
+import FileCard from './FileCard';
+import FileRow from './FileRow';
+
+import { useTranslation } from 'react-i18next';
+
+export default function FileManagerListing({
+ fileApi,
+ clearSelection,
+ dragActive,
+ currentPath,
+ loading,
+ dirError,
+ searchResults,
+ loadDirectory,
+ sortedFiltered,
+ activeFilter,
+ viewMode,
+ selectedPaths,
+ selectMode,
+ rowOpen,
+ rowToggleSelect,
+ rowContext,
+ isS3,
+ setSelectedPaths,
+ setSelectMode,
+ rowDownload,
+ rowRename,
+ rowPermissions,
+ rowDelete,
+}) {
+ const { t } = useTranslation();
+ return (
+ <>
+ <main className="file-manager-main">
+ <div
+ className="file-list-container"
+ onClick={(e) => {
+ if (e.target === e.currentTarget) clearSelection();
+ }}
+ >
+ {dragActive && (
+ <div className="drag-overlay">
+ <div className="drag-overlay-inner">
+ <CloudUpload size={56} strokeWidth={1.5} />
+ <h3>{t('app.fileManager.dropToUpload', 'Drop to upload')}</h3>
+ <p>
+ {t('app.fileManager.filesWillBeUploadedTo', 'Files will be uploaded to')}{' '}
+ <code>{currentPath}</code>
+ </p>
+ </div>
+ </div>
+ )}
+
+ {loading ? (
+ <EmptyState
+ loading
+ loadingVariant="tree"
+ title={t('app.fileManager.loadingFiles', 'Loading files')}
+ />
+ ) : dirError && !searchResults ? (
+ <ErrorState
+ title={t('app.fileManager.couldntOpenThisFolder', "Couldn't open this folder.")}
+ error={dirError}
+ onRetry={() => loadDirectory(currentPath)}
+ />
+ ) : sortedFiltered.length === 0 ? (
+ <EmptyState
+ icon={FolderOpen}
+ title={
+ searchResults
+ ? t('app.fileManager.noMatches', 'No matches')
+ : activeFilter !== 'all'
+ ? t('app.fileManager.noFiles', 'No {{activeFilter}} files', {
+ activeFilter: activeFilter,
+ })
+ : t('app.fileManager.thisFolderIsEmpty', 'This folder is empty')
+ }
+ description={
+ searchResults
+ ? t(
+ 'app.fileManager.tryADifferentSearchTermOr',
+ 'Try a different search term or browse another folder.',
+ )
+ : activeFilter !== 'all'
+ ? t('app.fileManager.tryADifferentFilter', 'Try a different filter.')
+ : t(
+ 'app.fileManager.dropFilesHereOrUseThe',
+ 'Drop files here, or use the buttons above to create something new.',
+ )
+ }
+ />
+ ) : viewMode === 'grid' ? (
+ <div className="file-grid">
+ {sortedFiltered.map((entry) => (
+ <FileCard
+ key={entry.path}
+ entry={entry}
+ selected={selectedPaths.has(entry.path)}
+ selectMode={selectMode}
+ onOpen={rowOpen}
+ onToggleSelect={rowToggleSelect}
+ onContext={rowContext}
+ isS3={isS3}
+ fileApi={fileApi}
+ />
+ ))}
+ </div>
+ ) : (
+ <div className="file-list">
+ <div className="file-list-header">
+ <span className="col-check">
+ <Button
+ variant="unstyled"
+ type="button"
+ className="checkbox-btn"
+ onClick={() => {
+ if (selectedPaths.size === sortedFiltered.length)
+ clearSelection();
+ else {
+ setSelectedPaths(new Set(sortedFiltered.map((x) => x.path)));
+ setSelectMode(sortedFiltered.length > 0);
+ }
+ }}
+ >
+ <span
+ className={`checkbox ${selectedPaths.size === sortedFiltered.length && sortedFiltered.length > 0 ? 'checked' : ''}`}
+ >
+ {selectedPaths.size === sortedFiltered.length &&
+ sortedFiltered.length > 0 && <Check size={12} />}
+ </span>
+ </Button>
+ </span>
+ <span className="col-name">{t('common.labels.name', 'Name')}</span>
+ <span className="col-size">{t('common.labels.size', 'Size')}</span>
+ <span className="col-modified">
+ {t('app.fileManager.modified', 'Modified')}
+ </span>
+ <span className="col-permissions">
+ {t('common.labels.permissions', 'Permissions')}
+ </span>
+ <span className="col-owner">{t('app.fileManager.owner', 'Owner')}</span>
+ <span className="col-actions">{t('common.labels.actions', 'Actions')}</span>
+ </div>
+ {sortedFiltered.map((entry) => (
+ <FileRow
+ key={entry.path}
+ entry={entry}
+ selected={selectedPaths.has(entry.path)}
+ selectMode={selectMode}
+ onOpen={rowOpen}
+ onToggleSelect={rowToggleSelect}
+ onContext={rowContext}
+ onDownload={rowDownload}
+ onRename={rowRename}
+ onPermissions={rowPermissions}
+ onDelete={rowDelete}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+ </main>
+ </>
+ );
+}
diff --git a/frontend/src/components/file-manager/FileManagerSidebar.jsx b/frontend/src/components/file-manager/FileManagerSidebar.jsx
new file mode 100644
index 00000000..aa524bab
--- /dev/null
+++ b/frontend/src/components/file-manager/FileManagerSidebar.jsx
@@ -0,0 +1,233 @@
+import {
+ FolderPlus,
+ X,
+ RefreshCw,
+ ChevronDown,
+ ChevronRight,
+ HardDrive,
+ Clock,
+ Zap,
+ FolderTree as FolderTreeIcon,
+} from 'lucide-react';
+
+import { Button } from '@/components/ui/button';
+import FolderTree from './FolderTree';
+
+import ServerPicker from '@/components/ServerPicker';
+import { serverTarget, targetServerId } from '@/utils/serverTarget';
+
+import { TREE_ROOTS } from './fileTypes';
+
+import { useTranslation } from 'react-i18next';
+
+import { formatTime } from '@/utils/intl';
+function mountDisplayName(mount) {
+ if (!mount?.mountpoint || mount.mountpoint === '/') return null;
+ const parts = mount.mountpoint.split('/').filter(Boolean);
+ const leaf = parts[parts.length - 1] || mount.mountpoint;
+ return leaf === 'docker-desktop-user-distro' ? 'docker-desktop' : leaf;
+}
+
+
+export default function FileManagerSidebar({
+ sidebarVisible,
+ setSidebarVisible,
+ target,
+ setTarget,
+ s3Options,
+ isS3,
+ isRemote,
+ loadDiskMounts,
+ diskLoading,
+ diskMounts,
+ activeMount,
+ navigateTo,
+ diskLastUpdated,
+ quickAccess,
+ currentPath,
+ setTreeCollapsed,
+ treeCollapsed,
+ setDialog,
+ treeExpanded,
+ treeCache,
+ treeLoading,
+ toggleTreeExpand,
+}) {
+ const getDiskColor = (percent) => {
+ if (percent >= 90) return 'critical';
+ if (percent >= 70) return 'warning';
+ return 'healthy';
+ };
+
+ const { t } = useTranslation();
+ return (
+ <>
+ {sidebarVisible && (
+ <aside className="file-manager-sidebar left">
+ <div className="file-manager-source">
+ <Button
+ variant="unstyled"
+ type="button"
+ className="file-manager-source__close"
+ onClick={() => setSidebarVisible(false)}
+ aria-label={t('app.fileManager.hideSidebar', 'Hide sidebar')}
+ >
+ <X size={14} />
+ </Button>
+ <ServerPicker
+ capability="files"
+ value={targetServerId(target)}
+ onChange={(id, server) =>
+ setTarget(serverTarget(id, server || (id === 's3' ? null : {})))
+ }
+ extraOptions={s3Options}
+ className="file-manager-source__picker"
+ />
+ <div className="file-manager-source__meta">
+ <span
+ className={`file-manager-source__dot${isS3 ? ' is-cloud' : ''}`}
+ aria-hidden="true"
+ />
+ <span>
+ {isRemote
+ ? t('app.fileManager.remoteAgent', 'Remote agent')
+ : isS3
+ ? t('app.fileManager.objectStorage', 'Object storage')
+ : t('app.fileManager.localPanelHost', 'Panel server')}
+ </span>
+ </div>
+ </div>
+
+ {!isRemote && !isS3 && (
+ <div className="sidebar-section sidebar-section--volumes">
+ <div className="sidebar-section-header sidebar-section-header--split">
+ <span
+ className="sidebar-section-title"
+ title={t('app.fileManager.diskUsage', 'Disk usage')}
+ >
+ <HardDrive size={13} />
+ <span>{t('app.fileManager.volumes', 'Volumes')}</span>
+ </span>
+ <Button
+ variant="unstyled"
+ type="button"
+ className="sidebar-action-btn"
+ onClick={loadDiskMounts}
+ disabled={diskLoading}
+ title={t('common.actions.refresh', 'Refresh')}
+ >
+ <RefreshCw size={12} className={diskLoading ? 'spinning' : ''} />
+ </Button>
+ </div>
+ <div className="sidebar-section-content disk-mount-list">
+ {diskMounts.map((mount) => (
+ <Button
+ variant="unstyled"
+ type="button"
+ key={`${mount.device}:${mount.mountpoint}`}
+ className={`disk-mount-item${activeMount?.mountpoint === mount.mountpoint ? ' active' : ''}`}
+ onClick={() => navigateTo(mount.mountpoint)}
+ title={`${mount.device} · ${mount.used_human} / ${mount.total_human}`}
+ >
+ <div className="disk-mount-header">
+ <span className="disk-mount-point">
+ {mount.mountpoint === '/'
+ ? t('app.fileManager.rootDisk', 'Root disk')
+ : mountDisplayName(mount)}
+ </span>
+ <span className={`disk-percent ${getDiskColor(mount.percent)}`}>
+ {mount.percent}%
+ </span>
+ </div>
+ <div className={`disk-progress ${getDiskColor(mount.percent)}`}>
+ <span
+ className="disk-progress-fill"
+ style={{ width: `${mount.percent}%` }}
+ />
+ </div>
+ </Button>
+ ))}
+ {diskLastUpdated && (
+ <span className="disk-updated disk-updated--footer">
+ <Clock size={11} />
+ {t('app.fileManager.updatedAt', 'Updated {{time}}', {
+ time: formatTime(diskLastUpdated, { seconds: true }),
+ })}
+ </span>
+ )}
+ </div>
+ </div>
+ )}
+
+ {!isS3 && (
+ <>
+ <div className="sidebar-section">
+ <div className="sidebar-section-header static">
+ <Zap size={16} />
+ <span>{t('app.fileManager.quickAccess', 'Quick access')}</span>
+ </div>
+ <div className="sidebar-section-content quick-access-list">
+ {quickAccess.map((q) => (
+ <Button
+ variant="unstyled"
+ type="button"
+ key={q.label}
+ className={`quick-access-item ${currentPath === q.path ? 'active' : ''}`}
+ onClick={() => navigateTo(q.path)}
+ >
+ <q.icon size={14} />
+ <span>{q.label}</span>
+ </Button>
+ ))}
+ </div>
+ </div>
+
+ <div className="sidebar-section">
+ <div className="sidebar-section-header sidebar-section-header--split">
+ <Button
+ variant="unstyled"
+ type="button"
+ className="sidebar-section-toggle"
+ onClick={() => setTreeCollapsed(!treeCollapsed)}
+ title={t('app.fileManager.folders', 'Folders')}
+ >
+ <FolderTreeIcon size={16} />
+ <span>{t('app.fileManager.fileSystem', 'File system')}</span>
+ {treeCollapsed ? (
+ <ChevronRight size={16} />
+ ) : (
+ <ChevronDown size={16} />
+ )}
+ </Button>
+ <Button
+ variant="unstyled"
+ type="button"
+ className="sidebar-action-btn"
+ onClick={() => setDialog({ kind: 'newFolder' })}
+ disabled={isRemote}
+ title={t('app.fileManager.newFolder', 'New folder')}
+ >
+ <FolderPlus size={14} />
+ </Button>
+ </div>
+ {!treeCollapsed && (
+ <div className="sidebar-section-content tree-content">
+ <FolderTree
+ roots={TREE_ROOTS}
+ expanded={treeExpanded}
+ treeCache={treeCache}
+ treeLoading={treeLoading}
+ currentPath={currentPath}
+ onNavigate={navigateTo}
+ onToggle={toggleTreeExpand}
+ />
+ </div>
+ )}
+ </div>
+ </>
+ )}
+ </aside>
+ )}
+ </>
+ );
+}
diff --git a/frontend/src/components/file-manager/FileManagerStatus.jsx b/frontend/src/components/file-manager/FileManagerStatus.jsx
new file mode 100644
index 00000000..2d8f2374
--- /dev/null
+++ b/frontend/src/components/file-manager/FileManagerStatus.jsx
@@ -0,0 +1,59 @@
+import { Folder, File } from 'lucide-react';
+
+import { formatBytes } from './fileTypes';
+
+import { useTranslation } from 'react-i18next';
+
+export default function FileManagerStatus({ stats }) {
+ const { t } = useTranslation();
+ return (
+ <>
+ <div className="status-bar">
+ <div className="status-bar-left">
+ <span className="status-item">
+ <span className="status-label">{t('app.fileManager.total', 'Total')}</span>
+ <span className="status-value">
+ {stats.total} item{stats.total !== 1 ? 's' : ''}
+ </span>
+ </span>
+ <span className="status-divider" />
+ <span className="status-item">
+ <Folder size={12} />
+ <span>
+ {stats.folders} folder{stats.folders !== 1 ? 's' : ''}
+ </span>
+ </span>
+ <span className="status-item">
+ <File size={12} />
+ <span>
+ {stats.files} file{stats.files !== 1 ? 's' : ''}
+ </span>
+ </span>
+ {stats.totalBytes > 0 && (
+ <>
+ <span className="status-divider" />
+ <span className="status-item">
+ <span className="status-label">{t('common.labels.size', 'Size')}</span>
+ <span className="status-value">{formatBytes(stats.totalBytes)}</span>
+ </span>
+ </>
+ )}
+ </div>
+ <div className="status-bar-right">
+ {stats.selectedCount > 0 && (
+ <span className="status-selection">
+ {stats.selectedCount} {t('app.fileManager.selected', 'selected ·')}{' '}
+ {formatBytes(stats.selectedBytes)}
+ </span>
+ )}
+ <span
+ className="status-shortcuts"
+ title={t('app.fileManager.keyboardShortcuts', 'Keyboard shortcuts')}
+ >
+ {t('app.fileManager.upDelDeleteF2RenameA', '⌫ Up · Del Delete · F2 Rename · ⌘A All')}
+ </span>
+ </div>
+ </div>
+ </>
+ );
+}
diff --git a/frontend/src/components/file-manager/FileManagerToolbar.jsx b/frontend/src/components/file-manager/FileManagerToolbar.jsx
new file mode 100644
index 00000000..78a21e20
--- /dev/null
+++ b/frontend/src/components/file-manager/FileManagerToolbar.jsx
@@ -0,0 +1,263 @@
+import {
+ File,
+ ArrowLeft,
+ ArrowRight,
+ ArrowUp,
+ Search,
+ X,
+ RefreshCw,
+ Eye,
+ EyeOff,
+ HardDrive,
+ PanelLeftClose,
+ PanelLeftOpen,
+ LayoutGrid,
+ List,
+ Home,
+ ArrowUpDown,
+} from 'lucide-react';
+
+import { Button } from '@/components/ui/button';
+
+import { Select, SelectTrigger, SelectContent, SelectItem, SelectValue } from '@/components/ui/select';
+
+import { useTranslation } from 'react-i18next';
+
+export default function FileManagerToolbar({
+ history,
+ setSidebarVisible,
+ sidebarVisible,
+ goBack,
+ historyIdx,
+ goForward,
+ goUp,
+ parentPath,
+ navigateTo,
+ isS3,
+ breadcrumbs,
+ activeMount,
+ isRemote,
+ activeFilter,
+ setActiveFilter,
+ FILTER_OPTIONS,
+ filterLabels,
+ filterCounts,
+ sortValue,
+ handleSortChange,
+ searchQuery,
+ setSearchQuery,
+ handleSearch,
+ searchResults,
+ clearSearch,
+ viewMode,
+ setViewMode,
+ showHidden,
+ setShowHidden,
+ loadDirectory,
+ currentPath,
+ loading,
+}) {
+ const { t } = useTranslation();
+ return (
+ <>
+ <div className="file-manager-toolbar">
+ <div className="toolbar-left">
+ <Button
+ variant="unstyled"
+ type="button"
+ className="toolbar-icon-btn"
+ onClick={() => setSidebarVisible(!sidebarVisible)}
+ title={
+ sidebarVisible
+ ? t('app.fileManager.hideSidebar', 'Hide sidebar')
+ : t('app.fileManager.showSidebar', 'Show sidebar')
+ }
+ >
+ {sidebarVisible ? <PanelLeftClose size={14} /> : <PanelLeftOpen size={14} />}
+ </Button>
+ <div className="nav-buttons">
+ <Button
+ variant="unstyled"
+ type="button"
+ className="nav-btn"
+ onClick={goBack}
+ disabled={historyIdx === 0}
+ title={t('common.actions.back', 'Back')}
+ >
+ <ArrowLeft size={14} />
+ </Button>
+ <Button
+ variant="unstyled"
+ type="button"
+ className="nav-btn"
+ onClick={goForward}
+ disabled={historyIdx >= history.length - 1}
+ title={t('app.fileManager.forward', 'Forward')}
+ >
+ <ArrowRight size={14} />
+ </Button>
+ <Button
+ variant="unstyled"
+ type="button"
+ className="nav-btn"
+ onClick={goUp}
+ disabled={!parentPath}
+ title="Up"
+ >
+ <ArrowUp size={14} />
+ </Button>
+ <Button
+ variant="unstyled"
+ type="button"
+ className="nav-btn"
+ onClick={() => navigateTo(isS3 ? '/' : '/home')}
+ title={t('app.fileManager.home', 'Home')}
+ >
+ <Home size={14} />
+ </Button>
+ </div>
+ <div className="path-breadcrumb">
+ {breadcrumbs.map((crumb, idx) => (
+ <span key={crumb.path + idx} className="crumb-segment">
+ {idx > 0 && <span className="crumb-separator">/</span>}
+ <Button
+ variant="unstyled"
+ type="button"
+ className={`crumb ${idx === breadcrumbs.length - 1 ? 'crumb-active' : ''}`}
+ onClick={() => navigateTo(crumb.path)}
+ >
+ {crumb.name}
+ </Button>
+ </span>
+ ))}
+ </div>
+ {activeMount && !isRemote && !isS3 && (
+ <span
+ className="file-mount-chip"
+ title={`${activeMount.device} · ${activeMount.total_human}`}
+ >
+ <HardDrive size={12} />
+ <span>
+ {activeMount.mountpoint === '/'
+ ? t('app.fileManager.rootDisk', 'Root disk')
+ : activeMount.mountpoint}
+ </span>
+ </span>
+ )}
+ </div>
+ <div className="toolbar-right">
+ <Select value={activeFilter} onValueChange={setActiveFilter}>
+ <SelectTrigger
+ className="file-toolbar-select"
+ title={t('app.fileManager.types', 'Types')}
+ aria-label={t('app.fileManager.types', 'Types')}
+ >
+ <File size={13} aria-hidden="true" />
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {FILTER_OPTIONS.map((option) => (
+ <SelectItem key={option.id} value={option.id}>
+ {filterLabels[option.id]} ({filterCounts[option.id] ?? 0})
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <Select value={sortValue} onValueChange={handleSortChange}>
+ <SelectTrigger
+ className="file-toolbar-select"
+ title={t('app.fileManager.sort', 'Sort')}
+ aria-label={t('app.fileManager.sort', 'Sort')}
+ >
+ <ArrowUpDown size={13} aria-hidden="true" />
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="name-asc">
+ {t('app.fileManager.nameAZ', 'Name A-Z')}
+ </SelectItem>
+ <SelectItem value="name-desc">
+ {t('app.fileManager.nameZA', 'Name Z-A')}
+ </SelectItem>
+ <SelectItem value="modified-desc">
+ {t('app.fileManager.newest', 'Newest')}
+ </SelectItem>
+ <SelectItem value="modified-asc">
+ {t('app.fileManager.oldest', 'Oldest')}
+ </SelectItem>
+ <SelectItem value="size-desc">
+ {t('app.fileManager.largest', 'Largest')}
+ </SelectItem>
+ <SelectItem value="size-asc">
+ {t('app.fileManager.smallest', 'Smallest')}
+ </SelectItem>
+ <SelectItem value="type-asc">{t('common.labels.type', 'Type')}</SelectItem>
+ <SelectItem value="type-desc">
+ {t('app.fileManager.typeZA', 'Type Z-A')}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ <div className="search-field">
+ <Search size={14} className="search-field-icon" />
+ <input
+ type="text"
+ placeholder={t('app.fileManager.searchFiles', 'Search files…')}
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
+ />
+ {(searchResults || searchQuery) && (
+ <Button
+ variant="unstyled"
+ type="button"
+ className="search-field-clear"
+ onClick={clearSearch}
+ title={t('common.actions.clear', 'Clear')}
+ >
+ <X size={12} />
+ </Button>
+ )}
+ </div>
+ <div className="view-toggle">
+ <Button
+ variant="unstyled"
+ type="button"
+ className={`view-toggle-btn ${viewMode === 'grid' ? 'active' : ''}`}
+ onClick={() => setViewMode('grid')}
+ title={t('app.fileManager.gridView', 'Grid view')}
+ >
+ <LayoutGrid size={14} />
+ </Button>
+ <Button
+ variant="unstyled"
+ type="button"
+ className={`view-toggle-btn ${viewMode === 'list' ? 'active' : ''}`}
+ onClick={() => setViewMode('list')}
+ title={t('app.fileManager.listView', 'List view')}
+ >
+ <List size={14} />
+ </Button>
+ </div>
+ <Button
+ variant="unstyled"
+ type="button"
+ className={`toolbar-icon-btn ${showHidden ? 'active' : ''}`}
+ onClick={() => setShowHidden(!showHidden)}
+ title={t('app.fileManager.toggleHiddenFiles', 'Toggle hidden files')}
+ >
+ {showHidden ? <Eye size={14} /> : <EyeOff size={14} />}
+ </Button>
+ <Button
+ variant="unstyled"
+ type="button"
+ className="toolbar-icon-btn"
+ onClick={() => loadDirectory(currentPath)}
+ title={t('common.actions.refresh', 'Refresh')}
+ >
+ <RefreshCw size={14} className={loading ? 'spinning' : ''} />
+ </Button>
+ </div>
+ </div>
+ </>
+ );
+}
diff --git a/frontend/src/components/file-manager/FileUploadTray.jsx b/frontend/src/components/file-manager/FileUploadTray.jsx
new file mode 100644
index 00000000..f679f8a5
--- /dev/null
+++ b/frontend/src/components/file-manager/FileUploadTray.jsx
@@ -0,0 +1,58 @@
+import { X, CloudUpload } from 'lucide-react';
+
+import { Button } from '@/components/ui/button';
+
+import { useTranslation } from 'react-i18next';
+
+export default function FileUploadTray({ uploads, activeUploads, totalUploadProgress, setUploads }) {
+ const { t } = useTranslation();
+ return (
+ <>
+ {uploads.length > 0 && (
+ <div className="upload-tray">
+ <div className="upload-tray-header">
+ <CloudUpload size={16} />
+ <span>
+ {activeUploads.length > 0
+ ? t('app.fileManager.uploadingFiles', {
+ count: activeUploads.length,
+ defaultValue_one: 'Uploading 1 file…',
+ defaultValue_other: 'Uploading {{count}} files…',
+ })
+ : t('app.fileManager.uploadsComplete', 'Uploads complete')}
+ </span>
+ {activeUploads.length > 0 && (
+ <span className="upload-tray-percent">{Math.round(totalUploadProgress)}%</span>
+ )}
+ <Button
+ variant="unstyled"
+ type="button"
+ className="toolbar-icon-btn small"
+ onClick={() => setUploads([])}
+ title={t('common.actions.clear', 'Clear')}
+ >
+ <X size={14} />
+ </Button>
+ </div>
+ <div className="upload-tray-list">
+ {uploads.map((u) => (
+ <div key={u.id} className={`upload-tray-item status-${u.status}`}>
+ <span className="upload-name">{u.name}</span>
+ <div className="upload-bar">
+ <div className="upload-bar-fill" style={{ width: `${u.progress}%` }} />
+ </div>
+ <span className="upload-status">
+ {u.status === 'done'
+ ? t('common.actions.done', 'Done')
+ : u.status === 'error'
+ ? t('app.fileManager.uploadFailed', 'Failed')
+ : `${Math.round(u.progress)}%`}
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ </>
+ );
+}
diff --git a/frontend/src/components/file-manager/ImageThumb.jsx b/frontend/src/components/file-manager/ImageThumb.jsx
index 7596d837..f40c0cc0 100644
--- a/frontend/src/components/file-manager/ImageThumb.jsx
+++ b/frontend/src/components/file-manager/ImageThumb.jsx
@@ -1,38 +1,7 @@
-import { useEffect, useState } from 'react';
-import { api } from '../../services/api';
+import useImagePreview from './hooks/useImagePreview';
-// Auth-fetches a file via the download endpoint, converts to a blob URL, and
-// renders it as an <img>. Falls back to whatever JSX is passed in `fallback`.
-export default function ImageThumb({ path, fallback, className = 'thumb-image', alt = '', isS3 = false }) {
- const [src, setSrc] = useState(null);
- const [errored, setErrored] = useState(false);
-
- useEffect(() => {
- let blobUrl = null;
- let cancelled = false;
- (async () => {
- try {
- // S3 objects load straight from a short-lived presigned URL — no
- // auth header or blob needed.
- if (isS3) {
- const res = await api.getS3DownloadUrl(path);
- if (!res || !res.url) throw new Error('no presigned url');
- if (!cancelled) setSrc(res.url);
- return;
- }
- const blob = await api.getFileBlob(path);
- blobUrl = URL.createObjectURL(blob);
- if (!cancelled) setSrc(blobUrl);
- } catch {
- if (!cancelled) setErrored(true);
- }
- })();
- return () => {
- cancelled = true;
- if (blobUrl) URL.revokeObjectURL(blobUrl);
- };
- }, [path, isS3]);
-
- if (errored || !src) return fallback;
+export default function ImageThumb({ path, fileApi, fallback, className = 'thumb-image', alt = '' }) {
+ const src = useImagePreview(fileApi, path);
+ if (!src) return fallback;
return <img src={src} alt={alt} className={className} loading="lazy" />;
}
diff --git a/frontend/src/components/file-manager/PreviewDrawer.jsx b/frontend/src/components/file-manager/PreviewDrawer.jsx
index 95b6fe7c..162e74c9 100644
--- a/frontend/src/components/file-manager/PreviewDrawer.jsx
+++ b/frontend/src/components/file-manager/PreviewDrawer.jsx
@@ -29,7 +29,7 @@ export default function PreviewDrawer({
// When true, render as a flush inline pane (file-manager 3rd column)
// instead of a fixed-position drawer-over-scrim.
inline = false,
- isS3 = false,
+ fileApi,
}) {
const { t } = useTranslation();
// Lock body scroll only for the overlay drawer; the inline pane scrolls
@@ -114,7 +114,7 @@ export default function PreviewDrawer({
<div className="preview-image-wrap">
<ImageThumb
path={file.path}
- isS3={isS3}
+ fileApi={fileApi}
fallback={
<div className="preview-unavailable">
<EyeOff size={48} strokeWidth={1.5} />
diff --git a/frontend/src/components/file-manager/__tests__/boundaries.test.js b/frontend/src/components/file-manager/__tests__/boundaries.test.js
new file mode 100644
index 00000000..43bc2d59
--- /dev/null
+++ b/frontend/src/components/file-manager/__tests__/boundaries.test.js
@@ -0,0 +1,20 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import {
+ checkFileManagerBoundaries,
+ inspectFileManagerSource,
+} from '../../../../scripts/check-file-manager-boundaries.mjs';
+
+test('File Manager keeps transport, orchestration and views separate', () => {
+ assert.doesNotThrow(checkFileManagerBoundaries);
+});
+
+test('boundary guard rejects dependencies that would recombine the feature', () => {
+ for (const [path, source] of [
+ ['pages/FileManager.jsx', 'async function load() { await api.browseFiles(); }'],
+ ['components/file-manager/FileManagerListing.jsx', "import { api } from '@/services/api';"],
+ ['components/file-manager/hooks/useFileEditor.js', "import Page from '@/pages/FileManager';"],
+ ['components/file-manager/FileManagerSidebar.jsx', "import useFileTree from './hooks/useFileTree';"],
+ ])
+ assert.ok(inspectFileManagerSource(path, source).length > 0, path);
+});
diff --git a/frontend/src/components/file-manager/__tests__/fileAdapter.test.js b/frontend/src/components/file-manager/__tests__/fileAdapter.test.js
index bf218f12..978c0b1f 100644
--- a/frontend/src/components/file-manager/__tests__/fileAdapter.test.js
+++ b/frontend/src/components/file-manager/__tests__/fileAdapter.test.js
@@ -24,7 +24,7 @@ for (const kind of ['agent', 's3']) {
test(`${kind} unsupported operations never reach the panel host`, () => {
const { adapter, calls } = fixture({ kind, server_id: 7 });
const unsupported = ['search', 'create folder', 'rename', 'change permissions'];
- if (kind === 'agent') unsupported.push('delete', 'download', 'upload');
+ if (kind === 'agent') unsupported.push('delete', 'download', 'upload', 'preview');
for (const operation of unsupported) {
assert.equal(adapter.supports(operation), false);
assert.throws(() => adapter[operation]('/home/a'), /unavailable/);
diff --git a/frontend/src/components/file-manager/fileAdapter.js b/frontend/src/components/file-manager/fileAdapter.js
index 6949c432..0561808f 100644
--- a/frontend/src/components/file-manager/fileAdapter.js
+++ b/frontend/src/components/file-manager/fileAdapter.js
@@ -1,7 +1,7 @@
// All file operations cross this boundary. Unsupported targets never fall back
// to the panel host, even if a caller forgets to disable a control.
const OPERATIONS = ['browse', 'read', 'write', 'delete', 'download', 'upload',
- 'search', 'create folder', 'rename', 'change permissions'];
+ 'search', 'create folder', 'rename', 'change permissions', 'preview'];
function unwrapAgentData(result) {
return result && typeof result === 'object' && 'success' in result && 'data' in result
@@ -20,6 +20,7 @@ export function createFileAdapter(api, target) {
'create folder': (path) => api.createDirectory(path),
rename: (path, name) => api.renameFile(path, name),
'change permissions': (path, mode) => api.changeFilePermissions(path, mode),
+ preview: async (path) => ({ blob: await api.getFileBlob(path) }),
};
const agent = {
browse: async (path) => unwrapAgentData(await api.browseRemoteFiles(target.server_id, path)),
@@ -33,6 +34,7 @@ export function createFileAdapter(api, target) {
delete: (path) => api.deleteS3(path),
download: (entry) => api.downloadS3File(entry.path),
upload: (path, file, progress) => api.uploadS3(path, file, progress),
+ preview: (path) => api.getS3DownloadUrl(path),
};
const methods = { local, agent, s3 }[target.kind];
if (!methods) throw new Error(`Unknown file target: ${target.kind}`);
diff --git a/frontend/src/components/file-manager/hooks/useDirectoryBrowser.js b/frontend/src/components/file-manager/hooks/useDirectoryBrowser.js
new file mode 100644
index 00000000..6c52aba4
--- /dev/null
+++ b/frontend/src/components/file-manager/hooks/useDirectoryBrowser.js
@@ -0,0 +1,276 @@
+import { useState, useRef, useEffect } from 'react';
+import { useSearchParams } from 'react-router-dom';
+import { useStableHandler } from '@/hooks/useStableHandler';
+import { errorReason } from '@/utils/errorMessage';
+
+function deriveParent(path) {
+ if (!path || path === '/' || path === '') return null;
+ // A Windows drive root ("C:/" or "C:") sits directly under the agent's
+ // drive list, which the agent serves for the "/" path. Remote agents
+ // emit forward-slash paths on the wire, so we only ever see "/" here.
+ if (/^[A-Za-z]:\/?$/.test(path)) return '/';
+ const trimmed = path.replace(/\/+$/, '');
+ const idx = trimmed.lastIndexOf('/');
+ if (idx <= 0) return '/';
+ const parent = trimmed.slice(0, idx);
+ // Keep a bare drive letter as a drive root ("C:" -> "C:/") so navigating
+ // up doesn't hit Windows' "current directory on C:" semantics.
+ if (/^[A-Za-z]:$/.test(parent)) return parent + '/';
+ return parent;
+}
+
+export default function useDirectoryBrowser({
+ fileApi,
+ target,
+ resetSelection,
+ onNavigate,
+ remoteGuard,
+ toast,
+ t,
+}) {
+ const [searchParams, setSearchParams] = useSearchParams();
+ const previousTargetRef = useRef({ kind: 'local', server_id: null });
+ // ─── core ────────────────────────────────────────────
+ const [currentPath, setCurrentPath] = useState(() => searchParams.get('path') || '/home');
+ const [entries, setEntries] = useState([]);
+ const [parentPath, setParentPath] = useState(null);
+ const [loading, setLoading] = useState(true);
+ // The open folder's own load failure, shown in the listing in place of
+ // "This folder is empty". Navigation into a folder that fails still
+ // toasts and steps back, since the previous folder is what stays shown.
+ const [dirError, setDirError] = useState(null);
+ const [showHidden, setShowHidden] = useState(false);
+
+ // ─── search ──────────────────────────────────────────
+ const [searchQuery, setSearchQuery] = useState('');
+ const [searchResults, setSearchResults] = useState(null);
+
+ // ─── history ─────────────────────────────────────────
+ const [history, setHistory] = useState([currentPath]);
+ const [historyIdx, setHistoryIdx] = useState(0);
+ const navByHistory = useRef(false);
+ const lastValidPathRef = useRef(null);
+ // Only the newest browse may write: a slow answer for the folder the
+ // user just left used to land last and navigate them back to it.
+ const loadSeqRef = useRef(0);
+ const activeRequest = useRef(null);
+ activeRequest.current = { api: fileApi, path: currentPath };
+ useEffect(
+ () => () => {
+ loadSeqRef.current++;
+ },
+ [],
+ );
+
+ useEffect(() => {
+ const pathFromUrl = searchParams.get('path') || '/home';
+ if (pathFromUrl !== currentPath) {
+ setCurrentPath(pathFromUrl);
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [searchParams]);
+
+ useEffect(() => {
+ const pathFromUrl = searchParams.get('path') || '/home';
+ if (pathFromUrl === currentPath) return;
+
+ const nextParams = new URLSearchParams(searchParams);
+ nextParams.set('path', currentPath);
+ setSearchParams(nextParams, { replace: true });
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [currentPath]);
+
+ // When the user switches to a remote target, jump to its first
+ // advertised allowed_path so they don't see a "panel /home" view
+ // that doesn't exist on the remote host.
+ useEffect(() => {
+ const previousTarget = previousTargetRef.current;
+ const targetChanged =
+ previousTarget.kind !== target.kind || previousTarget.server_id !== target.server_id;
+ previousTargetRef.current = { kind: target.kind, server_id: target.server_id };
+
+ if (!targetChanged) return;
+ lastValidPathRef.current = null;
+ onNavigate();
+ resetSelection();
+
+ const nextPath =
+ target.kind === 'agent'
+ ? target.allowedPaths?.[0] || currentPath
+ : target.kind === 's3'
+ ? '/'
+ : '/home';
+ navByHistory.current = nextPath !== currentPath;
+ setHistory([nextPath]);
+ setHistoryIdx(0);
+ setCurrentPath(nextPath);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [target.kind, target.server_id]);
+
+ // ─── load directory ──────────────────────────────────
+ const loadDirectory = useStableHandler(async (path) => {
+ if (path !== activeRequest.current.path || fileApi !== activeRequest.current.api) return;
+ const seq = ++loadSeqRef.current;
+ setLoading(true);
+ setSearchResults(null);
+ resetSelection();
+ try {
+ const data = await fileApi.browse(path, showHidden);
+ if (
+ seq !== loadSeqRef.current ||
+ fileApi !== activeRequest.current.api ||
+ path !== activeRequest.current.path
+ )
+ return;
+ // Agent file:list returns {path, files: [...]} with a flat
+ // entry shape; panel browseFiles returns {path, parent,
+ // entries: [...]}. Normalize so the UI can keep using
+ // entries/parent.
+ const entriesList = data.entries || data.files || [];
+ setEntries(entriesList);
+ setParentPath(data.parent ?? deriveParent(data.path || path));
+ setCurrentPath(data.path || path);
+ lastValidPathRef.current = data.path || path;
+ setDirError(null);
+ } catch (error) {
+ if (
+ seq !== loadSeqRef.current ||
+ fileApi !== activeRequest.current.api ||
+ path !== activeRequest.current.path
+ )
+ return;
+ if (lastValidPathRef.current !== null && path !== lastValidPathRef.current) {
+ toast.error(
+ t('app.fileManager.failedToLoadDirectory', "Couldn't load the folder. {{message}}", {
+ message: errorReason(error),
+ }),
+ );
+ setCurrentPath(lastValidPathRef.current);
+ } else {
+ setEntries([]);
+ setDirError(error);
+ }
+ } finally {
+ if (
+ seq === loadSeqRef.current &&
+ fileApi === activeRequest.current.api &&
+ path === activeRequest.current.path
+ )
+ setLoading(false);
+ }
+ });
+
+ useEffect(() => {
+ loadDirectory(currentPath);
+ }, [currentPath, showHidden, fileApi, loadDirectory]);
+
+ // history tracking
+ useEffect(() => {
+ if (navByHistory.current) {
+ navByHistory.current = false;
+ return;
+ }
+ setHistory((h) => {
+ const trimmed = h.slice(0, historyIdx + 1);
+ if (trimmed[trimmed.length - 1] === currentPath) return h;
+ return [...trimmed, currentPath];
+ });
+ setHistoryIdx((i) => (history[i] === currentPath ? i : i + 1));
+ }, [currentPath]); // eslint-disable-line react-hooks/exhaustive-deps
+
+ // ─── search ──────────────────────────────────────────
+ const clearSearch = () => {
+ loadSeqRef.current++;
+ setSearchResults(null);
+ setSearchQuery('');
+ setLoading(false);
+ };
+ const handleSearch = async () => {
+ if (remoteGuard('search')) {
+ setSearchResults([]);
+ return;
+ }
+ if (!searchQuery.trim()) {
+ clearSearch();
+ return;
+ }
+ const seq = ++loadSeqRef.current;
+ const path = currentPath;
+ setLoading(true);
+ try {
+ const data = await fileApi.search(currentPath, searchQuery);
+ if (
+ seq !== loadSeqRef.current ||
+ fileApi !== activeRequest.current.api ||
+ path !== activeRequest.current.path
+ )
+ return;
+ setSearchResults(data.results || []);
+ } catch (error) {
+ if (
+ seq !== loadSeqRef.current ||
+ fileApi !== activeRequest.current.api ||
+ path !== activeRequest.current.path
+ )
+ return;
+ toast.error(
+ t('app.fileManager.searchFailed', "Couldn't search. {{message}}", {
+ message: errorReason(error),
+ }),
+ );
+ } finally {
+ if (
+ seq === loadSeqRef.current &&
+ fileApi === activeRequest.current.api &&
+ path === activeRequest.current.path
+ )
+ setLoading(false);
+ }
+ };
+
+ // ─── navigation ──────────────────────────────────────
+ const navigateTo = (path) => {
+ onNavigate();
+ setCurrentPath(path);
+ };
+
+ const goBack = () => {
+ if (historyIdx > 0) {
+ onNavigate();
+ navByHistory.current = true;
+ setHistoryIdx(historyIdx - 1);
+ setCurrentPath(history[historyIdx - 1]);
+ }
+ };
+ const goForward = () => {
+ if (historyIdx < history.length - 1) {
+ onNavigate();
+ navByHistory.current = true;
+ setHistoryIdx(historyIdx + 1);
+ setCurrentPath(history[historyIdx + 1]);
+ }
+ };
+ const goUp = () => parentPath && navigateTo(parentPath);
+
+ return {
+ currentPath,
+ entries,
+ parentPath,
+ loading,
+ dirError,
+ showHidden,
+ setShowHidden,
+ searchQuery,
+ setSearchQuery,
+ searchResults,
+ clearSearch,
+ history,
+ historyIdx,
+ loadDirectory,
+ handleSearch,
+ navigateTo,
+ goBack,
+ goForward,
+ goUp,
+ };
+}
diff --git a/frontend/src/components/file-manager/hooks/useFileActions.js b/frontend/src/components/file-manager/hooks/useFileActions.js
new file mode 100644
index 00000000..f998a23b
--- /dev/null
+++ b/frontend/src/components/file-manager/hooks/useFileActions.js
@@ -0,0 +1,149 @@
+import { useState, useRef, useEffect } from 'react';
+import { useConfirm } from '@/hooks/useConfirm';
+import { errorReason } from '@/utils/errorMessage';
+
+export default function useFileActions({
+ fileApi,
+ currentPath,
+ remoteGuard,
+ loadDirectory,
+ refreshTree,
+ previewFile,
+ setPreviewFile,
+ clearSelection,
+ toast,
+ t,
+}) {
+ // ─── modals ──────────────────────────────────────────
+ // { kind: 'newFolder' } | { kind: 'rename', entry } | { kind: 'permissions', entry } | null
+ const [dialog, setDialog] = useState(null);
+ const closeDialog = () => setDialog(null);
+ const { confirm } = useConfirm();
+ const active = useRef(null);
+ active.current = { fileApi, currentPath };
+ const isCurrent = () =>
+ active.current?.fileApi === fileApi && active.current?.currentPath === currentPath;
+ useEffect(() => {
+ setDialog(null);
+ }, [fileApi, currentPath]);
+ useEffect(
+ () => () => {
+ active.current = null;
+ },
+ [],
+ );
+
+ const handleCreateFolder = async (name) => {
+ if (remoteGuard('create folder')) return;
+ try {
+ await fileApi['create folder'](`${currentPath}/${name}`);
+ if (!isCurrent()) return;
+ toast.success(t('app.fileManager.folderCreated', 'Folder created'));
+ closeDialog();
+ loadDirectory(currentPath);
+ refreshTree(currentPath);
+ } catch (error) {
+ if (!isCurrent()) return;
+ toast.error(
+ t('app.fileManager.failedToCreateFolder', "Couldn't create the folder. {{message}}", {
+ message: errorReason(error),
+ }),
+ );
+ }
+ };
+
+ const handleDelete = async (target) => {
+ const items = Array.isArray(target) ? target : [target];
+ if (items.length === 0) return;
+ if (remoteGuard('delete')) return;
+ const message =
+ items.length === 1
+ ? `Delete "${items[0].name}"?${items[0].is_dir ? ' All contents inside will be removed.' : ''}`
+ : `Delete ${items.length} items? This cannot be undone.`;
+ if (
+ !(await confirm({
+ title: t('app.fileManager.deleteConfirmation', 'Delete confirmation'),
+ message,
+ confirmText: t('common.actions.delete', 'Delete'),
+ variant: 'danger',
+ }))
+ )
+ return;
+ if (!isCurrent()) return;
+ const failures = [];
+ for (const it of items) {
+ try {
+ await fileApi.del(it.path);
+ } catch (error) {
+ failures.push(`${it.name}: ${error.message}`);
+ }
+ }
+ if (!isCurrent()) return;
+ if (failures.length === 0)
+ toast.success(
+ t('app.fileManager.deletedItems', {
+ count: items.length,
+ defaultValue_one: 'Deleted 1 item',
+ defaultValue_other: 'Deleted {{count}} items',
+ }),
+ );
+ else
+ toast.error(
+ t('app.fileManager.failed', "Couldn't finish for: {{value}}", { value: failures.join(', ') }),
+ );
+ if (previewFile && items.some((i) => i.path === previewFile.path)) setPreviewFile(null);
+ clearSelection();
+ loadDirectory(currentPath);
+ };
+
+ const handleRename = async (entry, name) => {
+ if (remoteGuard('rename')) return;
+ try {
+ await fileApi.rename(entry.path, name);
+ if (!isCurrent()) return;
+ toast.success(t('app.fileManager.renamed', 'Renamed'));
+ closeDialog();
+ loadDirectory(currentPath);
+ } catch (error) {
+ if (!isCurrent()) return;
+ toast.error(
+ t('app.fileManager.failedToRename', "Couldn't rename it. {{message}}", {
+ message: errorReason(error),
+ }),
+ );
+ }
+ };
+
+ const handleChangePermissions = async (entry, mode) => {
+ if (remoteGuard('change permissions')) return;
+ try {
+ await fileApi['change permissions'](entry.path, mode);
+ if (!isCurrent()) return;
+ toast.success(t('app.fileManager.permissionsUpdated', 'Permissions updated'));
+ closeDialog();
+ loadDirectory(currentPath);
+ } catch (error) {
+ if (!isCurrent()) return;
+ toast.error(
+ t('app.fileManager.failed2', "Couldn't do that. {{message}}", {
+ message: errorReason(error),
+ }),
+ );
+ }
+ };
+
+ const openRenameModal = (entry) => setDialog({ kind: 'rename', entry });
+ const openPermissionsModal = (entry) => setDialog({ kind: 'permissions', entry });
+
+ return {
+ dialog,
+ setDialog,
+ closeDialog,
+ handleCreateFolder,
+ handleDelete,
+ handleRename,
+ handleChangePermissions,
+ openRenameModal,
+ openPermissionsModal,
+ };
+}
diff --git a/frontend/src/components/file-manager/hooks/useFileEditor.js b/frontend/src/components/file-manager/hooks/useFileEditor.js
new file mode 100644
index 00000000..82344c4c
--- /dev/null
+++ b/frontend/src/components/file-manager/hooks/useFileEditor.js
@@ -0,0 +1,74 @@
+import { useEffect, useRef, useState } from 'react';
+import { errorReason } from '@/utils/errorMessage';
+
+export default function useFileEditor({ fileApi, toast, t, onSaved }) {
+ const [previewFile, setPreview] = useState(null);
+ const [fileContent, setFileContent] = useState('');
+ const [editing, setEditing] = useState(false);
+ const generation = useRef(0);
+ const activeApi = useRef(fileApi);
+ activeApi.current = fileApi;
+ useEffect(
+ () => () => {
+ generation.current++;
+ },
+ [],
+ );
+
+ const setPreviewFile = (entry) => {
+ generation.current++;
+ setPreview(entry);
+ setFileContent('');
+ setEditing(false);
+ };
+
+ const openFile = async (entry) => {
+ setPreviewFile(entry);
+ const request = generation.current;
+ if (!entry.is_editable) return;
+ try {
+ const data = await fileApi.read(entry.path);
+ if (request === generation.current && fileApi === activeApi.current) {
+ setFileContent(data.content);
+ }
+ } catch (error) {
+ if (request === generation.current && fileApi === activeApi.current) {
+ toast.error(
+ t('app.fileManager.failedToReadFile', "Couldn't read the file. {{message}}", {
+ message: errorReason(error),
+ }),
+ );
+ }
+ }
+ };
+
+ const handleSaveFile = async () => {
+ if (!previewFile) return;
+ const request = generation.current;
+ try {
+ await fileApi.write(previewFile.path, fileContent);
+ if (request !== generation.current || fileApi !== activeApi.current) return;
+ toast.success(t('app.fileManager.fileSaved', 'File saved'));
+ setEditing(false);
+ onSaved();
+ } catch (error) {
+ if (request !== generation.current || fileApi !== activeApi.current) return;
+ toast.error(
+ t('app.fileManager.failedToSave', "Couldn't save. {{message}}", {
+ message: errorReason(error),
+ }),
+ );
+ }
+ };
+
+ return {
+ previewFile,
+ setPreviewFile,
+ fileContent,
+ setFileContent,
+ editing,
+ setEditing,
+ openFile,
+ handleSaveFile,
+ };
+}
diff --git a/frontend/src/components/file-manager/hooks/useFileListingModel.js b/frontend/src/components/file-manager/hooks/useFileListingModel.js
new file mode 100644
index 00000000..7f31eb5f
--- /dev/null
+++ b/frontend/src/components/file-manager/hooks/useFileListingModel.js
@@ -0,0 +1,137 @@
+import { useMemo } from 'react';
+import { getFileType } from '../fileTypes';
+
+export const FILTER_OPTIONS = [
+ { id: 'all', labelKey: 'common.labels.all', label: 'All' },
+ { id: 'folder', labelKey: 'app.fileManager.folders', label: 'Folders' },
+ { id: 'image', labelKey: 'app.fileManager.images', label: 'Images' },
+ { id: 'code', labelKey: 'app.fileManager.code', label: 'Code' },
+ { id: 'text', labelKey: 'app.fileManager.documents', label: 'Documents' },
+ { id: 'data', labelKey: 'app.fileManager.data', label: 'Data' },
+ { id: 'video', labelKey: 'app.fileManager.videos', label: 'Videos' },
+ { id: 'audio', labelKey: 'app.fileManager.audio', label: 'Audio' },
+ { id: 'archive', labelKey: 'app.fileManager.archives', label: 'Archives' },
+];
+
+export default function useFileListingModel({
+ currentPath,
+ entries,
+ searchResults,
+ activeFilter,
+ sortBy,
+ sortDir,
+ selectedPaths,
+ setSortBy,
+ setSortDir,
+ t,
+}) {
+ // ─── derived ─────────────────────────────────────────
+ const breadcrumbs = useMemo(() => {
+ const parts = currentPath.split('/').filter(Boolean);
+ // Windows drive-rooted path ("C:/Users/Juan"): the first segment is
+ // the drive and the root crumb is the agent's drive list. Building
+ // crumbs with a leading "/" (the POSIX branch below) would produce
+ // bogus "/C:" paths that the agent can't resolve.
+ if (/^[A-Za-z]:$/.test(parts[0] || '')) {
+ const crumbs = [{ name: 'Drives', path: '/' }];
+ let acc = parts[0];
+ crumbs.push({ name: parts[0], path: acc + '/' });
+ for (let i = 1; i < parts.length; i++) {
+ acc += '/' + parts[i];
+ crumbs.push({ name: parts[i], path: acc });
+ }
+ return crumbs;
+ }
+ const crumbs = [{ name: '/', path: '/' }];
+ let acc = '';
+ parts.forEach((p) => {
+ acc += '/' + p;
+ crumbs.push({ name: p, path: acc });
+ });
+ return crumbs;
+ }, [currentPath]);
+
+ const sortedFiltered = useMemo(() => {
+ let list = [...(searchResults || entries)];
+ if (activeFilter !== 'all') list = list.filter((e) => getFileType(e) === activeFilter);
+ const dir = sortDir === 'asc' ? 1 : -1;
+ list.sort((a, b) => {
+ if (a.is_dir !== b.is_dir) return a.is_dir ? -1 : 1;
+ switch (sortBy) {
+ case 'size':
+ return ((a.size || 0) - (b.size || 0)) * dir;
+ case 'modified':
+ return (new Date(a.modified) - new Date(b.modified)) * dir;
+ case 'type':
+ return getFileType(a).localeCompare(getFileType(b)) * dir;
+ case 'name':
+ default:
+ return a.name.localeCompare(b.name) * dir;
+ }
+ });
+ return list;
+ }, [entries, searchResults, sortBy, sortDir, activeFilter]);
+
+ const filterCounts = useMemo(() => {
+ const counts = { all: entries.length };
+ FILTER_OPTIONS.forEach((c) => {
+ if (c.id !== 'all') counts[c.id] = 0;
+ });
+ entries.forEach((e) => {
+ const t = getFileType(e);
+ if (counts[t] !== undefined) counts[t]++;
+ });
+ return counts;
+ }, [entries]);
+
+ const stats = useMemo(() => {
+ const list = sortedFiltered;
+ const folders = list.filter((e) => e.is_dir).length;
+ const files = list.length - folders;
+ const totalBytes = list.reduce((s, e) => s + (e.size || 0), 0);
+ const selectedList = list.filter((e) => selectedPaths.has(e.path));
+ const selectedBytes = selectedList.reduce((s, e) => s + (e.size || 0), 0);
+ return {
+ folders,
+ files,
+ totalBytes,
+ total: list.length,
+ selectedCount: selectedList.length,
+ selectedBytes,
+ };
+ }, [sortedFiltered, selectedPaths]);
+
+ const sortValue = `${sortBy}-${sortDir}`;
+ const filterLabels = {
+ all: t('common.labels.all', 'All'),
+ folder: t('app.fileManager.folders', 'Folders'),
+ image: t('app.fileManager.images', 'Images'),
+ code: t('app.fileManager.code', 'Code'),
+ text: t('app.fileManager.documents', 'Documents'),
+ data: t('app.fileManager.data', 'Data'),
+ video: t('app.fileManager.videos', 'Videos'),
+ audio: t('app.fileManager.audio', 'Audio'),
+ archive: t('app.fileManager.archives', 'Archives'),
+ };
+ const handleSortChange = (value) => {
+ const [nextSortBy, nextSortDir] = value.split('-');
+ setSortBy(nextSortBy);
+ setSortDir(nextSortDir);
+ };
+
+ const selectedEntries = useMemo(
+ () => sortedFiltered.filter((e) => selectedPaths.has(e.path)),
+ [sortedFiltered, selectedPaths],
+ );
+
+ return {
+ breadcrumbs,
+ sortedFiltered,
+ filterCounts,
+ stats,
+ sortValue,
+ filterLabels,
+ handleSortChange,
+ selectedEntries,
+ };
+}
diff --git a/frontend/src/components/file-manager/hooks/useFilePreferences.js b/frontend/src/components/file-manager/hooks/useFilePreferences.js
new file mode 100644
index 00000000..ec15eb63
--- /dev/null
+++ b/frontend/src/components/file-manager/hooks/useFilePreferences.js
@@ -0,0 +1,33 @@
+import { useState } from 'react';
+import usePersistentState from '@/hooks/usePersistentState';
+import { STORAGE, isNarrowScreen } from '../preferences';
+export default function useFilePreferences() {
+ // ─── view prefs ──────────────────────────────────────
+ const [viewMode, setViewMode] = usePersistentState(STORAGE.viewMode, (v) => v || 'list');
+ const gridSize = 'md';
+ const [sortBy, setSortBy] = usePersistentState(STORAGE.sortBy, (v) => v || 'name');
+ const [sortDir, setSortDir] = usePersistentState(STORAGE.sortDir, (v) => v || 'asc');
+ const [activeFilter, setActiveFilter] = useState('all');
+
+ // ─── left sidebar ────────────────────────────────────
+ const [sidebarVisible, setSidebarVisible] = usePersistentState(STORAGE.sidebar, (v) =>
+ isNarrowScreen() ? false : v !== null ? v === 'true' : true,
+ );
+ const [treeCollapsed, setTreeCollapsed] = usePersistentState(STORAGE.treeCollapsed, (v) => v === 'true');
+
+ return {
+ viewMode,
+ setViewMode,
+ gridSize,
+ sortBy,
+ setSortBy,
+ sortDir,
+ setSortDir,
+ activeFilter,
+ setActiveFilter,
+ sidebarVisible,
+ setSidebarVisible,
+ treeCollapsed,
+ setTreeCollapsed,
+ };
+}
diff --git a/frontend/src/components/file-manager/hooks/useFileSelection.js b/frontend/src/components/file-manager/hooks/useFileSelection.js
new file mode 100644
index 00000000..eef15f44
--- /dev/null
+++ b/frontend/src/components/file-manager/hooks/useFileSelection.js
@@ -0,0 +1,47 @@
+import { useState } from 'react';
+export default function useFileSelection() {
+ // ─── selection ───────────────────────────────────────
+ const [selectedPaths, setSelectedPaths] = useState(new Set());
+ const [lastClickedPath, setLastClickedPath] = useState(null);
+ const [selectMode, setSelectMode] = useState(false);
+
+ // ─── selection ───────────────────────────────────────
+ const toggleSelect = (entry, e, sortedFiltered) => {
+ const path = entry.path;
+ if (e?.shiftKey && lastClickedPath) {
+ const list = sortedFiltered;
+ const a = list.findIndex((x) => x.path === lastClickedPath);
+ const b = list.findIndex((x) => x.path === path);
+ if (a >= 0 && b >= 0) {
+ const [from, to] = [Math.min(a, b), Math.max(a, b)];
+ const rangePaths = list.slice(from, to + 1).map((x) => x.path);
+ const next = new Set([...selectedPaths, ...rangePaths]);
+ setSelectedPaths(next);
+ setSelectMode(next.size > 0);
+ }
+ } else {
+ const next = new Set(selectedPaths);
+ if (next.has(path)) next.delete(path);
+ else next.add(path);
+ setSelectedPaths(next);
+ setSelectMode(next.size > 0);
+ setLastClickedPath(path);
+ }
+ };
+
+ const clearSelection = () => {
+ setSelectedPaths(new Set());
+ setSelectMode(false);
+ setLastClickedPath(null);
+ };
+
+ return {
+ selectedPaths,
+ setSelectedPaths,
+ selectMode,
+ setSelectMode,
+ setLastClickedPath,
+ toggleSelect,
+ clearSelection,
+ };
+}
diff --git a/frontend/src/components/file-manager/hooks/useFileTargets.js b/frontend/src/components/file-manager/hooks/useFileTargets.js
new file mode 100644
index 00000000..43f189a7
--- /dev/null
+++ b/frontend/src/components/file-manager/hooks/useFileTargets.js
@@ -0,0 +1,120 @@
+import { useState, useEffect, useMemo } from 'react';
+import { Globe, Boxes, SlidersHorizontal, FileText, Home } from 'lucide-react';
+import { api } from '@/services/api';
+// Demo rail shortcuts (Quick access) — one-click jumps to the paths people
+// actually visit on a ServerKit host. "Stack" starts at the default install
+// location and is re-pointed from /system/version's install_dir, so a custom
+// SERVERKIT_DIR install jumps to the real tree.
+const QUICK_ACCESS = [
+ { labelKey: 'app.fileManager.sites', label: 'Sites', path: '/var/www', icon: Globe },
+ { labelKey: 'app.fileManager.stack', label: 'Stack', path: '/opt/serverkit', icon: Boxes },
+ {
+ labelKey: 'app.fileManager.webConfig',
+ label: 'Web config',
+ path: '/etc/nginx',
+ icon: SlidersHorizontal,
+ },
+ { labelKey: 'common.labels.logs', label: 'Logs', path: '/var/log', icon: FileText },
+];
+
+// Remote-agent rails: the panel stack doesn't exist on an agent box, so link
+// the agent's own footprint instead. These paths are fixed by the agent
+// installers the panel serves (scripts/install.sh: /etc/serverkit-agent;
+// scripts/install.ps1: ProgramData\ServerKit\Agent) — agents run on the wire
+// with forward-slash paths, Windows included.
+const QUICK_ACCESS_AGENT = {
+ linux: [
+ { labelKey: 'app.fileManager.sites', label: 'Sites', path: '/var/www', icon: Globe },
+ { labelKey: 'app.fileManager.agent', label: 'Agent', path: '/etc/serverkit-agent', icon: Boxes },
+ {
+ labelKey: 'app.fileManager.webConfig',
+ label: 'Web config',
+ path: '/etc/nginx',
+ icon: SlidersHorizontal,
+ },
+ { labelKey: 'common.labels.logs', label: 'Logs', path: '/var/log', icon: FileText },
+ ],
+ windows: [
+ {
+ labelKey: 'app.fileManager.agent',
+ label: 'Agent',
+ path: 'C:/ProgramData/ServerKit/Agent',
+ icon: Boxes,
+ },
+ {
+ labelKey: 'app.fileManager.agentLogs',
+ label: 'Agent logs',
+ path: 'C:/ProgramData/ServerKit/Agent/logs',
+ icon: FileText,
+ },
+ { labelKey: 'app.fileManager.users', label: 'Users', path: 'C:/Users', icon: Home },
+ ],
+ darwin: [
+ { labelKey: 'app.fileManager.home', label: 'Home', path: '/Users', icon: Home },
+ { labelKey: 'common.labels.logs', label: 'Logs', path: '/var/log', icon: FileText },
+ ],
+};
+
+export default function useFileTargets({ target, isRemote, t }) {
+ // The "S3 bucket" target is offered only when an S3-compatible backup
+ // destination is configured (Connections → Storage, or the Backups page).
+ const [s3Available, setS3Available] = useState(false);
+ const s3Options = useMemo(
+ () => (s3Available ? [{ value: 's3', label: t('app.fileManager.s3Bucket', 'S3 bucket') }] : []),
+ [s3Available, t],
+ );
+ useEffect(() => {
+ let cancelled = false;
+ api.getStorageConfig()
+ .then((c) => {
+ if (cancelled) return;
+ const p = c?.provider;
+ setS3Available((p === 's3' || p === 'b2') && Boolean(c?.[p]?.bucket));
+ })
+ .catch(() => {});
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ // The "Stack" quick link tracks the panel's real install dir (custom
+ // SERVERKIT_DIR installs aren't at /opt/serverkit).
+ const [panelInstallDir, setPanelInstallDir] = useState('/opt/serverkit');
+ useEffect(() => {
+ let cancelled = false;
+ api.getVersion()
+ .then((v) => {
+ if (!cancelled && v?.install_dir) setPanelInstallDir(v.install_dir);
+ })
+ .catch(() => {});
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ // Per-target rail: agents get their OS's set (unknown os_type — an agent
+ // predating sysinfo reporting — is treated as linux, the historical
+ // behavior), with the agent's SELF-REPORTED config dir preferred over the
+ // installer convention when the agent sent one (system_info footprint);
+ // the local host gets the panel set with the resolved Stack dir.
+ const quickAccess = useMemo(() => {
+ if (isRemote) {
+ const os = (target.os_type || 'linux').toLowerCase();
+ const rail = QUICK_ACCESS_AGENT[os] || QUICK_ACCESS_AGENT.linux;
+ // Windows agents report filepath-style backslashes; the file
+ // wire protocol speaks forward slashes.
+ const configDir = target.agentConfigDir
+ ? target.agentConfigDir.replace(/\\/g, '/').replace(/\/+$/, '')
+ : null;
+ if (!configDir) return rail;
+ return rail.map((q) => {
+ if (q.label === 'Agent') return { ...q, path: configDir };
+ if (q.label === 'Agent logs') return { ...q, path: `${configDir}/logs` };
+ return q;
+ });
+ }
+ return QUICK_ACCESS.map((q) => (q.label === 'Stack' ? { ...q, path: panelInstallDir } : q));
+ }, [isRemote, target.os_type, target.agentConfigDir, panelInstallDir]);
+
+ return { s3Options, quickAccess };
+}
diff --git a/frontend/src/components/file-manager/hooks/useFileTransfers.js b/frontend/src/components/file-manager/hooks/useFileTransfers.js
new file mode 100644
index 00000000..9fb5fb79
--- /dev/null
+++ b/frontend/src/components/file-manager/hooks/useFileTransfers.js
@@ -0,0 +1,129 @@
+import { useState, useRef, useEffect } from 'react';
+export default function useFileTransfers({ fileApi, currentPath, remoteGuard, loadDirectory, toast, t }) {
+ // ─── upload ──────────────────────────────────────────
+ const [uploads, setUploads] = useState([]);
+ const [dragActive, setDragActive] = useState(false);
+ const fileInputRef = useRef(null);
+ const dragCounter = useRef(0);
+ const nextBatch = useRef(0);
+ const timers = useRef(new Set());
+ const mounted = useRef(true);
+ const active = useRef(null);
+ active.current = { fileApi, currentPath };
+ useEffect(() => {
+ mounted.current = true;
+ const pendingTimers = timers.current;
+ return () => {
+ mounted.current = false;
+ pendingTimers.forEach(clearTimeout);
+ };
+ }, []);
+
+ // ─── upload ──────────────────────────────────────────
+ const uploadFiles = async (files) => {
+ const fileList = Array.from(files);
+ if (fileList.length === 0) return;
+ if (remoteGuard('upload')) return;
+ const batch = ++nextBatch.current;
+ const queue = fileList.map((f, i) => ({
+ id: `${batch}-${i}`,
+ name: f.name,
+ size: f.size,
+ progress: 0,
+ status: 'pending',
+ }));
+ setUploads((p) => [...p, ...queue]);
+
+ let succeeded = 0;
+ for (let i = 0; i < fileList.length; i++) {
+ if (!mounted.current) return;
+ const file = fileList[i];
+ const itemId = queue[i].id;
+ try {
+ setUploads((p) => p.map((u) => (u.id === itemId ? { ...u, status: 'uploading' } : u)));
+ const doUpload = fileApi.upload;
+ await doUpload(currentPath, file, (progress) => {
+ if (!mounted.current) return;
+ setUploads((p) => p.map((u) => (u.id === itemId ? { ...u, progress } : u)));
+ });
+ if (!mounted.current) return;
+ setUploads((p) =>
+ p.map((u) => (u.id === itemId ? { ...u, status: 'done', progress: 100 } : u)),
+ );
+ succeeded++;
+ } catch (error) {
+ if (!mounted.current) return;
+ setUploads((p) =>
+ p.map((u) => (u.id === itemId ? { ...u, status: 'error', error: error.message } : u)),
+ );
+ }
+ }
+ if (succeeded > 0)
+ toast.success(
+ t('app.fileManager.uploadedFiles', {
+ count: fileList.length,
+ succeeded,
+ defaultValue_one: 'Uploaded {{succeeded}} of 1 file',
+ defaultValue_other: 'Uploaded {{succeeded}} of {{count}} files',
+ }),
+ );
+ if (active.current.fileApi === fileApi && active.current.currentPath === currentPath) {
+ loadDirectory(currentPath);
+ }
+ const ids = new Set(queue.map((item) => item.id));
+ const timer = setTimeout(() => {
+ timers.current.delete(timer);
+ setUploads((p) => p.filter((u) => !ids.has(u.id)));
+ }, 4000);
+ timers.current.add(timer);
+ };
+
+ const handleUploadInput = (e) => {
+ if (e.target.files) uploadFiles(e.target.files);
+ if (fileInputRef.current) fileInputRef.current.value = '';
+ };
+
+ const handleDragEnter = (e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ dragCounter.current += 1;
+ if (e.dataTransfer.items?.length > 0) setDragActive(true);
+ };
+ const handleDragLeave = (e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ dragCounter.current -= 1;
+ if (dragCounter.current === 0) setDragActive(false);
+ };
+ const handleDragOver = (e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ };
+ const handleDrop = (e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ dragCounter.current = 0;
+ setDragActive(false);
+ if (e.dataTransfer.files?.length > 0) uploadFiles(e.dataTransfer.files);
+ };
+
+ const activeUploads = uploads.filter((u) => u.status === 'uploading' || u.status === 'pending');
+ const totalUploadProgress =
+ activeUploads.length > 0
+ ? activeUploads.reduce((s, u) => s + u.progress, 0) / activeUploads.length
+ : 0;
+
+ return {
+ uploads,
+ setUploads,
+ dragActive,
+ fileInputRef,
+ handleUploadInput,
+ handleDragEnter,
+ handleDragLeave,
+ handleDragOver,
+ handleDrop,
+ activeUploads,
+ totalUploadProgress,
+ };
+}
diff --git a/frontend/src/components/file-manager/hooks/useFileTree.js b/frontend/src/components/file-manager/hooks/useFileTree.js
new file mode 100644
index 00000000..5c2827dd
--- /dev/null
+++ b/frontend/src/components/file-manager/hooks/useFileTree.js
@@ -0,0 +1,118 @@
+import { useState, useCallback, useEffect, useRef } from 'react';
+import usePersistentState from '@/hooks/usePersistentState';
+import { STORAGE, parseExpanded, serializeExpanded } from '../preferences';
+import { TREE_ROOTS } from '../fileTypes';
+export default function useFileTree({ fileApi, currentPath }) {
+ // ─── folder tree state ───────────────────────────────
+ const [treeExpanded, setTreeExpanded] = usePersistentState(
+ STORAGE.expanded,
+ parseExpanded,
+ serializeExpanded,
+ );
+ const [treeCache, setTreeCache] = useState(new Map());
+ const [treeLoading, setTreeLoading] = useState(new Set());
+ const activeApi = useRef(fileApi);
+ activeApi.current = fileApi;
+ const mounted = useRef(true);
+ useEffect(() => {
+ mounted.current = true;
+ return () => {
+ mounted.current = false;
+ };
+ }, []);
+ useEffect(() => {
+ setTreeCache(new Map());
+ setTreeLoading(new Set());
+ }, [fileApi]);
+
+ const refreshTree = async (path) => {
+ if (!treeCache.has(path)) return;
+ try {
+ const data = await fileApi.browse(path, false);
+ if (!mounted.current || activeApi.current !== fileApi) return;
+ const folders = (data.entries || data.files || [])
+ .filter((e) => e.is_dir)
+ .map(({ path, name }) => ({ path, name }));
+ setTreeCache((c) => new Map(c).set(path, folders));
+ } catch {
+ /* A failed refresh leaves the last known tree visible. */
+ }
+ };
+
+ // ─── tree expand/collapse ────────────────────────────
+ const toggleTreeExpand = useCallback(
+ async (path) => {
+ if (treeExpanded.has(path)) {
+ const next = new Set(treeExpanded);
+ next.delete(path);
+ setTreeExpanded(next);
+ return;
+ }
+ if (!treeCache.has(path)) {
+ setTreeLoading((s) => {
+ const n = new Set(s);
+ n.add(path);
+ return n;
+ });
+ try {
+ const data = await fileApi.browse(path, false);
+ if (!mounted.current || activeApi.current !== fileApi) return;
+ const entries = data.entries || data.files || [];
+ const folders = entries
+ .filter((e) => e.is_dir)
+ .map((e) => ({
+ path: e.path,
+ name: e.name,
+ }));
+ setTreeCache((c) => {
+ const n = new Map(c);
+ n.set(path, folders);
+ return n;
+ });
+ } catch {
+ if (!mounted.current || activeApi.current !== fileApi) return;
+ setTreeCache((c) => {
+ const n = new Map(c);
+ n.set(path, []);
+ return n;
+ });
+ } finally {
+ if (mounted.current && activeApi.current === fileApi) {
+ setTreeLoading((s) => {
+ const n = new Set(s);
+ n.delete(path);
+ return n;
+ });
+ }
+ }
+ }
+ setTreeExpanded((s) => {
+ const n = new Set(s);
+ n.add(path);
+ return n;
+ });
+ },
+ [treeExpanded, treeCache, fileApi, setTreeExpanded],
+ );
+
+ // Auto-expand the tree along the current path so the active row is visible.
+ useEffect(() => {
+ const parts = currentPath.split('/').filter(Boolean);
+ const ancestors = [];
+ let acc = '';
+ for (const p of parts) {
+ acc += '/' + p;
+ ancestors.push(acc);
+ }
+ ancestors.forEach((a) => {
+ const isUnderRoot = TREE_ROOTS.some(
+ (r) => a === r.path || a.startsWith(r.path + '/') || r.path.startsWith(a + '/'),
+ );
+ if (isUnderRoot && !treeExpanded.has(a) && a !== currentPath) {
+ toggleTreeExpand(a);
+ }
+ });
+ }, [currentPath]); // eslint-disable-line react-hooks/exhaustive-deps
+
+ return { treeExpanded, treeCache, refreshTree, treeLoading, toggleTreeExpand };
+}
diff --git a/frontend/src/components/file-manager/hooks/useFileVolumes.js b/frontend/src/components/file-manager/hooks/useFileVolumes.js
new file mode 100644
index 00000000..70a7b5a9
--- /dev/null
+++ b/frontend/src/components/file-manager/hooks/useFileVolumes.js
@@ -0,0 +1,43 @@
+import { useState, useEffect, useMemo } from 'react';
+import { api } from '@/services/api';
+export default function useFileVolumes(currentPath) {
+ // ─── disk ────────────────────────────────────────────
+ const [diskMounts, setDiskMounts] = useState([]);
+ const [diskLastUpdated, setDiskLastUpdated] = useState(null);
+ const [diskLoading, setDiskLoading] = useState(false);
+
+ // ─── disk mounts ─────────────────────────────────────
+ const loadDiskMounts = async () => {
+ setDiskLoading(true);
+ try {
+ const data = await api.getAllDiskMounts();
+ setDiskMounts(data.mounts || []);
+ setDiskLastUpdated(new Date());
+ } catch (e) {
+ console.error('Failed to load disk mounts:', e);
+ } finally {
+ setDiskLoading(false);
+ }
+ };
+
+ const activeMount = useMemo(
+ () =>
+ diskMounts
+ .filter((mount) => {
+ const mountPath = mount.mountpoint || '/';
+ if (mountPath === '/') return currentPath.startsWith('/');
+ return (
+ currentPath === mountPath ||
+ currentPath.startsWith(`${mountPath.replace(/\/$/, '')}/`)
+ );
+ })
+ .sort((a, b) => (b.mountpoint || '/').length - (a.mountpoint || '/').length)[0] || null,
+ [currentPath, diskMounts],
+ );
+
+ useEffect(() => {
+ loadDiskMounts();
+ }, []);
+
+ return { diskMounts, diskLastUpdated, diskLoading, loadDiskMounts, activeMount };
+}
diff --git a/frontend/src/components/file-manager/hooks/useImagePreview.js b/frontend/src/components/file-manager/hooks/useImagePreview.js
new file mode 100644
index 00000000..0e70d082
--- /dev/null
+++ b/frontend/src/components/file-manager/hooks/useImagePreview.js
@@ -0,0 +1,27 @@
+import { useEffect, useState } from 'react';
+
+// Blob lifetime belongs to the mounted thumbnail, not to the storage adapter.
+export default function useImagePreview(fileApi, path) {
+ const [image, setImage] = useState(null);
+ useEffect(() => {
+ let cancelled = false;
+ let blobUrl;
+ setImage(null);
+ if (!fileApi?.supports('preview')) return undefined;
+ fileApi
+ .preview(path)
+ .then((result) => {
+ if (cancelled) return;
+ const url = result.blob ? (blobUrl = URL.createObjectURL(result.blob)) : result.url;
+ setImage({ fileApi, path, url });
+ })
+ .catch(() => {
+ /* Render the supplied fallback on failure. */
+ });
+ return () => {
+ cancelled = true;
+ if (blobUrl) URL.revokeObjectURL(blobUrl);
+ };
+ }, [fileApi, path]);
+ return image?.fileApi === fileApi && image?.path === path ? image.url : null;
+}
diff --git a/frontend/src/components/file-manager/preferences.js b/frontend/src/components/file-manager/preferences.js
new file mode 100644
index 00000000..e6ccd627
--- /dev/null
+++ b/frontend/src/components/file-manager/preferences.js
@@ -0,0 +1,19 @@
+export const STORAGE = {
+ sidebar: 'serverkit-fm-sidebar',
+ treeCollapsed: 'serverkit-fm-tree-collapsed',
+ expanded: 'serverkit-fm-tree-expanded',
+ viewMode: 'serverkit-fm-view-mode',
+ sortBy: 'serverkit-fm-sort-by',
+ sortDir: 'serverkit-fm-sort-dir',
+};
+
+export const serializeExpanded = (set) => JSON.stringify([...set]);
+export const parseExpanded = (stored) => {
+ try {
+ return stored ? new Set(JSON.parse(stored)) : new Set();
+ } catch {
+ return new Set();
+ }
+};
+export const isNarrowScreen = () =>
+ typeof window !== 'undefined' && window.matchMedia('(max-width: 1024px)').matches;
diff --git a/frontend/src/pages/FileManager.jsx b/frontend/src/pages/FileManager.jsx
index eb1c1481..40cf619b 100644
--- a/frontend/src/pages/FileManager.jsx
+++ b/frontend/src/pages/FileManager.jsx
@@ -1,133 +1,40 @@
-import { useState, useEffect, useRef, useMemo, useCallback } from 'react';
+import useFileListingModel, { FILTER_OPTIONS } from '../components/file-manager/hooks/useFileListingModel';
+import FileManagerDialogs from '../components/file-manager/FileManagerDialogs';
+import FileManagerStatus from '../components/file-manager/FileManagerStatus';
+import FileUploadTray from '../components/file-manager/FileUploadTray';
+import FileManagerListing from '../components/file-manager/FileManagerListing';
+import FileManagerToolbar from '../components/file-manager/FileManagerToolbar';
+import FileManagerSidebar from '../components/file-manager/FileManagerSidebar';
+import useFileActions from '../components/file-manager/hooks/useFileActions';
+import useFileEditor from '../components/file-manager/hooks/useFileEditor';
+import useDirectoryBrowser from '../components/file-manager/hooks/useDirectoryBrowser';
+import useFileTransfers from '../components/file-manager/hooks/useFileTransfers';
+import useFileVolumes from '../components/file-manager/hooks/useFileVolumes';
+import useFileTree from '../components/file-manager/hooks/useFileTree';
+import useFileSelection from '../components/file-manager/hooks/useFileSelection';
+import useFilePreferences from '../components/file-manager/hooks/useFilePreferences';
+import useFileTargets from '../components/file-manager/hooks/useFileTargets';
+import { useState, useEffect, useMemo, useCallback } from 'react';
import { api } from '../services/api';
import { createFileAdapter } from '../components/file-manager/fileAdapter';
import { useToast } from '../contexts/useToast.js';
-import ConfirmDialog from '../components/ConfirmDialog';
-import EmptyState from '../components/EmptyState';
-import ErrorState from '../components/ErrorState';
-import {
- Folder, FolderOpen, File, Upload, FolderPlus,
- ArrowLeft, ArrowRight, ArrowUp, Search, X, RefreshCw, Eye, EyeOff,
- Download, Edit3, Trash2, ChevronDown, ChevronRight,
- HardDrive, Clock, PanelLeftClose, PanelLeftOpen,
- LayoutGrid, List, Home, CloudUpload,
- Check, Copy, ArrowUpDown, Zap, Globe, Boxes, SlidersHorizontal, FileText,
- FolderTree as FolderTreeIcon, Terminal,
-} from 'lucide-react';
-import { useNavigate, useSearchParams } from 'react-router-dom';
+
+import { Upload, FolderPlus, X, Download, Edit3, Trash2, Check, Copy, Terminal } from 'lucide-react';
+import { useNavigate } from 'react-router-dom';
import { Button } from '@/components/ui/button';
-import FolderTree from '../components/file-manager/FolderTree';
-import FileCard from '../components/file-manager/FileCard';
-import FileRow from '../components/file-manager/FileRow';
import PreviewDrawer from '../components/file-manager/PreviewDrawer';
import ContextMenu from '../components/file-manager/ContextMenu';
-import { NamePromptModal, PermissionsModal } from '../components/file-manager/FileDialogs';
-import ServerPicker from '../components/ServerPicker';
-import { serverTarget, targetServerId } from '../utils/serverTarget';
-import { Select, SelectTrigger, SelectContent, SelectItem, SelectValue } from '@/components/ui/select';
-import { TREE_ROOTS, getFileType, formatBytes } from '../components/file-manager/fileTypes';
+
+import { formatBytes } from '../components/file-manager/fileTypes';
import { useClipboard } from '@/hooks/useClipboard';
import { useTranslation } from 'react-i18next';
import { useTopbarActions } from '@/hooks/useTopbarActions';
-import { errorReason } from '@/utils/errorMessage';
-import usePersistentState from '@/hooks/usePersistentState';
import { useStableHandler } from '@/hooks/useStableHandler';
-import { formatTime } from '@/utils/intl';
-
-// Demo rail shortcuts (Quick access) — one-click jumps to the paths people
-// actually visit on a ServerKit host. "Stack" starts at the default install
-// location and is re-pointed from /system/version's install_dir, so a custom
-// SERVERKIT_DIR install jumps to the real tree.
-const QUICK_ACCESS = [
- { labelKey: 'app.fileManager.sites', label: 'Sites', path: '/var/www', icon: Globe },
- { labelKey: 'app.fileManager.stack', label: 'Stack', path: '/opt/serverkit', icon: Boxes },
- { labelKey: 'app.fileManager.webConfig', label: 'Web config', path: '/etc/nginx', icon: SlidersHorizontal },
- { labelKey: 'common.labels.logs', label: 'Logs', path: '/var/log', icon: FileText },
-];
-
-// Remote-agent rails: the panel stack doesn't exist on an agent box, so link
-// the agent's own footprint instead. These paths are fixed by the agent
-// installers the panel serves (scripts/install.sh: /etc/serverkit-agent;
-// scripts/install.ps1: ProgramData\ServerKit\Agent) — agents run on the wire
-// with forward-slash paths, Windows included.
-const QUICK_ACCESS_AGENT = {
- linux: [
- { labelKey: 'app.fileManager.sites', label: 'Sites', path: '/var/www', icon: Globe },
- { labelKey: 'app.fileManager.agent', label: 'Agent', path: '/etc/serverkit-agent', icon: Boxes },
- { labelKey: 'app.fileManager.webConfig', label: 'Web config', path: '/etc/nginx', icon: SlidersHorizontal },
- { labelKey: 'common.labels.logs', label: 'Logs', path: '/var/log', icon: FileText },
- ],
- windows: [
- { labelKey: 'app.fileManager.agent', label: 'Agent', path: 'C:/ProgramData/ServerKit/Agent', icon: Boxes },
- { labelKey: 'app.fileManager.agentLogs', label: 'Agent logs', path: 'C:/ProgramData/ServerKit/Agent/logs', icon: FileText },
- { labelKey: 'app.fileManager.users', label: 'Users', path: 'C:/Users', icon: Home },
- ],
- darwin: [
- { labelKey: 'app.fileManager.home', label: 'Home', path: '/Users', icon: Home },
- { labelKey: 'common.labels.logs', label: 'Logs', path: '/var/log', icon: FileText },
- ],
-};
-
-function deriveParent(path) {
- if (!path || path === '/' || path === '') return null;
- // A Windows drive root ("C:/" or "C:") sits directly under the agent's
- // drive list, which the agent serves for the "/" path. Remote agents
- // emit forward-slash paths on the wire, so we only ever see "/" here.
- if (/^[A-Za-z]:\/?$/.test(path)) return '/';
- const trimmed = path.replace(/\/+$/, '');
- const idx = trimmed.lastIndexOf('/');
- if (idx <= 0) return '/';
- const parent = trimmed.slice(0, idx);
- // Keep a bare drive letter as a drive root ("C:" -> "C:/") so navigating
- // up doesn't hit Windows' "current directory on C:" semantics.
- if (/^[A-Za-z]:$/.test(parent)) return parent + '/';
- return parent;
-}
-
-function mountDisplayName(mount) {
- if (!mount?.mountpoint || mount.mountpoint === '/') return null;
- const parts = mount.mountpoint.split('/').filter(Boolean);
- const leaf = parts[parts.length - 1] || mount.mountpoint;
- return leaf === 'docker-desktop-user-distro' ? 'docker-desktop' : leaf;
-}
-
-const STORAGE = {
- sidebar: 'serverkit-fm-sidebar',
- treeCollapsed: 'serverkit-fm-tree-collapsed',
- expanded: 'serverkit-fm-tree-expanded',
- viewMode: 'serverkit-fm-view-mode',
- sortBy: 'serverkit-fm-sort-by',
- sortDir: 'serverkit-fm-sort-dir',
-};
-
-const serializeExpanded = (set) => JSON.stringify([...set]);
-const parseExpanded = (stored) => {
- try {
- return stored ? new Set(JSON.parse(stored)) : new Set();
- } catch {
- return new Set();
- }
-};
-const isNarrowScreen = () => typeof window !== 'undefined'
- && window.matchMedia('(max-width: 1024px)').matches;
-
-const FILTER_OPTIONS = [
- { id: 'all', labelKey: 'common.labels.all', label: 'All' },
- { id: 'folder', labelKey: 'app.fileManager.folders', label: 'Folders' },
- { id: 'image', labelKey: 'app.fileManager.images', label: 'Images' },
- { id: 'code', labelKey: 'app.fileManager.code', label: 'Code' },
- { id: 'text', labelKey: 'app.fileManager.documents', label: 'Documents' },
- { id: 'data', labelKey: 'app.fileManager.data', label: 'Data' },
- { id: 'video', labelKey: 'app.fileManager.videos', label: 'Videos' },
- { id: 'audio', labelKey: 'app.fileManager.audio', label: 'Audio' },
- { id: 'archive', labelKey: 'app.fileManager.archives', label: 'Archives' },
-];
function FileManager() {
const { t } = useTranslation();
const navigate = useNavigate();
- const [searchParams, setSearchParams] = useSearchParams();
// ─── target ──────────────────────────────────────────
// Local panel host by default. Switching to an agent re-routes the
@@ -136,640 +43,182 @@ function FileManager() {
const [target, setTarget] = useState({ kind: 'local' });
const isRemote = target.kind === 'agent';
const isS3 = target.kind === 's3';
+ const fileApi = useMemo(() => createFileAdapter(api, target), [target]);
const { copy: copyText } = useClipboard({
successMessage: t('app.fileManager.pathCopied', 'Path copied'),
errorMessage: t('app.fileManager.couldNotCopyPath', "Couldn't copy the path."),
});
- const previousTargetRef = useRef({ kind: 'local', server_id: null });
-
- // The "S3 bucket" target is offered only when an S3-compatible backup
- // destination is configured (Connections → Storage, or the Backups page).
- const [s3Available, setS3Available] = useState(false);
- const s3Options = useMemo(
- () => (s3Available ? [{ value: 's3', label: t('app.fileManager.s3Bucket', 'S3 bucket') }] : []),
- [s3Available, t],
- );
- useEffect(() => {
- let cancelled = false;
- api.getStorageConfig()
- .then((c) => {
- if (cancelled) return;
- const p = c?.provider;
- setS3Available((p === 's3' || p === 'b2') && Boolean(c?.[p]?.bucket));
- })
- .catch(() => {});
- return () => { cancelled = true; };
- }, []);
-
- // The "Stack" quick link tracks the panel's real install dir (custom
- // SERVERKIT_DIR installs aren't at /opt/serverkit).
- const [panelInstallDir, setPanelInstallDir] = useState('/opt/serverkit');
- useEffect(() => {
- let cancelled = false;
- api.getVersion()
- .then((v) => {
- if (!cancelled && v?.install_dir) setPanelInstallDir(v.install_dir);
- })
- .catch(() => {});
- return () => { cancelled = true; };
- }, []);
-
- // Per-target rail: agents get their OS's set (unknown os_type — an agent
- // predating sysinfo reporting — is treated as linux, the historical
- // behavior), with the agent's SELF-REPORTED config dir preferred over the
- // installer convention when the agent sent one (system_info footprint);
- // the local host gets the panel set with the resolved Stack dir.
- const quickAccess = useMemo(() => {
- if (isRemote) {
- const os = (target.os_type || 'linux').toLowerCase();
- const rail = QUICK_ACCESS_AGENT[os] || QUICK_ACCESS_AGENT.linux;
- // Windows agents report filepath-style backslashes; the file
- // wire protocol speaks forward slashes.
- const configDir = target.agentConfigDir
- ? target.agentConfigDir.replace(/\\/g, '/').replace(/\/+$/, '')
- : null;
- if (!configDir) return rail;
- return rail.map((q) => {
- if (q.label === 'Agent') return { ...q, path: configDir };
- if (q.label === 'Agent logs') return { ...q, path: `${configDir}/logs` };
- return q;
- });
- }
- return QUICK_ACCESS.map((q) =>
- q.label === 'Stack' ? { ...q, path: panelInstallDir } : q
- );
- }, [isRemote, target.os_type, target.agentConfigDir, panelInstallDir]);
-
- // ─── core ────────────────────────────────────────────
- const [currentPath, setCurrentPath] = useState(() => searchParams.get('path') || '/home');
- const [entries, setEntries] = useState([]);
- const [parentPath, setParentPath] = useState(null);
- const [loading, setLoading] = useState(true);
- // The open folder's own load failure, shown in the listing in place of
- // "This folder is empty". Navigation into a folder that fails still
- // toasts and steps back, since the previous folder is what stays shown.
- const [dirError, setDirError] = useState(null);
- const [showHidden, setShowHidden] = useState(false);
-
- // ─── search ──────────────────────────────────────────
- const [searchQuery, setSearchQuery] = useState('');
- const [searchResults, setSearchResults] = useState(null);
-
- // ─── selection ───────────────────────────────────────
- const [selectedPaths, setSelectedPaths] = useState(new Set());
- const [lastClickedPath, setLastClickedPath] = useState(null);
- const [selectMode, setSelectMode] = useState(false);
-
- // ─── preview ─────────────────────────────────────────
- const [previewFile, setPreviewFile] = useState(null);
- const [fileContent, setFileContent] = useState('');
- const [editing, setEditing] = useState(false);
-
- // ─── modals ──────────────────────────────────────────
- // { kind: 'newFolder' } | { kind: 'rename', entry } | { kind: 'permissions', entry } | null
- const [dialog, setDialog] = useState(null);
- const closeDialog = () => setDialog(null);
- const [confirmDialog, setConfirmDialog] = useState(null);
-
- // ─── upload ──────────────────────────────────────────
- const [uploads, setUploads] = useState([]);
- const [dragActive, setDragActive] = useState(false);
- const fileInputRef = useRef(null);
- const dragCounter = useRef(0);
-
- // ─── view prefs ──────────────────────────────────────
- const [viewMode, setViewMode] = usePersistentState(STORAGE.viewMode, (v) => v || 'list');
- const gridSize = 'md';
- const [sortBy, setSortBy] = usePersistentState(STORAGE.sortBy, (v) => v || 'name');
- const [sortDir, setSortDir] = usePersistentState(STORAGE.sortDir, (v) => v || 'asc');
- const [activeFilter, setActiveFilter] = useState('all');
-
- // ─── left sidebar ────────────────────────────────────
- const [sidebarVisible, setSidebarVisible] = usePersistentState(
- STORAGE.sidebar, (v) => (isNarrowScreen() ? false : v !== null ? v === 'true' : true));
- const [treeCollapsed, setTreeCollapsed] = usePersistentState(STORAGE.treeCollapsed, (v) => v === 'true');
-
- // ─── folder tree state ───────────────────────────────
- const [treeExpanded, setTreeExpanded] = usePersistentState(STORAGE.expanded, parseExpanded, serializeExpanded);
- const [treeCache, setTreeCache] = useState(new Map());
- const [treeLoading, setTreeLoading] = useState(new Set());
- // ─── disk ────────────────────────────────────────────
- const [diskMounts, setDiskMounts] = useState([]);
- const [diskLastUpdated, setDiskLastUpdated] = useState(null);
- const [diskLoading, setDiskLoading] = useState(false);
-
- // ─── history ─────────────────────────────────────────
- const [history, setHistory] = useState(['/home']);
- const [historyIdx, setHistoryIdx] = useState(0);
- const navByHistory = useRef(false);
- const lastValidPathRef = useRef('/home');
- // Only the newest browse may write: a slow answer for the folder the
- // user just left used to land last and navigate them back to it.
- const loadSeqRef = useRef(0);
+ const { s3Options, quickAccess } = useFileTargets({ target, isRemote, t });
+
+ const {
+ selectedPaths,
+ setSelectedPaths,
+ selectMode,
+ setSelectMode,
+ setLastClickedPath,
+ toggleSelect,
+ clearSelection,
+ } = useFileSelection();
+ const handleToggleSelect = (entry, event) => toggleSelect(entry, event, sortedFiltered);
+
+ const {
+ viewMode,
+ setViewMode,
+ gridSize,
+ sortBy,
+ setSortBy,
+ sortDir,
+ setSortDir,
+ activeFilter,
+ setActiveFilter,
+ sidebarVisible,
+ setSidebarVisible,
+ treeCollapsed,
+ setTreeCollapsed,
+ } = useFilePreferences();
// ─── context menu ────────────────────────────────────
const [contextMenu, setContextMenu] = useState(null);
const toast = useToast();
- useEffect(() => {
- const pathFromUrl = searchParams.get('path') || '/home';
- if (pathFromUrl !== currentPath) {
- setCurrentPath(pathFromUrl);
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [searchParams]);
-
- useEffect(() => {
- const pathFromUrl = searchParams.get('path') || '/home';
- if (pathFromUrl === currentPath) return;
-
- const nextParams = new URLSearchParams(searchParams);
- nextParams.set('path', currentPath);
- setSearchParams(nextParams, { replace: true });
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [currentPath]);
-
- const fileApi = useMemo(() => createFileAdapter(api, target), [target]);
-
- const remoteGuard = useCallback((op) => {
- if (isRemote && !fileApi.supports(op)) {
- toast.error(t('app.fileManager.isNotYetSupportedOnRemote', '{{op}} is not yet supported on remote agents', { op: op }));
- return true;
- }
- if (isS3 && !fileApi.supports(op)) {
- toast.error(t('app.fileManager.isnTAvailableOnS3Buckets', '{{op}} isn\'t available on S3 buckets', { op: op }));
- return true;
- }
- return false;
- }, [isRemote, isS3, fileApi, t, toast]);
-
- // When the user switches to a remote target, jump to its first
- // advertised allowed_path so they don't see a "panel /home" view
- // that doesn't exist on the remote host.
- useEffect(() => {
- const previousTarget = previousTargetRef.current;
- const targetChanged = previousTarget.kind !== target.kind || previousTarget.server_id !== target.server_id;
- previousTargetRef.current = { kind: target.kind, server_id: target.server_id };
-
- if (!targetChanged) return;
-
- if (target.kind === 'agent' && Array.isArray(target.allowedPaths) && target.allowedPaths.length > 0) {
- setCurrentPath(target.allowedPaths[0]);
- } else if (target.kind === 's3') {
- setCurrentPath('/');
- } else if (target.kind === 'local') {
- setCurrentPath('/home');
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [target.kind, target.server_id]);
-
- // ─── load directory ──────────────────────────────────
- const loadDirectory = useCallback(async (path) => {
- const seq = ++loadSeqRef.current;
- setLoading(true);
- setSearchResults(null);
- setSelectedPaths(new Set());
- setSelectMode(false);
- try {
- const data = await fileApi.browse(path, showHidden);
- if (seq !== loadSeqRef.current) return;
- // Agent file:list returns {path, files: [...]} with a flat
- // entry shape; panel browseFiles returns {path, parent,
- // entries: [...]}. Normalize so the UI can keep using
- // entries/parent.
- const entriesList = data.entries || data.files || [];
- setEntries(entriesList);
- setParentPath(data.parent ?? deriveParent(data.path || path));
- setCurrentPath(data.path || path);
- lastValidPathRef.current = data.path || path;
- setDirError(null);
- } catch (error) {
- if (seq !== loadSeqRef.current) return;
- if (path !== lastValidPathRef.current) {
- toast.error(t('app.fileManager.failedToLoadDirectory', "Couldn't load the folder. {{message}}", { message: errorReason(error) }));
- setCurrentPath(lastValidPathRef.current);
- } else {
- setEntries([]);
- setDirError(error);
- }
- } finally {
- if (seq === loadSeqRef.current) setLoading(false);
- }
- }, [fileApi, showHidden, toast, t]);
-
- useEffect(() => {
- loadDirectory(currentPath);
- // fileApi, not loadDirectory: switching target must reload even when the
- // path stays the same, but loadDirectory also changes with toast/t.
- }, [currentPath, showHidden, fileApi]); // eslint-disable-line react-hooks/exhaustive-deps
-
- useEffect(() => {
- loadDiskMounts();
- }, []);
-
- // history tracking
- useEffect(() => {
- if (navByHistory.current) {
- navByHistory.current = false;
- return;
- }
- setHistory((h) => {
- const trimmed = h.slice(0, historyIdx + 1);
- if (trimmed[trimmed.length - 1] === currentPath) return h;
- return [...trimmed, currentPath];
- });
- setHistoryIdx((i) => (history[i] === currentPath ? i : i + 1));
- }, [currentPath]); // eslint-disable-line react-hooks/exhaustive-deps
-
- // ─── disk mounts ─────────────────────────────────────
- const loadDiskMounts = async () => {
- setDiskLoading(true);
- try {
- const data = await api.getAllDiskMounts();
- setDiskMounts(data.mounts || []);
- setDiskLastUpdated(new Date());
- } catch (e) {
- console.error('Failed to load disk mounts:', e);
- } finally {
- setDiskLoading(false);
- }
- };
-
- // ─── tree expand/collapse ────────────────────────────
- const toggleTreeExpand = useCallback(async (path) => {
- if (treeExpanded.has(path)) {
- const next = new Set(treeExpanded);
- next.delete(path);
- setTreeExpanded(next);
- return;
- }
- if (!treeCache.has(path)) {
- setTreeLoading((s) => { const n = new Set(s); n.add(path); return n; });
- try {
- const data = await fileApi.browse(path, false);
- const entries = data.entries || data.files || [];
- const folders = entries.filter((e) => e.is_dir).map((e) => ({
- path: e.path,
- name: e.name,
- }));
- setTreeCache((c) => { const n = new Map(c); n.set(path, folders); return n; });
- } catch {
- setTreeCache((c) => { const n = new Map(c); n.set(path, []); return n; });
- } finally {
- setTreeLoading((s) => { const n = new Set(s); n.delete(path); return n; });
- }
- }
- setTreeExpanded((s) => { const n = new Set(s); n.add(path); return n; });
- }, [treeExpanded, treeCache, fileApi, setTreeExpanded]);
-
- // Auto-expand the tree along the current path so the active row is visible.
- useEffect(() => {
- const parts = currentPath.split('/').filter(Boolean);
- const ancestors = [];
- let acc = '';
- for (const p of parts) {
- acc += '/' + p;
- ancestors.push(acc);
- }
- ancestors.forEach((a) => {
- const isUnderRoot = TREE_ROOTS.some((r) => a === r.path || a.startsWith(r.path + '/') || r.path.startsWith(a + '/'));
- if (isUnderRoot && !treeExpanded.has(a) && a !== currentPath) {
- toggleTreeExpand(a);
- }
- });
- }, [currentPath]); // eslint-disable-line react-hooks/exhaustive-deps
-
- // ─── search ──────────────────────────────────────────
- const handleSearch = async () => {
- if (remoteGuard('search')) { setSearchResults([]); return; }
- if (!searchQuery.trim()) { setSearchResults(null); return; }
- setLoading(true);
- try {
- const data = await fileApi.search(currentPath, searchQuery);
- setSearchResults(data.results || []);
- } catch (error) {
- toast.error(t('app.fileManager.searchFailed', "Couldn't search. {{message}}", { message: errorReason(error) }));
- } finally {
- setLoading(false);
- }
- };
-
- // ─── navigation ──────────────────────────────────────
- const navigateTo = (path) => {
- setPreviewFile(null);
- setEditing(false);
- setCurrentPath(path);
- };
-
- const goBack = () => {
- if (historyIdx > 0) {
- navByHistory.current = true;
- setHistoryIdx(historyIdx - 1);
- setCurrentPath(history[historyIdx - 1]);
- }
- };
- const goForward = () => {
- if (historyIdx < history.length - 1) {
- navByHistory.current = true;
- setHistoryIdx(historyIdx + 1);
- setCurrentPath(history[historyIdx + 1]);
- }
- };
- const goUp = () => parentPath && navigateTo(parentPath);
-
- const handleOpen = async (entry) => {
- if (entry.is_dir) {
- navigateTo(entry.path);
- } else {
- setPreviewFile(entry);
- setEditing(false);
- if (entry.is_editable) {
- try {
- const data = await fileApi.read(entry.path);
- setFileContent(data.content);
- } catch (error) {
- toast.error(t('app.fileManager.failedToReadFile', "Couldn't read the file. {{message}}", { message: errorReason(error) }));
- }
+ const remoteGuard = useCallback(
+ (op) => {
+ if (isRemote && !fileApi.supports(op)) {
+ toast.error(
+ t(
+ 'app.fileManager.isNotYetSupportedOnRemote',
+ '{{op}} is not yet supported on remote agents',
+ { op: op },
+ ),
+ );
+ return true;
}
- }
- };
-
- // ─── selection ───────────────────────────────────────
- const handleToggleSelect = (entry, e) => {
- const path = entry.path;
- if (e?.shiftKey && lastClickedPath) {
- const list = sortedFiltered;
- const a = list.findIndex((x) => x.path === lastClickedPath);
- const b = list.findIndex((x) => x.path === path);
- if (a >= 0 && b >= 0) {
- const [from, to] = [Math.min(a, b), Math.max(a, b)];
- const rangePaths = list.slice(from, to + 1).map((x) => x.path);
- const next = new Set([...selectedPaths, ...rangePaths]);
- setSelectedPaths(next);
- setSelectMode(next.size > 0);
+ if (isS3 && !fileApi.supports(op)) {
+ toast.error(
+ t('app.fileManager.isnTAvailableOnS3Buckets', "{{op}} isn't available on S3 buckets", {
+ op: op,
+ }),
+ );
+ return true;
}
- } else {
- const next = new Set(selectedPaths);
- if (next.has(path)) next.delete(path); else next.add(path);
- setSelectedPaths(next);
- setSelectMode(next.size > 0);
- setLastClickedPath(path);
- }
- };
-
- const clearSelection = () => {
- setSelectedPaths(new Set());
- setSelectMode(false);
- };
+ return false;
+ },
+ [isRemote, isS3, fileApi, t, toast],
+ );
- // ─── ops ─────────────────────────────────────────────
- const handleSaveFile = async () => {
- if (!previewFile) return;
- try {
- await fileApi.write(previewFile.path, fileContent);
- toast.success(t('app.fileManager.fileSaved', 'File saved'));
+ const {
+ previewFile,
+ setPreviewFile,
+ fileContent,
+ setFileContent,
+ editing,
+ setEditing,
+ openFile,
+ handleSaveFile,
+ } = useFileEditor({ fileApi, toast, t, onSaved: () => loadDirectory(currentPath) });
+
+ const {
+ currentPath,
+ entries,
+ parentPath,
+ loading,
+ dirError,
+ showHidden,
+ setShowHidden,
+ searchQuery,
+ setSearchQuery,
+ searchResults,
+ clearSearch,
+ history,
+ historyIdx,
+ loadDirectory,
+ handleSearch,
+ navigateTo,
+ goBack,
+ goForward,
+ goUp,
+ } = useDirectoryBrowser({
+ fileApi,
+ target,
+ resetSelection: clearSelection,
+ onNavigate: () => {
+ setPreviewFile(null);
setEditing(false);
- loadDirectory(currentPath);
- } catch (error) {
- toast.error(t('app.fileManager.failedToSave', "Couldn't save. {{message}}", { message: errorReason(error) }));
- }
- };
-
- const handleCreateFolder = async (name) => {
- if (remoteGuard('create folder')) return;
- try {
- await fileApi['create folder'](`${currentPath}/${name}`);
- toast.success(t('app.fileManager.folderCreated', 'Folder created'));
- closeDialog();
- loadDirectory(currentPath);
- // Refresh tree cache for parent so the new folder appears in the tree
- const parent = currentPath;
- if (treeCache.has(parent)) {
- try {
- const data = await fileApi.browse(parent, false);
- const folders = (data.entries || []).filter((e) => e.is_dir).map((e) => ({ path: e.path, name: e.name }));
- setTreeCache((c) => { const n = new Map(c); n.set(parent, folders); return n; });
- } catch { /* ignore */ }
- }
- } catch (error) {
- toast.error(t('app.fileManager.failedToCreateFolder', "Couldn't create the folder. {{message}}", { message: errorReason(error) }));
- }
- };
-
- const handleDelete = (target) => {
- const items = Array.isArray(target) ? target : [target];
- if (items.length === 0) return;
- if (remoteGuard('delete')) return;
- const message = items.length === 1
- ? `Delete "${items[0].name}"?${items[0].is_dir ? ' All contents inside will be removed.' : ''}`
- : `Delete ${items.length} items? This cannot be undone.`;
- setConfirmDialog({
- titleKey: 'app.fileManager.deleteConfirmation', title: 'Delete confirmation',
- message,
- confirmTextKey: 'common.actions.delete', confirmText: 'Delete',
- variant: 'danger',
- onConfirm: async () => {
- const failures = [];
- for (const it of items) {
- try {
- await fileApi.del(it.path);
- } catch (error) {
- failures.push(`${it.name}: ${error.message}`);
- }
- }
- if (failures.length === 0) toast.success(t('app.fileManager.deletedItems', { count: items.length, defaultValue_one: 'Deleted 1 item', defaultValue_other: 'Deleted {{count}} items' }));
- else toast.error(t('app.fileManager.failed', "Couldn't finish for: {{value}}", { value: failures.join(', ') }));
- if (previewFile && items.some((i) => i.path === previewFile.path)) setPreviewFile(null);
- clearSelection();
- loadDirectory(currentPath);
- setConfirmDialog(null);
- },
- onCancel: () => setConfirmDialog(null),
- });
- };
-
- const handleRename = async (entry, name) => {
- if (remoteGuard('rename')) return;
- try {
- await fileApi.rename(entry.path, name);
- toast.success(t('app.fileManager.renamed', 'Renamed'));
- closeDialog();
- loadDirectory(currentPath);
- } catch (error) {
- toast.error(t('app.fileManager.failedToRename', "Couldn't rename it. {{message}}", { message: errorReason(error) }));
- }
- };
-
- const handleChangePermissions = async (entry, mode) => {
- if (remoteGuard('change permissions')) return;
- try {
- await fileApi['change permissions'](entry.path, mode);
- toast.success(t('app.fileManager.permissionsUpdated', 'Permissions updated'));
- closeDialog();
- loadDirectory(currentPath);
- } catch (error) {
- toast.error(t('app.fileManager.failed2', "Couldn't do that. {{message}}", { message: errorReason(error) }));
- }
- };
-
- const openRenameModal = (entry) => setDialog({ kind: 'rename', entry });
- const openPermissionsModal = (entry) => setDialog({ kind: 'permissions', entry });
-
- // ─── upload ──────────────────────────────────────────
- const uploadFiles = async (files) => {
- const fileList = Array.from(files);
- if (fileList.length === 0) return;
- if (remoteGuard('upload')) return;
- const queue = fileList.map((f, i) => ({
- id: `${Date.now()}-${i}`,
- name: f.name,
- size: f.size,
- progress: 0,
- status: 'pending',
- }));
- setUploads((p) => [...p, ...queue]);
-
- let succeeded = 0;
- for (let i = 0; i < fileList.length; i++) {
- const file = fileList[i];
- const itemId = queue[i].id;
- try {
- setUploads((p) => p.map((u) => u.id === itemId ? { ...u, status: 'uploading' } : u));
- const doUpload = fileApi.upload;
- await doUpload(currentPath, file, (progress) => {
- setUploads((p) => p.map((u) => u.id === itemId ? { ...u, progress } : u));
- });
- setUploads((p) => p.map((u) => u.id === itemId ? { ...u, status: 'done', progress: 100 } : u));
- succeeded++;
- } catch (error) {
- setUploads((p) => p.map((u) => u.id === itemId ? { ...u, status: 'error', error: error.message } : u));
- }
- }
- if (succeeded > 0) toast.success(t('app.fileManager.uploadedFiles', { count: fileList.length, succeeded, defaultValue_one: 'Uploaded {{succeeded}} of 1 file', defaultValue_other: 'Uploaded {{succeeded}} of {{count}} files' }));
- loadDirectory(currentPath);
- setTimeout(() => {
- setUploads((p) => p.filter((u) => u.status === 'uploading' || u.status === 'pending'));
- }, 4000);
- };
-
- const handleUploadInput = (e) => {
- if (e.target.files) uploadFiles(e.target.files);
- if (fileInputRef.current) fileInputRef.current.value = '';
- };
-
- const handleDragEnter = (e) => {
- e.preventDefault(); e.stopPropagation();
- dragCounter.current += 1;
- if (e.dataTransfer.items?.length > 0) setDragActive(true);
- };
- const handleDragLeave = (e) => {
- e.preventDefault(); e.stopPropagation();
- dragCounter.current -= 1;
- if (dragCounter.current === 0) setDragActive(false);
- };
- const handleDragOver = (e) => { e.preventDefault(); e.stopPropagation(); };
- const handleDrop = (e) => {
- e.preventDefault(); e.stopPropagation();
- dragCounter.current = 0;
- setDragActive(false);
- if (e.dataTransfer.files?.length > 0) uploadFiles(e.dataTransfer.files);
- };
-
- // ─── derived ─────────────────────────────────────────
- const breadcrumbs = useMemo(() => {
- const parts = currentPath.split('/').filter(Boolean);
- // Windows drive-rooted path ("C:/Users/Juan"): the first segment is
- // the drive and the root crumb is the agent's drive list. Building
- // crumbs with a leading "/" (the POSIX branch below) would produce
- // bogus "/C:" paths that the agent can't resolve.
- if (/^[A-Za-z]:$/.test(parts[0] || '')) {
- const crumbs = [{ name: 'Drives', path: '/' }];
- let acc = parts[0];
- crumbs.push({ name: parts[0], path: acc + '/' });
- for (let i = 1; i < parts.length; i++) {
- acc += '/' + parts[i];
- crumbs.push({ name: parts[i], path: acc });
- }
- return crumbs;
- }
- const crumbs = [{ name: '/', path: '/' }];
- let acc = '';
- parts.forEach((p) => { acc += '/' + p; crumbs.push({ name: p, path: acc }); });
- return crumbs;
- }, [currentPath]);
-
- const sortedFiltered = useMemo(() => {
- let list = [...(searchResults || entries)];
- if (activeFilter !== 'all') list = list.filter((e) => getFileType(e) === activeFilter);
- const dir = sortDir === 'asc' ? 1 : -1;
- list.sort((a, b) => {
- if (a.is_dir !== b.is_dir) return a.is_dir ? -1 : 1;
- switch (sortBy) {
- case 'size': return ((a.size || 0) - (b.size || 0)) * dir;
- case 'modified': return (new Date(a.modified) - new Date(b.modified)) * dir;
- case 'type': return getFileType(a).localeCompare(getFileType(b)) * dir;
- case 'name':
- default: return a.name.localeCompare(b.name) * dir;
- }
- });
- return list;
- }, [entries, searchResults, sortBy, sortDir, activeFilter]);
-
- const filterCounts = useMemo(() => {
- const counts = { all: entries.length };
- FILTER_OPTIONS.forEach((c) => { if (c.id !== 'all') counts[c.id] = 0; });
- entries.forEach((e) => { const t = getFileType(e); if (counts[t] !== undefined) counts[t]++; });
- return counts;
- }, [entries]);
-
- const stats = useMemo(() => {
- const list = sortedFiltered;
- const folders = list.filter((e) => e.is_dir).length;
- const files = list.length - folders;
- const totalBytes = list.reduce((s, e) => s + (e.size || 0), 0);
- const selectedList = list.filter((e) => selectedPaths.has(e.path));
- const selectedBytes = selectedList.reduce((s, e) => s + (e.size || 0), 0);
- return { folders, files, totalBytes, total: list.length, selectedCount: selectedList.length, selectedBytes };
- }, [sortedFiltered, selectedPaths]);
-
- const activeMount = useMemo(() => diskMounts
- .filter((mount) => {
- const mountPath = mount.mountpoint || '/';
- if (mountPath === '/') return currentPath.startsWith('/');
- return currentPath === mountPath || currentPath.startsWith(`${mountPath.replace(/\/$/, '')}/`);
- })
- .sort((a, b) => (b.mountpoint || '/').length - (a.mountpoint || '/').length)[0] || null,
- [currentPath, diskMounts]);
-
- const activeUploads = uploads.filter((u) => u.status === 'uploading' || u.status === 'pending');
- const totalUploadProgress = activeUploads.length > 0
- ? activeUploads.reduce((s, u) => s + u.progress, 0) / activeUploads.length
- : 0;
+ },
+ remoteGuard,
+ toast,
+ t,
+ });
- const sortValue = `${sortBy}-${sortDir}`;
- const filterLabels = {
- all: t('common.labels.all', 'All'),
- folder: t('app.fileManager.folders', 'Folders'),
- image: t('app.fileManager.images', 'Images'),
- code: t('app.fileManager.code', 'Code'),
- text: t('app.fileManager.documents', 'Documents'),
- data: t('app.fileManager.data', 'Data'),
- video: t('app.fileManager.videos', 'Videos'),
- audio: t('app.fileManager.audio', 'Audio'),
- archive: t('app.fileManager.archives', 'Archives'),
- };
- const handleSortChange = (value) => {
- const [nextSortBy, nextSortDir] = value.split('-');
- setSortBy(nextSortBy);
- setSortDir(nextSortDir);
- };
+ const { treeExpanded, treeCache, refreshTree, treeLoading, toggleTreeExpand } = useFileTree({
+ fileApi,
+ currentPath,
+ });
- const selectedEntries = useMemo(
- () => sortedFiltered.filter((e) => selectedPaths.has(e.path)),
- [sortedFiltered, selectedPaths],
- );
+ const { diskMounts, diskLastUpdated, diskLoading, loadDiskMounts, activeMount } =
+ useFileVolumes(currentPath);
+
+ const {
+ dialog,
+ setDialog,
+ closeDialog,
+ handleCreateFolder,
+ handleDelete,
+ handleRename,
+ handleChangePermissions,
+ openRenameModal,
+ openPermissionsModal,
+ } = useFileActions({
+ fileApi,
+ currentPath,
+ remoteGuard,
+ loadDirectory,
+ refreshTree,
+ previewFile,
+ setPreviewFile,
+ clearSelection,
+ toast,
+ t,
+ });
+ const handleOpen = (entry) => (entry.is_dir ? navigateTo(entry.path) : openFile(entry));
+
+ const {
+ uploads,
+ setUploads,
+ dragActive,
+ fileInputRef,
+ handleUploadInput,
+ handleDragEnter,
+ handleDragLeave,
+ handleDragOver,
+ handleDrop,
+ activeUploads,
+ totalUploadProgress,
+ } = useFileTransfers({ fileApi, currentPath, remoteGuard, loadDirectory, toast, t });
+
+ const {
+ breadcrumbs,
+ sortedFiltered,
+ filterCounts,
+ stats,
+ sortValue,
+ filterLabels,
+ handleSortChange,
+ selectedEntries,
+ } = useFileListingModel({
+ currentPath,
+ entries,
+ searchResults,
+ activeFilter,
+ sortBy,
+ sortDir,
+ selectedPaths,
+ setSortBy,
+ setSortDir,
+ t,
+ });
// ─── shortcuts ───────────────────────────────────────
useEffect(() => {
@@ -791,7 +240,10 @@ function FileManager() {
setSelectedPaths(new Set(sortedFiltered.map((x) => x.path)));
setSelectMode(sortedFiltered.length > 0);
}
- if (e.key === 'Backspace' && !e.metaKey && parentPath) { e.preventDefault(); goUp(); }
+ if (e.key === 'Backspace' && !e.metaKey && parentPath) {
+ e.preventDefault();
+ goUp();
+ }
};
window.addEventListener('keydown', handler);
return () => window.removeEventListener('keydown', handler);
@@ -800,7 +252,9 @@ function FileManager() {
// ─── close popovers ──────────────────────────────────
useEffect(() => {
if (!contextMenu) return;
- const close = () => { setContextMenu(null); };
+ const close = () => {
+ setContextMenu(null);
+ };
document.addEventListener('click', close);
return () => document.removeEventListener('click', close);
}, [contextMenu]);
@@ -821,7 +275,9 @@ function FileManager() {
const rowOpen = useStableHandler(handleOpen);
const rowToggleSelect = useStableHandler(handleToggleSelect);
const rowContext = useStableHandler(openContextMenu);
- const handleDownload = (entry) => { if (!remoteGuard('download')) fileApi.download(entry); };
+ const handleDownload = (entry) => {
+ if (!remoteGuard('download')) fileApi.download(entry);
+ };
const rowDownload = useStableHandler(handleDownload);
const rowRename = useStableHandler(openRenameModal);
const rowPermissions = useStableHandler(openPermissionsModal);
@@ -830,42 +286,40 @@ function FileManager() {
const copyPathToClipboard = (path) => copyText(path);
const downloadSelected = () => {
- if (!remoteGuard('download')) selectedEntries.filter((e) => !e.is_dir).forEach((e) => fileApi.download(e));
+ if (!remoteGuard('download'))
+ selectedEntries.filter((e) => !e.is_dir).forEach((e) => fileApi.download(e));
};
- const getDiskColor = (percent) => {
- if (percent >= 90) return 'critical';
- if (percent >= 70) return 'warning';
- return 'healthy';
- };
-
- useTopbarActions(() => (
- <>
- <Button
- type="button"
- variant="outline"
- size="sm"
- onClick={() => setDialog({ kind: 'newFolder' })}
- disabled={isRemote || isS3}
- >
- <FolderPlus size={14} /> {t('app.fileManager.newFolder', 'New folder')}
- </Button>
- <Button
- type="button"
- variant="outline"
- size="sm"
- onClick={() => fileInputRef.current?.click()}
- disabled={isRemote}
- >
- <Upload size={14} /> {t('app.fileManager.upload', 'Upload')}
- </Button>
- {!isS3 && (
- <Button type="button" size="sm" onClick={() => navigate('/terminal')}>
- <Terminal size={14} /> {t('app.fileManager.terminal', 'Terminal')}
+ useTopbarActions(
+ () => (
+ <>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => setDialog({ kind: 'newFolder' })}
+ disabled={isRemote || isS3}
+ >
+ <FolderPlus size={14} /> {t('app.fileManager.newFolder', 'New folder')}
</Button>
- )}
- </>
- ), [isRemote, isS3, currentPath]);
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => fileInputRef.current?.click()}
+ disabled={isRemote}
+ >
+ <Upload size={14} /> {t('app.fileManager.upload', 'Upload')}
+ </Button>
+ {!isS3 && (
+ <Button type="button" size="sm" onClick={() => navigate('/terminal')}>
+ <Terminal size={14} /> {t('app.fileManager.terminal', 'Terminal')}
+ </Button>
+ )}
+ </>
+ ),
+ [isRemote, isS3, currentPath],
+ );
// ─── render ──────────────────────────────────────────
return (
@@ -876,216 +330,123 @@ function FileManager() {
onDragLeave={handleDragLeave}
onDrop={handleDrop}
>
- <input
- type="file"
- ref={fileInputRef}
- multiple
- className="hidden"
- onChange={handleUploadInput}
- />
+ <input type="file" ref={fileInputRef} multiple className="hidden" onChange={handleUploadInput} />
{isRemote && (
<div className="file-manager-target-banner">
- {t('app.fileManager.browsingOn', 'Browsing on')} <strong>{target.name}</strong> {t('app.fileManager.readWriteOnlyMkdirDeleteRename', "(read/write only). Mkdir/delete/rename/upload aren't yet supported on remote agents.")}
+ {t('app.fileManager.browsingOn', 'Browsing on')} <strong>{target.name}</strong>{' '}
+ {t(
+ 'app.fileManager.readWriteOnlyMkdirDeleteRename',
+ "(read/write only). Mkdir/delete/rename/upload aren't yet supported on remote agents.",
+ )}
</div>
)}
{isS3 && (
<div className="file-manager-target-banner">
- {t('app.fileManager.browsingYour', 'Browsing your')} <strong>{t('app.fileManager.s3Bucket', 'S3 bucket')}</strong>.{' '}
- {t('app.fileManager.s3SupportedOperations', "Upload, download, edit and delete work; folders, rename and permissions don't apply to object storage.")}
+ {t('app.fileManager.browsingYour', 'Browsing your')}{' '}
+ <strong>{t('app.fileManager.s3Bucket', 'S3 bucket')}</strong>.{' '}
+ {t(
+ 'app.fileManager.s3SupportedOperations',
+ "Upload, download, edit and delete work; folders, rename and permissions don't apply to object storage.",
+ )}
</div>
)}
- {uploads.length > 0 && (
- <div className="upload-tray">
- <div className="upload-tray-header">
- <CloudUpload size={16} />
- <span>
- {activeUploads.length > 0
- ? t('app.fileManager.uploadingFiles', { count: activeUploads.length, defaultValue_one: 'Uploading 1 file…', defaultValue_other: 'Uploading {{count}} files…' })
- : t('app.fileManager.uploadsComplete', 'Uploads complete')}
- </span>
- {activeUploads.length > 0 && (
- <span className="upload-tray-percent">{Math.round(totalUploadProgress)}%</span>
- )}
- <Button variant="unstyled" type="button" className="toolbar-icon-btn small" onClick={() => setUploads([])} title={t('common.actions.clear', 'Clear')}>
- <X size={14} />
- </Button>
- </div>
- <div className="upload-tray-list">
- {uploads.map((u) => (
- <div key={u.id} className={`upload-tray-item status-${u.status}`}>
- <span className="upload-name">{u.name}</span>
- <div className="upload-bar">
- <div className="upload-bar-fill" style={{ width: `${u.progress}%` }} />
- </div>
- <span className="upload-status">
- {u.status === 'done' ? t('common.actions.done', 'Done') : u.status === 'error' ? t('app.fileManager.uploadFailed', 'Failed') : `${Math.round(u.progress)}%`}
- </span>
- </div>
- ))}
- </div>
- </div>
- )}
+ <FileUploadTray
+ uploads={uploads}
+ activeUploads={activeUploads}
+ totalUploadProgress={totalUploadProgress}
+ setUploads={setUploads}
+ />
- <div className="file-manager-toolbar">
- <div className="toolbar-left">
- <Button variant="unstyled" type="button"
- className="toolbar-icon-btn"
- onClick={() => setSidebarVisible(!sidebarVisible)}
- title={sidebarVisible ? t('app.fileManager.hideSidebar', 'Hide sidebar') : t('app.fileManager.showSidebar', 'Show sidebar')}
- >
- {sidebarVisible ? <PanelLeftClose size={14} /> : <PanelLeftOpen size={14} />}
- </Button>
- <div className="nav-buttons">
- <Button variant="unstyled" type="button" className="nav-btn" onClick={goBack} disabled={historyIdx === 0} title={t('common.actions.back', 'Back')}>
- <ArrowLeft size={14} />
- </Button>
- <Button variant="unstyled" type="button" className="nav-btn" onClick={goForward} disabled={historyIdx >= history.length - 1} title={t('app.fileManager.forward', 'Forward')}>
- <ArrowRight size={14} />
- </Button>
- <Button variant="unstyled" type="button" className="nav-btn" onClick={goUp} disabled={!parentPath} title="Up">
- <ArrowUp size={14} />
- </Button>
- <Button variant="unstyled" type="button" className="nav-btn" onClick={() => navigateTo(isS3 ? '/' : '/home')} title={t('app.fileManager.home', 'Home')}>
- <Home size={14} />
- </Button>
- </div>
- <div className="path-breadcrumb">
- {breadcrumbs.map((crumb, idx) => (
- <span key={crumb.path + idx} className="crumb-segment">
- {idx > 0 && <span className="crumb-separator">/</span>}
- <Button variant="unstyled" type="button"
- className={`crumb ${idx === breadcrumbs.length - 1 ? 'crumb-active' : ''}`}
- onClick={() => navigateTo(crumb.path)}
- >
- {crumb.name}
- </Button>
- </span>
- ))}
- </div>
- {activeMount && !isRemote && !isS3 && (
- <span className="file-mount-chip" title={`${activeMount.device} · ${activeMount.total_human}`}>
- <HardDrive size={12} />
- <span>{activeMount.mountpoint === '/' ? t('app.fileManager.rootDisk', 'Root disk') : activeMount.mountpoint}</span>
- </span>
- )}
- </div>
- <div className="toolbar-right">
- <Select value={activeFilter} onValueChange={setActiveFilter}>
- <SelectTrigger
- className="file-toolbar-select"
- title={t('app.fileManager.types', 'Types')}
- aria-label={t('app.fileManager.types', 'Types')}
- >
- <File size={13} aria-hidden="true" />
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {FILTER_OPTIONS.map((option) => (
- <SelectItem key={option.id} value={option.id}>
- {filterLabels[option.id]} ({filterCounts[option.id] ?? 0})
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- <Select value={sortValue} onValueChange={handleSortChange}>
- <SelectTrigger
- className="file-toolbar-select"
- title={t('app.fileManager.sort', 'Sort')}
- aria-label={t('app.fileManager.sort', 'Sort')}
- >
- <ArrowUpDown size={13} aria-hidden="true" />
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="name-asc">{t('app.fileManager.nameAZ', 'Name A-Z')}</SelectItem>
- <SelectItem value="name-desc">{t('app.fileManager.nameZA', 'Name Z-A')}</SelectItem>
- <SelectItem value="modified-desc">{t('app.fileManager.newest', 'Newest')}</SelectItem>
- <SelectItem value="modified-asc">{t('app.fileManager.oldest', 'Oldest')}</SelectItem>
- <SelectItem value="size-desc">{t('app.fileManager.largest', 'Largest')}</SelectItem>
- <SelectItem value="size-asc">{t('app.fileManager.smallest', 'Smallest')}</SelectItem>
- <SelectItem value="type-asc">{t('common.labels.type', 'Type')}</SelectItem>
- <SelectItem value="type-desc">{t('app.fileManager.typeZA', 'Type Z-A')}</SelectItem>
- </SelectContent>
- </Select>
- <div className="search-field">
- <Search size={14} className="search-field-icon" />
- <input
- type="text"
- placeholder={t('app.fileManager.searchFiles', 'Search files…')}
- value={searchQuery}
- onChange={(e) => setSearchQuery(e.target.value)}
- onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
- />
- {(searchResults || searchQuery) && (
- <Button variant="unstyled" type="button"
- className="search-field-clear"
- onClick={() => { setSearchResults(null); setSearchQuery(''); }}
- title={t('common.actions.clear', 'Clear')}
- >
- <X size={12} />
- </Button>
- )}
- </div>
- <div className="view-toggle">
- <Button variant="unstyled" type="button"
- className={`view-toggle-btn ${viewMode === 'grid' ? 'active' : ''}`}
- onClick={() => setViewMode('grid')}
- title={t('app.fileManager.gridView', 'Grid view')}
- >
- <LayoutGrid size={14} />
- </Button>
- <Button variant="unstyled" type="button"
- className={`view-toggle-btn ${viewMode === 'list' ? 'active' : ''}`}
- onClick={() => setViewMode('list')}
- title={t('app.fileManager.listView', 'List view')}
- >
- <List size={14} />
- </Button>
- </div>
- <Button variant="unstyled" type="button"
- className={`toolbar-icon-btn ${showHidden ? 'active' : ''}`}
- onClick={() => setShowHidden(!showHidden)}
- title={t('app.fileManager.toggleHiddenFiles', 'Toggle hidden files')}
- >
- {showHidden ? <Eye size={14} /> : <EyeOff size={14} />}
- </Button>
- <Button variant="unstyled" type="button"
- className="toolbar-icon-btn"
- onClick={() => loadDirectory(currentPath)}
- title={t('common.actions.refresh', 'Refresh')}
- >
- <RefreshCw size={14} className={loading ? 'spinning' : ''} />
- </Button>
- </div>
- </div>
+ <FileManagerToolbar
+ setSidebarVisible={setSidebarVisible}
+ sidebarVisible={sidebarVisible}
+ goBack={goBack}
+ history={history}
+ historyIdx={historyIdx}
+ goForward={goForward}
+ goUp={goUp}
+ parentPath={parentPath}
+ navigateTo={navigateTo}
+ isS3={isS3}
+ breadcrumbs={breadcrumbs}
+ activeMount={activeMount}
+ isRemote={isRemote}
+ activeFilter={activeFilter}
+ setActiveFilter={setActiveFilter}
+ FILTER_OPTIONS={FILTER_OPTIONS}
+ filterLabels={filterLabels}
+ filterCounts={filterCounts}
+ sortValue={sortValue}
+ handleSortChange={handleSortChange}
+ searchQuery={searchQuery}
+ setSearchQuery={setSearchQuery}
+ handleSearch={handleSearch}
+ searchResults={searchResults}
+ clearSearch={clearSearch}
+ viewMode={viewMode}
+ setViewMode={setViewMode}
+ showHidden={showHidden}
+ setShowHidden={setShowHidden}
+ loadDirectory={loadDirectory}
+ currentPath={currentPath}
+ loading={loading}
+ />
{selectedPaths.size > 0 && (
<div className="bulk-bar">
<div className="bulk-bar-info">
<Check size={14} />
- <span>{selectedPaths.size} {t('app.fileManager.selected', 'selected ·')} {formatBytes(stats.selectedBytes)}</span>
+ <span>
+ {selectedPaths.size} {t('app.fileManager.selected', 'selected ·')}{' '}
+ {formatBytes(stats.selectedBytes)}
+ </span>
</div>
<div className="bulk-bar-actions">
- <Button variant="unstyled" type="button" className="bulk-btn" onClick={downloadSelected}>
+ <Button
+ variant="unstyled"
+ type="button"
+ className="bulk-btn"
+ onClick={downloadSelected}
+ >
<Download size={14} /> {t('common.actions.download', 'Download')}
</Button>
{selectedEntries.length === 1 && (
<>
- <Button variant="unstyled" type="button" className="bulk-btn" onClick={() => openRenameModal(selectedEntries[0])}>
+ <Button
+ variant="unstyled"
+ type="button"
+ className="bulk-btn"
+ onClick={() => openRenameModal(selectedEntries[0])}
+ >
<Edit3 size={14} /> {t('app.fileManager.rename', 'Rename')}
</Button>
- <Button variant="unstyled" type="button" className="bulk-btn" onClick={() => copyPathToClipboard(selectedEntries[0].path)}>
+ <Button
+ variant="unstyled"
+ type="button"
+ className="bulk-btn"
+ onClick={() => copyPathToClipboard(selectedEntries[0].path)}
+ >
<Copy size={14} /> {t('app.fileManager.copyPath', 'Copy path')}
</Button>
</>
)}
- <Button variant="unstyled" type="button" className="bulk-btn danger" onClick={() => handleDelete(selectedEntries)}>
+ <Button
+ variant="unstyled"
+ type="button"
+ className="bulk-btn danger"
+ onClick={() => handleDelete(selectedEntries)}
+ >
<Trash2 size={14} /> {t('common.actions.delete', 'Delete')}
</Button>
- <Button variant="unstyled" type="button" className="bulk-btn ghost" onClick={clearSelection}>
+ <Button
+ variant="unstyled"
+ type="button"
+ className="bulk-btn ghost"
+ onClick={clearSelection}
+ >
<X size={14} /> {t('common.actions.clear', 'Clear')}
</Button>
</div>
@@ -1093,238 +454,59 @@ function FileManager() {
)}
<div className={`file-manager-body ${previewFile ? 'has-preview' : ''}`}>
- {sidebarVisible && (
- <aside className="file-manager-sidebar left">
- <div className="file-manager-source">
- <Button variant="unstyled"
- type="button"
- className="file-manager-source__close"
- onClick={() => setSidebarVisible(false)}
- aria-label={t('app.fileManager.hideSidebar', 'Hide sidebar')}
- >
- <X size={14} />
- </Button>
- <ServerPicker
- capability="files"
- value={targetServerId(target)}
- onChange={(id, server) => setTarget(serverTarget(id, server || (id === 's3' ? null : {})))}
- extraOptions={s3Options}
- className="file-manager-source__picker"
- />
- <div className="file-manager-source__meta">
- <span className={`file-manager-source__dot${isS3 ? ' is-cloud' : ''}`} aria-hidden="true" />
- <span>
- {isRemote
- ? t('app.fileManager.remoteAgent', 'Remote agent')
- : isS3
- ? t('app.fileManager.objectStorage', 'Object storage')
- : t('app.fileManager.localPanelHost', 'Panel server')}
- </span>
- </div>
- </div>
-
- {!isRemote && !isS3 && (
- <div className="sidebar-section sidebar-section--volumes">
- <div className="sidebar-section-header sidebar-section-header--split">
- <span className="sidebar-section-title" title={t('app.fileManager.diskUsage', 'Disk usage')}>
- <HardDrive size={13} />
- <span>{t('app.fileManager.volumes', 'Volumes')}</span>
- </span>
- <Button variant="unstyled" type="button" className="sidebar-action-btn" onClick={loadDiskMounts} disabled={diskLoading} title={t('common.actions.refresh', 'Refresh')}>
- <RefreshCw size={12} className={diskLoading ? 'spinning' : ''} />
- </Button>
- </div>
- <div className="sidebar-section-content disk-mount-list">
- {diskMounts.map((mount) => (
- <Button variant="unstyled"
- type="button"
- key={`${mount.device}:${mount.mountpoint}`}
- className={`disk-mount-item${activeMount?.mountpoint === mount.mountpoint ? ' active' : ''}`}
- onClick={() => navigateTo(mount.mountpoint)}
- title={`${mount.device} · ${mount.used_human} / ${mount.total_human}`}
- >
- <div className="disk-mount-header">
- <span className="disk-mount-point">
- {mount.mountpoint === '/'
- ? t('app.fileManager.rootDisk', 'Root disk')
- : mountDisplayName(mount)}
- </span>
- <span className={`disk-percent ${getDiskColor(mount.percent)}`}>
- {mount.percent}%
- </span>
- </div>
- <div className={`disk-progress ${getDiskColor(mount.percent)}`}>
- <span className="disk-progress-fill" style={{ width: `${mount.percent}%` }} />
- </div>
- </Button>
- ))}
- {diskLastUpdated && (
- <span className="disk-updated disk-updated--footer">
- <Clock size={11} />
- {t('app.fileManager.updatedAt', 'Updated {{time}}', { time: formatTime(diskLastUpdated, { seconds: true }) })}
- </span>
- )}
- </div>
- </div>
- )}
-
- {!isS3 && (<>
- <div className="sidebar-section">
- <div className="sidebar-section-header static">
- <Zap size={16} />
- <span>{t('app.fileManager.quickAccess', 'Quick access')}</span>
- </div>
- <div className="sidebar-section-content quick-access-list">
- {quickAccess.map(q => (
- <Button variant="unstyled" type="button"
- key={q.label}
- className={`quick-access-item ${currentPath === q.path ? 'active' : ''}`}
- onClick={() => navigateTo(q.path)}
- >
- <q.icon size={14} />
- <span>{q.label}</span>
- </Button>
- ))}
- </div>
- </div>
-
- <div className="sidebar-section">
- <div className="sidebar-section-header sidebar-section-header--split">
- <Button variant="unstyled"
- type="button"
- className="sidebar-section-toggle"
- onClick={() => setTreeCollapsed(!treeCollapsed)}
- title={t('app.fileManager.folders', 'Folders')}
- >
- <FolderTreeIcon size={16} />
- <span>{t('app.fileManager.fileSystem', 'File system')}</span>
- {treeCollapsed ? <ChevronRight size={16} /> : <ChevronDown size={16} />}
- </Button>
- <Button variant="unstyled" type="button"
- className="sidebar-action-btn"
- onClick={() => setDialog({ kind: 'newFolder' })}
- disabled={isRemote}
- title={t('app.fileManager.newFolder', 'New folder')}
- >
- <FolderPlus size={14} />
- </Button>
- </div>
- {!treeCollapsed && (
- <div className="sidebar-section-content tree-content">
- <FolderTree
- roots={TREE_ROOTS}
- expanded={treeExpanded}
- treeCache={treeCache}
- treeLoading={treeLoading}
- currentPath={currentPath}
- onNavigate={navigateTo}
- onToggle={toggleTreeExpand}
- />
- </div>
- )}
- </div>
- </>)}
-
- </aside>
- )}
-
- <main className="file-manager-main">
- <div
- className="file-list-container"
- onClick={(e) => {
- if (e.target === e.currentTarget) clearSelection();
- }}
- >
- {dragActive && (
- <div className="drag-overlay">
- <div className="drag-overlay-inner">
- <CloudUpload size={56} strokeWidth={1.5} />
- <h3>{t('app.fileManager.dropToUpload', 'Drop to upload')}</h3>
- <p>{t('app.fileManager.filesWillBeUploadedTo', 'Files will be uploaded to')} <code>{currentPath}</code></p>
- </div>
- </div>
- )}
+ <FileManagerSidebar
+ sidebarVisible={sidebarVisible}
+ setSidebarVisible={setSidebarVisible}
+ target={target}
+ setTarget={setTarget}
+ s3Options={s3Options}
+ isS3={isS3}
+ isRemote={isRemote}
+ loadDiskMounts={loadDiskMounts}
+ diskLoading={diskLoading}
+ diskMounts={diskMounts}
+ activeMount={activeMount}
+ navigateTo={navigateTo}
+ diskLastUpdated={diskLastUpdated}
+ quickAccess={quickAccess}
+ currentPath={currentPath}
+ setTreeCollapsed={setTreeCollapsed}
+ treeCollapsed={treeCollapsed}
+ setDialog={setDialog}
+ treeExpanded={treeExpanded}
+ treeCache={treeCache}
+ treeLoading={treeLoading}
+ toggleTreeExpand={toggleTreeExpand}
+ />
- {loading ? (
- <EmptyState loading loadingVariant="tree" title={t('app.fileManager.loadingFiles', 'Loading files')} />
- ) : dirError && !searchResults ? (
- <ErrorState
- title={t('app.fileManager.couldntOpenThisFolder', "Couldn't open this folder.")}
- error={dirError}
- onRetry={() => loadDirectory(currentPath)}
- />
- ) : sortedFiltered.length === 0 ? (
- <EmptyState
- icon={FolderOpen}
- title={searchResults ? t('app.fileManager.noMatches', 'No matches') : activeFilter !== 'all' ? t('app.fileManager.noFiles', 'No {{activeFilter}} files', { activeFilter: activeFilter }) : t('app.fileManager.thisFolderIsEmpty', 'This folder is empty')}
- description={searchResults
- ? t('app.fileManager.tryADifferentSearchTermOr', 'Try a different search term or browse another folder.')
- : activeFilter !== 'all'
- ? t('app.fileManager.tryADifferentFilter', 'Try a different filter.')
- : t('app.fileManager.dropFilesHereOrUseThe', 'Drop files here, or use the buttons above to create something new.')}
- />
- ) : viewMode === 'grid' ? (
- <div className="file-grid">
- {sortedFiltered.map((entry) => (
- <FileCard
- key={entry.path}
- entry={entry}
- selected={selectedPaths.has(entry.path)}
- selectMode={selectMode}
- onOpen={rowOpen}
- onToggleSelect={rowToggleSelect}
- onContext={rowContext}
- isS3={isS3}
- />
- ))}
- </div>
- ) : (
- <div className="file-list">
- <div className="file-list-header">
- <span className="col-check">
- <Button variant="unstyled" type="button"
- className="checkbox-btn"
- onClick={() => {
- if (selectedPaths.size === sortedFiltered.length) clearSelection();
- else {
- setSelectedPaths(new Set(sortedFiltered.map((x) => x.path)));
- setSelectMode(sortedFiltered.length > 0);
- }
- }}
- >
- <span className={`checkbox ${selectedPaths.size === sortedFiltered.length && sortedFiltered.length > 0 ? 'checked' : ''}`}>
- {selectedPaths.size === sortedFiltered.length && sortedFiltered.length > 0 && <Check size={12} />}
- </span>
- </Button>
- </span>
- <span className="col-name">{t('common.labels.name', 'Name')}</span>
- <span className="col-size">{t('common.labels.size', 'Size')}</span>
- <span className="col-modified">{t('app.fileManager.modified', 'Modified')}</span>
- <span className="col-permissions">{t('common.labels.permissions', 'Permissions')}</span>
- <span className="col-owner">{t('app.fileManager.owner', 'Owner')}</span>
- <span className="col-actions">{t('common.labels.actions', 'Actions')}</span>
- </div>
- {sortedFiltered.map((entry) => (
- <FileRow
- key={entry.path}
- entry={entry}
- selected={selectedPaths.has(entry.path)}
- selectMode={selectMode}
- onOpen={rowOpen}
- onToggleSelect={rowToggleSelect}
- onContext={rowContext}
- onDownload={rowDownload}
- onRename={rowRename}
- onPermissions={rowPermissions}
- onDelete={rowDelete}
- />
- ))}
- </div>
- )}
- </div>
- </main>
+ <FileManagerListing
+ fileApi={fileApi}
+ clearSelection={clearSelection}
+ dragActive={dragActive}
+ currentPath={currentPath}
+ loading={loading}
+ dirError={dirError}
+ searchResults={searchResults}
+ loadDirectory={loadDirectory}
+ sortedFiltered={sortedFiltered}
+ activeFilter={activeFilter}
+ viewMode={viewMode}
+ selectedPaths={selectedPaths}
+ selectMode={selectMode}
+ rowOpen={rowOpen}
+ rowToggleSelect={rowToggleSelect}
+ rowContext={rowContext}
+ isS3={isS3}
+ setSelectedPaths={setSelectedPaths}
+ setSelectMode={setSelectMode}
+ rowDownload={rowDownload}
+ rowRename={rowRename}
+ rowPermissions={rowPermissions}
+ rowDelete={rowDelete}
+ />
<PreviewDrawer
+ fileApi={fileApi}
inline
isS3={isS3}
file={previewFile}
@@ -1334,7 +516,10 @@ function FileManager() {
onStartEdit={() => setEditing(true)}
onCancelEdit={() => setEditing(false)}
onSave={handleSaveFile}
- onClose={() => { setPreviewFile(null); setEditing(false); }}
+ onClose={() => {
+ setPreviewFile(null);
+ setEditing(false);
+ }}
onDownload={handleDownload}
onRename={openRenameModal}
onPermissions={openPermissionsModal}
@@ -1343,42 +528,7 @@ function FileManager() {
/>
</div>
- <div className="status-bar">
- <div className="status-bar-left">
- <span className="status-item">
- <span className="status-label">{t('app.fileManager.total', 'Total')}</span>
- <span className="status-value">{stats.total} item{stats.total !== 1 ? 's' : ''}</span>
- </span>
- <span className="status-divider" />
- <span className="status-item">
- <Folder size={12} />
- <span>{stats.folders} folder{stats.folders !== 1 ? 's' : ''}</span>
- </span>
- <span className="status-item">
- <File size={12} />
- <span>{stats.files} file{stats.files !== 1 ? 's' : ''}</span>
- </span>
- {stats.totalBytes > 0 && (
- <>
- <span className="status-divider" />
- <span className="status-item">
- <span className="status-label">{t('common.labels.size', 'Size')}</span>
- <span className="status-value">{formatBytes(stats.totalBytes)}</span>
- </span>
- </>
- )}
- </div>
- <div className="status-bar-right">
- {stats.selectedCount > 0 && (
- <span className="status-selection">
- {stats.selectedCount} {t('app.fileManager.selected', 'selected ·')} {formatBytes(stats.selectedBytes)}
- </span>
- )}
- <span className="status-shortcuts" title={t('app.fileManager.keyboardShortcuts', 'Keyboard shortcuts')}>
- {t('app.fileManager.upDelDeleteF2RenameA', '⌫ Up · Del Delete · F2 Rename · ⌘A All')}
- </span>
- </div>
- </div>
+ <FileManagerStatus stats={stats} />
<ContextMenu
menu={contextMenu}
@@ -1392,47 +542,14 @@ function FileManager() {
onDelete={(e) => handleDelete(selectedEntries.length > 1 ? selectedEntries : e)}
/>
- {dialog?.kind === 'newFolder' && (
- <NamePromptModal
- title={t('app.fileManager.createNewFolder', 'Create new folder')}
- label={t('app.fileManager.folderName', 'Folder name')}
- placeholder="new-folder"
- hint={<p className="text-muted">{t('app.fileManager.willBeCreatedIn', 'Will be created in:')} <code>{currentPath}</code></p>}
- submitLabel={t('app.fileManager.createFolder', 'Create folder')}
- onSubmit={handleCreateFolder}
- onClose={closeDialog}
- />
- )}
- {dialog?.kind === 'rename' && (
- <NamePromptModal
- key={dialog.entry.path}
- title={t('app.fileManager.rename2', 'Rename {{value}}', { value: dialog.entry.is_dir ? 'Folder' : 'File' })}
- label={t('app.fileManager.newName', 'New name')}
- initialValue={dialog.entry.name}
- submitLabel={t('app.fileManager.rename', 'Rename')}
- onSubmit={(name) => handleRename(dialog.entry, name)}
- onClose={closeDialog}
- />
- )}
- {dialog?.kind === 'permissions' && (
- <PermissionsModal
- key={dialog.entry.path}
- entry={dialog.entry}
- onSubmit={(mode) => handleChangePermissions(dialog.entry, mode)}
- onClose={closeDialog}
- />
- )}
-
- {confirmDialog && (
- <ConfirmDialog
- title={confirmDialog.title}
- message={confirmDialog.message}
- confirmText={confirmDialog.confirmText}
- variant={confirmDialog.variant}
- onConfirm={confirmDialog.onConfirm}
- onCancel={confirmDialog.onCancel}
- />
- )}
+ <FileManagerDialogs
+ dialog={dialog}
+ currentPath={currentPath}
+ handleCreateFolder={handleCreateFolder}
+ closeDialog={closeDialog}
+ handleRename={handleRename}
+ handleChangePermissions={handleChangePermissions}
+ />
</div>
);
}