Fully autonomous AI Agents system capable of performing complex penetration testing tasks
Go ai-agentsai-security-toolanthropicautonomous-agentsgolanggptgraphqlmulti-agent-systemoffensive-securityopen-sourceopenaipenetration-testingpenetration-testing-toolsreactsecurity-automationsecurity-testingsecurity-toolsself-hosted
refactor(frontend): data-router migration, FileManager sorting, shared utilities
Sergey Kozyrenko7125834e7e87
diff --git a/frontend/src/app.tsx b/frontend/src/app.tsxindex ef05b5a6..9030962c 100644--- a/frontend/src/app.tsx+++ b/frontend/src/app.tsx@@ -1,6 +1,13 @@import { ApolloProvider } from '@apollo/client';import { lazy, Suspense } from 'react';-import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom';+import {+ createBrowserRouter,+ createRoutesFromElements,+ Navigate,+ Outlet,+ Route,+ RouterProvider,+} from 'react-router-dom';import AppLayout from '@/components/layouts/app-layout';import FlowsLayout from '@/components/layouts/flows-layout';@@ -41,192 +48,195 @@ const SettingsPrompts = lazy(() => import('@/pages/settings/settings-prompts'));const SettingsProvider = lazy(() => import('@/pages/settings/settings-provider'));const SettingsProviders = lazy(() => import('@/pages/settings/settings-providers'));-const App = () => {- const renderProtectedRoute = () => (- <ProtectedRoute>- <SystemSettingsProvider>- <ProvidersProvider>- <SidebarFlowsProvider>- <AppLayout />- </SidebarFlowsProvider>- </ProvidersProvider>- </SystemSettingsProvider>- </ProtectedRoute>- );-- const renderPublicRoute = () => (- <PublicRoute>- <Login />- </PublicRoute>- );-- return (- <ApolloProvider client={client}>- <ThemeProvider>- <Toaster />- <BrowserRouter>- <UserProvider>- <FavoritesProvider>- <TemplatesProvider>- <KnowledgesProvider>- <ResourcesProvider>- <Suspense fallback={<PageLoader />}>- <Routes>- {/* private routes */}- <Route element={renderProtectedRoute()}>- {/* Main layout for chat pages */}- <Route element={<MainLayout />}>- <Route- element={<Dashboard />}- path="dashboard"- />-- {/* Flows section with FlowsProvider */}- <Route element={<FlowsLayout />}>- <Route- element={<Flows />}- path="flows"- />- <Route- element={<NewFlow />}- path="flows/new"- />- <Route- element={- <FlowProvider>- <Flow />- </FlowProvider>- }- path="flows/:flowId"- />- </Route>-- <Route- element={<Templates />}- path="templates"- />- <Route- element={<Template />}- path="templates/:templateId"- />-- <Route- element={<Knowledges />}- path="knowledges"- />- <Route- element={<Knowledge />}- path="knowledges/:knowledgeId"- />-- <Route- element={<Resources />}- path="resources"- />- </Route>-- {/* Settings with nested routes */}- <Route- element={<SettingsLayout />}- path="settings"- >- <Route- element={- <Navigate- replace- to="providers"- />- }- index- />- <Route- element={<SettingsProviders />}- path="providers"- />- <Route- element={<SettingsProvider />}- path="providers/:providerId"- />- <Route- element={<SettingsPrompts />}- path="prompts"- />- <Route- element={<SettingsPrompt />}- path="prompts/:promptId"- />- <Route- element={<SettingsAPITokens />}- path="api-tokens"- />- {/* <Route- path="mcp-servers"- element={<SettingsMcpServers />}- />- <Route- path="mcp-servers/new"- element={<SettingsMcpServer />}- />- <Route- path="mcp-servers/:mcpServerId"- element={<SettingsMcpServer />}- /> */}- {/* Catch-all route for unknown settings paths */}- <Route- element={- <Navigate- replace- to="/settings/providers"- />- }- path="*"- />- </Route>- </Route>-- {/* report routes */}- <Route- element={- <ProtectedRoute>- <SystemSettingsProvider>- <FlowReport />- </SystemSettingsProvider>- </ProtectedRoute>- }- path="flows/:flowId/report"- />-- {/* public routes */}- <Route- element={renderPublicRoute()}- path="login"- />-- <Route- element={<OAuthResult />}- path="oauth/result"- />-- {/* other routes */}- <Route- element={<Navigate to="/dashboard" />}- path="/"- />- <Route- element={<Navigate to="/dashboard" />}- path="*"- />- </Routes>- </Suspense>- </ResourcesProvider>- </KnowledgesProvider>- </TemplatesProvider>- </FavoritesProvider>- </UserProvider>- </BrowserRouter>- </ThemeProvider>- </ApolloProvider>- );-};+// Root layout for the data router. Everything that previously sat between+// `<BrowserRouter>` and `<Routes>` (providers, Suspense) lives here so it has+// access to router hooks (`useNavigate`, `useLocation`, ...) while still being+// rendered under the data router. This is what enables `useBlocker` and other+// data-router-only features inside our pages.+const RootLayout = () => (+ <UserProvider>+ <FavoritesProvider>+ <TemplatesProvider>+ <KnowledgesProvider>+ <ResourcesProvider>+ <Suspense fallback={<PageLoader />}>+ <Outlet />+ </Suspense>+ </ResourcesProvider>+ </KnowledgesProvider>+ </TemplatesProvider>+ </FavoritesProvider>+ </UserProvider>+);++const ProtectedAppLayout = () => (+ <ProtectedRoute>+ <SystemSettingsProvider>+ <ProvidersProvider>+ <SidebarFlowsProvider>+ <AppLayout />+ </SidebarFlowsProvider>+ </ProvidersProvider>+ </SystemSettingsProvider>+ </ProtectedRoute>+);++const ProtectedReportLayout = () => (+ <ProtectedRoute>+ <SystemSettingsProvider>+ <FlowReport />+ </SystemSettingsProvider>+ </ProtectedRoute>+);++const PublicLoginLayout = () => (+ <PublicRoute>+ <Login />+ </PublicRoute>+);++const FlowWithProvider = () => (+ <FlowProvider>+ <Flow />+ </FlowProvider>+);++const router = createBrowserRouter(+ createRoutesFromElements(+ <Route element={<RootLayout />}>+ {/* private routes */}+ <Route element={<ProtectedAppLayout />}>+ {/* Main layout for chat pages */}+ <Route element={<MainLayout />}>+ <Route+ element={<Dashboard />}+ path="dashboard"+ />++ {/* Flows section with FlowsProvider */}+ <Route element={<FlowsLayout />}>+ <Route+ element={<Flows />}+ path="flows"+ />+ <Route+ element={<NewFlow />}+ path="flows/new"+ />+ <Route+ element={<FlowWithProvider />}+ path="flows/:flowId"+ />+ </Route>++ <Route+ element={<Templates />}+ path="templates"+ />+ <Route+ element={<Template />}+ path="templates/:templateId"+ />++ <Route+ element={<Knowledges />}+ path="knowledges"+ />+ <Route+ element={<Knowledge />}+ path="knowledges/:knowledgeId"+ />++ <Route+ element={<Resources />}+ path="resources"+ />+ </Route>++ {/* Settings with nested routes */}+ <Route+ element={<SettingsLayout />}+ path="settings"+ >+ <Route+ element={+ <Navigate+ replace+ to="providers"+ />+ }+ index+ />+ <Route+ element={<SettingsProviders />}+ path="providers"+ />+ <Route+ element={<SettingsProvider />}+ path="providers/:providerId"+ />+ <Route+ element={<SettingsPrompts />}+ path="prompts"+ />+ <Route+ element={<SettingsPrompt />}+ path="prompts/:promptId"+ />+ <Route+ element={<SettingsAPITokens />}+ path="api-tokens"+ />+ {/* Catch-all route for unknown settings paths */}+ <Route+ element={+ <Navigate+ replace+ to="/settings/providers"+ />+ }+ path="*"+ />+ </Route>+ </Route>++ {/* report routes */}+ <Route+ element={<ProtectedReportLayout />}+ path="flows/:flowId/report"+ />++ {/* public routes */}+ <Route+ element={<PublicLoginLayout />}+ path="login"+ />++ <Route+ element={<OAuthResult />}+ path="oauth/result"+ />++ {/* other routes */}+ <Route+ element={<Navigate to="/dashboard" />}+ path="/"+ />+ <Route+ element={<Navigate to="/dashboard" />}+ path="*"+ />+ </Route>,+ ),+);++const App = () => (+ <ApolloProvider client={client}>+ <ThemeProvider>+ <Toaster />+ <RouterProvider router={router} />+ </ThemeProvider>+ </ApolloProvider>+);export default App;diff --git a/frontend/src/components/shared/file-manager/file-manager-bulk-actions-bar.tsx b/frontend/src/components/shared/file-manager/file-manager-bulk-actions-bar.tsxindex 8efac7a8..f9b202fc 100644--- a/frontend/src/components/shared/file-manager/file-manager-bulk-actions-bar.tsx+++ b/frontend/src/components/shared/file-manager/file-manager-bulk-actions-bar.tsx@@ -1,4 +1,4 @@-import { MoreHorizontal, X } from 'lucide-react';+import { Ellipsis, X } from 'lucide-react';import { type ComponentType, useCallback, useMemo, useState } from 'react';import ConfirmationDialog from '@/components/shared/confirmation-dialog';@@ -167,7 +167,7 @@ export const FileManagerBulkActionsBar = ({size="icon-sm"variant="outline">- <MoreHorizontal className="size-4" />+ <Ellipsis /></Button></DropdownMenuTrigger><DropdownMenuContent align="end">diff --git a/frontend/src/components/shared/file-manager/file-manager-row.tsx b/frontend/src/components/shared/file-manager/file-manager-row.tsxindex ffc7737d..75c45995 100644--- a/frontend/src/components/shared/file-manager/file-manager-row.tsx+++ b/frontend/src/components/shared/file-manager/file-manager-row.tsx@@ -1,12 +1,14 @@-import { ChevronRight, MoreVertical } from 'lucide-react';+import { ChevronRight, Ellipsis } from 'lucide-react';import {type CSSProperties,memo,type FocusEvent as ReactFocusEvent,type MouseEvent as ReactMouseEvent,type ReactNode,+ type PointerEvent as ReactPointerEvent,type SyntheticEvent,useMemo,+ useState,} from 'react';import { Button } from '@/components/ui/button';@@ -32,7 +34,7 @@ import type { FileManagerNodeDndHandlers } from './use-file-manager-dnd';import { FileManagerHighlightedName } from './file-manager-highlighted-name';import { getFileTypeIcon } from './file-manager-icons';-import { formatModified as defaultFormatModified, formatFileSize } from './file-manager-utils';+import { formatModifiedRelative as defaultFormatModified, formatFileSize } from './file-manager-utils';/*** Marker on every interactive child of the row that should NOT bubble into a row@@ -310,6 +312,15 @@ const FileManagerRowImpl = ({const hasOwnContextMenu = contextItems.length > 0;const isActiveRow = activeRowPath === file.path;+ // Mirror the hover highlight while a row-owned menu (right-click context+ // menu or actions dropdown) is open so the user always knows which row+ // the menu belongs to — pointer can drift off the row into the portaled+ // menu content, which would otherwise drop the `:hover` state and leave+ // the row visually indistinguishable from its neighbors.+ const [isContextMenuOpen, setIsContextMenuOpen] = useState(false);+ const [isDropdownMenuOpen, setIsDropdownMenuOpen] = useState(false);+ const isMenuOpen = isContextMenuOpen || isDropdownMenuOpen;+const rowStyle = {'--fm-depth': file.depth,gridTemplateColumns: gridTemplate,@@ -330,12 +341,12 @@ const FileManagerRowImpl = ({aria-selected={isSelected}aria-setsize={setSize}className={cn(- 'group hover:bg-accent grid cursor-pointer items-center gap-3 px-3 py-1.5 transition-colors outline-none',+ 'group hover:bg-muted grid cursor-pointer items-center gap-3 px-3 py-1.5 transition-colors outline-none','focus-visible:bg-muted/70 focus-visible:ring-ring focus-visible:ring-1',// `select-none` keeps double-click reserved for expand/collapse// — without it the browser would highlight the row's text on dblclick.'select-none',- isSelected && 'bg-muted',+ (isSelected || isMenuOpen) && 'bg-muted',isDropTarget && 'bg-primary/10 ring-primary/40 ring-1 ring-inset',// Ghost every row that's part of the in-flight drag (the grabbed row// plus any other selected rows being moved together) so the user sees@@ -381,6 +392,27 @@ const FileManagerRowImpl = ({onFocusRow(file.path);}}+ // Touch counterpart of the `onContextMenu` guard above. Radix's+ // `<ContextMenuTrigger>` opens the menu on touch devices via a+ // long-press timer started in `onPointerDown` — the native+ // `contextmenu` event the desktop guard relies on never fires.+ // Without stopping React-tree bubble here, the OUTER empty-area+ // trigger ALSO starts its own long-press timer, and the user+ // ends up with two menus stacked on top of each other (inner+ // row menu + empty-area menu) when long-pressing a row on+ // mobile / tablets. Mouse `pointerdown` is left alone so click,+ // selection and drag listeners higher up the tree keep working+ // exactly as before — the desktop right-click path is already+ // covered by `onContextMenu` above.+ onPointerDown={+ hasOwnContextMenu+ ? (event: ReactPointerEvent<HTMLDivElement>) => {+ if (event.pointerType !== 'mouse') {+ event.stopPropagation();+ }+ }+ : undefined+ }role="treeitem"style={rowStyle}tabIndex={isActiveRow ? 0 : -1}@@ -468,7 +500,7 @@ const FileManagerRowImpl = ({{hasActions && (<span {...skipRowClickProps}>{dropdownItems.length > 0 ? (- <DropdownMenu>+ <DropdownMenu onOpenChange={setIsDropdownMenuOpen}><DropdownMenuTrigger asChild><Buttonaria-label="Row actions"@@ -476,7 +508,7 @@ const FileManagerRowImpl = ({size="icon-xs"variant="ghost">- <MoreVertical className="size-3.5" />+ <Ellipsis /></Button></DropdownMenuTrigger><DropdownMenuContent align="end">{dropdownItems}</DropdownMenuContent>@@ -492,7 +524,7 @@ const FileManagerRowImpl = ({}return (- <ContextMenu>+ <ContextMenu onOpenChange={setIsContextMenuOpen}><ContextMenuTrigger asChild>{row}</ContextMenuTrigger><ContextMenuContent>{contextItems}</ContextMenuContent></ContextMenu>diff --git a/frontend/src/components/shared/file-manager/file-manager-storage.ts b/frontend/src/components/shared/file-manager/file-manager-storage.tsnew file mode 100644index 00000000..ee27e3f5--- /dev/null+++ b/frontend/src/components/shared/file-manager/file-manager-storage.ts@@ -0,0 +1,31 @@+import { z } from 'zod';++import { getStorageItem, setStorageItem } from '@/lib/local-storage';++import type { FileManagerSortState } from './file-manager-types';++/**+ * Storage shape for the FileManager active sort. Mirrors the runtime+ * `FileManagerSortState` (a `null` payload means "no sort, insertion order+ * preserved"). The schema is the source of truth for the on-disk format —+ * if the runtime type changes, this schema must change too so existing+ * payloads either upgrade cleanly or get rejected (and discarded by the+ * loader's safeParse fallback).+ */+const fileManagerSortingSchema = z+ .object({+ column: z.enum(['modified', 'name', 'size']),+ direction: z.enum(['asc', 'desc']),+ })+ .nullable();++/**+ * Loader for the FileManager sort descriptor. Both "nothing stored" and+ * "stored as null" surface as `null` (no-sort) — the two cases are+ * indistinguishable from the consumer's point of view.+ */+export const loadFileManagerSorting = (key: string): FileManagerSortState =>+ getStorageItem(key, fileManagerSortingSchema);++export const saveFileManagerSorting = (key: string, sorting: FileManagerSortState): void =>+ setStorageItem(key, sorting);diff --git a/frontend/src/components/shared/file-manager/file-manager-tree-node.tsx b/frontend/src/components/shared/file-manager/file-manager-tree-node.tsxindex b38a9435..2ff565af 100644--- a/frontend/src/components/shared/file-manager/file-manager-tree-node.tsx+++ b/frontend/src/components/shared/file-manager/file-manager-tree-node.tsx@@ -1,5 +1,3 @@-import { Fragment } from 'react';-import type { FileManagerRowDisplay, FileManagerRowHandlers } from './file-manager-row';import type { FileManagerAction, FileManagerInternalNode } from './file-manager-types';import type { FileManagerNodeDndHandlers } from './use-file-manager-dnd';@@ -62,7 +60,7 @@ export const FileManagerTreeNode = ({const subtreePaths = node.isDir ? dirSubtreePaths.get(node.path) : undefined;return (- <Fragment>+ <><FileManagerRowactions={actions}activeRowPath={activeRowPath}@@ -95,6 +93,6 @@ export const FileManagerTreeNode = ({setSize={node.children.length}/>))}- </Fragment>+ </>);};diff --git a/frontend/src/components/shared/file-manager/file-manager-types.ts b/frontend/src/components/shared/file-manager/file-manager-types.tsindex 5bdb24b3..23ad33e8 100644--- a/frontend/src/components/shared/file-manager/file-manager-types.ts+++ b/frontend/src/components/shared/file-manager/file-manager-types.ts@@ -91,7 +91,13 @@ export interface FileManagerBulkActionConfirm {/** Optional column toggles. Both columns default to visible. */export interface FileManagerColumnsConfig {+ /** Disable sorting on the "Modified" column header. Defaults to `true`. */+ isModifiedSortable?: boolean;isModifiedVisible?: boolean;+ /** Disable sorting on the "Name" column header. Defaults to `true`. */+ isNameSortable?: boolean;+ /** Disable sorting on the "Size" column header. Defaults to `true`. */+ isSizeSortable?: boolean;isSizeVisible?: boolean;}@@ -156,6 +162,13 @@ export interface FileManagerLabels {selectAllAriaLabel?: string;/** Label rendered in the bulk bar, e.g. "3 selected". */selectedLabel?: (count: number) => string;+ /**+ * aria-label for a sortable column header button. Receives the column id and the+ * current sort direction (`null` when the column is not currently sorted), and+ * should describe the action the next click will perform. Defaults to a plain+ * English description like `"Sort by name (ascending)"`.+ */+ sortHeaderAriaLabel?: (column: FileManagerSortColumn, direction: FileManagerSortDirection | null) => string;}export interface FileManagerProps {@@ -193,6 +206,19 @@ export interface FileManagerProps {*/enableSelection?: boolean;files: FileNode[];+ /**+ * Initial sort applied on first render when no value is loaded from+ * `sortStorageKey`. Defaults to `null` (no sort, insertion order preserved).+ */+ initialSorting?: FileManagerSortState;+ /**+ * Group directories before files at every tree level when a sort is active.+ * Default: `true` — matches Finder/Explorer behaviour. Set to `false` to mix+ * directories and files together by the chosen sort criterion.+ *+ * Has no effect while sorting is `null` (insertion order is preserved as-is).+ */+ isFoldersFirst?: boolean;isLoading?: boolean;/** Localizable user-facing strings. */labels?: FileManagerLabels;@@ -262,10 +288,28 @@ export interface FileManagerProps {* mutating it will desync the manager's internal state.*/onSelectionChange?: (selectedPaths: ReadonlySet<string>) => void;+ /**+ * Fires whenever the active sort changes (header click). The supplied+ * callback is read through a ref, so it does not need to be memoized.+ */+ onSortingChange?: (sorting: FileManagerSortState) => void;/** Synthetic top-level groups (e.g. Uploads / Container). When omitted, root is flat. */rootGroups?: FileManagerRootGroup[];/** Search query and matching empty state. Provide `query` to enable filtering. */search?: FileManagerSearchConfig;+ /**+ * Controlled sort state. When set, the manager renders this value and+ * delegates updates to `onSortingChange` (it does NOT update its own+ * state and ignores `sortStorageKey`). Pass `null` to render with no sort.+ */+ sorting?: FileManagerSortState;+ /**+ * When set, the active sort is persisted to `localStorage` under this key+ * across page reloads. Ignored in controlled mode (when `sorting` is set).+ * Pass a route-scoped key (e.g. `getSortingStorageKey('/flows/files')`)+ * to avoid collisions across pages.+ */+ sortStorageKey?: string;}export interface FileManagerRootGroup {@@ -286,6 +330,18 @@ export interface FileManagerSearchConfig {query?: string;}+/** Sortable column identifier. Mirrors the visible column headers. */+export type FileManagerSortColumn = 'modified' | 'name' | 'size';++/** Direction of an active sort. */+export type FileManagerSortDirection = 'asc' | 'desc';++/** Active sort descriptor; `null` means "no sort, preserve insertion order". */+export type FileManagerSortState = null | {+ column: FileManagerSortColumn;+ direction: FileManagerSortDirection;+};+export interface FileNode {id: string;isDir: boolean;diff --git a/frontend/src/components/shared/file-manager/file-manager-utils.test.ts b/frontend/src/components/shared/file-manager/file-manager-utils.test.tsindex e19ef7d0..0bf49197 100644--- a/frontend/src/components/shared/file-manager/file-manager-utils.test.ts+++ b/frontend/src/components/shared/file-manager/file-manager-utils.test.ts@@ -1,3 +1,4 @@+import { subMonths, subYears } from 'date-fns';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { FileManagerInternalNode, FileManagerRootGroup, FileNode } from './file-manager-types';@@ -20,16 +21,19 @@ import {filterFileManagerTree,findNodeByPath,formatFileSize,- formatModified,+ formatModifiedAbsolute,+ formatModifiedRelative,getCheckboxState,isEverySelected,normalizeRootGroups,pluralizeItemsEnglish,removeAllFromSet,resolveSelectionModifier,+ sortFileManagerTree,toggleSubtreeOnSet,walkTree,} from './file-manager-utils';+import { computeNextSort } from './use-file-manager-sorting';const file = (path: string, overrides: Partial<FileNode> = {}): FileNode => ({id: path,@@ -66,7 +70,7 @@ describe('formatFileSize', () => {});});-describe('formatModified', () => {+describe('formatModifiedRelative', () => {const NOW = new Date('2026-04-28T12:00:00Z').getTime();beforeEach(() => {@@ -79,30 +83,88 @@ describe('formatModified', () => {});it('returns empty for missing/invalid input', () => {- expect(formatModified(undefined)).toBe('');- expect(formatModified('not-a-date')).toBe('');+ expect(formatModifiedRelative(undefined)).toBe('');+ expect(formatModifiedRelative('not-a-date')).toBe('');});it('handles "just now"', () => {- expect(formatModified(new Date(NOW - 10_000))).toBe('just now');+ expect(formatModifiedRelative(new Date(NOW - 10_000))).toBe('just now');});it('formats minutes / hours / days within a week', () => {- expect(formatModified(new Date(NOW - 5 * 60_000))).toBe('5m ago');- expect(formatModified(new Date(NOW - 3 * 60 * 60_000))).toBe('3h ago');- expect(formatModified(new Date(NOW - 4 * 24 * 60 * 60_000))).toBe('4d ago');+ expect(formatModifiedRelative(new Date(NOW - 5 * 60_000))).toBe('5m ago');+ expect(formatModifiedRelative(new Date(NOW - 3 * 60 * 60_000))).toBe('3h ago');+ expect(formatModifiedRelative(new Date(NOW - 4 * 24 * 60 * 60_000))).toBe('4d ago');});- it('falls back to locale date for older entries', () => {- const old = new Date(NOW - 14 * 24 * 60 * 60_000);+ it('formats weeks for entries within 4 weeks', () => {+ expect(formatModifiedRelative(new Date(NOW - 14 * 24 * 60 * 60_000))).toBe('2w ago');+ expect(formatModifiedRelative(new Date(NOW - 21 * 24 * 60 * 60_000))).toBe('3w ago');+ });++ it('formats months for entries within a year', () => {+ // 90 days ≈ 2 calendar months from the fake `NOW`. Using subMonths+ // instead of arithmetic keeps the test robust against month-length+ // variation (date-fns' differenceInMonths is calendar-based, not 30d).+ expect(formatModifiedRelative(subMonths(new Date(NOW), 2))).toBe('2mo ago');+ expect(formatModifiedRelative(subMonths(new Date(NOW), 6))).toBe('6mo ago');+ });- expect(formatModified(old)).toBe(old.toLocaleDateString());+ it('formats years for entries older than a year', () => {+ expect(formatModifiedRelative(subYears(new Date(NOW), 1))).toBe('1y ago');+ expect(formatModifiedRelative(subYears(new Date(NOW), 5))).toBe('5y ago');});it('accepts ISO strings', () => {const iso = new Date(NOW - 10 * 60_000).toISOString();- expect(formatModified(iso)).toBe('10m ago');+ expect(formatModifiedRelative(iso)).toBe('10m ago');+ });+});++describe('formatModifiedAbsolute', () => {+ // Use local-time constructors throughout: `format()` and `isToday` /+ // `isThisYear` resolve in the host TZ, so anchoring the fake clock to+ // a UTC literal would let the rendered hours / "today" boundary drift+ // depending on where the test runs (CI's TZ is not guaranteed).+ const NOW = new Date(2026, 3, 28, 14, 30);++ beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(NOW);+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it('returns empty for missing/invalid input', () => {+ expect(formatModifiedAbsolute(undefined)).toBe('');+ expect(formatModifiedAbsolute('not-a-date')).toBe('');+ });++ it('renders only the time for today', () => {+ expect(formatModifiedAbsolute(new Date(2026, 3, 28, 9, 5))).toBe('09:05');+ expect(formatModifiedAbsolute(new Date(2026, 3, 28, 23, 59))).toBe('23:59');+ });++ it('renders day, month and time within the current calendar year', () => {+ expect(formatModifiedAbsolute(new Date(2026, 0, 3, 8, 7))).toBe('3 Jan, 08:07');+ expect(formatModifiedAbsolute(new Date(2026, 11, 15, 18, 0))).toBe('15 Dec, 18:00');+ });++ it('includes the year for entries from previous calendar years', () => {+ expect(formatModifiedAbsolute(new Date(2024, 5, 1, 6, 30))).toBe('1 Jun 2024, 06:30');+ expect(formatModifiedAbsolute(new Date(2020, 11, 31, 23, 45))).toBe('31 Dec 2020, 23:45');+ });++ it('accepts ISO strings', () => {+ // Build the ISO from the same local-time `Date` so the render is stable+ // across host time zones — toISOString() shifts to UTC, but formatting+ // back through the local clock returns the original wall-clock time.+ const local = new Date(2026, 2, 14, 10, 5);++ expect(formatModifiedAbsolute(local.toISOString())).toBe('14 Mar, 10:05');});});@@ -1661,3 +1723,156 @@ describe('computeDirSelectionState — synthetic group root (path === "")', () =).toBe('indeterminate');});});++describe('sortFileManagerTree', () => {+ const collectNames = (nodes: FileManagerInternalNode[]): string[] =>+ nodes.flatMap((n) => [n.name, ...collectNames(n.children)]);++ const collectTopNames = (nodes: FileManagerInternalNode[]): string[] => nodes.map((n) => n.name);++ it('returns input unchanged (by reference) when sorting is null AND isFoldersFirst is false', () => {+ const tree = buildFileManagerTree([file('b.txt'), file('a.txt')]);+ const result = sortFileManagerTree(tree, null, false);++ expect(result).toBe(tree);+ });++ it('partitions folders before files when sorting=null and isFoldersFirst=true', () => {+ // Insertion order is `b.txt`, `alpha/...`, `a.txt`, `beta/...`. With no+ // active sort and isFoldersFirst=true, the partitioner pulls folders to+ // the top while *preserving* the original order WITHIN each partition.+ const tree = buildFileManagerTree([+ file('b.txt'),+ file('alpha/inner.txt'),+ file('a.txt'),+ file('beta/inner.txt'),+ ]);+ const sorted = sortFileManagerTree(tree, null, true);++ // `buildFileManagerTree` itself sorts the input by path before walking,+ // so folders appear in path-alphabetical order (`alpha`, `beta`) and+ // files likewise (`a.txt`, `b.txt`). The folders-first partition keeps+ // both groups intact, only flipping their relative position.+ expect(collectTopNames(sorted)).toEqual(['alpha', 'beta', 'a.txt', 'b.txt']);+ });++ it('preserves insertion order within each partition when sorting=null', () => {+ // Same structure as above but verifying stability explicitly. Since+ // `buildFileManagerTree` pre-sorts files by path, the file partition+ // here reads in path order (z, then m), and the folder partition+ // contains a single entry. The point is no comparator runs, only the+ // folders-first partition.+ const tree = buildFileManagerTree([file('m.txt'), file('z.txt'), file('dir/inner.txt')]);+ const sorted = sortFileManagerTree(tree, null, true);++ expect(collectTopNames(sorted)).toEqual(['dir', 'm.txt', 'z.txt']);+ });++ it('sorts files alphabetically asc with isFoldersFirst=true', () => {+ const tree = buildFileManagerTree([file('b.txt'), file('a.txt'), dir('zzz'), file('c.txt')]);+ const sorted = sortFileManagerTree(tree, { column: 'name', direction: 'asc' }, true);++ expect(collectTopNames(sorted)).toEqual(['zzz', 'a.txt', 'b.txt', 'c.txt']);+ });++ it('sorts files alphabetically desc', () => {+ const tree = buildFileManagerTree([file('a.txt'), file('b.txt'), file('c.txt')]);+ const sorted = sortFileManagerTree(tree, { column: 'name', direction: 'desc' }, false);++ expect(collectTopNames(sorted)).toEqual(['c.txt', 'b.txt', 'a.txt']);+ });++ it('mixes folders with files when isFoldersFirst=false', () => {+ const tree = buildFileManagerTree([file('alpha/file.txt'), file('zzz.txt'), file('beta/file.txt')]);+ const sorted = sortFileManagerTree(tree, { column: 'name', direction: 'asc' }, false);++ expect(collectTopNames(sorted)).toEqual(['alpha', 'beta', 'zzz.txt']);+ });++ it('keeps folders above files when isFoldersFirst=true', () => {+ const tree = buildFileManagerTree([+ file('alpha/file.txt'),+ file('zzz.txt'),+ file('beta/file.txt'),+ file('aaa.txt'),+ ]);+ const sorted = sortFileManagerTree(tree, { column: 'name', direction: 'asc' }, true);++ expect(collectTopNames(sorted)).toEqual(['alpha', 'beta', 'aaa.txt', 'zzz.txt']);+ });++ it('sorts by size with `0` fallback for files lacking the field', () => {+ const tree = buildFileManagerTree([+ file('a.txt', { size: 100 }),+ file('b.txt', { size: 50 }),+ file('c.txt', { size: 200 }),+ ]);+ const sorted = sortFileManagerTree(tree, { column: 'size', direction: 'asc' }, false);++ expect(collectTopNames(sorted)).toEqual(['b.txt', 'a.txt', 'c.txt']);+ });++ it('sorts by modified ascending then descending', () => {+ const tree = buildFileManagerTree([+ file('a.txt', { modifiedAt: '2024-01-01' }),+ file('b.txt', { modifiedAt: '2026-01-01' }),+ file('c.txt', { modifiedAt: '2025-01-01' }),+ ]);+ const ascending = sortFileManagerTree(tree, { column: 'modified', direction: 'asc' }, false);+ const descending = sortFileManagerTree(tree, { column: 'modified', direction: 'desc' }, false);++ expect(collectTopNames(ascending)).toEqual(['a.txt', 'c.txt', 'b.txt']);+ expect(collectTopNames(descending)).toEqual(['b.txt', 'c.txt', 'a.txt']);+ });++ it('preserves the order of synthetic group roots but sorts their children', () => {+ const groups: FileManagerRootGroup[] = [+ { id: 'uploads', label: 'Uploads', pathPrefix: 'uploads' },+ { id: 'container', label: 'Container', pathPrefix: 'container' },+ ];+ const tree = buildFileManagerTree(+ [file('uploads/b.txt'), file('uploads/a.txt'), file('container/x.txt'), file('container/m.txt')],+ groups,+ );++ const sorted = sortFileManagerTree(tree, { column: 'name', direction: 'asc' }, false);++ expect(collectTopNames(sorted)).toEqual(['Uploads', 'Container']);+ expect(collectNames(sorted[0]?.children ?? [])).toEqual(['a.txt', 'b.txt']);+ expect(collectNames(sorted[1]?.children ?? [])).toEqual(['m.txt', 'x.txt']);+ });++ it('recursively sorts nested folder children', () => {+ const tree = buildFileManagerTree([file('outer/sub/c.txt'), file('outer/sub/a.txt'), file('outer/sub/b.txt')]);+ const sorted = sortFileManagerTree(tree, { column: 'name', direction: 'asc' }, true);++ const outer = sorted[0];+ const sub = outer?.children[0];+ expect(sub?.name).toBe('sub');+ expect(collectTopNames(sub?.children ?? [])).toEqual(['a.txt', 'b.txt', 'c.txt']);+ });+});++describe('computeNextSort', () => {+ it('cycles none → asc', () => {+ expect(computeNextSort(null, 'name')).toEqual({ column: 'name', direction: 'asc' });+ });++ it('cycles asc → desc on the same column', () => {+ expect(computeNextSort({ column: 'name', direction: 'asc' }, 'name')).toEqual({+ column: 'name',+ direction: 'desc',+ });+ });++ it('cycles desc → none on the same column', () => {+ expect(computeNextSort({ column: 'name', direction: 'desc' }, 'name')).toBeNull();+ });++ it('switches to a different column starting at asc', () => {+ expect(computeNextSort({ column: 'name', direction: 'desc' }, 'size')).toEqual({+ column: 'size',+ direction: 'asc',+ });+ });+});diff --git a/frontend/src/components/shared/file-manager/file-manager-utils.ts b/frontend/src/components/shared/file-manager/file-manager-utils.tsindex fe13cd30..f2caa02f 100644--- a/frontend/src/components/shared/file-manager/file-manager-utils.ts+++ b/frontend/src/components/shared/file-manager/file-manager-utils.ts@@ -1,6 +1,26 @@import type { MouseEvent as ReactMouseEvent } from 'react';-import type { FileManagerInternalNode, FileManagerRootGroup, FileNode } from './file-manager-types';+import {+ differenceInDays,+ differenceInHours,+ differenceInMinutes,+ differenceInMonths,+ differenceInSeconds,+ differenceInWeeks,+ differenceInYears,+ format,+ isThisYear,+ isToday,+ isValid,+} from 'date-fns';+import { enUS } from 'date-fns/locale';++import type {+ FileManagerInternalNode,+ FileManagerRootGroup,+ FileManagerSortState,+ FileNode,+} from './file-manager-types';export const formatFileSize = (size?: number): string => {if (size == null) {@@ -23,42 +43,91 @@ export const formatFileSize = (size?: number): string => {return `${value.toFixed(value >= 10 ? 0 : 1)} ${units[unitIndex]}`;};-export const formatModified = (modifiedAt?: Date | string): string => {+export const formatModifiedRelative = (modifiedAt?: Date | string): string => {if (!modifiedAt) {return '';}const date = typeof modifiedAt === 'string' ? new Date(modifiedAt) : modifiedAt;- if (Number.isNaN(date.getTime())) {+ if (!isValid(date)) {return '';}const now = Date.now();- const diffMs = now - date.getTime();- const diffMin = Math.round(diffMs / 60_000);-- if (diffMin < 1) {+ // All `differenceIn*` helpers are computed up-front so each branch's+ // fallback (`!minutes`, `!hours`, …) can guard against the upper unit+ // rounding down to zero — without it, an edge case like 59 minutes 30s+ // could fall through to the next branch and render as `0h ago`.+ const seconds = differenceInSeconds(now, date);+ const minutes = differenceInMinutes(now, date);+ const hours = differenceInHours(now, date);+ const days = differenceInDays(now, date);+ const weeks = differenceInWeeks(now, date);+ const months = differenceInMonths(now, date);+ const years = differenceInYears(now, date);++ if (seconds < 60 || !minutes) {return 'just now';}- if (diffMin < 60) {- return `${diffMin}m ago`;+ if (minutes < 60 || !hours) {+ return `${minutes}m ago`;+ }++ if (hours < 24 || !days) {+ return `${hours}h ago`;+ }++ if (days < 7 || !weeks) {+ return `${days}d ago`;+ }++ if (weeks < 4 || !months) {+ return `${weeks}w ago`;+ }++ if (months < 12 || !years) {+ return `${months}mo ago`;+ }++ return `${years}y ago`;+};++/**+ * Alternative "Modified" formatter that prints an absolute, minute-precision+ * timestamp instead of a relative ("5m ago") label. Used by hosts that let+ * the user opt out of relative dates via a column toggle — see `resources.tsx`.+ *+ * The output is contextual, mirroring `lib/utils/format.ts#formatDate`:+ * - same day → `HH:mm` (e.g. `14:32`)+ * - same calendar year → `d MMM, HH:mm` (e.g. `15 Apr, 14:32`)+ * - any other year → `d MMM yyyy, HH:mm` (e.g. `15 Apr 2024, 14:32`)+ *+ * Locale is forced to `en-US` so day/month tokens stay stable regardless of+ * the user's browser locale (matches the rest of the FileManager UI strings,+ * which are English-only by default).+ */+export const formatModifiedAbsolute = (modifiedAt?: Date | string): string => {+ if (!modifiedAt) {+ return '';}- const diffHours = Math.round(diffMin / 60);+ const date = typeof modifiedAt === 'string' ? new Date(modifiedAt) : modifiedAt;- if (diffHours < 24) {- return `${diffHours}h ago`;+ if (!isValid(date)) {+ return '';}- const diffDays = Math.round(diffHours / 24);+ if (isToday(date)) {+ return format(date, 'HH:mm');+ }- if (diffDays < 7) {- return `${diffDays}d ago`;+ if (isThisYear(date)) {+ return format(date, 'd MMM, HH:mm', { locale: enUS });}- return date.toLocaleDateString();+ return format(date, 'd MMM yyyy, HH:mm', { locale: enUS });};/** Strip trailing slashes from a `pathPrefix`. Empty / `'/'` collapse to `''`. */@@ -301,6 +370,134 @@ export const collectDirectoryPaths = (nodes: FileManagerInternalNode[]): string[include: (node) => node.isDir,});+/** Locale-aware case-insensitive name comparator. */+const compareNames = (a: FileManagerInternalNode, b: FileManagerInternalNode): number =>+ a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: 'base' });++/**+ * Compare by `size`. Directories and synthetic group roots have no own size —+ * they are treated as `0` so the comparator stays total. Combined with the+ * default `isFoldersFirst: true`, directories never actually mix with files+ * inside a single comparator call.+ */+const compareSizes = (a: FileManagerInternalNode, b: FileManagerInternalNode): number => {+ const aSize = a.isDir || a.isGroupRoot ? 0 : (a.size ?? 0);+ const bSize = b.isDir || b.isGroupRoot ? 0 : (b.size ?? 0);++ return aSize - bSize;+};++const toTimestamp = (value: Date | string | undefined): number => {+ if (!value) {+ return 0;+ }++ const date = typeof value === 'string' ? new Date(value) : value;+ const time = date.getTime();++ return Number.isNaN(time) ? 0 : time;+};++const compareModified = (a: FileManagerInternalNode, b: FileManagerInternalNode): number =>+ toTimestamp(a.modifiedAt) - toTimestamp(b.modifiedAt);++const SORT_COMPARATORS = {+ modified: compareModified,+ name: compareNames,+ size: compareSizes,+} as const;++/**+ * Recursively sort the tree by the given criterion. Pure: returns freshly+ * cloned arrays so React reference-equality bail-outs still work for+ * memoized consumers; nodes themselves are reused by reference (only the+ * `children` array is rebuilt for nodes whose children actually changed).+ *+ * Sort rules:+ * - The synthetic group-root level (top level when groups are configured) is+ * never re-ordered — groups must follow the order specified in `rootGroups`.+ * Their children are sorted as usual.+ * - When `isFoldersFirst` is true (default), directories are grouped above+ * files at every level. This applies even when `sorting` is `null` —+ * within each group (folders / files) the original insertion order is+ * preserved (`Array.sort` is stable per the TC39 spec).+ * - When a `sorting` is supplied, the comparator runs *inside* each group+ * after the folders-first partition. A stable secondary sort by `name`+ * breaks ties so the result is deterministic across renders.+ * - When both `sorting` is `null` AND `isFoldersFirst` is `false`, the input+ * is returned by reference — zero-cost pass-through for the no-op case.+ */+export const sortFileManagerTree = (+ nodes: readonly FileManagerInternalNode[],+ sorting: FileManagerSortState,+ isFoldersFirst: boolean,+): FileManagerInternalNode[] => {+ if (!sorting && !isFoldersFirst) {+ return nodes as FileManagerInternalNode[];+ }++ const comparator = sorting ? SORT_COMPARATORS[sorting.column] : null;+ const directionMultiplier = sorting?.direction === 'desc' ? -1 : 1;++ const sortLevel = (level: readonly FileManagerInternalNode[], skipReorder: boolean): FileManagerInternalNode[] => {+ const recursed = level.map((node) => {+ if (node.children.length === 0) {+ return node;+ }++ const sortedChildren = sortLevel(node.children, false);++ return sortedChildren === node.children ? node : { ...node, children: sortedChildren };+ });++ if (skipReorder) {+ return recursed;+ }++ const reordered = [...recursed].sort((a, b) => {+ // `isFoldersFirst` is treated as a primary partition before any+ // other criterion so directories always stay above files+ // regardless of the active comparator (or its absence).+ if (isFoldersFirst) {+ const aIsDir = a.isDir || a.isGroupRoot;+ const bIsDir = b.isDir || b.isGroupRoot;++ if (aIsDir !== bIsDir) {+ return aIsDir ? -1 : 1;+ }+ }++ // No comparator → preserve insertion order within each partition+ // (Array.sort is stable per the TC39 spec since 2019).+ if (!comparator) {+ return 0;+ }++ const primary = comparator(a, b) * directionMultiplier;++ if (primary !== 0) {+ return primary;+ }++ // Stable secondary sort by name so equal-by-criterion rows have a+ // deterministic order across renders. Direction is preserved so+ // `desc` still reads top-down alphabetically reversed.+ return compareNames(a, b) * directionMultiplier;+ });++ return reordered;+ };++ // Top-level group roots keep their declared order. We detect that case by+ // checking whether every root is a group root — if any root is a regular+ // node, the level is sorted normally. Children of group roots are always+ // sorted (the recursion call inside `sortLevel` re-enables sorting via+ // `skipReorder = false`).+ const skipTopReorder = nodes.length > 0 && nodes.every((node) => node.isGroupRoot);++ return sortLevel(nodes, skipTopReorder);+};+export const resolveSelectionModifier = (event: KeyboardEvent | MouseEvent | ReactMouseEvent,): 'range' | 'single' | 'toggle' => {diff --git a/frontend/src/components/shared/file-manager/file-manager.tsx b/frontend/src/components/shared/file-manager/file-manager.tsxindex 1c1f94bb..9d52858e 100644--- a/frontend/src/components/shared/file-manager/file-manager.tsx+++ b/frontend/src/components/shared/file-manager/file-manager.tsx@@ -1,3 +1,4 @@+import { ArrowDown, ArrowUp } from 'lucide-react';import {type MouseEvent as ReactMouseEvent,type ReactNode,@@ -8,6 +9,7 @@ import {useState,} from 'react';+import { Button } from '@/components/ui/button';import { Checkbox } from '@/components/ui/checkbox';import {ContextMenu,@@ -16,6 +18,7 @@ import {ContextMenuSeparator,ContextMenuTrigger,} from '@/components/ui/context-menu';+import { useLatestRef } from '@/hooks/use-latest-ref';import { cn } from '@/lib/utils';import type { FileManagerRowDisplay, FileManagerRowHandlers } from './file-manager-row';@@ -24,6 +27,8 @@ import type {FileManagerBulkAction,FileManagerEmptyAreaAction,FileManagerProps,+ FileManagerSortColumn,+ FileManagerSortDirection,FileNode,} from './file-manager-types';@@ -43,11 +48,35 @@ import { useFileManagerDnd } from './use-file-manager-dnd';import { useFileManagerExpansion } from './use-file-manager-expansion';import { useFileManagerKeyboardNavigation } from './use-file-manager-keyboard';import { useFileManagerSelection } from './use-file-manager-selection';+import { useFileManagerSorting } from './use-file-manager-sorting';const EMPTY_ACTIONS: readonly FileManagerAction[] = Object.freeze([]);const EMPTY_BULK_ACTIONS: readonly FileManagerBulkAction[] = Object.freeze([]);const EMPTY_AREA_ACTIONS: readonly FileManagerEmptyAreaAction[] = Object.freeze([]);+const COLUMN_LABEL_FOR_ARIA: Record<FileManagerSortColumn, string> = {+ modified: 'modified date',+ name: 'name',+ size: 'size',+};++const defaultSortHeaderAriaLabel = (+ column: FileManagerSortColumn,+ direction: FileManagerSortDirection | null,+): string => {+ const label = COLUMN_LABEL_FOR_ARIA[column];++ if (direction === 'asc') {+ return `Sort by ${label} (descending)`;+ }++ if (direction === 'desc') {+ return `Clear sorting on ${label}`;+ }++ return `Sort by ${label} (ascending)`;+};+/*** Renders the right-click context menu items for the empty area of the tree.* Kept as a plain helper so the same JSX can be reused inside the@@ -90,6 +119,8 @@ export const FileManager = ({emptyState,enableSelection,files,+ initialSorting,+ isFoldersFirst = true,isLoading,labels,onActiveRowChange,@@ -98,14 +129,28 @@ export const FileManager = ({onOpen,onOpenDirectory,onSelectionChange,+ onSortingChange,rootGroups,search,+ sorting: controlledSorting,+ sortStorageKey,}: FileManagerProps) => {const effectiveBulkActions = bulkActions ?? EMPTY_BULK_ACTIONS;const hasBulkActions = effectiveBulkActions.length > 0;const isCheckboxVisible = enableSelection ?? hasBulkActions;const hasActions = !!actions?.length;+ const isNameSortable = columns?.isNameSortable ?? true;+ const isSizeSortable = columns?.isSizeSortable ?? true;+ const isModifiedSortable = columns?.isModifiedSortable ?? true;++ const { sorting, toggleSort } = useFileManagerSorting({+ controlledSorting,+ initialSorting,+ onSortingChange,+ sortStorageKey,+ });+const {allSelectablePaths,dirSubtreePaths,@@ -121,8 +166,10 @@ export const FileManager = ({columns,files,hasActions,+ isFoldersFirst,rootGroups,searchQuery: search?.query,+ sorting,});const { expandedPaths, toggleExpand } = useFileManagerExpansion({@@ -181,43 +228,40 @@ export const FileManager = ({// Report selection changes upstream without forcing parents to memoize the// callback — stash it in a ref so the effect only re-fires when the actual// selection changes (not when a fresh function instance is passed in).- const onSelectionChangeRef = useRef(onSelectionChange);-- useEffect(() => {- onSelectionChangeRef.current = onSelectionChange;- }, [onSelectionChange]);+ const onSelectionChangeRef = useLatestRef(onSelectionChange);useEffect(() => {onSelectionChangeRef.current?.(selectedPaths);+ // `onSelectionChangeRef` is a stable ref; only `selectedPaths` should+ // re-trigger the upstream emit.+ // eslint-disable-next-line react-hooks/exhaustive-deps}, [selectedPaths]);// Same latest-ref pattern for `onOpen` / `onOpenDirectory`: both bleed into// the keyboard handler's deps and through `TreeNode` → `Row`, so a// non-memoized parent callback would otherwise invalidate the memo on every// row whenever the parent re-renders.- const onOpenRef = useRef(onOpen);- const onOpenDirectoryRef = useRef(onOpenDirectory);-- useEffect(() => {- onOpenRef.current = onOpen;- }, [onOpen]);+ const onOpenRef = useLatestRef(onOpen);+ const onOpenDirectoryRef = useLatestRef(onOpenDirectory);- useEffect(() => {- onOpenDirectoryRef.current = onOpenDirectory;- }, [onOpenDirectory]);-- const handleOpen = useCallback((file: FileNode) => {- onOpenRef.current?.(file);- }, []);+ const handleOpen = useCallback(+ (file: FileNode) => {+ onOpenRef.current?.(file);+ },+ [onOpenRef],+ );// We need the row + keyboard handler to know whether the consumer registered// a custom directory-open callback so the default expand/collapse is bypassed// only when an override actually exists. Wrapping in a stable callback keeps// the row memo intact across parent re-renders, but we conditionally pass it// (vs. an always-defined wrapper) by gating on the prop reference itself.- const handleOpenDirectory = useCallback((dir: FileNode) => {- onOpenDirectoryRef.current?.(dir);- }, []);+ const handleOpenDirectory = useCallback(+ (dir: FileNode) => {+ onOpenDirectoryRef.current?.(dir);+ },+ [onOpenDirectoryRef],+ );const stableHandleOpenDirectory = onOpenDirectory ? handleOpenDirectory : undefined;@@ -239,14 +283,11 @@ export const FileManager = ({// emit the raw `activeRowPath` (not `resolvedActiveRow`) so consumers can// distinguish "user picked something" from the auto-fallback to the first// visible row that the roving tabindex uses internally.- const onActiveRowChangeRef = useRef(onActiveRowChange);-- useEffect(() => {- onActiveRowChangeRef.current = onActiveRowChange;- }, [onActiveRowChange]);+ const onActiveRowChangeRef = useLatestRef(onActiveRowChange);useEffect(() => {onActiveRowChangeRef.current?.(activeRowPath);+ // eslint-disable-next-line react-hooks/exhaustive-deps}, [activeRowPath]);const focusRow = useCallback((path: null | string) => {@@ -307,6 +348,28 @@ export const FileManager = ({const formatModified = effectiveLabels.formatModified;const effectiveActions = actions ?? EMPTY_ACTIONS;const searchQuery = trimmedSearch || undefined;+ const sortHeaderAriaLabel = effectiveLabels.sortHeaderAriaLabel ?? defaultSortHeaderAriaLabel;++ const renderSortableHeader = (column: FileManagerSortColumn, label: string, isSortable: boolean) => {+ if (!isSortable) {+ return <span aria-hidden="true">{label}</span>;+ }++ const direction: FileManagerSortDirection | null = sorting?.column === column ? sorting.direction : null;++ return (+ <Button+ aria-label={sortHeaderAriaLabel(column, direction)}+ aria-sort={direction === 'asc' ? 'ascending' : direction === 'desc' ? 'descending' : 'none'}+ className="text-muted-foreground hover:text-primary -mx-2 flex h-auto justify-start gap-1.5 px-2 py-1 text-xs font-medium no-underline hover:no-underline"+ onClick={() => toggleSort(column)}+ variant="link"+ >+ {label}+ {direction === 'asc' ? <ArrowDown /> : direction === 'desc' ? <ArrowUp /> : null}+ </Button>+ );+ };// Bundle all per-tree-shared layout / i18n props into a single object so the// memoized `FileManagerRow` only does one reference check (instead of seven@@ -418,13 +481,13 @@ export const FileManager = ({return (<div- className={cn('bg-card flex flex-col overflow-hidden rounded-lg border', className)}+ className={cn('flex flex-col overflow-hidden rounded-lg border', className)}onClick={handleContainerClick}onKeyDown={handleKeyDown}ref={containerRef}><div- className="bg-muted/30 text-muted-foreground grid items-center gap-3 border-b px-3 py-2 text-xs font-medium"+ className="text-muted-foreground grid items-center gap-3 border-b px-3 py-2 text-xs font-medium"style={{ gridTemplateColumns: gridTemplate }}>{isCheckboxVisible ? (@@ -439,9 +502,10 @@ export const FileManager = ({className="size-4"/>)}- <span aria-hidden="true">{effectiveLabels.columnName ?? 'Name'}</span>- {isSizeVisible && <span aria-hidden="true">{effectiveLabels.columnSize ?? 'Size'}</span>}- {isModifiedVisible && <span aria-hidden="true">{effectiveLabels.columnModified ?? 'Modified'}</span>}+ {renderSortableHeader('name', effectiveLabels.columnName ?? 'Name', isNameSortable)}+ {isSizeVisible && renderSortableHeader('size', effectiveLabels.columnSize ?? 'Size', isSizeSortable)}+ {isModifiedVisible &&+ renderSortableHeader('modified', effectiveLabels.columnModified ?? 'Modified', isModifiedSortable)}{hasActions && (<spanaria-hidden="true"diff --git a/frontend/src/components/shared/file-manager/index.ts b/frontend/src/components/shared/file-manager/index.tsindex bd41a834..b14fcc36 100644--- a/frontend/src/components/shared/file-manager/index.ts+++ b/frontend/src/components/shared/file-manager/index.ts@@ -16,10 +16,14 @@ export type {FileManagerAction,FileManagerBulkAction,FileManagerBulkActionConfirm,+ FileManagerColumnsConfig,FileManagerEmptyAreaAction,FileManagerLabels,FileManagerProps,FileManagerRootGroup,+ FileManagerSortColumn,+ FileManagerSortDirection,+ FileManagerSortState,FileNode,} from './file-manager-types';-export { dedupeOverlappingPaths } from './file-manager-utils';+export { dedupeOverlappingPaths, formatModifiedAbsolute, formatModifiedRelative } from './file-manager-utils';diff --git a/frontend/src/components/shared/file-manager/use-file-manager-data.ts b/frontend/src/components/shared/file-manager/use-file-manager-data.tsindex dbaffb8b..c6b64272 100644--- a/frontend/src/components/shared/file-manager/use-file-manager-data.ts+++ b/frontend/src/components/shared/file-manager/use-file-manager-data.ts@@ -4,6 +4,7 @@ import type {FileManagerColumnsConfig,FileManagerInternalNode,FileManagerRootGroup,+ FileManagerSortState,FileNode,} from './file-manager-types';@@ -14,6 +15,7 @@ import {collectSubtreePaths,filterFileManagerTree,normalizeRootGroups,+ sortFileManagerTree,} from './file-manager-utils';interface UseFileManagerDataArgs {@@ -25,9 +27,16 @@ interface UseFileManagerDataArgs {* — `FileManager` and the row component must agree on the same `gridTemplate`.*/hasActions: boolean;+ /**+ * Whether to keep directories above files at every level when a sort is+ * active. When `null`/no sort, this flag is a no-op.+ */+ isFoldersFirst: boolean;rootGroups: FileManagerRootGroup[] | undefined;/** Raw `search.query` from props; trimming and emptiness checks live inside the hook. */searchQuery: string | undefined;+ /** Active sort descriptor; `null` preserves insertion order. */+ sorting: FileManagerSortState;}interface UseFileManagerDataResult {@@ -87,8 +96,10 @@ export const useFileManagerData = ({columns,files,hasActions,+ isFoldersFirst,rootGroups,searchQuery,+ sorting,}: UseFileManagerDataArgs): UseFileManagerDataResult => {const isSizeVisible = columns?.isSizeVisible ?? true;const isModifiedVisible = columns?.isModifiedVisible ?? true;@@ -100,10 +111,16 @@ export const useFileManagerData = ({const trimmedSearch = searchQuery?.trim() ?? '';const isFiltering = trimmedSearch.length > 0;- const visibleTree = useMemo(- () => (isFiltering ? filterFileManagerTree(fullTree, trimmedSearch) : fullTree),- [fullTree, isFiltering, trimmedSearch],- );+ // Sorting is applied AFTER the search filter so the filtered visible tree+ // reads in the user's chosen order. `sortFileManagerTree` returns the+ // input untouched when `sorting` is `null`, so the no-sort case stays a+ // zero-cost reference pass-through (the parent `useMemo` below still+ // bails out via reference equality).+ const visibleTree = useMemo(() => {+ const filtered = isFiltering ? filterFileManagerTree(fullTree, trimmedSearch) : fullTree;++ return sortFileManagerTree(filtered, sorting, isFoldersFirst);+ }, [fullTree, isFiltering, isFoldersFirst, sorting, trimmedSearch]);const allSelectablePaths = useMemo(() => collectAllNodePaths(visibleTree), [visibleTree]);diff --git a/frontend/src/components/shared/file-manager/use-file-manager-sorting.ts b/frontend/src/components/shared/file-manager/use-file-manager-sorting.tsnew file mode 100644index 00000000..a6d337e0--- /dev/null+++ b/frontend/src/components/shared/file-manager/use-file-manager-sorting.ts@@ -0,0 +1,134 @@+import { useCallback, useEffect, useRef, useState } from 'react';++import { useEffectAfterMount } from '@/hooks/use-effect-after-mount';++import type { FileManagerSortColumn, FileManagerSortState } from './file-manager-types';++import { loadFileManagerSorting, saveFileManagerSorting } from './file-manager-storage';++interface UseFileManagerSortingArgs {+ /**+ * Controlled sort value. When provided, the hook does not own state and+ * delegates updates to `onSortingChange`. Persistence (`sortStorageKey`)+ * is also bypassed — the parent owns the lifecycle.+ */+ controlledSorting?: FileManagerSortState;+ /**+ * Initial value used when no `sortStorageKey` payload is found. Ignored in+ * controlled mode (when `controlledSorting` is not undefined).+ */+ initialSorting?: FileManagerSortState;+ /** Fires whenever the active sort changes (uncontrolled mode only). */+ onSortingChange?: (sorting: FileManagerSortState) => void;+ /**+ * `localStorage` key for persisting the active sort between reloads.+ * Ignored in controlled mode. Pass `undefined` to disable persistence.+ */+ sortStorageKey?: string;+}++interface UseFileManagerSortingResult {+ /** Current active sort. `null` means "no sort, insertion order preserved". */+ sorting: FileManagerSortState;+ /**+ * Cycle the sort state for the given column following the+ * `none → asc → desc → none` order — matches DataTable header behaviour.+ * - First click on an unsorted column → `asc`.+ * - Click on a column already sorted `asc` → flip to `desc`.+ * - Click on a column already sorted `desc` → clear.+ * - Click on a *different* column → switch to that column at `asc`.+ */+ toggleSort: (column: FileManagerSortColumn) => void;+}++/**+ * Owns the active sort for a `FileManager`. Supports three modes:+ * 1. **Uncontrolled, ephemeral** — `sortStorageKey` and `controlledSorting`+ * both omitted. State lives only for the component lifetime.+ * 2. **Uncontrolled, persisted** — `sortStorageKey` is set. State is loaded+ * from `localStorage` on mount and rewritten whenever the user changes it.+ * 3. **Controlled** — `controlledSorting` is set. The hook reflects that+ * value verbatim and fires `onSortingChange` on user interaction.+ */+export const useFileManagerSorting = ({+ controlledSorting,+ initialSorting = null,+ onSortingChange,+ sortStorageKey,+}: UseFileManagerSortingArgs): UseFileManagerSortingResult => {+ const isControlled = controlledSorting !== undefined;++ // `localStorage` access is guarded inside `loadFileManagerSorting`, so the+ // lazy initializer is safe in SSR-style environments too.+ const [internalSorting, setInternalSorting] = useState<FileManagerSortState>(() => {+ if (isControlled) {+ return controlledSorting ?? null;+ }++ if (sortStorageKey) {+ const stored = loadFileManagerSorting(sortStorageKey);++ if (stored !== null) {+ return stored;+ }+ }++ return initialSorting;+ });++ const sorting = isControlled ? (controlledSorting ?? null) : internalSorting;++ useEffectAfterMount(() => {+ if (!isControlled && sortStorageKey) {+ saveFileManagerSorting(sortStorageKey, internalSorting);+ }+ }, [internalSorting, sortStorageKey, isControlled]);++ // Latest-ref trick keeps `toggleSort` stable across re-renders even when+ // the parent passes a fresh `onSortingChange` callback or the resolved+ // sort value changes between renders.+ const onSortingChangeRef = useRef(onSortingChange);+ const sortingRef = useRef(sorting);++ useEffect(() => {+ onSortingChangeRef.current = onSortingChange;+ }, [onSortingChange]);++ useEffect(() => {+ sortingRef.current = sorting;+ }, [sorting]);++ const isControlledRef = useRef(isControlled);++ useEffect(() => {+ isControlledRef.current = isControlled;+ }, [isControlled]);++ const toggleSort = useCallback((column: FileManagerSortColumn) => {+ const next = computeNextSort(sortingRef.current, column);++ if (!isControlledRef.current) {+ setInternalSorting(next);+ }++ onSortingChangeRef.current?.(next);+ }, []);++ return { sorting, toggleSort };+};++/** Pure reducer for the header three-state cycle. Exported for unit tests. */+export const computeNextSort = (+ current: FileManagerSortState,+ column: FileManagerSortColumn,+): FileManagerSortState => {+ if (current?.column !== column) {+ return { column, direction: 'asc' };+ }++ if (current.direction === 'asc') {+ return { column, direction: 'desc' };+ }++ return null;+};diff --git a/frontend/src/components/shared/markdown-editor.tsx b/frontend/src/components/shared/markdown-editor.tsxindex 5706f17d..c9135e96 100644--- a/frontend/src/components/shared/markdown-editor.tsx+++ b/frontend/src/components/shared/markdown-editor.tsx@@ -61,6 +61,12 @@ const MarkdownEditor = forwardRef<MarkdownEditorHandle, MarkdownEditorProps>() => {const onChangeRef = useRef(onChange);const onBlurRef = useRef(onBlur);+ // Tracks the last markdown the editor reported externally. We compare+ // against this to suppress echo updates: tiptap-markdown can re-serialize+ // content slightly differently than the input string (whitespace/list+ // markers/etc.), and we don't want to flag those normalizations as user+ // edits — that would falsely flip RHF's `isDirty` flag.+ const lastEmittedRef = useRef<string>(value);useEffect(() => {onChangeRef.current = onChange;@@ -90,7 +96,14 @@ const MarkdownEditor = forwardRef<MarkdownEditorHandle, MarkdownEditorProps>(immediatelyRender: false,onBlur: () => onBlurRef.current?.(),onUpdate: ({ editor: instance }) => {- onChangeRef.current?.(instance.storage.markdown.getMarkdown());+ const next = instance.storage.markdown.getMarkdown();++ if (next === lastEmittedRef.current) {+ return;+ }++ lastEmittedRef.current = next;+ onChangeRef.current?.(next);},});@@ -115,6 +128,10 @@ const MarkdownEditor = forwardRef<MarkdownEditorHandle, MarkdownEditorProps>(if (current !== value) {editor.commands.setContent(value, { emitUpdate: false });}++ // Sync the echo baseline so subsequent user edits compare against+ // the new external value, not the previously emitted one.+ lastEmittedRef.current = value;}, [editor, value]);useEffect(() => {diff --git a/frontend/src/components/ui/data-table.tsx b/frontend/src/components/ui/data-table.tsxindex 6f66cd07..084d9d6f 100644--- a/frontend/src/components/ui/data-table.tsx+++ b/frontend/src/components/ui/data-table.tsx@@ -8,12 +8,13 @@ import {getFilteredRowModel,getPaginationRowModel,getSortedRowModel,+ type Table as ReactTable,type Row,type SortingState,useReactTable,type VisibilityState,} from '@tanstack/react-table';-import { ChevronDown, ChevronLeft, ChevronRight, ChevronsLeft, ChevronsRight } from 'lucide-react';+import { ChevronDown, ChevronLeft, ChevronRight, ChevronsLeft, ChevronsRight, Search, X } from 'lucide-react';import { Fragment, type ReactElement, type ReactNode, useCallback, useMemo, useRef, useState } from 'react';import { Button } from '@/components/ui/button';@@ -24,7 +25,7 @@ import {DropdownMenuContent,DropdownMenuTrigger,} from '@/components/ui/dropdown-menu';-import { Input } from '@/components/ui/input';+import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from '@/components/ui/input-group';import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';import { useEffectAfterMount } from '@/hooks/use-effect-after-mount';@@ -57,6 +58,48 @@ interface DataTableProps<TData, TValue = unknown> {const PAGE_SIZE_OPTIONS = [10, 15, 20, 50, 100] as const;+interface DataTableFilterProps<TData> {+ column: string;+ placeholder: string;+ table: ReactTable<TData>;+}++/**+ * Search input bound to a single TanStack Table column. Reads/writes the column's+ * filter value directly — purely cosmetic shell around the table's existing+ * filter API. Extracted out of `DataTable` so the toolbar JSX doesn't have to+ * inline an IIFE just to capture the current `filterValue` once.+ */+const DataTableFilter = <TData,>({ column, placeholder, table }: DataTableFilterProps<TData>) => {+ const tableColumn = table.getColumn(column);+ const filterValue = (tableColumn?.getFilterValue() as string) ?? '';++ return (+ <InputGroup className="max-w-sm">+ <InputGroupAddon>+ <Search />+ </InputGroupAddon>+ <InputGroupInput+ autoComplete="off"+ onChange={(event) => tableColumn?.setFilterValue(event.target.value)}+ placeholder={placeholder}+ type="text"+ value={filterValue}+ />+ {filterValue ? (+ <InputGroupAddon align="inline-end">+ <InputGroupButton+ onClick={() => tableColumn?.setFilterValue('')}+ type="button"+ >+ <X />+ </InputGroupButton>+ </InputGroupAddon>+ ) : null}+ </InputGroup>+ );+};+function DataTable<TData, TValue = unknown>({columns,columnVisibility: externalColumnVisibility,@@ -210,21 +253,20 @@ function DataTable<TData, TValue = unknown>({return (<div className="w-full"><div className="flex items-center gap-4 py-4">- {filterColumn && (- <Input- className="max-w-sm"- onChange={(event) => table.getColumn(filterColumn)?.setFilterValue(event.target.value)}+ {filterColumn ? (+ <DataTableFilter+ column={filterColumn}placeholder={filterPlaceholder}- value={(table.getColumn(filterColumn)?.getFilterValue() as string) ?? ''}+ table={table}/>- )}+ ) : null}<DropdownMenu><DropdownMenuTrigger asChild><ButtonclassName="ml-auto"variant="outline">- Columns <ChevronDown className="ml-2 h-4 w-4" />+ Columns <ChevronDown className="ml-2" /></Button></DropdownMenuTrigger><DropdownMenuContent align="end">diff --git a/frontend/src/hooks/use-latest-ref.ts b/frontend/src/hooks/use-latest-ref.tsnew file mode 100644index 00000000..f64736f8--- /dev/null+++ b/frontend/src/hooks/use-latest-ref.ts@@ -0,0 +1,24 @@+import { type RefObject, useEffect, useRef } from 'react';++/**+ * Stash a value in a ref that's kept in sync with the latest render.+ *+ * Useful for the "stable callback" pattern: a memoized child accepts a stable+ * handler from the parent, but the handler internally needs to read the most+ * recent prop / state value without invalidating downstream memos. Reading+ * `ref.current` inside the stable handler always sees the latest value+ * because this hook re-syncs the ref after every commit.+ *+ * Don't read `ref.current` during render — use the value prop directly instead.+ * Reading the ref during render breaks React's snapshot guarantee (the ref may+ * be updated by a concurrent render before the current one commits).+ */+export const useLatestRef = <T>(value: T): RefObject<T> => {+ const ref = useRef(value);++ useEffect(() => {+ ref.current = value;+ }, [value]);++ return ref;+};diff --git a/frontend/src/lib/local-storage.ts b/frontend/src/lib/local-storage.tsnew file mode 100644index 00000000..37aee7ae--- /dev/null+++ b/frontend/src/lib/local-storage.ts@@ -0,0 +1,34 @@+import type { z } from 'zod';++/**+ * Read a value from `localStorage` and validate it with a Zod schema. Returns+ * `null` when the key is missing, JSON parsing fails, or the payload doesn't+ * match the schema — callers don't need to distinguish between those cases.+ *+ * `localStorage` access is wrapped in try/catch so this works in environments+ * where storage is disabled (private mode, SSR, sandboxed iframes).+ */+export function getStorageItem<T>(key: string, schema: z.ZodType<T>): null | T {+ try {+ const raw = localStorage.getItem(key);++ if (raw === null) {+ return null;+ }++ const result = schema.safeParse(JSON.parse(raw));++ return result.success ? result.data : null;+ } catch {+ return null;+ }+}++/** Serialize `value` to JSON and store it in `localStorage`. Silently no-ops on failure. */+export function setStorageItem(key: string, value: unknown): void {+ try {+ localStorage.setItem(key, JSON.stringify(value));+ } catch {+ /* localStorage may be unavailable */+ }+}diff --git a/frontend/src/lib/table-sort.ts b/frontend/src/lib/table-sort.tsnew file mode 100644index 00000000..b7ee4b43--- /dev/null+++ b/frontend/src/lib/table-sort.ts@@ -0,0 +1,31 @@+import type { Column } from '@tanstack/react-table';++/**+ * Cycle a TanStack Table column through the three-state sort order+ * `none → asc → desc → none`. Mirrors the header behaviour of `DataTable`+ * and the FileManager sortable headers.+ *+ * Pure with respect to React (does not call any hook), so it can be invoked+ * directly from a header `onClick` without wrapping in `useCallback`/`useMemo`.+ *+ * Generic over the row type so `column` keeps its full TanStack typing at the+ * call site — no need to inline a structural subset like+ * `{ getIsSorted; toggleSorting; clearSorting }` in every page.+ */+export const cycleColumnSort = <TData, TValue = unknown>(column: Column<TData, TValue>): void => {+ const sorted = column.getIsSorted();++ if (sorted === 'asc') {+ column.toggleSorting(true);++ return;+ }++ if (sorted === 'desc') {+ column.clearSorting();++ return;+ }++ column.toggleSorting(false);+};diff --git a/frontend/src/lib/table-storage.ts b/frontend/src/lib/table-storage.tsindex ff09635b..8defdc7e 100644--- a/frontend/src/lib/table-storage.ts+++ b/frontend/src/lib/table-storage.ts@@ -2,6 +2,8 @@ import type { SortingState, VisibilityState } from '@tanstack/react-table';import { z } from 'zod';+import { getStorageItem, setStorageItem } from './local-storage';+const sortingSchema = z.array(z.object({ desc: z.boolean(), id: z.string() }));const visibilitySchema = z.record(z.string(), z.boolean());@@ -10,38 +12,15 @@ const pageStateSchema = z.object({ page: z.number(), pageSize: z.number() });export type StoredPageState = z.infer<typeof pageStateSchema>;-function loadFromStorage<T>(key: string, schema: z.ZodType<T>): null | T {- try {- const raw = localStorage.getItem(key);-- if (raw === null) {- return null;- }-- const result = schema.safeParse(JSON.parse(raw));-- return result.success ? result.data : null;- } catch {- return null;- }-}--function saveToStorage(key: string, value: unknown): void {- try {- localStorage.setItem(key, JSON.stringify(value));- } catch {- /* localStorage may be unavailable */- }-}--export const loadSorting = (key: string): null | SortingState => loadFromStorage(key, sortingSchema);+export const loadSorting = (key: string): null | SortingState => getStorageItem(key, sortingSchema);-export const loadColumnVisibility = (key: string): null | VisibilityState => loadFromStorage(key, visibilitySchema);+export const loadColumnVisibility = (key: string): null | VisibilityState => getStorageItem(key, visibilitySchema);-export const loadPageState = (key: string): null | StoredPageState => loadFromStorage(key, pageStateSchema);+export const loadPageState = (key: string): null | StoredPageState => getStorageItem(key, pageStateSchema);-export const saveSorting = (key: string, sorting: SortingState): void => saveToStorage(key, sorting);+export const saveSorting = (key: string, sorting: SortingState): void => setStorageItem(key, sorting);-export const saveColumnVisibility = (key: string, visibility: VisibilityState): void => saveToStorage(key, visibility);+export const saveColumnVisibility = (key: string, visibility: VisibilityState): void =>+ setStorageItem(key, visibility);-export const savePageState = (key: string, state: StoredPageState): void => saveToStorage(key, state);+export const savePageState = (key: string, state: StoredPageState): void => setStorageItem(key, state);diff --git a/frontend/src/pages/flows/flows.tsx b/frontend/src/pages/flows/flows.tsxindex 511988a2..ca294839 100644--- a/frontend/src/pages/flows/flows.tsx+++ b/frontend/src/pages/flows/flows.tsx@@ -2,19 +2,7 @@ import type { ColumnDef } from '@tanstack/react-table';import { format, isToday } from 'date-fns';import { enUS } from 'date-fns/locale';-import {- ArrowDown,- ArrowUp,- Eye,- GitFork,- Loader2,- MoreHorizontal,- Pause,- Pencil,- Plus,- Star,- Trash,-} from 'lucide-react';+import { ArrowDown, ArrowUp, Ellipsis, Eye, GitFork, Loader2, Pause, Pencil, Plus, Star, Trash } from 'lucide-react';import { Check, CheckCircle2, X, XCircle } from 'lucide-react';import { useCallback, useMemo, useRef, useState } from 'react';import { useNavigate } from 'react-router-dom';@@ -600,7 +588,7 @@ const Flows = () => {onClick={(e) => e.stopPropagation()}variant="ghost">- <MoreHorizontal />+ <Ellipsis /></Button></DropdownMenuTrigger><DropdownMenuContentdiff --git a/frontend/src/pages/knowledges/knowledge.tsx b/frontend/src/pages/knowledges/knowledge.tsxindex 15586aae..1255485e 100644--- a/frontend/src/pages/knowledges/knowledge.tsx+++ b/frontend/src/pages/knowledges/knowledge.tsx@@ -1,8 +1,8 @@import { zodResolver } from '@hookform/resolvers/zod';import { GripVertical, LibraryBig, Save } from 'lucide-react';-import { useMemo, useState } from 'react';-import { useForm } from 'react-hook-form';-import { useNavigate, useParams } from 'react-router-dom';+import { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { type Control, type FieldPath, type SubmitHandler, useForm, useWatch } from 'react-hook-form';+import { type BlockerFunction, useBlocker, useNavigate, useParams } from 'react-router-dom';import { z } from 'zod';import type {@@ -18,6 +18,14 @@ import { Badge } from '@/components/ui/badge';import { Breadcrumb, BreadcrumbItem, BreadcrumbList, BreadcrumbPage } from '@/components/ui/breadcrumb';import { Button } from '@/components/ui/button';import { Card, CardContent } from '@/components/ui/card';+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog';import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';import { Input } from '@/components/ui/input';import { InputGroup, InputGroupTextareaAutosize } from '@/components/ui/input-group';@@ -28,8 +36,13 @@ import { SidebarTrigger } from '@/components/ui/sidebar';import { Spinner } from '@/components/ui/spinner';import { KnowledgeAnswerType, KnowledgeDocType, KnowledgeGuideType, useKnowledgeDocumentQuery } from '@/graphql/types';import { useBreakpoint } from '@/hooks/use-breakpoint';+import { Log } from '@/lib/log';import { useKnowledges } from '@/providers/knowledges-provider';+// ---------------------------------------------------------------------------+// Schema, types, pure helpers+// ---------------------------------------------------------------------------+const docTypeValues = [KnowledgeDocType.Answer, KnowledgeDocType.Guide, KnowledgeDocType.Code] as const;const guideTypeValues = Object.values(KnowledgeGuideType) as KnowledgeGuideTypeT[];const answerTypeValues = Object.values(KnowledgeAnswerType) as KnowledgeAnswerTypeT[];@@ -45,27 +58,26 @@ const formSchema = zquestion: z.string().trim().min(1, { message: 'Question is required' }),}).superRefine((value, ctx) => {- if (value.docType === KnowledgeDocType.Guide && !value.guideType) {- ctx.addIssue({- code: z.ZodIssueCode.custom,- message: 'Guide type is required',- path: ['guideType'],- });- }+ const requiredByDocType: Partial<Record<KnowledgeDocType, { field: FieldPath<FormValues>; message: string }>> = {+ [KnowledgeDocType.Answer]: { field: 'answerType', message: 'Answer type is required' },+ [KnowledgeDocType.Code]: { field: 'codeLang', message: 'Code language is required' },+ [KnowledgeDocType.Guide]: { field: 'guideType', message: 'Guide type is required' },+ };- if (value.docType === KnowledgeDocType.Answer && !value.answerType) {- ctx.addIssue({- code: z.ZodIssueCode.custom,- message: 'Answer type is required',- path: ['answerType'],- });+ const rule = requiredByDocType[value.docType];++ if (!rule) {+ return;}- if (value.docType === KnowledgeDocType.Code && (!value.codeLang || value.codeLang.length === 0)) {+ const fieldValue = value[rule.field];+ const isMissing = fieldValue === undefined || fieldValue === null || fieldValue === '';++ if (isMissing) {ctx.addIssue({code: z.ZodIssueCode.custom,- message: 'Code language is required',- path: ['codeLang'],+ message: rule.message,+ path: [rule.field],});}});@@ -92,81 +104,247 @@ const documentToFormValues = (k: KnowledgeDocumentFragmentFragment): FormValuesquestion: k.question,});-interface KnowledgeFormViewProps {- initialValues: FormValues;- isNew: boolean;- knowledge?: KnowledgeDocumentFragmentFragment | null;- knowledgeName: null | string;- onSubmit: (values: FormValues) => Promise<void>;+// `description` and `codeLang` are optional and we want empty strings to map+// to `undefined` so the backend treats them as "absent" instead of "set to ''".+const trimmedOrUndefined = (value: null | string | undefined): string | undefined => {+ if (!value) {+ return undefined;+ }++ const trimmed = value.trim();++ return trimmed.length === 0 ? undefined : trimmed;+};++const formValuesToCreateInput = (v: FormValues): CreateKnowledgeDocumentInput => ({+ answerType: v.docType === KnowledgeDocType.Answer ? v.answerType : undefined,+ codeLang: v.docType === KnowledgeDocType.Code ? trimmedOrUndefined(v.codeLang) : undefined,+ content: v.content,+ description: trimmedOrUndefined(v.description),+ docType: v.docType,+ guideType: v.docType === KnowledgeDocType.Guide ? v.guideType : undefined,+ question: v.question,+});++const formValuesToUpdateInput = (v: FormValues): UpdateKnowledgeDocumentInput => ({+ answerType: v.docType === KnowledgeDocType.Answer ? v.answerType : undefined,+ codeLang: v.docType === KnowledgeDocType.Code ? trimmedOrUndefined(v.codeLang) : undefined,+ content: v.content,+ description: trimmedOrUndefined(v.description),+ guideType: v.docType === KnowledgeDocType.Guide ? v.guideType : undefined,+ question: v.question,+});++// ---------------------------------------------------------------------------+// Unsaved-changes guard hook+// ---------------------------------------------------------------------------++interface UnsavedChangesGuard {+ handleCancel: () => void;+ handleDiscard: () => void;+ handleOpenChange: (open: boolean) => void;+ handleSaveAndLeave: () => Promise<void>;+ isOpen: boolean;+ isSavingFromDialog: boolean;+ /**+ * Allows the next router navigation to bypass the blocker. Use this after+ * a successful save when the form (or its parent) needs to navigate to+ * a fresh URL (e.g. the new document page) without showing the dialog.+ */+ skipNextBlock: () => void;}-const KnowledgeFormView = ({ initialValues, isNew, knowledge, knowledgeName, onSubmit }: KnowledgeFormViewProps) => {- const { isDesktop } = useBreakpoint();- const [isSaving, setIsSaving] = useState(false);+interface UseUnsavedChangesGuardArgs {+ isDirty: boolean;+ isFormValid: boolean;+ onSave: () => Promise<boolean>;+}- const form = useForm<FormValues>({- defaultValues: initialValues,- mode: 'onChange',- resolver: zodResolver(formSchema),- });+const useUnsavedChangesGuard = ({+ isDirty,+ isFormValid,+ onSave,+}: UseUnsavedChangesGuardArgs): UnsavedChangesGuard => {+ const allowNextRef = useRef(false);+ const isDirtyRef = useRef(isDirty);- const { control, formState, handleSubmit, reset, watch } = form;+ useEffect(() => {+ isDirtyRef.current = isDirty;+ }, [isDirty]);- const docType = watch('docType');- const hasUnsavedChanges = formState.isDirty;- const canSubmit = !isSaving && formState.isValid && (isNew || hasUnsavedChanges);+ const blockerFn = useCallback<BlockerFunction>(({ currentLocation, nextLocation }) => {+ if (allowNextRef.current) {+ allowNextRef.current = false;- const onSubmitWithGuard = async (values: FormValues) => {- if (isSaving) {+ return false;+ }++ if (currentLocation.pathname === nextLocation.pathname && currentLocation.search === nextLocation.search) {+ return false;+ }++ return isDirtyRef.current;+ }, []);++ const blocker = useBlocker(blockerFn);+ const [isSavingFromDialog, setIsSavingFromDialog] = useState(false);++ useEffect(() => {+ if (!isDirty) {return;}- setIsSaving(true);+ const handleBeforeUnload = (event: BeforeUnloadEvent) => {+ event.preventDefault();+ event.returnValue = '';+ };++ window.addEventListener('beforeunload', handleBeforeUnload);++ return () => {+ window.removeEventListener('beforeunload', handleBeforeUnload);+ };+ }, [isDirty]);++ const isOpen = blocker.state === 'blocked';++ const handleCancel = useCallback(() => {+ if (blocker.state === 'blocked') {+ blocker.reset();+ }+ }, [blocker]);++ const handleDiscard = useCallback(() => {+ if (blocker.state === 'blocked') {+ blocker.proceed();+ }+ }, [blocker]);++ const handleSaveAndLeave = useCallback(async () => {+ if (isSavingFromDialog || !isFormValid) {+ return;+ }++ setIsSavingFromDialog(true);try {- await onSubmit(values);+ const success = await onSave();- if (!isNew) {- reset(values, { keepDefaultValues: false });+ if (success && blocker.state === 'blocked') {+ blocker.proceed();}- } catch {- // Error already surfaced via toast in the provider} finally {- setIsSaving(false);+ setIsSavingFromDialog(false);}+ }, [blocker, isFormValid, isSavingFromDialog, onSave]);++ const handleOpenChange = useCallback(+ (open: boolean) => {+ if (isSavingFromDialog) {+ return;+ }++ if (!open && blocker.state === 'blocked') {+ blocker.reset();+ }+ },+ [blocker, isSavingFromDialog],+ );++ const skipNextBlock = useCallback(() => {+ allowNextRef.current = true;+ }, []);++ return {+ handleCancel,+ handleDiscard,+ handleOpenChange,+ handleSaveAndLeave,+ isOpen,+ isSavingFromDialog,+ skipNextBlock,};+};- const introBlock = (- <div className="flex flex-col gap-4">- <div className="text-center">- <h1 className="text-2xl font-semibold">- {isNew ? 'Create a new knowledge document' : 'Edit knowledge document'}- </h1>- <p className="text-muted-foreground mt-2">- {isNew- ? 'Add an entry to the vector knowledge base'- : 'Edits to content or metadata will trigger re-embedding'}- </p>- </div>+// ---------------------------------------------------------------------------+// Sub-components+// ---------------------------------------------------------------------------- {!isNew && knowledge ? (- <div className="text-muted-foreground flex flex-wrap items-center gap-2 text-xs">- <Badge variant={knowledge.manual ? 'secondary' : 'outline'}>- {knowledge.manual ? 'manual' : 'agent'}- </Badge>- {knowledge.flowId ? <Badge variant="outline">flow #{knowledge.flowId}</Badge> : null}- {knowledge.taskId ? <Badge variant="outline">task #{knowledge.taskId}</Badge> : null}- {knowledge.subtaskId ? <Badge variant="outline">subtask #{knowledge.subtaskId}</Badge> : null}- <span>·</span>- <span>- chunk {knowledge.partSize} of {knowledge.totalSize}- </span>- </div>- ) : null}+interface KnowledgePageHeaderProps {+ isNew: boolean;+ knowledgeName: null | string;+ saveButton?: ReactNode;+}++const KnowledgePageHeader = ({ isNew, knowledgeName, saveButton }: KnowledgePageHeaderProps) => (+ <header className="bg-background sticky top-0 z-10 flex h-12 shrink-0 items-center gap-2 border-b px-4">+ <SidebarTrigger className="-ml-1" />+ <Separator+ className="mr-2 h-4"+ orientation="vertical"+ />+ <Breadcrumb>+ <BreadcrumbList>+ <BreadcrumbItem>+ <LibraryBig className="size-4 shrink-0" />+ <BreadcrumbPage className="max-w-[240px] truncate">+ {isNew ? 'New knowledge' : (knowledgeName ?? 'Knowledge')}+ </BreadcrumbPage>+ </BreadcrumbItem>+ </BreadcrumbList>+ </Breadcrumb>+ {saveButton ? <div className="ml-auto flex items-center gap-2">{saveButton}</div> : null}+ </header>+);++interface KnowledgeIntroBlockProps {+ isNew: boolean;+ knowledge?: KnowledgeDocumentFragmentFragment | null;+}++const KnowledgeIntroBlock = ({ isNew, knowledge }: KnowledgeIntroBlockProps) => (+ <div className="flex flex-col gap-4">+ <div className="text-center">+ <h1 className="text-2xl font-semibold">+ {isNew ? 'Create a new knowledge document' : 'Edit knowledge document'}+ </h1>+ <p className="text-muted-foreground mt-2">+ {isNew+ ? 'Add an entry to the vector knowledge base'+ : 'Edits to content or metadata will trigger re-embedding'}+ </p></div>- );- const metaFields = (+ {!isNew && knowledge ? (+ <div className="text-muted-foreground flex flex-wrap items-center gap-2 text-xs">+ <Badge variant={knowledge.manual ? 'secondary' : 'outline'}>+ {knowledge.manual ? 'manual' : 'agent'}+ </Badge>+ {knowledge.flowId ? <Badge variant="outline">flow #{knowledge.flowId}</Badge> : null}+ {knowledge.taskId ? <Badge variant="outline">task #{knowledge.taskId}</Badge> : null}+ {knowledge.subtaskId ? <Badge variant="outline">subtask #{knowledge.subtaskId}</Badge> : null}+ <span>·</span>+ <span>+ chunk {knowledge.partSize} of {knowledge.totalSize}+ </span>+ </div>+ ) : null}+ </div>+);++interface KnowledgeMetaFieldsProps {+ control: Control<FormValues>;+ isNew: boolean;+ isSaving: boolean;+}++const KnowledgeMetaFields = ({ control, isNew, isSaving }: KnowledgeMetaFieldsProps) => {+ // Targeted subscription: only this component re-renders when docType changes,+ // not the whole form. The full-form `useWatch` from the original code+ // re-rendered on every keystroke in the markdown editor.+ const docType = useWatch({ control, name: 'docType' });++ return (<div className="flex flex-col gap-4"><div className="grid gap-4 sm:grid-cols-2"><FormField@@ -344,158 +522,350 @@ const KnowledgeFormView = ({ initialValues, isNew, knowledge, knowledgeName, onS/></div>);+};- const contentField = (- <FormField- control={control}- name="content"- render={({ field }) => (- <FormItem className="flex min-h-0 flex-1 flex-col">- <FormControl>- <MarkdownEditor- className="min-h-0 flex-1"- disabled={isSaving}- onBlur={field.onBlur}- onChange={field.onChange}- placeholder="Knowledge content (will be embedded into the vector store)"- value={field.value}- />- </FormControl>- <FormMessage />- </FormItem>- )}- />- );+interface KnowledgeContentFieldProps {+ control: Control<FormValues>;+ /** When `true`, the editor stretches to fill its parent (desktop split view). */+ fillParent?: boolean;+ isSaving: boolean;+ showLabel?: boolean;+}- const contentFieldStandalone = (- <FormField- control={control}- name="content"- render={({ field }) => (- <FormItem>- <FormLabel>Content</FormLabel>- <FormControl>- <MarkdownEditor- className="min-h-[280px]"- contentClassName="min-h-[240px]"- disabled={isSaving}- onBlur={field.onBlur}- onChange={field.onChange}- placeholder="Knowledge content (will be embedded into the vector store)"- value={field.value}- />- </FormControl>- <FormMessage />- </FormItem>- )}- />- );+const KnowledgeContentField = ({ control, fillParent = false, isSaving, showLabel = false }: KnowledgeContentFieldProps) => (+ <FormField+ control={control}+ name="content"+ render={({ field }) => (+ <FormItem className={fillParent ? 'flex min-h-0 flex-1 flex-col' : undefined}>+ {showLabel ? <FormLabel>Content</FormLabel> : null}+ <FormControl>+ <MarkdownEditor+ className={fillParent ? 'min-h-0 flex-1' : 'min-h-[280px]'}+ contentClassName={fillParent ? undefined : 'min-h-[240px]'}+ disabled={isSaving}+ onBlur={field.onBlur}+ onChange={field.onChange}+ placeholder="Knowledge content (will be embedded into the vector store)"+ value={field.value}+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+);++interface KnowledgeBodyProps {+ control: Control<FormValues>;+ isNew: boolean;+ isSaving: boolean;+ knowledge?: KnowledgeDocumentFragmentFragment | null;+}- const pageHeader = (- <header className="bg-background sticky top-0 z-10 flex h-12 shrink-0 items-center gap-2 border-b px-4">- <SidebarTrigger className="-ml-1" />- <Separator- className="mr-2 h-4"- orientation="vertical"- />- <Breadcrumb>- <BreadcrumbList>- <BreadcrumbItem>- <LibraryBig className="size-4 shrink-0" />- <BreadcrumbPage className="max-w-[240px] truncate">- {isNew ? 'New knowledge' : (knowledgeName ?? 'Knowledge')}- </BreadcrumbPage>- </BreadcrumbItem>- </BreadcrumbList>- </Breadcrumb>- <div className="ml-auto flex items-center gap-2">+const KnowledgeBodyDesktop = ({ control, isNew, isSaving, knowledge }: KnowledgeBodyProps) => (+ <div className="flex h-[calc(100dvh-3rem)] min-h-0 w-full max-w-full flex-1 overflow-hidden">+ <ResizablePanelGroup+ className="w-full"+ direction="horizontal"+ >+ <ResizablePanel+ className="h-[calc(100dvh-3rem)] min-h-0"+ defaultSize={45}+ minSize={30}+ >+ <div className="h-full min-h-0 overflow-y-auto">+ <Card className="mx-auto min-h-full w-full max-w-2xl rounded-none border-0">+ <CardContent className="flex flex-col gap-6 py-6">+ <KnowledgeIntroBlock+ isNew={isNew}+ knowledge={knowledge}+ />+ <KnowledgeMetaFields+ control={control}+ isNew={isNew}+ isSaving={isSaving}+ />+ </CardContent>+ </Card>+ </div>+ </ResizablePanel>+ <ResizableHandle withHandle>+ <GripVertical className="size-4" />+ </ResizableHandle>+ <ResizablePanel+ className="h-[calc(100dvh-3rem)] min-h-0"+ defaultSize={55}+ minSize={30}+ >+ <div className="flex h-full min-h-0 flex-col overflow-hidden p-4">+ <KnowledgeContentField+ control={control}+ fillParent+ isSaving={isSaving}+ />+ </div>+ </ResizablePanel>+ </ResizablePanelGroup>+ </div>+);++const KnowledgeBodyMobile = ({ control, isNew, isSaving, knowledge }: KnowledgeBodyProps) => (+ <div className="flex min-w-0 flex-1 items-start justify-center p-4">+ <Card className="w-full max-w-3xl">+ <CardContent className="flex flex-col gap-6 pt-6">+ <KnowledgeIntroBlock+ isNew={isNew}+ knowledge={knowledge}+ />+ <KnowledgeMetaFields+ control={control}+ isNew={isNew}+ isSaving={isSaving}+ />+ <KnowledgeContentField+ control={control}+ isSaving={isSaving}+ showLabel+ />+ </CardContent>+ </Card>+ </div>+);++interface KnowledgeLeaveDialogProps extends Pick<UnsavedChangesGuard, 'handleCancel' | 'handleDiscard' | 'handleOpenChange' | 'handleSaveAndLeave' | 'isOpen' | 'isSavingFromDialog'> {+ canSave: boolean;+}++const KnowledgeLeaveDialog = ({+ canSave,+ handleCancel,+ handleDiscard,+ handleOpenChange,+ handleSaveAndLeave,+ isOpen,+ isSavingFromDialog,+}: KnowledgeLeaveDialogProps) => (+ <Dialog+ onOpenChange={handleOpenChange}+ open={isOpen}+ >+ <DialogContent+ className="sm:max-w-md"+ onEscapeKeyDown={(event) => {+ if (isSavingFromDialog) {+ event.preventDefault();+ }+ }}+ onInteractOutside={(event) => {+ if (isSavingFromDialog) {+ event.preventDefault();+ }+ }}+ >+ <DialogHeader>+ <DialogTitle>Unsaved changes</DialogTitle>+ <DialogDescription>+ You have unsaved changes on this page. Would you like to save them before leaving?+ </DialogDescription>+ </DialogHeader>+ <DialogFooter className="flex-col-reverse gap-2 sm:flex-row sm:justify-end"><Button- disabled={!canSubmit}- size="sm"- type="submit"+ disabled={isSavingFromDialog}+ onClick={handleCancel}+ variant="outline">- {isSaving ? <Spinner variant="circle" /> : <Save />}- {isNew ? 'Create' : 'Save'}+ Cancel</Button>- </div>- </header>+ <Button+ disabled={isSavingFromDialog}+ onClick={handleDiscard}+ variant="destructive"+ >+ Discard+ </Button>+ <Button+ disabled={isSavingFromDialog || !canSave}+ onClick={handleSaveAndLeave}+ variant="default"+ >+ {isSavingFromDialog ? <Spinner variant="circle" /> : <Save />}+ Save+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+);++// ---------------------------------------------------------------------------+// Form view (uses the form, owns navigation guard)+// ---------------------------------------------------------------------------++interface KnowledgeFormViewProps {+ initialValues: FormValues;+ isNew: boolean;+ knowledge?: KnowledgeDocumentFragmentFragment | null;+ knowledgeName: null | string;+ onSubmit: (values: FormValues) => Promise<SubmitResult>;+}++interface SubmitResult {+ redirectTo?: string;+}++const KnowledgeFormView = ({ initialValues, isNew, knowledge, knowledgeName, onSubmit }: KnowledgeFormViewProps) => {+ const navigate = useNavigate();+ const { isDesktop } = useBreakpoint();+ const [isSaving, setIsSaving] = useState(false);++ const form = useForm<FormValues>({+ defaultValues: initialValues,+ mode: 'onChange',+ resolver: zodResolver(formSchema),+ });++ const { control, formState, handleSubmit, reset } = form;+ const { isDirty, isValid } = formState;++ const performSave = useCallback(+ async (values: FormValues): Promise<boolean> => {+ try {+ const result = await onSubmit(values);++ // Reset BEFORE navigate so `isDirty` is false by the time the+ // blocker re-evaluates. We also `skipNextBlock` defensively+ // because reset's state propagation is async.+ reset(values, { keepDefaultValues: false });++ if (result.redirectTo) {+ skipNextBlockRef.current();+ navigate(result.redirectTo);+ }++ return true;+ } catch (error) {+ Log.error('Failed to save knowledge document', error);++ return false;+ }+ },+ [navigate, onSubmit, reset],);- if (isDesktop) {- return (+ const skipNextBlockRef = useRef<() => void>(() => {});++ const onSubmitWithGuard: SubmitHandler<FormValues> = useCallback(+ async (values) => {+ if (isSaving) {+ return;+ }++ setIsSaving(true);++ try {+ await performSave(values);+ } finally {+ setIsSaving(false);+ }+ },+ [isSaving, performSave],+ );++ const onSaveFromDialog = useCallback(async (): Promise<boolean> => {+ if (isSaving || !isValid) {+ return false;+ }++ setIsSaving(true);++ try {+ return await performSave(form.getValues());+ } finally {+ setIsSaving(false);+ }+ }, [form, isSaving, isValid, performSave]);++ const guard = useUnsavedChangesGuard({+ isDirty,+ isFormValid: isValid,+ onSave: onSaveFromDialog,+ });++ // Wire the ref so `performSave` can call into the guard's `skipNextBlock`.+ useEffect(() => {+ skipNextBlockRef.current = guard.skipNextBlock;+ }, [guard.skipNextBlock]);++ const canSubmit = !isSaving && isValid && (isNew || isDirty);++ const saveButton = (+ <Button+ disabled={!canSubmit}+ size="sm"+ type="submit"+ >+ {isSaving ? <Spinner variant="circle" /> : <Save />}+ {isNew ? 'Create' : 'Save'}+ </Button>+ );++ return (+ <><Form {...form}><form- className="flex h-full min-h-0 w-full flex-1 flex-col"+ className={isDesktop ? 'flex h-full min-h-0 w-full flex-1 flex-col' : 'flex min-h-[100dvh] flex-col'}onSubmit={handleSubmit(onSubmitWithGuard)}>- {pageHeader}- <div className="flex h-[calc(100dvh-3rem)] min-h-0 w-full max-w-full flex-1 overflow-hidden">- <ResizablePanelGroup- className="w-full"- direction="horizontal"- >- <ResizablePanel- className="h-[calc(100dvh-3rem)] min-h-0"- defaultSize={45}- minSize={30}- >- <div className="h-full min-h-0 overflow-y-auto">- <Card className="mx-auto min-h-full w-full max-w-2xl rounded-none border-0">- <CardContent className="flex flex-col gap-6 py-6">- {introBlock}- {metaFields}- </CardContent>- </Card>- </div>- </ResizablePanel>- <ResizableHandle withHandle>- <GripVertical className="size-4" />- </ResizableHandle>- <ResizablePanel- className="h-[calc(100dvh-3rem)] min-h-0"- defaultSize={55}- minSize={30}- >- <div className="flex h-full min-h-0 flex-col overflow-hidden p-4">{contentField}</div>- </ResizablePanel>- </ResizablePanelGroup>- </div>+ <KnowledgePageHeader+ isNew={isNew}+ knowledgeName={knowledgeName}+ saveButton={saveButton}+ />+ {isDesktop ? (+ <KnowledgeBodyDesktop+ control={control}+ isNew={isNew}+ isSaving={isSaving}+ knowledge={knowledge}+ />+ ) : (+ <KnowledgeBodyMobile+ control={control}+ isNew={isNew}+ isSaving={isSaving}+ knowledge={knowledge}+ />+ )}</form></Form>- );- }-- return (- <Form {...form}>- <form- className="flex min-h-[100dvh] flex-col"- onSubmit={handleSubmit(onSubmitWithGuard)}- >- {pageHeader}- <div className="flex min-w-0 flex-1 items-start justify-center p-4">- <Card className="w-full max-w-3xl">- <CardContent className="flex flex-col gap-6 pt-6">- {introBlock}- {metaFields}- {contentFieldStandalone}- </CardContent>- </Card>- </div>- </form>- </Form>+ <KnowledgeLeaveDialog+ canSave={isValid}+ handleCancel={guard.handleCancel}+ handleDiscard={guard.handleDiscard}+ handleOpenChange={guard.handleOpenChange}+ handleSaveAndLeave={guard.handleSaveAndLeave}+ isOpen={guard.isOpen}+ isSavingFromDialog={guard.isSavingFromDialog}+ />+ </>);};+// ---------------------------------------------------------------------------+// Page container+// ---------------------------------------------------------------------------+const Knowledge = () => {const navigate = useNavigate();const { knowledgeId } = useParams<{ knowledgeId?: string }>();const { createKnowledge, updateKnowledge } = useKnowledges();const isNew = knowledgeId === 'new';+ const shouldFetch = Boolean(knowledgeId) && !isNew;const { data, loading: isLoadingKnowledge } = useKnowledgeDocumentQuery({- skip: isNew || !knowledgeId,- variables: knowledgeId && !isNew ? { id: knowledgeId } : undefined,+ skip: !shouldFetch,+ variables: shouldFetch && knowledgeId ? { id: knowledgeId } : undefined,});const knowledge = data?.knowledgeDocument ?? null;@@ -506,64 +876,34 @@ const Knowledge = () => {[knowledge],);- const handleSubmit = async (values: FormValues) => {- if (isNew) {- const input: CreateKnowledgeDocumentInput = {- answerType: values.docType === KnowledgeDocType.Answer ? values.answerType : undefined,- codeLang: values.docType === KnowledgeDocType.Code && values.codeLang ? values.codeLang : undefined,- content: values.content,- description: values.description ? values.description : undefined,- docType: values.docType,- guideType: values.docType === KnowledgeDocType.Guide ? values.guideType : undefined,- question: values.question,- };-- const created = await createKnowledge(input);- navigate(created?.id ? `/knowledges/${created.id}` : '/knowledges');+ const handleSubmit = useCallback(+ async (values: FormValues): Promise<SubmitResult> => {+ if (isNew) {+ const created = await createKnowledge(formValuesToCreateInput(values));- return;- }-- if (!knowledgeId) {- return;- }+ return {+ redirectTo: created?.id ? `/knowledges/${created.id}` : '/knowledges',+ };+ }- const input: UpdateKnowledgeDocumentInput = {- answerType: values.docType === KnowledgeDocType.Answer ? values.answerType : undefined,- codeLang: values.docType === KnowledgeDocType.Code && values.codeLang ? values.codeLang : undefined,- content: values.content,- description: values.description ? values.description : undefined,- guideType: values.docType === KnowledgeDocType.Guide ? values.guideType : undefined,- question: values.question,- };+ if (!knowledgeId) {+ return {};+ }- await updateKnowledge(knowledgeId, input);- };+ await updateKnowledge(knowledgeId, formValuesToUpdateInput(values));- const placeholderHeader = (- <header className="bg-background sticky top-0 z-10 flex h-12 shrink-0 items-center gap-2 border-b px-4">- <SidebarTrigger className="-ml-1" />- <Separator- className="mr-2 h-4"- orientation="vertical"- />- <Breadcrumb>- <BreadcrumbList>- <BreadcrumbItem>- <LibraryBig className="size-4 shrink-0" />- <BreadcrumbPage className="max-w-[240px] truncate">- {isNew ? 'New knowledge' : (knowledgeName ?? 'Knowledge')}- </BreadcrumbPage>- </BreadcrumbItem>- </BreadcrumbList>- </Breadcrumb>- </header>+ return {};+ },+ [createKnowledge, isNew, knowledgeId, updateKnowledge],);if (!isNew && isLoadingKnowledge) {return (<>- {placeholderHeader}+ <KnowledgePageHeader+ isNew={false}+ knowledgeName={knowledgeName}+ /><div className="flex min-h-[calc(100dvh-3rem)] items-center justify-center"><Spinner variant="circle" /></div>@@ -574,7 +914,10 @@ const Knowledge = () => {if (!isNew && !knowledge) {return (<>- {placeholderHeader}+ <KnowledgePageHeader+ isNew={false}+ knowledgeName={knowledgeName}+ /><div className="flex min-h-[calc(100dvh-3rem)] items-center justify-center p-4"><Card className="w-full max-w-2xl"><CardContent className="flex flex-col items-center gap-4 pt-6 text-center">diff --git a/frontend/src/pages/knowledges/knowledges.tsx b/frontend/src/pages/knowledges/knowledges.tsxindex 7cae2f89..c4aa3537 100644--- a/frontend/src/pages/knowledges/knowledges.tsx+++ b/frontend/src/pages/knowledges/knowledges.tsx@@ -1,16 +1,6 @@import type { ColumnDef } from '@tanstack/react-table';-import {- ArrowDown,- ArrowUp,- BrainCircuit,- LibraryBig,- Loader2,- MoreHorizontal,- Pencil,- Plus,- Trash,-} from 'lucide-react';+import { ArrowDown, ArrowUp, Ellipsis, LibraryBig, Loader2, Pencil, Plus, Trash } from 'lucide-react';import { useState } from 'react';import { useNavigate } from 'react-router-dom';@@ -32,6 +22,7 @@ import { Separator } from '@/components/ui/separator';import { SidebarTrigger } from '@/components/ui/sidebar';import { StatusCard } from '@/components/ui/status-card';import { KnowledgeDocType } from '@/graphql/types';+import { cycleColumnSort } from '@/lib/table-sort';import { type Knowledge, useKnowledges } from '@/providers/knowledges-provider';const docTypeBadgeVariant: Record<KnowledgeDocType, BadgeVariant> = {@@ -126,7 +117,7 @@ const Knowledges = () => {return (<ButtonclassName="text-muted-foreground hover:text-primary flex items-center gap-2 p-0 no-underline hover:no-underline"- onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}+ onClick={() => cycleColumnSort(column)}variant="link">Type@@ -162,7 +153,7 @@ const Knowledges = () => {return (<ButtonclassName="text-muted-foreground hover:text-primary flex items-center gap-2 p-0 no-underline hover:no-underline"- onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}+ onClick={() => cycleColumnSort(column)}variant="link">Question@@ -242,7 +233,7 @@ const Knowledges = () => {onClick={(event) => event.stopPropagation()}variant="ghost">- <MoreHorizontal />+ <Ellipsis /></Button></DropdownMenuTrigger><DropdownMenuContent@@ -313,7 +304,7 @@ const Knowledges = () => {<Breadcrumb><BreadcrumbList><BreadcrumbItem>- <BrainCircuit className="size-4" />+ <LibraryBig className="size-4" /><BreadcrumbPage>Knowledges</BreadcrumbPage></BreadcrumbItem></BreadcrumbList>diff --git a/frontend/src/pages/resources/resources.tsx b/frontend/src/pages/resources/resources.tsxindex a982002c..fe7c6296 100644--- a/frontend/src/pages/resources/resources.tsx+++ b/frontend/src/pages/resources/resources.tsx@@ -1,4 +1,4 @@-import { Copy, FileSymlink, Folder, FolderPlus, FolderUp, Loader2, Search, Upload, X } from 'lucide-react';+import { ChevronDown, Copy, FileSymlink, Folder, FolderPlus, FolderUp, Loader2, Search, Upload, X } from 'lucide-react';import { useCallback, useMemo, useState } from 'react';import { toast } from 'sonner';@@ -18,19 +18,28 @@ import {type FileManagerAction,type FileManagerBulkAction,type FileManagerEmptyAreaAction,+ type FileManagerLabels,type FileNode,+ formatModifiedAbsolute,+ formatModifiedRelative,} from '@/components/shared/file-manager';import { OverwriteConfirmDialog } from '@/components/shared/overwrite-confirm-dialog';import { useOverwriteAction } from '@/components/shared/use-overwrite-action';import { Breadcrumb, BreadcrumbItem, BreadcrumbList, BreadcrumbPage } from '@/components/ui/breadcrumb';import { Button } from '@/components/ui/button';+import {+ DropdownMenu,+ DropdownMenuCheckboxItem,+ DropdownMenuContent,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu';import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from '@/components/ui/empty';import { FileDropZone } from '@/components/ui/file-drop-zone';import { Form, FormControl, FormField, FormItem } from '@/components/ui/form';import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from '@/components/ui/input-group';import { Separator } from '@/components/ui/separator';import { SidebarTrigger } from '@/components/ui/sidebar';-import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';import { ResourcesCopyDialog } from '@/features/resources/resources-copy-dialog';import { ResourcesMkdirDialog } from '@/features/resources/resources-mkdir-dialog';import { ResourcesMoveDialog } from '@/features/resources/resources-move-dialog';@@ -39,10 +48,53 @@ import { useResourcesDelete } from '@/features/resources/use-resources-delete';import { useResourcesMove } from '@/features/resources/use-resources-move';import { useResourcesSearch } from '@/features/resources/use-resources-search';import { useResourcesUpload } from '@/features/resources/use-resources-upload';+import { useEffectAfterMount } from '@/hooks/use-effect-after-mount';import { useFilesDragAndDrop } from '@/hooks/use-files-drag-and-drop';import { copyToClipboard } from '@/lib/report';+import { getColumnStorageKey } from '@/lib/storage-keys';+import { loadColumnVisibility, saveColumnVisibility } from '@/lib/table-storage';import { useResources } from '@/providers/resources-provider';+/**+ * Per-page persisted toggles for FileManager view options:+ * - `size` / `modified` — optional column visibility+ * - `foldersFirst` — whether directories cluster above files at every+ * level when a sort is active+ * - `isModifiedRelative` — render Modified as a relative label ("5m ago",+ * the FileManager default) when `true`, or as an+ * absolute, minute-precision timestamp when `false`+ *+ * All flags persist into the same `column` storage bucket because the schema is+ * `Record<string, boolean>` — adding more toggles later does not require a new key.+ */+interface ResourcesViewOptions {+ foldersFirst: boolean;+ isModifiedRelative: boolean;+ modified: boolean;+ size: boolean;+}++/** Defaults match FileManager's out-of-the-box behaviour (relative dates, folders first, both columns visible). */+const defaultViewOptions: ResourcesViewOptions = {+ foldersFirst: true,+ isModifiedRelative: true,+ modified: true,+ size: true,+};++type ResourcesViewOptionKey = keyof ResourcesViewOptions;++const loadViewOptions = (storageKey: string): ResourcesViewOptions => {+ const stored = loadColumnVisibility(storageKey) ?? {};++ return {+ foldersFirst: stored.foldersFirst ?? defaultViewOptions.foldersFirst,+ isModifiedRelative: stored.isModifiedRelative ?? defaultViewOptions.isModifiedRelative,+ modified: stored.modified ?? defaultViewOptions.modified,+ size: stored.size ?? defaultViewOptions.size,+ };+};+const Resources = () => {const { isInitialLoading, resources } = useResources();const search = useResourcesSearch();@@ -59,6 +111,31 @@ const Resources = () => {const [filesToMove, setFilesToMove] = useState<FileNode[] | null>(null);const [filesToCopy, setFilesToCopy] = useState<FileNode[] | null>(null);+ const viewOptionsStorageKey = useMemo(() => getColumnStorageKey('/resources'), []);+ const [viewOptions, setViewOptions] = useState<ResourcesViewOptions>(() => loadViewOptions(viewOptionsStorageKey));++ useEffectAfterMount(() => {+ // Cast: `ResourcesViewOptions` is structurally a `Record<string, boolean>`+ // but TS doesn't widen object types with declared keys to an index+ // signature implicitly.+ saveColumnVisibility(viewOptionsStorageKey, viewOptions as unknown as Record<string, boolean>);+ }, [viewOptions, viewOptionsStorageKey]);++ const toggleViewOption = useCallback((option: ResourcesViewOptionKey) => {+ setViewOptions((previous) => ({ ...previous, [option]: !previous[option] }));+ }, []);++ // Keep the `labels` reference stable while the user keeps the same+ // formatting choice — FileManager threads it through the memoized row+ // bundle, and a fresh object identity on every render would invalidate+ // the row memo for the whole tree on unrelated re-renders.+ const fileManagerLabels = useMemo<FileManagerLabels>(+ () => ({+ formatModified: viewOptions.isModifiedRelative ? formatModifiedRelative : formatModifiedAbsolute,+ }),+ [viewOptions.isModifiedRelative],+ );+// Toolbar / empty-area mkdir + upload always target the library root —// row-level "Upload here" / "New folder here" handlers carry their own// explicit path, and DnD passes the destination per drop, so these@@ -277,18 +354,18 @@ const Resources = () => {// target the library root, identical to the toolbar buttons.const fileManagerEmptyAreaActions = useMemo<FileManagerEmptyAreaAction[]>(() => [- {- icon: FolderUp,- id: 'resources-empty-upload',- label: 'Upload files',- onSelect: upload.openFilePicker,- },{icon: FolderPlus,id: 'resources-empty-mkdir',label: 'New folder',onSelect: () => setIsMkdirOpen(true),},+ {+ icon: Upload,+ id: 'resources-empty-upload',+ label: 'Upload files',+ onSelect: upload.openFilePicker,+ },],[upload.openFilePicker],);@@ -319,6 +396,26 @@ const Resources = () => {</BreadcrumbList></Breadcrumb></div>+ <div className="ml-auto flex items-center gap-2 px-4">+ <Button+ disabled={upload.isUploading}+ onClick={() => setIsMkdirOpen(true)}+ size="sm"+ variant="outline"+ >+ <FolderPlus />+ New folder+ </Button>+ <Button+ disabled={upload.isUploading}+ onClick={upload.openFilePicker}+ size="sm"+ variant="secondary"+ >+ {upload.isUploading ? <Loader2 className="animate-spin" /> : <Upload />}+ {upload.isUploading ? 'Uploading...' : 'Upload files'}+ </Button>+ </div></header>);@@ -374,13 +471,13 @@ const Resources = () => {</div>)}- <Form {...search.form}>- <div className="flex gap-2 p-px">+ <div className="flex items-center gap-2">+ <Form {...search.form}><FormFieldcontrol={search.form.control}name="search"render={({ field }) => (- <FormItem className="flex-1">+ <FormItem className="max-w-sm flex-1"><FormControl><InputGroup><InputGroupAddon>@@ -407,51 +504,65 @@ const Resources = () => {</FormItem>)}/>-- <Tooltip>- <TooltipTrigger asChild>- <span>- <Button- disabled={upload.isUploading}- onClick={() => setIsMkdirOpen(true)}- size="icon-sm"- type="button"- variant="outline"- >- <FolderPlus />- </Button>- </span>- </TooltipTrigger>- <TooltipContent>Create new folder</TooltipContent>- </Tooltip>-- <Tooltip>- <TooltipTrigger asChild>- <span>- <Button- disabled={upload.isUploading}- onClick={upload.openFilePicker}- size="icon-sm"- type="button"- variant="outline"- >- {upload.isUploading ? <Loader2 className="animate-spin" /> : <Upload />}- </Button>- </span>- </TooltipTrigger>- <TooltipContent>Upload files</TooltipContent>- </Tooltip>- </div>- </Form>+ </Form>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ className="ml-auto"+ variant="outline"+ >+ Columns <ChevronDown className="ml-2" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuCheckboxItem+ checked={viewOptions.size}+ onCheckedChange={() => toggleViewOption('size')}+ onSelect={(event) => event.preventDefault()}+ >+ Size+ </DropdownMenuCheckboxItem>+ <DropdownMenuCheckboxItem+ checked={viewOptions.modified}+ onCheckedChange={() => toggleViewOption('modified')}+ onSelect={(event) => event.preventDefault()}+ >+ Modified+ </DropdownMenuCheckboxItem>+ <DropdownMenuSeparator />+ <DropdownMenuCheckboxItem+ checked={viewOptions.foldersFirst}+ onCheckedChange={() => toggleViewOption('foldersFirst')}+ onSelect={(event) => event.preventDefault()}+ >+ Folders first+ </DropdownMenuCheckboxItem>+ <DropdownMenuCheckboxItem+ checked={viewOptions.isModifiedRelative}+ disabled={!viewOptions.modified}+ onCheckedChange={() => toggleViewOption('isModifiedRelative')}+ onSelect={(event) => event.preventDefault()}+ >+ Relative dates+ </DropdownMenuCheckboxItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div><FileManageractions={fileManagerActions}bulkActions={fileManagerBulkActions}className="min-h-0 flex-1"+ columns={{+ isModifiedVisible: viewOptions.modified,+ isSizeVisible: viewOptions.size,+ }}emptyAreaActions={fileManagerEmptyAreaActions}emptyState={noResourcesState}files={fileNodes}+ isFoldersFirst={viewOptions.foldersFirst}isLoading={isInitialLoading}+ labels={fileManagerLabels}onExternalFileDrop={handleExternalFileDrop}onMoveItems={handleMoveItems}onOpen={handleOpenFile}diff --git a/frontend/src/pages/settings/settings-api-tokens.tsx b/frontend/src/pages/settings/settings-api-tokens.tsxindex 0f6a8c4b..b895348a 100644--- a/frontend/src/pages/settings/settings-api-tokens.tsx+++ b/frontend/src/pages/settings/settings-api-tokens.tsx@@ -9,10 +9,10 @@ import {CalendarIcon,Check,Copy,+ Ellipsis,ExternalLink,Key,Loader2,- MoreHorizontal,Pencil,Plus,Trash,@@ -762,7 +762,7 @@ const SettingsAPITokens = () => {variant="ghost"><span className="sr-only">Open menu</span>- <MoreHorizontal className="size-4" />+ <Ellipsis /></Button></DropdownMenuTrigger><DropdownMenuContentdiff --git a/frontend/src/pages/settings/settings-mcp-servers.tsx b/frontend/src/pages/settings/settings-mcp-servers.tsxindex 5649d4aa..75b916a6 100644--- a/frontend/src/pages/settings/settings-mcp-servers.tsx+++ b/frontend/src/pages/settings/settings-mcp-servers.tsx@@ -2,18 +2,7 @@ import type { ColumnDef } from '@tanstack/react-table';import { format, isToday } from 'date-fns';import { enUS } from 'date-fns/locale';-import {- AlertCircle,- ArrowDown,- ArrowUp,- Copy,- Loader2,- MoreHorizontal,- Pencil,- Plus,- Server,- Trash,-} from 'lucide-react';+import { AlertCircle, ArrowDown, ArrowUp, Copy, Ellipsis, Loader2, Pencil, Plus, Server, Trash } from 'lucide-react';import { useMemo, useState } from 'react';import { useNavigate } from 'react-router-dom';@@ -453,7 +442,7 @@ const SettingsMcpServers = () => {variant="ghost"><span className="sr-only">Open menu</span>- <MoreHorizontal className="size-4" />+ <Ellipsis /></Button></DropdownMenuTrigger><DropdownMenuContent@@ -466,7 +455,7 @@ const SettingsMcpServers = () => {Edit</DropdownMenuItem><DropdownMenuItem onClick={() => handleClone(server.id)}>- <Copy className="size-4" />+ <Copy className="size-3" />Clone</DropdownMenuItem><DropdownMenuSeparator />diff --git a/frontend/src/pages/settings/settings-prompts.tsx b/frontend/src/pages/settings/settings-prompts.tsxindex 3f27154c..84111afc 100644--- a/frontend/src/pages/settings/settings-prompts.tsx+++ b/frontend/src/pages/settings/settings-prompts.tsx@@ -6,8 +6,8 @@ import {ArrowUp,Bot,Code,+ Ellipsis,Loader2,- MoreHorizontal,Pencil,RotateCcw,Settings,@@ -400,7 +400,7 @@ const SettingsPrompts = () => {variant="ghost"><span className="sr-only">Open menu</span>- <MoreHorizontal className="size-4" />+ <Ellipsis /></Button></DropdownMenuTrigger><DropdownMenuContent@@ -556,7 +556,7 @@ const SettingsPrompts = () => {variant="ghost"><span className="sr-only">Open menu</span>- <MoreHorizontal className="size-4" />+ <Ellipsis /></Button></DropdownMenuTrigger><DropdownMenuContentdiff --git a/frontend/src/pages/settings/settings-providers.tsx b/frontend/src/pages/settings/settings-providers.tsxindex 4a69cad5..a5f8fac9 100644--- a/frontend/src/pages/settings/settings-providers.tsx+++ b/frontend/src/pages/settings/settings-providers.tsx@@ -8,8 +8,8 @@ import {ArrowUp,ChevronDown,Copy,+ Ellipsis,Loader2,- MoreHorizontal,Pencil,Plus,Settings,@@ -383,7 +383,7 @@ const SettingsProviders = () => {variant="ghost"><span className="sr-only">Open menu</span>- <MoreHorizontal className="size-4" />+ <Ellipsis /></Button></DropdownMenuTrigger><DropdownMenuContentdiff --git a/frontend/src/pages/templates/templates.tsx b/frontend/src/pages/templates/templates.tsxindex 63f4bd30..dd89f2f3 100644--- a/frontend/src/pages/templates/templates.tsx+++ b/frontend/src/pages/templates/templates.tsx@@ -1,6 +1,6 @@import type { ColumnDef } from '@tanstack/react-table';-import { ArrowDown, ArrowUp, FileText, Loader2, MoreHorizontal, Pencil, Plus, Trash } from 'lucide-react';+import { ArrowDown, ArrowUp, Ellipsis, FileText, Loader2, Pencil, Plus, Trash } from 'lucide-react';import { useState } from 'react';import { useNavigate } from 'react-router-dom';@@ -18,6 +18,7 @@ import {import { Separator } from '@/components/ui/separator';import { SidebarTrigger } from '@/components/ui/sidebar';import { StatusCard } from '@/components/ui/status-card';+import { cycleColumnSort } from '@/lib/table-sort';import { type Template, useTemplates } from '@/providers/templates-provider';const Templates = () => {@@ -68,7 +69,7 @@ const Templates = () => {return (<ButtonclassName="text-muted-foreground hover:text-primary flex items-center gap-2 p-0 no-underline hover:no-underline"- onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}+ onClick={() => cycleColumnSort(column)}variant="link">Title@@ -94,7 +95,7 @@ const Templates = () => {return (<ButtonclassName="text-muted-foreground hover:text-primary flex items-center gap-2 p-0 no-underline hover:no-underline"- onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}+ onClick={() => cycleColumnSort(column)}variant="link">Text@@ -119,7 +120,7 @@ const Templates = () => {className="size-8 p-0"variant="ghost">- <MoreHorizontal />+ <Ellipsis /></Button></DropdownMenuTrigger><DropdownMenuContent