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

add per-stage timeout overrides + duration hints on every timeout input (#424)

[._.]/ Adam Eivy6f5638972ef5
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index ec3d5b0386..3fee9e739f 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -8,6 +8,7 @@
## Changed
+- **[per-stage-timeout-overrides] Each prompt stage can now carry its own timeout, and provider/stage timeout inputs show a human duration.** `stage.timeout` (ms) overrides the provider default whenever a stage is run via `runStagedLLM`; callers can also pass `timeoutOverride` to beat both. The Prompts manager (stage editor) and the Writers Room's inline stage picker both gain a "Timeout override (ms)" field with the active provider's value as the placeholder, and the AI Providers timeout input now displays a `≈ 15m 0s per run` hint below the box. `min/max/step` are wired (1000 / 1,800,000 / 1000) on every timeout input so the OS-level spinner is sensible. Server-side: `PUT /api/prompts/:stage` validates the timeout field via Zod (rejects garbage like `"abc"`, coerces numeric strings, caps at 30 min); the runner also coerces a legacy stringified `stage.timeout` so older installs still work; non-positive values are ignored so a stray `0` can't silently cancel runs.
- **Writers Room analysis runs now show live elapsed-time feedback, and the Claude Code CLI provider timeout cap is raised to 30 minutes (default 15).** Long Opus-on-prose runs (e.g. `writers-room-script` with a 35k-char prompt) were dying at the old 5-minute provider cap; the in-tree provider for Claude Code now defaults to 900s and the validation cap on every provider's `timeout` field is raised to 1800s. The Writers Room work editor also gains a persistent status banner under the header while an analysis is running — analysis label, mm:ss elapsed, and reassurance text that escalates from "Working…" to "Still going — Opus on long prose runs 5–10+ minutes" so the UI no longer goes silent during multi-minute waits.
- **`plan-task` scheduler now skips dispatch when PLAN.md has nothing to do, and the `plan-task` prompt waits for code review before merging.** The scheduled `plan-task` agent used to spin up an LLM round even when PLAN.md was empty, only had `<!-- NEEDS_INPUT -->` items, or had `> ⚠️ DRIFT:` flags on every unchecked entry — the agent would just exit cleanly, burning a model call for no work. The scheduler now classifies the plan locally (cheap, no git/gh round-trip) and short-circuits the dispatch entirely in those cases, plus when every otherwise-eligible item is already claimed by another agent in flight. `feature-ideas` is intentionally never gated — its job is to brainstorm into an empty plan. The `plan-task` prompt itself also gained an explicit "wait for the configured reviewer's findings" step in Phase 6 between `gh pr create` and `gh pr merge`; previously `gh pr merge --auto` waited only on required status checks and could merge before Copilot's auto-review even arrived (as happened to PR #418). The reviewer is now configurable per scheduled task — pick Copilot, Claude, Codex, or Gemini from the Schedule tab, same picker as the add-task form. Copilot polls for the auto-review and addresses comments before merging (cap 3 iterations); the local-CLI options hand off to `/do:rpr --review-with <agent>`. The prompt's opening line and Phase 1 header were also rewritten so the dual scheduler-pre-reserved / agent-picks paths read clearly instead of contradicting each other.
- **GOALS.md now reflects the full app.** Added two missing core goals — **Creative Production Suite** (Writers Room, Universe Builder, Series Pipeline, Creative Director, Image/Video Gen, Timeline, LoRAs, Importer, Sharing) and **Cognitive Training & Lifelong Learning** (POST, Morse, Rapid Reader, Wiki). Reframed Purpose and tagline around "everything app," "create more than consume," and "interface with the world and with myself." Updated Status table and Secondary Goals (music/audio production, mood board, sketch canvas, federated sharing, cross-domain insights).
diff --git a/client/src/components/writers-room/StagePromptModelPicker.jsx b/client/src/components/writers-room/StagePromptModelPicker.jsx
index ac2d80a94a..523c0f1e75 100644
--- a/client/src/components/writers-room/StagePromptModelPicker.jsx
+++ b/client/src/components/writers-room/StagePromptModelPicker.jsx
@@ -1,7 +1,15 @@
import { useEffect, useMemo, useState } from 'react';
import toast from '../ui/Toast';
import ProviderModelSelector from '../ProviderModelSelector';
-import { filterSelectableModels } from '../../utils/providers';
+import useFieldDraft from '../../hooks/useFieldDraft';
+import { filterSelectableModels, getProviderTimeout } from '../../utils/providers';
+import {
+ formatDurationMs,
+ parseTimeoutMs,
+ TIMEOUT_INPUT_MIN_MS,
+ TIMEOUT_INPUT_MAX_MS,
+ TIMEOUT_INPUT_STEP_MS,
+} from '../../utils/formatters';
/**
* Inline picker for a prompt stage's provider+model. Mirrors the Tier/Specific
@@ -12,6 +20,7 @@ import { filterSelectableModels } from '../../utils/providers';
export default function StagePromptModelPicker({ stageName, label = 'Stage LLM', icon = null, hint = null }) {
const [stage, setStage] = useState(null);
const [providers, setProviders] = useState([]);
+ const [activeProviderId, setActiveProviderId] = useState(null);
const [saving, setSaving] = useState(false);
const [loaded, setLoaded] = useState(false);
@@ -22,8 +31,16 @@ export default function StagePromptModelPicker({ stageName, label = 'Stage LLM',
fetch('/api/providers').then((r) => (r.ok ? r.json() : null)).catch(() => null),
]).then(([s, p]) => {
if (cancelled) return;
- setStage(s || null);
+ // Normalize stage.timeout through parseTimeoutMs so a legacy on-disk
+ // garbage value (e.g. `'abc'` from a pre-validation install) doesn't
+ // flow into the number input (where it would render blank / log
+ // controlled-component warnings) and doesn't poison the hint logic.
+ // Accepts integers AND digit-only strings within range; everything
+ // else becomes `null` (no override).
+ const normalizedStage = s ? { ...s, timeout: parseTimeoutMs(s.timeout) } : null;
+ setStage(normalizedStage);
setProviders((p?.providers || []).filter((x) => x.enabled));
+ setActiveProviderId(p?.activeProvider || null);
setLoaded(true);
});
return () => { cancelled = true; };
@@ -38,13 +55,17 @@ export default function StagePromptModelPicker({ stageName, label = 'Stage LLM',
const prevStage = stage;
setSaving(true);
setStage((prev) => ({ ...prev, ...next }));
+ // Only include fields the caller actually wants to change. provider/model
+ // are sent together because the picker drives them as one switch;
+ // timeout is independent.
+ const body = {};
+ if ('provider' in next) body.provider = next.provider ?? null;
+ if ('model' in next) body.model = next.model;
+ if ('timeout' in next) body.timeout = next.timeout;
const res = await fetch(`/api/prompts/${encodeURIComponent(stageName)}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- provider: next.provider ?? null,
- model: next.model,
- }),
+ body: JSON.stringify(body),
});
setSaving(false);
if (!res.ok) {
@@ -136,7 +157,67 @@ export default function StagePromptModelPicker({ stageName, label = 'Stage LLM',
/>
)}
+ <StageTimeoutInput
+ value={stage.timeout}
+ providerFallback={getProviderTimeout(providers, stage.provider, activeProviderId)}
+ onCommit={(ms) => persist({ timeout: ms })}
+ />
+
{hint && <div className="text-[10px] text-gray-500">{hint}</div>}
</div>
);
}
+
+// Inline numeric input for stage.timeout (ms). Built on `useFieldDraft` so
+// the parent's optimistic state update doesn't race the user's keystrokes —
+// the hook returns the persisted value until the user actually types.
+function StageTimeoutInput({ value, providerFallback, onCommit }) {
+ const { value: draft, onChange, onBlur: hookBlur } = useFieldDraft(value, (raw) => {
+ const ms = parseTimeoutMs(raw);
+ // parseTimeoutMs returns null both for blank input (intentional clear)
+ // and for any non-positive/garbage value. Honor the clear; refuse the
+ // garbage by leaving `value` unchanged — useFieldDraft will snap the
+ // input back to persisted on the next render.
+ if (raw.trim() !== '' && ms == null) return;
+ if (ms !== value) onCommit(ms);
+ });
+
+ // Hint precedence: explicit override > provider fallback > nothing.
+ // Coerce to a finite number before formatting — a legacy on-disk garbage
+ // value (e.g. `timeout: "abc"` from a pre-validation install) reaches us
+ // as a string, and `formatDurationMs(NaN)` renders "NaNh NaNm".
+ const usingDefault = value == null || value <= 0;
+ const candidate = usingDefault ? providerFallback : value;
+ const effectiveMs = Number(candidate);
+ const haveValidEffective = Number.isFinite(effectiveMs) && effectiveMs > 0;
+ let hint;
+ if (!haveValidEffective) {
+ hint = 'No provider default set';
+ } else if (usingDefault) {
+ hint = `≈ ${formatDurationMs(effectiveMs)} · using provider default`;
+ } else {
+ hint = `≈ ${formatDurationMs(effectiveMs)}`;
+ }
+
+ return (
+ <div className="space-y-0.5">
+ <label className="block text-[9px] uppercase tracking-wider text-gray-500">
+ Timeout override (ms)
+ </label>
+ <input
+ type="number"
+ inputMode="numeric"
+ min={TIMEOUT_INPUT_MIN_MS}
+ max={TIMEOUT_INPUT_MAX_MS}
+ step={TIMEOUT_INPUT_STEP_MS}
+ value={draft}
+ onChange={onChange}
+ onBlur={hookBlur}
+ onKeyDown={(e) => { if (e.key === 'Enter') e.currentTarget.blur(); }}
+ placeholder={providerFallback != null ? String(providerFallback) : ''}
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1 text-[11px] text-gray-200"
+ />
+ <div className="text-[10px] text-gray-500">{hint}</div>
+ </div>
+ );
+}
diff --git a/client/src/pages/AIProviders.jsx b/client/src/pages/AIProviders.jsx
index 0f02527fe0..11d8e002be 100644
--- a/client/src/pages/AIProviders.jsx
+++ b/client/src/pages/AIProviders.jsx
@@ -3,6 +3,13 @@ import toast from '../components/ui/Toast';
import * as api from '../services/api';
import socket from '../services/socket';
import { filterSelectableModels, providerTypeClass, isTuiProvider, isApiProvider, isProcessProvider } from '../utils/providers';
+import {
+ formatDurationMs,
+ parseTimeoutMs,
+ TIMEOUT_INPUT_MIN_MS,
+ TIMEOUT_INPUT_MAX_MS,
+ TIMEOUT_INPUT_STEP_MS,
+} from '../utils/formatters';
export default function AIProviders() {
const [providers, setProviders] = useState([]);
@@ -599,12 +606,29 @@ function ProviderForm({ provider, onClose, onSave, allProviders = [] }) {
const tuiPromptDelay = parseInt(formData.tuiPromptDelayMs, 10);
const tuiIdleTimeout = parseInt(formData.tuiIdleTimeoutMs, 10);
+ // Three cases for the timeout field on submit:
+ // 1. valid integer within bounds → send the parsed number
+ // 2. blank/whitespace → omit so the server keeps the current value
+ // (Number('') is 0, which would 400 against the min-1000 rule)
+ // 3. non-empty but invalid (e.g. '1e3', '500', 'abc') → send the
+ // RAW STRING. Number() would accept '1e3' as 1000, silently
+ // saving an exponent form the client/runner reject as invalid;
+ // the server's digit-only preprocess will leave the string
+ // alone and z.number() will produce a clear validation error.
+ const parsedTimeout = parseTimeoutMs(formData.timeout);
+ const timeoutInput = String(formData.timeout ?? '').trim();
const data = {
...formData,
args: formData.args ? formData.args.split(' ').filter(Boolean) : [],
headlessArgs: formData.headlessArgs ? formData.headlessArgs.split(' ').filter(Boolean) : [],
- timeout: parseInt(formData.timeout, 10)
};
+ if (parsedTimeout != null) {
+ data.timeout = parsedTimeout;
+ } else if (timeoutInput === '') {
+ delete data.timeout;
+ } else {
+ data.timeout = formData.timeout;
+ }
if (formData.type === 'tui') {
if (Number.isFinite(tuiPromptDelay)) data.tuiPromptDelayMs = tuiPromptDelay;
else delete data.tuiPromptDelayMs;
@@ -907,10 +931,26 @@ function ProviderForm({ provider, onClose, onSave, allProviders = [] }) {
<label className="block text-sm text-gray-400 mb-1">Timeout (ms)</label>
<input
type="number"
+ inputMode="numeric"
+ min={TIMEOUT_INPUT_MIN_MS}
+ max={TIMEOUT_INPUT_MAX_MS}
+ step={TIMEOUT_INPUT_STEP_MS}
value={formData.timeout}
onChange={(e) => setFormData(prev => ({ ...prev, timeout: e.target.value }))}
className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"
/>
+ <p className="text-xs text-gray-500 mt-1">
+ {(() => {
+ // Same parser the submit path uses, so the displayed
+ // duration always matches what would be saved. parseTimeoutMs
+ // returns null for out-of-range/invalid → fall back to the
+ // generic cap message.
+ const ms = parseTimeoutMs(formData.timeout);
+ return ms != null
+ ? `≈ ${formatDurationMs(ms)} per run`
+ : `Per-call cap. Server max: ${TIMEOUT_INPUT_MAX_MS.toLocaleString()} ms (${formatDurationMs(TIMEOUT_INPUT_MAX_MS)}).`;
+ })()}
+ </p>
</div>
{/* Fallback Provider */}
diff --git a/client/src/pages/PromptManager.jsx b/client/src/pages/PromptManager.jsx
index 8620a3f7f4..b09c0b08eb 100644
--- a/client/src/pages/PromptManager.jsx
+++ b/client/src/pages/PromptManager.jsx
@@ -3,7 +3,15 @@ import { FileText, Variable, RefreshCw, Save, Plus, Trash2, Eye, Briefcase } fro
import toast from '../components/ui/Toast';
import BrailleSpinner from '../components/BrailleSpinner';
import ProviderModelSelector from '../components/ProviderModelSelector';
-import { filterSelectableModels } from '../utils/providers';
+import { filterSelectableModels, getProviderTimeout } from '../utils/providers';
+import {
+ formatDurationMs,
+ parseTimeoutMs,
+ TIMEOUT_INPUT_MIN_MS,
+ TIMEOUT_INPUT_MAX_MS,
+ TIMEOUT_INPUT_STEP_MS,
+} from '../utils/formatters';
+import useFieldDraft from '../hooks/useFieldDraft';
export default function PromptManager() {
const [tab, setTab] = useState('stages');
@@ -48,6 +56,7 @@ export default function PromptManager() {
const [jobSkillPreview, setJobSkillPreview] = useState('');
const [providers, setProviders] = useState([]);
+ const [activeProviderId, setActiveProviderId] = useState(null);
const [saving, setSaving] = useState(false);
const [deleteConfirm, setDeleteConfirm] = useState(null);
@@ -67,6 +76,7 @@ export default function PromptManager() {
setVariables(varsRes.variables || {});
setJobSkills(jobSkillsRes.skills || []);
setProviders((providersRes.providers || []).filter(p => p.enabled));
+ setActiveProviderId(providersRes.activeProvider || null);
setLoading(false);
};
@@ -74,7 +84,14 @@ export default function PromptManager() {
setSelectedStage(name);
const res = await fetch(`/api/prompts/${name}`).then(r => r.json());
setStageTemplate(res.template || '');
- setStageConfig({ name: res.name, description: res.description, model: res.model, provider: res.provider || null, variables: res.variables || [] });
+ // Normalize a server-returned timeout via parseTimeoutMs so the editor
+ // shares the validator's accept set: integers OR digit-only strings
+ // (e.g. legacy `'900000'` from pre-validation installs) round-trip
+ // through the UI, while non-positive / non-integer / garbage values
+ // (0, 'abc', undefined, 1.5) collapse to null so the input doesn't
+ // surface them as touched.
+ const timeout = parseTimeoutMs(res.timeout);
+ setStageConfig({ name: res.name, description: res.description, model: res.model, provider: res.provider || null, timeout, variables: res.variables || [] });
setPreview('');
};
@@ -412,6 +429,11 @@ export default function PromptManager() {
/>
)}
</div>
+ <StageTimeoutField
+ timeout={stageConfig.timeout}
+ providerFallback={getProviderTimeout(providers, stageConfig.provider, activeProviderId)}
+ onCommit={(ms) => setStageConfig({ ...stageConfig, timeout: ms })}
+ />
<div>
<label className="block text-sm text-gray-400 mb-1">Variables Used</label>
<div className="text-sm text-gray-300">
@@ -853,3 +875,42 @@ export default function PromptManager() {
</div>
);
}
+
+// Buffered timeout input — typing "9" toward "900000" must NOT snap the field
+// to blank just because `parseTimeoutMs("9")` returns null (below the 1s
+// floor). useFieldDraft keeps the raw string locally and only invokes
+// onCommit on blur with the validated value (or null when the user clears
+// it / leaves it invalid).
+function StageTimeoutField({ timeout, providerFallback, onCommit }) {
+ const { value: draft, onChange, onBlur } = useFieldDraft(timeout, (raw) => {
+ const trimmed = raw.trim();
+ if (trimmed === '') { onCommit(null); return; }
+ const ms = parseTimeoutMs(raw);
+ // Non-null parse → commit. Null result on non-empty input means out-of-range
+ // or non-integer; leave persisted state untouched so the input snaps back.
+ if (ms != null) onCommit(ms);
+ });
+ return (
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Timeout override (ms)</label>
+ <input
+ type="number"
+ inputMode="numeric"
+ min={TIMEOUT_INPUT_MIN_MS}
+ max={TIMEOUT_INPUT_MAX_MS}
+ step={TIMEOUT_INPUT_STEP_MS}
+ value={draft}
+ onChange={onChange}
+ onBlur={onBlur}
+ onKeyDown={(e) => { if (e.key === 'Enter') e.currentTarget.blur(); }}
+ placeholder={providerFallback != null ? String(providerFallback) : ''}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"
+ />
+ <p className="text-xs text-gray-500 mt-1">
+ {timeout && timeout > 0
+ ? `≈ ${formatDurationMs(timeout)} per run`
+ : 'Leave blank to use the provider default'}
+ </p>
+ </div>
+ );
+}
diff --git a/client/src/utils/formatters.js b/client/src/utils/formatters.js
index 644030edb3..3d56575fc0 100644
--- a/client/src/utils/formatters.js
+++ b/client/src/utils/formatters.js
@@ -181,6 +181,47 @@ export function formatDateShort(value) {
return date.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' });
}
+// Per-call LLM timeout bounds. Client-side mirror of the canonical
+// MIN_TIMEOUT / MAX_TIMEOUT in server/lib/aiToolkit/constants.js — the
+// client can't import across the server boundary (Vite vs Node, plus the
+// aiToolkit directory is kept self-contained per CLAUDE.md). The server
+// validators (validation.js, stageRunner.js) and aiToolkit's own
+// provider/run schemas all import from constants.js; this file is the
+// only known mirror. Bumping these here without the server constants —
+// or vice versa — would let a value through one validator that the
+// other rejects.
+export const TIMEOUT_INPUT_MIN_MS = 1000;
+export const TIMEOUT_INPUT_MAX_MS = 1800000;
+export const TIMEOUT_INPUT_STEP_MS = 1000;
+
+/**
+ * Parse a raw string from a timeout (ms) input into a stored value.
+ * Returns `null` for blank input (caller treats as "clear override") and
+ * for anything outside the validated [TIMEOUT_INPUT_MIN_MS,
+ * TIMEOUT_INPUT_MAX_MS] integer range — the caller is then responsible for
+ * snapping the input back to the persisted value. Clamping here keeps the
+ * client from emitting PUTs the server's Zod schema would 400 (e.g. a
+ * stray `1` that "looks positive" but is below the 1s floor).
+ *
+ * Accepts only digit-only strings (`^\d+$`), then parses via `Number(...)`
+ * + `Number.isInteger`. The digit-only gate is stricter than `Number(v)`
+ * alone — `Number("1e3")` is 1000 and `Number("1000.5")` is 1000.5 — and
+ * is mirrored in `stageConfigUpdateSchema`'s preprocess in
+ * server/lib/validation.js so client/server reject the same shapes. If
+ * you loosen this rule, loosen the server preprocess in lockstep.
+ */
+export function parseTimeoutMs(raw) {
+ if (raw == null) return null;
+ const trimmed = String(raw).trim();
+ if (trimmed === '') return null;
+ // Require an explicit digit-only string so "1e3" / "1.5" / "0x10" can't
+ // sneak past Number()'s permissive coercion.
+ if (!/^\d+$/.test(trimmed)) return null;
+ const ms = Number(trimmed);
+ if (!Number.isInteger(ms) || ms < TIMEOUT_INPUT_MIN_MS || ms > TIMEOUT_INPUT_MAX_MS) return null;
+ return ms;
+}
+
/**
* Format a duration in milliseconds as a human-readable string
* @param {number} ms - Duration in milliseconds
diff --git a/client/src/utils/providers.js b/client/src/utils/providers.js
index f6fe83082d..80c4d35e55 100644
--- a/client/src/utils/providers.js
+++ b/client/src/utils/providers.js
@@ -59,6 +59,19 @@ export const enabledApiProviderFilter = (provider) => Boolean(provider?.enabled)
*/
export const isProcessProvider = (provider) => isCliProvider(provider) || isTuiProvider(provider);
+/**
+ * Resolve the provider whose timeout is the "fallback" for a stage — the
+ * stage's pinned provider when set, otherwise the active provider. Used to
+ * power the placeholder + hint on stage-timeout UIs in PromptManager and
+ * the Writers Room. Returns the timeout in ms (or `undefined` if neither
+ * provider is present, or its timeout isn't set).
+ */
+export const getProviderTimeout = (providers, stagePinnedId, activeProviderId) => {
+ const id = stagePinnedId || activeProviderId;
+ if (!id) return undefined;
+ return providers.find((p) => p.id === id)?.timeout;
+};
+
/**
* Tailwind chip classes for the provider type badge ('cli' / 'tui' / 'api').
* Lifted out of AIProviders.jsx so other components can render the same
diff --git a/client/src/utils/providers.test.js b/client/src/utils/providers.test.js
index 31bd137286..ea90397694 100644
--- a/client/src/utils/providers.test.js
+++ b/client/src/utils/providers.test.js
@@ -9,6 +9,7 @@ import {
isProcessProvider,
enabledApiProviderFilter,
providerTypeClass,
+ getProviderTimeout,
} from './providers.js';
import { PROVIDER_TYPES as SERVER_PROVIDER_TYPES } from '../../../server/lib/aiToolkit/constants.js';
@@ -115,3 +116,33 @@ describe('providerTypeClass', () => {
expect(providerTypeClass('mystery')).toBe('bg-purple-500/20 text-purple-400');
});
});
+
+describe('getProviderTimeout', () => {
+ const providers = [
+ { id: 'p1', timeout: 300000 },
+ { id: 'p2', timeout: 900000 },
+ { id: 'p3' /* no timeout */ },
+ ];
+
+ it('returns the stage-pinned provider timeout when it wins over active', () => {
+ expect(getProviderTimeout(providers, 'p2', 'p1')).toBe(900000);
+ });
+
+ it('falls back to the active provider timeout when no stage pin', () => {
+ expect(getProviderTimeout(providers, null, 'p1')).toBe(300000);
+ expect(getProviderTimeout(providers, undefined, 'p1')).toBe(300000);
+ expect(getProviderTimeout(providers, '', 'p1')).toBe(300000);
+ });
+
+ it('returns undefined when neither pinned nor active id is given', () => {
+ expect(getProviderTimeout(providers, null, null)).toBeUndefined();
+ });
+
+ it('returns undefined when the matched provider has no timeout', () => {
+ expect(getProviderTimeout(providers, 'p3', null)).toBeUndefined();
+ });
+
+ it('returns undefined when the id matches no provider in the list', () => {
+ expect(getProviderTimeout(providers, 'ghost', 'also-ghost')).toBeUndefined();
+ });
+});
diff --git a/server/lib/promptRunner.js b/server/lib/promptRunner.js
index f263965ce4..b561813fe1 100644
--- a/server/lib/promptRunner.js
+++ b/server/lib/promptRunner.js
@@ -32,7 +32,7 @@ import { executeTuiRun } from './tuiPromptRunner.js';
import { ServerError } from './errorHandler.js';
import { PROVIDER_TYPES } from './aiToolkit/constants.js';
-const DEFAULT_TIMEOUT_MS = 300000;
+export const DEFAULT_TIMEOUT_MS = 300000;
const APPEND_CHUNK = (acc, chunk) => acc + (typeof chunk === 'string' ? chunk : (chunk?.text || ''));
/**
diff --git a/server/lib/stageRunner.js b/server/lib/stageRunner.js
index 593b17bd64..8ff83fa659 100644
--- a/server/lib/stageRunner.js
+++ b/server/lib/stageRunner.js
@@ -16,12 +16,13 @@
import { ServerError } from './errorHandler.js';
import { findBalancedBlocks, tryParseWithRepair } from './jsonExtract.js';
-import { resolveEffectiveModel, runPromptThroughProvider } from './promptRunner.js';
+import { resolveEffectiveModel, runPromptThroughProvider, DEFAULT_TIMEOUT_MS } from './promptRunner.js';
import { stripCodeFences } from './aiProvider.js';
import { extractCodexAssistant } from './codexAssistantExtract.js';
import { getActiveProvider, getProviderById } from '../services/providers.js';
import { buildPrompt, getStage } from '../services/promptService.js';
-import { createRun } from '../services/runner.js';
+import { createRun, patchRunMetadata } from '../services/runner.js';
+import { MIN_TIMEOUT as STAGE_TIMEOUT_MIN_MS, MAX_TIMEOUT as STAGE_TIMEOUT_MAX_MS } from './aiToolkit/constants.js';
// Stage configs name a model by tier (PromptManager UI). Map each tier name
// to the provider's per-tier model field; an unset tier falls through to
@@ -45,6 +46,36 @@ const providerFallbackModel = (provider) =>
|| (Array.isArray(provider.models) && provider.models[0])
|| null;
+// Per-call timeout bounds come from the canonical aiToolkit/constants.js
+// (imported at the top of the file). The runner, the route validator, and
+// the toolkit's own provider/run validation all reject the same shapes.
+// Internal callers (extractors, pipeline stages) hit the runner directly,
+// so it must enforce the same bounds as the HTTP boundary or a caller
+// could slip through a value the schema would reject.
+
+// Normalize a stage- or caller-supplied timeout into a positive integer
+// milliseconds value (or `undefined` to mean "fall through to provider
+// default"). Reject NaN, non-integer, exponent/hex string forms, and
+// anything outside [STAGE_TIMEOUT_MIN_MS, STAGE_TIMEOUT_MAX_MS] — matches
+// parseTimeoutMs on the client and the route validator's preprocess. The
+// digit-only string gate is critical: `Number('1e3')` is 1000 and
+// `Number.isInteger(1000)` is true, so without the gate an internal caller
+// passing `'1e3'` would be silently accepted here while the validator
+// rejects the same shape.
+function normalizeTimeout(raw) {
+ if (raw == null) return undefined;
+ let n;
+ if (typeof raw === 'number') {
+ n = raw;
+ } else if (typeof raw === 'string' && /^\d+$/.test(raw.trim())) {
+ n = Number(raw.trim());
+ } else {
+ return undefined;
+ }
+ if (!Number.isInteger(n) || n < STAGE_TIMEOUT_MIN_MS || n > STAGE_TIMEOUT_MAX_MS) return undefined;
+ return n;
+}
+
export function resolveModel(provider, modelHint) {
if (!modelHint) return providerFallbackModel(provider);
if (isTierName(modelHint)) {
@@ -175,6 +206,7 @@ export function extractJson(text, { promptToStrip } = {}) {
* Options:
* - providerOverride: explicit provider id, beats stage.provider
* - modelOverride: explicit model id, beats stage.model
+ * - timeoutOverride: explicit ms timeout, beats stage.timeout and the provider default
* - returnsJson: parse `content` via `extractJson` before returning
* - source: free-form tag persisted on the run record (e.g. 'pipeline-text-stage',
* 'writers-room-evaluate') so /runs is filterable
@@ -189,20 +221,67 @@ export async function runStagedLLM(stageName, variables, options = {}) {
// args-pinned model id so the run record + log line reflect what
// truly executes (rather than guessing from defaultModel, which can
// diverge from the args-baked value).
- const effectiveModel = resolveEffectiveModel(provider, resolvedModel);
+ let effectiveProvider = provider;
+ let effectiveModel = resolveEffectiveModel(effectiveProvider, resolvedModel);
- const { runId } = await createRun({
+ // Per-stage timeout override; timeoutOverride from the caller beats
+ // stage.timeout, which beats the provider default. `normalizeTimeout`
+ // coerces via `Number(...)` (so legacy stringified values from
+ // pre-validation installs still resolve), rejects non-finite or ≤0
+ // (so a stray "0" can't silently instant-cancel), and caps at
+ // STAGE_TIMEOUT_MAX_MS — applied to BOTH stage.timeout and the caller
+ // override, since `runPromptThroughProvider`/`executeCliRun` treat `0`
+ // as "no timeout" and would happily run unbounded if we forwarded a
+ // garbage override.
+ const stageTimeout = normalizeTimeout(stage?.timeout);
+ const overrideTimeout = normalizeTimeout(options.timeoutOverride);
+ const effectiveTimeout = overrideTimeout ?? stageTimeout;
+
+ // createRun may pick a fallback provider when the requested one is marked
+ // unavailable by providerStatusService. Capture the full result and
+ // reconcile, mirroring the promptRunner.js#createRun caller-runId path —
+ // otherwise execution would proceed against the original provider while
+ // /runs metadata claims the fallback ran. Pass `timeout` with a fallback
+ // to `provider.timeout` so the run record's persisted timeout reflects
+ // what executeXxxRun actually enforces (the runner falls back to
+ // `effectiveProvider.timeout` when no override is set — mirror that here
+ // so the recorded value isn't a misleading `undefined`).
+ const runResult = await createRun({
providerId: provider.id,
model: effectiveModel,
prompt,
source: options.source || 'staged-llm',
+ // createRun.timeout is returned but not persisted into metadata.json
+ // by the toolkit (only providerId/model/source/etc. are written at
+ // creation time). We always patch below to record the effective
+ // timeout so /runs can show what executeXxxRun actually enforced.
+ timeout: effectiveTimeout ?? provider.timeout ?? DEFAULT_TIMEOUT_MS,
});
- console.log(`📝 stage: ${provider.id} / ${effectiveModel || '(default)'} / ${stageName} → ${runId.slice(0, 8)}`);
+ const { runId } = runResult;
+ const fellBack = runResult.provider && runResult.provider.id !== provider.id;
+ if (fellBack) {
+ effectiveProvider = runResult.provider;
+ effectiveModel = resolveEffectiveModel(effectiveProvider, resolvedModel);
+ }
+ // Always patch metadata with the effective timeout (the toolkit doesn't
+ // persist `timeout` in its initial metadata.json write). On fallback we
+ // also patch provider id/name/model so /runs attribution matches the
+ // provider that actually ran. Best-effort: attribution, not load-bearing.
+ const recordedTimeout = effectiveTimeout ?? effectiveProvider.timeout ?? DEFAULT_TIMEOUT_MS;
+ const metadataPatch = { timeout: recordedTimeout };
+ if (fellBack) {
+ metadataPatch.model = effectiveModel;
+ metadataPatch.providerId = effectiveProvider.id;
+ metadataPatch.providerName = effectiveProvider.name;
+ }
+ patchRunMetadata(runId, metadataPatch).catch(() => { /* best-effort */ });
+ console.log(`📝 stage: ${effectiveProvider.id} / ${effectiveModel || '(default)'} / ${stageName} → ${runId.slice(0, 8)}`);
// Stage runs pre-create the run record (so the runId can be logged BEFORE
// the LLM call starts), then thread that id through the shared runner.
const { text } = await runPromptThroughProvider({
- provider, model: effectiveModel, prompt, source: options.source || 'staged-llm', runId,
+ provider: effectiveProvider, model: effectiveModel, prompt, source: options.source || 'staged-llm', runId,
+ timeout: effectiveTimeout,
});
// Codex CLI dumps the full transcript (banner + metadata + echoed prompt +
// `codex\n<reply>` + token-stats footer). Carve out the assistant reply
@@ -210,5 +289,5 @@ export async function runStagedLLM(stageName, variables, options = {}) {
// providers — returns input unchanged when the banner isn't present.
const cleaned = extractCodexAssistant(text);
const content = options.returnsJson ? extractJson(cleaned, { promptToStrip: prompt }) : cleaned;
- return { content, model: effectiveModel || null, providerId: provider.id, runId };
+ return { content, model: effectiveModel || null, providerId: effectiveProvider.id, runId };
}
diff --git a/server/lib/stageRunner.test.js b/server/lib/stageRunner.test.js
index d98a357548..e08e165bb9 100644
--- a/server/lib/stageRunner.test.js
+++ b/server/lib/stageRunner.test.js
@@ -15,6 +15,7 @@ vi.mock('../services/runner.js', () => ({
executeApiRun: vi.fn(),
executeCliRun: vi.fn(),
hasModelFlag: vi.fn(() => false),
+ patchRunMetadata: vi.fn(async () => undefined),
}));
const providers = await import('../services/providers.js');
@@ -244,4 +245,164 @@ describe('stageRunner — runStagedLLM dispatch', () => {
await runStagedLLM('s', {}, { source: 'pipeline-text-stage' });
expect(runner.createRun).toHaveBeenCalledWith(expect.objectContaining({ source: 'pipeline-text-stage' }));
});
+
+ it('passes stage.timeout to executeCliRun when set', async () => {
+ prompts.getStage.mockReturnValue({ timeout: 900000 });
+ providers.getActiveProvider.mockResolvedValue(cliProvider({ timeout: 5000 }));
+ runner.executeCliRun.mockImplementation(async (_id, _p, _pr, _cwd, _onData, onComplete, _t) => {
+ onComplete({ success: true });
+ });
+ await runStagedLLM('s', {});
+ // executeCliRun(runId, provider, prompt, cwd, onData, onComplete, timeout)
+ expect(runner.executeCliRun.mock.calls[0][6]).toBe(900000);
+ });
+
+ it('falls back to provider.timeout when stage.timeout is missing', async () => {
+ prompts.getStage.mockReturnValue(null);
+ providers.getActiveProvider.mockResolvedValue(cliProvider({ timeout: 5000 }));
+ runner.executeCliRun.mockImplementation(async (_id, _p, _pr, _cwd, _onData, onComplete, _t) => {
+ onComplete({ success: true });
+ });
+ await runStagedLLM('s', {});
+ expect(runner.executeCliRun.mock.calls[0][6]).toBe(5000);
+ });
+
+ it('coerces a legacy digit-only stringified stage.timeout to a number', async () => {
+ prompts.getStage.mockReturnValue({ timeout: '900000' });
+ providers.getActiveProvider.mockResolvedValue(cliProvider({ timeout: 5000 }));
+ runner.executeCliRun.mockImplementation(async (_id, _p, _pr, _cwd, _onData, onComplete, _t) => {
+ onComplete({ success: true });
+ });
+ await runStagedLLM('s', {});
+ expect(runner.executeCliRun.mock.calls[0][6]).toBe(900000);
+ });
+
+ it('rejects exponent/hex/float string forms (matches parseTimeoutMs)', async () => {
+ // Number('1e3') === 1000 would silently sneak past a bare Number()
+ // coercion. The digit-only gate keeps the runner in lockstep with
+ // the route validator and client parser.
+ prompts.getStage.mockReturnValue({ timeout: '1e3' });
+ providers.getActiveProvider.mockResolvedValue(cliProvider({ timeout: 5000 }));
+ runner.executeCliRun.mockImplementation(async (_id, _p, _pr, _cwd, _onData, onComplete, _t) => {
+ onComplete({ success: true });
+ });
+ await runStagedLLM('s', {});
+ expect(runner.executeCliRun.mock.calls[0][6]).toBe(5000);
+ });
+
+ it('rejects zero/negative stage.timeout instead of cancelling instantly', async () => {
+ prompts.getStage.mockReturnValue({ timeout: 0 });
+ providers.getActiveProvider.mockResolvedValue(cliProvider({ timeout: 5000 }));
+ runner.executeCliRun.mockImplementation(async (_id, _p, _pr, _cwd, _onData, onComplete, _t) => {
+ onComplete({ success: true });
+ });
+ await runStagedLLM('s', {});
+ expect(runner.executeCliRun.mock.calls[0][6]).toBe(5000);
+ });
+
+ it('honors timeoutOverride beating both stage.timeout and provider.timeout', async () => {
+ prompts.getStage.mockReturnValue({ timeout: 900000 });
+ providers.getActiveProvider.mockResolvedValue(cliProvider({ timeout: 5000 }));
+ runner.executeCliRun.mockImplementation(async (_id, _p, _pr, _cwd, _onData, onComplete, _t) => {
+ onComplete({ success: true });
+ });
+ await runStagedLLM('s', {}, { timeoutOverride: 1234 });
+ expect(runner.executeCliRun.mock.calls[0][6]).toBe(1234);
+ });
+
+ it('rejects a non-integer stage.timeout (no silent truncation)', async () => {
+ // 1000.9 must NOT round to 1000 — both parseTimeoutMs on the client
+ // and z.number().int() on the server reject non-integers, so the
+ // runner mirrors that. Falls back to provider default.
+ prompts.getStage.mockReturnValue({ timeout: 1000.9 });
+ providers.getActiveProvider.mockResolvedValue(cliProvider({ timeout: 5000 }));
+ runner.executeCliRun.mockImplementation(async (_id, _p, _pr, _cwd, _onData, onComplete, _t) => {
+ onComplete({ success: true });
+ });
+ await runStagedLLM('s', {});
+ expect(runner.executeCliRun.mock.calls[0][6]).toBe(5000);
+ });
+
+ it('rejects a non-positive timeoutOverride instead of running unbounded', async () => {
+ // The runner treats `0` as "no timeout" — a caller bug must not silently
+ // turn into an unbounded run. Drop to stage.timeout (or provider.timeout
+ // when neither is set).
+ prompts.getStage.mockReturnValue(null);
+ providers.getActiveProvider.mockResolvedValue(cliProvider({ timeout: 5000 }));
+ runner.executeCliRun.mockImplementation(async (_id, _p, _pr, _cwd, _onData, onComplete, _t) => {
+ onComplete({ success: true });
+ });
+ await runStagedLLM('s', {}, { timeoutOverride: 0 });
+ expect(runner.executeCliRun.mock.calls[0][6]).toBe(5000);
+ });
+
+ it('rejects a too-large timeoutOverride (above 30-min cap) and falls back', async () => {
+ // Matches the route validator's max: anything > 1_800_000 is invalid,
+ // not silently clamped. Falls through to provider.timeout.
+ prompts.getStage.mockReturnValue(null);
+ providers.getActiveProvider.mockResolvedValue(cliProvider({ timeout: 5000 }));
+ runner.executeCliRun.mockImplementation(async (_id, _p, _pr, _cwd, _onData, onComplete, _t) => {
+ onComplete({ success: true });
+ });
+ await runStagedLLM('s', {}, { timeoutOverride: 9_999_999_999 });
+ expect(runner.executeCliRun.mock.calls[0][6]).toBe(5000);
+ });
+
+ it('rejects a timeoutOverride below the 1s floor', async () => {
+ // Internal callers (extractors / pipeline stages) bypass the route
+ // validator, so the runner enforces the same min as the schema. A `1`
+ // override would otherwise become a near-instant cancel.
+ prompts.getStage.mockReturnValue(null);
+ providers.getActiveProvider.mockResolvedValue(cliProvider({ timeout: 5000 }));
+ runner.executeCliRun.mockImplementation(async (_id, _p, _pr, _cwd, _onData, onComplete, _t) => {
+ onComplete({ success: true });
+ });
+ await runStagedLLM('s', {}, { timeoutOverride: 999 });
+ expect(runner.executeCliRun.mock.calls[0][6]).toBe(5000);
+ });
+
+ it('passes effectiveTimeout into createRun so /runs metadata matches execution', async () => {
+ prompts.getStage.mockReturnValue({ timeout: 900000 });
+ providers.getActiveProvider.mockResolvedValue(cliProvider({ timeout: 5000 }));
+ runner.executeCliRun.mockImplementation(async (_id, _p, _pr, _cwd, _onData, onComplete, _t) => {
+ onComplete({ success: true });
+ });
+ await runStagedLLM('s', {});
+ expect(runner.createRun).toHaveBeenCalledWith(expect.objectContaining({ timeout: 900000 }));
+ });
+
+ it('falls back to provider.timeout in createRun call when no override is set', async () => {
+ prompts.getStage.mockReturnValue(null);
+ providers.getActiveProvider.mockResolvedValue(cliProvider({ timeout: 5000 }));
+ runner.executeCliRun.mockImplementation(async (_id, _p, _pr, _cwd, _onData, onComplete, _t) => {
+ onComplete({ success: true });
+ });
+ await runStagedLLM('s', {});
+ // /runs metadata must record what executeXxxRun actually enforces,
+ // not `undefined`. The runner's per-call timeout always resolves to
+ // provider.timeout when there's no stage/caller override; the run
+ // record needs to mirror that.
+ expect(runner.createRun).toHaveBeenCalledWith(expect.objectContaining({ timeout: 5000 }));
+ });
+
+ it('reconciles to a fallback provider when createRun returns a different provider', async () => {
+ prompts.getStage.mockReturnValue(null);
+ const original = cliProvider({ id: 'unavailable', timeout: 5000 });
+ const fallback = cliProvider({ id: 'fallback-cli', defaultModel: 'fallback-model', timeout: 7000 });
+ providers.getActiveProvider.mockResolvedValue(original);
+ runner.createRun.mockResolvedValueOnce({ runId: 'run-abc12345', provider: fallback });
+ runner.executeCliRun.mockImplementation(async (_id, providerArg, _pr, _cwd, _onData, onComplete, _t) => {
+ // Critical: execution must run against the fallback (the one createRun
+ // returned), NOT the original requested provider.
+ expect(providerArg.id).toBe('fallback-cli');
+ onComplete({ success: true });
+ });
+ const out = await runStagedLLM('s', {});
+ expect(out.providerId).toBe('fallback-cli');
+ // /runs attribution must be patched too so the record matches execution.
+ expect(runner.patchRunMetadata).toHaveBeenCalledWith(
+ 'run-abc12345',
+ expect.objectContaining({ providerId: 'fallback-cli' })
+ );
+ });
});
diff --git a/server/lib/validation.js b/server/lib/validation.js
index e229075c9e..e37b1a5ced 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -5,6 +5,7 @@ import { WORK_KINDS, WORK_STATUSES, ANALYSIS_KINDS } from './writersRoomPresets.
import { ALL_STYLE_IDS, STYLE_ID } from './writersRoomStylePresets.js';
import { BIBLE_LIMITS } from './storyBible.js';
import { ARC_SHAPE_IDS, ARC_ROLES } from './storyArc.js';
+import { MIN_TIMEOUT as STAGE_TIMEOUT_MIN_MS, MAX_TIMEOUT as STAGE_TIMEOUT_MAX_MS } from './aiToolkit/constants.js';
// gpt-image-2 (codex backend) caps at 3840px per edge and 8,294,400 total
// pixels. Mirror the ceiling for every image-gen route. Local mflux can
@@ -941,6 +942,57 @@ export function validate(schema, data) {
};
}
+// =============================================================================
+// PROMPT STAGE CONFIG (server/routes/prompts.js PUT /:stage body)
+// =============================================================================
+
+// Per-call timeout bounds: STAGE_TIMEOUT_MIN_MS / STAGE_TIMEOUT_MAX_MS are
+// imported (aliased) from aiToolkit/constants.js at the top of this file so
+// the route validator, the runner (server/lib/stageRunner.js), and the
+// toolkit's own provider/run validation all share one source of truth. The
+// client mirror in client/src/utils/formatters.js can't import across the
+// server boundary — comments on both sides flag the requirement to keep
+// them in lockstep.
+
+// Accept either a number or a numeric string (UI inputs frequently serialize
+// as strings) and validate the resulting integer. `nullable` lets the client
+// clear the override explicitly with `null`; absence leaves it untouched.
+export const stageConfigUpdateSchema = z.object({
+ name: z.string().optional(),
+ description: z.string().optional(),
+ model: z.string().nullable().optional(),
+ provider: z.string().nullable().optional(),
+ timeout: z.preprocess(
+ // Treat empty string as a "clear override" (null). Coerce digit-only
+ // strings to numbers so form clients that send "900000" still parse —
+ // but reject "1e3" / "1.5" / "0x10" by leaving them as the original
+ // string so the inner `.number()` check fails. The digit-only rule
+ // (and the `.trim()` before it) mirror `parseTimeoutMs` in
+ // client/src/utils/formatters.js and `normalizeTimeout` in
+ // server/lib/stageRunner.js so all three reject the same shapes.
+ (v) => {
+ if (v === '' || v === null) return null;
+ if (v === undefined) return undefined;
+ if (typeof v === 'number') return v;
+ if (typeof v === 'string') {
+ const trimmed = v.trim();
+ if (trimmed === '') return null;
+ if (/^\d+$/.test(trimmed)) return Number(trimmed);
+ }
+ return v;
+ },
+ z.number().int().min(STAGE_TIMEOUT_MIN_MS).max(STAGE_TIMEOUT_MAX_MS).nullable().optional()
+ ),
+ returnsJson: z.boolean().optional(),
+ variables: z.array(z.string()).optional(),
+}).strip();
+// `.strip()` (Zod default) silently drops unknown keys instead of letting
+// them flow into `updateStageConfig`'s `{...existing, ...updatedConfig}`
+// spread. Stripping prevents prototype-pollution shapes (`__proto__`,
+// `constructor`, `prototype`) and config-key squatting from a client that
+// sends an unmodelled field. If a future stage field is added, extend the
+// schema rather than reintroducing `.passthrough()`.
+
/**
* Validate data against a Zod schema, throwing on failure.
* Returns parsed data on success, throws ServerError on failure.
diff --git a/server/lib/validation.test.js b/server/lib/validation.test.js
index 8b9ae78e7c..bf8c91fac1 100644
--- a/server/lib/validation.test.js
+++ b/server/lib/validation.test.js
@@ -8,7 +8,8 @@ import {
featureAgentSchema,
featureAgentUpdateSchema,
validate,
- sanitizeTaskMetadata
+ sanitizeTaskMetadata,
+ stageConfigUpdateSchema
} from './validation.js';
describe('validation.js', () => {
@@ -522,4 +523,74 @@ describe('validation.js', () => {
expect(sanitizeTaskMetadata(obj)).toBeNull();
});
});
+
+ // The stage-config schema is the only validator standing between an
+ // unvalidated client PUT and disk, and its `timeout` preprocess + .strip()
+ // behaviors are explicitly engineered to mirror parseTimeoutMs on the
+ // client and to block prototype-pollution / config-key squatting. These
+ // tests pin the contract; a drift here would let one side accept shapes
+ // the other rejects, or quietly persist garbage to stage-config.json.
+ describe('stageConfigUpdateSchema', () => {
+ it('accepts a complete update', () => {
+ const out = stageConfigUpdateSchema.parse({
+ name: 'Adapt', description: 'd', model: 'heavy', provider: 'codex',
+ timeout: 900000, returnsJson: true, variables: ['schemaSnippet'],
+ });
+ expect(out.timeout).toBe(900000);
+ });
+
+ it('coerces a digit-only numeric string to a number', () => {
+ expect(stageConfigUpdateSchema.parse({ timeout: '900000' }).timeout).toBe(900000);
+ });
+
+ it('accepts a numeric value unchanged', () => {
+ expect(stageConfigUpdateSchema.parse({ timeout: 60000 }).timeout).toBe(60000);
+ });
+
+ it('treats empty string and null as a clear (timeout: null)', () => {
+ expect(stageConfigUpdateSchema.parse({ timeout: '' }).timeout).toBeNull();
+ expect(stageConfigUpdateSchema.parse({ timeout: null }).timeout).toBeNull();
+ });
+
+ it('leaves timeout untouched when absent', () => {
+ const out = stageConfigUpdateSchema.parse({ name: 'x' });
+ expect('timeout' in out).toBe(false);
+ });
+
+ it('rejects non-digit numeric strings (1e3 / 1.5 / 0x10) to mirror client parseTimeoutMs', () => {
+ // The client's digit-only regex rejects these; the server preprocess
+ // also leaves non-digit strings as-is so the inner z.number() fails.
+ expect(stageConfigUpdateSchema.safeParse({ timeout: '1e3' }).success).toBe(false);
+ expect(stageConfigUpdateSchema.safeParse({ timeout: '1000.5' }).success).toBe(false);
+ expect(stageConfigUpdateSchema.safeParse({ timeout: '0x10' }).success).toBe(false);
+ expect(stageConfigUpdateSchema.safeParse({ timeout: 'abc' }).success).toBe(false);
+ });
+
+ it('rejects non-integer numbers', () => {
+ expect(stageConfigUpdateSchema.safeParse({ timeout: 1000.5 }).success).toBe(false);
+ });
+
+ it('enforces the 1s lower bound', () => {
+ expect(stageConfigUpdateSchema.safeParse({ timeout: 999 }).success).toBe(false);
+ expect(stageConfigUpdateSchema.parse({ timeout: 1000 }).timeout).toBe(1000);
+ });
+
+ it('enforces the 30-minute upper bound', () => {
+ expect(stageConfigUpdateSchema.parse({ timeout: 1800000 }).timeout).toBe(1800000);
+ expect(stageConfigUpdateSchema.safeParse({ timeout: 1800001 }).success).toBe(false);
+ });
+
+ it('strips unknown keys (no prototype-pollution leak via spread merge)', () => {
+ const out = stageConfigUpdateSchema.parse({
+ name: 'x',
+ constructor: 'evil',
+ prototype: 'nope',
+ typoField: 'oops',
+ });
+ // `name` is the only schema-known key; constructor / prototype / typoField
+ // must be stripped so updateStageConfig's `{...existing, ...updated}`
+ // spread can never see them.
+ expect(out).toEqual({ name: 'x' });
+ });
+ });
});
diff --git a/server/routes/prompts.js b/server/routes/prompts.js
index 43aaca2d93..8363f78d0b 100644
--- a/server/routes/prompts.js
+++ b/server/routes/prompts.js
@@ -1,5 +1,6 @@
import { Router } from 'express';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import { stageConfigUpdateSchema, validateRequest } from '../lib/validation.js';
import {
listJobSkillTemplates,
loadJobSkillTemplate,
@@ -137,12 +138,20 @@ export function createPortOSPromptsRoutes(aiToolkit) {
res.json({ success: true, stageName });
}));
- // PUT /api/prompts/:stage - Update stage config and/or template
+ // PUT /api/prompts/:stage - Update stage config and/or template.
+ // Validate the config slice so a client sending `timeout: "abc"` 400s
+ // rather than persisting garbage that the runner would silently ignore.
+ // The schema strips unknown keys, so a body of only-unknown-keys parses
+ // to `{}` — skip the disk write in that case to avoid an atomicWrite
+ // churn on stage-config.json (the toolkit rewrites the entire file).
router.put('/:stage', asyncHandler(async (req, res) => {
- const { template, ...config } = req.body;
+ const { template, ...rawConfig } = req.body;
- if (Object.keys(config).length > 0) {
- await promptsService.updateStageConfig(req.params.stage, config);
+ if (Object.keys(rawConfig).length > 0) {
+ const config = validateRequest(stageConfigUpdateSchema, rawConfig);
+ if (Object.keys(config).length > 0) {
+ await promptsService.updateStageConfig(req.params.stage, config);
+ }
}
if (template !== undefined) {
await promptsService.updateStageTemplate(req.params.stage, template);
diff --git a/server/services/pipeline/textStages.test.js b/server/services/pipeline/textStages.test.js
index 9a9d941dce..f88dcf583c 100644
--- a/server/services/pipeline/textStages.test.js
+++ b/server/services/pipeline/textStages.test.js
@@ -43,6 +43,10 @@ vi.mock('../runner.js', () => ({
onComplete({ success: true });
}),
executeCliRun: vi.fn(),
+ // runStagedLLM always patches metadata post-createRun (to persist the
+ // effective timeout). Stub to return a resolved promise so the
+ // .catch(...) chain works.
+ patchRunMetadata: vi.fn(async () => undefined),
}));
vi.mock('../promptService.js', () => ({