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: preserve Beeper send timestamps during reconciliation (#7178)

[._.]/ Adam Eivy08ce1571acd8
diff --git a/client/src/hooks/useBeeperOutbox.js b/client/src/hooks/useBeeperOutbox.js
index 238842ed8b..e4564115fe 100644
--- a/client/src/hooks/useBeeperOutbox.js
+++ b/client/src/hooks/useBeeperOutbox.js
@@ -231,12 +231,12 @@ export default function useBeeperOutbox(conversationId, { onSent } = {}) {
const dismiss = useCallback((entry) => discardEntry(entry), [discardEntry]);
const reconcile = useCallback(async (entry) => {
+ const generation = ++scope.refreshGeneration;
const updated = await reconcileOutboxEntry(entry.id, { silent: true }).catch((err) => {
if (mountedRef.current && scopeRef.current === scope) toast.error(err.message || 'Could not check delivery');
return null;
});
- if (!updated || !mountedRef.current || scopeRef.current !== scope) return;
- ++scope.refreshGeneration;
+ if (!updated || !mountedRef.current || scopeRef.current !== scope || generation !== scope.refreshGeneration) return;
setEntries((prev) => prev.map((row) => row.id === updated.id ? updated : row));
}, [scope]);
diff --git a/client/src/hooks/useBeeperOutbox.test.jsx b/client/src/hooks/useBeeperOutbox.test.jsx
index 9464296db7..c441abd689 100644
--- a/client/src/hooks/useBeeperOutbox.test.jsx
+++ b/client/src/hooks/useBeeperOutbox.test.jsx
@@ -81,6 +81,24 @@ describe('useBeeperOutbox', () => {
expect(result.current.entries).toEqual([]);
});
+ it('does not overwrite a newer socket refresh with a delayed delivery-check response', async () => {
+ const pending = { ...ENTRY, state: 'awaiting-confirmation' };
+ listOutboxEntries.mockResolvedValue({ entries: [pending] });
+ const { result } = renderHook(() => useBeeperOutbox(CONVERSATION_ID));
+ await waitFor(() => expect(result.current.entries).toHaveLength(1));
+ let finish;
+ reconcileOutboxEntry.mockReturnValueOnce(new Promise((resolve) => { finish = resolve; }));
+ let checking;
+ act(() => { checking = result.current.reconcile(pending); });
+ listOutboxEntries.mockResolvedValue({ entries: [{ ...pending, state: 'sent' }] });
+ await act(async () => {
+ for (const handle of invalidateHandlers) handle?.({ kind: 'outbox.updated' });
+ });
+ await waitFor(() => expect(result.current.entries[0].state).toBe('sent'));
+ await act(async () => { finish(pending); await checking; });
+ expect(result.current.entries[0].state).toBe('sent');
+ });
+
it('creates the durable row first, then sends it exactly once', async () => {
const onSent = vi.fn();
const { result } = renderHook(() => useBeeperOutbox(CONVERSATION_ID, { onSent }));
diff --git a/scripts/migrations/382-beeper-outbox-send-time.js b/scripts/migrations/382-beeper-outbox-send-time.js
new file mode 100644
index 0000000000..e3c6c63ad6
--- /dev/null
+++ b/scripts/migrations/382-beeper-outbox-send-time.js
@@ -0,0 +1,11 @@
+/**
+ * Register the immutable Beeper send-attempt timestamp (#7178).
+ * ensureSchema applies the additive nullable column at boot, when the pool is
+ * ready. Old rows keep NULL: their original attempt time cannot be recreated
+ * after later recovery writes, so lookup retains its conservative legacy floor.
+ */
+export default {
+ async up() {
+ console.log('🫧 Beeper send-attempt timestamp is added idempotently by ensureSchema at boot');
+ },
+};
diff --git a/server/lib/db.ddlParity.test.js b/server/lib/db.ddlParity.test.js
index 51105c8aba..b30f273108 100644
--- a/server/lib/db.ddlParity.test.js
+++ b/server/lib/db.ddlParity.test.js
@@ -324,6 +324,7 @@ describe('DDL parity (init-db.sql ↔ db/schema ensureSchema)', () => {
it('beeper_* additive columns carry an ALTER TABLE for existing installs', () => {
for (const { table, columns } of [
{ table: 'beeper_messages', columns: ['is_sender'] },
+ { table: 'beeper_outbox', columns: ['send_requested_at'] },
{ table: 'beeper_attachments', columns: ['local_path', 'fetched_at', 'unavailable_at', 'fetch_error'] },
{ table: 'beeper_conversations', columns: ['seen_at'] },
]) {
diff --git a/server/lib/db/schema/beeper.js b/server/lib/db/schema/beeper.js
index 7f0c3b4c8f..6a9c838d40 100644
--- a/server/lib/db/schema/beeper.js
+++ b/server/lib/db/schema/beeper.js
@@ -306,9 +306,11 @@ export const beeperDdl = [
error_message TEXT,
created_at TIMESTAMPTZ DEFAULT NOW(),
approved_at TIMESTAMPTZ,
+ send_requested_at TIMESTAMPTZ,
sent_at TIMESTAMPTZ,
updated_at TIMESTAMPTZ DEFAULT NOW()
)`,
+ `ALTER TABLE beeper_outbox ADD COLUMN IF NOT EXISTS send_requested_at TIMESTAMPTZ`,
`CREATE INDEX IF NOT EXISTS idx_beeper_outbox_conversation_state ON beeper_outbox (conversation_id, state, created_at DESC)`,
// #96 backfill — one idempotent statement, LAST in this array because it
diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sql
index acee4b5892..335d75ee65 100644
--- a/server/scripts/init-db.sql
+++ b/server/scripts/init-db.sql
@@ -1822,6 +1822,7 @@ CREATE TABLE IF NOT EXISTS beeper_outbox (
error_message TEXT,
created_at TIMESTAMPTZ DEFAULT NOW(),
approved_at TIMESTAMPTZ,
+ send_requested_at TIMESTAMPTZ,
sent_at TIMESTAMPTZ,
updated_at TIMESTAMPTZ DEFAULT NOW()
);
diff --git a/server/services/beeperOutbox.js b/server/services/beeperOutbox.js
index 6fac755752..d8ba7c80f0 100644
--- a/server/services/beeperOutbox.js
+++ b/server/services/beeperOutbox.js
@@ -116,6 +116,7 @@ let breaker = { tripped: false, reason: null, trippedAt: null };
const pendingConfirmations = new Map();
const localTransitions = new Map();
const activeSends = new Set();
+const reconciliationOperations = new Map();
export const PERSISTENCE_RETRY_DELAYS_MS = Object.freeze([1000, 2000, 4000]);
const PERSISTENCE_RECOVERY_MESSAGE = 'Delivery unconfirmed: saving the send outcome failed. Check delivery to reconcile without sending again.';
@@ -250,7 +251,7 @@ function registerSendSuccess() {
const ENTRY_COLUMNS = `id, conversation_id AS "conversationId", chat_id AS "chatId", body, state,
pending_message_id AS "pendingMessageId", message_id AS "messageId",
error_code AS "errorCode", error_message AS "errorMessage",
- created_at AS "createdAt", updated_at AS "updatedAt", approved_at AS "approvedAt", sent_at AS "sentAt"`;
+ send_requested_at AS "requestedAt", created_at AS "createdAt", updated_at AS "updatedAt", approved_at AS "approvedAt", sent_at AS "sentAt"`;
async function readEntry(id) {
const result = await query(`SELECT ${ENTRY_COLUMNS} FROM beeper_outbox WHERE id = $1`, [id]);
@@ -443,9 +444,10 @@ export async function sendOutboxEntry(id, { confirmFirstContact = false } = {})
// The serialization point. A second concurrent send of the same row loses
// this conditional UPDATE and never reaches the POST.
+ const requestedAt = runtime.now();
const claimed = await query(
- "UPDATE beeper_outbox SET state = 'sending', updated_at = NOW() WHERE id = $1 AND state = 'approved' RETURNING id",
- [id],
+ "UPDATE beeper_outbox SET state = 'sending', send_requested_at = $2::timestamptz, updated_at = NOW() WHERE id = $1 AND state = 'approved' RETURNING id",
+ [id, new Date(requestedAt).toISOString()],
);
if ((claimed?.rowCount ?? 0) !== 1) {
throw new BeeperApiError('Outbox entry is already being sent', {
@@ -455,7 +457,6 @@ export async function sendOutboxEntry(id, { confirmFirstContact = false } = {})
// Retry is OFF (the client's send-safe default): no idempotency key means a
// retried POST is a second real message. One attempt, one row, no second POST.
- const requestedAt = runtime.now();
activeSends.add(id);
const result = await sendMessage(entry.chatId, { text: entry.body })
.then((value) => ({ ok: true, value }))
@@ -733,10 +734,18 @@ export function cancelPendingConfirmations() {
for (const transition of localTransitions.values()) runtime.clearTimeout(transition.timer);
localTransitions.clear();
activeSends.clear();
+ reconciliationOperations.clear();
}
/** Human-triggered reconciliation. Remote operations are GETs only. */
-export async function reconcileOutboxEntry(id) {
+export function reconcileOutboxEntry(id) {
+ if (reconciliationOperations.has(id)) return reconciliationOperations.get(id);
+ const operation = reconcileEntry(id).finally(() => reconciliationOperations.delete(id));
+ reconciliationOperations.set(id, operation);
+ return operation;
+}
+
+async function reconcileEntry(id) {
let entry = await readEntry(id);
if (!entry) throw new BeeperApiError('Outbox entry not found', { status: 404, code: 'OUTBOX_ENTRY_NOT_FOUND' });
if (activeSends.has(id)) return entry;
@@ -766,7 +775,7 @@ export async function reconcileOutboxEntry(id) {
/** The send moment a re-armed row is matched against, from what the row kept. */
function persistedSendMoment(row) {
- const stamped = Date.parse(row?.updatedAt ?? row?.createdAt ?? '');
+ const stamped = Date.parse(row?.requestedAt ?? row?.updatedAt ?? row?.createdAt ?? '');
return Number.isFinite(stamped) ? stamped : runtime.now();
}
@@ -803,7 +812,7 @@ function persistedSendMoment(row) {
*/
export async function reconcileOutboxOnBoot() {
const interrupted = await query(
- `UPDATE beeper_outbox SET state = 'failed', error_code = $1, error_message = $2, updated_at = NOW()
+ `UPDATE beeper_outbox SET state = 'failed', error_code = $1, error_message = $2
WHERE state = 'sending' RETURNING id`,
[SEND_INTERRUPTED_CODE, SEND_INTERRUPTED_MESSAGE],
).catch((err) => {
@@ -813,10 +822,13 @@ export async function reconcileOutboxOnBoot() {
// The table does not exist yet, so neither do the rows this would reconcile.
if (!interrupted) return { interrupted: 0, rearmed: 0 };
+ // JSON access tolerates the first upgrade boot, which can precede ensureSchema.
+ // Old rows have no immutable timestamp: keep their prior conservative floor.
const inFlight = await query(
`SELECT id, conversation_id AS "conversationId", chat_id AS "chatId", body,
pending_message_id AS "pendingMessageId", error_code AS "errorCode",
- created_at AS "createdAt", updated_at AS "updatedAt"
+ created_at AS "createdAt", updated_at AS "updatedAt",
+ to_jsonb(beeper_outbox)->>'send_requested_at' AS "requestedAt"
FROM beeper_outbox WHERE state = 'awaiting-confirmation'`,
);
diff --git a/server/services/beeperOutbox.test.js b/server/services/beeperOutbox.test.js
index fa4828d9a5..1476c210ea 100644
--- a/server/services/beeperOutbox.test.js
+++ b/server/services/beeperOutbox.test.js
@@ -139,6 +139,7 @@ const query = vi.fn(async (sql, params = []) => {
const row = outbox.get(params[0]);
if (row?.state !== 'approved') return { rows: [], rowCount: 0 };
row.state = 'sending';
+ row.requestedAt = params[1];
return { rows: [{ id: row.id }], rowCount: 1 };
}
if (/UPDATE beeper_outbox SET state = 'awaiting-confirmation'/.test(sql)) {
@@ -987,3 +988,26 @@ describe('local persistence recovery without another send', () => {
expect(mirrored).toHaveLength(1);
});
});
+
+
+it('keeps the original send time through timeout, boot and overlapping manual recovery', async () => {
+ const entry = await createOutboxEntry({ conversationId: CONVERSATION_ID, body: 'hello there' });
+ sendMessage.mockRejectedValueOnce(new BeeperApiError('response lost', { status: 0, code: 'NETWORK_ERROR' }));
+ listMessagesPage.mockResolvedValue({ items: [] });
+ await sendOutboxEntry(entry.id, { confirmFirstContact: true });
+ clock.runTimersWithDelay(CONFIRMATION_TIMEOUT_MS);
+ await flush();
+ const row = outbox.get(entry.id);
+ row.updatedAt = '2026-09-01T00:01:00.000Z';
+ // Represent process loss at either durable nonterminal state.
+ row.state = 'sending';
+ await reconcileOutboxOnBoot();
+ expect(row.state).toBe('failed');
+ listMessagesPage.mockResolvedValue({ items: [sentMessage()] });
+ const first = reconcileOutboxEntry(entry.id);
+ const second = reconcileOutboxEntry(entry.id);
+ expect(first).toBe(second);
+ expect(await first).toMatchObject({ state: 'sent' });
+ expect(mirrored).toHaveLength(1);
+ expect(sendMessage).toHaveBeenCalledTimes(1);
+});