Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

Cancel heartbeats when sessions are killed (#332)

Seth Kartend7fee382d27c
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.md
index 1dd9d0d663..e54cfd088b 100644
--- a/packages/coding-agent/CHANGELOG.md
+++ b/packages/coding-agent/CHANGELOG.md
@@ -7,6 +7,7 @@
- Fixed `/heartbeat` guidance to show `stop` and the `every <duration> <instruction>` interval syntax ([ENG-4484](https://linear.app/primeintellect/issue/ENG-4484/improve-heartbeat-command-syntax-guidance-in-ui)).
- Fixed login dialogs in fullscreen so sign-in URLs can be selected natively ([ENG-4480](https://linear.app/primeintellect/issue/ENG-4480/new-fullscreen-tui-makes-it-impossible-to-copy-login-url)).
- Fixed provider auth failures leaving stale credentials shown as connected in `/login` ([ENG-4491](https://linear.app/primeintellect/issue/ENG-4491/mark-provider-stale-after-repeated-401s)).
+- Fixed session-targeted heartbeat jobs staying scheduled after sessions are killed or saved sessions are deleted ([#332](https://github.com/PrimeIntellect-ai/prime-agent/pull/332)).
## [0.2.6] - 2026-07-06
diff --git a/packages/coding-agent/src/core/cron-jobs.ts b/packages/coding-agent/src/core/cron-jobs.ts
index 19506b7678..f388b75627 100644
--- a/packages/coding-agent/src/core/cron-jobs.ts
+++ b/packages/coding-agent/src/core/cron-jobs.ts
@@ -382,6 +382,30 @@ export class AgentCronJobStore {
return cancelled;
}
+ cancelJobsForSession(
+ input: { activeSessionId?: string; sessionId?: string; sessionFile?: string },
+ now = new Date(),
+ ): AgentCronJob[] {
+ const targetSessionFile = input.sessionFile ? resolve(input.sessionFile) : undefined;
+ const cancelled: AgentCronJob[] = [];
+ const jobs = this.readJobs().map((job) => {
+ const matches =
+ (input.activeSessionId !== undefined && job.activeSessionId === input.activeSessionId) ||
+ (input.sessionId !== undefined && job.sessionId === input.sessionId) ||
+ (targetSessionFile !== undefined && resolve(job.sessionFile) === targetSessionFile);
+ if (!matches || (job.status !== "active" && job.status !== "paused")) {
+ return job;
+ }
+ const cancelledJob = withoutNextRunAt({ ...job, status: "cancelled", updatedAt: now.toISOString() });
+ cancelled.push(cancelledJob);
+ return cancelledJob;
+ });
+ if (cancelled.length > 0) {
+ this.writeJobs(jobs);
+ }
+ return cancelled;
+ }
+
pauseHeartbeat(activeSessionId: string, now = new Date()): AgentCronJob | undefined {
let paused: AgentCronJob | undefined;
const current = this.getHeartbeat(activeSessionId);
diff --git a/packages/coding-agent/src/core/session-file-actions.ts b/packages/coding-agent/src/core/session-file-actions.ts
index 1f67f135c3..7bd537cb1f 100644
--- a/packages/coding-agent/src/core/session-file-actions.ts
+++ b/packages/coding-agent/src/core/session-file-actions.ts
@@ -5,6 +5,10 @@ import { basename, dirname, join } from "node:path";
export type DeleteSessionFileResult = { ok: true; method: "trash" | "unlink" } | { ok: false; error: string };
+export interface DeleteSessionFileOptions {
+ afterFileRemoved?: () => void;
+}
+
/**
* Permanently remove a session's artifact directory (kernel state snapshot, rlm
* scratch files, …), which lives at `<dirname(sessionDir)>/session-artifacts/<id>`.
@@ -56,9 +60,13 @@ async function removeSessionFile(sessionPath: string): Promise<DeleteSessionFile
* once the session file itself is gone — otherwise a failed delete would orphan a
* session whose kernel snapshot has already been destroyed.
*/
-export async function deleteSessionFile(sessionPath: string): Promise<DeleteSessionFileResult> {
+export async function deleteSessionFile(
+ sessionPath: string,
+ options: DeleteSessionFileOptions = {},
+): Promise<DeleteSessionFileResult> {
const result = await removeSessionFile(sessionPath);
if (result.ok) {
+ options.afterFileRemoved?.();
await deleteSessionArtifacts(sessionPath);
}
return result;
diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
index a329164c0e..8fa0c5219a 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
@@ -820,6 +820,40 @@ export class AgentDaemon {
}
}
+ private cancelScheduledJobsForSession(state: ActiveSessionState): void {
+ const session = state.runtime.session;
+ const target: { activeSessionId: string; sessionId?: string; sessionFile?: string } = {
+ activeSessionId: state.activeSessionId,
+ };
+ if (session?.sessionId) {
+ target.sessionId = session.sessionId;
+ }
+ if (session?.sessionFile) {
+ target.sessionFile = session.sessionFile;
+ }
+ const cancelled = this.cronStore.cancelJobsForSession(target);
+ for (const job of cancelled) {
+ this.removeQueuedHeartbeatFollowUp(state, job);
+ }
+ if (cancelled.length > 0) {
+ this.cronScheduler.wake();
+ }
+ }
+
+ private cancelScheduledJobsForSessionFile(sessionFile: string): void {
+ const cancelled = this.cronStore.cancelJobsForSession({ sessionFile });
+ if (cancelled.length > 0) {
+ this.cronScheduler.wake();
+ }
+ }
+
+ private deleteSavedSessionFile(
+ sessionPath: string,
+ options?: Parameters<typeof deleteSessionFile>[1],
+ ): ReturnType<typeof deleteSessionFile> {
+ return deleteSessionFile(sessionPath, options);
+ }
+
private removeQueuedHeartbeatFollowUp(state: ActiveSessionState, job: AgentCronJob): void {
if (!isHeartbeatCronJob(job)) {
return;
@@ -1302,7 +1336,12 @@ export class AgentDaemon {
if (this.findActiveSessionByFile(command.sessionPath)) {
throw new Error("Cannot delete the currently active session");
}
- return success(command.id, "delete_saved_session", await deleteSessionFile(command.sessionPath));
+ const result = await this.deleteSavedSessionFile(command.sessionPath, {
+ afterFileRemoved: () => {
+ this.cancelScheduledJobsForSessionFile(command.sessionPath);
+ },
+ });
+ return success(command.id, "delete_saved_session", result);
}
case "prompt": {
@@ -2196,7 +2235,11 @@ export class AgentDaemon {
if (!this.sessions.has(state.activeSessionId)) {
return;
}
- this.cancelSubagentRlmHeartbeats(state);
+ if (reason === "killed") {
+ this.cancelScheduledJobsForSession(state);
+ } else {
+ this.cancelSubagentRlmHeartbeats(state);
+ }
// Abort in-flight status work before any await/dispose so it can't write
// agent_status to a session being torn down.
this.summarizer.forget(state.activeSessionId);
diff --git a/packages/coding-agent/test/cron-jobs.test.ts b/packages/coding-agent/test/cron-jobs.test.ts
index 78765dd080..525e9b7413 100644
--- a/packages/coding-agent/test/cron-jobs.test.ts
+++ b/packages/coding-agent/test/cron-jobs.test.ts
@@ -462,6 +462,62 @@ describe("AgentCronJobStore", () => {
expect(store.listRlmHeartbeats("top-level-1")[0]).toMatchObject({ status: "active" });
});
+ it("cancels active and paused jobs for a removed session", () => {
+ const store = new AgentCronJobStore(makeStorePath(tempDirs));
+ const sessionFile = "/tmp/session-to-remove.jsonl";
+ const cron = store.create({
+ activeSessionId: "active-1",
+ sessionId: "session-1",
+ sessionFile,
+ cwd: "/tmp/project",
+ scheduleText: "in 1h",
+ prompt: "check the long run",
+ now: start,
+ });
+ const heartbeat = store.createHeartbeat({
+ activeSessionId: "active-1",
+ sessionId: "session-1",
+ sessionFile,
+ cwd: "/tmp/project",
+ scheduleText: "every 5m",
+ prompt: "continue the session",
+ now: start,
+ });
+ store.pauseHeartbeat("active-1", new Date("2026-01-01T12:35:00.000Z"));
+ const rlmHeartbeat = store.createRlmHeartbeat({
+ activeSessionId: "active-1",
+ sessionId: "session-1",
+ sessionFile,
+ cwd: "/tmp/project",
+ runtimeKind: "top-level",
+ label: "rlm",
+ scheduleText: "every 10m",
+ prompt: "continue internal work",
+ now: start,
+ });
+ const unrelated = store.create({
+ activeSessionId: "active-2",
+ sessionId: "session-2",
+ sessionFile: "/tmp/other-session.jsonl",
+ cwd: "/tmp/project",
+ scheduleText: "in 2h",
+ prompt: "keep other session alive",
+ now: start,
+ });
+
+ const cancelled = store.cancelJobsForSession({ sessionId: "session-1" }, new Date("2026-01-01T12:40:00.000Z"));
+
+ expect(cancelled.map((job) => job.id)).toEqual(expect.arrayContaining([cron.id, heartbeat.id, rlmHeartbeat.id]));
+ for (const id of [cron.id, heartbeat.id, rlmHeartbeat.id]) {
+ expect(store.list().find((job) => job.id === id)).toMatchObject({
+ status: "cancelled",
+ updatedAt: "2026-01-01T12:40:00.000Z",
+ });
+ expect(store.list().find((job) => job.id === id)).not.toHaveProperty("nextRunAt");
+ }
+ expect(store.list().find((job) => job.id === unrelated.id)).toMatchObject({ status: "active" });
+ });
+
it("returns undefined when updating inactive RLM heartbeats", () => {
const store = new AgentCronJobStore(makeStorePath(tempDirs));
const rlmHeartbeat = store.createRlmHeartbeat({
diff --git a/packages/coding-agent/test/daemon-mode.test.ts b/packages/coding-agent/test/daemon-mode.test.ts
index a7a0536e08..0a01acb643 100644
--- a/packages/coding-agent/test/daemon-mode.test.ts
+++ b/packages/coding-agent/test/daemon-mode.test.ts
@@ -2376,6 +2376,217 @@ describe("daemon mode helpers", () => {
}
});
+ it("cancels scheduled jobs when a live session is killed", async () => {
+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-kill-cron-"));
+ try {
+ const daemon = new AgentDaemon(join(tempDir, "daemon.sock"), {
+ defaultSessionConfig: {
+ agentDir: tempDir,
+ cwd: tempDir,
+ },
+ createRuntime: async () => {
+ throw new Error("unexpected runtime creation");
+ },
+ });
+ const sessionFile = join(tempDir, "session.jsonl");
+ const removeQueuedFollowUp = vi.fn();
+ const abort = vi.fn(async () => {});
+ const dispose = vi.fn(async () => {});
+ const appendSessionState = vi.fn();
+ const state = makeState("active-1") as ActiveSessionState;
+ state.extensionUiRequests = new Map();
+ state.runtime = {
+ metadata: { kind: "top-level", createdAt: 1 },
+ cwd: tempDir,
+ dispose,
+ session: {
+ sessionId: "session-1",
+ sessionFile,
+ messages: ["user message"],
+ sessionManager: {
+ appendSessionState,
+ hasUserContent: () => true,
+ },
+ abort,
+ removeQueuedFollowUp,
+ },
+ } as never;
+ const internals = daemon as unknown as {
+ cronStore: AgentCronJobStore;
+ sessions: Map<string, ActiveSessionState>;
+ handleCommand(client: DaemonSocketClient, command: DaemonCommand): Promise<unknown>;
+ };
+ internals.sessions.set(state.activeSessionId, state);
+ const cron = internals.cronStore.create({
+ activeSessionId: state.activeSessionId,
+ sessionId: "session-1",
+ sessionFile,
+ cwd: tempDir,
+ scheduleText: "in 1h",
+ prompt: "check long run",
+ now: new Date("2026-01-01T12:00:00.000Z"),
+ });
+ const heartbeat = internals.cronStore.createHeartbeat({
+ activeSessionId: state.activeSessionId,
+ sessionId: "session-1",
+ sessionFile,
+ cwd: tempDir,
+ scheduleText: "every 5m",
+ prompt: "keep working",
+ now: new Date("2026-01-01T12:00:00.000Z"),
+ });
+ internals.cronStore.pauseHeartbeat(state.activeSessionId, new Date("2026-01-01T12:01:00.000Z"));
+ const rlmHeartbeat = internals.cronStore.createRlmHeartbeat({
+ activeSessionId: state.activeSessionId,
+ sessionId: "session-1",
+ sessionFile,
+ cwd: tempDir,
+ runtimeKind: "top-level",
+ scheduleText: "every 10m",
+ prompt: "keep internal work moving",
+ now: new Date("2026-01-01T12:00:00.000Z"),
+ });
+
+ await internals.handleCommand(makeClient("client-1", state.activeSessionId), {
+ id: "command-1",
+ type: "kill",
+ activeSessionId: state.activeSessionId,
+ });
+
+ for (const id of [cron.id, heartbeat.id, rlmHeartbeat.id]) {
+ expect(internals.cronStore.list().find((job) => job.id === id)).toMatchObject({ status: "cancelled" });
+ expect(internals.cronStore.list().find((job) => job.id === id)).not.toHaveProperty("nextRunAt");
+ }
+ expect(removeQueuedFollowUp).toHaveBeenCalledWith(`heartbeat:${heartbeat.id}`);
+ expect(removeQueuedFollowUp).toHaveBeenCalledWith(`heartbeat:${rlmHeartbeat.id}`);
+ expect(abort).toHaveBeenCalledOnce();
+ expect(dispose).toHaveBeenCalledOnce();
+ expect(appendSessionState).toHaveBeenCalledWith({ status: "archived" });
+ } finally {
+ rmSync(tempDir, { recursive: true, force: true });
+ }
+ });
+
+ it("cancels scheduled jobs when a saved session is deleted", async () => {
+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-delete-cron-"));
+ try {
+ const daemon = new AgentDaemon(join(tempDir, "daemon.sock"), {
+ defaultSessionConfig: {
+ agentDir: tempDir,
+ cwd: tempDir,
+ },
+ createRuntime: async () => {
+ throw new Error("unexpected runtime creation");
+ },
+ });
+ const internals = daemon as unknown as {
+ cronStore: AgentCronJobStore;
+ handleCommand(client: DaemonSocketClient, command: DaemonCommand): Promise<unknown>;
+ };
+ const sessionFile = join(tempDir, "saved-session.jsonl");
+ const otherSessionFile = join(tempDir, "other-session.jsonl");
+ const cron = internals.cronStore.create({
+ activeSessionId: "active-1",
+ sessionId: "session-1",
+ sessionFile,
+ cwd: tempDir,
+ scheduleText: "in 1h",
+ prompt: "check saved session",
+ now: new Date("2026-01-01T12:00:00.000Z"),
+ });
+ const heartbeat = internals.cronStore.createHeartbeat({
+ activeSessionId: "active-1",
+ sessionId: "session-1",
+ sessionFile,
+ cwd: tempDir,
+ scheduleText: "every 5m",
+ prompt: "keep saved session alive",
+ now: new Date("2026-01-01T12:00:00.000Z"),
+ });
+ const unrelated = internals.cronStore.create({
+ activeSessionId: "active-2",
+ sessionId: "session-2",
+ sessionFile: otherSessionFile,
+ cwd: tempDir,
+ scheduleText: "in 2h",
+ prompt: "keep other session alive",
+ now: new Date("2026-01-01T12:00:00.000Z"),
+ });
+
+ await internals.handleCommand(makeClient("client-1", "active-1"), {
+ id: "command-1",
+ type: "delete_saved_session",
+ sessionPath: sessionFile,
+ });
+
+ expect(internals.cronStore.list().find((job) => job.id === cron.id)).toMatchObject({ status: "cancelled" });
+ expect(internals.cronStore.list().find((job) => job.id === heartbeat.id)).toMatchObject({
+ status: "cancelled",
+ });
+ expect(internals.cronStore.list().find((job) => job.id === unrelated.id)).toMatchObject({ status: "active" });
+ } finally {
+ rmSync(tempDir, { recursive: true, force: true });
+ }
+ });
+
+ it("keeps saved session jobs when file deletion fails", async () => {
+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-delete-cron-fail-"));
+ try {
+ const daemon = new AgentDaemon(join(tempDir, "daemon.sock"), {
+ defaultSessionConfig: {
+ agentDir: tempDir,
+ cwd: tempDir,
+ },
+ createRuntime: async () => {
+ throw new Error("unexpected runtime creation");
+ },
+ });
+ const deleteSavedSessionFile = vi.fn(async () => ({ ok: false, error: "delete failed" }) as const);
+ const internals = daemon as unknown as {
+ cronStore: AgentCronJobStore;
+ deleteSavedSessionFile: typeof deleteSavedSessionFile;
+ handleCommand(client: DaemonSocketClient, command: DaemonCommand): Promise<unknown>;
+ };
+ internals.deleteSavedSessionFile = deleteSavedSessionFile;
+ const sessionFile = join(tempDir, "saved-session.jsonl");
+ const cron = internals.cronStore.create({
+ activeSessionId: "active-1",
+ sessionId: "session-1",
+ sessionFile,
+ cwd: tempDir,
+ scheduleText: "in 1h",
+ prompt: "check saved session",
+ now: new Date("2026-01-01T12:00:00.000Z"),
+ });
+ const heartbeat = internals.cronStore.createHeartbeat({
+ activeSessionId: "active-1",
+ sessionId: "session-1",
+ sessionFile,
+ cwd: tempDir,
+ scheduleText: "every 5m",
+ prompt: "keep saved session alive",
+ now: new Date("2026-01-01T12:00:00.000Z"),
+ });
+
+ const response = await internals.handleCommand(makeClient("client-1", "active-1"), {
+ id: "command-1",
+ type: "delete_saved_session",
+ sessionPath: sessionFile,
+ });
+
+ expect(response).toMatchObject({ data: { ok: false, error: "delete failed" } });
+ expect(deleteSavedSessionFile).toHaveBeenCalledWith(sessionFile, {
+ afterFileRemoved: expect.any(Function),
+ });
+ expect(internals.cronStore.list().find((job) => job.id === cron.id)).toMatchObject({ status: "active" });
+ expect(internals.cronStore.list().find((job) => job.id === heartbeat.id)).toMatchObject({
+ status: "active",
+ });
+ } finally {
+ rmSync(tempDir, { recursive: true, force: true });
+ }
+ });
+
it("preserves omitted global scope on daemon refine commands", async () => {
const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {
defaultSessionConfig: {
diff --git a/packages/coding-agent/test/session-artifacts-delete.test.ts b/packages/coding-agent/test/session-artifacts-delete.test.ts
index 43d5da73bb..10be78ac3f 100644
--- a/packages/coding-agent/test/session-artifacts-delete.test.ts
+++ b/packages/coding-agent/test/session-artifacts-delete.test.ts
@@ -35,6 +35,32 @@ describe("deleteSessionFile removes the session artifact directory", () => {
expect(existsSync(sessionPath)).toBe(false);
});
+ it("runs the file-removed callback before deleting artifacts", async () => {
+ const sessionId = "session-with-callback";
+ const sessionsDir = join(root, "sessions");
+ mkdirSync(sessionsDir, { recursive: true });
+ const sessionPath = join(sessionsDir, `${sessionId}.jsonl`);
+ writeFileSync(sessionPath, '{"type":"session"}\n');
+
+ const artifactDir = join(root, "session-artifacts", sessionId);
+ mkdirSync(artifactDir, { recursive: true });
+ writeFileSync(join(artifactDir, "kernel-state.dill"), "payload");
+ let wasSessionRemovedBeforeCallback = false;
+ let wereArtifactsPresentDuringCallback = false;
+
+ const result = await deleteSessionFile(sessionPath, {
+ afterFileRemoved: () => {
+ wasSessionRemovedBeforeCallback = !existsSync(sessionPath);
+ wereArtifactsPresentDuringCallback = existsSync(artifactDir);
+ },
+ });
+
+ expect(result.ok).toBe(true);
+ expect(wasSessionRemovedBeforeCallback).toBe(true);
+ expect(wereArtifactsPresentDuringCallback).toBe(true);
+ expect(existsSync(artifactDir)).toBe(false);
+ });
+
it("succeeds when the session has no artifact directory", async () => {
const sessionsDir = join(root, "sessions");
mkdirSync(sessionsDir, { recursive: true });