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

give a scheduled agent job its own configuration form

Adam Eivyb8ecb73caf90
diff --git a/client/src/components/apps/tabs/CustomTasksSection.jsx b/client/src/components/apps/tabs/CustomTasksSection.jsx
index 774179b1f5..4254111b93 100644
--- a/client/src/components/apps/tabs/CustomTasksSection.jsx
+++ b/client/src/components/apps/tabs/CustomTasksSection.jsx
@@ -9,6 +9,7 @@ import AgentJobProviderFields from '../../cos/AgentJobProviderFields';
import JobCard, { AUTONOMY_OPTIONS, PRIORITY_OPTIONS, ScheduleFields, TaskMetadataFields } from '../../cos/JobCard';
import { filterRunnableProviders } from '../../../utils/providers';
import TaskDataInputs from '../../cos/TaskDataInputs';
+import { JobFormFieldsEditor, JobFormValueInputs, missingRequiredJobFormFields } from '../../cos/JobFormFields';
export function emptyForm() {
return {
@@ -26,6 +27,8 @@ export function emptyForm() {
model: '',
effort: '',
dataInputs: [],
+ formFields: [],
+ formValues: {},
taskMetadata: { useWorktree: true, openPR: true, simplify: true }
};
}
@@ -46,6 +49,8 @@ export function formFromJob(job) {
model: job.model || '',
effort: job.effort || '',
dataInputs: job.dataInputs || [],
+ formFields: job.formFields || [],
+ formValues: job.formValues || {},
taskMetadata: { useWorktree: false, openPR: false, simplify: false, ...(job.taskMetadata || {}) }
};
}
@@ -64,6 +69,8 @@ export function toPayload(form, appId) {
model: form.model || null,
effort: form.effort || null,
dataInputs: form.dataInputs || [],
+ formFields: form.formFields || [],
+ formValues: form.formValues || {},
taskMetadata: form.taskMetadata
};
if (form.scheduleMode === 'cron') {
@@ -146,6 +153,17 @@ function TaskForm({ form, setForm, onSave, onCancel, saveLabel, timezone, provid
onChange={dataInputs => update('dataInputs', dataInputs)}
/>
+ <JobFormFieldsEditor
+ fields={form.formFields}
+ onChange={formFields => update('formFields', formFields)}
+ />
+
+ <JobFormValueInputs
+ fields={form.formFields}
+ values={form.formValues}
+ onChange={formValues => update('formValues', formValues)}
+ />
+
<TaskMetadataFields data={form} onChange={patch => setForm(f => ({ ...f, ...patch }))} />
<div className="flex justify-end gap-2">
@@ -207,6 +225,14 @@ export default function CustomTasksSection({ appId, appName, providerCatalog, ac
if (form.scheduleMode === 'cron' && !form.cronSchedule && (!form.cronExpression?.trim() || form.cronExpression.trim().split(/\s+/).length !== 5)) {
toast.error('A valid recurrence or 5-field cron expression is required'); return false;
}
+ // Required is enforced here rather than in the API schema: a job is
+ // routinely saved before it is aimed, so the server must still accept a
+ // half-filled config — this is the gate that keeps one from being saved by
+ // accident and then dispatched with a blank parameter.
+ const missing = missingRequiredJobFormFields(form.formFields, form.formValues);
+ if (missing.length) {
+ toast.error(`Fill in ${missing.map(field => field.label || field.key).join(', ')}`); return false;
+ }
return true;
};
diff --git a/client/src/components/apps/tabs/CustomTasksSection.test.jsx b/client/src/components/apps/tabs/CustomTasksSection.test.jsx
index 57518c3a30..2d276e83c0 100644
--- a/client/src/components/apps/tabs/CustomTasksSection.test.jsx
+++ b/client/src/components/apps/tabs/CustomTasksSection.test.jsx
@@ -142,6 +142,75 @@ describe('CustomTasksSection trigger outcomes', () => {
}), { silent: true }));
});
+ it('declares a configuration field, fills it in, and saves both halves', async () => {
+ api.createCosJob.mockResolvedValue({ success: true, job: task });
+
+ render(<CustomTasksSection appId="app-1" appName="Example App" />);
+ await screen.findByText('Example Task');
+ fireEvent.click(screen.getByRole('button', { name: /New Custom Task/ }));
+ fireEvent.change(screen.getByPlaceholderText('Task name *'), { target: { value: 'Parameterized Task' } });
+ fireEvent.change(screen.getByPlaceholderText('Prompt for the agent *'), { target: { value: 'Do the thing' } });
+
+ fireEvent.click(screen.getByRole('button', { name: /Add field/ }));
+ fireEvent.change(screen.getByPlaceholderText('What the agent reads, e.g. Topic'), { target: { value: 'Subject' } });
+ fireEvent.change(screen.getByPlaceholderText('topic'), { target: { value: 'subject' } });
+ // The value input appears only once the definition exists, and is bound by key.
+ fireEvent.change(screen.getByLabelText('Subject'), { target: { value: 'tides' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Create' }));
+
+ await waitFor(() => expect(api.createCosJob).toHaveBeenCalledWith(expect.objectContaining({
+ formFields: [expect.objectContaining({ key: 'subject', label: 'Subject', type: 'text' })],
+ formValues: { subject: 'tides' }
+ })));
+ });
+
+ it('lets a multi-line choice list be typed without eating the newlines', async () => {
+ // parse→serialize is lossy, so echoing the re-serialized value back into the
+ // textarea erased each newline as it was typed and a second choice could
+ // never be entered. The editor keeps the raw text; only the parse leaves it.
+ api.createCosJob.mockResolvedValue({ success: true, job: task });
+
+ render(<CustomTasksSection appId="app-1" appName="Example App" />);
+ await screen.findByText('Example Task');
+ fireEvent.click(screen.getByRole('button', { name: /New Custom Task/ }));
+ fireEvent.change(screen.getByPlaceholderText('Task name *'), { target: { value: 'Choice Task' } });
+ fireEvent.change(screen.getByPlaceholderText('Prompt for the agent *'), { target: { value: 'Do the thing' } });
+
+ fireEvent.click(screen.getByRole('button', { name: /Add field/ }));
+ fireEvent.change(screen.getByPlaceholderText('What the agent reads, e.g. Topic'), { target: { value: 'Size' } });
+ fireEvent.change(screen.getByPlaceholderText('topic'), { target: { value: 'size' } });
+ fireEvent.change(screen.getByLabelText('Type'), { target: { value: 'select' } });
+
+ const choices = screen.getByLabelText('Choices');
+ fireEvent.change(choices, { target: { value: 'sq\n' } });
+ expect(choices.value).toBe('sq\n'); // the newline survives the round trip
+ fireEvent.change(choices, { target: { value: 'sq|Square\ntall' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Create' }));
+
+ await waitFor(() => expect(api.createCosJob).toHaveBeenCalledWith(expect.objectContaining({
+ formFields: [expect.objectContaining({
+ type: 'select',
+ options: [{ value: 'sq', label: 'Square' }, { value: 'tall' }]
+ })]
+ })));
+ });
+
+ it('refuses to save while a required configuration field is blank', async () => {
+ api.updateCosJob.mockResolvedValue({ success: true, job: task });
+ api.getCosJobs.mockResolvedValue({
+ jobs: [{ ...task, formFields: [{ key: 'subject', label: 'Subject', type: 'text', required: true }], formValues: {} }],
+ dataInputCatalog: []
+ });
+
+ render(<CustomTasksSection appId="app-1" appName="Example App" />);
+ await screen.findByText('Example Task');
+ fireEvent.click(screen.getByRole('button', { name: 'Edit' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
+
+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Fill in Subject'));
+ expect(api.updateCosJob).not.toHaveBeenCalled();
+ });
+
it('keeps required prompt validation when editing the shared card', async () => {
render(<CustomTasksSection appId="app-1" appName="Example App" />);
await screen.findByText('Example Task');
diff --git a/client/src/components/cos/JobCard.jsx b/client/src/components/cos/JobCard.jsx
index f7cbeb598e..cb59f8ec71 100644
--- a/client/src/components/cos/JobCard.jsx
+++ b/client/src/components/cos/JobCard.jsx
@@ -11,6 +11,7 @@ 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';
const SCHEDULE_MODE_OPTIONS = [
{ value: 'interval', label: 'Interval' },
@@ -75,6 +76,11 @@ export function normalizeJobPayload(formData) {
payload.model = null;
payload.effort = null;
payload.dataInputs = [];
+ // The configuration form exists to parameterize a PROMPT. A shell/script job
+ // has none, so its values would reach nothing — clear them rather than leave
+ // a saved job advertising knobs that do nothing.
+ payload.formFields = [];
+ payload.formValues = {};
}
// 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
@@ -304,6 +310,8 @@ export default function JobCard({
model: job.model || '',
effort: job.effort || '',
dataInputs: job.dataInputs || [],
+ formFields: job.formFields || [],
+ formValues: job.formValues || {},
taskMetadata: showTaskMetadata
? { useWorktree: false, openPR: false, simplify: false, ...(job.taskMetadata || {}) }
: job.taskMetadata || {}
@@ -327,6 +335,14 @@ export default function JobCard({
toast.error('Select a CLI/TUI provider before saving an agent job');
return;
}
+ // The API schema deliberately accepts a half-filled configuration form (a
+ // job is routinely saved before it is aimed), so the "required" marker is
+ // only real if the form that collects the values enforces it.
+ const missingFields = missingRequiredJobFormFields(editData.formFields, editData.formValues);
+ if (missingFields.length) {
+ toast.error(`Fill in ${missingFields.map(field => field.label || field.key).join(', ')}`);
+ return;
+ }
const constrained = {
...editData,
...(hasFixedApp ? { appId: fixedAppId } : {}),
@@ -520,6 +536,19 @@ export default function JobCard({
onChange={dataInputs => setEditData(d => ({ ...d, dataInputs }))}
/>
)}
+ {isAgentJobType(editData.type) && (
+ <JobFormFieldsEditor
+ fields={editData.formFields}
+ onChange={formFields => setEditData(d => ({ ...d, formFields }))}
+ />
+ )}
+ {isAgentJobType(editData.type) && (
+ <JobFormValueInputs
+ fields={editData.formFields}
+ values={editData.formValues}
+ onChange={formValues => setEditData(d => ({ ...d, formValues }))}
+ />
+ )}
{showTaskMetadata && isAgentJobType(editData.type) && <TaskMetadataFields data={editData} onChange={patch => setEditData(d => ({ ...d, ...patch }))} />}
{editData.config && (
<BriefingConfig
@@ -606,6 +635,7 @@ 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>
diff --git a/client/src/components/cos/JobFormFields.jsx b/client/src/components/cos/JobFormFields.jsx
new file mode 100644
index 0000000000..d727afc7fc
--- /dev/null
+++ b/client/src/components/cos/JobFormFields.jsx
@@ -0,0 +1,356 @@
+import { useState } from 'react';
+import { Plus, Trash2, ChevronUp, ChevronDown } from 'lucide-react';
+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.
+ *
+ * `JobFormFieldsEditor` edits the DEFINITIONS (what inputs this job has);
+ * `JobFormValueInputs` renders those definitions as real inputs and edits the
+ * VALUES. They are separate components because they are separate decisions at
+ * different tempos: the shape of a job is designed once, while its values are
+ * re-aimed before a run. `server/lib/jobFormFields.js` is the server half — it
+ * validates both and projects the values into the agent's prompt.
+ */
+
+const JOB_FORM_FIELD_TYPE_OPTIONS = [
+ { value: 'text', label: 'Text (single line)' },
+ { value: 'textarea', label: 'Text (multi-line)' },
+ { value: 'number', label: 'Number' },
+ { value: 'select', label: 'Choice' },
+ { value: 'checkbox', label: 'Yes / no' },
+];
+
+/** Whether a field's value comes from a declared option list. */
+const isChoiceField = (type) => type === 'select';
+
+const inputClass = 'w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm';
+
+/**
+ * A blank definition. The generated key is the first `field_N` not already in
+ * use rather than one derived from the length — add, delete the first, add again
+ * and a length-derived name collides with a key that is still there, which the
+ * server rejects only at save time.
+ */
+function emptyField(fields) {
+ const taken = new Set(fields.map((field) => field.key));
+ let n = fields.length + 1;
+ while (taken.has(`field_${n}`)) n += 1;
+ return { key: `field_${n}`, label: '', type: 'text' };
+}
+
+/** Parse the textarea form of an option list: one `value` or `value|Label` per line. */
+function parseOptions(text) {
+ return text
+ .split('\n')
+ .map((line) => line.trim())
+ .filter(Boolean)
+ .map((line) => {
+ const [value, ...rest] = line.split('|');
+ const label = rest.join('|').trim();
+ return label ? { value: value.trim(), label } : { value: value.trim() };
+ })
+ .filter((option) => option.value);
+}
+
+function serializeOptions(options) {
+ return (options || []).map(({ value, label }) => (label ? `${value}|${label}` : value)).join('\n');
+}
+
+/**
+ * The choice list, edited as text.
+ *
+ * It holds its own raw string because parse→serialize is deliberately lossy —
+ * blank lines are dropped, whitespace trimmed. Feeding the re-serialized value
+ * back into the textarea would erase each newline as it is typed (after `a\n`
+ * the parse yields one option and the serialize yields `a`), making a
+ * multi-option list impossible to enter. So: raw text drives the textarea, the
+ * parsed form is what leaves the component, and an external change to the field
+ * (a reorder, a type switch) re-seeds the raw text via `key`.
+ */
+function OptionsEditor({ options, onChange }) {
+ const [text, setText] = useState(() => serializeOptions(options));
+ return (
+ <FormField label="Choices" hint="One per line. Use value|Label to show something friendlier than the stored value." compact>
+ <textarea
+ value={text}
+ onChange={(e) => {
+ setText(e.target.value);
+ onChange(parseOptions(e.target.value));
+ }}
+ className={`${inputClass} font-mono h-20`}
+ />
+ </FormField>
+ );
+}
+
+/**
+ * The value a field should start at when it has never been set: `false` for a
+ * checkbox (a yes/no question always has an answer), `''` for everything else
+ * (which the server reads as "not supplied" and omits from the prompt).
+ */
+function blankValue(field) {
+ return field.type === 'checkbox' ? false : '';
+}
+
+/** Declared fields whose value is required but missing — the save/trigger gate. */
+export function missingRequiredJobFormFields(fields, values) {
+ return (fields || []).filter((field) => {
+ if (!field?.required) return false;
+ // A checkbox answers itself: `false` is an answer, so it can never be missing.
+ if (field.type === 'checkbox') return false;
+ const value = values?.[field.key];
+ return value == null || String(value).trim() === '';
+ });
+}
+
+/** Edit the definitions: what inputs this job exposes. */
+export function JobFormFieldsEditor({ fields = [], onChange }) {
+ const update = (index, patch) => {
+ onChange(fields.map((field, i) => (i === index ? { ...field, ...patch } : field)));
+ };
+
+ const changeType = (index, type) => {
+ const field = fields[index];
+ const patch = { type };
+ // Options only belong to option-typed fields, and the server rejects them
+ // on any other type — so drop them on the way out and seed one on the way in.
+ if (!isChoiceField(type)) patch.options = undefined;
+ else if (!field.options?.length) patch.options = [{ value: 'option-1' }];
+ update(index, patch);
+ };
+
+ const move = (index, delta) => {
+ const target = index + delta;
+ if (target < 0 || target >= fields.length) return;
+ const next = [...fields];
+ [next[index], next[target]] = [next[target], next[index]];
+ onChange(next);
+ };
+
+ return (
+ <div>
+ <span className="text-sm text-gray-400 block mb-1">Configuration fields</span>
+ <p className="text-xs text-gray-500 mb-2">
+ Inputs this task exposes. Whatever they are set to is appended to the agent&apos;s prompt as run configuration, so one prompt can be re-aimed without rewriting it.
+ </p>
+
+ <div className="space-y-2">
+ {fields.map((field, index) => (
+ <div key={index} className="bg-port-bg/60 border border-port-border rounded-lg p-3 space-y-2">
+ <div className="flex items-start gap-2">
+ <div className="flex-1 grid grid-cols-1 sm:grid-cols-2 gap-2">
+ <FormField label="Label" compact>
+ <input
+ type="text"
+ value={field.label || ''}
+ placeholder="What the agent reads, e.g. Topic"
+ onChange={(e) => update(index, { label: e.target.value })}
+ className={inputClass}
+ />
+ </FormField>
+ <FormField label="Key" compact>
+ <input
+ type="text"
+ value={field.key || ''}
+ placeholder="topic"
+ onChange={(e) => update(index, { key: e.target.value })}
+ className={inputClass}
+ />
+ </FormField>
+ </div>
+ <div className="flex flex-col gap-1 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"
+ >
+ <ChevronUp size={14} />
+ </button>
+ <button
+ type="button"
+ 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"
+ >
+ <ChevronDown size={14} />
+ </button>
+ </div>
+ </div>
+
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
+ <FormField label="Type" compact>
+ <select
+ value={field.type || 'text'}
+ onChange={(e) => changeType(index, e.target.value)}
+ className={inputClass}
+ >
+ {JOB_FORM_FIELD_TYPE_OPTIONS.map((option) => (
+ <option key={option.value} value={option.value}>{option.label}</option>
+ ))}
+ </select>
+ </FormField>
+ <FormField label="Placeholder" compact>
+ <input
+ type="text"
+ value={field.placeholder || ''}
+ onChange={(e) => update(index, { placeholder: e.target.value })}
+ className={inputClass}
+ />
+ </FormField>
+ </div>
+
+ {isChoiceField(field.type) && (
+ <OptionsEditor
+ key={`${index}-${field.type}`}
+ options={field.options}
+ onChange={(options) => update(index, { options })}
+ />
+ )}
+
+ <FormField label="Hint" hint="Shown under the input. Explains the field to you, and is not sent to the agent." compact>
+ <input
+ type="text"
+ value={field.description || ''}
+ onChange={(e) => update(index, { description: e.target.value })}
+ className={inputClass}
+ />
+ </FormField>
+
+ <div className="flex items-center justify-between">
+ <button
+ type="button"
+ aria-pressed={!!field.required}
+ aria-label={`Required: ${field.required ? 'on' : 'off'}`}
+ onClick={() => update(index, { required: !field.required })}
+ className="flex items-center gap-2 min-h-[44px] text-sm text-gray-400 hover:text-white"
+ >
+ <ToggleSwitch enabled={!!field.required} decorative />
+ Required
+ </button>
+ <button
+ type="button"
+ aria-label={`Remove ${field.label || field.key || 'field'}`}
+ onClick={() => onChange(fields.filter((_, i) => i !== index))}
+ className="flex items-center gap-1 px-2 py-1 text-xs text-gray-500 hover:text-red-400"
+ >
+ <Trash2 size={14} /> Remove
+ </button>
+ </div>
+ </div>
+ ))}
+ </div>
+
+ <button
+ type="button"
+ onClick={() => onChange([...fields, emptyField(fields)])}
+ className="mt-2 flex items-center gap-1 text-sm text-port-accent hover:text-port-accent/80 transition-colors"
+ >
+ <Plus size={16} /> Add field
+ </button>
+ </div>
+ );
+}
+
+/** Fill in the declared fields. Renders nothing when the job declares none. */
+export function JobFormValueInputs({ fields = [], values = {}, onChange, title = 'Run configuration' }) {
+ if (!fields.length) return null;
+
+ const set = (key, value) => onChange({ ...values, [key]: value });
+
+ return (
+ <div>
+ <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
+ // must not fall through to the blank default.
+ const value = values?.[field.key] ?? blankValue(field);
+ const label = `${field.label || field.key}${field.required ? ' *' : ''}`;
+
+ if (field.type === 'checkbox') {
+ return (
+ <div key={`${field.key}-${index}`}>
+ <button
+ type="button"
+ aria-pressed={!!value}
+ aria-label={`${field.label || field.key}: ${value ? 'on' : 'off'}`}
+ onClick={() => set(field.key, !value)}
+ className="w-full flex items-center justify-between gap-3 min-h-[44px] rounded px-2 -mx-2 text-left hover:bg-port-card/30"
+ >
+ <span className="min-w-0 flex-1">
+ <span className="text-sm text-white block">{label}</span>
+ {field.description && <span className="text-xs text-gray-500 block">{field.description}</span>}
+ </span>
+ <ToggleSwitch enabled={!!value} decorative />
+ </button>
+ </div>
+ );
+ }
+
+ return (
+ <FormField key={`${field.key}-${index}`} label={label} hint={field.description || undefined}>
+ {field.type === 'textarea' ? (
+ <textarea
+ value={value}
+ placeholder={field.placeholder || ''}
+ onChange={(e) => set(field.key, e.target.value)}
+ className={`${inputClass} h-24`}
+ />
+ ) : field.type === 'select' ? (
+ <select value={value} onChange={(e) => set(field.key, e.target.value)} className={inputClass}>
+ <option value="">—</option>
+ {(field.options || []).map((option) => (
+ <option key={option.value} value={option.value}>{option.label || option.value}</option>
+ ))}
+ </select>
+ ) : (
+ <input
+ type={field.type === 'number' ? 'number' : 'text'}
+ value={value}
+ placeholder={field.placeholder || ''}
+ onChange={(e) => set(field.key, e.target.value)}
+ className={inputClass}
+ />
+ )}
+ </FormField>
+ );
+ })}
+ </div>
+ </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/server/lib/README.md b/server/lib/README.md
index 39d38c6410..8b03bbf349 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -474,6 +474,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `appIdentity.js` | The baseline managed-app id (`PORTOS_APP_ID`) — importable without pulling in the `services/apps.js` graph (pm2, scheduler, settings) behind it. Re-exported by `apps.js`. |
| `appResolver.js` | Fuzzy-match a spoken/typed phrase to a managed app (`{ id, name }`). Tiered exact → prefix → substring, used by voice tools that target a specific app. |
| `autonomousJobIntervals.js` | Autonomous-job cadence vocabulary (pure). `INTERVAL_OPTIONS` (picker rows, `ms: null` for a cadence with no recurrence), `ON_DEMAND_INTERVAL`, `JOB_INTERVAL_VALUES` (every legal stored cadence, incl. `custom`), `resolveIntervalMs(interval, customMs)` → ms or `null` (the no-interval sentinel — never falls through to `DAY`), and `isOnDemandJob(job)` for the three due/next-fire implementations. Lives here so `cosValidation.js` can validate the cadence without a lib → services import; `services/autonomousJobs/constants.js` re-exports it. Separate vocabulary from the scheduled-CoS-task `INTERVAL_TYPES`. |
+| `jobFormFields.js` | A scheduled agent job's own configuration form (pure). `JOB_FORM_FIELD_TYPES` (text/textarea/number/select/checkbox), the `jobFormFieldsSchema` / `jobFormValuesSchema` pair Zod-validates the job payload against, and the prompt projection `formatJobFormValues(fields, values)` / `appendJobFormValues(job, prompt)`. Definitions and values are stored separately so re-aiming a job (a new value) is not an edit to its design (a new field), and the projection iterates DEFINITIONS — a value whose field was deleted is inert. A field the user left blank is omitted rather than passed as an empty line, but a `false` checkbox is a real answer and is kept. Consumed by `services/autonomousJobs/skillTemplates.js`; the values reach the agent as the prompt's `## Run configuration` section. |
| `capabilityMap.js` | Pure row builders for Setup & Capabilities, including strict network/provider first-run readiness and optional-integration health rollups; fed by `routes/capabilities.js`. |
| `claimFlowTaskTypes.js` | `CLAIM_FLOW_TASK_TYPES` — the ONE list of task kinds whose prompts own their own `claim/<item>` worktree and push/PR/MR/review lifecycle (#6613). `services/cosTaskGenerator.js` stamps `metadata.claimFlow` from it (WRITE side); `services/agentPromptBuilder.js` reads it back through `isClaimFlowTask()` to pick a run's claim posture (READ side). It lived as two byte-identical copies, so a new claim type added to one silently split the writer from the reader — no error, just a claim run treated as a plain commit-only handoff; `claimFlowTaskTypes.test.js` fails if a local copy reappears. Imports nothing. |
| `chiptuneRender.js` | Deterministic chiptune score → mono PCM → 16-bit WAV buffer (pure Node, no audio deps); `renderScoreToPcm` / `pcmToWavBuffer` / `renderScoreToWav`. |
diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.js
index d921a77a53..1207d66afe 100644
--- a/server/lib/cosValidation.js
+++ b/server/lib/cosValidation.js
@@ -23,6 +23,7 @@ import { recurrenceRuleSchema } from './recurrenceValidation.js';
import { AUDIT_TASK_TYPE_LIST } from './auditCatalog.js';
import { CLAIM_DRAIN_TASK_TYPES } from './qualitySchedulePlan.js';
import { JOB_INTERVAL_VALUES } from './autonomousJobIntervals.js';
+import { jobFormFieldsSchema, jobFormValuesSchema } from './jobFormFields.js';
import { TASK_DATA_INPUT_DEFINITIONS, TASK_DATA_INPUT_IDS } from './taskDataInputCatalog.js';
import {
EFFORT_SELECTABLE_REVIEWERS,
@@ -467,6 +468,12 @@ export const createCosJobSchema = z.object({
// An empty array actively clears every selection on update; absent preserves
// the stored selection.
dataInputs: taskDataInputsSchema.optional(),
+ // The job's own configuration form: `formFields` declares the inputs, and
+ // `formValues` carries what they are currently set to. They are validated —
+ // and stored — separately so re-aiming a job (a new value) is not an edit to
+ // its design (a new field), and an empty array/object actively clears each.
+ formFields: jobFormFieldsSchema.optional(),
+ formValues: jobFormValuesSchema.optional(),
// Null actively clears the field: the jobs UI emits `command: null` /
// `triggerAction: null` whenever a job is saved as an AI-agent type (the two
// keys only apply to shell/script jobs), so rejecting null 400'd every edit of
diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.js
index 864536e086..54772e3511 100644
--- a/server/lib/importScoping.test.js
+++ b/server/lib/importScoping.test.js
@@ -659,14 +659,29 @@ describe('deferred imports stay deferred (#6156)', () => {
// carry: the previous number had drifted to ONE above the measured total, the
// zero-headroom state #6305 raised it out of, where any addition at all fails.
//
-// Raised to 110700 for the stale git lock fix (#7513). Measured after the
+// Raised to 110,700 for the stale git lock fix (#7513). Measured after the
// change: 109,282, so its own cost is +82 — one new test file
// (`services/git.staleLock.test.js`) reaching `services/git.js`'s existing
// closure to cover `pull`/`syncBranch`/`ensureLatest`'s lock-clearing paths.
// No new heavy edge: `git.js` was already reached by a dozen other server
// test files. The remainder restores headroom the previous number had worn
// down to zero.
-const MAX_STATIC_INSTANTIATIONS = 110700;
+//
+// Raised to 111,500 for `lib/jobFormFields.js`, the per-job configuration-form
+// vocabulary + schemas: a NEW leaf on `lib/cosValidation.js` — one node on each
+// of the ~131 closures that already reach the job schema, dragging no subtree
+// with it (its only import is `zod`, which every one of those closures already
+// carries). That is the shape this budget is meant to allow: the cost is one
+// module, not a new heavy edge.
+//
+// This raise and the #7513 one above landed on INDEPENDENT branches, so the
+// ceiling is re-measured against the combined tree rather than resolved by
+// taking the larger of the two competing numbers — that would bank headroom
+// neither branch ever verified. Measured after both: 109,991 (so jobFormFields
+// costs +709 over #7513's 109,282), and the ceiling keeps the ~1.5k of real
+// headroom this budget exists to carry rather than being pinned to the
+// measurement.
+const MAX_STATIC_INSTANTIATIONS = 111500;
const SKIP_DIRS = new Set(['node_modules', 'coverage', 'dist', 'data']);
diff --git a/server/lib/index.js b/server/lib/index.js
index 93410fd5e5..2267fff106 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -437,6 +437,7 @@ export * from './songCraftRef.js';
export * from './appIdentity.js';
export * from './appResolver.js';
export * from './autonomousJobIntervals.js';
+export * from './jobFormFields.js';
export * from './capabilityMap.js';
export * from './claimFlowTaskTypes.js';
export * from './chiptuneRender.js';
diff --git a/server/lib/jobFormFields.js b/server/lib/jobFormFields.js
new file mode 100644
index 0000000000..dce11bce86
--- /dev/null
+++ b/server/lib/jobFormFields.js
@@ -0,0 +1,166 @@
+/**
+ * Custom configuration fields for a scheduled agent job.
+ *
+ * A job's prompt says what to do; these say what to do it *with*. A job may
+ * declare its own small form — a subject line, extra instructions, a variant to
+ * pick, a flag to set — so one prompt can be re-aimed without rewriting it, and
+ * an on-demand job can be re-aimed right before each trigger.
+ *
+ * Two halves travel on the job and are deliberately separate:
+ * - `formFields`: the DEFINITIONS (key, label, type, options). The shape of
+ * the form. Changing one is an edit to the job's design.
+ * - `formValues`: the filled-in VALUES, keyed by field key. Changing one is
+ * just re-aiming the next run.
+ * Splitting them is what lets `formatJobFormValues` render in the author's
+ * declared order and silently ignore a stale value whose field was removed.
+ *
+ * Pure: the vocabulary, its Zod schemas, and the prompt projection. No I/O, so
+ * `cosValidation.js` can validate against it without a lib → services inversion.
+ */
+
+import { z } from 'zod';
+
+/**
+ * The field vocabulary. Deliberately small and presentational — each entry is a
+ * widget the UI can render and a value shape the prompt can state in one line.
+ * Anything richer (a file, a repeating group) belongs in the prompt itself or a
+ * data input, not here.
+ */
+export const JOB_FORM_FIELD_TYPES = Object.freeze(['text', 'textarea', 'number', 'select', 'checkbox']);
+
+/** Whether a field's value is chosen from a declared option list. */
+const isChoiceField = (type) => type === 'select';
+
+// Bounds exist so a malformed client can't push an unbounded blob into every
+// generated prompt. They are generous: the textarea case is a real one (pasted
+// source, a long brief), and the prompt assembler is what budgets total size.
+const MAX_FIELDS = 40;
+const MAX_OPTIONS = 60;
+const MAX_VALUE_CHARS = 20000;
+
+const jobFormFieldOptionSchema = z.object({
+ value: z.string().min(1).max(200),
+ // Absent label renders as the value — the common case where they're the same.
+ label: z.string().max(200).optional(),
+});
+
+const jobFormFieldSchema = z.object({
+ // The key is the map key for `formValues`, never interpolated into the prompt,
+ // so it only has to be stable and comparable. Restricted anyway: a key with
+ // whitespace or punctuation reads as a bug when it surfaces in a stored job.
+ key: z.string().regex(/^[A-Za-z][A-Za-z0-9_-]*$/, 'Key must start with a letter and use only letters, numbers, _ or -').max(64),
+ // The label is what the agent actually reads — `formatJobFormValues` prints it,
+ // not the key — so it carries the meaning and is required.
+ label: z.string().min(1).max(120),
+ type: z.enum(JOB_FORM_FIELD_TYPES),
+ // Help text under the input. UI-only; never reaches the prompt, because it
+ // explains the field to the human filling it, not the work to the agent.
+ description: z.string().max(500).optional(),
+ placeholder: z.string().max(200).optional(),
+ // Enforced by the form that collects the values, not by this schema: a job is
+ // routinely saved before it is aimed, and refusing to persist a half-filled
+ // config would make the field impossible to add to an existing job.
+ required: z.boolean().optional(),
+ options: z.array(jobFormFieldOptionSchema).max(MAX_OPTIONS).optional(),
+}).superRefine((field, ctx) => {
+ const needsOptions = isChoiceField(field.type);
+ if (needsOptions && !(field.options?.length > 0)) {
+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['options'], message: `A ${field.type} field needs at least one option` });
+ }
+ if (!needsOptions && field.options?.length) {
+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['options'], message: `A ${field.type} field must not declare options` });
+ }
+ const values = field.options?.map((option) => option.value) || [];
+ if (new Set(values).size !== values.length) {
+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['options'], message: 'Option values must be unique' });
+ }
+});
+
+export const jobFormFieldsSchema = z.array(jobFormFieldSchema).max(MAX_FIELDS).superRefine((fields, ctx) => {
+ const keys = fields.map((field) => field.key);
+ if (new Set(keys).size !== keys.length) {
+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Field keys must be unique' });
+ }
+});
+
+/**
+ * The filled-in values. Kept as a loose record on purpose: a number input hands
+ * back a string, a checkbox a boolean, and a cleared field an empty string, and
+ * the projection below reads all three the same way. Values for fields that no
+ * longer exist are harmless — the projection iterates DEFINITIONS.
+ */
+export const jobFormValuesSchema = z.record(
+ z.string().max(64),
+ z.union([z.string().max(MAX_VALUE_CHARS), z.number(), z.boolean(), z.null()])
+);
+
+/**
+ * Whether a raw value counts as supplied.
+ *
+ * Absent, null, and blank all mean "the user did not fill this in", and an
+ * unfilled field must be OMITTED rather than sent as an empty line — `Topic:`
+ * with nothing after it reads to the agent as a topic of "", which is a worse
+ * instruction than no topic at all. A boolean is different: `false` is a real
+ * answer to a yes/no question, so it is always kept once the key exists.
+ */
+function isSupplied(value) {
+ if (value === undefined || value === null) return false;
+ if (typeof value === 'boolean') return true;
+ return String(value).trim().length > 0;
+}
+
+/** Render one value as the agent should read it. */
+function renderValue(field, value) {
+ if (typeof value === 'boolean') return value ? 'Yes' : 'No';
+ const raw = String(value).trim();
+ if (field.type !== 'select') return raw;
+ // Print the option's LABEL when it has one: the value is often a terse slug
+ // chosen for storage, and the label is the words the author meant.
+ const option = field.options?.find((candidate) => candidate.value === raw);
+ return option?.label?.trim() || raw;
+}
+
+/**
+ * Project a job's declared fields + filled values into the prompt section the
+ * agent reads, or `''` when nothing was supplied.
+ *
+ * Single-line values become a bullet list so a handful of small knobs stay
+ * compact; a multi-line value gets its own heading, because folding a pasted
+ * brief into a bullet destroys the structure the user typed.
+ */
+export function formatJobFormValues(fields, values) {
+ if (!Array.isArray(fields) || fields.length === 0) return '';
+ const supplied = fields
+ .filter((field) => field?.key && isSupplied(values?.[field.key]))
+ .map((field) => ({ label: String(field.label || field.key).trim(), text: renderValue(field, values[field.key]) }))
+ .filter(({ text }) => text.length > 0);
+ if (supplied.length === 0) return '';
+
+ const inline = supplied.filter(({ text }) => !text.includes('\n'));
+ const blocks = supplied.filter(({ text }) => text.includes('\n'));
+
+ const parts = [
+ '## Run configuration',
+ 'These values were set for this run in the task\'s own configuration form. They are the parameters for THIS run: where one of them narrows or contradicts a general instruction above, the value here wins. A field the user left blank is omitted rather than passed as empty, so treat anything absent as unconstrained.',
+ ];
+ if (inline.length > 0) {
+ parts.push(inline.map(({ label, text }) => `- ${label}: ${text}`).join('\n'));
+ }
+ for (const { label, text } of blocks) {
+ parts.push(`### ${label}\n\n${text}`);
+ }
+ return parts.join('\n\n');
+}
+
+/**
+ * Append the run configuration to a prompt. Returns the prompt unchanged when
+ * the job declares no fields or none were filled in, so a job that never uses
+ * the feature produces a byte-identical prompt to before it existed.
+ */
+export function appendJobFormValues(job, prompt) {
+ const section = formatJobFormValues(job?.formFields, job?.formValues);
+ if (!section) return prompt;
+ // A job with no stored template would otherwise stringify `undefined` into the
+ // dispatched prompt. The configuration alone is still the whole instruction.
+ return prompt ? `${prompt}\n\n---\n\n${section}` : section;
+}
diff --git a/server/lib/jobFormFields.test.js b/server/lib/jobFormFields.test.js
new file mode 100644
index 0000000000..190476ad26
--- /dev/null
+++ b/server/lib/jobFormFields.test.js
@@ -0,0 +1,116 @@
+import { describe, it, expect } from 'vitest';
+import {
+ JOB_FORM_FIELD_TYPES,
+ jobFormFieldsSchema,
+ jobFormValuesSchema,
+ formatJobFormValues,
+ appendJobFormValues,
+} from './jobFormFields.js';
+
+const textField = { key: 'topic', label: 'Topic', type: 'text' };
+
+describe('jobFormFieldsSchema', () => {
+ it('accepts one field of every declared type', () => {
+ const fields = JOB_FORM_FIELD_TYPES.map((type, i) => ({
+ key: `f${i}`,
+ label: `Field ${i}`,
+ type,
+ ...(type === 'select' ? { options: [{ value: 'a' }, { value: 'b', label: 'Bee' }] } : {}),
+ }));
+ expect(jobFormFieldsSchema.safeParse(fields).success).toBe(true);
+ });
+
+ it('rejects duplicate field keys', () => {
+ const result = jobFormFieldsSchema.safeParse([textField, { ...textField, label: 'Other' }]);
+ expect(result.success).toBe(false);
+ });
+
+ it('rejects a key that is not a safe identifier', () => {
+ expect(jobFormFieldsSchema.safeParse([{ ...textField, key: 'a topic' }]).success).toBe(false);
+ expect(jobFormFieldsSchema.safeParse([{ ...textField, key: '1topic' }]).success).toBe(false);
+ });
+
+ it('requires options on a choice field and forbids them elsewhere', () => {
+ expect(jobFormFieldsSchema.safeParse([{ key: 'k', label: 'K', type: 'select' }]).success).toBe(false);
+ expect(jobFormFieldsSchema.safeParse([{ key: 'k', label: 'K', type: 'select', options: [] }]).success).toBe(false);
+ expect(jobFormFieldsSchema.safeParse([{ ...textField, options: [{ value: 'a' }] }]).success).toBe(false);
+ });
+
+ it('rejects duplicate option values', () => {
+ const result = jobFormFieldsSchema.safeParse([
+ { key: 'k', label: 'K', type: 'select', options: [{ value: 'a' }, { value: 'a', label: 'Again' }] },
+ ]);
+ expect(result.success).toBe(false);
+ });
+
+ it('accepts the value shapes the inputs actually produce', () => {
+ // A number input hands back a string, a checkbox a boolean, a cleared field ''.
+ expect(jobFormValuesSchema.safeParse({ a: 'text', b: 3, c: '7', d: true, e: '', f: null }).success).toBe(true);
+ });
+});
+
+describe('formatJobFormValues', () => {
+ it('returns nothing when no field is declared or none is filled in', () => {
+ expect(formatJobFormValues([], { topic: 'x' })).toBe('');
+ expect(formatJobFormValues([textField], {})).toBe('');
+ expect(formatJobFormValues([textField], { topic: ' ' })).toBe('');
+ });
+
+ it('omits a blank field instead of sending it as an empty parameter', () => {
+ const fields = [textField, { key: 'notes', label: 'Notes', type: 'textarea' }];
+ const section = formatJobFormValues(fields, { topic: 'tides', notes: '' });
+ expect(section).toContain('- Topic: tides');
+ expect(section).not.toContain('Notes');
+ });
+
+ it('keeps a false checkbox, because no is an answer', () => {
+ const fields = [{ key: 'art', label: 'Include art', type: 'checkbox' }];
+ expect(formatJobFormValues(fields, { art: false })).toContain('- Include art: No');
+ expect(formatJobFormValues(fields, { art: true })).toContain('- Include art: Yes');
+ });
+
+ it('renders a choice by its label, falling back to the stored value', () => {
+ const fields = [{ key: 'size', label: 'Size', type: 'select', options: [{ value: 'sq', label: 'Square' }, { value: 'tall' }] }];
+ expect(formatJobFormValues(fields, { size: 'sq' })).toContain('- Size: Square');
+ expect(formatJobFormValues(fields, { size: 'tall' })).toContain('- Size: tall');
+ });
+
+ it('gives a multi-line value its own heading rather than folding it into a bullet', () => {
+ const fields = [textField, { key: 'brief', label: 'Brief', type: 'textarea' }];
+ const section = formatJobFormValues(fields, { topic: 'tides', brief: 'line one\nline two' });
+ expect(section).toContain('- Topic: tides');
+ expect(section).toContain('### Brief\n\nline one\nline two');
+ });
+
+ it('follows the declared field order, not the key order of the values', () => {
+ const fields = [{ key: 'b', label: 'Second', type: 'text' }, { key: 'a', label: 'First', type: 'text' }];
+ const section = formatJobFormValues(fields, { a: '1', b: '2' });
+ expect(section.indexOf('Second')).toBeLessThan(section.indexOf('First'));
+ });
+
+ it('ignores a value whose field was deleted', () => {
+ expect(formatJobFormValues([textField], { topic: 'tides', removed: 'stale' })).not.toContain('stale');
+ });
+});
+
+describe('appendJobFormValues', () => {
+ it('leaves a prompt byte-identical when the job uses no configuration form', () => {
+ expect(appendJobFormValues({}, 'do the thing')).toBe('do the thing');
+ expect(appendJobFormValues({ formFields: [], formValues: {} }, 'do the thing')).toBe('do the thing');
+ expect(appendJobFormValues({ formFields: [textField], formValues: {} }, 'do the thing')).toBe('do the thing');
+ });
+
+ it('does not stringify a missing prompt template', () => {
+ const job = { formFields: [textField], formValues: { topic: 'tides' } };
+ expect(appendJobFormValues(job, undefined)).not.toContain('undefined');
+ expect(appendJobFormValues(job, undefined)).toContain('- Topic: tides');
+ });
+
+ it('appends the run configuration below the prompt', () => {
+ const job = { formFields: [textField], formValues: { topic: 'tides' } };
+ const prompt = appendJobFormValues(job, 'do the thing');
+ expect(prompt.startsWith('do the thing')).toBe(true);
+ expect(prompt).toContain('## Run configuration');
+ expect(prompt).toContain('- Topic: tides');
+ });
+});
diff --git a/server/lib/quotaBurnLegacyConversion.js b/server/lib/quotaBurnLegacyConversion.js
index 22e89ae355..b7ab23c1be 100644
--- a/server/lib/quotaBurnLegacyConversion.js
+++ b/server/lib/quotaBurnLegacyConversion.js
@@ -155,6 +155,12 @@ export function buildQuotaBurnCustomJob({ id, familyId, stepId, label, appId, pr
autonomyLevel: UNATTENDED_AUTONOMY_LEVEL,
promptTemplate: prompt,
dataInputs: [],
+ // A converted step carries no configuration form — its prompt is already
+ // fully specified. Stamped anyway so the record this builder writes straight
+ // into the jobs file stays identical to the one `createJob` produces for an
+ // install that PUT the same legacy body (asserted in quotaBurnConversion.test.js).
+ formFields: [],
+ formValues: {},
providerId: null,
model: null,
effort: null,
diff --git a/server/routes/cosJobRoutes.js b/server/routes/cosJobRoutes.js
index 141d6c32d5..64e250315a 100644
--- a/server/routes/cosJobRoutes.js
+++ b/server/routes/cosJobRoutes.js
@@ -111,7 +111,7 @@ router.get('/jobs/:id', asyncHandler(async (req, res) => {
router.post('/jobs', asyncHandler(async (req, res) => {
const parsedJob = createCosJobSchema.safeParse(req.body);
if (!parsedJob.success) failValidation(parsedJob);
- const { name, description, category, type, interval, intervalMs, scheduledTime, cronExpression, cronSchedule, enabled, priority, autonomyLevel, promptTemplate, dataInputs, command, triggerAction, appId, taskMetadata, providerId, model, effort } = parsedJob.data;
+ const { name, description, category, type, interval, intervalMs, scheduledTime, cronExpression, cronSchedule, enabled, priority, autonomyLevel, promptTemplate, dataInputs, formFields, formValues, command, triggerAction, appId, taskMetadata, providerId, model, effort } = parsedJob.data;
if (type === 'shell' && !command?.trim()) {
throw new ServerError('command is required for shell jobs', { status: 400, code: 'VALIDATION_ERROR' });
@@ -126,9 +126,12 @@ router.post('/jobs', asyncHandler(async (req, res) => {
}
if (cronSchedule) validateRecurrenceRule(cronSchedule);
+ // This hand-off is an ALLOWLIST, not a spread: a field added to the schema and
+ // missed here is silently dropped — the request still succeeds and the job is
+ // still created, just without it. Keep both lists in step.
const job = await autonomousJobs.createJob({
name, description, category, type, interval, intervalMs, scheduledTime, cronExpression, cronSchedule,
- enabled, priority, autonomyLevel, promptTemplate, dataInputs, command, triggerAction, appId, taskMetadata, providerId, model, effort
+ enabled, priority, autonomyLevel, promptTemplate, dataInputs, formFields, formValues, command, triggerAction, appId, taskMetadata, providerId, model, effort
});
res.json({ success: true, job });
}));
@@ -138,14 +141,17 @@ router.put('/jobs/:id', asyncHandler(async (req, res) => {
const parsedJobUpdate = updateCosJobSchema.safeParse(req.body);
if (!parsedJobUpdate.success) failValidation(parsedJobUpdate);
const { name, description, category, type, interval, intervalMs, scheduledTime, cronExpression, cronSchedule,
- enabled, priority, autonomyLevel, promptTemplate, dataInputs, command, triggerAction, weekdaysOnly, appId, taskMetadata, providerId, model, effort } = parsedJobUpdate.data;
+ enabled, priority, autonomyLevel, promptTemplate, dataInputs, formFields, formValues, command, triggerAction, weekdaysOnly, appId, taskMetadata, providerId, model, effort } = parsedJobUpdate.data;
if (cronExpression) {
validateCronExpression(cronExpression);
}
if (cronSchedule) validateRecurrenceRule(cronSchedule);
+ // Same allowlist hazard as the create path above — `updateJob` skips only
+ // `undefined`, so a key missing HERE reads as "preserve", and an edit that
+ // clears a field looks like it saved while the old value stays on disk.
const job = await autonomousJobs.updateJob(req.params.id, {
name, description, category, type, interval, intervalMs, scheduledTime, cronExpression, cronSchedule,
- enabled, priority, autonomyLevel, promptTemplate, dataInputs, command, triggerAction, weekdaysOnly, appId, taskMetadata, providerId, model, effort
+ enabled, priority, autonomyLevel, promptTemplate, dataInputs, formFields, formValues, command, triggerAction, weekdaysOnly, appId, taskMetadata, providerId, model, effort
});
if (!job) {
throw new ServerError('Job not found', { status: 404, code: 'NOT_FOUND' });
diff --git a/server/routes/cosJobRoutes.test.js b/server/routes/cosJobRoutes.test.js
index bea07bf693..2409dc16cd 100644
--- a/server/routes/cosJobRoutes.test.js
+++ b/server/routes/cosJobRoutes.test.js
@@ -327,6 +327,36 @@ describe('CoS Job Routes', () => {
);
});
+ it('forwards the configuration form to createJob', async () => {
+ // The handler destructures an allowlist rather than spreading the parsed
+ // body, so a schema field it does not name is dropped with a 200 and a
+ // created job that silently lost it — which is how this one first shipped.
+ autonomousJobs.createJob.mockResolvedValue({ id: 'j1' });
+ const formFields = [
+ { key: 'topic', label: 'Topic', type: 'textarea' },
+ { key: 'size', label: 'Size', type: 'select', options: [{ value: 'sq', label: 'Square' }] },
+ ];
+
+ const response = await request(app)
+ .post('/api/cos/jobs')
+ .send({ name: 'Parameterized', type: 'agent', promptTemplate: 'test', formFields, formValues: { topic: 'tides', size: 'sq' } });
+
+ expect(response.status).toBe(200);
+ expect(autonomousJobs.createJob).toHaveBeenCalledWith(
+ expect.objectContaining({ formFields, formValues: { topic: 'tides', size: 'sq' } })
+ );
+ });
+
+ it('rejects a malformed configuration form', async () => {
+ const bad = [{ key: 'size', label: 'Size', type: 'select' }]; // a choice field with no choices
+ const response = await request(app)
+ .post('/api/cos/jobs')
+ .send({ name: 'Parameterized', type: 'agent', promptTemplate: 'test', formFields: bad });
+
+ expect(response.status).toBe(400);
+ expect(autonomousJobs.createJob).not.toHaveBeenCalled();
+ });
+
it('should reject unknown data input ids', async () => {
const response = await request(app)
.post('/api/cos/jobs')
@@ -368,6 +398,22 @@ describe('CoS Job Routes', () => {
expect(response.status).toBe(404);
});
+ it('re-aims a job by sending values alone, without restating the field design', async () => {
+ // `updateJob` skips only `undefined`, so the stored definitions survive an
+ // update that names just the values — which is what editing one knob sends.
+ autonomousJobs.updateJob.mockResolvedValue({ id: 'j1' });
+
+ const response = await request(app)
+ .put('/api/cos/jobs/j1')
+ .send({ formValues: { topic: 'a different subject' } });
+
+ expect(response.status).toBe(200);
+ expect(autonomousJobs.updateJob).toHaveBeenCalledWith('j1', expect.objectContaining({
+ formValues: { topic: 'a different subject' },
+ formFields: undefined,
+ }));
+ });
+
it('un-scopes a job to global when the client sends empty appId', async () => {
autonomousJobs.updateJob.mockResolvedValue({ id: 'j1', appId: null });
diff --git a/server/services/autonomousJobs.test.js b/server/services/autonomousJobs.test.js
index d2f8fe11c9..0f47b36c50 100644
--- a/server/services/autonomousJobs.test.js
+++ b/server/services/autonomousJobs.test.js
@@ -267,6 +267,29 @@ describe('autonomousJobs', () => {
const task = await generateTaskFromJob(mockJobsData.jobs[0])
expect(task.metadata.effort).toBeUndefined()
})
+
+ it('appends the configuration form values to the dispatched prompt', async () => {
+ const task = await generateTaskFromJob({
+ ...mockJobsData.jobs[0],
+ formFields: [
+ { key: 'subject', label: 'Subject', type: 'text' },
+ { key: 'skipped', label: 'Skipped', type: 'text' },
+ ],
+ formValues: { subject: 'tides', skipped: '' },
+ })
+ expect(task.metadata.prompt).toContain('Do the test thing')
+ expect(task.metadata.prompt).toContain('## Run configuration')
+ expect(task.metadata.prompt).toContain('- Subject: tides')
+ // A blank field must not reach the agent as an empty parameter.
+ expect(task.metadata.prompt).not.toContain('Skipped')
+ // The row summary is still the prompt's first line, not the appended block.
+ expect(task.description).toBe('Do the test thing')
+ })
+
+ it('leaves the prompt untouched when the job declares no configuration form', async () => {
+ const task = await generateTaskFromJob(mockJobsData.jobs[0])
+ expect(task.metadata.prompt).toBe('Do the test thing')
+ })
})
describe('createJob with resolveIntervalMs', () => {
diff --git a/server/services/autonomousJobs/crud.js b/server/services/autonomousJobs/crud.js
index 6ca8846ad5..15b1cf94b9 100644
--- a/server/services/autonomousJobs/crud.js
+++ b/server/services/autonomousJobs/crud.js
@@ -108,6 +108,11 @@ async function createJob(jobData) {
// Selected deterministic context sources resolved immediately before the
// agent task is generated. Empty is a real configured selection.
dataInputs: Array.isArray(jobData.dataInputs) ? jobData.dataInputs : [],
+ // The job's own configuration form — the declared inputs and what they are
+ // currently set to. `getJobEffectivePrompt` projects the pair into the run
+ // configuration section of the prompt. Empty is a real configured state.
+ formFields: Array.isArray(jobData.formFields) ? jobData.formFields : [],
+ formValues: jobData.formValues && typeof jobData.formValues === 'object' ? jobData.formValues : {},
// Optional per-job AI provider + model override. Null = use the active
// provider / its default model (historical behavior). generateTaskFromJob
// forwards these into the task metadata the agent runner resolves.
@@ -161,7 +166,10 @@ async function updateJob(jobId, updates) {
const updatableFields = [
'name', 'description', 'category', 'type', 'interval', 'intervalMs',
'scheduledTime', 'cronExpression', 'cronSchedule', 'weekdaysOnly', 'enabled', 'priority', 'autonomyLevel', 'promptTemplate', 'dataInputs',
- 'command', 'triggerAction', 'config', 'appId', 'taskMetadata', 'providerId', 'model', 'effort'
+ 'command', 'triggerAction', 'config', 'appId', 'taskMetadata', 'providerId', 'model', 'effort',
+ // Separately updatable on purpose: re-aiming a job sends `formValues`
+ // alone, which must not have to restate the whole field design to do it.
+ 'formFields', 'formValues'
]
for (const field of updatableFields) {
diff --git a/server/services/autonomousJobs/skillTemplates.js b/server/services/autonomousJobs/skillTemplates.js
index 3c613edb4e..4e4a38b37f 100644
--- a/server/services/autonomousJobs/skillTemplates.js
+++ b/server/services/autonomousJobs/skillTemplates.js
@@ -2,8 +2,9 @@
* Autonomous Jobs — skill templates and effective-prompt assembly.
*
* Reads/writes the per-job skill template markdown files, assembles a job's
- * effective prompt (skill template + briefing-config enrichments), and turns a
- * due job into a CoS task payload (`generateTaskFromJob`).
+ * effective prompt (skill template + per-job enrichments, including the values
+ * set in the job's own configuration form), and turns a due job into a CoS task
+ * payload (`generateTaskFromJob`).
*/
import { join } from 'path'
@@ -11,6 +12,7 @@ import { ensureDir, PATHS, tryReadFile, writeFileGuarded } from '../../lib/fileU
import { JOBS_SKILLS_DIR, JOB_SKILL_MAP } from './constants.js'
import { getAppById } from '../apps.js'
import { appendTaskDataInputs, resolveTaskDataInputs } from '../taskDataInputs.js'
+import { appendJobFormValues } from '../../lib/jobFormFields.js'
import { FILE_ISSUES_DELIVERY_SETTINGS, isExplicitFileIssuesRequest } from '../../lib/auditCatalog.js'
/**
@@ -89,6 +91,15 @@ function appendBriefingConfig(job, prompt) {
return extras ? prompt + '\n\n' + extras : prompt
}
+/**
+ * Apply every per-job enrichment that turns a stored template into the prompt a
+ * run actually receives. The job's own configuration form goes LAST so its
+ * values read as the final word on this run, after any generic enrichment.
+ */
+function enrichJobPrompt(job, prompt) {
+ return appendJobFormValues(job, appendBriefingConfig(job, prompt))
+}
+
/**
* Get the effective prompt for a job, using skill template if available
* Extracts the prompt from the skill template's structured format
@@ -97,10 +108,10 @@ function appendBriefingConfig(job, prompt) {
*/
async function getJobEffectivePrompt(job) {
const skillName = JOB_SKILL_MAP[job.id]
- if (!skillName) return appendBriefingConfig(job, job.promptTemplate)
+ if (!skillName) return enrichJobPrompt(job, job.promptTemplate)
const template = await loadJobSkillTemplate(skillName)
- if (!template) return appendBriefingConfig(job, job.promptTemplate)
+ if (!template) return enrichJobPrompt(job, job.promptTemplate)
// Extract structured sections from the skill template and build a prompt
// The skill template has: Prompt Template header, Steps, Expected Outputs, Success Criteria
@@ -135,7 +146,7 @@ async function getJobEffectivePrompt(job) {
prompt += '\n\nSuccess criteria:\n' + sections.successCriteria.trim()
}
- return prompt
+ return appendJobFormValues(job, prompt)
}
/**
@@ -217,6 +228,7 @@ export {
listJobSkillTemplates,
buildBriefingConfigInstructions,
appendBriefingConfig,
+ enrichJobPrompt,
getJobEffectivePrompt,
generateTaskFromJob
}