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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: recover Beeper delivery state after database failures (#7178)
[._.]/ Adam Eivy9096cb8442f6
diff --git a/client/src/components/messages/beeper/BeeperChatSurface.jsx b/client/src/components/messages/beeper/BeeperChatSurface.jsxindex 89f3b1fccd..b6d6efd553 100644--- a/client/src/components/messages/beeper/BeeperChatSurface.jsx+++ b/client/src/components/messages/beeper/BeeperChatSurface.jsx@@ -679,6 +679,7 @@ export default function BeeperChatSurface({cancelConfirmation: cancelOutboxConfirmation,retry: retryOutboxEntry,dismiss: dismissOutboxEntry,+ reconcile: reconcileOutboxEntry,} = useBeeperOutbox(conversationId, {onSent: (sentConversationId, body) => setDrafts((prev) => {// A send can finish after navigation or another draft edit. Clear only@@ -1050,6 +1051,7 @@ export default function BeeperChatSurface({cancelConfirmation={cancelOutboxConfirmation}retryOutboxEntry={retryOutboxEntry}dismissOutboxEntry={dismissOutboxEntry}+ reconcileOutboxEntry={reconcileOutboxEntry}breaker={breaker}people={people}linkingId={linkingId}diff --git a/client/src/components/messages/beeper/BeeperThread.jsx b/client/src/components/messages/beeper/BeeperThread.jsxindex 5997afd3e5..e01c3aa73f 100644--- a/client/src/components/messages/beeper/BeeperThread.jsx+++ b/client/src/components/messages/beeper/BeeperThread.jsx@@ -377,7 +377,7 @@ function TitleTribeChip({ conversation, onOpenParticipants, onOpenPerson }) {* and its 429 toasts, so it stays enabled.*/function OutboxRow({- entry, sending, isConfirming, onRetry, onDismiss, breakerTripped, breakerReason,+ entry, sending, isConfirming, onRetry, onDismiss, onReconcile, breakerTripped, breakerReason,}) {const failed = entry.state === 'failed';const interrupted = entry.errorCode === 'SEND_INTERRUPTED';@@ -402,7 +402,7 @@ function OutboxRow({const unconfirmedReason = interrupted? (entry.errorMessage || SEND_INTERRUPTED_COPY): (responseLost- ? DELIVERY_UNCONFIRMED_COPY+ ? (entry.errorCode === 'DELIVERY_UNCONFIRMED' && entry.errorMessage || DELIVERY_UNCONFIRMED_COPY): `Sent, unconfirmed${entry.errorMessage ? ` — ${entry.errorMessage}` : ''}`);return (<div@@ -446,6 +446,13 @@ function OutboxRow({{unconfirmedReason}</span>)}+ {onReconcile && (unconfirmed || entry.state === 'sending' || entry.state === 'awaiting-confirmation') && (+ <button type="button" onClick={() => onReconcile(entry)} disabled={sending}+ title="Look up delivery without sending another message"+ className="rounded px-1 py-0.5 text-port-accent hover:underline disabled:opacity-50">+ Check delivery+ </button>+ )}{!blocked && !unconfirmed && (<span className="flex items-center gap-1 text-gray-400"><Loader2 size={10} className="animate-spin" />@@ -476,6 +483,7 @@ export default function BeeperThread({cancelConfirmation,retryOutboxEntry,dismissOutboxEntry,+ reconcileOutboxEntry,breaker = null,people,linkingId,@@ -897,6 +905,7 @@ export default function BeeperThread({sending={sending}isConfirming={confirmation?.entry?.id === entry.id}onRetry={handleRetry}+ onReconcile={reconcileOutboxEntry}onDismiss={handleDismiss}breakerTripped={breakerTripped}breakerReason={sendDisabledReason}diff --git a/client/src/components/messages/beeper/BeeperThread.test.jsx b/client/src/components/messages/beeper/BeeperThread.test.jsxindex 024e809095..357069ef6a 100644--- a/client/src/components/messages/beeper/BeeperThread.test.jsx+++ b/client/src/components/messages/beeper/BeeperThread.test.jsx@@ -931,3 +931,14 @@ describe('BeeperThread — change and unlink a linked participant', () => {expect(screen.queryByLabelText('Link Sam Example to a Tribe person')).not.toBeInTheDocument();});});+++it('offers a lookup-only delivery check for persistence uncertainty, preserving the explanation', () => {+ const reconcileOutboxEntry = vi.fn();+ const entry = { ...UNRESOLVED_ENTRY, errorCode: 'DELIVERY_UNCONFIRMED', errorMessage: 'Delivery unconfirmed: saving the send outcome failed. Check delivery to reconcile without sending again.' };+ renderThread({ outboxEntries: [entry], reconcileOutboxEntry });+ expect(screen.getByText(entry.errorMessage)).toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: 'Check delivery' }));+ expect(reconcileOutboxEntry).toHaveBeenCalledWith(entry);+ expect(screen.queryByRole('button', { name: 'Retry' })).toBeNull();+});diff --git a/client/src/hooks/useBeeperOutbox.js b/client/src/hooks/useBeeperOutbox.jsindex 95dbbef3f2..238842ed8b 100644--- a/client/src/hooks/useBeeperOutbox.js+++ b/client/src/hooks/useBeeperOutbox.js@@ -1,7 +1,7 @@import { useCallback, useEffect, useRef, useState } from 'react';import toast from '../components/ui/Toast';import {- createOutboxEntry, discardOutboxEntry, listOutboxEntries, sendOutboxEntry,+ createOutboxEntry, discardOutboxEntry, listOutboxEntries, sendOutboxEntry, reconcileOutboxEntry,} from '../services/apiBeeper';import useBeeperRealtime from './useBeeperRealtime';import useMounted from './useMounted';@@ -230,6 +230,16 @@ export default function useBeeperOutbox(conversationId, { onSent } = {}) {/** Give up on a stalled `approved` row outright — see `discardEntry`. */const dismiss = useCallback((entry) => discardEntry(entry), [discardEntry]);+ const reconcile = useCallback(async (entry) => {+ 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;+ setEntries((prev) => prev.map((row) => row.id === updated.id ? updated : row));+ }, [scope]);+return {entries,sending,@@ -240,6 +250,7 @@ export default function useBeeperOutbox(conversationId, { onSent } = {}) {cancelConfirmation,retry,dismiss,+ reconcile,refresh,};}diff --git a/client/src/hooks/useBeeperOutbox.test.jsx b/client/src/hooks/useBeeperOutbox.test.jsxindex abefae8c14..9464296db7 100644--- a/client/src/hooks/useBeeperOutbox.test.jsx+++ b/client/src/hooks/useBeeperOutbox.test.jsx@@ -13,12 +13,14 @@ const listOutboxEntries = vi.fn();const createOutboxEntry = vi.fn();const sendOutboxEntry = vi.fn();const discardOutboxEntry = vi.fn();+const reconcileOutboxEntry = vi.fn();vi.mock('../services/apiBeeper', () => ({listOutboxEntries: (...args) => listOutboxEntries(...args),createOutboxEntry: (...args) => createOutboxEntry(...args),sendOutboxEntry: (...args) => sendOutboxEntry(...args),discardOutboxEntry: (...args) => discardOutboxEntry(...args),+ reconcileOutboxEntry: (...args) => reconcileOutboxEntry(...args),}));const invalidateHandlers = new Set();@@ -53,10 +55,32 @@ describe('useBeeperOutbox', () => {sendOutboxEntry.mockReset().mockResolvedValue({ ...ENTRY, state: 'awaiting-confirmation' });discardOutboxEntry.mockReset().mockResolvedValue(undefined);toastError.mockReset();+ reconcileOutboxEntry.mockReset();invalidateHandlers.clear();});afterEach(cleanup);+ it('checks delivery in place without sending or clearing the composer, and ignores a late result from another chat', async () => {+ const pending = { ...ENTRY, state: 'awaiting-confirmation', errorCode: 'DELIVERY_UNCONFIRMED' };+ listOutboxEntries.mockResolvedValue({ entries: [pending] });+ const onSent = vi.fn();+ const { result, rerender } = renderHook(({ id }) => useBeeperOutbox(id, { onSent }), { initialProps: { id: CONVERSATION_ID } });+ await waitFor(() => expect(result.current.entries).toHaveLength(1));+ reconcileOutboxEntry.mockResolvedValueOnce({ ...pending, state: 'sent' });+ await act(async () => result.current.reconcile(pending));+ expect(result.current.entries[0].state).toBe('sent');+ expect(sendOutboxEntry).not.toHaveBeenCalled();+ expect(onSent).not.toHaveBeenCalled();+ let finish;+ reconcileOutboxEntry.mockReturnValueOnce(new Promise((resolve) => { finish = resolve; }));+ let checking;+ act(() => { checking = result.current.reconcile(pending); });+ listOutboxEntries.mockResolvedValue({ entries: [] });+ rerender({ id: 'other-chat' });+ await act(async () => { finish({ ...pending, state: 'sent' }); await checking; });+ expect(result.current.entries).toEqual([]);+ });+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/client/src/services/apiBeeper.js b/client/src/services/apiBeeper.jsindex 46ee4cf868..fec5a2cae7 100644--- a/client/src/services/apiBeeper.js+++ b/client/src/services/apiBeeper.js@@ -176,3 +176,6 @@ export const discardOutboxEntry = (id, options = {}) => request(`/beeper/outbox/method: 'DELETE',...options,});++/** Read delivery state and finish local persistence, without sending again. */+export const reconcileOutboxEntry = (id, options = {}) => request(`/beeper/outbox/${encodeURIComponent(id)}/reconcile`, { method: 'POST', ...options });diff --git a/server/routes/beeper.js b/server/routes/beeper.jsindex 1ef5d148dc..e5e4cd470d 100644--- a/server/routes/beeper.js+++ b/server/routes/beeper.js@@ -13,7 +13,7 @@ import { getBeeperStatus, checkBeeperConnection } from '../services/beeperStatusimport { completeBeeperOAuth, connectWithPastedToken, disconnectBeeper, startBeeperOAuth } from '../services/beeperOAuth.js';import { runBeeperSweep } from '../services/beeperSync.js';import {- clearOutboxBreaker, createOutboxEntry, discardOutboxEntry, listOutboxEntries, sendOutboxEntry,+ clearOutboxBreaker, createOutboxEntry, discardOutboxEntry, reconcileOutboxEntry, listOutboxEntries, sendOutboxEntry,} from '../services/beeperOutbox.js';import {listConversations,@@ -487,6 +487,13 @@ router.post('/outbox/:id/send', asyncHandler(async (req, res) => {res.json(entry);}));+// Human recovery reads Beeper delivery state; it never sends another message.+router.post('/outbox/:id/reconcile', asyncHandler(async (req, res) => {+ const { id } = validateRequest(beeperOutboxParamsSchema, req.params);+ const entry = await reconcileOutboxEntry(id).catch((err) => { throw mapBeeperWriteError(err); });+ res.json(entry);+}));+// DELETE /api/beeper/outbox/:id — discard a row the human declined to send:// the first-contact confirmation's "Cancel" (#53). Only an `approved` row can// be discarded — nothing has POSTed to Beeper for it yet, so this is a purediff --git a/server/routes/beeper.test.js b/server/routes/beeper.test.jsindex e78d81e652..7014c9b75d 100644--- a/server/routes/beeper.test.js+++ b/server/routes/beeper.test.js@@ -17,6 +17,7 @@ vi.mock('../services/beeperOutbox.js', () => ({createOutboxEntry: vi.fn(),sendOutboxEntry: vi.fn(),discardOutboxEntry: vi.fn(),+ reconcileOutboxEntry: vi.fn(),listOutboxEntries: vi.fn(),clearOutboxBreaker: vi.fn(),}));@@ -55,7 +56,7 @@ import {} from '../services/beeperOAuth.js';import { runBeeperSweep } from '../services/beeperSync.js';import {- clearOutboxBreaker, createOutboxEntry, discardOutboxEntry, listOutboxEntries, sendOutboxEntry,+ clearOutboxBreaker, createOutboxEntry, discardOutboxEntry, listOutboxEntries, sendOutboxEntry, reconcileOutboxEntry,} from '../services/beeperOutbox.js';import {listConversations,@@ -885,3 +886,18 @@ describe('attachment mirror routes (#37)', () => {expect(res.body).toMatchObject({ purged: true, filesRemoved: 3, bytesFreed: 4096 });});});+++describe('POST /api/beeper/outbox/:id/reconcile', () => {+ beforeEach(() => vi.clearAllMocks());+ const ENTRY_ID = '44444444-4444-4444-8444-444444444444';+ it('validates the row and returns lookup recovery without invoking the send service', async () => {+ expect((await request(buildApp()).post('/api/beeper/outbox/not-a-uuid/reconcile').send({})).status).toBe(400);+ expect(reconcileOutboxEntry).not.toHaveBeenCalled();+ vi.mocked(reconcileOutboxEntry).mockResolvedValue({ id: ENTRY_ID, state: 'sent' });+ const res = await request(buildApp()).post(`/api/beeper/outbox/${ENTRY_ID}/reconcile`).send({});+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ id: ENTRY_ID, state: 'sent' });+ expect(sendOutboxEntry).not.toHaveBeenCalled();+ });+});diff --git a/server/services/beeperOutbox.js b/server/services/beeperOutbox.jsindex 67127e68d6..6fac755752 100644--- a/server/services/beeperOutbox.js+++ b/server/services/beeperOutbox.js@@ -38,7 +38,7 @@* asserts that structurally rather than by convention.*/-import { query } from '../lib/db.js';+import { query, withTransaction } from '../lib/db.js';import { BeeperApiError, getMessage, listMessagesPage, sendMessage } from './beeperClient.js';import { normalizeMessageRow } from './beeperSync.js';import { beeperSocketEvents } from './beeperSocketEvents.js';@@ -114,6 +114,49 @@ let breaker = { tripped: false, reason: null, trippedAt: null };// outboxId → { chatId, body, pendingMessageId, requestedAt,// deliveryOutcomeUnknown, timer, resolving }const pendingConfirmations = new Map();+const localTransitions = new Map();+const activeSends = new Set();+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.';++function invalidateOutbox(id) {+ beeperSocketEvents.emit('invalidate', { kind: 'outbox.updated', chatID: null, ids: [id], seq: null, ts: new Date(runtime.now()).toISOString() });+}++function recoveryView(entry) {+ if (!entry) return entry;+ if (!localTransitions.has(entry.id)) return entry;+ return { ...entry, state: 'awaiting-confirmation', errorCode: DELIVERY_UNCONFIRMED_CODE, errorMessage: PERSISTENCE_RECOVERY_MESSAGE };+}++// Own only local persistence here: the closure must NEVER contain a send POST.+// Retain it after the bounded timer budget, so a human can resume it later.+async function runLocalTransition(id, transition) {+ if (transition.running) return transition.running;+ runtime.clearTimeout(transition.timer);+ transition.running = transition.write().then((value) => {+ if (localTransitions.get(id) === transition) localTransitions.delete(id);+ transition.committed?.(value);+ invalidateOutbox(id);+ return value;+ }).catch(() => {+ if (transition.attempt < PERSISTENCE_RETRY_DELAYS_MS.length) {+ const delay = PERSISTENCE_RETRY_DELAYS_MS[transition.attempt++];+ transition.timer = runtime.setTimeout(() => {+ runLocalTransition(id, transition).catch((err) => console.error(`${LOG_PREFIX}: local recovery failed (${err.code || 'unknown'})`));+ }, delay);+ }+ invalidateOutbox(id);+ return null;+ }).finally(() => { transition.running = null; });+ return transition.running;+}++function persistTransition(id, write, committed) {+ const transition = { write, committed, attempt: 0, running: null, timer: null };+ localTransitions.set(id, transition);+ return runLocalTransition(id, transition);+}let invalidateListenerAttached = false;/** Test seam for injected time (mirrors `beeperSocket.js`'s runtime object). */@@ -207,7 +250,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", approved_at AS "approvedAt", sent_at AS "sentAt"`;+ 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]);@@ -221,7 +264,7 @@ export async function listOutboxEntries({ conversationId, limit = 50 } = {}) {WHERE conversation_id = $1 ORDER BY created_at DESC LIMIT $2`,[conversationId, Math.min(200, Math.max(1, Math.trunc(limit) || 50))],);- return Array.isArray(result?.rows) ? result.rows : [];+ return Array.isArray(result?.rows) ? result.rows.map(recoveryView) : [];}/**@@ -413,31 +456,23 @@ 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 })).catch((err) => ({ ok: false, err }));+ activeSends.delete(id);+ const confirmation = { ...entry, pendingMessageId: null, requestedAt };if (!result.ok) {const err = result.err;if (isDeliveryOutcomeUnknown(err)) {- const updated = await markAwaitingConfirmation(id, {- errorCode: DELIVERY_UNCONFIRMED_CODE,- errorMessage: DELIVERY_UNCONFIRMED_MESSAGE,- });registerSendFailure();- console.warn(`${LOG_PREFIX}: send response lost — delivery left unconfirmed, never re-sent`);- armConfirmation({- id,- chatId: entry.chatId,- conversationId: entry.conversationId,- body: entry.body,- pendingMessageId: null,- requestedAt,- deliveryOutcomeUnknown: true,- });- return updated;+ const updated = await persistTransition(id,+ () => markAwaitingConfirmation(id, { errorCode: DELIVERY_UNCONFIRMED_CODE, errorMessage: DELIVERY_UNCONFIRMED_MESSAGE }),+ () => armConfirmation({ ...confirmation, deliveryOutcomeUnknown: true }));+ return updated ?? recoveryView(entry);}- await markFailed(id, err?.code, err?.message);+ await persistTransition(id, () => markFailed(id, err?.code, err?.message));registerSendFailure();console.error(`${LOG_PREFIX}: send failed (${err?.code || 'SEND_FAILED'})`);throw new BeeperApiError(err?.message || 'Beeper send failed', {@@ -450,10 +485,11 @@ export async function sendOutboxEntry(id, { confirmFirstContact = false } = {})registerSendSuccess();const pendingMessageId = typeof result.value?.pendingMessageID === 'string' ? result.value.pendingMessageID : null;- const updated = await markAwaitingConfirmation(id, { pendingMessageId });+ const updated = await persistTransition(id,+ () => markAwaitingConfirmation(id, { pendingMessageId }),+ () => armConfirmation({ ...confirmation, pendingMessageId }));console.log(`${LOG_PREFIX}: sent, awaiting confirmation${pendingMessageId ? '' : ' (no pending id returned)'}`);- armConfirmation({ id, chatId: entry.chatId, conversationId: entry.conversationId, body: entry.body, pendingMessageId, requestedAt });- return updated;+ return updated ?? recoveryView(entry);}// ---------------------------------------------------------------------------@@ -569,10 +605,10 @@ async function lookupSentMessage(pending) {* the field cannot flip a message the user sent onto the other side of the* thread.*/-async function mirrorSentMessage(conversationId, message) {+async function mirrorSentMessage(client, conversationId, message) {const row = normalizeMessageRow(message, new Date(runtime.now()).toISOString());if (!row.id) return;- await query(+ 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@@ -609,8 +645,8 @@ function releasePending(id) {*/async function resolveConfirmation(id, reason) {const pending = pendingConfirmations.get(id);- if (!pending) return null;- if (reason === 'fallback-timeout') pending.deadlineReached = true;+ if (!pending || localTransitions.has(id)) return null;+ if (reason === 'fallback-timeout' || reason === 'manual') pending.deadlineReached = true;// The one-shot timer can fire during a socket lookup. Let that lookup own// the deadline outcome rather than dropping the only fallback signal.if (pending.resolving) return null;@@ -650,46 +686,41 @@ async function resolveConfirmation(id, reason) {}const status = typeof message?.sendStatus?.status === 'string' ? message.sendStatus.status : null;- if (status && status.startsWith('FAIL')) {- releasePending(id);- await markFailed(id, `SEND_${status}`, message?.sendStatus?.message || message?.sendStatus?.reason || 'Beeper reported a failed send');- console.error(`${LOG_PREFIX}: Beeper reported ${status} for a sent message`);+ if (status?.startsWith('FAIL')) {+ await persistTransition(id,+ () => markFailed(id, `SEND_${status}`, message?.sendStatus?.message || message?.sendStatus?.reason || 'Beeper reported a failed send'),+ () => releasePending(id));return null;}- const settled = await query(- `UPDATE beeper_outbox SET state = 'sent', message_id = $2, sent_at = COALESCE($3::timestamptz, NOW()),- error_code = NULL, error_message = NULL, updated_at = NOW()- WHERE id = $1 AND state = 'awaiting-confirmation' RETURNING ${ENTRY_COLUMNS}`,- [id, String(message.id), message?.timestamp ?? null],- );- releasePending(id);- if ((settled?.rowCount ?? 0) !== 1) return null;-- await mirrorSentMessage(pending.conversationId, message);- // Ids and kinds only, on the same relay #33 already forwards to subscribed- // browsers — never the body, which stays on this machine.- beeperSocketEvents.emit('invalidate', {- kind: 'message.upserted',- chatID: pending.chatId,- ids: [String(message.id)],- seq: null,- ts: new Date(runtime.now()).toISOString(),+ return persistTransition(id, () => withTransaction(async (client) => {+ const settled = await client.query(+ `UPDATE beeper_outbox SET state = 'sent', message_id = $2, sent_at = COALESCE($3::timestamptz, NOW()),+ error_code = NULL, error_message = NULL, updated_at = NOW()+ WHERE id = $1 AND state = 'awaiting-confirmation' RETURNING ${ENTRY_COLUMNS}`,+ [id, String(message.id), message?.timestamp ?? null],+ );+ if ((settled?.rowCount ?? 0) !== 1) return null;+ await mirrorSentMessage(client, pending.conversationId, message);+ return settled.rows[0];+ }), () => {+ releasePending(id);+ beeperSocketEvents.emit('invalidate', {+ kind: 'message.upserted', chatID: pending.chatId, ids: [String(message.id)],+ seq: null, ts: new Date(runtime.now()).toISOString(),+ });+ console.log(`${LOG_PREFIX}: send confirmed via ${reason}`);});- console.log(`${LOG_PREFIX}: send confirmed via ${reason}`);- return settled.rows[0];}/** Record why a send is unconfirmed without moving it out of flight. */async function noteUnresolved(id, message, deliveryOutcomeUnknown = false) {- releasePending(id);- await query(+ await persistTransition(id, () => query(`UPDATE beeper_outbox SET error_code = $2, error_message = $3, updated_at = NOW()WHERE id = $1 AND state = 'awaiting-confirmation'`,[id, deliveryOutcomeUnknown ? DELIVERY_UNCONFIRMED_CODE : 'CONFIRMATION_UNRESOLVED', message],- );- beeperSocketEvents.emit('invalidate', { kind: 'outbox.updated', chatID: null, ids: [id], seq: null, ts: new Date(runtime.now()).toISOString() });- console.warn(`${LOG_PREFIX}: send unconfirmed after ${CONFIRMATION_TIMEOUT_MS / 1000}s — left in flight, never re-sent`);+ ), () => releasePending(id));+ console.warn(`${LOG_PREFIX}: send unconfirmed — never re-sent`);}/**@@ -699,6 +730,34 @@ async function noteUnresolved(id, message, deliveryOutcomeUnknown = false) {*/export function cancelPendingConfirmations() {for (const id of [...pendingConfirmations.keys()]) releasePending(id);+ for (const transition of localTransitions.values()) runtime.clearTimeout(transition.timer);+ localTransitions.clear();+ activeSends.clear();+}++/** Human-triggered reconciliation. Remote operations are GETs only. */+export async function reconcileOutboxEntry(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;+ const transition = localTransitions.get(id);+ if (transition) {+ await runLocalTransition(id, transition);+ if (localTransitions.has(id)) return recoveryView(entry);+ entry = await readEntry(id);+ }+ const uncertainFailure = entry.state === 'failed' && [SEND_INTERRUPTED_CODE, DELIVERY_UNCONFIRMED_CODE, 'NETWORK_ERROR'].includes(entry.errorCode);+ if (!['sending', 'awaiting-confirmation'].includes(entry.state) && !uncertainFailure) return entry;+ if (!pendingConfirmations.has(id)) {+ const unknown = entry.state === 'sending' || uncertainFailure || entry.errorCode === DELIVERY_UNCONFIRMED_CODE;+ const requestedAt = persistedSendMoment(entry);+ if (entry.state !== 'awaiting-confirmation') {+ entry = await markAwaitingConfirmation(id, { errorCode: DELIVERY_UNCONFIRMED_CODE, errorMessage: DELIVERY_UNCONFIRMED_MESSAGE });+ }+ armConfirmation({ ...entry, requestedAt, deliveryOutcomeUnknown: unknown });+ }+ await resolveConfirmation(id, 'manual');+ return recoveryView(await readEntry(id));}// ---------------------------------------------------------------------------@@ -719,10 +778,8 @@ function persistedSendMoment(row) {** `sending` and `awaiting-confirmation` are exit-only through in-memory state:* `pendingConfirmations`, its timer, and the socket listener. A restart mid-- * flight takes all three with it, and no route can move a row out of either- * state — so without this the row is permanently un-actionable, and the client- * renders it as a spinner with no Retry and no Dismiss, forever, across every- * later restart.+ * flight takes all three with it. Boot reconciles automatically; a human can+ * also invoke the lookup-only reconciliation route without restarting.** Two different faults, two different answers:*diff --git a/server/services/beeperOutbox.test.js b/server/services/beeperOutbox.test.jsindex d19d894ea3..fa4828d9a5 100644--- a/server/services/beeperOutbox.test.js+++ b/server/services/beeperOutbox.test.js@@ -68,6 +68,8 @@ const mirroredSql = [];// stands in for.const mirroredMessages = [];let nextId = 1;+let failingSql = null;+let failedWrites = 0;/** A `beeper_messages` row synced in from Beeper, never through this outbox. */function seedMirroredMessage(conversationId, { isSender = true } = {}) {@@ -77,6 +79,7 @@ function seedMirroredMessage(conversationId, { isSender = true } = {}) {const entryView = (row) => ({ ...row });const query = vi.fn(async (sql, params = []) => {+ if (failingSql?.test(sql)) { failedWrites++; throw new Error('database unavailable'); }if (/SELECT id, source_chat_id/.test(sql)) {const conversation = conversations.get(params[0]);return { rows: conversation ? [{ id: params[0], sourceChatId: conversation }] : [], rowCount: conversation ? 1 : 0 };@@ -134,7 +137,7 @@ const query = vi.fn(async (sql, params = []) => {}if (/UPDATE beeper_outbox SET state = 'sending'/.test(sql)) {const row = outbox.get(params[0]);- if (!row || row.state !== 'approved') return { rows: [], rowCount: 0 };+ if (row?.state !== 'approved') return { rows: [], rowCount: 0 };row.state = 'sending';return { rows: [{ id: row.id }], rowCount: 1 };}@@ -155,7 +158,7 @@ const query = vi.fn(async (sql, params = []) => {}if (/UPDATE beeper_outbox SET state = 'sent'/.test(sql)) {const row = outbox.get(params[0]);- if (!row || row.state !== 'awaiting-confirmation') return { rows: [], rowCount: 0 };+ if (row?.state !== 'awaiting-confirmation') return { rows: [], rowCount: 0 };row.state = 'sent';row.messageId = params[1];row.sentAt = params[2] ?? '2026-09-01T00:00:05.000Z';@@ -165,14 +168,14 @@ const query = vi.fn(async (sql, params = []) => {}if (/UPDATE beeper_outbox SET error_code = \$2/.test(sql)) {const row = outbox.get(params[0]);- if (!row || row.state !== 'awaiting-confirmation') return { rows: [], rowCount: 0 };+ if (row?.state !== 'awaiting-confirmation') return { rows: [], rowCount: 0 };row.errorCode = params[1];row.errorMessage = params[2];return { rows: [], rowCount: 1 };}if (/DELETE FROM beeper_outbox WHERE id = \$1 AND state = 'approved'/.test(sql)) {const row = outbox.get(params[0]);- if (!row || row.state !== 'approved') return { rows: [], rowCount: 0 };+ if (row?.state !== 'approved') return { rows: [], rowCount: 0 };outbox.delete(params[0]);return { rows: [], rowCount: 1 };}@@ -184,14 +187,26 @@ const query = vi.fn(async (sql, params = []) => {throw new Error(`unexpected SQL in test: ${sql.slice(0, 60)}`);});-vi.mock('../lib/db.js', () => ({ query: (...args) => query(...args) }));+vi.mock('../lib/db.js', () => ({+ query: (...args) => query(...args),+ withTransaction: async (fn) => {+ const snapshot = [...outbox.entries()].map(([id, row]) => [id, { ...row }]);+ const mirrorLength = mirrored.length;+ return fn({ query }).catch((err) => {+ outbox.clear();+ for (const [id, row] of snapshot) outbox.set(id, row);+ mirrored.length = mirrorLength;+ throw err;+ });+ },+}));const {BREAKER_MAX_CONSECUTIVE_FAILURES, BREAKER_MAX_SENDS_IN_WINDOW, BREAKER_WINDOW_MS,CONFIRMATION_TIMEOUT_MS, DELIVERY_UNCONFIRMED_CODE, DELIVERY_UNCONFIRMED_MESSAGE, SEND_INTERRUPTED_MESSAGE,cancelPendingConfirmations, clearOutboxBreaker, configureOutboxRuntime, createOutboxEntry,discardOutboxEntry, getOutboxBreakerState, getOutboxStatus, isFirstContact, listOutboxEntries,- reconcileOutboxOnBoot, resetOutboxRuntime, sendOutboxEntry,+ reconcileOutboxEntry, PERSISTENCE_RETRY_DELAYS_MS, reconcileOutboxOnBoot, resetOutboxRuntime, sendOutboxEntry,} = await import('./beeperOutbox.js');const { beeperSocketEvents } = await import('./beeperSocketEvents.js');@@ -287,6 +302,8 @@ function strandedRow(state, overrides = {}) {}beforeEach(() => {+ failingSql = null;+ failedWrites = 0;outbox.clear();conversations.clear();mirrored.length = 0;@@ -903,3 +920,70 @@ describe('runaway breaker', () => {expect(getOutboxBreakerState()).toMatchObject({ tripped: false, consecutiveFailures: 2 });});});+++describe('local persistence recovery without another send', () => {+ it('retains an accepted pending id until the delayed database transition recovers', async () => {+ const entry = await createOutboxEntry({ conversationId: CONVERSATION_ID, body: 'hello there' });+ failingSql = /SET state = 'awaiting-confirmation'/;+ const result = await sendOutboxEntry(entry.id, { confirmFirstContact: true });+ expect(result).toMatchObject({ state: 'awaiting-confirmation', errorCode: DELIVERY_UNCONFIRMED_CODE });+ expect(outbox.get(entry.id).state).toBe('sending');+ expect(failedWrites).toBe(1);+ failingSql = null;+ expect(clock.runTimersWithDelay(PERSISTENCE_RETRY_DELAYS_MS[0])).toBe(1);+ await flush();+ expect(outbox.get(entry.id)).toMatchObject({ state: 'awaiting-confirmation', pendingMessageId: 'pending-1' });+ clock.runTimersWithDelay(CONFIRMATION_TIMEOUT_MS);+ await flush();+ expect(outbox.get(entry.id).state).toBe('sent');+ expect(sendMessage).toHaveBeenCalledTimes(1);+ });++ it('recovers a rejected transport outcome after its failure write fails', async () => {+ const entry = await createOutboxEntry({ conversationId: CONVERSATION_ID, body: 'hello there' });+ sendMessage.mockRejectedValueOnce(new BeeperApiError('rejected', { status: 403, code: 'FORBIDDEN' }));+ failingSql = /SET state = 'failed'/;+ await expect(sendOutboxEntry(entry.id, { confirmFirstContact: true })).rejects.toMatchObject({ code: 'FORBIDDEN' });+ expect((await listOutboxEntries({ conversationId: CONVERSATION_ID }))[0].errorCode).toBe(DELIVERY_UNCONFIRMED_CODE);+ failingSql = null;+ clock.runTimersWithDelay(PERSISTENCE_RETRY_DELAYS_MS[0]);+ await flush();+ expect(outbox.get(entry.id)).toMatchObject({ state: 'failed', errorCode: 'FORBIDDEN' });+ expect(sendMessage).toHaveBeenCalledTimes(1);+ });++ it('rolls back sent when mirroring fails, stops after bounded delays, and lets a human finish the retained transaction', async () => {+ const entry = await createOutboxEntry({ conversationId: CONVERSATION_ID, body: 'hello there' });+ await sendOutboxEntry(entry.id, { confirmFirstContact: true });+ failingSql = /INSERT INTO beeper_messages/;+ clock.runTimersWithDelay(CONFIRMATION_TIMEOUT_MS);+ await flush();+ expect(outbox.get(entry.id).state).toBe('awaiting-confirmation');+ expect(mirrored).toHaveLength(0);+ for (const delay of PERSISTENCE_RETRY_DELAYS_MS) {+ expect(clock.runTimersWithDelay(delay)).toBe(1);+ await flush();+ }+ expect(failedWrites).toBe(4);+ expect(clock.pending()).toBe(0);+ expect((await listOutboxEntries({ conversationId: CONVERSATION_ID }))[0]).toMatchObject({ errorCode: DELIVERY_UNCONFIRMED_CODE });+ failingSql = null;+ await reconcileOutboxEntry(entry.id);+ expect(outbox.get(entry.id)).toMatchObject({ state: 'sent', messageId: 'msg-final-1' });+ expect(mirrored).toHaveLength(1);+ expect(getOutboxStatus().awaitingConfirmation).toBe(0);+ await reconcileOutboxEntry(entry.id);+ expect(mirrored).toHaveLength(1);+ expect(sendMessage).toHaveBeenCalledTimes(1);+ });++ it('manually reconciles a durable stranded sending row with lookup only', async () => {+ const entry = await createOutboxEntry({ conversationId: CONVERSATION_ID, body: 'hello there' });+ outbox.get(entry.id).state = 'sending';+ listMessagesPage.mockResolvedValue({ items: [sentMessage()] });+ expect(await reconcileOutboxEntry(entry.id)).toMatchObject({ state: 'sent' });+ expect(sendMessage).not.toHaveBeenCalled();+ expect(mirrored).toHaveLength(1);+ });+});