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

fix: DRY/YAGNI/SOLID audit — fix bugs, eliminate duplication, remove dead code

Adam Eivyd7b1a9fb2344
diff --git a/.changelog/v0.15.x.md b/.changelog/v0.15.x.md
index 82009f155e..9f35ab9629 100644
--- a/.changelog/v0.15.x.md
+++ b/.changelog/v0.15.x.md
@@ -19,6 +19,30 @@ Plan cleanup and documentation reorganization.
- **Added `.catch()` handler** on fire-and-forget `cloneRepoInBackground()` in `brain.js` to prevent unhandled promise rejections
- **Added sensitive output redaction** in `scriptRunner.js` -- env vars containing keys, tokens, passwords, and secrets are now `[REDACTED]` before persisting to `scripts-state.json`
+### Bugs Fixed
+- **Fixed index out of bounds** in `agents.js` Windows process parsing -- checked `parts.length >= 6` but accessed `parts[6]` (needs `>= 7`)
+- **Fixed non-unique React keys** in `UpcomingTasksWidget` -- `task.taskType` isn't unique, now uses compound keys
+- **Fixed missing optional chaining** in `agentTools.js` -- `commentsResponse.comments` would throw if null
+- **Fixed falsy value bug** in `apps.js` routes -- used `||` instead of `??` for PM2 process fallback
+- **Fixed unsafe `JSON.parse`** in `pm2.js` `listProcesses` -- now uses `safeJSONParse` with fallback
+- **Fixed silent error swallowing** in `cos.js` actionable insights -- `Promise.all` catches now log errors
+- **Fixed missing date validation** in `formatters.js` -- `formatTime()` now guards against null/invalid timestamps
+- **Fixed hardcoded localhost** in `vite.config.js` proxy -- now configurable via `VITE_API_HOST` env var
+- **Fixed dependency version mismatches** -- aligned Express, PM2, and portos-ai-toolkit between root and server `package.json`
+- **Removed forbidden `pm2:kill`** npm script that violated project rules
+
+### DRY Refactors
+- **Extracted `spawnPm2Cli` helper** in `pm2.js` -- eliminated 3x duplicated spawn+stderr+close blocks for stop/restart/delete
+- **Extracted `loadApp` middleware** in `apps.js` routes -- eliminated 11 repeated `getAppById` + null check patterns
+- **Used existing `extractJSONArray`/`safeJSONParse`** in `pm2.js` -- removed duplicated JSON extraction logic
+- **Created `useAutoRefetch` hook** -- consolidated identical fetch+interval `useEffect` pattern across 4 dashboard widgets
+- **Extracted `pickScheduleSettings`** in `cos.js` -- eliminated duplicated `if (X !== undefined)` settings pattern
+- **Removed duplicate `.pm2` entry** from `.gitignore`
+
+### YAGNI Cleanup
+- **Deleted 3 dead `.old.js` route files** -- `prompts.old.js`, `providers.old.js`, `runs.old.js`
+- **Removed unused `addAllowedCommand`/`removeAllowedCommand`** from `commands.js` -- never called from any route
+
## Improvements
### Plan & Documentation Cleanup
diff --git a/.gitignore b/.gitignore
index 61c663419e..b389bbc1de 100644
--- a/.gitignore
+++ b/.gitignore
@@ -39,4 +39,3 @@ Thumbs.db
# Browser service node_modules (code is committed)
browser/node_modules/
-.pm2
diff --git a/client/src/components/CosDashboardWidget.jsx b/client/src/components/CosDashboardWidget.jsx
index 7a0295d075..176d50928d 100644
--- a/client/src/components/CosDashboardWidget.jsx
+++ b/client/src/components/CosDashboardWidget.jsx
@@ -1,4 +1,4 @@
-import { useState, useEffect, memo } from 'react';
+import { useState, memo } from 'react';
import { Link } from 'react-router-dom';
import {
CheckCircle,
@@ -15,40 +15,26 @@ import {
Activity
} from 'lucide-react';
import * as api from '../services/api';
+import { useAutoRefetch } from '../hooks/useAutoRefetch';
/**
* CosDashboardWidget - Compact CoS status widget for the main Dashboard
* Shows today's progress, streak status, learning health, CoS running state, and recent tasks
*/
const CosDashboardWidget = memo(function CosDashboardWidget() {
- const [summary, setSummary] = useState(null);
- const [learningSummary, setLearningSummary] = useState(null);
- const [recentTasks, setRecentTasks] = useState(null);
- const [activityCalendar, setActivityCalendar] = useState(null);
- const [loading, setLoading] = useState(true);
- const [tasksExpanded, setTasksExpanded] = useState(false);
-
- useEffect(() => {
- const loadData = async () => {
- const silent = { silent: true };
- const [quickData, learningData, tasksData, calendarData] = await Promise.all([
- api.getCosQuickSummary(silent).catch(() => null),
- api.getCosLearningSummary(silent).catch(() => null),
- api.getCosRecentTasks(5, silent).catch(() => null),
- api.getCosActivityCalendar(8, silent).catch(() => null)
- ]);
- setSummary(quickData);
- setLearningSummary(learningData);
- setRecentTasks(tasksData);
- setActivityCalendar(calendarData);
- setLoading(false);
- };
+ const { data: dashData, loading } = useAutoRefetch(async () => {
+ const silent = { silent: true };
+ const [summary, learningSummary, recentTasks, activityCalendar] = await Promise.all([
+ api.getCosQuickSummary(silent).catch(() => null),
+ api.getCosLearningSummary(silent).catch(() => null),
+ api.getCosRecentTasks(5, silent).catch(() => null),
+ api.getCosActivityCalendar(8, silent).catch(() => null)
+ ]);
+ return { summary, learningSummary, recentTasks, activityCalendar };
+ }, 30000);
- loadData();
- // Refresh every 30 seconds
- const interval = setInterval(loadData, 30000);
- return () => clearInterval(interval);
- }, []);
+ const { summary, learningSummary, recentTasks, activityCalendar } = dashData ?? {};
+ const [tasksExpanded, setTasksExpanded] = useState(false);
// Don't render while loading
if (loading) {
diff --git a/client/src/components/DecisionLogWidget.jsx b/client/src/components/DecisionLogWidget.jsx
index 9c44fae7cc..9e9728c004 100644
--- a/client/src/components/DecisionLogWidget.jsx
+++ b/client/src/components/DecisionLogWidget.jsx
@@ -1,4 +1,4 @@
-import { useState, useEffect, memo } from 'react';
+import { useState, memo } from 'react';
import { Link } from 'react-router-dom';
import {
Eye,
@@ -12,29 +12,19 @@ import {
Zap
} from 'lucide-react';
import * as api from '../services/api';
+import { useAutoRefetch } from '../hooks/useAutoRefetch';
/**
* DecisionLogWidget - Shows transparency into CoS decision-making
* Displays why tasks were skipped, intervals adjusted, or alternatives chosen
*/
const DecisionLogWidget = memo(function DecisionLogWidget() {
- const [summary, setSummary] = useState(null);
- const [loading, setLoading] = useState(true);
+ const { data: summary, loading } = useAutoRefetch(
+ () => api.getCosDecisionSummary({ silent: true }).catch(() => null),
+ 60000
+ );
const [expanded, setExpanded] = useState(false);
- useEffect(() => {
- const loadData = async () => {
- const data = await api.getCosDecisionSummary({ silent: true }).catch(() => null);
- setSummary(data);
- setLoading(false);
- };
-
- loadData();
- // Refresh every 60 seconds
- const interval = setInterval(loadData, 60000);
- return () => clearInterval(interval);
- }, []);
-
// Don't render while loading or if no data
if (loading || !summary) {
return null;
diff --git a/client/src/components/GoalProgressWidget.jsx b/client/src/components/GoalProgressWidget.jsx
index abfd93ed20..3b3ef676fb 100644
--- a/client/src/components/GoalProgressWidget.jsx
+++ b/client/src/components/GoalProgressWidget.jsx
@@ -1,4 +1,4 @@
-import { useState, useEffect, memo } from 'react';
+import { memo } from 'react';
import { Link } from 'react-router-dom';
import {
Target,
@@ -7,27 +7,17 @@ import {
AlertTriangle
} from 'lucide-react';
import * as api from '../services/api';
+import { useAutoRefetch } from '../hooks/useAutoRefetch';
/**
* GoalProgressWidget - Shows progress toward user goals on the dashboard
* Maps completed CoS tasks to goal categories from COS-GOALS.md
*/
const GoalProgressWidget = memo(function GoalProgressWidget() {
- const [progress, setProgress] = useState(null);
- const [loading, setLoading] = useState(true);
-
- useEffect(() => {
- const loadData = async () => {
- const data = await api.getCosGoalProgressSummary({ silent: true }).catch(() => null);
- setProgress(data);
- setLoading(false);
- };
-
- loadData();
- // Refresh every 60 seconds
- const interval = setInterval(loadData, 60000);
- return () => clearInterval(interval);
- }, []);
+ const { data: progress, loading } = useAutoRefetch(
+ () => api.getCosGoalProgressSummary({ silent: true }).catch(() => null),
+ 60000
+ );
// Don't render while loading or if no goals
if (loading || !progress?.goals?.length) {
diff --git a/client/src/components/UpcomingTasksWidget.jsx b/client/src/components/UpcomingTasksWidget.jsx
index a38065c03b..984e40447d 100644
--- a/client/src/components/UpcomingTasksWidget.jsx
+++ b/client/src/components/UpcomingTasksWidget.jsx
@@ -1,4 +1,4 @@
-import { useState, useEffect, memo } from 'react';
+import { memo } from 'react';
import { Link } from 'react-router-dom';
import {
Clock,
@@ -10,30 +10,20 @@ import {
Sparkles
} from 'lucide-react';
import * as api from '../services/api';
+import { useAutoRefetch } from '../hooks/useAutoRefetch';
/**
* UpcomingTasksWidget - Shows a preview of upcoming scheduled tasks
* Helps users understand what the CoS will work on next
*/
const UpcomingTasksWidget = memo(function UpcomingTasksWidget() {
- const [upcoming, setUpcoming] = useState([]);
- const [loading, setLoading] = useState(true);
-
- useEffect(() => {
- const loadData = async () => {
- const data = await api.getCosUpcomingTasks(6).catch(() => []);
- setUpcoming(data);
- setLoading(false);
- };
-
- loadData();
- // Refresh every 60 seconds
- const interval = setInterval(loadData, 60000);
- return () => clearInterval(interval);
- }, []);
+ const { data: upcoming, loading } = useAutoRefetch(
+ () => api.getCosUpcomingTasks(6).catch(() => []),
+ 60000
+ );
// Don't render while loading or if no upcoming tasks
- if (loading || !upcoming.length) {
+ if (loading || !upcoming?.length) {
return null;
}
@@ -103,9 +93,9 @@ const UpcomingTasksWidget = memo(function UpcomingTasksWidget() {
{/* Task List */}
<div className="space-y-2">
{/* Ready Tasks */}
- {readyTasks.slice(0, 3).map((task) => (
+ {readyTasks.slice(0, 3).map((task, index) => (
<div
- key={task.taskType}
+ key={`${task.taskType}-ready-${index}`}
className="flex items-center gap-3 p-2 rounded-lg bg-port-success/10 border border-port-success/20"
>
<span className="text-lg flex-shrink-0" aria-hidden="true">
@@ -150,9 +140,9 @@ const UpcomingTasksWidget = memo(function UpcomingTasksWidget() {
))}
{/* Scheduled Tasks */}
- {scheduledTasks.slice(0, readyTasks.length > 0 ? 2 : 4).map((task) => (
+ {scheduledTasks.slice(0, readyTasks.length > 0 ? 2 : 4).map((task, index) => (
<div
- key={task.taskType}
+ key={`${task.taskType}-scheduled-${index}`}
className="flex items-center gap-3 p-2 rounded-lg bg-port-bg/50"
>
<span className="text-lg flex-shrink-0 opacity-60" aria-hidden="true">
diff --git a/client/src/hooks/useAutoRefetch.js b/client/src/hooks/useAutoRefetch.js
new file mode 100644
index 0000000000..933e582144
--- /dev/null
+++ b/client/src/hooks/useAutoRefetch.js
@@ -0,0 +1,28 @@
+import { useState, useEffect } from 'react';
+
+/**
+ * Hook for auto-refetching data on an interval.
+ * Eliminates the repeated useEffect + setInterval pattern across dashboard widgets.
+ *
+ * @param {Function} fetchFn - Async function that returns data (should handle its own errors)
+ * @param {number} intervalMs - Refetch interval in milliseconds
+ * @returns {{ data: any, loading: boolean }}
+ */
+export function useAutoRefetch(fetchFn, intervalMs) {
+ const [data, setData] = useState(null);
+ const [loading, setLoading] = useState(true);
+
+ useEffect(() => {
+ const loadData = async () => {
+ const result = await fetchFn();
+ setData(result);
+ setLoading(false);
+ };
+
+ loadData();
+ const interval = setInterval(loadData, intervalMs);
+ return () => clearInterval(interval);
+ }, []); // eslint-disable-line react-hooks/exhaustive-deps
+
+ return { data, loading };
+}
diff --git a/client/src/utils/formatters.js b/client/src/utils/formatters.js
index a5fc80f7cf..3893c7505d 100644
--- a/client/src/utils/formatters.js
+++ b/client/src/utils/formatters.js
@@ -9,7 +9,9 @@
* @returns {string} Formatted relative time (e.g., "Just now", "5m ago", "2h ago")
*/
export function formatTime(timestamp) {
+ if (!timestamp) return 'Unknown';
const date = new Date(timestamp);
+ if (isNaN(date.getTime())) return 'Invalid date';
const now = new Date();
const diff = now - date;
diff --git a/client/vite.config.js b/client/vite.config.js
index 5e8699e008..04bcf071d1 100644
--- a/client/vite.config.js
+++ b/client/vite.config.js
@@ -1,6 +1,9 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
+const API_HOST = process.env.VITE_API_HOST || 'localhost';
+const API_TARGET = `http://${API_HOST}:5554`;
+
export default defineConfig({
plugins: [react()],
server: {
@@ -9,11 +12,11 @@ export default defineConfig({
open: false,
proxy: {
'/api': {
- target: 'http://localhost:5554',
+ target: API_TARGET,
changeOrigin: true
},
'/socket.io': {
- target: 'http://localhost:5554',
+ target: API_TARGET,
changeOrigin: true,
ws: true
}
diff --git a/package.json b/package.json
index 59f492b56f..3f4f652c67 100644
--- a/package.json
+++ b/package.json
@@ -22,7 +22,6 @@
"pm2:restart": "pm2 restart ecosystem.config.cjs",
"pm2:logs": "pm2 logs",
"pm2:status": "pm2 status",
- "pm2:kill": "pm2 kill",
"install:all": "npm install && cd client && npm install && cd ../server && npm install && cd .. && npm run setup",
"setup": "node scripts/setup-data.js && node scripts/setup-browser.js",
"setup:data": "node scripts/setup-data.js",
@@ -35,13 +34,13 @@
"@vitejs/plugin-react": "^4.3.4",
"autoprefixer": "^10.4.20",
"concurrently": "^8.2.2",
- "pm2": "^6.0.14",
+ "pm2": "^5.4.3",
"postcss": "^8.4.49",
"tailwindcss": "^3.4.17",
"vite": "^6.0.6"
},
"dependencies": {
- "express": "^5.2.1",
- "portos-ai-toolkit": "github:atomantic/portos-ai-toolkit#ac13168156f81c90dab57702c0de3f97de7970a9"
+ "express": "^4.21.2",
+ "portos-ai-toolkit": "^0.5.0"
}
}
diff --git a/server/routes/agentTools.js b/server/routes/agentTools.js
index b4bbaa33ad..d72f86989d 100644
--- a/server/routes/agentTools.js
+++ b/server/routes/agentTools.js
@@ -77,7 +77,7 @@ router.post('/generate-comment', asyncHandler(async (req, res) => {
const post = await client.getPost(data.postId);
const commentsResponse = await client.getComments(data.postId);
- const comments = commentsResponse.comments || commentsResponse || [];
+ const comments = commentsResponse?.comments ?? commentsResponse ?? [];
let generated;
if (data.parentId) {
diff --git a/server/routes/apps.js b/server/routes/apps.js
index 33a884c79b..8712fc5332 100644
--- a/server/routes/apps.js
+++ b/server/routes/apps.js
@@ -11,6 +11,19 @@ import { parseEcosystemFromPath } from '../services/streamingDetect.js';
const router = Router();
+/**
+ * Middleware to load app by :id param and attach to req.app
+ * Throws 404 if not found, eliminating repeated null checks across routes
+ */
+const loadApp = asyncHandler(async (req, res, next) => {
+ const app = await appsService.getAppById(req.params.id);
+ if (!app) {
+ throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ req.loadedApp = app;
+ next();
+});
+
// GET /api/apps - List all apps
router.get('/', asyncHandler(async (req, res) => {
const apps = await appsService.getAllApps();
@@ -40,7 +53,7 @@ router.get('/', asyncHandler(async (req, res) => {
const statuses = {};
for (const processName of app.pm2ProcessNames || []) {
const pm2Proc = pm2Map.get(processName);
- statuses[processName] = pm2Proc || { name: processName, status: 'not_found', pm2_env: null };
+ statuses[processName] = pm2Proc ?? { name: processName, status: 'not_found', pm2_env: null };
}
// Compute overall status
@@ -73,12 +86,8 @@ router.get('/', asyncHandler(async (req, res) => {
}));
// GET /api/apps/:id - Get single app
-router.get('/:id', asyncHandler(async (req, res, next) => {
- const app = await appsService.getAppById(req.params.id);
-
- if (!app) {
- throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });
- }
+router.get('/:id', loadApp, asyncHandler(async (req, res) => {
+ const app = req.loadedApp;
// Get PM2 status for each process (using app's custom PM2_HOME if set)
const statuses = {};
@@ -165,11 +174,8 @@ router.post('/:id/unarchive', asyncHandler(async (req, res) => {
}));
// GET /api/apps/:id/task-types - Get per-app task type overrides
-router.get('/:id/task-types', asyncHandler(async (req, res) => {
- const app = await appsService.getAppById(req.params.id);
- if (!app) {
- throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });
- }
+router.get('/:id/task-types', loadApp, asyncHandler(async (req, res) => {
+ const app = req.loadedApp;
res.json({ appId: app.id, appName: app.name, disabledTaskTypes: app.disabledTaskTypes || [] });
}));
@@ -190,12 +196,8 @@ router.put('/:id/task-types/:taskType', asyncHandler(async (req, res) => {
}));
// POST /api/apps/:id/start - Start app via PM2
-router.post('/:id/start', asyncHandler(async (req, res, next) => {
- const app = await appsService.getAppById(req.params.id);
-
- if (!app) {
- throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });
- }
+router.post('/:id/start', loadApp, asyncHandler(async (req, res) => {
+ const app = req.loadedApp;
const processNames = app.pm2ProcessNames || [app.name.toLowerCase().replace(/\s+/g, '-')];
@@ -234,13 +236,8 @@ router.post('/:id/start', asyncHandler(async (req, res, next) => {
}));
// POST /api/apps/:id/stop - Stop app
-router.post('/:id/stop', asyncHandler(async (req, res, next) => {
- const app = await appsService.getAppById(req.params.id);
-
- if (!app) {
- throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });
- }
-
+router.post('/:id/stop', loadApp, asyncHandler(async (req, res) => {
+ const app = req.loadedApp;
const results = {};
for (const name of app.pm2ProcessNames || []) {
@@ -257,13 +254,8 @@ router.post('/:id/stop', asyncHandler(async (req, res, next) => {
}));
// POST /api/apps/:id/restart - Restart app
-router.post('/:id/restart', asyncHandler(async (req, res, next) => {
- const app = await appsService.getAppById(req.params.id);
-
- if (!app) {
- throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });
- }
-
+router.post('/:id/restart', loadApp, asyncHandler(async (req, res) => {
+ const app = req.loadedApp;
const results = {};
for (const name of app.pm2ProcessNames || []) {
@@ -280,13 +272,8 @@ router.post('/:id/restart', asyncHandler(async (req, res, next) => {
}));
// GET /api/apps/:id/status - Get PM2 status
-router.get('/:id/status', asyncHandler(async (req, res, next) => {
- const app = await appsService.getAppById(req.params.id);
-
- if (!app) {
- throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });
- }
-
+router.get('/:id/status', loadApp, asyncHandler(async (req, res) => {
+ const app = req.loadedApp;
const statuses = {};
for (const name of app.pm2ProcessNames || []) {
@@ -299,13 +286,8 @@ router.get('/:id/status', asyncHandler(async (req, res, next) => {
}));
// GET /api/apps/:id/logs - Get logs
-router.get('/:id/logs', asyncHandler(async (req, res, next) => {
- const app = await appsService.getAppById(req.params.id);
-
- if (!app) {
- throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });
- }
-
+router.get('/:id/logs', loadApp, asyncHandler(async (req, res) => {
+ const app = req.loadedApp;
const lines = parseInt(req.query.lines) || 100;
const processName = req.query.process || app.pm2ProcessNames?.[0];
@@ -343,12 +325,8 @@ const ALLOWED_EDITORS = new Set([
]);
// POST /api/apps/:id/open-editor - Open app in editor
-router.post('/:id/open-editor', asyncHandler(async (req, res, next) => {
- const app = await appsService.getAppById(req.params.id);
-
- if (!app) {
- throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });
- }
+router.post('/:id/open-editor', loadApp, asyncHandler(async (req, res) => {
+ const app = req.loadedApp;
if (!existsSync(app.repoPath)) {
throw new ServerError('App path does not exist', { status: 400, code: 'PATH_NOT_FOUND' });
@@ -391,12 +369,8 @@ router.post('/:id/open-editor', asyncHandler(async (req, res, next) => {
}));
// POST /api/apps/:id/open-folder - Open app folder in file manager
-router.post('/:id/open-folder', asyncHandler(async (req, res, next) => {
- const app = await appsService.getAppById(req.params.id);
-
- if (!app) {
- throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });
- }
+router.post('/:id/open-folder', loadApp, asyncHandler(async (req, res) => {
+ const app = req.loadedApp;
if (!existsSync(app.repoPath)) {
throw new ServerError('App path does not exist', { status: 400, code: 'PATH_NOT_FOUND' });
@@ -427,12 +401,8 @@ router.post('/:id/open-folder', asyncHandler(async (req, res, next) => {
}));
// POST /api/apps/:id/refresh-config - Re-parse ecosystem config for PM2 processes
-router.post('/:id/refresh-config', asyncHandler(async (req, res, next) => {
- const app = await appsService.getAppById(req.params.id);
-
- if (!app) {
- throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });
- }
+router.post('/:id/refresh-config', loadApp, asyncHandler(async (req, res) => {
+ const app = req.loadedApp;
if (!existsSync(app.repoPath)) {
throw new ServerError('App path does not exist', { status: 400, code: 'PATH_NOT_FOUND' });
diff --git a/server/routes/cos.js b/server/routes/cos.js
index 146a49476c..87c4fc39aa 100644
--- a/server/routes/cos.js
+++ b/server/routes/cos.js
@@ -19,6 +19,19 @@ import { asyncHandler, ServerError } from '../lib/errorHandler.js';
const router = Router();
+const SCHEDULE_FIELDS = ['type', 'enabled', 'intervalMs', 'providerId', 'model', 'prompt'];
+
+/**
+ * Pick only defined values from body for schedule settings updates
+ */
+function pickScheduleSettings(body) {
+ const settings = {};
+ for (const key of SCHEDULE_FIELDS) {
+ if (body[key] !== undefined) settings[key] = body[key];
+ }
+ return settings;
+}
+
// GET /api/cos - Get CoS status
router.get('/', asyncHandler(async (req, res) => {
const status = await cos.getStatus();
@@ -586,17 +599,7 @@ router.get('/schedule/self-improvement/:taskType', asyncHandler(async (req, res)
// PUT /api/cos/schedule/self-improvement/:taskType - Update interval for self-improvement task
router.put('/schedule/self-improvement/:taskType', asyncHandler(async (req, res) => {
const { taskType } = req.params;
- const { type, enabled, intervalMs, providerId, model, prompt } = req.body;
-
- const settings = {};
- if (type !== undefined) settings.type = type;
- if (enabled !== undefined) settings.enabled = enabled;
- if (intervalMs !== undefined) settings.intervalMs = intervalMs;
- if (providerId !== undefined) settings.providerId = providerId;
- if (model !== undefined) settings.model = model;
- if (prompt !== undefined) settings.prompt = prompt;
-
- const result = await taskSchedule.updateSelfImprovementInterval(taskType, settings);
+ const result = await taskSchedule.updateSelfImprovementInterval(taskType, pickScheduleSettings(req.body));
res.json({ success: true, taskType, interval: result });
}));
@@ -610,17 +613,7 @@ router.get('/schedule/app-improvement/:taskType', asyncHandler(async (req, res)
// PUT /api/cos/schedule/app-improvement/:taskType - Update interval for app improvement task
router.put('/schedule/app-improvement/:taskType', asyncHandler(async (req, res) => {
const { taskType } = req.params;
- const { type, enabled, intervalMs, providerId, model, prompt } = req.body;
-
- const settings = {};
- if (type !== undefined) settings.type = type;
- if (enabled !== undefined) settings.enabled = enabled;
- if (intervalMs !== undefined) settings.intervalMs = intervalMs;
- if (providerId !== undefined) settings.providerId = providerId;
- if (model !== undefined) settings.model = model;
- if (prompt !== undefined) settings.prompt = prompt;
-
- const result = await taskSchedule.updateAppImprovementInterval(taskType, settings);
+ const result = await taskSchedule.updateAppImprovementInterval(taskType, pickScheduleSettings(req.body));
res.json({ success: true, taskType, interval: result });
}));
@@ -937,9 +930,9 @@ router.get('/productivity/calendar', asyncHandler(async (req, res) => {
// Surfaces the most important things to address right now across all CoS subsystems
router.get('/actionable-insights', asyncHandler(async (req, res) => {
const [tasksData, learningSummary, healthCheck, notificationsModule] = await Promise.all([
- cos.getAllTasks().catch(() => ({ user: null, cos: null })),
- taskLearning.getLearningInsights().catch(() => null),
- cos.runHealthCheck().catch(() => ({ issues: [] })),
+ cos.getAllTasks().catch(err => { console.error(`❌ Failed to load tasks: ${err.message}`); return { user: null, cos: null }; }),
+ taskLearning.getLearningInsights().catch(err => { console.error(`❌ Failed to load learning insights: ${err.message}`); return null; }),
+ cos.runHealthCheck().catch(err => { console.error(`❌ Failed to run health check: ${err.message}`); return { issues: [] }; }),
import('../services/notifications.js')
]);
diff --git a/server/routes/prompts.old.js b/server/routes/prompts.old.js
deleted file mode 100644
index 9c96ebbbde..0000000000
--- a/server/routes/prompts.old.js
+++ /dev/null
@@ -1,87 +0,0 @@
-import { Router } from 'express';
-import * as promptService from '../services/promptService.js';
-import { asyncHandler, ServerError } from '../lib/errorHandler.js';
-
-const router = Router();
-
-// GET /api/prompts - List all stages
-router.get('/', asyncHandler(async (req, res) => {
- const stages = promptService.getStages();
- res.json({ stages });
-}));
-
-// GET /api/prompts/variables - List all variables
-router.get('/variables', asyncHandler(async (req, res) => {
- const variables = promptService.getVariables();
- res.json({ variables });
-}));
-
-// GET /api/prompts/variables/:key - Get a variable
-router.get('/variables/:key', asyncHandler(async (req, res) => {
- const variable = promptService.getVariable(req.params.key);
- if (!variable) {
- throw new ServerError('Variable not found', { status: 404, code: 'NOT_FOUND' });
- }
- res.json({ key: req.params.key, ...variable });
-}));
-
-// POST /api/prompts/variables - Create a variable
-router.post('/variables', asyncHandler(async (req, res) => {
- const { key, name, category, content } = req.body;
- if (!key || !content) {
- throw new ServerError('key and content are required', { status: 400, code: 'VALIDATION_ERROR' });
- }
- await promptService.createVariable(key, { name, category, content });
- res.json({ success: true, key });
-}));
-
-// PUT /api/prompts/variables/:key - Update a variable
-router.put('/variables/:key', asyncHandler(async (req, res) => {
- const { name, category, content } = req.body;
- await promptService.updateVariable(req.params.key, { name, category, content });
- res.json({ success: true });
-}));
-
-// DELETE /api/prompts/variables/:key - Delete a variable
-router.delete('/variables/:key', asyncHandler(async (req, res) => {
- await promptService.deleteVariable(req.params.key);
- res.json({ success: true });
-}));
-
-// GET /api/prompts/:stage - Get stage with template
-router.get('/:stage', asyncHandler(async (req, res) => {
- const stage = promptService.getStage(req.params.stage);
- if (!stage) {
- throw new ServerError('Stage not found', { status: 404, code: 'NOT_FOUND' });
- }
- const template = await promptService.getStageTemplate(req.params.stage);
- res.json({ ...stage, template });
-}));
-
-// PUT /api/prompts/:stage - Update stage config and/or template
-router.put('/:stage', asyncHandler(async (req, res) => {
- const { template, ...config } = req.body;
-
- if (Object.keys(config).length > 0) {
- await promptService.updateStageConfig(req.params.stage, config);
- }
- if (template !== undefined) {
- await promptService.updateStageTemplate(req.params.stage, template);
- }
- res.json({ success: true });
-}));
-
-// POST /api/prompts/:stage/preview - Preview compiled prompt
-router.post('/:stage/preview', asyncHandler(async (req, res) => {
- const { testData = {} } = req.body;
- const preview = await promptService.previewPrompt(req.params.stage, testData);
- res.json({ preview });
-}));
-
-// POST /api/prompts/reload - Reload prompts from disk
-router.post('/reload', asyncHandler(async (req, res) => {
- await promptService.loadPrompts();
- res.json({ success: true });
-}));
-
-export default router;
diff --git a/server/routes/providers.old.js b/server/routes/providers.old.js
deleted file mode 100644
index eb10ae4beb..0000000000
--- a/server/routes/providers.old.js
+++ /dev/null
@@ -1,134 +0,0 @@
-import { Router } from 'express';
-import { asyncHandler, ServerError } from '../lib/errorHandler.js';
-import * as providers from '../services/providers.js';
-import { testVision, runVisionTestSuite, checkVisionHealth } from '../services/visionTest.js';
-
-const router = Router();
-
-// GET /api/providers - List all providers
-router.get('/', asyncHandler(async (req, res) => {
- const data = await providers.getAllProviders();
- res.json(data);
-}));
-
-// GET /api/providers/active - Get active provider
-router.get('/active', asyncHandler(async (req, res) => {
- const provider = await providers.getActiveProvider();
- res.json(provider);
-}));
-
-// PUT /api/providers/active - Set active provider
-router.put('/active', asyncHandler(async (req, res) => {
- const { id } = req.body;
- if (!id) {
- throw new ServerError('Provider ID required', { status: 400, code: 'MISSING_ID' });
- }
-
- const provider = await providers.setActiveProvider(id);
-
- if (!provider) {
- throw new ServerError('Provider not found', { status: 404, code: 'NOT_FOUND' });
- }
-
- res.json(provider);
-}));
-
-// GET /api/providers/:id - Get provider by ID
-router.get('/:id', asyncHandler(async (req, res) => {
- const provider = await providers.getProviderById(req.params.id);
-
- if (!provider) {
- throw new ServerError('Provider not found', { status: 404, code: 'NOT_FOUND' });
- }
-
- res.json(provider);
-}));
-
-// POST /api/providers - Create new provider
-router.post('/', asyncHandler(async (req, res) => {
- const { name, type } = req.body;
-
- if (!name) {
- throw new ServerError('Name is required', { status: 400, code: 'VALIDATION_ERROR' });
- }
-
- if (!type || !['cli', 'api'].includes(type)) {
- throw new ServerError('Type must be "cli" or "api"', { status: 400, code: 'VALIDATION_ERROR' });
- }
-
- const provider = await providers.createProvider(req.body);
- res.status(201).json(provider);
-}));
-
-// PUT /api/providers/:id - Update provider
-router.put('/:id', asyncHandler(async (req, res) => {
- const provider = await providers.updateProvider(req.params.id, req.body);
-
- if (!provider) {
- throw new ServerError('Provider not found', { status: 404, code: 'NOT_FOUND' });
- }
-
- res.json(provider);
-}));
-
-// DELETE /api/providers/:id - Delete provider
-router.delete('/:id', asyncHandler(async (req, res) => {
- const deleted = await providers.deleteProvider(req.params.id);
-
- if (!deleted) {
- throw new ServerError('Provider not found', { status: 404, code: 'NOT_FOUND' });
- }
-
- res.status(204).send();
-}));
-
-// POST /api/providers/:id/test - Test provider connectivity
-router.post('/:id/test', asyncHandler(async (req, res) => {
- const result = await providers.testProvider(req.params.id);
- res.json(result);
-}));
-
-// POST /api/providers/:id/refresh-models - Refresh models for API provider
-router.post('/:id/refresh-models', asyncHandler(async (req, res) => {
- const provider = await providers.refreshProviderModels(req.params.id);
-
- if (!provider) {
- throw new ServerError('Provider not found or not an API type', { status: 404, code: 'NOT_FOUND' });
- }
-
- res.json(provider);
-}));
-
-// GET /api/providers/:id/vision-health - Check vision capability health
-router.get('/:id/vision-health', asyncHandler(async (req, res) => {
- const result = await checkVisionHealth(req.params.id);
- res.json(result);
-}));
-
-// POST /api/providers/:id/test-vision - Test vision with a specific image
-router.post('/:id/test-vision', asyncHandler(async (req, res) => {
- const { imagePath, prompt, expectedContent, model } = req.body;
-
- if (!imagePath) {
- throw new ServerError('imagePath is required', { status: 400, code: 'VALIDATION_ERROR' });
- }
-
- const result = await testVision({
- imagePath,
- prompt: prompt || 'Describe what you see in this image.',
- expectedContent: expectedContent || [],
- providerId: req.params.id,
- model
- });
-
- res.json(result);
-}));
-
-// POST /api/providers/:id/vision-suite - Run full vision test suite
-router.post('/:id/vision-suite', asyncHandler(async (req, res) => {
- const { model } = req.body;
- const result = await runVisionTestSuite(req.params.id, model);
- res.json(result);
-}));
-
-export default router;
diff --git a/server/routes/runs.old.js b/server/routes/runs.old.js
deleted file mode 100644
index bd7a500882..0000000000
--- a/server/routes/runs.old.js
+++ /dev/null
@@ -1,191 +0,0 @@
-import { Router } from 'express';
-import * as runner from '../services/runner.js';
-import { asyncHandler, ServerError } from '../lib/errorHandler.js';
-
-const router = Router();
-
-// GET /api/runs - List runs
-// Query params: limit, offset, source (all|devtools|cos-agent)
-router.get('/', asyncHandler(async (req, res, next) => {
- const limit = parseInt(req.query.limit) || 50;
- const offset = parseInt(req.query.offset) || 0;
- const source = req.query.source || 'all'; // all, devtools, cos-agent
-
- const result = await runner.listRuns(limit, offset, source);
- res.json(result);
-}));
-
-// POST /api/runs - Create and execute a new run
-router.post('/', asyncHandler(async (req, res, next) => {
- const { providerId, model, prompt, workspacePath, workspaceName, timeout, screenshots } = req.body;
- console.log(`🚀 POST /api/runs - provider: ${providerId}, model: ${model}, workspace: ${workspaceName}, timeout: ${timeout}ms, screenshots: ${screenshots?.length || 0}`);
-
- if (!providerId) {
- throw new ServerError('providerId is required', {
- status: 400,
- code: 'VALIDATION_ERROR'
- });
- }
-
- if (!prompt) {
- throw new ServerError('prompt is required', {
- status: 400,
- code: 'VALIDATION_ERROR'
- });
- }
-
- const runData = await runner.createRun({
- providerId,
- model,
- prompt,
- workspacePath,
- workspaceName,
- timeout,
- screenshots
- });
-
- const { runId, provider, metadata, timeout: effectiveTimeout } = runData;
- const io = req.app.get('io');
- console.log(`🚀 Run created: ${runId}, provider type: ${provider.type}, command: ${provider.command}, timeout: ${effectiveTimeout}ms`);
-
- // Execute based on provider type
- if (provider.type === 'cli') {
- console.log(`🚀 Executing CLI run: ${provider.command} with args: ${JSON.stringify(provider.args)}`);
- runner.executeCliRun(
- runId,
- provider,
- prompt,
- workspacePath,
- (data) => {
- // Stream output via Socket.IO
- console.log(`📤 Emitting run:${runId}:data (${data.length} chars)`);
- io?.emit(`run:${runId}:data`, data);
- },
- (finalMetadata) => {
- console.log(`✅ Run complete: ${runId}, success: ${finalMetadata.success}`);
- io?.emit(`run:${runId}:complete`, finalMetadata);
- },
- effectiveTimeout
- );
- } else if (provider.type === 'api') {
- runner.executeApiRun(
- runId,
- provider,
- model,
- prompt,
- workspacePath,
- screenshots,
- (data) => {
- io?.emit(`run:${runId}:data`, data);
- },
- (finalMetadata) => {
- io?.emit(`run:${runId}:complete`, finalMetadata);
- }
- );
- }
-
- // Return immediately with run ID
- res.status(202).json({
- runId,
- status: 'started',
- metadata
- });
-}));
-
-// GET /api/runs/:id - Get run metadata
-router.get('/:id', asyncHandler(async (req, res, next) => {
- const metadata = await runner.getRun(req.params.id);
-
- if (!metadata) {
- throw new ServerError('Run not found', {
- status: 404,
- code: 'NOT_FOUND'
- });
- }
-
- const isActive = await runner.isRunActive(req.params.id);
- res.json({
- ...metadata,
- isActive
- });
-}));
-
-// GET /api/runs/:id/output - Get run output
-router.get('/:id/output', asyncHandler(async (req, res, next) => {
- const output = await runner.getRunOutput(req.params.id);
-
- if (output === null) {
- throw new ServerError('Run not found', {
- status: 404,
- code: 'NOT_FOUND'
- });
- }
-
- res.type('text/plain').send(output);
-}));
-
-// GET /api/runs/:id/prompt - Get run prompt
-router.get('/:id/prompt', asyncHandler(async (req, res, next) => {
- const prompt = await runner.getRunPrompt(req.params.id);
-
- if (prompt === null) {
- throw new ServerError('Run not found', {
- status: 404,
- code: 'NOT_FOUND'
- });
- }
-
- res.type('text/plain').send(prompt);
-}));
-
-// POST /api/runs/:id/stop - Stop a running execution
-router.post('/:id/stop', asyncHandler(async (req, res, next) => {
- const stopped = await runner.stopRun(req.params.id);
-
- if (!stopped) {
- throw new ServerError('Run not found or not active', {
- status: 404,
- code: 'NOT_ACTIVE'
- });
- }
-
- res.json({ stopped: true });
-}));
-
-// DELETE /api/runs/:id - Delete run and artifacts
-router.delete('/:id', asyncHandler(async (req, res, next) => {
- // Don't allow deleting active runs
- const isActive = await runner.isRunActive(req.params.id);
- if (isActive) {
- throw new ServerError('Cannot delete active run', {
- status: 409,
- code: 'RUN_ACTIVE'
- });
- }
-
- const deleted = await runner.deleteRun(req.params.id);
-
- if (!deleted) {
- throw new ServerError('Run not found', {
- status: 404,
- code: 'NOT_FOUND'
- });
- }
-
- res.status(204).send();
-}));
-
-// DELETE /api/runs - Delete all failed runs
-// Requires ?confirm=true query parameter to prevent accidental deletion
-router.delete('/', asyncHandler(async (req, res, next) => {
- if (req.query.confirm !== 'true') {
- throw new ServerError('Destructive operation requires ?confirm=true', {
- status: 400,
- code: 'CONFIRMATION_REQUIRED'
- });
- }
- const deletedCount = await runner.deleteFailedRuns();
- res.json({ deleted: deletedCount });
-}));
-
-export default router;
diff --git a/server/services/agents.js b/server/services/agents.js
index 0b502dbb27..eebce97809 100644
--- a/server/services/agents.js
+++ b/server/services/agents.js
@@ -181,7 +181,7 @@ async function findWindowsProcesses(pattern) {
// Skip header line
for (let i = 1; i < lines.length; i++) {
const parts = lines[i].split(',');
- if (parts.length >= 6) {
+ if (parts.length >= 7) {
const command = parts[1];
const creationDate = parts[2];
const ppid = parseInt(parts[3]);
diff --git a/server/services/commands.js b/server/services/commands.js
index 53848dccaa..4fda189d5d 100644
--- a/server/services/commands.js
+++ b/server/services/commands.js
@@ -147,22 +147,3 @@ export function getAllowedCommands() {
return Array.from(ALLOWED_COMMANDS).sort();
}
-/**
- * Add a command to the allowlist (runtime only)
- */
-export function addAllowedCommand(command) {
- ALLOWED_COMMANDS.add(command);
-}
-
-/**
- * Remove a command from the allowlist (runtime only)
- */
-export function removeAllowedCommand(command) {
- // Don't allow removing core commands
- const core = ['npm', 'node', 'git', 'pm2'];
- if (core.includes(command)) {
- return false;
- }
- ALLOWED_COMMANDS.delete(command);
- return true;
-}
diff --git a/server/services/pm2.js b/server/services/pm2.js
index fc09c29ab6..091cfc047b 100644
--- a/server/services/pm2.js
+++ b/server/services/pm2.js
@@ -1,6 +1,7 @@
import pm2 from 'pm2';
import { spawn } from 'child_process';
import { existsSync } from 'fs';
+import { extractJSONArray, safeJSONParse } from '../lib/fileUtils.js';
/**
* Build environment object with optional custom PM2_HOME
@@ -18,6 +19,29 @@ function buildEnv(pm2Home) {
return env;
}
+/**
+ * Spawn a PM2 CLI command with optional custom PM2_HOME
+ * @param {string} action PM2 action (stop, restart, delete)
+ * @param {string} name PM2 process name
+ * @param {string} pm2Home Optional custom PM2_HOME path
+ * @returns {Promise<{success: boolean}>}
+ */
+function spawnPm2Cli(action, name, pm2Home) {
+ return new Promise((resolve, reject) => {
+ const child = spawn('pm2', [action, name], {
+ shell: false,
+ env: buildEnv(pm2Home)
+ });
+ let stderr = '';
+ child.stderr.on('data', (data) => { stderr += data.toString(); });
+ child.on('close', (code) => {
+ if (code !== 0) return reject(new Error(stderr || `pm2 ${action} exited with code ${code}`));
+ resolve({ success: true });
+ });
+ child.on('error', reject);
+ });
+}
+
/**
* Connect to PM2 daemon and run an action
* Note: This uses the default PM2_HOME. For custom PM2_HOME, use CLI commands.
@@ -75,19 +99,7 @@ export async function startApp(name, options = {}) {
export async function stopApp(name, pm2Home = null) {
// Use CLI for custom PM2_HOME
if (pm2Home) {
- return new Promise((resolve, reject) => {
- const child = spawn('pm2', ['stop', name], {
- shell: false,
- env: buildEnv(pm2Home)
- });
- let stderr = '';
- child.stderr.on('data', (data) => { stderr += data.toString(); });
- child.on('close', (code) => {
- if (code !== 0) return reject(new Error(stderr || `pm2 stop exited with code ${code}`));
- resolve({ success: true });
- });
- child.on('error', reject);
- });
+ return spawnPm2Cli('stop', name, pm2Home);
}
return connectAndRun((pm2) => {
@@ -108,19 +120,7 @@ export async function stopApp(name, pm2Home = null) {
export async function restartApp(name, pm2Home = null) {
// Use CLI for custom PM2_HOME
if (pm2Home) {
- return new Promise((resolve, reject) => {
- const child = spawn('pm2', ['restart', name], {
- shell: false,
- env: buildEnv(pm2Home)
- });
- let stderr = '';
- child.stderr.on('data', (data) => { stderr += data.toString(); });
- child.on('close', (code) => {
- if (code !== 0) return reject(new Error(stderr || `pm2 restart exited with code ${code}`));
- resolve({ success: true });
- });
- child.on('error', reject);
- });
+ return spawnPm2Cli('restart', name, pm2Home);
}
return connectAndRun((pm2) => {
@@ -141,19 +141,7 @@ export async function restartApp(name, pm2Home = null) {
export async function deleteApp(name, pm2Home = null) {
// Use CLI for custom PM2_HOME
if (pm2Home) {
- return new Promise((resolve, reject) => {
- const child = spawn('pm2', ['delete', name], {
- shell: false,
- env: buildEnv(pm2Home)
- });
- let stderr = '';
- child.stderr.on('data', (data) => { stderr += data.toString(); });
- child.on('close', (code) => {
- if (code !== 0) return reject(new Error(stderr || `pm2 delete exited with code ${code}`));
- resolve({ success: true });
- });
- child.on('error', reject);
- });
+ return spawnPm2Cli('delete', name, pm2Home);
}
return connectAndRun((pm2) => {
@@ -184,18 +172,7 @@ export async function getAppStatus(name, pm2Home = null) {
});
child.on('close', () => {
- // pm2 jlist may output ANSI codes and warnings before JSON
- let jsonStart = stdout.indexOf('[{');
- if (jsonStart < 0) {
- jsonStart = stdout.lastIndexOf('[]');
- }
- const pm2Json = jsonStart >= 0 ? stdout.slice(jsonStart) : '[]';
- let processes;
- try {
- processes = JSON.parse(pm2Json);
- } catch {
- return resolve({ name, status: 'error', pm2_env: null });
- }
+ const processes = safeJSONParse(extractJSONArray(stdout), []);
const proc = processes.find(p => p.name === name);
if (!proc) {
@@ -242,15 +219,7 @@ export async function listProcesses(pm2Home = null) {
});
child.on('close', () => {
- // pm2 jlist may output ANSI codes and warnings before JSON
- // Look for '[{' (array with objects) or '[]' (empty array) to avoid matching ANSI codes like [31m
- let jsonStart = stdout.indexOf('[{');
- if (jsonStart < 0) {
- const emptyMatch = stdout.match(/\[\](?![0-9])/);
- jsonStart = emptyMatch ? stdout.indexOf(emptyMatch[0]) : -1;
- }
- const pm2Json = jsonStart >= 0 ? stdout.slice(jsonStart) : '[]';
- const list = JSON.parse(pm2Json);
+ const list = safeJSONParse(extractJSONArray(stdout), []);
const processes = list.map(proc => ({
name: proc.name,
status: proc.pm2_env?.status || 'unknown',