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
address review: fix cron scheduling, timezone handling, and error resilience
Adam Eivyf11dfe1a40e7
diff --git a/client/src/pages/CharacterSheet.jsx b/client/src/pages/CharacterSheet.jsxindex d9d4f3627c..5fc3ab5026 100644--- a/client/src/pages/CharacterSheet.jsx+++ b/client/src/pages/CharacterSheet.jsx@@ -5,11 +5,21 @@ import {} from 'lucide-react';import { timeAgo } from '../utils/formatters';-const request = (endpoint, options = {}) =>- fetch(`/api/character${endpoint}`, {+const request = async (endpoint, options = {}) => {+ const response = await fetch(`/api/character${endpoint}`, {headers: { 'Content-Type': 'application/json', ...options.headers },...options- }).then(r => r.json());+ });+ let data = null;+ try { data = await response.json(); } catch { /* non-JSON body */ }+ if (!response.ok) {+ const message = data?.message || `Request failed with status ${response.status}`;+ const error = new Error(message);+ error.status = response.status;+ throw error;+ }+ return data;+};const get = () => request('');const post = (path, body) => request(path, { method: 'POST', body: JSON.stringify(body) });diff --git a/client/src/pages/Settings.jsx b/client/src/pages/Settings.jsxindex 4997b9d2f2..a51bcfd0c7 100644--- a/client/src/pages/Settings.jsx+++ b/client/src/pages/Settings.jsx@@ -786,11 +786,32 @@ function GeneralTab() {}, []);const handleSave = async (tz) => {+ const tzToSave = tz || detectedTz;+ if (!tzToSave) {+ toast.error('Timezone is required.');+ return;+ }++ // Validate timezone string+ let isValid = false;+ if (allTimezones.length > 0) {+ isValid = allTimezones.includes(tzToSave);+ } else {+ try {+ new Intl.DateTimeFormat('en-US', { timeZone: tzToSave });+ isValid = true;+ } catch { isValid = false; }+ }+ if (!isValid) {+ toast.error('Invalid timezone. Please select a valid IANA timezone.');+ return;+ }+setSaving(true);- await updateSettings({ timezone: tz })+ await updateSettings({ timezone: tzToSave }).then(() => {- setTimezone(tz);- toast.success(`Timezone set to ${tz}`);+ setTimezone(tzToSave);+ toast.success(`Timezone set to ${tzToSave}`);}).catch(() => toast.error('Failed to save timezone')).finally(() => setSaving(false));@@ -815,7 +836,7 @@ function GeneralTab() {list="tz-list"/><button- onClick={() => handleSave(timezone || detectedTz)}+ onClick={() => handleSave(timezone)}disabled={saving}className="px-4 py-2 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded-lg text-sm transition-colors disabled:opacity-50">diff --git a/server/routes/character.js b/server/routes/character.jsindex c5b59da787..369384f4c6 100644--- a/server/routes/character.js+++ b/server/routes/character.js@@ -35,8 +35,7 @@ const takeRestSchema = z.object({const addEventSchema = z.object({description: z.string().min(1).max(500),xp: z.number().int().min(0).optional(),- diceNotation: z.string().regex(/^\d+d\d+([+-]\d+)?$/).optional(),- damageType: z.string().max(100).optional()+ diceNotation: z.string().regex(/^\d+d\d+([+-]\d+)?$/).optional()});// GET /api/character - Get character sheetdiff --git a/server/routes/cos.js b/server/routes/cos.jsindex c30fa3dada..f68e929e95 100644--- a/server/routes/cos.js+++ b/server/routes/cos.js@@ -18,6 +18,7 @@ import * as goalProgress from '../services/goalProgress.js';import * as decisionLog from '../services/decisionLog.js';import { reinitialize as reinitializeEmbeddings } from '../services/memoryEmbeddings.js';import * as claudeChangelog from '../services/claudeChangelog.js';+import { parseCronToNextRun } from '../services/eventScheduler.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest, sanitizeTaskMetadata } from '../lib/validation.js';import { z } from 'zod';@@ -965,6 +966,10 @@ router.post('/jobs', asyncHandler(async (req, res) => {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' });}+ const nextRun = parseCronToNextRun(cronExpression);+ if (!nextRun) {+ throw new ServerError('Invalid cronExpression: unable to parse next run time', { status: 400, code: 'VALIDATION_ERROR' });+ }}const job = await autonomousJobs.createJob({@@ -978,6 +983,16 @@ router.post('/jobs', asyncHandler(async (req, res) => {router.put('/jobs/:id', asyncHandler(async (req, res) => {const { name, description, category, type, interval, intervalMs, scheduledTime, cronExpression,enabled, priority, autonomyLevel, promptTemplate, command, triggerAction, weekdaysOnly } = req.body;+ 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' });+ }+ const nextRun = parseCronToNextRun(cronExpression);+ if (!nextRun) {+ throw new ServerError('Invalid cronExpression: unable to parse next run time', { status: 400, code: 'VALIDATION_ERROR' });+ }+ }const job = await autonomousJobs.updateJob(req.params.id, {name, description, category, type, interval, intervalMs, scheduledTime, cronExpression,enabled, priority, autonomyLevel, promptTemplate, command, triggerAction, weekdaysOnlydiff --git a/server/services/autonomousJobs.js b/server/services/autonomousJobs.jsindex 418f764cce..822c1b0a48 100644--- a/server/services/autonomousJobs.js+++ b/server/services/autonomousJobs.js@@ -27,6 +27,7 @@ import { checkAndPrompt as autobiographyCheckAndPrompt } from './autobiography.jimport { runGoalCheckIn } from './goalCheckIn.js'import { validateCommand, redactOutput, ALLOWED_COMMANDS_SORTED } from '../lib/commandSecurity.js'import { getUserTimezone, getLocalParts, nextLocalTime } from '../lib/timezone.js'+import { parseCronToNextRun } from './eventScheduler.js'/*** Run the moltworld-explore.mjs script as a child process (no AI agent needed).@@ -629,6 +630,21 @@ async function getDueJobs() {const due = []for (const job of enabledJobs) {+ // Cron-mode jobs: compute next run from cron expression+ if (job.cronExpression) {+ const from = job.lastRun ? new Date(job.lastRun) : new Date(0)+ const next = parseCronToNextRun(job.cronExpression, from, timezone)+ if (!next || next.getTime() > now) continue++ due.push({+ ...job,+ reason: job.lastRun ? 'cron-due' : 'never-run',+ overdueBy: now - next.getTime()+ })+ continue+ }++ // Interval-mode jobsconst lastRun = job.lastRun ? new Date(job.lastRun).getTime() : 0const timeSinceLastRun = now - lastRun@@ -1022,19 +1038,32 @@ async function getNextDueJob() {let earliestTime = Infinityfor (const job of enabledJobs) {- const lastRun = job.lastRun ? new Date(job.lastRun).getTime() : 0- let nextDue = lastRun + job.intervalMs-- // If job has scheduledTime, find next occurrence in user's timezone- if (job.scheduledTime) {- const [hours, minutes] = job.scheduledTime.split(':').map(Number)- const candidate = nextLocalTime(nextDue, hours, minutes, timezone)- if (candidate > nextDue) nextDue = candidate+ let nextDue++ if (job.cronExpression) {+ // Cron-mode: derive next due from cron expression+ const from = job.lastRun ? new Date(job.lastRun) : new Date(0)+ const next = parseCronToNextRun(job.cronExpression, from, timezone)+ if (!next) continue+ nextDue = next.getTime()+ } else {+ // Interval-mode+ const lastRun = job.lastRun ? new Date(job.lastRun).getTime() : 0+ nextDue = lastRun + job.intervalMs++ // If job has scheduledTime, find next occurrence in user's timezone+ if (job.scheduledTime) {+ const [hours, minutes] = job.scheduledTime.split(':').map(Number)+ const candidate = nextLocalTime(nextDue, hours, minutes, timezone)+ if (candidate > nextDue) nextDue = candidate+ }}if (nextDue < earliestTime) {earliestTime = nextDue- const isDue = Date.now() >= nextDue && isScheduledTimeMet(job.scheduledTime, timezone)+ const isDue = job.cronExpression+ ? Date.now() >= nextDue+ : Date.now() >= nextDue && isScheduledTimeMet(job.scheduledTime, timezone)earliest = {jobId: job.id,jobName: job.name,diff --git a/server/services/cos.js b/server/services/cos.jsindex dd7e13d2b5..ee12add2e1 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -3757,7 +3757,14 @@ function computeNextJobFireTime(job, timezone) {if (job.cronExpression) {const from = job.lastRun ? new Date(job.lastRun) : new Date();const next = parseCronToNextRun(job.cronExpression, from, timezone);- return next ? next.getTime() : Date.now() + 60_000;+ if (!next) {+ throw new Error(+ `Invalid cron expression for autonomous job` ++ (job.id ? ` "${job.id}"` : '') ++ `: ${job.cronExpression}`+ );+ }+ return next.getTime();}const lastRun = job.lastRun ? new Date(job.lastRun).getTime() : 0;diff --git a/server/services/portosChangelog.js b/server/services/portosChangelog.jsindex a015123d39..4be21c9159 100644--- a/server/services/portosChangelog.js+++ b/server/services/portosChangelog.js@@ -7,8 +7,8 @@import { execFileSync } from 'child_process';import { writeFile } from 'fs/promises';-import { join } from 'path';-import { readJSONFile, PATHS, DAY } from '../lib/fileUtils.js';+import { join, dirname } from 'path';+import { readJSONFile, ensureDir, PATHS, DAY } from '../lib/fileUtils.js';const STATE_FILE = join(PATHS.data, 'portos-changelog.json');const NUL = '\x00';@@ -32,10 +32,16 @@ export async function getRecentChanges(since) {sinceDate = state.lastBriefedAt || new Date(Date.now() - DAY).toISOString();}- // NUL delimiter avoids breakage from | in commit messages- const raw = execFileSync('git', [- 'log', `--since=${sinceDate}`, '--no-merges', `--format=%H${NUL}%s${NUL}%ai`- ], { cwd: process.cwd(), encoding: 'utf-8', windowsHide: true }).trim();+ let raw;+ try {+ // NUL delimiter avoids breakage from | in commit messages+ raw = execFileSync('git', [+ 'log', `--since=${sinceDate}`, '--no-merges', `--format=%H${NUL}%s${NUL}%ai`+ ], { cwd: process.cwd(), encoding: 'utf-8', windowsHide: true }).trim();+ } catch {+ console.log('📋 PortOS changelog: git not available, skipping');+ return { features: [], fixes: [], other: [], since: sinceDate };+ }if (!raw) {return { features: [], fixes: [], other: [], since: sinceDate };@@ -58,15 +64,22 @@ export async function getRecentChanges(since) {}export async function markBriefed() {- const headCommit = execFileSync('git', ['rev-parse', '--short', 'HEAD'], {- cwd: process.cwd(), encoding: 'utf-8', windowsHide: true- }).trim();+ let headCommit;+ try {+ headCommit = execFileSync('git', ['rev-parse', '--short', 'HEAD'], {+ cwd: process.cwd(), encoding: 'utf-8', windowsHide: true+ }).trim();+ } catch {+ console.log('📋 PortOS changelog: git not available, skipping markBriefed');+ return DEFAULT_STATE;+ }const state = {lastBriefedAt: new Date().toISOString(),lastBriefedCommit: headCommit};+ await ensureDir(dirname(STATE_FILE));await writeFile(STATE_FILE, JSON.stringify(state, null, 2));console.log(`📋 PortOS changelog briefed at ${headCommit}`);return state;diff --git a/server/services/portosChangelog.test.js b/server/services/portosChangelog.test.jsindex 59c59096e8..6c34d16aa6 100644--- a/server/services/portosChangelog.test.js+++ b/server/services/portosChangelog.test.js@@ -12,6 +12,7 @@ vi.mock('fs/promises', () => ({vi.mock('../lib/fileUtils.js', () => ({readJSONFile: vi.fn(),+ ensureDir: vi.fn().mockResolvedValue(undefined),PATHS: { data: '/mock/data' },DAY: 86400000}));diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.jsindex d6a4072d1f..bc9eb3cd28 100644--- a/server/services/taskSchedule.js+++ b/server/services/taskSchedule.js@@ -21,7 +21,7 @@ import { DAY, ensureDir, HOUR, readJSONFile, PATHS, safeDate } from '../lib/fileimport { getAdaptiveCooldownMultiplier } from './taskLearning.js';import { isTaskTypeEnabledForApp, getAppTaskTypeInterval, getActiveApps, getAppTaskTypeOverrides } from './apps.js';import { PORTOS_UI_URL } from '../lib/ports.js';-import { getUserTimezone } from '../lib/timezone.js';+import { getUserTimezone, getLocalParts } from '../lib/timezone.js';import { parseCronToNextRun } from './eventScheduler.js';const DATA_DIR = PATHS.cos;@@ -1233,10 +1233,11 @@ export async function shouldRunTask(taskType, appId = null) {return { shouldRun: false, reason: 'disabled' };}- // Weekday-only tasks skip weekends+ // Weekday-only tasks skip weekends (timezone-aware)if (interval.weekdaysOnly) {- const day = new Date().getDay();- if (day === 0 || day === 6) {+ const timezone = await getUserTimezone();+ const { dayOfWeek } = getLocalParts(new Date(), timezone);+ if (dayOfWeek === 0 || dayOfWeek === 6) {return { shouldRun: false, reason: 'weekday-only' };}}