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

quality: add Zod validation, NaN guards, and silent-catch logging

[._.]/ Adam Eivy51cd311304bd
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index 0ac686f4fb..ebe11fccf6 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -382,9 +382,11 @@ export default function Layout() {
const [sidebarApps, setSidebarApps] = useState([]);
useEffect(() => {
const fetchApps = () => {
- api.getApps().then(apps => {
+ api.getApps({ silent: true }).then(apps => {
setSidebarApps((apps || []).filter(a => !a.archived).sort((a, b) => a.name.localeCompare(b.name)));
- }).catch(() => {});
+ }).catch((err) => {
+ console.warn(`⚠️ Layout: getApps refresh failed: ${err?.message || err}`);
+ });
};
fetchApps();
socket.on('apps:changed', fetchApps);
diff --git a/client/src/services/apiApps.js b/client/src/services/apiApps.js
index 719bf49c35..8994d79531 100644
--- a/client/src/services/apiApps.js
+++ b/client/src/services/apiApps.js
@@ -2,7 +2,7 @@ import toast from '../components/ui/Toast';
import { request, API_BASE } from './apiCore.js';
// Apps
-export const getApps = () => request('/apps');
+export const getApps = (options) => request('/apps', options);
export const getApp = (id) => request(`/apps/${id}`);
export const createApp = (data) => request('/apps', {
method: 'POST',
diff --git a/server/lib/validation.js b/server/lib/validation.js
index af13e211d9..16aa3085af 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -534,6 +534,121 @@ export const searchQuerySchema = z.object({
q: z.string().min(2).max(200).trim()
});
+// =============================================================================
+// COS TASK SCHEMAS
+// =============================================================================
+
+export const createCosTaskSchema = z.object({
+ description: z.string().min(1),
+ priority: z.string().optional(),
+ context: z.string().optional(),
+ model: z.string().optional(),
+ provider: z.string().optional(),
+ app: z.string().optional(),
+ type: z.string().optional().default('user'),
+ approvalRequired: z.boolean().optional(),
+ screenshots: z.array(z.string()).optional(),
+ attachments: z.array(z.string()).optional(),
+ position: z.enum(['top', 'bottom']).optional().default('bottom'),
+ createJiraTicket: z.preprocess(
+ v => v === 'true' ? true : v === 'false' ? false : v,
+ z.boolean().optional()
+ ),
+ jiraTicketId: z.string().optional(),
+ jiraTicketUrl: z.string().optional(),
+ useWorktree: z.preprocess(
+ v => v === 'true' ? true : v === 'false' ? false : v,
+ z.boolean().optional()
+ ),
+ openPR: z.preprocess(
+ v => v === 'true' ? true : v === 'false' ? false : v,
+ z.boolean().optional()
+ ),
+ simplify: z.preprocess(
+ v => v === 'true' ? true : v === 'false' ? false : v,
+ z.boolean().optional()
+ ),
+ reviewLoop: z.preprocess(
+ v => v === 'true' ? true : v === 'false' ? false : v,
+ z.boolean().optional()
+ ),
+});
+
+export const updateCosTaskSchema = z.object({
+ description: z.string().min(1).optional(),
+ priority: z.string().optional(),
+ status: z.string().optional(),
+ context: z.string().optional(),
+ model: z.string().optional(),
+ provider: z.string().optional(),
+ app: z.string().optional(),
+ blockedReason: z.string().optional(),
+ type: z.string().optional().default('user'),
+});
+
+// =============================================================================
+// LOOP SCHEMAS
+// =============================================================================
+
+export const createLoopSchema = z.object({
+ prompt: z.string().min(1),
+ interval: z.union([z.string().min(1), z.number().positive()]),
+ name: z.string().optional(),
+ cwd: z.string().optional(),
+ providerId: z.preprocess(v => v === '' ? undefined : v, z.string().optional()),
+ timeout: z.number().positive().optional(),
+ runImmediately: z.boolean().optional(),
+});
+
+// =============================================================================
+// COS JOB SCHEMAS
+// =============================================================================
+
+export const createCosJobSchema = z.object({
+ name: z.string().min(1),
+ description: z.string().optional(),
+ category: z.string().optional(),
+ type: z.enum(['agent', 'shell', 'script']).optional(),
+ interval: z.string().optional(),
+ intervalMs: z.number().positive().int().optional(),
+ scheduledTime: z.string().optional(),
+ cronExpression: z.string().optional(),
+ enabled: z.boolean().optional(),
+ priority: z.string().optional(),
+ autonomyLevel: z.enum(['full', 'supervised', 'manual']).optional(),
+ promptTemplate: z.string().optional(),
+ command: z.string().optional(),
+ triggerAction: z.preprocess(v => v === '' ? undefined : v, z.string().optional()),
+});
+
+export const updateCosJobSchema = createCosJobSchema.partial().extend({
+ weekdaysOnly: z.boolean().optional(),
+});
+
+// =============================================================================
+// COS LEARNING SCHEMAS
+// =============================================================================
+
+export const recordLearningInsightSchema = z.object({
+ type: z.string().optional(),
+ message: z.string().min(1),
+ taskType: z.string().optional(),
+ context: z.record(z.unknown()).optional(),
+});
+
+export const dismissRecommendationSchema = z.object({
+ id: z.string().min(1),
+ snapshot: z.unknown().optional(),
+});
+
+export const restoreRecommendationSchema = z.object({
+ id: z.string().min(1),
+});
+
+export const generateWeeklyDigestSchema = z.object({
+ weekId: z.string().optional(),
+});
+
// =============================================================================
// BACKUP SCHEMAS
// =============================================================================
@@ -1213,3 +1328,15 @@ export const importerCommitSchema = z.object({
// Defaults to false to preserve the additive merge behavior.
replaceMode: z.boolean().optional().default(false),
}).strict();
+
+// =============================================================================
+// PIPELINE ISSUE QUERY SCHEMAS
+// =============================================================================
+
+// Query params for GET /api/pipeline/series/:id/issues — both are optional;
+// when either is present the route returns { items, total, offset, limit }
+// instead of the legacy raw array so callers can page large series.
+export const issuesListQuerySchema = z.object({
+ offset: z.preprocess((v) => (v === undefined ? 0 : Number(v)), z.number().int().min(0)).default(0),
+ limit: z.preprocess((v) => (v === undefined ? 1000 : Number(v)), z.number().int().min(1).max(1000)).default(1000),
+});
diff --git a/server/routes/agents.js b/server/routes/agents.js
index bff98d8fa1..5de71d3557 100644
--- a/server/routes/agents.js
+++ b/server/routes/agents.js
@@ -13,6 +13,7 @@ router.get('/', asyncHandler(async (req, res) => {
// GET /api/agents/:pid - Get specific process info
router.get('/:pid', asyncHandler(async (req, res) => {
const pid = parseInt(req.params.pid, 10);
+ if (Number.isNaN(pid)) throw new ServerError('Invalid PID', { status: 400, code: 'INVALID_PARAM' });
const info = await getProcessInfo(pid);
if (!info) {
throw new ServerError('Process not found', { status: 404, code: 'NOT_FOUND' });
@@ -23,6 +24,7 @@ router.get('/:pid', asyncHandler(async (req, res) => {
// DELETE /api/agents/:pid - Kill a process
router.delete('/:pid', asyncHandler(async (req, res) => {
const pid = parseInt(req.params.pid, 10);
+ if (Number.isNaN(pid)) throw new ServerError('Invalid PID', { status: 400, code: 'INVALID_PARAM' });
await killProcess(pid);
res.json({ success: true, pid });
}));
diff --git a/server/routes/cosJobRoutes.js b/server/routes/cosJobRoutes.js
index 0a94eb12fd..c4521d4967 100644
--- a/server/routes/cosJobRoutes.js
+++ b/server/routes/cosJobRoutes.js
@@ -7,7 +7,8 @@ import * as cos from '../services/cos.js';
import * as autonomousJobs from '../services/autonomousJobs.js';
import { checkJobGate, hasGate, getRegisteredGates } from '../services/jobGates.js';
import { parseCronToNextRun } from '../services/eventScheduler.js';
-import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import { asyncHandler, ServerError, failValidation } from '../lib/errorHandler.js';
+import { createCosJobSchema, updateCosJobSchema } from '../lib/validation.js';
const router = Router();
@@ -69,15 +70,10 @@ router.get('/jobs/:id', asyncHandler(async (req, res) => {
// POST /api/cos/jobs - Create a new autonomous job
router.post('/jobs', asyncHandler(async (req, res) => {
- const { name, description, category, type, interval, intervalMs, scheduledTime, cronExpression, enabled, priority, autonomyLevel, promptTemplate, command, triggerAction } = req.body;
+ const parsedJob = createCosJobSchema.safeParse(req.body);
+ if (!parsedJob.success) failValidation(parsedJob);
+ const { name, description, category, type, interval, intervalMs, scheduledTime, cronExpression, enabled, priority, autonomyLevel, promptTemplate, command, triggerAction } = parsedJob.data;
- const VALID_JOB_TYPES = ['agent', 'shell', 'script'];
- if (!name) {
- throw new ServerError('name is required', { status: 400, code: 'VALIDATION_ERROR' });
- }
- if (type && !VALID_JOB_TYPES.includes(type)) {
- throw new ServerError(`Invalid job type: ${type}. Must be one of: ${VALID_JOB_TYPES.join(', ')}`, { status: 400, code: 'VALIDATION_ERROR' });
- }
if (type === 'shell' && !command?.trim()) {
throw new ServerError('command is required for shell jobs', { status: 400, code: 'VALIDATION_ERROR' });
}
@@ -111,8 +107,10 @@ router.post('/jobs', asyncHandler(async (req, res) => {
// PUT /api/cos/jobs/:id - Update a job
router.put('/jobs/:id', asyncHandler(async (req, res) => {
+ const parsedJobUpdate = updateCosJobSchema.safeParse(req.body);
+ if (!parsedJobUpdate.success) failValidation(parsedJobUpdate);
const { name, description, category, type, interval, intervalMs, scheduledTime, cronExpression,
- enabled, priority, autonomyLevel, promptTemplate, command, triggerAction, weekdaysOnly } = req.body;
+ enabled, priority, autonomyLevel, promptTemplate, command, triggerAction, weekdaysOnly } = parsedJobUpdate.data;
if (cronExpression) {
const parts = cronExpression.trim().split(/\s+/);
if (parts.length !== 5) {
diff --git a/server/routes/cosLearningRoutes.js b/server/routes/cosLearningRoutes.js
index 47f341b995..950b36122c 100644
--- a/server/routes/cosLearningRoutes.js
+++ b/server/routes/cosLearningRoutes.js
@@ -6,7 +6,13 @@ import { Router } from 'express';
import * as taskLearning from '../services/taskLearning.js';
import * as weeklyDigest from '../services/weeklyDigest.js';
import { loadState } from '../services/cosState.js';
-import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import { asyncHandler, ServerError, failValidation } from '../lib/errorHandler.js';
+import {
+ recordLearningInsightSchema,
+ dismissRecommendationSchema,
+ restoreRecommendationSchema,
+ generateWeeklyDigestSchema,
+} from '../lib/validation.js';
const router = Router();
@@ -93,10 +99,9 @@ router.get('/learning/insights', asyncHandler(async (req, res) => {
// POST /api/cos/learning/insights - Record a learning insight
router.post('/learning/insights', asyncHandler(async (req, res) => {
- const { type, message, taskType, context } = req.body;
- if (!message) {
- throw new ServerError('Insight message is required', { status: 400, code: 'VALIDATION_ERROR' });
- }
+ const parsedInsight = recordLearningInsightSchema.safeParse(req.body);
+ if (!parsedInsight.success) failValidation(parsedInsight);
+ const { type, message, taskType, context } = parsedInsight.data;
const insight = await taskLearning.recordLearningInsight({
type: type || 'observation',
message,
@@ -129,20 +134,18 @@ router.get('/learning/recommendations/dismissed', asyncHandler(async (req, res)
// POST /api/cos/learning/recommendations/dismiss - Dismiss an AI recommendation
router.post('/learning/recommendations/dismiss', asyncHandler(async (req, res) => {
- const { id, snapshot } = req.body || {};
- if (!id || typeof id !== 'string') {
- throw new ServerError('Recommendation id is required', { status: 400, code: 'VALIDATION_ERROR' });
- }
+ const parsedDismiss = dismissRecommendationSchema.safeParse(req.body || {});
+ if (!parsedDismiss.success) failValidation(parsedDismiss);
+ const { id, snapshot } = parsedDismiss.data;
const result = await taskLearning.dismissRecommendation(id, snapshot ?? null);
res.json(result);
}));
// POST /api/cos/learning/recommendations/restore - Restore a dismissed recommendation
router.post('/learning/recommendations/restore', asyncHandler(async (req, res) => {
- const { id } = req.body || {};
- if (!id || typeof id !== 'string') {
- throw new ServerError('Recommendation id is required', { status: 400, code: 'VALIDATION_ERROR' });
- }
+ const parsedRestore = restoreRecommendationSchema.safeParse(req.body || {});
+ if (!parsedRestore.success) failValidation(parsedRestore);
+ const { id } = parsedRestore.data;
const result = await taskLearning.restoreRecommendation(id);
res.json(result);
}));
@@ -252,7 +255,9 @@ router.get('/digest/:weekId', asyncHandler(async (req, res) => {
// POST /api/cos/digest/generate - Force generate digest for a week
router.post('/digest/generate', asyncHandler(async (req, res) => {
- const { weekId } = req.body;
+ const parsedDigest = generateWeeklyDigestSchema.safeParse(req.body || {});
+ if (!parsedDigest.success) failValidation(parsedDigest);
+ const { weekId } = parsedDigest.data;
const digest = await weeklyDigest.generateWeeklyDigest(weekId || null);
res.json(digest);
}));
diff --git a/server/routes/cosTaskRoutes.js b/server/routes/cosTaskRoutes.js
index 3de5c656a7..46e2679ce1 100644
--- a/server/routes/cosTaskRoutes.js
+++ b/server/routes/cosTaskRoutes.js
@@ -7,7 +7,8 @@ import * as cos from '../services/cos.js';
import * as taskWatcher from '../services/taskWatcher.js';
import { enhanceTaskPrompt } from '../services/taskEnhancer.js';
import { loadSlashdoCommand } from '../services/subAgentSpawner.js';
-import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import { asyncHandler, ServerError, failValidation } from '../lib/errorHandler.js';
+import { createCosTaskSchema, updateCosTaskSchema } from '../lib/validation.js';
const SLASHDO_COMMANDS = {
push: { label: 'Push', description: 'Commit and push all work with changelog' },
@@ -98,15 +99,9 @@ router.post('/tasks/slashdo', asyncHandler(async (req, res) => {
// POST /api/cos/tasks - Add a new task
router.post('/tasks', asyncHandler(async (req, res) => {
- const { description, priority, context, model, provider, app, type = 'user', approvalRequired, screenshots, attachments, position = 'bottom', createJiraTicket, jiraTicketId, jiraTicketUrl, useWorktree, openPR, simplify, reviewLoop } = req.body;
-
- if (!description) {
- throw new ServerError('Description is required', { status: 400, code: 'VALIDATION_ERROR' });
- }
-
- // Coerce boolean flags — values from req.body may arrive as strings like 'false' (truthy in JS)
- const toBool = (v) => v === true || v === 'true' ? true : v === false || v === 'false' ? false : undefined;
- const taskData = { description, priority, context, model, provider, app, approvalRequired, screenshots, attachments, position, createJiraTicket: toBool(createJiraTicket), jiraTicketId, jiraTicketUrl, useWorktree: toBool(useWorktree), openPR: toBool(openPR), simplify: toBool(simplify), reviewLoop: toBool(reviewLoop) };
+ const parsed = createCosTaskSchema.safeParse(req.body);
+ if (!parsed.success) failValidation(parsed);
+ const { type, ...taskData } = parsed.data;
const result = await cos.addTask(taskData, type);
if (result?.duplicate) {
@@ -119,19 +114,21 @@ router.post('/tasks', asyncHandler(async (req, res) => {
// PUT /api/cos/tasks/:id - Update a task
router.put('/tasks/:id', asyncHandler(async (req, res) => {
const { id } = req.params;
- const { description, priority, status, context, model, provider, app, blockedReason, type = 'user' } = req.body;
+ const parsedUpdate = updateCosTaskSchema.safeParse(req.body);
+ if (!parsedUpdate.success) failValidation(parsedUpdate);
+ const { type, blockedReason, ...fields } = parsedUpdate.data;
const updates = {};
- if (description !== undefined) updates.description = description;
- if (priority !== undefined) updates.priority = priority;
- if (status !== undefined) updates.status = status;
- if (context !== undefined) updates.context = context;
- if (model !== undefined) updates.model = model;
- if (provider !== undefined) updates.provider = provider;
- if (app !== undefined) updates.app = app;
+ if (fields.description !== undefined) updates.description = fields.description;
+ if (fields.priority !== undefined) updates.priority = fields.priority;
+ if (fields.status !== undefined) updates.status = fields.status;
+ if (fields.context !== undefined) updates.context = fields.context;
+ if (fields.model !== undefined) updates.model = fields.model;
+ if (fields.provider !== undefined) updates.provider = fields.provider;
+ if (fields.app !== undefined) updates.app = fields.app;
// Set blocker metadata when marking as blocked
- if (status === 'blocked' && blockedReason) {
+ if (fields.status === 'blocked' && blockedReason) {
updates.metadata = { blocker: blockedReason };
}
diff --git a/server/routes/loops.js b/server/routes/loops.js
index 18ea13d6a3..0075dba478 100644
--- a/server/routes/loops.js
+++ b/server/routes/loops.js
@@ -1,6 +1,7 @@
import { Router } from 'express';
-import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import { asyncHandler, ServerError, failValidation } from '../lib/errorHandler.js';
import * as loopsService from '../services/loops.js';
+import { createLoopSchema } from '../lib/validation.js';
const router = Router();
@@ -25,25 +26,9 @@ router.get('/:id', asyncHandler(async (req, res) => {
// POST /api/loops
router.post('/', asyncHandler(async (req, res) => {
- const { prompt, interval, name, cwd, providerId, timeout, runImmediately } = req.body;
- if (!prompt || typeof prompt !== 'string') throw new ServerError('Prompt is required', { status: 400, code: 'VALIDATION_ERROR' });
- if (!interval) throw new ServerError('Interval is required', { status: 400, code: 'VALIDATION_ERROR' });
- if (typeof interval !== 'string' && typeof interval !== 'number') {
- throw new ServerError('Interval must be a string (e.g. "30s", "5m") or number of milliseconds', { status: 400, code: 'VALIDATION_ERROR' });
- }
- if (timeout !== undefined && typeof timeout !== 'number') {
- throw new ServerError('Timeout must be a number of milliseconds', { status: 400, code: 'VALIDATION_ERROR' });
- }
- if (name !== undefined && typeof name !== 'string') {
- throw new ServerError('Name must be a string', { status: 400, code: 'VALIDATION_ERROR' });
- }
- if (cwd !== undefined && typeof cwd !== 'string') {
- throw new ServerError('cwd must be a string', { status: 400, code: 'VALIDATION_ERROR' });
- }
- if (providerId !== undefined && typeof providerId !== 'string') {
- throw new ServerError('providerId must be a string', { status: 400, code: 'VALIDATION_ERROR' });
- }
-
+ const parsedLoop = createLoopSchema.safeParse(req.body);
+ if (!parsedLoop.success) failValidation(parsedLoop);
+ const { prompt, interval, name, cwd, providerId, timeout, runImmediately } = parsedLoop.data;
const loop = await loopsService.createLoop({
prompt, interval, name, cwd, providerId, timeout,
runImmediately: runImmediately !== false