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

run a custom scheduled task ad hoc from its card, with its own configuration

Adam Eivyb1421626e6e9
diff --git a/client/src/components/apps/tabs/AutomationTab.jsx b/client/src/components/apps/tabs/AutomationTab.jsx
index a92c3ea899..d1caab0afc 100644
--- a/client/src/components/apps/tabs/AutomationTab.jsx
+++ b/client/src/components/apps/tabs/AutomationTab.jsx
@@ -166,7 +166,7 @@ export default function AutomationTab({ appId, appName }) {
};
return (
- <div className="max-w-5xl space-y-4">
+ <div className="space-y-4">
<div className="border-b border-port-border pb-4">
<CustomTasksSection
appId={appId}
@@ -194,11 +194,11 @@ export default function AutomationTab({ appId, appName }) {
</button>
</div>
)}
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-4">
- <div>
+ <div className="flex flex-wrap items-center justify-between gap-3">
+ <div className="flex items-center gap-4 min-w-0">
+ <div className="min-w-0">
<h3 className="text-lg font-semibold text-white">Scheduled Task Options</h3>
- <p className="text-sm text-gray-500">
+ <p className="text-sm text-gray-500 max-w-3xl">
Each toggle turns that CoS scheduled task on or off for this app. The controls beside it are optional —
leave one on <em>Inherit</em> and it follows the global schedule defaults.
</p>
@@ -219,7 +219,7 @@ export default function AutomationTab({ appId, appName }) {
No task types configured in the schedule
</div>
) : (
- <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
+ <div className="grid grid-cols-1 lg:grid-cols-2 2xl:grid-cols-3 gap-4 items-start">
{taskTypes.map(taskType => {
const override = overrides[taskType] || {};
const globalConfig = schedule.tasks[taskType] || {};
diff --git a/client/src/components/apps/tabs/AutomationTab.test.jsx b/client/src/components/apps/tabs/AutomationTab.test.jsx
index b1b5b8189a..9824c7704d 100644
--- a/client/src/components/apps/tabs/AutomationTab.test.jsx
+++ b/client/src/components/apps/tabs/AutomationTab.test.jsx
@@ -108,6 +108,23 @@ describe('AutomationTab per-app options', () => {
expect(within(row).getByRole('button', { name: 'Run Now' })).toBeEnabled();
});
+ it('lets the task cards use the full desktop width instead of a narrow column', async () => {
+ api.getAppTaskTypes.mockResolvedValue({ taskTypeOverrides: {} });
+ api.getCosSchedule.mockResolvedValue(SCHEDULE);
+ api.getCosStatus.mockResolvedValue({ paused: false });
+ api.getProviders.mockResolvedValue(PROVIDERS);
+ api.getCosJobs.mockResolvedValue({ jobs: [] });
+ api.getSettings.mockResolvedValue({ timezone: 'UTC' });
+ const { container } = render(<AutomationTab appId="app-1" appName="MyApp" />);
+ await screen.findByText('layered-intelligence');
+ await act(async () => {});
+
+ expect(container.querySelector('.max-w-5xl')).toBeNull();
+ // Cards widen with the viewport rather than stopping at two columns.
+ const grid = screen.getByText('layered-intelligence').closest('.grid');
+ expect(grid).toHaveClass('grid-cols-1', 'lg:grid-cols-2', '2xl:grid-cols-3');
+ });
+
it('puts custom automations before the shared schedule cards and shows app cadence', async () => {
await renderTab({ security: { enabled: true, interval: 'on-demand' } });
const custom = screen.getByText('Custom Tasks');
diff --git a/client/src/components/apps/tabs/CustomTasksSection.jsx b/client/src/components/apps/tabs/CustomTasksSection.jsx
index 4254111b93..479a34208f 100644
--- a/client/src/components/apps/tabs/CustomTasksSection.jsx
+++ b/client/src/components/apps/tabs/CustomTasksSection.jsx
@@ -90,7 +90,7 @@ function TaskForm({ form, setForm, onSave, onCancel, saveLabel, timezone, provid
const update = (key, val) => setForm(f => ({ ...f, [key]: val }));
return (
- <div className="space-y-3 bg-port-card border border-port-accent/50 rounded-lg p-4">
+ <div className="space-y-3 bg-port-card border border-port-accent/50 rounded-lg p-4 max-w-4xl">
<FormField label="Task name *">
<input
type="text"
@@ -256,11 +256,13 @@ export default function CustomTasksSection({ appId, appName, providerCatalog, ac
setTasks(prev => prev.map(t => t.id === jobId ? { ...t, enabled: result.job.enabled } : t));
};
- const handleTrigger = async (jobId) => {
+ // `runOptions` carries the card's ad-hoc run configuration, when the task
+ // declares one — the values apply to this run only and are not saved.
+ const handleTrigger = async (jobId, runOptions) => {
const job = tasks.find(task => task.id === jobId);
if (!job) return;
setTriggering(jobId);
- const result = await api.triggerCosJob(jobId).catch(() => null);
+ const result = await api.triggerCosJob(jobId, runOptions).catch(() => null);
setTriggering(null);
if (!result) return; // HTTP/network error already toasted by the api helper
if (result.status === 'skipped') {
@@ -316,7 +318,7 @@ export default function CustomTasksSection({ appId, appName, providerCatalog, ac
</div>
)
) : (
- <div className="space-y-2">
+ <div className="grid grid-cols-1 xl:grid-cols-2 gap-3 items-start">
{tasks.map(job => (
<JobCard
key={job.id}
diff --git a/client/src/components/apps/tabs/CustomTasksSection.test.jsx b/client/src/components/apps/tabs/CustomTasksSection.test.jsx
index 2d276e83c0..eec826d4f9 100644
--- a/client/src/components/apps/tabs/CustomTasksSection.test.jsx
+++ b/client/src/components/apps/tabs/CustomTasksSection.test.jsx
@@ -263,6 +263,52 @@ describe('CustomTasksSection trigger outcomes', () => {
expect(toast.error).not.toHaveBeenCalled();
});
+ it('runs a task with values typed into the card, without saving them to the task', async () => {
+ api.getCosJobs.mockResolvedValue({
+ jobs: [{
+ ...task,
+ formFields: [{ key: 'subject', label: 'Subject', type: 'text' }],
+ formValues: { subject: 'Saved subject' }
+ }],
+ dataInputCatalog: []
+ });
+ api.triggerCosJob.mockResolvedValue({ success: true, status: 'queued', started: true });
+
+ render(<CustomTasksSection appId="app-1" appName="Example App" />);
+ await screen.findByText('Example Task');
+
+ // The card exposes the field itself — no Edit round-trip to re-aim a run.
+ const subject = screen.getByLabelText('Subject');
+ expect(subject).toHaveValue('Saved subject');
+ fireEvent.change(subject, { target: { value: 'One-off subject' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Run now' }));
+
+ await waitFor(() => expect(api.triggerCosJob).toHaveBeenCalledWith('job-1', {
+ formValues: { subject: 'One-off subject' }
+ }));
+ expect(api.updateCosJob).not.toHaveBeenCalled();
+ });
+
+ it('blocks an ad-hoc run that leaves a required card field blank', async () => {
+ api.getCosJobs.mockResolvedValue({
+ jobs: [{
+ ...task,
+ formFields: [{ key: 'subject', label: 'Subject', type: 'text', required: true }],
+ formValues: { subject: 'Saved subject' }
+ }],
+ dataInputCatalog: []
+ });
+
+ render(<CustomTasksSection appId="app-1" appName="Example App" />);
+ await screen.findByText('Example Task');
+
+ fireEvent.change(screen.getByLabelText('Subject *'), { target: { value: ' ' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Run now' }));
+
+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Fill in Subject'));
+ expect(api.triggerCosJob).not.toHaveBeenCalled();
+ });
+
it('keeps Run now available for a disabled recurring schedule', async () => {
api.getCosJobs.mockResolvedValue({ jobs: [{ ...task, enabled: false }] });
api.triggerCosJob.mockResolvedValue({ success: true, status: 'queued' });
@@ -274,7 +320,7 @@ describe('CustomTasksSection trigger outcomes', () => {
expect(runNow).not.toBeDisabled();
fireEvent.click(runNow);
- await waitFor(() => expect(api.triggerCosJob).toHaveBeenCalledWith('job-1'));
+ await waitFor(() => expect(api.triggerCosJob).toHaveBeenCalledWith('job-1', {}));
expect(api.toggleCosJob).not.toHaveBeenCalled();
});
});
diff --git a/client/src/components/cos/JobCard.jsx b/client/src/components/cos/JobCard.jsx
index cb59f8ec71..1e6c3917b8 100644
--- a/client/src/components/cos/JobCard.jsx
+++ b/client/src/components/cos/JobCard.jsx
@@ -1,4 +1,4 @@
-import { useState } from 'react';
+import { useState, useEffect } 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';
@@ -7,11 +7,15 @@ import { DEFAULT_CRON, describeCron, describeRecurrence, parseCronToRecurrence,
import CronSchedulePicker from '../CronSchedulePicker';
import AgentJobProviderFields, { hasRunnableAgentProvider } from './AgentJobProviderFields';
import { AGENT_OPTIONS, agentOptionButtonClass } from './constants';
+import { triggerButtonClass } from './tabs/schedule/scheduleConstants';
import InlineConfirmRow from '../ui/InlineConfirmRow';
import FormField from '../ui/FormField';
import { useConfirmDelete } from '../../hooks/useConfirmDelete';
import TaskDataInputs from './TaskDataInputs';
-import { JobFormFieldsEditor, JobFormValueInputs, JobFormValuesSummary, missingRequiredJobFormFields } from './JobFormFields';
+import { JobFormFieldsEditor, JobFormValueInputs, missingRequiredJobFormFields } from './JobFormFields';
+
+// Footer actions beside Run now — same shape, quieter than the accent trigger.
+const SECONDARY_ACTION_CLASS = 'flex items-center gap-1.5 px-3 py-1.5 text-sm rounded text-gray-300 hover:text-white hover:bg-port-border/50 transition-colors';
const SCHEDULE_MODE_OPTIONS = [
{ value: 'interval', label: 'Interval' },
@@ -286,12 +290,44 @@ export default function JobCard({
const [expanded, setExpanded] = useState(false);
const [editing, setEditing] = useState(false);
const [editData, setEditData] = useState({});
+ // The ad-hoc dial for the next Run now. `null` = "whatever the job is saved
+ // with", which is why this is a nullable override rather than a copy: a value
+ // the user never touched must keep tracking the saved one, so an edit made in
+ // the drawer (or another surface) is picked up instead of pinned to whatever
+ // the card happened to mount with.
+ const [runValues, setRunValues] = useState(null);
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;
+ // The job's own configuration form, rendered inline on the card so a one-off
+ // run can be re-aimed without opening the editor. Shell/script jobs have no
+ // prompt for the values to reach, so they never declare any.
+ const runFormFields = isAgentJobType(job.type) ? (job.formFields || []) : [];
+ const savedFormValues = job.formValues || {};
+ // A stable signature, not the object identity: every refetch hands back a new
+ // object, which would clear the dial the user is filling in on every poll.
+ const savedFormValuesKey = JSON.stringify(savedFormValues);
+ useEffect(() => { setRunValues(null); }, [savedFormValuesKey]);
+ const runFormValues = runValues ?? savedFormValues;
+ const runValuesDirty = runValues !== null && JSON.stringify(runValues) !== savedFormValuesKey;
+
+ const handleTrigger = () => {
+ // The API accepts a half-filled configuration on purpose (a job is saved
+ // before it is aimed), so "required" is only real where it is collected —
+ // here, the same gate the save path applies.
+ const missing = missingRequiredJobFormFields(runFormFields, runFormValues);
+ if (missing.length) {
+ toast.error(`Fill in ${missing.map(field => field.label || field.key).join(', ')}`);
+ return;
+ }
+ // Always an options object, so a caller can forward it to the API wrapper
+ // unconditionally; a job with no declared fields sends no configuration.
+ onTrigger(job.id, runFormFields.length ? { formValues: runFormValues } : {});
+ };
+
const startEditing = () => {
const base = {
name: job.name,
@@ -364,10 +400,10 @@ export default function JobCard({
: (!job.lastRun || (Date.now() - new Date(job.lastRun).getTime() >= job.intervalMs)));
return (
- <div className={`bg-port-card border rounded-lg transition-colors ${
+ <div className={`flex flex-col 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">
+ <div className="flex items-start gap-3 p-4">
<button
onClick={() => onToggle(job.id)}
className={`shrink-0 transition-colors ${job.enabled ? 'text-port-success' : 'text-gray-600'}`}
@@ -417,35 +453,39 @@ export default function JobCard({
)}
</div>
</div>
+ </div>
- <div className="flex items-center gap-2">
- <button
- onClick={() => onTrigger(job.id)}
- disabled={editing || triggering}
- className={`min-h-[44px] min-w-[44px] inline-flex items-center justify-center 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="min-h-[44px] min-w-[44px] inline-flex items-center justify-center 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="min-h-[44px] min-w-[44px] inline-flex items-center justify-center 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>
+ {/* Ad-hoc run configuration — the inputs the job declares, right on the
+ card, so an on-demand run can be re-aimed without opening the editor.
+ Hidden while editing: the edit form renders the same fields as the
+ SAVED values, and two live copies of one form is a merge nobody wins. */}
+ {runFormFields.length > 0 && !editing && (
+ <div className="border-t border-port-border px-4 py-3 space-y-2">
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-xs text-gray-500 uppercase tracking-wider">Run configuration</span>
+ {runValuesDirty && (
+ <button
+ type="button"
+ onClick={() => setRunValues(null)}
+ className="text-xs text-gray-500 hover:text-white transition-colors"
+ >
+ Reset to saved
+ </button>
+ )}
+ </div>
+ <JobFormValueInputs
+ fields={runFormFields}
+ values={runFormValues}
+ onChange={setRunValues}
+ title={null}
+ />
+ <p className="text-xs text-gray-500">
+ {runValuesDirty
+ ? 'These values apply to the next Run now only — the saved task is unchanged.'
+ : 'Change these and press Run now for a one-off run; Edit changes what the task is saved with.'}
+ </p>
</div>
- </div>
+ )}
{expanded && (
<div className="border-t border-port-border p-4 space-y-3">
@@ -635,7 +675,6 @@ export default function JobCard({
<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 break-all max-h-48 overflow-y-auto">{job.lastOutput}</pre>
</details>
)}
- {!isShell && !isScript && <JobFormValuesSummary fields={job.formFields || []} values={job.formValues || {}} />}
{!isShell && !isScript && (
<details className="group">
<summary className="text-xs text-gray-500 cursor-pointer hover:text-gray-300 transition-colors">View prompt template</summary>
@@ -664,6 +703,45 @@ export default function JobCard({
)}
</div>
)}
+
+ {/* Footer actions — labeled, on their own row, so a job card reads like
+ the scheduled-task cards it sits beside rather than a list row with
+ three unlabeled glyphs. `mt-auto` keeps the row on the bottom edge
+ when cards of unequal height share a grid row. */}
+ <div className="flex items-center gap-2 mt-auto px-4 py-2.5 border-t border-port-border">
+ <button
+ type="button"
+ onClick={handleTrigger}
+ disabled={editing || triggering}
+ className={triggerButtonClass(editing || triggering)}
+ 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} />
+ {triggering ? 'Sending…' : 'Run now'}
+ </button>
+ <button
+ type="button"
+ onClick={startEditing}
+ className={SECONDARY_ACTION_CLASS}
+ title="Edit"
+ aria-label="Edit"
+ >
+ <Edit3 size={14} />
+ Edit
+ </button>
+ <button
+ type="button"
+ onClick={() => setExpanded(!expanded)}
+ aria-expanded={expanded}
+ className={`ml-auto ${SECONDARY_ACTION_CLASS}`}
+ title={expanded ? 'Hide details' : 'Details'}
+ aria-label={expanded ? 'Hide details' : 'Details'}
+ >
+ {expanded ? <ChevronUp size={14} /> : <ChevronDown size={14} />}
+ {expanded ? 'Hide details' : 'Details'}
+ </button>
+ </div>
</div>
);
}
diff --git a/client/src/components/cos/JobCard.test.jsx b/client/src/components/cos/JobCard.test.jsx
index 8cf158775f..62767c5eff 100644
--- a/client/src/components/cos/JobCard.test.jsx
+++ b/client/src/components/cos/JobCard.test.jsx
@@ -62,7 +62,7 @@ describe('JobCard machine output', () => {
lastExitCode: 1,
lastOutput
});
- fireEvent.click(screen.getByRole('button', { name: 'Expand' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Details' }));
const pre = screen.getByText(lastOutput);
expect(pre.tagName).toBe('PRE');
diff --git a/client/src/components/cos/JobFormFields.jsx b/client/src/components/cos/JobFormFields.jsx
index d727afc7fc..6e0fc1cb67 100644
--- a/client/src/components/cos/JobFormFields.jsx
+++ b/client/src/components/cos/JobFormFields.jsx
@@ -4,7 +4,7 @@ import FormField from '../ui/FormField';
import ToggleSwitch from '../ToggleSwitch';
/**
- * A job's own configuration form — the two halves of it, plus the read-only view.
+ * A job's own configuration form — the two halves of it.
*
* `JobFormFieldsEditor` edits the DEFINITIONS (what inputs this job has);
* `JobFormValueInputs` renders those definitions as real inputs and edits the
@@ -160,13 +160,13 @@ export function JobFormFieldsEditor({ fields = [], onChange }) {
/>
</FormField>
</div>
- <div className="flex flex-col gap-1 pt-5">
+ <div className="flex flex-col pt-5">
<button
type="button"
aria-label={`Move ${field.label || field.key || 'field'} up`}
onClick={() => move(index, -1)}
disabled={index === 0}
- className="p-1 text-gray-500 hover:text-white disabled:opacity-30 disabled:hover:text-gray-500"
+ className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center p-1 text-gray-500 hover:text-white disabled:opacity-30 disabled:hover:text-gray-500"
>
<ChevronUp size={14} />
</button>
@@ -175,7 +175,7 @@ export function JobFormFieldsEditor({ fields = [], onChange }) {
aria-label={`Move ${field.label || field.key || 'field'} down`}
onClick={() => move(index, 1)}
disabled={index === fields.length - 1}
- className="p-1 text-gray-500 hover:text-white disabled:opacity-30 disabled:hover:text-gray-500"
+ className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center p-1 text-gray-500 hover:text-white disabled:opacity-30 disabled:hover:text-gray-500"
>
<ChevronDown size={14} />
</button>
@@ -256,7 +256,11 @@ export function JobFormFieldsEditor({ fields = [], onChange }) {
);
}
-/** Fill in the declared fields. Renders nothing when the job declares none. */
+/**
+ * Fill in the declared fields. Renders nothing when the job declares none.
+ * `title` may be null for a host that labels the section itself (the card's
+ * inline ad-hoc run panel).
+ */
export function JobFormValueInputs({ fields = [], values = {}, onChange, title = 'Run configuration' }) {
if (!fields.length) return null;
@@ -264,7 +268,7 @@ export function JobFormValueInputs({ fields = [], values = {}, onChange, title =
return (
<div>
- <span className="text-sm text-gray-400 block mb-2">{title}</span>
+ {title && <span className="text-sm text-gray-400 block mb-2">{title}</span>}
<div className="space-y-2">
{fields.map((field, index) => {
// `??` rather than `||`: a stored `false` or `0` is a real value and
@@ -324,33 +328,3 @@ export function JobFormValueInputs({ fields = [], values = {}, onChange, title =
</div>
);
}
-
-/** Read-only summary of what a job is currently aimed at. */
-export function JobFormValuesSummary({ fields = [], values = {} }) {
- const filled = fields
- .map((field) => {
- const value = values?.[field.key];
- if (value == null) return null;
- if (typeof value === 'boolean') return { key: field.key, label: field.label || field.key, text: value ? 'Yes' : 'No' };
- const text = String(value).trim();
- if (!text) return null;
- const option = field.options?.find((candidate) => candidate.value === text);
- return { key: field.key, label: field.label || field.key, text: option?.label || text };
- })
- .filter(Boolean);
- if (!filled.length) return null;
-
- return (
- <div>
- <span className="text-xs text-gray-500 uppercase tracking-wider">Run configuration</span>
- <dl className="mt-1 space-y-1">
- {filled.map(({ key, label, text }) => (
- <div key={key} className="flex gap-2 text-xs">
- <dt className="text-gray-500 shrink-0">{label}:</dt>
- <dd className="text-gray-300 whitespace-pre-wrap break-words min-w-0">{text}</dd>
- </div>
- ))}
- </dl>
- </div>
- );
-}
diff --git a/client/src/components/cos/tabs/JobsTab.jsx b/client/src/components/cos/tabs/JobsTab.jsx
index c77a5a22ac..1d6924021a 100644
--- a/client/src/components/cos/tabs/JobsTab.jsx
+++ b/client/src/components/cos/tabs/JobsTab.jsx
@@ -134,9 +134,11 @@ export default function JobsTab() {
}
};
- const handleTrigger = async (jobId) => {
+ // `runOptions` carries the card's ad-hoc run configuration, when the job
+ // declares one — the values apply to this run only and are not saved.
+ const handleTrigger = async (jobId, runOptions) => {
toast.loading('Triggering job...', { id: 'job-trigger' });
- const result = await api.triggerCosJob(jobId, { silent: true }).catch(err => {
+ const result = await api.triggerCosJob(jobId, { ...runOptions, silent: true }).catch(err => {
toast.error(err.message, { id: 'job-trigger' });
return null;
});
diff --git a/client/src/services/apiAgents.js b/client/src/services/apiAgents.js
index 2181943be2..013cb50d82 100644
--- a/client/src/services/apiAgents.js
+++ b/client/src/services/apiAgents.js
@@ -383,7 +383,13 @@ export const updateCosJob = (id, data, options = {}) => request(`/cos/jobs/${id}
...options
});
export const toggleCosJob = (id, options = {}) => request(`/cos/jobs/${id}/toggle`, { method: 'POST', ...options });
-export const triggerCosJob = (id, options = {}) => request(`/cos/jobs/${id}/trigger`, { method: 'POST', ...options });
+// `formValues` re-aims this ONE run (the server merges them over the job's
+// stored values and writes nothing back); omit it to run the job as saved.
+export const triggerCosJob = (id, { formValues = null, ...options } = {}) => request(`/cos/jobs/${id}/trigger`, {
+ method: 'POST',
+ ...(formValues ? { body: JSON.stringify({ formValues }) } : {}),
+ ...options
+});
export const deleteCosJob = (id, options = {}) => request(`/cos/jobs/${id}`, { method: 'DELETE', ...options });
// Workflow visualizer — canonical scheduled-task ordering across tasks + jobs
diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.js
index 1207d66afe..66d842b5ce 100644
--- a/server/lib/cosValidation.js
+++ b/server/lib/cosValidation.js
@@ -535,6 +535,15 @@ export const updateCosJobSchema = createCosJobSchema.partial().extend({
weekdaysOnly: z.boolean().optional(),
});
+// Manual "Run now", with an optional one-off configuration. The values are
+// merged over the job's stored `formValues` for THAT RUN ONLY — nothing is
+// written back to the job — which is the whole point of an on-demand job: it is
+// re-aimed per trigger without an edit to its saved design. An absent body (the
+// historical shape of this endpoint) runs the job exactly as stored.
+export const triggerCosJobSchema = z.object({
+ formValues: jobFormValuesSchema.optional(),
+});
+
// =============================================================================
// COS LEARNING SCHEMAS
// =============================================================================
diff --git a/server/routes/cosJobRoutes.js b/server/routes/cosJobRoutes.js
index 64e250315a..77d8be33fb 100644
--- a/server/routes/cosJobRoutes.js
+++ b/server/routes/cosJobRoutes.js
@@ -10,7 +10,7 @@ import { computeNextJobRun } from '../services/autonomousJobs/scheduler.js';
import { parseCronToNextRun, isValidRecurrence } from '../services/eventScheduler.js';
import { getUserTimezone } from '../services/userTimezone.js';
import { asyncHandler, ServerError, failValidation } from '../lib/errorHandler.js';
-import { createCosJobSchema, updateCosJobSchema } from '../lib/validation.js';
+import { createCosJobSchema, updateCosJobSchema, triggerCosJobSchema } from '../lib/validation.js';
import { getTaskDataInputCatalog } from '../lib/taskDataInputCatalog.js';
import { generatedJobTaskFields } from '../lib/autonomousJobTask.js';
@@ -175,6 +175,10 @@ router.post('/jobs/:id/trigger', asyncHandler(async (req, res) => {
throw new ServerError('Job not found', { status: 404, code: 'NOT_FOUND' });
}
+ const parsedTrigger = triggerCosJobSchema.safeParse(req.body || {});
+ if (!parsedTrigger.success) failValidation(parsedTrigger);
+ const { formValues: runFormValues } = parsedTrigger.data;
+
// Shell jobs execute the command directly
if (autonomousJobs.isShellJob(job)) {
const result = await autonomousJobs.executeShellJob(job);
@@ -193,7 +197,14 @@ router.post('/jobs/:id/trigger', asyncHandler(async (req, res) => {
// Generate task and add to CoS internal task queue
// 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);
+ // A one-off run configuration re-aims THIS run only: the values are merged
+ // over the stored ones for prompt assembly and the job on disk is left alone,
+ // so the card's inputs are an ad-hoc dial rather than a silent edit. Merged
+ // (not replaced) so a field the caller didn't render keeps its saved value.
+ const jobForRun = runFormValues
+ ? { ...job, formValues: { ...job.formValues, ...runFormValues } }
+ : job;
+ const task = await autonomousJobs.generateTaskFromJob(jobForRun);
// 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
diff --git a/server/routes/cosJobRoutes.test.js b/server/routes/cosJobRoutes.test.js
index 2409dc16cd..824c32310f 100644
--- a/server/routes/cosJobRoutes.test.js
+++ b/server/routes/cosJobRoutes.test.js
@@ -533,6 +533,51 @@ describe('CoS Job Routes', () => {
expect(cos.forceSpawnTask).toHaveBeenCalledWith('task-1');
});
+ it('re-aims one run with the request body values without touching the stored job', async () => {
+ const storedJob = {
+ id: 'j1',
+ type: 'agent',
+ name: 'Review',
+ formFields: [
+ { key: 'subject', label: 'Subject', type: 'text' },
+ { key: 'depth', label: 'Depth', type: 'text' }
+ ],
+ formValues: { subject: 'Saved subject', depth: 'shallow' }
+ };
+ autonomousJobs.getJob.mockResolvedValue(storedJob);
+ autonomousJobs.isShellJob.mockReturnValue(false);
+ 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')
+ .send({ formValues: { subject: 'One-off subject' } });
+
+ expect(response.status).toBe(200);
+ // Merged over the stored values for THIS run: the untouched field keeps
+ // its saved value, and nothing is written back to the job.
+ expect(autonomousJobs.generateTaskFromJob).toHaveBeenCalledWith(expect.objectContaining({
+ formValues: { subject: 'One-off subject', depth: 'shallow' }
+ }));
+ expect(storedJob.formValues).toEqual({ subject: 'Saved subject', depth: 'shallow' });
+ expect(autonomousJobs.updateJob).not.toHaveBeenCalled();
+ });
+
+ it('rejects a malformed one-off run configuration', async () => {
+ autonomousJobs.getJob.mockResolvedValue({ id: 'j1', type: 'agent', name: 'Review' });
+ autonomousJobs.isShellJob.mockReturnValue(false);
+ autonomousJobs.isScriptJob.mockReturnValue(false);
+
+ const response = await request(app)
+ .post('/api/cos/jobs/j1/trigger')
+ .send({ formValues: { subject: { nested: true } } });
+
+ expect(response.status).toBe(400);
+ expect(autonomousJobs.generateTaskFromJob).not.toHaveBeenCalled();
+ });
+
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);