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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: align trigger route error envelopes (#4904)
Adam Eivya0f343168d63
diff --git a/client/src/components/apps/tabs/CustomTasksSection.jsx b/client/src/components/apps/tabs/CustomTasksSection.jsxindex 472f0aae28..b1811300b0 100644--- a/client/src/components/apps/tabs/CustomTasksSection.jsx+++ b/client/src/components/apps/tabs/CustomTasksSection.jsx@@ -283,9 +283,8 @@ export default function CustomTasksSection({ appId, appName }) {// The api.* job wrappers toast HTTP/network errors themselves (request() is not// silent here), so catches just return null — guarding on the result avoids a- // second toast and the success-on-error footgun. Business-logic failures the- // server returns as a 200 { success: false } are NOT toasted by the helper, so- // those branches toast explicitly.+ // second toast and the success-on-error footgun. Deliberate 200 `skipped`+ // outcomes are NOT toasted by the helper, so those branches toast explicitly.const handleCreate = async () => {if (!validate(createForm)) return;const created = await api.createCosJob(toPayload(createForm, appId)).catch(() => null);@@ -321,7 +320,10 @@ export default function CustomTasksSection({ appId, appName }) {const result = await api.triggerCosJob(job.id).catch(() => null);setTriggering(null);if (!result) return; // HTTP/network error already toasted by the api helper- if (result.success === false) toast.error('Task failed to trigger');+ if (result.status === 'skipped') {+ const notify = result.duplicate ? toast.success : toast.error;+ notify(result.reason || 'Task was not queued');+ } else if (result.success === false) toast.error(result.reason || 'Task failed to trigger');else toast.success(`Triggered "${job.name}" for ${appName}`);fetchTasks();};diff --git a/client/src/components/apps/tabs/CustomTasksSection.test.jsx b/client/src/components/apps/tabs/CustomTasksSection.test.jsxnew file mode 100644index 0000000000..fdc4d51cb7--- /dev/null+++ b/client/src/components/apps/tabs/CustomTasksSection.test.jsx@@ -0,0 +1,61 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';++const api = vi.hoisted(() => ({+ getCosJobs: vi.fn(),+ triggerCosJob: vi.fn()+}));+const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }));++vi.mock('../../../services/api', () => api);+vi.mock('../../ui/Toast', () => ({ default: toast }));++import CustomTasksSection from './CustomTasksSection';++const task = {+ id: 'job-1',+ appId: 'app-1',+ name: 'Example Task',+ enabled: true,+ type: 'agent',+ interval: 'daily',+ runCount: 0+};++describe('CustomTasksSection trigger outcomes', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ api.getCosJobs.mockResolvedValue({ jobs: [task] });+ });++ it('surfaces a skipped trigger without claiming the task ran', async () => {+ api.triggerCosJob.mockResolvedValue({+ success: false,+ status: 'skipped',+ reason: 'Task was not queued'+ });+ render(<CustomTasksSection appId="app-1" appName="Example App" />);+ await screen.findByText('Example Task');++ fireEvent.click(screen.getByRole('button', { name: 'Run now' }));++ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Task was not queued'));+ expect(toast.success).not.toHaveBeenCalled();+ });++ it('treats an existing equivalent task as an informational skip', async () => {+ api.triggerCosJob.mockResolvedValue({+ success: true,+ status: 'skipped',+ reason: 'An equivalent task is already queued',+ duplicate: true+ });+ render(<CustomTasksSection appId="app-1" appName="Example App" />);+ await screen.findByText('Example Task');++ fireEvent.click(screen.getByRole('button', { name: 'Run now' }));++ await waitFor(() => expect(toast.success).toHaveBeenCalledWith('An equivalent task is already queued'));+ expect(toast.error).not.toHaveBeenCalled();+ });+});diff --git a/client/src/components/cos/tabs/JobsTab.jsx b/client/src/components/cos/tabs/JobsTab.jsxindex bd75fd6a7b..56492d77b1 100644--- a/client/src/components/cos/tabs/JobsTab.jsx+++ b/client/src/components/cos/tabs/JobsTab.jsx@@ -712,8 +712,11 @@ export default function JobsTab() {return null;});if (result) {- if (result.success === false) {- toast.error(`Job failed (exit ${result.exitCode ?? '?'})`, { id: 'job-trigger' });+ if (result.status === 'skipped') {+ const notify = result.duplicate ? toast.success : toast.error;+ notify(result.reason || 'Job was not queued', { id: 'job-trigger' });+ } else if (result.success === false) {+ toast.error(result.reason || `Job failed (exit ${result.exitCode ?? '?'})`, { id: 'job-trigger' });} else {const msg = result.type === 'shell' || result.type === 'script' ? 'Job executed successfully' : 'Job triggered — task queued';toast.success(msg, { id: 'job-trigger' });diff --git a/client/src/components/cos/tabs/JobsTab.test.jsx b/client/src/components/cos/tabs/JobsTab.test.jsxindex 58109710a1..1b45e9bb92 100644--- a/client/src/components/cos/tabs/JobsTab.test.jsx+++ b/client/src/components/cos/tabs/JobsTab.test.jsx@@ -13,7 +13,7 @@ const api = vi.hoisted(() => ({getProviders: vi.fn(),}));-const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }));+const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn(), loading: vi.fn() }));vi.mock('../../../services/api', () => api);vi.mock('../../ui/Toast', () => ({ default: toast }));@@ -45,6 +45,24 @@ beforeEach(() => {});describe('JobsTab / JobCard Run Now disable behavior (#4036)', () => {+ it('surfaces a deliberate skipped trigger without claiming the job ran', async () => {+ api.triggerCosJob.mockResolvedValue({+ success: false,+ status: 'skipped',+ reason: 'Task was not queued'+ });+ render(<JobsTab apps={[]} providers={[]} />);+ await waitFor(() => expect(screen.getByText('Test Job')).toBeInTheDocument());++ fireEvent.click(screen.getByRole('button', { name: 'Run now' }));++ await waitFor(() => expect(toast.error).toHaveBeenCalledWith(+ 'Task was not queued',+ { id: 'job-trigger' }+ ));+ expect(toast.success).not.toHaveBeenCalled();+ });+it('enables the Run now button when not editing and disables it while editing (save flow)', async () => {render(<JobsTab apps={[]} providers={[]} />);diff --git a/server/routes/cosJobRoutes.js b/server/routes/cosJobRoutes.jsindex ba300faf8a..9c737ccc39 100644--- a/server/routes/cosJobRoutes.js+++ b/server/routes/cosJobRoutes.js@@ -148,12 +148,8 @@ router.post('/jobs/:id/trigger', asyncHandler(async (req, res) => {// Shell jobs execute the command directlyif (autonomousJobs.isShellJob(job)) {- const result = await autonomousJobs.executeShellJob(job).catch(err => ({- success: false,- exitCode: err.exitCode ?? 1,- output: err.message- }));- return res.json({ success: result.success !== false, type: 'shell', ...result });+ const result = await autonomousJobs.executeShellJob(job);+ return res.json({ success: result.success !== false, type: 'shell', status: 'completed', ...result });}// Script jobs run their built-in handler directly. This is the manual@@ -161,11 +157,8 @@ router.post('/jobs/:id/trigger', asyncHandler(async (req, res) => {// (`manual: true`) and any fan-out handler reports failures individually// rather than coalescing them as unattended background work.if (autonomousJobs.isScriptJob(job)) {- const result = await autonomousJobs.executeScriptJob(job, { manual: true }).catch(err => ({- success: false,- error: err.message- }));- return res.json({ success: (result?.success ?? true) !== false, type: 'script', ...(result || {}) });+ const result = await autonomousJobs.executeScriptJob(job, { manual: true });+ return res.json({ success: (result?.success ?? true) !== false, type: 'script', status: 'completed', ...(result || {}) });}// Generate task and add to CoS internal task queue@@ -193,7 +186,12 @@ router.post('/jobs/:id/trigger', asyncHandler(async (req, res) => {}, 'internal');if (!taskResult?.id) {- res.json({ success: false, type: 'agent', error: 'Task was not queued (may be duplicate or blocked)' });+ res.json({+ success: false,+ type: 'agent',+ status: 'skipped',+ reason: 'Task was not queued (may be duplicate or blocked)'+ });return;}if (taskResult.duplicate) {@@ -202,13 +200,20 @@ router.post('/jobs/:id/trigger', asyncHandler(async (req, res) => {// at a task that will never run; an active twin is surfaced as-is.if (taskResult.status === 'blocked') {await cos.reviveBlockedTask(taskResult.id, { priority: task.priority, metadata: task.metadata }, 'internal');- res.json({ success: true, type: 'agent', taskId: taskResult.id, revived: true });+ res.json({ success: true, type: 'agent', status: 'queued', taskId: taskResult.id, revived: true });return;}- res.json({ success: true, type: 'agent', taskId: taskResult.id, duplicate: true });+ res.json({+ success: true,+ type: 'agent',+ status: 'skipped',+ reason: 'An equivalent task is already queued',+ taskId: taskResult.id,+ duplicate: true+ });return;}- res.json({ success: true, type: 'agent', taskId: taskResult.id });+ res.json({ success: true, type: 'agent', status: 'queued', taskId: taskResult.id });}));// DELETE /api/cos/jobs/:id - Delete a jobdiff --git a/server/routes/cosJobRoutes.test.js b/server/routes/cosJobRoutes.test.jsindex 7c046d1794..c67077e806 100644--- a/server/routes/cosJobRoutes.test.js+++ b/server/routes/cosJobRoutes.test.js@@ -1,6 +1,7 @@import { describe, it, expect, vi, beforeEach } from 'vitest';import express from 'express';import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';import jobRoutes from './cosJobRoutes.js';vi.mock('../services/cos.js', () => ({@@ -47,6 +48,7 @@ describe('CoS Job Routes', () => {app = express();app.use(express.json());app.use('/api/cos', jobRoutes);+ app.use(errorMiddleware);vi.clearAllMocks();});@@ -362,6 +364,19 @@ describe('CoS Job Routes', () => {expect(response.status).toBe(200);expect(response.body.type).toBe('shell');+ expect(response.body.status).toBe('completed');+ });++ it('returns the standard error envelope when a shell job fails', async () => {+ autonomousJobs.getJob.mockResolvedValue({ id: 'j1', type: 'shell' });+ autonomousJobs.isShellJob.mockReturnValue(true);+ autonomousJobs.executeShellJob.mockRejectedValue(new Error('command failed'));++ const response = await request(app).post('/api/cos/jobs/j1/trigger');++ expect(response.status).toBe(500);+ expect(response.body).toMatchObject({ error: 'command failed', code: 'INTERNAL_ERROR' });+ expect(response.body).not.toHaveProperty('success');});it('should trigger a script job', async () => {@@ -374,6 +389,20 @@ describe('CoS Job Routes', () => {expect(response.status).toBe(200);expect(response.body.type).toBe('script');+ expect(response.body.status).toBe('completed');+ });++ it('returns the standard error envelope when a script job fails', async () => {+ autonomousJobs.getJob.mockResolvedValue({ id: 'j1', type: 'script' });+ autonomousJobs.isShellJob.mockReturnValue(false);+ autonomousJobs.isScriptJob.mockReturnValue(true);+ autonomousJobs.executeScriptJob.mockRejectedValue(new Error('handler failed'));++ const response = await request(app).post('/api/cos/jobs/j1/trigger');++ expect(response.status).toBe(500);+ expect(response.body).toMatchObject({ error: 'handler failed', code: 'INTERNAL_ERROR' });+ expect(response.body).not.toHaveProperty('success');});it('should trigger an agent job', async () => {@@ -387,6 +416,7 @@ describe('CoS Job Routes', () => {expect(response.status).toBe(200);expect(response.body.type).toBe('agent');+ expect(response.body.status).toBe('queued');expect(response.body.taskId).toBe('task-1');});@@ -449,6 +479,8 @@ describe('CoS Job Routes', () => {expect(response.status).toBe(200);expect(response.body.success).toBe(false);+ expect(response.body.status).toBe('skipped');+ expect(response.body.reason).toMatch(/not queued/i);});});diff --git a/server/routes/detect.js b/server/routes/detect.jsindex b97c6d0513..3922e57b56 100644--- a/server/routes/detect.js+++ b/server/routes/detect.js@@ -243,10 +243,7 @@ router.post('/ai', asyncHandler(async (req, res) => {throw new ServerError('Path is required', { status: 400, code: 'MISSING_PATH' });}- const result = await detectAppWithAi(path, providerId).catch(err => ({- success: false,- error: err.message- }));+ const result = await detectAppWithAi(path, providerId);res.json(result);}));diff --git a/server/routes/detect.test.js b/server/routes/detect.test.jsnew file mode 100644index 0000000000..3570005acc--- /dev/null+++ b/server/routes/detect.test.js@@ -0,0 +1,46 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';+import { errorMiddleware } from '../lib/errorHandler.js';+import { request } from '../lib/testHelper.js';+import detectRoutes from './detect.js';++vi.mock('../services/aiDetect.js', () => ({+ detectAppWithAi: vi.fn()+}));++import { detectAppWithAi } from '../services/aiDetect.js';++describe('Detect Routes', () => {+ let app;++ beforeEach(() => {+ app = express();+ app.use(express.json());+ app.use('/api/detect', detectRoutes);+ app.use(errorMiddleware);+ vi.clearAllMocks();+ });++ it('keeps an expected AI detection refusal as a structured 200 outcome', async () => {+ detectAppWithAi.mockResolvedValue({ success: false, error: 'No AI provider configured' });++ const response = await request(app)+ .post('/api/detect/ai')+ .send({ path: '/example/project' });++ expect(response.status).toBe(200);+ expect(response.body).toEqual({ success: false, error: 'No AI provider configured' });+ });++ it('returns the standard error envelope when AI detection throws', async () => {+ detectAppWithAi.mockRejectedValue(new Error('provider crashed'));++ const response = await request(app)+ .post('/api/detect/ai')+ .send({ path: '/example/project' });++ expect(response.status).toBe(500);+ expect(response.body).toMatchObject({ error: 'provider crashed', code: 'INTERNAL_ERROR' });+ expect(response.body).not.toHaveProperty('success');+ });+});