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
feat: timezone-aware scheduling with cron expression support
Adam Eivy3868caf19ddb
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 94b08ce7dd..9d207fc58f 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -1,2 +1,18 @@+### Fixed+- Job scheduling now uses user's configured timezone instead of UTC — daily briefing and all scheduled jobs fire at the correct local time+- Briefing notification date uses user timezone instead of UTC date+### Added- Character Sheet page: D&D-style character tracking with XP, HP, leveling, dice-based damage, short/long rests, custom event logging, and JIRA/CoS task sync for XP+- Timezone setting in Settings > General — auto-detects from browser, configurable per user+- Cron expression support across all scheduling systems — full 5-field crontab syntax (minute hour dayOfMonth month dayOfWeek)+- Cron support in System Tasks (Jobs), per-app Task Type Overrides, and global CoS Schedule+- Shared CronInput component with presets dropdown and human-readable descriptions+- Schedule mode toggle (Interval vs Cron) in job create/edit forms+- Timezone-aware cron matching in event scheduler and task schedule evaluator+- Shared cron utilities (cronHelpers.js) — DRY across all scheduling UIs+- Timezone utility module with cached Intl.DateTimeFormat and comprehensive test coverage++### Changed+- Task Type Overrides switched from table to card layout for mobile responsiveness+- Task type subtitle shows effective schedule (cron/override) instead of always showing global typediff --git a/client/src/components/CronInput.jsx b/client/src/components/CronInput.jsxnew file mode 100644index 0000000000..07e4559304--- /dev/null+++ b/client/src/components/CronInput.jsx@@ -0,0 +1,61 @@+import { useState } from 'react';+import { CRON_PRESETS, describeCron } from '../utils/cronHelpers';++/**+ * Inline cron expression editor with presets dropdown.+ * Shows a text input + presets select + human-readable description.+ * Calls onSave with the validated expression, onCancel to dismiss.+ */+export default function CronInput({ value, onSave, onCancel, className = '' }) {+ const [expr, setExpr] = useState(value || '0 7 * * *');++ const handleSave = () => {+ const trimmed = expr.trim();+ if (trimmed.split(/\s+/).length !== 5) return;+ onSave(trimmed);+ };++ return (+ <div className={`flex flex-wrap items-center gap-1 ${className}`}>+ <input+ type="text"+ value={expr}+ onChange={e => setExpr(e.target.value)}+ onKeyDown={e => {+ if (e.key === 'Enter') handleSave();+ if (e.key === 'Escape') onCancel?.();+ }}+ className="w-28 sm:w-32 px-2 py-1 bg-port-bg border border-port-border rounded text-xs text-white font-mono focus:border-port-accent focus:outline-hidden"+ placeholder="0 7 * * *"+ autoFocus+ />+ <select+ value=""+ onChange={e => { if (e.target.value) setExpr(e.target.value); }}+ className="px-1 py-1 bg-port-bg border border-port-border rounded text-gray-400 text-xs"+ >+ <option value="">Presets</option>+ {CRON_PRESETS.map(p => (+ <option key={p.value} value={p.value}>{p.label}</option>+ ))}+ </select>+ <button+ onClick={handleSave}+ className="px-1.5 py-1 bg-port-accent/20 text-port-accent rounded text-xs hover:bg-port-accent/30"+ >+ OK+ </button>+ {onCancel && (+ <button+ onClick={onCancel}+ className="px-1.5 py-1 text-gray-500 hover:text-gray-300 rounded text-xs"+ >+ X+ </button>+ )}+ {expr && (+ <span className="text-xs text-gray-500 truncate hidden sm:inline">{describeCron(expr)}</span>+ )}+ </div>+ );+}diff --git a/client/src/components/agents/constants.js b/client/src/components/agents/constants.jsindex 2661d0582b..72e3a2a6af 100644--- a/client/src/components/agents/constants.js+++ b/client/src/components/agents/constants.js@@ -67,16 +67,8 @@ export const DEFAULT_AVATAR = {color: '#3b82f6'};-// Cron presets for easy scheduling-export const CRON_PRESETS = [- { value: '0 * * * *', label: 'Every hour' },- { value: '0 */2 * * *', label: 'Every 2 hours' },- { value: '0 */4 * * *', label: 'Every 4 hours' },- { value: '0 */6 * * *', label: 'Every 6 hours' },- { value: '0 9,12,15,18 * * *', label: 'Peak hours (9am, 12pm, 3pm, 6pm)' },- { value: '0 9 * * *', label: 'Daily at 9am' },- { value: '0 12 * * *', label: 'Daily at noon' }-];+// Re-export shared cron presets for agent scheduling+export { CRON_PRESETS } from '../../utils/cronHelpers';// Interval presets (in milliseconds)export const INTERVAL_PRESETS = [diff --git a/client/src/components/apps/tabs/AutomationTab.jsx b/client/src/components/apps/tabs/AutomationTab.jsxindex dfa57f0665..b3efee5419 100644--- a/client/src/components/apps/tabs/AutomationTab.jsx+++ b/client/src/components/apps/tabs/AutomationTab.jsx@@ -2,8 +2,10 @@ import { useState, useEffect, useCallback } from 'react';import { RefreshCw, Play } from 'lucide-react';import toast from 'react-hot-toast';import BrailleSpinner from '../../BrailleSpinner';+import CronInput from '../../CronInput';import * as api from '../../../services/api';import { AGENT_OPTIONS, toggleAppMetadataOverride } from '../../cos/constants';+import { isCronExpression, describeCron } from '../../../utils/cronHelpers';const INTERVAL_OPTIONS = [{ value: null, label: 'Inherit Global' },@@ -11,7 +13,8 @@ const INTERVAL_OPTIONS = [{ value: 'daily', label: 'Daily' },{ value: 'weekly', label: 'Weekly' },{ value: 'once', label: 'Once' },- { value: 'on-demand', label: 'On-demand' }+ { value: 'on-demand', label: 'On-demand' },+ { value: 'cron', label: 'Cron' }];export default function AutomationTab({ appId, appName }) {@@ -19,6 +22,7 @@ export default function AutomationTab({ appId, appName }) {const [schedule, setSchedule] = useState(null);const [loading, setLoading] = useState(true);const [triggering, setTriggering] = useState(null);+ const [cronEditing, setCronEditing] = useState({});const fetchData = useCallback(async () => {const [taskTypesData, scheduleData] = await Promise.all([@@ -47,6 +51,13 @@ export default function AutomationTab({ appId, appName }) {};const handleIntervalChange = async (taskType, interval) => {+ if (interval === 'cron') {+ // Open cron editor — don't save until user enters expression+ const existing = overrides[taskType]?.interval;+ setCronEditing(prev => ({ ...prev, [taskType]: isCronExpression(existing) ? existing : '0 7 * * *' }));+ return;+ }+ setCronEditing(prev => { const n = { ...prev }; delete n[taskType]; return n; });const value = interval === 'null' ? null : interval;await api.updateAppTaskTypeOverride(appId, taskType, { interval: value }).catch(err => {toast.error(err.message);@@ -58,6 +69,18 @@ export default function AutomationTab({ appId, appName }) {}));};+ const handleCronSave = async (taskType, expr) => {+ await api.updateAppTaskTypeOverride(appId, taskType, { interval: expr }).catch(err => {+ toast.error(err.message);+ return null;+ });+ setOverrides(prev => ({+ ...prev,+ [taskType]: { ...prev[taskType], interval: expr }+ }));+ setCronEditing(prev => { const n = { ...prev }; delete n[taskType]; return n; });+ };+const handleMetaToggle = async (taskType, field, globalTaskMetadata) => {const taskMetadata = toggleAppMetadataOverride(overrides[taskType]?.taskMetadata, globalTaskMetadata, field);await api.updateAppTaskTypeOverride(appId, taskType, { taskMetadata }).catch(err => {@@ -108,96 +131,96 @@ export default function AutomationTab({ appId, appName }) {No task types configured in the schedule</div>) : (- <div className="bg-port-card border border-port-border rounded-lg overflow-hidden">- <div className="overflow-x-auto">- <table className="w-full text-sm">- <thead>- <tr className="border-b border-port-border">- <th className="text-left px-4 py-3 text-xs text-gray-500 uppercase tracking-wide font-medium">Task Type</th>- <th className="text-center px-4 py-3 text-xs text-gray-500 uppercase tracking-wide font-medium">Enabled</th>- <th className="text-left px-4 py-3 text-xs text-gray-500 uppercase tracking-wide font-medium">Interval</th>- <th className="text-center px-4 py-3 text-xs text-gray-500 uppercase tracking-wide font-medium cursor-help" title="Bright = app override on, Dim = inherited from global, Gray = app override off">Agent Options</th>- <th className="text-right px-4 py-3 text-xs text-gray-500 uppercase tracking-wide font-medium">Actions</th>- </tr>- </thead>- <tbody>- {taskTypes.map(taskType => {- const override = overrides[taskType] || {};- const globalConfig = schedule.tasks[taskType] || {};- const isEnabled = override.enabled !== false;- const overrideInterval = override.interval || null;+ <div className="space-y-2">+ {taskTypes.map(taskType => {+ const override = overrides[taskType] || {};+ const globalConfig = schedule.tasks[taskType] || {};+ const isEnabled = override.enabled !== false;+ const overrideInterval = override.interval || null;+ const effectiveLabel = isCronExpression(overrideInterval)+ ? describeCron(overrideInterval) || 'cron'+ : overrideInterval || (globalConfig.type || 'rotation');+ const intervalSuffix = !overrideInterval && globalConfig.intervalMs ? ` (${Math.round(globalConfig.intervalMs / 3600000)}h)` : '';- return (- <tr key={taskType} className="border-b border-port-border/50 hover:bg-white/5">- <td className="px-4 py-3">- <div>- <span className="text-white font-mono text-xs">{taskType}</span>- <div className="text-xs text-gray-500">{globalConfig.type || 'rotation'}{globalConfig.intervalMs ? ` (${Math.round(globalConfig.intervalMs / 3600000)}h)` : ''}</div>- </div>- </td>- <td className="px-4 py-3 text-center">+ return (+ <div key={taskType} className="bg-port-card border border-port-border rounded-lg p-3 space-y-2">+ {/* Row 1: name + toggle + run now */}+ <div className="flex items-center gap-3">+ <button+ onClick={() => handleToggle(taskType, isEnabled)}+ className={`w-10 h-5 rounded-full transition-colors relative shrink-0 ${+ isEnabled ? 'bg-port-success' : 'bg-gray-600'+ }`}+ >+ <span className={`absolute top-0.5 w-4 h-4 rounded-full bg-white transition-transform ${+ isEnabled ? 'left-5' : 'left-0.5'+ }`} />+ </button>+ <div className="flex-1 min-w-0">+ <span className="text-white font-mono text-xs">{taskType}</span>+ <div className="text-xs text-gray-500">{effectiveLabel}{intervalSuffix}</div>+ </div>+ <button+ onClick={() => handleTrigger(taskType)}+ disabled={triggering === taskType || !isEnabled}+ className="px-2 py-1 bg-port-accent/20 text-port-accent hover:bg-port-accent/30 rounded text-xs disabled:opacity-50 inline-flex items-center gap-1 shrink-0"+ >+ <Play size={12} />+ {triggering === taskType ? '...' : 'Run'}+ </button>+ </div>+ {/* Row 2: interval + cron + agent options */}+ <div className="flex flex-wrap items-center gap-2">+ <select+ value={cronEditing[taskType] !== undefined || isCronExpression(overrideInterval) ? 'cron' : (overrideInterval ?? 'null')}+ onChange={e => handleIntervalChange(taskType, e.target.value)}+ className="px-2 py-1 bg-port-bg border border-port-border rounded text-xs text-white focus:border-port-accent focus:outline-hidden"+ >+ {INTERVAL_OPTIONS.map(opt => (+ <option key={String(opt.value)} value={String(opt.value)}>{opt.label}</option>+ ))}+ </select>+ {cronEditing[taskType] !== undefined ? (+ <CronInput+ value={cronEditing[taskType]}+ onSave={expr => handleCronSave(taskType, expr)}+ onCancel={() => setCronEditing(prev => { const n = { ...prev }; delete n[taskType]; return n; })}+ />+ ) : isCronExpression(overrideInterval) ? (+ <button+ onClick={() => setCronEditing(prev => ({ ...prev, [taskType]: overrideInterval }))}+ className="px-2 py-1 text-xs text-gray-400 font-mono bg-port-bg border border-port-border rounded hover:border-port-accent cursor-pointer"+ title={describeCron(overrideInterval)}+ >+ {overrideInterval}+ </button>+ ) : null}+ <div className="flex items-center gap-1 ml-auto">+ {AGENT_OPTIONS.map(({ field, shortLabel, label }) => {+ const effective = override.taskMetadata?.[field] ?? globalConfig.taskMetadata?.[field] ?? false;+ const hasOverride = override.taskMetadata?.[field] !== undefined;+ return (<button- onClick={() => handleToggle(taskType, isEnabled)}- className={`w-10 h-5 rounded-full transition-colors relative ${- isEnabled ? 'bg-port-success' : 'bg-gray-600'+ key={field}+ onClick={() => handleMetaToggle(taskType, field, globalConfig.taskMetadata)}+ aria-pressed={effective}+ aria-label={`${label}: ${effective ? 'on' : 'off'}${hasOverride ? ' (app override)' : ' (inherited)'}`}+ className={`text-xs px-1.5 py-0.5 rounded transition-colors ${+ effective+ ? hasOverride ? 'bg-port-accent/30 text-port-accent' : 'bg-port-accent/15 text-port-accent/60'+ : hasOverride ? 'bg-gray-600/50 text-gray-400' : 'bg-gray-600/25 text-gray-500'}`}+ title={`${label}: ${effective ? 'on' : 'off'}${hasOverride ? ' (app override)' : ' (inherited)'}`}>- <span className={`absolute top-0.5 w-4 h-4 rounded-full bg-white transition-transform ${- isEnabled ? 'left-5' : 'left-0.5'- }`} />- </button>- </td>- <td className="px-4 py-3">- <select- value={overrideInterval ?? 'null'}- onChange={e => handleIntervalChange(taskType, e.target.value)}- className="px-2 py-1 bg-port-bg border border-port-border rounded text-xs text-white focus:border-port-accent focus:outline-hidden"- >- {INTERVAL_OPTIONS.map(opt => (- <option key={String(opt.value)} value={String(opt.value)}>{opt.label}</option>- ))}- </select>- </td>- <td className="px-4 py-3">- <div className="flex items-center justify-center gap-1">- {AGENT_OPTIONS.map(({ field, shortLabel, label }) => {- const effective = override.taskMetadata?.[field] ?? globalConfig.taskMetadata?.[field] ?? false;- const hasOverride = override.taskMetadata?.[field] !== undefined;- return (- <button- key={field}- onClick={() => handleMetaToggle(taskType, field, globalConfig.taskMetadata)}- aria-pressed={effective}- aria-label={`${label}: ${effective ? 'on' : 'off'}${hasOverride ? ' (app override)' : ' (inherited)'}`}- className={`text-xs px-1.5 py-0.5 rounded transition-colors ${- effective- ? hasOverride ? 'bg-port-accent/30 text-port-accent' : 'bg-port-accent/15 text-port-accent/60'- : hasOverride ? 'bg-gray-600/50 text-gray-400' : 'bg-gray-600/25 text-gray-500'- }`}- title={`${label}: ${effective ? 'on' : 'off'}${hasOverride ? ' (app override)' : ' (inherited)'}`}- >- {shortLabel}- </button>- );- })}- </div>- </td>- <td className="px-4 py-3 text-right">- <button- onClick={() => handleTrigger(taskType)}- disabled={triggering === taskType || !isEnabled}- className="px-2 py-1 bg-port-accent/20 text-port-accent hover:bg-port-accent/30 rounded text-xs disabled:opacity-50 inline-flex items-center gap-1"- >- <Play size={12} />- {triggering === taskType ? '...' : 'Run Now'}+ {shortLabel}</button>- </td>- </tr>- );- })}- </tbody>- </table>- </div>+ );+ })}+ </div>+ </div>+ </div>+ );+ })}</div>)}</div>diff --git a/client/src/components/cos/tabs/JobsTab.jsx b/client/src/components/cos/tabs/JobsTab.jsxindex 70d055233c..822623e47b 100644--- a/client/src/components/cos/tabs/JobsTab.jsx+++ b/client/src/components/cos/tabs/JobsTab.jsx@@ -3,6 +3,7 @@ import { Plus, RefreshCw, Play, Trash2, ChevronDown, ChevronUp, Clock, ToggleLefimport toast from 'react-hot-toast';import * as api from '../../../services/api';import { timeAgo } from '../../../utils/formatters';+import { CRON_PRESETS, describeCron } from '../../../utils/cronHelpers';const INTERVAL_OPTIONS = [{ value: 'hourly', label: 'Every Hour' },@@ -15,6 +16,11 @@ const INTERVAL_OPTIONS = [{ value: 'monthly', label: 'Monthly' }];+const SCHEDULE_MODE_OPTIONS = [+ { value: 'interval', label: 'Interval' },+ { value: 'cron', label: 'Cron' }+];+const PRIORITY_OPTIONS = ['LOW', 'MEDIUM', 'HIGH', 'CRITICAL'];const AUTONOMY_OPTIONS = [{ value: 'standby', label: 'Standby', desc: 'Creates tasks but waits for approval' },@@ -39,7 +45,95 @@ const JOB_TYPE_OPTIONS = [{ value: 'shell', label: 'Shell Command' }];-function formatNextDue(lastRun, intervalMs, scheduledTime) {+function normalizeJobPayload(formData) {+ const payload = { ...formData };+ if (payload.type !== 'shell' && payload.type !== 'script') {+ payload.command = null;+ payload.triggerAction = null;+ }+ if (payload.scheduleMode === 'cron') {+ payload.cronExpression = payload.cronExpression?.trim() || null;+ payload.scheduledTime = null;+ } else {+ payload.cronExpression = null;+ }+ delete payload.scheduleMode;+ return payload;+}++function ScheduleFields({ data, onChange }) {+ return (+ <div className="space-y-2">+ <div className="flex items-center gap-2">+ <span className="text-xs text-gray-400">Schedule:</span>+ {SCHEDULE_MODE_OPTIONS.map(opt => (+ <button+ key={opt.value}+ type="button"+ onClick={() => onChange('scheduleMode', opt.value)}+ className={`px-2 py-1 text-xs rounded transition-colors ${+ data.scheduleMode === opt.value+ ? 'bg-port-accent/20 text-port-accent'+ : 'bg-port-bg text-gray-500 hover:text-gray-300'+ }`}+ >+ {opt.label}+ </button>+ ))}+ </div>+ {data.scheduleMode === 'cron' ? (+ <div className="flex gap-2 items-center">+ <input+ type="text"+ value={data.cronExpression || ''}+ onChange={e => onChange('cronExpression', e.target.value)}+ className="flex-1 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm font-mono"+ placeholder="0 7 * * *"+ title="Cron expression: minute hour dayOfMonth month dayOfWeek"+ />+ <select+ value=""+ onChange={e => { if (e.target.value) onChange('cronExpression', e.target.value); }}+ className="px-2 py-2 bg-port-bg border border-port-border rounded-lg text-gray-400 text-xs"+ >+ <option value="">Presets</option>+ {CRON_PRESETS.map(p => (+ <option key={p.value} value={p.value}>{p.label}</option>+ ))}+ </select>+ {data.cronExpression && (+ <span className="text-xs text-gray-500">{describeCron(data.cronExpression)}</span>+ )}+ </div>+ ) : (+ <div className="flex gap-3">+ <select+ value={data.interval}+ onChange={e => onChange('interval', e.target.value)}+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ >+ {INTERVAL_OPTIONS.map(opt => (+ <option key={opt.value} value={opt.value}>{opt.label}</option>+ ))}+ </select>+ <input+ type="time"+ value={data.scheduledTime || ''}+ onChange={e => onChange('scheduledTime', e.target.value || null)}+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ title="Run at specific time (leave empty for any time)"+ />+ </div>+ )}+ </div>+ );+}++function formatNextDue(job) {+ // Cron jobs: show human-readable schedule (server computes exact next fire time)+ if (job.cronExpression) return describeCron(job.cronExpression);++ const { lastRun, intervalMs, scheduledTime } = job;if (!lastRun) return scheduledTime ? `at ${scheduledTime}` : 'Immediately';let nextDue = new Date(lastRun).getTime() + intervalMs;if (scheduledTime) {@@ -50,10 +144,10 @@ function formatNextDue(lastRun, intervalMs, scheduledTime) {}const diff = nextDue - Date.now();if (diff <= 0) return 'Now';- const hours = Math.floor(diff / 3600000);- const days = Math.floor(hours / 24);+ const hrs = Math.floor(diff / 3600000);+ const days = Math.floor(hrs / 24);if (days > 0) return `in ${days}d`;- if (hours > 0) return `in ${hours}h`;+ if (hrs > 0) return `in ${hrs}h`;const mins = Math.floor(diff / 60000);return `in ${mins}m`;}@@ -77,8 +171,10 @@ function JobCard({ job, onToggle, onTrigger, onDelete, onUpdate }) {name: job.name,description: job.description,type: job.type || 'agent',+ scheduleMode: job.cronExpression ? 'cron' : 'interval',interval: job.interval,scheduledTime: job.scheduledTime || '',+ cronExpression: job.cronExpression || '',priority: job.priority,autonomyLevel: job.autonomyLevel,promptTemplate: job.promptTemplate || ''@@ -92,11 +188,7 @@ function JobCard({ job, onToggle, onTrigger, onDelete, onUpdate }) {};const handleSave = async () => {- const payload = { ...editData };- if (payload.type !== 'shell' && payload.type !== 'script') {- payload.command = null;- payload.triggerAction = null;- }+ const payload = normalizeJobPayload(editData);await api.updateCosJob(job.id, payload).catch(err => {toast.error(err.message);return null;@@ -149,13 +241,18 @@ function JobCard({ job, onToggle, onTrigger, onDelete, onUpdate }) {<div className="flex items-center gap-3 text-xs text-gray-500 mt-1"><span className="flex items-center gap-1"><Clock size={10} />- {INTERVAL_OPTIONS.find(i => i.value === job.interval)?.label || job.interval}- {job.scheduledTime && ` at ${job.scheduledTime}`}+ {job.cronExpression+ ? <span title={job.cronExpression}>{describeCron(job.cronExpression)}</span>+ : <>+ {INTERVAL_OPTIONS.find(i => i.value === job.interval)?.label || job.interval}+ {job.scheduledTime && ` at ${job.scheduledTime}`}+ </>+ }</span><span>Last: {timeAgo(job.lastRun, 'Never')}</span>{job.enabled && (<span className={isDue ? 'text-port-warning' : 'text-gray-500'}>- Next: {formatNextDue(job.lastRun, job.intervalMs, job.scheduledTime)}+ Next: {formatNextDue(job)}</span>)}<span>Runs: {job.runCount || 0}</span>@@ -223,22 +320,6 @@ function JobCard({ job, onToggle, onTrigger, onDelete, onUpdate }) {))}{isScript && <option value="script">Script Handler</option>}</select>- <select- value={editData.interval}- onChange={e => setEditData(d => ({ ...d, interval: e.target.value }))}- className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"- >- {INTERVAL_OPTIONS.map(opt => (- <option key={opt.value} value={opt.value}>{opt.label}</option>- ))}- </select>- <input- type="time"- value={editData.scheduledTime || ''}- onChange={e => setEditData(d => ({ ...d, scheduledTime: e.target.value || null }))}- className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"- title="Run at specific time (leave empty for any time)"- /><selectvalue={editData.priority}onChange={e => setEditData(d => ({ ...d, priority: e.target.value }))}@@ -260,6 +341,7 @@ function JobCard({ job, onToggle, onTrigger, onDelete, onUpdate }) {</select>)}</div>+ <ScheduleFields data={editData} onChange={(key, val) => setEditData(d => ({ ...d, [key]: val }))} />{editData.type === 'shell' ? (<><textarea@@ -367,8 +449,10 @@ export default function JobsTab() {description: '',category: 'custom',type: 'agent',+ scheduleMode: 'interval',interval: 'daily',scheduledTime: '',+ cronExpression: '',priority: 'MEDIUM',autonomyLevel: 'manager',promptTemplate: '',@@ -405,7 +489,7 @@ export default function JobsTab() {return;}- const created = await api.createCosJob(newJob).catch(err => {+ const created = await api.createCosJob(normalizeJobPayload(newJob)).catch(err => {toast.error(err.message);return null;});@@ -416,8 +500,10 @@ export default function JobsTab() {description: '',category: 'custom',type: 'agent',+ scheduleMode: 'interval',interval: 'daily',scheduledTime: '',+ cronExpression: '',priority: 'MEDIUM',autonomyLevel: 'manager',promptTemplate: '',@@ -551,22 +637,6 @@ export default function JobsTab() {className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"/><div className="flex gap-3">- <select- value={newJob.interval}- onChange={e => setNewJob(j => ({ ...j, interval: e.target.value }))}- className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"- >- {INTERVAL_OPTIONS.map(opt => (- <option key={opt.value} value={opt.value}>{opt.label}</option>- ))}- </select>- <input- type="time"- value={newJob.scheduledTime || ''}- onChange={e => setNewJob(j => ({ ...j, scheduledTime: e.target.value || null }))}- className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"- title="Run at specific time (leave empty for any time)"- /><selectvalue={newJob.priority}onChange={e => setNewJob(j => ({ ...j, priority: e.target.value }))}@@ -588,6 +658,7 @@ export default function JobsTab() {</select>)}</div>+ <ScheduleFields data={newJob} onChange={(key, val) => setNewJob(j => ({ ...j, [key]: val }))} />{newJob.type === 'shell' ? (<><textareadiff --git a/client/src/components/cos/tabs/ScheduleTab.jsx b/client/src/components/cos/tabs/ScheduleTab.jsxindex e6fc4ddec1..14ea014776 100644--- a/client/src/components/cos/tabs/ScheduleTab.jsx+++ b/client/src/components/cos/tabs/ScheduleTab.jsx@@ -3,7 +3,9 @@ import { Play, RotateCcw, ChevronDown, ChevronRight, AlertCircle, RefreshCw, Pacimport toast from 'react-hot-toast';import * as api from '../../../services/api';import AppIcon from '../../AppIcon';+import CronInput from '../../CronInput';import { AGENT_OPTIONS, toggleAppMetadataOverride } from '../constants';+import { isCronExpression, describeCron } from '../../../utils/cronHelpers';const INTERVAL_LABELS = {rotation: 'Rotation',@@ -11,7 +13,8 @@ const INTERVAL_LABELS = {weekly: 'Weekly',once: 'Once','on-demand': 'On Demand',- custom: 'Custom'+ custom: 'Custom',+ cron: 'Cron'};const INTERVAL_DESCRIPTIONS = {@@ -20,7 +23,8 @@ const INTERVAL_DESCRIPTIONS = {weekly: 'Runs once per week',once: 'Runs once then stops','on-demand': 'Only runs when manually triggered',- custom: 'Custom interval'+ custom: 'Custom interval',+ cron: 'Cron expression schedule'};// Toggle a global taskMetadata field, enforcing the openPR→useWorktree invariant.@@ -41,16 +45,20 @@ function toggleMetadataField(metadata, field) {}-function IntervalBadge({ type }) {+function IntervalBadge({ type, cronExpression }) {+ const label = type === 'cron' && cronExpression+ ? describeCron(cronExpression) || cronExpression+ : INTERVAL_LABELS[type] || type;return (<span className={`text-xs px-2 py-0.5 rounded ${type === 'daily' ? 'bg-port-accent/20 text-port-accent' :type === 'weekly' ? 'bg-purple-500/20 text-purple-400' :type === 'once' ? 'bg-port-warning/20 text-port-warning' :type === 'on-demand' ? 'bg-gray-500/20 text-gray-400' :+ type === 'cron' ? 'bg-cyan-500/20 text-cyan-400' :'bg-port-success/20 text-port-success'- }`}>- {INTERVAL_LABELS[type]}+ }`} title={type === 'cron' && cronExpression ? cronExpression : undefined}>+ {label}</span>);}@@ -87,12 +95,29 @@ function GlobalConfigControls({ taskType, config, onUpdate, onTrigger, onReset,const activeApps = apps?.filter(app => !app.archived) || [];+ const [cronEditing, setCronEditing] = useState(false);+const handleTypeChange = async (newType) => {+ if (newType === 'cron') {+ setCronEditing(true);+ setSelectedType('cron');+ return;+ }+ setCronEditing(false);setUpdating(true);setSelectedType(newType);- await onUpdate(taskType, { type: newType }).catch(() => {+ await onUpdate(taskType, { type: newType, cronExpression: null }).catch(() => {+ setSelectedType(config.type);+ });+ setUpdating(false);+ };++ const handleCronSave = async (expr) => {+ setUpdating(true);+ await onUpdate(taskType, { type: 'cron', cronExpression: expr }).catch(() => {setSelectedType(config.type);});+ setCronEditing(false);setUpdating(false);};@@ -169,8 +194,18 @@ function GlobalConfigControls({ taskType, config, onUpdate, onTrigger, onReset,<option value="weekly">Weekly (once per week)</option><option value="once">Once (run once then stop)</option><option value="on-demand">On Demand (manual trigger only)</option>+ <option value="cron">Cron (custom schedule)</option></select>- <p className="text-xs text-gray-500 mt-1">{INTERVAL_DESCRIPTIONS[selectedType]}</p>+ {(selectedType === 'cron' && (cronEditing || config.type === 'cron')) ? (+ <CronInput+ value={config.cronExpression || '0 7 * * *'}+ onSave={handleCronSave}+ onCancel={() => { setCronEditing(false); setSelectedType(config.type); }}+ className="mt-2"+ />+ ) : (+ <p className="text-xs text-gray-500 mt-1">{INTERVAL_DESCRIPTIONS[selectedType]}</p>+ )}</div><div>@@ -387,8 +422,10 @@ function GlobalConfigControls({ taskType, config, onUpdate, onTrigger, onReset,function AppOverrideRow({ app, taskType, globalIntervalType, globalTaskMetadata, override, onUpdate }) {const [updating, setUpdating] = useState(false);+ const [cronEditing, setCronEditing] = useState(false);const isEnabled = override?.enabled === true;const currentInterval = override?.interval || null;+ const hasCron = isCronExpression(currentInterval);const handleToggle = async () => {setUpdating(true);@@ -397,12 +434,24 @@ function AppOverrideRow({ app, taskType, globalIntervalType, globalTaskMetadata,};const handleIntervalChange = async (newInterval) => {+ if (newInterval === 'cron') {+ setCronEditing(true);+ return;+ }+ setCronEditing(false);setUpdating(true);const interval = newInterval === '' ? null : newInterval;await onUpdate(app.id, taskType, { enabled: isEnabled, interval }).catch(() => {});setUpdating(false);};+ const handleCronSave = async (expr) => {+ setUpdating(true);+ await onUpdate(app.id, taskType, { enabled: isEnabled, interval: expr }).catch(() => {});+ setCronEditing(false);+ setUpdating(false);+ };+const handleMetaToggle = async (field) => {setUpdating(true);const taskMetadata = toggleAppMetadataOverride(override?.taskMetadata, globalTaskMetadata, field);@@ -417,19 +466,37 @@ function AppOverrideRow({ app, taskType, globalIntervalType, globalTaskMetadata,<span className="text-sm text-white truncate">{app.name}</span></div>- <select- value={currentInterval || ''}- onChange={(e) => handleIntervalChange(e.target.value)}- disabled={updating}- className="bg-port-card border border-port-border rounded px-2 py-1 text-xs text-white min-w-[140px]"- >- <option value="">Inherit ({INTERVAL_LABELS[globalIntervalType]})</option>- <option value="rotation">Rotation</option>- <option value="daily">Daily</option>- <option value="weekly">Weekly</option>- <option value="once">Once</option>- <option value="on-demand">On Demand</option>- </select>+ <div className="flex items-center gap-1">+ <select+ value={cronEditing || hasCron ? 'cron' : (currentInterval || '')}+ onChange={(e) => handleIntervalChange(e.target.value)}+ disabled={updating}+ className="bg-port-card border border-port-border rounded px-2 py-1 text-xs text-white min-w-[120px]"+ >+ <option value="">Inherit ({INTERVAL_LABELS[globalIntervalType] || globalIntervalType})</option>+ <option value="rotation">Rotation</option>+ <option value="daily">Daily</option>+ <option value="weekly">Weekly</option>+ <option value="once">Once</option>+ <option value="on-demand">On Demand</option>+ <option value="cron">Cron</option>+ </select>+ {cronEditing ? (+ <CronInput+ value={hasCron ? currentInterval : '0 7 * * *'}+ onSave={handleCronSave}+ onCancel={() => setCronEditing(false)}+ />+ ) : hasCron ? (+ <button+ onClick={() => setCronEditing(true)}+ className="px-2 py-1 text-xs text-gray-400 font-mono bg-port-bg border border-port-border rounded hover:border-port-accent cursor-pointer"+ title={describeCron(currentInterval)}+ >+ {currentInterval}+ </button>+ ) : null}+ </div>{AGENT_OPTIONS.map(({ field, label, shortLabel }) => {const effective = override?.taskMetadata?.[field] ?? globalTaskMetadata?.[field] ?? false;diff --git a/client/src/pages/Settings.jsx b/client/src/pages/Settings.jsxindex 7e6ccf5a0c..4997b9d2f2 100644--- a/client/src/pages/Settings.jsx+++ b/client/src/pages/Settings.jsx@@ -1,4 +1,4 @@-import { useState, useEffect, useCallback, useRef } from 'react';+import { useState, useEffect, useCallback, useRef, useMemo } from 'react';import { useParams, useNavigate } from 'react-router-dom';import { Save, Plus, X, Eye, EyeOff, Trash2, Send, Container, HardDrive, Download, ArrowRightLeft, Wrench, RefreshCw, Square, RotateCw, Play } from 'lucide-react';import toast from 'react-hot-toast';@@ -771,7 +771,84 @@ function TelegramTab() {);}+function GeneralTab() {+ const [loading, setLoading] = useState(true);+ const [timezone, setTimezone] = useState('');+ const [saving, setSaving] = useState(false);+ const detectedTz = Intl.DateTimeFormat().resolvedOptions().timeZone;+ const allTimezones = useMemo(() => Intl.supportedValuesOf?.('timeZone') ?? [], []);++ useEffect(() => {+ getSettings()+ .then(settings => setTimezone(settings?.timezone || ''))+ .catch(() => toast.error('Failed to load settings'))+ .finally(() => setLoading(false));+ }, []);++ const handleSave = async (tz) => {+ setSaving(true);+ await updateSettings({ timezone: tz })+ .then(() => {+ setTimezone(tz);+ toast.success(`Timezone set to ${tz}`);+ })+ .catch(() => toast.error('Failed to save timezone'))+ .finally(() => setSaving(false));+ };++ if (loading) return <BrailleSpinner />;++ return (+ <div className="space-y-6">+ <div className="bg-port-card border border-port-border rounded-lg p-6">+ <h3 className="text-lg font-semibold text-white mb-4">Timezone</h3>+ <p className="text-sm text-gray-400 mb-4">+ Used for job scheduling (cron expressions & scheduled times) and briefing dates.+ </p>+ <div className="flex items-center gap-3">+ <input+ type="text"+ value={timezone}+ onChange={e => setTimezone(e.target.value)}+ placeholder={detectedTz}+ className="flex-1 max-w-xs px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ list="tz-list"+ />+ <button+ onClick={() => handleSave(timezone || detectedTz)}+ 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"+ >+ <Save size={14} className="inline mr-1" />+ {saving ? 'Saving...' : 'Save'}+ </button>+ {!timezone && (+ <button+ onClick={() => handleSave(detectedTz)}+ disabled={saving}+ className="px-3 py-2 text-sm text-gray-400 hover:text-white transition-colors"+ >+ Use detected: {detectedTz}+ </button>+ )}+ </div>+ {timezone && timezone !== detectedTz && (+ <p className="text-xs text-gray-500 mt-2">+ Browser detected: {detectedTz}+ </p>+ )}+ <datalist id="tz-list">+ {allTimezones.map(tz => (+ <option key={tz} value={tz} />+ ))}+ </datalist>+ </div>+ </div>+ );+}+const TABS = [+ { id: 'general', label: 'General' },{ id: 'backup', label: 'Backup' },{ id: 'database', label: 'Database' },{ id: 'telegram', label: 'Telegram' }@@ -780,7 +857,7 @@ const TABS = [export default function Settings() {const { tab } = useParams();const navigate = useNavigate();- const activeTab = tab || 'backup';+ const activeTab = tab || 'general';const handleTabChange = (tabId) => {navigate(`/settings/${tabId}`);@@ -788,10 +865,11 @@ export default function Settings() {const renderTabContent = () => {switch (activeTab) {+ case 'general': return <GeneralTab />;case 'backup': return <BackupTab />;case 'database': return <DatabaseTab />;case 'telegram': return <TelegramTab />;- default: return <BackupTab />;+ default: return <GeneralTab />;}};diff --git a/client/src/utils/cronHelpers.js b/client/src/utils/cronHelpers.jsnew file mode 100644index 0000000000..7c19caba71--- /dev/null+++ b/client/src/utils/cronHelpers.js@@ -0,0 +1,40 @@+export const CRON_PRESETS = [+ { value: '*/15 * * * *', label: 'Every 15 min' },+ { value: '0 * * * *', label: 'Every hour' },+ { value: '0 */2 * * *', label: 'Every 2 hours' },+ { value: '0 */4 * * *', label: 'Every 4 hours' },+ { value: '0 */6 * * *', label: 'Every 6 hours' },+ { value: '0 7 * * *', label: 'Daily at 7 AM' },+ { value: '0 7 * * 1-5', label: 'Weekdays at 7 AM' },+ { value: '0 9,12,15,18 * * *', label: 'Peak hours (9, 12, 3, 6)' },+ { value: '0 0 * * 0', label: 'Weekly Sun midnight' },+ { value: '0 0 1 * *', label: 'Monthly 1st at midnight' }+];++export function isCronExpression(val) {+ return typeof val === 'string' && val.trim().split(/\s+/).length === 5;+}++const DOW_MAP = { '0': 'Sun', '1': 'Mon', '2': 'Tue', '3': 'Wed', '4': 'Thu', '5': 'Fri', '6': 'Sat', '7': 'Sun' };++export function describeCron(expr) {+ if (!expr) return '';+ const parts = expr.trim().split(/\s+/);+ if (parts.length !== 5) return expr;+ const [min, hour, dom, mon, dow] = parts;+ const segments = [];+ if (min === '0' && hour !== '*') {+ if (dow === '1-5') segments.push('Weekdays');+ else if (dow !== '*') segments.push(dow.split(',').map(d => DOW_MAP[d] || d).join(', '));+ if (dom !== '*') segments.push(`day ${dom}`);+ if (mon !== '*') segments.push(`month ${mon}`);+ segments.push(`at ${hour.padStart(2, '0')}:${min.padStart(2, '0')}`);+ } else if (min.startsWith('*/')) {+ segments.push(`every ${min.slice(2)} min`);+ } else if (hour.startsWith('*/')) {+ segments.push(`every ${hour.slice(2)} hours at :${min.padStart(2, '0')}`);+ } else {+ return expr;+ }+ return segments.join(' ');+}diff --git a/server/lib/timezone.js b/server/lib/timezone.jsnew file mode 100644index 0000000000..18d2ae545b--- /dev/null+++ b/server/lib/timezone.js@@ -0,0 +1,117 @@+/**+ * Timezone utilities for scheduling+ *+ * All scheduling runs in the user's configured timezone.+ * The server process uses TZ=UTC, so all Date operations are UTC internally.+ * These helpers convert between UTC and the user's local timezone.+ */++import { getSettings } from '../services/settings.js'++const WEEKDAY_MAP = { Sun: 0, Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6 }++// Cache Intl.DateTimeFormat instances per timezone — these are expensive to construct+// but safe to reuse since they're stateless formatters.+const formatterCache = new Map()++function getFormatter(timezone) {+ let fmt = formatterCache.get(timezone)+ if (!fmt) {+ fmt = new Intl.DateTimeFormat('en-US', {+ timeZone: timezone,+ year: 'numeric',+ month: '2-digit',+ day: '2-digit',+ hour: '2-digit',+ minute: '2-digit',+ weekday: 'short',+ hour12: false+ })+ formatterCache.set(timezone, fmt)+ }+ return fmt+}++/**+ * Get the user's configured timezone, falling back to system timezone.+ * @returns {Promise<string>} IANA timezone string (e.g., 'America/Los_Angeles')+ */+export async function getUserTimezone() {+ const settings = await getSettings()+ return settings.timezone || Intl.DateTimeFormat().resolvedOptions().timeZone+}++/**+ * Get local date/time parts for a UTC Date in the given timezone.+ * @param {Date} utcDate - Date object (interpreted as UTC since TZ=UTC)+ * @param {string} timezone - IANA timezone string+ * @returns {{ year: number, month: number, day: number, hour: number, minute: number, dayOfWeek: number }}+ */+export function getLocalParts(utcDate, timezone) {+ const parts = {}+ for (const { type, value } of getFormatter(timezone).formatToParts(utcDate)) {+ parts[type] = value+ }+ return {+ year: parseInt(parts.year),+ month: parseInt(parts.month),+ day: parseInt(parts.day),+ hour: parts.hour === '24' ? 0 : parseInt(parts.hour),+ minute: parseInt(parts.minute),+ dayOfWeek: WEEKDAY_MAP[parts.weekday] ?? 0+ }+}++/**+ * Get the UTC offset (in ms) for a timezone at a given UTC time.+ * Positive = ahead of UTC (e.g., +9h for Tokyo), negative = behind (e.g., -7h for PDT).+ * @param {Date} utcDate - Reference UTC date+ * @param {string} timezone - IANA timezone string+ * @returns {number} Offset in milliseconds+ */+export function getUtcOffsetMs(utcDate, timezone) {+ const utcStr = utcDate.toLocaleString('en-US', { timeZone: 'UTC' })+ const localStr = utcDate.toLocaleString('en-US', { timeZone: timezone })+ return new Date(localStr).getTime() - new Date(utcStr).getTime()+}++/**+ * Find the next UTC timestamp where the local time in `timezone` matches HH:MM.+ * @param {number} afterMs - UTC timestamp to search after+ * @param {number} hours - Target hour (0-23) in local timezone+ * @param {number} minutes - Target minute (0-59) in local timezone+ * @param {string} timezone - IANA timezone string+ * @returns {number} UTC timestamp+ */+export function nextLocalTime(afterMs, hours, minutes, timezone) {+ // Start from the after point, find what the current local time is+ const ref = new Date(afterMs)+ const local = getLocalParts(ref, timezone)++ // Compute desired vs current in minutes-since-midnight+ const desiredMin = hours * 60 + minutes+ const currentMin = local.hour * 60 + local.minute++ // How many minutes until the target time?+ let deltaMin = desiredMin - currentMin+ if (deltaMin <= 0) deltaMin += 1440 // wrap to next day++ const candidate = afterMs + deltaMin * 60_000+ // DST transitions can shift the result by up to ±60 min — verify and nudge if needed.+ const check = getLocalParts(new Date(candidate), timezone)+ const checkMin = check.hour * 60 + check.minute+ if (checkMin !== desiredMin) {+ return candidate + (desiredMin - checkMin) * 60_000+ }+ return candidate+}++/**+ * Get today's date string (YYYY-MM-DD) in the user's timezone.+ * @param {string} timezone - IANA timezone string+ * @returns {string}+ */+export function todayInTimezone(timezone) {+ const parts = getLocalParts(new Date(), timezone)+ return `${parts.year}-${String(parts.month).padStart(2, '0')}-${String(parts.day).padStart(2, '0')}`+}diff --git a/server/lib/timezone.test.js b/server/lib/timezone.test.jsnew file mode 100644index 0000000000..f7e057f52b--- /dev/null+++ b/server/lib/timezone.test.js@@ -0,0 +1,114 @@+import { describe, it, expect, vi } from 'vitest'+import { getLocalParts, getUtcOffsetMs, nextLocalTime, todayInTimezone } from './timezone.js'++describe('timezone', () => {+ describe('getLocalParts', () => {+ it('returns UTC parts when timezone is UTC', () => {+ const date = new Date('2026-03-24T14:30:00Z')+ const parts = getLocalParts(date, 'UTC')+ expect(parts.year).toBe(2026)+ expect(parts.month).toBe(3)+ expect(parts.day).toBe(24)+ expect(parts.hour).toBe(14)+ expect(parts.minute).toBe(30)+ expect(parts.dayOfWeek).toBe(2) // Tuesday+ })++ it('converts UTC to Pacific time', () => {+ // March 24, 2026 14:00 UTC = March 24, 2026 07:00 PDT (UTC-7)+ const date = new Date('2026-03-24T14:00:00Z')+ const parts = getLocalParts(date, 'America/Los_Angeles')+ expect(parts.hour).toBe(7)+ expect(parts.day).toBe(24)+ })++ it('handles date boundary crossing', () => {+ // March 24, 2026 03:00 UTC = March 23, 2026 20:00 PDT (UTC-7)+ const date = new Date('2026-03-24T03:00:00Z')+ const parts = getLocalParts(date, 'America/Los_Angeles')+ expect(parts.hour).toBe(20)+ expect(parts.day).toBe(23)+ })++ it('handles hour 24 normalization', () => {+ // Intl can sometimes return hour 24 for midnight+ // Test with a known midnight time+ const date = new Date('2026-03-25T00:00:00Z')+ const parts = getLocalParts(date, 'UTC')+ expect(parts.hour).toBe(0)+ })+ })++ describe('getUtcOffsetMs', () => {+ it('returns 0 for UTC', () => {+ const date = new Date('2026-03-24T12:00:00Z')+ expect(getUtcOffsetMs(date, 'UTC')).toBe(0)+ })++ it('returns negative offset for US Pacific', () => {+ // PDT is UTC-7 in March+ const date = new Date('2026-03-24T12:00:00Z')+ const offset = getUtcOffsetMs(date, 'America/Los_Angeles')+ expect(offset).toBe(-7 * 60 * 60 * 1000) // -7 hours in ms+ })++ it('returns positive offset for Tokyo', () => {+ // JST is UTC+9 always+ const date = new Date('2026-03-24T12:00:00Z')+ const offset = getUtcOffsetMs(date, 'Asia/Tokyo')+ expect(offset).toBe(9 * 60 * 60 * 1000) // +9 hours in ms+ })+ })++ describe('nextLocalTime', () => {+ it('finds the next occurrence of a local time in UTC timezone', () => {+ const after = new Date('2026-03-24T10:00:00Z').getTime()+ const result = nextLocalTime(after, 14, 0, 'UTC')+ // Should be 14:00 UTC same day+ const resultDate = new Date(result)+ expect(resultDate.getUTCHours()).toBe(14)+ expect(resultDate.getUTCMinutes()).toBe(0)+ expect(resultDate.getUTCDate()).toBe(24)+ })++ it('wraps to next day if time has passed', () => {+ const after = new Date('2026-03-24T15:00:00Z').getTime()+ const result = nextLocalTime(after, 14, 0, 'UTC')+ // 14:00 has passed, should find 14:00 tomorrow+ const resultDate = new Date(result)+ expect(resultDate.getUTCHours()).toBe(14)+ expect(resultDate.getUTCDate()).toBe(25)+ })++ it('handles timezone offset correctly', () => {+ // At 2026-03-24 08:00 UTC, it's 01:00 PDT+ // Next 07:00 PDT = 14:00 UTC same day+ const after = new Date('2026-03-24T08:00:00Z').getTime()+ const result = nextLocalTime(after, 7, 0, 'America/Los_Angeles')+ const resultDate = new Date(result)+ const parts = getLocalParts(resultDate, 'America/Los_Angeles')+ expect(parts.hour).toBe(7)+ expect(parts.minute).toBe(0)+ })+ })++ describe('todayInTimezone', () => {+ it('returns date string in YYYY-MM-DD format', () => {+ const result = todayInTimezone('UTC')+ expect(result).toMatch(/^\d{4}-\d{2}-\d{2}$/)+ })++ it('may differ from UTC date in offset timezones', () => {+ // At 2026-03-24 03:00 UTC, it's still March 23 in Pacific time+ vi.useFakeTimers()+ vi.setSystemTime(new Date('2026-03-24T03:00:00Z'))++ const utcDate = todayInTimezone('UTC')+ const pdtDate = todayInTimezone('America/Los_Angeles')+ expect(utcDate).toBe('2026-03-24')+ expect(pdtDate).toBe('2026-03-23')++ vi.useRealTimers()+ })+ })+})diff --git a/server/routes/apps.js b/server/routes/apps.jsindex 75ad0ef10a..410625784b 100644--- a/server/routes/apps.js+++ b/server/routes/apps.js@@ -347,11 +347,16 @@ router.put('/:id/task-types/:taskType', asyncHandler(async (req, res) => {}}- // Validate interval against allowed values+ // Validate interval against allowed values (also accepts 5-field cron expressions)if (interval !== undefined) {const allowedIntervals = ['rotation', 'daily', 'weekly', 'once', 'on-demand'];- if (interval !== null && (typeof interval !== 'string' || !allowedIntervals.includes(interval))) {- throw new ServerError('interval must be one of rotation|daily|weekly|once|on-demand or null', { status: 400, code: 'VALIDATION_ERROR' });+ if (interval !== null && typeof interval === 'string') {+ const isCron = interval.trim().split(/\s+/).length === 5;+ if (!isCron && !allowedIntervals.includes(interval)) {+ throw new ServerError('interval must be one of rotation|daily|weekly|once|on-demand, a cron expression, or null', { status: 400, code: 'VALIDATION_ERROR' });+ }+ } else if (interval !== null) {+ throw new ServerError('interval must be a string or null', { status: 400, code: 'VALIDATION_ERROR' });}}diff --git a/server/routes/cos.js b/server/routes/cos.jsindex 681822d8d2..c30fa3dada 100644--- a/server/routes/cos.js+++ b/server/routes/cos.js@@ -64,7 +64,7 @@ const cosConfigSchema = z.object({}).optional()}).strict();-const SCHEDULE_FIELDS = ['type', 'enabled', 'intervalMs', 'providerId', 'model', 'prompt', 'taskMetadata', 'runAfter'];+const SCHEDULE_FIELDS = ['type', 'enabled', 'intervalMs', 'cronExpression', 'providerId', 'model', 'prompt', 'taskMetadata', 'runAfter'];/*** Pick only defined values from body for schedule settings updates@@ -875,7 +875,8 @@ router.get('/schedule/interval-types', (req, res) => {weekly: 'Runs once per week',once: 'Runs once per app or globally, then stops','on-demand': 'Only runs when manually triggered',- custom: 'Custom interval in milliseconds'+ custom: 'Custom interval in milliseconds',+ cron: 'Cron expression schedule (minute hour dayOfMonth month dayOfWeek)'}});});@@ -942,7 +943,7 @@ router.get('/jobs/:id', asyncHandler(async (req, res) => {// POST /api/cos/jobs - Create a new autonomous jobrouter.post('/jobs', asyncHandler(async (req, res) => {- const { name, description, category, type, interval, intervalMs, scheduledTime, enabled, priority, autonomyLevel, promptTemplate, command, triggerAction } = req.body;+ const { name, description, category, type, interval, intervalMs, scheduledTime, cronExpression, enabled, priority, autonomyLevel, promptTemplate, command, triggerAction } = req.body;const VALID_JOB_TYPES = ['agent', 'shell', 'script'];if (!name) {@@ -959,9 +960,15 @@ router.post('/jobs', asyncHandler(async (req, res) => {throw new ServerError('promptTemplate is required for agent jobs', { status: 400, code: 'VALIDATION_ERROR' });}}+ 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' });+ }+ }const job = await autonomousJobs.createJob({- name, description, category, type, interval, intervalMs, scheduledTime,+ name, description, category, type, interval, intervalMs, scheduledTime, cronExpression,enabled, priority, autonomyLevel, promptTemplate, command, triggerAction});res.json({ success: true, job });@@ -969,10 +976,10 @@ router.post('/jobs', asyncHandler(async (req, res) => {// PUT /api/cos/jobs/:id - Update a jobrouter.put('/jobs/:id', asyncHandler(async (req, res) => {- const { name, description, category, type, interval, intervalMs, scheduledTime,+ const { name, description, category, type, interval, intervalMs, scheduledTime, cronExpression,enabled, priority, autonomyLevel, promptTemplate, command, triggerAction, weekdaysOnly } = req.body;const job = await autonomousJobs.updateJob(req.params.id, {- name, description, category, type, interval, intervalMs, scheduledTime,+ name, description, category, type, interval, intervalMs, scheduledTime, cronExpression,enabled, priority, autonomyLevel, promptTemplate, command, triggerAction, weekdaysOnly});if (!job) {diff --git a/server/services/automationScheduler.js b/server/services/automationScheduler.jsindex 0c5f8a0752..3fe8a0fcf1 100644--- a/server/services/automationScheduler.js+++ b/server/services/automationScheduler.js@@ -11,6 +11,7 @@ import EventEmitter from 'events';import { PATHS, createCachedStore } from '../lib/fileUtils.js';import * as eventScheduler from './eventScheduler.js';import * as agentActivity from './agentActivity.js';+import { getUserTimezone } from '../lib/timezone.js';const SCHEDULES_FILE = join(PATHS.agentPersonalities, 'schedules.json');const store = createCachedStore(SCHEDULES_FILE, { schedules: {} }, { context: 'automation schedules' });@@ -209,6 +210,7 @@ async function activateSchedule(id, schedule) {if (schedule.schedule.type === 'cron') {eventConfig.type = 'cron';eventConfig.cron = schedule.schedule.cron;+ eventConfig.timezone = await getUserTimezone();} else if (schedule.schedule.type === 'interval') {eventConfig.type = 'interval';eventConfig.intervalMs = schedule.schedule.intervalMs;diff --git a/server/services/autonomousJobs.js b/server/services/autonomousJobs.jsindex 80aade3ba5..418f764cce 100644--- a/server/services/autonomousJobs.js+++ b/server/services/autonomousJobs.js@@ -26,6 +26,7 @@ import { createMutex } from '../lib/asyncMutex.js'import { checkAndPrompt as autobiographyCheckAndPrompt } from './autobiography.js'import { runGoalCheckIn } from './goalCheckIn.js'import { validateCommand, redactOutput, ALLOWED_COMMANDS_SORTED } from '../lib/commandSecurity.js'+import { getUserTimezone, getLocalParts, nextLocalTime } from '../lib/timezone.js'/*** Run the moltworld-explore.mjs script as a child process (no AI agent needed).@@ -592,27 +593,29 @@ async function getEnabledJobs() {/*** Check if the current time has passed a job's scheduledTime today.- * scheduledTime is "HH:MM" in local time (e.g., "05:00").+ * scheduledTime is "HH:MM" in the user's configured timezone.* Returns true if no scheduledTime is set, or if current local time >= scheduledTime.* @param {string|null} scheduledTime - "HH:MM" or null/undefined+ * @param {string} timezone - IANA timezone string* @returns {boolean}*/-function isScheduledTimeMet(scheduledTime) {+function isScheduledTimeMet(scheduledTime, timezone) {if (!scheduledTime) return trueconst [hours, minutes] = scheduledTime.split(':').map(Number)- const now = new Date()- const nowMinutes = now.getHours() * 60 + now.getMinutes()+ const local = getLocalParts(new Date(), timezone)+ const nowMinutes = local.hour * 60 + local.minuteconst targetMinutes = hours * 60 + minutesreturn nowMinutes >= targetMinutes}/**- * Check if today is a weekday (Monday-Friday).+ * Check if today is a weekday (Monday-Friday) in the user's timezone.+ * @param {string} timezone - IANA timezone string* @returns {boolean}*/-function isWeekday() {- const day = new Date().getDay()- return day >= 1 && day <= 5+function isWeekday(timezone) {+ const local = getLocalParts(new Date(), timezone)+ return local.dayOfWeek >= 1 && local.dayOfWeek <= 5}/**@@ -622,6 +625,7 @@ function isWeekday() {async function getDueJobs() {const enabledJobs = await getEnabledJobs()const now = Date.now()+ const timezone = await getUserTimezone()const due = []for (const job of enabledJobs) {@@ -630,10 +634,10 @@ async function getDueJobs() {if (timeSinceLastRun >= job.intervalMs) {// If job has a scheduledTime, only mark due if we've passed that time today- if (!isScheduledTimeMet(job.scheduledTime)) continue+ if (!isScheduledTimeMet(job.scheduledTime, timezone)) continue// If job is weekdaysOnly, skip weekends- if (job.weekdaysOnly && !isWeekday()) continue+ if (job.weekdaysOnly && !isWeekday(timezone)) continuedue.push({...job,@@ -687,6 +691,7 @@ async function createJob(jobData) {name: jobData.name,description: jobData.description || '',category: jobData.category || 'custom',+ cronExpression: jobData.cronExpression || null,type: jobType,interval: jobData.interval || 'weekly',intervalMs: resolveIntervalMs(jobData.interval || 'weekly', jobData.intervalMs),@@ -739,7 +744,7 @@ async function updateJob(jobId, updates) {const updatableFields = ['name', 'description', 'category', 'type', 'interval', 'intervalMs',- 'scheduledTime', 'weekdaysOnly', 'enabled', 'priority', 'autonomyLevel', 'promptTemplate',+ 'scheduledTime', 'cronExpression', 'weekdaysOnly', 'enabled', 'priority', 'autonomyLevel', 'promptTemplate','command', 'triggerAction']@@ -1012,6 +1017,7 @@ async function getNextDueJob() {const enabledJobs = await getEnabledJobs()if (enabledJobs.length === 0) return null+ const timezone = await getUserTimezone()let earliest = nulllet earliestTime = Infinity@@ -1019,21 +1025,16 @@ async function getNextDueJob() {const lastRun = job.lastRun ? new Date(job.lastRun).getTime() : 0let nextDue = lastRun + job.intervalMs- // If job has scheduledTime, adjust nextDue to that time of day+ // If job has scheduledTime, find next occurrence in user's timezoneif (job.scheduledTime) {const [hours, minutes] = job.scheduledTime.split(':').map(Number)- const nextDueDate = new Date(nextDue)- nextDueDate.setHours(hours, minutes, 0, 0)- // If the scheduled time already passed on the interval-due date, it's fine- // If not, the job waits until that time- if (nextDueDate.getTime() > nextDue) {- nextDue = nextDueDate.getTime()- }+ 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)+ const isDue = Date.now() >= nextDue && isScheduledTimeMet(job.scheduledTime, timezone)earliest = {jobId: job.id,jobName: job.name,diff --git a/server/services/autonomousJobs.test.js b/server/services/autonomousJobs.test.jsindex 319f99b66e..c69951caf6 100644--- a/server/services/autonomousJobs.test.js+++ b/server/services/autonomousJobs.test.js@@ -8,6 +8,7 @@ vi.mock('./cosEvents.js', () => ({vi.mock('../lib/fileUtils.js', () => ({readJSONFile: vi.fn(),ensureDir: vi.fn().mockResolvedValue(),+ safeJSONParse: (raw, fallback) => { try { return JSON.parse(raw) } catch { return fallback } },PATHS: { cos: '/mock/data/cos', digitalTwin: '/mock/data/digital-twin', data: '/mock/data' },HOUR: 60 * 60 * 1000,DAY: 24 * 60 * 60 * 1000diff --git a/server/services/backupScheduler.js b/server/services/backupScheduler.jsindex 54b4275f98..3f9857cb8f 100644--- a/server/services/backupScheduler.js+++ b/server/services/backupScheduler.js@@ -8,6 +8,7 @@import { schedule, cancel } from './eventScheduler.js';import { getSettings } from './settings.js';import { runBackup } from './backup.js';+import { getUserTimezone } from '../lib/timezone.js';/*** Start the backup scheduler.@@ -30,11 +31,13 @@ export async function startBackupScheduler() {const cronExpression = settings.backup?.cronExpression || '0 0 * * *';const destPath = settings.backup.destPath;const excludePaths = settings.backup?.excludePaths || [];+ const timezone = await getUserTimezone();schedule({id: 'backup-daily',type: 'cron',cron: cronExpression,+ timezone,handler: async () => {console.log('💾 Backup scheduler: running scheduled backup');await runBackup(destPath, null, { excludePaths });diff --git a/server/services/cos.js b/server/services/cos.jsindex 568c77b5ab..4e98258196 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -17,7 +17,7 @@ import { parseTasksMarkdown, groupTasksByStatus, getNextTask, getAutoApprovedTasimport { isAppOnCooldown, getNextAppForReview, markAppReviewStarted, markIdleReviewStarted } from './appActivity.js';import { getActiveApps, getAppTaskTypeOverrides } from './apps.js';import { getAdaptiveCooldownMultiplier, getSkippedTaskTypes, getPerformanceSummary, checkAndRehabilitateSkippedTasks, getLearningInsights } from './taskLearning.js';-import { schedule as scheduleEvent, cancel as cancelEvent, getStats as getSchedulerStats } from './eventScheduler.js';+import { schedule as scheduleEvent, cancel as cancelEvent, getStats as getSchedulerStats, parseCronToNextRun } from './eventScheduler.js';import { createMutex } from '../lib/asyncMutex.js';import { generateProactiveTasks as generateMissionTasks, getStats as getMissionStats } from './missions.js';import { generateTaskFromJob, recordJobExecution, recordJobGateSkip, isScriptJob, executeScriptJob, isShellJob, executeShellJob } from './autonomousJobs.js';@@ -26,6 +26,7 @@ import { ensureDir, ensureDirs, formatDuration, safeJSONParse, PATHS } from '../import { sanitizeTaskMetadata } from '../lib/validation.js';import { addNotification, NOTIFICATION_TYPES } from './notifications.js';import { recordDecision, DECISION_TYPES } from './decisionLog.js';+import { getUserTimezone, nextLocalTime, todayInTimezone } from '../lib/timezone.js';// Import and re-export cosEvents from separate module to avoid circular dependenciesimport { cosEvents as _cosEvents } from './cosEvents.js';export const cosEvents = _cosEvents;@@ -3743,22 +3744,28 @@ export async function approveTask(taskId) {}/**- * Compute the next fire time for an autonomous job- * @param {Object} job - The job object with intervalMs, lastRun, scheduledTime, weekdaysOnly+ * Compute the next fire time for an autonomous job.+ * Supports two scheduling modes:+ * 1. Cron mode: job.cronExpression defines the full schedule+ * 2. Interval mode: job.intervalMs + optional job.scheduledTime (HH:MM in user timezone)+ *+ * @param {Object} job - The job object+ * @param {string} timezone - IANA timezone string for interpreting scheduledTime/cron* @returns {number} Timestamp (ms) of next fire time*/-function computeNextJobFireTime(job) {+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;+ }+const lastRun = job.lastRun ? new Date(job.lastRun).getTime() : 0;let nextDue = lastRun + job.intervalMs;- // If job has scheduledTime, adjust to that time of dayif (job.scheduledTime) {const [hours, minutes] = job.scheduledTime.split(':').map(Number);- const nextDueDate = new Date(nextDue);- nextDueDate.setHours(hours, minutes, 0, 0);- if (nextDueDate.getTime() > nextDue) {- nextDue = nextDueDate.getTime();- }+ nextDue = nextLocalTime(nextDue, hours, minutes, timezone);}// If weekdaysOnly, skip to next weekday@@ -3784,7 +3791,8 @@ async function registerSingleJobSchedule(jobId) {return;}- const nextFire = computeNextJobFireTime(job);+ const timezone = await getUserTimezone();+ const nextFire = computeNextJobFireTime(job, timezone);const delayMs = Math.max(nextFire - Date.now(), 1000);scheduleEvent({@@ -4011,12 +4019,13 @@ async function init() {await ensureDirectories();// When an agent completes, immediately try to dequeue the next pending task- cosEvents.on('agent:completed', (agent) => {+ cosEvents.on('agent:completed', async (agent) => {setImmediate(() => dequeueNextTask());// Create notification when a daily briefing completesif (agent?.metadata?.jobId === 'job-daily-briefing' && agent?.result?.success) {- const today = new Date().toISOString().split('T')[0];+ const tz = await getUserTimezone();+ const today = todayInTimezone(tz);addNotification({type: NOTIFICATION_TYPES.BRIEFING_READY,title: 'Daily Briefing Ready',diff --git a/server/services/eventScheduler.js b/server/services/eventScheduler.jsindex 66837ae273..0c85cec06c 100644--- a/server/services/eventScheduler.js+++ b/server/services/eventScheduler.js@@ -6,6 +6,7 @@*/import { cosEvents } from './cosEvents.js'+import { getLocalParts } from '../lib/timezone.js'// Maximum safe setTimeout value (2^31 - 1 ms, ~24.8 days)const MAX_TIMEOUT = 2147483647@@ -63,9 +64,10 @@ const MAX_CRON_ITERATIONS = 525960** @param {string} cronExpr - Cron expression* @param {Date} from - Starting point (default: now)- * @returns {Date|null} - Next execution time, or null if invalid/no match+ * @param {string} timezone - IANA timezone for matching (default: 'UTC')+ * @returns {Date|null} - Next execution time (UTC), or null if invalid/no match*/-function parseCronToNextRun(cronExpr, from = new Date()) {+function parseCronToNextRun(cronExpr, from = new Date(), timezone = 'UTC') {const parts = cronExpr.trim().split(/\s+/)if (parts.length !== 5) {throw new Error(`Invalid cron expression: ${cronExpr}`)@@ -97,17 +99,29 @@ function parseCronToNextRun(cronExpr, from = new Date()) {const maxDate = new Date(from)maxDate.setFullYear(maxDate.getFullYear() + 2)+ const useLocal = timezone !== 'UTC'+let iterations = 0while (next < maxDate) {if (++iterations > MAX_CRON_ITERATIONS) {console.error(`❌ Cron search exceeded ${MAX_CRON_ITERATIONS} iterations for: ${cronExpr}`)return null}- if (matchesCronField(next.getMonth() + 1, monthExpr) &&- matchesCronField(next.getDate(), dayOfMonthExpr) &&- matchesCronField(next.getDay(), dayOfWeekExpr) &&- matchesCronField(next.getHours(), hourExpr) &&- matchesCronField(next.getMinutes(), minuteExpr)) {++ let month, day, dow, hour, minute+ if (useLocal) {+ const lp = getLocalParts(next, timezone)+ month = lp.month; day = lp.day; dow = lp.dayOfWeek; hour = lp.hour; minute = lp.minute+ } else {+ month = next.getMonth() + 1; day = next.getDate(); dow = next.getDay()+ hour = next.getHours(); minute = next.getMinutes()+ }++ if (matchesCronField(month, monthExpr) &&+ matchesCronField(day, dayOfMonthExpr) &&+ matchesCronField(dow, dayOfWeekExpr) &&+ matchesCronField(hour, hourExpr) &&+ matchesCronField(minute, minuteExpr)) {return next}next.setMinutes(next.getMinutes() + 1)@@ -195,7 +209,7 @@ function createSafeTimer(callback, delayMs, eventId) {* @returns {Object} - Scheduled event*/function schedule(config) {- const { id, type, cron, intervalMs, delayMs, handler, metadata = {} } = config+ const { id, type, cron, timezone, intervalMs, delayMs, handler, metadata = {} } = configif (!id || !type || !handler) {throw new Error('Event requires id, type, and handler')@@ -210,6 +224,7 @@ function schedule(config) {id,type,cron,+ timezone: timezone || 'UTC',intervalMs,delayMs,handler,@@ -225,7 +240,7 @@ function schedule(config) {switch (type) {case 'cron':if (!cron) throw new Error('Cron type requires cron expression')- event.nextRunAt = parseCronToNextRun(cron)?.getTime() || null+ event.nextRunAt = parseCronToNextRun(cron, new Date(), event.timezone)?.getTime() || nullbreakcase 'interval':@@ -334,7 +349,7 @@ async function runEvent(event) {function updateNextRunTime(event) {switch (event.type) {case 'cron':- const nextDate = parseCronToNextRun(event.cron, new Date())+ const nextDate = parseCronToNextRun(event.cron, new Date(), event.timezone || 'UTC')event.nextRunAt = nextDate?.getTime() || nullbreakdiff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.jsindex 4006a42653..d6a4072d1f 100644--- a/server/services/taskSchedule.js+++ b/server/services/taskSchedule.js@@ -21,6 +21,8 @@ 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 { parseCronToNextRun } from './eventScheduler.js';const DATA_DIR = PATHS.cos;const SCHEDULE_FILE = join(DATA_DIR, 'task-schedule.json');@@ -32,7 +34,8 @@ export const INTERVAL_TYPES = {WEEKLY: 'weekly', // Runs once per weekONCE: 'once', // Runs once per app or globallyON_DEMAND: 'on-demand', // Only runs when manually triggered- CUSTOM: 'custom' // Custom interval in milliseconds+ CUSTOM: 'custom', // Custom interval in milliseconds+ CRON: 'cron' // Cron expression schedule};const WEEK = 7 * DAY;@@ -1247,7 +1250,9 @@ export async function shouldRunTask(taskType, appId = null) {// Determine effective interval type: per-app override takes precedenceconst perAppInterval = appId ? await getAppTaskTypeInterval(appId, taskType) : null;- const effectiveType = perAppInterval || interval.type;+ // Cron expressions (contain spaces) are stored directly as the interval value+ const isCronOverride = perAppInterval && perAppInterval.includes(' ');+ const effectiveType = isCronOverride ? INTERVAL_TYPES.CRON : (perAppInterval || interval.type);const key = `task:${taskType}`;const execution = schedule.executions[key] || { lastRun: null, count: 0, perApp: {} };@@ -1335,6 +1340,25 @@ export async function shouldRunTask(taskType, appId = null) {break;}+ case INTERVAL_TYPES.CRON: {+ // Cron expression: per-app override (stored as the interval string) or global config+ const cronExpr = isCronOverride ? perAppInterval : interval.cronExpression;+ if (!cronExpr || typeof cronExpr !== 'string' || cronExpr.trim().split(/\s+/).length !== 5) {+ result = { shouldRun: false, reason: 'invalid-cron' };+ break;+ }+ 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()) {+ result = { shouldRun: true, reason: 'cron-due', cronExpression: cronExpr, nextRunAt: nextRun.toISOString() };+ } else {+ result = { shouldRun: false, reason: 'cron-cooldown', cronExpression: cronExpr,+ nextRunAt: nextRun?.toISOString() || null };+ }+ break;+ }+default:result = { shouldRun: true, reason: 'unknown-default-rotation' };}