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

fix: start manually triggered scheduled tasks

[._.]/ Adam Eivy523a5f709747
diff --git a/client/src/components/apps/tabs/CustomTasksSection.jsx b/client/src/components/apps/tabs/CustomTasksSection.jsx
index 92936ba00f..a354ae3fbe 100644
--- a/client/src/components/apps/tabs/CustomTasksSection.jsx
+++ b/client/src/components/apps/tabs/CustomTasksSection.jsx
@@ -1,42 +1,14 @@
import { useState, useEffect, useCallback, useMemo } from 'react';
-import { Plus, Play, Trash2, Edit3, Save, X, Clock } from 'lucide-react';
+import { Plus, Save, X } from 'lucide-react';
import toast from '../../ui/Toast';
-import ToggleSwitch from '../../ToggleSwitch';
-import ConfirmButtonPair from '../../ui/ConfirmButtonPair';
import FormField from '../../ui/FormField';
-import { useConfirmDelete } from '../../../hooks/useConfirmDelete';
import useUserTimezone from '../../../hooks/useUserTimezone.js';
import * as api from '../../../services/api';
-import { timeAgo } from '../../../utils/formatters';
-import { DEFAULT_CRON, describeCron, describeRecurrence, parseCronToRecurrence, buildCronFromRecurrence } from '../../../utils/cronHelpers';
-import CronSchedulePicker from '../../CronSchedulePicker';
-import { AGENT_OPTIONS, agentOptionButtonClass } from '../../cos/constants';
+import { parseCronToRecurrence, buildCronFromRecurrence } from '../../../utils/cronHelpers';
import AgentJobProviderFields from '../../cos/AgentJobProviderFields';
+import JobCard, { AUTONOMY_OPTIONS, PRIORITY_OPTIONS, ScheduleFields, TaskMetadataFields } from '../../cos/JobCard';
import { filterRunnableProviders } from '../../../utils/providers';
-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));
-
export function emptyForm() {
return {
name: '',
@@ -103,30 +75,8 @@ export function toPayload(form, appId) {
return payload;
}
-function scheduleSummary(job) {
- if (job.cronSchedule) return describeRecurrence(job.cronSchedule);
- 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, timezone, providers, activeProviderId }) {
const update = (key, val) => setForm(f => ({ ...f, [key]: val }));
- // Switching to cron seeds the expression with the default the picker displays
- // (07:00 daily) so an untouched picker is actually saveable — otherwise the
- // form shows a schedule while cronExpression stays empty and Save is blocked.
- const setScheduleMode = (mode) =>
- setForm(f => ({ ...f, scheduleMode: mode, cronExpression: mode === 'cron' && !f.cronExpression && !f.cronSchedule ? DEFAULT_CRON : f.cronExpression }));
- // Toggle a git-workflow flag while preserving the system-wide invariant that
- // openPR implies useWorktree (matches toggleAppMetadataOverride used elsewhere):
- // turning openPR on forces useWorktree on; turning useWorktree off forces openPR off.
- const toggleMeta = (field) =>
- setForm(f => {
- const meta = { ...f.taskMetadata, [field]: !f.taskMetadata?.[field] };
- if (field === 'openPR' && meta.openPR) meta.useWorktree = true;
- if (field === 'useWorktree' && !meta.useWorktree) meta.openPR = false;
- return { ...f, taskMetadata: meta };
- });
return (
<div className="space-y-3 bg-port-card border border-port-accent/50 rounded-lg p-4">
@@ -157,57 +107,7 @@ function TaskForm({ form, setForm, onSave, onCancel, saveLabel, timezone, provid
/>
</FormField>
- {/* 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={() => setScheduleMode(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="space-y-2">
- <CronSchedulePicker
- value={form.cronSchedule || form.cronExpression || DEFAULT_CRON}
- valueShape="recurrence"
- timezone={timezone}
- onChange={rule => {
- update('cronSchedule', rule);
- const cron = buildCronFromRecurrence(rule);
- update('cronExpression', cron || null);
- }}
- />
- </div>
- ) : (
- <div className="flex gap-3">
- <select
- aria-label="Interval"
- 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)"
- aria-label="Run at time"
- />
- </div>
- )}
- </div>
+ <ScheduleFields data={form} timezone={timezone} onChange={update} />
{/* Priority + autonomy */}
<div className="flex gap-3">
@@ -236,26 +136,7 @@ function TaskForm({ form, setForm, onSave, onCancel, saveLabel, timezone, provid
onChange={patch => setForm(f => ({ ...f, ...patch }))}
/>
- {/* 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>
+ <TaskMetadataFields data={form} onChange={patch => setForm(f => ({ ...f, ...patch }))} />
<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">
@@ -275,12 +156,9 @@ export default function CustomTasksSection({ appId, appName, providerCatalog, ac
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 [rawProviders, setRawProviders] = useState(providerCatalog || []);
const [activeProviderId, setActiveProviderId] = useState(inheritedActiveProviderId);
const [triggering, setTriggering] = useState(null);
- const { isConfirming, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();
const providers = useMemo(
() => filterRunnableProviders(rawProviders, tasks.map(job => job.providerId)),
@@ -331,44 +209,32 @@ export default function CustomTasksSection({ appId, appName, providerCatalog, ac
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(() => null);
+ const handleToggle = async (jobId) => {
+ const result = await api.toggleCosJob(jobId).catch(() => null);
if (!result) return;
- toast.success('Custom task updated');
- setEditingId(null);
- fetchTasks();
+ setTasks(prev => prev.map(t => t.id === jobId ? { ...t, enabled: result.job.enabled } : t));
};
- const handleToggle = async (job) => {
- const result = await api.toggleCosJob(job.id).catch(() => 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(() => null);
+ const handleTrigger = async (jobId) => {
+ const job = tasks.find(task => task.id === jobId);
+ if (!job) return;
+ setTriggering(jobId);
+ const result = await api.triggerCosJob(jobId).catch(() => null);
setTriggering(null);
if (!result) return; // HTTP/network error already toasted by the api helper
if (result.status === 'skipped') {
const notify = result.duplicate ? toast.success : toast.error;
notify(result.reason || 'Task was not queued');
} else if (result.success === false) toast.error(result.reason || 'Task failed to trigger');
- else toast.success(`Triggered "${job.name}" for ${appName}`);
+ else toast.success(`${result.started ? 'Started' : 'Triggered'} "${job.name}" for ${appName}`);
fetchTasks();
};
- const handleDelete = async (job) => {
- const result = await api.deleteCosJob(job.id).catch(() => null);
+ const handleDelete = async (jobId) => {
+ const result = await api.deleteCosJob(jobId).catch(() => null);
if (!result) return;
toast.success('Custom task deleted');
- setTasks(prev => prev.filter(t => t.id !== job.id));
+ setTasks(prev => prev.filter(t => t.id !== jobId));
};
return (
@@ -410,57 +276,22 @@ export default function CustomTasksSection({ appId, appName, providerCatalog, ac
) : (
<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"
- timezone={timezone}
- providers={providers}
- activeProviderId={activeProviderId}
- />
- </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} className="p-1.5 text-gray-500 hover:text-port-accent transition-colors disabled:opacity-40" title="Run now" aria-label="Run now">
- <Play size={14} />
- </button>
- <button onClick={() => startEdit(job)} className="p-1.5 text-gray-500 hover:text-white transition-colors" title="Edit" aria-label="Edit">
- <Edit3 size={14} />
- </button>
- {isConfirming(job.id) ? (
- <ConfirmButtonPair
- prompt="Delete?"
- onConfirm={() => confirmDelete(() => handleDelete(job))}
- onCancel={cancelDelete}
- ariaLabel="Confirm delete custom task"
- />
- ) : (
- <button onClick={() => requestDelete(job.id)} className="p-1.5 text-red-400/60 hover:text-red-400 transition-colors" title="Delete" aria-label="Delete">
- <Trash2 size={14} />
- </button>
- )}
- </div>
- </div>
- {job.description && <p className="text-xs text-gray-500 pl-12">{job.description}</p>}
- </div>
- )}
- </div>
+ <JobCard
+ key={job.id}
+ job={job}
+ providers={providers}
+ activeProviderId={activeProviderId}
+ timezone={timezone}
+ onToggle={handleToggle}
+ onTrigger={handleTrigger}
+ onDelete={handleDelete}
+ onUpdate={fetchTasks}
+ fixedAppId={appId}
+ fixedType="agent"
+ showTaskMetadata
+ silentUpdate={false}
+ triggering={triggering === job.id}
+ />
))}
</div>
)}
diff --git a/client/src/components/apps/tabs/CustomTasksSection.test.jsx b/client/src/components/apps/tabs/CustomTasksSection.test.jsx
index 7aa5b35866..505c39e708 100644
--- a/client/src/components/apps/tabs/CustomTasksSection.test.jsx
+++ b/client/src/components/apps/tabs/CustomTasksSection.test.jsx
@@ -114,6 +114,7 @@ describe('CustomTasksSection trigger outcomes', () => {
render(<CustomTasksSection appId="app-1" appName="Example App" />);
await screen.findByText('Example Task');
fireEvent.click(screen.getByRole('button', { name: 'Edit' }));
+ expect(screen.queryByLabelText('App scope')).not.toBeInTheDocument();
fireEvent.change(screen.getByLabelText('Provider'), { target: { value: 'codex' } });
fireEvent.change(screen.getByLabelText('Model'), { target: { value: 'gpt-5' } });
fireEvent.change(screen.getByLabelText('Thinking effort'), { target: { value: 'high' } });
@@ -127,6 +128,16 @@ describe('CustomTasksSection trigger outcomes', () => {
})));
});
+ it('reports a direct manual trigger as started', async () => {
+ api.triggerCosJob.mockResolvedValue({ success: true, status: 'queued', started: true });
+ render(<CustomTasksSection appId="app-1" appName="Example App" />);
+ await screen.findByText('Example Task');
+
+ fireEvent.click(screen.getByRole('button', { name: 'Run now' }));
+
+ await waitFor(() => expect(toast.success).toHaveBeenCalledWith('Started "Example Task" for Example App'));
+ });
+
it('surfaces a skipped trigger without claiming the task ran', async () => {
api.triggerCosJob.mockResolvedValue({
success: false,
diff --git a/client/src/components/cos/JobCard.jsx b/client/src/components/cos/JobCard.jsx
new file mode 100644
index 0000000000..83d1f6760d
--- /dev/null
+++ b/client/src/components/cos/JobCard.jsx
@@ -0,0 +1,604 @@
+import { useState } from 'react';
+import { Play, Trash2, ChevronDown, ChevronUp, Clock, ToggleLeft, ToggleRight, Edit3, Save, X, Terminal } from 'lucide-react';
+import toast from '../ui/Toast';
+import * as api from '../../services/api';
+import { timeAgo, timeUntil, formatDateNumeric } from '../../utils/formatters';
+import { DEFAULT_CRON, describeCron, describeRecurrence, parseCronToRecurrence, buildCronFromRecurrence, JOB_INTERVAL_OPTIONS as INTERVAL_OPTIONS } from '../../utils/cronHelpers';
+import CronSchedulePicker from '../CronSchedulePicker';
+import AgentJobProviderFields, { hasRunnableAgentProvider } from './AgentJobProviderFields';
+import { AGENT_OPTIONS, agentOptionButtonClass } from './constants';
+import InlineConfirmRow from '../ui/InlineConfirmRow';
+import FormField from '../ui/FormField';
+import { useConfirmDelete } from '../../hooks/useConfirmDelete';
+
+const SCHEDULE_MODE_OPTIONS = [
+ { value: 'interval', label: 'Interval' },
+ { value: 'cron', label: 'Cron' }
+];
+
+export const PRIORITY_OPTIONS = ['LOW', 'MEDIUM', 'HIGH', 'CRITICAL'];
+export const AUTONOMY_OPTIONS = [
+ { value: 'standby', label: 'Standby', desc: 'Creates tasks but waits for approval' },
+ { value: 'assistant', label: 'Assistant', desc: 'Creates tasks, notifies you' },
+ { value: 'manager', label: 'Manager', desc: 'Executes tasks autonomously' },
+ { value: 'yolo', label: 'YOLO', desc: 'Full autonomy, no guardrails' }
+];
+
+export const TRIGGER_ACTION_OPTIONS = [
+ { value: 'log-only', label: 'Log Only' },
+ { value: 'spawn-agent', label: 'Spawn Agent' },
+ { value: 'create-task', label: 'Create Task' }
+];
+
+const SHELL_TRIGGER_ACTIONS = new Set(['spawn-agent', 'create-task']);
+export const SHELL_TRIGGER_ACTION_OPTIONS = TRIGGER_ACTION_OPTIONS.filter(
+ opt => !SHELL_TRIGGER_ACTIONS.has(opt.value)
+);
+
+export const JOB_TYPE_OPTIONS = [
+ { value: 'agent', label: 'AI Agent' },
+ { value: 'shell', label: 'Shell Command' }
+];
+
+// App scope, provider/model override, and prompt template only apply to
+// AI-agent jobs — shell/script jobs run a fixed command and never reach the
+// AI runner.
+export const isAgentJobType = (type) => type !== 'shell' && type !== 'script';
+
+const BRIEFING_CONFIG_OPTIONS = [
+ { key: 'dailyJoke', label: 'Daily Joke', desc: 'Include a short joke to start the day' },
+ { key: 'dailyQuote', label: 'Daily Quote', desc: 'Include an inspirational quote related to focus areas' },
+ { key: 'dailyImage', label: 'Daily Image', desc: 'Generate an image via Stable Diffusion (requires image gen API)' }
+];
+
+export function normalizeJobPayload(formData) {
+ const payload = { ...formData };
+ if (isAgentJobType(payload.type)) {
+ payload.command = null;
+ payload.triggerAction = null;
+ } else {
+ // App scope only applies to AI-agent jobs (the scope drives the agent's
+ // workspace). Shell/script jobs always run in the PortOS root, so clear any
+ // appId left over from when the job was an agent type — otherwise the saved
+ // job shows a misleading app badge while executing in root.
+ payload.appId = null;
+ // Provider/model/effort overrides only apply to AI-agent jobs — clear any
+ // leftover selection so a shell/script job doesn't carry a misleading AI badge.
+ payload.providerId = null;
+ payload.model = null;
+ payload.effort = null;
+ }
+ // Empty app picker selection ('') → null so a PUT actively un-scopes the job
+ // back to global (undefined would be dropped from JSON and updateJob would
+ // preserve the old scope). The schema maps '' → null too; sending null directly
+ // is unambiguous across create and update.
+ if (!payload.appId) payload.appId = null;
+ if (payload.scheduleMode === 'cron') {
+ const derivedCron = buildCronFromRecurrence(payload.cronSchedule);
+ payload.cronExpression = derivedCron || payload.cronExpression?.trim() || null;
+ payload.cronSchedule = payload.cronSchedule || null;
+ payload.scheduledTime = null;
+ } else {
+ payload.cronExpression = null;
+ payload.cronSchedule = null;
+ }
+ delete payload.scheduleMode;
+ return payload;
+}
+
+export function ScheduleFields({ data, onChange, timezone }) {
+ 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);
+ // Seed the expression with the picker's displayed default (07:00
+ // daily) so an untouched Cron picker is actually saveable.
+ if (opt.value === 'cron' && !data.cronExpression && !data.cronSchedule) onChange('cronExpression', DEFAULT_CRON);
+ }}
+ 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="space-y-2">
+ <CronSchedulePicker
+ value={data.cronSchedule || data.cronExpression || DEFAULT_CRON}
+ valueShape="recurrence"
+ timezone={timezone}
+ onChange={rule => {
+ onChange('cronSchedule', rule);
+ const cron = buildCronFromRecurrence(rule);
+ onChange('cronExpression', cron || null);
+ }}
+ />
+ </div>
+ ) : (
+ <div className="flex gap-3">
+ <select
+ aria-label="Interval"
+ 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)"
+ aria-label="Run at a 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.cronSchedule) return describeRecurrence(job.cronSchedule);
+ 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) {
+ const [hours, minutes] = scheduledTime.split(':').map(Number);
+ const nextDate = new Date(nextDue);
+ nextDate.setHours(hours, minutes, 0, 0);
+ if (nextDate.getTime() > nextDue) nextDue = nextDate.getTime();
+ }
+ return timeUntil(nextDue, 'Now');
+}
+
+function getJobTypeLabel(job) {
+ if (job.type === 'shell') return 'Shell';
+ if (job.type === 'script') return 'Script';
+ return 'AI';
+}
+
+function BriefingConfig({ config, onChange }) {
+ return (
+ <div className="space-y-2">
+ <span className="text-xs text-gray-400">Briefing Enrichments</span>
+ <div className="grid grid-cols-1 sm:grid-cols-3 gap-2">
+ {BRIEFING_CONFIG_OPTIONS.map(opt => (
+ <button
+ key={opt.key}
+ type="button"
+ onClick={() => onChange(opt.key, !config[opt.key])}
+ className={`flex items-center gap-2 px-3 py-2 rounded-lg border text-left text-sm transition-colors ${
+ config[opt.key]
+ ? 'border-port-accent/50 bg-port-accent/10 text-white'
+ : 'border-port-border bg-port-bg text-gray-500 hover:text-gray-300'
+ }`}
+ >
+ <span className={`w-3 h-3 rounded-sm border shrink-0 ${
+ config[opt.key] ? 'bg-port-accent border-port-accent' : 'border-gray-600'
+ }`} />
+ <div>
+ <div className="font-medium">{opt.label}</div>
+ <div className="text-xs opacity-60">{opt.desc}</div>
+ </div>
+ </button>
+ ))}
+ </div>
+ </div>
+ );
+}
+
+export function TaskMetadataFields({ data, onChange }) {
+ const toggle = (field) => {
+ const metadata = { ...data.taskMetadata, [field]: !data.taskMetadata?.[field] };
+ if (field === 'openPR' && metadata.openPR) metadata.useWorktree = true;
+ if (field === 'useWorktree' && !metadata.useWorktree) metadata.openPR = false;
+ onChange({ taskMetadata: metadata });
+ };
+ const fields = AGENT_OPTIONS.filter(option => ['useWorktree', 'openPR', 'simplify'].includes(option.field));
+
+ return (
+ <div className="flex items-center gap-2 flex-wrap">
+ <span className="text-xs text-gray-400">Options:</span>
+ {fields.map(({ field, shortLabel, label }) => {
+ const effective = !!data.taskMetadata?.[field];
+ return (
+ <button
+ key={field}
+ type="button"
+ onClick={() => toggle(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>
+ );
+}
+
+/**
+ * Shared scheduled-job card used by CoS System Tasks and app-scoped Custom
+ * Tasks. `fixedAppId`/`fixedType` constrain the edit form for the app surface,
+ * while the card, schedule, provider controls, and Run now behavior stay shared.
+ */
+export default function JobCard({
+ job,
+ apps = [],
+ providers,
+ activeProviderId,
+ timezone,
+ onToggle,
+ onTrigger,
+ onDelete,
+ onUpdate,
+ fixedAppId = null,
+ fixedType = null,
+ showTaskMetadata = false,
+ silentUpdate = true,
+ triggering = false
+}) {
+ const [expanded, setExpanded] = useState(false);
+ const [editing, setEditing] = useState(false);
+ const [editData, setEditData] = useState({});
+ const { isConfirming, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();
+ const hasFixedApp = typeof fixedAppId === 'string' && fixedAppId.length > 0;
+ const isShell = job.type === 'shell';
+ const isScript = job.type === 'script';
+ const appName = job.appId ? (apps.find(a => a.id === job.appId)?.name || job.appId) : null;
+
+ const startEditing = () => {
+ const base = {
+ name: job.name,
+ description: job.description,
+ type: fixedType || job.type || 'agent',
+ scheduleMode: job.cronExpression || job.cronSchedule ? 'cron' : 'interval',
+ interval: job.interval,
+ scheduledTime: job.scheduledTime || '',
+ cronExpression: job.cronExpression || '',
+ cronSchedule: job.cronSchedule || (job.cronExpression ? parseCronToRecurrence(job.cronExpression) : null),
+ priority: job.priority,
+ autonomyLevel: job.autonomyLevel,
+ promptTemplate: job.promptTemplate || '',
+ appId: hasFixedApp ? fixedAppId : (job.appId || ''),
+ providerId: job.providerId || '',
+ model: job.model || '',
+ effort: job.effort || '',
+ taskMetadata: showTaskMetadata
+ ? { useWorktree: false, openPR: false, simplify: false, ...(job.taskMetadata || {}) }
+ : job.taskMetadata || {}
+ };
+ // Always initialize shell fields so switching type to 'shell' during editing works
+ base.command = job.command || '';
+ base.triggerAction = job.triggerAction || 'log-only';
+ if (job.id === 'job-daily-briefing') {
+ base.config = { dailyJoke: false, dailyQuote: false, dailyImage: false, ...job.config };
+ }
+ setEditData(base);
+ setEditing(true);
+ setExpanded(true);
+ };
+
+ const handleSave = async () => {
+ const providerResolutionKnown = Boolean(editData.providerId || activeProviderId || providers?.length);
+ if (isAgentJobType(editData.type) && providerResolutionKnown
+ && !hasRunnableAgentProvider(providers, editData.providerId, activeProviderId)) {
+ toast.error('Select a CLI/TUI provider before saving an agent job');
+ return;
+ }
+ const constrained = {
+ ...editData,
+ ...(hasFixedApp ? { appId: fixedAppId } : {}),
+ ...(fixedType ? { type: fixedType } : {})
+ };
+ const payload = normalizeJobPayload(constrained);
+ const update = silentUpdate
+ ? api.updateCosJob(job.id, payload, { silent: true })
+ : api.updateCosJob(job.id, payload);
+ const result = await update.catch(err => {
+ toast.error(err.message);
+ return null;
+ });
+ if (!result) return;
+ toast.success('Job updated');
+ setEditing(false);
+ onUpdate();
+ };
+
+ const isDue = job.enabled && (job.cronSchedule
+ ? (!job.lastRun || Boolean(job.nextRunAt && Date.now() >= new Date(job.nextRunAt).getTime()))
+ : (!job.lastRun || (Date.now() - new Date(job.lastRun).getTime() >= job.intervalMs)));
+
+ return (
+ <div className={`bg-port-card border rounded-lg transition-colors ${
+ job.enabled ? 'border-port-border' : 'border-port-border/50 opacity-60'
+ }`}>
+ <div className="flex items-center gap-3 p-4">
+ <button
+ onClick={() => onToggle(job.id)}
+ className={`shrink-0 transition-colors ${job.enabled ? 'text-port-success' : 'text-gray-600'}`}
+ title={job.enabled ? 'Disable job' : 'Enable job'}
+ aria-label={job.enabled ? 'Disable job' : 'Enable job'}
+ >
+ {job.enabled ? <ToggleRight size={24} /> : <ToggleLeft size={24} />}
+ </button>
+
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-2 flex-wrap">
+ <span className="text-white font-medium truncate">{job.name}</span>
+ {isDue && (
+ <span className="px-1.5 py-0.5 bg-port-warning/20 text-port-warning text-xs rounded">Due</span>
+ )}
+ <span className={`px-1.5 py-0.5 text-xs rounded ${
+ isShell ? 'bg-emerald-500/20 text-emerald-400' :
+ isScript ? 'bg-port-accent-2/20 text-port-accent-2' :
+ 'bg-port-bg text-gray-400'
+ }`}>
+ {getJobTypeLabel(job)}
+ </span>
+ <span className="px-1.5 py-0.5 bg-port-bg text-gray-400 text-xs rounded">{job.category}</span>
+ {!hasFixedApp && 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 flex-wrap">
+ <span className="flex items-center gap-1">
+ <Clock size={10} />
+ {job.cronSchedule
+ ? <span title={job.cronExpression || undefined}>{describeRecurrence(job.cronSchedule)}</span>
+ : 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)}</span>}
+ <span>Runs: {job.runCount || 0}</span>
+ {isShell && job.lastExitCode != null && (
+ <span className={job.lastExitCode === 0 ? 'text-port-success' : 'text-port-error'}>Exit: {job.lastExitCode}</span>
+ )}
+ </div>
+ </div>
+
+ <div className="flex items-center gap-1">
+ <button
+ onClick={() => onTrigger(job.id)}
+ disabled={editing || triggering}
+ className={`p-1.5 transition-colors text-gray-500 ${editing || triggering ? 'opacity-50 cursor-not-allowed' : 'hover:text-port-accent'}`}
+ title={editing ? 'Save changes before running job' : triggering ? 'Triggering job' : 'Run now'}
+ aria-label={editing ? 'Save changes before running job' : triggering ? 'Triggering job' : 'Run now'}
+ >
+ <Play size={14} />
+ </button>
+ <button
+ onClick={startEditing}
+ className="p-1.5 text-gray-500 hover:text-white transition-colors"
+ title="Edit"
+ aria-label="Edit"
+ >
+ <Edit3 size={14} />
+ </button>
+ <button
+ onClick={() => setExpanded(!expanded)}
+ className="p-1.5 text-gray-500 hover:text-white transition-colors"
+ title={expanded ? 'Collapse' : 'Expand'}
+ aria-label={expanded ? 'Collapse' : 'Expand'}
+ >
+ {expanded ? <ChevronUp size={14} /> : <ChevronDown size={14} />}
+ </button>
+ </div>
+ </div>
+
+ {expanded && (
+ <div className="border-t border-port-border p-4 space-y-3">
+ {editing ? (
+ <>
+ <FormField label="Job name" labelClassName="block text-xs text-gray-400 mb-1">
+ <input
+ type="text"
+ value={editData.name}
+ onChange={e => setEditData(d => ({ ...d, name: e.target.value }))}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"
+ />
+ </FormField>
+ <FormField label="Description" labelClassName="block text-xs text-gray-400 mb-1">
+ <input
+ type="text"
+ value={editData.description}
+ onChange={e => setEditData(d => ({ ...d, description: e.target.value }))}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"
+ />
+ </FormField>
+ <div className="flex gap-3">
+ {fixedType ? (
+ <span className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-gray-400 text-sm">AI Agent</span>
+ ) : (
+ <select
+ aria-label="Job type"
+ value={editData.type}
+ onChange={e => setEditData(d => ({ ...d, type: e.target.value }))}
+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"
+ disabled={isScript}
+ >
+ {JOB_TYPE_OPTIONS.map(opt => <option key={opt.value} value={opt.value}>{opt.label}</option>)}
+ {isScript && <option value="script">Script Handler</option>}
+ </select>
+ )}
+ <select
+ aria-label="Priority"
+ value={editData.priority}
+ onChange={e => setEditData(d => ({ ...d, 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>
+ {editData.type !== 'shell' && (
+ <select
+ aria-label="Autonomy level"
+ value={editData.autonomyLevel}
+ onChange={e => setEditData(d => ({ ...d, 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>
+ <ScheduleFields data={editData} timezone={timezone} onChange={(key, val) => setEditData(d => ({ ...d, [key]: val }))} />
+ {isAgentJobType(editData.type) && !hasFixedApp && (
+ <div className="flex items-center gap-2">
+ <span className="text-xs text-gray-400">App scope:</span>
+ <select
+ aria-label="App scope"
+ 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>
+ )}
+ {isAgentJobType(editData.type) && (
+ <AgentJobProviderFields
+ data={editData}
+ providers={providers}
+ activeProviderId={activeProviderId}
+ onChange={patch => setEditData(d => ({ ...d, ...patch }))}
+ />
+ )}
+ {showTaskMetadata && isAgentJobType(editData.type) && <TaskMetadataFields data={editData} onChange={patch => setEditData(d => ({ ...d, ...patch }))} />}
+ {editData.config && (
+ <BriefingConfig
+ config={editData.config}
+ onChange={(key, val) => setEditData(d => ({ ...d, config: { ...d.config, [key]: val } }))}
+ />
+ )}
+ {editData.type === 'shell' ? (
+ <>
+ <textarea
+ aria-label="Shell command"
+ value={editData.command}
+ onChange={e => setEditData(d => ({ ...d, command: 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-20"
+ placeholder="Shell command"
+ />
+ <select
+ aria-label="Trigger action"
+ value={editData.triggerAction}
+ onChange={e => setEditData(d => ({ ...d, triggerAction: e.target.value }))}
+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"
+ >
+ {SHELL_TRIGGER_ACTION_OPTIONS.map(opt => <option key={opt.value} value={opt.value}>{opt.label}</option>)}
+ </select>
+ </>
+ ) : editData.type === 'script' ? (
+ <div className="space-y-1">
+ <span className="text-xs text-gray-400">Legacy script command (read-only)</span>
+ <pre className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-gray-400 text-sm font-mono">{editData.command || 'No command'}</pre>
+ </div>
+ ) : (
+ <textarea
+ aria-label="Prompt template"
+ value={editData.promptTemplate}
+ onChange={e => setEditData(d => ({ ...d, 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-40"
+ placeholder="Prompt template for the agent"
+ />
+ )}
+ <div className="flex justify-end gap-2">
+ <button
+ onClick={() => setEditing(false)}
+ 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={handleSave}
+ 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} /> Save
+ </button>
+ </div>
+ </>
+ ) : (
+ <>
+ <p className="text-sm text-gray-400">{job.description}</p>
+ {isShell && job.command && (
+ <div className="flex items-center gap-2 text-xs">
+ <Terminal size={12} className="text-emerald-400 shrink-0" />
+ <code className="text-emerald-300 bg-port-bg px-2 py-1 rounded font-mono">{job.command}</code>
+ </div>
+ )}
+ <div className="flex flex-wrap gap-4 text-xs text-gray-500">
+ <span>Priority: <span className="text-gray-300">{job.priority}</span></span>
+ {!isShell && <span>Autonomy: <span className="text-gray-300">{job.autonomyLevel}</span></span>}
+ {isAgentJobType(job.type) && job.providerId && (
+ <span>AI: <span className="text-gray-300">{providers?.find(p => p.id === job.providerId)?.name || job.providerId}{job.model ? ` / ${job.model}` : ''}{job.effort ? ` · ${job.effort}` : ''}</span></span>
+ )}
+ {isShell && <span>Action: <span className="text-gray-300">{job.triggerAction || 'log-only'}</span></span>}
+ <span>Created: <span className="text-gray-300">{formatDateNumeric(job.createdAt, '—')}</span></span>
+ </div>
+ {job.config && BRIEFING_CONFIG_OPTIONS.some(o => job.config[o.key]) && (
+ <div className="flex flex-wrap gap-2 text-xs">
+ <span className="text-gray-500">Enrichments:</span>
+ {BRIEFING_CONFIG_OPTIONS.filter(o => job.config[o.key]).map(o => (
+ <span key={o.key} className="px-2 py-0.5 bg-port-accent/10 text-port-accent rounded">{o.label}</span>
+ ))}
+ </div>
+ )}
+ {isShell && job.lastOutput && (
+ <details className="group">
+ <summary className="text-xs text-gray-500 cursor-pointer hover:text-gray-300 transition-colors">Last output (exit {job.lastExitCode})</summary>
+ <pre className="mt-2 p-3 bg-port-bg border border-port-border rounded-lg text-xs text-gray-400 font-mono whitespace-pre-wrap max-h-48 overflow-y-auto">{job.lastOutput}</pre>
+ </details>
+ )}
+ {!isShell && !isScript && (
+ <details className="group">
+ <summary className="text-xs text-gray-500 cursor-pointer hover:text-gray-300 transition-colors">View prompt template</summary>
+ <pre className="mt-2 p-3 bg-port-bg border border-port-border rounded-lg text-xs text-gray-400 font-mono whitespace-pre-wrap max-h-48 overflow-y-auto">{job.promptTemplate}</pre>
+ </details>
+ )}
+ {isConfirming(job.id) ? (
+ <InlineConfirmRow
+ question="Delete this job? This cannot be undone."
+ confirmTitle="Confirm delete"
+ cancelTitle="Cancel delete"
+ onConfirm={() => confirmDelete(() => onDelete(job.id))}
+ onCancel={cancelDelete}
+ />
+ ) : (
+ <div className="flex justify-end">
+ <button
+ onClick={() => requestDelete(job.id)}
+ className="flex items-center gap-1 px-2 py-1 text-xs text-red-400/60 hover:text-red-400 transition-colors"
+ >
+ <Trash2 size={12} /> Delete
+ </button>
+ </div>
+ )}
+ </>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/cos/tabs/JobsTab.jsx b/client/src/components/cos/tabs/JobsTab.jsx
index 9c001a26d7..7915a221f5 100644
--- a/client/src/components/cos/tabs/JobsTab.jsx
+++ b/client/src/components/cos/tabs/JobsTab.jsx
@@ -1,51 +1,23 @@
import { useState, useEffect, useCallback, useMemo } from 'react';
-import { Plus, RefreshCw, Play, Trash2, ChevronDown, ChevronUp, Clock, ToggleLeft, ToggleRight, Edit3, Save, X, Terminal } from 'lucide-react';
+import { Plus, RefreshCw } from 'lucide-react';
import toast from '../../ui/Toast';
import * as api from '../../../services/api';
-import { timeAgo, timeUntil, formatDateTime, formatDateNumeric } from '../../../utils/formatters';
-import { DEFAULT_CRON, describeCron, describeRecurrence, parseCronToRecurrence, buildCronFromRecurrence, JOB_INTERVAL_OPTIONS as INTERVAL_OPTIONS } from '../../../utils/cronHelpers';
-import CronSchedulePicker from '../../CronSchedulePicker';
+import { formatDateTime } from '../../../utils/formatters';
import AgentJobProviderFields, { hasRunnableAgentProvider } from '../AgentJobProviderFields';
import { filterRunnableProviders } from '../../../utils/providers';
-import InlineConfirmRow from '../../ui/InlineConfirmRow';
import FormField from '../../ui/FormField';
-import { useConfirmDelete } from '../../../hooks/useConfirmDelete';
+import JobCard, {
+ AUTONOMY_OPTIONS,
+ JOB_TYPE_OPTIONS,
+ isAgentJobType,
+ normalizeJobPayload,
+ PRIORITY_OPTIONS,
+ ScheduleFields,
+ SHELL_TRIGGER_ACTION_OPTIONS,
+ TRIGGER_ACTION_OPTIONS
+} from '../JobCard';
import useUserTimezone from '../../../hooks/useUserTimezone.js';
-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' },
- { value: 'assistant', label: 'Assistant', desc: 'Creates tasks, notifies you' },
- { value: 'manager', label: 'Manager', desc: 'Executes tasks autonomously' },
- { value: 'yolo', label: 'YOLO', desc: 'Full autonomy, no guardrails' }
-];
-
-const TRIGGER_ACTION_OPTIONS = [
- { value: 'log-only', label: 'Log Only' },
- { value: 'spawn-agent', label: 'Spawn Agent' },
- { value: 'create-task', label: 'Create Task' }
-];
-
-const SHELL_TRIGGER_ACTIONS = new Set(['spawn-agent', 'create-task']);
-const SHELL_TRIGGER_ACTION_OPTIONS = TRIGGER_ACTION_OPTIONS.filter(
- opt => !SHELL_TRIGGER_ACTIONS.has(opt.value)
-);
-
-const JOB_TYPE_OPTIONS = [
- { value: 'agent', label: 'AI Agent' },
- { value: 'shell', label: 'Shell Command' }
-];
-
-// App scope, provider/model override, and prompt template only apply to
-// AI-agent jobs — shell/script jobs run a fixed command and never reach the
-// AI runner.
-const isAgentJobType = (type) => type !== 'shell' && type !== 'script';
-
// Blank create-form state — shared by the initial useState and the post-create
// reset so the two can't drift (a field added to one but not the other would
// silently carry the previous job's value into the next).
@@ -71,531 +43,6 @@ const INITIAL_JOB = {
enabled: false
};
-const BRIEFING_CONFIG_OPTIONS = [
- { key: 'dailyJoke', label: 'Daily Joke', desc: 'Include a short joke to start the day' },
- { key: 'dailyQuote', label: 'Daily Quote', desc: 'Include an inspirational quote related to focus areas' },
- { key: 'dailyImage', label: 'Daily Image', desc: 'Generate an image via Stable Diffusion (requires image gen API)' }
-];
-
-function BriefingConfig({ config, onChange }) {
- return (
- <div className="space-y-2">
- <span className="text-xs text-gray-400">Briefing Enrichments</span>
- <div className="grid grid-cols-1 sm:grid-cols-3 gap-2">
- {BRIEFING_CONFIG_OPTIONS.map(opt => (
- <button
- key={opt.key}
- type="button"
- onClick={() => onChange(opt.key, !config[opt.key])}
- className={`flex items-center gap-2 px-3 py-2 rounded-lg border text-left text-sm transition-colors ${
- config[opt.key]
- ? 'border-port-accent/50 bg-port-accent/10 text-white'
- : 'border-port-border bg-port-bg text-gray-500 hover:text-gray-300'
- }`}
- >
- <span className={`w-3 h-3 rounded-sm border shrink-0 ${
- config[opt.key] ? 'bg-port-accent border-port-accent' : 'border-gray-600'
- }`} />
- <div>
- <div className="font-medium">{opt.label}</div>
- <div className="text-xs opacity-60">{opt.desc}</div>
- </div>
- </button>
- ))}
- </div>
- </div>
- );
-}
-
-function normalizeJobPayload(formData) {
- const payload = { ...formData };
- if (isAgentJobType(payload.type)) {
- payload.command = null;
- payload.triggerAction = null;
- } else {
- // App scope only applies to AI-agent jobs (the scope drives the agent's
- // workspace). Shell/script jobs always run in the PortOS root, so clear any
- // appId left over from when the job was an agent type — otherwise the saved
- // job shows a misleading app badge while executing in root.
- payload.appId = null;
- // Provider/model/effort overrides only apply to AI-agent jobs — clear any
- // leftover selection so a shell/script job doesn't carry a misleading AI badge.
- payload.providerId = null;
- payload.model = null;
- payload.effort = null;
- }
- // Empty app picker selection ('') → null so a PUT actively un-scopes the job
- // back to global (undefined would be dropped from JSON and updateJob would
- // preserve the old scope). The schema maps '' → null too; sending null directly
- // is unambiguous across create and update.
- if (!payload.appId) payload.appId = null;
- if (payload.scheduleMode === 'cron') {
- const derivedCron = buildCronFromRecurrence(payload.cronSchedule);
- payload.cronExpression = derivedCron || payload.cronExpression?.trim() || null;
- payload.cronSchedule = payload.cronSchedule || null;
- payload.scheduledTime = null;
- } else {
- payload.cronExpression = null;
- payload.cronSchedule = null;
- }
- delete payload.scheduleMode;
- return payload;
-}
-
-function ScheduleFields({ data, onChange, timezone }) {
- 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);
- // Seed the expression with the picker's displayed default (07:00
- // daily) so an untouched Cron picker is actually saveable.
- if (opt.value === 'cron' && !data.cronExpression && !data.cronSchedule) onChange('cronExpression', DEFAULT_CRON);
- }}
- 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="space-y-2">
- <CronSchedulePicker
- value={data.cronSchedule || data.cronExpression || DEFAULT_CRON}
- valueShape="recurrence"
- timezone={timezone}
- onChange={rule => {
- onChange('cronSchedule', rule);
- const cron = buildCronFromRecurrence(rule);
- onChange('cronExpression', cron || null);
- }}
- />
- </div>
- ) : (
- <div className="flex gap-3">
- <select
- aria-label="Interval"
- 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)"
- aria-label="Run at a 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.cronSchedule) return describeRecurrence(job.cronSchedule);
- 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) {
- const [hours, minutes] = scheduledTime.split(':').map(Number);
- const nextDate = new Date(nextDue);
- nextDate.setHours(hours, minutes, 0, 0);
- if (nextDate.getTime() > nextDue) nextDue = nextDate.getTime();
- }
- return timeUntil(nextDue, 'Now');
-}
-
-function getJobTypeLabel(job) {
- if (job.type === 'shell') return 'Shell';
- if (job.type === 'script') return 'Script';
- return 'AI';
-}
-
-function JobCard({ job, apps, providers, activeProviderId, timezone, onToggle, onTrigger, onDelete, onUpdate }) {
- const [expanded, setExpanded] = useState(false);
- const [editing, setEditing] = useState(false);
- const [editData, setEditData] = useState({});
- const { isConfirming, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();
- 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';
-
- const startEditing = () => {
- const base = {
- name: job.name,
- description: job.description,
- type: job.type || 'agent',
- scheduleMode: job.cronExpression || job.cronSchedule ? 'cron' : 'interval',
- interval: job.interval,
- scheduledTime: job.scheduledTime || '',
- cronExpression: job.cronExpression || '',
- cronSchedule: job.cronSchedule || (job.cronExpression ? parseCronToRecurrence(job.cronExpression) : null),
- priority: job.priority,
- autonomyLevel: job.autonomyLevel,
- promptTemplate: job.promptTemplate || '',
- appId: job.appId || '',
- providerId: job.providerId || '',
- model: job.model || '',
- effort: job.effort || ''
- };
- // Always initialize shell fields so switching type to 'shell' during editing works
- base.command = job.command || '';
- base.triggerAction = job.triggerAction || 'log-only';
- if (job.id === 'job-daily-briefing') {
- base.config = { dailyJoke: false, dailyQuote: false, dailyImage: false, ...job.config };
- }
- setEditData(base);
- setEditing(true);
- setExpanded(true);
- };
-
- const handleSave = async () => {
- const providerResolutionKnown = Boolean(editData.providerId || activeProviderId || providers.length);
- if (isAgentJobType(editData.type) && providerResolutionKnown
- && !hasRunnableAgentProvider(providers, editData.providerId, activeProviderId)) {
- toast.error('Select a CLI/TUI provider before saving an agent job');
- return;
- }
- const payload = normalizeJobPayload(editData);
- const result = await api.updateCosJob(job.id, payload, { silent: true }).catch(err => {
- toast.error(err.message);
- return null;
- });
- if (!result) return;
- toast.success('Job updated');
- setEditing(false);
- onUpdate();
- };
-
- const isDue = job.enabled && (job.cronSchedule
- ? (!job.lastRun || Boolean(job.nextRunAt && Date.now() >= new Date(job.nextRunAt).getTime()))
- : (!job.lastRun || (Date.now() - new Date(job.lastRun).getTime() >= job.intervalMs)));
-
- return (
- <div className={`bg-port-card border rounded-lg transition-colors ${
- job.enabled ? 'border-port-border' : 'border-port-border/50 opacity-60'
- }`}>
- <div className="flex items-center gap-3 p-4">
- {/* Toggle */}
- <button
- onClick={() => onToggle(job.id)}
- className={`shrink-0 transition-colors ${
- job.enabled ? 'text-port-success' : 'text-gray-600'
- }`}
- title={job.enabled ? 'Disable job' : 'Enable job'} aria-label={job.enabled ? 'Disable job' : 'Enable job'}
- >
- {job.enabled ? <ToggleRight size={24} /> : <ToggleLeft size={24} />}
- </button>
-
- {/* Info */}
- <div className="flex-1 min-w-0">
- <div className="flex items-center gap-2">
- <span className="text-white font-medium truncate">{job.name}</span>
- {isDue && (
- <span className="px-1.5 py-0.5 bg-port-warning/20 text-port-warning text-xs rounded">
- Due
- </span>
- )}
- <span className={`px-1.5 py-0.5 text-xs rounded ${
- isShell ? 'bg-emerald-500/20 text-emerald-400' :
- isScript ? 'bg-port-accent-2/20 text-port-accent-2' :
- 'bg-port-bg text-gray-400'
- }`}>
- {getJobTypeLabel(job)}
- </span>
- <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">
- <Clock size={10} />
- {job.cronSchedule
- ? <span title={job.cronExpression || undefined}>{describeRecurrence(job.cronSchedule)}</span>
- : 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)}
- </span>
- )}
- <span>Runs: {job.runCount || 0}</span>
- {isShell && job.lastExitCode != null && (
- <span className={job.lastExitCode === 0 ? 'text-port-success' : 'text-port-error'}>
- Exit: {job.lastExitCode}
- </span>
- )}
- </div>
- </div>
-
- {/* Actions */}
- <div className="flex items-center gap-1">
- <button
- onClick={() => onTrigger(job.id)}
- disabled={editing}
- className={`p-1.5 transition-colors text-gray-500 ${
- editing ? 'opacity-50 cursor-not-allowed' : 'hover:text-port-accent'
- }`}
- title={editing ? 'Save changes before running job' : 'Run now'}
- aria-label={editing ? 'Save changes before running job' : 'Run now'}
- >
- <Play size={14} />
- </button>
- <button
- onClick={startEditing}
- className="p-1.5 text-gray-500 hover:text-white transition-colors"
- title="Edit" aria-label="Edit"
- >
- <Edit3 size={14} />
- </button>
- <button
- onClick={() => setExpanded(!expanded)}
- className="p-1.5 text-gray-500 hover:text-white transition-colors"
- title={expanded ? 'Collapse' : 'Expand'} aria-label={expanded ? 'Collapse' : 'Expand'}
- >
- {expanded ? <ChevronUp size={14} /> : <ChevronDown size={14} />}
- </button>
- </div>
- </div>
-
- {/* Expanded content */}
- {expanded && (
- <div className="border-t border-port-border p-4 space-y-3">
- {editing ? (
- <>
- <FormField label="Job name" labelClassName="block text-xs text-gray-400 mb-1">
- <input
- type="text"
- value={editData.name}
- onChange={e => setEditData(d => ({ ...d, name: e.target.value }))}
- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"
- />
- </FormField>
- <FormField label="Description" labelClassName="block text-xs text-gray-400 mb-1">
- <input
- type="text"
- value={editData.description}
- onChange={e => setEditData(d => ({ ...d, description: e.target.value }))}
- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"
- />
- </FormField>
- <div className="flex gap-3">
- <select
- aria-label="Job type"
- value={editData.type}
- onChange={e => setEditData(d => ({ ...d, type: e.target.value }))}
- className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"
- disabled={isScript}
- >
- {JOB_TYPE_OPTIONS.map(opt => (
- <option key={opt.value} value={opt.value}>{opt.label}</option>
- ))}
- {isScript && <option value="script">Script Handler</option>}
- </select>
- <select
- aria-label="Priority"
- value={editData.priority}
- onChange={e => setEditData(d => ({ ...d, 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>
- {editData.type !== 'shell' && (
- <select
- aria-label="Autonomy level"
- value={editData.autonomyLevel}
- onChange={e => setEditData(d => ({ ...d, 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>
- <ScheduleFields data={editData} timezone={timezone} onChange={(key, val) => setEditData(d => ({ ...d, [key]: val }))} />
- {isAgentJobType(editData.type) && (
- <div className="flex items-center gap-2">
- <span className="text-xs text-gray-400">App scope:</span>
- <select
- aria-label="App scope"
- 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>
- )}
- {isAgentJobType(editData.type) && (
- <AgentJobProviderFields
- data={editData}
- providers={providers}
- activeProviderId={activeProviderId}
- onChange={patch => setEditData(d => ({ ...d, ...patch }))}
- />
- )}
- {editData.config && (
- <BriefingConfig
- config={editData.config}
- onChange={(key, val) => setEditData(d => ({ ...d, config: { ...d.config, [key]: val } }))}
- />
- )}
- {editData.type === 'shell' ? (
- <>
- <textarea
- aria-label="Shell command"
- value={editData.command}
- onChange={e => setEditData(d => ({ ...d, command: 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-20"
- placeholder="Shell command"
- />
- <select
- aria-label="Trigger action"
- value={editData.triggerAction}
- onChange={e => setEditData(d => ({ ...d, triggerAction: e.target.value }))}
- className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"
- >
- {SHELL_TRIGGER_ACTION_OPTIONS.map(opt => (
- <option key={opt.value} value={opt.value}>{opt.label}</option>
- ))}
- </select>
- </>
- ) : editData.type === 'script' ? (
- <div className="space-y-1">
- <span className="text-xs text-gray-400">Legacy script command (read-only)</span>
- <pre className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-gray-400 text-sm font-mono">{editData.command || 'No command'}</pre>
- </div>
- ) : (
- <textarea
- aria-label="Prompt template"
- value={editData.promptTemplate}
- onChange={e => setEditData(d => ({ ...d, 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-40"
- placeholder="Prompt template for the agent"
- />
- )}
- <div className="flex justify-end gap-2">
- <button
- onClick={() => setEditing(false)}
- 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={handleSave}
- 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} /> Save
- </button>
- </div>
- </>
- ) : (
- <>
- <p className="text-sm text-gray-400">{job.description}</p>
- {isShell && job.command && (
- <div className="flex items-center gap-2 text-xs">
- <Terminal size={12} className="text-emerald-400 shrink-0" />
- <code className="text-emerald-300 bg-port-bg px-2 py-1 rounded font-mono">{job.command}</code>
- </div>
- )}
- <div className="flex flex-wrap gap-4 text-xs text-gray-500">
- <span>Priority: <span className="text-gray-300">{job.priority}</span></span>
- {!isShell && <span>Autonomy: <span className="text-gray-300">{job.autonomyLevel}</span></span>}
- {isAgentJobType(job.type) && job.providerId && (
- <span>AI: <span className="text-gray-300">{providers.find(p => p.id === job.providerId)?.name || job.providerId}{job.model ? ` / ${job.model}` : ''}{job.effort ? ` · ${job.effort}` : ''}</span></span>
- )}
- {isShell && <span>Action: <span className="text-gray-300">{job.triggerAction || 'log-only'}</span></span>}
- <span>Created: <span className="text-gray-300">{formatDateNumeric(job.createdAt, '—')}</span></span>
- </div>
- {job.config && BRIEFING_CONFIG_OPTIONS.some(o => job.config[o.key]) && (
- <div className="flex flex-wrap gap-2 text-xs">
- <span className="text-gray-500">Enrichments:</span>
- {BRIEFING_CONFIG_OPTIONS.filter(o => job.config[o.key]).map(o => (
- <span key={o.key} className="px-2 py-0.5 bg-port-accent/10 text-port-accent rounded">{o.label}</span>
- ))}
- </div>
- )}
- {isShell && job.lastOutput && (
- <details className="group">
- <summary className="text-xs text-gray-500 cursor-pointer hover:text-gray-300 transition-colors">
- Last output (exit {job.lastExitCode})
- </summary>
- <pre className="mt-2 p-3 bg-port-bg border border-port-border rounded-lg text-xs text-gray-400 font-mono whitespace-pre-wrap max-h-48 overflow-y-auto">
- {job.lastOutput}
- </pre>
- </details>
- )}
- {!isShell && !isScript && (
- <details className="group">
- <summary className="text-xs text-gray-500 cursor-pointer hover:text-gray-300 transition-colors">
- View prompt template
- </summary>
- <pre className="mt-2 p-3 bg-port-bg border border-port-border rounded-lg text-xs text-gray-400 font-mono whitespace-pre-wrap max-h-48 overflow-y-auto">
- {job.promptTemplate}
- </pre>
- </details>
- )}
- {isConfirming(job.id) ? (
- <InlineConfirmRow
- question="Delete this job? This cannot be undone."
- confirmTitle="Confirm delete"
- cancelTitle="Cancel delete"
- onConfirm={() => confirmDelete(() => onDelete(job.id))}
- onCancel={cancelDelete}
- />
- ) : (
- <div className="flex justify-end">
- <button
- onClick={() => requestDelete(job.id)}
- className="flex items-center gap-1 px-2 py-1 text-xs text-red-400/60 hover:text-red-400 transition-colors"
- >
- <Trash2 size={12} /> Delete
- </button>
- </div>
- )}
- </>
- )}
- </div>
- )}
- </div>
- );
-}
-
export default function JobsTab() {
const timezone = useUserTimezone();
const [jobs, setJobs] = useState([]);
@@ -696,7 +143,9 @@ export default function JobsTab() {
} else if (result.success === false) {
toast.error(result.reason || `Job failed (exit ${result.exitCode ?? '?'})`, { id: 'job-trigger' });
} else {
- const msg = result.type === 'shell' || result.type === 'script' ? 'Job executed successfully' : 'Job triggered — task queued';
+ const msg = result.type === 'shell' || result.type === 'script'
+ ? 'Job executed successfully'
+ : result.started ? 'Job started — agent launching' : 'Job triggered — task queued';
toast.success(msg, { id: 'job-trigger' });
}
fetchJobs();
@@ -723,7 +172,6 @@ export default function JobsTab() {
return (
<div className="space-y-6">
- {/* Header */}
<div className="flex items-center justify-between">
<div>
<h3 className="text-lg font-semibold text-white">System Tasks</h3>
@@ -749,7 +197,6 @@ export default function JobsTab() {
</div>
</div>
- {/* Stats bar */}
{stats && (
<div className="flex gap-4 text-xs text-gray-500">
<span>{stats.enabled} enabled / {stats.total} total</span>
@@ -762,7 +209,6 @@ export default function JobsTab() {
</div>
)}
- {/* Create form */}
{showCreate && (
<div className="bg-port-card border border-port-accent/50 rounded-lg p-4">
<div className="space-y-3">
@@ -781,9 +227,7 @@ export default function JobsTab() {
onChange={e => setNewJob(j => ({ ...j, type: e.target.value }))}
className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"
>
- {JOB_TYPE_OPTIONS.map(opt => (
- <option key={opt.value} value={opt.value}>{opt.label}</option>
- ))}
+ {JOB_TYPE_OPTIONS.map(opt => <option key={opt.value} value={opt.value}>{opt.label}</option>)}
</select>
</FormField>
<FormField label="Category" labelClassName="block text-xs text-gray-400 mb-1">
@@ -810,9 +254,7 @@ export default function JobsTab() {
onChange={e => setNewJob(j => ({ ...j, 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>
- ))}
+ {PRIORITY_OPTIONS.map(p => <option key={p} value={p}>{p}</option>)}
</select>
{newJob.type !== 'shell' && (
<select
@@ -821,9 +263,7 @@ export default function JobsTab() {
onChange={e => setNewJob(j => ({ ...j, 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} — {opt.desc}</option>
- ))}
+ {AUTONOMY_OPTIONS.map(opt => <option key={opt.value} value={opt.value}>{opt.label} — {opt.desc}</option>)}
</select>
)}
</div>
@@ -865,9 +305,7 @@ export default function JobsTab() {
onChange={e => setNewJob(j => ({ ...j, triggerAction: e.target.value }))}
className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"
>
- {(newJob.type === 'shell' ? SHELL_TRIGGER_ACTION_OPTIONS : TRIGGER_ACTION_OPTIONS).map(opt => (
- <option key={opt.value} value={opt.value}>{opt.label}</option>
- ))}
+ {(newJob.type === 'shell' ? SHELL_TRIGGER_ACTION_OPTIONS : TRIGGER_ACTION_OPTIONS).map(opt => <option key={opt.value} value={opt.value}>{opt.label}</option>)}
</select>
</>
) : (
@@ -898,7 +336,6 @@ export default function JobsTab() {
</div>
)}
- {/* Jobs list */}
{jobs.length === 0 ? (
<div className="bg-port-card border border-port-border rounded-lg p-8 text-center">
<div className="text-gray-500 mb-3">No system tasks configured.</div>
diff --git a/server/routes/cosJobRoutes.js b/server/routes/cosJobRoutes.js
index fd7f1d8092..936e929464 100644
--- a/server/routes/cosJobRoutes.js
+++ b/server/routes/cosJobRoutes.js
@@ -240,7 +240,25 @@ router.post('/jobs/:id/trigger', asyncHandler(async (req, res) => {
});
return;
}
- res.json({ success: true, type: 'agent', status: 'queued', taskId: taskResult.id });
+
+ // A manual trigger is an explicit Run now action, so use the same force-spawn
+ // path as the task-list play button. The ordinary `tasks:changed` listener
+ // intentionally applies autonomous scheduling gates to internal tasks and can
+ // leave this freshly-created task pending until a later evaluation or manual
+ // start. Keep the task queued when the spawn cannot proceed (for example, no
+ // capacity), but report the actionable reason instead of claiming it started.
+ const spawnResult = await cos.forceSpawnTask(taskResult.id);
+ if (spawnResult?.error) {
+ res.json({
+ success: false,
+ type: 'agent',
+ status: 'skipped',
+ reason: spawnResult.error,
+ taskId: taskResult.id
+ });
+ return;
+ }
+ res.json({ success: true, type: 'agent', status: 'queued', started: true, taskId: taskResult.id });
}));
// DELETE /api/cos/jobs/:id - Delete a job
diff --git a/server/routes/cosJobRoutes.test.js b/server/routes/cosJobRoutes.test.js
index aca289995c..dd1e8f4eee 100644
--- a/server/routes/cosJobRoutes.test.js
+++ b/server/routes/cosJobRoutes.test.js
@@ -5,7 +5,8 @@ import { errorMiddleware } from '../lib/errorHandler.js';
import jobRoutes from './cosJobRoutes.js';
vi.mock('../services/cos.js', () => ({
- addTask: vi.fn()
+ addTask: vi.fn(),
+ forceSpawnTask: vi.fn()
}));
vi.mock('../services/autonomousJobs.js', () => ({
@@ -451,13 +452,16 @@ describe('CoS Job Routes', () => {
autonomousJobs.isScriptJob.mockReturnValue(false);
autonomousJobs.generateTaskFromJob.mockResolvedValue({ description: 'Review', priority: 'MEDIUM' });
cos.addTask.mockResolvedValue({ id: 'task-1' });
+ cos.forceSpawnTask.mockResolvedValue({ success: true, taskId: 'task-1' });
const response = await request(app).post('/api/cos/jobs/j1/trigger');
expect(response.status).toBe(200);
expect(response.body.type).toBe('agent');
expect(response.body.status).toBe('queued');
+ expect(response.body.started).toBe(true);
expect(response.body.taskId).toBe('task-1');
+ expect(cos.forceSpawnTask).toHaveBeenCalledWith('task-1');
});
it('should forward app scope + git options into addTask for an app-scoped agent job', async () => {
@@ -480,6 +484,7 @@ describe('CoS Job Routes', () => {
}
});
cos.addTask.mockResolvedValue({ id: 'task-2' });
+ cos.forceSpawnTask.mockResolvedValue({ success: true, taskId: 'task-2' });
const response = await request(app).post('/api/cos/jobs/j1/trigger');
@@ -498,6 +503,7 @@ describe('CoS Job Routes', () => {
}),
'internal'
);
+ expect(cos.forceSpawnTask).toHaveBeenCalledWith('task-2');
});
it('should forward provider + model overrides into addTask', async () => {
@@ -510,6 +516,7 @@ describe('CoS Job Routes', () => {
metadata: { provider: 'anthropic', model: 'claude-opus-4-8', effort: 'high' }
});
cos.addTask.mockResolvedValue({ id: 'task-3' });
+ cos.forceSpawnTask.mockResolvedValue({ success: true, taskId: 'task-3' });
const response = await request(app).post('/api/cos/jobs/j1/trigger');
@@ -518,6 +525,27 @@ describe('CoS Job Routes', () => {
expect.objectContaining({ provider: 'anthropic', model: 'claude-opus-4-8', effort: 'high' }),
'internal'
);
+ expect(cos.forceSpawnTask).toHaveBeenCalledWith('task-3');
+ });
+
+ it('reports a direct-spawn failure while retaining the queued task', async () => {
+ autonomousJobs.getJob.mockResolvedValue({ id: 'j1', type: 'agent', name: 'Review' });
+ autonomousJobs.isShellJob.mockReturnValue(false);
+ autonomousJobs.isScriptJob.mockReturnValue(false);
+ autonomousJobs.generateTaskFromJob.mockResolvedValue({ description: 'Review', priority: 'MEDIUM' });
+ cos.addTask.mockResolvedValue({ id: 'task-4' });
+ cos.forceSpawnTask.mockResolvedValue({ error: 'No available agent slots (1/1)' });
+
+ const response = await request(app).post('/api/cos/jobs/j1/trigger');
+
+ expect(response.status).toBe(200);
+ expect(response.body).toMatchObject({
+ success: false,
+ type: 'agent',
+ status: 'skipped',
+ taskId: 'task-4',
+ reason: 'No available agent slots (1/1)'
+ });
});
it('should return 404 if job not found', async () => {