Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat(cos): add runAfter dependency support for task scheduling

Adam Eivy97dc4eafb3bb
diff --git a/client/src/components/cos/tabs/ScheduleTab.jsx b/client/src/components/cos/tabs/ScheduleTab.jsx
index cc301c7625..0d1ddb5073 100644
--- a/client/src/components/cos/tabs/ScheduleTab.jsx
+++ b/client/src/components/cos/tabs/ScheduleTab.jsx
@@ -57,7 +57,7 @@ function IntervalBadge({ type }) {
);
}
-function GlobalConfigControls({ taskType, config, onUpdate, onTrigger, onReset, category: _category, providers, apps, updating, setUpdating }) {
+function GlobalConfigControls({ taskType, config, onUpdate, onTrigger, onReset, category: _category, providers, apps, updating, setUpdating, allTaskTypes }) {
const [selectedType, setSelectedType] = useState(config.type);
const [selectedProviderId, setSelectedProviderId] = useState(config.providerId || '');
const [selectedModel, setSelectedModel] = useState(config.model || '');
@@ -289,6 +289,38 @@ function GlobalConfigControls({ taskType, config, onUpdate, onTrigger, onReset,
</div>
</div>
+ {allTaskTypes?.length > 1 && (
+ <div>
+ <label className="text-sm text-gray-400 block mb-2">Run After (dependencies)</label>
+ <div className="flex flex-wrap gap-2">
+ {allTaskTypes.filter(t => t !== taskType).map(dep => {
+ const isSelected = (config.runAfter || []).includes(dep);
+ return (
+ <button
+ key={dep}
+ onClick={() => {
+ const current = config.runAfter || [];
+ const updated = isSelected
+ ? current.filter(d => d !== dep)
+ : [...current, dep];
+ onUpdate(taskType, { runAfter: updated.length > 0 ? updated : null });
+ }}
+ disabled={updating}
+ className={`text-xs px-2 py-1 rounded border transition-colors ${
+ isSelected
+ ? 'bg-port-accent/20 border-port-accent/50 text-port-accent'
+ : 'bg-port-card border-port-border text-gray-400 hover:border-gray-500'
+ }`}
+ >
+ {dep}
+ </button>
+ );
+ })}
+ </div>
+ <p className="text-xs text-gray-500 mt-1">This task will wait for selected tasks to complete first within the same cycle</p>
+ </div>
+ )}
+
<div className="flex gap-2">
{activeApps.length > 0 ? (
<div className="relative" ref={appSelectorRef}>
@@ -493,7 +525,7 @@ function PerAppOverrideList({ taskType, config, apps, onUpdateOverride, onBulkTo
);
}
-function AppTaskTypeRow({ taskType, config, onUpdate, onTrigger, onReset, providers, apps, onUpdateOverride, onBulkToggleOverride }) {
+function AppTaskTypeRow({ taskType, config, onUpdate, onTrigger, onReset, providers, apps, onUpdateOverride, onBulkToggleOverride, allTaskTypes }) {
const [expanded, setExpanded] = useState(false);
const [updating, setUpdating] = useState(false);
@@ -520,12 +552,20 @@ function AppTaskTypeRow({ taskType, config, onUpdate, onTrigger, onReset, provid
{!config.enabled && (
<span className="text-xs px-2 py-0.5 bg-gray-600/50 text-gray-400 rounded">Disabled</span>
)}
+ {config.status?.reason === 'waiting-on-dependencies' && (
+ <span className="text-xs px-2 py-0.5 bg-port-warning/20 text-port-warning rounded" title={`Waiting for: ${config.status.pendingDeps?.join(', ')}`}>
+ Waiting on deps
+ </span>
+ )}
+ </div>
+ <div className="flex items-center gap-2 text-xs text-gray-500 flex-wrap">
+ {config.globalLastRun && (
+ <span>Last run: {new Date(config.globalLastRun).toLocaleDateString()} ({config.globalRunCount || 0} total)</span>
+ )}
+ {config.runAfter?.length > 0 && (
+ <span className="text-gray-500">after: {config.runAfter.join(', ')}</span>
+ )}
</div>
- {config.globalLastRun && (
- <div className="text-xs text-gray-500">
- Last run: {new Date(config.globalLastRun).toLocaleDateString()} ({config.globalRunCount || 0} total)
- </div>
- )}
</div>
<div className="flex items-center gap-2">
@@ -557,6 +597,7 @@ function AppTaskTypeRow({ taskType, config, onUpdate, onTrigger, onReset, provid
apps={apps}
updating={updating}
setUpdating={setUpdating}
+ allTaskTypes={allTaskTypes}
/>
</div>
@@ -578,6 +619,7 @@ function AppTaskTypeSection({ tasks, onUpdate, onTrigger, onReset, providers, ap
if (taskEntries.length === 0) return null;
const enabledCount = taskEntries.filter(([, config]) => config.enabled).length;
+ const allTaskTypes = taskEntries.map(([taskType]) => taskType);
return (
<div className="space-y-3">
@@ -603,6 +645,7 @@ function AppTaskTypeSection({ tasks, onUpdate, onTrigger, onReset, providers, ap
apps={apps}
onUpdateOverride={onUpdateOverride}
onBulkToggleOverride={onBulkToggleOverride}
+ allTaskTypes={allTaskTypes}
/>
))}
</div>
diff --git a/server/routes/cos.js b/server/routes/cos.js
index d66582648f..3139973af0 100644
--- a/server/routes/cos.js
+++ b/server/routes/cos.js
@@ -63,7 +63,7 @@ const cosConfigSchema = z.object({
}).optional()
}).strict();
-const SCHEDULE_FIELDS = ['type', 'enabled', 'intervalMs', 'providerId', 'model', 'prompt', 'taskMetadata'];
+const SCHEDULE_FIELDS = ['type', 'enabled', 'intervalMs', 'providerId', 'model', 'prompt', 'taskMetadata', 'runAfter'];
/**
* Pick only defined values from body for schedule settings updates
@@ -89,6 +89,17 @@ function pickScheduleSettings(body) {
}
settings.taskMetadata = sanitized;
}
+ if (settings.runAfter !== undefined && settings.runAfter !== null) {
+ if (!Array.isArray(settings.runAfter)) {
+ throw new ServerError('runAfter must be an array of task type strings or null', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ if (!settings.runAfter.every(v => typeof v === 'string')) {
+ throw new ServerError('runAfter entries must be strings', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ if (settings.runAfter.length === 0) {
+ settings.runAfter = null;
+ }
+ }
return settings;
}
@@ -691,7 +702,13 @@ router.get('/schedule/task/:taskType', asyncHandler(async (req, res) => {
// PUT /api/cos/schedule/task/:taskType - Update interval for a task type (unified)
router.put('/schedule/task/:taskType', asyncHandler(async (req, res) => {
const { taskType } = req.params;
- const result = await taskSchedule.updateTaskInterval(taskType, pickScheduleSettings(req.body));
+ const settings = pickScheduleSettings(req.body);
+ // Filter self-references from runAfter to prevent permanent blocking
+ if (Array.isArray(settings.runAfter)) {
+ settings.runAfter = settings.runAfter.filter(dep => dep !== taskType);
+ if (settings.runAfter.length === 0) settings.runAfter = null;
+ }
+ const result = await taskSchedule.updateTaskInterval(taskType, settings);
res.json({ success: true, taskType, interval: result });
}));
diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.js
index 3c9c5b8c65..808da54444 100644
--- a/server/services/taskSchedule.js
+++ b/server/services/taskSchedule.js
@@ -17,7 +17,7 @@ import { writeFile } from 'fs/promises';
import { existsSync } from 'fs';
import { join } from 'path';
import { cosEvents, emitLog } from './cos.js';
-import { DAY, ensureDir, HOUR, readJSONFile, PATHS } from '../lib/fileUtils.js';
+import { DAY, ensureDir, HOUR, readJSONFile, PATHS, safeDate } from '../lib/fileUtils.js';
import { getAdaptiveCooldownMultiplier } from './taskLearning.js';
import { isTaskTypeEnabledForApp, getAppTaskTypeInterval, getActiveApps, getAppTaskTypeOverrides } from './apps.js';
import { PORTOS_UI_URL } from '../lib/ports.js';
@@ -1174,6 +1174,34 @@ export async function getExecutionHistory(taskType) {
return schedule.executions[key] || { lastRun: null, count: 0, perApp: {} };
}
+/**
+ * Check if all runAfter dependencies have completed since this task's last run.
+ * Returns { satisfied, pending } where pending lists unfinished dependency task types.
+ */
+function checkRunAfterDeps(schedule, taskType, appId = null) {
+ const interval = schedule.tasks[taskType];
+ const deps = interval?.runAfter;
+ if (!deps || deps.length === 0) return { satisfied: true, pending: [] };
+
+ const key = `task:${taskType}`;
+ const execution = schedule.executions[key] || { lastRun: null, perApp: {} };
+ const ownLastRun = safeDate(appId ? execution.perApp[appId]?.lastRun : execution.lastRun);
+
+ const pending = [];
+ for (const dep of deps) {
+ const depKey = `task:${dep}`;
+ const depExec = schedule.executions[depKey] || { lastRun: null, perApp: {} };
+ const depLastRun = safeDate(appId ? depExec.perApp[appId]?.lastRun : depExec.lastRun);
+
+ // Dependency must have run after this task's last run (i.e., within the current cycle)
+ if (depLastRun <= ownLastRun) {
+ pending.push(dep);
+ }
+ }
+
+ return { satisfied: pending.length === 0, pending };
+}
+
/**
* Check if a task type should run for a specific app (or globally)
*/
@@ -1227,71 +1255,82 @@ export async function shouldRunTask(taskType, appId = null) {
return result;
};
+ let result;
+
switch (effectiveType) {
case INTERVAL_TYPES.ROTATION:
- return { shouldRun: true, reason: 'rotation' };
+ result = { shouldRun: true, reason: 'rotation' };
+ break;
case INTERVAL_TYPES.DAILY: {
const learningAdjustment = await getPerformanceAdjustedInterval(taskType, DAY);
const adjustedInterval = learningAdjustment.adjustedIntervalMs;
-
if (timeSinceLastRun >= adjustedInterval) {
- return buildResult(true, learningAdjustment.adjusted ? 'daily-due-adjusted' : 'daily-due', DAY, { learningAdjustment });
+ result = buildResult(true, learningAdjustment.adjusted ? 'daily-due-adjusted' : 'daily-due', DAY, { learningAdjustment });
+ } else {
+ result = buildResult(false, learningAdjustment.adjusted ? 'daily-cooldown-adjusted' : 'daily-cooldown', DAY, {
+ learningAdjustment, nextRunIn: adjustedInterval - timeSinceLastRun,
+ nextRunAt: new Date(lastRun + adjustedInterval).toISOString(),
+ baseIntervalMs: DAY, adjustedIntervalMs: adjustedInterval
+ });
}
- return buildResult(false, learningAdjustment.adjusted ? 'daily-cooldown-adjusted' : 'daily-cooldown', DAY, {
- learningAdjustment,
- nextRunIn: adjustedInterval - timeSinceLastRun,
- nextRunAt: new Date(lastRun + adjustedInterval).toISOString(),
- baseIntervalMs: DAY,
- adjustedIntervalMs: adjustedInterval
- });
+ break;
}
case INTERVAL_TYPES.WEEKLY: {
const learningAdjustment = await getPerformanceAdjustedInterval(taskType, WEEK);
const adjustedInterval = learningAdjustment.adjustedIntervalMs;
-
if (timeSinceLastRun >= adjustedInterval) {
- return buildResult(true, learningAdjustment.adjusted ? 'weekly-due-adjusted' : 'weekly-due', WEEK, { learningAdjustment });
+ result = buildResult(true, learningAdjustment.adjusted ? 'weekly-due-adjusted' : 'weekly-due', WEEK, { learningAdjustment });
+ } else {
+ result = buildResult(false, learningAdjustment.adjusted ? 'weekly-cooldown-adjusted' : 'weekly-cooldown', WEEK, {
+ learningAdjustment, nextRunIn: adjustedInterval - timeSinceLastRun,
+ nextRunAt: new Date(lastRun + adjustedInterval).toISOString(),
+ baseIntervalMs: WEEK, adjustedIntervalMs: adjustedInterval
+ });
}
- return buildResult(false, learningAdjustment.adjusted ? 'weekly-cooldown-adjusted' : 'weekly-cooldown', WEEK, {
- learningAdjustment,
- nextRunIn: adjustedInterval - timeSinceLastRun,
- nextRunAt: new Date(lastRun + adjustedInterval).toISOString(),
- baseIntervalMs: WEEK,
- adjustedIntervalMs: adjustedInterval
- });
+ break;
}
case INTERVAL_TYPES.ONCE:
- if (appExecution.count === 0) {
- return { shouldRun: true, reason: 'once-first-run' };
- }
- return { shouldRun: false, reason: 'once-completed', completedAt: appExecution.lastRun };
+ result = appExecution.count === 0
+ ? { shouldRun: true, reason: 'once-first-run' }
+ : { shouldRun: false, reason: 'once-completed', completedAt: appExecution.lastRun };
+ break;
case INTERVAL_TYPES.ON_DEMAND:
- return { shouldRun: false, reason: 'on-demand-only' };
+ result = { shouldRun: false, reason: 'on-demand-only' };
+ break;
case INTERVAL_TYPES.CUSTOM: {
const baseInterval = interval.intervalMs || DAY;
const learningAdjustment = await getPerformanceAdjustedInterval(taskType, baseInterval);
const adjustedInterval = learningAdjustment.adjustedIntervalMs;
-
if (timeSinceLastRun >= adjustedInterval) {
- return buildResult(true, learningAdjustment.adjusted ? 'custom-due-adjusted' : 'custom-due', baseInterval, { learningAdjustment });
+ result = buildResult(true, learningAdjustment.adjusted ? 'custom-due-adjusted' : 'custom-due', baseInterval, { learningAdjustment });
+ } else {
+ result = buildResult(false, learningAdjustment.adjusted ? 'custom-cooldown-adjusted' : 'custom-cooldown', baseInterval, {
+ learningAdjustment, nextRunIn: adjustedInterval - timeSinceLastRun,
+ nextRunAt: new Date(lastRun + adjustedInterval).toISOString(),
+ baseIntervalMs: baseInterval, adjustedIntervalMs: adjustedInterval
+ });
}
- return buildResult(false, learningAdjustment.adjusted ? 'custom-cooldown-adjusted' : 'custom-cooldown', baseInterval, {
- learningAdjustment,
- nextRunIn: adjustedInterval - timeSinceLastRun,
- nextRunAt: new Date(lastRun + adjustedInterval).toISOString(),
- baseIntervalMs: baseInterval,
- adjustedIntervalMs: adjustedInterval
- });
+ break;
}
default:
- return { shouldRun: true, reason: 'unknown-default-rotation' };
+ result = { shouldRun: true, reason: 'unknown-default-rotation' };
}
+
+ // If the task would run, check runAfter dependencies — blocked until all deps have run since our last run
+ if (result.shouldRun && interval.runAfter?.length > 0) {
+ const depCheck = checkRunAfterDeps(schedule, taskType, appId);
+ if (!depCheck.satisfied) {
+ return { shouldRun: false, reason: 'waiting-on-dependencies', pendingDeps: depCheck.pending };
+ }
+ }
+
+ return result;
}
/**