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([issue-989]): release stranded app-review marker on spawn failure
Adam Eivyccf1919df8d4
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex e26c00b5d4..02b193d659 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -26,6 +26,7 @@ import { buildCliSpawnConfig, isClaudeCliProvider, isTuiProvider, getClaudeSettiimport { extractCodexAssistantTail } from '../lib/codexAssistantExtract.js';import { buildTuiSpawnConfig, spawnTuiAgent } from './agentTuiSpawning.js';import { processAgentCompletion } from './agentCompletion.js';+import { releaseAppReviewMarker } from './appActivity.js';import { runnerAgents, pausedAgents, spawningTasks, useRunner, isTruthyMeta } from './agentState.js';import { v4 as uuidv4 } from '../lib/uuid.js';@@ -129,6 +130,10 @@ export async function spawnAgentForTask(task) {blockedAt: new Date().toISOString()}}, task.taskType || 'user').catch(() => {});+ // Give up on this task — release the synthetic app-review marker so the app+ // doesn't read "in review" forever (issue #989). No-op without metadata.app+ // or when a real agent holds the marker.+ await releaseAppReviewMarker(task.metadata?.app).catch(() => {});return null;}@@ -143,6 +148,7 @@ export async function spawnAgentForTask(task) {if (!laneResult.success) {spawningTasks.delete(task.id);emitLog('warn', `Failed to tag lane ${laneName}: ${laneResult.error}`, { taskId: task.id });+ await releaseAppReviewMarker(task.metadata?.app).catch(() => {});return null;}@@ -154,12 +160,22 @@ export async function spawnAgentForTask(task) {});startExecution(toolExecution.id);- // Helper to cleanup on early exit- const cleanupOnError = (error) => {+ // Helper to cleanup on early exit. Releases the dedup guard, the execution+ // lane, and the tool-execution state — and the synthetic app-review marker+ // bound by `bindAppReviewAgent` before this spawn. Without the marker+ // release, a pre-completion `return null` (provider resolution, prep+ // deferred/blocked, in_progress updateTask failure) strands the app reading+ // "in review" until the next daemon restart (issue #989). The release is a+ // no-op when the task carries no `metadata.app` or the marker is a real+ // `agent-*` id from a different live agent.+ const cleanupOnError = async (error) => {spawningTasks.delete(task.id);release(agentId);errorExecution(toolExecution.id, { message: error });completeExecution(toolExecution.id, { success: false });+ await releaseAppReviewMarker(task.metadata?.app).catch(err => {+ emitLog('warn', `Failed to release app review marker for ${task.metadata?.app}: ${err.message}`, { taskId: task.id });+ });};// Single try wraps setup + the spawn handoff so all locals stay in@@ -191,7 +207,7 @@ export async function spawnAgentForTask(task) {// spawn-local guard/lane/execution state lives.const resolution = await resolveAgentProviderAndModel(task);if (!resolution.ok) {- cleanupOnError(resolution.error);+ await cleanupOnError(resolution.error);cosEvents.emit('agent:error', {taskId: task.id,error: resolution.error,@@ -208,12 +224,12 @@ export async function spawnAgentForTask(task) {// dedup guard / lane / execution state are released consistently.const prep = await prepareAgentWorkspace({ agentId, task });if (prep.outcome === 'deferred') {- cleanupOnError(prep.reason);+ await cleanupOnError(prep.reason);cosEvents.emit('agent:deferred', { taskId: task.id, reason: prep.deferReason, branch: prep.branch });return null;}if (prep.outcome === 'blocked') {- cleanupOnError(prep.reason);+ await cleanupOnError(prep.reason);cosEvents.emit('agent:error', { taskId: task.id, error: prep.reason });return null;}@@ -298,7 +314,7 @@ export async function spawnAgentForTask(task) {return null;});if (!updateResult) {- cleanupOnError('Failed to update task status');+ await cleanupOnError('Failed to update task status');return null;}@@ -378,7 +394,7 @@ export async function spawnAgentForTask(task) {throw err;}emitLog('error', `Agent spawn setup failed: ${err.message}`, { taskId: task.id, error: err.message });- cleanupOnError(err.message);+ await cleanupOnError(err.message);cosEvents.emit('agent:error', { taskId: task.id, error: err.message });// Preserve the autonomous-job retry contract. Pre-widening, an uncaught// throw here propagated to subAgentSpawner's `task:ready` listener,diff --git a/server/services/agentLifecycle.test.js b/server/services/agentLifecycle.test.jsindex 3e11b978ee..8762b51cfc 100644--- a/server/services/agentLifecycle.test.js+++ b/server/services/agentLifecycle.test.js@@ -342,6 +342,44 @@ describe('agentLifecycle source — spawningTasks delete placement', () => {});});+// Source-level assertion (issue #989): the synthetic app-review marker bound by+// `bindAppReviewAgent` before this spawn MUST be released on every+// pre-completion `return null` path, or the app reads "in review" until the next+// daemon restart. The shared `cleanupOnError` closure owns the release for the+// four detected-error paths (provider resolution, prep deferred/blocked,+// updateTask failure) + the pre-spawn catch arm; the two earliest returns+// (max-spawns block, lane-acquire failure) release inline because they fire+// before `cleanupOnError` is defined.++describe('agentLifecycle source — app-review marker release (issue #989)', () => {+ it('cleanupOnError releases the synthetic app-review marker', () => {+ const start = AGENT_LIFECYCLE_SRC.indexOf('const cleanupOnError =');+ expect(start, 'cleanupOnError must exist').toBeGreaterThan(-1);+ const body = AGENT_LIFECYCLE_SRC.slice(start, start + 800);+ expect(body, 'cleanupOnError must release the app-review marker').toMatch(/releaseAppReviewMarker\(task\.metadata\?\.app\)/);+ });++ it('every cleanupOnError call is awaited so the release persists before return null', () => {+ const fnStart = AGENT_LIFECYCLE_SRC.indexOf('export async function spawnAgentForTask');+ const fnBody = AGENT_LIFECYCLE_SRC.slice(fnStart, fnStart + 60_000);+ // No bare `cleanupOnError(` call may exist — only `await cleanupOnError(`+ // (and the `const cleanupOnError =` definition). A bare call would fire the+ // async marker release without awaiting it, racing the `return null`.+ const bareCalls = fnBody.match(/(?<!await )(?<!const )cleanupOnError\(/g) || [];+ expect(bareCalls, 'all cleanupOnError calls must be awaited').toEqual([]);+ });++ it('the max-spawns and lane-acquire early returns release the marker inline', () => {+ const fnStart = AGENT_LIFECYCLE_SRC.indexOf('export async function spawnAgentForTask');+ // Slice from the function start up to where cleanupOnError is defined —+ // the two earliest `return null` paths live in this prefix.+ const defIdx = AGENT_LIFECYCLE_SRC.indexOf('const cleanupOnError =', fnStart);+ const prefix = AGENT_LIFECYCLE_SRC.slice(fnStart, defIdx);+ const inlineReleases = prefix.match(/await releaseAppReviewMarker\(task\.metadata\?\.app\)/g) || [];+ expect(inlineReleases.length, 'max-spawns + lane-acquire returns must each release inline').toBe(2);+ });+});+// ─── spawnAgentForTask — cleanupOnError ────────────────────────────────────//// `spawnAgentForTask` has ~400 LOC of async work betweendiff --git a/server/services/appActivity.js b/server/services/appActivity.jsindex a8c512374e..67dcd46cac 100644--- a/server/services/appActivity.js+++ b/server/services/appActivity.js@@ -121,6 +121,45 @@ export async function bindAppReviewAgent(appId, agentId) {});}+/**+ * Synthetic review markers bound by `bindAppReviewAgent` before the real agent+ * spawns: `idle-review-<ts>` (idle loop) and `on-demand-<ts>` (on-demand loop).+ * A *real* agent marker is `agent-<id>` and must never be cleared by the+ * spawn-failure release below.+ */+const SYNTHETIC_REVIEW_AGENT_RE = /^(idle-review|on-demand)-/;++/**+ * Release a *synthetic* app-review marker stranded by a spawn that failed before+ * completion.+ *+ * `bindAppReviewAgent` writes a synthetic `activeAgentId` (`idle-review-*` /+ * `on-demand-*`) the instant a review task is produced — but `spawnAgentForTask`+ * has several `return null` failure paths *after* that bind (provider resolution+ * fails, workspace prep deferred/blocked, the in_progress `updateTask` fails,+ * max-spawns block). On any of those, no agent runs to completion, so+ * `processAgentCompletion` never clears the marker via `markAppReviewCompleted` ++ * `startAppCooldown` — the app reads "in review" until the next daemon restart's+ * `clearStaleActiveAgents` sweep (the synthetic id is never in the live+ * `agent-*` set). This is the same failure *class* as #978, one step later in the+ * lifecycle. See issue #989.+ *+ * Releasing only clears `activeAgentId`: it does NOT bump `reviewCount` /+ * `issuesFound` (no review actually ran) and it leaves the cooldown that+ * `markAppReviewCooldown` already advanced intact — so the app is re-picked after+ * its normal cooldown window, not immediately. The synthetic-id guard makes this+ * safe to call on any failing task that carries `metadata.app`: a real `agent-*`+ * marker (a different live agent) is left untouched, and a no-marker app is a+ * no-op.+ */+export async function releaseAppReviewMarker(appId) {+ if (!appId) return null;+ const activity = await loadAppActivity();+ const app = activity.apps?.[appId];+ if (!SYNTHETIC_REVIEW_AGENT_RE.test(app?.activeAgentId || '')) return null;+ return updateAppActivity(appId, { activeAgentId: null });+}+/*** Mark an app review as completed*/diff --git a/server/services/appActivity.test.js b/server/services/appActivity.test.jsindex c8f7df04a4..33bccb72a0 100644--- a/server/services/appActivity.test.js+++ b/server/services/appActivity.test.js@@ -77,3 +77,82 @@ describe('appActivity review markers (issue #978)', () => {expect(afterBind.activeAgentId).toBe('on-demand-456');});});++/**+ * Tests for releaseAppReviewMarker (issue #989).+ *+ * The remaining gap after #978: bindAppReviewAgent writes a synthetic+ * `activeAgentId` (`idle-review-*` / `on-demand-*`) the instant a task is+ * produced, but spawnAgentForTask can still `return null` *after* that bind+ * (provider resolution, prep deferred/blocked, in_progress updateTask failure,+ * max-spawns). On those paths processAgentCompletion never fires, so the+ * synthetic marker was stranded until the next daemon restart. releaseAppReviewMarker+ * clears ONLY a synthetic marker, leaves stats and the advanced cooldown intact,+ * and refuses to touch a real `agent-*` marker.+ */+describe('releaseAppReviewMarker (issue #989)', () => {+ beforeEach(() => {+ rmSync(TEST_DATA_ROOT, { recursive: true, force: true });+ mkdirSync(TEST_DATA_ROOT, { recursive: true });+ });++ it('clears a stranded idle-review marker (provider resolution / prep / updateTask failure)', async () => {+ await appActivity.markAppReviewCooldown('app-1');+ await appActivity.bindAppReviewAgent('app-1', 'idle-review-123');+ await appActivity.releaseAppReviewMarker('app-1');+ const rec = await appActivity.getAppActivityById('app-1');+ expect(rec.activeAgentId, 'synthetic marker must be cleared on spawn failure').toBeNull();+ });++ it('clears a stranded on-demand marker', async () => {+ await appActivity.markAppReviewCooldown('app-1');+ await appActivity.bindAppReviewAgent('app-1', 'on-demand-456');+ await appActivity.releaseAppReviewMarker('app-1');+ const rec = await appActivity.getAppActivityById('app-1');+ expect(rec.activeAgentId).toBeNull();+ });++ it('preserves the advanced cooldown so the app is re-picked later, not immediately', async () => {+ await appActivity.markAppReviewCooldown('app-1');+ const stamp = (await appActivity.getAppActivityById('app-1')).lastReviewedAt;+ await appActivity.bindAppReviewAgent('app-1', 'idle-review-789');+ await appActivity.releaseAppReviewMarker('app-1');+ const rec = await appActivity.getAppActivityById('app-1');+ expect(rec.lastReviewedAt, 'cooldown stamp survives the release').toBe(stamp);+ expect(await appActivity.isAppOnCooldown('app-1', 60_000), 'app stays on cooldown after release').toBe(true);+ });++ it('does NOT bump review stats (no review actually ran)', async () => {+ await appActivity.markAppReviewCooldown('app-1');+ await appActivity.bindAppReviewAgent('app-1', 'idle-review-1');+ await appActivity.releaseAppReviewMarker('app-1');+ const rec = await appActivity.getAppActivityById('app-1');+ expect(rec.stats?.reviewCount ?? 0, 'release must not count as a completed review').toBe(0);+ });++ it('refuses to clear a real agent-* marker held by a different live agent', async () => {+ await appActivity.markAppReviewCooldown('app-1');+ await appActivity.updateAppActivity('app-1', { activeAgentId: 'agent-abcd1234' });+ await appActivity.releaseAppReviewMarker('app-1');+ const rec = await appActivity.getAppActivityById('app-1');+ expect(rec.activeAgentId, 'a real bound agent must be left untouched').toBe('agent-abcd1234');+ });++ it('is a no-op for an app with no marker', async () => {+ await appActivity.markAppReviewCooldown('app-1');+ await appActivity.releaseAppReviewMarker('app-1');+ const rec = await appActivity.getAppActivityById('app-1');+ expect(rec.activeAgentId).toBeNull();+ });++ it('is a no-op for an unknown app id (no record created)', async () => {+ await appActivity.releaseAppReviewMarker('never-seen');+ const rec = await appActivity.getAppActivityById('never-seen');+ expect(rec, 'release must not materialize a record for an unknown app').toBeNull();+ });++ it('is a no-op when appId is falsy', async () => {+ const result = await appActivity.releaseAppReviewMarker(undefined);+ expect(result).toBeNull();+ });+});