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: recover a restart survivor's run id so its run closes and its spend is billed (#3244)

[._.]/ Adam Eivy94f6955dceb1
diff --git a/server/services/agentRunnerSync.js b/server/services/agentRunnerSync.js
index 5ef12c3fda..53beee8052 100644
--- a/server/services/agentRunnerSync.js
+++ b/server/services/agentRunnerSync.js
@@ -14,6 +14,7 @@
import { connectTuiSessionViaRunner, getActiveAgentsFromRunner } from './cosRunnerClient.js';
import { isInternalTaskId } from '../lib/taskParser.js';
import { runnerAgents } from './agentState.js';
+import { getAgent } from './cosAgents.js';
import * as shellService from './shell.js';
/**
@@ -56,14 +57,29 @@ export async function syncRunnerAgents() {
const task = taskMap.get(agent.taskId);
const inferredType = isInternalTaskId(agent.taskId) ? 'internal' : 'user';
+ // Recover the run id from the PERSISTED agent record (#3244). The runner's
+ // /agents response describes the live process and carries no `metadata`,
+ // but `spawnViaRunner` wrote `runId` into the agent record before handing
+ // off, so it is still on disk — `agentManagement.js` reads it the same way
+ // on its orphan path. Dropping it here left the survivor's run permanently
+ // open (`completeAgentRun` returns early on a null id), so the Runs list
+ // showed it running forever and `recordCompletedRunUsage` never fired —
+ // silently exempting the longest-lived runs in the system from all cost
+ // accounting. Survivors are the normal case since #3202 made TUI agents
+ // durable, so this cannot stay a best-effort null.
+ const persisted = await getAgent(agent.id).catch(() => null);
+ const recoveredRunId = persisted?.metadata?.runId || null;
runnerAgents.set(agent.id, {
taskId: agent.taskId,
task: task || { id: agent.taskId, taskType: inferredType, description: 'Recovered from runner' },
- runId: null, // Run tracking may be lost on restart
- model: null,
+ runId: recoveredRunId,
+ model: persisted?.metadata?.model || null,
hasStartedWorking: true,
startedAt: agent.startedAt
});
+ if (!recoveredRunId) {
+ console.warn(`⚠️ Recovered agent ${agent.id} has no run id on record — its run stays open and unbilled`);
+ }
if (agent.kind === 'tui' && agent.sessionId && !shellService.getSession(agent.sessionId)) {
const session = connectTuiSessionViaRunner(agent);
shellService.registerExternalSession(agent.sessionId, session.ptyProcess, {
diff --git a/server/services/agentRunnerSync.test.js b/server/services/agentRunnerSync.test.js
index 8a1b55b88c..31d0e72d7d 100644
--- a/server/services/agentRunnerSync.test.js
+++ b/server/services/agentRunnerSync.test.js
@@ -30,8 +30,13 @@ vi.mock('./cos.js', () => ({
}),
}));
+vi.mock('./cosAgents.js', () => ({
+ getAgent: vi.fn(),
+}));
+
import { connectTuiSessionViaRunner, getActiveAgentsFromRunner } from './cosRunnerClient.js';
import * as shellService from './shell.js';
+import { getAgent } from './cosAgents.js';
import { runnerAgents } from './agentState.js';
import { syncRunnerAgents } from './agentRunnerSync.js';
@@ -40,6 +45,7 @@ describe('syncRunnerAgents runner-owned TUI recovery', () => {
vi.clearAllMocks();
runnerAgents.clear();
vi.mocked(shellService.getSession).mockReturnValue(null);
+ vi.mocked(getAgent).mockResolvedValue(null);
});
it('reconciles one surviving TUI and restores its attachable shell relay', async () => {
@@ -71,4 +77,40 @@ describe('syncRunnerAgents runner-owned TUI recovery', () => {
}),
);
});
+
+ // #3244. The runner's /agents response describes the live process and carries
+ // no `metadata`, so the run id has to come off the persisted agent record.
+ // Dropping it left the survivor's run open forever and unbilled, because
+ // `completeAgentRun` returns early on a null id — and survivors are the normal
+ // case since #3202 made TUI agents durable.
+ it('recovers the run id and model from the persisted agent record', async () => {
+ vi.mocked(getAgent).mockResolvedValue({
+ id: 'agent-1',
+ metadata: { runId: 'run-abc123', model: 'claude-opus-5' },
+ });
+ vi.mocked(getActiveAgentsFromRunner).mockResolvedValue([{
+ id: 'agent-1', taskId: 'task-1', pid: 1234, startedAt: Date.now(), kind: 'cli',
+ }]);
+
+ await expect(syncRunnerAgents()).resolves.toBe(1);
+
+ expect(getAgent).toHaveBeenCalledWith('agent-1');
+ expect(runnerAgents.get('agent-1')).toMatchObject({
+ runId: 'run-abc123',
+ model: 'claude-opus-5',
+ });
+ });
+
+ it('recovers with a null run id rather than throwing when the record is gone', async () => {
+ // A record that cannot be read must not take the whole recovery sweep down
+ // with it — the surviving agent still needs re-adopting so its completion
+ // event lands. The run stays open, which the warning line says out loud.
+ vi.mocked(getAgent).mockRejectedValue(new Error('metadata.json unreadable'));
+ vi.mocked(getActiveAgentsFromRunner).mockResolvedValue([{
+ id: 'agent-2', taskId: 'task-1', pid: 99, startedAt: Date.now(), kind: 'cli',
+ }]);
+
+ await expect(syncRunnerAgents()).resolves.toBe(1);
+ expect(runnerAgents.get('agent-2')).toMatchObject({ runId: null });
+ });
});
diff --git a/server/services/bootstrap.js b/server/services/bootstrap.js
index 5a3ee3e0df..8f2d655aa5 100644
--- a/server/services/bootstrap.js
+++ b/server/services/bootstrap.js
@@ -878,8 +878,14 @@ export const registerShutdownHandlers = ({ io, httpServer, localHttpServer }) =>
// tell "PortOS was restarted out from under a healthy agent" apart from "the
// agent's own process died" and skip the retry-budget/cooldown penalty for a
// fault the agent didn't cause (#3202). Only `activeAgents` — the ones whose
- // child processes live in THIS process's tree — belong here; runner-mode
- // agents are owned by portos-cos and survive this restart untouched.
+ // child processes live in THIS process's tree — belong here; agents the CoS
+ // runner owns survive this restart untouched and are re-adopted by
+ // `syncRunnerAgents` on the next boot.
+ //
+ // Note `activeAgents` is NOT "direct-spawn only": runner-launched TUI agents
+ // register there too (`agentTuiSpawning.js`, both launch modes). The
+ // distinction that matters here is process ownership, not spawn mode — do
+ // not re-derive the snapshot from "was this spawned via the runner".
//
// Started here so the agent snapshot is taken before anything can await, but
// awaited just before exit so a stalled filesystem spends none of the graceful