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(cos): add file attachment support for tasks
Adam Eivyd398a7cbcbc4
diff --git a/.changelog/v0.10.x.md b/.changelog/v0.10.x.mdindex 12dd9a9c06..a125ec33d1 100644--- a/.changelog/v0.10.x.md+++ b/.changelog/v0.10.x.md@@ -161,6 +161,15 @@ This release introduces a structured changelog documentation system for creating- **Visual Feedback**: Loading spinner and "Enhancing..." state during prompt processing, with clear success/error toasts- **API Endpoint**: New `POST /api/cos/tasks/enhance` endpoint for programmatic access to prompt enhancement+### Chief of Staff - Task File Attachments+- **File Upload Support**: Tasks now support attaching files for additional context or action requirements+- **Multiple File Types**: Supports documents (txt, md, json, csv, xml, yaml, pdf), images (png, jpg, gif, webp, svg), code files (js, ts, jsx, tsx, py, sh, sql, html, css), and archives (zip, tar, gz)+- **50MB File Limit**: Each attachment can be up to 50MB to accommodate larger documents+- **Visual Attachment Display**: Attached files show in task items with file name, size, and download/view links+- **Attachment Persistence**: Files stored in `data/cos/attachments/` with unique IDs to prevent naming conflicts+- **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+### 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/components/cos/tabs/TaskItem.jsx b/client/src/components/cos/tabs/TaskItem.jsxindex 15bbc31b59..40e8b8040b 100644--- a/client/src/components/cos/tabs/TaskItem.jsx+++ b/client/src/components/cos/tabs/TaskItem.jsx@@ -9,7 +9,10 @@ import {Save,X,GripVertical,- Timer+ Timer,+ Paperclip,+ FileText,+ ExternalLink} from 'lucide-react';import toast from 'react-hot-toast';import * as api from '../../../services/api';@@ -68,6 +71,14 @@ function formatDurationMin(mins) {return `~${mins}m`;}+// Format file size for display+function formatAttachmentSize(bytes) {+ if (!bytes) return '';+ if (bytes < 1024) return `${bytes} B`;+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;+}+export default function TaskItem({ task, isSystem, awaitingApproval, onRefresh, providers, durations, dragHandleProps }) {const [editing, setEditing] = useState(false);const [editData, setEditData] = useState({@@ -260,6 +271,26 @@ export default function TaskItem({ task, isSystem, awaitingApproval, onRefresh,)}</div>)}+ {/* Attachments display */}+ {task.metadata?.attachments?.length > 0 && (+ <div className="flex items-center gap-2 mt-2 flex-wrap">+ <Paperclip size={12} className="text-gray-500" aria-hidden="true" />+ {task.metadata.attachments.map((att, idx) => (+ <a+ key={idx}+ href={`/api/attachments/${encodeURIComponent(att.filename)}`}+ target="_blank"+ rel="noopener noreferrer"+ className="flex items-center gap-1 px-2 py-0.5 text-xs bg-port-accent/10 text-port-accent hover:bg-port-accent/20 rounded transition-colors"+ title={`${att.originalName || att.filename} (${formatAttachmentSize(att.size)})`}+ >+ <FileText size={10} aria-hidden="true" />+ <span className="truncate max-w-[100px]">{att.originalName || att.filename}</span>+ <ExternalLink size={10} aria-hidden="true" />+ </a>+ ))}+ </div>+ )}</>)}</div>diff --git a/client/src/components/cos/tabs/TasksTab.jsx b/client/src/components/cos/tabs/TasksTab.jsxindex eadb7200b1..cb785f9d2c 100644--- a/client/src/components/cos/tabs/TasksTab.jsx+++ b/client/src/components/cos/tabs/TasksTab.jsx@@ -1,5 +1,5 @@import { useState, useEffect, useRef, useMemo } from 'react';-import { Plus, Play, Image, X, ChevronDown, ChevronRight, Sparkles, Loader2 } from 'lucide-react';+import { Plus, Play, Image, X, ChevronDown, ChevronRight, Sparkles, Loader2, Paperclip, FileText } from 'lucide-react';import toast from 'react-hot-toast';import {DndContext,@@ -16,7 +16,7 @@ import {verticalListSortingStrategy,} from '@dnd-kit/sortable';import * as api from '../../../services/api';-import { processScreenshotUploads } from '../../../utils/fileUpload';+import { processScreenshotUploads, processAttachmentUploads, formatFileSize } from '../../../utils/fileUpload';import TaskItem from './TaskItem';import SortableTaskItem from './SortableTaskItem';@@ -26,12 +26,14 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {const [addToTop, setAddToTop] = useState(false);const [userTasksLocal, setUserTasksLocal] = useState([]);const [screenshots, setScreenshots] = useState([]);+ const [attachments, setAttachments] = useState([]);const [durations, setDurations] = useState(null);const [showCompletedUserTasks, setShowCompletedUserTasks] = useState(false);const [showCompletedSystemTasks, setShowCompletedSystemTasks] = useState(false);const [enhancePrompt, setEnhancePrompt] = useState(false);const [isEnhancing, setIsEnhancing] = useState(false);const fileInputRef = useRef(null);+ const attachmentInputRef = useRef(null);// Fetch task duration estimates from learning datauseEffect(() => {@@ -145,6 +147,19 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {setScreenshots(prev => prev.filter(s => s.id !== id));};+ // Attachment handling using shared utility+ const handleAttachmentSelect = async (e) => {+ await processAttachmentUploads(e.target.files, {+ onSuccess: (fileInfo) => setAttachments(prev => [...prev, fileInfo]),+ onError: (msg) => toast.error(msg)+ });+ e.target.value = '';+ };++ const removeAttachment = (id) => {+ setAttachments(prev => prev.filter(a => a.id !== id));+ };+// Get models for selected providerconst selectedProvider = providers?.find(p => p.id === newTask.provider);const availableModels = selectedProvider?.models || [];@@ -189,6 +204,13 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {provider: newTask.provider || undefined,app: newTask.app || undefined,screenshots: screenshots.length > 0 ? screenshots.map(s => s.path) : undefined,+ attachments: attachments.length > 0 ? attachments.map(a => ({+ filename: a.filename,+ originalName: a.originalName,+ path: a.path,+ size: a.size,+ mimeType: a.mimeType+ })) : undefined,position: addToTop ? 'top' : 'bottom'}).catch(err => {toast.error(err.message);@@ -198,6 +220,7 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {toast.success('Task added');setNewTask({ description: '', context: '', model: '', provider: '', app: '' });setScreenshots([]);+ setAttachments([]);setAddToTop(false);setEnhancePrompt(false);setShowAddTask(false);@@ -338,8 +361,8 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {</select></div></div>- {/* Screenshot Upload */}- <div className="flex items-center gap-3">+ {/* Screenshot and Attachment Upload */}+ <div className="flex items-center gap-3 flex-wrap"><buttontype="button"onClick={() => fileInputRef.current?.click()}@@ -357,8 +380,28 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {className="hidden"aria-label="Upload screenshot files"/>+ <button+ type="button"+ onClick={() => attachmentInputRef.current?.click()}+ className="flex items-center gap-2 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-gray-400 hover:text-white text-sm transition-colors"+ >+ <Paperclip size={16} aria-hidden="true" />+ Attach File+ </button>+ <input+ ref={attachmentInputRef}+ type="file"+ accept=".txt,.md,.json,.csv,.xml,.yaml,.yml,.png,.jpg,.jpeg,.gif,.webp,.svg,.pdf,.js,.ts,.jsx,.tsx,.py,.sh,.sql,.html,.css,.zip,.tar,.gz"+ multiple+ onChange={handleAttachmentSelect}+ className="hidden"+ aria-label="Upload attachment files"+ />{screenshots.length > 0 && (- <span className="text-xs text-gray-500">{screenshots.length} screenshot{screenshots.length > 1 ? 's' : ''} attached</span>+ <span className="text-xs text-gray-500">{screenshots.length} screenshot{screenshots.length > 1 ? 's' : ''}</span>+ )}+ {attachments.length > 0 && (+ <span className="text-xs text-gray-500">{attachments.length} file{attachments.length > 1 ? 's' : ''}</span>)}</div>{/* Screenshot Previews */}@@ -383,11 +426,44 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {))}</div>)}+ {/* Attachment Previews */}+ {attachments.length > 0 && (+ <div className="flex gap-2 flex-wrap">+ {attachments.map(a => (+ <div key={a.id} className="relative group flex items-center gap-2 px-3 py-2 bg-port-bg border border-port-border rounded-lg">+ {a.isImage && a.preview ? (+ <img+ src={a.preview}+ alt={a.originalName}+ className="w-8 h-8 object-cover rounded"+ />+ ) : (+ <FileText size={20} className="text-gray-400" aria-hidden="true" />+ )}+ <div className="flex flex-col">+ <span className="text-xs text-white truncate max-w-[120px]" title={a.originalName}>+ {a.originalName}+ </span>+ <span className="text-xs text-gray-500">{formatFileSize(a.size)}</span>+ </div>+ <button+ type="button"+ onClick={() => removeAttachment(a.id)}+ className="ml-1 p-0.5 text-gray-500 hover:text-port-error transition-colors"+ aria-label={`Remove attachment ${a.originalName}`}+ >+ <X size={14} aria-hidden="true" />+ </button>+ </div>+ ))}+ </div>+ )}<div className="flex justify-end gap-2"><buttononClick={() => {setShowAddTask(false);setScreenshots([]);+ setAttachments([]);setEnhancePrompt(false);}}className="px-3 py-1.5 text-sm text-gray-400 hover:text-white transition-colors"diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 8270533a2f..5f6e6877c3 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -215,6 +215,15 @@ export const uploadScreenshot = (base64Data, filename, mimeType) => request('/scbody: JSON.stringify({ data: base64Data, filename, mimeType })});+// Attachments (generic file uploads for tasks)+export const uploadAttachment = (base64Data, filename) => request('/attachments', {+ method: 'POST',+ body: JSON.stringify({ data: base64Data, filename })+});+export const getAttachment = (filename) => request(`/attachments/${encodeURIComponent(filename)}`);+export const deleteAttachment = (filename) => request(`/attachments/${encodeURIComponent(filename)}`, { method: 'DELETE' });+export const listAttachments = () => request('/attachments');+// Running Agents (Process Management)export const getRunningAgents = () => request('/agents');export const getRunningAgentInfo = (pid) => request(`/agents/${pid}`);diff --git a/client/src/utils/fileUpload.js b/client/src/utils/fileUpload.jsindex 212de70387..6b06418878 100644--- a/client/src/utils/fileUpload.js+++ b/client/src/utils/fileUpload.js@@ -1,10 +1,19 @@/*** Shared file upload utilities- * Used by DevTools Runner and CoS TasksTab for screenshot uploads+ * Used by DevTools Runner and CoS TasksTab for screenshot and attachment uploads*/import * as api from '../services/api';+// Allowed attachment extensions (should match server)+const ALLOWED_ATTACHMENT_EXTENSIONS = [+ '.txt', '.md', '.json', '.csv', '.xml', '.yaml', '.yml',+ '.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg',+ '.pdf',+ '.js', '.ts', '.jsx', '.tsx', '.py', '.sh', '.sql', '.html', '.css',+ '.zip', '.tar', '.gz'+];+// Default max file size: 10MBconst DEFAULT_MAX_FILE_SIZE = 10 * 1024 * 1024;@@ -100,3 +109,143 @@ export async function uploadScreenshotFile(file, options = {}) {reader.readAsDataURL(file);});}++// Max file size for attachments: 50MB+const ATTACHMENT_MAX_FILE_SIZE = 50 * 1024 * 1024;++/**+ * Check if a file extension is allowed for attachments+ */+function isAllowedAttachmentExtension(filename) {+ const ext = filename.lastIndexOf('.') > -1+ ? filename.slice(filename.lastIndexOf('.')).toLowerCase()+ : '';+ return ALLOWED_ATTACHMENT_EXTENSIONS.includes(ext);+}++/**+ * Get file extension from filename+ */+function getFileExtension(filename) {+ const lastDot = filename.lastIndexOf('.');+ return lastDot > -1 ? filename.slice(lastDot).toLowerCase() : '';+}++/**+ * Check if a file is an image based on extension+ */+function isImageFile(filename) {+ const ext = getFileExtension(filename);+ return ['.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg'].includes(ext);+}++/**+ * Process and upload generic file attachments+ *+ * @param {FileList|File[]} files - Files to process+ * @param {Object} options - Upload options+ * @param {number} options.maxFileSize - Max file size in bytes (default: 50MB)+ * @param {Function} options.onSuccess - Callback for successful upload (receives uploaded file info)+ * @param {Function} options.onError - Callback for errors (receives error message)+ * @returns {Promise<void>}+ */+export async function processAttachmentUploads(files, options = {}) {+ const {+ maxFileSize = ATTACHMENT_MAX_FILE_SIZE,+ onSuccess,+ onError+ } = options;++ const fileArray = Array.from(files);++ for (const file of fileArray) {+ // Check file extension is allowed+ if (!isAllowedAttachmentExtension(file.name)) {+ const allowedList = ALLOWED_ATTACHMENT_EXTENSIONS.join(', ');+ onError?.(`File "${file.name}" has unsupported type. Allowed: ${allowedList}`);+ continue;+ }++ // Check file size+ if (file.size > maxFileSize) {+ const sizeMB = Math.round(maxFileSize / (1024 * 1024));+ onError?.(`File "${file.name}" exceeds ${sizeMB}MB limit`);+ continue;+ }++ await uploadAttachmentFile(file, { onSuccess, onError });+ }+}++/**+ * Upload a single attachment file+ *+ * @param {File} file - File to upload+ * @param {Object} options - Upload options+ * @param {Function} options.onSuccess - Callback for successful upload+ * @param {Function} options.onError - Callback for errors+ * @returns {Promise<Object|null>} Uploaded file info or null on failure+ */+export async function uploadAttachmentFile(file, options = {}) {+ const { onSuccess, onError } = options;++ return new Promise((resolve) => {+ const reader = new FileReader();++ reader.onload = async (ev) => {+ const result = ev?.target?.result;+ if (typeof result !== 'string') {+ onError?.('Failed to read file: unexpected result type');+ resolve(null);+ return;+ }++ const parts = result.split(',');+ if (parts.length < 2) {+ onError?.('Failed to read file: invalid data URL format');+ resolve(null);+ return;+ }++ const base64 = parts[1];+ const uploaded = await api.uploadAttachment(base64, file.name).catch((err) => {+ onError?.(`Failed to upload: ${err.message}`);+ return null;+ });++ if (uploaded) {+ const fileInfo = {+ id: uploaded.id,+ filename: uploaded.filename,+ originalName: uploaded.originalName || file.name,+ path: uploaded.path,+ size: uploaded.size,+ mimeType: uploaded.mimeType,+ // For images, create preview from the data URL+ preview: isImageFile(file.name) ? result : null,+ isImage: isImageFile(file.name)+ };+ onSuccess?.(fileInfo);+ resolve(fileInfo);+ } else {+ resolve(null);+ }+ };++ reader.onerror = () => {+ onError?.('Failed to read file');+ resolve(null);+ };++ reader.readAsDataURL(file);+ });+}++/**+ * Format file size for display+ */+export function formatFileSize(bytes) {+ if (bytes < 1024) return `${bytes} B`;+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;+}diff --git a/server/index.js b/server/index.jsindex 694782c7ff..22c6dade5a 100644--- a/server/index.js+++ b/server/index.js@@ -17,6 +17,7 @@ import commandsRoutes from './routes/commands.js';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 agentsRoutes from './routes/agents.js';import agentPersonalitiesRoutes from './routes/agentPersonalities.js';import platformAccountsRoutes from './routes/platformAccounts.js';@@ -166,6 +167,7 @@ app.use('/api/commands', commandsRoutes);app.use('/api/git', gitRoutes);app.use('/api/usage', usageRoutes);app.use('/api/screenshots', screenshotsRoutes);+app.use('/api/attachments', attachmentsRoutes);// 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/lib/taskParser.js b/server/lib/taskParser.jsindex 3c3441adf2..8bbd5377fa 100644--- a/server/lib/taskParser.js+++ b/server/lib/taskParser.js@@ -120,8 +120,13 @@ function unescapeNewlines(value) {** For values containing special characters (newlines, backslashes), uses JSON* string escaping with a sentinel prefix for reversibility. Simple values are stored as-is.+ * Arrays and objects are always JSON-encoded with the sentinel prefix.*/function escapeNewlines(value) {+ // Handle arrays and objects - always JSON encode+ if (Array.isArray(value) || (typeof value === 'object' && value !== null)) {+ return JSON_SENTINEL + JSON.stringify(value);+ }if (typeof value !== 'string') return String(value);// Only use JSON encoding if the value contains characters that need escapingif (value.includes('\n') || value.includes('\\')) {diff --git a/server/routes/attachments.js b/server/routes/attachments.jsnew file mode 100644index 0000000000..1db3a0403b--- /dev/null+++ b/server/routes/attachments.js@@ -0,0 +1,217 @@+/**+ * File Attachments API Routes+ * Handles generic file uploads for task attachments (not just images)+ */++import { Router } from 'express';+import { writeFile, mkdir, readFile, unlink } 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 ATTACHMENTS_DIR = resolve(__dirname, '../../data/cos/attachments');++const router = Router();++// Max file size: 50MB (larger than screenshots to accommodate documents)+const MAX_FILE_SIZE = 50 * 1024 * 1024;++// Allowed file extensions and their MIME types+const ALLOWED_EXTENSIONS = {+ // Documents+ '.txt': 'text/plain',+ '.md': 'text/markdown',+ '.json': 'application/json',+ '.csv': 'text/csv',+ '.xml': 'application/xml',+ '.yaml': 'application/x-yaml',+ '.yml': 'application/x-yaml',+ // Images+ '.png': 'image/png',+ '.jpg': 'image/jpeg',+ '.jpeg': 'image/jpeg',+ '.gif': 'image/gif',+ '.webp': 'image/webp',+ '.svg': 'image/svg+xml',+ // Documents+ '.pdf': 'application/pdf',+ // 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',+ // Archives (useful for providing multiple files)+ '.zip': 'application/zip',+ '.tar': 'application/x-tar',+ '.gz': 'application/gzip'+};++/**+ * Validate and sanitize filename to prevent path traversal+ * @param {string} filename - User-provided filename+ * @returns {string} - Safe filename+ */+function sanitizeFilename(filename) {+ const base = basename(filename);+ // Replace problematic characters but keep extension dots+ const sanitized = base.replace(/[^a-zA-Z0-9._-]/g, '_');+ // Ensure it doesn't start with a dot (hidden files)+ if (sanitized.startsWith('.')) {+ return '_' + sanitized.slice(1);+ }+ return sanitized;+}++/**+ * Get file extension, normalized to lowercase with leading dot+ */+function getExtension(filename) {+ const ext = extname(filename).toLowerCase();+ return ext || null;+}++/**+ * Validate file extension is allowed+ */+function isAllowedExtension(filename) {+ const ext = getExtension(filename);+ return ext && ALLOWED_EXTENSIONS[ext];+}++// POST /api/attachments - Upload a file attachment (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' });+ }++ // Validate extension+ if (!isAllowedExtension(filename)) {+ const allowedList = Object.keys(ALLOWED_EXTENSIONS).join(', ');+ throw new ServerError(`File type not allowed. Supported: ${allowedList}`, { status: 400, code: 'INVALID_FILE_TYPE' });+ }++ // 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 attachments directory exists+ if (!existsSync(ATTACHMENTS_DIR)) {+ await mkdir(ATTACHMENTS_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(ATTACHMENTS_DIR, fname);++ // Double-check path is within attachments directory (defense in depth)+ const resolvedPath = resolve(filepath);+ if (!resolvedPath.startsWith(ATTACHMENTS_DIR)) {+ throw new ServerError('Invalid filename', { status: 400, code: 'INVALID_FILENAME' });+ }++ await writeFile(filepath, buffer);++ const mimeType = ALLOWED_EXTENSIONS[ext] || 'application/octet-stream';++ console.log(`📎 Attachment saved: ${fname} (${buffer.length} bytes, ${mimeType})`);++ res.json({+ id,+ filename: fname,+ originalName: filename,+ path: filepath,+ size: buffer.length,+ mimeType+ });+}));++// GET /api/attachments/:filename - Serve an attachment+router.get('/:filename', asyncHandler(async (req, res) => {+ const { filename } = req.params;+ // Sanitize filename to prevent path traversal+ const safeFilename = sanitizeFilename(filename);+ const filepath = resolve(ATTACHMENTS_DIR, safeFilename);++ // Verify the resolved path is within attachments directory+ if (!filepath.startsWith(ATTACHMENTS_DIR)) {+ throw new ServerError('Invalid filename', { status: 400, code: 'INVALID_FILENAME' });+ }++ if (!existsSync(filepath)) {+ throw new ServerError('Attachment not found', { status: 404, code: 'NOT_FOUND' });+ }++ const ext = getExtension(safeFilename);+ const mimeType = ALLOWED_EXTENSIONS[ext] || 'application/octet-stream';++ res.type(mimeType).sendFile(filepath);+}));++// DELETE /api/attachments/:filename - Delete an attachment+router.delete('/:filename', asyncHandler(async (req, res) => {+ const { filename } = req.params;+ const safeFilename = sanitizeFilename(filename);+ const filepath = resolve(ATTACHMENTS_DIR, safeFilename);++ // Verify the resolved path is within attachments directory+ if (!filepath.startsWith(ATTACHMENTS_DIR)) {+ throw new ServerError('Invalid filename', { status: 400, code: 'INVALID_FILENAME' });+ }++ if (!existsSync(filepath)) {+ throw new ServerError('Attachment not found', { status: 404, code: 'NOT_FOUND' });+ }++ await unlink(filepath);++ console.log(`🗑️ Attachment deleted: ${safeFilename}`);++ res.json({ success: true, filename: safeFilename });+}));++// GET /api/attachments - List all attachments (for debugging)+router.get('/', asyncHandler(async (req, res) => {+ const { readdirSync, statSync } = await import('fs');++ if (!existsSync(ATTACHMENTS_DIR)) {+ return res.json({ attachments: [] });+ }++ const files = readdirSync(ATTACHMENTS_DIR);+ const attachments = files.map(filename => {+ const filepath = join(ATTACHMENTS_DIR, filename);+ const stats = statSync(filepath);+ const ext = getExtension(filename);+ return {+ filename,+ path: filepath,+ size: stats.size,+ mimeType: ALLOWED_EXTENSIONS[ext] || 'application/octet-stream',+ createdAt: stats.birthtime+ };+ });++ res.json({ attachments });+}));++export default router;diff --git a/server/routes/cos.js b/server/routes/cos.jsindex 5a14c2b9ed..9b65d126a3 100644--- a/server/routes/cos.js+++ b/server/routes/cos.js@@ -109,13 +109,13 @@ router.post('/tasks/enhance', asyncHandler(async (req, res) => {// POST /api/cos/tasks - Add a new taskrouter.post('/tasks', asyncHandler(async (req, res) => {- const { description, priority, context, model, provider, app, type = 'user', approvalRequired, screenshots, position = 'bottom' } = req.body;+ const { description, priority, context, model, provider, app, type = 'user', approvalRequired, screenshots, attachments, position = 'bottom' } = req.body;if (!description) {throw new ServerError('Description is required', { status: 400, code: 'VALIDATION_ERROR' });}- const taskData = { description, priority, context, model, provider, app, approvalRequired, screenshots, position };+ const taskData = { description, priority, context, model, provider, app, approvalRequired, screenshots, attachments, position };const result = await cos.addTask(taskData, type);res.json(result);}));diff --git a/server/services/cos.js b/server/services/cos.jsindex dce07a7b01..2d1bfaec85 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -2362,6 +2362,7 @@ export async function addTask(taskData, taskType = 'user') {if (taskData.provider) metadata.provider = taskData.provider;if (taskData.app) metadata.app = taskData.app;if (taskData.screenshots?.length > 0) metadata.screenshots = taskData.screenshots;+ if (taskData.attachments?.length > 0) metadata.attachments = taskData.attachments;// Create the new taskconst newTask = {