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
refactor: dedupe cron validation, name magic numbers, reuse shared JSON reader
Adam Eivy6619cc47d9cb
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdnew file mode 100644index 0000000000..f9eedc3358--- /dev/null+++ b/.changelog/NEXT.md@@ -0,0 +1,5 @@+## Changed++- Code quality: extracted the duplicated cron-expression validation in `cosJobRoutes.js` (job create/update) into a single `validateCronExpression()` helper, and unified the two slightly-divergent error messages.+- Code quality: replaced inline `8000` / `8` / `4` / `20 * 1024 * 1024` literals in the image-generation routes with named constants (`MAX_PROMPT_LENGTH`, `MAX_LORAS`, `MAX_REFERENCE_IMAGES`, `MAX_IMAGE_UPLOAD_BYTES`); the `referenceImageN` upload field list now derives from `MAX_REFERENCE_IMAGES` so it can't drift.+- Code quality: replaced the local `safeReadJson` reimplementation in `apps.js` with the shared `readJSONFile` helper from `fileUtils.js`, and named the repeated `1500` ms inter-action throttle in `agentActionExecutor.js` as `INTER_ACTION_DELAY_MS`.diff --git a/server/routes/apps.js b/server/routes/apps.jsindex 1424244878..653d829a47 100644--- a/server/routes/apps.js+++ b/server/routes/apps.js@@ -2,7 +2,7 @@ import { Router } from 'express';import { spawn } from 'child_process';import { readFile, writeFile, stat, access, mkdir } from 'fs/promises';import { join, resolve, extname } from 'path';-import { PATHS, tryReadFile } from '../lib/fileUtils.js';+import { PATHS, tryReadFile, readJSONFile, safeJSONParse } from '../lib/fileUtils.js';import * as appsService from '../services/apps.js';import { notifyAppsChanged, PORTOS_APP_ID } from '../services/apps.js';import * as pm2Service from '../services/pm2.js';@@ -15,7 +15,6 @@ import { validateRequest, appSchema, appUpdateSchema, sanitizeTaskMetadata } froimport * as git from '../services/git.js';import { parseCronToNextRun } from '../services/eventScheduler.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';-import { safeJSONParse } from '../lib/fileUtils.js';import { parseEcosystemFromPath, usesPm2 } from '../services/streamingDetect.js';import { detectAppIcon, getIconContentType, isUsableSvg } from '../services/appIconDetect.js';import { hasDeployScript } from '../services/appDeployer.js';@@ -37,9 +36,6 @@ function deriveUiPort(uiPort, apiPort, devUiPort) {return uiPort;}-/** Read and parse a JSON file, returning null on any failure (missing file, bad JSON, etc.) */-const safeReadJson = (path) => readFile(path, 'utf-8').then(JSON.parse).catch(() => null);-/*** Middleware to load app by :id param and attach to req.loadedApp* Throws 404 if not found, eliminating repeated null checks across routes@@ -187,7 +183,7 @@ router.get('/:id', loadApp, asyncHandler(async (req, res) => {// Read version from app's package.json if availablelet appVersion = null;if (app.repoPath) {- const pkg = await safeReadJson(join(app.repoPath, 'package.json'));+ const pkg = await readJSONFile(join(app.repoPath, 'package.json'), null, { logError: false });appVersion = pkg?.version || null;}diff --git a/server/routes/cosJobRoutes.js b/server/routes/cosJobRoutes.jsindex 3e18677691..ee682c6eef 100644--- a/server/routes/cosJobRoutes.js+++ b/server/routes/cosJobRoutes.js@@ -12,6 +12,24 @@ import { createCosJobSchema, updateCosJobSchema } from '../lib/validation.js';const router = Router();+// Validate a 5-field cron expression for job create/update. Throws a 400+// ServerError on a malformed field count or an unparseable expression.+function validateCronExpression(cronExpression) {+ const parts = cronExpression.trim().split(/\s+/);+ if (parts.length !== 5) {+ throw new ServerError('cronExpression must be a 5-field cron expression (minute hour dayOfMonth month dayOfWeek)', { status: 400, code: 'VALIDATION_ERROR' });+ }+ let nextRun;+ try {+ nextRun = parseCronToNextRun(cronExpression, new Date(), 'UTC');+ } catch (err) {+ throw new ServerError(`Invalid cronExpression: ${err?.message || 'unable to parse'}`, { status: 400, code: 'VALIDATION_ERROR' });+ }+ if (nextRun === null) {+ throw new ServerError('Invalid cronExpression: no valid run time could be determined', { status: 400, code: 'VALIDATION_ERROR' });+ }+}+// GET /api/cos/jobs - Get all autonomous jobsrouter.get('/jobs', asyncHandler(async (req, res) => {const jobs = await autonomousJobs.getAllJobs();@@ -83,19 +101,7 @@ router.post('/jobs', asyncHandler(async (req, res) => {}}if (cronExpression) {- const parts = cronExpression.trim().split(/\s+/);- if (parts.length !== 5) {- throw new ServerError('cronExpression must be a 5-field cron expression (minute hour dayOfMonth month dayOfWeek)', { status: 400, code: 'VALIDATION_ERROR' });- }- let nextRun;- try {- nextRun = parseCronToNextRun(cronExpression, new Date(), 'UTC');- } catch (err) {- throw new ServerError(`Invalid cronExpression: ${err?.message || 'unable to parse'}`, { status: 400, code: 'VALIDATION_ERROR' });- }- if (nextRun === null) {- throw new ServerError('Invalid cronExpression: no valid run time could be determined', { status: 400, code: 'VALIDATION_ERROR' });- }+ validateCronExpression(cronExpression);}const job = await autonomousJobs.createJob({@@ -112,19 +118,7 @@ router.put('/jobs/:id', asyncHandler(async (req, res) => {const { name, description, category, type, interval, intervalMs, scheduledTime, cronExpression,enabled, priority, autonomyLevel, promptTemplate, command, triggerAction, weekdaysOnly, appId, taskMetadata } = parsedJobUpdate.data;if (cronExpression) {- const parts = cronExpression.trim().split(/\s+/);- if (parts.length !== 5) {- throw new ServerError('cronExpression must be a 5-field cron expression', { status: 400, code: 'VALIDATION_ERROR' });- }- let nextRun;- try {- nextRun = parseCronToNextRun(cronExpression, new Date(), 'UTC');- } catch (err) {- throw new ServerError(`Invalid cronExpression: ${err?.message || 'unable to parse'}`, { status: 400, code: 'VALIDATION_ERROR' });- }- if (nextRun === null) {- throw new ServerError('Invalid cronExpression: no valid run time could be determined', { status: 400, code: 'VALIDATION_ERROR' });- }+ validateCronExpression(cronExpression);}const job = await autonomousJobs.updateJob(req.params.id, {name, description, category, type, interval, intervalMs, scheduledTime, cronExpression,diff --git a/server/routes/imageGen.js b/server/routes/imageGen.jsindex 1c4b3dff52..d21c449f91 100644--- a/server/routes/imageGen.js+++ b/server/routes/imageGen.js@@ -49,14 +49,21 @@ import { itemKey } from '../lib/mediaItemKey.js';const router = Router();+// Shared validation limits. MAX_REFERENCE_IMAGES must stay in sync with the+// number of `referenceImageN` upload field names below.+const MAX_PROMPT_LENGTH = 8000;+const MAX_LORAS = 8;+const MAX_REFERENCE_IMAGES = 4;+const MAX_IMAGE_UPLOAD_BYTES = 20 * 1024 * 1024;+router.get('/style-presets', (_req, res) => res.json(STYLE_PRESETS));const generateSchema = z.object({// Empty prompt allowed — i2i / edit / unconditional generation don't require// one. The multipart FormData builder drops empty-string fields, so an empty// prompt arrives as `undefined`; default it to '' rather than rejecting.- prompt: z.string().max(8000).optional().default(''),- negativePrompt: z.string().max(8000).optional(),+ prompt: z.string().max(MAX_PROMPT_LENGTH).optional().default(''),+ negativePrompt: z.string().max(MAX_PROMPT_LENGTH).optional(),// Per-request backend override. If omitted, the dispatcher uses// `imageGen.mode` from settings.json.mode: z.enum(IMAGE_GEN_MODES).optional(),@@ -72,9 +79,9 @@ const generateSchema = z.object({// Filenames only (basenames) — server resolves against PATHS.loras and// applies the prefix-check. Old payloads sent absolute server paths// (`loraPaths`); accept both for back-compat with stored gallery sidecars.- loraFilenames: z.array(z.string().max(256).regex(/^[^/\\]+$/, 'lora filename must not contain path separators')).max(8).optional(),- loraPaths: z.array(z.string().max(512)).max(8).optional(),- loraScales: z.array(z.number().min(0).max(2)).max(8).optional(),+ loraFilenames: z.array(z.string().max(256).regex(/^[^/\\]+$/, 'lora filename must not contain path separators')).max(MAX_LORAS).optional(),+ loraPaths: z.array(z.string().max(512)).max(MAX_LORAS).optional(),+ loraScales: z.array(z.number().min(0).max(2)).max(MAX_LORAS).optional(),// i2i: pick an existing gallery image (basename) as the init image. If// initImage was uploaded via multipart, this is ignored in favor of the// upload. Strength: 0.0 = ignore source, 1.0 = max influence.@@ -86,7 +93,7 @@ const generateSchema = z.object({// reference, 1.0 = full influence). The schema only constrains the strengths// array — file presence is enforced at the upload layer, and the route// pairs filled slots with their strengths positionally.- referenceStrengths: z.array(z.number().min(0).max(1)).max(4).optional(),+ referenceStrengths: z.array(z.number().min(0).max(1)).max(MAX_REFERENCE_IMAGES).optional(),// Per-render override of the cleaners. When omitted, the route inherits// from `settings.imageGen.{mode}.{cleanC2PA,denoise}`. Explicit booleans// here force the value for this one render. Legacy `autoClean` is still@@ -109,11 +116,11 @@ const MIME_TO_EXT = { 'image/png': '.png', 'image/jpeg': '.jpg', 'image/webp': '// Multi-reference editing accepts up to 4 references on dedicated field names.// The legacy single `initImage` upload (mflux i2i) stays on its own slot so a// FLUX.2 multi-ref upload and an mflux i2i upload don't collide.-const REFERENCE_IMAGE_FIELDS = ['referenceImage1', 'referenceImage2', 'referenceImage3', 'referenceImage4'];+const REFERENCE_IMAGE_FIELDS = Array.from({ length: MAX_REFERENCE_IMAGES }, (_, i) => `referenceImage${i + 1}`);const IMAGE_UPLOAD_FIELDS = ['initImage', ...REFERENCE_IMAGE_FIELDS];const imageGenUploads = optionalUploadFields(IMAGE_UPLOAD_FIELDS, {- limits: { fileSize: 20 * 1024 * 1024 },+ limits: { fileSize: MAX_IMAGE_UPLOAD_BYTES },fileFilter: (_req, file, cb) => cb(null, ACCEPTED_INIT_IMAGE_MIME.has((file.mimetype || '').toLowerCase())),});@@ -159,7 +166,7 @@ const avatarSchema = z.object({const regenerateSchema = z.object({strength: z.number().min(REGEN_STRENGTH_MIN).max(REGEN_STRENGTH_MAX).optional(),steps: z.number().int().min(1).max(50).optional(),- prompt: z.string().max(8000).optional(),+ prompt: z.string().max(MAX_PROMPT_LENGTH).optional(),// 'flux' (default) = GPU img2img round-trip; 'light' = CPU-only spatial pass// for installs without a FLUX runner (strength/steps/prompt ignored).method: z.enum(['flux', 'light']).optional(),diff --git a/server/services/agentActionExecutor.js b/server/services/agentActionExecutor.jsindex 2d6904314f..92b0366e85 100644--- a/server/services/agentActionExecutor.js+++ b/server/services/agentActionExecutor.js@@ -17,6 +17,10 @@ import { findRelevantPosts, findReplyOpportunities } from './agentFeedFilter.js'const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));+// Throttle between successive platform writes (votes/comments/replies) so a+// single agent run doesn't burst the platform API.+const INTER_ACTION_DELAY_MS = 1500;+/*** Execute an action based on type*/@@ -248,7 +252,7 @@ async function executeEngage(client, agent, params) {});if (suspended) break;votes.push({ postId: post.id, title: post.title });- await delay(1500);+ await delay(INTER_ACTION_DELAY_MS);}// Comment on best matches@@ -276,7 +280,7 @@ async function executeEngage(client, agent, params) {postTitle: opportunity.post.title,reason: opportunity.reason});- await delay(1500);+ await delay(INTER_ACTION_DELAY_MS);}}@@ -352,7 +356,7 @@ async function executeMonitor(client, agent, schedule, params) {});if (suspended) break;upvoted.push({ commentId: comment.id, postId, postTitle: post.title });- await delay(1500);+ await delay(INTER_ACTION_DELAY_MS);}}@@ -369,7 +373,7 @@ async function executeMonitor(client, agent, schedule, params) {postId,postTitle: post.title});- await delay(1500);+ await delay(INTER_ACTION_DELAY_MS);}}@@ -549,7 +553,7 @@ async function executeMoltworldInteract(client, account, params) {// Optionally buildif (params.buildType) {- await delay(1500);+ await delay(INTER_ACTION_DELAY_MS);const buildResult = await client.build({x,y,