Skip to content

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

feat: replace apps polling with WebSocket events

Adam Eivy98fe8c752130
diff --git a/client/src/components/cos/tabs/TasksTab.jsx b/client/src/components/cos/tabs/TasksTab.jsx
index 4e1fb57af3..acb8032273 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, useCallback } from 'react';
-import { Plus, RefreshCw, Image, X } from 'lucide-react';
+import { Plus, RefreshCw, Image, X, ChevronDown, ChevronRight } from 'lucide-react';
import toast from 'react-hot-toast';
import {
DndContext,
@@ -25,6 +25,8 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {
const [userTasksLocal, setUserTasksLocal] = useState([]);
const [screenshots, setScreenshots] = useState([]);
const [durations, setDurations] = useState(null);
+ const [showCompletedUserTasks, setShowCompletedUserTasks] = useState(false);
+ const [showCompletedSystemTasks, setShowCompletedSystemTasks] = useState(false);
const fileInputRef = useRef(null);
// Fetch task duration estimates from learning data
@@ -39,18 +41,46 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {
const cosTasks = useMemo(() => tasks.cos?.tasks || [], [tasks.cos?.tasks]);
const awaitingApproval = useMemo(() => tasks.cos?.awaitingApproval || [], [tasks.cos?.awaitingApproval]);
+ // Split tasks into pending (includes in_progress, blocked) and completed
+ const pendingUserTasks = useMemo(() =>
+ userTasks.filter(t => t.status !== 'completed'),
+ [userTasks]
+ );
+ const completedUserTasks = useMemo(() =>
+ userTasks.filter(t => t.status === 'completed'),
+ [userTasks]
+ );
+ const pendingSystemTasks = useMemo(() =>
+ cosTasks.filter(t => t.status !== 'completed'),
+ [cosTasks]
+ );
+ const completedSystemTasks = useMemo(() =>
+ cosTasks.filter(t => t.status === 'completed'),
+ [cosTasks]
+ );
+
// Memoize enabled providers for dropdown
const enabledProviders = useMemo(() =>
providers?.filter(p => p.enabled) || [],
[providers]
);
- // Memoize sortable item IDs for DndContext
- const sortableIds = useMemo(() =>
- userTasksLocal.map(t => t.id),
+ // Memoize pending tasks from local state for drag-and-drop (only pending tasks are sortable)
+ const pendingUserTasksLocal = useMemo(() =>
+ userTasksLocal.filter(t => t.status !== 'completed'),
+ [userTasksLocal]
+ );
+ const completedUserTasksLocal = useMemo(() =>
+ userTasksLocal.filter(t => t.status === 'completed'),
[userTasksLocal]
);
+ // Memoize sortable item IDs for DndContext (only pending tasks)
+ const sortableIds = useMemo(() =>
+ pendingUserTasksLocal.map(t => t.id),
+ [pendingUserTasksLocal]
+ );
+
// Keep local state in sync with server state
useEffect(() => {
setUserTasksLocal(userTasks);
@@ -325,27 +355,69 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {
</div>
)}
- {userTasksLocal.length === 0 ? (
+ {/* Pending User Tasks */}
+ {pendingUserTasksLocal.length === 0 && completedUserTasksLocal.length === 0 ? (
<div className="bg-port-card border border-port-border rounded-lg p-6 text-center text-gray-500">
No user tasks. Click "Add Task" or edit TASKS.md directly.
</div>
) : (
- <DndContext
- sensors={sensors}
- collisionDetection={closestCenter}
- onDragEnd={handleDragEnd}
- >
- <SortableContext
- items={sortableIds}
- strategy={verticalListSortingStrategy}
- >
- <div className="space-y-2">
- {userTasksLocal.map(task => (
- <SortableTaskItem key={task.id} task={task} onRefresh={onRefresh} providers={providers} durations={durations} />
- ))}
+ <div className="space-y-3">
+ {/* Pending Section */}
+ <div className="bg-port-card border border-port-border rounded-lg overflow-hidden">
+ <div className="px-3 py-2 bg-port-accent/10 border-b border-port-border flex items-center justify-between">
+ <span className="text-sm font-medium text-port-accent">
+ Pending ({pendingUserTasksLocal.length})
+ </span>
+ </div>
+ {pendingUserTasksLocal.length === 0 ? (
+ <div className="p-4 text-center text-gray-500 text-sm">
+ No pending tasks
+ </div>
+ ) : (
+ <div className="p-2">
+ <DndContext
+ sensors={sensors}
+ collisionDetection={closestCenter}
+ onDragEnd={handleDragEnd}
+ >
+ <SortableContext
+ items={sortableIds}
+ strategy={verticalListSortingStrategy}
+ >
+ <div className="space-y-1.5">
+ {pendingUserTasksLocal.map(task => (
+ <SortableTaskItem key={task.id} task={task} onRefresh={onRefresh} providers={providers} durations={durations} />
+ ))}
+ </div>
+ </SortableContext>
+ </DndContext>
+ </div>
+ )}
+ </div>
+
+ {/* Completed Section - Collapsible */}
+ {completedUserTasksLocal.length > 0 && (
+ <div className="bg-port-card border border-port-border rounded-lg overflow-hidden">
+ <button
+ onClick={() => setShowCompletedUserTasks(!showCompletedUserTasks)}
+ className="w-full px-3 py-2 bg-port-success/10 border-b border-port-border flex items-center justify-between hover:bg-port-success/20 transition-colors"
+ aria-expanded={showCompletedUserTasks}
+ >
+ <span className="text-sm font-medium text-port-success flex items-center gap-2">
+ {showCompletedUserTasks ? <ChevronDown size={14} aria-hidden="true" /> : <ChevronRight size={14} aria-hidden="true" />}
+ Completed ({completedUserTasksLocal.length})
+ </span>
+ </button>
+ {showCompletedUserTasks && (
+ <div className="p-2 space-y-1.5">
+ {completedUserTasksLocal.map(task => (
+ <TaskItem key={task.id} task={task} onRefresh={onRefresh} providers={providers} durations={durations} />
+ ))}
+ </div>
+ )}
</div>
- </SortableContext>
- </DndContext>
+ )}
+ </div>
)}
</div>
@@ -353,16 +425,46 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {
<div>
<h3 className="text-lg font-semibold text-white mb-3">System Tasks (COS-TASKS.md)</h3>
- {cosTasks.length === 0 ? (
+ {/* Pending System Tasks */}
+ {pendingSystemTasks.length === 0 && completedSystemTasks.length === 0 ? (
<div className="bg-port-card border border-port-border rounded-lg p-6 text-center text-gray-500">
No system tasks.
</div>
) : (
- <div className="space-y-2">
- {cosTasks.map(task => (
- <TaskItem key={task.id} task={task} isSystem onRefresh={onRefresh} providers={providers} durations={durations} />
- ))}
- </div>
+ <>
+ {pendingSystemTasks.length === 0 ? (
+ <div className="bg-port-card border border-port-border rounded-lg p-4 text-center text-gray-500 text-sm">
+ No pending tasks
+ </div>
+ ) : (
+ <div className="space-y-2">
+ {pendingSystemTasks.map(task => (
+ <TaskItem key={task.id} task={task} isSystem onRefresh={onRefresh} providers={providers} durations={durations} />
+ ))}
+ </div>
+ )}
+
+ {/* Completed System Tasks - Collapsible */}
+ {completedSystemTasks.length > 0 && (
+ <div className="mt-3">
+ <button
+ onClick={() => setShowCompletedSystemTasks(!showCompletedSystemTasks)}
+ className="flex items-center gap-2 text-sm text-gray-400 hover:text-white transition-colors mb-2"
+ aria-expanded={showCompletedSystemTasks}
+ >
+ {showCompletedSystemTasks ? <ChevronDown size={16} aria-hidden="true" /> : <ChevronRight size={16} aria-hidden="true" />}
+ Completed ({completedSystemTasks.length})
+ </button>
+ {showCompletedSystemTasks && (
+ <div className="space-y-2">
+ {completedSystemTasks.map(task => (
+ <TaskItem key={task.id} task={task} isSystem onRefresh={onRefresh} providers={providers} durations={durations} />
+ ))}
+ </div>
+ )}
+ </div>
+ )}
+ </>
)}
</div>
diff --git a/client/src/pages/Apps.jsx b/client/src/pages/Apps.jsx
index c97445f0d8..955b7751d4 100644
--- a/client/src/pages/Apps.jsx
+++ b/client/src/pages/Apps.jsx
@@ -5,6 +5,7 @@ import toast from 'react-hot-toast';
import StatusBadge from '../components/StatusBadge';
import IconPicker from '../components/IconPicker';
import * as api from '../services/api';
+import socket from '../services/socket';
export default function Apps() {
const [apps, setApps] = useState([]);
@@ -24,8 +25,16 @@ export default function Apps() {
useEffect(() => {
fetchApps();
- const interval = setInterval(fetchApps, 5000);
- return () => clearInterval(interval);
+
+ // Listen for apps changes via WebSocket instead of polling
+ const handleAppsChanged = () => {
+ fetchApps();
+ };
+ socket.on('apps:changed', handleAppsChanged);
+
+ return () => {
+ socket.off('apps:changed', handleAppsChanged);
+ };
}, [fetchApps]);
const handleDelete = async (app) => {
@@ -37,28 +46,19 @@ export default function Apps() {
const handleStart = async (app) => {
setActionLoading(prev => ({ ...prev, [app.id]: 'start' }));
await api.startApp(app.id).catch(() => null);
- setTimeout(() => {
- setActionLoading(prev => ({ ...prev, [app.id]: null }));
- fetchApps();
- }, 1500);
+ setActionLoading(prev => ({ ...prev, [app.id]: null }));
};
const handleStop = async (app) => {
setActionLoading(prev => ({ ...prev, [app.id]: 'stop' }));
await api.stopApp(app.id).catch(() => null);
- setTimeout(() => {
- setActionLoading(prev => ({ ...prev, [app.id]: null }));
- fetchApps();
- }, 1500);
+ setActionLoading(prev => ({ ...prev, [app.id]: null }));
};
const handleRestart = async (app) => {
setActionLoading(prev => ({ ...prev, [app.id]: 'restart' }));
await api.restartApp(app.id).catch(() => null);
- setTimeout(() => {
- setActionLoading(prev => ({ ...prev, [app.id]: null }));
- fetchApps();
- }, 2000);
+ setActionLoading(prev => ({ ...prev, [app.id]: null }));
};
const handleRefreshConfig = async (app) => {
diff --git a/client/src/pages/Dashboard.jsx b/client/src/pages/Dashboard.jsx
index 1987b144e2..67d0a427d7 100644
--- a/client/src/pages/Dashboard.jsx
+++ b/client/src/pages/Dashboard.jsx
@@ -2,6 +2,7 @@ import { useState, useEffect, useCallback, useMemo } from 'react';
import { Link } from 'react-router-dom';
import AppTile from '../components/AppTile';
import * as api from '../services/api';
+import socket from '../services/socket';
export default function Dashboard() {
const [apps, setApps] = useState([]);
@@ -22,8 +23,16 @@ export default function Dashboard() {
useEffect(() => {
fetchData();
- const interval = setInterval(fetchData, 10000);
- return () => clearInterval(interval);
+
+ // Listen for apps changes via WebSocket instead of polling
+ const handleAppsChanged = () => {
+ fetchData();
+ };
+ socket.on('apps:changed', handleAppsChanged);
+
+ return () => {
+ socket.off('apps:changed', handleAppsChanged);
+ };
}, [fetchData]);
// Memoize derived stats to prevent recalculation on every render
diff --git a/server/routes/apps.js b/server/routes/apps.js
index 9b3a526cc6..cdd1a3afec 100644
--- a/server/routes/apps.js
+++ b/server/routes/apps.js
@@ -2,6 +2,7 @@ import { Router } from 'express';
import { spawn } from 'child_process';
import { existsSync } from 'fs';
import * as appsService from '../services/apps.js';
+import { notifyAppsChanged } from '../services/apps.js';
import * as pm2Service from '../services/pm2.js';
import { logAction } from '../services/history.js';
import { validate, appSchema, appUpdateSchema } from '../lib/validation.js';
@@ -144,6 +145,7 @@ router.post('/:id/start', asyncHandler(async (req, res, next) => {
const allSuccess = Object.values(results).every(r => r.success !== false);
await logAction('start', app.id, app.name, { processNames }, allSuccess);
+ notifyAppsChanged('start');
res.json({ success: true, results });
}));
@@ -166,6 +168,7 @@ router.post('/:id/stop', asyncHandler(async (req, res, next) => {
const allSuccess = Object.values(results).every(r => r.success !== false);
await logAction('stop', app.id, app.name, { processNames: app.pm2ProcessNames }, allSuccess);
+ notifyAppsChanged('stop');
res.json({ success: true, results });
}));
@@ -188,6 +191,7 @@ router.post('/:id/restart', asyncHandler(async (req, res, next) => {
const allSuccess = Object.values(results).every(r => r.success !== false);
await logAction('restart', app.id, app.name, { processNames: app.pm2ProcessNames }, allSuccess);
+ notifyAppsChanged('restart');
res.json({ success: true, results });
}));
diff --git a/server/routes/apps.test.js b/server/routes/apps.test.js
index 7b6060c31c..636485d376 100644
--- a/server/routes/apps.test.js
+++ b/server/routes/apps.test.js
@@ -9,7 +9,8 @@ vi.mock('../services/apps.js', () => ({
getAppById: vi.fn(),
createApp: vi.fn(),
updateApp: vi.fn(),
- deleteApp: vi.fn()
+ deleteApp: vi.fn(),
+ notifyAppsChanged: vi.fn()
}));
vi.mock('../services/pm2.js', () => ({
diff --git a/server/services/apps.js b/server/services/apps.js
index b851a7d642..b40dcd9b32 100644
--- a/server/services/apps.js
+++ b/server/services/apps.js
@@ -3,12 +3,16 @@ import { existsSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import { v4 as uuidv4 } from 'uuid';
+import EventEmitter from 'events';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const DATA_DIR = join(__dirname, '../../data');
const APPS_FILE = join(DATA_DIR, 'apps.json');
+// Event emitter for apps changes
+export const appsEvents = new EventEmitter();
+
// In-memory cache for apps data
let appsCache = null;
let cacheTimestamp = 0;
@@ -67,6 +71,14 @@ export function invalidateCache() {
cacheTimestamp = 0;
}
+/**
+ * Notify clients that apps data has changed
+ * Call this after any operation that modifies app state
+ */
+export function notifyAppsChanged(action = 'update') {
+ appsEvents.emit('changed', { action, timestamp: Date.now() });
+}
+
/**
* Get all apps (injects id from key)
*/
diff --git a/server/services/socket.js b/server/services/socket.js
index edf3827b81..63facc2840 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -1,6 +1,7 @@
import { spawn } from 'child_process';
import { streamDetection } from './streamingDetect.js';
import { cosEvents } from './cos.js';
+import { appsEvents } from './apps.js';
import { errorEvents } from '../lib/errorHandler.js';
import { handleErrorRecovery } from './autoFixer.js';
import * as pm2Standardizer from './pm2Standardizer.js';
@@ -11,6 +12,8 @@ const activeStreams = new Map();
const cosSubscribers = new Set();
// Store error subscribers for auto-fix notifications
const errorSubscribers = new Set();
+// Store io instance for broadcasting
+let ioInstance = null;
export function initSocket(io) {
io.on('connection', (socket) => {
@@ -205,11 +208,17 @@ export function initSocket(io) {
});
});
+ // Store io instance for apps broadcasting
+ ioInstance = io;
+
// Set up CoS event forwarding to subscribers
setupCosEventForwarding();
// Set up error event forwarding to subscribers
setupErrorEventForwarding();
+
+ // Set up apps event forwarding to all clients
+ setupAppsEventForwarding();
}
function cleanupStream(socketId) {
@@ -293,3 +302,12 @@ function setupErrorEventForwarding() {
});
});
}
+
+// Set up apps event forwarding - broadcasts to ALL clients
+function setupAppsEventForwarding() {
+ appsEvents.on('changed', (data) => {
+ if (ioInstance) {
+ ioInstance.emit('apps:changed', data);
+ }
+ });
+}