Skip to content

Fully autonomous AI Agents system capable of performing complex penetration testing tasks

feat: add resourses

Sergey Kozyrenko3002b2bf5eb3
diff --git a/frontend/src/app.tsx b/frontend/src/app.tsx
index 4d57be7f..c6263f42 100644
--- a/frontend/src/app.tsx
+++ b/frontend/src/app.tsx
@@ -14,6 +14,7 @@ import client from '@/lib/apollo';
import { FavoritesProvider } from '@/providers/favorites-provider';
import { FlowProvider } from '@/providers/flow-provider';
import { ProvidersProvider } from '@/providers/providers-provider';
+import { ResourcesProvider } from '@/providers/resources-provider';
import { SidebarFlowsProvider } from '@/providers/sidebar-flows-provider';
import { TemplatesProvider } from '@/providers/templates-provider';
import { ThemeProvider } from '@/providers/theme-provider';
@@ -27,6 +28,7 @@ const FlowReport = lazy(() => import('@/pages/flows/flow-report'));
const Flows = lazy(() => import('@/pages/flows/flows'));
const NewFlow = lazy(() => import('@/pages/flows/new-flow'));
const Login = lazy(() => import('@/pages/login'));
+const Resources = lazy(() => import('@/pages/resources/resources'));
const Template = lazy(() => import('@/pages/templates/template'));
const Templates = lazy(() => import('@/pages/templates/templates'));
const OAuthResult = lazy(() => import('@/pages/oauth-result'));
@@ -63,82 +65,88 @@ const App = () => {
<UserProvider>
<FavoritesProvider>
<TemplatesProvider>
- <Suspense fallback={<PageLoader />}>
- <Routes>
- {/* private routes */}
- <Route element={renderProtectedRoute()}>
- {/* Main layout for chat pages */}
- <Route element={<MainLayout />}>
- <Route
- element={<Dashboard />}
- path="dashboard"
- />
+ <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>
- {/* Flows section with FlowsProvider */}
- <Route element={<FlowsLayout />}>
<Route
- element={<Flows />}
- path="flows"
+ element={<Templates />}
+ path="templates"
/>
<Route
- element={<NewFlow />}
- path="flows/new"
+ element={<Template />}
+ path="templates/:templateId"
/>
+
<Route
- element={
- <FlowProvider>
- <Flow />
- </FlowProvider>
- }
- path="flows/:flowId"
+ element={<Resources />}
+ path="resources"
/>
</Route>
+ {/* Settings with nested routes */}
<Route
- element={<Templates />}
- path="templates"
- />
- <Route
- element={<Template />}
- path="templates/:templateId"
- />
- </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
+ 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 />}
/>
@@ -150,53 +158,54 @@ const App = () => {
path="mcp-servers/:mcpServerId"
element={<SettingsMcpServer />}
/> */}
- {/* Catch-all route for unknown settings paths */}
- <Route
- element={
- <Navigate
- replace
- to="/settings/providers"
- />
- }
- path="*"
- />
+ {/* Catch-all route for unknown settings paths */}
+ <Route
+ element={
+ <Navigate
+ replace
+ to="/settings/providers"
+ />
+ }
+ path="*"
+ />
+ </Route>
</Route>
- </Route>
- {/* report routes */}
- <Route
- element={
- <ProtectedRoute>
- <SystemSettingsProvider>
- <FlowReport />
- </SystemSettingsProvider>
- </ProtectedRoute>
- }
- path="flows/:flowId/report"
- />
+ {/* report routes */}
+ <Route
+ element={
+ <ProtectedRoute>
+ <SystemSettingsProvider>
+ <FlowReport />
+ </SystemSettingsProvider>
+ </ProtectedRoute>
+ }
+ path="flows/:flowId/report"
+ />
- {/* public routes */}
- <Route
- element={renderPublicRoute()}
- path="login"
- />
+ {/* public routes */}
+ <Route
+ element={renderPublicRoute()}
+ path="login"
+ />
- <Route
- element={<OAuthResult />}
- path="oauth/result"
- />
+ <Route
+ element={<OAuthResult />}
+ path="oauth/result"
+ />
- {/* other routes */}
- <Route
- element={<Navigate to="/dashboard" />}
- path="/"
- />
- <Route
- element={<Navigate to="/dashboard" />}
- path="*"
- />
- </Routes>
- </Suspense>
+ {/* other routes */}
+ <Route
+ element={<Navigate to="/dashboard" />}
+ path="/"
+ />
+ <Route
+ element={<Navigate to="/dashboard" />}
+ path="*"
+ />
+ </Routes>
+ </Suspense>
+ </ResourcesProvider>
</TemplatesProvider>
</FavoritesProvider>
</UserProvider>
diff --git a/frontend/src/components/layouts/main-sidebar.tsx b/frontend/src/components/layouts/main-sidebar.tsx
index 62431308..4aca03a8 100644
--- a/frontend/src/components/layouts/main-sidebar.tsx
+++ b/frontend/src/components/layouts/main-sidebar.tsx
@@ -3,6 +3,7 @@ import {
ChevronsUpDown,
Clock,
FileText,
+ Folder,
GitFork,
KeyRound,
LayoutDashboard,
@@ -16,7 +17,7 @@ import {
Sun,
UserIcon,
} from 'lucide-react';
-import { useMemo, useState } from 'react';
+import { type ChangeEvent, useMemo, useRef, useState } from 'react';
import { Link, useMatch, useParams } from 'react-router-dom';
import type { Flow } from '@/providers/sidebar-flows-provider';
@@ -48,6 +49,9 @@ import {
} from '@/components/ui/sidebar';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { PasswordChangeForm } from '@/features/authentication/password-change-form';
+import { ACCEPTED_FILE_TYPES } from '@/features/resources/constants';
+import { ResourcesUploadOptionsDialog } from '@/features/resources/resources-upload-options-dialog';
+import { useFileUpload } from '@/features/resources/use-file-upload';
import { useTheme } from '@/hooks/use-theme';
import { useFavorites } from '@/providers/favorites-provider';
import { useSidebarFlows } from '@/providers/sidebar-flows-provider';
@@ -90,9 +94,11 @@ const FlowMenuItem = ({ activeFlowId, flow, isFavorite, onToggleFavorite }: Flow
export const MainSidebar = () => {
const [isPasswordModalOpen, setIsPasswordModalOpen] = useState(false);
+ const resourcesFileInputRef = useRef<HTMLInputElement>(null);
const isDashboardActive = useMatch('/dashboard');
const isFlowsActive = useMatch('/flows/*');
const isTemplatesActive = useMatch('/templates/*');
+ const isResourcesActive = useMatch('/resources/*');
const isSettingsActive = useMatch('/settings/*');
const { flowId: flowIdParam } = useParams<{ flowId: string }>();
@@ -102,6 +108,21 @@ export const MainSidebar = () => {
const { addFavoriteFlow, favoriteFlowIds, removeFavoriteFlow } = useFavorites();
const { flows } = useSidebarFlows();
+ const {
+ handleFileChange: handleResourcesFileChange,
+ handleUploadOptionsCancel,
+ handleUploadOptionsConfirm,
+ isUploadOptionsDialogOpen,
+ } = useFileUpload();
+
+ const handleResourcesUploadClick = () => {
+ resourcesFileInputRef.current?.click();
+ };
+
+ const handleResourcesFileInputChange = async (event: ChangeEvent<HTMLInputElement>) => {
+ await handleResourcesFileChange(event.target.files, resourcesFileInputRef);
+ };
+
const flowId = useMemo(() => (flowIdParam ? Number(flowIdParam) : null), [flowIdParam]);
const favoriteFlows = useMemo(
@@ -198,6 +219,26 @@ export const MainSidebar = () => {
</Link>
</SidebarMenuAction>
</SidebarMenuItem>
+ <SidebarMenuItem>
+ <SidebarMenuButton
+ asChild
+ isActive={!!isResourcesActive}
+ >
+ <Link to="/resources">
+ <Folder />
+ Resources
+ </Link>
+ </SidebarMenuButton>
+ <SidebarMenuAction
+ className="data-[state=open]:bg-accent rounded-sm"
+ onClick={handleResourcesUploadClick}
+ showOnHover
+ title="Upload file"
+ type="button"
+ >
+ <Plus />
+ </SidebarMenuAction>
+ </SidebarMenuItem>
</SidebarMenu>
</SidebarGroupContent>
</SidebarGroup>
@@ -355,6 +396,20 @@ export const MainSidebar = () => {
</SidebarFooter>
<SidebarRail />
+ <input
+ accept={ACCEPTED_FILE_TYPES}
+ className="hidden"
+ multiple
+ onChange={handleResourcesFileInputChange}
+ ref={resourcesFileInputRef}
+ type="file"
+ />
+ <ResourcesUploadOptionsDialog
+ isOpen={isUploadOptionsDialogOpen}
+ onCancel={handleUploadOptionsCancel}
+ onConfirm={handleUploadOptionsConfirm}
+ />
+
<Dialog
onOpenChange={setIsPasswordModalOpen}
open={isPasswordModalOpen}
diff --git a/frontend/src/features/flows/flow-form.tsx b/frontend/src/features/flows/flow-form.tsx
index de3038ee..198ebfdb 100644
--- a/frontend/src/features/flows/flow-form.tsx
+++ b/frontend/src/features/flows/flow-form.tsx
@@ -1,10 +1,23 @@
import { zodResolver } from '@hookform/resolvers/zod';
-import { ArrowUp, Check, ChevronDown, FileSymlink, FileText, Square, X } from 'lucide-react';
+import {
+ ArrowUp,
+ Check,
+ ChevronDown,
+ FileSymlink,
+ FileText,
+ Loader2,
+ Paperclip,
+ Plus,
+ Square,
+ X,
+} from 'lucide-react';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useRef } from 'react';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
+import type { ResourceItem } from '@/features/resources/types';
+
import { ProviderIcon } from '@/components/icons/provider-icon';
import ConfirmationDialog from '@/components/shared/confirmation-dialog';
import {
@@ -26,8 +39,12 @@ import {
import { Spinner } from '@/components/ui/spinner';
import { Switch } from '@/components/ui/switch';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
+import { ACCEPTED_FILE_TYPES } from '@/features/resources/constants';
+import { ResourcesUploadOptionsDialog } from '@/features/resources/resources-upload-options-dialog';
+import { useFileUpload } from '@/features/resources/use-file-upload';
import { getProviderDisplayName } from '@/models/provider';
import { useProviders } from '@/providers/providers-provider';
+import { useResources } from '@/providers/resources-provider';
import { type Template, useTemplates } from '@/providers/templates-provider';
const formSchema = z.object({
@@ -65,10 +82,56 @@ export const FlowForm = ({
}: FlowFormProps) => {
const { providers, setSelectedProvider } = useProviders();
const { templates } = useTemplates();
+ const { resources } = useResources();
const [isReplaceConfirmOpen, setIsReplaceConfirmOpen] = useState(false);
const [pendingTemplate, setPendingTemplate] = useState<null | Template>(null);
const [providerSearch, setProviderSearch] = useState('');
const [templateSearch, setTemplateSearch] = useState('');
+ const [resourceSearch, setResourceSearch] = useState('');
+ const [attachedFileIds, setAttachedFileIds] = useState<string[]>([]);
+
+ const fileInputRef = useRef<HTMLInputElement>(null);
+
+ const handleResourceAttach = useCallback((resource: ResourceItem) => {
+ setAttachedFileIds((current) => (current.includes(resource.id) ? current : [...current, resource.id]));
+ }, []);
+
+ const { handleFileChange, handleUploadOptionsCancel, handleUploadOptionsConfirm, isUploadOptionsDialogOpen } =
+ useFileUpload({ onResourceAttach: handleResourceAttach });
+
+ const attachedFiles = useMemo<ResourceItem[]>(() => {
+ const byId = new Map(resources.map((item) => [item.id, item]));
+
+ return attachedFileIds
+ .map((id) => byId.get(id))
+ .filter((item): item is ResourceItem => Boolean(item));
+ }, [attachedFileIds, resources]);
+
+ const isAnyAttachmentUploading = attachedFiles.some((file) => !file.isUploaded);
+
+ const sortedResources = useMemo(
+ () =>
+ [...resources].sort(
+ (a, b) => new Date(b.uploadedAt).getTime() - new Date(a.uploadedAt).getTime(),
+ ),
+ [resources],
+ );
+
+ const filteredResources = useMemo(() => {
+ const search = resourceSearch.trim().toLowerCase();
+
+ if (!search) {
+ return sortedResources;
+ }
+
+ return sortedResources.filter((resource) => {
+ const fullName = resource.format
+ ? `${resource.name}.${resource.format}`
+ : resource.name;
+
+ return fullName.toLowerCase().includes(search);
+ });
+ }, [sortedResources, resourceSearch]);
const filteredTemplates = useMemo(() => {
if (!templateSearch.trim()) {
@@ -158,6 +221,25 @@ export const FlowForm = ({
const handleSubmit = async (values: FlowFormValues) => {
await onSubmit(values);
resetField('message');
+ setAttachedFileIds([]);
+ };
+
+ const handleAttachClick = () => {
+ fileInputRef.current?.click();
+ };
+
+ const handleFileInputChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
+ await handleFileChange(event.target.files, fileInputRef);
+ };
+
+ const handleRemoveAttachment = (id: string) => {
+ setAttachedFileIds((current) => current.filter((fileId) => fileId !== id));
+ };
+
+ const handleToggleAttachment = (id: string) => {
+ setAttachedFileIds((current) =>
+ current.includes(id) ? current.filter((fileId) => fileId !== id) : [...current, id],
+ );
};
const handleKeyDown = (event: React.KeyboardEvent<HTMLTextAreaElement>) => {
@@ -203,6 +285,47 @@ export const FlowForm = ({
render={({ field }) => (
<FormControl>
<InputGroup className="block">
+ {attachedFiles.length > 0 && (
+ <InputGroupAddon
+ align="block-start"
+ className="flex-wrap gap-1.5"
+ >
+ {attachedFiles.map((file) => {
+ const fullName = file.format ? `${file.name}.${file.format}` : file.name;
+
+ return (
+ <div
+ className="bg-muted/50 flex max-w-full items-center gap-1.5 rounded-md border px-2 py-1 text-xs"
+ key={file.id}
+ title={fullName}
+ >
+ {file.isUploaded ? (
+ <FileText className="text-muted-foreground size-3.5 shrink-0" />
+ ) : (
+ <Loader2 className="text-muted-foreground size-3.5 shrink-0 animate-spin" />
+ )}
+ <span className="text-foreground max-w-40 truncate">
+ {fullName}
+ </span>
+ {!file.isUploaded && (
+ <span className="text-muted-foreground tabular-nums">
+ {file.progress}%
+ </span>
+ )}
+ <button
+ aria-label={`Remove ${fullName}`}
+ className="text-muted-foreground hover:text-destructive ml-0.5 flex shrink-0 items-center justify-center"
+ disabled={isFormDisabled}
+ onClick={() => handleRemoveAttachment(file.id)}
+ type="button"
+ >
+ <X className="size-3.5" />
+ </button>
+ </div>
+ );
+ })}
+ </InputGroupAddon>
+ )}
<InputGroupTextareaAutosize
{...field}
autoFocus
@@ -426,10 +549,130 @@ export const FlowForm = ({
</DropdownMenuContent>
</DropdownMenu>
+ <DropdownMenu
+ onOpenChange={(open) => {
+ if (!open) {
+ setResourceSearch('');
+ }
+ }}
+ >
+ <DropdownMenuTrigger asChild>
+ <InputGroupButton
+ disabled={isFormDisabled}
+ variant="ghost"
+ >
+ <Paperclip className="shrink-0" />
+ {attachedFiles.length > 0 && (
+ <span className="bg-muted text-muted-foreground -mx-0.5 flex h-4 min-w-4 items-center justify-center rounded px-1 text-xs font-medium tabular-nums">
+ {attachedFiles.length}
+ </span>
+ )}
+ <ChevronDown />
+ </InputGroupButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ align="start"
+ side="top"
+ >
+ <DropdownMenuGroup className="-m-1 rounded-none p-0">
+ <InputGroup className="-mb-1 rounded-none border-0 shadow-none [&:has([data-slot=input-group-control]:focus-visible)]:border-0 [&:has([data-slot=input-group-control]:focus-visible)]:ring-0">
+ <InputGroupInput
+ onChange={(event) => setResourceSearch(event.target.value)}
+ onClick={(event) => event.stopPropagation()}
+ onKeyDown={(event) => event.stopPropagation()}
+ placeholder="Search..."
+ value={resourceSearch}
+ />
+ {resourceSearch && (
+ <InputGroupAddon align="inline-end">
+ <InputGroupButton
+ onClick={(event) => {
+ event.stopPropagation();
+ setResourceSearch('');
+ }}
+ >
+ <X />
+ </InputGroupButton>
+ </InputGroupAddon>
+ )}
+ </InputGroup>
+ <DropdownMenuSeparator />
+ </DropdownMenuGroup>
+ <DropdownMenuGroup className="max-h-64 overflow-y-auto">
+ {!filteredResources.length ? (
+ <DropdownMenuItem
+ className="min-h-16 justify-center"
+ disabled
+ >
+ {resourceSearch
+ ? 'No results found'
+ : 'No available resources'}
+ </DropdownMenuItem>
+ ) : (
+ filteredResources.map((resource) => {
+ const isSelected = attachedFileIds.includes(resource.id);
+ const fullName = resource.format
+ ? `${resource.name}.${resource.format}`
+ : resource.name;
+
+ return (
+ <DropdownMenuItem
+ key={resource.id}
+ onSelect={(event) => {
+ event.preventDefault();
+
+ if (isFormDisabled) {
+ return;
+ }
+
+ handleToggleAttachment(resource.id);
+ }}
+ >
+ <div className="flex w-full min-w-0 items-center gap-2">
+ {resource.isUploaded ? (
+ <FileText className="text-muted-foreground size-4 shrink-0" />
+ ) : (
+ <Loader2 className="text-muted-foreground size-4 shrink-0 animate-spin" />
+ )}
+ <span className="max-w-80 flex-1 truncate">
+ {fullName}
+ </span>
+ {!resource.isUploaded && (
+ <span className="text-muted-foreground tabular-nums text-xs">
+ {resource.progress}%
+ </span>
+ )}
+ {isSelected && (
+ <Check className="ml-auto size-4 shrink-0" />
+ )}
+ </div>
+ </DropdownMenuItem>
+ );
+ })
+ )}
+ </DropdownMenuGroup>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onSelect={(event) => {
+ event.preventDefault();
+
+ if (isFormDisabled) {
+ return;
+ }
+
+ handleAttachClick();
+ }}
+ >
+ <Plus />
+ Upload file
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+
{!isLoading || isSubmitting ? (
<InputGroupButton
className="ml-auto"
- disabled={isSubmitting || !isValid}
+ disabled={isSubmitting || !isValid || isAnyAttachmentUploading}
size="icon-xs"
type="submit"
variant="default"
@@ -454,6 +697,14 @@ export const FlowForm = ({
)}
/>
</form>
+ <input
+ accept={ACCEPTED_FILE_TYPES}
+ className="hidden"
+ multiple
+ onChange={handleFileInputChange}
+ ref={fileInputRef}
+ type="file"
+ />
<ConfirmationDialog
confirmIcon={<FileSymlink />}
confirmText="Replace"
@@ -470,6 +721,11 @@ export const FlowForm = ({
isOpen={isReplaceConfirmOpen}
title="Replace content?"
/>
+ <ResourcesUploadOptionsDialog
+ isOpen={isUploadOptionsDialogOpen}
+ onCancel={handleUploadOptionsCancel}
+ onConfirm={handleUploadOptionsConfirm}
+ />
</Form>
);
};
diff --git a/frontend/src/features/resources/api.ts b/frontend/src/features/resources/api.ts
new file mode 100644
index 00000000..c1a8be12
--- /dev/null
+++ b/frontend/src/features/resources/api.ts
@@ -0,0 +1,100 @@
+import type { ResourcePreviewModel, UploadUrlResponse } from './types';
+
+import { getFileBaseName, getFileExtension } from './constants';
+import { mockStore } from './mock-store';
+
+const NETWORK_LATENCY_MIN_MS = 200;
+const NETWORK_LATENCY_MAX_MS = 500;
+const UPLOAD_TICK_INTERVAL_MS = 120;
+const UPLOAD_TICK_PROGRESS_STEP = 10;
+
+const randomDelay = () =>
+ new Promise<void>((resolve) => {
+ const delay = NETWORK_LATENCY_MIN_MS + Math.random() * (NETWORK_LATENCY_MAX_MS - NETWORK_LATENCY_MIN_MS);
+ setTimeout(resolve, delay);
+ });
+
+const generateId = () => {
+ if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) {
+ return `res_${crypto.randomUUID()}`;
+ }
+
+ return `res_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
+};
+
+export async function deleteResource(id: string): Promise<void> {
+ await randomDelay();
+ mockStore.removeById(id);
+}
+
+export async function getResources(): Promise<ResourcePreviewModel[]> {
+ await randomDelay();
+
+ return mockStore.list();
+}
+
+export async function getUploadUrl({
+ fileName,
+ knowledgeId,
+}: {
+ fileName: string;
+ knowledgeId?: string;
+}): Promise<UploadUrlResponse> {
+ await randomDelay();
+
+ const id = knowledgeId ?? generateId();
+ const item: ResourcePreviewModel = {
+ format: getFileExtension(fileName),
+ id,
+ name: getFileBaseName(fileName),
+ uploadedAt: new Date().toISOString(),
+ };
+
+ if (knowledgeId) {
+ const updated = mockStore.update(knowledgeId, item);
+
+ if (!updated) {
+ mockStore.insert(item);
+ }
+ } else {
+ mockStore.insert(item);
+ }
+
+ return {
+ id,
+ item,
+ uploadUrl: `mock://upload/${id}`,
+ };
+}
+
+export async function uploadResource({
+ file,
+ onProgress,
+}: {
+ file: File;
+ onProgress?: (progress: number) => void;
+ uploadUrl: string;
+}): Promise<void> {
+ if (!file.size) {
+ throw new Error('Cannot upload an empty file');
+ }
+
+ return new Promise<void>((resolve) => {
+ let progress = 0;
+
+ const tick = () => {
+ progress = Math.min(100, progress + UPLOAD_TICK_PROGRESS_STEP);
+ onProgress?.(progress);
+
+ if (progress >= 100) {
+ resolve();
+
+ return;
+ }
+
+ setTimeout(tick, UPLOAD_TICK_INTERVAL_MS);
+ };
+
+ setTimeout(tick, UPLOAD_TICK_INTERVAL_MS);
+ });
+}
diff --git a/frontend/src/features/resources/constants.ts b/frontend/src/features/resources/constants.ts
new file mode 100644
index 00000000..9e68d8d7
--- /dev/null
+++ b/frontend/src/features/resources/constants.ts
@@ -0,0 +1,45 @@
+export const UPLOAD_COMPLETE_ANIMATION_DELAY = 200;
+
+export const MAX_FILE_SIZE_MB = 5;
+
+export const MAX_FILE_SIZE_MB_BY_EXTENSION: Record<string, number> = {
+ ppt: 20,
+ pptx: 20,
+};
+
+export const ACCEPTED_FILE_EXTENSIONS = [
+ 'txt',
+ 'md',
+ 'html',
+ 'doc',
+ 'docx',
+ 'csv',
+ 'tsv',
+ 'xls',
+ 'xlsx',
+ 'pdf',
+ 'ppt',
+ 'pptx',
+];
+
+export const ACCEPTED_FILE_TYPES = ACCEPTED_FILE_EXTENSIONS.map((extension) => `.${extension}`).join(',');
+
+export function getFileBaseName(fileName: string): string {
+ const lastDotIndex = fileName.lastIndexOf('.');
+
+ return lastDotIndex === -1 ? fileName : fileName.slice(0, lastDotIndex);
+}
+
+export function getFileExtension(fileName: string): string {
+ return fileName.split('.').pop()?.toLowerCase() ?? '';
+}
+
+export function isFileTypeAccepted(fileName: string): boolean {
+ const extension = fileName.split('.').pop()?.toLowerCase();
+
+ if (!extension) {
+ return false;
+ }
+
+ return ACCEPTED_FILE_EXTENSIONS.includes(extension);
+}
diff --git a/frontend/src/features/resources/mock-store.ts b/frontend/src/features/resources/mock-store.ts
new file mode 100644
index 00000000..e8c536d4
--- /dev/null
+++ b/frontend/src/features/resources/mock-store.ts
@@ -0,0 +1,132 @@
+import { Log } from '@/lib/log';
+
+import type { ResourcePreviewModel } from './types';
+
+const STORAGE_KEY = 'pentagi:resources';
+
+const SEED_RESOURCES: ResourcePreviewModel[] = [
+ {
+ format: 'pdf',
+ id: 'res_seed_1',
+ name: 'web-app-pentest-checklist',
+ uploadedAt: new Date(Date.now() - 1000 * 60 * 60 * 2).toISOString(),
+ },
+ {
+ format: 'md',
+ id: 'res_seed_2',
+ name: 'recon-tools-cheatsheet',
+ uploadedAt: new Date(Date.now() - 1000 * 60 * 60 * 24 * 3).toISOString(),
+ },
+ {
+ format: 'docx',
+ id: 'res_seed_3',
+ name: 'incident-response-playbook',
+ uploadedAt: new Date(Date.now() - 1000 * 60 * 60 * 24 * 10).toISOString(),
+ },
+ {
+ format: 'csv',
+ id: 'res_seed_4',
+ name: 'cve-export-2025-q4',
+ uploadedAt: new Date(Date.now() - 1000 * 60 * 60 * 24 * 32).toISOString(),
+ },
+ {
+ format: 'txt',
+ id: 'res_seed_5',
+ name: 'wordlist-rockyou-top-1000',
+ uploadedAt: new Date(Date.now() - 1000 * 60 * 60 * 24 * 60).toISOString(),
+ },
+];
+
+const isBrowser = typeof window !== 'undefined';
+
+const readFromStorage = (): null | ResourcePreviewModel[] => {
+ if (!isBrowser) {
+ return null;
+ }
+
+ try {
+ const raw = window.localStorage.getItem(STORAGE_KEY);
+
+ if (!raw) {
+ return null;
+ }
+
+ const parsed = JSON.parse(raw) as unknown;
+
+ if (!Array.isArray(parsed)) {
+ return null;
+ }
+
+ return parsed as ResourcePreviewModel[];
+ } catch (error) {
+ Log.warn('Failed to parse resources from localStorage');
+ Log.error('mock-store readFromStorage error:', error);
+
+ return null;
+ }
+};
+
+const writeToStorage = (items: ResourcePreviewModel[]): void => {
+ if (!isBrowser) {
+ return;
+ }
+
+ try {
+ window.localStorage.setItem(STORAGE_KEY, JSON.stringify(items));
+ } catch (error) {
+ Log.warn('Failed to persist resources to localStorage');
+ Log.error('mock-store writeToStorage error:', error);
+ }
+};
+
+const ensureSeed = (): ResourcePreviewModel[] => {
+ const existing = readFromStorage();
+
+ if (existing) {
+ return existing;
+ }
+
+ writeToStorage(SEED_RESOURCES);
+
+ return [...SEED_RESOURCES];
+};
+
+export const mockStore = {
+ insert(item: ResourcePreviewModel): ResourcePreviewModel {
+ const items = ensureSeed();
+ const next = [item, ...items.filter((existing) => existing.id !== item.id)];
+ writeToStorage(next);
+
+ return item;
+ },
+ list(): ResourcePreviewModel[] {
+ return ensureSeed();
+ },
+ removeById(id: string): boolean {
+ const items = ensureSeed();
+ const next = items.filter((item) => item.id !== id);
+
+ if (next.length === items.length) {
+ return false;
+ }
+
+ writeToStorage(next);
+
+ return true;
+ },
+ update(id: string, patch: Partial<ResourcePreviewModel>): null | ResourcePreviewModel {
+ const items = ensureSeed();
+ const index = items.findIndex((item) => item.id === id);
+
+ if (index === -1) {
+ return null;
+ }
+
+ const updated: ResourcePreviewModel = { ...items[index]!, ...patch, id };
+ const next = [...items];
+ next[index] = updated;
+ writeToStorage(next);
+
+ return updated;
+ },
+};
diff --git a/frontend/src/features/resources/resources-upload-options-dialog.tsx b/frontend/src/features/resources/resources-upload-options-dialog.tsx
new file mode 100644
index 00000000..72c8e1f5
--- /dev/null
+++ b/frontend/src/features/resources/resources-upload-options-dialog.tsx
@@ -0,0 +1,128 @@
+import { useState } from 'react';
+
+import { Button } from '@/components/ui/button';
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog';
+import { cn } from '@/lib/utils';
+
+import type { UploadOption } from './use-file-upload';
+
+interface OptionDescriptor {
+ description: string;
+ label: string;
+ value: UploadOption;
+}
+
+interface ResourcesUploadOptionsDialogProps {
+ isOpen: boolean;
+ onCancel: () => void;
+ onConfirm: (option: UploadOption) => void;
+}
+
+const OPTIONS: OptionDescriptor[] = [
+ {
+ description: 'Uploads will overwrite files with the same names.',
+ label: 'Replace existing files',
+ value: 'replace',
+ },
+ {
+ description: 'Saves both copies. New files get renamed automatically.',
+ label: 'Keep both versions',
+ value: 'keep-both',
+ },
+];
+
+export function ResourcesUploadOptionsDialog({ isOpen, onCancel, onConfirm }: ResourcesUploadOptionsDialogProps) {
+ const [selectedOption, setSelectedOption] = useState<UploadOption>('replace');
+
+ const handleCancel = () => {
+ setSelectedOption('replace');
+ onCancel();
+ };
+
+ const handleConfirm = () => {
+ const option = selectedOption;
+ setSelectedOption('replace');
+ onConfirm(option);
+ };
+
+ return (
+ <Dialog
+ onOpenChange={(open) => {
+ if (!open) {
+ handleCancel();
+ }
+ }}
+ open={isOpen}
+ >
+ <DialogContent
+ className="max-w-md"
+ onEscapeKeyDown={(event) => {
+ event.stopPropagation();
+ event.preventDefault();
+ }}
+ onInteractOutside={(event) => event.preventDefault()}
+ >
+ <DialogHeader>
+ <DialogTitle>Upload options</DialogTitle>
+ <DialogDescription>One or more files already exist in Resources.</DialogDescription>
+ </DialogHeader>
+
+ <div className="flex flex-col gap-2">
+ {OPTIONS.map((option) => {
+ const isSelected = selectedOption === option.value;
+
+ return (
+ <button
+ aria-pressed={isSelected}
+ className={cn(
+ 'flex items-start gap-3 rounded-lg border p-3 text-left transition-colors',
+ 'hover:bg-muted/40 focus-visible:ring-ring focus-visible:ring-2 focus-visible:outline-hidden',
+ isSelected ? 'border-primary bg-muted/30' : 'border-border',
+ )}
+ key={option.value}
+ onClick={() => setSelectedOption(option.value)}
+ type="button"
+ >
+ <span
+ aria-hidden
+ className={cn(
+ 'mt-0.5 inline-flex size-4 shrink-0 items-center justify-center rounded-full border',
+ isSelected ? 'border-primary' : 'border-input',
+ )}
+ >
+ <span
+ className={cn(
+ 'size-2 rounded-full transition-opacity',
+ isSelected ? 'bg-primary opacity-100' : 'opacity-0',
+ )}
+ />
+ </span>
+ <span className="flex flex-col gap-0.5">
+ <span className="text-sm font-medium">{option.label}</span>
+ <span className="text-muted-foreground text-xs">{option.description}</span>
+ </span>
+ </button>
+ );
+ })}
+ </div>
+
+ <DialogFooter className="gap-2">
+ <Button
+ onClick={handleCancel}
+ variant="outline"
+ >
+ Cancel
+ </Button>
+ <Button onClick={handleConfirm}>Upload</Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/frontend/src/features/resources/types.ts b/frontend/src/features/resources/types.ts
new file mode 100644
index 00000000..3d8b0a96
--- /dev/null
+++ b/frontend/src/features/resources/types.ts
@@ -0,0 +1,17 @@
+export interface ResourceItem extends ResourcePreviewModel {
+ isUploaded: boolean;
+ progress: number;
+}
+
+export interface ResourcePreviewModel {
+ format: string;
+ id: string;
+ name: string;
+ uploadedAt: string;
+}
+
+export interface UploadUrlResponse {
+ id: string;
+ item: ResourcePreviewModel;
+ uploadUrl: string;
+}
diff --git a/frontend/src/features/resources/use-file-upload.ts b/frontend/src/features/resources/use-file-upload.ts
new file mode 100644
index 00000000..39e4305a
--- /dev/null
+++ b/frontend/src/features/resources/use-file-upload.ts
@@ -0,0 +1,188 @@
+import { useCallback, useState } from 'react';
+import { toast } from 'sonner';
+
+import { useResources } from '@/providers/resources-provider';
+
+import type { ResourceItem } from './types';
+
+import {
+ getFileBaseName,
+ getFileExtension,
+ isFileTypeAccepted,
+ MAX_FILE_SIZE_MB,
+ MAX_FILE_SIZE_MB_BY_EXTENSION,
+} from './constants';
+
+export type UploadOption = 'keep-both' | 'replace';
+
+interface PendingFile {
+ existingResource: null | ResourceItem;
+ file: File;
+}
+
+interface UseFileUploadOptions {
+ onResourceAttach?: (resource: ResourceItem) => void;
+}
+
+const getNextAvailableFileName = (originalFileName: string, usedNames: Set<string>): string => {
+ const lastDotIndex = originalFileName.lastIndexOf('.');
+ const hasExtension = lastDotIndex !== -1;
+
+ const baseName = hasExtension ? originalFileName.slice(0, lastDotIndex) : originalFileName;
+ const extension = hasExtension ? originalFileName.slice(lastDotIndex) : '';
+
+ let counter = 1;
+ let nextName = `${baseName} (${counter})${extension}`;
+
+ while (usedNames.has(nextName)) {
+ counter += 1;
+ nextName = `${baseName} (${counter})${extension}`;
+ }
+
+ return nextName;
+};
+
+const buildFullName = (item: { format: string; name: string }) => {
+ if (!item.format) {
+ return item.name;
+ }
+
+ return `${item.name}.${item.format}`;
+};
+
+export function useFileUpload(options?: UseFileUploadOptions) {
+ const { resources, uploadResource } = useResources();
+ const onResourceAttach = options?.onResourceAttach;
+
+ const [pendingFiles, setPendingFiles] = useState<PendingFile[]>([]);
+ const [isUploadOptionsDialogOpen, setIsUploadOptionsDialogOpen] = useState(false);
+
+ const processFiles = useCallback(
+ async (files: PendingFile[], option: UploadOption) => {
+ const usedFileNames = new Set<string>(resources.map(buildFullName));
+
+ const filesToUpload = files.map(({ existingResource, file }) => {
+ let fileName: string;
+ let knowledgeId: string | undefined;
+
+ if (option === 'replace' && existingResource) {
+ knowledgeId = existingResource.id;
+ fileName = file.name;
+ } else if (option === 'keep-both' && usedFileNames.has(file.name)) {
+ fileName = getNextAvailableFileName(file.name, usedFileNames);
+ usedFileNames.add(fileName);
+ } else {
+ fileName = file.name;
+ usedFileNames.add(fileName);
+ }
+
+ return { file, fileName, knowledgeId };
+ });
+
+ await Promise.allSettled(
+ filesToUpload.map(({ file, fileName, knowledgeId }) =>
+ uploadResource(file, { fileName, knowledgeId, onStart: onResourceAttach }),
+ ),
+ );
+ },
+ [resources, uploadResource, onResourceAttach],
+ );
+
+ const handleFileChange = useCallback(
+ async (selectedFiles: FileList | null, fileInputRef?: React.RefObject<HTMLInputElement | null>) => {
+ const resetInput = () => {
+ if (!fileInputRef?.current) {
+ return;
+ }
+
+ requestAnimationFrame(() => {
+ if (fileInputRef.current) {
+ fileInputRef.current.value = '';
+ }
+ });
+ };
+
+ if (!selectedFiles?.length) {
+ return;
+ }
+
+ const filesToProcess: PendingFile[] = [];
+
+ for (const file of Array.from(selectedFiles)) {
+ if (!file.size) {
+ toast.error(`File "${file.name}" is empty`, {
+ description: 'Please upload a file with content.',
+ });
+
+ continue;
+ }
+
+ if (!isFileTypeAccepted(file.name)) {
+ toast.error(`File "${file.name}" has unsupported format`, {
+ description: 'Please upload a supported file type.',
+ });
+
+ continue;
+ }
+
+ const extension = getFileExtension(file.name);
+ const maxFileSize = MAX_FILE_SIZE_MB_BY_EXTENSION[extension] ?? MAX_FILE_SIZE_MB;
+
+ if (file.size > maxFileSize * 1024 * 1024) {
+ toast.error(`File "${file.name}" is too large`, {
+ description: `Maximum file size is ${maxFileSize}MB.`,
+ });
+
+ continue;
+ }
+
+ const baseName = getFileBaseName(file.name);
+ const existingResource =
+ resources.find((item) => item.name === baseName && item.format === extension) ?? null;
+
+ filesToProcess.push({ existingResource, file });
+ }
+
+ if (!filesToProcess.length) {
+ resetInput();
+
+ return;
+ }
+
+ const hasDuplicates = filesToProcess.some((entry) => entry.existingResource !== null);
+
+ if (hasDuplicates) {
+ setPendingFiles(filesToProcess);
+ setIsUploadOptionsDialogOpen(true);
+ } else {
+ await processFiles(filesToProcess, 'keep-both');
+ }
+
+ resetInput();
+ },
+ [processFiles, resources],
+ );
+
+ const handleUploadOptionsConfirm = useCallback(
+ async (option: UploadOption) => {
+ setIsUploadOptionsDialogOpen(false);
+ const files = pendingFiles;
+ setPendingFiles([]);
+ await processFiles(files, option);
+ },
+ [pendingFiles, processFiles],
+ );
+
+ const handleUploadOptionsCancel = useCallback(() => {
+ setIsUploadOptionsDialogOpen(false);
+ setPendingFiles([]);
+ }, []);
+
+ return {
+ handleFileChange,
+ handleUploadOptionsCancel,
+ handleUploadOptionsConfirm,
+ isUploadOptionsDialogOpen,
+ pendingFiles,
+ };
+}
diff --git a/frontend/src/pages/resources/resources.tsx b/frontend/src/pages/resources/resources.tsx
new file mode 100644
index 00000000..e8a3bdc7
--- /dev/null
+++ b/frontend/src/pages/resources/resources.tsx
@@ -0,0 +1,353 @@
+import type { ColumnDef } from '@tanstack/react-table';
+
+import { format, formatDistanceToNow } from 'date-fns';
+import { ArrowDown, ArrowUp, Folder, Loader2, MoreHorizontal, Plus, Trash } from 'lucide-react';
+import { useMemo, useRef, useState } from 'react';
+
+import type { ResourceItem } from '@/features/resources/types';
+
+import ConfirmationDialog from '@/components/shared/confirmation-dialog';
+import { Breadcrumb, BreadcrumbItem, BreadcrumbList, BreadcrumbPage } from '@/components/ui/breadcrumb';
+import { Button } from '@/components/ui/button';
+import { ContextMenuItem } from '@/components/ui/context-menu';
+import { DataTable } from '@/components/ui/data-table';
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu';
+import { Separator } from '@/components/ui/separator';
+import { SidebarTrigger } from '@/components/ui/sidebar';
+import { StatusCard } from '@/components/ui/status-card';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
+import { ACCEPTED_FILE_TYPES } from '@/features/resources/constants';
+import { ResourcesUploadOptionsDialog } from '@/features/resources/resources-upload-options-dialog';
+import { useFileUpload } from '@/features/resources/use-file-upload';
+import { useResources } from '@/providers/resources-provider';
+
+const Resources = () => {
+ const { deleteResource, resources } = useResources();
+ const fileInputRef = useRef<HTMLInputElement>(null);
+
+ const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
+ const [deletingResource, setDeletingResource] = useState<null | ResourceItem>(null);
+ const [deletingIds, setDeletingIds] = useState<Set<string>>(new Set());
+
+ const { handleFileChange, handleUploadOptionsCancel, handleUploadOptionsConfirm, isUploadOptionsDialogOpen } =
+ useFileUpload();
+
+ const handleUploadFile = () => {
+ fileInputRef.current?.click();
+ };
+
+ const handleFileInputChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
+ await handleFileChange(event.target.files, fileInputRef);
+ };
+
+ const handleDeleteDialogOpen = (resource: ResourceItem) => {
+ setDeletingResource(resource);
+ setIsDeleteDialogOpen(true);
+ };
+
+ const handleDelete = async () => {
+ if (!deletingResource) {
+ return;
+ }
+
+ setDeletingIds((prev) => new Set(prev).add(deletingResource.id));
+
+ try {
+ await deleteResource(deletingResource.id);
+ setDeletingResource(null);
+ } catch {
+ // Error already handled in provider with toast
+ } finally {
+ setDeletingIds((prev) => {
+ const next = new Set(prev);
+ next.delete(deletingResource.id);
+
+ return next;
+ });
+ }
+ };
+
+ const columns: ColumnDef<ResourceItem>[] = useMemo(
+ () => [
+ {
+ accessorKey: 'name',
+ cell: ({ row }) => {
+ const resource = row.original;
+
+ return (
+ <div className="flex min-w-0 flex-col gap-0.5">
+ <span className="truncate font-medium">{resource.name}</span>
+ {!resource.isUploaded && (
+ <span className="text-muted-foreground flex items-center gap-1.5 text-xs">
+ <Loader2 className="size-3 animate-spin" />
+ Uploading… {resource.progress}%
+ </span>
+ )}
+ </div>
+ );
+ },
+ enableHiding: false,
+ header: ({ column }) => {
+ const sorted = column.getIsSorted();
+
+ return (
+ <Button
+ className="text-muted-foreground hover:text-primary flex items-center gap-2 p-0 no-underline hover:no-underline"
+ onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
+ variant="link"
+ >
+ Name
+ {sorted === 'asc' ? (
+ <ArrowDown className="size-4" />
+ ) : sorted === 'desc' ? (
+ <ArrowUp className="size-4" />
+ ) : null}
+ </Button>
+ );
+ },
+ },
+ {
+ accessorKey: 'format',
+ cell: ({ row }) => {
+ const value = (row.getValue('format') as string) ?? '';
+
+ return <span className="text-muted-foreground uppercase">{value || '—'}</span>;
+ },
+ header: ({ column }) => {
+ const sorted = column.getIsSorted();
+
+ return (
+ <Button
+ className="text-muted-foreground hover:text-primary flex items-center gap-2 p-0 no-underline hover:no-underline"
+ onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
+ variant="link"
+ >
+ Format
+ {sorted === 'asc' ? (
+ <ArrowDown className="size-4" />
+ ) : sorted === 'desc' ? (
+ <ArrowUp className="size-4" />
+ ) : null}
+ </Button>
+ );
+ },
+ size: 120,
+ },
+ {
+ accessorKey: 'uploadedAt',
+ cell: ({ row }) => {
+ const value = row.getValue('uploadedAt') as string;
+ const date = new Date(value);
+ const relative = formatDistanceToNow(date, { addSuffix: true });
+ const absolute = format(date, 'd MMM yyyy, HH:mm');
+
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="text-muted-foreground cursor-default text-sm">{relative}</span>
+ </TooltipTrigger>
+ <TooltipContent>
+ <span className="text-xs">{absolute}</span>
+ </TooltipContent>
+ </Tooltip>
+ );
+ },
+ header: ({ column }) => {
+ const sorted = column.getIsSorted();
+
+ return (
+ <Button
+ className="text-muted-foreground hover:text-primary flex items-center gap-2 p-0 no-underline hover:no-underline"
+ onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
+ variant="link"
+ >
+ Date
+ {sorted === 'asc' ? (
+ <ArrowDown className="size-4" />
+ ) : sorted === 'desc' ? (
+ <ArrowUp className="size-4" />
+ ) : null}
+ </Button>
+ );
+ },
+ size: 160,
+ sortingFn: (rowA, rowB) =>
+ new Date(rowA.original.uploadedAt).getTime() - new Date(rowB.original.uploadedAt).getTime(),
+ },
+ {
+ cell: ({ row }) => {
+ const resource = row.original;
+ const isDeleting = deletingIds.has(resource.id);
+ const disabled = isDeleting || !resource.isUploaded;
+
+ return (
+ <div className="flex items-center justify-end gap-1 opacity-0 transition-opacity group-hover:opacity-100">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ className="size-8 p-0"
+ variant="ghost"
+ >
+ <MoreHorizontal />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ align="end"
+ className="min-w-24"
+ >
+ <DropdownMenuItem
+ disabled={disabled}
+ onClick={() => handleDeleteDialogOpen(resource)}
+ >
+ {isDeleting ? (
+ <>
+ <Loader2 className="size-4 animate-spin" />
+ Deleting...
+ </>
+ ) : (
+ <>
+ <Trash className="size-4" />
+ Delete
+ </>
+ )}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ );
+ },
+ enableHiding: false,
+ header: () => null,
+ id: 'actions',
+ meta: { preventRowClick: true },
+ size: 48,
+ },
+ ],
+ [deletingIds],
+ );
+
+ const renderRowContextMenu = (resource: ResourceItem) => {
+ const isDeleting = deletingIds.has(resource.id);
+ const disabled = isDeleting || !resource.isUploaded;
+
+ return (
+ <ContextMenuItem
+ disabled={disabled}
+ onClick={() => handleDeleteDialogOpen(resource)}
+ >
+ <Trash />
+ {isDeleting ? 'Deleting...' : 'Delete'}
+ </ContextMenuItem>
+ );
+ };
+
+ const pageHeader = (
+ <header className="bg-background sticky top-0 z-10 flex h-12 w-full shrink-0 items-center gap-2 border-b transition-[width,height] ease-linear group-has-data-[collapsible=icon]/sidebar-wrapper:h-12">
+ <div className="flex items-center gap-2 px-4">
+ <SidebarTrigger className="-ml-1" />
+ <Separator
+ className="h-4"
+ orientation="vertical"
+ />
+ <Breadcrumb>
+ <BreadcrumbList>
+ <BreadcrumbItem>
+ <Folder className="size-4" />
+ <BreadcrumbPage>Resources</BreadcrumbPage>
+ </BreadcrumbItem>
+ </BreadcrumbList>
+ </Breadcrumb>
+ </div>
+ <div className="ml-auto flex items-center gap-2 px-4">
+ <Button
+ onClick={handleUploadFile}
+ size="sm"
+ variant="secondary"
+ >
+ <Plus />
+ Add file
+ </Button>
+ </div>
+ </header>
+ );
+
+ const fileInput = (
+ <input
+ accept={ACCEPTED_FILE_TYPES}
+ className="hidden"
+ multiple
+ onChange={handleFileInputChange}
+ ref={fileInputRef}
+ type="file"
+ />
+ );
+
+ if (!resources.length) {
+ return (
+ <>
+ {pageHeader}
+ {fileInput}
+ <div className="flex flex-col gap-4 p-4">
+ <StatusCard
+ action={
+ <Button
+ onClick={handleUploadFile}
+ variant="secondary"
+ >
+ <Plus className="size-4" />
+ Upload file
+ </Button>
+ }
+ description="Upload documents so PentAGI agents can reference them during your flows"
+ icon={<Folder className="text-muted-foreground size-8" />}
+ title="No resources yet"
+ />
+ </div>
+ <ResourcesUploadOptionsDialog
+ isOpen={isUploadOptionsDialogOpen}
+ onCancel={handleUploadOptionsCancel}
+ onConfirm={handleUploadOptionsConfirm}
+ />
+ </>
+ );
+ }
+
+ return (
+ <>
+ {pageHeader}
+ {fileInput}
+ <div className="flex flex-col gap-4 p-4 pt-0">
+ <DataTable
+ columns={columns}
+ data={resources}
+ filterColumn="name"
+ filterPlaceholder="Filter resources..."
+ renderRowContextMenu={renderRowContextMenu}
+ />
+
+ <ConfirmationDialog
+ cancelText="Cancel"
+ confirmText="Delete"
+ handleConfirm={handleDelete}
+ handleOpenChange={setIsDeleteDialogOpen}
+ isOpen={isDeleteDialogOpen}
+ itemName={deletingResource?.name}
+ itemType="resource"
+ />
+
+ <ResourcesUploadOptionsDialog
+ isOpen={isUploadOptionsDialogOpen}
+ onCancel={handleUploadOptionsCancel}
+ onConfirm={handleUploadOptionsConfirm}
+ />
+ </div>
+ </>
+ );
+};
+
+export default Resources;
diff --git a/frontend/src/providers/resources-provider.tsx b/frontend/src/providers/resources-provider.tsx
new file mode 100644
index 00000000..3c3709db
--- /dev/null
+++ b/frontend/src/providers/resources-provider.tsx
@@ -0,0 +1,208 @@
+import { createContext, type ReactNode, useCallback, useContext, useEffect, useMemo, useState } from 'react';
+import { toast } from 'sonner';
+
+import type { ResourceItem, ResourcePreviewModel } from '@/features/resources/types';
+
+import {
+ deleteResource as deleteResourceApi,
+ getResources,
+ getUploadUrl,
+ uploadResource as uploadResourceApi,
+} from '@/features/resources/api';
+import { UPLOAD_COMPLETE_ANIMATION_DELAY } from '@/features/resources/constants';
+import { Log } from '@/lib/log';
+import { useUser } from '@/providers/user-provider';
+
+interface ResourcesContextValue {
+ deleteResource: (id: string) => Promise<void>;
+ getResource: (id: string) => ResourceItem | undefined;
+ isLoading: boolean;
+ resources: ResourceItem[];
+ uploadResource: (file: File, options?: UploadResourceOptions) => Promise<ResourceItem>;
+}
+
+interface ResourcesProviderProps {
+ children: ReactNode;
+}
+
+interface UploadResourceOptions {
+ fileName?: string;
+ knowledgeId?: string;
+ onStart?: (resource: ResourceItem) => void;
+}
+
+const ResourcesContext = createContext<ResourcesContextValue | undefined>(undefined);
+
+const toResourceItem = (item: ResourcePreviewModel): ResourceItem => ({
+ ...item,
+ isUploaded: true,
+ progress: 100,
+});
+
+export const ResourcesProvider = ({ children }: ResourcesProviderProps) => {
+ const { authInfo, isAuthenticated } = useUser();
+
+ const shouldFetchResources = Boolean(authInfo && authInfo.type !== 'guest' && isAuthenticated());
+
+ const [resources, setResources] = useState<ResourceItem[]>([]);
+ const [isLoading, setIsLoading] = useState(false);
+ const [hasLoaded, setHasLoaded] = useState(false);
+
+ useEffect(() => {
+ if (!shouldFetchResources || hasLoaded) {
+ return;
+ }
+
+ let isCancelled = false;
+ setIsLoading(true);
+
+ getResources()
+ .then((items) => {
+ if (isCancelled) {
+ return;
+ }
+
+ setResources(items.map(toResourceItem));
+ setHasLoaded(true);
+ })
+ .catch((error: unknown) => {
+ if (isCancelled) {
+ return;
+ }
+
+ const description = error instanceof Error ? error.message : 'Failed to load resources';
+ toast.error('Failed to load resources', {
+ description,
+ });
+ Log.error('Error loading resources:', error);
+ })
+ .finally(() => {
+ if (!isCancelled) {
+ setIsLoading(false);
+ }
+ });
+
+ return () => {
+ isCancelled = true;
+ };
+ }, [shouldFetchResources, hasLoaded]);
+
+ const getResource = useCallback(
+ (id: string): ResourceItem | undefined => resources.find((item) => item.id === id),
+ [resources],
+ );
+
+ const upsertResource = useCallback((next: ResourceItem) => {
+ setResources((current) => {
+ const exists = current.some((item) => item.id === next.id);
+
+ if (exists) {
+ return current.map((item) => (item.id === next.id ? next : item));
+ }
+
+ return [next, ...current];
+ });
+ }, []);
+
+ const updateResource = useCallback((id: string, patch: Partial<ResourceItem>) => {
+ setResources((current) => current.map((item) => (item.id === id ? { ...item, ...patch } : item)));
+ }, []);
+
+ const removeResourceFromState = useCallback((id: string) => {
+ setResources((current) => current.filter((item) => item.id !== id));
+ }, []);
+
+ const uploadResource = useCallback(
+ async (file: File, options?: UploadResourceOptions): Promise<ResourceItem> => {
+ try {
+ const fileName = options?.fileName ?? file.name;
+ const { id, item, uploadUrl } = await getUploadUrl({
+ fileName,
+ knowledgeId: options?.knowledgeId,
+ });
+
+ const optimisticItem: ResourceItem = {
+ ...item,
+ isUploaded: false,
+ progress: 0,
+ };
+ upsertResource(optimisticItem);
+ options?.onStart?.(optimisticItem);
+
+ try {
+ await uploadResourceApi({
+ file,
+ onProgress: (progress) => {
+ updateResource(id, { progress });
+ },
+ uploadUrl,
+ });
+ } catch (uploadError) {
+ removeResourceFromState(id);
+ throw uploadError;
+ }
+
+ const finalItem: ResourceItem = {
+ ...item,
+ isUploaded: false,
+ progress: 100,
+ };
+ updateResource(id, finalItem);
+
+ setTimeout(() => {
+ updateResource(id, { isUploaded: true, progress: 100 });
+ }, UPLOAD_COMPLETE_ANIMATION_DELAY);
+
+ return { ...finalItem, isUploaded: true };
+ } catch (error) {
+ const description = error instanceof Error ? error.message : 'Failed to upload file';
+ toast.error('Failed to upload file', {
+ description,
+ });
+ Log.error('Error uploading resource:', error);
+ throw error;
+ }
+ },
+ [removeResourceFromState, updateResource, upsertResource],
+ );
+
+ const deleteResource = useCallback(
+ async (id: string) => {
+ try {
+ await deleteResourceApi(id);
+ removeResourceFromState(id);
+ } catch (error) {
+ const description = error instanceof Error ? error.message : 'Failed to delete resource';
+ toast.error('Failed to delete resource', {
+ description,
+ });
+ Log.error('Error deleting resource:', error);
+ throw error;
+ }
+ },
+ [removeResourceFromState],
+ );
+
+ const value = useMemo<ResourcesContextValue>(
+ () => ({
+ deleteResource,
+ getResource,
+ isLoading,
+ resources,
+ uploadResource,
+ }),
+ [deleteResource, getResource, isLoading, resources, uploadResource],
+ );
+
+ return <ResourcesContext.Provider value={value}>{children}</ResourcesContext.Provider>;
+};
+
+export const useResources = () => {
+ const context = useContext(ResourcesContext);
+
+ if (context === undefined) {
+ throw new Error('useResources must be used within ResourcesProvider');
+ }
+
+ return context;
+};