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 field matching, error handling, and validation robustness
Adam Eivy2035eea7246c
diff --git a/client/src/components/cos/tabs/ScheduleTab.jsx b/client/src/components/cos/tabs/ScheduleTab.jsxindex 14ea014776..91538dceb0 100644--- a/client/src/components/cos/tabs/ScheduleTab.jsx+++ b/client/src/components/cos/tabs/ScheduleTab.jsx@@ -643,7 +643,7 @@ function AppTaskTypeRow({ taskType, config, onUpdate, onTrigger, onReset, provid{enabledCount}/{totalCount} apps</span>)}- <IntervalBadge type={config.type} />+ <IntervalBadge type={config.type} cronExpression={config.cronExpression} /></div></div>diff --git a/client/src/pages/CharacterSheet.jsx b/client/src/pages/CharacterSheet.jsxindex 5fc3ab5026..197a2718c7 100644--- a/client/src/pages/CharacterSheet.jsx+++ b/client/src/pages/CharacterSheet.jsx@@ -3,6 +3,7 @@ import {Sword, Star, Moon, ScrollText, Shield, Heart,Sparkles, RefreshCw, Dices, X, ChevronDown, Zap} from 'lucide-react';+import toast from 'react-hot-toast';import { timeAgo } from '../utils/formatters';const request = async (endpoint, options = {}) => {@@ -64,6 +65,7 @@ function hpColor(pct) {export default function CharacterSheet() {const [char, setChar] = useState(null);const [loading, setLoading] = useState(true);+ const [loadError, setLoadError] = useState(null);const [activeAction, setActiveAction] = useState(null);const [editingName, setEditingName] = useState(false);const [editingClass, setEditingClass] = useState(false);@@ -81,12 +83,21 @@ export default function CharacterSheet() {const [evtDice, setEvtDice] = useState('');const load = useCallback(async () => {- const data = await get().catch(() => null);- if (!data || data.error) return setLoading(false);- setChar(data);- setNameVal(data.name || '');- setClassVal(data.class || '');- setLoading(false);+ setLoadError(null);+ try {+ const data = await get();+ if (!data || data.error) {+ setLoadError('Failed to load character data');+ return;+ }+ setChar(data);+ setNameVal(data.name || '');+ setClassVal(data.class || '');+ } catch (err) {+ setLoadError(err.message || 'Failed to load character data');+ } finally {+ setLoading(false);+ }}, []);useEffect(() => { load(); }, [load]);@@ -96,69 +107,88 @@ export default function CharacterSheet() {};const handleDamage = async () => {- const result = await post('/damage', { diceNotation: dmgDice, description: dmgDesc || undefined });- setChar(result.character);- setActiveAction(null);- setDmgDice('1d6');- setDmgDesc('');+ try {+ const result = await post('/damage', { diceNotation: dmgDice, description: dmgDesc || undefined });+ setChar(result.character);+ setActiveAction(null);+ setDmgDice('1d6');+ setDmgDesc('');+ } catch (err) { toast.error(err.message || 'Failed to apply damage'); }};const handleShortRest = async () => {- const result = await post('/rest', { type: 'short' });- setChar(result.character);+ try {+ const result = await post('/rest', { type: 'short' });+ setChar(result.character);+ } catch (err) { toast.error(err.message || 'Failed to take short rest'); }};const handleLongRest = async () => {- const result = await post('/rest', { type: 'long' });- setChar(result.character);+ try {+ const result = await post('/rest', { type: 'long' });+ setChar(result.character);+ } catch (err) { toast.error(err.message || 'Failed to take long rest'); }};const handleAddXp = async () => {if (!xpAmount) return;- const result = await post('/xp', { amount: Number(xpAmount), source: 'manual', description: xpDesc || undefined });- setChar(result.character);- setActiveAction(null);- setXpAmount('');- setXpDesc('');+ try {+ const result = await post('/xp', { amount: Number(xpAmount), source: 'manual', description: xpDesc || undefined });+ setChar(result.character);+ setActiveAction(null);+ setXpAmount('');+ setXpDesc('');+ } catch (err) { toast.error(err.message || 'Failed to add XP'); }};const handleLogEvent = async () => {if (!evtDesc) return;- const body = { description: evtDesc };- if (evtXp) body.xp = Number(evtXp);- if (evtDice) body.diceNotation = evtDice;- const result = await post('/event', body);- setChar(result.character);- setActiveAction(null);- setEvtDesc('');- setEvtXp('');- setEvtDice('');+ try {+ const body = { description: evtDesc };+ if (evtXp) body.xp = Number(evtXp);+ if (evtDice) body.diceNotation = evtDice;+ const result = await post('/event', body);+ setChar(result.character);+ setActiveAction(null);+ setEvtDesc('');+ setEvtXp('');+ setEvtDice('');+ } catch (err) { toast.error(err.message || 'Failed to log event'); }};const handleSync = async (type) => {setSyncing(type);- const result = await post(`/sync/${type}`, {});- setChar(result.character);- setSyncing(null);+ try {+ const result = await post(`/sync/${type}`, {});+ setChar(result.character);+ } catch (err) {+ toast.error(err.message || `Failed to sync ${type}`);+ } finally {+ setSyncing(null);+ }};const handleNameSave = async () => {- if (nameVal.trim() && nameVal !== char.name) {- const data = await put({ name: nameVal.trim() });- setChar(data);- }+ try {+ if (nameVal.trim() && nameVal !== char.name) {+ const data = await put({ name: nameVal.trim() });+ setChar(data);+ }+ } catch (err) { toast.error(err.message || 'Failed to save name'); }setEditingName(false);};const handleClassSave = async () => {- if (classVal.trim() && classVal !== char.class) {- const data = await put({ class: classVal.trim() });- setChar(data);- }+ try {+ if (classVal.trim() && classVal !== char.class) {+ const data = await put({ class: classVal.trim() });+ setChar(data);+ }+ } catch (err) { toast.error(err.message || 'Failed to save class'); }setEditingClass(false);};- if (loading || !char) {+ if (loading) {return (<div className="h-full flex items-center justify-center text-gray-400"><RefreshCw className="w-6 h-6 animate-spin mr-2" /> Loading character...@@ -166,6 +196,17 @@ export default function CharacterSheet() {);}+ if (loadError || !char) {+ return (+ <div className="h-full flex flex-col items-center justify-center text-gray-400 gap-4">+ <p className="text-port-error">{loadError || 'Failed to load character data'}</p>+ <button onClick={load} className="px-4 py-2 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded-lg text-sm transition-colors">+ Retry+ </button>+ </div>+ );+ }+const hpPct = Math.max(0, Math.min(100, (char.hp / char.maxHp) * 100));const nextLevelXP = xpForNextLevel(char.level);const currentLevelXP = xpForCurrentLevel(char.level);diff --git a/server/routes/cos.js b/server/routes/cos.jsindex f68e929e95..49e6c427f3 100644--- a/server/routes/cos.js+++ b/server/routes/cos.js@@ -966,9 +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);+ // Validate by computing next run within a 90-day window to avoid expensive searches+ const nextRun = parseCronToNextRun(cronExpression, new Date(), 'UTC');if (!nextRun) {- throw new ServerError('Invalid cronExpression: unable to parse next run time', { status: 400, code: 'VALIDATION_ERROR' });+ throw new ServerError('Invalid cronExpression: unable to compute next run time', { status: 400, code: 'VALIDATION_ERROR' });}}@@ -988,9 +989,9 @@ router.put('/jobs/:id', asyncHandler(async (req, res) => {if (parts.length !== 5) {throw new ServerError('cronExpression must be a 5-field cron expression', { status: 400, code: 'VALIDATION_ERROR' });}- const nextRun = parseCronToNextRun(cronExpression);+ const nextRun = parseCronToNextRun(cronExpression, new Date(), 'UTC');if (!nextRun) {- throw new ServerError('Invalid cronExpression: unable to parse next run time', { status: 400, code: 'VALIDATION_ERROR' });+ throw new ServerError('Invalid cronExpression: unable to compute next run time', { status: 400, code: 'VALIDATION_ERROR' });}}const job = await autonomousJobs.updateJob(req.params.id, {diff --git a/server/services/autonomousJobs.js b/server/services/autonomousJobs.jsindex 822c1b0a48..3c592d5f90 100644--- a/server/services/autonomousJobs.js+++ b/server/services/autonomousJobs.js@@ -632,7 +632,7 @@ async function getDueJobs() {for (const job of enabledJobs) {// Cron-mode jobs: compute next run from cron expressionif (job.cronExpression) {- const from = job.lastRun ? new Date(job.lastRun) : new Date(0)+ const from = job.lastRun ? new Date(job.lastRun) : new Date(now)const next = parseCronToNextRun(job.cronExpression, from, timezone)if (!next || next.getTime() > now) continue@@ -1042,7 +1042,7 @@ async function getNextDueJob() {if (job.cronExpression) {// Cron-mode: derive next due from cron expression- const from = job.lastRun ? new Date(job.lastRun) : new Date(0)+ const from = job.lastRun ? new Date(job.lastRun) : new Date()const next = parseCronToNextRun(job.cronExpression, from, timezone)if (!next) continuenextDue = next.getTime()diff --git a/server/services/cos.js b/server/services/cos.jsindex fa02578267..f36cb809e0 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -4025,21 +4025,24 @@ async function init() {await ensureDirectories();// When an agent completes, immediately try to dequeue the next pending task- cosEvents.on('agent:completed', async (agent) => {+ cosEvents.on('agent:completed', (agent) => {setImmediate(() => dequeueNextTask());// Create notification when a daily briefing completesif (agent?.metadata?.jobId === 'job-daily-briefing' && agent?.result?.success) {- const tz = await getUserTimezone();- const today = todayInTimezone(tz);- addNotification({- type: NOTIFICATION_TYPES.BRIEFING_READY,- title: 'Daily Briefing Ready',- description: `Your daily briefing for ${today} is ready for review.`,- priority: 'low',- link: '/cos/briefing',- metadata: { date: today, agentId: agent.id }- }).catch(err => console.error(`❌ Failed to create briefing notification: ${err.message}`));+ getUserTimezone()+ .then(tz => {+ const today = todayInTimezone(tz);+ return addNotification({+ type: NOTIFICATION_TYPES.BRIEFING_READY,+ title: 'Daily Briefing Ready',+ description: `Your daily briefing for ${today} is ready for review.`,+ priority: 'low',+ link: '/cos/briefing',+ metadata: { date: today, agentId: agent.id }+ });+ })+ .catch(err => console.error(`❌ Failed to create briefing notification: ${err.message}`));}});diff --git a/server/services/eventScheduler.js b/server/services/eventScheduler.jsindex f8c4a057b4..da1a17a180 100644--- a/server/services/eventScheduler.js+++ b/server/services/eventScheduler.js@@ -117,11 +117,11 @@ function parseCronToNextRun(cronExpr, from = new Date(), timezone = 'UTC') {hour = next.getHours(); minute = next.getMinutes()}- if (matchesCronField(month, monthExpr) &&- matchesCronField(day, dayOfMonthExpr) &&- matchesCronField(dow, dayOfWeekExpr) &&- matchesCronField(hour, hourExpr) &&- matchesCronField(minute, minuteExpr)) {+ if (matchesCronField(month, monthExpr, 1) &&+ matchesCronField(day, dayOfMonthExpr, 1) &&+ matchesCronField(dow, dayOfWeekExpr, 0) &&+ matchesCronField(hour, hourExpr, 0) &&+ matchesCronField(minute, minuteExpr, 0)) {return next}next.setMinutes(next.getMinutes() + 1)@@ -136,22 +136,22 @@ function parseCronToNextRun(cronExpr, from = new Date(), timezone = 'UTC') {* @param {string} expr - Cron field expression* @returns {boolean} - True if matches*/-function matchesCronField(value, expr) {+function matchesCronField(value, expr, fieldMin = 0) {if (expr === '*') return true// Handle comma-separated valuesif (expr.includes(',')) {- return expr.split(',').some(part => matchesCronField(value, part.trim()))+ return expr.split(',').some(part => matchesCronField(value, part.trim(), fieldMin))}// Handle step values first (e.g., */5, 0/10, 1-5/2)if (expr.includes('/')) {const [rangeExpr, step] = expr.split('/')const stepNum = Number(step)- let startNum = 0+ let startNum = fieldMinlet endNum = Infinityif (rangeExpr === '*') {- startNum = 0+ startNum = fieldMin} else if (rangeExpr.includes('-')) {const [s, e] = rangeExpr.split('-').map(Number)startNum = sdiff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.jsindex bc9eb3cd28..abeb2f4e2f 100644--- a/server/services/taskSchedule.js+++ b/server/services/taskSchedule.js@@ -1351,11 +1351,15 @@ export async function shouldRunTask(taskType, appId = null) {const timezone = await getUserTimezone();const fromDate = lastRun ? new Date(lastRun) : new Date(now - DAY);const nextRun = parseCronToNextRun(cronExpr, fromDate, timezone);- if (nextRun && now >= nextRun.getTime()) {+ if (!nextRun) {+ result = { shouldRun: false, reason: 'invalid-cron', cronExpression: cronExpr };+ break;+ }+ if (now >= nextRun.getTime()) {result = { shouldRun: true, reason: 'cron-due', cronExpression: cronExpr, nextRunAt: nextRun.toISOString() };} else {result = { shouldRun: false, reason: 'cron-cooldown', cronExpression: cronExpr,- nextRunAt: nextRun?.toISOString() || null };+ nextRunAt: nextRun.toISOString() };}break;}