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 adaptive task learning and performance optimizations
Adam Eivy7d3d2bcdfbe4
diff --git a/client/src/components/AppTile.jsx b/client/src/components/AppTile.jsxindex b509bac315..a0ebc78835 100644--- a/client/src/components/AppTile.jsx+++ b/client/src/components/AppTile.jsx@@ -1,4 +1,4 @@-import { useState } from 'react';+import { useState, memo, useCallback, useMemo } from 'react';import StatusBadge from './StatusBadge';import AppIcon from './AppIcon';import * as api from '../services/api';@@ -14,7 +14,8 @@ function getAppUrl(app) {return null;}-export default function AppTile({ app, onUpdate }) {+// Memoized component to prevent re-renders when parent polls for updates+const AppTile = memo(function AppTile({ app, onUpdate }) {const [loading, setLoading] = useState(null);const appUrl = getAppUrl(app);@@ -115,4 +116,6 @@ export default function AppTile({ app, onUpdate }) {</div></div>);-}+});++export default AppTile;diff --git a/client/src/pages/Apps.jsx b/client/src/pages/Apps.jsxindex efc814b8b8..c97445f0d8 100644--- a/client/src/pages/Apps.jsx+++ b/client/src/pages/Apps.jsx@@ -1,4 +1,4 @@-import { useState, useEffect } from 'react';+import { useState, useEffect, useCallback } from 'react';import { Link } from 'react-router-dom';import { ExternalLink, Play, Square, RotateCcw, FolderOpen, Terminal, Code, RefreshCw, Wrench } from 'lucide-react';import toast from 'react-hot-toast';@@ -16,17 +16,17 @@ export default function Apps() {const [refreshingConfig, setRefreshingConfig] = useState({});const [standardizing, setStandardizing] = useState({});- const fetchApps = async () => {+ const fetchApps = useCallback(async () => {const data = await api.getApps().catch(() => []);setApps(data);setLoading(false);- };+ }, []);useEffect(() => {fetchApps();const interval = setInterval(fetchApps, 5000);return () => clearInterval(interval);- }, []);+ }, [fetchApps]);const handleDelete = async (app) => {await api.deleteApp(app.id);diff --git a/client/src/pages/Dashboard.jsx b/client/src/pages/Dashboard.jsxindex 460f0fa050..1987b144e2 100644--- a/client/src/pages/Dashboard.jsx+++ b/client/src/pages/Dashboard.jsx@@ -1,4 +1,4 @@-import { useState, useEffect } from 'react';+import { useState, useEffect, useCallback, useMemo } from 'react';import { Link } from 'react-router-dom';import AppTile from '../components/AppTile';import * as api from '../services/api';@@ -9,7 +9,7 @@ export default function Dashboard() {const [loading, setLoading] = useState(true);const [error, setError] = useState(null);- const fetchData = async () => {+ const fetchData = useCallback(async () => {setError(null);const [appsData, healthData] = await Promise.all([api.getApps().catch(err => { setError(err.message); return []; }),@@ -18,13 +18,21 @@ export default function Dashboard() {setApps(appsData);setHealth(healthData);setLoading(false);- };+ }, []);useEffect(() => {fetchData();const interval = setInterval(fetchData, 10000);return () => clearInterval(interval);- }, []);+ }, [fetchData]);++ // Memoize derived stats to prevent recalculation on every render+ const appStats = useMemo(() => ({+ total: apps.length,+ online: apps.filter(a => a.overallStatus === 'online').length,+ stopped: apps.filter(a => a.overallStatus === 'stopped').length,+ notStarted: apps.filter(a => a.overallStatus === 'not_started' || a.overallStatus === 'not_found').length+ }), [apps]);if (loading) {return (@@ -86,22 +94,22 @@ export default function Dashboard() {<div className="mt-8 grid grid-cols-2 md:grid-cols-4 gap-4"><StatCardlabel="Total Apps"- value={apps.length}+ value={appStats.total}icon="📦"/><StatCardlabel="Online"- value={apps.filter(a => a.overallStatus === 'online').length}+ value={appStats.online}icon="🟢"/><StatCardlabel="Stopped"- value={apps.filter(a => a.overallStatus === 'stopped').length}+ value={appStats.stopped}icon="🟡"/><StatCardlabel="Not Started"- value={apps.filter(a => a.overallStatus === 'not_started' || a.overallStatus === 'not_found').length}+ value={appStats.notStarted}icon="⚪"/></div>diff --git a/server/routes/cos.js b/server/routes/cos.jsindex 9a58b8e525..6495ed719d 100644--- a/server/routes/cos.js+++ b/server/routes/cos.js@@ -315,4 +315,26 @@ router.post('/learning/backfill', asyncHandler(async (req, res) => {res.json({ success: true, backfilledCount: count });}));+// GET /api/cos/learning/skipped - Get task types being skipped due to poor performance+router.get('/learning/skipped', asyncHandler(async (req, res) => {+ const skipped = await taskLearning.getSkippedTaskTypes();+ res.json({+ skippedCount: skipped.length,+ skippedTypes: skipped,+ message: skipped.length > 0+ ? 'These task types have <30% success rate after 5+ attempts and are being skipped'+ : 'No task types are currently being skipped'+ });+}));++// GET /api/cos/learning/cooldown/:taskType - Get adaptive cooldown for specific task type+router.get('/learning/cooldown/:taskType', asyncHandler(async (req, res) => {+ const { taskType } = req.params;+ const cooldownInfo = await taskLearning.getAdaptiveCooldownMultiplier(taskType);+ res.json({+ taskType,+ ...cooldownInfo+ });+}));+export default router;diff --git a/server/services/apps.js b/server/services/apps.jsindex 726ec7743e..b851a7d642 100644--- a/server/services/apps.js+++ b/server/services/apps.js@@ -9,6 +9,11 @@ const __dirname = dirname(__filename);const DATA_DIR = join(__dirname, '../../data');const APPS_FILE = join(DATA_DIR, 'apps.json');+// In-memory cache for apps data+let appsCache = null;+let cacheTimestamp = 0;+const CACHE_TTL_MS = 2000; // Cache for 2 seconds to reduce file reads during rapid polling+/*** Ensure data directory exists*/@@ -19,25 +24,47 @@ async function ensureDataDir() {}/**- * Load apps registry from disk+ * Load apps registry from disk (with caching)*/async function loadApps() {+ const now = Date.now();++ // Return cached data if still valid+ if (appsCache && (now - cacheTimestamp) < CACHE_TTL_MS) {+ return appsCache;+ }+await ensureDataDir();if (!existsSync(APPS_FILE)) {- return { apps: {} };+ appsCache = { apps: {} };+ cacheTimestamp = now;+ return appsCache;}const content = await readFile(APPS_FILE, 'utf-8');- return JSON.parse(content);+ appsCache = JSON.parse(content);+ cacheTimestamp = now;+ return appsCache;}/**- * Save apps registry to disk+ * Save apps registry to disk (and invalidate cache)*/async function saveApps(data) {await ensureDataDir();await writeFile(APPS_FILE, JSON.stringify(data, null, 2));+ // Update cache with saved data+ appsCache = data;+ cacheTimestamp = Date.now();+}++/**+ * Invalidate the apps cache (call after external changes)+ */+export function invalidateCache() {+ appsCache = null;+ cacheTimestamp = 0;}/**diff --git a/server/services/cos.js b/server/services/cos.jsindex 3239e476fe..0bd3c702fa 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -17,6 +17,7 @@ import { getActiveProvider } from './providers.js';import { parseTasksMarkdown, groupTasksByStatus, getNextTask, getAutoApprovedTasks, getAwaitingApprovalTasks, updateTaskStatus, generateTasksMarkdown } from '../lib/taskParser.js';import { isAppOnCooldown, getNextAppForReview, markAppReviewStarted, markIdleReviewStarted } from './appActivity.js';import { getAllApps } from './apps.js';+import { shouldSkipTaskType, getAdaptiveCooldownMultiplier, getSkippedTaskTypes } from './taskLearning.js';const execAsync = promisify(exec);@@ -700,12 +701,70 @@ const SELF_IMPROVEMENT_TYPES = [/*** Generate a self-improvement task for PortOS itself* Uses Playwright and Opus to analyze and fix issues+ *+ * Enhanced with adaptive learning:+ * - Skips task types with consistently poor success rates+ * - Logs learning-based recommendations+ * - Falls back to next available task type if current is skipped*/async function generateSelfImprovementTask(state) {- // Get the next analysis type in rotation+ // Get the next analysis type in rotation, but skip failing task typesconst lastType = state.stats.lastSelfImprovementType || '';- const currentIndex = SELF_IMPROVEMENT_TYPES.indexOf(lastType);- const nextType = SELF_IMPROVEMENT_TYPES[(currentIndex + 1) % SELF_IMPROVEMENT_TYPES.length];+ let currentIndex = SELF_IMPROVEMENT_TYPES.indexOf(lastType);+ let nextType = null;+ let attempts = 0;+ const maxAttempts = SELF_IMPROVEMENT_TYPES.length;++ // Find next task type that isn't being skipped due to poor performance+ while (attempts < maxAttempts) {+ currentIndex = (currentIndex + 1) % SELF_IMPROVEMENT_TYPES.length;+ const candidateType = SELF_IMPROVEMENT_TYPES[currentIndex];+ const taskTypeKey = `self-improve:${candidateType}`;++ // Check if this task type should be skipped based on learning data+ const cooldownInfo = await getAdaptiveCooldownMultiplier(taskTypeKey).catch(() => ({ skip: false }));++ if (cooldownInfo.skip) {+ emitLog('warn', `Skipping ${candidateType} - poor success rate (${cooldownInfo.successRate}% after ${cooldownInfo.completed} attempts)`, {+ taskType: candidateType,+ successRate: cooldownInfo.successRate,+ completed: cooldownInfo.completed,+ reason: cooldownInfo.reason+ });+ attempts++;+ continue;+ }++ // Log if there's a recommendation from learning system+ if (cooldownInfo.recommendation) {+ emitLog('info', `Learning insight for ${candidateType}: ${cooldownInfo.recommendation}`, {+ taskType: candidateType,+ multiplier: cooldownInfo.multiplier+ });+ }++ nextType = candidateType;+ break;+ }++ // If all task types are failing, log warning and pick the one that's been failing longest+ if (!nextType) {+ const skippedTypes = await getSkippedTaskTypes().catch(() => []);+ emitLog('warn', `All self-improvement task types are underperforming - selecting oldest failed type for retry`, {+ skippedCount: skippedTypes.length+ });++ // Sort by lastCompleted ascending (oldest first) and pick that one+ if (skippedTypes.length > 0) {+ skippedTypes.sort((a, b) => new Date(a.lastCompleted || 0) - new Date(b.lastCompleted || 0));+ const oldestType = skippedTypes[0].taskType.replace('self-improve:', '');+ nextType = oldestType;+ emitLog('info', `Retrying ${oldestType} as it hasn't been attempted recently`);+ } else {+ // Fallback to first type in rotation+ nextType = SELF_IMPROVEMENT_TYPES[0];+ }+ }// Update state with new timestamp and typeawait withStateLock(async () => {diff --git a/server/services/taskLearning.js b/server/services/taskLearning.jsindex 7bb70e7b9b..8d8446c223 100644--- a/server/services/taskLearning.js+++ b/server/services/taskLearning.js@@ -380,6 +380,135 @@ export async function suggestModelTier(taskType) {return null; // Current selection is working fine}+/**+ * Get adaptive cooldown multiplier for a task type based on historical performance+ *+ * This allows the CoS to work more efficiently:+ * - High success rate tasks: Reduced cooldown (can work on similar tasks sooner)+ * - Low success rate tasks: Increased cooldown (give time for fixes/investigation)+ * - Very low success rate: Skip this task type (needs review)+ *+ * @param {string} taskType - The task type (e.g., 'self-improve:ui-bugs')+ * @returns {Object} Cooldown adjustment info+ */+export async function getAdaptiveCooldownMultiplier(taskType) {+ const data = await loadLearningData();++ const metrics = data.byTaskType[taskType];++ // Not enough data - use default cooldown+ if (!metrics || metrics.completed < 3) {+ return {+ multiplier: 1.0,+ reason: 'insufficient-data',+ skip: false,+ successRate: null,+ completed: metrics?.completed || 0+ };+ }++ const successRate = metrics.successRate;++ // Very high success (90%+): Reduce cooldown by 30% - this task type works well+ if (successRate >= 90) {+ return {+ multiplier: 0.7,+ reason: 'high-success',+ skip: false,+ successRate,+ completed: metrics.completed,+ recommendation: `Task type has ${successRate}% success rate - reduced cooldown`+ };+ }++ // Good success (75-89%): Slight reduction (15%)+ if (successRate >= 75) {+ return {+ multiplier: 0.85,+ reason: 'good-success',+ skip: false,+ successRate,+ completed: metrics.completed+ };+ }++ // Moderate success (50-74%): Default cooldown+ if (successRate >= 50) {+ return {+ multiplier: 1.0,+ reason: 'moderate-success',+ skip: false,+ successRate,+ completed: metrics.completed+ };+ }++ // Low success (30-49%): Increase cooldown by 50%+ if (successRate >= 30) {+ return {+ multiplier: 1.5,+ reason: 'low-success',+ skip: false,+ successRate,+ completed: metrics.completed,+ recommendation: `Task type has only ${successRate}% success rate - increased cooldown`+ };+ }++ // Very low success (<30%) with significant attempts: Skip this task type+ if (metrics.completed >= 5) {+ return {+ multiplier: 0, // Effectively infinite cooldown+ reason: 'skip-failing',+ skip: true,+ successRate,+ completed: metrics.completed,+ recommendation: `Task type has ${successRate}% success rate after ${metrics.completed} attempts - skipping until reviewed`+ };+ }++ // Very low success but few attempts: Double cooldown and keep trying+ return {+ multiplier: 2.0,+ reason: 'very-low-success',+ skip: false,+ successRate,+ completed: metrics.completed,+ recommendation: `Task type has ${successRate}% success rate - doubled cooldown for retry`+ };+}++/**+ * Get all task types that should be skipped due to poor performance+ * Useful for filtering out problematic task types in evaluateTasks+ */+export async function getSkippedTaskTypes() {+ const data = await loadLearningData();+ const skipped = [];++ for (const [taskType, metrics] of Object.entries(data.byTaskType)) {+ // Skip if: completed >= 5 AND success rate < 30%+ if (metrics.completed >= 5 && metrics.successRate < 30) {+ skipped.push({+ taskType,+ successRate: metrics.successRate,+ completed: metrics.completed,+ lastCompleted: metrics.lastCompleted+ });+ }+ }++ return skipped;+}++/**+ * Check if a specific task type should be skipped+ */+export async function shouldSkipTaskType(taskType) {+ const result = await getAdaptiveCooldownMultiplier(taskType);+ return result.skip;+}+/*** Get estimated duration for a task based on historical averages* @param {string} taskDescription - The task description to analyze