Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: answer loop and message-action caller errors with 4xx instead of 500 (#9187)

[._.]/ Adam Eivy11408145c6b8
diff --git a/server/lib/README.md b/server/lib/README.md
index ceb1ad15d2..6a065a30ca 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -792,3 +792,4 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `trackLimits.js` | Track record length/count caps shared by the tracks sanitizer and client editors. |
| `shellLimits.js` | `MAX_TOTAL_SESSIONS` shell-session cap shared by the shell service and the Shell UI. |
| `muscriptorModels.js` | `MUSCRIPTOR_MODELS` (`small`/`medium`/`large`) — MuScriptor size tiers shared by route schemas and `audioMidiTranscription.js`; pinned to the Python runner's argparse choices. |
+| `loopInterval.js` | Loop interval grammar (`MIN_INTERVAL_MS`, `parseInterval`, `isValidLoopInterval`) shared by `services/loops.js` and `createLoopSchema` so the route rejects what the service would. |
diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.js
index 3b78b49115..0ee897e6a4 100644
--- a/server/lib/cosValidation.js
+++ b/server/lib/cosValidation.js
@@ -11,6 +11,7 @@
import { z } from 'zod';
import { emptyToUndefined, emptyToNull, providerRefFieldSchema, providerRefSchema } from './zodCompat.js';
import { isPlainObject } from './objects.js';
+import { MIN_INTERVAL_MS, isValidLoopInterval } from './loopInterval.js';
import { EFFORT_LEVELS } from './providerModels.js';
import { isValidSlashdoCommand } from './slashdoInvocation.js';
import { PR_COMPLETION_VALUES, PR_REVIEW_MODE_VALUES } from './prDisposition.js';
@@ -425,8 +426,9 @@ export const goalFidelityFalsePositiveSchema = z.object({
// =============================================================================
export const createLoopSchema = z.object({
- prompt: z.string().min(1),
- interval: z.union([z.string().min(1), z.number().positive()]),
+ prompt: z.string().trim().min(1),
+ interval: z.union([z.string().min(1), z.number().positive()])
+ .refine(isValidLoopInterval, `Interval must be at least ${MIN_INTERVAL_MS / 1000} seconds`),
name: z.string().optional(),
cwd: z.string().optional(),
providerId: z.preprocess(v => v === '' ? undefined : v, z.string().optional()),
diff --git a/server/lib/index.js b/server/lib/index.js
index dab4b96258..3ba537b3b5 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -774,3 +774,4 @@ export * from './shellLimits.js';
export * from './layeredIntelligenceRejectionLabels.js';
export * from './muscriptorModels.js';
export * from './metadataFlags.js';
+export * from './loopInterval.js';
diff --git a/server/lib/loopInterval.js b/server/lib/loopInterval.js
new file mode 100644
index 0000000000..ad0cd3a0d9
--- /dev/null
+++ b/server/lib/loopInterval.js
@@ -0,0 +1,18 @@
+// Loop interval grammar shared by services/loops.js and the loop route schema,
+// so the route rejects exactly what the service would.
+export const MIN_INTERVAL_MS = 10_000;
+
+export function parseInterval(str) {
+ const match = String(str).match(/^(\d+(?:\.\d+)?)\s*(s|m|h|d|ms)?$/i);
+ if (!match) return null;
+ const val = parseFloat(match[1]);
+ const unit = (match[2] || 'm').toLowerCase();
+ const multipliers = { ms: 1, s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 };
+ return Math.round(val * (multipliers[unit] || 60_000));
+}
+
+// True when `interval` (ms number or grammar string) resolves to >= MIN_INTERVAL_MS.
+export function isValidLoopInterval(interval) {
+ const ms = typeof interval === 'number' ? interval : parseInterval(interval);
+ return Boolean(ms) && ms >= MIN_INTERVAL_MS;
+}
diff --git a/server/routes/loops.test.js b/server/routes/loops.test.js
new file mode 100644
index 0000000000..afbeb1e014
--- /dev/null
+++ b/server/routes/loops.test.js
@@ -0,0 +1,50 @@
+import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware, errorEvents } from '../lib/errorHandler.js';
+
+const created = vi.hoisted(() => ({ writes: 0 }));
+vi.mock('../lib/fileUtils.js', async (orig) => {
+ const actual = await orig();
+ return {
+ ...actual,
+ tryReadFile: async () => '[]',
+ ensureDir: async () => {},
+ atomicWrite: async () => { created.writes++; }
+ };
+});
+import loopsRoutes from './loops.js';
+
+const observe = () => {};
+beforeAll(() => errorEvents.on('error', observe));
+afterAll(() => errorEvents.off('error', observe));
+
+const app = express();
+app.use(express.json());
+app.use('/api/loops', loopsRoutes);
+app.use(errorMiddleware);
+
+describe('loops routes — caller errors are 4xx', () => {
+ it.each([
+ [{ prompt: 'hi', interval: 5 }],
+ [{ prompt: 'hi', interval: 'abc' }],
+ [{ prompt: ' ', interval: '1m' }]
+ ])('rejects %j with 400 before writing', async (body) => {
+ const res = await request(app).post('/api/loops').send(body);
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('VALIDATION_ERROR');
+ expect(created.writes).toBe(0);
+ });
+
+ it('404s an unknown id on resume, trigger and put', async () => {
+ expect((await request(app).post('/api/loops/nope/resume')).status).toBe(404);
+ expect((await request(app).put('/api/loops/nope').send({ name: 'x' })).status).toBe(404);
+ expect((await request(app).post('/api/loops/nope/trigger')).status).toBe(404);
+ });
+
+ it('409s stop on a loop that is not running', async () => {
+ const res = await request(app).post('/api/loops/nope/stop');
+ expect(res.status).toBe(409);
+ expect(res.body.code).toBe('INVALID_STATE');
+ });
+});
diff --git a/server/services/loops.js b/server/services/loops.js
index 0b63a56f8d..e95a1a3c31 100644
--- a/server/services/loops.js
+++ b/server/services/loops.js
@@ -11,6 +11,8 @@ import { EventEmitter } from 'events';
import { join } from 'path';
import { PATHS, ensureDir, atomicWrite, tryReadFile } from '../lib/fileUtils.js';
import { randomUUID } from 'crypto';
+import { ServerError } from '../lib/errorHandler.js';
+import { MIN_INTERVAL_MS, parseInterval } from '../lib/loopInterval.js';
import { createRun } from './runner.js';
import { resolveProviderAndModel, runPromptThroughProvider } from './promptRunner.js';
import { listSelectableProviders, getActiveProvider } from './providers.js';
@@ -20,19 +22,9 @@ export const loopEvents = new EventEmitter();
const LOOPS_FILE = join(PATHS.data, 'loops.json');
const LOOPS_OUTPUT_DIR = join(PATHS.data, 'loops');
const DEFAULT_TIMEOUT_MS = 300_000;
-const MIN_INTERVAL_MS = 10_000;
const activeLoops = new Map();
-function parseInterval(str) {
- const match = String(str).match(/^(\d+(?:\.\d+)?)\s*(s|m|h|d|ms)?$/i);
- if (!match) return null;
- const val = parseFloat(match[1]);
- const unit = (match[2] || 'm').toLowerCase();
- const multipliers = { ms: 1, s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 };
- return Math.round(val * (multipliers[unit] || 60_000));
-}
-
function formatInterval(ms) {
if (ms >= 86_400_000) return `${ms / 86_400_000}d`;
if (ms >= 3_600_000) return `${ms / 3_600_000}h`;
@@ -270,10 +262,10 @@ async function updatePersistedLoop(id, updates) {
export async function createLoop({ prompt, interval, name, cwd, providerId, timeout, runImmediately = true }) {
const intervalMs = typeof interval === 'number' ? interval : parseInterval(interval);
if (!intervalMs || intervalMs < MIN_INTERVAL_MS) {
- throw new Error('Interval must be at least 10 seconds');
+ throw new ServerError('Interval must be at least 10 seconds', { status: 400, code: 'VALIDATION_ERROR' });
}
if (!prompt?.trim()) {
- throw new Error('Prompt is required');
+ throw new ServerError('Prompt is required', { status: 400, code: 'VALIDATION_ERROR' });
}
await ensureDir(LOOPS_OUTPUT_DIR);
@@ -327,7 +319,7 @@ function startLoopTimer(loop, runImmediately = false) {
export async function stopLoop(id) {
const active = activeLoops.get(id);
- if (!active) throw new Error(`Loop ${id} is not running`);
+ if (!active) throw new ServerError(`Loop ${id} is not running`, { status: 409, code: 'INVALID_STATE' });
clearInterval(active.timer);
activeLoops.delete(id);
@@ -347,13 +339,13 @@ export async function stopLoop(id) {
}
export async function resumeLoop(id) {
- if (activeLoops.has(id)) throw new Error(`Loop ${id} is already running`);
+ if (activeLoops.has(id)) throw new ServerError(`Loop ${id} is already running`, { status: 409, code: 'INVALID_STATE' });
let loopRecord;
await withLoopsTail(async () => {
const loops = await loadLoops();
const loop = loops.find(l => l.id === id);
- if (!loop) throw new Error(`Loop ${id} not found`);
+ if (!loop) throw new ServerError(`Loop ${id} not found`, { status: 404, code: 'NOT_FOUND' });
loop.status = 'running';
loop.stoppedAt = null;
await saveLoops(loops);
@@ -408,8 +400,8 @@ export async function getLoop(id) {
export async function triggerLoop(id) {
const loops = await loadLoops();
const loop = loops.find(l => l.id === id);
- if (!loop) throw new Error(`Loop ${id} not found`);
- if (!activeLoops.has(id)) throw new Error(`Loop ${id} is not running`);
+ if (!loop) throw new ServerError(`Loop ${id} not found`, { status: 404, code: 'NOT_FOUND' });
+ if (!activeLoops.has(id)) throw new ServerError(`Loop ${id} is not running`, { status: 409, code: 'INVALID_STATE' });
runIteration(id);
return { triggered: true };
@@ -420,14 +412,14 @@ export async function updateLoop(id, updates) {
await withLoopsTail(async () => {
const loops = await loadLoops();
const idx = loops.findIndex(l => l.id === id);
- if (idx < 0) throw new Error(`Loop ${id} not found`);
+ if (idx < 0) throw new ServerError(`Loop ${id} not found`, { status: 404, code: 'NOT_FOUND' });
const allowed = ['name', 'prompt', 'interval', 'cwd', 'providerId', 'timeout'];
for (const key of allowed) {
if (updates[key] !== undefined) {
if (key === 'interval') {
const ms = typeof updates[key] === 'number' ? updates[key] : parseInterval(updates[key]);
- if (!ms || ms < MIN_INTERVAL_MS) throw new Error('Interval must be at least 10 seconds');
+ if (!ms || ms < MIN_INTERVAL_MS) throw new ServerError('Interval must be at least 10 seconds', { status: 400, code: 'VALIDATION_ERROR' });
loops[idx].intervalMs = ms;
} else {
loops[idx][key] = updates[key];
diff --git a/server/services/messageActions.js b/server/services/messageActions.js
index 6f7b7241b0..6a1d7242e7 100644
--- a/server/services/messageActions.js
+++ b/server/services/messageActions.js
@@ -52,14 +52,14 @@ async function ensureProviderPage(accountType) {
* Auto-launches the browser tab and waits for auth if needed.
*/
export async function executeAction(accountId, messageId, action) {
- if (!UUID_RE.test(accountId)) throw new Error('Invalid accountId');
- if (!['archive', 'delete'].includes(action)) throw new Error(`Unsupported action: ${action}`);
+ if (!UUID_RE.test(accountId)) throw new ServerError('Invalid accountId', { status: 400, code: 'VALIDATION_ERROR' });
+ if (!['archive', 'delete'].includes(action)) throw new ServerError(`Unsupported action: ${action}`, { status: 400, code: 'VALIDATION_ERROR' });
const account = await getAccount(accountId);
- if (!account) throw new Error('Account not found');
+ if (!account) throw new ServerError('Account not found', { status: 404, code: 'NOT_FOUND' });
const message = await getMessage(accountId, messageId);
- if (!message) throw new Error('Message not found');
+ if (!message) throw new ServerError('Message not found', { status: 404, code: 'NOT_FOUND' });
// Gmail: use API directly instead of browser automation
if (account.type === 'gmail' && message.apiId) {
diff --git a/server/services/messageActions.test.js b/server/services/messageActions.test.js
index ee92ed56fd..5539a05c9f 100644
--- a/server/services/messageActions.test.js
+++ b/server/services/messageActions.test.js
@@ -101,3 +101,17 @@ it('preserves Gmail API-by-ID archive and delete without browser calls', async (
expect(mocks.modify).toHaveBeenCalledWith({ userId: 'me', id: 'api-target', requestBody: { removeLabelIds: ['INBOX'] } });
expect(mocks.evaluate).not.toHaveBeenCalled();
});
+
+describe('executeAction caller-error statuses', () => {
+ beforeEach(() => { mocks.account.mockReset(); mocks.message.mockReset(); });
+ it('answers a stale message or account with 404 NOT_FOUND', async () => {
+ mocks.account.mockResolvedValueOnce({ id: accountId, type: 'gmail' });
+ mocks.message.mockResolvedValueOnce(null);
+ await expect(executeAction(accountId, 'gone', 'archive')).rejects.toMatchObject({ status: 404, code: 'NOT_FOUND', message: 'Message not found' });
+ mocks.account.mockResolvedValueOnce(null);
+ await expect(executeAction(accountId, 'gone', 'archive')).rejects.toMatchObject({ status: 404, code: 'NOT_FOUND', message: 'Account not found' });
+ });
+ it('answers a bad action with 400', async () => {
+ await expect(executeAction(accountId, 'm', 'explode')).rejects.toMatchObject({ status: 400 });
+ });
+});