Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(outbox): preserve rejected appends across quarantine interruptions
Zeding Zhang42245f9d9986
diff --git a/apps/desktop/electron/main/persistence-outbox.ts b/apps/desktop/electron/main/persistence-outbox.tsindex 72aa31d96..34c7e1816 100644--- a/apps/desktop/electron/main/persistence-outbox.ts+++ b/apps/desktop/electron/main/persistence-outbox.ts@@ -1,3 +1,4 @@+import { randomUUID } from "node:crypto";import { link, mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";import { dirname, join } from "node:path";import { decodeBinaryStorage, encodeBinaryStorage } from "@pi-desktop/host-runtime";@@ -20,8 +21,11 @@ type MessageAppend = {type QuarantinedAppend = MessageAppend & {quarantinedAt: string;reason: string;+ quarantineId?: string;};+type PendingQuarantine = QuarantinedAppend & { pendingQuarantineId: string };+type OutboxLogger = (level: "warn" | "error", message: string, data?: unknown) => void;type OutboxOptions = {@@ -91,7 +95,7 @@ export class PersistenceOutbox {getHost: () => HostProcess | null,): Promise<void> {await this.loaded;- const existing = this.entries.findIndex((item) => item.key === entry.key);+ const existing = this.entries.findIndex((item) => item.key === entry.key && !isPendingQuarantine(item));if (existing >= 0) this.entries[existing] = entry;else {if (this.entries.length >= MAX_ENTRIES) await this.flush(getHost);@@ -107,7 +111,9 @@ export class PersistenceOutbox {this.entries.push(entry);}await this.persist();- void this.flush(getHost);+ void this.flush(getHost).catch((error: unknown) => {+ this.logger("error", "session persistence background flush failed", String(error));+ });}async flush(getHost: () => HostProcess | null): Promise<void> {@@ -133,6 +139,7 @@ export class PersistenceOutbox {if (!entriesChanged && !deadLettersChanged) return;this.entries = next;this.deadLetters = nextDeadLetters;+ if (this.headRetry?.entry.sessionId === sessionId) this.headRetry = null;if (entriesChanged) await this.persist();if (deadLettersChanged) await this.persistDeadLetters();}@@ -179,6 +186,10 @@ export class PersistenceOutbox {private async flushLoop(getHost: () => HostProcess | null): Promise<void> {while (this.entries.length > 0) {const current = this.entries[0];+ if (isPendingQuarantine(current)) {+ await this.finishQuarantine(current);+ continue;+ }const currentHost = getHost();if (!currentHost || !currentHost.isAvailable()) return;// Bounded backoff: a head that just failed is not retried on every@@ -231,6 +242,8 @@ export class PersistenceOutbox {data: String(error),});} else {+ // A deleted session can be enqueued under the same key before its old call settles.+ if (this.entries[0] !== current && this.headRetry?.entry !== current) continue;const attempts = this.noteTransientFailure(current, currentHost);if (attempts < MAX_TRANSIENT_ATTEMPTS) {// Transient failure (host busy/overloaded/pipe dead). Keep the head@@ -248,7 +261,7 @@ export class PersistenceOutbox {// An error the outbox cannot classify as permanent or as a// duplicate recurs on every retry. Quarantine the head instead of// blocking the whole application queue behind it forever (#1560).- await this.quarantine(current, attempts, error);+ this.stageQuarantine(current, error);continue;}}@@ -268,33 +281,51 @@ export class PersistenceOutbox {return attempts;}- /** Move a head the host keeps refusing into the dead-letter file. */- private async quarantine(entry: MessageAppend, attempts: number, error: unknown): Promise<void> {- this.deadLetters.push({+ private stageQuarantine(entry: MessageAppend, error: unknown): void {+ const pending: PendingQuarantine = {...entry,+ pendingQuarantineId: randomUUID(),quarantinedAt: new Date(this.now()).toISOString(),reason: String(error),- });- while (this.deadLetters.length > this.maxDeadLetters) {- const dropped = this.deadLetters.shift();- this.logger("warn", "session persistence outbox dead letter discarded", {- key: dropped?.key,- sessionId: dropped?.sessionId,- max: this.maxDeadLetters,- file: this.deadLetterPath,- });+ };+ if (this.entries[0] === entry) {+ this.entries[0] = pending;+ } else {+ // Keep the newer snapshot that replaced this one during the host call.+ this.entries.unshift(pending);+ }+ this.headRetry = null;+ }++ private async finishQuarantine(entry: PendingQuarantine): Promise<void> {+ // Commit the decision and its identity in the source before touching the archive.+ // A restart can then resume the transfer without sending this snapshot to the host.+ await this.persist();+ if (this.entries[0] !== entry) return; // The session was deleted during the write.+ const { pendingQuarantineId, ...letter } = entry;+ if (!this.deadLetters.some((item) => item.quarantineId === pendingQuarantineId)) {+ this.deadLetters.push({ ...letter, quarantineId: pendingQuarantineId });+ while (this.deadLetters.length > this.maxDeadLetters) {+ const dropped = this.deadLetters.shift();+ this.logger("warn", "session persistence outbox dead letter discarded", {+ key: dropped?.key,+ sessionId: dropped?.sessionId,+ max: this.maxDeadLetters,+ file: this.deadLetterPath,+ });+ }}+ // An earlier archive write may have failed after updating the in-memory list.+ await this.persistDeadLetters();+ if (this.entries[0] !== entry) return;+ await this.persist(entry);this.logger("error", "session persistence flush quarantined entry", {key: entry.key,sessionId: entry.sessionId,- attempts,+ attempts: MAX_TRANSIENT_ATTEMPTS,file: this.deadLetterPath,- data: String(error),+ data: entry.reason,});- if (this.entries[0] === entry) this.entries.shift();- this.headRetry = null;- await this.persist();- await this.persistDeadLetters();}private async load(): Promise<void> {@@ -399,11 +430,10 @@ export class PersistenceOutbox {if (!Array.isArray(parsed)) throw new Error("Invalid session persistence dead letters: expected an array");this.deadLetters = parsed.map((value) => {const entry = decodeAppend(value);- if (!("quarantinedAt" in entry) || typeof entry.quarantinedAt !== "string" ||- !("reason" in entry) || typeof entry.reason !== "string") {+ if (!isDeadLetter(entry)) {throw new Error("Invalid session persistence dead letter entry");}- return entry as QuarantinedAppend;+ return entry;});} catch (error: unknown) {if (!isMissingFile(error)) {@@ -413,11 +443,14 @@ export class PersistenceOutbox {}}- private async persist(): Promise<void> {+ private async persist(archived?: PendingQuarantine): Promise<void> {const write = this.persistChain.then(async () => {await mkdir(dirname(this.path), { recursive: true });- await writeFile(this.tempPath, `${JSON.stringify(this.entries.map(encodeBinaryStorage))}\n`, "utf8");+ const entries = archived ? this.entries.filter((entry) => entry !== archived) : this.entries;+ await writeFile(this.tempPath, `${JSON.stringify(entries.map(encodeBinaryStorage))}\n`, "utf8");await rename(this.tempPath, this.path);+ // Keep a failed cleanup visible to a later flush or session deletion.+ if (archived && this.entries[0] === archived) this.entries.shift();});this.persistChain = write.catch(() => undefined);await write;@@ -434,6 +467,15 @@ export class PersistenceOutbox {}}+function isDeadLetter(entry: MessageAppend): entry is QuarantinedAppend {+ return "quarantinedAt" in entry && typeof entry.quarantinedAt === "string" &&+ "reason" in entry && typeof entry.reason === "string";+}++function isPendingQuarantine(entry: MessageAppend): entry is PendingQuarantine {+ return "pendingQuarantineId" in entry && typeof entry.pendingQuarantineId === "string" && isDeadLetter(entry);+}+function isDuplicateMessageIdError(error: unknown): boolean {return /UNIQUE constraint failed: messages\.id/i.test(String(error));}diff --git a/apps/desktop/test/persistence-outbox-quarantine.test.mjs b/apps/desktop/test/persistence-outbox-quarantine.test.mjsnew file mode 100644index 000000000..201a14efd--- /dev/null+++ b/apps/desktop/test/persistence-outbox-quarantine.test.mjs@@ -0,0 +1,165 @@+import assert from "node:assert/strict";+import { spawnSync } from "node:child_process";+import fs, { mkdir, mkdtemp, readFile, rm, rmdir, writeFile } from "node:fs/promises";+import { syncBuiltinESMExports } from "node:module";+import { tmpdir } from "node:os";+import { join } from "node:path";+import test from "node:test";+import { PersistenceOutbox } from "../electron/main/persistence-outbox.ts";++const queueFile = "session-message-outbox.json";+const archiveFile = "session-message-outbox.dead-letter.json";+const rejected = { key: "message:s:one", sessionId: "s", message: { id: "one", text: "original" } };+const healthy = { key: "message:t:two", sessionId: "t", message: { id: "two" } };++async function seedQueue(t, entries = [rejected, healthy]) {+ const dir = await mkdtemp(join(tmpdir(), "pi-quarantine-"));+ t.after(() => rm(dir, { recursive: true, force: true }));+ await writeFile(join(dir, queueFile), JSON.stringify(entries));+ return dir;+}++async function retryFourTimes(dir, host) {+ let now = 0;+ const outbox = new PersistenceOutbox(dir, () => {}, { now: () => now });+ for (let attempt = 0; attempt < 4; attempt++) {+ await outbox.flush(() => host);+ now += 60_000;+ }+ return outbox;+}++for (const boundary of ["before", "after"]) {+ test(`restarting ${boundary} the dead-letter rename retains the rejected append exactly once`, async (t) => {+ const dir = await seedQueue(t);+ const previous = { ...rejected, quarantinedAt: "2026-01-01T00:00:00Z", reason: "earlier rejection" };+ await writeFile(join(dir, archiveFile), JSON.stringify([previous]));+ const moduleUrl = new URL("../electron/main/persistence-outbox.ts", import.meta.url).href;+ const child = spawnSync(process.execPath, ["--input-type=module", "-e", `+ import fs from "node:fs/promises";+ import { syncBuiltinESMExports } from "node:module";+ const [moduleUrl, dir, archive, boundary] = process.argv.slice(1);+ const originalRename = fs.rename;+ fs.rename = async (from, to) => {+ if (to === archive && boundary === "before") process.exit(77);+ await originalRename(from, to);+ if (to === archive && boundary === "after") process.exit(77);+ };+ syncBuiltinESMExports();+ const { PersistenceOutbox } = await import(moduleUrl);+ let now = 0;+ const outbox = new PersistenceOutbox(dir, () => {}, { now: () => now });+ const host = { isAvailable: () => true, call: async () => { throw new Error("busy"); } };+ for (let attempt = 0; attempt < 5; attempt++) {+ now += 60_000;+ await outbox.flush(() => host);+ }+ `, moduleUrl, dir, join(dir, archiveFile), boundary], { encoding: "utf8", timeout: 10_000 });+ assert.equal(child.status, 77, child.stderr || "the child must reach the archive rename");++ const recovered = new PersistenceOutbox(dir, () => {});+ const calls = [];+ const host = { isAvailable: () => true, call: async (_method, params) => calls.push(params.message) };+ // A fresh enqueue may have the same key and even the same payload as either dead letter.+ await recovered.enqueue(rejected, () => host);+ await recovered.flush(() => host);+ assert.deepEqual(calls, [healthy.message, rejected.message]);+ const archived = JSON.parse(await readFile(join(dir, archiveFile), "utf8"));+ assert.equal(archived.length, 2);+ assert.deepEqual(archived[0], previous);+ assert.deepEqual(archived[1].message, rejected.message);+ assert.match(archived[1].reason, /busy/);+ assert.deepEqual(JSON.parse(await readFile(join(dir, queueFile), "utf8")), []);++ // The archive record itself can still be requeued explicitly for manual recovery.+ await recovered.enqueue(archived[1], () => host);+ await recovered.flush(() => host);+ assert.deepEqual(calls, [healthy.message, rejected.message, rejected.message]);+ });+}++test("a failed dead-letter write can be retried without sending the rejected append again", async (t) => {+ const dir = await seedQueue(t);+ const calls = [];+ const host = {+ isAvailable: () => true,+ call: async (_method, { message }) => {+ calls.push(message.id);+ if (message.id === rejected.message.id) throw new Error("busy");+ },+ };+ const outbox = await retryFourTimes(dir, host);+ // The archive has already been loaded. A directory at its path makes the next rename fail.+ await mkdir(join(dir, archiveFile));+ await assert.rejects(outbox.flush(() => host));+ const pending = JSON.parse(await readFile(join(dir, queueFile), "utf8"));+ assert.deepEqual(pending.map((entry) => entry.message), [rejected.message, healthy.message]);+ await rmdir(join(dir, archiveFile));++ await outbox.flush(() => null);+ const archived = JSON.parse(await readFile(join(dir, archiveFile), "utf8"));+ assert.deepEqual(archived.map((entry) => entry.message), [rejected.message]);+ await outbox.flush(() => host);+ assert.deepEqual(calls, ["one", "one", "one", "one", "one", "two"]);+ assert.deepEqual(JSON.parse(await readFile(join(dir, queueFile), "utf8")), []);+});++test("deleting the session after a failed queue cleanup also clears the pending transfer", async (t) => {+ const dir = await seedQueue(t);+ const host = { isAvailable: () => true, call: async () => { throw new Error("busy"); } };+ const outbox = await retryFourTimes(dir, host);+ const originalRename = fs.rename;+ let archiveCommitted = false;+ const rename = t.mock.method(fs, "rename", async (from, to) => {+ if (archiveCommitted && to === join(dir, queueFile)) {+ archiveCommitted = false;+ throw Object.assign(new Error("queue rename denied"), { code: "EPERM" });+ }+ await originalRename(from, to);+ if (to === join(dir, archiveFile)) archiveCommitted = true;+ });+ syncBuiltinESMExports();+ t.after(() => {+ rename.mock.restore();+ syncBuiltinESMExports();+ });++ await assert.rejects(outbox.flush(() => host), { code: "EPERM" });+ await outbox.dropSession(rejected.sessionId);+ assert.deepEqual(JSON.parse(await readFile(join(dir, queueFile), "utf8")).map((entry) => entry.key), [healthy.key]);+ assert.deepEqual(JSON.parse(await readFile(join(dir, archiveFile), "utf8")), []);+});++for (const change of ["replacement", "deletion", "deletion and re-enqueue"]) {+ test(`quarantine respects a concurrent ${change} during the final host attempt`, async (t) => {+ const dir = await seedQueue(t, [rejected]);+ await writeFile(join(dir, archiveFile), "[]");+ const started = Promise.withResolvers();+ const finalAttempt = Promise.withResolvers();+ const delivered = [];+ let failures = 0;+ const host = {+ isAvailable: () => true,+ call: async (_method, { message }) => {+ if (message.text !== "original") return delivered.push(message);+ if (++failures === 5) {+ started.resolve();+ return finalAttempt.promise;+ }+ throw new Error("busy");+ },+ };+ const outbox = await retryFourTimes(dir, host);+ const flush = outbox.flush(() => host);+ await started.promise;+ const replacement = { ...rejected, message: { ...rejected.message, text: "updated" } };+ if (change !== "replacement") await outbox.dropSession(rejected.sessionId);+ if (change !== "deletion") await outbox.enqueue(replacement, () => host);+ finalAttempt.reject(new Error("busy"));+ await flush;++ const archived = JSON.parse(await readFile(join(dir, archiveFile), "utf8"));+ assert.deepEqual(archived.map((entry) => entry.message), change === "replacement" ? [rejected.message] : []);+ assert.deepEqual(delivered, change === "deletion" ? [] : [replacement.message]);+ });+}diff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.mdindex 8c16e573b..029e5c824 100644--- a/docs/spec/03-runtime/04-data-storage.md+++ b/docs/spec/03-runtime/04-data-storage.md@@ -2004,6 +2004,11 @@ and host error, so one unclassifiable head cannot starve every session's writes(D656). A restarted host is a new generation and retries the head at once.Quarantined appends are never replayed automatically, and `session.delete`drops that session's quarantined appends too.+Before archiving, the outbox saves the rejection reason, timestamp, and a+unique transfer ID with the queued snapshot. It removes that snapshot only+after the dead-letter file has been replaced successfully. On restart, a+pending transfer finishes using the same ID, even without a host. A later+enqueue with the same message key remains independent.Every outbox and dead-letter snapshot, including an empty array, is writtento its sibling temporary file before replacing the committed file by rename.Interrupted writes leave the previous committed snapshot readable; a faileddiff --git a/docs/spec/06-delivery/e2e/conversation.md b/docs/spec/06-delivery/e2e/conversation.mdindex 821762cf2..cfc10238e 100644--- a/docs/spec/06-delivery/e2e/conversation.md+++ b/docs/spec/06-delivery/e2e/conversation.md@@ -753,19 +753,24 @@ folder/mixed-selection behavior. No system clipboard contents are changed.`session-message-outbox.dead-letter.json` holds that key with its payload anderror, and that `session-message-outbox.json` drops below the cap. 5) Restartthe app and confirm the quarantined append is not replayed. 6) Optional:- delete the failing session and confirm its dead letter is dropped.+ delete the failing session and confirm its dead letter is dropped. Repeat in+ an isolated profile with a process exit immediately before and immediately+ after the dead-letter rename. Reopen and enqueue a new snapshot with the+ same key.- **Expected**: The failing append is paused four times with a growing backoffand quarantined on the fifth consecutive failure, then skipped. Laterappends from every session drain, no enqueue is rejected with `outbox isfull`, and the queued outbox file empties. The dead letter survives a- restart without being replayed.+ restart without being replayed. At either interruption point the rejected+ snapshot is archived once, and the new snapshot still reaches the host.- **Specs linked**: `03-runtime/04-data-storage.md`,`03-runtime/06-host-rpc-protocol.md`, ADR 0041, D318, D444, D597, D656- **Acceptance**: F (persistence)- **Milestone**: M2-- **Status**: Unit-covered (`persistence-outbox.test.mjs` bounded retry,- quarantine, dead-letter persistence and cap tests); desktop journey- outstanding+- **Status**: Bounded retry, dead-letter retention and capacity are covered by+ `persistence-outbox.test.mjs`. Process interruption and filesystem errors+ are covered by `persistence-outbox-quarantine.test.mjs`. The full desktop+ journey is outstanding.## E2E-SESSION-outbox-empty-snapshot-is-atomic