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: add Quick Task Templates for one-click task creation
Adam Eivyc2e1ea390695
diff --git a/.changelog/v0.11.x.md b/.changelog/v0.11.x.mdindex 923553b28c..ef7237e062 100644--- a/.changelog/v0.11.x.md+++ b/.changelog/v0.11.x.md@@ -154,6 +154,21 @@ This release focuses on security improvements, bug fixes for the AI runner syste**Files Modified**:- `client/src/components/cos/tabs/AgentsTab.jsx` — Added search state, filtered list with `useMemo`, search input UI+### Quick Task Templates+- **One-click task creation**: Added a collapsible "Quick Templates" section above the task form with 8 built-in templates for common task patterns (fix mobile, add feature, fix bug, refactor, add tests, improve UX, add API, security fix)+- **Save as template**: New "Save Template" button lets you save the current form as a reusable template for future tasks+- **Usage tracking**: Templates show usage counts and are sorted by popularity so your most-used templates appear first+- **Custom templates**: Create and delete your own templates; built-in templates cannot be deleted+- **Template presets**: Each template populates description, context, and optionally provider/model/app settings++**Files Added**:+- `server/services/taskTemplates.js` — Template management with built-in templates, usage tracking, CRUD operations++**Files Modified**:+- `server/routes/cos.js` — Added `/api/cos/templates` REST endpoints+- `client/src/services/api.js` — Added template API functions+- `client/src/components/cos/tabs/TasksTab.jsx` — Template UI with apply/save/delete functionality+## 🔧 Improvements### Live Output Streaming for Claude CLI Agentsdiff --git a/client/src/components/cos/tabs/TasksTab.jsx b/client/src/components/cos/tabs/TasksTab.jsxindex c5e0bf7765..b8f96892e5 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, Paperclip, FileText } from 'lucide-react';+import { useState, useEffect, useRef, useMemo, useCallback } from 'react';+import { Plus, Play, Image, X, ChevronDown, ChevronRight, Sparkles, Loader2, Paperclip, FileText, Zap, Bookmark, Trash2 } from 'lucide-react';import toast from 'react-hot-toast';import {DndContext,@@ -32,14 +32,82 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {const [showCompletedSystemTasks, setShowCompletedSystemTasks] = useState(false);const [enhancePrompt, setEnhancePrompt] = useState(false);const [isEnhancing, setIsEnhancing] = useState(false);+ const [templates, setTemplates] = useState([]);+ const [showTemplates, setShowTemplates] = useState(true);const fileInputRef = useRef(null);const attachmentInputRef = useRef(null);- // Fetch task duration estimates from learning data+ // Fetch task duration estimates and templatesuseEffect(() => {api.getCosLearningDurations().then(setDurations).catch(() => setDurations(null));++ api.getCosPopularTemplates(8)+ .then(data => setTemplates(data.templates || []))+ .catch(() => setTemplates([]));+ }, []);++ // Apply template to form+ const applyTemplate = useCallback(async (template) => {+ setNewTask({+ description: template.description,+ context: template.context || '',+ model: template.model || '',+ provider: template.provider || '',+ app: template.app || ''+ });++ // Record usage for popularity tracking+ await api.useCosTaskTemplate(template.id).catch(() => {});++ toast.success(`Template applied: ${template.name}`);+ }, []);++ // Save current form as template+ const saveAsTemplate = useCallback(async () => {+ if (!newTask.description.trim()) {+ toast.error('Enter a task description first');+ return;+ }++ const name = prompt('Template name:', newTask.description.substring(0, 40));+ if (!name) return;++ const result = await api.createCosTaskTemplate({+ name,+ description: newTask.description,+ context: newTask.context,+ provider: newTask.provider,+ model: newTask.model,+ app: newTask.app+ }).catch(err => {+ toast.error(err.message);+ return null;+ });++ if (result?.success) {+ toast.success('Template saved');+ // Refresh templates+ api.getCosPopularTemplates(8)+ .then(data => setTemplates(data.templates || []))+ .catch(() => {});+ }+ }, [newTask]);++ // Delete a user template+ const deleteTemplate = useCallback(async (templateId, e) => {+ e.stopPropagation();++ const result = await api.deleteCosTaskTemplate(templateId).catch(err => {+ toast.error(err.message);+ return null;+ });++ if (result?.success) {+ toast.success('Template deleted');+ setTemplates(prev => prev.filter(t => t.id !== templateId));+ }}, []);// Memoize task arrays to prevent unnecessary re-renders@@ -245,6 +313,49 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {</button></div>+ {/* Quick Templates */}+ {templates.length > 0 && (+ <div className="mb-4">+ <button+ onClick={() => setShowTemplates(!showTemplates)}+ className="flex items-center gap-2 text-sm text-gray-400 hover:text-white transition-colors mb-2"+ aria-expanded={showTemplates}+ >+ {showTemplates ? <ChevronDown size={14} /> : <ChevronRight size={14} />}+ <Zap size={14} className="text-yellow-500" />+ Quick Templates+ <span className="text-xs text-gray-600">({templates.length})</span>+ </button>+ {showTemplates && (+ <div className="flex flex-wrap gap-2">+ {templates.map(template => (+ <button+ key={template.id}+ onClick={() => applyTemplate(template)}+ className="group relative flex items-center gap-1.5 px-3 py-1.5 bg-port-card border border-port-border rounded-lg text-sm text-gray-300 hover:text-white hover:border-port-accent/50 transition-colors"+ title={template.description}+ >+ <span>{template.icon || '📝'}</span>+ <span className="max-w-[120px] truncate">{template.name}</span>+ {template.useCount > 0 && (+ <span className="text-xs text-gray-600">({template.useCount})</span>+ )}+ {!template.isBuiltin && (+ <button+ onClick={(e) => deleteTemplate(template.id, e)}+ className="hidden group-hover:flex absolute -top-1 -right-1 w-4 h-4 bg-port-error rounded-full items-center justify-center"+ title="Delete template"+ >+ <X size={10} />+ </button>+ )}+ </button>+ ))}+ </div>+ )}+ </div>+ )}+{/* Add Task Form */}{showAddTask && (<div className="bg-port-card border border-port-accent/50 rounded-lg p-4 mb-4" role="form" aria-label="Add new task">@@ -447,7 +558,16 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {))}</div>)}- <div className="flex justify-end">+ <div className="flex justify-end gap-2">+ <button+ onClick={saveAsTemplate}+ type="button"+ className="flex items-center gap-1 px-3 py-1.5 bg-port-border hover:bg-port-border/80 text-gray-400 hover:text-white rounded-lg text-sm transition-colors min-h-[40px]"+ title="Save current form as a reusable template"+ >+ <Bookmark size={14} aria-hidden="true" />+ <span className="hidden sm:inline">Save Template</span>+ </button><buttononClick={handleAddTask}disabled={isEnhancing}diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 3ed4ee5a43..7d8d292246 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -399,6 +399,25 @@ export const getCosLearningPerformance = () => request('/cos/learning/performancexport const backfillCosLearning = () => request('/cos/learning/backfill', { method: 'POST' });export const resetCosTaskTypeLearning = (taskType) => request(`/cos/learning/reset/${encodeURIComponent(taskType)}`, { method: 'POST' });+// CoS Quick Task Templates+export const getCosTaskTemplates = () => request('/cos/templates');+export const getCosPopularTemplates = (limit = 5) => request(`/cos/templates/popular?limit=${limit}`);+export const getCosTemplateCategories = () => request('/cos/templates/categories');+export const createCosTaskTemplate = (data) => request('/cos/templates', {+ method: 'POST',+ body: JSON.stringify(data)+});+export const createCosTemplateFromTask = (task, templateName) => request('/cos/templates/from-task', {+ method: 'POST',+ body: JSON.stringify({ task, templateName })+});+export const useCosTaskTemplate = (id) => request(`/cos/templates/${id}/use`, { method: 'POST' });+export const updateCosTaskTemplate = (id, data) => request(`/cos/templates/${id}`, {+ method: 'PUT',+ body: JSON.stringify(data)+});+export const deleteCosTaskTemplate = (id) => request(`/cos/templates/${id}`, { method: 'DELETE' });+// CoS Scriptsexport const getCosScripts = () => request('/cos/scripts');export const getCosScript = (id) => request(`/cos/scripts/${id}`);diff --git a/server/routes/cos.js b/server/routes/cos.jsindex e8d3d68593..236c905f77 100644--- a/server/routes/cos.js+++ b/server/routes/cos.js@@ -10,6 +10,7 @@ import * as taskLearning from '../services/taskLearning.js';import * as weeklyDigest from '../services/weeklyDigest.js';import * as taskSchedule from '../services/taskSchedule.js';import * as autonomousJobs from '../services/autonomousJobs.js';+import * as taskTemplates from '../services/taskTemplates.js';import { enhanceTaskPrompt } from '../services/taskEnhancer.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';@@ -754,4 +755,77 @@ router.delete('/jobs/:id', asyncHandler(async (req, res) => {res.json({ success: true });}));+// ============================================================+// Quick Task Templates Routes+// ============================================================++// GET /api/cos/templates - Get all task templates+router.get('/templates', asyncHandler(async (req, res) => {+ const templates = await taskTemplates.getAllTemplates();+ res.json({ templates });+}));++// GET /api/cos/templates/popular - Get popular templates+router.get('/templates/popular', asyncHandler(async (req, res) => {+ const limit = parseInt(req.query.limit, 10) || 5;+ const templates = await taskTemplates.getPopularTemplates(limit);+ res.json({ templates });+}));++// GET /api/cos/templates/categories - Get template categories+router.get('/templates/categories', asyncHandler(async (req, res) => {+ const categories = await taskTemplates.getCategories();+ res.json({ categories });+}));++// POST /api/cos/templates - Create a new template+router.post('/templates', asyncHandler(async (req, res) => {+ const { name, icon, description, context, category, provider, model, app } = req.body;++ if (!name || !description) {+ throw new ServerError('name and description are required', { status: 400, code: 'VALIDATION_ERROR' });+ }++ const template = await taskTemplates.createTemplate({+ name, icon, description, context, category, provider, model, app+ });+ res.json({ success: true, template });+}));++// POST /api/cos/templates/from-task - Create template from task+router.post('/templates/from-task', asyncHandler(async (req, res) => {+ const { task, templateName } = req.body;++ if (!task || !task.description) {+ throw new ServerError('task with description is required', { status: 400, code: 'VALIDATION_ERROR' });+ }++ const template = await taskTemplates.createTemplateFromTask(task, templateName);+ res.json({ success: true, template });+}));++// POST /api/cos/templates/:id/use - Record template usage+router.post('/templates/:id/use', asyncHandler(async (req, res) => {+ const useCount = await taskTemplates.recordTemplateUsage(req.params.id);+ res.json({ success: true, useCount });+}));++// PUT /api/cos/templates/:id - Update a template+router.put('/templates/:id', asyncHandler(async (req, res) => {+ const result = await taskTemplates.updateTemplate(req.params.id, req.body);+ if (result.error) {+ throw new ServerError(result.error, { status: 400, code: 'BAD_REQUEST' });+ }+ res.json({ success: true, template: result });+}));++// DELETE /api/cos/templates/:id - Delete a template+router.delete('/templates/:id', asyncHandler(async (req, res) => {+ const result = await taskTemplates.deleteTemplate(req.params.id);+ if (result.error) {+ throw new ServerError(result.error, { status: 400, code: 'BAD_REQUEST' });+ }+ res.json(result);+}));+export default router;diff --git a/server/services/taskTemplates.js b/server/services/taskTemplates.jsnew file mode 100644index 0000000000..dc22701511--- /dev/null+++ b/server/services/taskTemplates.js@@ -0,0 +1,281 @@+/**+ * Task Templates Service+ *+ * Quick task templates for common user task patterns.+ * Helps users quickly create tasks for frequently needed operations.+ */++import { writeFile, mkdir } from 'fs/promises';+import { existsSync } from 'fs';+import { join, dirname } from 'path';+import { fileURLToPath } from 'url';+import { readJSONFile } from '../lib/fileUtils.js';++const __filename = fileURLToPath(import.meta.url);+const __dirname = dirname(__filename);+const DATA_DIR = join(__dirname, '../../data/cos');+const TEMPLATES_FILE = join(DATA_DIR, 'task-templates.json');++// Built-in templates based on common task patterns+const BUILT_IN_TEMPLATES = [+ {+ id: 'builtin-mobile-fix',+ name: 'Fix Mobile Responsiveness',+ icon: '📱',+ description: 'Make this page mobile-friendly',+ context: 'Check viewport sizes 375px, 768px, and 1024px. Fix Tailwind responsive classes.',+ category: 'ui',+ isBuiltin: true+ },+ {+ id: 'builtin-add-feature',+ name: 'Add New Feature',+ icon: '✨',+ description: 'Add a new feature to',+ context: 'Follow existing patterns in the codebase. Write tests for new functionality.',+ category: 'feature',+ isBuiltin: true+ },+ {+ id: 'builtin-fix-bug',+ name: 'Fix Bug',+ icon: '🐛',+ description: 'Fix the bug where',+ context: 'Investigate root cause, implement fix, add test to prevent regression.',+ category: 'bugfix',+ isBuiltin: true+ },+ {+ id: 'builtin-refactor',+ name: 'Refactor Code',+ icon: '🔧',+ description: 'Refactor',+ context: 'Improve code quality while maintaining existing behavior. Ensure tests pass.',+ category: 'refactor',+ isBuiltin: true+ },+ {+ id: 'builtin-add-test',+ name: 'Add Tests',+ icon: '🧪',+ description: 'Add tests for',+ context: 'Write unit tests with good coverage. Follow existing test patterns.',+ category: 'testing',+ isBuiltin: true+ },+ {+ id: 'builtin-improve-ux',+ name: 'Improve UX',+ icon: '🎨',+ description: 'Improve the user experience of',+ context: 'Focus on usability, accessibility, and visual polish.',+ category: 'ui',+ isBuiltin: true+ },+ {+ id: 'builtin-add-api',+ name: 'Add API Endpoint',+ icon: '🔌',+ description: 'Add API endpoint for',+ context: 'Add route with Zod validation, service function, and API tests.',+ category: 'feature',+ isBuiltin: true+ },+ {+ id: 'builtin-security-fix',+ name: 'Security Fix',+ icon: '🔒',+ description: 'Fix security issue in',+ context: 'Address vulnerability with proper input validation and sanitization.',+ category: 'security',+ isBuiltin: true+ }+];++// Default empty state+const DEFAULT_STATE = {+ version: 1,+ lastUpdated: null,+ userTemplates: [],+ usage: {}+};++/**+ * Load templates state+ */+async function loadState() {+ const data = await readJSONFile(TEMPLATES_FILE);+ if (!data) return { ...DEFAULT_STATE };+ return data;+}++/**+ * Save templates state+ */+async function saveState(state) {+ state.lastUpdated = new Date().toISOString();++ if (!existsSync(DATA_DIR)) {+ await mkdir(DATA_DIR, { recursive: true });+ }++ await writeFile(TEMPLATES_FILE, JSON.stringify(state, null, 2));+}++/**+ * Get all templates (built-in + user)+ */+export async function getAllTemplates() {+ const state = await loadState();++ // Combine built-in and user templates+ const templates = [+ ...BUILT_IN_TEMPLATES,+ ...state.userTemplates+ ];++ // Add usage counts+ return templates.map(t => ({+ ...t,+ useCount: state.usage[t.id] || 0+ }));+}++/**+ * Get templates sorted by recent usage+ */+export async function getPopularTemplates(limit = 5) {+ const templates = await getAllTemplates();++ return templates+ .sort((a, b) => (b.useCount || 0) - (a.useCount || 0))+ .slice(0, limit);+}++/**+ * Record template usage (for popularity tracking)+ */+export async function recordTemplateUsage(templateId) {+ const state = await loadState();++ if (!state.usage) {+ state.usage = {};+ }++ state.usage[templateId] = (state.usage[templateId] || 0) + 1;+ await saveState(state);++ return state.usage[templateId];+}++/**+ * Create a new user template+ */+export async function createTemplate(templateData) {+ const state = await loadState();++ const newTemplate = {+ id: `user-${Date.now().toString(36)}`,+ name: templateData.name,+ icon: templateData.icon || '📝',+ description: templateData.description,+ context: templateData.context || '',+ category: templateData.category || 'custom',+ provider: templateData.provider || '',+ model: templateData.model || '',+ app: templateData.app || '',+ isBuiltin: false,+ createdAt: new Date().toISOString()+ };++ state.userTemplates.push(newTemplate);+ await saveState(state);++ return newTemplate;+}++/**+ * Update a user template+ */+export async function updateTemplate(templateId, updates) {+ const state = await loadState();++ const index = state.userTemplates.findIndex(t => t.id === templateId);+ if (index === -1) {+ return { error: 'Template not found or is a built-in template' };+ }++ state.userTemplates[index] = {+ ...state.userTemplates[index],+ ...updates,+ id: templateId, // Preserve ID+ isBuiltin: false,+ updatedAt: new Date().toISOString()+ };++ await saveState(state);+ return state.userTemplates[index];+}++/**+ * Delete a user template+ */+export async function deleteTemplate(templateId) {+ const state = await loadState();++ // Can't delete built-in templates+ if (templateId.startsWith('builtin-')) {+ return { error: 'Cannot delete built-in templates' };+ }++ const index = state.userTemplates.findIndex(t => t.id === templateId);+ if (index === -1) {+ return { error: 'Template not found' };+ }++ const deleted = state.userTemplates.splice(index, 1)[0];++ // Also clean up usage data+ if (state.usage && state.usage[templateId]) {+ delete state.usage[templateId];+ }++ await saveState(state);++ return { success: true, deleted };+}++/**+ * Get categories with counts+ */+export async function getCategories() {+ const templates = await getAllTemplates();++ const categories = {};+ for (const t of templates) {+ const cat = t.category || 'other';+ if (!categories[cat]) {+ categories[cat] = { name: cat, count: 0 };+ }+ categories[cat].count++;+ }++ return Object.values(categories);+}++/**+ * Create template from a completed task+ * Useful for saving successful task patterns+ */+export async function createTemplateFromTask(task, templateName) {+ return createTemplate({+ name: templateName || `Custom: ${task.description?.substring(0, 30)}...`,+ icon: '⭐',+ description: task.description,+ context: task.context || '',+ category: 'from-task',+ provider: task.provider || '',+ model: task.model || '',+ app: task.app || ''+ });+}