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: custom scheduled tasks per app via app-scoped autonomous jobs

Adam Eivy1a4818cf0248
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index a6658cf8b4..4aaad56b89 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,7 @@
## Added
+- **Custom scheduled tasks per app** — Each managed app's Automation tab gains a "Custom Tasks" section where you write your own prompt and pick a schedule (interval or cron), and a Chief-of-Staff agent runs it against that app's repo on cadence — just like the built-in task types, but fully your own. Per task you choose priority, autonomy level, and whether the agent works in an isolated worktree and opens a PR (or commits/auto-merges) in the target app. Run-now triggers an immediate pass. Custom tasks also appear (with an app badge) in the Chief of Staff → System Tasks list, where the create/edit form now has an optional app-scope picker so any agent job can be pointed at a specific app or left global.
- **Password-protected federated peers** — If one of your PortOS instances sits behind an HTTP Basic auth proxy (Tailscale `serve`, Caddy, nginx), its peers can now reach it: probes were failing with `HTTP 401`. Each peer in the Instances page gains an optional credential — set a username (optional) and password when adding a peer, or click "set credential" on an existing peer. The credential is attached to every outbound hop to that peer (health probes, snapshot sync, per-record push/pull, asset pulls, and the live agent socket relay), so a reachable-but-401 peer now connects. A peer that returns 401/403 is flagged "auth required" in the UI instead of just reading as offline. Credentials are stored locally per peer and are never synced or announced to the peer itself.
- **[issue-708] Digital Twin "Voice" tab — spoken vs. written style** — Paste a transcript of yourself speaking and the Digital Twin compares it against how you write (a pasted sample, or your existing twin documents), surfacing where your spoken voice differs from your writing — formality, verbosity, sentence length, directness, filler words — and suggesting a communication profile for voice contexts that you can apply in one click.
- **[issue-711] "While You Were Away" dashboard card** — A new dashboard widget recaps what your agents did since your last visit: a count of completed runs, success/failure tally, total time worked, and the most recent wins plus anything that failed and needs a look. Each item opens the agents view, and a "Mark as seen" button resets the window to now. It appears on the Everything and Agent Watch layouts and can be added to any layout via Arrange.
diff --git a/client/src/components/apps/tabs/AutomationTab.jsx b/client/src/components/apps/tabs/AutomationTab.jsx
index 3a7465d708..5632f15dea 100644
--- a/client/src/components/apps/tabs/AutomationTab.jsx
+++ b/client/src/components/apps/tabs/AutomationTab.jsx
@@ -7,6 +7,7 @@ import ToggleSwitch from '../../ToggleSwitch';
import * as api from '../../../services/api';
import { AGENT_OPTIONS, toggleAppMetadataOverride, agentOptionButtonClass } from '../../cos/constants';
import { isCronExpression, describeCron } from '../../../utils/cronHelpers';
+import CustomTasksSection from './CustomTasksSection';
const INTERVAL_OPTIONS = [
{ value: null, label: 'Inherit Global' },
@@ -238,6 +239,10 @@ export default function AutomationTab({ appId, appName }) {
})}
</div>
)}
+
+ <div className="border-t border-port-border pt-4">
+ <CustomTasksSection appId={appId} appName={appName} />
+ </div>
</div>
);
}
diff --git a/client/src/components/apps/tabs/CustomTasksSection.jsx b/client/src/components/apps/tabs/CustomTasksSection.jsx
new file mode 100644
index 0000000000..065d2bab51
--- /dev/null
+++ b/client/src/components/apps/tabs/CustomTasksSection.jsx
@@ -0,0 +1,368 @@
+import { useState, useEffect, useCallback } from 'react';
+import { Plus, Play, Trash2, Edit3, Save, X, Clock } from 'lucide-react';
+import toast from '../../ui/Toast';
+import ToggleSwitch from '../../ToggleSwitch';
+import * as api from '../../../services/api';
+import { timeAgo } from '../../../utils/formatters';
+import { CRON_PRESETS, describeCron } from '../../../utils/cronHelpers';
+import { AGENT_OPTIONS, agentOptionButtonClass } from '../../cos/constants';
+
+const INTERVAL_OPTIONS = [
+ { value: 'hourly', label: 'Every Hour' },
+ { value: 'every-2-hours', label: 'Every 2 Hours' },
+ { value: 'every-4-hours', label: 'Every 4 Hours' },
+ { value: 'every-8-hours', label: 'Every 8 Hours' },
+ { value: 'daily', label: 'Daily' },
+ { value: 'weekly', label: 'Weekly' },
+ { value: 'biweekly', label: 'Every 2 Weeks' },
+ { value: 'monthly', label: 'Monthly' }
+];
+
+const PRIORITY_OPTIONS = ['LOW', 'MEDIUM', 'HIGH', 'CRITICAL'];
+const AUTONOMY_OPTIONS = [
+ { value: 'standby', label: 'Standby' },
+ { value: 'assistant', label: 'Assistant' },
+ { value: 'manager', label: 'Manager' },
+ { value: 'yolo', label: 'YOLO' }
+];
+
+// Custom tasks always spawn an AI agent scoped to this app. The worktree/PR/simplify
+// toggles below mirror the per-app built-in task overrides for visual consistency.
+const TASK_META_FIELDS = AGENT_OPTIONS.filter(o => ['useWorktree', 'openPR', 'simplify'].includes(o.field));
+
+function emptyForm() {
+ return {
+ name: '',
+ description: '',
+ promptTemplate: '',
+ scheduleMode: 'interval',
+ interval: 'weekly',
+ scheduledTime: '',
+ cronExpression: '',
+ priority: 'MEDIUM',
+ autonomyLevel: 'manager',
+ taskMetadata: { useWorktree: true, openPR: true, simplify: true }
+ };
+}
+
+function formFromJob(job) {
+ return {
+ name: job.name || '',
+ description: job.description || '',
+ promptTemplate: job.promptTemplate || '',
+ scheduleMode: job.cronExpression ? 'cron' : 'interval',
+ interval: job.interval || 'weekly',
+ scheduledTime: job.scheduledTime || '',
+ cronExpression: job.cronExpression || '',
+ priority: job.priority || 'MEDIUM',
+ autonomyLevel: job.autonomyLevel || 'manager',
+ taskMetadata: { useWorktree: false, openPR: false, simplify: false, ...(job.taskMetadata || {}) }
+ };
+}
+
+// Build the API payload from form state, scoped to this app as an agent job.
+function toPayload(form, appId) {
+ const payload = {
+ name: form.name.trim(),
+ description: form.description.trim(),
+ type: 'agent',
+ appId,
+ promptTemplate: form.promptTemplate,
+ priority: form.priority,
+ autonomyLevel: form.autonomyLevel,
+ taskMetadata: form.taskMetadata
+ };
+ if (form.scheduleMode === 'cron') {
+ payload.cronExpression = form.cronExpression?.trim() || null;
+ payload.scheduledTime = null;
+ } else {
+ payload.cronExpression = null;
+ payload.interval = form.interval;
+ payload.scheduledTime = form.scheduledTime || null;
+ }
+ return payload;
+}
+
+function scheduleSummary(job) {
+ if (job.cronExpression) return describeCron(job.cronExpression);
+ const label = INTERVAL_OPTIONS.find(i => i.value === job.interval)?.label || job.interval;
+ return job.scheduledTime ? `${label} at ${job.scheduledTime}` : label;
+}
+
+function TaskForm({ form, setForm, onSave, onCancel, saveLabel }) {
+ const update = (key, val) => setForm(f => ({ ...f, [key]: val }));
+ const toggleMeta = (field) =>
+ setForm(f => ({ ...f, taskMetadata: { ...f.taskMetadata, [field]: !f.taskMetadata?.[field] } }));
+
+ return (
+ <div className="space-y-3 bg-port-card border border-port-accent/50 rounded-lg p-4">
+ <input
+ type="text"
+ placeholder="Task name *"
+ value={form.name}
+ onChange={e => update('name', e.target.value)}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"
+ />
+ <input
+ type="text"
+ placeholder="Description"
+ value={form.description}
+ onChange={e => update('description', e.target.value)}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"
+ />
+ <textarea
+ placeholder="Prompt for the agent *"
+ value={form.promptTemplate}
+ onChange={e => update('promptTemplate', e.target.value)}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm font-mono h-32"
+ />
+
+ {/* Schedule */}
+ <div className="space-y-2">
+ <div className="flex items-center gap-2">
+ <span className="text-xs text-gray-400">Schedule:</span>
+ {['interval', 'cron'].map(mode => (
+ <button
+ key={mode}
+ type="button"
+ onClick={() => update('scheduleMode', mode)}
+ className={`px-2 py-1 text-xs rounded transition-colors ${
+ form.scheduleMode === mode ? 'bg-port-accent/20 text-port-accent' : 'bg-port-bg text-gray-500 hover:text-gray-300'
+ }`}
+ >
+ {mode === 'interval' ? 'Interval' : 'Cron'}
+ </button>
+ ))}
+ </div>
+ {form.scheduleMode === 'cron' ? (
+ <div className="flex gap-2 items-center flex-wrap">
+ <input
+ type="text"
+ value={form.cronExpression || ''}
+ onChange={e => update('cronExpression', e.target.value)}
+ className="flex-1 min-w-[10rem] 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) update('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>
+ {form.cronExpression && <span className="text-xs text-gray-500">{describeCron(form.cronExpression)}</span>}
+ </div>
+ ) : (
+ <div className="flex gap-3">
+ <select
+ value={form.interval}
+ onChange={e => update('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={form.scheduledTime || ''}
+ onChange={e => update('scheduledTime', e.target.value || '')}
+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"
+ title="Run at a specific time (leave empty for any time)"
+ />
+ </div>
+ )}
+ </div>
+
+ {/* Priority + autonomy */}
+ <div className="flex gap-3">
+ <select
+ value={form.priority}
+ onChange={e => update('priority', e.target.value)}
+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"
+ >
+ {PRIORITY_OPTIONS.map(p => <option key={p} value={p}>{p}</option>)}
+ </select>
+ <select
+ value={form.autonomyLevel}
+ onChange={e => update('autonomyLevel', e.target.value)}
+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"
+ >
+ {AUTONOMY_OPTIONS.map(opt => <option key={opt.value} value={opt.value}>{opt.label}</option>)}
+ </select>
+ </div>
+
+ {/* Git-workflow options */}
+ <div className="flex items-center gap-2 flex-wrap">
+ <span className="text-xs text-gray-400">Options:</span>
+ {TASK_META_FIELDS.map(({ field, shortLabel, label }) => {
+ const effective = !!form.taskMetadata?.[field];
+ return (
+ <button
+ key={field}
+ type="button"
+ onClick={() => toggleMeta(field)}
+ aria-pressed={effective}
+ aria-label={`${label}: ${effective ? 'on' : 'off'}`}
+ title={`${label}: ${effective ? 'on' : 'off'}`}
+ className={`text-xs px-1.5 py-0.5 rounded transition-colors border ${agentOptionButtonClass(effective, true)}`}
+ >
+ {shortLabel}
+ </button>
+ );
+ })}
+ </div>
+
+ <div className="flex justify-end gap-2">
+ <button onClick={onCancel} className="flex items-center gap-1 px-3 py-1.5 text-sm text-gray-400 hover:text-white transition-colors">
+ <X size={14} /> Cancel
+ </button>
+ <button onClick={onSave} className="flex items-center gap-1 px-3 py-1.5 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded-lg text-sm transition-colors">
+ <Save size={14} /> {saveLabel}
+ </button>
+ </div>
+ </div>
+ );
+}
+
+export default function CustomTasksSection({ appId, appName }) {
+ const [tasks, setTasks] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [showCreate, setShowCreate] = useState(false);
+ const [createForm, setCreateForm] = useState(emptyForm);
+ const [editingId, setEditingId] = useState(null);
+ const [editForm, setEditForm] = useState(emptyForm);
+ const [triggering, setTriggering] = useState(null);
+
+ const fetchTasks = useCallback(async () => {
+ const data = await api.getCosJobs().catch(() => null);
+ setTasks((data?.jobs || []).filter(j => j.appId === appId));
+ setLoading(false);
+ }, [appId]);
+
+ useEffect(() => { fetchTasks(); }, [fetchTasks]);
+
+ const validate = (form) => {
+ if (!form.name.trim()) { toast.error('Name is required'); return false; }
+ if (!form.promptTemplate.trim()) { toast.error('Prompt is required'); return false; }
+ if (form.scheduleMode === 'cron' && (!form.cronExpression?.trim() || form.cronExpression.trim().split(/\s+/).length !== 5)) {
+ toast.error('A valid 5-field cron expression is required'); return false;
+ }
+ return true;
+ };
+
+ const handleCreate = async () => {
+ if (!validate(createForm)) return;
+ const created = await api.createCosJob(toPayload(createForm, appId)).catch(err => { toast.error(err.message); return null; });
+ if (!created) return;
+ toast.success('Custom task created');
+ setCreateForm(emptyForm());
+ setShowCreate(false);
+ fetchTasks();
+ };
+
+ const startEdit = (job) => {
+ setEditingId(job.id);
+ setEditForm(formFromJob(job));
+ };
+
+ const handleEditSave = async () => {
+ if (!validate(editForm)) return;
+ const result = await api.updateCosJob(editingId, toPayload(editForm, appId)).catch(err => { toast.error(err.message); return null; });
+ if (!result) return;
+ toast.success('Custom task updated');
+ setEditingId(null);
+ fetchTasks();
+ };
+
+ const handleToggle = async (job) => {
+ const result = await api.toggleCosJob(job.id).catch(err => { toast.error(err.message); return null; });
+ if (!result) return;
+ setTasks(prev => prev.map(t => t.id === job.id ? { ...t, enabled: result.job.enabled } : t));
+ };
+
+ const handleTrigger = async (job) => {
+ setTriggering(job.id);
+ const result = await api.triggerCosJob(job.id).catch(err => { toast.error(err.message); return null; });
+ setTriggering(null);
+ if (result?.success !== false) toast.success(`Triggered "${job.name}" for ${appName}`);
+ else toast.error('Task failed to trigger');
+ fetchTasks();
+ };
+
+ const handleDelete = async (job) => {
+ const result = await api.deleteCosJob(job.id).catch(err => { toast.error(err.message); return null; });
+ if (!result) return;
+ toast.success('Custom task deleted');
+ setTasks(prev => prev.filter(t => t.id !== job.id));
+ };
+
+ return (
+ <div className="space-y-3">
+ <div className="flex items-center justify-between">
+ <div>
+ <h3 className="text-lg font-semibold text-white">Custom Tasks</h3>
+ <p className="text-sm text-gray-500">Your own prompt + schedule, run by a CoS agent against this app</p>
+ </div>
+ <button
+ onClick={() => setShowCreate(v => !v)}
+ className="flex items-center gap-1 text-sm text-port-accent hover:text-port-accent/80 transition-colors"
+ >
+ <Plus size={16} /> New Custom Task
+ </button>
+ </div>
+
+ {showCreate && (
+ <TaskForm form={createForm} setForm={setCreateForm} onSave={handleCreate} onCancel={() => setShowCreate(false)} saveLabel="Create" />
+ )}
+
+ {loading ? (
+ <div className="text-sm text-gray-500 py-4">Loading custom tasks…</div>
+ ) : tasks.length === 0 ? (
+ !showCreate && (
+ <div className="bg-port-card border border-port-border rounded-lg p-6 text-center text-gray-500 text-sm">
+ No custom tasks yet. Create one to run a prompt on a schedule for {appName}.
+ </div>
+ )
+ ) : (
+ <div className="space-y-2">
+ {tasks.map(job => (
+ <div key={job.id} className={`bg-port-card border rounded-lg ${job.enabled ? 'border-port-border' : 'border-port-border/50 opacity-70'}`}>
+ {editingId === job.id ? (
+ <div className="p-3">
+ <TaskForm form={editForm} setForm={setEditForm} onSave={handleEditSave} onCancel={() => setEditingId(null)} saveLabel="Save" />
+ </div>
+ ) : (
+ <div className="p-3 space-y-1">
+ <div className="flex items-center gap-3">
+ <ToggleSwitch enabled={job.enabled} onChange={() => handleToggle(job)} size="sm" activeColor="bg-port-success" ariaLabel={job.enabled ? 'Disable task' : 'Enable task'} />
+ <div className="flex-1 min-w-0">
+ <span className="text-white font-medium truncate">{job.name}</span>
+ <div className="flex items-center gap-3 text-xs text-gray-500 mt-0.5">
+ <span className="flex items-center gap-1"><Clock size={10} />{scheduleSummary(job)}</span>
+ <span>Last: {timeAgo(job.lastRun, 'Never')}</span>
+ <span>Runs: {job.runCount || 0}</span>
+ </div>
+ </div>
+ <div className="flex items-center gap-1 shrink-0">
+ <button onClick={() => handleTrigger(job)} disabled={triggering === job.id || !job.enabled} className="p-1.5 text-gray-500 hover:text-port-accent transition-colors disabled:opacity-40" title="Run now">
+ <Play size={14} />
+ </button>
+ <button onClick={() => startEdit(job)} className="p-1.5 text-gray-500 hover:text-white transition-colors" title="Edit">
+ <Edit3 size={14} />
+ </button>
+ <button onClick={() => handleDelete(job)} className="p-1.5 text-red-400/60 hover:text-red-400 transition-colors" title="Delete">
+ <Trash2 size={14} />
+ </button>
+ </div>
+ </div>
+ {job.description && <p className="text-xs text-gray-500 pl-12">{job.description}</p>}
+ </div>
+ )}
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/cos/tabs/JobsTab.jsx b/client/src/components/cos/tabs/JobsTab.jsx
index 9d26f6fe0e..dff803dd58 100644
--- a/client/src/components/cos/tabs/JobsTab.jsx
+++ b/client/src/components/cos/tabs/JobsTab.jsx
@@ -87,6 +87,8 @@ function normalizeJobPayload(formData) {
payload.command = null;
payload.triggerAction = null;
}
+ // Empty app picker selection ('') → undefined so the server treats it as a global job.
+ if (!payload.appId) payload.appId = undefined;
if (payload.scheduleMode === 'cron') {
payload.cronExpression = payload.cronExpression?.trim() || null;
payload.scheduledTime = null;
@@ -194,10 +196,11 @@ function getJobTypeLabel(job) {
return 'AI';
}
-function JobCard({ job, onToggle, onTrigger, onDelete, onUpdate }) {
+function JobCard({ job, apps, onToggle, onTrigger, onDelete, onUpdate }) {
const [expanded, setExpanded] = useState(false);
const [editing, setEditing] = useState(false);
const [editData, setEditData] = useState({});
+ const appName = job.appId ? (apps.find(a => a.id === job.appId)?.name || job.appId) : null;
const isShell = job.type === 'shell';
const isScript = job.type === 'script';
@@ -213,7 +216,8 @@ function JobCard({ job, onToggle, onTrigger, onDelete, onUpdate }) {
cronExpression: job.cronExpression || '',
priority: job.priority,
autonomyLevel: job.autonomyLevel,
- promptTemplate: job.promptTemplate || ''
+ promptTemplate: job.promptTemplate || '',
+ appId: job.appId || ''
};
// Always initialize shell fields so switching type to 'shell' during editing works
base.command = job.command || '';
@@ -277,6 +281,11 @@ function JobCard({ job, onToggle, onTrigger, onDelete, onUpdate }) {
<span className="px-1.5 py-0.5 bg-port-bg text-gray-400 text-xs rounded">
{job.category}
</span>
+ {appName && (
+ <span className="px-1.5 py-0.5 bg-port-accent/15 text-port-accent text-xs rounded" title={`Scoped to app: ${appName}`}>
+ {appName}
+ </span>
+ )}
</div>
<div className="flex items-center gap-3 text-xs text-gray-500 mt-1">
<span className="flex items-center gap-1">
@@ -382,6 +391,19 @@ function JobCard({ job, onToggle, onTrigger, onDelete, onUpdate }) {
)}
</div>
<ScheduleFields data={editData} onChange={(key, val) => setEditData(d => ({ ...d, [key]: val }))} />
+ {editData.type !== 'shell' && editData.type !== 'script' && (
+ <div className="flex items-center gap-2">
+ <span className="text-xs text-gray-400">App scope:</span>
+ <select
+ value={editData.appId || ''}
+ onChange={e => setEditData(d => ({ ...d, appId: e.target.value }))}
+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"
+ >
+ <option value="">Global (PortOS)</option>
+ {apps.map(a => <option key={a.id} value={a.id}>{a.name}</option>)}
+ </select>
+ </div>
+ )}
{editData.config && (
<BriefingConfig
config={editData.config}
@@ -495,6 +517,7 @@ function JobCard({ job, onToggle, onTrigger, onDelete, onUpdate }) {
export default function JobsTab() {
const [jobs, setJobs] = useState([]);
+ const [apps, setApps] = useState([]);
const [stats, setStats] = useState(null);
const [loading, setLoading] = useState(true);
const [showCreate, setShowCreate] = useState(false);
@@ -512,6 +535,7 @@ export default function JobsTab() {
promptTemplate: '',
command: '',
triggerAction: 'log-only',
+ appId: '',
enabled: false
});
@@ -529,6 +553,10 @@ export default function JobsTab() {
useEffect(() => { fetchJobs(); }, [fetchJobs]);
+ useEffect(() => {
+ api.getApps().then(data => setApps(data?.apps || data || [])).catch(() => setApps([]));
+ }, []);
+
const handleCreate = async () => {
if (!newJob.name.trim()) {
toast.error('Name is required');
@@ -567,6 +595,7 @@ export default function JobsTab() {
promptTemplate: '',
command: '',
triggerAction: 'log-only',
+ appId: '',
enabled: false
});
setShowCreate(false);
@@ -718,6 +747,19 @@ export default function JobsTab() {
)}
</div>
<ScheduleFields data={newJob} onChange={(key, val) => setNewJob(j => ({ ...j, [key]: val }))} />
+ {newJob.type !== 'shell' && newJob.type !== 'script' && (
+ <div className="flex items-center gap-2">
+ <span className="text-xs text-gray-400">App scope:</span>
+ <select
+ value={newJob.appId || ''}
+ onChange={e => setNewJob(j => ({ ...j, appId: e.target.value }))}
+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"
+ >
+ <option value="">Global (PortOS)</option>
+ {apps.map(a => <option key={a.id} value={a.id}>{a.name}</option>)}
+ </select>
+ </div>
+ )}
{newJob.type === 'shell' ? (
<>
<textarea
@@ -777,6 +819,7 @@ export default function JobsTab() {
<JobCard
key={job.id}
job={job}
+ apps={apps}
onToggle={handleToggle}
onTrigger={handleTrigger}
onDelete={handleDelete}
diff --git a/docs/plans/2026-06-04-custom-scheduled-app-tasks.md b/docs/plans/2026-06-04-custom-scheduled-app-tasks.md
new file mode 100644
index 0000000000..59f7eec815
--- /dev/null
+++ b/docs/plans/2026-06-04-custom-scheduled-app-tasks.md
@@ -0,0 +1,174 @@
+# Custom Scheduled App Tasks
+
+## Context
+
+The user wants to create **custom scheduled tasks per managed app**: provide a free-form
+prompt + a schedule (interval or cron), scoped to one app, running through the CoS
+(Chief of Staff) agent system — just like the built-in per-app scheduled tasks, but
+user-authored rather than chosen from the fixed catalog.
+
+PortOS already has two relevant systems:
+
+1. **Built-in task types** (`DEFAULT_TASK_INTERVALS` in `server/services/taskSchedule.js`) —
+ a fixed catalog (security, code-quality, plan-task, …) with per-app enable/interval
+ overrides surfaced in `/apps/{appId}/automation`. These cannot host arbitrary user prompts.
+2. **Autonomous jobs** (`server/services/autonomousJobs/`, `cosJobScheduler.js`, the CoS
+ "System Tasks" / Jobs tab) — already does exactly **"custom prompt + schedule → spawn a
+ CoS agent"**, with full interval+cron scheduling, autonomy levels, gates, and the
+ spawning-guard machinery. **It is just not app-scoped** — a job has no `appId`, so its
+ agent runs in the PortOS root instead of a target app's repo.
+
+**Approach (verified):** Add an optional `appId` (and optional git-workflow `taskMetadata`)
+to autonomous jobs. When `appId` is set, the generated CoS task carries `metadata.app = appId`,
+which the *existing* spawn path (`prepareAgentWorkspace` → `getAppWorkspace`) already resolves
+to `app.repoPath`. This reuses the entire built-in workspace/JIRA/worktree pipeline — no new
+scheduler, no new store, no migration. Surface it as a **"Custom Tasks" section in the per-app
+Automation tab**, with optional worktree/PR/simplify toggles so a custom task can do isolated
+work and open a PR in the target app.
+
+This is backward/forward compatible per the CLAUDE.md distribution model: `appId` absent =
+global job = today's behavior. No on-disk migration required.
+
+## Verified payoff chain (no change needed here)
+
+- `server/services/agentWorkspacePrep.js:50` — `prepareAgentWorkspace` sets
+ `workspacePath = getAppWorkspace(task.metadata.app)` when present, else ROOT_DIR.
+- `server/services/agentPromptBuilder.js:~955` — `getAppWorkspace(appName)` resolves by id
+ **or** name from `data/apps.json`, returns `app.repoPath || ROOT_DIR`.
+- `getAppDataForTask(task)` (~977) reads `task.metadata.app` for JIRA context.
+- `server/services/cosTaskStore.js` `addTask` maps `taskData.app → metadata.app`, and also
+ `useWorktree/openPR/simplify/reviewLoop` flags (lines ~159–179). So both the scheduled and
+ manual-trigger paths can carry app + git-workflow options.
+- `agentWorkspacePrep.js:60-61` — `useWorktree`/`openPR` on `task.metadata` drive worktree
+ isolation + PR. Setting these in the generated task is sufficient.
+
+## Server changes
+
+### 1. Job model + CRUD — `server/services/autonomousJobs/crud.js`
+- `createJob` job object: add `appId: jobData.appId || null` and
+ `taskMetadata: jobData.taskMetadata || null`.
+- `updateJob` `updatableFields` allow-list: add `'appId'` and `'taskMetadata'`.
+
+### 2. Task generation — `server/services/autonomousJobs/skillTemplates.js` (`generateTaskFromJob`, ~line 144)
+Thread app + git options into the task metadata so the spawn path picks them up:
+```js
+metadata: {
+ autonomousJob: true,
+ jobId: job.id, jobName: job.name, jobCategory: job.category,
+ autonomyLevel: job.autonomyLevel,
+ ...(job.appId ? { app: job.appId } : {}),
+ ...(job.taskMetadata?.useWorktree != null ? { useWorktree: job.taskMetadata.useWorktree } : {}),
+ ...(job.taskMetadata?.openPR != null ? { openPR: job.taskMetadata.openPR } : {}),
+ ...(job.taskMetadata?.simplify != null ? { simplify: job.taskMetadata.simplify } : {}),
+}
+```
+
+### 3. Validation — `server/lib/validation.js` (`createCosJobSchema`, line 713)
+Add (tolerating UI `''` sentinels, mirroring the existing `triggerAction` preprocess):
+```js
+appId: z.preprocess(v => v === '' ? undefined : v, z.string().optional()),
+taskMetadata: z.object({
+ useWorktree: z.boolean().optional(),
+ openPR: z.boolean().optional(),
+ simplify: z.boolean().optional(),
+}).optional(),
+```
+`updateCosJobSchema` inherits both via `.partial()`.
+
+### 4. Routes — `server/routes/cosJobRoutes.js`
+- **POST `/jobs`** (~line 75) and **PUT `/jobs/:id`** (~line 112): add `appId` and
+ `taskMetadata` to the destructured fields and pass them into `createJob`/`updateJob`.
+- **CRITICAL GOTCHA — manual trigger** (`POST /jobs/:id/trigger`, ~line 177): it currently
+ calls `cos.addTask({ description, priority, context, approvalRequired }, 'internal')` and
+ **drops `task.metadata`**, so a manually-triggered app-scoped job would run in ROOT_DIR.
+ Forward the app + git options:
+ ```js
+ const taskResult = await cos.addTask({
+ description: task.description,
+ priority: task.priority,
+ context: `Manually triggered autonomous job: ${job.name}`,
+ approvalRequired: false,
+ app: task.metadata?.app,
+ useWorktree: task.metadata?.useWorktree,
+ openPR: task.metadata?.openPR,
+ simplify: task.metadata?.simplify,
+ }, 'internal');
+ ```
+ (The scheduled path is unaffected — it emits the full task object via `task:ready`.)
+
+### 5. No migration / no JOB_ADDITIVE_FIELDS change
+The `defaults.js` restart-merge only touches jobs whose IDs match shipped `DEFAULT_JOBS`; a
+user job's `appId`/`taskMetadata` persists on its own through `saveJobs`. Absent `appId` =
+global = current behavior, so no `scripts/migrations/` entry is needed.
+
+## Client changes
+
+### Primary — per-app "Custom Tasks" section in `client/src/components/apps/tabs/AutomationTab.jsx`
+Route already exists: `/apps/{appId}/automation`. Add a section below the existing
+"Task Type Overrides":
+- Fetch `api.getCosJobs()` and filter to `jobs.filter(j => j.appId === appId)`.
+- Render each as a compact card (name, schedule summary via `describeCron`/interval label,
+ enabled toggle, Run-now, edit, delete) — reuse the patterns already in
+ `client/src/components/cos/tabs/JobsTab.jsx` (`JobCard`, `ScheduleFields`, `normalizeJobPayload`,
+ `formatNextDue`). Consider extracting the shared form bits into
+ `client/src/components/cos/JobForm.jsx` to avoid duplication, or import the existing helpers.
+- Create/edit form fields: name, description, prompt template, schedule (interval/cron via
+ existing `ScheduleFields` + `cronHelpers`), priority, autonomy level, and the new
+ worktree/PR/simplify toggles (reuse `AGENT_OPTIONS` / `agentOptionButtonClass` from
+ `client/src/components/cos/constants.js` for visual consistency with built-in overrides).
+- On save: force `type: 'agent'` and `appId` to this app; send `taskMetadata` for the toggles.
+ `apiAgents.js` `createCosJob`/`updateCosJob` already accept arbitrary payloads — no signature
+ change required, but confirm they forward the body verbatim.
+
+### Secondary — app badge/picker in the global `JobsTab.jsx`
+- Add an optional **app picker** to the global create/edit forms (populate via
+ `apiApps.getApps()` from `client/src/services/apiApps.js`); blank = global job.
+- Show an **app badge** on each `JobCard` when `job.appId` is set (resolve id → name).
+- This keeps every custom task centrally visible/manageable in CoS → System Tasks, while the
+ per-app tab is the discovery surface.
+
+### API client — `client/src/services/apiAgents.js`
+No new endpoints. Verify `createCosJob`/`updateCosJob` pass the full payload (including `appId`,
+`taskMetadata`) through `request()`; add fields to any payload-whitelisting if present.
+
+## Prompt / app context note
+A raw `promptTemplate` is not run through `{appName}`/`{repoPath}` templating, but correctness
+holds: the agent's cwd **is** `app.repoPath` (so the CLI provider loads that repo's CLAUDE.md),
+and `buildTaskBlock` already adds a `**Target App**` line from `metadata.app`. Optional polish:
+resolve the app id to its display name in that line.
+
+## Gotchas / guardrails (already correct)
+- `state.config.autonomousJobsEnabled` and the per-domain CoS autonomy gate
+ (`cosJobScheduler.js:170,185`) already apply to all scheduled jobs, including app-scoped — desired.
+- Duplicate-spawn guards (`spawningJobIds`) and capacity checks already cover these jobs.
+- `metadata.app` duplicate-detection in `addTask` is scoped per app, so two apps' custom tasks
+ with similar prompts won't collide.
+
+## Tests
+- **`server/services/autonomousJobs.test.js`**: `appId` + `taskMetadata` persisted on create;
+ settable/clearable via update; `generateTaskFromJob` sets `metadata.app` (and worktree/PR flags)
+ when `appId`/`taskMetadata` present, omits them otherwise. Extend the existing describe block.
+ Follow the project rule: record-creating tests must `mockNoPeers()` + `mockNoPeerSync()` if they
+ touch app create paths — but these tests operate on the jobs store, not universes/series, so
+ verify whether peer mocking is needed (likely not; jobs store has no peer fan-out).
+- **`server/routes/cosJobRoutes.test.js`**: POST/PUT accept `appId` + `taskMetadata`; `'' → undefined`;
+ manual **trigger** forwards `app`/`useWorktree`/`openPR` into the `addTask` call (assert via mock).
+- **Client**: a `JobsTab`/`AutomationTab` Vitest covering the app filter + create payload shape
+ (`type:'agent'`, `appId` set) if a matching test harness exists.
+
+## Catalog / barrel / README
+No new public module in `server/lib/`, `client/src/lib/`, `client/src/hooks/`,
+`client/src/utils/`, or a new `apiX.js` — so no barrel/README maintenance is triggered. If a
+shared `JobForm.jsx` component is extracted under `client/src/components/cos/`, that's a
+component (not a catalogued lib), so no index/README update is required.
+
+## Verification (end-to-end)
+1. `cd server && npm test` — new job appId/taskMetadata + route tests pass; existing job tests green.
+2. `cd client && npm test` — any new component test passes; build the client.
+3. Manual: `npm run dev`, open `/apps/{appId}/automation`, create a custom task (e.g. prompt
+ "Update the README badges", cron `0 9 * * 1`, worktree+PR on), enable it, click **Run now**.
+ Confirm in CoS → Agents that the spawned agent's workspace is the app's `repoPath` (check the
+ agent record's `workspacePath`/`sourceWorkspace`) and — with PR on — that an isolated worktree
+ was created. Verify a scheduled fire also targets the app repo (temporarily set a near-future
+ cron) and that toggling the global `autonomousJobsEnabled` off withholds it.
+4. Confirm the task also appears (with an app badge) in the global CoS System Tasks tab.
diff --git a/server/lib/validation.js b/server/lib/validation.js
index ce777b63df..65da5ddb49 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -725,6 +725,14 @@ export const createCosJobSchema = z.object({
promptTemplate: z.string().optional(),
command: z.string().optional(),
triggerAction: z.preprocess(v => v === '' ? undefined : v, z.string().optional()),
+ // Optional managed-app scope (empty string from the UI picker → undefined → global job).
+ appId: z.preprocess(v => v === '' ? undefined : v, z.string().optional()),
+ // Optional git-workflow options for app-scoped agent jobs.
+ taskMetadata: z.object({
+ useWorktree: z.boolean().optional(),
+ openPR: z.boolean().optional(),
+ simplify: z.boolean().optional(),
+ }).optional(),
});
export const updateCosJobSchema = createCosJobSchema.partial().extend({
diff --git a/server/routes/cosJobRoutes.js b/server/routes/cosJobRoutes.js
index c4521d4967..3e18677691 100644
--- a/server/routes/cosJobRoutes.js
+++ b/server/routes/cosJobRoutes.js
@@ -72,7 +72,7 @@ router.get('/jobs/:id', asyncHandler(async (req, res) => {
router.post('/jobs', asyncHandler(async (req, res) => {
const parsedJob = createCosJobSchema.safeParse(req.body);
if (!parsedJob.success) failValidation(parsedJob);
- const { name, description, category, type, interval, intervalMs, scheduledTime, cronExpression, enabled, priority, autonomyLevel, promptTemplate, command, triggerAction } = parsedJob.data;
+ const { name, description, category, type, interval, intervalMs, scheduledTime, cronExpression, enabled, priority, autonomyLevel, promptTemplate, command, triggerAction, appId, taskMetadata } = parsedJob.data;
if (type === 'shell' && !command?.trim()) {
throw new ServerError('command is required for shell jobs', { status: 400, code: 'VALIDATION_ERROR' });
@@ -100,7 +100,7 @@ router.post('/jobs', asyncHandler(async (req, res) => {
const job = await autonomousJobs.createJob({
name, description, category, type, interval, intervalMs, scheduledTime, cronExpression,
- enabled, priority, autonomyLevel, promptTemplate, command, triggerAction
+ enabled, priority, autonomyLevel, promptTemplate, command, triggerAction, appId, taskMetadata
});
res.json({ success: true, job });
}));
@@ -110,7 +110,7 @@ router.put('/jobs/:id', asyncHandler(async (req, res) => {
const parsedJobUpdate = updateCosJobSchema.safeParse(req.body);
if (!parsedJobUpdate.success) failValidation(parsedJobUpdate);
const { name, description, category, type, interval, intervalMs, scheduledTime, cronExpression,
- enabled, priority, autonomyLevel, promptTemplate, command, triggerAction, weekdaysOnly } = parsedJobUpdate.data;
+ enabled, priority, autonomyLevel, promptTemplate, command, triggerAction, weekdaysOnly, appId, taskMetadata } = parsedJobUpdate.data;
if (cronExpression) {
const parts = cronExpression.trim().split(/\s+/);
if (parts.length !== 5) {
@@ -128,7 +128,7 @@ router.put('/jobs/:id', asyncHandler(async (req, res) => {
}
const job = await autonomousJobs.updateJob(req.params.id, {
name, description, category, type, interval, intervalMs, scheduledTime, cronExpression,
- enabled, priority, autonomyLevel, promptTemplate, command, triggerAction, weekdaysOnly
+ enabled, priority, autonomyLevel, promptTemplate, command, triggerAction, weekdaysOnly, appId, taskMetadata
});
if (!job) {
throw new ServerError('Job not found', { status: 404, code: 'NOT_FOUND' });
@@ -175,11 +175,19 @@ router.post('/jobs/:id/trigger', asyncHandler(async (req, res) => {
// Job execution is recorded via the job:spawned event when the agent actually starts
// Manual triggers always bypass approval — the user explicitly requested execution
const task = await autonomousJobs.generateTaskFromJob(job);
+ // Forward the app scope + git-workflow options from the generated task's
+ // metadata. addTask maps these top-level keys back onto metadata; without
+ // them an app-scoped job triggered manually would run in the PortOS root
+ // (the scheduled path emits the full task object via task:ready and is unaffected).
const taskResult = await cos.addTask({
description: task.description,
priority: task.priority,
context: `Manually triggered autonomous job: ${job.name}`,
- approvalRequired: false
+ approvalRequired: false,
+ app: task.metadata?.app,
+ useWorktree: task.metadata?.useWorktree,
+ openPR: task.metadata?.openPR,
+ simplify: task.metadata?.simplify
}, 'internal');
if (!taskResult?.id) {
diff --git a/server/routes/cosJobRoutes.test.js b/server/routes/cosJobRoutes.test.js
index 6824293d19..f922370849 100644
--- a/server/routes/cosJobRoutes.test.js
+++ b/server/routes/cosJobRoutes.test.js
@@ -204,6 +204,32 @@ describe('CoS Job Routes', () => {
expect(response.status).toBe(400);
});
+
+ it('should accept appId + taskMetadata and forward them to createJob', async () => {
+ autonomousJobs.createJob.mockResolvedValue({ id: 'j1' });
+
+ const response = await request(app)
+ .post('/api/cos/jobs')
+ .send({ name: 'App Task', type: 'agent', promptTemplate: 'test', appId: 'app-xyz', taskMetadata: { useWorktree: true, openPR: true } });
+
+ expect(response.status).toBe(200);
+ expect(autonomousJobs.createJob).toHaveBeenCalledWith(
+ expect.objectContaining({ appId: 'app-xyz', taskMetadata: { useWorktree: true, openPR: true } })
+ );
+ });
+
+ it('should coerce empty-string appId to undefined (global job)', async () => {
+ autonomousJobs.createJob.mockResolvedValue({ id: 'j1' });
+
+ const response = await request(app)
+ .post('/api/cos/jobs')
+ .send({ name: 'Global Task', type: 'agent', promptTemplate: 'test', appId: '' });
+
+ expect(response.status).toBe(200);
+ expect(autonomousJobs.createJob).toHaveBeenCalledWith(
+ expect.objectContaining({ appId: undefined })
+ );
+ });
});
describe('PUT /api/cos/jobs/:id', () => {
@@ -286,6 +312,26 @@ describe('CoS Job Routes', () => {
expect(response.body.taskId).toBe('task-1');
});
+ it('should forward app scope + git options into addTask for an app-scoped agent job', async () => {
+ autonomousJobs.getJob.mockResolvedValue({ id: 'j1', type: 'agent', name: 'App Review' });
+ autonomousJobs.isShellJob.mockReturnValue(false);
+ autonomousJobs.isScriptJob.mockReturnValue(false);
+ autonomousJobs.generateTaskFromJob.mockResolvedValue({
+ description: 'Review',
+ priority: 'MEDIUM',
+ metadata: { app: 'app-xyz', useWorktree: true, openPR: true, simplify: false }
+ });
+ cos.addTask.mockResolvedValue({ id: 'task-2' });
+
+ const response = await request(app).post('/api/cos/jobs/j1/trigger');
+
+ expect(response.status).toBe(200);
+ expect(cos.addTask).toHaveBeenCalledWith(
+ expect.objectContaining({ app: 'app-xyz', useWorktree: true, openPR: true, simplify: false }),
+ 'internal'
+ );
+ });
+
it('should return 404 if job not found', async () => {
autonomousJobs.getJob.mockResolvedValue(null);
diff --git a/server/services/autonomousJobs.test.js b/server/services/autonomousJobs.test.js
index 6a17c18100..72b220d08c 100644
--- a/server/services/autonomousJobs.test.js
+++ b/server/services/autonomousJobs.test.js
@@ -197,6 +197,27 @@ describe('autonomousJobs', () => {
expect(task.autoApprove).toBe(true)
expect(task.metadata.autonomyLevel).toBe('yolo')
})
+
+ it('omits app + git options when job has no appId/taskMetadata', async () => {
+ const task = await generateTaskFromJob(mockJobsData.jobs[0])
+ expect(task.metadata.app).toBeUndefined()
+ expect(task.metadata.useWorktree).toBeUndefined()
+ expect(task.metadata.openPR).toBeUndefined()
+ expect(task.metadata.simplify).toBeUndefined()
+ })
+
+ it('app-scoped job sets metadata.app and forwards git options', async () => {
+ const appJob = {
+ ...mockJobsData.jobs[0],
+ appId: 'app-xyz',
+ taskMetadata: { useWorktree: true, openPR: true, simplify: false }
+ }
+ const task = await generateTaskFromJob(appJob)
+ expect(task.metadata.app).toBe('app-xyz')
+ expect(task.metadata.useWorktree).toBe(true)
+ expect(task.metadata.openPR).toBe(true)
+ expect(task.metadata.simplify).toBe(false)
+ })
})
describe('createJob with resolveIntervalMs', () => {
@@ -719,6 +740,23 @@ describe('autonomousJobs', () => {
name: 'New Job'
})
})
+
+ it('defaults appId/taskMetadata to null when omitted', async () => {
+ const job = await createJob({ name: 'Global Job', promptTemplate: 'do it' })
+ expect(job.appId).toBeNull()
+ expect(job.taskMetadata).toBeNull()
+ })
+
+ it('persists appId + taskMetadata when provided', async () => {
+ const job = await createJob({
+ name: 'App Job',
+ promptTemplate: 'do it',
+ appId: 'app-xyz',
+ taskMetadata: { useWorktree: true, openPR: true, simplify: false }
+ })
+ expect(job.appId).toBe('app-xyz')
+ expect(job.taskMetadata).toEqual({ useWorktree: true, openPR: true, simplify: false })
+ })
})
describe('updateJob', () => {
@@ -743,6 +781,15 @@ describe('autonomousJobs', () => {
expect(job).toBeNull()
})
+
+ it('updates appId + taskMetadata, and can clear appId', async () => {
+ const scoped = await updateJob('job-test-1', { appId: 'app-abc', taskMetadata: { openPR: true } })
+ expect(scoped.appId).toBe('app-abc')
+ expect(scoped.taskMetadata).toEqual({ openPR: true })
+
+ const cleared = await updateJob('job-test-1', { appId: null })
+ expect(cleared.appId).toBeNull()
+ })
})
describe('deleteJob', () => {
diff --git a/server/services/autonomousJobs/crud.js b/server/services/autonomousJobs/crud.js
index 74b554afbc..e5a3a31eff 100644
--- a/server/services/autonomousJobs/crud.js
+++ b/server/services/autonomousJobs/crud.js
@@ -80,6 +80,14 @@ async function createJob(jobData) {
name: jobData.name,
description: jobData.description || '',
category: jobData.category || 'custom',
+ // Optional managed-app scope. When set, the spawned agent targets the
+ // app's repoPath (via task.metadata.app → prepareAgentWorkspace) instead
+ // of the PortOS root. Absent/null = global job (historical behavior).
+ appId: jobData.appId || null,
+ // Optional git-workflow options forwarded into the generated task's
+ // metadata (useWorktree/openPR/simplify) so an app-scoped custom task can
+ // do isolated work and open a PR like the built-in task types.
+ taskMetadata: jobData.taskMetadata || null,
cronExpression: jobData.cronExpression || null,
type: jobType,
interval: jobData.interval || 'weekly',
@@ -135,7 +143,7 @@ async function updateJob(jobId, updates) {
const updatableFields = [
'name', 'description', 'category', 'type', 'interval', 'intervalMs',
'scheduledTime', 'cronExpression', 'weekdaysOnly', 'enabled', 'priority', 'autonomyLevel', 'promptTemplate',
- 'command', 'triggerAction', 'config'
+ 'command', 'triggerAction', 'config', 'appId', 'taskMetadata'
]
for (const field of updatableFields) {
diff --git a/server/services/autonomousJobs/skillTemplates.js b/server/services/autonomousJobs/skillTemplates.js
index 39042533ba..e59cb61719 100644
--- a/server/services/autonomousJobs/skillTemplates.js
+++ b/server/services/autonomousJobs/skillTemplates.js
@@ -143,6 +143,7 @@ async function getJobEffectivePrompt(job) {
*/
async function generateTaskFromJob(job) {
const description = await getJobEffectivePrompt(job)
+ const meta = job.taskMetadata || {}
return {
id: `${job.id}-${Date.now().toString(36)}`,
description,
@@ -152,7 +153,15 @@ async function generateTaskFromJob(job) {
jobId: job.id,
jobName: job.name,
jobCategory: job.category,
- autonomyLevel: job.autonomyLevel
+ autonomyLevel: job.autonomyLevel,
+ // App-scoped jobs carry the target app id so prepareAgentWorkspace resolves
+ // the agent's workspace to the app's repoPath. Absent = runs in PortOS root.
+ ...(job.appId ? { app: job.appId } : {}),
+ // Forward git-workflow options so an app-scoped task can isolate via a
+ // worktree and open a PR (same metadata flags the built-in task types use).
+ ...(meta.useWorktree != null ? { useWorktree: meta.useWorktree } : {}),
+ ...(meta.openPR != null ? { openPR: meta.openPR } : {}),
+ ...(meta.simplify != null ? { simplify: meta.simplify } : {})
},
taskType: 'internal',
autoApprove: job.autonomyLevel === 'yolo'