Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(remote): serialize remote registry mutations

vastsae4ff07692199
diff --git a/apps/desktop/electron/main/remote/remote-host-registry.ts b/apps/desktop/electron/main/remote/remote-host-registry.ts
index c1da759a3..471b102a1 100644
--- a/apps/desktop/electron/main/remote/remote-host-registry.ts
+++ b/apps/desktop/electron/main/remote/remote-host-registry.ts
@@ -114,6 +114,17 @@ export function createRemoteHostRegistry(
): RemoteHostRegistry {
const log = options.log ?? (() => undefined);
const filePath = join(options.dataDir, options.fileName ?? "remote-hosts.json");
+ let mutationQueue: Promise<void> = Promise.resolve();
+
+ /** Keep each read-modify-write and quarantine transaction exclusive. */
+ const serializeMutation = <T>(mutation: () => Promise<T>): Promise<T> => {
+ const result = mutationQueue.then(mutation);
+ mutationQueue = result.then(
+ () => undefined,
+ () => undefined,
+ );
+ return result;
+ };
const readFileState = async (): Promise<RegistryRead> => {
let raw: string;
@@ -235,45 +246,49 @@ export function createRemoteHostRegistry(
}
return decoded;
},
- async upsert(record) {
- if (!options.encryption.isAvailable()) {
- throw Object.assign(new Error("safeStorage unavailable; refusing to write remote host token"), {
- errorCode: "REMOTE_STORAGE_UNAVAILABLE",
- });
- }
- const hosts = await writableHosts();
- const ciphertext = options.encryption.encryptString(record.deviceToken).toString("base64");
- const serialized: SerializedRecord = {
- hostKey: record.hostKey,
- label: record.label,
- url: record.url,
- encryptedDeviceToken: ciphertext,
- ...(record.sshSecret
- ? {
- encryptedSshSecret: options.encryption
- .encryptString(record.sshSecret)
- .toString("base64"),
- }
- : {}),
- ...(record.metadata ? { metadata: record.metadata } : {}),
- };
- const next = hosts.filter((existing) => existing.hostKey !== record.hostKey);
- next.push(serialized);
- await persist({ version: CURRENT_VERSION, hosts: next });
+ upsert(record) {
+ return serializeMutation(async () => {
+ if (!options.encryption.isAvailable()) {
+ throw Object.assign(new Error("safeStorage unavailable; refusing to write remote host token"), {
+ errorCode: "REMOTE_STORAGE_UNAVAILABLE",
+ });
+ }
+ const hosts = await writableHosts();
+ const ciphertext = options.encryption.encryptString(record.deviceToken).toString("base64");
+ const serialized: SerializedRecord = {
+ hostKey: record.hostKey,
+ label: record.label,
+ url: record.url,
+ encryptedDeviceToken: ciphertext,
+ ...(record.sshSecret
+ ? {
+ encryptedSshSecret: options.encryption
+ .encryptString(record.sshSecret)
+ .toString("base64"),
+ }
+ : {}),
+ ...(record.metadata ? { metadata: record.metadata } : {}),
+ };
+ const next = hosts.filter((existing) => existing.hostKey !== record.hostKey);
+ next.push(serialized);
+ await persist({ version: CURRENT_VERSION, hosts: next });
+ });
},
- async remove(hostKey) {
- const hosts = await writableHosts();
- const next = hosts.filter((existing) => existing.hostKey !== hostKey);
- if (next.length === hosts.length) return;
- if (next.length === 0) {
- try {
- await unlink(filePath);
- } catch (error) {
- if (!fileNotFound(error)) log("warn", "remote-hosts.json unlink failed", { error: String(error) });
+ remove(hostKey) {
+ return serializeMutation(async () => {
+ const hosts = await writableHosts();
+ const next = hosts.filter((existing) => existing.hostKey !== hostKey);
+ if (next.length === hosts.length) return;
+ if (next.length === 0) {
+ try {
+ await unlink(filePath);
+ } catch (error) {
+ if (!fileNotFound(error)) log("warn", "remote-hosts.json unlink failed", { error: String(error) });
+ }
+ return;
}
- return;
- }
- await persist({ version: CURRENT_VERSION, hosts: next });
+ await persist({ version: CURRENT_VERSION, hosts: next });
+ });
},
};
}
diff --git a/apps/desktop/test/remote-host-registry.test.mjs b/apps/desktop/test/remote-host-registry.test.mjs
index ebca01c9b..447f88f67 100644
--- a/apps/desktop/test/remote-host-registry.test.mjs
+++ b/apps/desktop/test/remote-host-registry.test.mjs
@@ -241,3 +241,29 @@ test("a corrupt file is quarantined with its bytes preserved, then pairing conti
assert.ok(warnings.some((entry) => /quarantined corrupt/.test(entry.message)));
await cleanup();
});
+
+test("concurrent pairings serialize quarantine and preserve every host", async () => {
+ const { dir, cleanup } = await tmpDir();
+ const garbage = '{"version": 1, "hosts": [{"hostKey": "tru';
+ await writeFile(join(dir, "remote-hosts.json"), garbage, "utf8");
+ const registry = createRemoteHostRegistry({ dataDir: dir, encryption: reversibleEncryption() });
+ const records = Array.from({ length: 12 }, (_, index) => ({
+ hostKey: `host-${index}`,
+ label: `Host ${index}`,
+ url: `wss://host-${index}`,
+ deviceToken: `token-${index}`,
+ }));
+
+ await Promise.all(records.map((record) => registry.upsert(record)));
+
+ const rows = await registry.list();
+ assert.deepEqual(
+ rows.map((row) => row.hostKey).sort(),
+ records.map((record) => record.hostKey).sort(),
+ );
+ const entries = await (await import("node:fs/promises")).readdir(dir);
+ const quarantine = entries.find((name) => name.startsWith("remote-hosts.json.corrupt-"));
+ assert.ok(quarantine, "the original corrupt registry must remain quarantined");
+ assert.equal(await readFile(join(dir, quarantine), "utf8"), garbage);
+ await cleanup();
+});