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: start feature agent runs immediately
[._.]/ Adam Eivyfd567a89514d
diff --git a/client/src/pages/FeatureAgentDetail.jsx b/client/src/pages/FeatureAgentDetail.jsxindex f9b7f820d8..9f653b71be 100644--- a/client/src/pages/FeatureAgentDetail.jsx+++ b/client/src/pages/FeatureAgentDetail.jsx@@ -74,7 +74,14 @@ export default function FeatureAgentDetail() {api.stopFeatureAgent(agentId, { silent: true }).then(data => { setAgent(prev => ({ ...prev, ...data })); toast.success('Stopped'); }).catch(err => toast.error(err.message || 'Action failed'));}, []);const handleTrigger = useCallback((agentId) => {- api.triggerFeatureAgent(agentId, { silent: true }).then(() => toast.success('Run triggered')).catch(err => toast.error(err.message || 'Action failed'));+ api.triggerFeatureAgent(agentId, { silent: true }).then(result => {+ if (result?.triggered === false) {+ toast.error(result.reason || 'Run could not be started');+ return;+ }+ if (result?.agent) setAgent(prev => ({ ...prev, ...result.agent }));+ toast.success('Run started');+ }).catch(err => toast.error(err.message || 'Action failed'));}, []);const handleSave = useCallback((saved) => {diff --git a/client/src/pages/FeatureAgents.jsx b/client/src/pages/FeatureAgents.jsxindex 631fed2825..730e361dbd 100644--- a/client/src/pages/FeatureAgents.jsx+++ b/client/src/pages/FeatureAgents.jsx@@ -59,8 +59,13 @@ export default function FeatureAgents() {}, []);const handleTrigger = useCallback((id) => {- api.triggerFeatureAgent(id, { silent: true }).then(() => {- toast.success('Run triggered');+ api.triggerFeatureAgent(id, { silent: true }).then(result => {+ if (result?.triggered === false) {+ toast.error(result.reason || 'Run could not be started');+ return;+ }+ if (result?.agent) setAgents(prev => prev.map(a => a.id === id ? { ...a, ...result.agent } : a));+ toast.success('Run started');}).catch(err => toast.error(err.message || 'Action failed'));}, []);diff --git a/server/routes/featureAgents.js b/server/routes/featureAgents.jsindex 50ff8e3f51..9c4ab751fd 100644--- a/server/routes/featureAgents.js+++ b/server/routes/featureAgents.js@@ -68,9 +68,9 @@ router.post('/:id/resume', asyncHandler(async (req, res) => {// POST /:id/trigger - Force immediate runrouter.post('/:id/trigger', asyncHandler(async (req, res) => {- const agent = await featureAgents.triggerFeatureAgent(req.params.id);- if (!agent) throw new ServerError('Feature agent not found', { status: 404, code: 'NOT_FOUND' });- res.json({ triggered: true, agent });+ const result = await featureAgents.triggerFeatureAgent(req.params.id);+ if (!result) throw new ServerError('Feature agent not found', { status: 404, code: 'NOT_FOUND' });+ res.json(result);}));// POST /:id/stop - Deactivate fullydiff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex cd37582425..7dc9049a58 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -607,7 +607,12 @@ async function runAgentSpawn(task) {configReviewers: normalizeReviewers(task.metadata),configUseWorktree: !!worktreeInfo,configWorktreeAutoDetected: !!worktreeInfo && !explicitWorktree,- configCodingOnMain: !worktreeInfo && !jiraBranchName+ configCodingOnMain: !worktreeInfo && !jiraBranchName,+ // Feature-agent provenance must survive the in-memory runner handoff and+ // server restarts so featureAgents can clear currentAgentId and record the+ // run when the shared CoS lifecycle emits agent:completed.+ featureAgentId: task.metadata?.featureAgentId || null,+ featureAgentRun: isTruthyMeta(task.metadata?.featureAgentRun)});emitLog('info', `Agent ${agentId} initializing...${worktreeInfo ? ' (worktree)' : ''}${jiraBranchName ? ` (JIRA: ${jiraTicket?.ticketId})` : ''}`, { agentId, taskId: task.id });diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex 6cf07dd6fa..61566b3e13 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -192,6 +192,20 @@ export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo// Feeds both the briefing template (via the reconciled `task` object) and the// full-path fallback below.task = reconcileSplitContext(task);++ // Feature-agent tasks carry only a compact queue description. Expand the+ // persisted persona briefing at spawn time so scheduled and manually+ // triggered runs share the same feature-specific goals, constraints, branch+ // context, and previous-run history without storing that prompt in the task+ // queue or duplicating it in every task producer.+ if (task.metadata?.featureAgentRun && task.metadata?.featureAgentId) {+ const { getFeatureAgent, buildFeatureAgentPrompt } = await import('./featureAgents.js');+ const featureAgent = await getFeatureAgent(task.metadata.featureAgentId);+ if (featureAgent) {+ const featurePrompt = await buildFeatureAgentPrompt(featureAgent);+ task = { ...task, metadata: { ...task.metadata, prompt: featurePrompt } };+ }+ }const providerType = options.providerType || PROVIDER_TYPES.API;const providerId = options.providerId || null;const providerCommand = options.providerCommand || null;diff --git a/server/services/featureAgents.js b/server/services/featureAgents.jsindex f31813482f..3e0560a956 100644--- a/server/services/featureAgents.js+++ b/server/services/featureAgents.js@@ -273,36 +273,66 @@ export async function stopFeatureAgent(id) {* Force-trigger an immediate run for a feature agent*/export async function triggerFeatureAgent(id) {- const agent = await getFeatureAgent(id);+ let agent = await getFeatureAgent(id);if (!agent) return null;- // Activate if in draft/paused, then reset lastRunAt/backoff so it's picked up immediately+ // Activation enables scheduling, while Trigger is an explicit Run now. Draft+ // and paused agents therefore become active first, then all states use the+ // same immediate-dispatch path below.if (agent.status === 'draft' || agent.status === 'paused') {- await activateFeatureAgent(id);- return withLock(async () => {- const data = await readData();- const idx = data.agents.findIndex(a => a.id === id);- if (idx === -1) return null;- data.agents[idx].backoff = null;- data.agents[idx].lastRunAt = null;- data.agents[idx].updatedAt = new Date().toISOString();- await writeData(data);- return data.agents[idx];- });+ agent = await activateFeatureAgent(id);}- // For active agents, reset backoff and lastRunAt so getDueFeatureAgents picks it up immediately- return withLock(async () => {+ agent = await withLock(async () => {const data = await readData();const idx = data.agents.findIndex(a => a.id === id);if (idx === -1) return null;+ if (data.agents[idx].currentAgentId) return data.agents[idx];data.agents[idx].backoff = null;data.agents[idx].lastRunAt = null;data.agents[idx].updatedAt = new Date().toISOString();await writeData(data);- console.log(`🤖 Feature agent force-triggered: ${data.agents[idx].name} (${id})`);return data.agents[idx];});+ if (!agent) return null;++ if (agent.currentAgentId) {+ return {+ triggered: false,+ reason: 'Feature agent already has a run in progress',+ agent,+ taskId: agent.currentAgentId+ };+ }++ const task = generateTaskFromFeatureAgent(agent);+ const { addTask, forceSpawnTask } = await import('./cos.js');+ const persisted = await addTask(task, 'internal', { raw: true, suppressDequeue: true });+ if (!persisted?.id) {+ return { triggered: false, reason: 'Feature agent run was not queued', agent };+ }++ // A previous scheduler evaluation can leave an equivalent pending task in+ // COS-TASKS.md. Reuse it and force-spawn it rather than reporting a trigger+ // that only reset the feature-agent timestamps.+ if (persisted.duplicate && persisted.status !== 'pending') {+ return {+ triggered: false,+ reason: `Feature agent run is already ${persisted.status}`,+ agent,+ taskId: persisted.id+ };+ }++ await setCurrentAgent(id, persisted.id);+ const spawnResult = await forceSpawnTask(persisted.id);+ if (spawnResult?.error) {+ await clearPendingAgentTask(id, persisted.id);+ return { triggered: false, reason: spawnResult.error, agent, taskId: persisted.id };+ }++ console.log(`🤖 Feature agent force-triggered: ${agent.name} (${id})`);+ return { triggered: true, started: true, agent, taskId: persisted.id };}/**@@ -534,6 +564,17 @@ export async function setCurrentAgent(id, taskId) {});}+async function clearPendingAgentTask(id, taskId) {+ return withLock(async () => {+ const data = await readData();+ const idx = data.agents.findIndex(a => a.id === id);+ if (idx === -1 || data.agents[idx].currentAgentId !== taskId) return;+ data.agents[idx].currentAgentId = null;+ data.agents[idx].updatedAt = new Date().toISOString();+ await writeData(data);+ });+}+// Listen for agent:spawned events to update currentAgentId from the// temporary task ID to the real CoS agent ID (needed for output streaming).cosEvents.on('agent:spawned', async (agentData) => {@@ -547,4 +588,33 @@ cosEvents.on('agent:spawned', async (agentData) => {await setCurrentAgent(fa.id, agentData.id).catch(err => {console.log(`⚠️ Failed to update feature agent currentAgentId: ${err.message}`);});+ cosEvents.emit(`${EVT}:status`, { id: fa.id, status: fa.status, name: fa.name });+});++// Feature-agent tasks are ordinary CoS agents at runtime. Keep the persistent+// feature-agent record in sync with that shared lifecycle so a completed run+// does not permanently block the next scheduled or manual run.+cosEvents.on('agent:completed', async (agentData) => {+ const featureAgentId = agentData?.metadata?.featureAgentId;+ if (!agentData?.metadata?.featureAgentRun || !featureAgentId) return;+ const success = agentData.result?.success === true;+ await recordRunCompletion(featureAgentId, {+ status: success ? 'working' : 'error',+ summary: success ? 'Feature agent run completed' : agentData.result?.error || 'Feature agent run failed'+ }).catch(err => {+ console.log(`⚠️ Failed to record feature agent completion: ${err.message}`);+ });+});++// Provider/worktree setup can fail before a CoS agent record exists, so no+// completion event will clear the temporary task pointer. Release that pointer+// when the spawn path reports the task-level error.+cosEvents.on('agent:error', async (agentData) => {+ if (!agentData?.taskId) return;+ const data = await readData().catch(() => null);+ const agent = data?.agents?.find(candidate => candidate.currentAgentId === agentData.taskId);+ if (!agent) return;+ await clearPendingAgentTask(agent.id, agentData.taskId).catch(err => {+ console.log(`⚠️ Failed to clear feature agent pending task: ${err.message}`);+ });});diff --git a/server/services/featureAgents.trigger.test.js b/server/services/featureAgents.trigger.test.jsnew file mode 100644index 0000000000..feacb1844c--- /dev/null+++ b/server/services/featureAgents.trigger.test.js@@ -0,0 +1,106 @@+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { mkdirSync, rmSync, writeFileSync } from 'fs';+import { readFile } from 'fs/promises';+import { join } from 'path';+import { createTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';++const tempRoot = createTempDataRoot('portos-feature-agent-trigger-');++vi.mock('../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../lib/fileUtils.js');+ return makePathsProxy(actual, { dataRoot: tempRoot });+});++vi.mock('./cos.js', () => ({+ addTask: vi.fn(),+ forceSpawnTask: vi.fn()+}));++vi.mock('./apps.js', () => ({+ getAppById: vi.fn()+}));++import { addTask, forceSpawnTask } from './cos.js';+import { getAppById } from './apps.js';+const { generateTaskFromFeatureAgent, triggerFeatureAgent } = await import('./featureAgents.js');+import { cosEvents } from './cosEvents.js';++const agent = {+ id: 'fa-example',+ name: 'Example Agent',+ description: 'Improve the example feature',+ appId: 'app-example',+ status: 'active',+ currentAgentId: null,+ lastRunAt: new Date().toISOString(),+ backoff: { currentDelayMs: 3600000, consecutiveIdles: 1, lastIdleAt: new Date().toISOString() },+ schedule: { mode: 'continuous', pauseBetweenRunsMs: 60000 },+ git: { branchName: 'feature-agent/example-fa-example', baseBranch: 'main' }+};++const dataPath = () => join(tempRoot, 'cos', 'feature-agents.json');++beforeEach(() => {+ vi.clearAllMocks();+ mkdirSync(join(tempRoot, 'cos'), { recursive: true });+ writeFileSync(dataPath(), JSON.stringify({ version: 1, agents: [structuredClone(agent)] }));+ getAppById.mockResolvedValue({ id: 'app-example', repoPath: '/tmp/example-repo' });+ addTask.mockResolvedValue({ ...generateTaskFromFeatureAgent(agent) });+ forceSpawnTask.mockResolvedValue({ success: true, taskId: 'fa-run' });+});++afterAll(() => rmSync(tempRoot, { recursive: true, force: true }));++describe('triggerFeatureAgent', () => {+ it('queues and immediately force-spawns a manual run', async () => {+ const result = await triggerFeatureAgent(agent.id);++ expect(result).toMatchObject({ triggered: true, started: true, taskId: expect.any(String) });+ expect(addTask).toHaveBeenCalledWith(+ expect.objectContaining({ metadata: expect.objectContaining({ featureAgentId: agent.id }) }),+ 'internal',+ { raw: true, suppressDequeue: true }+ );+ expect(forceSpawnTask).toHaveBeenCalledWith(result.taskId);+ });++ it('force-spawns an equivalent pending task left by the scheduler', async () => {+ const pendingTask = { ...generateTaskFromFeatureAgent(agent), id: 'fa-run-existing', duplicate: true };+ addTask.mockResolvedValue(pendingTask);++ const result = await triggerFeatureAgent(agent.id);++ expect(result).toMatchObject({ triggered: true, taskId: 'fa-run-existing' });+ expect(forceSpawnTask).toHaveBeenCalledWith('fa-run-existing');+ });++ it('does not leave a pending pointer when immediate spawn is refused', async () => {+ forceSpawnTask.mockResolvedValue({ error: 'CoS daemon is stopped' });++ const result = await triggerFeatureAgent(agent.id);+ const saved = JSON.parse(await readFile(dataPath(), 'utf8'));++ expect(result).toMatchObject({ triggered: false, reason: 'CoS daemon is stopped' });+ expect(saved.agents[0].currentAgentId).toBeNull();+ });++ it('clears the active pointer and records the run after CoS completion', async () => {+ const result = await triggerFeatureAgent(agent.id);++ cosEvents.emit('agent:spawned', { taskId: result.taskId, id: 'agent-real' });+ await vi.waitFor(async () => {+ const saved = JSON.parse(await readFile(dataPath(), 'utf8'));+ expect(saved.agents[0].currentAgentId).toBe('agent-real');+ });+ cosEvents.emit('agent:completed', {+ metadata: { featureAgentId: agent.id, featureAgentRun: true },+ result: { success: true }+ });+ await vi.waitFor(async () => {+ const saved = JSON.parse(await readFile(dataPath(), 'utf8'));+ expect(saved.agents[0].runCount).toBe(1);+ });+ const saved = JSON.parse(await readFile(dataPath(), 'utf8'));+ expect(saved.agents[0].currentAgentId).toBeNull();+ });+});