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: avoid duplicate Beeper sends after response loss (#7177)

[._.]/ Adam Eivy93c841a1c77d
diff --git a/client/src/components/messages/BeeperTab.test.jsx b/client/src/components/messages/BeeperTab.test.jsx
index df780bf609..88858dbc05 100644
--- a/client/src/components/messages/BeeperTab.test.jsx
+++ b/client/src/components/messages/BeeperTab.test.jsx
@@ -609,21 +609,26 @@ describe('the composer sends', () => {
expect(screen.getAllByText(OUTBOUND_TEXT)).toHaveLength(1);
});
- it('shows Retry on a failed send and leaves the composer text intact — never re-sent automatically', async () => {
+ it('shows a response-less send as unconfirmed with no Retry or automatic re-send', async () => {
apiBeeper.createOutboxEntry.mockResolvedValue({ id: 'outbox-1', conversationId: CONV_A, body: OUTBOUND_TEXT, state: 'approved' });
- apiBeeper.sendOutboxEntry.mockRejectedValue(Object.assign(new Error('Beeper request failed: connection refused'), { code: 'NETWORK_ERROR' }));
- apiBeeper.listOutboxEntries.mockResolvedValue({
- entries: [{ id: 'outbox-1', conversationId: CONV_A, body: OUTBOUND_TEXT, state: 'failed', errorCode: 'NETWORK_ERROR' }],
+ apiBeeper.sendOutboxEntry.mockResolvedValue({
+ id: 'outbox-1',
+ conversationId: CONV_A,
+ body: OUTBOUND_TEXT,
+ state: 'awaiting-confirmation',
+ errorCode: 'DELIVERY_UNCONFIRMED',
+ errorMessage: 'Delivery unconfirmed; check the chat before sending again.',
});
const composer = await openComposer();
fireEvent.click(screen.getByRole('button', { name: 'Send' }));
const row = await screen.findByTestId('beeper-outbox-row');
- await waitFor(() => expect(row).toHaveAttribute('data-state', 'failed'));
- expect(within(row).getByRole('button', { name: 'Retry' })).toBeInTheDocument();
+ await waitFor(() => expect(row).toHaveAttribute('data-state', 'awaiting-confirmation'));
+ expect(within(row).getByText('Delivery unconfirmed; check the chat before sending again.')).toBeInTheDocument();
+ expect(within(row).queryByRole('button', { name: 'Retry' })).toBeNull();
expect(apiBeeper.sendOutboxEntry).toHaveBeenCalledTimes(1);
- expect(composer).toHaveValue(OUTBOUND_TEXT);
+ await waitFor(() => expect(composer).toHaveValue(''));
});
it('surfaces a first-contact refusal as an inline confirmation naming the network and recipient, then resends the SAME row', async () => {
diff --git a/client/src/components/messages/beeper/BeeperThread.jsx b/client/src/components/messages/beeper/BeeperThread.jsx
index 30189f0df6..5997afd3e5 100644
--- a/client/src/components/messages/beeper/BeeperThread.jsx
+++ b/client/src/components/messages/beeper/BeeperThread.jsx
@@ -259,9 +259,10 @@ function ParticipantRow({
* It deliberately does not claim a delivery verdict. The POST was in flight
* when the process died, so whether it landed is unknowable from here; the copy
* points at the chat, because looking is the only thing that actually answers
- * it, and Retry composes a new message rather than resending that one.
+ * it. The row offers no Retry control while the outcome remains uncertain.
*/
const SEND_INTERRUPTED_COPY = 'Delivery unconfirmed: PortOS restarted mid-send. Check the chat before retrying.';
+const DELIVERY_UNCONFIRMED_COPY = 'Delivery unconfirmed; check the chat before sending again.';
/** The outbox states that still have something to say above the composer. */
const RENDERED_OUTBOX_STATES = new Set(['approved', 'sending', 'awaiting-confirmation', 'failed']);
@@ -351,7 +352,7 @@ function TitleTribeChip({ conversation, onOpenParticipants, onOpenPerson }) {
*
* Only ONE of the four outcomes below spins, and the spinner is the exception
* rather than the default. Every state that will not change on its own — a
- * failure, an interrupted send, an unconfirmed one, a refused one — resolves to
+ * definitive failure, an interrupted send, an unconfirmed one, a refused one — resolves to
* a terminal line that says what happened, because a spinner for a state
* nothing can ever advance is a lie the user cannot dismiss, and it survives
* every reload.
@@ -366,11 +367,12 @@ function TitleTribeChip({ conversation, onOpenParticipants, onOpenPerson }) {
* reason, a Retry, and — since nothing here was ever posted to Beeper — a
* Dismiss that gives up on it outright.
*
- * The two Retries are not the same action, and the breaker splits them (PR
- * #60 blocker 2). A `failed` row's Retry composes a NEW entry through the
- * composer's own send path, which the breaker blocks exactly as it blocks
- * Send — so with the breaker tripped that button is disabled and carries the
- * same reason as the Send button, rather than staying live and doing nothing.
+ * The two safe Retries are not the same action, and the breaker splits them (PR
+ * #60 blocker 2). A definitively `failed` row's Retry composes a NEW entry
+ * through the composer's own send path, which the breaker blocks exactly as it
+ * blocks Send — so with the breaker tripped that button is disabled and
+ * carries the same reason as the Send button, rather than staying live and
+ * doing nothing. Uncertain failures never render that control.
* A `stalled` row's Retry re-dispatches the existing row: the server decides,
* and its 429 toasts, so it stays enabled.
*/
@@ -378,7 +380,9 @@ function OutboxRow({
entry, sending, isConfirming, onRetry, onDismiss, breakerTripped, breakerReason,
}) {
const failed = entry.state === 'failed';
- const interrupted = failed && entry.errorCode === 'SEND_INTERRUPTED';
+ const interrupted = entry.errorCode === 'SEND_INTERRUPTED';
+ const responseLost = entry.errorCode === 'DELIVERY_UNCONFIRMED'
+ || (failed && entry.errorCode === 'NETWORK_ERROR');
// Recorded by the server's 30s fallback when it could not find the message it
// had just sent. The row stays `awaiting-confirmation` on purpose — the send
// may well have been delivered, and marking it failed would invite the one
@@ -386,16 +390,20 @@ function OutboxRow({
// carries the reason the server recorded, and offers NO Retry. It never
// changes on its own, so it must never spin.
const unresolved = !failed && entry.errorCode === 'CONFIRMATION_UNRESOLVED';
+ const unconfirmed = interrupted || responseLost || unresolved;
const stalled = entry.state === 'approved' && !sending && !isConfirming;
- const blocked = failed || stalled;
+ const blocked = (failed && !unconfirmed) || stalled;
const confirming = entry.state === 'awaiting-confirmation' || entry.state === 'sent';
const retryBlocked = breakerTripped && !stalled;
- const outcome = blocked ? (failed ? 'failed' : 'stalled') : (unresolved ? 'unconfirmed' : 'pending');
- // An interrupted send gets the copy verbatim and nothing else: prefixing
- // "Not delivered" would assert a verdict the crash destroyed the evidence for.
- let blockedReason = 'Not sent — the send was refused';
- if (interrupted) blockedReason = SEND_INTERRUPTED_COPY;
- else if (failed) blockedReason = `Not delivered${entry.errorMessage ? ` — ${entry.errorMessage}` : ''}`;
+ const outcome = unconfirmed ? 'unconfirmed' : (blocked ? (failed ? 'failed' : 'stalled') : 'pending');
+ const blockedReason = failed
+ ? `Not delivered${entry.errorMessage ? ` — ${entry.errorMessage}` : ''}`
+ : 'Not sent — the send was refused';
+ const unconfirmedReason = interrupted
+ ? (entry.errorMessage || SEND_INTERRUPTED_COPY)
+ : (responseLost
+ ? DELIVERY_UNCONFIRMED_COPY
+ : `Sent, unconfirmed${entry.errorMessage ? ` — ${entry.errorMessage}` : ''}`);
return (
<div
data-testid="beeper-outbox-row"
@@ -433,12 +441,12 @@ function OutboxRow({
)}
</>
)}
- {unresolved && (
+ {unconfirmed && (
<span className="text-port-warning">
- {`Sent, unconfirmed${entry.errorMessage ? ` — ${entry.errorMessage}` : ''}`}
+ {unconfirmedReason}
</span>
)}
- {!blocked && !unresolved && (
+ {!blocked && !unconfirmed && (
<span className="flex items-center gap-1 text-gray-400">
<Loader2 size={10} className="animate-spin" />
{confirming ? 'Confirming…' : 'Sending…'}
@@ -536,8 +544,9 @@ export default function BeeperThread({
handleSendClick();
}
};
- // A failed row's only recovery: compose the SAME text again as a brand new
- // outbox entry. Never a resend of the failed row — see the file docstring.
+ // A definitively failed row's recovery: compose the SAME text again as a
+ // brand new outbox entry. Never a resend of the failed row — see the file
+ // docstring. Uncertain failures never render the control that reaches here.
// A stalled `approved` row (PR #60 blocker 1) is the opposite case: nothing
// ever reached Beeper for it, so retrying re-sends the SAME row instead —
// composing a new one on every click would just manufacture more phantoms
diff --git a/client/src/components/messages/beeper/BeeperThread.test.jsx b/client/src/components/messages/beeper/BeeperThread.test.jsx
index 120ad5388f..024e809095 100644
--- a/client/src/components/messages/beeper/BeeperThread.test.jsx
+++ b/client/src/components/messages/beeper/BeeperThread.test.jsx
@@ -71,6 +71,7 @@ const TRIPPED_BREAKER = { tripped: true, reason: 'too many sends' };
// `SEND_INTERRUPTED_MESSAGE` in `server/services/beeperOutbox.js` are pinned by
// a test on each side rather than by an import.
const SEND_INTERRUPTED_COPY = 'Delivery unconfirmed: PortOS restarted mid-send. Check the chat before retrying.';
+const DELIVERY_UNCONFIRMED_COPY = 'Delivery unconfirmed; check the chat before sending again.';
const UNRESOLVED_REASON = 'Beeper reported no matching message within 30s — it may still have been delivered, so it was not re-sent.';
// A send that settled long ago. `GET /outbox` returns up to 50 entries in every
@@ -92,6 +93,20 @@ const INTERRUPTED_ENTRY = {
errorCode: 'SEND_INTERRUPTED',
errorMessage: SEND_INTERRUPTED_COPY,
};
+const RESPONSE_LOST_ENTRY = {
+ id: 'outbox-6',
+ state: 'awaiting-confirmation',
+ body: 'hello there',
+ errorCode: 'DELIVERY_UNCONFIRMED',
+ errorMessage: DELIVERY_UNCONFIRMED_COPY,
+};
+const LEGACY_NETWORK_ENTRY = {
+ id: 'outbox-7',
+ state: 'failed',
+ body: 'hello there',
+ errorCode: 'NETWORK_ERROR',
+ errorMessage: 'Beeper request failed: connection reset',
+};
const renderThread = (overrides = {}) => render(<BeeperThread {...BASE_PROPS} {...overrides} />);
@@ -246,19 +261,36 @@ describe('BeeperThread — terminal outbox states never spin', () => {
expect(screen.queryByRole('button', { name: 'Retry' })).toBeNull();
});
- it('renders an interrupted send with the exact copy and the usual failed-row Retry', () => {
- const onSend = vi.fn();
- const { container } = renderThread({ outboxEntries: [INTERRUPTED_ENTRY], onSend });
+ it('renders an interrupted send as unconfirmed with no Retry', () => {
+ const { container } = renderThread({ outboxEntries: [INTERRUPTED_ENTRY] });
const row = screen.getByTestId('beeper-outbox-row');
- expect(row).toHaveAttribute('data-outcome', 'failed');
+ expect(row).toHaveAttribute('data-outcome', 'unconfirmed');
expect(within(row).getByText(SEND_INTERRUPTED_COPY)).toBeInTheDocument();
expect(container.querySelector('.animate-spin')).toBeNull();
+ expect(within(row).queryByRole('button', { name: 'Retry' })).toBeNull();
+ });
- fireEvent.click(within(row).getByRole('button', { name: 'Retry' }));
- // Retry composes a NEW entry from that row's text, exactly like any other
- // failed row — never a resend of a POST whose outcome is unknown.
- expect(onSend).toHaveBeenCalledWith('hello there', { clearsDraft: false });
+ it('shows a response-less send as unconfirmed while read-only confirmation remains possible', () => {
+ const { container } = renderThread({ outboxEntries: [RESPONSE_LOST_ENTRY] });
+
+ const row = screen.getByTestId('beeper-outbox-row');
+ expect(row).toHaveAttribute('data-outcome', 'unconfirmed');
+ expect(within(row).getByText(DELIVERY_UNCONFIRMED_COPY)).toBeInTheDocument();
+ expect(within(row).queryByText(/Not delivered/)).toBeNull();
+ expect(within(row).queryByRole('button', { name: 'Retry' })).toBeNull();
+ expect(container.querySelector('.animate-spin')).toBeNull();
+ });
+
+ it('renders persisted NETWORK_ERROR rows safely without a migration or Retry', () => {
+ renderThread({ outboxEntries: [LEGACY_NETWORK_ENTRY] });
+
+ const row = screen.getByTestId('beeper-outbox-row');
+ expect(row).toHaveAttribute('data-state', 'failed');
+ expect(row).toHaveAttribute('data-outcome', 'unconfirmed');
+ expect(within(row).getByText(DELIVERY_UNCONFIRMED_COPY)).toBeInTheDocument();
+ expect(within(row).queryByText(/Not delivered/)).toBeNull();
+ expect(within(row).queryByRole('button', { name: 'Retry' })).toBeNull();
});
it('keeps both terminal states across a remount, the shape a reload takes', () => {
@@ -270,7 +302,7 @@ describe('BeeperThread — terminal outbox states never spin', () => {
// Rendered oldest-last: `entries` arrives newest-first and is reversed.
expect(screen.getAllByTestId('beeper-outbox-row').map((row) => row.dataset.outcome))
- .toEqual(['failed', 'unconfirmed']);
+ .toEqual(['unconfirmed', 'unconfirmed']);
expect(within(screen.getAllByTestId('beeper-outbox-row')[0]).getByText(SEND_INTERRUPTED_COPY)).toBeInTheDocument();
expect(container.querySelector('.animate-spin')).toBeNull();
});
diff --git a/client/src/hooks/useBeeperOutbox.test.jsx b/client/src/hooks/useBeeperOutbox.test.jsx
index a64ae8f1e4..abefae8c14 100644
--- a/client/src/hooks/useBeeperOutbox.test.jsx
+++ b/client/src/hooks/useBeeperOutbox.test.jsx
@@ -183,16 +183,24 @@ describe('useBeeperOutbox', () => {
await waitFor(() => expect(result.current.entries).toHaveLength(1));
});
- it('never re-sends after a transport failure — it reports it and refetches the failed row', async () => {
- sendOutboxEntry.mockRejectedValue(new ApiError('Beeper request failed', 'NETWORK_ERROR'));
- listOutboxEntries.mockResolvedValue({ entries: [{ ...ENTRY, state: 'failed', errorCode: 'NETWORK_ERROR' }] });
- const { result } = renderHook(() => useBeeperOutbox(CONVERSATION_ID));
+ it('keeps a response-less send visible as unconfirmed without toasting or sending again', async () => {
+ const onSent = vi.fn();
+ sendOutboxEntry.mockResolvedValue({
+ ...ENTRY,
+ state: 'awaiting-confirmation',
+ errorCode: 'DELIVERY_UNCONFIRMED',
+ errorMessage: 'Delivery unconfirmed; check the chat before sending again.',
+ });
+ const { result } = renderHook(() => useBeeperOutbox(CONVERSATION_ID, { onSent }));
await act(async () => { await result.current.submit('hello there'); });
expect(sendOutboxEntry).toHaveBeenCalledTimes(1);
- expect(toastError).toHaveBeenCalled();
- await waitFor(() => expect(result.current.entries[0].state).toBe('failed'));
+ expect(toastError).not.toHaveBeenCalled();
+ expect(onSent).toHaveBeenCalledTimes(1);
+ expect(result.current.entries[0]).toMatchObject({
+ state: 'awaiting-confirmation', errorCode: 'DELIVERY_UNCONFIRMED',
+ });
expect(sendOutboxEntry).toHaveBeenCalledTimes(1);
});
diff --git a/server/services/beeperOutbox.js b/server/services/beeperOutbox.js
index 739d8e2cdb..3e01a9e2ea 100644
--- a/server/services/beeperOutbox.js
+++ b/server/services/beeperOutbox.js
@@ -19,9 +19,9 @@
* a double-click cannot double-post.
* 2. **A send is NEVER retried automatically.** Beeper has no idempotency key
* on `POST /v1/chats/{chatID}/messages`, so a retry delivers a second real
- * message to a real person. A transport failure leaves exactly one row in
- * `failed`, with the code and message, and no second POST. Re-sending is a
- * NEW row, created by a new human action; the failed one stays visible.
+ * message to a real person. A response-less transport failure leaves the
+ * row in `awaiting-confirmation`, because the POST may have landed. Only a
+ * definitive rejection becomes `failed` and offers a new human send.
* 3. **Confirmation is a resolve, never a re-send.** The send is asynchronous
* and answers only `{ chatID, pendingMessageID }`. The row confirms on the
* `message.upserted` invalidation relayed by #33, with a 30-second fallback
@@ -59,16 +59,21 @@ export const CONFIRMATION_TIMEOUT_MS = 30_000;
*
* The outcome is UNKNOWABLE: the request may have been delivered, refused, or
* never have left. Rule 2 above therefore still holds — nothing re-POSTs it.
- * The row lands `failed` so it is actionable (a failed row's Retry composes a
- * NEW row, exactly like typing the message again), and the copy says what
- * actually happened rather than claiming a delivery verdict PortOS does not
- * have. The client renders this sentence verbatim off the code, so the same
- * string is repeated in `client/src/components/messages/beeper/BeeperThread.jsx`
- * — the two bundles cannot share a module, so they share a test instead.
+ * The row lands in the existing terminal `failed` state so it cannot spin
+ * forever, while this error code tells the client to show uncertainty with no
+ * Retry control. The copy says what actually happened rather than claiming a
+ * delivery verdict PortOS does not have. The client renders this sentence
+ * verbatim off the code, so the same string is repeated in
+ * `client/src/components/messages/beeper/BeeperThread.jsx` — the two bundles
+ * cannot share a module, so they share a test instead.
*/
export const SEND_INTERRUPTED_CODE = 'SEND_INTERRUPTED';
export const SEND_INTERRUPTED_MESSAGE = 'Delivery unconfirmed: PortOS restarted mid-send. Check the chat before retrying.';
+/** A send whose POST may have landed, but whose response never reached PortOS. */
+export const DELIVERY_UNCONFIRMED_CODE = 'DELIVERY_UNCONFIRMED';
+export const DELIVERY_UNCONFIRMED_MESSAGE = 'Delivery unconfirmed; check the chat before sending again.';
+
/**
* PostgreSQL's `undefined_table`. The boot reconcile runs before the DB phase
* has called `ensureSchema()`, so a brand-new install's very first start can
@@ -313,6 +318,23 @@ async function markFailed(id, code, message) {
);
}
+async function markAwaitingConfirmation(id, {
+ pendingMessageId = null, errorCode = null, errorMessage = null,
+} = {}) {
+ const updated = await query(
+ `UPDATE beeper_outbox SET state = 'awaiting-confirmation', pending_message_id = $2,
+ error_code = $3, error_message = $4, updated_at = NOW()
+ WHERE id = $1 RETURNING ${ENTRY_COLUMNS}`,
+ [id, pendingMessageId, errorCode, errorMessage],
+ );
+ return updated.rows[0];
+}
+
+/** No HTTP response means the server cannot prove whether the POST landed. */
+function isDeliveryOutcomeUnknown(err) {
+ return err?.status === 0 || err?.code === 'NETWORK_ERROR';
+}
+
/**
* Discard a row the human declined to send — the first-contact confirmation's
* "Cancel" (#53's fix; the original design deliberately left the row
@@ -389,12 +411,30 @@ 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();
const result = await sendMessage(entry.chatId, { text: entry.body })
.then((value) => ({ ok: true, value }))
.catch((err) => ({ ok: false, err }));
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,
+ });
+ return updated;
+ }
await markFailed(id, err?.code, err?.message);
registerSendFailure();
console.error(`${LOG_PREFIX}: send failed (${err?.code || 'SEND_FAILED'})`);
@@ -408,15 +448,10 @@ export async function sendOutboxEntry(id, { confirmFirstContact = false } = {})
registerSendSuccess();
const pendingMessageId = typeof result.value?.pendingMessageID === 'string' ? result.value.pendingMessageID : null;
- const updated = await query(
- `UPDATE beeper_outbox SET state = 'awaiting-confirmation', pending_message_id = $2,
- error_code = NULL, error_message = NULL, updated_at = NOW()
- WHERE id = $1 RETURNING ${ENTRY_COLUMNS}`,
- [id, pendingMessageId],
- );
+ const updated = await markAwaitingConfirmation(id, { 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 });
- return updated.rows[0];
+ armConfirmation({ id, chatId: entry.chatId, conversationId: entry.conversationId, body: entry.body, pendingMessageId, requestedAt });
+ return updated;
}
// ---------------------------------------------------------------------------
@@ -669,8 +704,8 @@ function persistedSendMoment(row) {
* - **`sending` → `failed` / `SEND_INTERRUPTED`.** The POST was in flight; its
* outcome is unknowable. Never auto-resent (rule 2 has no exception for a
* crash — Beeper has no idempotency key, so a "recovery" resend is a second
- * real message). `failed` is the actionable state: the user reads the copy,
- * checks the chat, and Retry composes a NEW row like any other failed one.
+ * real message). `failed` terminates the spinner, while the error code keeps
+ * the client from presenting the ordinary definitive-failure Retry control.
* - **`awaiting-confirmation` → re-armed.** The send DID leave; only the
* resolve was lost. Re-arming replays the lookup from the row's own
* `chat_id` / `pending_message_id` / `body`, which is a read on both paths
diff --git a/server/services/beeperOutbox.test.js b/server/services/beeperOutbox.test.js
index 9337873950..64aa290894 100644
--- a/server/services/beeperOutbox.test.js
+++ b/server/services/beeperOutbox.test.js
@@ -142,6 +142,8 @@ const query = vi.fn(async (sql, params = []) => {
const row = outbox.get(params[0]);
row.state = 'awaiting-confirmation';
row.pendingMessageId = params[1];
+ row.errorCode = params[2];
+ row.errorMessage = params[3];
return { rows: [entryView(row)], rowCount: 1 };
}
if (/UPDATE beeper_outbox SET state = 'failed'/.test(sql)) {
@@ -186,7 +188,7 @@ vi.mock('../lib/db.js', () => ({ query: (...args) => query(...args) }));
const {
BREAKER_MAX_CONSECUTIVE_FAILURES, BREAKER_MAX_SENDS_IN_WINDOW, BREAKER_WINDOW_MS,
- CONFIRMATION_TIMEOUT_MS, SEND_INTERRUPTED_MESSAGE,
+ CONFIRMATION_TIMEOUT_MS, DELIVERY_UNCONFIRMED_CODE, DELIVERY_UNCONFIRMED_MESSAGE, SEND_INTERRUPTED_MESSAGE,
cancelPendingConfirmations, clearOutboxBreaker, configureOutboxRuntime, createOutboxEntry,
discardOutboxEntry, getOutboxBreakerState, getOutboxStatus, isFirstContact, listOutboxEntries,
reconcileOutboxOnBoot, resetOutboxRuntime, sendOutboxEntry,
@@ -480,23 +482,69 @@ describe('isFirstContact — has PortOS addressed this conversation before', ()
});
});
-describe('sendOutboxEntry — transport failure', () => {
- it('leaves exactly one failed row with the error, and posts nothing a second time', async () => {
+describe('sendOutboxEntry — ambiguous and definitive outcomes', () => {
+ it('confirms a response-less send through chat/body/time lookup without another POST', async () => {
markPriorSend();
const entry = await approvedEntry();
sendMessage.mockRejectedValueOnce(new BeeperApiError('Beeper request failed: connection refused', {
status: 0, code: 'NETWORK_ERROR', retryable: false,
}));
+ listMessagesPage.mockResolvedValueOnce({ items: [sentMessage()] });
- await expect(sendOutboxEntry(entry.id)).rejects.toMatchObject({ code: 'NETWORK_ERROR', retryable: false });
+ await expect(sendOutboxEntry(entry.id)).resolves.toMatchObject({
+ state: 'awaiting-confirmation',
+ errorCode: DELIVERY_UNCONFIRMED_CODE,
+ errorMessage: DELIVERY_UNCONFIRMED_MESSAGE,
+ });
expect(sendMessage).toHaveBeenCalledTimes(1);
- const rows = [...outbox.values()].filter((row) => row.state === 'failed');
- expect(rows).toHaveLength(1);
- expect(rows[0].id).toBe(entry.id);
- expect(rows[0].errorCode).toBe('NETWORK_ERROR');
- expect(rows[0].errorMessage).toContain('connection refused');
- // No confirmation was armed for a send that never left.
+ expect(clock.pending()).toBe(1);
+
+ clock.advance(CONFIRMATION_TIMEOUT_MS);
+ clock.runTimersWithDelay(CONFIRMATION_TIMEOUT_MS);
+ await flush();
+
+ expect(getMessage).not.toHaveBeenCalled();
+ expect(listMessagesPage).toHaveBeenCalledWith(CHAT_ID);
+ expect(outbox.get(entry.id)).toMatchObject({ state: 'sent', messageId: 'msg-final-1' });
+ expect(sendMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('leaves a response-less send comprehensibly unconfirmed when read-only lookup finds no match', async () => {
+ markPriorSend();
+ const entry = await approvedEntry();
+ sendMessage.mockRejectedValueOnce(new BeeperApiError('Beeper request failed: connection reset', {
+ status: 0, code: 'NETWORK_ERROR', retryable: false,
+ }));
+ listMessagesPage.mockResolvedValueOnce({ items: [] });
+
+ await sendOutboxEntry(entry.id);
+ clock.advance(CONFIRMATION_TIMEOUT_MS);
+ clock.runTimersWithDelay(CONFIRMATION_TIMEOUT_MS);
+ await flush();
+
+ expect(outbox.get(entry.id)).toMatchObject({
+ state: 'awaiting-confirmation', errorCode: 'CONFIRMATION_UNRESOLVED',
+ });
+ expect(outbox.get(entry.id).errorMessage).toContain('may still have been delivered');
+ expect(sendMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('marks a definitive upstream rejection failed and leaves deliberate Retry available', async () => {
+ markPriorSend();
+ const entry = await approvedEntry();
+ sendMessage.mockRejectedValueOnce(new BeeperApiError('Recipient rejected the message', {
+ status: 400, code: 'INVALID_REQUEST', retryable: false,
+ }));
+
+ await expect(sendOutboxEntry(entry.id)).rejects.toMatchObject({
+ status: 400, code: 'INVALID_REQUEST', retryable: false,
+ });
+
+ expect(outbox.get(entry.id)).toMatchObject({
+ state: 'failed', errorCode: 'INVALID_REQUEST', errorMessage: 'Recipient rejected the message',
+ });
+ expect(sendMessage).toHaveBeenCalledTimes(1);
expect(clock.pending()).toBe(0);
});
});
@@ -756,7 +804,9 @@ describe('runaway breaker', () => {
// eslint-disable-next-line no-await-in-loop -- ordered failures
const entry = await approvedEntry(`attempt ${i}`);
// eslint-disable-next-line no-await-in-loop
- await expect(sendOutboxEntry(entry.id)).rejects.toMatchObject({ code: 'NETWORK_ERROR' });
+ await expect(sendOutboxEntry(entry.id)).resolves.toMatchObject({
+ state: 'awaiting-confirmation', errorCode: DELIVERY_UNCONFIRMED_CODE,
+ });
}
expect(getOutboxBreakerState()).toMatchObject({
tripped: true, consecutiveFailures: BREAKER_MAX_CONSECUTIVE_FAILURES,
@@ -791,7 +841,9 @@ describe('runaway breaker', () => {
const failOnce = async (label) => {
sendMessage.mockRejectedValueOnce(new BeeperApiError('Beeper request failed', { status: 0, code: 'NETWORK_ERROR' }));
const entry = await approvedEntry(label);
- await expect(sendOutboxEntry(entry.id)).rejects.toMatchObject({ code: 'NETWORK_ERROR' });
+ await expect(sendOutboxEntry(entry.id)).resolves.toMatchObject({
+ state: 'awaiting-confirmation', errorCode: DELIVERY_UNCONFIRMED_CODE,
+ });
};
await failOnce('one');