fix(server): give restored agent runtimes a fresh idle cleanup window (#8857)

When an archived or persisted agent is restored via resumeAgentFromPersistence, its managed record intentionally preserves the historical updatedAt timestamp so sidebar ordering and activity timestamps are not artificially bumped just by viewing or reopening the agent.

However, getRuntimeCleanupCandidates() previously used updatedAt.getTime() directly as lastActivityAt for idle runtime garbage collection. For any restored agent whose last conversation turn was older than the idle runtime threshold (default 60 minutes), the next periodic idle cleanup sweep (every 60s) immediately saw the newly spawned runtime as idle for >60m and terminated its live process.

Record openedAt on the per-session runtimeCleanupIdentities entry when a session is registered, and compute lastActivityAt in getRuntimeCleanupCandidates() as Math.max(updatedAt.getTime(), identity.openedAt) so a newly restored runtime gets a full idle window without mutating the agent's persisted updatedAt.
This commit is contained in:
FDKevin authored and GitHub committed 2026-11-14 15:29:42 +00:00
1 parent 42c7b7f886
commit a730ad1924
2 files changed
+56 -16

No files matched your search

@@ -13457,7 +13457,20 @@ function idleCleanupHarness() {
const storage = new AgentStorage(join(workdir, "agents"), logger);
const commands: AgentPromptInput[] = [];
const prompts: AgentPromptInput[] = [];
const sessions: AgentSession[] = [];
const probes: Array<(() => Promise<boolean>) | undefined> = [];
const closeEntered = deferred<void>();
let closeGate: Promise<void> | undefined;
let closes = 0;
const recordPrompts = (session: AgentSession) => {
const index = sessions.length;
session.canStopRuntime = async () => probes[index]?.() ?? false;
session.close = async () => {
closes++;
closeEntered.resolve();
await closeGate;
};
sessions.push(session);
session.tryHandleOutOfBand = (prompt) =>
prompt === "/maintenance"
? {
@@ -13473,11 +13486,6 @@ function idleCleanupHarness() {
};
return session;
};
const sessions: AgentSession[] = [];
const probes: Array<(() => Promise<boolean>) | undefined> = [];
const closeEntered = deferred<void>();
let closeGate: Promise<void> | undefined;
let closes = 0;
const client = new (class extends TestAgentClient {
override async resumeSession(
handle: AgentPersistenceHandle,
@@ -13488,15 +13496,7 @@ function idleCleanupHarness() {
return recordPrompts(session);
}
override async createSession(config: AgentSessionConfig): Promise<AgentSession> {
const index = sessions.length;
const session: AgentSession = await super.createSession(config);
session.canStopRuntime = async () => probes[index]?.() ?? false;
session.close = async () => {
closes++;
closeEntered.resolve();
await closeGate;
};
sessions.push(session);
return recordPrompts(session);
}
})();
@@ -14419,3 +14419,39 @@ test("workspace archive preserves a loaded history agent stamp and stamps cascad
rmSync(workdir, { recursive: true, force: true });
}
});
test("idle cleanup gives a newly restored runtime a fresh idle window while keeping historical updatedAt", async () => {
const h = idleCleanupHarness();
const created = await h.create();
h.probes[0] = async () => true;
h.probes[1] = async () => true;
await h.manager.closeAgent(created.id);
await h.storage.flush();
const historicalUpdatedAt = new Date(Date.now() - 180 * 60_000);
const existingRecord = await h.storage.get(created.id);
expect(existingRecord).not.toBeNull();
const staleRecord: StoredAgentRecord = {
...existingRecord!,
updatedAt: historicalUpdatedAt.toISOString(),
lastActivityAt: historicalUpdatedAt.toISOString(),
};
await h.storage.upsert(staleRecord);
await h.storage.flush();
const closesBeforeRestore = h.closes;
const restored = await h.manager.resumeAgentFromPersistence(
created.persistence!,
{ cwd: created.cwd },
created.id,
{ updatedAt: historicalUpdatedAt },
);
expect(restored.updatedAt.getTime()).toBe(historicalUpdatedAt.getTime());
// Sweeping 1 minute after restoring an old agent must NOT immediately kill the newly opened runtime.
expect((await h.sweep({ now: h.later(1) })).collected).toEqual([]);
expect(h.closes).toBe(closesBeforeRestore);
// Sweeping 61 minutes after restoration collects the runtime as expected.
expect((await h.sweep({ now: h.later(61) })).collected).toHaveLength(1);
expect(h.closes).toBe(closesBeforeRestore + 1);
});
@@ -856,7 +856,10 @@ export class AgentManager {
private readonly inFlightAgentCloses = new Map<string, Promise<void>>();
private readonly historySessions = new WeakSet<AgentSession>();
private readonly reloadedSessionCloses = new WeakMap<AgentSession, Promise<void>>();
private readonly runtimeCleanupIdentities = new WeakMap<AgentSession, object>();
private readonly runtimeCleanupIdentities = new WeakMap<
AgentSession,
{ readonly openedAt: number }
>();
private readonly collectingRuntimes = new Set<string>();
private readonly lifecycleMutationTails = new Map<string, Promise<void>>();
private readonly agentStreamCoalescer: AgentStreamCoalescer;
@@ -2068,7 +2071,7 @@ export class AgentManager {
const updatedAt = agent.updatedAt;
let identity = this.runtimeCleanupIdentities.get(agent.session);
if (!identity) {
identity = Object.freeze({});
identity = Object.freeze({ openedAt: Date.now() });
this.runtimeCleanupIdentities.set(agent.session, identity);
}
const isEligible = () =>
@@ -2081,7 +2084,7 @@ export class AgentManager {
parentAgentId: getParentAgentIdFromLabels(agent.labels) ?? undefined,
provider: agent.provider,
sessionId: agent.persistence?.sessionId ?? null,
lastActivityAt: updatedAt.getTime(),
lastActivityAt: Math.max(updatedAt.getTime(), identity.openedAt),
isEligible,
canStopRuntime: agent.session.canStopRuntime?.bind(agent.session),
closeIfEligible: async (revalidate) => {
@@ -4342,6 +4345,7 @@ export class AgentManager {
}
this.assertAcceptingAgentRegistrations();
this.runtimeCleanupIdentities.set(session, Object.freeze({ openedAt: Date.now() }));
this.agents.set(resolvedAgentId, managed);
registered = true;
// Initialize previousStatus to track transitions