A personal agent with a browser, terminal, files, and work that keeps going built with CopilotKit and AG-UI.
TypeScript
fix(monitors): preserve concurrent observe commits on pause (#116)
Kevin Rajancbd4417fae73
diff --git a/apps/server/src/engine/service.ts b/apps/server/src/engine/service.tsindex 3c31d7f..5e27540 100644--- a/apps/server/src/engine/service.ts+++ b/apps/server/src/engine/service.ts@@ -445,14 +445,16 @@ export class AgentService {throw new AppError("Create a new watch to restart this stopped monitor", 409);if (action === "pause" || action === "stop") {const status = action === "pause" ? "paused" : "stopped";- const saved = await this.db.put(owner, "monitors", {- ...monitor,- status,- nextCheckAt: date(),- });+ const saved = await this.db.compareAndSwap<Monitor>(+ owner,+ "monitors",+ id,+ {},+ { status, nextCheckAt: date() },+ );const task = await this.getTask(owner, monitor.taskId);await this.control(owner, task.id, action === "pause" ? "pause" : "cancel");- return saved;+ return saved ?? monitor;}let monitorStatus = monitor.status;for (let attempt = 0; attempt < 2; attempt++) {diff --git a/tests/monitor-recovery.test.ts b/tests/monitor-recovery.test.tsindex 19ca5c0..a989944 100644--- a/tests/monitor-recovery.test.ts+++ b/tests/monitor-recovery.test.ts@@ -703,3 +703,41 @@ test("a second observe from a stale snapshot loses its monitor commit instead of// The loser's commit was rejected: exactly one increment landed.assert.equal((await db.get<Monitor>(owner, "monitors", monitor.id))?.checks, 2);});++test("pausing a watch preserves a concurrent observe() commit", async () => {+ const monitor = await createMonitor("Pause during observe");+ // Simulate an observe() committing between the pause request's read and its+ // write: the pause must move only the control fields, never clobber the commit.+ const stale = (await db.get<Monitor>(owner, "monitors", monitor.id)) as Monitor;+ await db.compareAndSwap(+ owner,+ "monitors",+ monitor.id,+ {},+ {+ checks: 41,+ lastCheckedAt: new Date().toISOString(),+ lastHash: "deadbeef",+ lastValue: "committed value",+ },+ );+ const originalGet: Store["get"] = db.get.bind(db);+ let served = false;+ db.get = (async (o: string, kind: string, key: string) => {+ if (!served && kind === "monitors" && key === monitor.id) {+ served = true;+ return stale;+ }+ return originalGet(o, kind, key);+ }) as Store["get"];+ try {+ await read<Monitor>(`/monitors/${monitor.id}/control`, { action: "pause" });+ } finally {+ db.get = originalGet;+ }+ const after = (await db.get<Monitor>(owner, "monitors", monitor.id)) as Monitor;+ assert.equal(after.status, "paused");+ assert.equal(after.checks, 41);+ assert.equal(after.lastHash, "deadbeef");+ assert.equal(after.lastValue, "committed value");+});