Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(phones): report failed removal persistence

Sebastian Bc9ca773a13a9
diff --git a/server/host/phones-revocation.test.ts b/server/host/phones-revocation.test.ts
index aaa5f76b13..0401b22450 100644
--- a/server/host/phones-revocation.test.ts
+++ b/server/host/phones-revocation.test.ts
@@ -3,8 +3,9 @@ import { createServer } from "node:http";
import type { AddressInfo } from "node:net";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { afterEach, expect, it } from "vitest";
+import { afterEach, expect, it, vi } from "vitest";
+import * as atomic from "../atomic.ts";
import { flushDecisionLog } from "../decision-log.ts";
import { json, readBody } from "../harness/http.ts";
import type { RequestAuth } from "../request-auth.ts";
@@ -15,7 +16,7 @@ import { removeTempDir } from "../testing/cleanup.ts";
import { createPhones } from "./phones.ts";
const cleanups: Array<() => Promise<void>> = [];
-afterEach(async () => { for (const cleanup of cleanups.splice(0)) await cleanup(); });
+afterEach(async () => { vi.restoreAllMocks(); for (const cleanup of cleanups.splice(0)) await cleanup(); });
async function fixture() {
const dir = mkdtempSync(join(tmpdir(), "phone-session-revocation-"));
@@ -64,7 +65,7 @@ async function fixture() {
const request = () => phones.handle({ method: "tools/call", params: {
name: "PHONE_CREATE_EVENT", arguments: { title: "Private appointment", start: "2026-10-28T10:00:00Z", end: "2026-10-28T11:00:00Z" },
} }, { botId: bot.id, threadId: "thread-1", generation: "gen-1" }, () => {});
- return { phones, sessions, paired, session, call, polling, request };
+ return { dir, phones, sessions, paired, session, call, polling, request };
}
it("revoking a session removes its phone and ends its pending poll before a later job", async () => {
@@ -92,3 +93,19 @@ it("revoking a session fails both a leased job and a queued job", async () => {
]);
expect(ended).toEqual([expect.objectContaining({ isError: true }), expect.objectContaining({ isError: true })]);
});
+
+it("a phone save failure does not interrupt session revocation or leave its job waiting", async () => {
+ const h = await fixture();
+ const pending = h.request();
+ const write = atomic.writeFileAtomic;
+ vi.spyOn(atomic, "writeFileAtomic").mockImplementation((file, ...args) => {
+ if (file === join(h.dir, "phones.json")) throw Object.assign(new Error("fixture permission denied"), { code: "EACCES" });
+ write(file, ...args);
+ });
+ let notified = false;
+ h.sessions.onSessionRevoked(() => { notified = true; });
+ expect(() => h.sessions.revoke(h.paired.session.id)).not.toThrow();
+ expect(notified).toBe(true);
+ expect(new SessionRegistry({ file: join(h.dir, "sessions.json") }).isLive(h.paired.session.id)).toBe(false);
+ expect(await pending).toMatchObject({ isError: true });
+});
diff --git a/server/host/phones.ts b/server/host/phones.ts
index b57a8648f4..128a68e82d 100644
--- a/server/host/phones.ts
+++ b/server/host/phones.ts
@@ -62,7 +62,7 @@ export function createPhones(deps: PhonesDeps) {
const jobs = new PhoneJobs((phone, id) => deps.nudge({ kind: "device.job", phone, id }));
const unsubscribe = deps.sessions.onSessionRevoked((id) => {
const key = `session:${id}`;
- registry.remove(key);
+ try { registry.remove(key); } catch {}
jobs.drop(key, PHONE_ACCESS_CHANGED);
});
const ownerRoutinesFile = join(deps.dataDir, "owner-routines.json");
diff --git a/server/phones/registry.test.ts b/server/phones/registry.test.ts
index d33367ce10..14c9aaa658 100644
--- a/server/phones/registry.test.ts
+++ b/server/phones/registry.test.ts
@@ -1,8 +1,9 @@
import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import * as atomic from "../atomic.ts";
import { removeTempDir } from "../testing/cleanup.ts";
import { MAX_BLOCKED, MAX_PHONES, PHONE_ONLINE_MS, PHONE_REMOVED_TEXT, phoneRegistration, PhoneRegistry, type PhoneRegistration } from "./registry.ts";
@@ -14,7 +15,7 @@ describe("PhoneRegistry", () => {
let at: number;
const now = () => at;
beforeEach(() => { dir = mkdtempSync(join(tmpdir(), "omb-phones-")); file = join(dir, "phones.json"); at = 1_000_000; });
- afterEach(async () => { await removeTempDir(dir); });
+ afterEach(async () => { vi.restoreAllMocks(); await removeTempDir(dir); });
it("registers, lists online, and persists across a reload", () => {
const registry = new PhoneRegistry(file, now);
@@ -108,6 +109,35 @@ describe("PhoneRegistry", () => {
expect(new PhoneRegistry(file, now).blocked(`session:s${MAX_BLOCKED}`)).toBe(true);
});
+ it.each([false, true])("reports a failed removal save and persists its retry (block=%s)", (block) => {
+ const registry = new PhoneRegistry(file, now);
+ registry.register("session:s1", "owner", reg());
+ const saved = readFileSync(file, "utf8");
+ const fault = Object.assign(new Error("fixture permission denied"), { code: "EACCES" });
+ const write = vi.spyOn(atomic, "writeFileAtomic").mockImplementation(() => { throw fault; });
+ expect(() => registry.remove("session:s1", { block })).toThrow(fault);
+ expect(registry.get("session:s1")).toBeUndefined();
+ expect(registry.blocked("session:s1")).toBe(block);
+ expect(readFileSync(file, "utf8")).toBe(saved);
+ if (block) expect(() => registry.register("session:s1", "owner", reg())).toThrow(expect.objectContaining({ status: 403 }));
+ write.mockRestore();
+ expect(registry.remove("session:s1", { block })).toBe(false);
+ const reloaded = new PhoneRegistry(file, now);
+ expect(reloaded.get("session:s1")).toBeUndefined();
+ expect(reloaded.blocked("session:s1")).toBe(block);
+ });
+
+ it("retries storing a failed block even when the key was already absent", () => {
+ const registry = new PhoneRegistry(file, now);
+ const fault = Object.assign(new Error("fixture permission denied"), { code: "EACCES" });
+ const write = vi.spyOn(atomic, "writeFileAtomic").mockImplementation(() => { throw fault; });
+ expect(() => registry.remove("session:gone", { block: true })).toThrow(fault);
+ expect(registry.blocked("session:gone")).toBe(true);
+ write.mockRestore();
+ expect(registry.remove("session:gone", { block: true })).toBe(false);
+ expect(new PhoneRegistry(file, now).blocked("session:gone")).toBe(true);
+ });
+
it("reads a file written before blocks existed", () => {
writeFileSync(file, JSON.stringify({ version: 1, phones: [{ key: "companion:d1", owner: "owner", registration: reg(), registeredAt: 1, seen: 1, lastUsedAt: null }] }));
const registry = new PhoneRegistry(file, now);
diff --git a/server/phones/registry.ts b/server/phones/registry.ts
index 1a5f70d29d..9ae30d0806 100644
--- a/server/phones/registry.ts
+++ b/server/phones/registry.ts
@@ -48,6 +48,7 @@ export class PhoneRegistry {
private readonly now: () => number;
private phones = new Map<string, PhoneRecord>();
private written = new Map<string, number>();
+ private removalPending = false;
/** Removed on the computer: such a key never registers again; pairing the phone again gives it a new one. */
private removed = new Set<string>();
@@ -67,9 +68,14 @@ export class PhoneRegistry {
}
}
- private save(): void {
- try { writeFileAtomic(this.file, `${JSON.stringify({ version: 1, phones: [...this.phones.values()], blocked: [...this.removed] })}\n`, { mode: 0o600 }); }
- catch (error) { console.warn(`phones: could not save the record of paired phones: ${error instanceof Error ? error.message : String(error)}`); }
+ private save(required = false): void {
+ try {
+ writeFileAtomic(this.file, `${JSON.stringify({ version: 1, phones: [...this.phones.values()], blocked: [...this.removed] })}\n`, { mode: 0o600 });
+ this.removalPending = false;
+ } catch (error) {
+ console.warn(`phones: could not save the record of paired phones: ${error instanceof Error ? error.message : String(error)}`);
+ if (required) throw error;
+ }
}
/** Same key: update. Same owner + installId under another key: replace that record, keeping its history. A key the
@@ -120,7 +126,8 @@ export class PhoneRegistry {
this.removed.add(key);
for (const oldest of this.removed) { if (this.removed.size <= MAX_BLOCKED) break; this.removed.delete(oldest); }
}
- if (removed || blocking) this.save();
+ if (removed || blocking) this.removalPending = true;
+ if (this.removalPending) this.save(true);
return removed;
}
diff --git a/server/routes/phones.test.ts b/server/routes/phones.test.ts
index f3fd85ba9a..13a43f20df 100644
--- a/server/routes/phones.test.ts
+++ b/server/routes/phones.test.ts
@@ -5,6 +5,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
+import * as atomic from "../atomic.ts";
import { json, readBody } from "../harness/http.ts";
import { PhoneJobs } from "../phones/jobs.ts";
import { PhoneRegistry } from "../phones/registry.ts";
@@ -16,6 +17,7 @@ import { dispatchRoutes } from "./table.ts";
const servers: Server[] = [];
const dirs: string[] = [];
afterEach(async () => {
+ vi.restoreAllMocks();
await Promise.all(servers.splice(0).map((server) => new Promise((done) => server.close(done))));
await Promise.all(dirs.splice(0).map(removeTempDir));
});
@@ -62,7 +64,7 @@ async function setup(options: { auth?: RequestAuth; owner?: () => string | null;
});
return { status: response.status, body: (await response.json()) as any };
};
- return { registry, jobs, call };
+ return { registry, jobs, call, dir };
}
describe("phone routes", () => {
@@ -162,6 +164,27 @@ describe("phone routes", () => {
expect((await call("GET", "/api/phones/self/jobs", undefined, fromPhone("d1"))).status).toBe(404);
});
+ it.each(["/api/phones/self", "/api/phones/companion%3Ad1"])("reports a failed removal save at %s and still drops jobs", async (path) => {
+ const { call, jobs, registry, dir } = await setup({ auth: companion("d1") });
+ try {
+ await call("PUT", "/api/phones/self", registration);
+ const pending = jobs.request("companion:d1", "PHONE_LIST_EVENTS", {}, { active: () => true, timeoutMs: 10_000, offlineText: "offline", online: () => true });
+ const job = (await call("GET", "/api/phones/self/jobs")).body.job;
+ expect((await call("POST", `/api/phones/self/jobs/${job.id}/lease`)).body).toEqual({ active: true });
+ const fault = Object.assign(new Error("fixture permission denied"), { code: "EACCES" });
+ const write = vi.spyOn(atomic, "writeFileAtomic").mockImplementation(() => { throw fault; });
+ expect((await call("DELETE", path)).status).toBe(500);
+ expect(registry.get("companion:d1")).toBeUndefined();
+ expect(jobs.busy("companion:d1")).toBe(false);
+ expect(await pending).toMatchObject({ ok: false, code: "denied" });
+ write.mockRestore();
+ expect((await call("DELETE", path)).status).toBe(200);
+ const reloaded = new PhoneRegistry(join(dir, "phones.json"));
+ expect(reloaded.get("companion:d1")).toBeUndefined();
+ expect(reloaded.blocked("companion:d1")).toBe(path !== "/api/phones/self");
+ } finally { jobs.close(); }
+ });
+
it("an open poll answers empty when its phone is removed", async () => {
const { call, jobs } = await setup({ auth: companion("d1") });
await call("PUT", "/api/phones/self", registration, fromPhone("d1"));
diff --git a/server/routes/phones.ts b/server/routes/phones.ts
index b5bbb3a871..91d42401d3 100644
--- a/server/routes/phones.ts
+++ b/server/routes/phones.ts
@@ -32,6 +32,10 @@ export interface PhoneRouteDeps {
export function createPhoneRoutes(deps: PhoneRouteDeps): RouteHandler {
const { registry, jobs } = deps;
+ const removePhone = (key: string, block = false) => {
+ try { return registry.remove(key, { block }); }
+ finally { jobs.drop(key, PHONE_ACCESS_CHANGED); }
+ };
return async ({ req, res, path, method, auth, json, readBody }: RouteContext): Promise<typeof PASS | void> => {
if (path !== "/api/phones" && !path.startsWith("/api/phones/")) return PASS;
res.setHeader("Cache-Control", "no-store");
@@ -59,8 +63,7 @@ export function createPhoneRoutes(deps: PhoneRouteDeps): RouteHandler {
}
if (method === "GET") return json(res, 200, { phone: registry.list(owner, (k) => jobs.busy(k)).find((p) => p.key === key) ?? null });
if (method === "DELETE") {
- const removed = registry.remove(key);
- jobs.drop(key, PHONE_ACCESS_CHANGED);
+ const removed = removePhone(key);
return json(res, 200, { removed });
}
}
@@ -88,8 +91,7 @@ export function createPhoneRoutes(deps: PhoneRouteDeps): RouteHandler {
if (!deps.isAdmin(auth)) return json(res, 403, { error: "Only the owner or an admin can remove phones." });
// Removed on the computer: its waiting jobs fail and the key stays refused, so the phone must pair again.
const key = decodeURIComponent(one[1]!);
- const removed = registry.remove(key, { block: true });
- jobs.drop(key, PHONE_ACCESS_CHANGED);
+ const removed = removePhone(key, true);
return json(res, 200, { removed });
}
return json(res, 404, { error: "not found" });