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: close orphaned agent run records (#3211)

[._.]/ Adam Eivybec60c036834
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 42851a4281..c9dd9b440f 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -18,6 +18,7 @@
- **[issue-3193] OpenCode agents now run in the app you selected, not the PortOS folder** — even with a correct Repository Path, agents on an OpenCode provider wrote their files into the PortOS directory and reported the PortOS path as their working folder. OpenCode decides where it is by reading an environment variable that describes the folder PortOS itself was started in, rather than the folder it was actually handed, so the workspace you picked was quietly ignored — only on OpenCode, which is why Codex, Claude Code, and Gemini looked fine. PortOS now sets that variable to the real working directory everywhere it starts an agent, a provider run, a TUI session, or a terminal. Troubleshooting steps for telling this apart from a mistyped Repository Path are in `docs/TROUBLESHOOTING.md`.
- **[issue-3180] Agent terminals on Windows get a working environment** — the environment filter for agent shell sessions was written for macOS/Linux and dropped variables Windows needs, including `Path` itself (Windows spells it mixed-case, which the filter didn't match), plus `SystemRoot`, `ComSpec`, `TEMP`, and the per-user `APPDATA` folders where the coding CLIs keep their configuration and credentials. Windows sessions now keep those while still withholding API keys and tokens.
- **[issue-3202] Restarting PortOS no longer marks a running agent "completed" or burns its retry budget** — a restart kills every agent PortOS owns, and the terminal-based ones reported that as a clean finish. The task was recorded as done with nothing but two startup lines to show for it, and the folder holding its work was deleted on the way out. When the task did come back, the restart was counted against it as a failure: three routine restarts were enough to block the task outright, and two in a row left it sitting in a 30-minute cooldown. PortOS now recognizes that it was the one that pulled the plug. An agent cut short by a restart — terminal-based or headless — is recorded as interrupted rather than finished, its working folder is left untouched, and the task returns to the queue immediately, resuming from what the interrupted run left behind with no retry charged and no cooldown. An agent that had already reported its results still completes normally, one you terminated yourself is still recorded as terminated, and agents that genuinely fail on their own are unaffected. Agents still stop when PortOS restarts; keeping them running across one is separate work.
+- **[issue-3211] Orphaned agents now close their run history during recovery** — a process that disappeared before normal completion left its run permanently unfinished, with no end time, outcome, transcript size, or usage reconciliation. The recovery sweep now closes that run exactly once before requeuing the task, records PortOS-restart interruptions separately from ordinary failures, and safely handles older agents or missing run data.
- **A brief internet outage no longer kills a working CoS agent.** When the machine lost its connection, a running agent's terminal went quiet — it couldn't reach the model — and after a few minutes the idle watchdog mistook that silence for a hung or finished agent and reaped it, throwing away in-progress work. PortOS now checks whether the machine is actually online before reaping an idle agent: while the connection is down, the reap is deferred and the agent is left alone to resume the moment the network returns (with a short grace so it isn't reaped in the instant between reconnecting and picking back up). Genuinely stuck agents on a healthy connection are still reaped on the same schedule as before, and the long absolute run-time ceiling still bounds an agent kept alive through a very long outage.
- **An agent killed by a server restart now picks up where it left off instead of starting over.** Restarting PortOS kills every running agent mid-edit, and the task went back in the queue for a brand-new agent that built a fresh worktree from `main` — so hours of in-progress work sat on disk, untouched, while the replacement redid it from scratch. PortOS now records what the interrupted run left behind and hands the retry its actual working directory: its commits, its uncommitted edits, and its untracked files, exactly as they were. The retry is told up front that it's continuing someone else's run and to check `git status`, the commit log, and whether a PR was already opened or merged before writing any code. Work that already landed is still never resumed onto, and if the leftover folder can't be handed over for any reason the retry starts clean rather than failing to start.
## Image generation
diff --git a/server/services/agentManagement.js b/server/services/agentManagement.js
index 2b429600e5..393bf470b1 100644
--- a/server/services/agentManagement.js
+++ b/server/services/agentManagement.js
@@ -5,6 +5,7 @@
* and orphaned task retry logic.
*/
+import { join } from 'path';
import { ServerError } from '../lib/errorHandler.js';
import { emitLog } from './cosEvents.js';
import { completeAgent, updateAgent } from './cosAgents.js';
@@ -21,9 +22,9 @@ import { activeAgents, runnerAgents, userTerminatedAgents, pausedAgents, useRunn
import { cleanupAgentWorktree, resolveTaskResumePatch } from './agentWorktreeCleanup.js';
import { syncRunnerAgents } from './agentRunnerSync.js';
import { flushRunnerOutputBatcher } from './agentRunnerOutputBatchers.js';
-import { checkForTaskCommit } from './agentRunTracking.js';
+import { checkForTaskCommit, completeAgentRun } from './agentRunTracking.js';
import { dispatchRecoveredTaskOutputHook } from './agentFinalization.js';
-import { PATHS } from '../lib/fileUtils.js';
+import { PATHS, tryReadFile } from '../lib/fileUtils.js';
import { readHostShutdownMarker, clearHostShutdownMarker, HOST_SHUTDOWN_REASON } from '../lib/hostShutdown.js';
import { killProcessTree } from '../lib/bufferedSpawn.js';
import { release } from './executionLanes.js';
@@ -612,6 +613,9 @@ export async function cleanupOrphanedAgents() {
}
const interrupted = interruptedByRestart.has(agent.id);
+ const errorMessage = interrupted
+ ? 'Agent was interrupted by a PortOS server restart'
+ : 'Agent process terminated unexpectedly';
console.log(interrupted
? `🛑 Recovering agent ${agent.id} interrupted by a PortOS restart (PID ${agent.pid || 'unknown'} not running)`
: `🧹 Cleaning up orphaned agent ${agent.id} (PID ${agent.pid || 'unknown'} not running)`);
@@ -622,11 +626,24 @@ export async function cleanupOrphanedAgents() {
success: false,
workspacePath: agent.metadata?.workspacePath || null,
});
+ if (agent.metadata?.runId) {
+ const bufferedOutput = Array.isArray(agent.output)
+ ? agent.output.map((entry) => typeof entry === 'string' ? entry : entry?.line).filter(Boolean).join('\n')
+ : '';
+ const output = await tryReadFile(join(PATHS.cosAgents, agent.id, 'output.txt')) ?? bufferedOutput;
+ const startedAt = Date.parse(agent.startedAt);
+ const duration = Number.isFinite(startedAt) ? Math.max(0, Date.now() - startedAt) : 0;
+ // Close the run BEFORE the agent record. If the run write fails, the
+ // agent remains eligible for the next sweep; if the later agent write
+ // fails, completeAgentRun's endTime guard makes this retry harmless.
+ await completeAgentRun(agent.metadata.runId, output, interrupted ? 143 : 1, duration, {
+ message: errorMessage,
+ category: interrupted ? 'interrupted' : 'orphaned',
+ });
+ }
await markComplete(agent.id, {
success: false,
- error: interrupted
- ? 'Agent was interrupted by a PortOS server restart'
- : 'Agent process terminated unexpectedly',
+ error: errorMessage,
orphaned: true,
// Post-mortem telemetry on the agent record (nothing reads it yet —
// the human-visible distinction is the `error` string above). Worth
diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.js
index 09645f1480..3cf439a39c 100644
--- a/server/services/agentManagement.test.js
+++ b/server/services/agentManagement.test.js
@@ -57,7 +57,8 @@ vi.mock('./cosEvents.js', () => ({
}));
vi.mock('./agentRunTracking.js', () => ({
- checkForTaskCommit: vi.fn().mockResolvedValue(false)
+ checkForTaskCommit: vi.fn().mockResolvedValue(false),
+ completeAgentRun: vi.fn().mockResolvedValue(undefined),
}));
// Stub other transitive imports we don't exercise in handleOrphanedTask.
@@ -107,6 +108,7 @@ import { pauseAgentViaRunner } from './cosRunnerClient.js';
import * as shellService from './shell.js';
import { readHostShutdownMarker, clearHostShutdownMarker } from '../lib/hostShutdown.js';
import { completeAgent as markAgentComplete } from './cos.js';
+import { completeAgentRun } from './agentRunTracking.js';
import { activeAgents, runnerAgents, pausedAgents } from './agentState.js';
describe('settleOrphanedCreativeDirectorRun — reap a dead CD agent run (#2705)', () => {
@@ -850,6 +852,35 @@ describe('orphan retries resume what the dead run left behind', () => {
expect(resolveTaskResumePatch).not.toHaveBeenCalled();
});
+ it('closes the orphaned run before completing the agent record', async () => {
+ getAgents.mockResolvedValue([{
+ ...deadAgent,
+ startedAt: new Date(Date.now() - 1000).toISOString(),
+ metadata: { ...deadMetadata, runId: 'run-orphan' },
+ output: [{ line: 'last buffered line' }],
+ }]);
+ const order = [];
+ completeAgentRun.mockImplementation(() => { order.push('run'); });
+ markAgentComplete.mockImplementation(() => { order.push('agent'); });
+
+ await cleanupOrphanedAgents();
+
+ expect(completeAgentRun).toHaveBeenCalledWith(
+ 'run-orphan',
+ 'last buffered line',
+ 1,
+ expect.any(Number),
+ { message: 'Agent process terminated unexpectedly', category: 'orphaned' },
+ );
+ expect(order.slice(0, 2)).toEqual(['run', 'agent']);
+ });
+
+ it('skips run completion for legacy agents without a runId', async () => {
+ await cleanupOrphanedAgents();
+
+ expect(completeAgentRun).not.toHaveBeenCalled();
+ });
+
// A caller that doesn't know which agent died (resetOrphanedTasks on an archived
// agent) still requeues — it just starts clean.
it('requeues without a pointer when no agent metadata is available', async () => {
@@ -1056,6 +1087,10 @@ describe('host-restart interruptions are not charged orphan-retry budget (#3202)
it('flags the interruption on the agent record and consumes the marker', async () => {
getTaskById.mockResolvedValue({ id: 'task-1', taskType: 'user', status: 'in_progress', metadata: {} });
+ getAgents.mockResolvedValue([{
+ ...deadAgent,
+ metadata: { ...deadMetadata, runId: 'run-interrupted' },
+ }]);
readHostShutdownMarker.mockResolvedValue({ at: null, signal: 'SIGTERM', agentIds: ['agent-dead'] });
await cleanupOrphanedAgents();
@@ -1065,6 +1100,13 @@ describe('host-restart interruptions are not charged orphan-retry budget (#3202)
interruptedByRestart: true,
error: expect.stringContaining('restart'),
}));
+ expect(completeAgentRun).toHaveBeenCalledWith(
+ 'run-interrupted',
+ '',
+ 143,
+ 0,
+ { message: expect.stringContaining('restart'), category: 'interrupted' },
+ );
expect(clearHostShutdownMarker).toHaveBeenCalled();
});
diff --git a/server/services/agentRunTracking.js b/server/services/agentRunTracking.js
index 909ab2fcd8..7a834f1208 100644
--- a/server/services/agentRunTracking.js
+++ b/server/services/agentRunTracking.js
@@ -109,6 +109,7 @@ export async function completeAgentRun(runId, output, exitCode, duration, errorA
const metadata = await readJSONFile(metaPath, null);
if (!metadata) return;
+ if (metadata.endTime) return;
metadata.endTime = new Date().toISOString();
metadata.duration = duration;
diff --git a/server/services/agentRunTracking.test.js b/server/services/agentRunTracking.test.js
index 0e1d099c0d..bf5ed1ecb4 100644
--- a/server/services/agentRunTracking.test.js
+++ b/server/services/agentRunTracking.test.js
@@ -1,4 +1,4 @@
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
import { extractErrorFromOutput } from './agentRunTracking.js';
// extractErrorFromOutput is the real home of the exit-code → message mapping
@@ -63,3 +63,46 @@ describe('extractErrorFromOutput', () => {
});
});
});
+
+describe('completeAgentRun idempotency', () => {
+ it('does not rewrite an already-closed run', async () => {
+ vi.resetModules();
+ const atomicWrite = vi.fn();
+ const writeFile = vi.fn();
+ vi.doMock('../lib/fileUtils.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ readJSONFile: vi.fn().mockResolvedValue({ id: 'run-closed', endTime: '2026-07-29T00:00:00.000Z' }),
+ atomicWrite,
+ }));
+ vi.doMock('fs/promises', async (importOriginal) => ({
+ ...(await importOriginal()),
+ writeFile,
+ }));
+ const { completeAgentRun } = await import('./agentRunTracking.js');
+
+ await completeAgentRun('run-closed', 'output', 1, 100, { message: 'ignored' });
+
+ expect(atomicWrite).not.toHaveBeenCalled();
+ expect(writeFile).not.toHaveBeenCalled();
+ });
+
+ it('skips a run whose metadata directory is missing', async () => {
+ vi.resetModules();
+ const atomicWrite = vi.fn();
+ const writeFile = vi.fn();
+ vi.doMock('../lib/fileUtils.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ readJSONFile: vi.fn().mockResolvedValue(null),
+ atomicWrite,
+ }));
+ vi.doMock('fs/promises', async (importOriginal) => ({
+ ...(await importOriginal()),
+ writeFile,
+ }));
+ const { completeAgentRun } = await import('./agentRunTracking.js');
+
+ await expect(completeAgentRun('run-missing', '', 1, 0)).resolves.toBeUndefined();
+ expect(atomicWrite).not.toHaveBeenCalled();
+ expect(writeFile).not.toHaveBeenCalled();
+ });
+});