Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: reconcile archived Beeper edits and unsends (#8682)

[._.]/ Adam Eivy045d8b7b9384
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 0d5560ea49..c171a52213 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -21,6 +21,9 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](
## `db-primary` — app-native relational records
+- Beeper's `beeper_reconcile_cursors` stores a machine-local per-account rotating checkpoint and a fixed per-rotation upper bound over already mirrored message IDs. Each sweep refetches at most 20 stored messages per account, independently of forward ingestion; failed retrievals retain the archive and retry on the next rotation. Checkpoints survive restart, cascade on account deletion, and are covered by PostgreSQL backup. They never federate. `beeper_messages.observed_at` records fetch-start time to break equal source-version ties; source edit timestamps prevent stale sweep/outbox writes from replacing edits. Additive schema initialization upgrades existing installs without a data seed.
+
+
- `mind_tool_recipes` / `mind_tool_recipe_versions` — machine-local authored read-tool definitions, stable IDs, active revision/archive metadata, and immutable revisions linked by recipe ID (#7194). No execution output is stored; no definitions or literals enter federation/status payloads. PostgreSQL backup covers both tables. Migration 381 registers schema-only installation; empty installs receive no user recipe seed. Unknown future definitions are retained but unavailable.
**Definition.** Records that PortOS itself authors and relates: they have foreign keys, statuses, audit trails, search/vector indexes, and federated sync cursors/tombstones. The DB is the source of truth; there is no meaningful file representation of the record.
diff --git a/server/lib/db/schema/beeper.js b/server/lib/db/schema/beeper.js
index 8e14fac5a4..b69cb63106 100644
--- a/server/lib/db/schema/beeper.js
+++ b/server/lib/db/schema/beeper.js
@@ -146,6 +146,7 @@ export const beeperDdl = [
unsent_at TIMESTAMPTZ,
sort_key TEXT NOT NULL DEFAULT '',
is_sender BOOLEAN NOT NULL DEFAULT FALSE,
+ observed_at TIMESTAMPTZ NOT NULL DEFAULT 'epoch',
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
)`,
@@ -156,6 +157,7 @@ export const beeperDdl = [
// rather than NULL: an unbackfilled row renders as inbound, which is the
// right way round for a mirror that is mostly other people's messages.
`ALTER TABLE beeper_messages ADD COLUMN IF NOT EXISTS is_sender BOOLEAN NOT NULL DEFAULT FALSE`,
+ `ALTER TABLE beeper_messages ADD COLUMN IF NOT EXISTS observed_at TIMESTAMPTZ NOT NULL DEFAULT 'epoch'`,
// `idx_beeper_messages_conversation_sort (conversation_id, sort_key)` served
// no query — `sort_key` is written on ingest and never read back. A thread
// page (listMessages) and the "latest message" LATERAL each conversation
@@ -274,6 +276,15 @@ export const beeperDdl = [
PRIMARY KEY (account_id, chat_id)
)`,
+ // Machine-local rotating archive checkpoint, independent of forward ingestion.
+ `CREATE TABLE IF NOT EXISTS beeper_reconcile_cursors (
+ account_id TEXT PRIMARY KEY REFERENCES beeper_accounts (account_id) ON DELETE CASCADE,
+ message_id TEXT NOT NULL,
+ upper_bound TEXT
+ )`,
+
+ `ALTER TABLE beeper_reconcile_cursors ADD COLUMN IF NOT EXISTS upper_bound TEXT`,
+
// The outbound OUTBOX (#36, decided on #8). A row is written BEFORE the
// `POST /v1/chats/{chatID}/messages` that sends it, so intent survives a
// crash between the click and the POST, and one row is the serialization
diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sql
index 90d7aac2e2..39d87cca52 100644
--- a/server/scripts/init-db.sql
+++ b/server/scripts/init-db.sql
@@ -1799,6 +1799,7 @@ CREATE TABLE IF NOT EXISTS beeper_messages (
-- against the local user (accounts[].user.id differs from senderID on every
-- network), so this is the only reliable inbound/outbound signal.
is_sender BOOLEAN NOT NULL DEFAULT FALSE,
+ observed_at TIMESTAMPTZ NOT NULL DEFAULT 'epoch',
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
@@ -2244,3 +2245,9 @@ DROP TRIGGER IF EXISTS trg_catalog_ingredient_media_sync_feed ON catalog_ingredi
CREATE CONSTRAINT TRIGGER trg_catalog_ingredient_media_sync_feed AFTER INSERT OR DELETE ON catalog_ingredient_media DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION sync_feed_capture();
DROP TRIGGER IF EXISTS trg_catalog_ingredient_media_sync_feed_update ON catalog_ingredient_media;
CREATE CONSTRAINT TRIGGER trg_catalog_ingredient_media_sync_feed_update AFTER UPDATE ON catalog_ingredient_media DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (OLD.sync_sequence IS DISTINCT FROM NEW.sync_sequence) EXECUTE FUNCTION sync_feed_capture();
+
+CREATE TABLE IF NOT EXISTS beeper_reconcile_cursors (
+ account_id TEXT PRIMARY KEY REFERENCES beeper_accounts (account_id) ON DELETE CASCADE,
+ message_id TEXT NOT NULL,
+ upper_bound TEXT
+ );
diff --git a/server/services/beeperOutbox.js b/server/services/beeperOutbox.js
index 56f0567b00..b2709279b0 100644
--- a/server/services/beeperOutbox.js
+++ b/server/services/beeperOutbox.js
@@ -40,7 +40,7 @@
import { query, withTransaction } from '../lib/db.js';
import { BeeperApiError, getMessage, listMessagesPage, sendMessage } from './beeperClient.js';
-import { normalizeMessageRow } from './beeperSync.js';
+import { normalizeMessageRow, upsertMirroredMessage } from './beeperSync.js';
import { beeperSocketEvents } from './beeperSocketEvents.js';
const LOG_PREFIX = '🫧 Beeper outbox';
@@ -591,38 +591,13 @@ async function lookupSentMessage(pending) {
}) ?? null;
}
-/**
- * Mirror the confirmed message so the thread shows it without waiting for the
- * next sweep. `normalizeMessageRow` is beeperSync's own normalizer, reused so
- * an outbound row is shaped exactly like an ingested one; the upsert carries
- * the same non-destructive COALESCE guards as the sweep's, and the sweep's
- * later re-observation of the same id updates rather than duplicates it.
- *
- * `is_sender` is written as TRUE literally rather than from the normalizer's
- * `row.isSender`: PortOS just sent this message, so it is outbound whatever the
- * confirming payload says, and the field is optional on the API's own `Message`
- * (`normalizeMessageRow` lands an omitted one on FALSE). The ON CONFLICT arm
- * keeps the sweep's never-downgrade rule, so a later inbound page that omits
- * the field cannot flip a message the user sent onto the other side of the
- * thread.
+/** Mirror confirmed sends through the same version/retention gate as ingestion.
+ * PortOS knows this is outbound even when the source omits isSender.
*/
-async function mirrorSentMessage(client, conversationId, message) {
- const row = normalizeMessageRow(message, new Date(runtime.now()).toISOString());
+async function mirrorSentMessage(client, conversationId, message, observedAt) {
+ const row = normalizeMessageRow(message, observedAt);
if (!row.id) return;
- await client.query(
- `INSERT INTO beeper_messages (id, conversation_id, sender_id, body, sent_at, edited_at, unsent_at, sort_key, is_sender)
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, TRUE)
- ON CONFLICT (id) DO UPDATE SET
- body = COALESCE(NULLIF(EXCLUDED.body, ''), beeper_messages.body),
- sender_id = COALESCE(NULLIF(EXCLUDED.sender_id, ''), beeper_messages.sender_id),
- sent_at = COALESCE(EXCLUDED.sent_at, beeper_messages.sent_at),
- edited_at = COALESCE(EXCLUDED.edited_at, beeper_messages.edited_at),
- unsent_at = COALESCE(beeper_messages.unsent_at, EXCLUDED.unsent_at),
- sort_key = COALESCE(NULLIF(EXCLUDED.sort_key, ''), beeper_messages.sort_key),
- is_sender = beeper_messages.is_sender OR EXCLUDED.is_sender,
- updated_at = NOW()`,
- [row.id, conversationId, row.senderId, row.body, row.sentAt, row.editedAt, row.unsentAt, row.sortKey],
- );
+ await upsertMirroredMessage(client, conversationId, { ...row, isSender: true });
}
function releasePending(id) {
@@ -660,6 +635,7 @@ async function resolveConfirmation(id, reason, { terminal = false } = {}) {
if (pending.resolving) return null;
pending.resolving = true;
+ const observedAt = new Date(runtime.now()).toISOString();
const found = await lookupSentMessage(pending)
.then((value) => ({ ok: true, value }))
.catch((err) => ({ ok: false, err }));
@@ -709,7 +685,7 @@ async function resolveConfirmation(id, reason, { terminal = false } = {}) {
[id, String(message.id), message?.timestamp ?? null],
);
if ((settled?.rowCount ?? 0) !== 1) return null;
- await mirrorSentMessage(client, pending.conversationId, message);
+ await mirrorSentMessage(client, pending.conversationId, message, observedAt);
return settled.rows[0];
}), () => {
releasePending(id);
diff --git a/server/services/beeperOutbox.test.js b/server/services/beeperOutbox.test.js
index 9135b1cd28..44faa89221 100644
--- a/server/services/beeperOutbox.test.js
+++ b/server/services/beeperOutbox.test.js
@@ -44,17 +44,7 @@ vi.mock('./beeperClient.js', () => ({
// The real normalizer is pure and covered by beeperSync's own suite; mocked
// here only to keep the ingestion stack (settings, Tribe, the pool) out of this
// module graph.
-vi.mock('./beeperSync.js', () => ({
- normalizeMessageRow: (message, observedAt) => ({
- id: String(message?.id ?? ''),
- senderId: String(message?.senderID ?? ''),
- body: typeof message?.text === 'string' ? message.text : '',
- sentAt: message?.timestamp ?? null,
- editedAt: message?.editedTimestamp ?? null,
- unsentAt: message?.isDeleted === true ? observedAt : null,
- sortKey: String(message?.sortKey ?? ''),
- }),
-}));
+
// --- in-memory stand-in for the tables this service touches -----------------
const outbox = new Map();
@@ -606,13 +596,8 @@ describe('confirmation — socket first, 30s GET fallback', () => {
expect(mirrored).toHaveLength(1);
expect(mirrored[0][0]).toBe('msg-final-1');
expect(mirrored[0][1]).toBe(CONVERSATION_ID);
- // The mirrored row is OUTBOUND. `is_sender` is written as a literal TRUE
- // rather than read off the confirming payload — the field is optional on
- // the API's own Message, and PortOS knows it sent this one — and the
- // conflict arm keeps the sweep's never-downgrade rule so a later inbound
- // page that omits the field cannot flip it back to the other side.
- expect(mirroredSql[0]).toMatch(/INSERT INTO beeper_messages \([^)]*, is_sender\)/);
- expect(mirroredSql[0]).toMatch(/VALUES \(\$1, \$2, \$3, \$4, \$5, \$6, \$7, \$8, TRUE\)/);
+ // PortOS knows this is outbound even if the confirming payload omits isSender.
+ expect(mirrored[0][8]).toBe(true);
expect(mirroredSql[0]).toMatch(/is_sender = beeper_messages\.is_sender OR EXCLUDED\.is_sender/);
// The frame this service emits carries ids only — never the body.
const emitted = frames.find((frame) => frame.ids?.includes('msg-final-1') && frame.ts);
diff --git a/server/services/beeperSocket.js b/server/services/beeperSocket.js
index dbdf4bece5..bf01faa09b 100644
--- a/server/services/beeperSocket.js
+++ b/server/services/beeperSocket.js
@@ -50,7 +50,7 @@
import WebSocket from 'ws';
import { beeperSocketEvents } from './beeperSocketEvents.js';
import { DEFAULT_BASE_URL, resolveBeeperConfig } from './beeperClient.js';
-import { getBeeperSyncConfig, isBeeperIngestionArmed, runBeeperSweep } from './beeperSync.js';
+import { getBeeperSyncConfig, isBeeperIngestionArmed, runBeeperSweep, reconcileBeeperEvent } from './beeperSync.js';
const LOG_PREFIX = '🫧 Beeper socket';
@@ -396,7 +396,11 @@ function handleFrame(raw, target) {
return;
}
if (DOMAIN_EVENT_TYPES.has(frame.type)) {
- beeperSocketEvents.emit('invalidate', toInvalidation(frame));
+ const invalidation = toInvalidation(frame);
+ beeperSocketEvents.emit('invalidate', invalidation);
+ reconcileBeeperEvent(invalidation).catch(() => {
+ console.warn('🫧 Beeper message reconciliation deferred to the periodic sweep');
+ });
}
}
diff --git a/server/services/beeperSocket.test.js b/server/services/beeperSocket.test.js
index ada41acec7..93d29c1b39 100644
--- a/server/services/beeperSocket.test.js
+++ b/server/services/beeperSocket.test.js
@@ -59,6 +59,7 @@ let resolvedConfig = { baseUrl: 'http://127.0.0.1:23373', token: 'example-token'
const sweeps = [];
vi.mock('./beeperSync.js', () => ({
+ reconcileBeeperEvent: vi.fn(async () => {}),
isBeeperIngestionArmed: vi.fn(async () => armed),
getBeeperSyncConfig: vi.fn(async () => ({ enabled: syncEnabled, intervalMinutes: 5 })),
runBeeperSweep: vi.fn(async ({ reason }) => { sweeps.push(reason); return { skipped: false }; }),
diff --git a/server/services/beeperSync.db.test.js b/server/services/beeperSync.db.test.js
index 04851abc38..09286c0be6 100644
--- a/server/services/beeperSync.db.test.js
+++ b/server/services/beeperSync.db.test.js
@@ -34,14 +34,14 @@
import {
describe, it, expect, beforeAll, afterAll, vi,
} from 'vitest';
-import { checkHealth, ensureSchema, close, query } from '../lib/db.js';
+import { checkHealth, ensureSchema, close, query, withTransaction } from '../lib/db.js';
import { requireDbOrSkip } from '../lib/dbTestGate.js';
vi.mock('./settings.js', async (importOriginal) => {
const actual = await importOriginal();
return {
...actual,
- getSettings: async () => ({ beeper: { baseUrl: 'http://127.0.0.1:23373' } }),
+ getSettings: async () => ({ beeper: { baseUrl: 'http://127.0.0.1:23373', enabled: true } }),
};
});
@@ -55,7 +55,10 @@ vi.mock('./beeperCredentials.js', async (importOriginal) => {
};
});
-const { runBeeperSweep } = await import('./beeperSync.js');
+vi.mock('./instanceFeatures.js', () => ({ isInstanceFeatureEnabled: async () => true }));
+const { runBeeperSweep, reconcileBeeperEvent, upsertMirroredMessage, normalizeMessageRow } = await import('./beeperSync.js');
+const { listMessages: readThread } = await import('./beeperConversations.js');
+const { beeperSocketEvents } = await import('./beeperSocketEvents.js');
let dbReady = false;
let skipReason = '';
@@ -133,6 +136,11 @@ function installFetch({ chats, messages }) {
if (pathname === '/v1/bridges') return jsonResponse(BRIDGES);
if (pathname === '/v1/chats') return jsonResponse(chats);
if (/\/messages$/.test(pathname)) return jsonResponse(messages);
+ if (/\/messages\//.test(pathname)) {
+ const message = messages.items?.find((item) => pathname.endsWith('/' + encodeURIComponent(item.id)));
+ if (message) return jsonResponse(message);
+ return { ok: false, status: 404, text: async () => '{}' };
+ }
throw new Error(`unexpected fetch: ${url}`);
}));
return urls;
@@ -234,6 +242,68 @@ describe.skipIf(!runDb)('beeperSync against Postgres', () => {
expect(participant.rows[0]).toMatchObject({ display_name: 'Alice Example', handle: 'alice_example' });
});
+ it('repairs behind-cursor edits and missed events, preserving archive data and rejecting stale writers', async () => {
+ // Regression: neither forward pagination nor reader refetch could repair message 50.
+ const conversation = await query('SELECT conversation_id FROM beeper_messages WHERE id = $1', [MESSAGE_ID]);
+ const conversationId = conversation.rows[0].conversation_id;
+ const originalCursor = await query('SELECT cursor FROM beeper_sync_cursors WHERE account_id = $1', [ACCOUNT_ID]);
+ let upstream = { ...messageFixture(), text: 'Corrected example', editedTimestamp: '2026-09-04T12:00:00Z' };
+ const originalFetch = globalThis.fetch;
+ vi.stubGlobal('fetch', vi.fn(async (url) => {
+ if (new URL(url).pathname.endsWith('/messages/' + encodeURIComponent(MESSAGE_ID))) return jsonResponse(upstream);
+ return originalFetch(url);
+ }));
+ const persistedFrames = [];
+ const listener = (frame) => { if (frame.kind === 'beeper-reconciled') persistedFrames.push(frame); };
+ beeperSocketEvents.on('invalidate', listener);
+ try {
+ await reconcileBeeperEvent({ kind: 'message.upserted', chatID: CHAT_ID, ids: [MESSAGE_ID] });
+ expect((await readThread(conversationId)).messages[0]).toMatchObject({
+ body: 'Corrected example', editedAt: '2026-09-04T12:00:00.000Z',
+ });
+ expect(persistedFrames).toHaveLength(1);
+ // Both an older source version and an older same-version observation lose,
+ // even if a stale sweep/outbox transaction commits after the event.
+ await withTransaction(async (client) => {
+ await upsertMirroredMessage(client, conversationId,
+ normalizeMessageRow(messageFixture({ text: 'Stale example' }), '2099-01-01T00:00:00Z'));
+ await upsertMirroredMessage(client, conversationId,
+ normalizeMessageRow({ ...upstream, text: 'Older concurrent example' }, '2020-01-01T00:00:00Z'));
+ });
+ expect((await readThread(conversationId)).messages[0].body).toBe('Corrected example');
+
+ // Drop the event. An unchanged chat still participates in the independent
+ // stored-ID rotation. Persisted checkpoint is the only progress state.
+ upstream = { ...upstream, text: 'Missed event correction', editedTimestamp: '2026-09-05T12:00:00Z' };
+ await runBeeperSweep({ reason: 'db-test' });
+ expect((await readThread(conversationId)).messages[0].body).toBe('Missed event correction');
+ const progress = await query('SELECT message_id FROM beeper_reconcile_cursors WHERE account_id = $1', [ACCOUNT_ID]);
+ expect(progress.rows[0].message_id).toBe(MESSAGE_ID);
+ expect((await query('SELECT cursor FROM beeper_sync_cursors WHERE account_id = $1', [ACCOUNT_ID])).rows).toEqual(originalCursor.rows);
+
+ // End of rotation resets durably, then an unavailable fetch must not
+ // manufacture a source deletion. The next rotation retries the row.
+ upstream = null;
+ await runBeeperSweep({ reason: 'db-test' });
+ await runBeeperSweep({ reason: 'db-test' });
+ expect((await readThread(conversationId)).messages[0]).toMatchObject({
+ body: 'Missed event correction', unsentAt: null,
+ });
+ upstream = { ...messageFixture({ isDeleted: true }), text: 'Source tombstone placeholder' };
+ await reconcileBeeperEvent({ kind: 'message.deleted', chatID: CHAT_ID, ids: [MESSAGE_ID] });
+ await reconcileBeeperEvent({ kind: 'message.deleted', chatID: CHAT_ID, ids: [MESSAGE_ID] });
+ const archived = await query('SELECT body, unsent_at FROM beeper_messages WHERE id = $1', [MESSAGE_ID]);
+ expect(archived.rows[0].body).toBe('Missed event correction');
+ expect(archived.rows[0].unsent_at).toBeTruthy();
+ expect((await query('SELECT * FROM beeper_attachments WHERE message_id = $1', [MESSAGE_ID])).rows).toHaveLength(1);
+ expect((await readThread(conversationId)).messages[0]).toMatchObject({ body: '', unsentAt: expect.any(String) });
+ } finally {
+ beeperSocketEvents.off('invalidate', listener);
+ // Restore the fixture for the pre-existing forward-ingestion cases.
+ await query("UPDATE beeper_messages SET body = 'Example message body', edited_at = NULL, unsent_at = NULL, observed_at = 'epoch' WHERE id = $1", [MESSAGE_ID]);
+ }
+ });
+
it('keeps the body and stamps unsent_at when the source unsends the message', async () => {
installFetch({
chats: { items: [chatFixture('2026-09-03T10:00:00.000Z')], hasMore: false },
@@ -358,4 +428,44 @@ describe.skipIf(!runDb)('beeperSync against Postgres', () => {
const second = await query('SELECT is_sender FROM beeper_messages WHERE id = $1', [messageId]);
expect(second.rows[0].is_sender).toBe(true);
});
+ it('resumes a durable bounded rotation and retries failures without starving later rows', async () => {
+ const conversation = await query('SELECT id FROM beeper_conversations WHERE account_id = $1 LIMIT 1', [ACCOUNT_ID]);
+ const conversationId = conversation.rows[0].id;
+ const ids = Array.from({ length: 21 }, (_, i) => MESSAGE_ID + '-rotation-' + String(i).padStart(2, '0'));
+ await query(
+ "INSERT INTO beeper_messages (id, conversation_id, body) SELECT id, $2, 'Original' FROM unnest($1::text[]) id",
+ [ids, conversationId],
+ );
+ // Represents a restart: progress already exists in PostgreSQL, with no
+ // process-local rotation state to restore.
+ await query(
+ `INSERT INTO beeper_reconcile_cursors (account_id, message_id, upper_bound) VALUES ($1, $2, $3)
+ ON CONFLICT (account_id) DO UPDATE SET message_id = EXCLUDED.message_id, upper_bound = EXCLUDED.upper_bound`,
+ [ACCOUNT_ID, MESSAGE_ID, ids.at(-1)],
+ );
+ let failFirst = true;
+ const fetched = [];
+ vi.stubGlobal('fetch', vi.fn(async (url) => {
+ const pathname = new URL(url).pathname;
+ if (pathname === '/v1/accounts') return jsonResponse(ACCOUNTS);
+ if (pathname === '/v1/bridges') return jsonResponse(BRIDGES);
+ if (pathname === '/v1/chats') return jsonResponse({ items: [], hasMore: false });
+ const id = decodeURIComponent(pathname.split('/').at(-1));
+ fetched.push(id);
+ if (id === ids[0] && failFirst) return { ok: false, status: 404, text: async () => '{}' };
+ return jsonResponse({ id, text: 'Reconciled', editedTimestamp: '2026-09-06T00:00:00Z' });
+ }));
+ await runBeeperSweep({ reason: 'db-test' });
+ expect(fetched).toEqual(ids.slice(0, 20));
+ expect((await query('SELECT body, unsent_at FROM beeper_messages WHERE id = $1', [ids[0]])).rows[0])
+ .toMatchObject({ body: 'Original', unsent_at: null });
+ fetched.length = 0;
+ await runBeeperSweep({ reason: 'db-test' });
+ expect(fetched).toEqual([ids[20]]);
+ failFirst = false;
+ await runBeeperSweep({ reason: 'db-test' }); // end-of-rotation reset
+ await runBeeperSweep({ reason: 'db-test' });
+ expect((await query('SELECT body FROM beeper_messages WHERE id = $1', [ids[0]])).rows[0].body).toBe('Reconciled');
+ });
+
});
diff --git a/server/services/beeperSync.js b/server/services/beeperSync.js
index 3a2a34870b..80bab6e3ae 100644
--- a/server/services/beeperSync.js
+++ b/server/services/beeperSync.js
@@ -85,6 +85,7 @@ import {
getJoinedAccounts,
listChatsPage,
listMessagesPage,
+ getMessage,
} from './beeperClient.js';
import { upsertParticipant, logSenderTouchpoints, loadRosterIndex } from './beeperTribe.js';
import { isInstanceFeatureEnabled } from './instanceFeatures.js';
@@ -246,6 +247,7 @@ export function normalizeMessageRow(message, observedAt) {
// comparison against the local user cannot be made. Strict `=== true`, so a
// bridge that omits the field lands on inbound rather than on `undefined`.
isSender: message?.isSender === true,
+ observedAt,
};
}
@@ -445,61 +447,65 @@ async function upsertConversation(chat) {
return result.rows[0]?.id ?? null;
}
-/**
- * Message rows, attachment references and the cursor row — the one atomic
- * unit. Attachments are written after their message inside the SAME
- * transaction because `beeper_attachments.message_id` is a foreign key onto a
- * row this transaction is itself creating.
- *
- * Three COALESCE guards make a re-observation non-destructive, which matters
- * because an unsend arrives as a normal message with its text stripped:
- * `body` never regresses to empty, `unsent_at` never un-tombstones, and
- * `edited_at` never clears. #7's rule is that a body is never discarded
- * automatically, so the archive keeps the caption even after the source
- * forgets it.
+/** Shared transaction writer: source edit versions outrank fetch-start time.
+ * Tombstones are terminal and preserve the archived body and attachments.
*/
+export async function upsertMirroredMessage(client, conversationId, message, attachments = []) {
+ const result = await client.query(
+ `INSERT INTO beeper_messages (id, conversation_id, sender_id, body, sent_at, edited_at, unsent_at, sort_key, is_sender, observed_at)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
+ ON CONFLICT (id) DO UPDATE SET
+ body = CASE WHEN EXCLUDED.unsent_at IS NOT NULL OR beeper_messages.unsent_at IS NOT NULL
+ THEN beeper_messages.body ELSE COALESCE(NULLIF(EXCLUDED.body, ''), beeper_messages.body) END,
+ sender_id = COALESCE(NULLIF(EXCLUDED.sender_id, ''), beeper_messages.sender_id),
+ sent_at = COALESCE(EXCLUDED.sent_at, beeper_messages.sent_at),
+ edited_at = GREATEST(EXCLUDED.edited_at, beeper_messages.edited_at),
+ unsent_at = COALESCE(beeper_messages.unsent_at, EXCLUDED.unsent_at),
+ sort_key = COALESCE(NULLIF(EXCLUDED.sort_key, ''), beeper_messages.sort_key),
+ -- Never downgrades a stored TRUE to FALSE: the field is optional on
+ -- the inbound Message, so a later page that omits it must not flip a
+ -- message the user actually sent onto the other side of the thread.
+ is_sender = beeper_messages.is_sender OR EXCLUDED.is_sender,
+ observed_at = EXCLUDED.observed_at, updated_at = NOW()
+ WHERE beeper_messages.conversation_id = EXCLUDED.conversation_id
+ AND (EXCLUDED.unsent_at IS NOT NULL OR
+ (beeper_messages.unsent_at IS NULL
+ AND COALESCE(EXCLUDED.edited_at, 'epoch'::timestamptz) >= COALESCE(beeper_messages.edited_at, 'epoch'::timestamptz)
+ AND (EXCLUDED.edited_at > COALESCE(beeper_messages.edited_at, 'epoch'::timestamptz)
+ OR EXCLUDED.observed_at >= beeper_messages.observed_at)))
+ RETURNING id`,
+ [
+ message.id, conversationId, message.senderId, message.body,
+ message.sentAt, message.editedAt, message.unsentAt, message.sortKey,
+ message.isSender, message.observedAt,
+ ],
+ );
+ // A stale observation or tombstone must not rewrite attachment references.
+ if (result.rowCount === 0 || message.unsentAt) return;
+ for (const attachment of attachments) {
+ // eslint-disable-next-line no-await-in-loop -- same transaction, ordered after its message
+ await client.query(
+ `INSERT INTO beeper_attachments (conversation_id, message_id, idx, mxc_id, mime_type,
+ byte_length, file_name, width, height)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
+ ON CONFLICT (conversation_id, message_id, idx) DO UPDATE SET
+ mxc_id = COALESCE(EXCLUDED.mxc_id, beeper_attachments.mxc_id),
+ mime_type = EXCLUDED.mime_type, byte_length = EXCLUDED.byte_length,
+ file_name = EXCLUDED.file_name, width = EXCLUDED.width, height = EXCLUDED.height,
+ updated_at = NOW()`,
+ [
+ conversationId, message.id, attachment.idx, attachment.mxcId, attachment.mimeType,
+ attachment.byteLength, attachment.fileName, attachment.width, attachment.height,
+ ],
+ );
+ }
+}
+
async function commitMessages({ conversationId, accountId, sourceChatId, rows, cursor, lastActivity }) {
return withTransaction(async (client) => {
for (const { message, attachments } of rows) {
// eslint-disable-next-line no-await-in-loop -- ordered writes inside one transaction
- await client.query(
- `INSERT INTO beeper_messages (id, conversation_id, sender_id, body, sent_at, edited_at, unsent_at, sort_key, is_sender)
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
- ON CONFLICT (id) DO UPDATE SET
- body = COALESCE(NULLIF(EXCLUDED.body, ''), beeper_messages.body),
- sender_id = COALESCE(NULLIF(EXCLUDED.sender_id, ''), beeper_messages.sender_id),
- sent_at = COALESCE(EXCLUDED.sent_at, beeper_messages.sent_at),
- edited_at = COALESCE(EXCLUDED.edited_at, beeper_messages.edited_at),
- unsent_at = COALESCE(beeper_messages.unsent_at, EXCLUDED.unsent_at),
- sort_key = COALESCE(NULLIF(EXCLUDED.sort_key, ''), beeper_messages.sort_key),
- -- Never downgrades a stored TRUE to FALSE: the field is optional on
- -- the inbound Message, so a later page that omits it must not flip a
- -- message the user actually sent onto the other side of the thread.
- is_sender = beeper_messages.is_sender OR EXCLUDED.is_sender,
- updated_at = NOW()`,
- [
- message.id, conversationId, message.senderId, message.body,
- message.sentAt, message.editedAt, message.unsentAt, message.sortKey,
- message.isSender,
- ],
- );
- for (const attachment of attachments) {
- // eslint-disable-next-line no-await-in-loop -- same transaction, ordered after its message
- await client.query(
- `INSERT INTO beeper_attachments (conversation_id, message_id, idx, mxc_id, mime_type,
- byte_length, file_name, width, height)
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
- ON CONFLICT (conversation_id, message_id, idx) DO UPDATE SET
- mxc_id = COALESCE(EXCLUDED.mxc_id, beeper_attachments.mxc_id),
- mime_type = EXCLUDED.mime_type, byte_length = EXCLUDED.byte_length,
- file_name = EXCLUDED.file_name, width = EXCLUDED.width, height = EXCLUDED.height,
- updated_at = NOW()`,
- [
- conversationId, message.id, attachment.idx, attachment.mxcId, attachment.mimeType,
- attachment.byteLength, attachment.fileName, attachment.width, attachment.height,
- ],
- );
- }
+ await upsertMirroredMessage(client, conversationId, message, attachments);
}
// The cursor moves LAST and only inside this transaction, so a failure
@@ -703,6 +709,7 @@ async function sweepChat({
* the checkpoint so failed chats remain reachable on subsequent traversals.
*/
async function sweepAccount(account, clientOptions, observedAt, personIndex) {
+ await reconcileStoredMessages(account.accountId, clientOptions);
const cursors = await readAccountCursors(account.accountId);
const checkpoint = await query('SELECT chat_cursor FROM beeper_accounts WHERE account_id = $1', [account.accountId]);
let cursor = checkpoint.rows[0]?.chat_cursor || undefined;
@@ -771,6 +778,112 @@ async function sweepAccount(account, clientOptions, observedAt, personIndex) {
return { chatsSwept, messagesWritten, failedChats, continuationPending, cursorRestarts };
}
+// One bounded rotation per account, independent of the forward message cursor.
+// A persisted upper bound makes each rotation finite even during new ingestion.
+// Advance past failures so one inaccessible message cannot starve the archive;
+// a later rotation retries it. No failure is interpreted as a deletion.
+const RECONCILE_LIMIT = 20;
+
+async function reconcileStoredRow(row, clientOptions) {
+ const observedAt = new Date().toISOString();
+ const raw = await getMessage(row.source_chat_id, row.id, clientOptions);
+ if (raw?.id !== row.id) throw new Error('Unexpected Beeper message identity');
+ await withTransaction(async (client) => {
+ // Lock the existing row: purge must not resurrect a message while HTTP was in flight.
+ const existing = await client.query(
+ 'SELECT id FROM beeper_messages WHERE id = $1 AND conversation_id = $2 FOR UPDATE',
+ [row.id, row.conversation_id],
+ );
+ if (!existing.rows.length) return;
+ await upsertMirroredMessage(client, row.conversation_id,
+ normalizeMessageRow(raw, observedAt), normalizeAttachmentRows(raw));
+ });
+ beeperSocketEvents.emit('invalidate', {
+ kind: 'beeper-reconciled', chatID: row.source_chat_id, ids: [row.id],
+ seq: null, ts: observedAt,
+ });
+}
+
+async function reconcileStoredMessages(accountId, clientOptions) {
+ const checkpoint = await query(
+ 'SELECT message_id, upper_bound FROM beeper_reconcile_cursors WHERE account_id = $1', [accountId],
+ );
+ let position = checkpoint.rows[0];
+ if (!position?.upper_bound) {
+ const boundary = await query(
+ `SELECT MAX(m.id) AS upper_bound FROM beeper_messages m
+ JOIN beeper_conversations c ON c.id = m.conversation_id WHERE c.account_id = $1`, [accountId],
+ );
+ if (!boundary.rows[0]?.upper_bound) return;
+ position = { message_id: '', upper_bound: boundary.rows[0].upper_bound };
+ await query(
+ `INSERT INTO beeper_reconcile_cursors (account_id, message_id, upper_bound) VALUES ($1, '', $2)
+ ON CONFLICT (account_id) DO UPDATE SET message_id = '', upper_bound = EXCLUDED.upper_bound`,
+ [accountId, position.upper_bound],
+ );
+ }
+ const result = await query(
+ `SELECT m.id, m.conversation_id, c.source_chat_id
+ FROM beeper_messages m JOIN beeper_conversations c ON c.id = m.conversation_id
+ WHERE c.account_id = $1 AND m.id > $2 AND m.id <= $4 ORDER BY m.id LIMIT $3`,
+ [accountId, position.message_id, RECONCILE_LIMIT, position.upper_bound],
+ );
+ for (const row of result.rows) {
+ // eslint-disable-next-line no-await-in-loop -- bounded sequential upstream work
+ await reconcileStoredRow(row, clientOptions).catch(() => {
+ console.warn('🫧 Beeper reconciliation deferred a message until the next rotation');
+ });
+ // Progress commits after persistence; a crash before this repeats harmlessly.
+ // eslint-disable-next-line no-await-in-loop -- durable checkpoint follows each attempt
+ await query(
+ `UPDATE beeper_reconcile_cursors SET message_id = $2 WHERE account_id = $1`,
+ [accountId, row.id],
+ );
+ }
+ if (result.rows.length === 0) {
+ await query('DELETE FROM beeper_reconcile_cursors WHERE account_id = $1', [accountId]);
+ }
+}
+
+// Bound both the event queue and concurrency. Overflow is repaired by the
+// durable rotation; event payloads never authorize ingesting unmirrored history.
+const pendingReconciliations = new Map();
+let eventReconciliation = null;
+export function reconcileBeeperEvent(frame) {
+ if (!['message.upserted', 'message.deleted'].includes(frame?.kind) || !frame.chatID) return Promise.resolve();
+ for (const id of (frame.ids || []).slice(0, RECONCILE_LIMIT)) {
+ if (typeof id === 'string' && pendingReconciliations.size < 100) {
+ pendingReconciliations.set(JSON.stringify([frame.chatID, id]), { chatID: frame.chatID, id });
+ }
+ }
+ if (eventReconciliation) return eventReconciliation;
+ eventReconciliation = drainReconciliationEvents().finally(() => { eventReconciliation = null; });
+ return eventReconciliation;
+}
+
+async function drainReconciliationEvents() {
+ while (pendingReconciliations.size) {
+ const [key, item] = pendingReconciliations.entries().next().value;
+ pendingReconciliations.delete(key);
+ // eslint-disable-next-line no-await-in-loop -- recheck ingestion consent for queued work
+ const config = await getBeeperSyncConfig();
+ // eslint-disable-next-line no-await-in-loop -- credential/feature gate
+ if (!config.enabled || !await isBeeperIngestionArmed()) {
+ pendingReconciliations.clear();
+ return;
+ }
+ // eslint-disable-next-line no-await-in-loop -- one transport request at a time
+ await (async () => {
+ const result = await query(
+ `SELECT m.id, m.conversation_id, c.source_chat_id
+ FROM beeper_messages m JOIN beeper_conversations c ON c.id = m.conversation_id
+ WHERE m.id = $1 AND c.source_chat_id = $2`, [item.id, item.chatID],
+ );
+ if (result.rows[0]) await reconcileStoredRow(result.rows[0], await resolveBeeperConfig());
+ })().catch(() => console.warn('🫧 Beeper event reconciliation deferred to the periodic rotation'));
+ }
+}
+
// A per-run re-entrancy guard: one sweep at a time, process-wide. The timer,
// the manual run-now route and #33's three socket triggers (reconnect, `seq`
// gap, `app.state` recovery) all land here, and two overlapping sweeps would
diff --git a/server/services/beeperSync.test.js b/server/services/beeperSync.test.js
index f5dd321154..f700854227 100644
--- a/server/services/beeperSync.test.js
+++ b/server/services/beeperSync.test.js
@@ -82,7 +82,8 @@ vi.mock('./beeperTribe.js', () => ({
}));
const {
- runBeeperSweep, isBeeperIngestionArmed, getBeeperSyncConfig, chatNeedsSweep,
+ runBeeperSweep,
+ reconcileBeeperEvent, isBeeperIngestionArmed, getBeeperSyncConfig, chatNeedsSweep,
normalizeAccountRow, normalizeMessageRow, normalizeAttachmentRows, DEFAULT_INTERVAL_MINUTES,
} = await import('./beeperSync.js');
const { getBeeperSweepProgress, __resetBeeperSweepProgressForTests } = await import('./beeperSweepProgress.js');
@@ -561,7 +562,7 @@ describe('cursor transactionality', () => {
const insert = txWrites.find(({ text }) => text.includes('INSERT INTO beeper_messages'));
expect(insert).toBeTruthy();
- expect(insert.params.at(-1)).toBe(true);
+ expect(insert.params[8]).toBe(true);
// A later page may omit the optional field; the upsert must not flip a
// message the user actually sent onto the other side of the thread. This is
// the guard's SHAPE against a mocked client — the row-level proof that a
@@ -1215,3 +1216,17 @@ describe('account enumeration continuation', () => {
expect(accountCheckpoint).toBe('21');
});
});
+
+describe('stored-message event reconciliation', () => {
+ it('does no transport work when ingestion is disabled or the message is not mirrored', async () => {
+ installFetch();
+ getSettingsMock.mockResolvedValue({ beeper: { enabled: false } });
+ await reconcileBeeperEvent({ kind: 'message.upserted', chatID: 'example-chat', ids: ['old-message'] });
+ expect(dbCalls).toEqual([]);
+ expect(fetchedUrls).toEqual([]);
+ getSettingsMock.mockResolvedValue({ beeper: { enabled: true, token: 'test-token' } });
+ await reconcileBeeperEvent({ kind: 'message.deleted', chatID: 'example-chat', ids: ['unknown-message'] });
+ expect(fetchedUrls).toEqual([]);
+ expect(txWrites).toEqual([]);
+ });
+});