Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/cli/src/daemonBuildId.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,4 @@
//
// This file is excluded from its own hash, and it imports nothing on purpose:
// the CLI fast path reads it, so it must never pull in a module graph.
export const DAEMON_BUILD_ID = "43ce973d63b5";
export const DAEMON_BUILD_ID = "2788e9b42deb";
19 changes: 19 additions & 0 deletions packages/cli/src/syncService.timeout.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -432,3 +432,22 @@ describe("SyncService mutation queue bypass (skipQueue)", () => {
expect(direct[0]).toContain("skipQueue: true");
});
});

describe("SyncService.renewTaskLease", () => {
const serviceWith = (mutate: () => Promise<unknown>) => {
const svc = new SyncService({ convexUrl: "http://localhost:0", userId: "u", authToken: "t" }) as any;
svc.apiToken = "token";
svc.mutate = mutate;
return svc as SyncService;
};

it("answers null, not false, when the backend cannot be reached", async () => {
const svc = serviceWith(async () => { throw new Error("The operation timed out."); });
expect(await svc.renewTaskLease("t1", "daemon")).toBeNull();
});

it("passes the backend's answer through", async () => {
expect(await serviceWith(async () => true).renewTaskLease("t1", "daemon")).toBe(true);
expect(await serviceWith(async () => false).renewTaskLease("t1", "daemon")).toBe(false);
});
});
6 changes: 3 additions & 3 deletions packages/cli/src/syncService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2725,16 +2725,16 @@ export class SyncService {
}
}

async renewTaskLease(taskId: string, daemonId: string): Promise<boolean> {
if (!this.apiToken) return false;
async renewTaskLease(taskId: string, daemonId: string): Promise<boolean | null> {
if (!this.apiToken) return null;
try {
const result = await this.mutate(
"agentTasks:renewLease" as any,
{ api_token: this.apiToken, task_id: taskId, daemon_id: daemonId }
);
return result as boolean;
} catch {
return false;
return null;
}
}

Expand Down
54 changes: 54 additions & 0 deletions packages/cli/src/taskScheduler.heartbeat.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { describe, it, expect, beforeEach, afterEach } from "bun:test";
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import { TaskScheduler } from "./taskScheduler.js";

let dir: string;

beforeEach(() => {
dir = fs.mkdtempSync(path.join(os.tmpdir(), "tasksched-heartbeat-"));
});

afterEach(() => {
fs.rmSync(dir, { recursive: true, force: true });
});

function makeScheduler(renew: () => Promise<boolean | null>) {
const scheduler = new TaskScheduler({
syncService: { renewTaskLease: renew } as any,
config: {},
log: () => {},
runsFile: path.join(dir, "trigger-runs.json"),
}) as any;
scheduler.track({ taskId: "t1", tmuxSession: "ct-claude-renew", startedAt: Date.now(), maxRuntimeMs: 600_000 });
// The tmux probe is not under test: a beat here is only about the renewal.
scheduler.checkTaskCompletion = async () => {};
return scheduler;
}

describe("a run's lease renewal", () => {
it("keeps watching the run when the backend cannot be reached, and renews on the next beat", async () => {
const answers: Array<boolean | null> = [null, true];
const scheduler = makeScheduler(async () => answers.shift() as boolean | null);
try {
await scheduler.heartbeat("t1");
expect(scheduler.running.has("t1")).toBe(true);
await scheduler.heartbeat("t1");
expect(answers).toEqual([]);
expect(scheduler.running.has("t1")).toBe(true);
} finally {
scheduler.stop();
}
});

it("stops watching the run when the backend answers that the lease is no longer held", async () => {
const scheduler = makeScheduler(async () => false);
try {
await scheduler.heartbeat("t1");
expect(scheduler.running.has("t1")).toBe(false);
} finally {
scheduler.stop();
}
});
});
25 changes: 16 additions & 9 deletions packages/cli/src/taskScheduler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -591,15 +591,7 @@ export class TaskScheduler {
}

private track(run: TrackedRun): void {
const heartbeatTimer = setInterval(async () => {
const renewed = await this.syncService.renewTaskLease(run.taskId, this.daemonId);
if (!renewed) {
this.log(`Lease renewal failed for task ${run.taskId}, stopping monitor`);
this.cleanupTask(run.taskId);
}

await this.checkTaskCompletion(run.taskId);
}, HEARTBEAT_INTERVAL_MS);
const heartbeatTimer = setInterval(() => this.heartbeat(run.taskId), HEARTBEAT_INTERVAL_MS);

this.running.set(run.taskId, { ...run, heartbeatTimer });
// Link the run's conversation to the task as soon as it syncs (bounded
Expand Down Expand Up @@ -732,6 +724,21 @@ export class TaskScheduler {
}, delaysMs[attempt]);
}

/** One lease beat. renewTaskLease answers null when the backend did not answer: that says nothing
* about the lease, so the monitor stays (after a wake the first calls time out, and stopping here
* lets a live run's lease lapse and the trigger refire). Only false, the backend's "lost", stops it. */
private async heartbeat(taskId: string): Promise<void> {
const renewed = await this.syncService.renewTaskLease(taskId, this.daemonId);
if (renewed === false) {
this.log(`Lease for task ${taskId} lost, stopping monitor`);
this.cleanupTask(taskId);
} else if (renewed === null) {
this.log(`Lease renewal for task ${taskId} unanswered`, "warn");
}

await this.checkTaskCompletion(taskId);
}

private async checkTaskCompletion(taskId: string): Promise<void> {
const entry = this.running.get(taskId);
if (!entry) return;
Expand Down
Loading