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: keep a freshly registered agent from being retired by the orphan sweep mid-spawn

[._.]/ Adam Eivydb96e1eda69a
diff --git a/server/services/agentManagement.js b/server/services/agentManagement.js
index 7914c6949d..305b435371 100644
--- a/server/services/agentManagement.js
+++ b/server/services/agentManagement.js
@@ -23,7 +23,7 @@ import { terminateAgentViaRunner, killAgentViaRunner, pauseAgentViaRunner, getAg
import { runnerEntryShieldsRunningRecord } from '../lib/runnerAgentLiveness.js';
import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';
import { isInternalTaskId } from '../lib/taskParser.js';
-import { activeAgents, runnerAgents, userTerminatedAgents, pausedAgents, whenPausedAgentExits, useRunner, unregisterSpawnedAgent } from './agentState.js';
+import { activeAgents, runnerAgents, spawningTasks, userTerminatedAgents, pausedAgents, whenPausedAgentExits, useRunner, unregisterSpawnedAgent } from './agentState.js';
// Both were extracted out of agentLifecycle.js (issue #2837) so this module no
// longer depends on the lifecycle orchestrator — which depends on THIS module
// for handleOrphanedTask. Importing them from their own leaf modules is what
@@ -1124,6 +1124,9 @@ async function retireStrandedPausedAgents(agents) {
}
}
+// A running record with no pid this young may still be mid-spawn.
+const SPAWN_GRACE_MS = 30000;
+
export function cleanupOrphanedAgents() {
if (!orphanCleanupPromise) {
orphanCleanupPromise = runCleanupOrphanedAgents().finally(() => {
@@ -1231,6 +1234,15 @@ async function runCleanupOrphanedAgents() {
// the durable record running forever.
if (activeAgents.has(agent.id)) continue;
if (inRemoteRunner) continue;
+ // The record is written before the spawn finishes (prompt build, task claim,
+ // PTY open), so a fresh one has no pid and no handle yet. Retiring it here
+ // completes a run that goes on to launch — its claim ownership bind then
+ // fails with owner-not-running. Mirrors the zombie sweep's guards.
+ if (agent.taskId && spawningTasks.has(agent.taskId)) continue;
+ if (!agent.pid) {
+ const startedAtMs = agent.startedAt ? Date.parse(agent.startedAt) : 0;
+ if (Date.now() - startedAtMs < SPAWN_GRACE_MS) continue;
+ }
if (runnerAgents.has(agent.id)) runnerAgents.delete(agent.id);
// Before marking as orphaned, check if the process is actually still running
diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.js
index 75f73b47fa..50d64f5063 100644
--- a/server/services/agentManagement.test.js
+++ b/server/services/agentManagement.test.js
@@ -142,7 +142,7 @@ import { pauseAgentViaRunner, terminateAgentViaRunner, getActiveAgentsFromRunner
import * as shellService from './shell.js';
import { readHostShutdownMarker, clearHostShutdownMarker } from '../lib/hostShutdown.js';
import { committedDuringRun } from '../lib/gitCommitProbe.js';
-import { activeAgents, runnerAgents, pausedAgents, consumePausedAgentExit } from './agentState.js';
+import { activeAgents, runnerAgents, spawningTasks, pausedAgents, consumePausedAgentExit } from './agentState.js';
/**
* A direct-mode agent's spawned handle. Its prototype is ChildProcess so it
@@ -234,6 +234,28 @@ describe('cleanupOrphanedAgents — startup recovery coordination', () => {
expect(updateTask).not.toHaveBeenCalled();
});
+ // A record is written before its spawn finishes. Retiring it then completes a
+ // run that launches anyway, so its claim-ownership bind fails owner-not-running.
+ it('does not reap a pid-less record that is still mid-spawn', async () => {
+ getActiveAgentsFromRunner.mockResolvedValue([]);
+ getTaskById.mockResolvedValue({ id: 'task-1', taskType: 'user', status: 'in_progress', metadata: {} });
+ const base = { status: 'running', taskId: 'task-1', metadata: {} };
+
+ getAgents.mockResolvedValueOnce([{ ...base, id: 'agent-fresh', startedAt: new Date().toISOString() }]);
+ await cleanupOrphanedAgents();
+ expect(retireDeadAgent).not.toHaveBeenCalled();
+
+ spawningTasks.add('task-1');
+ getAgents.mockResolvedValueOnce([{ ...base, id: 'agent-spawning', startedAt: new Date(Date.now() - 120000).toISOString() }]);
+ await cleanupOrphanedAgents();
+ spawningTasks.delete('task-1');
+ expect(retireDeadAgent).not.toHaveBeenCalled();
+
+ getAgents.mockResolvedValueOnce([{ ...base, id: 'agent-old', startedAt: new Date(Date.now() - 120000).toISOString() }]);
+ await cleanupOrphanedAgents();
+ expect(retireDeadAgent).toHaveBeenCalledWith(expect.objectContaining({ agent: expect.objectContaining({ id: 'agent-old' }) }));
+ });
+
it('reaps a durable running record whose runner listing is stale', async () => {
getAgents.mockResolvedValueOnce([{
id: 'agent-stale',
@@ -1814,7 +1836,7 @@ describe('orphan retries resume what the dead run left behind', () => {
it('hands retireDeadAgent the orphaned exit code, duration and category for the dead run', async () => {
getAgents.mockResolvedValue([{
...deadAgent,
- startedAt: new Date(Date.now() - 1000).toISOString(),
+ startedAt: new Date(Date.now() - 60000).toISOString(),
metadata: { ...deadMetadata, runId: 'run-orphan' },
output: [{ line: 'last buffered line' }],
}]);