Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(uploads): add generic file uploader page
Adam Eivy4168a3ddadd6
diff --git a/.changelog/v0.10.x.md b/.changelog/v0.10.x.mdindex a125ec33d1..3db11fbd51 100644--- a/.changelog/v0.10.x.md+++ b/.changelog/v0.10.x.md@@ -170,6 +170,16 @@ This release introduces a structured changelog documentation system for creating- **API Endpoints**: New `/api/attachments` CRUD endpoints for uploading, retrieving, and deleting attachments- **Task Metadata Integration**: Attachments stored in task metadata and serialized properly in TASKS.md+### File Uploads Page+- **Dedicated Upload Interface**: New `/uploads` page for general-purpose file storage at `data/uploads/`+- **Drag and Drop**: Drop zone with visual feedback for easy file uploads+- **100MB File Limit**: Larger limit than task attachments for general storage needs+- **File Preview**: Image thumbnails displayed inline, file icons for other types+- **Storage Stats**: Shows total file count and disk space used+- **Bulk Delete**: "Delete All" option to clear all uploaded files at once+- **Wide Format Support**: Accepts documents, images, audio, video, code files, archives, and config files+- **API Endpoints**: New `/api/uploads` CRUD endpoints with list, upload, download, delete, and delete-all operations+### Brain Links - Quick URL Capture with GitHub Clone- **Links Tab in Brain**: New "Links" tab in the Brain feature for quickly saving URLs for later reference- **Quick-Add Form**: Paste any URL and it's automatically saved - GitHub repos are detected and tagged automaticallydiff --git a/client/src/App.jsx b/client/src/App.jsxindex 80a3b753c8..b0043efc53 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -11,6 +11,7 @@ import Brain from './pages/Brain';import Media from './pages/Media';import DigitalTwin from './pages/DigitalTwin';import Agents from './pages/Agents';+import Uploads from './pages/Uploads';// Lazy load heavier pages for code splitting// DevTools pages are large (~2300 lines total) so lazy load them@@ -56,6 +57,7 @@ export default function App() {<Route path="apps/create" element={<CreateApp />} /><Route path="templates" element={<Templates />} /><Route path="media" element={<Media />} />+ <Route path="uploads" element={<Uploads />} /><Route path="agents" element={<Navigate to="/agents/personalities" replace />} /><Route path="agents/:tab" element={<Agents />} /><Route path="*" element={<Navigate to="/" replace />} />diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex ba1737f53a..0f8e53643b 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -30,7 +30,8 @@ import {Settings,Users,Link2,- LineChart+ LineChart,+ Upload} from 'lucide-react';import packageJson from '../../package.json';import Logo from './Logo';@@ -99,7 +100,8 @@ const navItems = [{ to: '/devtools/usage', label: 'Usage', icon: BarChart3 }]},- { to: '/media', label: 'Media', icon: Camera, single: true }+ { to: '/media', label: 'Media', icon: Camera, single: true },+ { to: '/uploads', label: 'Uploads', icon: Upload, single: true }];const SIDEBAR_KEY = 'portos-sidebar-collapsed';diff --git a/client/src/pages/Uploads.jsx b/client/src/pages/Uploads.jsxnew file mode 100644index 0000000000..f1bc6fd9e1--- /dev/null+++ b/client/src/pages/Uploads.jsx@@ -0,0 +1,280 @@+import { useState, useEffect, useCallback, useRef } from 'react';+import { Upload, Trash2, Download, FileText, Image, File, X, FolderOpen, RefreshCw } from 'lucide-react';+import toast from 'react-hot-toast';+import * as api from '../services/api';++// File type icons based on MIME type+function getFileIcon(mimeType) {+ if (mimeType?.startsWith('image/')) return <Image size={20} className="text-purple-400" />;+ if (mimeType?.startsWith('text/') || mimeType?.includes('json') || mimeType?.includes('xml')) {+ return <FileText size={20} className="text-blue-400" />;+ }+ return <File size={20} className="text-gray-400" />;+}++// Check if file is previewable as image+function isPreviewableImage(mimeType) {+ return mimeType?.startsWith('image/') && !mimeType?.includes('svg');+}++export default function Uploads() {+ const [uploads, setUploads] = useState([]);+ const [stats, setStats] = useState({ count: 0, totalSizeFormatted: '0 B' });+ const [loading, setLoading] = useState(true);+ const [uploading, setUploading] = useState(false);+ const [dragActive, setDragActive] = useState(false);+ const fileInputRef = useRef(null);++ const fetchUploads = useCallback(async () => {+ const data = await api.listUploads().catch(err => {+ toast.error(err.message);+ return { uploads: [], count: 0, totalSizeFormatted: '0 B' };+ });+ setUploads(data.uploads || []);+ setStats({ count: data.count || 0, totalSizeFormatted: data.totalSizeFormatted || '0 B' });+ setLoading(false);+ }, []);++ useEffect(() => {+ fetchUploads();+ }, [fetchUploads]);++ const handleFileUpload = async (files) => {+ if (!files || files.length === 0) return;++ setUploading(true);+ const fileArray = Array.from(files);++ for (const file of fileArray) {+ // Check file size (100MB limit)+ if (file.size > 100 * 1024 * 1024) {+ toast.error(`File "${file.name}" exceeds 100MB limit`);+ continue;+ }++ // Read file as base64+ const base64 = await new Promise((resolve) => {+ const reader = new FileReader();+ reader.onload = (e) => {+ const result = e.target?.result;+ if (typeof result === 'string') {+ resolve(result.split(',')[1]);+ } else {+ resolve(null);+ }+ };+ reader.onerror = () => resolve(null);+ reader.readAsDataURL(file);+ });++ if (!base64) {+ toast.error(`Failed to read file "${file.name}"`);+ continue;+ }++ const result = await api.uploadFile(base64, file.name).catch(err => {+ toast.error(`Failed to upload "${file.name}": ${err.message}`);+ return null;+ });++ if (result) {+ toast.success(`Uploaded "${file.name}"`);+ }+ }++ setUploading(false);+ fetchUploads();+ };++ const handleDelete = async (filename) => {+ const result = await api.deleteUpload(filename).catch(err => {+ toast.error(err.message);+ return null;+ });++ if (result?.success) {+ toast.success('File deleted');+ fetchUploads();+ }+ };++ const handleDeleteAll = async () => {+ if (uploads.length === 0) {+ toast.error('No files to delete');+ return;+ }++ const result = await api.deleteAllUploads().catch(err => {+ toast.error(err.message);+ return null;+ });++ if (result?.success) {+ toast.success(`Deleted ${result.deleted} files (${result.freedSpaceFormatted})`);+ fetchUploads();+ }+ };++ const handleDrag = (e) => {+ e.preventDefault();+ e.stopPropagation();+ if (e.type === 'dragenter' || e.type === 'dragover') {+ setDragActive(true);+ } else if (e.type === 'dragleave') {+ setDragActive(false);+ }+ };++ const handleDrop = (e) => {+ e.preventDefault();+ e.stopPropagation();+ setDragActive(false);+ if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {+ handleFileUpload(e.dataTransfer.files);+ }+ };++ if (loading) {+ return (+ <div className="flex items-center justify-center h-64">+ <div className="text-gray-500">Loading...</div>+ </div>+ );+ }++ return (+ <div>+ {/* Header */}+ <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 sm:gap-4 mb-6">+ <div>+ <h2 className="text-2xl font-bold text-white">File Uploads</h2>+ <p className="text-gray-500 text-sm sm:text-base">+ {stats.count} file{stats.count !== 1 ? 's' : ''} ({stats.totalSizeFormatted})+ </p>+ </div>+ <div className="flex items-center gap-2">+ <button+ onClick={fetchUploads}+ className="flex items-center gap-2 px-3 py-2 bg-port-card border border-port-border rounded-lg text-gray-400 hover:text-white hover:border-port-accent/50 transition-colors"+ title="Refresh"+ >+ <RefreshCw size={16} />+ </button>+ {uploads.length > 0 && (+ <button+ onClick={handleDeleteAll}+ className="flex items-center gap-2 px-3 py-2 bg-port-error/20 border border-port-error/50 rounded-lg text-port-error hover:bg-port-error/30 transition-colors"+ >+ <Trash2 size={16} />+ Delete All+ </button>+ )}+ </div>+ </div>++ {/* Upload Zone */}+ <div+ className={`relative mb-6 p-8 border-2 border-dashed rounded-lg text-center transition-colors ${+ dragActive+ ? 'border-port-accent bg-port-accent/10'+ : 'border-port-border hover:border-port-accent/50 bg-port-card'+ }`}+ onDragEnter={handleDrag}+ onDragLeave={handleDrag}+ onDragOver={handleDrag}+ onDrop={handleDrop}+ >+ <input+ ref={fileInputRef}+ type="file"+ multiple+ onChange={(e) => handleFileUpload(e.target.files)}+ className="hidden"+ />++ <Upload size={40} className={`mx-auto mb-4 ${dragActive ? 'text-port-accent' : 'text-gray-500'}`} />++ <p className="text-white mb-2">+ {dragActive ? 'Drop files here' : 'Drag and drop files here'}+ </p>+ <p className="text-gray-500 text-sm mb-4">or</p>+ <button+ onClick={() => fileInputRef.current?.click()}+ disabled={uploading}+ className="px-4 py-2 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded-lg transition-colors disabled:opacity-50"+ >+ {uploading ? 'Uploading...' : 'Browse Files'}+ </button>+ <p className="text-gray-500 text-xs mt-4">+ Maximum file size: 100MB+ </p>+ </div>++ {/* Files List */}+ {uploads.length === 0 ? (+ <div className="bg-port-card border border-port-border rounded-lg p-8 text-center">+ <FolderOpen size={48} className="mx-auto mb-4 text-gray-500" />+ <p className="text-gray-500">No files uploaded yet</p>+ <p className="text-gray-600 text-sm mt-1">Upload files using the drop zone above</p>+ </div>+ ) : (+ <div className="bg-port-card border border-port-border rounded-lg overflow-hidden">+ <div className="grid grid-cols-1 divide-y divide-port-border">+ {uploads.map((file) => (+ <div+ key={file.filename}+ className="flex items-center gap-4 p-4 hover:bg-port-bg/50 transition-colors group"+ >+ {/* Icon or Preview */}+ <div className="w-12 h-12 flex items-center justify-center bg-port-bg rounded-lg shrink-0">+ {isPreviewableImage(file.mimeType) ? (+ <img+ src={api.getUploadUrl(file.filename)}+ alt={file.filename}+ className="w-12 h-12 object-cover rounded-lg"+ />+ ) : (+ getFileIcon(file.mimeType)+ )}+ </div>++ {/* File Info */}+ <div className="flex-1 min-w-0">+ <p className="text-white font-medium truncate" title={file.filename}>+ {file.filename}+ </p>+ <p className="text-gray-500 text-sm">+ {file.sizeFormatted} · {file.mimeType}+ </p>+ <p className="text-gray-600 text-xs">+ Uploaded {new Date(file.createdAt).toLocaleString()}+ </p>+ </div>++ {/* Actions */}+ <div className="flex items-center gap-2 opacity-0 group-hover:opacity-100 transition-opacity">+ <a+ href={api.getUploadUrl(file.filename)}+ target="_blank"+ rel="noopener noreferrer"+ className="p-2 text-gray-500 hover:text-port-accent transition-colors"+ title="Download / View"+ >+ <Download size={18} />+ </a>+ <button+ onClick={() => handleDelete(file.filename)}+ className="p-2 text-gray-500 hover:text-port-error transition-colors"+ title="Delete"+ >+ <Trash2 size={18} />+ </button>+ </div>+ </div>+ ))}+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 5f6e6877c3..d31e0284e4 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -224,6 +224,16 @@ export const getAttachment = (filename) => request(`/attachments/${encodeURICompexport const deleteAttachment = (filename) => request(`/attachments/${encodeURIComponent(filename)}`, { method: 'DELETE' });export const listAttachments = () => request('/attachments');+// Uploads (general file storage)+export const uploadFile = (base64Data, filename) => request('/uploads', {+ method: 'POST',+ body: JSON.stringify({ data: base64Data, filename })+});+export const listUploads = () => request('/uploads');+export const getUploadUrl = (filename) => `/api/uploads/${encodeURIComponent(filename)}`;+export const deleteUpload = (filename) => request(`/uploads/${encodeURIComponent(filename)}`, { method: 'DELETE' });+export const deleteAllUploads = () => request('/uploads?confirm=true', { method: 'DELETE' });+// Running Agents (Process Management)export const getRunningAgents = () => request('/agents');export const getRunningAgentInfo = (pid) => request(`/agents/${pid}`);diff --git a/server/index.js b/server/index.jsindex 22c6dade5a..e615de33d6 100644--- a/server/index.js+++ b/server/index.js@@ -18,6 +18,7 @@ import gitRoutes from './routes/git.js';import usageRoutes from './routes/usage.js';import screenshotsRoutes from './routes/screenshots.js';import attachmentsRoutes from './routes/attachments.js';+import uploadsRoutes from './routes/uploads.js';import agentsRoutes from './routes/agents.js';import agentPersonalitiesRoutes from './routes/agentPersonalities.js';import platformAccountsRoutes from './routes/platformAccounts.js';@@ -168,6 +169,7 @@ app.use('/api/git', gitRoutes);app.use('/api/usage', usageRoutes);app.use('/api/screenshots', screenshotsRoutes);app.use('/api/attachments', attachmentsRoutes);+app.use('/api/uploads', uploadsRoutes);// Agent Personalities feature routes (must be before /api/agents to avoid route conflicts)app.use('/api/agents/personalities', agentPersonalitiesRoutes);app.use('/api/agents/accounts', platformAccountsRoutes);diff --git a/server/routes/uploads.js b/server/routes/uploads.jsnew file mode 100644index 0000000000..14a32cc5dd--- /dev/null+++ b/server/routes/uploads.js@@ -0,0 +1,281 @@+/**+ * Generic File Uploads API Routes+ * Handles file uploads to data/uploads directory+ */++import { Router } from 'express';+import { writeFile, mkdir, unlink, readdir, stat } from 'fs/promises';+import { existsSync } from 'fs';+import { join, dirname, resolve, basename, extname } from 'path';+import { fileURLToPath } from 'url';+import { v4 as uuidv4 } from 'uuid';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';++const __filename = fileURLToPath(import.meta.url);+const __dirname = dirname(__filename);+const UPLOADS_DIR = resolve(__dirname, '../../data/uploads');++const router = Router();++// Max file size: 100MB for general uploads+const MAX_FILE_SIZE = 100 * 1024 * 1024;++/**+ * Validate and sanitize filename to prevent path traversal+ */+function sanitizeFilename(filename) {+ const base = basename(filename);+ const sanitized = base.replace(/[^a-zA-Z0-9._-]/g, '_');+ if (sanitized.startsWith('.')) {+ return '_' + sanitized.slice(1);+ }+ return sanitized;+}++/**+ * Get file extension, normalized to lowercase with leading dot+ */+function getExtension(filename) {+ return extname(filename).toLowerCase() || null;+}++/**+ * Get MIME type from extension+ */+function getMimeType(ext) {+ const mimeTypes = {+ // Documents+ '.txt': 'text/plain',+ '.md': 'text/markdown',+ '.json': 'application/json',+ '.csv': 'text/csv',+ '.xml': 'application/xml',+ '.yaml': 'application/x-yaml',+ '.yml': 'application/x-yaml',+ '.pdf': 'application/pdf',+ // Images+ '.png': 'image/png',+ '.jpg': 'image/jpeg',+ '.jpeg': 'image/jpeg',+ '.gif': 'image/gif',+ '.webp': 'image/webp',+ '.svg': 'image/svg+xml',+ '.ico': 'image/x-icon',+ '.bmp': 'image/bmp',+ // Audio+ '.mp3': 'audio/mpeg',+ '.wav': 'audio/wav',+ '.ogg': 'audio/ogg',+ '.m4a': 'audio/mp4',+ // Video+ '.mp4': 'video/mp4',+ '.webm': 'video/webm',+ '.mov': 'video/quicktime',+ // Code+ '.js': 'text/javascript',+ '.ts': 'text/typescript',+ '.jsx': 'text/javascript',+ '.tsx': 'text/typescript',+ '.py': 'text/x-python',+ '.sh': 'text/x-shellscript',+ '.sql': 'text/x-sql',+ '.html': 'text/html',+ '.css': 'text/css',+ '.go': 'text/x-go',+ '.rs': 'text/x-rust',+ '.java': 'text/x-java',+ '.c': 'text/x-c',+ '.cpp': 'text/x-c++',+ '.h': 'text/x-c',+ // Archives+ '.zip': 'application/zip',+ '.tar': 'application/x-tar',+ '.gz': 'application/gzip',+ '.7z': 'application/x-7z-compressed',+ '.rar': 'application/vnd.rar',+ // Other+ '.log': 'text/plain',+ '.env': 'text/plain',+ '.conf': 'text/plain',+ '.cfg': 'text/plain',+ '.ini': 'text/plain'+ };+ return mimeTypes[ext] || 'application/octet-stream';+}++/**+ * Format file size for display+ */+function formatSize(bytes) {+ if (bytes < 1024) return `${bytes} B`;+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;+ if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;+ return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;+}++// POST /api/uploads - Upload a file (base64)+router.post('/', asyncHandler(async (req, res) => {+ const { data, filename } = req.body;++ if (!data) {+ throw new ServerError('data is required (base64)', { status: 400, code: 'VALIDATION_ERROR' });+ }++ if (!filename) {+ throw new ServerError('filename is required', { status: 400, code: 'VALIDATION_ERROR' });+ }++ // Decode base64 and validate size+ const buffer = Buffer.from(data, 'base64');+ if (buffer.length > MAX_FILE_SIZE) {+ throw new ServerError(`File exceeds maximum size of ${MAX_FILE_SIZE / 1024 / 1024}MB`, { status: 400, code: 'FILE_TOO_LARGE' });+ }++ // Ensure uploads directory exists+ if (!existsSync(UPLOADS_DIR)) {+ await mkdir(UPLOADS_DIR, { recursive: true });+ }++ const id = uuidv4();+ const safeName = sanitizeFilename(filename);+ const ext = getExtension(safeName);+ // Create unique filename with UUID prefix to avoid collisions+ const fname = `${id.slice(0, 8)}-${safeName}`;+ const filepath = join(UPLOADS_DIR, fname);++ // Double-check path is within uploads directory (defense in depth)+ const resolvedPath = resolve(filepath);+ if (!resolvedPath.startsWith(UPLOADS_DIR)) {+ throw new ServerError('Invalid filename', { status: 400, code: 'INVALID_FILENAME' });+ }++ await writeFile(filepath, buffer);++ const mimeType = getMimeType(ext);++ console.log(`📤 File uploaded: ${fname} (${formatSize(buffer.length)}, ${mimeType})`);++ res.json({+ id,+ filename: fname,+ originalName: filename,+ path: filepath,+ size: buffer.length,+ sizeFormatted: formatSize(buffer.length),+ mimeType,+ createdAt: new Date().toISOString()+ });+}));++// GET /api/uploads - List all uploads+router.get('/', asyncHandler(async (req, res) => {+ if (!existsSync(UPLOADS_DIR)) {+ return res.json({ uploads: [], totalSize: 0, totalSizeFormatted: '0 B' });+ }++ const files = await readdir(UPLOADS_DIR);+ let totalSize = 0;++ const uploads = await Promise.all(files.map(async (filename) => {+ const filepath = join(UPLOADS_DIR, filename);+ const stats = await stat(filepath);+ const ext = getExtension(filename);+ totalSize += stats.size;++ return {+ filename,+ path: filepath,+ size: stats.size,+ sizeFormatted: formatSize(stats.size),+ mimeType: getMimeType(ext),+ createdAt: stats.birthtime.toISOString(),+ modifiedAt: stats.mtime.toISOString()+ };+ }));++ // Sort by creation date, newest first+ uploads.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));++ res.json({+ uploads,+ count: uploads.length,+ totalSize,+ totalSizeFormatted: formatSize(totalSize)+ });+}));++// GET /api/uploads/:filename - Serve a file+router.get('/:filename', asyncHandler(async (req, res) => {+ const { filename } = req.params;+ const safeFilename = sanitizeFilename(filename);+ const filepath = resolve(UPLOADS_DIR, safeFilename);++ if (!filepath.startsWith(UPLOADS_DIR)) {+ throw new ServerError('Invalid filename', { status: 400, code: 'INVALID_FILENAME' });+ }++ if (!existsSync(filepath)) {+ throw new ServerError('File not found', { status: 404, code: 'NOT_FOUND' });+ }++ const ext = getExtension(safeFilename);+ const mimeType = getMimeType(ext);++ res.type(mimeType).sendFile(filepath);+}));++// DELETE /api/uploads/:filename - Delete a file+router.delete('/:filename', asyncHandler(async (req, res) => {+ const { filename } = req.params;+ const safeFilename = sanitizeFilename(filename);+ const filepath = resolve(UPLOADS_DIR, safeFilename);++ if (!filepath.startsWith(UPLOADS_DIR)) {+ throw new ServerError('Invalid filename', { status: 400, code: 'INVALID_FILENAME' });+ }++ if (!existsSync(filepath)) {+ throw new ServerError('File not found', { status: 404, code: 'NOT_FOUND' });+ }++ const stats = await stat(filepath);+ await unlink(filepath);++ console.log(`🗑️ File deleted: ${safeFilename} (${formatSize(stats.size)})`);++ res.json({ success: true, filename: safeFilename, size: stats.size });+}));++// DELETE /api/uploads - Delete all files+router.delete('/', asyncHandler(async (req, res) => {+ const { confirm } = req.query;++ if (confirm !== 'true') {+ throw new ServerError('Add ?confirm=true to delete all uploads', { status: 400, code: 'CONFIRMATION_REQUIRED' });+ }++ if (!existsSync(UPLOADS_DIR)) {+ return res.json({ success: true, deleted: 0, freedSpace: 0 });+ }++ const files = await readdir(UPLOADS_DIR);+ let freedSpace = 0;++ for (const filename of files) {+ const filepath = join(UPLOADS_DIR, filename);+ const stats = await stat(filepath);+ freedSpace += stats.size;+ await unlink(filepath);+ }++ console.log(`🗑️ Cleared all uploads: ${files.length} files (${formatSize(freedSpace)})`);++ res.json({+ success: true,+ deleted: files.length,+ freedSpace,+ freedSpaceFormatted: formatSize(freedSpace)+ });+}));++export default router;