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: harden Beeper integration and resolve upstream conflicts

[._.]/ Adam Eivyd990126d9a59
diff --cc client/src/components/messages/beeper/BeeperChatSurface.jsx
index 0000000000,eb59cade0b..89f3b1fccd
mode 000000,100644..100644
--- a/client/src/components/messages/beeper/BeeperChatSurface.jsx
+++ b/client/src/components/messages/beeper/BeeperChatSurface.jsx
@@@ -1,0 -1,1063 +1,1073 @@@
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+ import { useNavigate, useSearchParams } from 'react-router';
+ import {
+ Archive, BellOff, Clock, Filter, Inbox, Loader2, Mail, MoreHorizontal,
+ PenSquare, Plus, RefreshCw, Search, Settings, TrendingDown,
+ } from 'lucide-react';
+ import NetworkLogo, { networkLabel } from './BeeperNetworkLogo';
+ import BeeperThread from './BeeperThread';
+ import ConnectionStatusDot from '../../ui/ConnectionStatusDot';
+ import toast from '../../ui/Toast';
+ import useMounted from '../../../hooks/useMounted';
+ import useBeeperOutbox from '../../../hooks/useBeeperOutbox';
+ import { messagePreviewText } from '../../../lib/beeperMessageBody';
+ import { safeReadJsonStorage, safeWriteJsonStorage } from '../../../lib/safeStorage';
+ import { formatClockTime } from '../../../utils/formatters';
+ import * as api from '../../../services/api';
+
+ /**
+ * The Beeper chat surface (#35): rail, pinned grid, conversation rows, thread
+ * and composer, ported from the #9 prototype onto the real mirror.
+ *
+ * #9's resolution is that **the reference interface IS the design** — port
+ * Beeper Desktop, mark the deltas, do not redesign around it. The deltas:
+ *
+ * - **Network badges appear on rows only when the list spans networks.**
+ * Inside a single-network scope the rail already states the network, so a
+ * per-row badge is noise and is dropped entirely. This is the one rule a
+ * from-scratch design would most likely have got wrong, in either direction.
+ * - **The rail is one entry per network the MIRROR holds**, never a hardcoded
+ * roster and never the reference's user-curated saved scopes at mixed grain
+ * (a Discord-DMs chip beside a single-server chip). Those are deferred.
+ * - **`Archive` and `Low priority` are wired**, because `isArchived` and
+ * `isLowPriority` are real fields on every chat row. `Requests`, `Later`,
+ * `add scope` and the overflow menu render INERT with a tooltip saying so —
+ * an inert control that looks live is worse than an absent one.
+ * - **The pinned grid is Beeper's own `isPinned`, mirrored.** PortOS never
+ * stores a pin of its own; a second source of truth for it is the whole
+ * thing #27 was designed to avoid.
+ *
+ * Selection lives in the URL (`/messages/beeper/:conversationId`), as does the
+ * scope and the unread-only filter, so a conversation is shareable, bookmarkable
+ * and reachable from ⌘K and voice — and a cold load on a deep link opens the
+ * thread directly rather than the index.
+ *
+ * Realtime is invalidation-driven (#33): a frame never carries rows, so the
+ * surface refetches from the PortOS mirror. Every fetch is generation-guarded,
+ * so a response that lands after the user has moved on is dropped rather than
+ * rendered over the newer one.
+ */
+
+ // Fixed system scopes, in the reference's own order. `live: false` entries
+ // render disabled with a tooltip rather than being omitted, so the deferral is
+ // visible instead of silently missing (#9).
+ const SYSTEM_SCOPES = [
+ { id: 'inbox', label: 'Inbox', icon: Inbox, live: true },
+ { id: 'archive', label: 'Archive', icon: Archive, live: true },
+ { id: 'requests', label: 'Requests', icon: Mail, live: false },
+ { id: 'low', label: 'Low priority', icon: TrendingDown, live: true },
+ { id: 'later', label: 'Later', icon: Clock, live: false },
+ ];
+
+ const LIVE_SYSTEM_SCOPES = new Set(SYSTEM_SCOPES.filter((scope) => scope.live).map((scope) => scope.id));
+ const NETWORK_SCOPE_PREFIX = 'net:';
+ const PINNED_GRID_CAP = 6;
+ const DRAFTS_STORAGE_KEY = 'portos-beeper-drafts';
+ // One coalescing window for a burst of invalidation frames. A busy account can
+ // emit several per second; refetching per frame would hammer the mirror for a
+ // list that has not finished rendering the previous answer.
+ const INVALIDATION_DEBOUNCE_MS = 350;
+ // A CEILING on how long the debounce above may keep resetting itself, anchored
+ // to the FIRST frame of the current window rather than the last. Without this
+ // a sustained stream (the "several per second" case the comment above already
+ // warns about) never goes quiet for 350ms, so the coalescing timer restarts
+ // forever and the list/thread never refresh at all (finding PERF-10). 2s is
+ // six debounce windows: loose enough that an ordinary burst still coalesces
+ // into one refetch, tight enough that a busy account's view is never more
+ // than two seconds stale.
+ const INVALIDATION_MAX_WAIT_MS = 2000;
+ // #81: how long a conversation with no mirrored message is still read as
+ // "the mirror hasn't caught up yet" rather than "genuinely has no history".
+ // The mirror sweep (`beeperSync.js`) now retries an empty first page exactly
+ // once and settles within a sweep pass or two (minutes, not hours), so this
+ // is deliberately generous rather than tuned to that — it exists to cover a
+ // slow initial sweep across many accounts/chats, not to model the retry
+ // timing precisely.
+ const RECENT_ACTIVITY_WINDOW_MS = 24 * 60 * 60 * 1000;
+
+ /** The filter set one scope means. Absent keys are absent FILTERS, not `false`. */
+ function filtersForScope(scope, unreadOnly) {
+ const base = unreadOnly ? { unreadOnly: true } : {};
+ if (scope === 'archive') return { ...base, archived: true };
+ if (scope === 'low') return { ...base, lowPriority: true };
+ if (typeof scope === 'string' && scope.startsWith(NETWORK_SCOPE_PREFIX)) {
+ return { ...base, network: scope.slice(NETWORK_SCOPE_PREFIX.length), archived: false };
+ }
+ return { ...base, archived: false, lowPriority: false };
+ }
+
+ const scopeNetwork = (scope) => (
+ typeof scope === 'string' && scope.startsWith(NETWORK_SCOPE_PREFIX)
+ ? scope.slice(NETWORK_SCOPE_PREFIX.length)
+ : null
+ );
+
+ const rowTime = (iso) => {
+ if (!iso) return '';
+ const date = new Date(iso);
+ const days = Math.floor((Date.now() - date.getTime()) / 86400000);
+ if (days === 0) return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
+ if (days === 1) return 'Yesterday';
+ if (days < 7) return date.toLocaleDateString([], { weekday: 'short' });
+ return date.toLocaleDateString([], { day: 'numeric', month: 'short' });
+ };
+
+ // #81: `lastActivity` is Beeper's own chat-level watermark, mirrored
+ // regardless of whether any message has been mirrored yet (`beeperSync.js`'s
+ // `normalizeChatRow`) — so a row can carry a recent one while `lastMessage`
+ // is still `null`. That combination is what distinguishes "still syncing"
+ // from "this chat has no history", and is the ONLY thing that does: nothing
+ // else in the row shape says whether the mirror has caught up.
+ const isRecentActivity = (iso) => {
+ if (!iso) return false;
+ const ts = new Date(iso).getTime();
+ return Number.isFinite(ts) && Date.now() - ts < RECENT_ACTIVITY_WINDOW_MS;
+ };
+
+ const initials = (name) => String(name || '?')
+ .replace(/^[#+@]/, '')
+ .split(/\s+/)
+ .slice(0, 2)
+ .map((word) => word[0])
+ .filter(Boolean)
+ .join('')
+ .toUpperCase() || '?';
+
+ function Avatar({ name, size = 40 }) {
+ return (
+ <div
+ className="flex shrink-0 items-center justify-center rounded-full bg-port-border font-medium text-gray-300"
+ style={{ width: size, height: size, fontSize: size * 0.34 }}
+ aria-hidden="true"
+ >
+ {initials(name)}
+ </div>
+ );
+ }
+
+ /**
+ * The list header's sweep-visibility strip (#80): "Syncing… N of M accounts"
+ * while a sweep runs, "Last synced HH:MM" once one has finished, and nothing
+ * at all before the first sweep has ever run (a fresh install with no `sweep`
+ * snapshot yet, or one whose `accountsTotal` is not known yet mid-sweep still
+ * says "Syncing…" alone rather than "0 of null accounts").
+ */
+ function SyncStrip({ sweep }) {
+ if (!sweep) return null;
+ if (sweep.running) {
+ const total = Number.isFinite(sweep.accountsTotal) ? sweep.accountsTotal : null;
+ const done = Number.isFinite(sweep.accountsDone) ? sweep.accountsDone : 0;
+ return (
+ <div className="flex shrink-0 items-center gap-1.5 border-b border-port-border/60 px-3 py-1.5 text-[11px] text-gray-400">
+ <Loader2 size={11} className="animate-spin" />
+ {total === null ? 'Syncing…' : `Syncing… ${done} of ${total} account${total === 1 ? '' : 's'}`}
+ </div>
+ );
+ }
+ if (!sweep.finishedAt) return null;
+ return (
+ <div className="shrink-0 border-b border-port-border/60 px-3 py-1.5 text-[11px] text-gray-500">
+ Last synced {formatClockTime(sweep.finishedAt, { seconds: false })}
+ </div>
+ );
+ }
+
+ function InertControl({ icon: Icon, label, className }) {
+ return (
+ <button
+ type="button"
+ disabled
+ aria-label={label}
+ title={`${label} — not available yet`}
+ className={`${className} cursor-not-allowed opacity-35`}
+ >
+ <Icon size={17} />
+ </button>
+ );
+ }
+
+ /* ------------------------------------------------------------------ rail -- */
+
+ function Rail({
+ networks, scope, onScope, totalUnread, onOpenSettings,
+ }) {
+ const item = 'relative flex size-11 shrink-0 items-center justify-center rounded-xl transition';
+ return (
+ <div className="flex w-full shrink-0 flex-row items-center gap-1 overflow-x-auto border-b border-port-border bg-port-bg/60 px-2 py-1.5 sm:w-[68px] sm:flex-col sm:overflow-x-visible sm:overflow-y-auto sm:border-b-0 sm:border-r sm:px-0 sm:py-2">
+ {SYSTEM_SCOPES.map((systemScope) => {
+ const Icon = systemScope.icon;
+ const active = scope === systemScope.id;
+ if (!systemScope.live) {
+ return <InertControl key={systemScope.id} icon={Icon} label={systemScope.label} className={`${item} text-gray-500`} />;
+ }
+ return (
+ <button
+ key={systemScope.id}
+ type="button"
+ title={systemScope.label}
+ aria-label={systemScope.label}
+ aria-pressed={active}
+ onClick={() => onScope(systemScope.id)}
+ className={`${item} ${active ? 'bg-port-card text-white' : 'text-gray-500 hover:text-white'}`}
+ >
+ <Icon size={19} />
+ {systemScope.id === 'inbox' && totalUnread > 0 && (
+ <span className="absolute -right-0.5 -top-0.5 rounded-full bg-port-accent px-1 text-[9px] font-semibold text-port-bg">
+ {totalUnread > 999 ? '999+' : totalUnread}
+ </span>
+ )}
+ </button>
+ );
+ })}
+
+ <div className="mx-1 h-7 w-px shrink-0 bg-port-border sm:mx-0 sm:my-1.5 sm:h-px sm:w-7" />
+
+ {networks.map((entry) => {
+ const id = `${NETWORK_SCOPE_PREFIX}${entry.network}`;
+ const active = scope === id;
+ const label = networkLabel(entry.network);
+ return (
+ <button
+ key={entry.network}
+ type="button"
+ title={label}
+ aria-label={label}
+ aria-pressed={active}
+ onClick={() => onScope(id)}
+ className={`${item} ${active ? 'bg-port-card ring-2 ring-port-accent' : 'opacity-80 hover:opacity-100'}`}
+ >
+ <NetworkLogo network={entry.network} label={label} size={26} />
+ {entry.unreadCount > 0 && (
+ <span className="absolute -right-1 -top-1 min-w-4 rounded-full bg-port-accent px-1 text-[9px] font-semibold text-port-bg">
+ {entry.unreadCount > 99 ? '99+' : entry.unreadCount}
+ </span>
+ )}
+ </button>
+ );
+ })}
+
+ <div className="mx-1 h-7 w-px shrink-0 bg-port-border sm:mx-0 sm:my-1.5 sm:h-px sm:w-7" />
+ <InertControl icon={Plus} label="Add scope" className={`${item} border border-dashed border-port-border text-gray-500`} />
+ <InertControl icon={MoreHorizontal} label="More scope options" className={`${item} text-gray-500`} />
+
+ <button
+ type="button"
+ onClick={onOpenSettings}
+ title="Beeper settings and connection status"
+ aria-label="Beeper settings"
+ className={`${item} ml-auto text-gray-500 hover:text-white sm:ml-0 sm:mt-auto`}
+ >
+ <Settings size={18} />
+ </button>
+ </div>
+ );
+ }
+
+ /* ------------------------------------------------------------ pinned grid -- */
+
+ function PinnedGrid({ conversations, unified, onSelect }) {
+ if (conversations.length === 0) return null;
+ return (
+ <div className="grid shrink-0 grid-cols-3 gap-2 border-b border-port-border px-3 pb-3 pt-2">
+ {conversations.map((conversation) => (
+ <button
+ key={conversation.id}
+ type="button"
+ onClick={() => onSelect(conversation.id)}
+ className="relative flex flex-col items-center gap-1 pt-1"
+ >
+ <span className="relative">
+ <Avatar name={conversation.title} size={48} />
+ {conversation.unreadCount > 0 && (
+ <span className="absolute -right-1 -top-1 z-10 min-w-4 rounded-full bg-port-accent px-1 text-center text-[10px] font-semibold text-port-bg ring-2 ring-port-bg">
+ {conversation.unreadCount > 99 ? '99+' : conversation.unreadCount}
+ </span>
+ )}
+ {unified && (
+ <span data-testid="network-badge" className="absolute -bottom-0.5 -right-0.5 rounded-full ring-2 ring-port-bg">
+ <NetworkLogo network={conversation.network} size={16} />
+ </span>
+ )}
+ </span>
+ <span className="flex w-full items-center justify-center gap-0.5">
+ <span className="truncate text-[11px] text-gray-400">{(conversation.title || '—').split(' ')[0]}</span>
+ {conversation.isMuted && <BellOff size={9} className="shrink-0 text-gray-600" />}
+ </span>
+ </button>
+ ))}
+ </div>
+ );
+ }
+
+ /* -------------------------------------------------------------------- row -- */
+
+ function ConversationRow({ conversation, unified, selected, onSelect }) {
+ const preview = conversation.lastMessage;
+ // The same body the thread renders, flattened to one line: some networks
+ // deliver HTML, and this row used to show the tags literally.
+ //
+ // #81: no mirrored message does not always mean "there is nothing to
+ // mirror" — a chat whose first sweep came back empty is retried, and until
+ // that lands the row used to look identical to a chat that is genuinely
+ // history-less forever, sorting at the top (recency) while reading like a
+ // stale placeholder. Beeper's Chat payload carries no preview/snippet text
+ // of its own to show instead (only `beeperSync.js`'s own mirrored messages
+ // do), so a recent `lastActivity` with no `lastMessage` reads as still
+ // syncing; the honest copy is kept for everything else.
+ const previewText = preview
+ ? (preview.isUnsent ? 'Message unsent' : messagePreviewText(preview.body))
+ : (isRecentActivity(conversation.lastActivity) ? 'Syncing…' : 'No messages mirrored yet');
+ // The reference's leading state chip. Direction is the mirrored `isSender`,
+ // never a comparison against the local user — there is nothing to compare
+ // `senderId` against (#2).
+ const outbound = preview?.isSender === true;
+ return (
+ <button
+ type="button"
+ onClick={() => onSelect(conversation.id)}
+ aria-current={selected ? 'true' : undefined}
+ className={`flex w-full items-center gap-2.5 px-3 py-2 text-left transition hover:bg-port-card ${selected ? 'bg-port-card' : ''}`}
+ >
+ <span className="relative shrink-0">
+ <Avatar name={conversation.title} />
+ {/* THE conditional rule from #9: badge only when the list spans networks. */}
+ {unified && (
+ <span data-testid="network-badge" className="absolute -bottom-0.5 -right-0.5 rounded-full ring-2 ring-port-bg">
+ <NetworkLogo network={conversation.network} size={15} />
+ </span>
+ )}
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="flex items-center gap-1">
+ <span className={`truncate text-[13px] ${conversation.unreadCount > 0 ? 'font-semibold text-white' : 'text-gray-200'}`}>
+ {conversation.title || 'Untitled conversation'}
+ </span>
+ {conversation.isMuted && <BellOff size={11} className="shrink-0 text-gray-600" />}
+ <span className="ml-auto shrink-0 pl-1 text-[11px] text-gray-500">{rowTime(conversation.lastActivity)}</span>
+ </span>
+ <span className="mt-0.5 flex items-center gap-1">
+ {outbound && <span className="shrink-0 text-xs text-gray-500">You:</span>}
+ <span className="min-w-0 flex-1 truncate text-xs text-gray-400">{previewText}</span>
+ {conversation.unreadCount > 0 && (
+ <span className="shrink-0 rounded-full bg-port-accent px-1.5 py-px text-[10px] font-semibold text-port-bg">
+ {conversation.unreadCount > 99 ? '99+' : conversation.unreadCount}
+ </span>
+ )}
+ </span>
+ </span>
+ </button>
+ );
+ }
+
+ /* ---------------------------------------------------------------- surface -- */
+
+ export default function BeeperChatSurface({
+ conversationId = null, realtime = null, invalidationSeq = 0, invalidationFrames = null, breaker = null,
+ sweep = null, tokenConfigured = false, onOpenSettings,
+ }) {
+ const navigate = useNavigate();
+ const mountedRef = useMounted();
+ const [searchParams, setSearchParams] = useSearchParams();
+
+ const scopeParam = searchParams.get('scope') || 'inbox';
+ const unreadOnly = searchParams.get('unread') === '1';
+
+ const [networks, setNetworks] = useState([]);
+ const [conversations, setConversations] = useState([]);
+ const [listCursor, setListCursor] = useState(null);
+ const [listLoading, setListLoading] = useState(true);
+ const [listError, setListError] = useState(null);
+
+ const [conversation, setConversation] = useState(null);
+ const [conversationMissing, setConversationMissing] = useState(false);
+ const [messages, setMessages] = useState([]);
+ const [messageCursor, setMessageCursor] = useState(null);
+ const [threadLoading, setThreadLoading] = useState(false);
+ const [threadError, setThreadError] = useState(null);
+ const [loadingMore, setLoadingMore] = useState(false);
+
+ const [people, setPeople] = useState([]);
+ const [linkingId, setLinkingId] = useState(null);
+ const [writePending, setWritePending] = useState(false);
+ const [purging, setPurging] = useState(false);
+
+ // A PortOS-side draft buffer, keyed by conversation, so a half-written
+ // message survives switching threads AND leaving the page. It is deliberately
+ // NOT Beeper's own chat draft: that is a two-call clear-then-set dance on
+ // PATCH, and syncing one before a send path exists would put half-written
+ // text on the user's phone.
+ const [drafts, setDrafts] = useState(() => safeReadJsonStorage(DRAFTS_STORAGE_KEY, {}) || {});
+
+ // Generation guards. Every async response checks the generation it was issued
+ // under and drops itself if the user has moved on — the stale-response rule
+ // from the socket-UI conventions, which matters here because an invalidation
+ // burst can put several list fetches in flight at once.
+ const listGenRef = useRef(0);
+ const threadGenRef = useRef(0);
+
+ const scope = LIVE_SYSTEM_SCOPES.has(scopeParam) || scopeParam.startsWith(NETWORK_SCOPE_PREFIX)
+ ? scopeParam
+ : 'inbox';
+ const activeNetwork = scopeNetwork(scope);
+ const unified = !activeNetwork;
+ const filters = useMemo(() => filtersForScope(scope, unreadOnly), [scope, unreadOnly]);
+
+ const setParam = useCallback((key, value) => {
+ setSearchParams((prev) => {
+ const next = new URLSearchParams(prev);
+ if (value === null || value === undefined) next.delete(key);
+ else next.set(key, value);
+ return next;
+ }, { replace: true });
+ }, [setSearchParams]);
+
+ const loadNetworks = useCallback(async () => {
+ const data = await api.getBeeperNetworks({ silent: true }).catch(() => null);
+ if (!mountedRef.current) return;
+ setNetworks(Array.isArray(data?.networks) ? data.networks : []);
+ }, [mountedRef]);
+
+ const loadList = useCallback(async () => {
+ const generation = ++listGenRef.current;
+ setListLoading(true);
+ const [data, error] = await api.getBeeperConversations(filters, { silent: true })
+ .then((value) => [value, null])
+ .catch((err) => [null, err]);
+ if (!mountedRef.current || generation !== listGenRef.current) return;
+ if (error) {
+ setListError(error?.message || 'Could not load conversations');
+ } else {
+ setListError(null);
+ setConversations(Array.isArray(data?.conversations) ? data.conversations : []);
+ setListCursor(data?.nextCursor || null);
+ }
+ setListLoading(false);
+ }, [filters, mountedRef]);
+
+ // "Sync now" (#79): the list-header action used to be a pure re-fetch of
+ // whatever the mirror already held (`loadList` + `loadNetworks`), which is
+ // why it never visibly did anything — those are plain SELECTs. This runs
+ // one sweep first, then refetches, so the button's own label matches what
+ // it does. `skipped: true` (a sweep was already in flight — the scheduled
+ // one, most likely) still refetches: whatever that sweep has written so far
+ // is worth showing.
+ const [syncing, setSyncing] = useState(false);
+ const syncNow = useCallback(async () => {
+ setSyncing(true);
+ const result = await api.syncBeeperNow({ silent: true }).catch((err) => {
+ toast.error(err?.message || 'Beeper sync failed');
+ return null;
+ });
+ if (!mountedRef.current) return;
+ setSyncing(false);
+ if (result?.skipped) toast('A sync is already running');
+ loadList();
+ loadNetworks();
+ }, [loadList, loadNetworks, mountedRef]);
+
+ // LOCAL "seen in PortOS" watermark (#83): fire the mark-seen POST and clear
+ // the row's own badge immediately (optimistic), rather than waiting on the
+ // next list/networks refetch to reflect it. NEVER touches Beeper — the POST
+ // is a local `seen_at` stamp, not a read receipt (see the TODO on
+ // `markConversationSeen` server-side for the deferred toggle that would add
+ // one). The call is fire-and-forget: a failure just means the badge is
+ // whatever Beeper's own `unread_count` says until the next successful call,
+ // which is the same "eventually correct" posture every other mirror read
+ // here already has.
+ const markSeen = useCallback((id) => {
+ if (!id) return;
+ api.markBeeperConversationSeen(id, { silent: true }).catch(() => {});
+ setConversations((prev) => (
+ prev.some((row) => row.id === id && row.unreadCount > 0)
+ ? prev.map((row) => (row.id === id ? { ...row, unreadCount: 0 } : row))
+ : prev
+ ));
+ }, []);
+
+ const loadThread = useCallback(async (id) => {
+ if (!id) {
+ setConversation(null);
+ setMessages([]);
+ setMessageCursor(null);
+ setConversationMissing(false);
+ setThreadError(null);
+ return;
+ }
+ const generation = ++threadGenRef.current;
+ setThreadLoading(true);
+ setThreadError(null);
+ const [result, error] = await Promise.all([
+ api.getBeeperConversation(id, { silent: true }),
+ api.getBeeperMessages(id, {}, { silent: true }),
+ ]).then((value) => [value, null]).catch((err) => [null, err]);
+ if (!mountedRef.current || generation !== threadGenRef.current) return;
+ if (error) {
+ // A 404 is "this id is gone or was never here" — a stale bookmark, not a
+ // fault. It renders as not-found rather than as an error banner.
+ if (error?.status === 404) {
+ setConversationMissing(true);
+ setConversation(null);
+ setMessages([]);
+ } else {
+ setThreadError(error?.message || 'Could not load this conversation');
+ }
+ } else {
+ const [detail, page] = result;
+ setConversationMissing(false);
+ setConversation(detail);
+ setMessages(Array.isArray(page?.messages) ? page.messages : []);
+ setMessageCursor(page?.nextCursor || null);
+ // Opening the thread is what "seen" means here (#83) — mark it every
+ // time a thread successfully loads, not only on the first open, so
+ // re-navigating back into an already-open conversation still clears a
+ // badge a sweep put back.
+ markSeen(id);
+ }
+ setThreadLoading(false);
+ }, [mountedRef, markSeen]);
+
+ // The ADDITIVE counterpart to `loadThread` above, for a frame-scoped
+ // invalidation refetch (findings PERF-6/BEEP-5): fetch just the first page
+ // and merge it into the HEAD of `messages` by id, rather than replacing the
+ // thread wholesale. `loadThread` is still correct for a real navigation (a
+ // brand new conversation has no history to preserve); this one exists so an
+ // invalidation on the OPEN thread never discards what the reader already
+ // paged in — `messageCursor` is deliberately left untouched, since it still
+ // points at the oldest page already loaded.
+ //
+ // Guarded like `loadMoreMessages` below (generation CAPTURED, not bumped):
+ // this is compatible with an in-flight load-more for the same conversation,
+ // and only needs to detect a real conversation SWITCH landing mid-fetch —
+ // which `loadThread` marks by incrementing `threadGenRef` itself.
+ const refreshThreadHead = useCallback(async (id) => {
+ if (!id) return;
+ const generation = threadGenRef.current;
+ const page = await api.getBeeperMessages(id, {}, { silent: true }).catch(() => null);
+ if (!mountedRef.current || generation !== threadGenRef.current || !page) return;
+ const incoming = Array.isArray(page.messages) ? page.messages : [];
+ if (incoming.length === 0) return;
+ // Whether this refetch actually surfaced a message the thread did not
+ // already have — computed against the CURRENT `messages` state before the
+ // merge below, not inside `setMessages`'s own updater (whose timing is
+ // not something to build a side-effect decision on). PR 86's sweep emits
+ // an invalidation frame with `chatID: null` once per account, and this
+ // surface's debounce treats that as "could be about anything" and
+ // refetches the open thread regardless — so a 9-account sweep with
+ // nothing new in THIS thread would otherwise fire ~9 no-op mark-seen
+ // POSTs (an UPDATE plus a full `getConversation` read each) below.
+ const existingIds = new Set(messages.map((message) => message.id));
+ const hasNewMessage = incoming.some((message) => !existingIds.has(message.id));
+ setMessages((prev) => {
+ const incomingIds = new Set(incoming.map((message) => message.id));
+ // A message already present is updated in place (the fresh copy wins)
+ // rather than duplicated; everything genuinely older survives untouched
+ // behind it, in whatever order `loadMoreMessages` paged it in.
+ const rest = prev.filter((message) => !incomingIds.has(message.id));
+ return [...incoming, ...rest];
+ });
+ // A new message just landed in the thread the user already has open —
+ // re-stamp the watermark (#83) so the sweep that mirrored it doesn't leave
+ // this conversation's badge showing again on the next list/networks
+ // refetch, which would otherwise read as "unread" a thread that is
+ // visibly on screen right now. Skipped when nothing was actually new: an
+ // UPDATED copy of an already-known message (an edit, or the eventual
+ // `message.upserted` confirmation of something already rendered) is not
+ // new activity for this purpose.
+ if (hasNewMessage) markSeen(id);
+ }, [mountedRef, markSeen, messages]);
+
+ useEffect(() => { loadNetworks(); }, [loadNetworks]);
+ useEffect(() => { loadList(); }, [loadList]);
+ useEffect(() => { loadThread(conversationId); }, [conversationId, loadThread]);
+ useEffect(() => {
+ api.getTribePeople({ silent: true })
+ .then((data) => { if (mountedRef.current) setPeople(Array.isArray(data) ? data : (data?.people || [])); })
+ .catch(() => {});
+ }, [mountedRef]);
+
+ // Invalidation-driven refetch (#33). The frame carries no rows, so the only
+ // correct reaction is to re-read the mirror. Deferred work is guarded twice:
+ // the timer is cleared on unmount, and `mountedRef` stops a fetch that
+ // resolves into a torn-down view.
+ //
+ // The list and networks refetch on ANY frame — other chats' previews and
+ // unread counts genuinely do change. The OPEN THREAD is different: traffic
+ // in any of the install's other chats used to reset it too (PERF-6/BEEP-5),
+ // discarding whatever the reader had paged in. It now refetches only when
+ // some frame seen in this window names this thread's `sourceChatId`, or
+ // carries no chatID at all (a frame this vague could be about anything, so
+ // the safe read is "maybe this thread" rather than "not this thread") — and
+ // even then, additively via `refreshThreadHead`, never via `loadThread`.
+ const refetchRef = useRef({
+ loadList, loadThread, loadNetworks, refreshThreadHead, conversationId, sourceChatId: conversation?.sourceChatId ?? null,
+ });
+ refetchRef.current = {
+ loadList, loadThread, loadNetworks, refreshThreadHead, conversationId, sourceChatId: conversation?.sourceChatId ?? null,
+ };
+ // Anchors the MAX-WAIT ceiling to the first frame of the current window; see
+ // `INVALIDATION_MAX_WAIT_MS`. Reset only when a timer actually fires, never
+ // by the effect's own cleanup — the cleanup fires on every frame in a burst
+ // just to reschedule, and resetting there would defeat the ceiling entirely.
+ const invalidationWindowStartRef = useRef(null);
+ useEffect(() => {
+ if (!invalidationSeq) return undefined;
+ const now = Date.now();
+ if (invalidationWindowStartRef.current === null) invalidationWindowStartRef.current = now;
+ const elapsed = now - invalidationWindowStartRef.current;
+ const wait = Math.max(0, Math.min(INVALIDATION_DEBOUNCE_MS, INVALIDATION_MAX_WAIT_MS - elapsed));
+ const timer = setTimeout(() => {
+ invalidationWindowStartRef.current = null;
+ if (!mountedRef.current) return;
+ const current = refetchRef.current;
+ current.loadList();
+ current.loadNetworks();
+ const frames = invalidationFrames?.current || [];
+ if (invalidationFrames) invalidationFrames.current = [];
+ const inScope = frames.some((frame) => (
+ !frame || frame.chatID === null || frame.chatID === undefined || frame.chatID === current.sourceChatId
+ ));
+ if (current.conversationId && inScope) current.refreshThreadHead(current.conversationId);
+ }, wait);
+ return () => clearTimeout(timer);
+ }, [invalidationSeq, mountedRef, invalidationFrames]);
+
+ // The scope and the unread filter ride along on every selection change, so a
+ // shared conversation link reopens the list the sender was looking at.
+ const querySuffix = useMemo(() => {
+ const encoded = searchParams.toString();
+ return encoded ? `?${encoded}` : '';
+ }, [searchParams]);
+
+ const selectConversation = useCallback((id) => {
+ navigate(`/messages/beeper/${encodeURIComponent(id)}${querySuffix}`);
+ }, [navigate, querySuffix]);
+
+ const clearSelection = useCallback(() => {
+ navigate(`/messages/beeper${querySuffix}`);
+ }, [navigate, querySuffix]);
+
+ // The Tribe link (#98 parts A/C): the title chip for a linked 1:1 chat, and
+ // the "Linked · <name>" row in the participants panel, both jump to the
+ // Tribe page pre-selected on that person via `?person=<id>` (Tribe.jsx
+ // reads it, switches to the Circle tab, and scrolls the card into view).
+ const openTribePerson = useCallback((personId) => {
+ if (!personId) return;
+ navigate(`/tribe?person=${encodeURIComponent(personId)}`);
+ }, [navigate]);
+
+ const setDraft = useCallback((value) => {
+ if (!conversationId) return;
+ setDrafts((prev) => {
+ const next = { ...prev, [conversationId]: value };
+ if (!value) delete next[conversationId];
+ safeWriteJsonStorage(DRAFTS_STORAGE_KEY, next);
+ return next;
+ });
+ }, [conversationId]);
+
+ // The composer's send lifecycle (#36, wired here on #53). `onSent` clears
+ // the PortOS-side draft buffer the same way any other draft edit does —
+ // through `setDraft`, so it also drops the persisted `drafts` entry rather
+ // than leaving a stale one in localStorage under a conversation that no
+ // longer needs it.
+ const {
+ entries: outboxEntries,
+ sending: outboxSending,
+ confirmation: outboxConfirmation,
+ submit: sendOutboxMessage,
+ confirmAndSend: confirmOutboxSend,
+ cancelConfirmation: cancelOutboxConfirmation,
+ retry: retryOutboxEntry,
+ dismiss: dismissOutboxEntry,
- } = useBeeperOutbox(conversationId, { onSent: () => setDraft('') });
++ } = useBeeperOutbox(conversationId, {
++ onSent: (sentConversationId, body) => setDrafts((prev) => {
++ // A send can finish after navigation or another draft edit. Clear only
++ // the text actually sent, in the conversation that owned the request.
++ if (prev[sentConversationId]?.trim() !== body?.trim()) return prev;
++ const next = { ...prev };
++ delete next[sentConversationId];
++ safeWriteJsonStorage(DRAFTS_STORAGE_KEY, next);
++ return next;
++ }),
++ });
+
+ const loadMoreMessages = useCallback(async () => {
+ if (!conversationId || !messageCursor) return;
+ const generation = threadGenRef.current;
+ setLoadingMore(true);
+ try {
+ const page = await api.getBeeperMessages(conversationId, { cursor: messageCursor }, { silent: true }).catch(() => null);
+ // A conversation switch mid-load bumps `threadGenRef` (via `loadThread`),
+ // and this response belongs to the conversation the reader left — it
+ // must not land, but `loadingMore` still has to come back down, or
+ // "Load earlier messages" on the NEW conversation renders permanently
+ // disabled (finding T3). The `finally` below is what guarantees that.
+ if (!mountedRef.current || generation !== threadGenRef.current) return;
+ if (page) {
+ setMessages((prev) => [...prev, ...(Array.isArray(page.messages) ? page.messages : [])]);
+ setMessageCursor(page.nextCursor || null);
+ }
+ } finally {
+ if (mountedRef.current) setLoadingMore(false);
+ }
+ }, [conversationId, messageCursor, mountedRef]);
+
+ // A synchronous in-flight latch, mirroring `submittingRef` in
+ // `useBeeperOutbox.js` (finding T5): `listGenRef`/`listLoading` alone do not
+ // stop two clicks landing inside the same render from both reading "not
+ // loading yet" and both firing the same cursor page, appending it twice.
+ // The ref latches before the first `await`, so the second call returns
+ // immediately no matter how close together the two clicks are.
+ const loadingListRef = useRef(false);
+ const loadMoreConversations = useCallback(async () => {
+ if (!listCursor || loadingListRef.current) return;
+ loadingListRef.current = true;
+ const generation = listGenRef.current;
+ try {
+ const page = await api.getBeeperConversations({ ...filters, cursor: listCursor }, { silent: true }).catch(() => null);
+ if (!mountedRef.current || generation !== listGenRef.current) return;
+ if (page) {
+ setConversations((prev) => [...prev, ...(Array.isArray(page.conversations) ? page.conversations : [])]);
+ setListCursor(page.nextCursor || null);
+ }
+ } finally {
+ loadingListRef.current = false;
+ }
+ }, [filters, listCursor, mountedRef]);
+
+ // Both wired rail controls go through one path: the write reaches Beeper, and
+ // the response — not an optimistic guess — updates local state. A write never
+ // retries, so a failure is reported once and left failed.
+ const applyFlag = useCallback(async (writer, value, label) => {
+ if (!conversationId) return;
+ setWritePending(true);
+ const updated = await writer(conversationId, value, { silent: true }).catch((err) => {
+ toast.error(err?.message || `Could not ${label} this conversation`);
+ return null;
+ });
+ if (!mountedRef.current) return;
+ setWritePending(false);
+ if (!updated) return;
+ // The open thread's own row is set from the server's answer; the LIST is
+ // refetched rather than merged, because archiving changes which scope a
+ // conversation belongs to — a local merge would leave it sitting in a
+ // scope it no longer matches until the next load anyway.
+ setConversation(updated);
+ loadList();
+ }, [conversationId, loadList, mountedRef]);
+
+ // Purging one conversation's mirror. Local state is updated from the result
+ // rather than refetched: the row is gone, the thread has nothing left to
+ // show, and the surface navigates back to the list it came from.
+ const purgeMirror = useCallback(async () => {
+ if (!conversationId) return;
+ setPurging(true);
+ const result = await api.purgeBeeperConversation(conversationId, { silent: true }).catch((err) => {
+ toast.error(err?.message || 'Could not purge this conversation');
+ return null;
+ });
+ if (!mountedRef.current) return;
+ setPurging(false);
+ if (!result) return;
+ setConversations((prev) => prev.filter((row) => row.id !== conversationId));
+ // The purge removes every message the mirror held for this conversation,
+ // so a drafted-but-unsent reply left in `drafts` would otherwise survive
+ // it forever in localStorage — nothing else ever clears an entry once its
+ // conversation is gone from the list. Same shape `setDraft` uses.
+ setDraft('');
+ toast.success(`Mirror purged — ${result.messagesRemoved} message(s), ${result.filesRemoved} attachment file(s) removed`);
+ clearSelection();
+ }, [clearSelection, conversationId, mountedRef, setDraft]);
+
+ // One attachment changed under the thread (a "fetch anyway", a keep toggle).
+ // Merge it into the message it belongs to instead of refetching the page —
+ // the rest of the thread has not moved.
+ const applyAttachmentUpdate = useCallback((messageId, updated) => {
+ setMessages((prev) => prev.map((message) => (
+ message.id === messageId
+ ? {
+ ...message,
+ attachments: (message.attachments || []).map((attachment) => (
+ attachment.idx === updated.idx ? { ...attachment, ...updated } : attachment
+ )),
+ }
+ : message
+ )));
+ }, []);
+
+ const linkParticipant = useCallback(async (participant, personId) => {
+ setLinkingId(participant.sourceUserId);
+ const result = await api.linkBeeperParticipant({
+ conversationId, sourceUserId: participant.sourceUserId, personId,
+ }, { silent: true }).catch((err) => {
+ toast.error(err?.message || 'Could not link this participant');
+ return null;
+ });
+ if (!mountedRef.current) return;
+ setLinkingId(null);
+ if (!result) return;
+ if (result.displacedPersonId) toast.success('Handle moved from another Tribe person');
+ loadThread(conversationId);
+ }, [conversationId, loadThread, mountedRef]);
+
+ // The confirm-and-rename form (#97 part A) hands back the edited fields
+ // rather than this callback inventing them from the participant's raw
+ // display name — the whole point of the form is that the name posted is
+ // the one the user confirmed or corrected, not whatever Beeper reported.
+ const createAndLinkParticipant = useCallback(async (participant, { name, ring, relationship } = {}) => {
+ setLinkingId(participant.sourceUserId);
+ const result = await api.createTribePersonFromBeeper({
+ conversationId,
+ sourceUserId: participant.sourceUserId,
+ name: name || participant.displayName || participant.handle || undefined,
+ ring,
+ relationship,
+ }, { silent: true }).catch((err) => {
+ toast.error(err?.message || 'Could not create a Tribe person');
+ return null;
+ });
+ if (!mountedRef.current) return;
+ setLinkingId(null);
+ if (!result) return;
+ toast.success('Linked to a new Tribe person');
+ loadThread(conversationId);
+ api.getTribePeople({ silent: true })
+ .then((data) => { if (mountedRef.current) setPeople(Array.isArray(data) ? data : (data?.people || [])); })
+ .catch(() => {});
+ }, [conversationId, loadThread, mountedRef]);
+
+ // Unlink (#97 part B): the row's affordances flip immediately — cleared
+ // optimistically in the loaded thread the same shape `linkParticipant`'s
+ // successful result carries (`tribePersonId`/`tribePersonName`) — and then
+ // `loadThread` settles the truth from the server either way, the same
+ // refresh-after-write shape every other write in this surface uses.
+ const unlinkParticipant = useCallback(async (participant) => {
+ setLinkingId(participant.sourceUserId);
+ setConversation((prev) => (prev ? {
+ ...prev,
+ participants: (prev.participants || []).map((row) => (
+ row.sourceUserId === participant.sourceUserId
+ ? { ...row, tribePersonId: null, tribePersonName: null }
+ : row
+ )),
+ } : prev));
+ await api.unlinkBeeperParticipant({
+ conversationId, sourceUserId: participant.sourceUserId,
+ }, { silent: true }).catch((err) => {
+ toast.error(err?.message || 'Could not unlink this participant');
+ return null;
+ });
+ if (!mountedRef.current) return;
+ setLinkingId(null);
+ loadThread(conversationId);
+ }, [conversationId, loadThread, mountedRef]);
+
+ const pinned = useMemo(
+ () => conversations.filter((row) => row.isPinned).slice(0, PINNED_GRID_CAP),
+ [conversations],
+ );
+ const totalUnread = useMemo(
+ () => networks.reduce((sum, entry) => sum + (entry.unreadCount || 0), 0),
+ [networks],
+ );
+ const scopeLabel = activeNetwork
+ ? networkLabel(activeNetwork)
+ : (SYSTEM_SCOPES.find((entry) => entry.id === scope)?.label || 'Inbox');
+
+ return (
+ <div className="flex h-full min-h-0 flex-col sm:flex-row">
+ <Rail
+ networks={networks}
+ scope={scope}
+ onScope={(next) => setParam('scope', next)}
+ totalUnread={totalUnread}
+ onOpenSettings={onOpenSettings}
+ />
+
+ {/* The thread pane only appears at `md`, so the list is full width below
+ it: a fixed 280px column in the 640–767px band put a narrow strip
+ beside dead space. */}
+ <div className={`flex min-h-0 w-full flex-col border-port-border md:w-[280px] md:shrink-0 md:border-r ${conversationId ? 'hidden md:flex' : 'flex'}`}>
+ {/* Liveness renders on exactly two surfaces (#12 decision 4): this
+ Moltworld-shape dot, and the settings card for an actionable fault.
+ There is no global banner, and the dot lives at the head of the
+ scope column rather than inside the 68px icon rail, where the
+ component's status word has nowhere to go. `null` = the transport
+ has not reported yet, and is never drawn as offline. */}
+ {realtime?.state && (
+ <div className="shrink-0 border-b border-port-border/60 px-3 py-1.5">
+ <ConnectionStatusDot status={realtime.state} label="Realtime:" className="text-[11px]" />
+ </div>
+ )}
+
+ <SyncStrip sweep={sweep} />
+
+ <div className="flex shrink-0 items-center gap-1 px-3 py-2.5">
+ <span className="flex min-w-0 items-center gap-1 text-sm font-semibold text-white">
+ {/* No chevron here (audit cluster 08, COPY-3): a scope-picker menu
+ does not exist, and an inert control that looks live is worse
+ than an absent one — the file's own governing rule. */}
+ <span className="truncate">{scopeLabel}</span>
+ </span>
+ <button
+ type="button"
+ onClick={() => setParam('unread', unreadOnly ? null : '1')}
+ title="Unread only"
+ aria-label="Unread only"
+ aria-pressed={unreadOnly}
+ className={`ml-auto inline-flex min-h-[44px] min-w-[44px] items-center justify-center rounded p-1.5 ${unreadOnly ? 'bg-port-accent text-port-bg' : 'text-gray-500 hover:text-white'}`}
+ >
+ <Filter size={15} />
+ </button>
+ <button
+ type="button"
+ onClick={syncNow}
+ disabled={syncing}
+ title="Sync now — runs a Beeper sweep immediately, then refreshes this list"
+ aria-label="Sync now"
+ className="inline-flex min-h-[44px] min-w-[44px] items-center justify-center rounded p-1.5 text-gray-500 hover:text-white disabled:opacity-50"
+ >
+ <RefreshCw size={15} className={syncing || listLoading ? 'animate-spin' : undefined} />
+ </button>
+ <InertControl icon={Search} label="Search conversations" className="rounded p-1.5 text-gray-500" />
+ <InertControl icon={PenSquare} label="New conversation" className="rounded p-1.5 text-gray-500" />
+ </div>
+
+ {listError && (
+ <p role="alert" className="mx-3 mb-2 rounded border border-port-error/40 bg-port-error/10 px-2 py-1.5 text-[11px] text-port-error">
+ {listError}
+ </p>
+ )}
+
+ {!unreadOnly && <PinnedGrid conversations={pinned} unified={unified} onSelect={selectConversation} />}
+
+ {listLoading && conversations.length === 0 ? (
+ <p className="flex flex-1 items-center justify-center gap-2 p-6 text-xs text-gray-500">
+ <Loader2 size={12} className="animate-spin" /> Loading conversations…
+ </p>
+ ) : conversations.length === 0 ? (
+ <div className="flex flex-1 flex-col items-center justify-center gap-1 p-6 text-center">
+ <p className="text-sm text-gray-300">Nothing here</p>
+ {/* The reassurance below only makes sense once the list itself is
+ known-good (#3/A11Y-3): a failed fetch already explains itself
+ via the error banner above, and repeating "often correct" right
+ under it read as a contradiction. Zero mirrored networks and an
+ active unread filter are their own, more useful answers than a
+ generic count. */}
+ {!listError && (
+ <p className="text-[11px] text-gray-500">
+ {networks.length === 0 ? (
+ // Branches on `tokenConfigured` (#80), not on `networks.length`
+ // alone: a connected install whose first sweep just hasn't
+ // written a network row yet is a different state from one
+ // that was never told to connect anything, and telling the
+ // first case to "open settings" sends a user who already did
+ // that back to the same drawer for no reason.
+ tokenConfigured ? (
+ 'First sync in progress — give it a moment and mirrored networks will start appearing here.'
+ ) : (
+ <>
+ Nothing is mirrored yet.{' '}
+ <button
+ type="button"
+ onClick={onOpenSettings}
+ className="text-port-accent underline underline-offset-2"
+ >
+ Open Beeper settings
+ </button>{' '}
+ to connect a network.
+ </>
+ )
+ ) : unreadOnly ? (
+ 'The unread filter is on — nothing unread here.'
+ ) : (
+ <>
+ {networks.length} network{networks.length === 1 ? '' : 's'} mirrored. History depth varies
+ enormously per network, so an empty list is often correct rather than broken.
+ </>
+ )}
+ </p>
+ )}
+ </div>
+ ) : (
+ <div className="min-h-0 flex-1 divide-y divide-port-border/50 overflow-y-auto">
+ {conversations.map((row) => (
+ <ConversationRow
+ key={row.id}
+ conversation={row}
+ unified={unified}
+ selected={conversationId === row.id}
+ onSelect={selectConversation}
+ />
+ ))}
+ {listCursor && (
+ <div className="p-2 text-center">
+ <button
+ type="button"
+ onClick={loadMoreConversations}
+ className="min-h-[32px] rounded-full border border-port-border px-3 text-[11px] text-gray-300 transition-colors hover:border-port-accent"
+ >
+ Load more
+ </button>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+
+ <div className={`min-h-0 flex-1 ${conversationId ? 'flex flex-col' : 'hidden md:flex md:flex-col'}`}>
+ {conversationMissing ? (
+ <div className="flex h-full flex-col items-center justify-center gap-2 p-6 text-center">
+ <p className="text-sm text-gray-300">Conversation not found</p>
+ <p className="max-w-sm text-[11px] text-gray-500">
+ This link points at a conversation that is not in the mirror — it may have been removed, or belong to an
+ account that is no longer connected.
+ </p>
+ <button
+ type="button"
+ onClick={clearSelection}
+ className="min-h-[36px] rounded-lg border border-port-border px-3 text-xs text-gray-200 transition-colors hover:border-port-accent"
+ >
+ Back to conversations
+ </button>
+ </div>
+ ) : (
+ <BeeperThread
+ conversation={conversation}
+ messages={messages}
+ loading={threadLoading}
+ error={threadError}
+ hasMore={Boolean(messageCursor)}
+ loadingMore={loadingMore}
+ onLoadMore={loadMoreMessages}
+ draft={drafts[conversationId] || ''}
+ onDraftChange={setDraft}
+ outboxEntries={outboxEntries}
+ sending={outboxSending}
+ confirmation={outboxConfirmation}
+ onSend={sendOutboxMessage}
+ confirmAndSend={confirmOutboxSend}
+ cancelConfirmation={cancelOutboxConfirmation}
+ retryOutboxEntry={retryOutboxEntry}
+ dismissOutboxEntry={dismissOutboxEntry}
+ breaker={breaker}
+ people={people}
+ linkingId={linkingId}
+ onLinkParticipant={linkParticipant}
+ onCreateAndLinkParticipant={createAndLinkParticipant}
+ onUnlinkParticipant={unlinkParticipant}
+ onOpenTribePerson={openTribePerson}
+ onBack={clearSelection}
+ onRetry={conversationId ? () => loadThread(conversationId) : null}
+ writePending={writePending}
+ onArchive={(value) => applyFlag(api.setBeeperConversationArchived, value, 'archive')}
+ onLowPriority={(value) => applyFlag(api.setBeeperConversationLowPriority, value, 'update')}
+ onPurge={purgeMirror}
+ purging={purging}
+ onAttachmentUpdated={applyAttachmentUpdate}
+ />
+ )}
+ </div>
+ </div>
+ );
+ }
diff --cc client/src/hooks/useBeeperOutbox.js
index 0000000000,e0779f3500..95dbbef3f2
mode 000000,100644..100644
--- a/client/src/hooks/useBeeperOutbox.js
+++ b/client/src/hooks/useBeeperOutbox.js
@@@ -1,0 -1,235 +1,245 @@@
+ import { useCallback, useEffect, useRef, useState } from 'react';
+ import toast from '../components/ui/Toast';
+ import {
+ createOutboxEntry, discardOutboxEntry, listOutboxEntries, sendOutboxEntry,
+ } from '../services/apiBeeper';
+ import useBeeperRealtime from './useBeeperRealtime';
+ import useMounted from './useMounted';
+
+ /**
+ * The Beeper composer's send lifecycle (#36, decided on #8).
+ *
+ * Two server steps, deliberately: `POST /api/beeper/outbox` writes the durable
+ * row from the typed body, then `POST /api/beeper/outbox/:id/send` performs the
+ * send. This hook drives both from one `submit(body)` so the composer stays a
+ * text box with a button, while the row exists on disk before anything is sent.
+ *
+ * Three rules it exists to keep:
+ *
+ * - **A send that touched the wire never retries in place.** Beeper has no
+ * idempotency key on send, so retrying an attempt that reached
+ * `sendMessage` is a second real message. A `failed` row stays failed and
+ * visible in `entries`; sending again means composing again, via
+ * `submit()`, which creates a NEW row. `retry()` is the narrow exception:
+ * it only ever re-dispatches a row still `approved` — refused before the
+ * server could claim it (`OUTBOX_BREAKER_OPEN` is the practical case) —
+ * where nothing has touched the wire yet, so re-sending the same row is
+ * exactly as safe as sending it the first time.
+ * - **First contact confirms inline.** The server refuses the first outbound
+ * message to a conversation with `FIRST_CONTACT_CONFIRMATION_REQUIRED`;
+ * that answer is surfaced as `confirmation`, NOT as an error toast, so the
+ * composer can render an `InlineConfirmRow` (never `window.confirm`, which
+ * client conventions forbid). `confirmAndSend()` re-sends the SAME row with
+ * the flag — it does not create a second one.
+ * - **Confirmation is the server's business.** A sent row sits in
+ * `awaiting-confirmation` until the socket or the 30s fallback resolves it;
+ * this hook just refetches when an invalidation says the mirror moved.
+ *
+ * @param {string|null} conversationId the open conversation (a route param).
+ * @param {object} [options]
- * @param {() => void} [options.onSent] called after a send that CAME FROM the
- * composer is accepted, so the composer can clear its draft buffer. A send
++ * @param {(conversationId: string, body: string) => void} [options.onSent]
++ * Called after a composer send is accepted, with its original conversation
++ * and text so navigation or a newer edit cannot clear an unrelated draft. A send
+ * whose text came from somewhere else — a failed row's Retry, which passes
+ * `submit(body, { clearsDraft: false })`, or `retry()` re-dispatching an
+ * existing row — never fires it: the draft may hold a newer message the
+ * user has typed since, and clearing it would discard text that was never
+ * sent.
+ */
+ export default function useBeeperOutbox(conversationId, { onSent } = {}) {
+ const [entries, setEntries] = useState([]);
+ const [sending, setSending] = useState(false);
+ // `null` = no confirmation pending. When set it carries the entry the user is
+ // being asked about, so confirming re-sends that row rather than a new one.
+ const [confirmation, setConfirmation] = useState(null);
+ const [error, setError] = useState(null);
+ const mountedRef = useMounted();
+ const onSentRef = useRef(onSent);
+ onSentRef.current = onSent;
++ const scopeRef = useRef({ conversationId, refreshGeneration: 0 });
++ if (scopeRef.current.conversationId !== conversationId) {
++ scopeRef.current = { conversationId, refreshGeneration: 0 };
++ }
++ const scope = scopeRef.current;
+
+ const refresh = useCallback(async () => {
+ if (!conversationId) {
+ setEntries([]);
+ return;
+ }
++ const generation = ++scope.refreshGeneration;
+ const result = await listOutboxEntries(conversationId, { silent: true }).catch(() => null);
- if (!mountedRef.current) return;
++ if (!mountedRef.current || scopeRef.current !== scope || generation !== scope.refreshGeneration) return;
+ // A failed GET leaves the list alone rather than blanking it — absent is
+ // not the same as empty, and an emptied list would hide a failed send.
+ if (Array.isArray(result?.entries)) setEntries(result.entries);
- }, [conversationId]);
++ }, [conversationId, scope]);
+
+ useEffect(() => {
++ setEntries([]);
++ setSending(false);
+ setConfirmation(null);
+ setError(null);
+ refresh();
+ }, [refresh]);
+
+ // A send confirms server-side (socket `message.upserted`, or the 30s GET
+ // fallback), and the server re-broadcasts an id-only invalidation when it
+ // lands. That is the cue to refetch the outbox — no polling, no timers here.
+ const awaitingRef = useRef(false);
+ awaitingRef.current = entries.some((entry) => entry.state === 'awaiting-confirmation' || entry.state === 'sending');
+ useBeeperRealtime({
+ onInvalidate: (frame) => {
- if (frame?.kind !== 'message.upserted' || !awaitingRef.current) return;
++ if (!['message.upserted', 'outbox.updated'].includes(frame?.kind) || !awaitingRef.current) return;
+ refresh();
+ },
+ });
+
+ /**
+ * Send one existing row. Shared by the first attempt and the confirmation.
+ * `clearsDraft` says whether this send's text is the composer's current
+ * draft — the only case where finishing it should clear the composer.
+ */
+ const dispatch = useCallback(async (entry, confirmFirstContact, clearsDraft = false) => {
+ setSending(true);
+ const [sent, err] = await sendOutboxEntry(entry.id, { confirmFirstContact }, { silent: true })
+ .then((value) => [value, null])
+ .catch((sendError) => [null, sendError]);
+ if (!mountedRef.current) return false;
++ if (!err && clearsDraft) onSentRef.current?.(conversationId, entry.body);
++ if (scopeRef.current !== scope) return !err;
+ setSending(false);
+
+ if (err?.code === 'FIRST_CONTACT_CONFIRMATION_REQUIRED') {
+ // Not an error state: a question. The composer renders it inline.
+ // `clearsDraft` rides along so answering "Send anyway" keeps whatever
+ // this attempt's origin decided, rather than defaulting back to the
+ // composer's.
+ setConfirmation({ entry, message: err.message, clearsDraft });
+ return false;
+ }
+ setConfirmation(null);
+ if (err) {
+ setError(err.message || 'Could not send the message');
+ toast.error(err.message || 'Could not send the message');
+ await refresh();
+ return false;
+ }
+ setError(null);
+ setEntries((prev) => [sent, ...prev.filter((row) => row.id !== sent.id)]);
- if (clearsDraft) onSentRef.current?.();
+ return true;
- }, [refresh]);
++ }, [refresh, conversationId, scope]);
+
+ // `sending` is React state, so it only reflects a send that has already
+ // re-rendered. Two `submit()` calls inside ONE render — a double-fired Send
+ // button, an Enter keydown racing the click — both read it as false, both
+ // create a durable row, and both dispatch a real message. Beeper has no
+ // idempotency key, so that second message is unrecallable. This ref latches
+ // synchronously, before the first await, and is the actual guard; `sending`
+ // stays as the RENDER signal it already is.
+ const submittingRef = useRef(false);
+
+ /**
+ * Step one + step two, from the composer's Send action.
+ *
+ * `clearsDraft` defaults to true because the composer is the ordinary
+ * caller. The one caller that passes false is a `failed` row's Retry, which
+ * composes a new entry from that ROW's text — clearing the composer there
+ * would throw away a message typed since the failure.
+ */
+ const submit = useCallback(async (body, { clearsDraft = true } = {}) => {
+ const text = typeof body === 'string' ? body.trim() : '';
+ if (!conversationId || !text || sending || submittingRef.current) return false;
+ submittingRef.current = true;
+ try {
+ setError(null);
+ const [entry, err] = await createOutboxEntry(conversationId, text, { silent: true })
+ .then((value) => [value, null])
+ .catch((createError) => [null, createError]);
- if (!mountedRef.current) return false;
++ if (!mountedRef.current || scopeRef.current !== scope) return false;
+ if (err) {
+ setError(err.message || 'Could not queue the message');
+ toast.error(err.message || 'Could not queue the message');
+ return false;
+ }
+ setEntries((prev) => [entry, ...prev]);
+ // Awaited into a local rather than returned bare: `return dispatch(...)`
+ // would run the `finally` and drop the latch before the send resolved.
+ const dispatched = await dispatch(entry, false, clearsDraft);
+ return dispatched;
+ } finally {
+ // `finally`, not a catch: nothing is swallowed, but the latch must not
+ // survive a throw or the composer is wedged shut for the session.
+ submittingRef.current = false;
+ }
- }, [conversationId, dispatch, sending]);
++ }, [conversationId, dispatch, sending, scope]);
+
+ /** The inline confirmation's "Send" — the same row, now explicitly confirmed. */
+ const confirmAndSend = useCallback(async () => {
+ if (!confirmation?.entry) return false;
+ return dispatch(confirmation.entry, true, confirmation.clearsDraft === true);
+ }, [confirmation, dispatch]);
+
+ /**
+ * Discard a row the human has given up on. Legal only while the row is
+ * still `approved` — the server enforces that, and this mirrors it exactly
+ * — because that is the only state meaning nothing has POSTed to Beeper
+ * for it yet. Leaving an unwanted `approved` row behind was the original
+ * design, but the composer had no way to render or dismiss it distinctly
+ * from "sending": it fell into `OutboxRow`'s default branch and rendered
+ * as a permanent "Sending…" bubble, including across a reload, because
+ * `GET /outbox` returns every approved row (#53's Cancel fix; #60 blocker
+ * 1 closed the other way in — a refused send, e.g. `OUTBOX_BREAKER_OPEN`
+ * — into the same phantom). A discard failure (e.g. a network hiccup)
+ * refetches instead of silently dropping the row from just the client's
+ * view — the truth is the server's.
+ */
+ const discardEntry = useCallback(async (entry) => {
+ if (!entry) return;
+ const [, err] = await discardOutboxEntry(entry.id, { silent: true })
+ .then(() => [true, null])
+ .catch((discardError) => [null, discardError]);
- if (!mountedRef.current) return;
++ if (!mountedRef.current || scopeRef.current !== scope) return;
+ if (err) {
+ toast.error(err.message || 'Could not discard the message');
+ await refresh();
+ return;
+ }
+ setEntries((prev) => prev.filter((row) => row.id !== entry.id));
- }, [refresh]);
++ }, [refresh, scope]);
+
+ /** The inline confirmation's "Cancel" — see `discardEntry`. */
+ const cancelConfirmation = useCallback(async () => {
+ const entry = confirmation?.entry;
+ setConfirmation(null);
+ if (!entry) return;
+ await discardEntry(entry);
+ }, [confirmation, discardEntry]);
+
+ /**
+ * Retry a row that never reached Beeper — a stalled `approved` entry
+ * refused before the server could claim it (`OUTBOX_BREAKER_OPEN` is the
+ * practical case, #60 blocker 1). Re-dispatches the SAME row rather than
+ * composing a new one: nothing has touched the wire for it, so this is as
+ * safe as sending it the first time, and it means a stuck breaker does not
+ * manufacture a fresh phantom on every click the way retrying via `submit`
+ * would. It never clears the composer: the row's text is not the draft.
+ */
+ const retry = useCallback((entry) => dispatch(entry, false, false), [dispatch]);
+
+ /** Give up on a stalled `approved` row outright — see `discardEntry`. */
+ const dismiss = useCallback((entry) => discardEntry(entry), [discardEntry]);
+
+ return {
+ entries,
+ sending,
+ error,
+ confirmation,
+ submit,
+ confirmAndSend,
+ cancelConfirmation,
+ retry,
+ dismiss,
+ refresh,
+ };
+ }
diff --cc client/src/hooks/useBeeperOutbox.test.jsx
index 0000000000,abdfac4c14..a64ae8f1e4
mode 000000,100644..100644
--- a/client/src/hooks/useBeeperOutbox.test.jsx
+++ b/client/src/hooks/useBeeperOutbox.test.jsx
@@@ -1,0 -1,285 +1,312 @@@
+ import {
+ describe, it, expect, vi, beforeEach, afterEach,
+ } from 'vitest';
+ import { renderHook, act, cleanup, waitFor } from '@testing-library/react';
+
+ /**
+ * The composer's send lifecycle (#36). What matters here is the SHAPE of the
+ * two-step flow, not the HTTP: create then send, one send per row ever, and a
+ * first-contact refusal surfacing as an inline question rather than an error.
+ */
+
+ const listOutboxEntries = vi.fn();
+ const createOutboxEntry = vi.fn();
+ const sendOutboxEntry = vi.fn();
+ const discardOutboxEntry = vi.fn();
+
+ vi.mock('../services/apiBeeper', () => ({
+ listOutboxEntries: (...args) => listOutboxEntries(...args),
+ createOutboxEntry: (...args) => createOutboxEntry(...args),
+ sendOutboxEntry: (...args) => sendOutboxEntry(...args),
+ discardOutboxEntry: (...args) => discardOutboxEntry(...args),
+ }));
+
+ const invalidateHandlers = new Set();
+ vi.mock('./useBeeperRealtime', () => ({
+ default: ({ onInvalidate } = {}) => {
+ invalidateHandlers.add(onInvalidate);
+ return { realtime: null };
+ },
+ }));
+
+ const toastError = vi.fn();
+ vi.mock('../components/ui/Toast', () => ({
+ default: { error: (...args) => toastError(...args), success: vi.fn() },
+ }));
+
+ const useBeeperOutbox = (await import('./useBeeperOutbox.js')).default;
+
+ const CONVERSATION_ID = '11111111-1111-4111-8111-111111111111';
+ const ENTRY = { id: 'outbox-1', state: 'approved', body: 'hello there' };
+
+ class ApiError extends Error {
+ constructor(message, code) {
+ super(message);
+ this.code = code;
+ }
+ }
+
+ describe('useBeeperOutbox', () => {
+ beforeEach(() => {
+ listOutboxEntries.mockReset().mockResolvedValue({ entries: [] });
+ createOutboxEntry.mockReset().mockResolvedValue(ENTRY);
+ sendOutboxEntry.mockReset().mockResolvedValue({ ...ENTRY, state: 'awaiting-confirmation' });
+ discardOutboxEntry.mockReset().mockResolvedValue(undefined);
+ toastError.mockReset();
+ invalidateHandlers.clear();
+ });
+ afterEach(cleanup);
+
+ it('creates the durable row first, then sends it exactly once', async () => {
+ const onSent = vi.fn();
+ const { result } = renderHook(() => useBeeperOutbox(CONVERSATION_ID, { onSent }));
+
+ await act(async () => { await result.current.submit('hello there'); });
+
+ expect(createOutboxEntry).toHaveBeenCalledWith(CONVERSATION_ID, 'hello there', { silent: true });
+ expect(sendOutboxEntry).toHaveBeenCalledTimes(1);
+ expect(sendOutboxEntry).toHaveBeenCalledWith('outbox-1', { confirmFirstContact: false }, { silent: true });
+ expect(onSent).toHaveBeenCalledTimes(1);
+ expect(result.current.entries[0].state).toBe('awaiting-confirmation');
+ });
+
++ it('keeps delayed requests scoped to their original conversation', async () => {
++ let finishSend;
++ let finishList;
++ const onSent = vi.fn();
++ sendOutboxEntry.mockImplementationOnce(() => new Promise((resolve) => { finishSend = resolve; }));
++ const { result, rerender } = renderHook(({ id }) => useBeeperOutbox(id, { onSent }), {
++ initialProps: { id: CONVERSATION_ID },
++ });
++ await act(async () => {});
++ let sending;
++ await act(async () => { sending = result.current.submit('hello there'); });
++ listOutboxEntries.mockImplementationOnce(() => new Promise((resolve) => { finishList = resolve; }));
++ let refresh;
++ act(() => { refresh = result.current.refresh(); });
++ rerender({ id: 'other-conversation' });
++ await act(async () => {});
++ await act(async () => {
++ finishSend({ ...ENTRY, state: 'awaiting-confirmation' });
++ finishList({ entries: [ENTRY] });
++ await Promise.all([sending, refresh]);
++ });
++ expect(result.current.entries).toEqual([]);
++ expect(result.current.confirmation).toBeNull();
++ expect(result.current.sending).toBe(false);
++ expect(onSent).toHaveBeenCalledWith(CONVERSATION_ID, ENTRY.body);
++ });
++
+ // `sending` is React state and does not update until a re-render, so it
+ // cannot stop two calls made inside one render — a double-fired Send button,
+ // or Enter racing the click. Beeper has no idempotency key, so the second row
+ // would be a second unrecallable message.
+ it('latches submit so two calls in one render create and send exactly one row', async () => {
+ const { result } = renderHook(() => useBeeperOutbox(CONVERSATION_ID));
+
+ let outcomes;
+ await act(async () => {
+ outcomes = await Promise.all([
+ result.current.submit('hello there'),
+ result.current.submit('hello there'),
+ ]);
+ });
+
+ expect(createOutboxEntry).toHaveBeenCalledTimes(1);
+ expect(sendOutboxEntry).toHaveBeenCalledTimes(1);
+ // The loser is refused, not queued behind the winner.
+ expect(outcomes).toEqual([true, false]);
+ expect(result.current.entries).toHaveLength(1);
+
+ // And the latch releases: a later, deliberate send still goes through.
+ await act(async () => { await result.current.submit('hello again'); });
+ expect(createOutboxEntry).toHaveBeenCalledTimes(2);
+ });
+
+ it('surfaces a first-contact refusal as an inline confirmation, then re-sends the SAME row', async () => {
+ sendOutboxEntry.mockRejectedValueOnce(new ApiError(
+ 'This is the first message PortOS has ever sent to this conversation',
+ 'FIRST_CONTACT_CONFIRMATION_REQUIRED',
+ ));
+ const { result } = renderHook(() => useBeeperOutbox(CONVERSATION_ID));
+
+ await act(async () => { await result.current.submit('hello there'); });
+ // A question, not an error: nothing toasts, and the row is still there.
+ expect(result.current.confirmation?.entry.id).toBe('outbox-1');
+ expect(toastError).not.toHaveBeenCalled();
+
+ await act(async () => { await result.current.confirmAndSend(); });
+ expect(createOutboxEntry).toHaveBeenCalledTimes(1);
+ expect(sendOutboxEntry).toHaveBeenLastCalledWith('outbox-1', { confirmFirstContact: true }, { silent: true });
+ expect(result.current.confirmation).toBeNull();
+ });
+
+ // The reviewer's blocker on #53: a cancelled first-contact confirmation used
+ // to leave the row `approved` and in `entries` forever, with no server call
+ // and no way to dismiss it — a phantom "Sending…" bubble that survived
+ // reloads. Cancel must discard the row, not just clear the local question.
+ it('discards the row on Cancel, so it does not linger as a phantom pending send', async () => {
+ sendOutboxEntry.mockRejectedValueOnce(new ApiError(
+ 'This is the first message PortOS has ever sent to this conversation',
+ 'FIRST_CONTACT_CONFIRMATION_REQUIRED',
+ ));
+ const { result } = renderHook(() => useBeeperOutbox(CONVERSATION_ID));
+
+ await act(async () => { await result.current.submit('hello there'); });
+ expect(result.current.confirmation?.entry.id).toBe('outbox-1');
+ expect(result.current.entries).toHaveLength(1);
+
+ await act(async () => { await result.current.cancelConfirmation(); });
+
+ expect(discardOutboxEntry).toHaveBeenCalledWith('outbox-1', { silent: true });
+ expect(result.current.confirmation).toBeNull();
+ expect(result.current.entries).toHaveLength(0);
+ // Cancel never re-sends — it never even reaches the send path a second time.
+ expect(sendOutboxEntry).toHaveBeenCalledTimes(1);
+ });
+
+ it('refetches rather than silently hiding the row when the discard itself fails', async () => {
+ sendOutboxEntry.mockRejectedValueOnce(new ApiError(
+ 'This is the first message PortOS has ever sent to this conversation',
+ 'FIRST_CONTACT_CONFIRMATION_REQUIRED',
+ ));
+ discardOutboxEntry.mockRejectedValueOnce(new ApiError('Beeper request failed', 'NETWORK_ERROR'));
+ listOutboxEntries.mockResolvedValue({ entries: [ENTRY] });
+ const { result } = renderHook(() => useBeeperOutbox(CONVERSATION_ID));
+
+ await act(async () => { await result.current.submit('hello there'); });
+ await act(async () => { await result.current.cancelConfirmation(); });
+
+ expect(result.current.confirmation).toBeNull();
+ expect(toastError).toHaveBeenCalled();
+ // The row is not fabricated as removed — it stays, reflecting the server.
+ 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));
+
+ 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(sendOutboxEntry).toHaveBeenCalledTimes(1);
+ });
+
+ it('refetches when a message.upserted invalidation lands on a send awaiting confirmation', async () => {
+ const { result } = renderHook(() => useBeeperOutbox(CONVERSATION_ID));
+ await act(async () => { await result.current.submit('hello there'); });
+ const before = listOutboxEntries.mock.calls.length;
+
+ listOutboxEntries.mockResolvedValue({ entries: [{ ...ENTRY, state: 'sent', messageId: 'msg-final-1' }] });
+ await act(async () => {
+ for (const handler of invalidateHandlers) handler?.({ kind: 'message.upserted', chatID: 'example-chat-1' });
+ });
+
+ expect(listOutboxEntries.mock.calls.length).toBeGreaterThan(before);
+ await waitFor(() => expect(result.current.entries[0].state).toBe('sent'));
+ });
+
+ // PR #60 blocker 1: `assertBreakerClosed()` runs before the row is claimed,
+ // so a 429 `OUTBOX_BREAKER_OPEN` leaves the row `approved` by design (#36)
+ // — the same shape as the first-contact refusal, but with no `confirmation`
+ // to hang a Cancel off. The row must stay `approved` and visible (never
+ // fabricated as failed) so `retry()`/`dismiss()` have something to act on.
+ it('leaves a breaker-refused row `approved` rather than `failed`, ready to retry or dismiss', async () => {
+ sendOutboxEntry.mockRejectedValueOnce(new ApiError(
+ 'Beeper sending is blocked by the runaway breaker',
+ 'OUTBOX_BREAKER_OPEN',
+ ));
+ listOutboxEntries.mockResolvedValue({ entries: [ENTRY] });
+ const { result } = renderHook(() => useBeeperOutbox(CONVERSATION_ID));
+
+ await act(async () => { await result.current.submit('hello there'); });
+
+ expect(toastError).toHaveBeenCalled();
+ await waitFor(() => expect(result.current.entries).toHaveLength(1));
+ expect(result.current.entries[0].state).toBe('approved');
+ expect(result.current.confirmation).toBeNull();
+ });
+
+ // `retry()` is the one exception to "nothing here ever retries in place":
+ // legal only because a still-`approved` row never reached `sendMessage`, so
+ // re-dispatching it is exactly as safe as sending it the first time. It
+ // must NOT compose a new row — that would manufacture a second phantom on
+ // every click while the breaker stays tripped, the exact failure the
+ // reviewer flagged.
+ it('retries a stalled approved row in place, without composing a new one', async () => {
+ sendOutboxEntry.mockRejectedValueOnce(new ApiError(
+ 'Beeper sending is blocked by the runaway breaker',
+ 'OUTBOX_BREAKER_OPEN',
+ ));
+ listOutboxEntries.mockResolvedValue({ entries: [ENTRY] });
+ const { result } = renderHook(() => useBeeperOutbox(CONVERSATION_ID));
+ await act(async () => { await result.current.submit('hello there'); });
+ await waitFor(() => expect(result.current.entries[0].state).toBe('approved'));
+
+ sendOutboxEntry.mockResolvedValueOnce({ ...ENTRY, state: 'awaiting-confirmation' });
+ await act(async () => { await result.current.retry(result.current.entries[0]); });
+
+ expect(createOutboxEntry).toHaveBeenCalledTimes(1);
+ expect(sendOutboxEntry).toHaveBeenCalledTimes(2);
+ expect(sendOutboxEntry).toHaveBeenLastCalledWith('outbox-1', { confirmFirstContact: false }, { silent: true });
+ expect(result.current.entries).toHaveLength(1);
+ expect(result.current.entries[0].state).toBe('awaiting-confirmation');
+ });
+
+ // `dismiss()` is the general form of Cancel: giving up on a stalled
+ // `approved` row that is not part of any pending first-contact question.
+ it('dismisses a stalled approved row on request, discarding it server-side', async () => {
+ sendOutboxEntry.mockRejectedValueOnce(new ApiError(
+ 'Beeper sending is blocked by the runaway breaker',
+ 'OUTBOX_BREAKER_OPEN',
+ ));
+ listOutboxEntries.mockResolvedValue({ entries: [ENTRY] });
+ const { result } = renderHook(() => useBeeperOutbox(CONVERSATION_ID));
+ await act(async () => { await result.current.submit('hello there'); });
+ await waitFor(() => expect(result.current.entries[0].state).toBe('approved'));
+
+ await act(async () => { await result.current.dismiss(result.current.entries[0]); });
+
+ expect(discardOutboxEntry).toHaveBeenCalledWith('outbox-1', { silent: true });
+ expect(result.current.entries).toHaveLength(0);
+ });
+
+ // `onSent` exists for exactly one purpose: clearing the composer. A send
+ // whose text did NOT come from the composer must not fire it, or a message
+ // typed while a failed row sat above it is thrown away unsent — the
+ // composer clears through `setDraft('')`, which also drops the persisted
+ // draft.
+ it('only clears the draft for the composer\'s own send, not a failed row\'s retry', async () => {
+ const onSent = vi.fn();
+ const { result } = renderHook(() => useBeeperOutbox(CONVERSATION_ID, { onSent }));
+
+ await act(async () => { await result.current.submit('older text', { clearsDraft: false }); });
+ expect(sendOutboxEntry).toHaveBeenCalledTimes(1);
+ expect(onSent).not.toHaveBeenCalled();
+
+ await act(async () => { await result.current.submit('freshly typed'); });
+ expect(onSent).toHaveBeenCalledTimes(1);
+ });
+
+ // The same rule has to survive the first-contact question: the origin rides
+ // on the confirmation, so answering "Send anyway" for a failed row's retry
+ // still leaves the composer alone.
+ it('carries the no-clear origin through a first-contact confirmation', async () => {
+ sendOutboxEntry.mockRejectedValueOnce(new ApiError(
+ 'This is the first message PortOS has ever sent to this conversation',
+ 'FIRST_CONTACT_CONFIRMATION_REQUIRED',
+ ));
+ const onSent = vi.fn();
+ const { result } = renderHook(() => useBeeperOutbox(CONVERSATION_ID, { onSent }));
+
+ await act(async () => { await result.current.submit('older text', { clearsDraft: false }); });
+ await act(async () => { await result.current.confirmAndSend(); });
+
+ expect(sendOutboxEntry).toHaveBeenLastCalledWith('outbox-1', { confirmFirstContact: true }, { silent: true });
+ expect(onSent).not.toHaveBeenCalled();
+ });
+ });
diff --cc client/src/hooks/useInstanceFeatures.js
index 186a68fbfc,8f2aa459f1..b9a52fde99
--- a/client/src/hooks/useInstanceFeatures.js
+++ b/client/src/hooks/useInstanceFeatures.js
@@@ -2,75 -2,65 +2,87 @@@ import { useCallback, useSyncExternalSt
import { INSTANCE_FEATURES_CHANGED } from '../constants/events.js';
import * as api from '../services/api';
-// Shared read of Settings > Features (`GET /api/settings/features`), with one
-// module-level cache so the sidebar, the ⌘K palette, and the Features tab
-// collapse to a single fetch per page load.
-//
-// Change notification rides the EXISTING `INSTANCE_FEATURES_CHANGED` window
-// event rather than a second broadcast channel — the engagement-reminder toast
-// already publishes on it and three dashboard widgets already listen, so a
-// private subscriber list here would have left those halves able to drift.
-// A publisher that already holds the server's fresh list passes it as
-// `detail.features` to skip the refetch; the `{ featureId, enabled }` shape the
-// existing publisher sends still works and simply triggers one.
-//
-// `null` features means NOT LOADED — deliberately distinct from `[]`, which
-// means loaded and this version registers no optional features.
-let cached = null;
+// One snapshot and event bridge for every mounted consumer. `null` means not
+// loaded (or failed), while [] is a successfully loaded empty feature list.
- const INITIAL_STATE = { features: null, error: null };
++const INITIAL_STATE = { features: null, groups: null, error: null };
+let snapshot = INITIAL_STATE;
let inFlight = null;
-let inFlightGeneration = null;
-// Bumped whenever something newer than an outstanding request lands (a toggle
-// publishing the server's fresh list, or an invalidation). A response that read
-// the OLD state must not overwrite it just because it resolved later — without
-// this, saving a JIRA instance while the initial fetch is still in flight leaves
-// the sidebar and ⌘K showing the pre-save answer until a reload.
let generation = 0;
+const subscribers = new Set();
+
+const getSnapshot = () => snapshot;
+const commitSnapshot = (result) => {
+ snapshot = result;
+ subscribers.forEach((notify) => notify());
+};
const loadInstanceFeatures = () => {
- if (!inFlight || inFlightGeneration !== generation) {
+ if (!inFlight) {
const requested = generation;
const request = api.getInstanceFeatures({ silent: true })
- .then((data) => ({ features: Array.isArray(data?.features) ? data.features : [], error: null }))
+ .then((data) => ({
+ features: Array.isArray(data?.features) ? data.features : [],
+ // Feature GROUPS (#40) — Settings > Features is the only consumer that
+ // reads this; the sidebar, ⌘K, and voice keep reading `features[].enabled`
+ // exactly as before, since a grouped feature's `enabled` already carries
+ // its group's effect.
+ groups: Array.isArray(data?.groups) ? data.groups : [],
+ error: null,
+ }))
.catch((error) => {
- // Fail OPEN: an unreadable feature list must not blank out navigation.
console.warn(`⚠️ instance features fetch failed: ${error?.message || error}`);
- return { features: null, error };
+ return { features: null, groups: null, error };
})
.then((result) => {
- if (inFlight === request) {
- inFlight = null;
- inFlightGeneration = null;
- }
- // Superseded while in flight — hand the caller what IS current instead
- // of the answer it asked for, so no consumer renders the stale one.
- if (requested !== generation) return cached || result;
- cached = result;
- return result;
+ if (inFlight === request) inFlight = null;
+ // A superseded request never publishes, even while its replacement is
+ // pending. Subscribers receive only the current generation's result.
+ if (requested === generation) commitSnapshot(result);
});
inFlight = request;
- inFlightGeneration = requested;
}
return inFlight;
};
+const onFeaturesChanged = (event) => {
+ generation += 1;
+ inFlight = null;
+ const features = event?.detail?.features;
+ if (Array.isArray(features)) {
- commitSnapshot({ features, error: null });
++ commitSnapshot({
++ features,
++ groups: Array.isArray(event?.detail?.groups) ? event.detail.groups : snapshot.groups,
++ error: null,
++ });
+ } else {
+ loadInstanceFeatures();
+ }
+};
+
+const subscribe = (notify) => {
+ if (subscribers.size === 0) {
+ window.addEventListener(INSTANCE_FEATURES_CHANGED, onFeaturesChanged);
+ }
+ subscribers.add(notify);
+ if (snapshot === INITIAL_STATE) loadInstanceFeatures();
+ return () => {
+ subscribers.delete(notify);
+ if (subscribers.size === 0) {
+ window.removeEventListener(INSTANCE_FEATURES_CHANGED, onFeaturesChanged);
+ }
+ };
+};
+
+const reload = () => {
+ generation += 1;
+ const requested = generation;
+ inFlight = null;
+ return loadInstanceFeatures().then(() => {
+ // Preserve the public success announcement for non-hook event listeners.
- if (requested === generation && snapshot.features) publishInstanceFeatures(snapshot.features);
++ if (requested === generation && snapshot.features) publishInstanceFeatures(snapshot.features, { groups: snapshot.groups });
+ });
+};
+
/**
* @returns {{
* features: Array|null, // null while loading or after a failed fetch
@@@ -84,9 -75,45 +97,13 @@@
* (an unknown gate must never erase a page)
* - loading → false, so a gated row appears once rather than flashing away
* - errored → true, so a server hiccup shows everything instead of hiding it
+ *
+ * `groups` is consumed by the Settings > Features tab only — every other
+ * consumer (sidebar, ⌘K, voice) keeps reading `features[].enabled`, which
+ * already carries a grouped feature's effective (group-aware) state.
*/
export function useInstanceFeatures() {
- const { features, error } = useSyncExternalStore(subscribe, getSnapshot);
- const [state, setState] = useState(() => cached || { features: null, groups: null, error: null });
-
- useEffect(() => {
- let active = true;
- const sync = (result) => { if (active) setState(result); };
-
- if (cached) sync(cached); else loadInstanceFeatures().then(sync);
-
- const onFeaturesChanged = (event) => {
- const features = event?.detail?.features;
- const groups = event?.detail?.groups;
- // A publisher that doesn't know about groups (e.g. a caller only
- // announcing a `featureId`/`enabled` pair) must not wipe the groups this
- // hook already knows — keep the previous value rather than resetting it.
- const previousGroups = cached?.groups ?? null;
- generation += 1;
- if (Array.isArray(features)) {
- cached = { features, groups: Array.isArray(groups) ? groups : previousGroups, error: null };
- sync(cached);
- return;
- }
- cached = null;
- loadInstanceFeatures().then(sync);
- };
-
- window.addEventListener(INSTANCE_FEATURES_CHANGED, onFeaturesChanged);
- return () => {
- active = false;
- window.removeEventListener(INSTANCE_FEATURES_CHANGED, onFeaturesChanged);
- };
- }, []);
-
- const { features, groups, error } = state;
++ const { features, groups, error } = useSyncExternalStore(subscribe, getSnapshot);
const isFeatureEnabled = useCallback((featureId) => {
if (!featureId) return true;
@@@ -96,7 -123,19 +113,7 @@@
return feature ? feature.enabled !== false : true;
}, [features, error]);
- return { features, error, isFeatureEnabled, reload };
- // Announced rather than applied locally: after a failed first fetch every
- // consumer is sitting in the fail-open error state, and a retry that updated
- // only the Settings tab would leave the sidebar and ⌘K stale until a reload.
- const reload = useCallback(() => {
- generation += 1;
- cached = null;
- return loadInstanceFeatures().then((result) => {
- if (result.features) publishInstanceFeatures(result.features, { groups: result.groups });
- else setState(result);
- });
- }, []);
-
+ return { features, groups, error, isFeatureEnabled, reload };
}
/**
diff --cc server/lib/importScoping.test.js
index 4c785c45db,2f66b2046a..4094521a46
--- a/server/lib/importScoping.test.js
+++ b/server/lib/importScoping.test.js
@@@ -298,18 -293,26 +298,23 @@@ describe('deferred imports stay deferre
// already in every one of them). A leaf with nothing behind it to defer is the
// tolerated shape. The allowance had drifted to ~30 again, so restore the ~1.5k.
//
-// The Beeper fork carries its own suites, so this budget is above upstream's.
-// Measured on the merge of upstream v2.60.0: 99,024 against upstream's own
-// 97,070 at the same commit, +1,954. Two parts, both the tolerated shape and
-// neither an eager edge into a heavy subtree. 1,030 is 21 test files upstream
-// does not have, whose mean closure (49) is BELOW the tree's (58) — mass, not
-// depth. The other 924 is diffuse: +19 on routes/settings.test.js and +2/+3
-// across ~300 suites, from dependency-free leaves reached through
-// `validation.js`'s flat re-export of `mediaValidation.js`. The largest of
-// them, `beeperOAuthOrigin.js`, has a closure of exactly 1 and imports
-// nothing, and it is read inside a synchronous zod refine — there is no
-// subtree to narrow and no call site to defer to. So restore the ~1.5k
-// allowance over the measured total rather than pretend the delta is free.
-//
-// Re-measured after rebuilding this branch as three layered commits on top
-// of a newer upstream/main (9 commits past the previous base, none of them
-// touching a heavy subtree): 99,168, essentially flat against the 99,024
-// measured above at the older v2.60.0 merge point (+144 — ordinary drift
-// from upstream's own intervening growth, not a new eager edge this branch
-// introduced). Restore the same ~1.5k allowance over that fresh total.
-const MAX_STATIC_INSTANTIATIONS = 100668;
+// #6617 is that shape once more: collapsing `runAgentSpawn`'s eight hand-copied
+// block-and-bail epilogues into one helper meant lifting the steps they were
+// tangled with out of the orchestrator — `lib/publicReviewSpawnGate.js`,
+// `lib/agentRegistrationRecord.js`, `lib/taskGenerationOverrides.js` and
+// `services/publicReviewSpawnInput.js`. Measured 98,642 (+142 over main's
+// 98,500): four modules appearing as +1 each in the closures that already
+// reached `agentLifecycle.js`, pulling in nothing those closures lacked. The
+// one edge that WOULD have been new — `agentRegistrationRecord.js` reaching
+// `normalizeReviewers` through the 123-module `validation.js` catch-all — is
+// narrowed to its declaring leaf, `reviewerConfig.js`, so it contributes
+// nothing. Restore the ~1.5k allowance.
- const MAX_STATIC_INSTANTIATIONS = 100000;
++// Beeper adds 22 server suites (1,045 instantiations) and 933 instantiations
++// across existing suites, primarily dependency-free validation/attachment
++// leaves. Measured against current main: 99,794 -> 101,772. No new heavy eager
++// subtree is introduced; retain the standard roughly 1,500 allowance.
++const MAX_STATIC_INSTANTIATIONS = 103272;
++
const SKIP_DIRS = new Set(['node_modules', 'coverage', 'dist', 'data']);
const serverTestFiles = (dir = SERVER_DIR, out = []) => {
diff --cc server/routes/settings.js
index bca8de3f66,0c57ad3a1e..157166e67d
--- a/server/routes/settings.js
+++ b/server/routes/settings.js
@@@ -241,7 -240,46 +260,46 @@@ router.post('/features/eidoverse/host'
res.json(await ensureEidoverseHost());
}));
+ // The Beeper sweep scheduler and its realtime transport arm on the instance
+ // feature plus a stored token, and that gate used to be read at boot only — so
+ // turning the feature on left realtime down and no sweep registered until the
+ // next restart (fork issue #1, final live pass). Reconciling here closes that
+ // half; the credential paths close the other. Beeper sits in the `comms` group,
+ // so the group toggle moves the same gate — and so does the general settings
+ // PUT below, when it flips the user's own `settings.beeper.enabled` sync
+ // toggle: that save used to persist silently and never reach
+ // `startBeeperScheduler()` until a restart.
+ //
+ // Imported lazily inside the handler: a feature toggle is a rare path, and the
+ // arming module reaches the whole Beeper service graph (`ws` included), which
+ // has no business loading with every settings request.
+ const BEEPER_FEATURE_GROUP = 'comms';
-async function reconcileBeeperArming(reason) {
++async function reconcileBeeperArming(reason, options = {}) {
+ const { reconcileBeeperIngestion } = await import('../services/beeperArming.js');
+ // The flag is already persisted, so a reconcile failure must not turn a saved
+ // toggle into a 500.
- await reconcileBeeperIngestion({ reason })
++ await reconcileBeeperIngestion({ reason, ...options })
+ .catch((err) => console.error(`❌ Beeper ingestion reconcile (${reason}) failed: ${err.message}`));
+ }
+
+ // An interval-only Beeper save (no `enabled` flip) used to take effect only
+ // at the next process restart: the registered event's `intervalMs` is read
+ // once, at `schedule()` time (`createSettingsGatedSyncScheduler.js`), and
+ // `startBeeperScheduler()` deliberately no-ops once `beeper-sync` is already
+ // registered (fork issue #79). `restartBeeperScheduler()` is the fix — cancel
+ // and register fresh, which reads `getBeeperSyncConfig()` again and picks up
+ // whatever interval was just persisted. Lazily imported for the same reason
+ // `reconcileBeeperArming` above is: this is a rare save, and the scheduler
+ // module reaches the whole Beeper service graph.
+ async function restartBeeperSchedulerForIntervalChange(reason) {
+ const { restartBeeperScheduler } = await import('../services/beeperScheduler.js');
+ await restartBeeperScheduler()
+ .catch((err) => console.error(`❌ Beeper scheduler restart (${reason}) failed: ${err.message}`));
+ }
+
// PUT /api/settings/features/:featureId
+ // `enabled` is nullable: null clears a grouped feature's override back to
+ // "inherit" (see instanceFeatureUpdateSchema and updateInstanceFeature).
router.put('/features/:featureId', asyncHandler(async (req, res) => {
const featureId = validateRequest(instanceFeatureIdSchema, req.params.featureId);
const { enabled } = validateRequest(instanceFeatureUpdateSchema, req.body || {});
@@@ -486,11 -554,54 +574,63 @@@ router.put('/', asyncHandler(async (req
// `actor: 'user'` is what separates a save made HERE — a human on the Settings
// page — from every other `save()` caller (schedulers, sync hooks, feature
// writes), which keep the `'system'` default in the operator-action ledger (#5594).
- let merged = await updateSettingsWith((current) =>
- preserveExternallyOwnedKeys(
+ let previousBeeperEnabled;
+ let previousBeeperIntervalMinutes;
++ let previousBeeperConnection;
++ let previousBeeperGates;
+ let merged = await updateSettingsWith((current) => {
+ // Read inside the queue, against the freshest persisted snapshot (same
+ // reasoning as `mergeFederationSlice` above) — a stale pre-image here could
+ // read a no-op as a flip, or a real flip as a no-op.
+ previousBeeperEnabled = current?.beeper?.enabled === true;
+ previousBeeperIntervalMinutes = current?.beeper?.intervalMinutes;
++ previousBeeperConnection = JSON.stringify([current?.beeper?.baseUrl, current?.beeper?.allowNonLoopbackBaseUrl]);
++ previousBeeperGates = JSON.stringify([current?.instanceFeatures?.beeper, current?.instanceFeatureGroups?.comms]);
+ return preserveExternallyOwnedKeys(
mergeFederationSlice({ ...current, ...settingsPatch }, current),
current,
- ), { actor: 'user' });
+ );
+ }, { actor: 'user' });
+ // A beeper save that flips `enabled` never armed the scheduler until a
+ // restart. `startBeeperScheduler()` is the only thing that registers the
+ // sweep, and it's reached exclusively through `reconcileBeeperArming` —
+ // which the feature and comms-group toggles call, but this generic PUT path
+ // never did. `undefined` counts as `false` on both sides, matching how
+ // `getBeeperSyncConfig()` reads the stored flag, so an install that has
+ // never touched the Beeper card doesn't read as a flip. Fires AFTER the
+ // write above so the reconcile (and the scheduler's own re-read) see the
+ // value that was actually persisted, not the request body.
+ const nextBeeperEnabled = merged?.beeper?.enabled === true;
+ const beeperIntervalChanged = merged?.beeper?.intervalMinutes !== previousBeeperIntervalMinutes;
+ if (nextBeeperEnabled !== previousBeeperEnabled) {
+ // Fork issue #94: the flip branch does NOT always get a fresh
+ // registration. `reconcileBeeperArming` only registers the scheduler when
+ // it is not already registered (fork issue #79's re-registration guard in
+ // beeperArming.js), and a true→false save deliberately leaves the
+ // scheduler registered — it just gates per tick (see the true→false test
+ // beside this route's other Beeper tests) — so a false→true flip right
+ // after finds it already registered and the reconcile below is a no-op
+ // for the scheduler. Capture that "already registered" state BEFORE
+ // reconciling: if this save also changed the interval, the still-
+ // registered event is holding the stale `intervalMs`
+ // `createSettingsGatedSyncScheduler.js` locked in at `schedule()` time, so
+ // restart explicitly to pick up what was just persisted.
+ const { isBeeperSchedulerRegistered } = await import('../services/beeperScheduler.js');
+ const wasSchedulerRegisteredBeforeReconcile = isBeeperSchedulerRegistered();
+ await reconcileBeeperArming('sync-toggle');
+ if (nextBeeperEnabled && beeperIntervalChanged && wasSchedulerRegisteredBeforeReconcile) {
+ await restartBeeperSchedulerForIntervalChange('sync-toggle-interval-change');
+ }
+ } else if (beeperIntervalChanged) {
+ // Fork issue #79: an interval-only change (no `enabled` flip) still has to
+ // take effect without a restart.
+ await restartBeeperSchedulerForIntervalChange('interval-change');
+ }
++ const beeperConnectionChanged = JSON.stringify([merged?.beeper?.baseUrl, merged?.beeper?.allowNonLoopbackBaseUrl]) !== previousBeeperConnection;
++ const beeperGatesChanged = JSON.stringify([merged?.instanceFeatures?.beeper, merged?.instanceFeatureGroups?.comms]) !== previousBeeperGates;
++ if (beeperConnectionChanged || beeperGatesChanged) {
++ await reconcileBeeperArming('connection-settings', { restartSocket: beeperConnectionChanged });
++ }
if (subscriptionCostsPatch !== undefined) {
const costs = await saveSubscriptionCosts(subscriptionCostsPatch, { actor: 'user' });
merged = { ...merged, subscriptionCosts: costs };
diff --cc server/routes/settings.test.js
index 400c5fe826,cc7032dfba..148480a10f
--- a/server/routes/settings.test.js
+++ b/server/routes/settings.test.js
@@@ -685,6 -828,244 +828,263 @@@ describe('Settings routes — videoGen
});
});
+ describe('Settings routes — beeper slice (#30)', () => {
+ beforeEach(() => {
+ store = {};
+ vi.clearAllMocks();
+ });
+
+ it('accepts a valid beeper slice and persists it', async () => {
+ const res = await request(buildApp())
+ .put('/api/settings')
+ .send({ beeper: { enabled: true, intervalMinutes: 10, baseUrl: 'http://127.0.0.1:23373', attachmentBudgetGb: 5 } });
+ expect(res.status).toBe(200);
+ expect(res.body.beeper).toEqual({ enabled: true, intervalMinutes: 10, baseUrl: 'http://127.0.0.1:23373', attachmentBudgetGb: 5 });
+ });
+
+ it('rejects a non-boolean enabled gate', async () => {
+ const res = await request(buildApp())
+ .put('/api/settings')
+ .send({ beeper: { enabled: 'yes' } });
+ expect(res.status).toBe(400);
+ });
+
+ it('rejects an out-of-range interval', async () => {
+ const res = await request(buildApp())
+ .put('/api/settings')
+ .send({ beeper: { intervalMinutes: 0 } });
+ expect(res.status).toBe(400);
+ });
+
+ // The security-load-bearing case (#30/#31): this slice must never add a
+ // plaintext write path for the token, and `.strict()` is what enforces it —
+ // a client attempting to smuggle one through the generic settings route
+ // gets a 400, not a silent write to disk.
+ it('rejects a beeper patch that carries a token — no plaintext write path through this route', async () => {
+ const res = await request(buildApp())
+ .put('/api/settings')
+ .send({ beeper: { enabled: true, token: 'smuggled-token' } });
+ expect(res.status).toBe(400);
+ });
+
+ it('never echoes a stored beeper token back on GET /api/settings', async () => {
+ store = { beeper: { enabled: true, token: 'super-secret-token' } };
+ const res = await request(buildApp()).get('/api/settings');
+ expect(res.status).toBe(200);
+ expect(res.body.beeper.token).toBeUndefined();
+ expect(JSON.stringify(res.body)).not.toMatch(/super-secret-token/);
+ });
+
+ // Without this, the generic top-level shallow merge would REPLACE
+ // current.beeper wholesale and silently wipe out a token stored by another
+ // write path (#31's vault, or a hand-edited settings.json) the instant the
+ // user saves an unrelated field like `enabled` from this slice's settings
+ // card — same posture as imageGen.hfToken / civitai.apiKey above. The
+ // ordinary ingestion-config fields (baseUrl, intervalMinutes,
+ // attachmentBudgetGb) follow the existing iMessage/Signal convention
+ // instead: the settings card always PUTs its complete known slice, so
+ // there's no separate "don't drop this on a partial patch" guard for them.
+ it('preserves a stored token across a beeper patch that only touches other fields', async () => {
+ store = { beeper: { enabled: false, token: 'existing-token' } };
+ const res = await request(buildApp())
+ .put('/api/settings')
+ .send({ beeper: { enabled: true } });
+ expect(res.status).toBe(200);
+ // The response itself redacts the token (see the GET test above); assert
+ // against the mocked store, which reflects what was actually persisted.
+ expect(store.beeper).toEqual({ enabled: true, token: 'existing-token' });
+ });
+ });
+
+ // The general settings PUT persists `settings.beeper.enabled` but, unlike the
+ // feature and comms-group toggles above, used to never reconcile arming — so a
+ // save made right after connecting (enabled still false at that point) left
+ // the sweep unregistered until the next restart. These pin the fix: reconcile
+ // only fires when the effective (boolean-coerced) value actually changes.
+ describe('Settings routes — beeper sync-toggle arming', () => {
+ beforeEach(() => {
+ store = {};
+ vi.clearAllMocks();
+ });
+
++ it('reconnects after a saved endpoint change without requiring a sync-toggle change', async () => {
++ store = { beeper: { enabled: true, intervalMinutes: 5, baseUrl: 'http://127.0.0.1:23373' } };
++ const res = await request(buildApp()).put('/api/settings').send({
++ beeper: { ...store.beeper, baseUrl: 'http://127.0.0.1:23374' },
++ });
++ expect(res.status).toBe(200);
++ expect(reconcileBeeperIngestion).toHaveBeenCalledWith({ reason: 'connection-settings', restartSocket: true });
++ expect(updateSettingsWith.mock.invocationCallOrder[0]).toBeLessThan(reconcileBeeperIngestion.mock.invocationCallOrder[0]);
++ });
++
++ it('reconciles a group gate changed through the general settings route', async () => {
++ store = { instanceFeatureGroups: { comms: { enabled: true } } };
++ const res = await request(buildApp()).put('/api/settings').send({
++ instanceFeatureGroups: { comms: { enabled: false } },
++ });
++ expect(res.status).toBe(200);
++ expect(reconcileBeeperIngestion).toHaveBeenCalledWith({ reason: 'connection-settings', restartSocket: false });
++ });
++
+ it('reconciles once, after the settings are persisted, when enabled flips false→true', async () => {
+ store = { beeper: { enabled: false, intervalMinutes: 5 } };
+
+ const res = await request(buildApp())
+ .put('/api/settings')
+ .send({ beeper: { enabled: true, intervalMinutes: 5 } });
+
+ expect(res.status).toBe(200);
+ expect(reconcileBeeperIngestion).toHaveBeenCalledTimes(1);
+ expect(reconcileBeeperIngestion).toHaveBeenCalledWith({ reason: 'sync-toggle' });
+ // Ordering: the write must land before the reconcile fires, so the
+ // scheduler's own settings re-read (and the reconcile itself) see the
+ // value that was actually persisted, not the request body.
+ const [writeOrder] = updateSettingsWith.mock.invocationCallOrder;
+ const [reconcileOrder] = reconcileBeeperIngestion.mock.invocationCallOrder;
+ expect(writeOrder).toBeLessThan(reconcileOrder);
+ });
+
+ // Registering the scheduler is `reconcileBeeperArming`'s job; stopping it on
+ // a true→false flip is not — `reconcileBeeperIngestion` only disarms on the
+ // feature+token gate, not on this opt-in (see beeperArming.js), so it is the
+ // scheduler's own per-tick `getBeeperSyncConfig()` re-read that actually
+ // stops runs here. This still calls reconcile, for symmetry and so the
+ // transition is logged/serialized on the same tail as every other trigger.
+ it('reconciles once when enabled flips true→false', async () => {
+ store = { beeper: { enabled: true, intervalMinutes: 5 } };
+
+ const res = await request(buildApp())
+ .put('/api/settings')
+ .send({ beeper: { enabled: false, intervalMinutes: 5 } });
+
+ expect(res.status).toBe(200);
+ expect(reconcileBeeperIngestion).toHaveBeenCalledTimes(1);
+ expect(reconcileBeeperIngestion).toHaveBeenCalledWith({ reason: 'sync-toggle' });
+ });
+
+ it('does not reconcile arming when a save leaves enabled unchanged (interval-only)', async () => {
+ store = { beeper: { enabled: true, intervalMinutes: 5 } };
+
+ const res = await request(buildApp())
+ .put('/api/settings')
+ .send({ beeper: { enabled: true, intervalMinutes: 15 } });
+
+ expect(res.status).toBe(200);
+ expect(reconcileBeeperIngestion).not.toHaveBeenCalled();
+ });
+
+ it('does not fail the PUT when the reconcile rejects', async () => {
+ reconcileBeeperIngestion.mockRejectedValueOnce(new Error('boom'));
+ store = { beeper: { enabled: false, intervalMinutes: 5 } };
+
+ const res = await request(buildApp())
+ .put('/api/settings')
+ .send({ beeper: { enabled: true, intervalMinutes: 5 } });
+
+ expect(res.status).toBe(200);
+ expect(res.body.beeper.enabled).toBe(true);
+ });
+
+ // Fork issue #94: a true→false save leaves the scheduler registered (see
+ // "reconciles once when enabled flips true→false" above) — it just gates
+ // per tick — so a false→true flip right after finds
+ // `isBeeperSchedulerRegistered()` already true and the reconcile is a no-op
+ // for the scheduler. When this save also changes the interval, the still-
+ // registered event is holding the stale `intervalMs`, so the route has to
+ // restart the scheduler explicitly, after reconciling, to pick up what was
+ // just persisted.
+ it('restarts the scheduler, after reconciling, when enabled flips and the interval changes on an already-registered scheduler', async () => {
+ isBeeperSchedulerRegistered.mockReturnValueOnce(true);
+ store = { beeper: { enabled: false, intervalMinutes: 5 } };
+
+ const res = await request(buildApp())
+ .put('/api/settings')
+ .send({ beeper: { enabled: true, intervalMinutes: 15 } });
+
+ expect(res.status).toBe(200);
+ expect(reconcileBeeperIngestion).toHaveBeenCalledTimes(1);
+ expect(restartBeeperScheduler).toHaveBeenCalledTimes(1);
+ const [reconcileOrder] = reconcileBeeperIngestion.mock.invocationCallOrder;
+ const [restartOrder] = restartBeeperScheduler.mock.invocationCallOrder;
+ expect(reconcileOrder).toBeLessThan(restartOrder);
+ });
+ });
+
+ // Fork issue #79's other half: an interval-only save (no `enabled` flip) used
+ // to take effect only at the next process restart, because the registered
+ // event's `intervalMs` is locked in at `schedule()` time and
+ // `startBeeperScheduler()` deliberately no-ops once `beeper-sync` is already
+ // registered. `restartBeeperScheduler()` (cancel, then register fresh) is the
+ // fix; this describe block pins WHEN the route calls it, not what it does —
+ // that lives in services/beeperScheduler.test.js.
+ describe('Settings routes — beeper interval change', () => {
+ beforeEach(() => {
+ store = {};
+ vi.clearAllMocks();
+ });
+
+ it('restarts the scheduler, after the settings are persisted, when only the interval changes', async () => {
+ store = { beeper: { enabled: true, intervalMinutes: 5 } };
+
+ const res = await request(buildApp())
+ .put('/api/settings')
+ .send({ beeper: { enabled: true, intervalMinutes: 15 } });
+
+ expect(res.status).toBe(200);
+ expect(restartBeeperScheduler).toHaveBeenCalledTimes(1);
+ expect(reconcileBeeperIngestion).not.toHaveBeenCalled();
+ // Same ordering requirement as the arming reconcile: the restart has to
+ // read the interval AFTER it lands on disk, or a fast save/restart race
+ // could re-register against the value that was about to be overwritten.
+ const [writeOrder] = updateSettingsWith.mock.invocationCallOrder;
+ const [restartOrder] = restartBeeperScheduler.mock.invocationCallOrder;
+ expect(writeOrder).toBeLessThan(restartOrder);
+ });
+
+ it('does not restart the scheduler when the interval is unchanged', async () => {
+ store = { beeper: { enabled: true, intervalMinutes: 5 } };
+
+ const res = await request(buildApp())
+ .put('/api/settings')
+ .send({ beeper: { enabled: true, intervalMinutes: 5 } });
+
+ expect(res.status).toBe(200);
+ expect(restartBeeperScheduler).not.toHaveBeenCalled();
+ });
+
+ // With the scheduler not yet registered (`isBeeperSchedulerRegistered()`
+ // defaults to `false` in this file's mock — a fresh install / first
+ // enable), the `enabled`-flip branch's reconcile does the fresh
+ // registration itself and picks up the just-persisted interval, so
+ // restarting the scheduler too would just cancel and re-register a second
+ // time for nothing. When the scheduler IS already registered going in, the
+ // route restarts it explicitly — see the "already-registered scheduler"
+ // test under "beeper sync-toggle arming" above (fork issue #94).
+ it('does not also restart the scheduler when enabled flips, even if the interval changed in the same save', async () => {
+ store = { beeper: { enabled: false, intervalMinutes: 5 } };
+
+ const res = await request(buildApp())
+ .put('/api/settings')
+ .send({ beeper: { enabled: true, intervalMinutes: 15 } });
+
+ expect(res.status).toBe(200);
+ expect(reconcileBeeperIngestion).toHaveBeenCalledTimes(1);
+ expect(restartBeeperScheduler).not.toHaveBeenCalled();
+ });
+
+ it('does not fail the PUT when the scheduler restart rejects', async () => {
+ restartBeeperScheduler.mockRejectedValueOnce(new Error('boom'));
+ store = { beeper: { enabled: true, intervalMinutes: 5 } };
+
+ const res = await request(buildApp())
+ .put('/api/settings')
+ .send({ beeper: { enabled: true, intervalMinutes: 20 } });
+
+ expect(res.status).toBe(200);
+ expect(res.body.beeper.intervalMinutes).toBe(20);
+ });
+ });
+
describe('Settings routes — credential inventory', () => {
it('returns presence and source without secret values', async () => {
const { getCredentialInventory } = await import('../services/credentialInventory.js');
diff --cc server/services/beeperArming.js
index 0000000000,85aa2bb41c..8c3170065e
mode 000000,100644..100644
--- a/server/services/beeperArming.js
+++ b/server/services/beeperArming.js
@@@ -1,0 -1,128 +1,131 @@@
+ /**
+ * Beeper ingestion arming — the one place that decides whether the sweep
+ * scheduler and the realtime transport should be live (fork issue #1, found on
+ * the final live pass).
+ *
+ * Both are gated on `isBeeperIngestionArmed()` — the instance FEATURE plus a
+ * vaulted token — and both used to be evaluated at boot and nowhere else. So on
+ * a live install, storing a credential or turning the feature on left realtime
+ * down (`reconnectAttempts: 0`) and no sweep registered until the next server
+ * restart; the mirror image was a `disconnect` that revoked the token while the
+ * WebSocket kept relaying on it.
+ *
+ * `reconcileBeeperIngestion()` closes both halves. It reads the gate and moves
+ * the two subsystems to match it, so every caller is the same one line:
+ *
+ * - after a credential is stored (OAuth callback, pasted token),
+ * - after the instance feature (or the Comms group that contains it) changes,
+ * - after a disconnect deletes the credential.
+ *
+ * It is IDEMPOTENT and safe to call repeatedly: `startBeeperSocket()` declines
+ * while the transport is already running, and the scheduler is only registered
+ * when `eventScheduler` does not already hold `beeper-sync` (re-registering
+ * would silently push the next sweep a full interval into the future every time
+ * a user touched an unrelated toggle).
+ *
+ * Calls are serialized on one tail so two overlapping triggers — a feature
+ * toggle landing while a connect is finishing — cannot interleave their
+ * gate-read and their start/stop and settle on the losing answer. That is the
+ * single-writer re-entrancy guard root AGENTS.md sanctions, not a defence
+ * against competing humans.
+ *
+ * Logging is transition-only, which keeps #32's "a fresh install narrates
+ * nothing it does not have" acceptance intact: reconciling an install with the
+ * feature off and no token stops nothing, starts nothing and says nothing.
+ *
+ * **Arming also kicks one sweep immediately (fork issue #79).** Before this,
+ * connecting Beeper (or flipping the feature or sync toggle on) registered the
+ * scheduler's interval timer but fired nothing until a full interval had
+ * elapsed — up to the configured cadence, several minutes on a default
+ * install, with an empty inbox the whole time. `reconcileOnce` below fires
+ * `runBeeperSweep({ reason: 'arm' })` — fire-and-forget, never awaited — the
+ * moment a reconcile is the one that newly registers the scheduler
+ * (`schedulerStarted`), never on a reconcile that finds it already
+ * registered. This is deliberately NOT routed through `eventScheduler`'s
+ * `triggerNow`: a direct call keeps the registered event's own `nextRunAt`
+ * exactly where `schedule()` set it (registration time + one interval), so
+ * the very next scheduled tick lands one full interval after the immediate
+ * kick rather than being pulled forward by it — "kicks one sweep immediately,
+ * THEN the interval," not "resets the interval." It shares `runBeeperSweep`'s
+ * own re-entrancy guard with the timer and the manual sync route, so it can
+ * never race a sweep already in flight.
+ */
+
+ import { isBeeperIngestionArmed, runBeeperSweep } from './beeperSync.js';
+ import { isBeeperSchedulerRegistered, startBeeperScheduler, stopBeeperScheduler } from './beeperScheduler.js';
+ import { isBeeperSocketRunning, startBeeperSocket, stopBeeperSocket } from './beeperSocket.js';
+
+ const LOG_PREFIX = '🫧 Beeper ingestion';
+
+ // Serializes overlapping reconciles. Rejections are absorbed here so one failed
+ // reconcile cannot poison every later one.
+ let tail = Promise.resolve();
+
+ /**
+ * Bring the sweep scheduler and the realtime transport into line with the
+ * current arming gate.
+ *
+ * @param {object} [options]
+ * @param {string} [options.reason] - What triggered this, for the log line.
+ * @returns {Promise<{armed: boolean, socketRunning: boolean, schedulerRegistered: boolean, changed: boolean}>}
+ */
-export function reconcileBeeperIngestion({ reason = 'unspecified' } = {}) {
- const run = () => reconcileOnce(reason);
++export function reconcileBeeperIngestion({ reason = 'unspecified', restartSocket = false } = {}) {
++ const run = () => reconcileOnce(reason, restartSocket);
+ const next = tail.then(run, run);
+ tail = next.then(() => {}, () => {});
+ return next;
+ }
+
-async function reconcileOnce(reason) {
++async function reconcileOnce(reason, restartSocket) {
+ // A gate that cannot be read (corrupt settings, unreadable vault) already
+ // resolves to `false` inside `isBeeperIngestionArmed`, which says so once and
+ // declines to arm — so there is no third answer to handle here.
+ if (!await isBeeperIngestionArmed()) return disarm(reason);
+
+ // The transport arms on the feature+token gate alone: it writes nothing, and
+ // the liveness dot it feeds is what the settings card shows while the user
+ // decides whether to enable ingestion. Returns false when already running.
++ // A connection setting or credential replacement must retire the old
++ // authenticated transport before starting one with the saved configuration.
++ if (restartSocket) stopBeeperSocket();
+ const socketStarted = await startBeeperSocket();
+
+ // The sweep carries the user's own `settings.beeper.enabled` opt-in on top of
+ // the gate; `startBeeperScheduler` owns that check, so a reconcile with the
+ // toggle off correctly registers nothing.
+ let schedulerStarted = false;
+ if (!isBeeperSchedulerRegistered()) {
+ await startBeeperScheduler();
+ schedulerStarted = isBeeperSchedulerRegistered();
+ }
+
+ // #79: a fresh registration on a LIVE trigger — never on boot, which calls
+ // `startBeeperScheduler()` directly and never reaches this reconcile at all
+ // — earns one immediate sweep. Wrapped in `Promise.resolve(...)` so a test
+ // double that returns `undefined` instead of a promise cannot throw on
+ // `.catch`, and never awaited: a sweep can run long, and `reconcileOnce`
+ // calls are serialized on `tail` above — blocking here would stall a fast
+ // toggle-off landing right behind this one.
+ if (schedulerStarted) {
+ Promise.resolve(runBeeperSweep({ reason: 'arm' })).catch((err) => {
+ console.error(`${LOG_PREFIX}: immediate sweep on arm failed: ${err.message}`);
+ });
+ }
+
+ const changed = socketStarted || schedulerStarted;
+ if (changed) console.log(`${LOG_PREFIX}: armed (${reason})`);
+ return {
+ armed: true,
+ socketRunning: isBeeperSocketRunning(),
+ schedulerRegistered: isBeeperSchedulerRegistered(),
+ changed,
+ };
+ }
+
+ function disarm(reason) {
+ const socketStopped = stopBeeperSocket();
+ const schedulerStopped = stopBeeperScheduler();
+ const changed = socketStopped || schedulerStopped;
+ if (changed) console.log(`${LOG_PREFIX}: disarmed (${reason})`);
+ return { armed: false, socketRunning: false, schedulerRegistered: false, changed };
+ }
diff --cc server/services/beeperArming.test.js
index 0000000000,1699e35372..45df252fd4
mode 000000,100644..100644
--- a/server/services/beeperArming.test.js
+++ b/server/services/beeperArming.test.js
@@@ -1,0 -1,291 +1,303 @@@
+ import {
+ describe, it, expect, vi, beforeEach, afterEach,
+ } from 'vitest';
+
+ // The regression this file exists for (fork issue #1, final live pass): the
+ // arming gate — instance feature plus a stored token — used to be read at boot
+ // and nowhere else, so connecting on a running install left realtime down and
+ // no sweep registered for as long as the process stayed up, and a disconnect
+ // left the relay running on a revoked token.
+ //
+ // The scheduler side runs for REAL here (real `eventScheduler`, real
+ // `beeperScheduler`) so "registered" is the scheduler's own answer rather than a
+ // mock's; only the socket is doubled, since it owns a `ws` connection.
+ const state = {
+ armed: true,
+ config: { enabled: true, intervalMinutes: 5 },
+ };
+
+ const socket = {
+ running: false,
+ starts: 0,
+ stops: 0,
+ // Both default to an immediate no-op so every existing test below observes
+ // exactly the old synchronous mock. The overlapping arm/disarm test further
+ // down replaces them for that one case, to force `startBeeperSocket()` to
+ // suspend at a known point instead of resolving on the same microtask tick.
+ gate: Promise.resolve(),
+ onStart: () => {},
+ };
+
+ vi.mock('./beeperSync.js', () => ({
+ isBeeperIngestionArmed: async () => state.armed,
+ getBeeperSyncConfig: async () => state.config,
+ runBeeperSweep: vi.fn(),
+ }));
+
+ vi.mock('./beeperSocket.js', () => ({
+ // Same contract as the real module: declines (false) when already running.
+ startBeeperSocket: async () => {
+ socket.starts += 1;
+ socket.onStart();
+ await socket.gate;
+ if (socket.running) return false;
+ socket.running = true;
+ return true;
+ },
+ stopBeeperSocket: () => {
+ socket.stops += 1;
+ const wasRunning = socket.running;
+ socket.running = false;
+ return wasRunning;
+ },
+ isBeeperSocketRunning: () => socket.running,
+ }));
+
+ const { reconcileBeeperIngestion } = await import('./beeperArming.js');
+ const { runBeeperSweep } = await import('./beeperSync.js');
+ const { cancel, getEvent } = await import('./eventScheduler.js');
+
+ function captureLogs() {
+ const lines = [];
+ vi.spyOn(console, 'log').mockImplementation((line) => { lines.push(String(line)); });
+ vi.spyOn(console, 'error').mockImplementation((line) => { lines.push(String(line)); });
+ return lines;
+ }
+
+ beforeEach(() => {
+ state.armed = true;
+ state.config = { enabled: true, intervalMinutes: 5 };
+ socket.running = false;
+ socket.starts = 0;
+ socket.stops = 0;
+ socket.gate = Promise.resolve();
+ socket.onStart = () => {};
+ runBeeperSweep.mockClear();
+ });
+
+ afterEach(() => {
+ cancel('beeper-sync');
+ vi.restoreAllMocks();
+ });
+
+ describe('reconcileBeeperIngestion', () => {
+ it('arms the transport and the sweep when a credential lands on a running install', async () => {
+ captureLogs();
+
+ const result = await reconcileBeeperIngestion({ reason: 'oauth-connect' });
+
+ expect(socket.running).toBe(true);
+ expect(getEvent('beeper-sync')).toBeTruthy();
+ expect(result).toMatchObject({ armed: true, socketRunning: true, schedulerRegistered: true, changed: true });
+ });
+
++ it('replaces the active transport after connection settings change without resetting the sweep', async () => {
++ captureLogs();
++ await reconcileBeeperIngestion();
++ const firstRun = getEvent('beeper-sync').nextRunAt;
++
++ await reconcileBeeperIngestion({ reason: 'connection-settings', restartSocket: true });
++
++ expect(socket.stops).toBe(1);
++ expect(socket.running).toBe(true);
++ expect(getEvent('beeper-sync').nextRunAt).toBe(firstRun);
++ });
++
+ it('is idempotent — a repeat call restarts nothing and does not push the next sweep out', async () => {
+ captureLogs();
+ await reconcileBeeperIngestion({ reason: 'oauth-connect' });
+ const firstRun = getEvent('beeper-sync').nextRunAt;
+
+ const result = await reconcileBeeperIngestion({ reason: 'feature-toggle' });
+
+ // `eventScheduler.schedule` cancels and replaces an event with the same id,
+ // resetting `nextRunAt` a whole interval into the future. Re-registering on
+ // every unrelated toggle would keep the sweep permanently five minutes away.
+ expect(getEvent('beeper-sync').nextRunAt).toBe(firstRun);
+ expect(socket.running).toBe(true);
+ expect(result.changed).toBe(false);
+ });
+
+ it('arms the transport but registers no sweep while the user has scheduled sync off', async () => {
+ // The two flags stay distinct (#11): the feature+token gate arms the
+ // transport, `settings.beeper.enabled` is the ingestion opt-in.
+ state.config = { enabled: false, intervalMinutes: 5 };
+ captureLogs();
+
+ const result = await reconcileBeeperIngestion({ reason: 'oauth-connect' });
+
+ expect(socket.running).toBe(true);
+ expect(getEvent('beeper-sync')).toBeFalsy();
+ expect(result).toMatchObject({ armed: true, schedulerRegistered: false });
+ });
+
+ it('stops the relay and cancels the sweep when the credential is deleted', async () => {
+ captureLogs();
+ await reconcileBeeperIngestion({ reason: 'oauth-connect' });
+ expect(socket.running).toBe(true);
+
+ state.armed = false;
+ const result = await reconcileBeeperIngestion({ reason: 'disconnect' });
+
+ expect(socket.running).toBe(false);
+ expect(getEvent('beeper-sync')).toBeFalsy();
+ expect(result).toMatchObject({ armed: false, socketRunning: false, schedulerRegistered: false, changed: true });
+ });
+
+ it('does nothing and says nothing on an install that was never armed', async () => {
+ // #32's acceptance: with the feature off or no token, nothing registers and
+ // nothing logs — a fresh install must not narrate a feature it does not have.
+ state.armed = false;
+ const logs = captureLogs();
+
+ const result = await reconcileBeeperIngestion({ reason: 'feature-toggle' });
+
+ expect(getEvent('beeper-sync')).toBeFalsy();
+ expect(socket.running).toBe(false);
+ expect(result.changed).toBe(false);
+ expect(logs).toEqual([]);
+ });
+
+ it('serializes overlapping triggers so a toggle landing mid-connect cannot double-arm', async () => {
+ captureLogs();
+
+ await Promise.all([
+ reconcileBeeperIngestion({ reason: 'oauth-connect' }),
+ reconcileBeeperIngestion({ reason: 'feature-toggle' }),
+ ]);
+
+ expect(socket.running).toBe(true);
+ // Two calls into the transport, but only the first one started it.
+ expect(socket.starts).toBe(2);
+ expect(getEvent('beeper-sync')).toBeTruthy();
+ });
+
+ // The serialization case an arm+arm race does not stress: two OPPOSITE
+ // triggers landing in the same tick. Without the `tail` queue in
+ // `reconcileBeeperIngestion`, both calls' `reconcileOnce()` run concurrently
+ // instead of one fully finishing before the next starts, and whichever one's
+ // async chain happens to settle LAST wins — not whichever was issued last.
+ // Here that would leave the socket running and the sweep registered even
+ // though `disconnect` (issued second) is the trigger that should have had
+ // the final say.
+ //
+ // This is proved by temporarily removing the queue: replace
+ // `reconcileBeeperIngestion`'s body in beeperArming.js with
+ // `return reconcileOnce(reason);` and re-run this file. The socket stays
+ // running (asserted false below) because the arm call's `startBeeperSocket()`
+ // — parked on `socket.gate` until this test releases it — resumes and starts
+ // the socket AFTER the disarm call has already run and found nothing to stop.
+ // Restore the `tail.then(run, run)` body afterward; this test passes again
+ // once it is back.
+ it('lets a disarm issued while an arm is still starting the socket win the final state', async () => {
+ captureLogs();
+ let releaseSocket;
+ socket.gate = new Promise((resolve) => { releaseSocket = resolve; });
+ const socketStartSeen = new Promise((resolve) => { socket.onStart = resolve; });
+
+ // `state.armed` is read again inside `reconcileOnce` — flipping it here
+ // (once the arm call has already captured `true` and is parked inside
+ // `startBeeperSocket()`) is what makes the disarm call, issued next, a
+ // genuine disarm rather than a second arm.
+ const armPromise = reconcileBeeperIngestion({ reason: 'oauth-connect' });
+ await socketStartSeen;
+ state.armed = false;
+ const disarmPromise = reconcileBeeperIngestion({ reason: 'disconnect' });
+ releaseSocket();
+
+ await Promise.all([armPromise, disarmPromise]);
+
+ expect(socket.running).toBe(false);
+ expect(getEvent('beeper-sync')).toBeFalsy();
+ });
+
+ // Pins the arming-level half of the settings-route sync-toggle fix
+ // (server/routes/settings.js): saving `settings.beeper.enabled` now calls
+ // `reconcileBeeperIngestion({ reason: 'sync-toggle' })` when the flag
+ // actually changes. Registering the sweep on that call is this module's
+ // job; STOPPING it on a false flip is not — `reconcileOnce` only disarms
+ // when the feature+token gate itself is false, so a sync-toggle reconcile
+ // with the gate still armed must leave an already-running sweep alone. The
+ // scheduler's own per-tick `getBeeperSyncConfig()` re-read is what actually
+ // stops runs in that case (see server/routes/settings.test.js's
+ // true→false case for the route side of this).
+ it('registers the scheduler on a sync-toggle reconcile when enabled is true, but does not stop it when enabled flips false while still armed', async () => {
+ captureLogs();
+
+ const armedResult = await reconcileBeeperIngestion({ reason: 'sync-toggle' });
+
+ expect(socket.running).toBe(true);
+ expect(getEvent('beeper-sync')).toBeTruthy();
+ expect(armedResult).toMatchObject({ armed: true, schedulerRegistered: true, changed: true });
+
+ // The gate (feature + token) stays armed; only the user's own sync opt-in
+ // flips off. A reconcile here must not disarm anything.
+ state.config = { enabled: false, intervalMinutes: 5 };
+ const disabledResult = await reconcileBeeperIngestion({ reason: 'sync-toggle' });
+
+ expect(getEvent('beeper-sync')).toBeTruthy();
+ expect(socket.running).toBe(true);
+ expect(disabledResult.changed).toBe(false);
+ });
+
+ // Fork issue #79: before this, connecting (or flipping a feature/sync
+ // toggle on) registered the interval timer but fired nothing until a full
+ // interval had elapsed. This fails on the old code — which never called
+ // `runBeeperSweep` from `reconcileOnce` at all.
+ describe('immediate sweep on arm (#79)', () => {
+ it('kicks one sweep immediately when a reconcile newly registers the scheduler', async () => {
+ captureLogs();
+
+ await reconcileBeeperIngestion({ reason: 'oauth-connect' });
+
+ expect(runBeeperSweep).toHaveBeenCalledTimes(1);
+ expect(runBeeperSweep).toHaveBeenCalledWith({ reason: 'arm' });
+ });
+
+ it('does not kick a second sweep on a reconcile that finds the scheduler already registered', async () => {
+ captureLogs();
+ await reconcileBeeperIngestion({ reason: 'oauth-connect' });
+ runBeeperSweep.mockClear();
+
+ await reconcileBeeperIngestion({ reason: 'feature-toggle' });
+
+ expect(runBeeperSweep).not.toHaveBeenCalled();
+ });
+
+ it('does not kick a sweep when the gate is armed but the user has scheduled sync off', async () => {
+ state.config = { enabled: false, intervalMinutes: 5 };
+ captureLogs();
+
+ await reconcileBeeperIngestion({ reason: 'oauth-connect' });
+
+ expect(getEvent('beeper-sync')).toBeFalsy();
+ expect(runBeeperSweep).not.toHaveBeenCalled();
+ });
+
+ it('does not kick a sweep on disarm', async () => {
+ captureLogs();
+ await reconcileBeeperIngestion({ reason: 'oauth-connect' });
+ runBeeperSweep.mockClear();
+
+ state.armed = false;
+ await reconcileBeeperIngestion({ reason: 'disconnect' });
+
+ expect(runBeeperSweep).not.toHaveBeenCalled();
+ });
+
+ // A rejected kick is logged, not thrown — the fire-and-forget promise
+ // must never turn a completed arm into a caller-visible failure.
+ it('logs rather than throws when the kicked sweep rejects', async () => {
+ runBeeperSweep.mockRejectedValueOnce(new Error('boom'));
+ const logs = captureLogs();
+
+ const result = await reconcileBeeperIngestion({ reason: 'oauth-connect' });
+
+ expect(result.armed).toBe(true);
+ // Give the unawaited rejection's `.catch` a turn of the microtask queue.
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(logs.some((line) => line.includes('immediate sweep on arm failed'))).toBe(true);
+ });
+ });
+ });
diff --cc server/services/beeperClient.js
index 0000000000,9c8b6c51db..4a1918d334
mode 000000,100644..100644
--- a/server/services/beeperClient.js
+++ b/server/services/beeperClient.js
@@@ -1,0 -1,906 +1,908 @@@
+ /**
+ * Beeper Desktop API client (fork issue #29, part of #1).
+ *
+ * Raw `fetch`, deliberately NOT `@beeper/desktop-api` — the published SDK lags
+ * the live API and exposes no `Account.status`, no `loginID`, no `/v1/bridges`;
+ * `GET /v1/spec` on the running instance is the authoritative reference (see
+ * the API-surface research note, `docs/research/2026-08-31-beeper-api-surface.md`
+ * on the `research/beeper` branch — not merged onto `beeper/integration`, so the
+ * path is not resolvable from this branch alone). Every other Beeper feature
+ * (#30-#37) is built on this module.
+ *
+ * `server/lib/safeUrlFetch.js` cannot wrap this: it blocks loopback in both
+ * postures by design, and Beeper Desktop's whole API IS a loopback service
+ * (default `http://127.0.0.1:23373`). This module goes straight to
+ * `fetchWithTimeout` instead, same as `ollamaManager.js` / `lmStudioManager.js`
+ * for the other local-daemon integrations. `safeUrlFetch`'s `readBodyCapped`
+ * two-stage byte cap (Content-Length early-out, then a streamed abort once
+ * accumulated bytes exceed the ceiling) is NOT reused here — every JSON
+ * response this module reads is small, from a local trusted process, read via
+ * `readResponseJson`. The byte-streaming asset fetch (attachment mirror, #37 —
+ * `headAsset` / `fetchAssetStream` below) is the one caller that wants that
+ * two-stage shape, and it enforces its own: a `HEAD` pre-flight plus a
+ * mid-stream abort, both against `BEEPER_ATTACHMENT_MAX_BYTES`.
+ *
+ * Auth and base URL: `settings.beeper.baseUrl` (default below) and, since #31,
+ * the vault-backed credential store (`beeperCredentials.resolveBeeperToken` —
+ * AES-256-GCM in Postgres, per fork issue #11 decision 6). `resolveBeeperConfig`
+ * is the one call site that resolves it; the legacy plaintext
+ * `settings.beeper.token` from #29 survives there as a READ-only fallback so an
+ * install that hand-edited one keeps working. Nothing here ever writes a token.
+ * Every caller-facing function also accepts an explicit `{ baseUrl, token }`
+ * override, which skips both stores entirely.
+ */
+
+ import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';
+ import { readResponseJson } from '../lib/readResponseJson.js';
+ import { describeFetchError, isReplayableConnectionError } from '../lib/fetchErrorChain.js';
+ import { ServerError } from '../lib/errorHandler.js';
+ import { isPlainObject } from '../lib/objects.js';
+ import { isLoopbackHostname, parseBrowserOrigin } from '../lib/beeperOAuthOrigin.js';
+ import { getSettings } from './settings.js';
+ import { resolveBeeperToken } from './beeperCredentials.js';
+
+ export const DEFAULT_BASE_URL = 'http://127.0.0.1:23373';
+ const DEFAULT_REQUEST_TIMEOUT_MS = 15_000;
+ // Fork issue #61, decision 7. The original 1s cap (a live Beeper Desktop
+ // answers in single-digit-to-low-double-digit ms, and a closed loopback port
+ // refuses near-instantly) turned out to be too tight on a loaded machine: a
+ // Beeper Desktop that is genuinely up but briefly slow to answer the bare
+ // liveness probe timed out and reported the same "unreachable" card as a
+ // closed app, even seconds after it had handled a real request. 3s is still
+ // well short of `DEFAULT_REQUEST_TIMEOUT_MS` (this stays a liveness probe, not
+ // a request budget) but gives a momentarily busy app room to answer before the
+ // card treats it as gone. A timeout on ITS OWN is still ambiguous, though —
+ // nothing distinguishes "briefly slow" from "actually closed" from timing
+ // alone — which is what `RECENT_SUCCESS_WINDOW_MS` below is for.
+ export const DEFAULT_PROBE_TIMEOUT_MS = 3_000;
+ // Paired with the cap above: a probe timeout is reported as `probeState:
+ // 'slow'` (reachable stays true) rather than `'unreachable'` ONLY when a real
+ // Beeper call — an authenticated API request through this client, or a
+ // realtime-socket ping (server/services/beeperSocket.js) — succeeded within
+ // this window. 60s comfortably survives one missed probe against the socket's
+ // own ~30s ping cadence while staying short enough that an app closed for real
+ // still reaches the unreachable card within a minute of going quiet — a probe
+ // timeout with no recent success (nothing else has talked to Beeper lately
+ // either) is exactly what "unreachable" means, promptly.
+ export const RECENT_SUCCESS_WINDOW_MS = 60_000;
+
+ // Last time ANY call through `beeperRequest` (a real API call, or a successful
+ // probe) completed. `null` until the first one — `hasRecentBeeperSuccess`
+ // reads that as "no recent success" rather than an epoch-zero false positive.
+ let lastSuccessAt = null;
+
+ function noteSuccess() {
+ lastSuccessAt = Date.now();
+ }
+
+ /** Whether a Beeper call has completed within `RECENT_SUCCESS_WINDOW_MS`. */
+ export function hasRecentBeeperSuccess(nowMs = Date.now()) {
+ return typeof lastSuccessAt === 'number' && (nowMs - lastSuccessAt) <= RECENT_SUCCESS_WINDOW_MS;
+ }
+
+ // Test-only: `beeperStatus.test.js` and `beeperClient.test.js` need to drive
+ // `hasRecentBeeperSuccess` without waiting on a real successful request first.
+ export function __setLastBeeperSuccessAtForTests(value) {
+ lastSuccessAt = value;
+ }
+ // Reads may retry once on a replayable connection failure (Beeper Desktop
+ // restarting mid-request); a fresh request-scoped budget on the replay, same
+ // shape as fetchWithTimeout's own retry contract.
+ const READ_RETRY = { retries: 1, retryDelayMs: 300, shouldRetry: isReplayableConnectionError };
+
+ /**
+ * Typed Beeper API error. `retryable` reflects the mapping in
+ * `mapBeeperResponseError`, clamped to `false` whenever the originating call
+ * ran with `allowRetry: false` (every write: send/edit/delete/react/archive/
+ * read-state) — callers building their own retry policy on top of this client
+ * should key on it rather than re-deriving from `status`.
+ */
+ export class BeeperApiError extends ServerError {
+ constructor(message, { status = 500, code, retryable = false, details } = {}) {
+ super(message, { status, code, context: { retryable, ...(details !== undefined ? { details } : {}) } });
+ this.name = 'BeeperApiError';
+ this.retryable = retryable;
+ // ServerError's constructor does `this.status = options.status || 500`, which
+ // silently rewrites a deliberate `status: 0` ("no HTTP response at all", the
+ // network-error case below) into a fabricated 500. Restore the caller's actual
+ // value here so `err.status === 0` is a reliable way to spot a transport
+ // failure, not just `err.code === 'NETWORK_ERROR'`.
+ this.status = status;
+ }
+ }
+
+ // Logged at most once per distinct rejected value (not on every call — this
+ // runs on the hot path: every sweep tick, every status poll) so a
+ // misconfigured install narrates the fallback without spamming the log.
+ let lastRejectedBaseUrl;
+
+ /**
+ * Normalize a candidate Beeper Desktop base URL, re-applying the SAME
+ * loopback-only gate `beeperSettingsSchema` enforces on the PUT route
+ * (SEC-2, `server/lib/mediaValidation.js`) — not belt-and-suspenders.
+ * `getSettings()` reads `settings.json` off disk with NO schema
+ * re-validation on read, so a hand-edited file is a path that can still hand
+ * a non-loopback origin — with a live vault token attached to every request —
+ * to `beeperRequest`, even though the settings PUT route would have refused
+ * it. A rejected value falls back to the shipped loopback default rather than
+ * reaching a single request.
+ */
+ function normalizeBaseUrl(value, { allowNonLoopback = false } = {}) {
+ const trimmed = String(value || '').trim().replace(/\/+$/, '');
+ if (!trimmed) return DEFAULT_BASE_URL;
+ const parsed = parseBrowserOrigin(trimmed);
+ if (parsed && (isLoopbackHostname(parsed.hostname) || allowNonLoopback)) {
+ return parsed.origin;
+ }
+ if (trimmed !== lastRejectedBaseUrl) {
+ lastRejectedBaseUrl = trimmed;
+ console.error(`❌ Beeper baseUrl "${trimmed}" is not a loopback origin and allowNonLoopbackBaseUrl is not set — falling back to ${DEFAULT_BASE_URL}`);
+ }
+ return DEFAULT_BASE_URL;
+ }
+
+ /**
+ * The configured Beeper Desktop base URL, trailing slash trimmed, falling back
+ * to the loopback default. Exported so the connect flow (#31) resolves it
+ * exactly the way every API call does instead of re-deriving it.
+ */
+ export async function resolveBeeperBaseUrl() {
+ const settings = await getSettings().catch(() => null);
+ return normalizeBaseUrl(settings?.beeper?.baseUrl, {
+ allowNonLoopback: settings?.beeper?.allowNonLoopbackBaseUrl === true,
+ });
+ }
+
+ function normalizeToken(value) {
+ return typeof value === 'string' && value.trim() ? value.trim() : null;
+ }
+
+ /**
+ * Resolve `{ baseUrl, token }` for a call. An explicit `baseUrl` AND `token`
+ * (token may be `null`, meaning "deliberately unauthenticated") skip both
+ * stores entirely — this is what keeps most tests in this file free of any
+ * mock. Otherwise the base URL falls back to `settings.beeper.baseUrl` and then
+ * to the hardcoded default, while the token comes from the vault-backed store
+ * (`resolveBeeperToken`, #31), which itself falls back to the legacy plaintext
+ * `settings.beeper.token` for reads.
+ *
+ * An unreadable vault THROWS out of here rather than resolving `token: null`:
+ * "the credential cannot be read" and "no credential is configured" are
+ * different conditions, and collapsing them would report a connected install as
+ * unconfigured (the absent-vs-empty sentinel rule).
+ *
+ * SEC-2's loopback-only gate applies whenever `baseUrl` is resolved FROM
+ * settings below — the one path a hand-edited `settings.json` can reach. The
+ * "both explicit" bypass above trusts its caller instead of re-deriving the
+ * gate here: it exists for values ALREADY resolved through
+ * `resolveBeeperBaseUrl()` (the OAuth discovery baseUrl, and
+ * `beeperStatus.js`'s probes — both call `resolveBeeperBaseUrl()` rather than
+ * reading `settings.beeper.baseUrl` directly for exactly this reason) plus the
+ * many tests in this file, and gating it a second time would need the
+ * opt-in re-derived here anyway, defeating "skip both stores entirely." A
+ * caller with a genuinely unvalidated `baseUrl` must resolve it through
+ * `resolveBeeperBaseUrl()` first, never pass it straight into this bypass.
+ */
+ export async function resolveBeeperConfig({ baseUrl, token } = {}) {
+ if (baseUrl !== undefined && token !== undefined) {
+ // `allowNonLoopback: true` — trust the caller entirely rather than
+ // re-deriving the settings-sourced opt-in (which would defeat "skip both
+ // stores"). `normalizeBaseUrl` still enforces the bare-origin SHAPE and
+ // still trims a trailing slash; only the loopback gate is waived here.
+ return { baseUrl: normalizeBaseUrl(baseUrl, { allowNonLoopback: true }), token: normalizeToken(token) };
+ }
+ const settings = await getSettings().catch(() => null);
+ const resolvedBaseUrl = baseUrl !== undefined ? baseUrl : settings?.beeper?.baseUrl;
+ const allowNonLoopback = settings?.beeper?.allowNonLoopbackBaseUrl === true;
+ if (token !== undefined) {
+ return { baseUrl: normalizeBaseUrl(resolvedBaseUrl, { allowNonLoopback }), token: normalizeToken(token) };
+ }
+ const stored = await resolveBeeperToken();
+ return { baseUrl: normalizeBaseUrl(resolvedBaseUrl, { allowNonLoopback }), token: normalizeToken(stored?.token) };
+ }
+
+ /**
+ * Map a non-ok Beeper response to a typed, retry-classified error.
+ *
+ * `retryEligible` (default `true`) clamps every status-table verdict to
+ * non-retryable when the call itself was never eligible to retry. A write
+ * call runs with `allowRetry: false` (the client-wide send-safe default) and
+ * must never hand back `retryable: true` on its thrown error — that field is
+ * the client's own documented "key on this, not on status" contract
+ * (`BeeperApiError` above), and a caller following it would otherwise
+ * duplicate a real send. `beeperRequest` passes its own `allowRetry` through
+ * unchanged as `retryEligible`; only the asset-502 branch below ignores it,
+ * since that mapping is `retryable: false` unconditionally regardless of
+ * retry eligibility.
+ *
+ * The one non-conventional case: `GET`/`HEAD /v1/assets/serve` answers `502`
+ * for a missing/expired asset, not `404` (live-verified on both methods). A
+ * generic "5xx is transient" retry policy loops forever on media the network
+ * has aged out, so an asset-endpoint `502` maps to a TERMINAL
+ * `ASSET_UNAVAILABLE` rather than the ordinarily-retryable `UPSTREAM_ERROR`.
+ * `POST /v1/assets/download` does NOT share this — it answers `200` with an
+ * `{ error }` body instead, so this `502` branch never fires for it; that
+ * shape is validated separately in `downloadAsset` below. Every other status
+ * follows the spec's documented meaning (see the
+ * API-surface research note, `docs/research/2026-08-31-beeper-api-surface.md`
+ * §7, on the `research/beeper` branch); `code` is never a published enum, so
+ * it rides along under `details` for logging only.
+ */
+ export function mapBeeperResponseError(status, body, { isAssetEndpoint = false, retryEligible = true } = {}) {
+ const beeperCode = body?.code;
+ const message = typeof body?.message === 'string' && body.message
+ ? body.message
+ : `Beeper API error: ${status}`;
+ const details = beeperCode !== undefined ? { beeperCode } : undefined;
+
+ if (status === 502 && isAssetEndpoint) {
+ return new BeeperApiError(message, { status, code: 'ASSET_UNAVAILABLE', retryable: false, details });
+ }
+
+ const STATUS_TABLE = {
+ 400: { code: 'BAD_REQUEST', retryable: false },
+ 401: { code: 'UNAUTHORIZED', retryable: false },
+ 403: { code: 'FORBIDDEN', retryable: false },
+ 404: { code: 'NOT_FOUND', retryable: false },
+ 409: { code: 'CONFLICT', retryable: false },
+ 422: { code: 'VALIDATION_ERROR', retryable: false },
+ 429: { code: 'RATE_LIMITED', retryable: true },
+ 500: { code: 'INTERNAL_ERROR', retryable: true },
+ 502: { code: 'UPSTREAM_ERROR', retryable: true },
+ };
+ const mapped = STATUS_TABLE[status] || { code: 'UNKNOWN_ERROR', retryable: status >= 500 };
+ return new BeeperApiError(message, { status, code: mapped.code, retryable: retryEligible && mapped.retryable, details });
+ }
+
+ /**
+ * Low-level authenticated request. Every call goes through `fetchWithTimeout`
+ * (requirement: "fetchWithTimeout on every call"). `allowRetry` is OFF by
+ * default — the send-safe default, since Beeper has no idempotency key on
+ * send and a retried POST duplicates a real message. Read call sites opt in
+ * explicitly with `allowRetry: true`.
+ */
+ async function beeperRequest(path, {
+ method = 'GET',
+ body,
+ headers,
+ timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS,
+ baseUrl,
+ token,
+ requireAuth = true,
+ allowRetry = false,
+ isAssetEndpoint = false,
+ } = {}) {
+ const resolved = await resolveBeeperConfig({ baseUrl, token });
+ if (requireAuth && !resolved.token) {
+ throw new BeeperApiError('Beeper access token is not configured', {
+ status: 401, code: 'NOT_CONFIGURED', retryable: false,
+ });
+ }
+
+ const reqHeaders = { 'Content-Type': 'application/json', ...headers };
+ if (resolved.token) reqHeaders.Authorization = `Bearer ${resolved.token}`;
+
+ let response;
+ try {
+ response = await fetchWithTimeout(`${resolved.baseUrl}${path}`, {
+ method,
+ headers: reqHeaders,
++ redirect: 'error',
+ body: body === undefined ? undefined : JSON.stringify(body),
+ }, timeoutMs, allowRetry ? READ_RETRY : {});
+ } catch (err) {
+ const description = describeFetchError(err);
+ // AbortController firing (the timeout above, or a caller-supplied
+ // `signal`) is the one network failure that means "no answer arrived in
+ // time" rather than "nothing is listening" — the distinction
+ // `probeBeeperInfo` needs to tell `slow` from `unreachable` (fork issue
+ // #61, decision 7). Node/undici's own AbortError always carries "abort" in
+ // its name or message; `describeFetchError` folds both into this string.
+ const timedOut = /\babort/i.test(description);
+ throw new BeeperApiError(`Beeper request failed: ${description}`, {
+ status: 0, code: 'NETWORK_ERROR', retryable: allowRetry && isReplayableConnectionError(err),
+ details: timedOut ? { timedOut: true } : undefined,
+ });
+ }
+
+ if (response.status === 204) {
+ noteSuccess();
+ return null;
+ }
+ const data = await readResponseJson(response, { fallback: (text) => ({ message: text }) });
+ if (!response.ok) throw mapBeeperResponseError(response.status, data, { isAssetEndpoint, retryEligible: allowRetry });
+ noteSuccess();
+ return data;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Discovery / liveness
+ // ---------------------------------------------------------------------------
+
+ /**
+ * `GET /v1/info` — the one endpoint that also answers UNAUTHENTICATED, which is
+ * what makes it the liveness probe and what disqualifies it as a credential
+ * check: it answers 200 for a bogus token just as happily (#31's connect flow
+ * introspects instead). `token: null` is explicit, so a probe never triggers a
+ * credential read.
+ */
+ export async function getInfo({ baseUrl, timeoutMs = DEFAULT_PROBE_TIMEOUT_MS } = {}) {
+ return beeperRequest('/v1/info', { baseUrl, token: null, requireAuth: false, timeoutMs });
+ }
+
+ /**
+ * Structural check on `/v1/info`'s response body (#30 — a wave-one reviewer
+ * requirement on the status probe). `app.name` and `server.status` are the
+ * two fields every documented shape carries (see the API-surface research
+ * note). A 200 with an unexpected body — some other local HTTP service
+ * answering on a misconfigured `settings.beeper.baseUrl` (#30 makes that
+ * user-editable), or a Beeper Desktop version mid-upgrade — must not be
+ * reported as a healthy probe just because the transport succeeded. Exported
+ * so a caller that wants the raw typed error (rather than `probeBeeperInfo`'s
+ * swallowed boolean) can throw it directly.
+ */
+ export function assertValidInfoResponse(info) {
+ const valid = isPlainObject(info)
+ && typeof info?.app?.name === 'string' && info.app.name.length > 0
+ && typeof info?.server?.status === 'string' && info.server.status.length > 0;
+ if (!valid) {
+ throw new BeeperApiError('Beeper API returned an unexpected /v1/info response shape (expected { app: { name }, server: { status } })', {
+ status: 502, code: 'MALFORMED_RESPONSE', retryable: false,
+ });
+ }
+ }
+
+ /**
+ * Liveness probe with a `DEFAULT_PROBE_TIMEOUT_MS` cap (#11, revised at fork
+ * issue #61 decision 7) — generous headroom over a live Beeper Desktop's
+ * actual response time, without being a real request budget. Never throws —
+ * an unreachable/misconfigured install is a normal outcome for a feature the
+ * user hasn't set up yet, not an exceptional one. A shape-invalid 200 (see
+ * `assertValidInfoResponse`) reports `reachable: false` exactly like a
+ * transport failure — a body that isn't Beeper's `/v1/info` never counts as
+ * "reachable" just because *something* answered.
+ *
+ * `timedOut` and `latencyMs` are additive fields for `beeperStatus.js` to
+ * derive `probeState: 'ok' | 'slow' | 'unreachable'` from — see
+ * `hasRecentBeeperSuccess` above. Every existing caller that reads only
+ * `reachable`/`info`/`error` is unaffected.
+ */
+ export async function probeBeeperInfo({ baseUrl, timeoutMs = DEFAULT_PROBE_TIMEOUT_MS } = {}) {
+ const startedAt = Date.now();
+ try {
+ const info = await getInfo({ baseUrl, timeoutMs });
+ assertValidInfoResponse(info);
+ return {
+ reachable: true, info, error: null, timedOut: false, latencyMs: Date.now() - startedAt,
+ };
+ } catch (err) {
+ const timedOut = err instanceof BeeperApiError && err.context?.details?.timedOut === true;
+ return {
+ reachable: false,
+ info: null,
+ error: err instanceof BeeperApiError ? err.message : describeFetchError(err),
+ timedOut,
+ latencyMs: Date.now() - startedAt,
+ };
+ }
+ }
+
+ // ---------------------------------------------------------------------------
+ // Cursor pagination
+ // ---------------------------------------------------------------------------
+
+ /**
+ * Walk a cursor-paginated Beeper endpoint as an async iterator, so callers
+ * never hand-roll the cursor loop. `fetchPage({ cursor, direction })` must
+ * return the standard envelope `{ items, hasMore, oldestCursor, newestCursor }`.
+ *
+ * `direction: 'before'` (default) walks `oldestCursor` — the only direction
+ * the endpoints this client wraps document as safe to auto-paginate (the SDK's
+ * own auto-pagination only ever walks backwards too). `hasMore: true` with no
+ * cursor to continue on is treated as exhausted rather than looping forever —
+ * a defensive stop, since the spec never documents that combination. Same
+ * defense if a server answers `hasMore: true` with the SAME cursor it was
+ * just called with (a value that would otherwise walk in place forever).
+ *
+ * A page whose `items` isn't an array (a malformed/unexpected response body —
+ * see `getAccounts`/`getBridges` below for the same rule) throws a typed
+ * `MALFORMED_RESPONSE` `BeeperApiError` rather than silently coercing to `[]`
+ * and reporting "no items" — the AGENTS.md "sentinel + validate" rule: absent,
+ * failed, and invalid must never collapse into the same value as
+ * legitimately-empty.
+ */
+ export async function* paginateBeeperCursor(fetchPage, { direction = 'before' } = {}) {
+ let cursor;
+ for (;;) {
+ const page = await fetchPage({ cursor, direction });
+ if (!Array.isArray(page?.items)) {
+ throw new BeeperApiError('Beeper API returned an unexpected paginated response shape (expected { items: [] })', {
+ status: 502, code: 'MALFORMED_RESPONSE', retryable: false,
+ });
+ }
+ for (const item of page.items) yield item;
+ if (!page?.hasMore) return;
+ const nextCursor = direction === 'after' ? page?.newestCursor : page?.oldestCursor;
+ if (!nextCursor || nextCursor === cursor) return;
+ cursor = nextCursor;
+ }
+ }
+
+ function cursorQuery({ cursor, direction }) {
+ const qs = new URLSearchParams();
+ if (cursor) qs.set('cursor', cursor);
+ if (direction) qs.set('direction', direction);
+ const query = qs.toString();
+ return query ? `?${query}` : '';
+ }
+
+ function clampLimit(value, { min = 1, max, fallback }) {
+ const n = Number(value);
+ if (!Number.isFinite(n)) return fallback;
+ return Math.min(max, Math.max(min, Math.trunc(n)));
+ }
+
+ /**
+ * Append arbitrary search/filter params onto a `URLSearchParams`. An array
+ * value (`accountIDs`, `chatIDs`, `mediaTypes` — all declared as array query
+ * params in `/v1/spec`) is serialized as REPEATED keys (`?chatIDs=a&chatIDs=b`),
+ * not `qs.set(key, String(array))`, which would comma-join it into one value
+ * (`chatIDs=a%2Cb`) that the server reads as a single id matching nothing.
+ */
+ function appendSearchParams(qs, params) {
+ for (const [key, value] of Object.entries(params)) {
+ if (value === undefined || value === null || value === '') continue;
+ if (Array.isArray(value)) {
+ for (const item of value) {
+ if (item === undefined || item === null || item === '') continue;
+ qs.append(key, String(item));
+ }
+ continue;
+ }
+ qs.set(key, String(value));
+ }
+ }
+
+ // ---------------------------------------------------------------------------
+ // Chats
+ // ---------------------------------------------------------------------------
+
+ /**
+ * `GET /v1/chats` — no `limit` param (server-chosen page size). One page.
+ *
+ * `accountIDs` is the endpoint's only filter and is declared as an ARRAY query
+ * param, so it goes through `appendSearchParams` (repeated keys) rather than
+ * `qs.set`, which would comma-join two ids into one value matching no account.
+ * The ingestion sweep (#32) pages one account at a time so a chat row is
+ * always attributable to the account whose cursor bounds it — without the
+ * filter it would have to page the whole cross-account list once per account.
+ * An omitted/empty `accountIDs` sends no filter at all (every account), never
+ * an empty `accountIDs=` that the server would read as "match nothing".
+ */
+ export async function listChatsPage({ cursor, direction = 'before', accountIDs, baseUrl, token, timeoutMs } = {}) {
+ const qs = new URLSearchParams();
+ appendSearchParams(qs, { accountIDs });
+ if (cursor) qs.set('cursor', cursor);
+ if (direction) qs.set('direction', direction);
+ const query = qs.toString();
+ return beeperRequest(`/v1/chats${query ? `?${query}` : ''}`, { baseUrl, token, timeoutMs, allowRetry: true });
+ }
+
+ /** Async iterator over every chat, walking cursors automatically. */
+ export function listChats({ direction = 'before', accountIDs, baseUrl, token, timeoutMs } = {}) {
+ return paginateBeeperCursor(
+ ({ cursor, direction: dir }) => listChatsPage({
+ cursor, direction: dir, accountIDs, baseUrl, token, timeoutMs,
+ }),
+ { direction },
+ );
+ }
+
+ export async function getChat(chatId, { baseUrl, token, timeoutMs } = {}) {
+ return beeperRequest(`/v1/chats/${encodeURIComponent(chatId)}`, { baseUrl, token, timeoutMs, allowRetry: true });
+ }
+
+ /** `GET /v1/chats/search` — has `limit` (default 50, max 200). One page. */
+ export async function searchChatsPage({ limit, cursor, direction = 'before', baseUrl, token, timeoutMs, ...params } = {}) {
+ const qs = new URLSearchParams();
+ appendSearchParams(qs, params);
+ const clamped = clampLimit(limit, { min: 1, max: 200, fallback: undefined });
+ if (clamped !== undefined) qs.set('limit', String(clamped));
+ if (cursor) qs.set('cursor', cursor);
+ if (direction) qs.set('direction', direction);
+ const query = qs.toString();
+ return beeperRequest(`/v1/chats/search${query ? `?${query}` : ''}`, { baseUrl, token, timeoutMs, allowRetry: true });
+ }
+
+ // ---------------------------------------------------------------------------
+ // Messages
+ // ---------------------------------------------------------------------------
+
+ /** `GET /v1/chats/{chatID}/messages` — no `limit` param. One page. */
+ export async function listMessagesPage(chatId, { cursor, direction = 'before', baseUrl, token, timeoutMs } = {}) {
+ return beeperRequest(
+ `/v1/chats/${encodeURIComponent(chatId)}/messages${cursorQuery({ cursor, direction })}`,
+ { baseUrl, token, timeoutMs, allowRetry: true },
+ );
+ }
+
+ /** Async iterator over every message in a chat, walking cursors automatically. */
+ export function listMessages(chatId, { direction = 'before', baseUrl, token, timeoutMs } = {}) {
+ return paginateBeeperCursor(
+ ({ cursor, direction: dir }) => listMessagesPage(chatId, { cursor, direction: dir, baseUrl, token, timeoutMs }),
+ { direction },
+ );
+ }
+
+ export async function getMessage(chatId, messageId, { baseUrl, token, timeoutMs } = {}) {
+ return beeperRequest(
+ `/v1/chats/${encodeURIComponent(chatId)}/messages/${encodeURIComponent(messageId)}`,
+ { baseUrl, token, timeoutMs, allowRetry: true },
+ );
+ }
+
+ /** `GET /v1/messages/search` — `limit` is hard-capped at 20 (default 20). One page. */
+ export async function searchMessagesPage({ limit, cursor, direction = 'before', baseUrl, token, timeoutMs, ...params } = {}) {
+ const qs = new URLSearchParams();
+ appendSearchParams(qs, params);
+ const clamped = clampLimit(limit, { min: 1, max: 20, fallback: 20 });
+ qs.set('limit', String(clamped));
+ if (cursor) qs.set('cursor', cursor);
+ if (direction) qs.set('direction', direction);
+ return beeperRequest(`/v1/messages/search?${qs.toString()}`, { baseUrl, token, timeoutMs, allowRetry: true });
+ }
+
+ /**
+ * Send a message. Retry is OFF (the client-wide default) — there is no
+ * idempotency key on send, so a retried POST sends a second real message.
+ */
+ export async function sendMessage(chatId, { text, replyToMessageID, attachment } = {}, { baseUrl, token, timeoutMs } = {}) {
+ return beeperRequest(`/v1/chats/${encodeURIComponent(chatId)}/messages`, {
+ method: 'POST',
+ body: { text, replyToMessageID, attachment },
+ baseUrl, token, timeoutMs,
+ });
+ }
+
+ /** Edit a message. No retry — same send-safety posture as `sendMessage`. */
+ export async function editMessage(chatId, messageId, text, { baseUrl, token, timeoutMs } = {}) {
+ return beeperRequest(`/v1/chats/${encodeURIComponent(chatId)}/messages/${encodeURIComponent(messageId)}`, {
+ method: 'PUT',
+ body: { text },
+ baseUrl, token, timeoutMs,
+ });
+ }
+
+ /**
+ * Delete (unsend) a message. `forEveryone` is REQUIRED and must be an
+ * explicit boolean — the API defaults it to `true` when omitted, unsending
+ * for every participant on networks that support it. No retry.
+ */
+ export async function deleteMessage(chatId, messageId, forEveryone, { baseUrl, token, timeoutMs } = {}) {
+ if (typeof forEveryone !== 'boolean') {
+ throw new BeeperApiError(
+ 'deleteMessage requires an explicit boolean forEveryone — Beeper defaults an omitted value to true (unsend for everyone)',
+ { status: 400, code: 'FOR_EVERYONE_REQUIRED', retryable: false },
+ );
+ }
+ return beeperRequest(
+ `/v1/chats/${encodeURIComponent(chatId)}/messages/${encodeURIComponent(messageId)}?forEveryone=${forEveryone}`,
+ { method: 'DELETE', baseUrl, token, timeoutMs },
+ );
+ }
+
+ export async function addReaction(chatId, messageId, reactionKey, { baseUrl, token, timeoutMs } = {}) {
+ return beeperRequest(`/v1/chats/${encodeURIComponent(chatId)}/messages/${encodeURIComponent(messageId)}/reactions`, {
+ method: 'POST',
+ body: { reactionKey },
+ baseUrl, token, timeoutMs,
+ });
+ }
+
+ export async function removeReaction(chatId, messageId, reactionKey, { baseUrl, token, timeoutMs } = {}) {
+ return beeperRequest(
+ `/v1/chats/${encodeURIComponent(chatId)}/messages/${encodeURIComponent(messageId)}/reactions/${encodeURIComponent(reactionKey)}`,
+ { method: 'DELETE', baseUrl, token, timeoutMs },
+ );
+ }
+
+ // ---------------------------------------------------------------------------
+ // Chat state (archive / read)
+ // ---------------------------------------------------------------------------
+
+ /** `PATCH /v1/chats/{chatID}` with `{isArchived}` — returns the updated Chat. */
+ export async function archiveChat(chatId, archived = true, { baseUrl, token, timeoutMs } = {}) {
+ return beeperRequest(`/v1/chats/${encodeURIComponent(chatId)}`, {
+ method: 'PATCH',
+ body: { isArchived: archived },
+ baseUrl, token, timeoutMs,
+ });
+ }
+
+ /**
+ * `PATCH /v1/chats/{chatID}` — the chat-state update endpoint, and the write
+ * path behind the two rail controls #9 wired (Archive, Low priority). The body
+ * is an explicit allowlist rather than a passthrough: `PATCH` also carries the
+ * draft field, and a spread of caller-supplied keys would let a route body
+ * clear a draft (or set one) as a side effect of archiving a chat.
+ *
+ * `archiveChat` above stays as the narrow archive-only spelling; this is the
+ * general form and returns the updated `Chat` either way. Retries are OFF
+ * (`beeperRequest`'s default) — a Beeper write has no idempotency key.
+ */
+ export async function updateChat(chatId, patch = {}, { baseUrl, token, timeoutMs } = {}) {
+ const body = {};
+ if (typeof patch.isArchived === 'boolean') body.isArchived = patch.isArchived;
+ if (typeof patch.isLowPriority === 'boolean') body.isLowPriority = patch.isLowPriority;
+ return beeperRequest(`/v1/chats/${encodeURIComponent(chatId)}`, {
+ method: 'PATCH',
+ body,
+ baseUrl, token, timeoutMs,
+ });
+ }
+
+ export async function markRead(chatId, { messageID } = {}, { baseUrl, token, timeoutMs } = {}) {
+ return beeperRequest(`/v1/chats/${encodeURIComponent(chatId)}/read`, {
+ method: 'POST',
+ body: messageID ? { messageID } : {},
+ baseUrl, token, timeoutMs,
+ });
+ }
+
+ export async function markUnread(chatId, { messageID } = {}, { baseUrl, token, timeoutMs } = {}) {
+ return beeperRequest(`/v1/chats/${encodeURIComponent(chatId)}/unread`, {
+ method: 'POST',
+ body: messageID ? { messageID } : {},
+ baseUrl, token, timeoutMs,
+ });
+ }
+
+ // ---------------------------------------------------------------------------
+ // Assets
+ // ---------------------------------------------------------------------------
+
+ /**
+ * `POST /v1/assets/download` — resolves an `mxc://`/`localmxc://` reference to
+ * a local file URL, returned as `{ srcURL }`. A missing/expired asset answers
+ * HTTP `200` here — NOT `502` — with `{ error: '<message>' }` and no `srcURL`
+ * (`AssetDownloadResponse` documents both fields as optional siblings on the
+ * one 200 shape; live-verified against an unresolvable `mxc://` reference).
+ * `beeperRequest` only maps non-2xx statuses, so a 200-with-`error` body would
+ * otherwise pass through as a "success" carrying no file to read. Validate the
+ * body here instead: an `error` string, or a response missing a non-empty
+ * `srcURL`, is the same terminal condition the 502 branch of
+ * `mapBeeperResponseError` exists for — `ASSET_UNAVAILABLE`, never retryable
+ * — so both failure shapes converge on the same caller-facing error. The
+ * `502`-on-`assets/serve` case (`GET`/`HEAD`, see below) is unrelated and
+ * still goes through `mapBeeperResponseError`'s status branch. Byte streaming
+ * (`GET /v1/assets/serve`, implemented below as `fetchAssetStream`/
+ * `headAsset`) and disk mirroring (`beeperAttachments.js`) are not
+ * implemented in `downloadAsset`.
+ */
+ export async function downloadAsset(url, { baseUrl, token, timeoutMs } = {}) {
+ const data = await beeperRequest('/v1/assets/download', {
+ method: 'POST',
+ body: { url },
+ baseUrl, token, timeoutMs,
+ isAssetEndpoint: true,
+ });
+ const srcURL = typeof data?.srcURL === 'string' ? data.srcURL : '';
+ if (typeof data?.error === 'string' && data.error) {
+ throw new BeeperApiError(data.error, { status: 200, code: 'ASSET_UNAVAILABLE', retryable: false });
+ }
+ if (!srcURL) {
+ throw new BeeperApiError('Beeper /v1/assets/download returned no srcURL', {
+ status: 200, code: 'ASSET_UNAVAILABLE', retryable: false,
+ });
+ }
+ return data;
+ }
+
+ /**
+ * The byte-streaming half of the asset surface (#37): `GET /v1/assets/serve`.
+ *
+ * `beeperRequest` cannot serve these — it reads every response through
+ * `readResponseJson`, which is right for the small local JSON the rest of this
+ * client speaks to and catastrophic for a 30 MB video (it would buffer the
+ * whole body in memory to hand back a `{ message: '<binary>' }`). These two
+ * functions therefore go to `fetchWithTimeout` directly and hand the caller
+ * the RAW `Response`, whose body the mirror streams to disk.
+ *
+ * What they do NOT skip is the error mapping. `serve` answers `502` for media
+ * the network has aged out — unlike `POST /v1/assets/download`, which answers
+ * 200 with an { error } body — so both run through `mapBeeperResponseError`
+ * with `isAssetEndpoint: true` — a terminal `ASSET_UNAVAILABLE`, never the
+ * ordinarily-retryable `UPSTREAM_ERROR` a generic "5xx is transient" policy
+ * would loop on forever.
+ */
+ // Time to the RESPONSE HEADERS, not to the last byte: `fetchWithTimeout` clears
+ // its abort timer once `fetch` resolves, which is the moment the headers land.
+ // Generous rather than the 15s a JSON call gets, because Beeper may have to
+ // pull the media off the network before it can answer at all. The BODY is
+ // bounded separately by the mirror's own idle-abort (`STREAM_IDLE_TIMEOUT_MS`
+ // in `beeperAttachments.js`), which is what a caller passing `signal` here is
+ // usually doing.
+ const ASSET_REQUEST_TIMEOUT_MS = 60_000;
+
+ function assetErrorFrom(response) {
+ // A `serve`/HEAD failure body is not reliably JSON (and a HEAD has no body
+ // at all), so the mapper is handed the status alone and builds its own
+ // message rather than inventing a `code` that never came from Beeper.
+ return mapBeeperResponseError(response.status, null, { isAssetEndpoint: true, retryEligible: false });
+ }
+
+ async function assetRequest(mxcId, { method, baseUrl, token, timeoutMs = ASSET_REQUEST_TIMEOUT_MS, signal } = {}) {
+ const resolved = await resolveBeeperConfig({ baseUrl, token });
+ if (!resolved.token) {
+ throw new BeeperApiError('Beeper access token is not configured', {
+ status: 401, code: 'NOT_CONFIGURED', retryable: false,
+ });
+ }
+ const reference = String(mxcId || '').trim();
+ if (!reference) {
+ throw new BeeperApiError('Beeper asset reference is empty', {
+ status: 400, code: 'BAD_REQUEST', retryable: false,
+ });
+ }
+ const url = `${resolved.baseUrl}/v1/assets/serve?url=${encodeURIComponent(reference)}`;
+ const response = await fetchWithTimeout(url, {
+ method,
+ headers: { Authorization: `Bearer ${resolved.token}` },
++ redirect: 'error',
+ signal,
+ }, timeoutMs).catch((err) => {
+ throw new BeeperApiError(`Beeper asset request failed: ${describeFetchError(err)}`, {
+ status: 0, code: 'NETWORK_ERROR', retryable: false,
+ });
+ });
+ if (!response.ok) {
+ // Drain, so an error body cannot hold the socket open.
+ await response.body?.cancel?.().catch(() => {});
+ throw assetErrorFrom(response);
+ }
+ return response;
+ }
+
+ /**
+ * `HEAD /v1/assets/serve` — the pre-flight the size ceiling and the eviction
+ * guard both key on. Returns `{ bytes }`, with `bytes: null` when the server
+ * declines to say (the absent-vs-empty rule: "unknown size" must not read as
+ * "zero bytes", which would sail under any ceiling).
+ *
+ * A `502` here is the eviction guard's whole point: it means Beeper can no
+ * longer supply the file, so the local copy is the last one and must be kept
+ * regardless of age.
+ */
+ export async function headAsset(mxcId, { baseUrl, token, timeoutMs, signal } = {}) {
+ const response = await assetRequest(mxcId, { method: 'HEAD', baseUrl, token, timeoutMs, signal });
+ const raw = response.headers?.get?.('content-length');
+ const bytes = Number(raw);
+ return { bytes: raw !== null && raw !== undefined && Number.isFinite(bytes) ? bytes : null };
+ }
+
+ /**
+ * `GET /v1/assets/serve` — the raw streaming response. The caller owns the
+ * body: it must consume or cancel it.
+ *
+ * `serve` sends NO `Content-Type` (probed live, #13), which is why the mirror
+ * stores Beeper's declared `mimeType` from the message payload and serves from
+ * that instead of sniffing anything here. `timeoutMs` covers the headers only;
+ * pass `signal` to bound the body.
+ */
+ export async function fetchAssetStream(mxcId, { baseUrl, token, timeoutMs, signal } = {}) {
+ return assetRequest(mxcId, { method: 'GET', baseUrl, token, timeoutMs, signal });
+ }
+
+ // ---------------------------------------------------------------------------
+ // Accounts / bridges
+ // ---------------------------------------------------------------------------
+
+ // Strips the top-level `loginID` field — it is the user's phone number
+ // (requirement: never log or persist it from either /v1/accounts or
+ // /v1/bridges) — and ONLY that field. This is a narrow, named boundary, not a
+ // PII allowlist: `GET /v1/spec`'s `Account.user` (a `User`) carries its own
+ // `phoneNumber`/`email`/`fullName`, and none of those are touched here — they
+ // deliberately survive into every caller of `getAccounts`/`getBridges`/
+ // `getJoinedAccounts`, because fork issue #10 (Tribe identity) needs
+ // `user.phoneNumber` from this same client. A caller that logs or persists a
+ // whole account/user row is still responsible for that PII itself.
+ function stripLoginId(account) {
+ if (!account || typeof account !== 'object') return account;
+ const { loginID, ...rest } = account;
+ return rest;
+ }
+
+ // Also strips `activeAccountCount` — documented to over-report (requirement:
+ // do not surface it) — alongside the nested loginID strip, so a bridge row
+ // never carries either field past this boundary.
+ function stripBridgeAccountsLoginId(bridge) {
+ if (!bridge || typeof bridge !== 'object') return bridge;
+ const { activeAccountCount, ...rest } = bridge;
+ return {
+ ...rest,
+ accounts: Array.isArray(bridge.accounts) ? bridge.accounts.map(stripLoginId) : bridge.accounts,
+ };
+ }
+
+ /**
+ * `GET /v1/accounts` — a BARE array, not a paginated envelope.
+ *
+ * Throws a typed `MALFORMED_RESPONSE` `BeeperApiError` when the body isn't an
+ * array, instead of coercing to `[]` — the AGENTS.md "sentinel + validate"
+ * rule (`lmStudioManager.getLastListError` is the named precedent): a 200 with
+ * a non-JSON body becomes `{ message: text }` and a blank 200 becomes `{}` via
+ * `readResponseJson`'s fallback, and both used to be indistinguishable from a
+ * genuinely empty roster. With `settings.beeper.baseUrl` user-editable (#30),
+ * any other local service answering 200 must surface as a fault here, not as
+ * "no accounts connected".
+ */
+ export async function getAccounts({ baseUrl, token, timeoutMs } = {}) {
+ const raw = await beeperRequest('/v1/accounts', { baseUrl, token, timeoutMs, allowRetry: true });
+ if (!Array.isArray(raw)) {
+ throw new BeeperApiError('Beeper API returned an unexpected /v1/accounts response shape (expected an array)', {
+ status: 502, code: 'MALFORMED_RESPONSE', retryable: false,
+ });
+ }
+ return raw.map(stripLoginId);
+ }
+
+ /**
+ * `GET /v1/bridges` — `{ items: Bridge[] }`. Deliberately does not surface
+ * `activeAccountCount` (documented to over-report; requirement: do not use it).
+ *
+ * Same "sentinel + validate" rule as `getAccounts` above: throws a typed
+ * `MALFORMED_RESPONSE` `BeeperApiError` when `items` isn't an array, instead
+ * of coercing a missing/invalid `items` to `[]`.
+ */
+ export async function getBridges({ baseUrl, token, timeoutMs } = {}) {
+ const raw = await beeperRequest('/v1/bridges', { baseUrl, token, timeoutMs, allowRetry: true });
+ if (!Array.isArray(raw?.items)) {
+ throw new BeeperApiError('Beeper API returned an unexpected /v1/bridges response shape (expected { items: [] })', {
+ status: 502, code: 'MALFORMED_RESPONSE', retryable: false,
+ });
+ }
+ return { items: raw.items.map(stripBridgeAccountsLoginId) };
+ }
+
+ /**
+ * Join accounts to their bridge by `accountID` through each bridge's nested
+ * `accounts[]` — NOT by `network` (accounts carry a display name, bridges
+ * carry a lowercase slug; that join returns zero rows). An account with no
+ * matching bridge is kept, with bridge-derived fields `null`.
+ *
+ * `statusText` is taken from the bridge only — observed live (#11) to exist
+ * only on `connected` bridge rows and never populated on the account itself,
+ * even though the account schema allows the field.
+ *
+ * Pure — no I/O — so it's testable directly against a fixture without a
+ * network mock. `getJoinedAccounts` is the I/O wrapper below.
+ */
+ export function joinAccountsWithBridges(accounts, bridgesResponse) {
+ const bridges = Array.isArray(bridgesResponse?.items) ? bridgesResponse.items : [];
+ const bridgeByAccountId = new Map();
+ for (const bridge of bridges) {
+ for (const acct of Array.isArray(bridge?.accounts) ? bridge.accounts : []) {
+ if (acct?.accountID) bridgeByAccountId.set(acct.accountID, bridge);
+ }
+ }
+ return (Array.isArray(accounts) ? accounts : []).map((account) => {
+ const safeAccount = stripLoginId(account);
+ const bridge = safeAccount?.accountID ? bridgeByAccountId.get(safeAccount.accountID) : null;
+ return {
+ ...safeAccount,
+ network: safeAccount.network ?? bridge?.network ?? null,
+ bridgeId: bridge?.id ?? null,
+ bridgeStatus: bridge?.status ?? null,
+ statusText: bridge?.statusText ?? null,
+ };
+ });
+ }
+
+ /** `getAccounts()` joined to `getBridges()` by `accountID`. */
+ export async function getJoinedAccounts({ baseUrl, token, timeoutMs } = {}) {
+ const [accounts, bridges] = await Promise.all([
+ getAccounts({ baseUrl, token, timeoutMs }),
+ getBridges({ baseUrl, token, timeoutMs }),
+ ]);
+ return joinAccountsWithBridges(accounts, bridges);
+ }
diff --cc server/services/beeperClient.test.js
index 0000000000,cb845d20b0..72cf017655
mode 000000,100644..100644
--- a/server/services/beeperClient.test.js
+++ b/server/services/beeperClient.test.js
@@@ -1,0 -1,830 +1,844 @@@
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
+ import { getSettings } from './settings.js';
+ import { resolveBeeperToken } from './beeperCredentials.js';
+ import {
+ BeeperApiError,
+ DEFAULT_BASE_URL,
+ resolveBeeperBaseUrl,
+ resolveBeeperConfig,
+ mapBeeperResponseError,
+ paginateBeeperCursor,
+ listChatsPage,
+ listChats,
+ listMessages,
+ searchChatsPage,
+ searchMessagesPage,
+ getInfo,
+ probeBeeperInfo,
+ assertValidInfoResponse,
+ getAccounts,
+ getBridges,
+ joinAccountsWithBridges,
+ getJoinedAccounts,
+ sendMessage,
+ editMessage,
+ deleteMessage,
+ downloadAsset,
++ fetchAssetStream,
+ updateChat,
+ } from './beeperClient.js';
+
+ // resolveBeeperConfig only touches settings.js (base URL) and the vault-backed
+ // credential store (token) when EITHER baseUrl or token is omitted; every other
+ // test in this file passes both explicitly and never exercises these mocks, so
+ // they're safe to hoist for the whole file. `beeperCredentials` is mocked
+ // rather than exercised because its own suite covers the vault contract and it
+ // would otherwise reach for Postgres from here.
+ vi.mock('./settings.js', () => ({ getSettings: vi.fn() }));
+ vi.mock('./beeperCredentials.js', () => ({ resolveBeeperToken: vi.fn() }));
+
+ // A fixture-shaped fake Response, matching what readResponseJson consumes
+ // (only `.text()` is read; `.ok`/`.status` drive the beeperRequest branch).
+ function jsonResponse(status, body) {
+ return { ok: status >= 200 && status < 300, status, text: async () => JSON.stringify(body) };
+ }
+
+ // A response whose body is NOT valid JSON — readResponseJson's fallback turns
+ // this into `{ message: text }`, which is the exact shape the malformed-
+ // response tests below must NOT let getAccounts/getBridges/paginateBeeperCursor
+ // coerce into an empty (but "successful") roster.
+ function nonJsonResponse(status, text) {
+ return { ok: status >= 200 && status < 300, status, text: async () => text };
+ }
+
+ describe('beeperClient', () => {
+ beforeEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ });
+
+ // -------------------------------------------------------------------------
+ // Config resolution
+ // -------------------------------------------------------------------------
+
+ describe('resolveBeeperConfig', () => {
+ it('defaults the base URL and reports no token when neither is configured', async () => {
+ vi.mocked(getSettings).mockResolvedValue({});
+ vi.mocked(resolveBeeperToken).mockResolvedValue(null);
+ const config = await resolveBeeperConfig();
+ expect(config).toEqual({ baseUrl: DEFAULT_BASE_URL, token: null });
+ });
+
+ it('reads the base URL from settings and the token from the vault-backed store (#31)', async () => {
+ vi.mocked(getSettings).mockResolvedValue({ beeper: { baseUrl: 'http://127.0.0.1:23373/' } });
+ vi.mocked(resolveBeeperToken).mockResolvedValue({ token: 'vaulted-token', tokenSource: 'oauth' });
+ const config = await resolveBeeperConfig();
+ expect(config).toEqual({ baseUrl: 'http://127.0.0.1:23373', token: 'vaulted-token' });
+ });
+
+ // The vault read throwing means "the credential cannot be read", which is
+ // NOT "no credential is configured" — collapsing the two would silently
+ // make an authenticated call anonymous.
+ it('propagates an unreadable credential store instead of resolving token:null', async () => {
+ vi.mocked(getSettings).mockResolvedValue({});
+ vi.mocked(resolveBeeperToken).mockRejectedValue(new Error('Malformed vault ciphertext'));
+ await expect(resolveBeeperConfig()).rejects.toThrow(/vault ciphertext/);
+ });
+
+ it('an explicit baseUrl + token bypasses settings entirely', async () => {
+ const config = await resolveBeeperConfig({ baseUrl: 'http://127.0.0.1:9999/', token: 'abc123' });
+ expect(config).toEqual({ baseUrl: 'http://127.0.0.1:9999', token: 'abc123' });
+ });
+
+ it('an explicit token of null is honored as "deliberately unauthenticated", not "unset"', async () => {
+ vi.mocked(resolveBeeperToken).mockClear();
+ const config = await resolveBeeperConfig({ baseUrl: DEFAULT_BASE_URL, token: null });
+ expect(config.token).toBeNull();
+ expect(resolveBeeperToken).not.toHaveBeenCalled();
+ });
+
+ // The liveness probe must never trigger a credential read: /v1/info is the
+ // one endpoint that answers unauthenticated, and a probe that decrypts the
+ // vault on every status poll would be both slower and a wider blast radius.
+ it('an explicit token (with no baseUrl) still skips the credential store', async () => {
+ vi.mocked(resolveBeeperToken).mockClear();
+ vi.mocked(getSettings).mockResolvedValue({ beeper: { baseUrl: DEFAULT_BASE_URL } });
+ const config = await resolveBeeperConfig({ token: null });
+ expect(config).toEqual({ baseUrl: DEFAULT_BASE_URL, token: null });
+ expect(resolveBeeperToken).not.toHaveBeenCalled();
+ });
+
+ // SEC-2: `getSettings()` reads `settings.json` off disk with no schema
+ // re-validation on read, so `normalizeBaseUrl` re-applies the SAME
+ // loopback-only gate `beeperSettingsSchema` enforces on the PUT route —
+ // otherwise a hand-edited settings.json is a second path to the exact
+ // value the schema exists to block.
+ it('falls back to the loopback default for a non-loopback settings baseUrl with no opt-in', async () => {
+ vi.mocked(getSettings).mockResolvedValue({ beeper: { baseUrl: 'https://example.com:23373' } });
+ vi.mocked(resolveBeeperToken).mockResolvedValue({ token: 'vaulted-token', tokenSource: 'oauth' });
+ const config = await resolveBeeperConfig();
+ expect(config).toEqual({ baseUrl: DEFAULT_BASE_URL, token: 'vaulted-token' });
+ });
+
+ it('honors a non-loopback settings baseUrl once allowNonLoopbackBaseUrl is set', async () => {
+ vi.mocked(getSettings).mockResolvedValue({
+ beeper: { baseUrl: 'https://example.com:23373', allowNonLoopbackBaseUrl: true },
+ });
+ vi.mocked(resolveBeeperToken).mockResolvedValue({ token: 'vaulted-token', tokenSource: 'oauth' });
+ const config = await resolveBeeperConfig();
+ expect(config).toEqual({ baseUrl: 'https://example.com:23373', token: 'vaulted-token' });
+ });
+
+ // The "both explicit" bypass trusts its caller rather than re-deriving the
+ // opt-in here — it exists for values a caller ALREADY resolved through
+ // `resolveBeeperBaseUrl()` (which is where the gate lives), not for a raw
+ // unvalidated string. `beeperStatus.js` is the worked example: it calls
+ // `resolveBeeperBaseUrl()` first and passes the result in here, rather
+ // than reading `settings.beeper.baseUrl` straight into this bypass.
+ it('does not re-derive the opt-in for the "both explicit" bypass — it trusts an already-resolved baseUrl', async () => {
+ const config = await resolveBeeperConfig({ baseUrl: 'https://example.com:23373', token: 'abc123' });
+ expect(config).toEqual({ baseUrl: 'https://example.com:23373', token: 'abc123' });
+ });
+ });
+
+ describe('resolveBeeperBaseUrl', () => {
+ it('falls back to the loopback default for a non-loopback settings baseUrl with no opt-in', async () => {
+ vi.mocked(getSettings).mockResolvedValue({ beeper: { baseUrl: 'http://example.com:23373' } });
+ await expect(resolveBeeperBaseUrl()).resolves.toBe(DEFAULT_BASE_URL);
+ });
+
+ it('honors a non-loopback settings baseUrl once allowNonLoopbackBaseUrl is set', async () => {
+ vi.mocked(getSettings).mockResolvedValue({
+ beeper: { baseUrl: 'http://example.com:23373', allowNonLoopbackBaseUrl: true },
+ });
+ await expect(resolveBeeperBaseUrl()).resolves.toBe('http://example.com:23373');
+ });
+ });
+
+ // -------------------------------------------------------------------------
+ // 502-is-terminal mapping
+ // -------------------------------------------------------------------------
+
+ describe('mapBeeperResponseError', () => {
+ it('maps a 502 from an asset endpoint to the terminal ASSET_UNAVAILABLE', () => {
+ const err = mapBeeperResponseError(502, { message: 'Failed to download asset: Transfer failed for mxc://abc', code: 'BRIDGE_ERROR' }, { isAssetEndpoint: true });
+ expect(err).toBeInstanceOf(BeeperApiError);
+ expect(err.code).toBe('ASSET_UNAVAILABLE');
+ expect(err.retryable).toBe(false);
+ });
+
+ it('maps a 502 from a non-asset endpoint to the ordinarily-retryable UPSTREAM_ERROR', () => {
+ const err = mapBeeperResponseError(502, { message: 'bridge unavailable' }, { isAssetEndpoint: false });
+ expect(err.code).toBe('UPSTREAM_ERROR');
+ expect(err.retryable).toBe(true);
+ });
+
+ it('maps 401 to a non-retryable UNAUTHORIZED', () => {
+ const err = mapBeeperResponseError(401, { message: 'Unauthorized: Invalid or missing token', code: 'unauthorized' });
+ expect(err.code).toBe('UNAUTHORIZED');
+ expect(err.retryable).toBe(false);
+ });
+
+ // Live-verified: POST /v1/assets/download answers HTTP 200 for an
+ // unresolvable mxc:// reference, with an `{ error }` body and no `srcURL`
+ // — never a 502. beeperRequest treats any `response.ok` body as success,
+ // so downloadAsset itself must reject a 200 body shaped like a failure.
+ it('downloadAsset end-to-end surfaces ASSET_UNAVAILABLE on a live 200-with-error body', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(
+ jsonResponse(200, { error: 'Failed to download asset: Transfer failed for mxc://gone' }),
+ ));
+ await expect(downloadAsset('mxc://gone', { baseUrl: DEFAULT_BASE_URL, token: 't' }))
+ .rejects.toMatchObject({ code: 'ASSET_UNAVAILABLE', retryable: false });
+ });
+
+ it('downloadAsset also rejects a 200 body with neither an error nor a srcURL', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse(200, {})));
+ await expect(downloadAsset('mxc://odd', { baseUrl: DEFAULT_BASE_URL, token: 't' }))
+ .rejects.toMatchObject({ code: 'ASSET_UNAVAILABLE', retryable: false });
+ });
+
+ it('downloadAsset resolves with the body when srcURL is a non-empty string', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(
+ jsonResponse(200, { srcURL: 'file:///tmp/example.png' }),
+ ));
+ await expect(downloadAsset('mxc://ok', { baseUrl: DEFAULT_BASE_URL, token: 't' }))
+ .resolves.toEqual({ srcURL: 'file:///tmp/example.png' });
+ });
+
+ // The mapper's asset-502 branch above still applies to GET/HEAD
+ // /v1/assets/serve — the byte-streaming half of the asset surface — which
+ // really does answer 502 for a missing/expired asset (live-verified).
+ // downloadAsset (POST /v1/assets/download) is the one caller that never
+ // reaches this branch, per the two tests above.
+ });
+
+ // -------------------------------------------------------------------------
+ // Cursor pagination / exhaustion
+ // -------------------------------------------------------------------------
+
+ describe('paginateBeeperCursor', () => {
+ it('walks every page until hasMore is false', async () => {
+ const pages = [
+ { items: ['a', 'b'], hasMore: true, oldestCursor: 'c1', newestCursor: null },
+ { items: ['c'], hasMore: true, oldestCursor: 'c2', newestCursor: null },
+ { items: ['d'], hasMore: false, oldestCursor: null, newestCursor: null },
+ ];
+ const fetchPage = vi.fn(async ({ cursor }) => {
+ if (!cursor) return pages[0];
+ if (cursor === 'c1') return pages[1];
+ if (cursor === 'c2') return pages[2];
+ throw new Error(`unexpected cursor ${cursor}`);
+ });
+
+ const collected = [];
+ for await (const item of paginateBeeperCursor(fetchPage)) collected.push(item);
+
+ expect(collected).toEqual(['a', 'b', 'c', 'd']);
+ expect(fetchPage).toHaveBeenCalledTimes(3);
+ });
+
+ it('stops (does not loop forever) when hasMore is true but the walked cursor is null', async () => {
+ const fetchPage = vi.fn(async () => ({ items: ['only'], hasMore: true, oldestCursor: null, newestCursor: null }));
+ const collected = [];
+ for await (const item of paginateBeeperCursor(fetchPage)) collected.push(item);
+ expect(collected).toEqual(['only']);
+ expect(fetchPage).toHaveBeenCalledTimes(1);
+ });
+
+ it('stops (does not loop forever) when a server echoes back the same cursor it was just called with', async () => {
+ // hasMore stays true and oldestCursor never advances past 'stuck' — a
+ // naive loop would walk in place forever.
+ const fetchPage = vi.fn(async () => ({ items: ['x'], hasMore: true, oldestCursor: 'stuck', newestCursor: null }));
+ const collected = [];
+ for await (const item of paginateBeeperCursor(fetchPage)) collected.push(item);
+ expect(collected).toEqual(['x', 'x']);
+ expect(fetchPage).toHaveBeenCalledTimes(2);
+ });
+
+ it('yields nothing and makes one call for a single empty page', async () => {
+ const fetchPage = vi.fn(async () => ({ items: [], hasMore: false }));
+ const collected = [];
+ for await (const item of paginateBeeperCursor(fetchPage)) collected.push(item);
+ expect(collected).toEqual([]);
+ expect(fetchPage).toHaveBeenCalledTimes(1);
+ });
+
+ it('throws MALFORMED_RESPONSE instead of silently treating a missing items array as exhausted', async () => {
+ const fetchPage = vi.fn(async () => ({ hasMore: false }));
+ const collected = [];
+ await expect((async () => {
+ for await (const item of paginateBeeperCursor(fetchPage)) collected.push(item);
+ })()).rejects.toMatchObject({ code: 'MALFORMED_RESPONSE', retryable: false });
+ expect(collected).toEqual([]);
+ });
+
+ it('throws MALFORMED_RESPONSE when a later page (not the first) has a non-array items', async () => {
+ const fetchPage = vi.fn(async ({ cursor }) => (!cursor
+ ? { items: ['a'], hasMore: true, oldestCursor: 'c1' }
+ : { items: 'not-an-array', hasMore: true, oldestCursor: 'c2' }));
+ const collected = [];
+ await expect((async () => {
+ for await (const item of paginateBeeperCursor(fetchPage)) collected.push(item);
+ })()).rejects.toMatchObject({ code: 'MALFORMED_RESPONSE', retryable: false });
+ expect(collected).toEqual(['a']);
+ });
+
+ it('walks newestCursor when direction is "after"', async () => {
+ const fetchPage = vi.fn(async ({ cursor }) => (!cursor
+ ? { items: [1], hasMore: true, oldestCursor: null, newestCursor: 'n1' }
+ : { items: [2], hasMore: false }));
+ const collected = [];
+ for await (const item of paginateBeeperCursor(fetchPage, { direction: 'after' })) collected.push(item);
+ expect(collected).toEqual([1, 2]);
+ expect(fetchPage).toHaveBeenNthCalledWith(2, { cursor: 'n1', direction: 'after' });
+ });
+
+ it('listChats/listMessages iterators drive listChatsPage/listMessagesPage across real HTTP pages', async () => {
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(jsonResponse(200, { items: [{ id: 'chat1' }], hasMore: true, oldestCursor: 'cur1' }))
+ .mockResolvedValueOnce(jsonResponse(200, { items: [{ id: 'chat2' }], hasMore: false }));
+ vi.stubGlobal('fetch', fetchMock);
+
+ const chats = [];
+ for await (const chat of listChats({ baseUrl: DEFAULT_BASE_URL, token: 't' })) chats.push(chat);
+ expect(chats.map((c) => c.id)).toEqual(['chat1', 'chat2']);
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(fetchMock.mock.calls[1][0]).toContain('cursor=cur1');
+ });
+ });
+
+ // -------------------------------------------------------------------------
+ // probeBeeperInfo body-shape check (#30 — a wave-one reviewer requirement:
+ // a 200 with an unexpected body must not be reported as a healthy probe)
+ // -------------------------------------------------------------------------
+
+ describe('probeBeeperInfo / assertValidInfoResponse', () => {
+ it('reports reachable:true for a well-shaped /v1/info body', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(
+ jsonResponse(200, { app: { name: 'Beeper', version: '4.3.73' }, server: { status: 'running' } }),
+ ));
+ const result = await probeBeeperInfo({ baseUrl: DEFAULT_BASE_URL });
+ expect(result).toEqual({
+ reachable: true, info: expect.objectContaining({ app: expect.any(Object) }), error: null, timedOut: false, latencyMs: expect.any(Number),
+ });
+ });
+
+ it('reports reachable:false — not true — for a 200 whose body is not the documented /v1/info shape', async () => {
+ // A misconfigured settings.beeper.baseUrl (#30 makes it user-editable)
+ // could point at some other local HTTP service that happens to answer
+ // 200 with an unrelated JSON body. The transport succeeded but this is
+ // not Beeper, so it must never read as a healthy probe.
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse(200, { ok: true })));
+ const result = await probeBeeperInfo({ baseUrl: DEFAULT_BASE_URL });
+ expect(result.reachable).toBe(false);
+ expect(result.info).toBeNull();
+ expect(result.error).toMatch(/unexpected \/v1\/info response shape/);
+ });
+
+ it('reports reachable:false for a 200 with a blank/non-JSON body', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(nonJsonResponse(200, '')));
+ const result = await probeBeeperInfo({ baseUrl: DEFAULT_BASE_URL });
+ expect(result.reachable).toBe(false);
+ expect(result.error).toMatch(/unexpected \/v1\/info response shape/);
+ });
+
+ it('assertValidInfoResponse throws a typed MALFORMED_RESPONSE BeeperApiError directly', () => {
+ expect(() => assertValidInfoResponse({ app: { name: '' }, server: { status: 'running' } }))
+ .toThrow(expect.objectContaining({ code: 'MALFORMED_RESPONSE', status: 502 }));
+ expect(() => assertValidInfoResponse(null)).toThrow(BeeperApiError);
+ expect(() => assertValidInfoResponse({ app: { name: 'Beeper' }, server: { status: 'running' } })).not.toThrow();
+ });
+
+ // Fork issue #61, decision 7: `timedOut` is what `beeperStatus.js` reads to
+ // tell "briefly slow" from "genuinely closed" — a fast refusal (nothing
+ // listening) must never be mistaken for a timeout, or a closed Beeper
+ // Desktop could ride a stale recent-success window into a false "slow".
+ it('reports timedOut:false for a fast connection refusal, distinct from an abort', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockRejectedValue(Object.assign(new TypeError('fetch failed'), { cause: { code: 'ECONNREFUSED' } })));
+ const result = await probeBeeperInfo({ baseUrl: DEFAULT_BASE_URL });
+ expect(result.reachable).toBe(false);
+ expect(result.timedOut).toBe(false);
+ });
+ });
+
+ // -------------------------------------------------------------------------
+ // Timeout behaviour with injected time (no real sleeps)
+ // -------------------------------------------------------------------------
+
+ describe('timeout behavior (fake timers)', () => {
+ // Fork issue #61, decision 7: 1s proved too tight for a briefly-busy Beeper
+ // Desktop, so the cap moved to 3s.
+ it('probeBeeperInfo caps at 3s and resolves reachable:false/timedOut:true without throwing, and without a real sleep', async () => {
+ vi.useFakeTimers();
+ try {
+ vi.stubGlobal('fetch', vi.fn().mockImplementation((_url, opts) =>
+ new Promise((_resolve, reject) => {
+ opts.signal.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError')));
+ })));
+
+ const probePromise = probeBeeperInfo({ baseUrl: DEFAULT_BASE_URL });
+ // Advance virtual time only — a real 3s sleep here would fail CI timing
+ // budgets and defeats the point of injected time.
+ await vi.advanceTimersByTimeAsync(3000);
+ const result = await probePromise;
+
+ expect(result.reachable).toBe(false);
+ expect(result.error).toBeTruthy();
+ // The abort IS the timeout — this is the signal `beeperStatus.js` reads
+ // to decide `slow` vs `unreachable` (fork issue #61, decision 7), so a
+ // regression here is silent everywhere downstream.
+ expect(result.timedOut).toBe(true);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('a read call (allowRetry) retries a replayable connection error using injected delay, not a real sleep', async () => {
+ vi.useFakeTimers();
+ try {
+ const fetchMock = vi.fn()
+ .mockRejectedValueOnce(Object.assign(new TypeError('fetch failed'), { cause: { code: 'ECONNRESET' } }))
+ .mockResolvedValueOnce(jsonResponse(200, { items: [], hasMore: false }));
+ vi.stubGlobal('fetch', fetchMock);
+
+ const promise = listChatsPage({ baseUrl: DEFAULT_BASE_URL, token: 't' });
+ // Let the first attempt's rejection settle, then advance past the
+ // retry delay entirely in virtual time.
+ await vi.advanceTimersByTimeAsync(400);
+ const result = await promise;
+
+ expect(result).toEqual({ items: [], hasMore: false });
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('getInfo does not retry (unauthenticated probe, no allowRetry) — a connection error surfaces immediately', async () => {
+ const fetchMock = vi.fn().mockRejectedValue(Object.assign(new TypeError('fetch failed'), { cause: { code: 'ECONNREFUSED' } }));
+ vi.stubGlobal('fetch', fetchMock);
+
+ await expect(getInfo({ baseUrl: DEFAULT_BASE_URL })).rejects.toMatchObject({ code: 'NETWORK_ERROR' });
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ // -------------------------------------------------------------------------
+ // Send-safe retries
+ // -------------------------------------------------------------------------
+
+ describe('send-safe retries', () => {
++ it('refuses redirects for message bodies and attachment requests', async () => {
++ const fetchMock = vi.fn().mockRejectedValue(new TypeError('unexpected redirect'));
++ vi.stubGlobal('fetch', fetchMock);
++
++ await expect(sendMessage('chat1', { text: 'Example private message' }, { baseUrl: DEFAULT_BASE_URL, token: 'example-token' }))
++ .rejects.toMatchObject({ code: 'NETWORK_ERROR', retryable: false });
++ await expect(fetchAssetStream('mxc://example.com/asset', { baseUrl: DEFAULT_BASE_URL, token: 'example-token' }))
++ .rejects.toMatchObject({ code: 'NETWORK_ERROR', retryable: false });
++
++ expect(fetchMock).toHaveBeenCalledTimes(2);
++ for (const [, options] of fetchMock.mock.calls) expect(options.redirect).toBe('error');
++ });
++
+ it('sendMessage does NOT retry a replayable connection error — a retry would duplicate a real message', async () => {
+ const fetchMock = vi.fn().mockRejectedValue(Object.assign(new TypeError('fetch failed'), { cause: { code: 'ECONNRESET' } }));
+ vi.stubGlobal('fetch', fetchMock);
+
+ await expect(sendMessage('chat1', { text: 'hi' }, { baseUrl: DEFAULT_BASE_URL, token: 't' }))
+ .rejects.toMatchObject({ code: 'NETWORK_ERROR', retryable: false });
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('sendMessage rejects with retryable: false on a 429 too — a write\'s thrown error must never advertise retry-safety, regardless of status', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(jsonResponse(429, { message: 'Too Many Requests' }));
+ vi.stubGlobal('fetch', fetchMock);
+
+ await expect(sendMessage('chat1', { text: 'hi' }, { baseUrl: DEFAULT_BASE_URL, token: 't' }))
+ .rejects.toMatchObject({ code: 'RATE_LIMITED', retryable: false });
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('editMessage rejects with retryable: false on a 502 — same write send-safety posture as sendMessage', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(jsonResponse(502, { message: 'Bad Gateway' }));
+ vi.stubGlobal('fetch', fetchMock);
+
+ await expect(editMessage('chat1', 'msg1', 'edited text', { baseUrl: DEFAULT_BASE_URL, token: 't' }))
+ .rejects.toMatchObject({ code: 'UPSTREAM_ERROR', retryable: false });
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('updateChat does NOT retry a replayable connection error — it is a write, like every other chat-state PATCH', async () => {
+ const fetchMock = vi.fn().mockRejectedValue(Object.assign(new TypeError('fetch failed'), { cause: { code: 'ECONNRESET' } }));
+ vi.stubGlobal('fetch', fetchMock);
+
+ await expect(updateChat('chat1', { isArchived: true }, { baseUrl: DEFAULT_BASE_URL, token: 't' }))
+ .rejects.toMatchObject({ code: 'NETWORK_ERROR', retryable: false });
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('updateChat sends ONLY the two allowlisted flags — a PATCH body spread could clear the chat draft as a side effect', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(jsonResponse(200, { id: 'chat1', isArchived: true }));
+ vi.stubGlobal('fetch', fetchMock);
+
+ await updateChat(
+ 'chat1',
+ { isArchived: true, isLowPriority: false, draft: { text: 'nope' }, isPinned: true },
+ { baseUrl: DEFAULT_BASE_URL, token: 't' },
+ );
+
+ const [, init] = fetchMock.mock.calls[0];
+ expect(JSON.parse(init.body)).toEqual({ isArchived: true, isLowPriority: false });
+ });
+
+ it('a read call (allowRetry) still surfaces retryable: true on a 500 — the write clamp above must not leak into reads', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(jsonResponse(500, { message: 'Internal Server Error' }));
+ vi.stubGlobal('fetch', fetchMock);
+
+ await expect(listChatsPage({ baseUrl: DEFAULT_BASE_URL, token: 't' }))
+ .rejects.toMatchObject({ code: 'INTERNAL_ERROR', retryable: true });
+ });
+
+ it('deleteMessage requires an explicit boolean forEveryone and never calls fetch without one', async () => {
+ const fetchMock = vi.fn();
+ vi.stubGlobal('fetch', fetchMock);
+
+ await expect(deleteMessage('chat1', 'msg1', undefined, { baseUrl: DEFAULT_BASE_URL, token: 't' }))
+ .rejects.toMatchObject({ code: 'FOR_EVERYONE_REQUIRED' });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('deleteMessage passes forEveryone=false explicitly in the query string', async () => {
+ const fetchMock = vi.fn().mockResolvedValue({ ok: true, status: 204, text: async () => '' });
+ vi.stubGlobal('fetch', fetchMock);
+
+ await deleteMessage('chat1', 'msg1', false, { baseUrl: DEFAULT_BASE_URL, token: 't' });
+ expect(fetchMock.mock.calls[0][0]).toContain('forEveryone=false');
+ });
+ });
+
+ // -------------------------------------------------------------------------
+ // Accounts / bridges join on a fixture where the `network` join is zero rows
+ // -------------------------------------------------------------------------
+
+ describe('joinAccountsWithBridges', () => {
+ // Deliberately fake identifiers per repo privacy rules — no real handles,
+ // phone numbers, hostnames, or message bodies. `user` is shaped like the
+ // live `Account.user` (a `User`, per `GET /v1/spec`) — carrying its own
+ // `phoneNumber`/`email`/`fullName` — so a test against this fixture would
+ // actually catch a leak of those fields, not just of the flat `id` the
+ // old `{ id: 'user-1' }` fixture had no way to catch.
+ const accounts = [
+ {
+ accountID: 'discordgo',
+ network: 'Discord', // display name
+ status: 'connected',
+ loginID: '+15550000001', // must never survive into the joined output
+ user: {
+ id: 'user-1',
+ username: 'example-user-1',
+ isSelf: true,
+ phoneNumber: '+15550000001', // deliberately SURVIVES — fork issue #10 needs it
+ email: '[email protected]', // deliberately SURVIVES
+ fullName: 'Alice Example', // deliberately SURVIVES
+ },
+ },
+ {
+ accountID: 'local-whatsapp_ba_example',
+ network: 'WhatsApp', // display name
+ status: 'connection_required',
+ loginID: '+15550000002',
+ user: {
+ id: 'user-2',
+ username: 'example-user-2',
+ isSelf: true,
+ phoneNumber: '+15550000002',
+ email: '[email protected]',
+ fullName: 'Bob Example',
+ },
+ },
+ {
+ accountID: 'orphan-account',
+ network: 'Mystery Network',
+ status: 'connected',
+ // no matching bridge below — must be tolerated, not dropped
+ },
+ ];
+
+ const bridgesResponse = {
+ items: [
+ {
+ id: 'bridge-discord',
+ network: 'discord', // lowercase slug — differs from account.network 'Discord'
+ status: 'connected',
+ statusText: 'Connected',
+ supportsMultipleAccounts: false,
+ activeAccountCount: 3, // must never survive — documented to over-report
+ accounts: [{ accountID: 'discordgo', loginID: '+15550000001', user: { id: 'user-1', phoneNumber: '+15550000001' } }],
+ },
+ {
+ id: 'bridge-whatsapp',
+ network: 'whatsapp', // lowercase slug — differs from account.network 'WhatsApp'
+ status: 'connection_required',
+ statusText: null,
+ activeAccountCount: 1,
+ accounts: [{ accountID: 'local-whatsapp_ba_example', loginID: '+15550000002', user: { id: 'user-2', phoneNumber: '+15550000002' } }],
+ },
+ ],
+ };
+
+ it('joins on accountID even though every account.network differs from its bridge.network (the network join is zero rows)', () => {
+ // Prove the trap: naive equality on network would match nothing.
+ const naiveMatches = accounts.filter((a) => bridgesResponse.items.some((b) => b.network === a.network));
+ expect(naiveMatches).toHaveLength(0);
+
+ const joined = joinAccountsWithBridges(accounts, bridgesResponse);
+ const discord = joined.find((a) => a.accountID === 'discordgo');
+ const whatsapp = joined.find((a) => a.accountID === 'local-whatsapp_ba_example');
+
+ expect(discord.bridgeId).toBe('bridge-discord');
+ expect(discord.statusText).toBe('Connected');
+ expect(whatsapp.bridgeId).toBe('bridge-whatsapp');
+ expect(whatsapp.statusText).toBeNull();
+ });
+
+ it('tolerates an account with no matching bridge', () => {
+ const joined = joinAccountsWithBridges(accounts, bridgesResponse);
+ const orphan = joined.find((a) => a.accountID === 'orphan-account');
+ expect(orphan).toMatchObject({ bridgeId: null, bridgeStatus: null, statusText: null });
+ });
+
+ it('never surfaces loginID in the joined output', () => {
+ const joined = joinAccountsWithBridges(accounts, bridgesResponse);
+ for (const account of joined) expect(account).not.toHaveProperty('loginID');
+ });
+
+ it('strips ONLY loginID — nested user.phoneNumber/email/fullName deliberately survive the join (fork issue #10 needs user.phoneNumber for Tribe identity)', () => {
+ const joined = joinAccountsWithBridges(accounts, bridgesResponse);
+ const discord = joined.find((a) => a.accountID === 'discordgo');
+ expect(discord).not.toHaveProperty('loginID');
+ expect(discord.user).toMatchObject({
+ phoneNumber: '+15550000001',
+ email: '[email protected]',
+ fullName: 'Alice Example',
+ });
+ });
+
+ it('getAccounts / getBridges strip loginID and activeAccountCount at the client boundary too, before any join — but deliberately leave nested user PII (phoneNumber/email/fullName) intact', async () => {
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(jsonResponse(200, accounts))
+ .mockResolvedValueOnce(jsonResponse(200, bridgesResponse));
+ vi.stubGlobal('fetch', fetchMock);
+
+ const [gotAccounts, gotBridges] = await Promise.all([
+ getAccounts({ baseUrl: DEFAULT_BASE_URL, token: 't' }),
+ getBridges({ baseUrl: DEFAULT_BASE_URL, token: 't' }),
+ ]);
+
+ for (const account of gotAccounts) expect(account).not.toHaveProperty('loginID');
+ expect(gotAccounts.find((a) => a.accountID === 'discordgo').user).toMatchObject({ phoneNumber: '+15550000001' });
+
+ for (const bridge of gotBridges.items) {
+ expect(bridge).not.toHaveProperty('activeAccountCount');
+ for (const account of bridge.accounts) expect(account).not.toHaveProperty('loginID');
+ }
+ expect(gotBridges.items[0].accounts[0].user).toMatchObject({ phoneNumber: '+15550000001' });
+ });
+
+ it('getJoinedAccounts wires getAccounts + getBridges through the fetch layer end-to-end', async () => {
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(jsonResponse(200, accounts))
+ .mockResolvedValueOnce(jsonResponse(200, bridgesResponse));
+ vi.stubGlobal('fetch', fetchMock);
+
+ const joined = await getJoinedAccounts({ baseUrl: DEFAULT_BASE_URL, token: 't' });
+ expect(joined.find((a) => a.accountID === 'discordgo').bridgeId).toBe('bridge-discord');
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+ });
+
+ // -------------------------------------------------------------------------
+ // Malformed response shapes — must throw a typed MALFORMED_RESPONSE error,
+ // never silently coerce to an empty roster (AGENTS.md "sentinel + validate":
+ // absent/failed/invalid must never collapse into "legitimately empty").
+ // -------------------------------------------------------------------------
+
+ describe('getAccounts / getBridges malformed response', () => {
+ it('getAccounts throws MALFORMED_RESPONSE (not an empty roster) on a 200 with a non-JSON body', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(nonJsonResponse(200, 'not json at all')));
+ await expect(getAccounts({ baseUrl: DEFAULT_BASE_URL, token: 't' }))
+ .rejects.toMatchObject({ code: 'MALFORMED_RESPONSE', retryable: false });
+ });
+
+ it('getAccounts throws MALFORMED_RESPONSE on a 200 object body where an array is expected', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse(200, { accounts: [] })));
+ await expect(getAccounts({ baseUrl: DEFAULT_BASE_URL, token: 't' }))
+ .rejects.toMatchObject({ code: 'MALFORMED_RESPONSE', retryable: false });
+ });
+
+ it('getAccounts throws MALFORMED_RESPONSE on a blank 200 body (readResponseJson\'s emptyValue {})', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(nonJsonResponse(200, '')));
+ await expect(getAccounts({ baseUrl: DEFAULT_BASE_URL, token: 't' }))
+ .rejects.toMatchObject({ code: 'MALFORMED_RESPONSE', retryable: false });
+ });
+
+ it('getBridges throws MALFORMED_RESPONSE (not an empty roster) on a 200 with a non-JSON body', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(nonJsonResponse(200, 'not json at all')));
+ await expect(getBridges({ baseUrl: DEFAULT_BASE_URL, token: 't' }))
+ .rejects.toMatchObject({ code: 'MALFORMED_RESPONSE', retryable: false });
+ });
+
+ it('getBridges throws MALFORMED_RESPONSE on a 200 body whose items is not an array', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse(200, { items: 'not-an-array' })));
+ await expect(getBridges({ baseUrl: DEFAULT_BASE_URL, token: 't' }))
+ .rejects.toMatchObject({ code: 'MALFORMED_RESPONSE', retryable: false });
+ });
+
+ it('a genuinely empty roster (200 with []/{ items: [] }) is NOT malformed — still resolves empty', async () => {
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(jsonResponse(200, []))
+ .mockResolvedValueOnce(jsonResponse(200, { items: [] }));
+ vi.stubGlobal('fetch', fetchMock);
+
+ await expect(getAccounts({ baseUrl: DEFAULT_BASE_URL, token: 't' })).resolves.toEqual([]);
+ await expect(getBridges({ baseUrl: DEFAULT_BASE_URL, token: 't' })).resolves.toEqual({ items: [] });
+ });
+ });
+
+ // -------------------------------------------------------------------------
+ // Search endpoint limit clamping (limit max 20 on /v1/messages/search)
+ // -------------------------------------------------------------------------
+
+ describe('searchMessagesPage limit clamping', () => {
+ it('clamps an over-cap limit to 20 rather than passing it through unbounded', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(jsonResponse(200, { items: [], hasMore: false, chats: {} }));
+ vi.stubGlobal('fetch', fetchMock);
+
+ await searchMessagesPage({ query: 'hello', limit: 500, baseUrl: DEFAULT_BASE_URL, token: 't' });
+ expect(fetchMock.mock.calls[0][0]).toContain('limit=20');
+ });
+
+ it('defaults limit to 20 when omitted', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(jsonResponse(200, { items: [], hasMore: false }));
+ vi.stubGlobal('fetch', fetchMock);
+
+ await searchMessagesPage({ query: 'hello', baseUrl: DEFAULT_BASE_URL, token: 't' });
+ expect(fetchMock.mock.calls[0][0]).toContain('limit=20');
+ });
+ });
+
+ // -------------------------------------------------------------------------
+ // Array query params (accountIDs, chatIDs, mediaTypes) must serialize as
+ // repeated keys, not one comma-joined value the server reads as a single id.
+ // -------------------------------------------------------------------------
+
+ describe('array query param serialization', () => {
+ it('searchMessagesPage serializes an array filter (accountIDs) as repeated keys, not comma-joined', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(jsonResponse(200, { items: [], hasMore: false }));
+ vi.stubGlobal('fetch', fetchMock);
+
+ await searchMessagesPage({ query: 'hello', accountIDs: ['acct-a', 'acct-b'], baseUrl: DEFAULT_BASE_URL, token: 't' });
+ const url = fetchMock.mock.calls[0][0];
+ const params = new URL(url).searchParams;
+ expect(params.getAll('accountIDs')).toEqual(['acct-a', 'acct-b']);
+ expect(url).not.toContain('acct-a%2Cacct-b');
+ });
+
+ it('searchChatsPage serializes an array filter (chatIDs) as repeated keys, not comma-joined', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(jsonResponse(200, { items: [], hasMore: false }));
+ vi.stubGlobal('fetch', fetchMock);
+
+ await searchChatsPage({ chatIDs: ['chat-a', 'chat-b'], baseUrl: DEFAULT_BASE_URL, token: 't' });
+ const url = fetchMock.mock.calls[0][0];
+ const params = new URL(url).searchParams;
+ expect(params.getAll('chatIDs')).toEqual(['chat-a', 'chat-b']);
+ expect(url).not.toContain('chat-a%2Cchat-b');
+ });
+
+ // #32: the ingestion sweep pages ONE account at a time so every chat row is
+ // attributable to the account whose cursor bounds it. `GET /v1/chats` takes
+ // no `limit`, so `accountIDs` is its only filter and has to survive into the
+ // query string as repeated keys.
+ it('listChatsPage sends accountIDs as repeated keys alongside cursor and direction', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(jsonResponse(200, { items: [], hasMore: false }));
+ vi.stubGlobal('fetch', fetchMock);
+
+ await listChatsPage({
+ accountIDs: ['acct-a', 'acct-b'], cursor: 'cur1', direction: 'after', baseUrl: DEFAULT_BASE_URL, token: 't',
+ });
+ const url = fetchMock.mock.calls[0][0];
+ const params = new URL(url).searchParams;
+ expect(params.getAll('accountIDs')).toEqual(['acct-a', 'acct-b']);
+ expect(params.get('cursor')).toBe('cur1');
+ expect(params.get('direction')).toBe('after');
+ expect(url).not.toContain('acct-a%2Cacct-b');
+ expect(url).not.toContain('limit=');
+ });
+
+ it('listChatsPage omits accountIDs entirely when unset — an empty filter must not read as "match nothing"', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(jsonResponse(200, { items: [], hasMore: false }));
+ vi.stubGlobal('fetch', fetchMock);
+
+ await listChatsPage({ baseUrl: DEFAULT_BASE_URL, token: 't' });
+ const url = fetchMock.mock.calls[0][0];
+ expect(url).not.toContain('accountIDs');
+ expect(new URL(url).searchParams.get('direction')).toBe('before');
+ });
+
+ it('the listChats iterator carries accountIDs onto every page it walks', async () => {
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(jsonResponse(200, { items: [{ id: 'chat1' }], hasMore: true, oldestCursor: 'cur1' }))
+ .mockResolvedValueOnce(jsonResponse(200, { items: [{ id: 'chat2' }], hasMore: false }));
+ vi.stubGlobal('fetch', fetchMock);
+
+ const chats = [];
+ for await (const chat of listChats({ accountIDs: ['acct-a'], baseUrl: DEFAULT_BASE_URL, token: 't' })) chats.push(chat);
+ expect(chats.map((c) => c.id)).toEqual(['chat1', 'chat2']);
+ for (const call of fetchMock.mock.calls) {
+ expect(new URL(call[0]).searchParams.getAll('accountIDs')).toEqual(['acct-a']);
+ }
+ });
+
+ it('a scalar filter still serializes as a single key (no regression from the array path)', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(jsonResponse(200, { items: [], hasMore: false }));
+ vi.stubGlobal('fetch', fetchMock);
+
+ await searchMessagesPage({ query: 'hello', chatType: 'group', baseUrl: DEFAULT_BASE_URL, token: 't' });
+ const params = new URL(fetchMock.mock.calls[0][0]).searchParams;
+ expect(params.getAll('chatType')).toEqual(['group']);
+ });
+ });
+
+ // -------------------------------------------------------------------------
+ // Auth requirement
+ // -------------------------------------------------------------------------
+
+ describe('auth requirement', () => {
+ it('an authenticated call with no token configured fails fast with NOT_CONFIGURED, without calling fetch', async () => {
+ const fetchMock = vi.fn();
+ vi.stubGlobal('fetch', fetchMock);
+
+ await expect(getAccounts({ baseUrl: DEFAULT_BASE_URL, token: null }))
+ .rejects.toMatchObject({ code: 'NOT_CONFIGURED' });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('getInfo requires no token (the one unauthenticated endpoint) and sends no Authorization header', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(jsonResponse(200, { app: { name: 'Beeper' } }));
+ vi.stubGlobal('fetch', fetchMock);
+
+ await getInfo({ baseUrl: DEFAULT_BASE_URL });
+ const [, opts] = fetchMock.mock.calls[0];
+ expect(opts.headers.Authorization).toBeUndefined();
+ });
+
+ it('an authenticated call sends the configured token as an Authorization: Bearer header', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(jsonResponse(200, []));
+ vi.stubGlobal('fetch', fetchMock);
+
+ await getAccounts({ baseUrl: DEFAULT_BASE_URL, token: 'secret-token' });
+ const [, opts] = fetchMock.mock.calls[0];
+ expect(opts.headers.Authorization).toBe('Bearer secret-token');
+ });
+ });
+ });
diff --cc server/services/beeperConversations.db.test.js
index 0000000000,5a7609b848..2b35730d25
mode 000000,100644..100644
--- a/server/services/beeperConversations.db.test.js
+++ b/server/services/beeperConversations.db.test.js
@@@ -1,0 -1,301 +1,301 @@@
+ /**
+ * Postgres-backed query-plan tests for the Beeper conversation/message list
+ * paths (audit cluster 06 — indexes and query plans). The unit suite
+ * (`beeperConversations.test.js`) mocks the database and pins query SHAPE;
- * this file proves the shape a real planner chooses, against real indexes, on
- * a real seeded dataset — the plans proven on a small seeded database only,
- * not measured against a large mirror.
++ * this file proves that the indexes can serve ordered reads on a real seeded
++ * dataset, alongside service pagination and eviction-order behavior. It does
++ * not measure which plan an unrestricted planner chooses for a large mirror.
+ *
- * `SET LOCAL enable_seqscan = off` (inside a throwaway transaction) is used to
- * make these plans deterministic: Postgres's planner prefers a sequential
- * scan below some row-count threshold regardless of which indexes exist, on a
- * table small enough for a test to seed and tear down quickly. Forcing the
- * planner away from a seq scan does not change what is being asserted — the
++ * Sequential and bitmap scans are disabled inside the EXPLAIN transaction:
++ * on small fixtures PostgreSQL may prefer either a sequential scan or a
++ * bitmap scan followed by a tiny sort even when an ordered index exists.
++ * Restricting those alternatives does not change what is being asserted — the
+ * point is that an index CAN serve the query's ORDER BY / keyset predicate
+ * with no extra Sort node, which this reveals whether or not the planner
+ * would have picked it unprompted at this row count.
+ *
+ * `*.db.test.js` → runs ONLY via `npm run test:db` against `portos_test`
+ * (registered in vitest.config.db.js's DB_TEST_INCLUDE — a `<name>.db.test.js`
+ * file is not auto-globbed). Every fixture value is invented per root
+ * AGENTS.md Sensitive Data & Privacy — no real handle, name, or content.
+ */
+ import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+ import { checkHealth, ensureSchema, close, query, withTransaction } from '../lib/db.js';
+ import { requireDbOrSkip } from '../lib/dbTestGate.js';
+ import { listConversations, listMessages } from './beeperConversations.js';
+
+ let dbReady = false;
+ let skipReason = '';
+ {
+ const health = await checkHealth().catch((e) => ({ connected: false, error: e?.message }));
+ if (!health.connected) {
+ skipReason = `Postgres not reachable (${health.error || 'no connection'})`;
+ } else {
+ await ensureSchema().catch(() => {});
+ dbReady = true;
+ }
+ }
+ const runDb = requireDbOrSkip('services/beeperConversations.db.test', dbReady, skipReason);
+
+ const nonce = `beeperconv-test-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
+ const ACCOUNT_ID = nonce;
+ const NETWORK = nonce;
+ const CONV_COUNT = 12;
+ const MESSAGES_PER_CONV = 4;
+ const conversationIds = [];
+ const msgId = (convIdx, j) => `${nonce}-conv${convIdx}-msg${j}`;
+
+ /**
+ * Run one read-only statement inside a throwaway transaction with
- * `enable_seqscan` disabled for that transaction alone (`SET LOCAL` resets on
- * COMMIT/ROLLBACK, so it never leaks onto another connection from the pool).
++ * sequential and bitmap scans disabled for that transaction alone (`SET LOCAL`
++ * resets on COMMIT/ROLLBACK, so it never leaks onto another pooled request).
+ * Returns the EXPLAIN plan as one joined string.
+ */
+ async function explainPlan(sql, params, { analyze = false } = {}) {
+ return withTransaction(async (client) => {
+ await client.query('SET LOCAL enable_seqscan = off');
++ await client.query('SET LOCAL enable_bitmapscan = off');
+ const result = await client.query(`EXPLAIN ${analyze ? '(ANALYZE, TIMING OFF) ' : ''}${sql}`, params);
+ return result.rows.map((row) => row['QUERY PLAN']).join('\n');
+ });
+ }
+
+ beforeAll(async () => {
+ if (!dbReady) return;
+
+ await query(
+ `INSERT INTO beeper_accounts (account_id, network, display_name, status, bridge_id)
+ VALUES ($1, $2, 'Example Account', 'connected', 'example-bridge')`,
+ [ACCOUNT_ID, NETWORK],
+ );
+
+ const now = Date.now();
+ for (let i = 0; i < CONV_COUNT; i += 1) {
+ // Conversations 0..8 carry a real last_activity, freshest first (i=0
+ // newest). Conversations 9..11 have NO last_activity at all — #81's
+ // fallback is `'epoch'::timestamptz`, not `created_at`, so all three tie
+ // on the same sentinel ordering value and sort LAST as a group,
+ // regardless of when their row was minted. `created_at` is set to a
+ // point in the FUTURE here deliberately: if the ordering ever regressed
+ // to the old `COALESCE(last_activity, created_at)` fallback, these three
+ // would sort ahead of every real-activity conversation instead of behind
+ // all of them, and the "sorts last" test below would fail loudly rather
+ // than passing on a coincidence of timing.
+ const nullActivity = i >= 9;
+ const lastActivity = nullActivity ? null : new Date(now - i * 60_000).toISOString();
+ const createdAt = nullActivity ? new Date(now + (100 + i) * 60_000).toISOString() : null;
+ // eslint-disable-next-line no-await-in-loop -- deterministic seed order
+ const { rows } = await query(
+ `INSERT INTO beeper_conversations
+ (account_id, network, source_chat_id, title, type, last_activity, created_at)
+ VALUES ($1, $2, $3, $4, 'single', $5, COALESCE($6::timestamptz, NOW()))
+ RETURNING id`,
+ [ACCOUNT_ID, NETWORK, `${nonce}-chat-${i}`, `Example Chat ${i}`, lastActivity, createdAt],
+ );
+ conversationIds.push(rows[0].id);
+
+ for (let j = 0; j < MESSAGES_PER_CONV; j += 1) {
+ // Message j is more recent as j increases (msg 3 is the latest), so the
+ // conversation's "last message" preview is deterministic.
+ const ts = new Date(now - i * 60_000 + j * 1_000).toISOString();
+ // eslint-disable-next-line no-await-in-loop -- deterministic seed order
+ await query(
+ `INSERT INTO beeper_messages (id, conversation_id, sender_id, body, sent_at, created_at)
+ VALUES ($1, $2, 'user-1', $3, $4, $4)`,
+ [msgId(i, j), conversationIds[i], `message ${j} in conversation ${i}`, ts],
+ );
+ }
+ }
+
+ // One real attachment, for the (message_id, idx) index-shape proof below.
+ await query(
+ `INSERT INTO beeper_attachments (conversation_id, message_id, idx, mxc_id, mime_type, file_name)
+ VALUES ($1, $2, 0, 'mxc://example/attachment-1', 'image/png', 'example.png')`,
+ [conversationIds[0], msgId(0, MESSAGES_PER_CONV - 1)],
+ );
+
+ // Eviction fixture (LENS-4): four attachments on conversationIds[1]'s
+ // messages. Only A and B are eviction-eligible at all — C has no bytes, D
+ // is locked — so the ORDER BY proves both the predicate and NULLS FIRST.
+ await query(
+ `INSERT INTO beeper_attachments
+ (conversation_id, message_id, idx, mxc_id, mime_type, file_name, local_path, keep, last_viewed_at, unavailable_at)
+ VALUES
+ ($1, $2, 0, 'mxc://example/evict-a', 'image/png', 'a.png', 'ev/a.png', FALSE, NULL, NULL),
+ ($1, $3, 0, 'mxc://example/evict-b', 'image/png', 'b.png', 'ev/b.png', FALSE, '2020-01-01T00:00:00Z', NULL),
+ ($1, $4, 0, 'mxc://example/evict-c', 'image/png', 'c.png', NULL, FALSE, NULL, NULL),
+ ($1, $5, 0, 'mxc://example/evict-d', 'image/png', 'd.png', 'ev/d.png', TRUE, '2019-01-01T00:00:00Z', NULL)`,
+ [conversationIds[1], msgId(1, 0), msgId(1, 1), msgId(1, 2), msgId(1, 3)],
+ );
+ });
+
+ afterAll(async () => {
+ if (dbReady) {
+ await query('DELETE FROM beeper_accounts WHERE account_id = $1', [ACCOUNT_ID]).catch(() => {});
+ await close();
+ }
+ });
+
+ describe.skipIf(!runDb)('beeper conversation/message list query plans (audit cluster 06)', () => {
+ it('pages the conversation list on the activity-ordering index, with no separate Sort node', async () => {
+ const basePlan = await explainPlan(
+ `SELECT c.*, COALESCE(c.last_activity, 'epoch'::timestamptz) AS ordering_ts
+ FROM beeper_conversations c
+ ORDER BY COALESCE(c.last_activity, 'epoch'::timestamptz) DESC, c.id DESC
+ LIMIT $1`,
+ [6],
+ );
+ expect(basePlan).toMatch(/Index Scan.*idx_beeper_conversations_activity_epoch_keyset/s);
+ expect(basePlan).not.toMatch(/\bSort\b/);
+
+ // A keyset-paginated page (the cursor predicate) is served the same way.
+ const keysetPlan = await explainPlan(
+ `SELECT c.*, COALESCE(c.last_activity, 'epoch'::timestamptz) AS ordering_ts
+ FROM beeper_conversations c
+ WHERE (COALESCE(c.last_activity, 'epoch'::timestamptz), c.id) < ($1::timestamptz, $2::uuid)
+ ORDER BY COALESCE(c.last_activity, 'epoch'::timestamptz) DESC, c.id DESC
+ LIMIT $3`,
+ [new Date().toISOString(), conversationIds[0], 6],
+ );
+ expect(keysetPlan).toMatch(/Index Scan.*idx_beeper_conversations_activity_epoch_keyset/s);
+ expect(keysetPlan).not.toMatch(/\bSort\b/);
+ });
+
+ it('evaluates the last-message preview LATERAL once per PAGE id, never once per matching conversation', async () => {
+ const pageIds = conversationIds.slice(0, 5); // 5 of the 12 seeded conversations
+ const plan = await explainPlan(
+ `SELECT ids.conversation_id, lm.id AS preview_id
+ FROM unnest($1::uuid[]) AS ids(conversation_id)
+ LEFT JOIN LATERAL (
+ SELECT m.id
+ FROM beeper_messages m
+ WHERE m.conversation_id = ids.conversation_id
+ ORDER BY COALESCE(m.sent_at, m.created_at) DESC, m.id DESC
+ LIMIT 1
+ ) lm ON TRUE`,
+ [pageIds],
+ { analyze: true },
+ );
+ expect(plan).toMatch(/idx_beeper_messages_conversation_order/);
+ const loopCounts = [...plan.matchAll(/loops=(\d+)/g)].map((m) => Number(m[1]));
+ expect(loopCounts.length).toBeGreaterThan(0);
+ // The LATERAL sub-plan runs once per array element (the page), never once
+ // per the 12 seeded conversations — a `unnest($1)` restructuring makes
+ // this a property of the SQL, not of a plan the optimizer happened to
+ // choose.
+ expect(Math.max(...loopCounts)).toBe(pageIds.length);
+ });
+
+ it('paginates conversations by activity and attaches each page\'s own last-message preview', async () => {
+ const { conversations: page1, nextCursor } = await listConversations({ network: NETWORK, limit: 5 });
+ expect(page1.map((c) => c.id)).toEqual(conversationIds.slice(0, 5));
+ expect(nextCursor).toBeTruthy();
+ for (const conv of page1) {
+ expect(conv.lastMessage).toBeTruthy();
+ }
+ // Conversation 0's latest message is index MESSAGES_PER_CONV-1 (the
+ // preview orders newest-first within the conversation).
+ expect(page1[0].lastMessage.id).toBe(msgId(0, MESSAGES_PER_CONV - 1));
+
+ const { conversations: page2 } = await listConversations({ network: NETWORK, limit: 5, cursor: nextCursor });
+ // conv5..conv8 (real, decreasing last_activity) keep a fixed, deterministic
+ // order; conv9..conv11 all tie on the epoch sentinel, so only ONE of them
+ // fills the page's 5th slot and which one is an implementation detail of
+ // the id tiebreak, not a contract this test should pin.
+ expect(page2.slice(0, 4).map((c) => c.id)).toEqual(conversationIds.slice(5, 9));
+ expect(conversationIds.slice(9, 12)).toContain(page2[4].id);
+ });
+
+ // #81: an activity-less conversation sorts LAST as a group, never
+ // interleaved with (or ahead of) a conversation with real activity — the
+ // fix for the reported symptom (empty rows sorting above recent threads).
+ it('sorts every activity-less conversation after every conversation with real activity', async () => {
+ const { conversations: all } = await listConversations({ network: NETWORK, limit: CONV_COUNT });
+ expect(all).toHaveLength(CONV_COUNT);
+ expect(all.slice(0, 9).map((c) => c.id)).toEqual(conversationIds.slice(0, 9));
+ // The last three are exactly the activity-less set, in ANY order — their
+ // relative order is an id tiebreak, not a product contract.
+ expect(new Set(all.slice(9).map((c) => c.id))).toEqual(new Set(conversationIds.slice(9, 12)));
+ for (const conv of all.slice(9)) {
+ expect(conv.lastActivity).toBeNull();
+ }
+ });
+
+ it('pages a thread on the conversation+order index, without sorting the whole history', async () => {
+ const targetConv = conversationIds[3];
+ const basePlan = await explainPlan(
+ `SELECT m.*, COALESCE(m.sent_at, m.created_at) AS ordering_ts
+ FROM beeper_messages m
+ WHERE m.conversation_id = $1
+ ORDER BY COALESCE(m.sent_at, m.created_at) DESC, m.id DESC
+ LIMIT $2`,
+ [targetConv, 2],
+ );
+ expect(basePlan).toMatch(/Index Scan.*idx_beeper_messages_conversation_order/s);
+ expect(basePlan).not.toMatch(/\bSort\b/);
+
+ const keysetPlan = await explainPlan(
+ `SELECT m.*, COALESCE(m.sent_at, m.created_at) AS ordering_ts
+ FROM beeper_messages m
+ WHERE m.conversation_id = $1
+ AND (COALESCE(m.sent_at, m.created_at), m.id) < ($2::timestamptz, $3::text)
+ ORDER BY COALESCE(m.sent_at, m.created_at) DESC, m.id DESC
+ LIMIT $4`,
+ [targetConv, new Date().toISOString(), msgId(3, MESSAGES_PER_CONV - 1), 2],
+ );
+ expect(keysetPlan).toMatch(/Index Scan.*idx_beeper_messages_conversation_order/s);
+ expect(keysetPlan).not.toMatch(/\bSort\b/);
+
+ // Functional: the real listMessages() paginates the full seeded history
+ // with no gaps or repeats.
+ const seen = [];
+ let cursor;
+ for (let guard = 0; guard < MESSAGES_PER_CONV + 1; guard += 1) {
+ // eslint-disable-next-line no-await-in-loop -- exercising real pagination
+ const page = await listMessages(targetConv, { limit: 2, cursor });
+ seen.push(...page.messages.map((m) => m.id));
+ if (!page.nextCursor) break;
+ cursor = page.nextCursor;
+ }
+ expect(seen).toEqual([
+ msgId(3, 3), msgId(3, 2), msgId(3, 1), msgId(3, 0),
+ ]);
+ });
+
+ it('looks up an attachment by (message_id, idx) via an index, not a table scan', async () => {
+ const plan = await explainPlan(
+ `SELECT * FROM beeper_attachments WHERE message_id = $1 AND idx = $2`,
+ [msgId(0, MESSAGES_PER_CONV - 1), 0],
+ );
+ expect(plan).toMatch(/Index Scan.*idx_beeper_attachments_message/s);
+ expect(plan).not.toMatch(/Seq Scan/);
+ });
+
+ it('picks the never-viewed evictable attachment first (NULLS FIRST), with no separate Sort node', async () => {
+ // Verbatim `evictToBudget()` query shape — no `conversation_id` filter:
+ // the sweep picks its single best candidate across the WHOLE mirror, not
+ // per conversation. Adding a `conversation_id` predicate here (as an
+ // earlier draft of this test did) changes the plan the assertion is
+ // supposed to prove: with an equality filter this selective, the planner
+ // reaches for the PK (which leads with `conversation_id`) instead of the
+ // new partial index, which is a real answer to a different question than
+ // the one `evictToBudget()` actually asks.
+ const candidateSql = `
+ SELECT message_id, idx, mxc_id, local_path, byte_length
+ FROM beeper_attachments
+ WHERE local_path IS NOT NULL AND keep = FALSE
+ AND unavailable_at IS NULL AND mxc_id IS NOT NULL
+ ORDER BY last_viewed_at ASC NULLS FIRST, fetched_at ASC NULLS FIRST
+ LIMIT 1`;
+ const { rows } = await query(candidateSql);
+ // Row A (never viewed) outranks row B (viewed in 2020) under NULLS FIRST;
+ // row C (no bytes) and row D (kept) are excluded by the predicate. No
+ // other seeded attachment (the lone conv0 fixture) has `local_path` set,
+ // so A is the single global candidate.
+ expect(rows[0].message_id).toBe(msgId(1, 0));
+
+ const plan = await explainPlan(candidateSql);
+ expect(plan).toMatch(/Index Scan.*idx_beeper_attachments_eviction_candidates/s);
+ expect(plan).not.toMatch(/\bSort\b/);
+ });
+ });
diff --cc server/services/beeperOAuth.js
index 0000000000,718f763e4c..1e8e50134c
mode 000000,100644..100644
--- a/server/services/beeperOAuth.js
+++ b/server/services/beeperOAuth.js
@@@ -1,0 -1,479 +1,516 @@@
+ /**
+ * Beeper connect flow (fork issue #31; decisions 2-4, 6 and 10 on #11).
+ *
+ * PortOS runs the OAuth flow ITSELF rather than asking the user for a token it
+ * cannot mint. Beeper Desktop's `/.well-known/oauth-authorization-server`
+ * advertises a `registration_endpoint`, `token_endpoint_auth_methods_supported:
+ * ["none"]` and `code_challenge_methods_supported: ["S256"]`, so PortOS
+ * registers as a PUBLIC client (no pre-shared secret) and runs
+ * authorization_code + PKCE S256 with a `state` parameter. Both scopes are
+ * requested in one authorization (`read write`): sending is in scope for the
+ * product, and a second consent round-trip in the middle of composing a message
+ * is worse than one prompt at setup.
+ *
+ * Pasting a token stays a FIRST-CLASS alternative, not a fallback. Nothing in
+ * the OAuth surface accepts a lifetime — `/oauth/authorize`, `/oauth/token` and
+ * `/oauth/register` take no expiry parameter and `expires_in` appears only as a
+ * response field — while Beeper's own UI can mint a NO-EXPIRY token. There is
+ * no `refresh_token` grant anywhere in the metadata, so an expired token is
+ * re-connected, never refreshed. Both paths terminate in the same vaulted
+ * credential (`beeperCredentials.js`).
+ *
+ * The token value never leaves this module except into the vault: it is never
+ * logged, never put into an error message, and never returned to a route.
+ *
+ * Every path that changes whether a credential exists ends in
+ * `reconcileBeeperIngestion()` — storing one arms the sweep and the realtime
+ * transport without waiting for a restart, and a disconnect stops the relay
+ * rather than leaving it running on a token that was just revoked.
+ */
+
+ import { createHash, randomBytes } from 'crypto';
+ import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';
+ import { readResponseJson } from '../lib/readResponseJson.js';
+ import { describeFetchError } from '../lib/fetchErrorChain.js';
+ import { isPlainObject } from '../lib/objects.js';
+ import {
+ BeeperApiError, getAccounts, getInfo, probeBeeperInfo, resolveBeeperBaseUrl,
+ } from './beeperClient.js';
+ import { deleteBeeperCredential, readBeeperCredential, saveBeeperCredential } from './beeperCredentials.js';
+ import { reconcileBeeperIngestion } from './beeperArming.js';
++import { updateSettingsWith } from './settings.js';
++import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
+
+ const METADATA_PATH = '/.well-known/oauth-authorization-server';
+ export const BEEPER_OAUTH_SCOPES = ['read', 'write'];
+ // Generous next to a live Beeper Desktop's 11-21 ms, and still short enough
+ // that a base URL pointing at a host that blackholes packets fails the connect
+ // action rather than hanging it. The 1 s liveness cap (#11 decision 5) is for
+ // the passive status probe, not for a user-initiated connect.
+ const OAUTH_TIMEOUT_MS = 10_000;
+ // An authorization the user never completes is garbage after this. Beeper's
+ // consent screen is local and takes seconds; ten minutes is slack, not a budget.
+ const PENDING_TTL_MS = 10 * 60 * 1000;
+
+ /**
+ * In-flight authorizations, keyed by the `state` parameter: the PKCE verifier
+ * that must never leave the server, plus the endpoints discovered when the flow
+ * started (so the callback cannot be steered at a different token endpoint by a
+ * base-URL change mid-flow). Module-level and in-memory on purpose — one server
+ * process, one user, and a pending authorization that does not survive a
+ * restart is correct: the user simply clicks Connect again.
+ */
+ const pendingAuthorizations = new Map();
++// Disconnect invalidates unfinished connects, including a token exchange already
++// waiting on the network. Serialize only credential mutation and reconciliation
++// so a save already underway finishes before disconnect removes it.
++let connectionGeneration = 0;
++const queueCredentialMutation = createFileWriteQueue();
++
++function assertConnectionCurrent(generation) {
++ if (generation !== connectionGeneration) {
++ throw oauthError('This Beeper connection was cancelled — start the connect again', 'OAUTH_STATE_UNKNOWN', { status: 400 });
++ }
++}
++
++function storeConnectedCredential(input, generation, reason) {
++ return queueCredentialMutation(async () => {
++ assertConnectionCurrent(generation);
++ const saved = await saveBeeperCredential(input);
++ await armIngestion(reason);
++ return saved;
++ });
++}
+
+ function prunePending(now = Date.now()) {
+ for (const [state, pending] of pendingAuthorizations) {
+ if (now - pending.createdAt >= PENDING_TTL_MS) pendingAuthorizations.delete(state);
+ }
+ }
+
+ const base64url = (buffer) => buffer.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
+
+ /** RFC 7636 S256: `code_challenge = BASE64URL(SHA256(ASCII(code_verifier)))`. */
+ export function createPkcePair() {
+ const codeVerifier = base64url(randomBytes(32));
+ const codeChallenge = base64url(createHash('sha256').update(codeVerifier).digest());
+ return { codeVerifier, codeChallenge };
+ }
+
+ function oauthError(message, code, { status = 502 } = {}) {
+ return new BeeperApiError(message, { status, code, retryable: false });
+ }
+
+ // `localhost` and the loopback literals are the same host wearing different
+ // spellings — #11 decision 5 defaults the base URL to `127.0.0.1` precisely
+ // because a dual-stack box may resolve `localhost` to `::1` first, so treating
+ // them as different origins here would reject Beeper's own metadata.
+ const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '[::1]']);
+ const sameHost = (a, b) => a === b || (LOOPBACK_HOSTS.has(a) && LOOPBACK_HOSTS.has(b));
+
+ /**
+ * Resolve one advertised endpoint against the configured base URL, and refuse
+ * one that points somewhere else. The metadata document is fetched from a
+ * user-editable base URL (#30 makes it editable); without this check, whatever
+ * answers on that URL could name any host as the token endpoint and PortOS
+ * would POST the authorization code — and receive a token — off-box.
+ *
+ * Host and port are pinned for every base URL; SCHEME is pinned too UNLESS
+ * both sides are loopback (SEC-3). Without that, metadata served from an
+ * `https` base could name an `http` endpoint on the same host/port and
+ * silently downgrade the token exchange to plaintext — same class of bug as
+ * the OAuth redirect-origin check in `lib/beeperOAuthOrigin.js`, applied here
+ * to the discovered endpoints instead of the browser-supplied origin. Loopback
+ * still accepts a scheme mismatch: `resolveBeeperBaseUrl`'s own default is
+ * `http://127.0.0.1:23373`, and a loopback connection carries no
+ * network-path downgrade risk to defend against.
+ */
+ function resolveEndpoint(value, baseUrl, field) {
+ if (typeof value !== 'string' || !value.trim()) {
+ throw oauthError(`Beeper authorization-server metadata is missing ${field}`, 'OAUTH_DISCOVERY_INVALID');
+ }
+ const base = new URL(baseUrl);
+ const url = new URL(value.trim(), base);
+ const bothLoopback = LOOPBACK_HOSTS.has(url.hostname) && LOOPBACK_HOSTS.has(base.hostname);
+ if (
+ !['http:', 'https:'].includes(url.protocol)
+ || !sameHost(url.hostname, base.hostname)
+ || url.port !== base.port
+ || (!bothLoopback && url.protocol !== base.protocol)
+ ) {
+ throw oauthError(`Beeper authorization-server metadata points ${field} at a different host`, 'OAUTH_DISCOVERY_INVALID');
+ }
+ return url.toString();
+ }
+
+ async function fetchJson(url, init, { timeoutMs = OAUTH_TIMEOUT_MS } = {}) {
+ let response;
+ try {
- response = await fetchWithTimeout(url, init, timeoutMs);
++ // A 307/308 can forward the token or PKCE verifier in the POST body to
++ // another origin. Endpoint validation must also hold after the request.
++ response = await fetchWithTimeout(url, { ...init, redirect: 'error' }, timeoutMs);
+ } catch (err) {
+ throw new BeeperApiError(`Beeper request failed: ${describeFetchError(err)}`, {
+ status: 0, code: 'NETWORK_ERROR', retryable: false,
+ });
+ }
+ const body = await readResponseJson(response, { fallback: (text) => ({ message: text }) });
+ return { ok: response.ok, status: response.status, body };
+ }
+
+ /**
+ * A live Beeper Desktop's metadata document (verified against 4.3.89) carries
+ * twelve keys and no `introspection_endpoint` — the RFC 8414 field is
+ * genuinely optional, and this server omits it, which makes the paste path's
+ * introspection branch dead on every real install and every pasted token gets
+ * stored with `expiresAt: null` / `scopes: []`, silencing the expiry warnings
+ * `beeperStatus.tokenExpiryInfo` exists for. `GET /v1/info` advertises the
+ * same endpoint at `endpoints.oauth.introspection_endpoint` instead
+ * (live-verified), so this is the fallback discovery falls back to when the
+ * metadata document is silent. It goes through the identical `resolveEndpoint`
+ * same-host check as every other discovered endpoint — `/v1/info` is fetched
+ * from the same user-editable base URL as the metadata document, so a value it
+ * names still needs to be refused if it points elsewhere. A `/v1/info` that
+ * fails outright (network error, malformed body) is not itself a discovery
+ * failure — it just leaves introspection unavailable, same as if the metadata
+ * document had said nothing at all, and `connectWithPastedToken` already falls
+ * back to `verifyByAuthenticatedCall` for that case.
+ *
+ * `timeoutMs: OAUTH_TIMEOUT_MS` is deliberate — `getInfo`'s own default is
+ * `DEFAULT_PROBE_TIMEOUT_MS` (1s), sized for the passive, frequently-polled
+ * status card, not for a user-initiated connect/paste action that already
+ * budgets 10s for every other request in this flow (`fetchJson` above).
+ * Reusing the 1s probe cap here made this fallback fail under exactly the
+ * kind of everyday local latency a live Beeper Desktop can show under load —
+ * silently landing back on the no-expiry authenticated-call path this fix
+ * exists to avoid.
+ */
+ async function discoverIntrospectionEndpointFromInfo(resolvedBase) {
+ let info;
+ try {
+ info = await getInfo({ baseUrl: resolvedBase, timeoutMs: OAUTH_TIMEOUT_MS });
+ } catch {
+ return null;
+ }
+ const value = info?.endpoints?.oauth?.introspection_endpoint;
+ if (typeof value !== 'string' || !value.trim()) return null;
+ return resolveEndpoint(value, resolvedBase, 'endpoints.oauth.introspection_endpoint');
+ }
+
+ /**
+ * `GET /.well-known/oauth-authorization-server` on the configured base URL,
+ * validated rather than trusted: every endpoint this flow uses must be present
+ * and on the same host, and the server must advertise S256 when it advertises
+ * anything at all (a server offering only `plain` would silently downgrade PKCE
+ * to no protection).
+ */
+ export async function discoverAuthorizationServer({ baseUrl } = {}) {
+ const resolvedBase = baseUrl || await resolveBeeperBaseUrl();
+ const { ok, status, body } = await fetchJson(`${resolvedBase}${METADATA_PATH}`, { method: 'GET' });
+ if (!ok || !isPlainObject(body)) {
+ throw oauthError(`Beeper authorization-server metadata unavailable (${status})`, 'OAUTH_DISCOVERY_FAILED');
+ }
+ const methods = body.code_challenge_methods_supported;
+ if (Array.isArray(methods) && !methods.includes('S256')) {
+ throw oauthError('Beeper authorization server does not support PKCE S256', 'OAUTH_DISCOVERY_INVALID');
+ }
+ // Optional: RFC 7662 introspection, which is how the paste path proves a
+ // pasted token is real (see `connectWithPastedToken`). Falls back to
+ // `/v1/info` when the metadata document omits it (see
+ // `discoverIntrospectionEndpointFromInfo` above) — a live install commonly
+ // does.
+ const introspectionEndpoint = body.introspection_endpoint
+ ? resolveEndpoint(body.introspection_endpoint, resolvedBase, 'introspection_endpoint')
+ : await discoverIntrospectionEndpointFromInfo(resolvedBase);
+ return {
+ baseUrl: resolvedBase,
+ authorizationEndpoint: resolveEndpoint(body.authorization_endpoint, resolvedBase, 'authorization_endpoint'),
+ tokenEndpoint: resolveEndpoint(body.token_endpoint, resolvedBase, 'token_endpoint'),
+ registrationEndpoint: resolveEndpoint(body.registration_endpoint, resolvedBase, 'registration_endpoint'),
+ // Optional: "Disconnect" revokes when the server offers it, and merely
+ // forgets when it does not.
+ revocationEndpoint: body.revocation_endpoint
+ ? resolveEndpoint(body.revocation_endpoint, resolvedBase, 'revocation_endpoint')
+ : null,
+ introspectionEndpoint,
+ };
+ }
+
+ /**
+ * RFC 7662 token introspection. Returns `{ active, expiresAt, scopes }` — the
+ * only three fields this flow reads. `exp` is seconds since the epoch; absent
+ * means the token does not expire, which is exactly the no-expiry credential
+ * Beeper's own UI can mint, so it becomes `null` rather than a guessed default.
+ *
+ * `sub` is deliberately ignored: on this API it is an account identity, and
+ * PortOS never stores or displays one.
+ */
+ export async function introspectToken(token, { introspectionEndpoint, clientId } = {}) {
+ const params = new URLSearchParams({ token });
+ if (clientId) params.set('client_id', clientId);
+ const { ok, status, body } = await fetchJson(introspectionEndpoint, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ // Some deployments gate introspection on the token itself; sending it as
+ // a bearer as well is harmless when they do not.
+ Authorization: `Bearer ${token}`,
+ },
+ body: params.toString(),
+ });
+ if (!ok) {
+ throw oauthError(`Beeper token introspection failed (HTTP ${status})`, 'OAUTH_INTROSPECTION_FAILED');
+ }
+ const exp = Number(body?.exp);
+ return {
+ active: body?.active === true,
+ expiresAt: Number.isFinite(exp) && exp > 0 ? new Date(exp * 1000).toISOString() : null,
+ scopes: typeof body?.scope === 'string' && body.scope.trim() ? body.scope.trim().split(/\s+/) : [],
+ };
+ }
+
+ /**
+ * RFC 7591 dynamic client registration as a PUBLIC client
+ * (`token_endpoint_auth_method: 'none'`), which is what lets PortOS run this
+ * flow with no pre-shared secret. Registration is per connect attempt: the
+ * returned `client_id` is not a secret, costs one local round trip, and
+ * re-registering keeps the redirect URI correct when the user reaches PortOS
+ * over a different origin than last time.
+ */
+ export async function registerOAuthClient({ registrationEndpoint, redirectUri, clientUri }) {
+ const { ok, status, body } = await fetchJson(registrationEndpoint, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ client_name: 'PortOS',
+ ...(clientUri ? { client_uri: clientUri } : {}),
+ grant_types: ['authorization_code'],
+ response_types: ['code'],
+ redirect_uris: [redirectUri],
+ scope: BEEPER_OAUTH_SCOPES.join(' '),
+ token_endpoint_auth_method: 'none',
+ }),
+ });
+ const clientId = typeof body?.client_id === 'string' ? body.client_id.trim() : '';
+ if (!ok || !clientId) {
+ throw oauthError(`Beeper dynamic client registration failed (${status})`, 'OAUTH_REGISTRATION_FAILED');
+ }
+ return { clientId };
+ }
+
+ /**
+ * Start a connect: discover, register, mint a PKCE pair plus `state`, and hand
+ * back the authorization URL for the browser to open. The verifier stays here.
+ */
+ export async function startBeeperOAuth({ redirectUri, clientUri } = {}) {
+ if (typeof redirectUri !== 'string' || !redirectUri) {
+ throw oauthError('A redirect URI is required to start the Beeper OAuth flow', 'OAUTH_REDIRECT_URI_MISSING', { status: 400 });
+ }
++ const generation = connectionGeneration;
+ prunePending();
+ const discovery = await discoverAuthorizationServer();
+ const { clientId } = await registerOAuthClient({
+ registrationEndpoint: discovery.registrationEndpoint, redirectUri, clientUri,
+ });
++ assertConnectionCurrent(generation);
+ const { codeVerifier, codeChallenge } = createPkcePair();
+ const state = base64url(randomBytes(24));
+ pendingAuthorizations.set(state, {
- codeVerifier, clientId, redirectUri, createdAt: Date.now(),
++ codeVerifier, clientId, redirectUri, createdAt: Date.now(), generation,
+ tokenEndpoint: discovery.tokenEndpoint, baseUrl: discovery.baseUrl,
+ });
+
+ const params = new URLSearchParams({
+ client_id: clientId,
+ response_type: 'code',
+ redirect_uri: redirectUri,
+ state,
+ scope: BEEPER_OAUTH_SCOPES.join(' '),
+ code_challenge: codeChallenge,
+ code_challenge_method: 'S256',
+ });
+ const separator = discovery.authorizationEndpoint.includes('?') ? '&' : '?';
+ console.log(`🔗 Beeper OAuth authorization started (scopes=${BEEPER_OAUTH_SCOPES.join(' ')})`);
+ return {
+ authorizationUrl: `${discovery.authorizationEndpoint}${separator}${params.toString()}`,
+ redirectUri,
+ state,
+ };
+ }
+
+ /** `expires_in` (seconds from now) → an absolute ISO instant, or null. */
+ export function expiryFromTokenResponse(body, now = Date.now()) {
+ const seconds = Number(body?.expires_in);
+ if (!Number.isFinite(seconds) || seconds <= 0) return null;
+ return new Date(now + seconds * 1000).toISOString();
+ }
+
+ /**
+ * Complete a connect: match `state` to its pending authorization, exchange the
+ * code with the PKCE verifier, store the token + expiry in the vault, then
+ * probe `/v1/info` so the caller learns whether Beeper Desktop is actually
+ * answering. `state` is single-use — consumed before the exchange, so a replayed
+ * callback cannot re-run it.
+ *
+ * `redirect_uri` is deliberately NOT sent on the exchange: the live
+ * `/oauth/token` surface takes `grant_type, code, code_verifier, client_id`
+ * (plus an optional `resource`) and nothing else.
+ */
+ export async function completeBeeperOAuth({ code, state } = {}) {
+ prunePending();
+ const pending = state ? pendingAuthorizations.get(state) : null;
+ if (!pending) {
+ throw oauthError('This Beeper authorization has expired or was already used — start the connect again', 'OAUTH_STATE_UNKNOWN', { status: 400 });
+ }
+ pendingAuthorizations.delete(state);
+
+ const { ok, status, body } = await fetchJson(pending.tokenEndpoint, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
+ body: new URLSearchParams({
+ grant_type: 'authorization_code',
+ code,
+ code_verifier: pending.codeVerifier,
+ client_id: pending.clientId,
+ }).toString(),
+ });
+ const token = typeof body?.access_token === 'string' ? body.access_token.trim() : '';
+ if (!ok || !token) {
+ // `body.error` is the RFC 6749 error CODE (`invalid_grant`, …), never the
+ // token — safe to surface. `error_description` is deliberately not
+ // interpolated: it is free text from the authorization server.
+ const reason = typeof body?.error === 'string' ? body.error : `HTTP ${status}`;
+ throw oauthError(`Beeper token exchange failed (${reason})`, 'OAUTH_EXCHANGE_FAILED');
+ }
+
+ const scopes = typeof body.scope === 'string' && body.scope.trim()
+ ? body.scope.trim().split(/\s+/)
+ : BEEPER_OAUTH_SCOPES;
- const saved = await saveBeeperCredential({
++ const saved = await storeConnectedCredential({
+ token,
+ expiresAt: expiryFromTokenResponse(body),
+ scopes,
+ source: 'oauth',
+ clientId: pending.clientId,
- });
-
- await armIngestion('oauth-connect');
++ }, pending.generation, 'oauth-connect');
+
+ // Never throws (see beeperClient) — a token that stored fine while Beeper
+ // Desktop happens to be closed is connected, not failed, and the status card
+ // renders the unreachable state on its own.
+ const probe = await probeBeeperInfo({ baseUrl: pending.baseUrl });
+ return { ...saved, reachable: probe.reachable, lastProbeError: probe.error };
+ }
+
+ /**
+ * The paste path (#11 decision 3). Beeper's own UI can mint a NO-EXPIRY token
+ * and no OAuth parameter can request one, so this is a first-class alternative
+ * rather than a fallback — and it terminates in the same vaulted credential.
+ *
+ * Validation must actually exercise the credential. `/v1/info` is Beeper's one
+ * endpoint that ALSO answers unauthenticated, so probing it would happily
+ * store a bogus token as connected. Instead:
+ *
+ * 1. RFC 7662 introspection when the authorization server advertises an
+ * `introspection_endpoint` — an inactive token is refused, and `exp`
+ * (absent for a no-expiry token) plus the returned scopes are stored.
+ * 2. Otherwise `GET /v1/accounts`, which REQUIRES the bearer, so a rejected
+ * token surfaces here as a 401 instead of at first use. Nothing is known
+ * about its lifetime on this path, so the expiry is stored as `null`.
+ *
+ * Either way a token the server refuses is never written to the vault.
+ */
+ export async function connectWithPastedToken(token) {
++ const generation = connectionGeneration;
+ const value = typeof token === 'string' ? token.trim() : '';
+ if (!value) {
+ throw oauthError('A Beeper access token is required', 'TOKEN_REQUIRED', { status: 400 });
+ }
+ const discovery = await discoverAuthorizationServer();
+ const verified = discovery.introspectionEndpoint
+ ? await verifyByIntrospection(value, discovery)
+ : await verifyByAuthenticatedCall(value, discovery.baseUrl);
+
- const saved = await saveBeeperCredential({
++ const saved = await storeConnectedCredential({
+ token: value, expiresAt: verified.expiresAt, scopes: verified.scopes, source: 'pasted',
- });
- await armIngestion('token-pasted');
++ }, generation, 'token-pasted');
+ return { ...saved, reachable: true, lastProbeError: null };
+ }
+
+ /**
+ * Reconcile the sweep + realtime transport against the credential that just
+ * changed. Isolated from the caller's verdict on purpose: the credential is
+ * already stored (or already gone), so a reconcile that fails must not turn a
+ * completed connect into a 500 — it is logged and the next trigger, or the next
+ * restart, picks it up.
+ */
+ async function armIngestion(reason) {
- await reconcileBeeperIngestion({ reason })
++ await reconcileBeeperIngestion({ reason, restartSocket: true })
+ .catch((err) => console.error(`❌ Beeper ingestion reconcile (${reason}) failed: ${err.message}`));
+ }
+
+ async function verifyByIntrospection(token, { introspectionEndpoint }) {
+ const result = await introspectToken(token, { introspectionEndpoint });
+ if (!result.active) {
+ // Nothing about the token itself goes into the message — only the verdict.
+ throw oauthError('Beeper rejected that access token (introspection reports it is not active)', 'TOKEN_REJECTED', { status: 401 });
+ }
+ return { expiresAt: result.expiresAt, scopes: result.scopes };
+ }
+
+ async function verifyByAuthenticatedCall(token, baseUrl) {
+ // Throws UNAUTHORIZED on a rejected token and MALFORMED_RESPONSE when the
+ // base URL points at something that answers 200 but isn't Beeper.
+ await getAccounts({ baseUrl, token });
+ return { expiresAt: null, scopes: [] };
+ }
+
+ /**
+ * Disconnect. Best-effort revocation first (#11 decision 2: "Disconnect calls
+ * `/oauth/revoke` rather than merely deleting the local copy"), then the local
+ * delete — which runs whether or not revocation worked, because a user asking
+ * to disconnect must always end up disconnected. A pasted token has no
+ * registered client to revoke against, so it is only forgotten.
+ */
-export async function disconnectBeeper() {
++export function disconnectBeeper() {
++ connectionGeneration += 1;
++ pendingAuthorizations.clear();
++ return queueCredentialMutation(disconnectCredential);
++}
++
++async function disconnectCredential() {
+ const credential = await readBeeperCredential().catch(() => null);
+ if (credential?.tokenSource === 'oauth' && credential.clientId) {
+ const revoked = await revokeToken(credential).catch((err) => ({ revoked: false, error: err?.message }));
+ console.log(revoked?.revoked
+ ? '🔓 Beeper token revoked at the authorization server'
+ : '⚠️ Beeper token revocation was not accepted; deleting the local copy anyway');
+ }
++ // Clear the supported legacy fallback before deleting the vault entry;
++ // otherwise the resolver resurrects that credential and re-arms ingestion.
++ await updateSettingsWith((settings) => {
++ if (!isPlainObject(settings.beeper)) return settings;
++ const { token, tokenExpiresAt, ...beeper } = settings.beeper;
++ return { ...settings, beeper };
++ });
+ const result = await deleteBeeperCredential();
+ // The credential is gone, so the gate is now shut: stop the relay rather than
+ // leaving a live WebSocket running on a token the user just revoked.
+ await armIngestion('disconnect');
+ return result;
+ }
+
+ async function revokeToken({ token, clientId }) {
+ const discovery = await discoverAuthorizationServer();
+ if (!discovery.revocationEndpoint) return { revoked: false };
+ const { ok } = await fetchJson(discovery.revocationEndpoint, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
+ body: new URLSearchParams({ token, client_id: clientId }).toString(),
+ });
+ return { revoked: ok };
+ }
+
+ /** Test seam: forget every pending authorization between cases. */
+ export function __resetPendingAuthorizationsForTests() {
+ pendingAuthorizations.clear();
+ }
diff --cc server/services/beeperOAuth.test.js
index 0000000000,5b70305ced..601e2c4af9
mode 000000,100644..100644
--- a/server/services/beeperOAuth.test.js
+++ b/server/services/beeperOAuth.test.js
@@@ -1,0 -1,581 +1,677 @@@
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
+ import { createHash } from 'crypto';
+
+ vi.mock('../lib/fetchWithTimeout.js', () => ({ fetchWithTimeout: vi.fn() }));
-vi.mock('./settings.js', () => ({ getSettings: vi.fn() }));
++vi.mock('./settings.js', () => ({ getSettings: vi.fn(), updateSettingsWith: vi.fn() }));
+ vi.mock('./beeperCredentials.js', () => ({
+ saveBeeperCredential: vi.fn(),
+ readBeeperCredential: vi.fn(),
+ deleteBeeperCredential: vi.fn(),
+ // beeperClient imports this; nothing here should ever reach it, since every
+ // call in this flow passes an explicit token (or an explicit null).
+ resolveBeeperToken: vi.fn(),
+ }));
+ // Arming the sweep and the realtime transport is orchestration this module
+ // triggers but does not own — what a reconcile actually does to each subsystem
+ // is `beeperArming.test.js`. Here the assertion is only that every path which
+ // changes whether a credential exists fires one.
+ vi.mock('./beeperArming.js', () => ({
+ reconcileBeeperIngestion: vi.fn(async () => ({ armed: true, changed: true })),
+ }));
+
+ import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';
+ import { mockJsonResponse } from '../lib/testHelper.js';
-import { getSettings } from './settings.js';
++import { getSettings, updateSettingsWith } from './settings.js';
+ import { reconcileBeeperIngestion } from './beeperArming.js';
+ import { deleteBeeperCredential, readBeeperCredential, saveBeeperCredential } from './beeperCredentials.js';
+ import {
+ __resetPendingAuthorizationsForTests, completeBeeperOAuth, connectWithPastedToken,
+ createPkcePair, disconnectBeeper, discoverAuthorizationServer, expiryFromTokenResponse,
+ introspectToken, startBeeperOAuth,
+ } from './beeperOAuth.js';
+
+ // Metadata WITHOUT introspection — the fallback branch of the paste path.
+ const { introspection_endpoint: _omitted, ...METADATA_NO_INTROSPECTION } = {
+ authorization_endpoint: '/oauth/authorize',
+ token_endpoint: '/oauth/token',
+ registration_endpoint: '/oauth/register',
+ introspection_endpoint: '/oauth/introspect',
+ };
+
+ const BASE_URL = 'http://127.0.0.1:23373';
+ const REDIRECT_URI = 'https://example.com/api/beeper/oauth/callback';
+ // Placeholders — never a value observed on a real install.
+ const TOKEN = 'example-beeper-token';
+
+ const METADATA = {
+ authorization_endpoint: '/oauth/authorize',
+ token_endpoint: '/oauth/token',
+ registration_endpoint: '/oauth/register',
+ revocation_endpoint: '/oauth/revoke',
+ introspection_endpoint: '/oauth/introspect',
+ grant_types_supported: ['authorization_code'],
+ token_endpoint_auth_methods_supported: ['none'],
+ code_challenge_methods_supported: ['S256'],
+ scopes_supported: ['read', 'write'],
+ };
+
+ const INFO = { app: { name: 'Beeper', version: '4.3.73' }, server: { status: 'running' } };
+ // A live install's /v1/info also has no oauth endpoints block — used to test
+ // the FINAL fallback (authenticated call), when neither source advertises
+ // introspection.
+ const INFO_NO_OAUTH_ENDPOINTS = INFO;
+ // The shape live-verified on Beeper Desktop 4.3.89: the metadata document
+ // omits `introspection_endpoint`, but `/v1/info` advertises it under
+ // `endpoints.oauth.introspection_endpoint`.
+ const INFO_WITH_INTROSPECTION = {
+ ...INFO,
+ endpoints: { oauth: { introspection_endpoint: '/oauth/introspect' } },
+ };
+
+ const urlOf = (call) => String(call[0]);
+ const bodyOf = (call) => String(call[1]?.body ?? '');
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ __resetPendingAuthorizationsForTests();
+ vi.mocked(getSettings).mockResolvedValue({ beeper: { baseUrl: BASE_URL } });
++ vi.mocked(updateSettingsWith).mockImplementation(async (mutate) => mutate(await getSettings()));
+ vi.mocked(saveBeeperCredential).mockImplementation(async ({ expiresAt = null, source }) => ({
+ tokenConfigured: true, tokenExpiresAt: expiresAt, tokenSource: source,
+ }));
+ });
+
+ // Discovery + registration + authorize, in the order the real flow runs them.
+ const mockConnectStart = ({ clientId = 'client-1' } = {}) => {
+ vi.mocked(fetchWithTimeout)
+ .mockResolvedValueOnce(mockJsonResponse(METADATA))
+ .mockResolvedValueOnce(mockJsonResponse({ client_id: clientId }));
+ };
+
+ describe('createPkcePair', () => {
+ it('produces a base64url S256 challenge derived from the verifier', () => {
+ const { codeVerifier, codeChallenge } = createPkcePair();
+ const expected = createHash('sha256').update(codeVerifier).digest('base64')
+ .replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
+ expect(codeChallenge).toBe(expected);
+ expect(codeChallenge).not.toMatch(/[+/=]/);
+ expect(codeVerifier).not.toBe(codeChallenge);
+ });
+ });
+
+ describe('discoverAuthorizationServer', () => {
+ it('resolves relative endpoints against the configured base URL', async () => {
+ vi.mocked(fetchWithTimeout).mockResolvedValue(mockJsonResponse(METADATA));
+ const discovery = await discoverAuthorizationServer();
+ expect(urlOf(vi.mocked(fetchWithTimeout).mock.calls[0])).toBe(`${BASE_URL}/.well-known/oauth-authorization-server`);
+ expect(discovery.tokenEndpoint).toBe(`${BASE_URL}/oauth/token`);
+ expect(discovery.registrationEndpoint).toBe(`${BASE_URL}/oauth/register`);
+ expect(discovery.revocationEndpoint).toBe(`${BASE_URL}/oauth/revoke`);
+ expect(discovery.introspectionEndpoint).toBe(`${BASE_URL}/oauth/introspect`);
+ });
+
+ it('reports a null introspection endpoint when the server advertises none', async () => {
+ vi.mocked(fetchWithTimeout).mockResolvedValue(mockJsonResponse(METADATA_NO_INTROSPECTION));
+ await expect(discoverAuthorizationServer()).resolves.toMatchObject({ introspectionEndpoint: null });
+ });
+
+ // The base URL is user-editable (#30). Whatever answers on it must not be
+ // able to name a different host as the token endpoint and collect the
+ // authorization code.
+ it('refuses metadata that points the token endpoint at another host', async () => {
+ vi.mocked(fetchWithTimeout).mockResolvedValue(mockJsonResponse({
+ ...METADATA, token_endpoint: 'https://example.com/oauth/token',
+ }));
+ await expect(discoverAuthorizationServer()).rejects.toMatchObject({ code: 'OAUTH_DISCOVERY_INVALID' });
+ });
+
+ it('accepts loopback spelled either way, since the default base URL is 127.0.0.1', async () => {
+ vi.mocked(fetchWithTimeout).mockResolvedValue(mockJsonResponse({
+ ...METADATA, token_endpoint: 'http://localhost:23373/oauth/token',
+ }));
+ await expect(discoverAuthorizationServer()).resolves.toMatchObject({
+ tokenEndpoint: 'http://localhost:23373/oauth/token',
+ });
+ });
+
+ // SEC-3: host and port were pinned, but not scheme — metadata served from an
+ // `https` base could still name an `http` endpoint on the same host/port and
+ // silently downgrade the token exchange to plaintext.
+ it('refuses an http token endpoint under a non-loopback https base (scheme downgrade)', async () => {
+ vi.mocked(fetchWithTimeout).mockResolvedValue(mockJsonResponse({
+ ...METADATA, token_endpoint: 'http://example.com:23373/oauth/token',
+ }));
+ await expect(discoverAuthorizationServer({ baseUrl: 'https://example.com:23373' }))
+ .rejects.toMatchObject({ code: 'OAUTH_DISCOVERY_INVALID' });
+ });
+
+ it('still accepts a scheme mismatch when both the base and the endpoint are loopback', async () => {
+ vi.mocked(fetchWithTimeout).mockResolvedValue(mockJsonResponse({
+ ...METADATA, token_endpoint: 'http://127.0.0.1:23373/oauth/token',
+ }));
+ await expect(discoverAuthorizationServer({ baseUrl: 'https://127.0.0.1:23373' })).resolves.toMatchObject({
+ tokenEndpoint: 'http://127.0.0.1:23373/oauth/token',
+ });
+ });
+
+ it('refuses a server that advertises PKCE without S256', async () => {
+ vi.mocked(fetchWithTimeout).mockResolvedValue(mockJsonResponse({
+ ...METADATA, code_challenge_methods_supported: ['plain'],
+ }));
+ await expect(discoverAuthorizationServer()).rejects.toMatchObject({ code: 'OAUTH_DISCOVERY_INVALID' });
+ });
+
+ it('maps an unreachable Beeper Desktop to NETWORK_ERROR rather than a discovery fault', async () => {
+ vi.mocked(fetchWithTimeout).mockRejectedValue(Object.assign(new Error('fetch failed'), { cause: { code: 'ECONNREFUSED' } }));
+ await expect(discoverAuthorizationServer()).rejects.toMatchObject({ code: 'NETWORK_ERROR', status: 0 });
+ });
+
+ // A live Beeper Desktop's metadata document (verified against 4.3.89)
+ // omits `introspection_endpoint` entirely. This is the fallback that keeps
+ // the paste path's introspection branch alive on a real install instead of
+ // silently landing every pasted token on the authenticated-call path with
+ // no expiry/scopes.
+ describe('the /v1/info introspection-endpoint fallback', () => {
+ it("reads endpoints.oauth.introspection_endpoint off /v1/info when the metadata document omits it", async () => {
+ vi.mocked(fetchWithTimeout)
+ .mockResolvedValueOnce(mockJsonResponse(METADATA_NO_INTROSPECTION))
+ .mockResolvedValueOnce(mockJsonResponse(INFO_WITH_INTROSPECTION));
+
+ const discovery = await discoverAuthorizationServer();
+
+ expect(urlOf(vi.mocked(fetchWithTimeout).mock.calls[1])).toBe(`${BASE_URL}/v1/info`);
+ expect(discovery.introspectionEndpoint).toBe(`${BASE_URL}/oauth/introspect`);
+ });
+
+ it('refuses a /v1/info fallback endpoint that points at a different host', async () => {
+ vi.mocked(fetchWithTimeout)
+ .mockResolvedValueOnce(mockJsonResponse(METADATA_NO_INTROSPECTION))
+ .mockResolvedValueOnce(mockJsonResponse({
+ ...INFO, endpoints: { oauth: { introspection_endpoint: 'https://example.com/oauth/introspect' } },
+ }));
+ await expect(discoverAuthorizationServer()).rejects.toMatchObject({ code: 'OAUTH_DISCOVERY_INVALID' });
+ });
+
+ it('stays null when /v1/info also carries no oauth introspection endpoint', async () => {
+ vi.mocked(fetchWithTimeout)
+ .mockResolvedValueOnce(mockJsonResponse(METADATA_NO_INTROSPECTION))
+ .mockResolvedValueOnce(mockJsonResponse(INFO_NO_OAUTH_ENDPOINTS));
+ await expect(discoverAuthorizationServer()).resolves.toMatchObject({ introspectionEndpoint: null });
+ });
+
+ it('stays null rather than failing discovery when the /v1/info fallback request itself errors', async () => {
+ vi.mocked(fetchWithTimeout)
+ .mockResolvedValueOnce(mockJsonResponse(METADATA_NO_INTROSPECTION))
+ .mockRejectedValueOnce(Object.assign(new Error('fetch failed'), { cause: { code: 'ECONNREFUSED' } }));
+ await expect(discoverAuthorizationServer()).resolves.toMatchObject({ introspectionEndpoint: null });
+ });
+ });
+ });
+
+ describe('startBeeperOAuth', () => {
+ it('registers as a public client and returns an S256 authorization URL carrying both scopes', async () => {
+ mockConnectStart();
+ const { authorizationUrl, state } = await startBeeperOAuth({ redirectUri: REDIRECT_URI, clientUri: 'https://example.com' });
+
+ const registration = JSON.parse(bodyOf(vi.mocked(fetchWithTimeout).mock.calls[1]));
+ expect(registration).toMatchObject({
+ token_endpoint_auth_method: 'none',
+ grant_types: ['authorization_code'],
+ response_types: ['code'],
+ redirect_uris: [REDIRECT_URI],
+ scope: 'read write',
+ });
+ expect(registration.client_secret).toBeUndefined();
+
+ const url = new URL(authorizationUrl);
+ expect(url.origin + url.pathname).toBe(`${BASE_URL}/oauth/authorize`);
+ expect(url.searchParams.get('code_challenge_method')).toBe('S256');
+ expect(url.searchParams.get('scope')).toBe('read write');
+ expect(url.searchParams.get('state')).toBe(state);
+ // The verifier is the half that must never leave the server.
+ expect(url.searchParams.get('code_verifier')).toBeNull();
+ expect(url.searchParams.get('code_challenge')).toBeTruthy();
+ expect(url.searchParams.get('redirect_uri')).toBe(REDIRECT_URI);
+ });
+
+ it('reports a failed registration as OAUTH_REGISTRATION_FAILED', async () => {
+ vi.mocked(fetchWithTimeout)
+ .mockResolvedValueOnce(mockJsonResponse(METADATA))
+ .mockResolvedValueOnce(mockJsonResponse({ error: 'invalid_client_metadata' }, { ok: false, status: 400 }));
+ await expect(startBeeperOAuth({ redirectUri: REDIRECT_URI })).rejects.toMatchObject({ code: 'OAUTH_REGISTRATION_FAILED' });
+ });
+
+ it('refuses to start without a redirect URI rather than inventing a localhost one', async () => {
+ await expect(startBeeperOAuth({})).rejects.toMatchObject({ code: 'OAUTH_REDIRECT_URI_MISSING' });
+ expect(fetchWithTimeout).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('completeBeeperOAuth', () => {
+ it('exchanges the code with the PKCE verifier, vaults token + expiry, then probes /v1/info', async () => {
+ mockConnectStart();
+ const { authorizationUrl, state } = await startBeeperOAuth({ redirectUri: REDIRECT_URI });
+ const challenge = new URL(authorizationUrl).searchParams.get('code_challenge');
+
+ vi.mocked(fetchWithTimeout)
+ .mockResolvedValueOnce(mockJsonResponse({ access_token: TOKEN, expires_in: 3600, scope: 'read write' }))
+ .mockResolvedValueOnce(mockJsonResponse(INFO));
+
+ const result = await completeBeeperOAuth({ code: 'auth-code', state });
+
+ const exchange = vi.mocked(fetchWithTimeout).mock.calls[2];
+ expect(urlOf(exchange)).toBe(`${BASE_URL}/oauth/token`);
++ expect(exchange[1].redirect).toBe('error');
+ const form = new URLSearchParams(bodyOf(exchange));
+ expect(form.get('grant_type')).toBe('authorization_code');
+ expect(form.get('code')).toBe('auth-code');
+ expect(form.get('client_id')).toBe('client-1');
+ // The verifier sent must be the pre-image of the challenge the browser saw.
+ const verifier = form.get('code_verifier');
+ expect(createHash('sha256').update(verifier).digest('base64')
+ .replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')).toBe(challenge);
+
+ expect(saveBeeperCredential).toHaveBeenCalledWith(expect.objectContaining({
+ token: TOKEN, source: 'oauth', scopes: ['read', 'write'], clientId: 'client-1',
+ }));
+ expect(vi.mocked(saveBeeperCredential).mock.calls[0][0].expiresAt).toMatch(/^\d{4}-/);
+ expect(result).toMatchObject({ tokenConfigured: true, tokenSource: 'oauth', reachable: true });
+ // Presence and provenance only — never the value.
+ expect(JSON.stringify(result)).not.toContain(TOKEN);
+ });
+
+ it('reports connected with reachable:false when Beeper Desktop is closed after a successful exchange', async () => {
+ mockConnectStart();
+ const { state } = await startBeeperOAuth({ redirectUri: REDIRECT_URI });
+ vi.mocked(fetchWithTimeout)
+ .mockResolvedValueOnce(mockJsonResponse({ access_token: TOKEN }))
+ .mockRejectedValueOnce(new Error('fetch failed'));
+
+ const result = await completeBeeperOAuth({ code: 'auth-code', state });
+ expect(saveBeeperCredential).toHaveBeenCalled();
+ expect(result.reachable).toBe(false);
+ expect(result.lastProbeError).toBeTruthy();
+ });
+
+ // No `expires_in` in the response means no expiry to store — not "expired",
+ // and not a guessed default.
+ it('stores a null expiry when the token response carries no expires_in', async () => {
+ mockConnectStart();
+ const { state } = await startBeeperOAuth({ redirectUri: REDIRECT_URI });
+ vi.mocked(fetchWithTimeout)
+ .mockResolvedValueOnce(mockJsonResponse({ access_token: TOKEN }))
+ .mockResolvedValueOnce(mockJsonResponse(INFO));
+ await completeBeeperOAuth({ code: 'auth-code', state });
+ expect(vi.mocked(saveBeeperCredential).mock.calls[0][0].expiresAt).toBeNull();
+ });
+
+ it('rejects an unknown state and never exchanges the code', async () => {
+ await expect(completeBeeperOAuth({ code: 'auth-code', state: 'not-a-real-state' }))
+ .rejects.toMatchObject({ code: 'OAUTH_STATE_UNKNOWN', status: 400 });
+ expect(fetchWithTimeout).not.toHaveBeenCalled();
+ });
+
+ // The authorization code is single-use: a replayed callback must not re-run
+ // the exchange (Beeper would reject it, and a retry is never safe).
+ it('consumes the state so a replayed callback cannot re-exchange', async () => {
+ mockConnectStart();
+ const { state } = await startBeeperOAuth({ redirectUri: REDIRECT_URI });
+ vi.mocked(fetchWithTimeout)
+ .mockResolvedValueOnce(mockJsonResponse({ access_token: TOKEN }))
+ .mockResolvedValueOnce(mockJsonResponse(INFO));
+ await completeBeeperOAuth({ code: 'auth-code', state });
+ await expect(completeBeeperOAuth({ code: 'auth-code', state })).rejects.toMatchObject({ code: 'OAUTH_STATE_UNKNOWN' });
+ });
+
+ it('surfaces the RFC 6749 error code on a failed exchange and stores nothing', async () => {
+ mockConnectStart();
+ const { state } = await startBeeperOAuth({ redirectUri: REDIRECT_URI });
+ vi.mocked(fetchWithTimeout).mockResolvedValueOnce(
+ mockJsonResponse({ error: 'invalid_grant', error_description: 'code expired' }, { ok: false, status: 400 }),
+ );
+ await expect(completeBeeperOAuth({ code: 'auth-code', state }))
+ .rejects.toMatchObject({ code: 'OAUTH_EXCHANGE_FAILED', message: expect.stringContaining('invalid_grant') });
+ expect(saveBeeperCredential).not.toHaveBeenCalled();
+ // Nothing was stored, so the gate did not move.
+ expect(reconcileBeeperIngestion).not.toHaveBeenCalled();
+ });
+
+ // The live-pass blocker: the arming gate was read at boot only, so a connect
+ // on a running install left realtime down (`reconnectAttempts: 0`) and no
+ // sweep registered until the next restart.
+ it('arms ingestion once the credential is stored, without waiting for a restart', async () => {
+ mockConnectStart();
+ const { state } = await startBeeperOAuth({ redirectUri: REDIRECT_URI });
+ vi.mocked(fetchWithTimeout)
+ .mockResolvedValueOnce(mockJsonResponse({ access_token: TOKEN }))
+ .mockResolvedValueOnce(mockJsonResponse(INFO));
+
+ await completeBeeperOAuth({ code: 'auth-code', state });
+
- expect(reconcileBeeperIngestion).toHaveBeenCalledWith({ reason: 'oauth-connect' });
++ expect(reconcileBeeperIngestion).toHaveBeenCalledWith({ reason: 'oauth-connect', restartSocket: true });
+ });
+
+ // The credential is already vaulted by then, so a reconcile that throws must
+ // not turn a completed connect into a failure.
+ it('still reports a successful connect when arming fails', async () => {
+ vi.mocked(reconcileBeeperIngestion).mockRejectedValueOnce(new Error('Beeper request failed'));
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ mockConnectStart();
+ const { state } = await startBeeperOAuth({ redirectUri: REDIRECT_URI });
+ vi.mocked(fetchWithTimeout)
+ .mockResolvedValueOnce(mockJsonResponse({ access_token: TOKEN }))
+ .mockResolvedValueOnce(mockJsonResponse(INFO));
+
+ await expect(completeBeeperOAuth({ code: 'auth-code', state }))
+ .resolves.toMatchObject({ tokenConfigured: true, tokenSource: 'oauth' });
+ });
+ });
+
+ describe('expiryFromTokenResponse', () => {
+ it('turns expires_in seconds into an absolute instant, and anything else into null', () => {
+ const now = Date.parse('2026-09-03T00:00:00.000Z');
+ expect(expiryFromTokenResponse({ expires_in: 3600 }, now)).toBe('2026-09-03T01:00:00.000Z');
+ expect(expiryFromTokenResponse({}, now)).toBeNull();
+ expect(expiryFromTokenResponse({ expires_in: 'soon' }, now)).toBeNull();
+ expect(expiryFromTokenResponse({ expires_in: 0 }, now)).toBeNull();
+ });
+ });
+
+ describe('introspectToken', () => {
+ it('reads active, exp and scope, and treats an absent exp as no expiry', async () => {
+ vi.mocked(fetchWithTimeout).mockResolvedValue(mockJsonResponse({
+ active: true, scope: 'read write', exp: Math.floor(Date.parse('2026-12-01T00:00:00.000Z') / 1000),
+ }));
+ await expect(introspectToken(TOKEN, { introspectionEndpoint: `${BASE_URL}/oauth/introspect` })).resolves.toEqual({
+ active: true, expiresAt: '2026-12-01T00:00:00.000Z', scopes: ['read', 'write'],
+ });
+ const call = vi.mocked(fetchWithTimeout).mock.calls[0];
+ expect(new URLSearchParams(bodyOf(call)).get('token')).toBe(TOKEN);
++ expect(call[1].redirect).toBe('error');
+ });
+
+ it('reports inactive without inventing an expiry', async () => {
+ vi.mocked(fetchWithTimeout).mockResolvedValue(mockJsonResponse({ active: false }));
+ await expect(introspectToken(TOKEN, { introspectionEndpoint: `${BASE_URL}/oauth/introspect` }))
+ .resolves.toEqual({ active: false, expiresAt: null, scopes: [] });
+ });
+ });
+
+ // The paste path must EXERCISE the credential. /v1/info also answers
+ // unauthenticated, so probing it would store a bogus token as connected —
+ // introspection (or, failing that, a call that requires the bearer) is what
+ // makes "saved" mean "Beeper accepted this".
+ describe('connectWithPastedToken', () => {
+ it('introspects the pasted token, then vaults it with the expiry and scopes introspection reported', async () => {
+ const exp = Math.floor(Date.parse('2026-12-01T00:00:00.000Z') / 1000);
+ vi.mocked(fetchWithTimeout)
+ .mockResolvedValueOnce(mockJsonResponse(METADATA))
+ .mockResolvedValueOnce(mockJsonResponse({ active: true, scope: 'read write', exp }));
+
+ const result = await connectWithPastedToken(` ${TOKEN} `);
+
+ const introspect = vi.mocked(fetchWithTimeout).mock.calls[1];
+ expect(urlOf(introspect)).toBe(`${BASE_URL}/oauth/introspect`);
+ expect(new URLSearchParams(bodyOf(introspect)).get('token')).toBe(TOKEN);
+ expect(saveBeeperCredential).toHaveBeenCalledWith({
+ token: TOKEN, expiresAt: '2026-12-01T00:00:00.000Z', scopes: ['read', 'write'], source: 'pasted',
+ });
+ expect(result).toMatchObject({ tokenConfigured: true, tokenSource: 'pasted', reachable: true });
+ expect(JSON.stringify(result)).not.toContain(TOKEN);
+ });
+
+ // A no-expiry token — the credential this path exists for — introspects
+ // active with no `exp` at all, which must stay `null`, never a guess.
+ it('stores a null expiry for an active token introspection reports no exp for', async () => {
+ vi.mocked(fetchWithTimeout)
+ .mockResolvedValueOnce(mockJsonResponse(METADATA))
+ .mockResolvedValueOnce(mockJsonResponse({ active: true, scope: 'read write' }));
+ const result = await connectWithPastedToken(TOKEN);
+ expect(vi.mocked(saveBeeperCredential).mock.calls[0][0].expiresAt).toBeNull();
+ expect(result.tokenExpiresAt).toBeNull();
+ });
+
+ it('refuses an inactive token and stores nothing', async () => {
+ vi.mocked(fetchWithTimeout)
+ .mockResolvedValueOnce(mockJsonResponse(METADATA))
+ .mockResolvedValueOnce(mockJsonResponse({ active: false }));
+ await expect(connectWithPastedToken(TOKEN)).rejects.toMatchObject({ code: 'TOKEN_REJECTED', status: 401 });
+ expect(saveBeeperCredential).not.toHaveBeenCalled();
+ });
+
+ it('surfaces a failed introspection call rather than storing the token anyway', async () => {
+ vi.mocked(fetchWithTimeout)
+ .mockResolvedValueOnce(mockJsonResponse(METADATA))
+ .mockResolvedValueOnce(mockJsonResponse({ error: 'server_error' }, { ok: false, status: 500 }));
+ await expect(connectWithPastedToken(TOKEN)).rejects.toMatchObject({ code: 'OAUTH_INTROSPECTION_FAILED' });
+ expect(saveBeeperCredential).not.toHaveBeenCalled();
+ });
+
+ // Metadata omits introspection_endpoint AND /v1/info's fallback (see the
+ // `discoverAuthorizationServer` suite above) also has no oauth endpoints —
+ // the FINAL fallback, an authenticated call, is what's under test here.
+ describe('without an introspection endpoint anywhere', () => {
+ it('falls back to an authenticated call and stores on success', async () => {
+ vi.mocked(fetchWithTimeout)
+ .mockResolvedValueOnce(mockJsonResponse(METADATA_NO_INTROSPECTION))
+ .mockResolvedValueOnce(mockJsonResponse(INFO_NO_OAUTH_ENDPOINTS))
+ .mockResolvedValueOnce(mockJsonResponse([{ accountID: 'acct-1', network: 'Example Network' }]));
+
+ const result = await connectWithPastedToken(TOKEN);
+
+ const probe = vi.mocked(fetchWithTimeout).mock.calls[2];
+ expect(urlOf(probe)).toBe(`${BASE_URL}/v1/accounts`);
+ expect(probe[1].headers.Authorization).toBe(`Bearer ${TOKEN}`);
+ expect(saveBeeperCredential).toHaveBeenCalledWith({
+ token: TOKEN, expiresAt: null, scopes: [], source: 'pasted',
+ });
+ expect(result).toMatchObject({ tokenConfigured: true, tokenSource: 'pasted' });
+ });
+
+ it('stores nothing when the authenticated call rejects the token', async () => {
+ vi.mocked(fetchWithTimeout)
+ .mockResolvedValueOnce(mockJsonResponse(METADATA_NO_INTROSPECTION))
+ .mockResolvedValueOnce(mockJsonResponse(INFO_NO_OAUTH_ENDPOINTS))
+ .mockResolvedValue(mockJsonResponse({ message: 'unauthorized' }, { ok: false, status: 401 }));
+ await expect(connectWithPastedToken(TOKEN)).rejects.toMatchObject({ code: 'UNAUTHORIZED' });
+ expect(saveBeeperCredential).not.toHaveBeenCalled();
+ });
+
+ it('stores nothing when the base URL answers 200 with something that is not Beeper', async () => {
+ vi.mocked(fetchWithTimeout)
+ .mockResolvedValueOnce(mockJsonResponse(METADATA_NO_INTROSPECTION))
+ .mockResolvedValueOnce(mockJsonResponse(INFO_NO_OAUTH_ENDPOINTS))
+ .mockResolvedValueOnce(mockJsonResponse({ hello: 'other service' }));
+ await expect(connectWithPastedToken(TOKEN)).rejects.toMatchObject({ code: 'MALFORMED_RESPONSE' });
+ expect(saveBeeperCredential).not.toHaveBeenCalled();
+ });
+ });
+
+ // The shape actually observed on a live install (Beeper Desktop 4.3.89):
+ // the metadata document is silent, but /v1/info fills in the endpoint, so
+ // the paste path introspects instead of falling all the way back to an
+ // authenticated call — and gets real expiry/scopes out of it.
+ describe('when /v1/info advertises an introspection endpoint the metadata omitted', () => {
+ it('introspects through the /v1/info fallback endpoint', async () => {
+ const exp = Math.floor(Date.parse('2026-12-01T00:00:00.000Z') / 1000);
+ vi.mocked(fetchWithTimeout)
+ .mockResolvedValueOnce(mockJsonResponse(METADATA_NO_INTROSPECTION))
+ .mockResolvedValueOnce(mockJsonResponse(INFO_WITH_INTROSPECTION))
+ .mockResolvedValueOnce(mockJsonResponse({ active: true, scope: 'read write', exp }));
+
+ const result = await connectWithPastedToken(TOKEN);
+
+ const introspect = vi.mocked(fetchWithTimeout).mock.calls[2];
+ expect(urlOf(introspect)).toBe(`${BASE_URL}/oauth/introspect`);
+ expect(saveBeeperCredential).toHaveBeenCalledWith({
+ token: TOKEN, expiresAt: '2026-12-01T00:00:00.000Z', scopes: ['read', 'write'], source: 'pasted',
+ });
+ expect(result).toMatchObject({ tokenConfigured: true, tokenSource: 'pasted' });
+ });
+ });
+
+ it('rejects an empty token without a network call', async () => {
+ await expect(connectWithPastedToken(' ')).rejects.toMatchObject({ code: 'TOKEN_REQUIRED', status: 400 });
+ expect(fetchWithTimeout).not.toHaveBeenCalled();
+ expect(saveBeeperCredential).not.toHaveBeenCalled();
+ expect(reconcileBeeperIngestion).not.toHaveBeenCalled();
+ });
+
+ // Both credential-store paths arm, not just OAuth: pasting a token is a
+ // first-class alternative (#11 decision 3), so it must leave the install in
+ // the same running state.
+ it('arms ingestion after vaulting a pasted token', async () => {
+ vi.mocked(fetchWithTimeout)
+ .mockResolvedValueOnce(mockJsonResponse(METADATA))
+ .mockResolvedValueOnce(mockJsonResponse({ active: true, scope: 'read write' }));
+
+ await connectWithPastedToken(TOKEN);
+
- expect(reconcileBeeperIngestion).toHaveBeenCalledWith({ reason: 'token-pasted' });
++ expect(reconcileBeeperIngestion).toHaveBeenCalledWith({ reason: 'token-pasted', restartSocket: true });
+ });
+
+ it('does not arm when the token was refused', async () => {
+ vi.mocked(fetchWithTimeout)
+ .mockResolvedValueOnce(mockJsonResponse(METADATA))
+ .mockResolvedValueOnce(mockJsonResponse({ active: false }));
+ await expect(connectWithPastedToken(TOKEN)).rejects.toMatchObject({ code: 'TOKEN_REJECTED' });
+ expect(reconcileBeeperIngestion).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('disconnectBeeper', () => {
++ it('cancels an outstanding authorization before its callback can reconnect', async () => {
++ mockConnectStart();
++ const { state } = await startBeeperOAuth({ redirectUri: REDIRECT_URI });
++ vi.mocked(readBeeperCredential).mockResolvedValue(null);
++ vi.mocked(deleteBeeperCredential).mockResolvedValue({ deleted: false, tokenConfigured: false });
++
++ await disconnectBeeper();
++
++ await expect(completeBeeperOAuth({ code: 'example-code', state })).rejects.toMatchObject({ code: 'OAUTH_STATE_UNKNOWN' });
++ expect(saveBeeperCredential).not.toHaveBeenCalled();
++ });
++
++ it('cannot restore a token whose exchange finishes after disconnect', async () => {
++ mockConnectStart();
++ const { state } = await startBeeperOAuth({ redirectUri: REDIRECT_URI });
++ let finishExchange;
++ let exchangeStarted;
++ const started = new Promise((resolve) => { exchangeStarted = resolve; });
++ vi.mocked(fetchWithTimeout).mockImplementationOnce(() => {
++ exchangeStarted();
++ return new Promise((resolve) => { finishExchange = resolve; });
++ });
++ const completion = completeBeeperOAuth({ code: 'example-code', state });
++ const rejected = expect(completion).rejects.toMatchObject({ code: 'OAUTH_STATE_UNKNOWN' });
++ await started;
++ vi.mocked(readBeeperCredential).mockResolvedValue(null);
++ vi.mocked(deleteBeeperCredential).mockResolvedValue({ deleted: false, tokenConfigured: false });
++ await disconnectBeeper();
++ finishExchange(mockJsonResponse({ access_token: TOKEN }));
++
++ await rejected;
++ expect(saveBeeperCredential).not.toHaveBeenCalled();
++ });
++
++ it('waits for an already-started credential save before deleting it', async () => {
++ let finishSave;
++ let saveStarted;
++ const started = new Promise((resolve) => { saveStarted = resolve; });
++ vi.mocked(fetchWithTimeout)
++ .mockResolvedValueOnce(mockJsonResponse(METADATA))
++ .mockResolvedValueOnce(mockJsonResponse({ active: true }));
++ vi.mocked(saveBeeperCredential).mockImplementationOnce(() => {
++ saveStarted();
++ return new Promise((resolve) => { finishSave = resolve; });
++ });
++ const connecting = connectWithPastedToken(TOKEN);
++ await started;
++ vi.mocked(readBeeperCredential).mockResolvedValue({ token: TOKEN, tokenSource: 'pasted' });
++ vi.mocked(deleteBeeperCredential).mockResolvedValue({ deleted: true, tokenConfigured: false });
++ const disconnecting = disconnectBeeper();
++ expect(deleteBeeperCredential).not.toHaveBeenCalled();
++ finishSave({ tokenConfigured: true });
++
++ await connecting;
++ await expect(disconnecting).resolves.toMatchObject({ tokenConfigured: false });
++ expect(reconcileBeeperIngestion.mock.calls.at(-1)).toEqual([{ reason: 'disconnect', restartSocket: true }]);
++ expect(deleteBeeperCredential).toHaveBeenCalledOnce();
++ });
++
++ it.each([null, { token: TOKEN, tokenSource: 'pasted', clientId: '' }])(
++ 'removes the legacy fallback before ingestion reconciles, with vaulted credential %j',
++ async (credential) => {
++ let settings = {
++ theme: 'dark',
++ beeper: { baseUrl: BASE_URL, enabled: true, token: 'legacy-example-token', tokenExpiresAt: '2027-01-01' },
++ };
++ vi.mocked(readBeeperCredential).mockResolvedValue(credential);
++ vi.mocked(getSettings).mockImplementation(async () => settings);
++ vi.mocked(updateSettingsWith).mockImplementation(async (mutate) => {
++ settings = await mutate(settings);
++ return settings;
++ });
++ vi.mocked(deleteBeeperCredential).mockResolvedValue({ deleted: Boolean(credential), tokenConfigured: false });
++
++ await expect(disconnectBeeper()).resolves.toMatchObject({ tokenConfigured: false });
++
++ expect(settings).toEqual({ theme: 'dark', beeper: { baseUrl: BASE_URL, enabled: true } });
++ expect(updateSettingsWith.mock.invocationCallOrder[0]).toBeLessThan(deleteBeeperCredential.mock.invocationCallOrder[0]);
++ expect(deleteBeeperCredential.mock.invocationCallOrder[0]).toBeLessThan(reconcileBeeperIngestion.mock.invocationCallOrder[0]);
++ },
++ );
++
++ it('reports failure instead of claiming disconnected when legacy credential removal cannot persist', async () => {
++ vi.mocked(readBeeperCredential).mockResolvedValue(null);
++ vi.mocked(updateSettingsWith).mockRejectedValue(new Error('Settings unavailable'));
++
++ await expect(disconnectBeeper()).rejects.toThrow('Settings unavailable');
++
++ expect(deleteBeeperCredential).not.toHaveBeenCalled();
++ expect(reconcileBeeperIngestion).not.toHaveBeenCalled();
++ });
++
+ it('revokes an OAuth credential at the authorization server, then deletes the local copy', async () => {
+ vi.mocked(readBeeperCredential).mockResolvedValue({ token: TOKEN, tokenSource: 'oauth', clientId: 'client-1' });
+ vi.mocked(deleteBeeperCredential).mockResolvedValue({ deleted: true, tokenConfigured: false });
+ vi.mocked(fetchWithTimeout)
+ .mockResolvedValueOnce(mockJsonResponse(METADATA))
+ .mockResolvedValueOnce(mockJsonResponse({}));
+
+ await expect(disconnectBeeper()).resolves.toMatchObject({ deleted: true, tokenConfigured: false });
+ const revoke = vi.mocked(fetchWithTimeout).mock.calls[1];
+ expect(urlOf(revoke)).toBe(`${BASE_URL}/oauth/revoke`);
++ expect(revoke[1].redirect).toBe('error');
+ expect(new URLSearchParams(bodyOf(revoke)).get('client_id')).toBe('client-1');
+ expect(deleteBeeperCredential).toHaveBeenCalled();
+ });
+
+ // A user asking to disconnect must always end up disconnected, whatever the
+ // authorization server does.
+ it('still deletes the local copy when revocation fails', async () => {
+ vi.mocked(readBeeperCredential).mockResolvedValue({ token: TOKEN, tokenSource: 'oauth', clientId: 'client-1' });
+ vi.mocked(deleteBeeperCredential).mockResolvedValue({ deleted: true, tokenConfigured: false });
+ vi.mocked(fetchWithTimeout).mockRejectedValue(new Error('fetch failed'));
+ await expect(disconnectBeeper()).resolves.toMatchObject({ deleted: true });
+ expect(deleteBeeperCredential).toHaveBeenCalled();
+ });
+
+ it('skips revocation for a pasted token, which has no registered client', async () => {
+ vi.mocked(readBeeperCredential).mockResolvedValue({ token: TOKEN, tokenSource: 'pasted', clientId: '' });
+ vi.mocked(deleteBeeperCredential).mockResolvedValue({ deleted: true, tokenConfigured: false });
+ await expect(disconnectBeeper()).resolves.toMatchObject({ deleted: true });
+ expect(fetchWithTimeout).not.toHaveBeenCalled();
+ });
+
+ // The symmetric half of the live-pass blocker: without this the relay kept
+ // running on a token that had just been revoked.
+ it('reconciles ingestion after deleting the credential, so the relay stops', async () => {
+ vi.mocked(readBeeperCredential).mockResolvedValue({ token: TOKEN, tokenSource: 'pasted', clientId: '' });
+ vi.mocked(deleteBeeperCredential).mockResolvedValue({ deleted: true, tokenConfigured: false });
+
+ await disconnectBeeper();
+
- expect(reconcileBeeperIngestion).toHaveBeenCalledWith({ reason: 'disconnect' });
++ expect(reconcileBeeperIngestion).toHaveBeenCalledWith({ reason: 'disconnect', restartSocket: true });
+ });
+ });
diff --cc server/services/beeperOutbox.js
index 0000000000,c83da6c095..739d8e2cdb
mode 000000,100644..100644
--- a/server/services/beeperOutbox.js
+++ b/server/services/beeperOutbox.js
@@@ -1,0 -1,725 +1,732 @@@
+ /**
+ * Beeper outbound outbox (fork issue #36, decided on #8, confirmation
+ * transport decided on #12).
+ *
+ * PortOS's send posture is upstream's tier 2 — draft → human approve → human
+ * send, through ONE service whose only non-test caller is a human HTTP route
+ * (`server/routes/beeper.js`). `messageSender.sendDraft` is the shape this
+ * reuses: the `status === 'approved'` gate, the mismatch gate, and the
+ * one-human-caller rule. What it deliberately does NOT reuse is that service's
+ * FILE-BACKED draft store — the `beeper_*` tables are `db-primary`, and #8
+ * rejected straddling two storage classifications. Hence a Beeper-native
+ * `beeper_outbox` row.
+ *
+ * Four rules this module exists to enforce:
+ *
+ * 1. **The row is written before the POST.** Intent survives a crash between
+ * the click and the send, and the row is the one serialization point per
+ * entry — the `approved → sending` transition is a conditional UPDATE, so
+ * 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.
+ * 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
+ * to `GET /v1/chats/{chatID}/messages/{messageID}` — WebSocket delivery is
+ * at-most-once with no replay, so the socket cannot be the only path.
+ * Neither path sends anything.
+ * 4. **A runaway breaker, not a rate quota.** Every send is one human click,
+ * so a quota paces a human who is already paced. The breaker catches the
+ * failure this design cannot otherwise see — a software loop — and only a
+ * human clears it.
+ *
+ * No AI drafting and no AI review (#8 decision 8), and no agent reach: no
+ * `cosToolRegistry` entry, no voice tool, no scheduler. `beeperOutboxHumanGate.test.js`
+ * asserts that structurally rather than by convention.
+ */
+
+ import { query } from '../lib/db.js';
+ import { BeeperApiError, getMessage, listMessagesPage, sendMessage } from './beeperClient.js';
+ import { normalizeMessageRow } from './beeperSync.js';
+ import { beeperSocketEvents } from './beeperSocketEvents.js';
+
+ const LOG_PREFIX = '🫧 Beeper outbox';
+
+ /**
+ * The socket is the fast path; this is the floor under it. 30 s is #12's
+ * decision: long enough that a healthy `message.upserted` almost always wins
+ * the race (so the fallback GET is rare rather than routine), short enough
+ * that a dropped frame does not leave a send unresolved on screen.
+ */
+ export const CONFIRMATION_TIMEOUT_MS = 30_000;
+
+ /**
+ * The code and the recorded reason for a send this process found stranded in
+ * `sending` at boot — a POST that was in flight when the previous process died.
+ *
+ * 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.
+ */
+ export const SEND_INTERRUPTED_CODE = 'SEND_INTERRUPTED';
+ export const SEND_INTERRUPTED_MESSAGE = 'Delivery unconfirmed: PortOS restarted mid-send. Check the chat before retrying.';
+
+ /**
+ * 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
+ * reach it with no `beeper_outbox` table — which is not a fault to narrate: an
+ * absent table holds no interrupted sends. Every other error still logs.
+ */
+ const UNDEFINED_TABLE = '42P01';
+
+ /**
+ * Runaway-breaker thresholds. Deliberately far above anything a human at a
+ * composer produces and far below what an unattended loop produces in the same
+ * minute: eleven sends inside a minute is one every 5.5 seconds, sustained,
+ * which is a fault rather than a conversation. The consecutive-failure arm
+ * catches the other loop shape — a caller that keeps firing at a Beeper that
+ * keeps refusing.
+ */
+ export const BREAKER_WINDOW_MS = 60_000;
+ export const BREAKER_MAX_SENDS_IN_WINDOW = 10;
+ export const BREAKER_MAX_CONSECUTIVE_FAILURES = 3;
+
+ const DEFAULT_RUNTIME = Object.freeze({
+ now: () => Date.now(),
+ setTimeout: (fn, ms) => setTimeout(fn, ms),
+ clearTimeout: (handle) => clearTimeout(handle),
+ });
+
+ let runtime = { ...DEFAULT_RUNTIME };
+
+ // Breaker + confirmation state is in-memory ON PURPOSE. The failure it defends
+ // against is a live in-process loop, so process-lifetime scope is the right
+ // scope: a restart clears it, and a loop that survived the restart re-trips it
+ // within the same window. Persisting it would instead let one bad minute wedge
+ // the composer across restarts with no way back except the same human click.
+ let sendTimestamps = [];
+ let consecutiveFailures = 0;
+ let breaker = { tripped: false, reason: null, trippedAt: null };
+
+ // outboxId → { chatId, body, pendingMessageId, requestedAt, timer, resolving }
+ const pendingConfirmations = new Map();
+ let invalidateListenerAttached = false;
+
+ /** Test seam for injected time (mirrors `beeperSocket.js`'s runtime object). */
+ export function configureOutboxRuntime(overrides = {}) {
+ runtime = { ...DEFAULT_RUNTIME, ...overrides };
+ }
+
+ export function resetOutboxRuntime() {
+ runtime = { ...DEFAULT_RUNTIME };
+ }
+
+ // ---------------------------------------------------------------------------
+ // Runaway breaker
+ // ---------------------------------------------------------------------------
+
+ function trip(reason) {
+ breaker = { tripped: true, reason, trippedAt: new Date(runtime.now()).toISOString() };
+ console.error(`${LOG_PREFIX}: runaway breaker tripped (${reason}) — sends blocked until a human clears it`);
+ }
+
+ /**
+ * The breaker's read model, surfaced on `GET /api/beeper/status`. `tripped` is
+ * the gate; the two counters ride along so the card can say WHY rather than
+ * just that something is blocked.
+ */
+ export function getOutboxBreakerState() {
+ const cutoff = runtime.now() - BREAKER_WINDOW_MS;
+ return {
+ tripped: breaker.tripped,
+ reason: breaker.reason,
+ trippedAt: breaker.trippedAt,
+ sendsInWindow: sendTimestamps.filter((ts) => ts > cutoff).length,
+ consecutiveFailures,
+ windowMs: BREAKER_WINDOW_MS,
+ maxSendsInWindow: BREAKER_MAX_SENDS_IN_WINDOW,
+ maxConsecutiveFailures: BREAKER_MAX_CONSECUTIVE_FAILURES,
+ };
+ }
+
+ /**
+ * The ONLY way back. Reachable exclusively from `POST /api/beeper/outbox/breaker/clear`
+ * — no timer, no backoff, no automatic recovery: a breaker that resets itself
+ * is a delay, not a breaker.
+ */
+ export function clearOutboxBreaker() {
+ breaker = { tripped: false, reason: null, trippedAt: null };
+ sendTimestamps = [];
+ consecutiveFailures = 0;
+ console.log(`${LOG_PREFIX}: runaway breaker cleared by a human action`);
+ return getOutboxBreakerState();
+ }
+
+ function assertBreakerClosed() {
+ if (!breaker.tripped) return;
+ throw new BeeperApiError(
+ `Beeper sending is blocked by the runaway breaker (${breaker.reason}). Clear it to send again.`,
+ { status: 429, code: 'OUTBOX_BREAKER_OPEN', retryable: false },
+ );
+ }
+
+ /**
+ * Count this attempt against the window BEFORE the POST, and refuse the one
+ * that crosses the line. Counting after the POST would let the loop's own
+ * first burst through before the breaker ever saw it.
+ */
+ function registerSendAttempt() {
+ const now = runtime.now();
+ sendTimestamps = sendTimestamps.filter((ts) => ts > now - BREAKER_WINDOW_MS);
+ sendTimestamps.push(now);
+ if (sendTimestamps.length > BREAKER_MAX_SENDS_IN_WINDOW) {
+ trip(`more than ${BREAKER_MAX_SENDS_IN_WINDOW} sends in ${BREAKER_WINDOW_MS / 1000}s`);
+ assertBreakerClosed();
+ }
+ }
+
+ function registerSendFailure() {
+ consecutiveFailures += 1;
+ if (consecutiveFailures >= BREAKER_MAX_CONSECUTIVE_FAILURES) {
+ trip(`${consecutiveFailures} consecutive send failures`);
+ }
+ }
+
+ function registerSendSuccess() {
+ consecutiveFailures = 0;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Rows
+ // ---------------------------------------------------------------------------
+
+ 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"`;
+
+ async function readEntry(id) {
+ const result = await query(`SELECT ${ENTRY_COLUMNS} FROM beeper_outbox WHERE id = $1`, [id]);
+ return result?.rows?.[0] ?? null;
+ }
+
+ /** Every outbox row for one conversation, newest first — including failed ones. */
+ export async function listOutboxEntries({ conversationId, limit = 50 } = {}) {
+ const result = await query(
+ `SELECT ${ENTRY_COLUMNS} FROM beeper_outbox
+ 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 : [];
+ }
+
+ /**
+ * Step one of the two-step send: a human composed this text and submitted it.
+ * The row lands `approved` (with `approved_at` stamped) because the create call
+ * itself IS the approval — it is reachable only from a human HTTP route, and
+ * the send is a second, separate human action against the row this returns.
+ * `draft` exists in the state CHECK for a later persisted/AI-assisted draft and
+ * has no writer here; the send gate keys on `approved`, so nothing can send
+ * from it.
+ */
+ export async function createOutboxEntry({ conversationId, body }) {
+ const text = typeof body === 'string' ? body.trim() : '';
+ if (!text) {
+ throw new BeeperApiError('An outbox entry needs a non-empty message body', {
+ status: 400, code: 'OUTBOX_EMPTY_BODY', retryable: false,
+ });
+ }
+
+ const conversation = await query(
+ 'SELECT id, source_chat_id AS "sourceChatId" FROM beeper_conversations WHERE id = $1',
+ [conversationId],
+ );
+ const chatId = conversation?.rows?.[0]?.sourceChatId;
+ if (!chatId) {
+ throw new BeeperApiError('Conversation not found in the Beeper mirror', {
+ status: 404, code: 'CONVERSATION_NOT_FOUND', retryable: false,
+ });
+ }
+
+ const inserted = await query(
+ `INSERT INTO beeper_outbox (conversation_id, chat_id, body, state, approved_at)
+ VALUES ($1, $2, $3, 'approved', NOW())
+ RETURNING ${ENTRY_COLUMNS}`,
+ [conversationId, chatId, text],
+ );
+ console.log(`${LOG_PREFIX}: entry approved for chat (${text.length} chars)`);
+ return inserted.rows[0];
+ }
+
+ /**
+ * States that mean PortOS has already ADDRESSED this conversation — the POST
+ * reached Beeper, whatever the mirror has confirmed since. `sent` alone is the
+ * wrong test: an `awaiting-confirmation` row is a send that left this machine
+ * and was very likely delivered (the unresolved case is deliberately not
+ * `failed` for exactly that reason), and `sending` is one in flight right now.
+ * Counting only `sent` re-asks the first-contact question on the next message
+ * to someone PortOS has already messaged — which is precisely the prompt the
+ * design says must fire once and never again, or the user learns to click
+ * through it.
+ */
+ const CONTACTED_STATES = ['sent', 'awaiting-confirmation', 'sending'];
+
+ /**
+ * Whether PortOS has ever ADDRESSED this conversation. First contact is the
+ * case #8 decision 5 puts a confirmation on — a first message to a possibly
+ * mis-resolved handle on a possibly wrong network — and it is the only one,
+ * because confirming every reply trains the user to click through.
+ *
+ * Keyed on EITHER source of outbound history, not the outbox alone (fork
+ * issue #82): a mirrored `beeper_messages` row with `is_sender` true means the
+ * user has messaged this chat from some client, which is exactly the "have I
+ * addressed this recipient and network before" question the confirmation
+ * exists to answer — restricting it to sends this particular PortOS install
+ * made re-asked the question on every chat with older phone/desktop history,
+ * which is precisely the "fires when it should not" case #82 reports. The
+ * outbox arm stays for the gap the mirror cannot see: a send whose POST left
+ * this machine but has not (yet, or ever) come back through the mirror as an
+ * `isSender` message — `awaiting-confirmation` and `sending` are exactly that
+ * gap, per `CONTACTED_STATES` above. Either source alone is sufficient; the
+ * confirmation is reserved for a conversation neither source has any
+ * outbound history for.
+ */
+ export async function isFirstContact(conversationId) {
+ const outboxSend = await query(
+ `SELECT 1 FROM beeper_outbox
+ WHERE conversation_id = $1 AND state = ANY($2::text[]) LIMIT 1`,
+ [conversationId, CONTACTED_STATES],
+ );
+ if ((outboxSend?.rows?.length ?? 0) > 0) return false;
+
+ const mirroredSend = await query(
+ `SELECT 1 FROM beeper_messages
+ WHERE conversation_id = $1 AND is_sender = TRUE LIMIT 1`,
+ [conversationId],
+ );
+ return (mirroredSend?.rows?.length ?? 0) === 0;
+ }
+
+ async function markFailed(id, code, message) {
+ await query(
+ `UPDATE beeper_outbox SET state = 'failed', error_code = $2, error_message = $3, updated_at = NOW()
+ WHERE id = $1`,
+ [id, code || 'SEND_FAILED', String(message || '').slice(0, 2000)],
+ );
+ }
+
+ /**
+ * Discard a row the human declined to send — the first-contact confirmation's
+ * "Cancel" (#53's fix; the original design deliberately left the row
+ * `approved` and visible, which the client had no way to render or dismiss,
+ * so it surfaced as a permanent phantom "Sending…" bubble). Reachable only
+ * while the row is `approved`: nothing has POSTed to Beeper for it yet, so
+ * removing it is a pure local record change, never an unsend. Anything past
+ * `approved` is a record of a real send attempt and stays — the client
+ * composes a new entry rather than discarding one that already touched the
+ * wire.
+ */
+ export async function discardOutboxEntry(id) {
+ const entry = await readEntry(id);
+ if (!entry) {
+ throw new BeeperApiError('Outbox entry not found', {
+ status: 404, code: 'OUTBOX_ENTRY_NOT_FOUND', retryable: false,
+ });
+ }
+ if (entry.state !== 'approved') {
+ throw new BeeperApiError(
+ `Outbox entry is "${entry.state}", must be "approved" to discard — it has already been sent or attempted.`,
+ { status: 409, code: 'OUTBOX_INVALID_STATE', retryable: false },
+ );
+ }
+ await query("DELETE FROM beeper_outbox WHERE id = $1 AND state = 'approved'", [id]);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Send
+ // ---------------------------------------------------------------------------
+
+ /**
+ * Step two: perform the send. Every gate below runs BEFORE the row is claimed,
+ * so a refused send leaves the row exactly as it was and re-sendable by the
+ * same human action.
+ *
+ * `confirmFirstContact` must be explicitly `true` on the first outbound message
+ * to a conversation. The client obtains it from an inline confirmation row, not
+ * a `window.confirm` (client conventions forbid the latter).
+ */
+ export async function sendOutboxEntry(id, { confirmFirstContact = false } = {}) {
+ const entry = await readEntry(id);
+ if (!entry) {
+ throw new BeeperApiError('Outbox entry not found', {
+ status: 404, code: 'OUTBOX_ENTRY_NOT_FOUND', retryable: false,
+ });
+ }
+ if (entry.state !== 'approved') {
+ throw new BeeperApiError(
+ `Outbox entry is "${entry.state}", must be "approved" to send. A failed or already-sent entry is never re-sent in place — compose a new message.`,
+ { status: 409, code: 'OUTBOX_INVALID_STATE', retryable: false },
+ );
+ }
+ assertBreakerClosed();
+ if (!confirmFirstContact && await isFirstContact(entry.conversationId)) {
+ throw new BeeperApiError(
+ 'This is the first message PortOS has ever sent to this conversation — confirm the recipient and network before sending.',
+ { status: 409, code: 'FIRST_CONTACT_CONFIRMATION_REQUIRED', retryable: false },
+ );
+ }
+ registerSendAttempt();
+
+ // The serialization point. A second concurrent send of the same row loses
+ // this conditional UPDATE and never reaches the POST.
+ const claimed = await query(
+ "UPDATE beeper_outbox SET state = 'sending', updated_at = NOW() WHERE id = $1 AND state = 'approved' RETURNING id",
+ [id],
+ );
+ if ((claimed?.rowCount ?? 0) !== 1) {
+ throw new BeeperApiError('Outbox entry is already being sent', {
+ status: 409, code: 'OUTBOX_INVALID_STATE', retryable: 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 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;
+ await 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', {
+ status: err?.status === 0 || !err?.status ? 0 : err.status,
+ code: err?.code || 'SEND_FAILED',
+ retryable: false,
+ details: { outboxId: id },
+ });
+ }
+
+ 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],
+ );
+ 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];
+ }
+
+ // ---------------------------------------------------------------------------
+ // Confirmation (socket first, 30s GET fallback)
+ // ---------------------------------------------------------------------------
+
+ function detachInvalidateListener() {
+ if (!invalidateListenerAttached || pendingConfirmations.size > 0) return;
+ beeperSocketEvents.off('invalidate', handleInvalidation);
+ invalidateListenerAttached = false;
+ }
+
+ /**
+ * Relayed invalidation frames carry ids and kinds only — never bodies — so a
+ * frame is a PROMPT to resolve, not the resolution. Any `message.upserted` on a
+ * chat with a send in flight triggers the same lookup the timer would have run,
+ * just sooner.
+ *
+ * Runs outside the Express lifecycle (an EventEmitter callback), so the
+ * rejection is caught and logged here rather than crashing the process.
+ */
+ function handleInvalidation(frame) {
+ if (frame?.kind !== 'message.upserted') return;
+ for (const [id, pending] of pendingConfirmations) {
+ if (frame.chatID && frame.chatID !== pending.chatId) continue;
+ resolveConfirmation(id, 'socket').catch((err) => {
+ console.error(`${LOG_PREFIX}: socket-triggered confirmation failed: ${err.message}`);
+ });
+ }
+ }
+
+ /**
+ * `requestedAt` defaults to now because the ordinary caller is the send that
+ * just happened. The boot reconcile passes the row's persisted send moment
+ * instead: it is the floor `lookupSentMessage` matches timestamps against, so
+ * dating a week-old re-armed row to boot time would reject the very message it
+ * is looking for.
+ */
+ function armConfirmation({ id, chatId, conversationId, body, pendingMessageId, requestedAt = runtime.now() }) {
+ const timer = runtime.setTimeout(() => {
+ resolveConfirmation(id, 'fallback-timeout').catch((err) => {
+ console.error(`${LOG_PREFIX}: fallback confirmation failed: ${err.message}`);
+ });
+ }, CONFIRMATION_TIMEOUT_MS);
+ pendingConfirmations.set(id, {
+ chatId, conversationId, body, pendingMessageId, requestedAt, timer, resolving: false,
+ });
+ if (!invalidateListenerAttached) {
+ beeperSocketEvents.on('invalidate', handleInvalidation);
+ invalidateListenerAttached = true;
+ }
+ }
+
+ /**
+ * Find the message this send became. Two lookups, in order, and NEITHER sends:
+ *
+ * 1. `GET /v1/chats/{chatID}/messages/{messageID}` with the `pendingMessageID`
+ * — the spec states that endpoint accepts a pending id, a final id, or a
+ * Matrix event id, which is exactly what makes the resolve step work.
+ * 2. Failing that (no pending id came back, or the id 404s because the network
+ * assigned a final one), the chat's newest page, matched on
+ * `isSender` + the exact body + a timestamp at or after the send. The body
+ * match is deliberately exact: a near-match is a different message.
+ */
+ async function lookupSentMessage(pending) {
+ if (pending.pendingMessageId) {
+ const direct = await getMessage(pending.chatId, pending.pendingMessageId)
+ .then((value) => value)
+ .catch((err) => {
+ if (err?.code === 'NOT_FOUND') return null;
+ throw err;
+ });
+ if (direct?.id) return direct;
+ }
+
+ const page = await listMessagesPage(pending.chatId);
+ const items = Array.isArray(page?.items) ? page.items : [];
+ // A minute of slack below the send: `timestamp` is assigned by the network,
+ // not by PortOS, and the two clocks are not the same clock.
+ const floor = pending.requestedAt - 60_000;
+ return items.find((message) => message?.isSender === true
+ && message?.text === pending.body
+ && (!message?.timestamp || new Date(message.timestamp).getTime() >= floor)) ?? 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.
+ */
+ async function mirrorSentMessage(conversationId, message) {
+ const row = normalizeMessageRow(message, new Date(runtime.now()).toISOString());
+ if (!row.id) return;
+ await 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],
+ );
+ }
+
+ function releasePending(id) {
+ const pending = pendingConfirmations.get(id);
+ if (pending?.timer !== undefined) runtime.clearTimeout(pending.timer);
+ pendingConfirmations.delete(id);
+ detachInvalidateListener();
+ }
+
+ /**
+ * Resolve one in-flight send. Idempotent by construction: the `resolving` flag
+ * stops the socket path and the timer path overlapping, and the terminal UPDATE
+ * is conditional on `awaiting-confirmation`, so whichever path lands first is
+ * the one that writes.
+ *
+ * The unresolved case is deliberately NOT `failed`. A send whose message cannot
+ * be found may well have been delivered, and marking it failed invites a
+ * re-send — the one mistake that cannot be taken back, since Beeper's own
+ * `DELETE` unsends for everyone. It stays `awaiting-confirmation` with a
+ * recorded reason, which reads as "sent, unconfirmed" and offers no re-send.
+ */
+ async function resolveConfirmation(id, reason) {
+ const pending = pendingConfirmations.get(id);
- if (!pending || pending.resolving) return null;
++ if (!pending) return null;
++ if (reason === 'fallback-timeout') 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;
+ pending.resolving = true;
+
+ const found = await lookupSentMessage(pending)
+ .then((value) => ({ ok: true, value }))
+ .catch((err) => ({ ok: false, err }));
+ pending.resolving = false;
++ if (pendingConfirmations.get(id) !== pending) return null;
++ if (pending.deadlineReached) reason = 'fallback-timeout';
+
+ if (!found.ok) {
+ // A lookup failure on the socket path costs nothing — the timer is still
+ // armed. On the fallback path it is the end of the road.
+ console.error(`${LOG_PREFIX}: confirmation lookup failed (${found.err?.code || 'unknown'})`);
+ if (reason === 'fallback-timeout') {
+ await noteUnresolved(id, `Confirmation lookup failed: ${found.err?.code || 'unknown error'}`);
+ }
+ return null;
+ }
+
+ const message = found.value;
+ if (!message) {
+ if (reason === 'fallback-timeout') {
+ await noteUnresolved(id, 'Beeper reported no matching message within 30s — it may still have been delivered, so it was not re-sent.');
+ }
+ return null;
+ }
+
+ 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`);
+ 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(),
+ });
+ 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) {
+ releasePending(id);
+ await query(
+ `UPDATE beeper_outbox SET error_code = 'CONFIRMATION_UNRESOLVED', error_message = $2, updated_at = NOW()
+ WHERE id = $1 AND state = 'awaiting-confirmation'`,
+ [id, 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`);
+ }
+
+ /**
+ * Drop every armed confirmation timer. Used by the suite between cases; there
+ * is no production caller, because a process that is exiting takes its timers
+ * with it and the durable state is the row, not the timer.
+ */
+ export function cancelPendingConfirmations() {
+ for (const id of [...pendingConfirmations.keys()]) releasePending(id);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Boot reconcile
+ // ---------------------------------------------------------------------------
+
+ /** 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 ?? '');
+ return Number.isFinite(stamped) ? stamped : runtime.now();
+ }
+
+ /**
+ * Reconcile the two NON-TERMINAL states against a process that no longer
+ * exists. Called once per server start, from `bootstrap.js`, regardless of
+ * whether the Beeper feature is armed — a stranded row is stranded whether or
+ * not ingestion is switched on.
+ *
+ * `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.
+ *
+ * Two different faults, two different answers:
+ *
+ * - **`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.
+ * - **`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
+ * (`getMessage`, then the newest page) and sends nothing. A row already
+ * recorded `CONFIRMATION_UNRESOLVED` is re-armed too: the message may have
+ * landed in the mirror since, and one more GET can only upgrade the record.
+ *
+ * Terminal rows (`sent`, `failed`) are not touched. Idempotent: the second call
+ * finds no `sending` rows left, and skips every `awaiting-confirmation` row the
+ * first call already armed rather than stacking a second timer on it.
+ *
+ * @returns {Promise<{interrupted: number, rearmed: number}>}
+ */
+ export async function reconcileOutboxOnBoot() {
+ const interrupted = await query(
+ `UPDATE beeper_outbox SET state = 'failed', error_code = $1, error_message = $2, updated_at = NOW()
+ WHERE state = 'sending' RETURNING id`,
+ [SEND_INTERRUPTED_CODE, SEND_INTERRUPTED_MESSAGE],
+ ).catch((err) => {
+ if (err?.code === UNDEFINED_TABLE) return null;
+ throw err;
+ });
+ // The table does not exist yet, so neither do the rows this would reconcile.
+ if (!interrupted) return { interrupted: 0, rearmed: 0 };
+
+ const inFlight = await query(
+ `SELECT id, conversation_id AS "conversationId", chat_id AS "chatId", body,
+ pending_message_id AS "pendingMessageId", created_at AS "createdAt", updated_at AS "updatedAt"
+ FROM beeper_outbox WHERE state = 'awaiting-confirmation'`,
+ );
+
+ let rearmed = 0;
+ for (const row of inFlight?.rows ?? []) {
+ if (pendingConfirmations.has(row.id)) continue;
+ armConfirmation({
+ id: row.id,
+ chatId: row.chatId,
+ conversationId: row.conversationId,
+ body: row.body,
+ pendingMessageId: row.pendingMessageId,
+ requestedAt: persistedSendMoment(row),
+ });
+ rearmed += 1;
+ }
+
+ const counts = { interrupted: interrupted.rows?.length ?? 0, rearmed };
+ if (counts.interrupted || counts.rearmed) {
+ console.log(`${LOG_PREFIX}: boot reconcile — ${counts.interrupted} interrupted send(s) failed, ${counts.rearmed} awaiting confirmation re-armed`);
+ }
+ return counts;
+ }
+
+ /** The outbox's slice of `GET /api/beeper/status`. */
+ export function getOutboxStatus() {
+ return {
+ breaker: getOutboxBreakerState(),
+ awaitingConfirmation: pendingConfirmations.size,
+ };
+ }
diff --cc server/services/beeperOutbox.test.js
index 0000000000,0559828d68..9337873950
mode 000000,100644..100644
--- a/server/services/beeperOutbox.test.js
+++ b/server/services/beeperOutbox.test.js
@@@ -1,0 -1,793 +1,810 @@@
+ import {
+ describe, it, expect, vi, beforeEach, afterEach,
+ } from 'vitest';
+
+ /**
+ * The outbound outbox (#36, decided on #8; confirmation transport on #12).
+ *
+ * Time is INJECTED — the confirmation fallback is a 30-second contract and the
+ * breaker is a 60-second window, and proving either with a real sleep would put
+ * a minute-plus of wall clock into CI for behaviour a fake clock pins exactly.
+ *
+ * `beeperClient` is mocked at the boundary: NOTHING in this suite reaches a
+ * real Beeper Desktop, and the assertions that matter are about how many times
+ * `sendMessage` is called (exactly once per entry, ever) rather than what the
+ * network did with it.
+ *
+ * The DB is a small in-memory stand-in keyed on the same SQL this service
+ * writes, so a state transition is asserted as a row state rather than as a
+ * mock call. The real DDL is covered by `lib/db/schema/beeper.db.test.js`.
+ */
+
+ class BeeperApiError extends Error {
+ constructor(message, { status = 500, code, retryable = false, details } = {}) {
+ super(message);
+ this.name = 'BeeperApiError';
+ this.status = status;
+ this.code = code;
+ this.retryable = retryable;
+ this.details = details;
+ }
+ }
+
+ const sendMessage = vi.fn();
+ const getMessage = vi.fn();
+ const listMessagesPage = vi.fn();
+
+ vi.mock('./beeperClient.js', () => ({
+ BeeperApiError,
+ sendMessage: (...args) => sendMessage(...args),
+ getMessage: (...args) => getMessage(...args),
+ listMessagesPage: (...args) => listMessagesPage(...args),
+ }));
+
+ // 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();
+ const conversations = new Map();
+ const mirrored = [];
+ const mirroredSql = [];
+ // The mirrored thread's own outbound history — separate from `mirrored`
+ // above, which only ever holds what THIS module's own `mirrorSentMessage`
+ // wrote. `isFirstContact` (#82) also has to see history a sync sweep mirrored
+ // from the user's phone or another client, which `seedMirroredMessage` below
+ // stands in for.
+ const mirroredMessages = [];
+ let nextId = 1;
+
+ /** A `beeper_messages` row synced in from Beeper, never through this outbox. */
+ function seedMirroredMessage(conversationId, { isSender = true } = {}) {
+ mirroredMessages.push({ conversationId, isSender });
+ }
+
+ const entryView = (row) => ({ ...row });
+
+ const query = vi.fn(async (sql, params = []) => {
+ 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 };
+ }
+ if (/INSERT INTO beeper_outbox/.test(sql)) {
+ const row = {
+ id: `outbox-${nextId++}`,
+ conversationId: params[0],
+ chatId: params[1],
+ body: params[2],
+ state: 'approved',
+ pendingMessageId: null,
+ messageId: null,
+ errorCode: null,
+ errorMessage: null,
+ createdAt: '2026-09-01T00:00:00.000Z',
+ approvedAt: '2026-09-01T00:00:00.000Z',
+ updatedAt: '2026-09-01T00:00:00.000Z',
+ sentAt: null,
+ };
+ outbox.set(row.id, row);
+ return { rows: [entryView(row)], rowCount: 1 };
+ }
+ if (/SELECT 1 FROM beeper_outbox\s+WHERE conversation_id = \$1 AND state = ANY/.test(sql)) {
+ const contacted = [...outbox.values()]
+ .filter((row) => row.conversationId === params[0] && params[1].includes(row.state));
+ return { rows: contacted.map(() => ({ '?column?': 1 })), rowCount: contacted.length };
+ }
+ if (/SELECT 1 FROM beeper_messages\s+WHERE conversation_id = \$1 AND is_sender = TRUE/.test(sql)) {
+ const sent = mirroredMessages
+ .filter((message) => message.conversationId === params[0] && message.isSender === true);
+ return { rows: sent.map(() => ({ '?column?': 1 })), rowCount: sent.length };
+ }
+ // The boot reconcile's two statements. Both are keyed on a STATE rather than
+ // on an id, so they sit ahead of the single-row branches whose patterns they
+ // would otherwise be caught by.
+ if (/UPDATE beeper_outbox SET state = 'failed'[\s\S]*WHERE state = 'sending'/.test(sql)) {
+ const stranded = [...outbox.values()].filter((row) => row.state === 'sending');
+ for (const row of stranded) {
+ row.state = 'failed';
+ row.errorCode = params[0];
+ row.errorMessage = params[1];
+ }
+ return { rows: stranded.map((row) => ({ id: row.id })), rowCount: stranded.length };
+ }
+ if (/FROM beeper_outbox WHERE state = 'awaiting-confirmation'/.test(sql)) {
+ return { rows: [...outbox.values()].filter((row) => row.state === 'awaiting-confirmation').map(entryView) };
+ }
+ if (/FROM beeper_outbox\s+WHERE conversation_id = \$1 ORDER BY/.test(sql)) {
+ return { rows: [...outbox.values()].filter((row) => row.conversationId === params[0]).map(entryView) };
+ }
+ if (/^SELECT[\s\S]*FROM beeper_outbox WHERE id = \$1/.test(sql)) {
+ const row = outbox.get(params[0]);
+ return { rows: row ? [entryView(row)] : [], rowCount: row ? 1 : 0 };
+ }
+ if (/UPDATE beeper_outbox SET state = 'sending'/.test(sql)) {
+ const row = outbox.get(params[0]);
+ if (!row || row.state !== 'approved') return { rows: [], rowCount: 0 };
+ row.state = 'sending';
+ return { rows: [{ id: row.id }], rowCount: 1 };
+ }
+ if (/UPDATE beeper_outbox SET state = 'awaiting-confirmation'/.test(sql)) {
+ const row = outbox.get(params[0]);
+ row.state = 'awaiting-confirmation';
+ row.pendingMessageId = params[1];
+ return { rows: [entryView(row)], rowCount: 1 };
+ }
+ if (/UPDATE beeper_outbox SET state = 'failed'/.test(sql)) {
+ const row = outbox.get(params[0]);
+ row.state = 'failed';
+ row.errorCode = params[1];
+ row.errorMessage = params[2];
+ return { rows: [], rowCount: 1 };
+ }
+ 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 };
+ row.state = 'sent';
+ row.messageId = params[1];
+ row.sentAt = params[2] ?? '2026-09-01T00:00:05.000Z';
+ row.errorCode = null;
+ row.errorMessage = null;
+ return { rows: [entryView(row)], rowCount: 1 };
+ }
+ if (/UPDATE beeper_outbox SET error_code = 'CONFIRMATION_UNRESOLVED'/.test(sql)) {
+ const row = outbox.get(params[0]);
+ if (!row || row.state !== 'awaiting-confirmation') return { rows: [], rowCount: 0 };
+ row.errorCode = 'CONFIRMATION_UNRESOLVED';
+ row.errorMessage = params[1];
+ 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 };
+ outbox.delete(params[0]);
+ return { rows: [], rowCount: 1 };
+ }
+ if (/INSERT INTO beeper_messages/.test(sql)) {
+ mirroredSql.push(sql);
+ mirrored.push(params);
+ return { rows: [], rowCount: 1 };
+ }
+ throw new Error(`unexpected SQL in test: ${sql.slice(0, 60)}`);
+ });
+
+ 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,
+ cancelPendingConfirmations, clearOutboxBreaker, configureOutboxRuntime, createOutboxEntry,
+ discardOutboxEntry, getOutboxBreakerState, getOutboxStatus, isFirstContact, listOutboxEntries,
+ reconcileOutboxOnBoot, resetOutboxRuntime, sendOutboxEntry,
+ } = await import('./beeperOutbox.js');
+ const { beeperSocketEvents } = await import('./beeperSocketEvents.js');
+
+ // Timers are recorded rather than run, so a test fires exactly the one it cares
+ // about — the same controllable-clock shape `beeperSocket.test.js` uses.
+ function makeClock() {
+ const timers = new Map();
+ let nextTimerId = 1;
+ let current = 0;
+ return {
+ now: () => current,
+ advance: (ms) => { current += ms; },
+ setTimeout: (fn, ms) => {
+ const id = nextTimerId++;
+ timers.set(id, { fn, ms });
+ return id;
+ },
+ clearTimeout: (id) => { timers.delete(id); },
+ runTimersWithDelay: (ms) => {
+ const due = [...timers.entries()].filter(([, timer]) => timer.ms === ms);
+ for (const [id, timer] of due) { timers.delete(id); timer.fn(); }
+ return due.length;
+ },
+ pending: () => timers.size,
+ };
+ }
+
+ let clock;
+ const flush = () => new Promise((resolve) => setImmediate(resolve));
+
+ const CONVERSATION_ID = '11111111-1111-4111-8111-111111111111';
+ const OTHER_CONVERSATION_ID = '22222222-2222-4222-8222-222222222222';
+ const CHAT_ID = 'example-chat-1';
+
+ const sentMessage = (overrides = {}) => ({
+ id: 'msg-final-1',
+ chatID: CHAT_ID,
+ senderID: 'user-self',
+ text: 'hello there',
+ timestamp: '2026-09-01T00:00:05.000Z',
+ sortKey: '900',
+ isSender: true,
+ ...overrides,
+ });
+
+ async function approvedEntry(body = 'hello there', conversationId = CONVERSATION_ID) {
+ return createOutboxEntry({ conversationId, body });
+ }
+
+ /** A conversation PortOS has already sent to, so first contact is not in play. */
+ function markPriorSend(conversationId = CONVERSATION_ID) {
+ const row = {
+ id: `outbox-prior-${nextId++}`,
+ conversationId,
+ chatId: CHAT_ID,
+ body: 'an earlier message',
+ state: 'sent',
+ pendingMessageId: null,
+ messageId: 'msg-earlier',
+ errorCode: null,
+ errorMessage: null,
+ createdAt: '2026-08-31T00:00:00.000Z',
+ approvedAt: '2026-08-31T00:00:00.000Z',
+ updatedAt: '2026-08-31T00:00:01.000Z',
+ sentAt: '2026-08-31T00:00:01.000Z',
+ };
+ outbox.set(row.id, row);
+ }
+
+ /**
+ * A row the PREVIOUS process left behind: persisted mid-flight, with nothing
+ * armed in memory for it, which is exactly the state a restart produces.
+ */
+ function strandedRow(state, overrides = {}) {
+ const row = {
+ id: `outbox-stranded-${nextId++}`,
+ conversationId: CONVERSATION_ID,
+ chatId: CHAT_ID,
+ body: 'hello there',
+ state,
+ pendingMessageId: state === 'awaiting-confirmation' ? 'pending-1' : null,
+ messageId: null,
+ errorCode: null,
+ errorMessage: null,
+ createdAt: '2026-09-01T00:00:00.000Z',
+ approvedAt: '2026-09-01T00:00:00.000Z',
+ updatedAt: '2026-09-01T00:00:01.000Z',
+ sentAt: null,
+ ...overrides,
+ };
+ outbox.set(row.id, row);
+ return row;
+ }
+
+ beforeEach(() => {
+ outbox.clear();
+ conversations.clear();
+ mirrored.length = 0;
+ mirroredSql.length = 0;
+ mirroredMessages.length = 0;
+ nextId = 1;
+ conversations.set(CONVERSATION_ID, CHAT_ID);
+ conversations.set(OTHER_CONVERSATION_ID, 'example-chat-2');
+ sendMessage.mockReset();
+ getMessage.mockReset();
+ listMessagesPage.mockReset();
+ query.mockClear();
+ sendMessage.mockResolvedValue({ chatID: CHAT_ID, pendingMessageID: 'pending-1' });
+ getMessage.mockResolvedValue(sentMessage());
+ listMessagesPage.mockResolvedValue({ items: [] });
+ clock = makeClock();
+ configureOutboxRuntime({ now: clock.now, setTimeout: clock.setTimeout, clearTimeout: clock.clearTimeout });
+ clearOutboxBreaker();
+ });
+
+ afterEach(() => {
+ cancelPendingConfirmations();
+ clearOutboxBreaker();
+ resetOutboxRuntime();
+ });
+
+ describe('createOutboxEntry — step one, the durable row', () => {
+ it('writes an approved row carrying the source chat id, before anything is sent', async () => {
+ const entry = await approvedEntry();
+ expect(entry.state).toBe('approved');
+ expect(entry.chatId).toBe(CHAT_ID);
+ expect(entry.body).toBe('hello there');
+ expect(sendMessage).not.toHaveBeenCalled();
+ });
+
+ it('refuses an empty body and an unknown conversation', async () => {
+ await expect(createOutboxEntry({ conversationId: CONVERSATION_ID, body: ' ' }))
+ .rejects.toMatchObject({ code: 'OUTBOX_EMPTY_BODY', status: 400 });
+ await expect(createOutboxEntry({ conversationId: '33333333-3333-4333-8333-333333333333', body: 'hi' }))
+ .rejects.toMatchObject({ code: 'CONVERSATION_NOT_FOUND', status: 404 });
+ });
+
+ it('lists entries for one conversation, failed ones included', async () => {
+ const first = await approvedEntry('one');
+ await approvedEntry('two');
+ await approvedEntry('other', OTHER_CONVERSATION_ID);
+ outbox.get(first.id).state = 'failed';
+ const entries = await listOutboxEntries({ conversationId: CONVERSATION_ID });
+ expect(entries).toHaveLength(2);
+ expect(entries.map((e) => e.state).sort()).toEqual(['approved', 'failed']);
+ });
+ });
+
+ // The reviewer's blocker on #53: cancelling the first-contact confirmation
+ // left the row `approved` forever, with no way to remove it — a phantom
+ // pending send the client rendered as a permanent "Sending…" bubble. This is
+ // the discard the "Cancel" action now calls.
+ describe('discardOutboxEntry — the "Cancel" path', () => {
+ it('removes an approved row that was never sent', async () => {
+ const entry = await approvedEntry();
+ await discardOutboxEntry(entry.id);
+ expect(outbox.has(entry.id)).toBe(false);
+ expect(await listOutboxEntries({ conversationId: CONVERSATION_ID })).toHaveLength(0);
+ });
+
+ it('404s an unknown entry', async () => {
+ await expect(discardOutboxEntry('outbox-missing')).rejects.toMatchObject({
+ code: 'OUTBOX_ENTRY_NOT_FOUND', status: 404,
+ });
+ });
+
+ it('refuses to discard a row that already left "approved" — sent, failed, or in flight', async () => {
+ const sending = await approvedEntry();
+ outbox.get(sending.id).state = 'sending';
+ await expect(discardOutboxEntry(sending.id)).rejects.toMatchObject({ code: 'OUTBOX_INVALID_STATE', status: 409 });
+
+ const sent = await approvedEntry();
+ outbox.get(sent.id).state = 'sent';
+ await expect(discardOutboxEntry(sent.id)).rejects.toMatchObject({ code: 'OUTBOX_INVALID_STATE', status: 409 });
+
+ const failed = await approvedEntry();
+ outbox.get(failed.id).state = 'failed';
+ await expect(discardOutboxEntry(failed.id)).rejects.toMatchObject({ code: 'OUTBOX_INVALID_STATE', status: 409 });
+
+ // None of those rows were touched.
+ expect(outbox.has(sending.id)).toBe(true);
+ expect(outbox.has(sent.id)).toBe(true);
+ expect(outbox.has(failed.id)).toBe(true);
+ expect(sendMessage).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('sendOutboxEntry — the human gates', () => {
+ it('refuses the first message to a conversation without an explicit confirmation, and sends nothing', async () => {
+ const entry = await approvedEntry();
+ expect(await isFirstContact(CONVERSATION_ID)).toBe(true);
+ await expect(sendOutboxEntry(entry.id)).rejects.toMatchObject({
+ code: 'FIRST_CONTACT_CONFIRMATION_REQUIRED', status: 409,
+ });
+ expect(sendMessage).not.toHaveBeenCalled();
+ expect(outbox.get(entry.id).state).toBe('approved');
+ });
+
+ it('sends once the first contact is confirmed, and asks no confirmation on the next message', async () => {
+ const first = await approvedEntry();
+ await sendOutboxEntry(first.id, { confirmFirstContact: true });
+ expect(sendMessage).toHaveBeenCalledTimes(1);
+ expect(sendMessage).toHaveBeenCalledWith(CHAT_ID, { text: 'hello there' });
+ expect(outbox.get(first.id).state).toBe('awaiting-confirmation');
+
+ // Resolve it so the conversation has a completed send on record.
+ beeperSocketEvents.emit('invalidate', { kind: 'message.upserted', chatID: CHAT_ID, ids: ['msg-final-1'] });
+ await flush();
+ expect(outbox.get(first.id).state).toBe('sent');
+
+ const second = await approvedEntry('a reply');
+ await expect(sendOutboxEntry(second.id)).resolves.toMatchObject({ state: 'awaiting-confirmation' });
+ });
+
+ it('refuses to send an entry that is not approved, and never re-sends a failed one', async () => {
+ markPriorSend();
+ const entry = await approvedEntry();
+ outbox.get(entry.id).state = 'failed';
+ await expect(sendOutboxEntry(entry.id, { confirmFirstContact: true }))
+ .rejects.toMatchObject({ code: 'OUTBOX_INVALID_STATE', status: 409 });
+ expect(sendMessage).not.toHaveBeenCalled();
+ });
+
+ it('404s an unknown entry', async () => {
+ await expect(sendOutboxEntry('outbox-missing')).rejects.toMatchObject({ code: 'OUTBOX_ENTRY_NOT_FOUND', status: 404 });
+ });
+ });
+
+ // The first-contact prompt has to fire exactly once per conversation, or the
+ // user learns to click through it. Counting only `sent` rows re-asked it after
+ // a send that left the machine but never confirmed — which is the NORMAL
+ // resting state of an unresolved send, since that case deliberately stays
+ // `awaiting-confirmation` rather than being marked failed.
+ //
+ // Fork issue #82: a contact is known when EITHER source has outbound history
+ // — a mirrored `is_sender` message (any client, not just this install) OR a
+ // prior PortOS outbox send — scoped to the one conversation being sent to.
+ // The confirmation is reserved for a chat neither source has ever addressed.
+ describe('isFirstContact — has PortOS addressed this conversation before', () => {
+ it.each(['sent', 'awaiting-confirmation', 'sending'])(
+ 'treats a prior %s row as contact already made, so no confirmation is asked',
+ async (state) => {
+ const prior = await approvedEntry('an earlier message');
+ outbox.get(prior.id).state = state;
+
+ expect(await isFirstContact(CONVERSATION_ID)).toBe(false);
+
+ const next = await approvedEntry('a reply');
+ await expect(sendOutboxEntry(next.id)).resolves.toMatchObject({ state: 'awaiting-confirmation' });
+ },
+ );
+
+ it('treats a mirrored isSender message alone as contact already made, with no PortOS send on record', async () => {
+ seedMirroredMessage(CONVERSATION_ID, { isSender: true });
+
+ expect(await isFirstContact(CONVERSATION_ID)).toBe(false);
+
+ const entry = await approvedEntry('a reply');
+ await expect(sendOutboxEntry(entry.id)).resolves.toMatchObject({ state: 'awaiting-confirmation' });
+ });
+
+ it('still asks when nothing PortOS composed ever reached Beeper and the mirror holds no outbound message', async () => {
+ const failed = await approvedEntry('never left');
+ outbox.get(failed.id).state = 'failed';
+ await approvedEntry('still queued');
+
+ expect(await isFirstContact(CONVERSATION_ID)).toBe(true);
+ expect(await isFirstContact(OTHER_CONVERSATION_ID)).toBe(true);
+ });
+
+ it('still asks first contact when the mirrored thread holds only inbound messages', async () => {
+ seedMirroredMessage(CONVERSATION_ID, { isSender: false });
+ seedMirroredMessage(CONVERSATION_ID, { isSender: false });
+
+ expect(await isFirstContact(CONVERSATION_ID)).toBe(true);
+
+ const entry = await approvedEntry();
+ await expect(sendOutboxEntry(entry.id)).rejects.toMatchObject({
+ code: 'FIRST_CONTACT_CONFIRMATION_REQUIRED', status: 409,
+ });
+ });
+
+ it('scopes the mirrored-message check to the conversation being sent to', async () => {
+ seedMirroredMessage(OTHER_CONVERSATION_ID, { isSender: true });
+
+ expect(await isFirstContact(CONVERSATION_ID)).toBe(true);
+ expect(await isFirstContact(OTHER_CONVERSATION_ID)).toBe(false);
+ });
+ });
+
+ describe('sendOutboxEntry — transport failure', () => {
+ it('leaves exactly one failed row with the error, and posts nothing a second time', async () => {
+ markPriorSend();
+ const entry = await approvedEntry();
+ sendMessage.mockRejectedValueOnce(new BeeperApiError('Beeper request failed: connection refused', {
+ status: 0, code: 'NETWORK_ERROR', retryable: false,
+ }));
+
+ await expect(sendOutboxEntry(entry.id)).rejects.toMatchObject({ code: 'NETWORK_ERROR', retryable: false });
+
+ 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(0);
+ });
+ });
+
+ describe('confirmation — socket first, 30s GET fallback', () => {
+ it('confirms on a message.upserted invalidation, mirrors the message and re-broadcasts an id-only frame', async () => {
+ markPriorSend();
+ const entry = await approvedEntry();
+ await sendOutboxEntry(entry.id);
+
+ const frames = [];
+ const listener = (frame) => frames.push(frame);
+ beeperSocketEvents.on('invalidate', listener);
+ beeperSocketEvents.emit('invalidate', { kind: 'message.upserted', chatID: CHAT_ID, ids: ['msg-final-1'] });
+ await flush();
+ beeperSocketEvents.off('invalidate', listener);
+
+ expect(outbox.get(entry.id).state).toBe('sent');
+ expect(outbox.get(entry.id).messageId).toBe('msg-final-1');
+ 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\)/);
+ 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);
+ expect(emitted).toBeTruthy();
+ expect(JSON.stringify(emitted)).not.toContain('hello there');
+ expect(sendMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('resolves through the GET fallback when message.upserted never arrives, and does not send twice', async () => {
+ markPriorSend();
+ const entry = await approvedEntry();
+ await sendOutboxEntry(entry.id);
+
+ // No socket frame at all. The fallback fires at exactly 30s.
+ expect(outbox.get(entry.id).state).toBe('awaiting-confirmation');
+ clock.advance(CONFIRMATION_TIMEOUT_MS);
+ expect(clock.runTimersWithDelay(CONFIRMATION_TIMEOUT_MS)).toBe(1);
+ await flush();
+
+ expect(getMessage).toHaveBeenCalledWith(CHAT_ID, 'pending-1');
+ expect(outbox.get(entry.id).state).toBe('sent');
+ expect(sendMessage).toHaveBeenCalledTimes(1);
+ });
+
++ it('settles a missed confirmation when its deadline fires during a socket lookup', async () => {
++ markPriorSend();
++ const entry = await approvedEntry();
++ await sendOutboxEntry(entry.id);
++ let finishLookup;
++ getMessage.mockImplementationOnce(() => new Promise((resolve) => { finishLookup = resolve; }));
++ listMessagesPage.mockResolvedValue({ items: [] });
++ beeperSocketEvents.emit('invalidate', { kind: 'message.upserted', chatID: CHAT_ID });
++ clock.advance(CONFIRMATION_TIMEOUT_MS);
++ clock.runTimersWithDelay(CONFIRMATION_TIMEOUT_MS);
++ finishLookup(null);
++ await flush();
++ expect(outbox.get(entry.id)).toMatchObject({ state: 'awaiting-confirmation', errorCode: 'CONFIRMATION_UNRESOLVED' });
++ expect(getOutboxStatus().awaitingConfirmation).toBe(0);
++ expect(sendMessage).toHaveBeenCalledTimes(1);
++ });
++
+ it('falls back to a chat + body + isSender match when the pending id no longer resolves', async () => {
+ markPriorSend();
+ const entry = await approvedEntry();
+ await sendOutboxEntry(entry.id);
+ getMessage.mockRejectedValue(new BeeperApiError('not found', { status: 404, code: 'NOT_FOUND' }));
+ listMessagesPage.mockResolvedValue({
+ items: [
+ { id: 'msg-someone-else', text: 'hello there', isSender: false, timestamp: '2026-09-01T00:00:06.000Z' },
+ sentMessage({ id: 'msg-final-2' }),
+ ],
+ });
+
+ clock.advance(CONFIRMATION_TIMEOUT_MS);
+ clock.runTimersWithDelay(CONFIRMATION_TIMEOUT_MS);
+ await flush();
+
+ expect(outbox.get(entry.id).messageId).toBe('msg-final-2');
+ expect(outbox.get(entry.id).state).toBe('sent');
+ expect(sendMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('leaves an unresolvable send in flight with a reason rather than marking it failed', async () => {
+ markPriorSend();
+ const entry = await approvedEntry();
+ await sendOutboxEntry(entry.id);
+ getMessage.mockResolvedValue(null);
+ listMessagesPage.mockResolvedValue({ items: [] });
+
+ clock.advance(CONFIRMATION_TIMEOUT_MS);
+ clock.runTimersWithDelay(CONFIRMATION_TIMEOUT_MS);
+ await flush();
+
+ const row = outbox.get(entry.id);
+ // Not `failed`: a failed row invites a re-send, and the message may well
+ // have been delivered.
+ expect(row.state).toBe('awaiting-confirmation');
+ expect(row.errorCode).toBe('CONFIRMATION_UNRESOLVED');
+ expect(sendMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('marks the row failed when Beeper reports a failed send status, and never retries it', async () => {
+ markPriorSend();
+ const entry = await approvedEntry();
+ await sendOutboxEntry(entry.id);
+ getMessage.mockResolvedValue(sentMessage({
+ sendStatus: { status: 'FAIL_PERMANENT', timestamp: '2026-09-01T00:00:06.000Z', message: 'Recipient unreachable' },
+ }));
+
+ clock.advance(CONFIRMATION_TIMEOUT_MS);
+ clock.runTimersWithDelay(CONFIRMATION_TIMEOUT_MS);
+ await flush();
+
+ expect(outbox.get(entry.id).state).toBe('failed');
+ expect(outbox.get(entry.id).errorCode).toBe('SEND_FAIL_PERMANENT');
+ expect(sendMessage).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ // `sending` and `awaiting-confirmation` are exit-only through in-memory state,
+ // so a restart mid-flight used to leave a row nothing could ever move: the
+ // client rendered it as a spinner with no Retry and no Dismiss, permanently.
+ describe('reconcileOutboxOnBoot — the durable half of the confirmation state', () => {
+ it('fails every row stranded in "sending" with SEND_INTERRUPTED, and posts nothing', async () => {
+ const stranded = strandedRow('sending');
+ const settled = strandedRow('sent', { messageId: 'msg-earlier', sentAt: '2026-09-01T00:00:02.000Z' });
+ const failed = strandedRow('failed', { errorCode: 'NETWORK_ERROR', errorMessage: 'connection refused' });
+
+ const result = await reconcileOutboxOnBoot();
+
+ expect(result.interrupted).toBe(1);
+ expect(outbox.get(stranded.id)).toMatchObject({ state: 'failed', errorCode: 'SEND_INTERRUPTED' });
+ // The exact sentence the client renders off the code, asserted literally on
+ // both sides so the two bundles cannot drift apart.
+ expect(outbox.get(stranded.id).errorMessage)
+ .toBe('Delivery unconfirmed: PortOS restarted mid-send. Check the chat before retrying.');
+ expect(SEND_INTERRUPTED_MESSAGE).toBe(outbox.get(stranded.id).errorMessage);
+ // Terminal rows are left exactly as they were.
+ expect(outbox.get(settled.id)).toMatchObject({ state: 'sent', messageId: 'msg-earlier', errorCode: null });
+ expect(outbox.get(failed.id)).toMatchObject({ state: 'failed', errorCode: 'NETWORK_ERROR' });
+ // The whole point: a crash never resends. Nothing on this path POSTs.
+ expect(sendMessage).not.toHaveBeenCalled();
+ });
+
+ it('re-arms an "awaiting-confirmation" row from its persisted fields and resolves it without sending', async () => {
+ const stranded = strandedRow('awaiting-confirmation');
+ expect(getOutboxStatus().awaitingConfirmation).toBe(0);
+
+ const result = await reconcileOutboxOnBoot();
+
+ expect(result).toEqual({ interrupted: 0, rearmed: 1 });
+ expect(getOutboxStatus().awaitingConfirmation).toBe(1);
+
+ // The re-armed row now resolves through the same socket path a live send
+ // uses — a lookup, never a second POST.
+ beeperSocketEvents.emit('invalidate', { kind: 'message.upserted', chatID: CHAT_ID, ids: ['msg-final-1'] });
+ await flush();
+
+ expect(getMessage).toHaveBeenCalledWith(CHAT_ID, 'pending-1');
+ expect(outbox.get(stranded.id)).toMatchObject({ state: 'sent', messageId: 'msg-final-1' });
+ expect(sendMessage).not.toHaveBeenCalled();
+ });
+
+ it('re-arms a row already recorded unresolved, and still never sends on the fallback path', async () => {
+ const stranded = strandedRow('awaiting-confirmation', {
+ errorCode: 'CONFIRMATION_UNRESOLVED', errorMessage: 'Beeper reported no matching message within 30s',
+ });
+ getMessage.mockResolvedValue(null);
+ listMessagesPage.mockResolvedValue({ items: [sentMessage({ id: 'msg-final-3' })] });
+
+ await reconcileOutboxOnBoot();
+ clock.advance(CONFIRMATION_TIMEOUT_MS);
+ expect(clock.runTimersWithDelay(CONFIRMATION_TIMEOUT_MS)).toBe(1);
+ await flush();
+
+ // The body match is floored on the row's PERSISTED send moment, not on boot
+ // time — dating it to now would reject the very message it is looking for.
+ expect(outbox.get(stranded.id)).toMatchObject({ state: 'sent', messageId: 'msg-final-3' });
+ expect(sendMessage).not.toHaveBeenCalled();
+ });
+
+ it('is idempotent across two calls — nothing double-fails and nothing double-arms', async () => {
+ const stranded = strandedRow('sending');
+ strandedRow('awaiting-confirmation');
+
+ const first = await reconcileOutboxOnBoot();
+ const second = await reconcileOutboxOnBoot();
+
+ expect(first).toEqual({ interrupted: 1, rearmed: 1 });
+ expect(second).toEqual({ interrupted: 0, rearmed: 0 });
+ expect(getOutboxStatus().awaitingConfirmation).toBe(1);
+ // One armed fallback timer, not two.
+ expect(clock.pending()).toBe(1);
+ expect(outbox.get(stranded.id).errorCode).toBe('SEND_INTERRUPTED');
+ expect(sendMessage).not.toHaveBeenCalled();
+ });
+
+ it('leaves an interrupted row re-sendable only as a NEW row, exactly like any other failure', async () => {
+ markPriorSend();
+ const stranded = strandedRow('sending');
+ await reconcileOutboxOnBoot();
+
+ // The failed row itself refuses to send in place…
+ await expect(sendOutboxEntry(stranded.id)).rejects.toMatchObject({ code: 'OUTBOX_INVALID_STATE', status: 409 });
+ expect(sendMessage).not.toHaveBeenCalled();
+
+ // …and the recovery is a fresh, human-composed entry.
+ const composed = await approvedEntry('hello there');
+ await sendOutboxEntry(composed.id);
+ expect(sendMessage).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe('runaway breaker', () => {
+ it('trips on a synthetic send loop and blocks every further send until a human clears it', async () => {
+ markPriorSend();
+ const entries = [];
+ for (let i = 0; i < BREAKER_MAX_SENDS_IN_WINDOW + 1; i += 1) {
+ // eslint-disable-next-line no-await-in-loop -- the loop under test is sequential
+ entries.push(await approvedEntry(`message ${i}`));
+ }
+
+ for (let i = 0; i < BREAKER_MAX_SENDS_IN_WINDOW; i += 1) {
+ // eslint-disable-next-line no-await-in-loop -- ordered sends inside the same window
+ await sendOutboxEntry(entries[i].id);
+ }
+ expect(getOutboxBreakerState().tripped).toBe(false);
+
+ const overflow = entries[BREAKER_MAX_SENDS_IN_WINDOW];
+ await expect(sendOutboxEntry(overflow.id)).rejects.toMatchObject({ code: 'OUTBOX_BREAKER_OPEN', status: 429 });
+ expect(sendMessage).toHaveBeenCalledTimes(BREAKER_MAX_SENDS_IN_WINDOW);
+ expect(getOutboxBreakerState().tripped).toBe(true);
+ expect(getOutboxStatus().breaker.tripped).toBe(true);
+
+ // Still blocked, and time alone does not reopen it.
+ clock.advance(60 * 60 * 1000);
+ await expect(sendOutboxEntry(overflow.id)).rejects.toMatchObject({ code: 'OUTBOX_BREAKER_OPEN' });
+ expect(sendMessage).toHaveBeenCalledTimes(BREAKER_MAX_SENDS_IN_WINDOW);
+
+ expect(clearOutboxBreaker().tripped).toBe(false);
+ await expect(sendOutboxEntry(overflow.id)).resolves.toMatchObject({ state: 'awaiting-confirmation' });
+ });
+
+ it('trips on consecutive transport failures', async () => {
+ markPriorSend();
+ sendMessage.mockRejectedValue(new BeeperApiError('Beeper request failed', { status: 0, code: 'NETWORK_ERROR' }));
+ for (let i = 0; i < BREAKER_MAX_CONSECUTIVE_FAILURES; i += 1) {
+ // 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' });
+ }
+ expect(getOutboxBreakerState()).toMatchObject({
+ tripped: true, consecutiveFailures: BREAKER_MAX_CONSECUTIVE_FAILURES,
+ });
+ const next = await approvedEntry('one more');
+ await expect(sendOutboxEntry(next.id)).rejects.toMatchObject({ code: 'OUTBOX_BREAKER_OPEN' });
+ expect(sendMessage).toHaveBeenCalledTimes(BREAKER_MAX_CONSECUTIVE_FAILURES);
+ });
+
+ // The window is ROLLING, and that is the whole difference between a runaway
+ // breaker and a rate quota: the same count of sends spread over an afternoon
+ // is a person using the app, and must never be treated as a loop.
+ it('stays closed when the same count of sends is spread beyond the window', async () => {
+ markPriorSend();
+ for (let i = 0; i <= BREAKER_MAX_SENDS_IN_WINDOW; i += 1) {
+ // eslint-disable-next-line no-await-in-loop -- ordered sends, one per window
+ const entry = await approvedEntry(`message ${i}`);
+ // eslint-disable-next-line no-await-in-loop
+ await sendOutboxEntry(entry.id);
+ clock.advance(BREAKER_WINDOW_MS + 1);
+ }
+
+ expect(sendMessage).toHaveBeenCalledTimes(BREAKER_MAX_SENDS_IN_WINDOW + 1);
+ expect(getOutboxBreakerState()).toMatchObject({ tripped: false, sendsInWindow: 0 });
+ });
+
+ // The consecutive arm counts a RUN, not a total. Two failures either side of
+ // a success are two runs of one, so a flaky connection cannot accumulate its
+ // way into a breaker only a human can clear.
+ it('resets the consecutive-failure count on a successful send', async () => {
+ markPriorSend();
+ 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 failOnce('one');
+ await failOnce('two');
+ expect(getOutboxBreakerState()).toMatchObject({ tripped: false, consecutiveFailures: 2 });
+
+ const recovered = await approvedEntry('three');
+ await sendOutboxEntry(recovered.id);
+ expect(getOutboxBreakerState().consecutiveFailures).toBe(0);
+
+ // Two more failures are now a run of two, not the fourth and fifth of five.
+ await failOnce('four');
+ await failOnce('five');
+ expect(getOutboxBreakerState()).toMatchObject({ tripped: false, consecutiveFailures: 2 });
+ });
+ });
diff --cc server/services/beeperSync.js
index 0000000000,7996cfeb83..c2b5d30c7e
mode 000000,100644..100644
--- a/server/services/beeperSync.js
+++ b/server/services/beeperSync.js
@@@ -1,0 -1,880 +1,874 @@@
+ /**
+ * Beeper ingestion sweep (#32, decided on #3 and #12; store shape from #7/#27,
+ * Tribe linking from #10/#34, attachment policy from #13).
+ *
+ * This is the HTTP refetch that makes ingestion CORRECT. It is not a fallback
+ * for a dead socket: Beeper's WebSocket is at-most-once with no replay on
+ * reconnect, and it drops events during hydration while the connection looks
+ * perfectly healthy, so a poll that only ran when the socket was down would be
+ * asleep during two of the three loss paths. The socket (#33) makes ingestion
+ * PROMPT; this sweep makes it complete, and it runs unconditionally on its own
+ * timer.
+ *
+ * Watermark-bounded, never a full history rebuild. Per account:
+ * 1. refresh `beeper_accounts` from the live roster (never `loginID`);
+ * 2. page `GET /v1/chats?accountIDs=…` newest-first, sweeping every chat on
+ * the page that is newer than its stored
- * `beeper_sync_cursors.last_activity`, and STOP at the first page that
- * asked for nothing. A single caught-up chat does not end the walk: a
- * chat whose forward walk was truncated keeps its OLD watermark on
++ * `beeper_sync_cursors.last_activity`, within the bounded account page
++ * walk. A caught-up chat does not end the walk: a chat whose forward walk was truncated keeps its OLD watermark on
+ * purpose, so it stays eligible while sorting below chats that are
+ * already caught up;
+ * 3. for each changed chat: upsert the conversation, upsert participants
+ * (`beeperTribe.upsertParticipant`), page new messages from the stored
+ * opaque cursor with `direction: 'after'`, log daily Tribe touchpoints
+ * (`beeperTribe.logSenderTouchpoints`), then commit message rows,
+ * attachment references and the cursor row in ONE transaction.
+ *
+ * **The transaction boundary is the point of the whole module.** Message rows,
+ * attachment references and the `beeper_sync_cursors` row commit together, so
+ * an interrupted sweep leaves the cursor exactly where it was and the next
+ * sweep refetches the same window. `imessageSync` implements the same
+ * never-skip rule by hand precisely because its store and its cursor live in
+ * different places (#12 decision 8); here they share a database, so the
+ * guarantee is the transaction's rather than the author's.
+ *
+ * Everything OUTSIDE that transaction is deliberately idempotent and ordered
+ * BEFORE it, so a crash between steps can only cause repeated work, never lost
+ * work: the conversation upsert, the participant upserts and the touchpoint
+ * writes are all keyed and deduped (touchpoints on `beeper:<YYYY-MM-DD>`), and
+ * they all re-run on the next sweep because the cursor never moved.
+ *
+ * No AI provider call happens anywhere on this path — ingestion is
+ * deterministic — so AGENTS.md's "No cold-bootstrap LLM calls" does not gate
+ * it, exactly as `imessageScheduler.js` records for the same shape.
+ *
+ * **Progress (fork issue #80).** `executeSweep` keeps `beeperSweepProgress.js`
+ * current as it goes — running/idle, started/finished, accounts done of the
+ * total, chats and messages mirrored so far — and `beeperStatus.js` reads it
+ * into the status payload the list header and the drawer card render from. It
+ * also fires an invalidation frame on `beeperSocketEvents` after the account
+ * count is known and after every account finishes, reusing #33's existing
+ * push path rather than adding a client-side poller.
+ *
+ * **A chat's first-page fetch is retried once if it comes back empty (#81).**
+ * A brand-new chat's first sweep takes exactly one `direction: 'before'` page
+ * (step 3 above). `sweepChat` withholds the cursor and watermark the first
+ * time that page comes back with zero items (the same mechanism a truncated
+ * forward walk already used), so `chatNeedsSweep` retries the same first page
+ * next pass; if the retry is ALSO empty, the real watermark commits (so a
+ * genuinely history-less chat still reaches the steady state `chatNeedsSweep`'s
+ * docblock describes) and one warn-level line records it.
+ *
+ * **This retry does not reach every chat #81's live-instance investigation
+ * found empty.** `chatNeedsSweep` only re-selects a chat once `chat.lastActivity`
+ * is truthy, and the investigation's *entire observed population* was chats
+ * Beeper itself never reports any activity for — `chat.lastActivity` null on
+ * every sweep, not merely an empty first page. Those chats are swept exactly
+ * once, commit `lastActivity: null`, and are never re-selected; the retry
+ * above only covers a chat whose `chat.lastActivity` IS truthy but whose
+ * first page still came back empty (a transient fetch hiccup, or a
+ * history-less chat gaining its first-ever activity right as it enters the
+ * mirror). What actually fixed the *reported* symptom — empty rows sorting
+ * above threads with recent messages — for the observed population is the
+ * ORDER BY in `beeperConversations.js`: it no longer falls back to the
+ * mirror row's `created_at` for an activity-less chat (which made a whole
+ * batch of them look freshly active because they were freshly SWEPT), so
+ * they sort LAST instead of first. See `sweepChat`'s inline comment for the
+ * full account of why the two null/null-producing paths are handled
+ * identically rather than being told apart.
+ */
+
+ import { query, withTransaction } from '../lib/db.js';
+ import {
+ BeeperApiError,
+ resolveBeeperConfig,
+ getJoinedAccounts,
+ listChatsPage,
+ listMessagesPage,
+ } from './beeperClient.js';
+ import { upsertParticipant, logSenderTouchpoints, loadRosterIndex } from './beeperTribe.js';
+ import { isInstanceFeatureEnabled } from './instanceFeatures.js';
+ import { getSettings } from './settings.js';
+ import { updateBeeperSweepProgress } from './beeperSweepProgress.js';
+ import { beeperSocketEvents } from './beeperSocketEvents.js';
+
+ export const DEFAULT_INTERVAL_MINUTES = 5;
+
+ // Safety caps. `GET /v1/chats` has no `limit`, so the page size is the
+ // server's; these bound one sweep's work rather than one page's.
+ const MAX_CHAT_PAGES_PER_ACCOUNT = 20;
+ // Catching up on new messages walks forward from the stored cursor, so this is
+ // a burst ceiling, not a history depth. A chat that is further behind than this
+ // keeps its (advanced) cursor AND its old watermark — see `fetchNewMessages`'s
+ // `truncated` flag — so it stays eligible and finishes catching up on the next
+ // sweep instead of being skipped as caught-up.
+ const MAX_MESSAGE_PAGES_PER_CHAT = 10;
+
+ const LOG_PREFIX = '🫧 Beeper sweep';
+
+ // ---------------------------------------------------------------------------
+ // Config + arming gate
+ // ---------------------------------------------------------------------------
+
+ /**
+ * The `createSyncScheduler` config contract: `{ enabled, intervalMinutes }`.
+ * `enabled` is the user's own "Enable scheduled Beeper sync" toggle from the
+ * Comms → Beeper card (#30) — the ingestion flag, distinct from the instance
+ * FEATURE flag that governs navigation (#11 keeps the two separate). The
+ * interval is locked at registration by the factory; changing it needs a
+ * restart, identical to the four existing ingestion domains.
+ */
+ export async function getBeeperSyncConfig() {
+ const settings = await getSettings().catch(() => ({}));
+ const config = settings?.beeper || {};
+ return {
+ enabled: config.enabled === true,
+ intervalMinutes: Number.isFinite(config.intervalMinutes) && config.intervalMinutes >= 1
+ ? Math.floor(config.intervalMinutes)
+ : DEFAULT_INTERVAL_MINUTES,
+ };
+ }
+
+ /**
+ * Whether the sweep may be armed at all: the instance feature is on AND a
+ * token is configured (#12 decision 2). Deliberately SILENT — the acceptance
+ * criterion on #32 is that with the feature off, or with no token, nothing is
+ * registered and *nothing logs*; a fresh install that has never opened the
+ * Beeper card should not narrate a feature it does not have.
+ *
+ * **Never gates on Beeper's `app.state`.** Measured on a live instance (#12):
+ * the stream reported `initializing` for 105 continuous seconds while nine
+ * accounts were `connected` and a chat page returned in 230 ms. Gating on it
+ * would stall a healthy install indefinitely.
+ *
+ * The token is read through `resolveBeeperConfig`, the client's single
+ * credential call site, so this works unchanged whether the token still lives
+ * in `settings.beeper.token` or behind the encrypted vault (#31), which sits
+ * behind that same function. The token value itself is never returned, logged
+ * or stored.
+ */
+ export async function isBeeperIngestionArmed() {
+ const featureEnabled = await isInstanceFeatureEnabled('beeper').catch(() => false);
+ if (!featureEnabled) return false;
+ // A vault that cannot be read (corrupt row, rotated key) must not masquerade
+ // as "no token": say so once, then decline to arm.
+ const { token } = await resolveBeeperConfig().catch((err) => {
+ console.error(`❌ Beeper credential unreadable, ingestion not armed: ${err.message}`);
+ return { token: null };
+ });
+ return Boolean(token);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Normalizers (pure — no I/O, no DB)
+ // ---------------------------------------------------------------------------
+
+ function toIsoOrNull(value) {
+ if (value === null || value === undefined || value === '') return null;
+ const date = new Date(value);
+ return Number.isNaN(date.getTime()) ? null : date.toISOString();
+ }
+
+ function toIntOrNull(value) {
+ return Number.isFinite(value) ? Math.trunc(value) : null;
+ }
+
+ /**
+ * Account roster row. Fields are picked EXPLICITLY rather than spread — the
+ * client already strips the top-level `loginID` (the bridge login credential,
+ * effectively the user's phone number), and picking by name means a future
+ * field added upstream cannot reach the database without someone naming it
+ * here.
+ */
+ export function normalizeAccountRow(account) {
+ const accountId = typeof account?.accountID === 'string' ? account.accountID : '';
+ return {
+ accountId,
+ network: String(account?.network ?? ''),
+ displayName: String(account?.user?.fullName || account?.user?.username || account?.network || accountId || ''),
+ status: String(account?.status || account?.bridgeStatus || ''),
+ // account.bridgeId is the join result from getJoinedAccounts (see
+ // beeperClient.js joinAccountsWithBridges). account?.bridge is the RAW
+ // field /v1/accounts itself carries — live, it is an object
+ // { id, type, provider }, never a string, so it must be narrowed to
+ // `.id` rather than coerced whole (String() on the object stringifies to
+ // the literal text "[object Object]"). The join can also legitimately
+ // miss (an account absent from every /v1/bridges items[].accounts[]),
+ // which is when this raw fallback is needed at all.
+ bridgeId: String(account?.bridgeId || account?.bridge?.id || ''),
+ };
+ }
+
+ /**
+ * Conversation row. `type` is stored RAW: the schema deliberately carries no
+ * enum constraint on it (`db.catalogDdlParity.test.js` forbids one), so a new
+ * Beeper chat type never needs a two-file migration to accept. `is_group` is
+ * the derived boolean the UI filters on.
+ */
+ export function normalizeChatRow(chat) {
+ const type = String(chat?.type || 'single');
+ return {
+ accountId: String(chat?.accountID ?? ''),
+ sourceChatId: String(chat?.id ?? ''),
+ network: String(chat?.network ?? ''),
+ title: String(chat?.title ?? ''),
+ type,
+ isGroup: type === 'group',
+ isPinned: chat?.isPinned === true,
+ isArchived: chat?.isArchived === true,
+ isLowPriority: chat?.isLowPriority === true,
+ isMuted: chat?.isMuted === true,
+ lastActivity: toIsoOrNull(chat?.lastActivity),
+ unreadCount: Number.isFinite(chat?.unreadCount) ? Math.max(0, Math.trunc(chat.unreadCount)) : 0,
+ };
+ }
+
+ /**
+ * Message row. Two mutation shapes ride in on an ordinarily-shaped message
+ * rather than as their own events (#7/#13):
+ * - an EDIT is a populated `editedTimestamp`;
+ * - an UNSEND is `isDeleted: true`, a tombstone that keeps the row and its
+ * body. The API reports no deletion timestamp, so `unsent_at` records when
+ * PortOS first OBSERVED the tombstone (`observedAt`) — the upsert below
+ * COALESCEs it, so the first observation is the one that sticks.
+ */
+ export function normalizeMessageRow(message, observedAt) {
+ return {
+ id: String(message?.id ?? ''),
+ senderId: String(message?.senderID ?? ''),
+ body: typeof message?.text === 'string' ? message.text : '',
+ sentAt: toIsoOrNull(message?.timestamp),
+ editedAt: toIsoOrNull(message?.editedTimestamp),
+ unsentAt: message?.isDeleted === true ? observedAt : null,
+ sortKey: String(message?.sortKey ?? ''),
+ // The API's own `isSender`, and the ONLY reliable inbound/outbound signal:
+ // `accounts[].user.id` differs from `senderID` on every network (#2), so a
+ // 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,
+ };
+ }
+
+ /**
+ * Attachment REFERENCES only — metadata, never bytes (#13 puts the lazy byte
+ * mirror and its disk budget in its own slice). `srcURL` and `posterImg` are
+ * deliberately not persisted: both carry the spec's own "may be temporary or
+ * local-only to this device" warning, so storing either would put a decaying
+ * value in a durable archive. `sha256` has no source field on the inbound
+ * `Attachment` at all and stays NULL until the byte mirror computes one.
+ */
+ export function normalizeAttachmentRows(message) {
+ const attachments = Array.isArray(message?.attachments) ? message.attachments : [];
+ return attachments.map((attachment, idx) => ({
+ idx,
+ mxcId: typeof attachment?.id === 'string' && attachment.id ? attachment.id : null,
+ // Lowercased (RFC 2045: a media type is case-insensitive) so the stored
+ // value matches what `beeperAttachmentPaths.MIRRORED_MIME_TYPES` and the
+ // client's `isImage()` check both compare against — a bridge that sends
+ // `Image/JPEG` must not silently miss either one.
+ mimeType: String(attachment?.mimeType ?? '').toLowerCase(),
+ byteLength: toIntOrNull(attachment?.fileSize),
+ fileName: String(attachment?.fileName ?? ''),
+ width: toIntOrNull(attachment?.size?.width),
+ height: toIntOrNull(attachment?.size?.height),
+ }));
+ }
+
+ /**
+ * Participant roster entries for one chat. `participants` is always an OBJECT
+ * (`{ hasMore, items, total }`), never a bare array, and it TRUNCATES at 20 on
+ * the list endpoint with no participants endpoint and no cursor to continue on
+ * — which is exactly why `beeper_participants.observed_via` exists (#27): a
+ * roster row set is always a possible subset.
+ */
+ export function normalizeParticipants(chat) {
+ const items = Array.isArray(chat?.participants?.items) ? chat.participants.items : [];
+ return items
+ .filter((participant) => typeof participant?.id === 'string' && participant.id)
+ .map((participant) => ({
+ sourceUserId: participant.id,
+ displayName: String(participant.fullName || participant.username || ''),
+ handle: String(participant.phoneNumber || participant.username || ''),
+ }));
+ }
+
+ /**
+ * Whether a chat has moved since its stored watermark. Three distinct states,
+ * never collapsed (the root AGENTS.md absent-vs-empty rule):
+ * - no cursor row at all → never swept, always sweep;
+ * - a row with no watermark → sweep only once the chat reports activity, so
+ * a genuinely empty chat (a Discord server channel with zero history is
+ * frequently correct) is not re-paged every five minutes forever;
+ * - both present → strictly newer wins.
+ */
+ export function chatNeedsSweep(chat, stored) {
+ if (!stored) return true;
+ if (!stored.lastActivity) return Boolean(chat?.lastActivity);
+ if (!chat?.lastActivity) return false;
+ return new Date(chat.lastActivity).getTime() > new Date(stored.lastActivity).getTime();
+ }
+
+ // ---------------------------------------------------------------------------
+ // Reads
+ // ---------------------------------------------------------------------------
+
+ /** Every stored cursor for one account, as a `Map` keyed on the Beeper chat id. */
+ async function readAccountCursors(accountId) {
+ const result = await query(
+ `SELECT chat_id, cursor, last_activity FROM beeper_sync_cursors WHERE account_id = $1`,
+ [accountId],
+ );
+ const rows = Array.isArray(result?.rows) ? result.rows : [];
+ return new Map(rows.map((row) => [row.chat_id, {
+ cursor: row.cursor || null,
+ lastActivity: row.last_activity ? new Date(row.last_activity).toISOString() : null,
+ }]));
+ }
+
+ function assertPagedShape(page, what) {
+ if (!Array.isArray(page?.items)) {
+ throw new BeeperApiError(`Beeper API returned an unexpected ${what} response shape (expected { items: [] })`, {
+ status: 502, code: 'MALFORMED_RESPONSE', retryable: false,
+ });
+ }
+ }
+
+ /**
+ * New messages for one chat, plus the opaque cursor to store and whether the
+ * forward walk stopped short of the end.
+ *
+ * With a stored cursor this walks FORWARD (`direction: 'after'`), which the
+ * SDK's own auto-pagination never does — it only ever reads `oldestCursor` —
+ * so the forward walk is driven by hand here.
+ *
+ * With NO stored cursor this takes the newest page ONLY and anchors the cursor
+ * there. Deep history backfill is a different feature with a different cost
+ * profile (history depth varies wildly per network, #3), and silently pulling
+ * every message of every chat the first time a user enables the toggle is not
+ * a sweep.
+ *
+ * `truncated` is true whenever a FORWARD walk ends with the server still
+ * reporting `hasMore` — i.e. messages exist that this pass did not fetch.
+ * That is the page budget running out, and equally a server that answers
+ * `hasMore: true` with no usable cursor to continue on (a null one, or the one
+ * it was just handed). The caller MUST NOT advance the chat's watermark in that case
+ * (see `sweepChat`): the cursor moved forward but the newest messages are
+ * still missing, and a watermark equal to the chat's current activity would
+ * make `chatNeedsSweep` skip the chat forever. The first-page-only anchor walk
+ * is never truncated — it is not trying to reach the end.
+ */
+ async function fetchNewMessages(chatId, storedCursor, clientOptions) {
+ const direction = storedCursor ? 'after' : 'before';
+ const maxPages = storedCursor ? MAX_MESSAGE_PAGES_PER_CHAT : 1;
+ const messages = [];
+ let cursor = storedCursor || undefined;
+ let anchorCursor = null;
+ let truncated = false;
+
+ for (let pageIndex = 0; pageIndex < maxPages; pageIndex++) {
+ // eslint-disable-next-line no-await-in-loop -- cursor pagination is inherently sequential
+ const page = await listMessagesPage(chatId, { cursor, direction, ...clientOptions });
+ assertPagedShape(page, `/v1/chats/{chatID}/messages`);
+ messages.push(...page.items);
+ if (page.newestCursor) anchorCursor = page.newestCursor;
+ if (!page.hasMore) break;
+ const nextCursor = direction === 'after' ? page.newestCursor : page.oldestCursor;
+ if (!nextCursor || nextCursor === cursor) {
+ // The server says there is more and hands back no way to ask for it — a
+ // null cursor, or the very cursor it was just given. On a forward walk
+ // that is the same state as running out of page budget: messages exist
+ // that this pass did not fetch, so the watermark must not commit over
+ // them. Reading it as a clean end (which is what falling out of the loop
+ // with `truncated === false` did) marked the chat caught up and lost
+ // every message beyond the stall.
+ truncated = direction === 'after';
+ break;
+ }
+ cursor = nextCursor;
+ if (direction === 'after' && pageIndex === maxPages - 1) truncated = true;
+ }
+
+ return { messages, cursor: anchorCursor, truncated };
+ }
+
+ // ---------------------------------------------------------------------------
+ // Writes
+ // ---------------------------------------------------------------------------
+
+ /**
+ * Refresh `beeper_accounts` from the live roster. `getJoinedAccounts` joins
+ * `/v1/accounts` to `/v1/bridges` by `accountID` (never by `network` — that
+ * join returns zero rows) so the status card's `status`/`bridge_id` columns
+ * are populated with Beeper Desktop closed. `loginID` never reaches here.
+ */
+ async function refreshAccounts(clientOptions) {
+ const accounts = (await getJoinedAccounts(clientOptions)).map(normalizeAccountRow)
+ .filter((account) => account.accountId);
+ for (const account of accounts) {
+ // eslint-disable-next-line no-await-in-loop -- one roster, a handful of rows
+ await query(
+ `INSERT INTO beeper_accounts (account_id, network, display_name, status, bridge_id, last_seen_at)
+ VALUES ($1, $2, $3, $4, $5, NOW())
+ ON CONFLICT (account_id) DO UPDATE SET network = EXCLUDED.network,
+ display_name = EXCLUDED.display_name, status = EXCLUDED.status,
+ bridge_id = EXCLUDED.bridge_id, last_seen_at = NOW(), updated_at = NOW()`,
+ [account.accountId, account.network, account.displayName, account.status, account.bridgeId],
+ );
+ }
+ return accounts;
+ }
+
+ /**
+ * Upsert the conversation row and return its synthetic UUID. Committed on its
+ * own, BEFORE the message transaction, for two reasons: the participant writer
+ * (`beeperTribe.upsertParticipant`) runs on the pool and cannot see an
+ * uncommitted row, and a conversation row carries no cursor, so re-running it
+ * is free. The watermark lives in `beeper_sync_cursors`, never here.
+ */
+ async function upsertConversation(chat) {
+ const result = await query(
+ `INSERT INTO beeper_conversations (account_id, network, source_chat_id, title, type, is_group,
+ is_pinned, is_archived, is_low_priority, is_muted, last_activity, unread_count)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
+ ON CONFLICT (account_id, source_chat_id) DO UPDATE SET network = EXCLUDED.network,
+ title = EXCLUDED.title, type = EXCLUDED.type, is_group = EXCLUDED.is_group,
+ is_pinned = EXCLUDED.is_pinned, is_archived = EXCLUDED.is_archived,
+ is_low_priority = EXCLUDED.is_low_priority, is_muted = EXCLUDED.is_muted,
+ last_activity = COALESCE(EXCLUDED.last_activity, beeper_conversations.last_activity),
+ unread_count = EXCLUDED.unread_count, updated_at = NOW()
+ RETURNING id`,
+ [
+ chat.accountId, chat.network, chat.sourceChatId, chat.title, chat.type, chat.isGroup,
+ chat.isPinned, chat.isArchived, chat.isLowPriority, chat.isMuted, chat.lastActivity, chat.unreadCount,
+ ],
+ );
+ 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.
+ */
+ 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,
+ ],
+ );
+ }
+ }
+
+ // The cursor moves LAST and only inside this transaction, so a failure
+ // anywhere above rolls it back with the rows it was going to describe.
+ //
+ // `WHERE EXISTS` is the purge interlock. `beeper_sync_cursors` carries an FK
+ // onto `beeper_accounts` alone, so the conversation's cascade cannot reach
+ // it and `purgeConversation` deletes the two by hand in one transaction. A
+ // sweep already in flight when that purge commits would otherwise re-insert
+ // the cursor here — unconditionally, because a window with ZERO message rows
+ // still writes it — carrying the chat's current `last_activity`. That
+ // resurrected watermark makes `chatNeedsSweep` skip the chat, so the history
+ // the user just purged never comes back, contradicting the typed
+ // confirmation's promise that the next sync will mirror it again.
+ //
+ // The guard is a row check rather than a constraint on purpose: no DDL, no
+ // cascade, and the schema's own note that "a cursor can exist before the
+ // conversation row does" still holds everywhere else. On this path the
+ // conversation is upserted before the walk starts, so a missing row means it
+ // was deleted underneath us — exactly the case to decline.
+ await client.query(
+ `INSERT INTO beeper_sync_cursors (account_id, chat_id, cursor, last_activity, last_swept_at)
+ SELECT $1::text, $2::text, $3::text, $4::timestamptz, NOW()
+ WHERE EXISTS (SELECT 1 FROM beeper_conversations WHERE id = $5::uuid)
+ ON CONFLICT (account_id, chat_id) DO UPDATE SET
+ cursor = COALESCE(EXCLUDED.cursor, beeper_sync_cursors.cursor),
+ last_activity = COALESCE(EXCLUDED.last_activity, beeper_sync_cursors.last_activity),
+ last_swept_at = NOW()`,
+ [accountId, sourceChatId, cursor, lastActivity, conversationId],
+ );
+ return rows.length;
+ });
+ }
+
+ // ---------------------------------------------------------------------------
+ // Sweep
+ // ---------------------------------------------------------------------------
+
+ async function sweepChat({
+ chat, stored, clientOptions, observedAt, personIndex,
+ }) {
+ const normalized = normalizeChatRow(chat);
+ if (!normalized.accountId || !normalized.sourceChatId) return { messages: 0 };
+
+ const conversationId = await upsertConversation(normalized);
+ if (!conversationId) return { messages: 0 };
+
+ const { messages, cursor, truncated } = await fetchNewMessages(
+ normalized.sourceChatId, stored?.cursor, clientOptions,
+ );
+
+ // #81: a first-page anchor fetch (no stored cursor to walk forward from,
+ // so `fetchNewMessages` took the `direction: 'before'` branch) that comes
+ // back with zero items is NOT the same as "caught up" — `truncated` is
+ // never set on that branch, so falling through to the normal commit below
+ // would watermark the chat as done on one empty page and never look again.
+ //
+ // IMPORTANT — this retry does NOT reach every empty chat. `chatNeedsSweep`
+ // only re-selects a chat once `chat.lastActivity` is truthy; a chat Beeper
+ // itself never reports any activity for (`chat.lastActivity` stays null
+ // forever, which is the *entire observed population* on the live instance
+ // #81 investigated) is swept exactly once, commits null/null below, and is
+ // then never re-selected — the retry cannot fire because there is nothing
+ // for `chatNeedsSweep` to compare a "gained activity" transition against.
+ // That population's empty-row-sorts-first symptom is fixed separately, in
+ // `beeperConversations.js`'s ORDER BY (an activity-less chat now sorts
+ // LAST instead of by its mirror row's mint time). This retry instead
+ // covers the case `chat.lastActivity` IS truthy but the first page still
+ // came back empty — a transient fetch hiccup, or a chat that gains its
+ // first-ever activity right as it enters the mirror.
+ //
+ // `hadEmptyFirstPageAttempt` recognizes the state a WITHHELD commit leaves
+ // behind: a cursor row that exists but carries neither a cursor nor a
+ // watermark. That state is NOT exclusive to the withholding branch below —
+ // a chat with `chat.lastActivity` null commits exactly the same null/null
+ // shape on an ordinary first sweep (see above). The two are handled
+ // identically on purpose: whether this null/null row is a prior withhold
+ // or a history-less chat that has just gained its first real activity,
+ // the right move is the same — one retry, then commit-and-warn if it is
+ // still empty — so nothing here needs to (or can, from one sweep's
+ // evidence) tell the two apart. No new DB column or migration needed.
+ const isFirstPageAttempt = !stored?.cursor;
+ const emptyFirstPage = isFirstPageAttempt && messages.length === 0;
+ const hadEmptyFirstPageAttempt = Boolean(stored) && !stored.cursor && !stored.lastActivity;
+
+ let commitCursor = cursor || stored?.cursor || null;
+ let commitLastActivity = truncated ? null : normalized.lastActivity;
+
+ if (emptyFirstPage) {
+ if (hadEmptyFirstPageAttempt) {
+ // Still empty after one retry: commit the real watermark so the chat
+ // stops being re-swept every pass (mirroring the "genuinely empty
+ // chat" steady state `chatNeedsSweep` already protects), and log once
+ // so an operator can tell a chat landed here versus simply having no
+ // history. Chat id only — never message content.
+ console.warn(`${LOG_PREFIX}: chat ${normalized.sourceChatId} still has no mirrored messages after a retry`);
+ } else {
+ // First time this chat has come back empty. Withhold the cursor and
+ // watermark so `chatNeedsSweep` picks it back up next pass and retries
+ // the same first-page fetch, exactly once.
+ commitCursor = null;
+ commitLastActivity = null;
+ }
+ }
+
+ // Roster first, then senders: a message-sender observation carries a richer
+ // handle than a truncated roster entry, and `upsertParticipant` COALESCEs
+ // the handle rather than overwriting it, so the better one wins either way.
+ //
+ // `personIndex` is `executeSweep`'s ONE Tribe-roster load for the whole
+ // sweep pass, threaded down here and to the sender loop below — without it
+ // `upsertParticipant`'s phone-match fallback would reload and reindex every
+ // Tribe person once per participant, in every chat, on every pass.
+ for (const participant of normalizeParticipants(chat)) {
+ // eslint-disable-next-line no-await-in-loop -- at most 20 per chat (the list endpoint truncates there)
+ await upsertParticipant({
+ conversationId, ...participant, observedVia: 'participant-list', personIndex,
+ });
+ }
+
+ const rows = messages
+ .map((message) => ({ message: normalizeMessageRow(message, observedAt), raw: message }))
+ .filter(({ message }) => message.id)
+ .map(({ message, raw }) => ({ message, raw, attachments: normalizeAttachmentRows(raw) }));
+
+ const seenSenders = new Set();
+ for (const { message, raw } of rows) {
+ if (!message.senderId || seenSenders.has(message.senderId)) continue;
+ seenSenders.add(message.senderId);
+ // eslint-disable-next-line no-await-in-loop -- one row per distinct sender in this window
+ await upsertParticipant({
+ conversationId,
+ sourceUserId: message.senderId,
+ displayName: String(raw?.senderName ?? ''),
+ handle: '',
+ observedVia: 'message-sender',
+ personIndex,
+ });
+ }
+
+ // Touchpoints are derived from message SENDERS only, never from the
+ // participant roster (which truncates, so iterating it would invent contact
+ // with people who never messaged). Written BEFORE the commit deliberately:
+ // they are day-deduped on `beeper:<YYYY-MM-DD>`, so a rolled-back sweep
+ // re-derives exactly the same ones next pass, whereas writing them after the
+ // cursor advanced would lose them for good.
+ await logSenderTouchpoints(rows
+ .filter(({ raw }) => raw?.isSender !== true)
+ .map(({ message }) => ({
+ conversationId,
+ senderId: message.senderId,
+ sentAt: message.sentAt,
+ network: normalized.network,
+ })));
+
+ await commitMessages({
+ conversationId,
+ accountId: normalized.accountId,
+ sourceChatId: normalized.sourceChatId,
+ rows,
+ // A truncated forward walk advanced the cursor but did NOT reach the
+ // chat's newest message, so the watermark must stay where it was: a null
+ // here hits `COALESCE(EXCLUDED.last_activity, beeper_sync_cursors.…)` in
+ // `commitMessages` and keeps the stored value. `chatNeedsSweep` then still
+ // sees the chat as newer than its watermark next pass and resumes from the
+ // advanced cursor. Committing `normalized.lastActivity` instead would make
+ // the two timestamps equal, end the account walk at this chat, and strand
+ // the un-fetched backlog until unrelated new activity arrived. An empty
+ // first-page attempt withholds both for the same reason — see
+ // `emptyFirstPage` / `hadEmptyFirstPageAttempt` above (#81).
+ cursor: commitCursor,
+ lastActivity: commitLastActivity,
+ });
+
+ return { messages: rows.length };
+ }
+
+ /**
+ * One account's newest-first walk. A chat that throws is logged and counted,
+ * and the walk CONTINUES — the same blast-radius bound `executeSweep` gives
+ * each account. Without it, one chat that fails persistently (a bridge that
+ * 502s on its messages, say) sitting at the top of the newest-first list would
+ * abort this account's whole walk on every single pass and starve every chat
+ * below it indefinitely. Its cursor and watermark are untouched by the failed
+ * transaction, so it is retried next pass either way.
+ *
+ * A CAUGHT-UP CHAT DOES NOT END THE WALK, and that is the whole reason the
+ * truncation contract works. `sweepChat` withholds the watermark from a chat
+ * whose forward walk ran out of page budget, precisely so the chat stays
+ * eligible next pass — but the list is ordered by last activity, not by
+ * eligibility, so that chat sorts wherever its last message puts it. Ending the
+ * walk at the first chat that is not newer than its watermark therefore made
+ * the two rules cancel each other out: in the steady state, where the chats
+ * above are all caught up, a truncated chat sitting below one of them was never
+ * reached again and its backlog was stranded until unrelated activity moved it
+ * to the top of the list.
+ *
- * The termination rule is the PAGE instead: a page scanned end to end that
- * asked for no sweep at all means everything below it is older still. The page
- * budget stays the hard guarantee, so a pathological account still ends.
++ * A caught-up page cannot terminate the walk either: older pages can contain
++ * truncated, failed, or purged chats. Walk to the server's end or the page cap.
+ */
+ async function sweepAccount(account, clientOptions, observedAt, personIndex) {
+ const cursors = await readAccountCursors(account.accountId);
+ let cursor;
+ let chatsSwept = 0;
+ let messagesWritten = 0;
+ let failedChats = 0;
+
+ for (let pageIndex = 0; pageIndex < MAX_CHAT_PAGES_PER_ACCOUNT; pageIndex++) {
+ // eslint-disable-next-line no-await-in-loop -- cursor pagination is inherently sequential
+ const page = await listChatsPage({
+ cursor, direction: 'before', accountIDs: [account.accountId], ...clientOptions,
+ });
+ assertPagedShape(page, '/v1/chats');
+
- let pageNeededSweep = false;
+ for (const chat of page.items) {
+ const stored = cursors.get(String(chat?.id ?? ''));
+ if (!chatNeedsSweep(chat, stored)) continue;
- pageNeededSweep = true;
+ // eslint-disable-next-line no-await-in-loop -- one chat at a time; each is its own transaction
+ const result = await sweepChat({
+ chat, stored, clientOptions, observedAt, personIndex,
+ }).catch((err) => {
+ failedChats++;
+ console.error(`❌ ${LOG_PREFIX}: chat ${String(chat?.id ?? 'unknown')} failed: ${err.message}`);
+ return null;
+ });
+ if (!result) continue;
+ chatsSwept++;
+ messagesWritten += result.messages;
+ }
+
- // A chat that FAILED still counted as needing a sweep, so a bridge that
- // 502s cannot end the account's walk early either.
- if (!pageNeededSweep || !page.hasMore) break;
++ if (!page.hasMore) break;
+ if (!page.oldestCursor || page.oldestCursor === cursor) break;
+ cursor = page.oldestCursor;
+ }
+
+ return { chatsSwept, messagesWritten, failedChats };
+ }
+
+ // 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
+ // page the same chats twice and race on the same cursor rows. A caller that
+ // arrives mid-sweep is told so rather than queued — the in-flight sweep is
+ // already fetching everything the newcomer would have.
+ let inFlightSweep = null;
+
+ /**
+ * One invalidation frame, reusing the exact shape `beeperSocket.js` emits for
+ * a live domain frame (`{ kind, chatID, ids, seq, ts }`, fork issue #33) so
+ * the browser side needs no new handling: `useBeeperRealtime` already relays
+ * every frame's `kind` untouched, and `BeeperChatSurface`'s debounce treats a
+ * `chatID: null` frame as "could be about anything" and refetches the list —
+ * exactly right here, since one sweep can touch any number of conversations.
+ * This is fork issue #80's "reuse the existing push path instead of adding a
+ * client poller": `BeeperTab.jsx` already re-fetches `GET /api/beeper/status`
+ * on every invalidation frame, so a frame here is what makes the "Syncing… N
+ * of M accounts" strip move and the "Last synced" timestamp update live,
+ * without a second polling loop anywhere.
+ */
+ function emitSweepInvalidation() {
+ beeperSocketEvents.emit('invalidate', {
+ kind: 'beeper-sweep', chatID: null, ids: [], seq: null, ts: new Date().toISOString(),
+ });
+ }
+
+ async function executeSweep(reason) {
+ updateBeeperSweepProgress({
+ running: true, startedAt: new Date().toISOString(), finishedAt: null, reason,
+ accountsDone: 0, accountsTotal: null, chats: 0, messages: 0,
+ });
+ try {
+ const clientOptions = await resolveBeeperConfig();
+ if (!clientOptions.token) {
+ throw new BeeperApiError('Beeper access token is not configured', {
+ status: 401, code: 'NOT_CONFIGURED', retryable: false,
+ });
+ }
+
+ const startedAt = Date.now();
+ const observedAt = new Date(startedAt).toISOString();
+ const accounts = await refreshAccounts(clientOptions);
+ updateBeeperSweepProgress({ accountsTotal: accounts.length });
+ emitSweepInvalidation();
+
+ // Loaded ONCE for the whole sweep pass, across every account/chat/participant
+ // below — not once per participant. `upsertParticipant`'s phone-match
+ // fallback reindexes the entire Tribe roster on a miss, and a sweep touches
+ // every participant of every changed chat on every account.
+ const personIndex = await loadRosterIndex();
+
+ let chats = 0;
+ let messages = 0;
+ let accountsDone = 0;
+ let failedAccounts = 0;
+ let failedChats = 0;
+ for (const account of accounts) {
+ // eslint-disable-next-line no-await-in-loop -- accounts are swept in order; each owns its own cursors
+ const result = await sweepAccount(account, clientOptions, observedAt, personIndex).catch((err) => {
+ failedAccounts++;
+ console.error(`❌ ${LOG_PREFIX}: account ${account.accountId} failed: ${err.message}`);
+ return null;
+ });
+ if (result) {
+ chats += result.chatsSwept;
+ messages += result.messagesWritten;
+ failedChats += result.failedChats;
+ }
+ // #80: one account done, whether it succeeded or failed — "N of M" counts
+ // accounts attempted, not accounts that mirrored something.
+ accountsDone++;
+ updateBeeperSweepProgress({ accountsDone, chats, messages });
+ emitSweepInvalidation();
+ }
+
+ // Every account failing is a FAILED sweep, not a successful one that wrote
+ // nothing. Resolving here would have `eventScheduler` record a green run and
+ // `POST /api/beeper/sync` answer 200 while nothing was ingested at all —
+ // with only the `failedAccounts` count in the payload to say otherwise.
+ // Partial failure still resolves: the accounts that worked kept their pass.
+ if (accounts.length > 0 && failedAccounts === accounts.length) {
+ throw new BeeperApiError(`Beeper sweep failed for all ${accounts.length} accounts`, {
+ status: 502, code: 'SWEEP_FAILED', retryable: true,
+ });
+ }
+
+ const durationMs = Date.now() - startedAt;
+ console.log(`${LOG_PREFIX} (${reason}): ${accounts.length} accounts, ${chats} chats, ${messages} messages in ${durationMs}ms`);
+ return {
+ skipped: false,
+ reason,
+ accounts: accounts.length,
+ chats,
+ messages,
+ failedAccounts,
+ failedChats,
+ durationMs,
+ };
+ } finally {
+ // Always runs — a thrown NOT_CONFIGURED or SWEEP_FAILED must flip `running`
+ // back to false exactly like a clean resolve, or the status card would show
+ // a sweep in progress forever after the first failure.
+ updateBeeperSweepProgress({ running: false, finishedAt: new Date().toISOString() });
+ emitSweepInvalidation();
+ }
+ }
+
+ /**
+ * Run one watermark-bounded sweep. Exported for the scheduler, the manual
+ * run-now route, and #33's three socket triggers.
+ *
+ * Throws when the sweep cannot start at all (no token, roster unreachable) or
+ * when EVERY account failed — that is a failed run, not a successful one that
+ * wrote nothing. Partial failure resolves: a single account is isolated and
+ * reported as `failedAccounts` so one broken bridge cannot cost the others
+ * their pass, and a single failing chat as `failedChats` so it cannot starve
+ * the chats below it in its account's walk.
+ */
+ export async function runBeeperSweep({ reason = 'scheduler' } = {}) {
+ if (inFlightSweep) {
+ console.log(`${LOG_PREFIX} (${reason}): a sweep is already running — skipping`);
+ return {
+ skipped: true, reason, accounts: 0, chats: 0, messages: 0, failedAccounts: 0, failedChats: 0, durationMs: 0,
+ };
+ }
+ const run = executeSweep(reason);
+ inFlightSweep = run;
+ try {
+ return await run;
+ } finally {
+ inFlightSweep = null;
+ }
+ }
diff --cc server/services/beeperSync.test.js
index 0000000000,b9fdd2dc54..5c1e08fb05
mode 000000,100644..100644
--- a/server/services/beeperSync.test.js
+++ b/server/services/beeperSync.test.js
@@@ -1,0 -1,1113 +1,1112 @@@
+ import {
+ describe, it, expect, vi, beforeEach, afterEach,
+ } from 'vitest';
+
+ // The ingestion sweep (#32). Postgres is mocked (the row shapes themselves are
+ // pinned by beeperSync.db.test.js, which needs a real portos_test); `fetch` is
+ // mocked but the REAL beeperClient runs on top of it, so these tests also prove
+ // what actually reaches the wire — `accountIDs`, `cursor`, `direction` — rather
+ // than what the sweep merely intended to ask for.
+
+ const dbCalls = [];
+ const txCalls = [];
+ // Same statements as `txCalls`, with their params — `txCalls` is asserted as an
+ // ordered list of SQL strings all over this file, so the values ride alongside
+ // rather than inside it.
+ const txWrites = [];
+ let storedCursorRows = [];
+ let txFailPattern = null;
+
+ const queryMock = vi.fn(async (text, params) => {
+ dbCalls.push({ text, params });
+ if (/FROM beeper_sync_cursors/.test(text)) return { rows: storedCursorRows };
+ if (/INSERT INTO beeper_conversations/.test(text)) return { rows: [{ id: `conv-${params[2]}` }] };
+ return { rows: [] };
+ });
+
+ // Mirrors db.js's withTransaction contract: BEGIN, run, COMMIT — or ROLLBACK
+ // and rethrow. Recording the statements in order is what lets the tests below
+ // assert WHERE the cursor write sits relative to the rows it describes.
+ const withTransactionMock = vi.fn(async (fn) => {
+ txCalls.push('BEGIN');
+ const client = {
+ query: async (text, params) => {
+ txCalls.push(text.trim().split('\n')[0].trim());
+ txWrites.push({ text, params });
+ if (txFailPattern && txFailPattern.test(text)) throw new Error('simulated write failure');
+ return { rows: [] };
+ },
+ };
+ try {
+ const result = await fn(client);
+ txCalls.push('COMMIT');
+ return result;
+ } catch (err) {
+ txCalls.push('ROLLBACK');
+ throw err;
+ }
+ });
+
+ vi.mock('../lib/db.js', () => ({
+ query: (...args) => queryMock(...args),
+ withTransaction: (...args) => withTransactionMock(...args),
+ }));
+
+ const getSettingsMock = vi.fn(async () => ({
+ beeper: { token: 'test-token', baseUrl: 'http://127.0.0.1:23373', enabled: true, intervalMinutes: 5 },
+ }));
+ vi.mock('./settings.js', () => ({ getSettings: (...args) => getSettingsMock(...args) }));
+
+ const isInstanceFeatureEnabledMock = vi.fn(async () => true);
+ vi.mock('./instanceFeatures.js', () => ({
+ isInstanceFeatureEnabled: (...args) => isInstanceFeatureEnabledMock(...args),
+ }));
+
+ const upsertParticipantMock = vi.fn(async () => ({}));
+ const logSenderTouchpointsMock = vi.fn(async () => ({ created: 0, matched: 0 }));
+ // A stand-in roster index — its shape only matters to `buildPersonMatchIndex`
+ // consumers, and `upsertParticipant` itself is mocked above, so an empty index
+ // is enough to prove it is loaded once per sweep and threaded through.
+ const loadRosterIndexMock = vi.fn(async () => ({ byIdentifier: new Map(), byPhone: new Map(), byName: new Map() }));
+ vi.mock('./beeperTribe.js', () => ({
+ upsertParticipant: (...args) => upsertParticipantMock(...args),
+ logSenderTouchpoints: (...args) => logSenderTouchpointsMock(...args),
+ loadRosterIndex: (...args) => loadRosterIndexMock(...args),
+ }));
+
+ const {
+ runBeeperSweep, isBeeperIngestionArmed, getBeeperSyncConfig, chatNeedsSweep,
+ normalizeAccountRow, normalizeMessageRow, normalizeAttachmentRows, DEFAULT_INTERVAL_MINUTES,
+ } = await import('./beeperSync.js');
+ const { getBeeperSweepProgress, __resetBeeperSweepProgressForTests } = await import('./beeperSweepProgress.js');
+ const { beeperSocketEvents } = await import('./beeperSocketEvents.js');
+
+ // ---------------------------------------------------------------------------
+ // Fetch routing
+ // ---------------------------------------------------------------------------
+
+ const fetchedUrls = [];
+
+ function jsonResponse(body) {
+ return { ok: true, status: 200, text: async () => JSON.stringify(body) };
+ }
+
+ const ACCOUNTS = [{ accountID: 'acct-a', network: 'Example Net', user: { id: 'u-self', fullName: 'Example Owner' } }];
+ const BRIDGES = { items: [{ id: 'bridge-1', network: 'examplenet', status: 'connected', accounts: [{ accountID: 'acct-a' }] }] };
+
+ function installFetch({ chatPages = [], messagePages = {} } = {}) {
+ let chatPageIndex = 0;
+ const fetchMock = vi.fn(async (url) => {
+ fetchedUrls.push(url);
+ const parsed = new URL(url);
+ if (parsed.pathname === '/v1/accounts') return jsonResponse(ACCOUNTS);
+ if (parsed.pathname === '/v1/bridges') return jsonResponse(BRIDGES);
+ if (parsed.pathname === '/v1/chats') {
+ const page = chatPages[Math.min(chatPageIndex, chatPages.length - 1)] || { items: [], hasMore: false };
+ chatPageIndex++;
+ return jsonResponse(page);
+ }
+ const messageMatch = parsed.pathname.match(/^\/v1\/chats\/([^/]+)\/messages$/);
+ if (messageMatch) {
+ const chatId = decodeURIComponent(messageMatch[1]);
+ return jsonResponse(messagePages[chatId] || { items: [], hasMore: false });
+ }
+ throw new Error(`unexpected fetch: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ return fetchMock;
+ }
+
+ const chatsRequests = () => fetchedUrls.filter((url) => new URL(url).pathname === '/v1/chats');
+ const messageRequests = () => fetchedUrls.filter((url) => /\/messages$/.test(new URL(url).pathname));
+
+ /** The `(cursor, last_activity)` pair the last cursor upsert actually carried. */
+ const committedCursorRow = () => txWrites
+ .filter(({ text }) => text.includes('INSERT INTO beeper_sync_cursors'))
+ .map(({ params }) => ({ cursor: params[2], lastActivity: params[3] }))
+ .at(-1);
+
+ beforeEach(() => {
+ dbCalls.length = 0;
+ txCalls.length = 0;
+ txWrites.length = 0;
+ fetchedUrls.length = 0;
+ storedCursorRows = [];
+ txFailPattern = null;
+ queryMock.mockClear();
+ withTransactionMock.mockClear();
+ upsertParticipantMock.mockClear();
+ logSenderTouchpointsMock.mockClear();
+ loadRosterIndexMock.mockClear();
+ isInstanceFeatureEnabledMock.mockResolvedValue(true);
+ getSettingsMock.mockResolvedValue({
+ beeper: { token: 'test-token', baseUrl: 'http://127.0.0.1:23373', enabled: true, intervalMinutes: 5 },
+ });
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ __resetBeeperSweepProgressForTests();
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ });
+
+ // ---------------------------------------------------------------------------
+ // Arming gate (#32 acceptance: feature off or no token → nothing happens)
+ // ---------------------------------------------------------------------------
+
+ describe('isBeeperIngestionArmed', () => {
+ it('is false with the instance feature off, and never reads the credential', async () => {
+ isInstanceFeatureEnabledMock.mockResolvedValue(false);
+ expect(await isBeeperIngestionArmed()).toBe(false);
+ expect(getSettingsMock).not.toHaveBeenCalled();
+ });
+
+ it('is false with the feature on but no token configured', async () => {
+ getSettingsMock.mockResolvedValue({ beeper: { baseUrl: 'http://127.0.0.1:23373' } });
+ expect(await isBeeperIngestionArmed()).toBe(false);
+ });
+
+ it('is true only with both the feature on and a token present', async () => {
+ expect(await isBeeperIngestionArmed()).toBe(true);
+ });
+
+ it('never gates on Beeper app.state — a live instance reported "initializing" for 105s while healthy', async () => {
+ // Deliberately no /v1/app or /v1/info call at all: the gate must not be
+ // able to consult app.state even indirectly (#12 decision 2).
+ installFetch();
+ await isBeeperIngestionArmed();
+ expect(fetchedUrls).toEqual([]);
+ });
+ });
+
+ describe('getBeeperSyncConfig', () => {
+ it('defaults the interval to 5 minutes and treats a missing enabled flag as off', async () => {
+ getSettingsMock.mockResolvedValue({});
+ expect(await getBeeperSyncConfig()).toEqual({ enabled: false, intervalMinutes: DEFAULT_INTERVAL_MINUTES });
+ });
+
+ it('reads the user-configured interval', async () => {
+ getSettingsMock.mockResolvedValue({ beeper: { enabled: true, intervalMinutes: 15 } });
+ expect(await getBeeperSyncConfig()).toEqual({ enabled: true, intervalMinutes: 15 });
+ });
+ });
+
+ describe('runBeeperSweep without a token', () => {
+ it('throws a typed NOT_CONFIGURED error instead of sweeping', async () => {
+ getSettingsMock.mockResolvedValue({ beeper: {} });
+ installFetch();
+ await expect(runBeeperSweep({ reason: 'manual' })).rejects.toMatchObject({ code: 'NOT_CONFIGURED' });
+ expect(fetchedUrls).toEqual([]);
+ });
+ });
+
+ // ---------------------------------------------------------------------------
+ // Sweep progress + invalidation frames (#80) — this fails on the old code,
+ // which never touched `beeperSweepProgress.js` or `beeperSocketEvents` at all.
+ // ---------------------------------------------------------------------------
+
+ describe('sweep progress', () => {
+ it('is idle before any sweep has run', () => {
+ expect(getBeeperSweepProgress()).toMatchObject({
+ running: false, startedAt: null, finishedAt: null, accountsTotal: null, accountsDone: 0, chats: 0, messages: 0,
+ });
+ });
+
+ it('flips back to idle with the final counts once a sweep completes', async () => {
+ installFetch({ chatPages: [{ items: [], hasMore: false }] });
+
+ const result = await runBeeperSweep({ reason: 'manual' });
+
+ const progress = getBeeperSweepProgress();
+ expect(progress.running).toBe(false);
+ expect(progress.startedAt).toEqual(expect.any(String));
+ expect(progress.finishedAt).toEqual(expect.any(String));
+ // ACCOUNTS fixture carries exactly one account.
+ expect(progress.accountsTotal).toBe(1);
+ expect(progress.accountsDone).toBe(1);
+ expect(progress.chats).toBe(result.chats);
+ expect(progress.messages).toBe(result.messages);
+ });
+
+ it('still flips running back to false when the sweep throws before it can start (no token)', async () => {
+ getSettingsMock.mockResolvedValue({ beeper: {} });
+ installFetch();
+
+ await expect(runBeeperSweep({ reason: 'manual' })).rejects.toMatchObject({ code: 'NOT_CONFIGURED' });
+
+ const progress = getBeeperSweepProgress();
+ expect(progress.running).toBe(false);
+ expect(progress.finishedAt).toEqual(expect.any(String));
+ });
+
+ it('still flips running back to false when every account fails (SWEEP_FAILED)', async () => {
+ const fetchMock = vi.fn(async (url) => {
+ fetchedUrls.push(url);
+ const parsed = new URL(url);
+ if (parsed.pathname === '/v1/accounts') return jsonResponse(ACCOUNTS);
+ if (parsed.pathname === '/v1/bridges') return jsonResponse(BRIDGES);
+ if (parsed.pathname === '/v1/chats') return { ok: false, status: 502, text: async () => '{"error":"down"}' };
+ throw new Error(`unexpected fetch: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ await expect(runBeeperSweep({ reason: 'manual' })).rejects.toMatchObject({ code: 'SWEEP_FAILED' });
+
+ const progress = getBeeperSweepProgress();
+ expect(progress.running).toBe(false);
+ // The account was attempted (and failed) before the whole-sweep throw.
+ expect(progress.accountsDone).toBe(1);
+ expect(progress.finishedAt).toEqual(expect.any(String));
+ });
+
+ it('emits one invalidation frame per account, plus one when the total is known and one on completion', async () => {
+ installFetch({ chatPages: [{ items: [], hasMore: false }] });
+ const frames = [];
+ const onInvalidate = (frame) => frames.push(frame);
+ beeperSocketEvents.on('invalidate', onInvalidate);
+
+ try {
+ await runBeeperSweep({ reason: 'manual' });
+ } finally {
+ beeperSocketEvents.off('invalidate', onInvalidate);
+ }
+
+ // One account: the "accountsTotal known" frame, one per-account frame, and
+ // the finish frame in the `finally` — three, in order.
+ expect(frames).toHaveLength(3);
+ expect(frames.every((frame) => frame.kind === 'beeper-sweep' && frame.chatID === null)).toBe(true);
+ expect(frames.every((frame) => typeof frame.ts === 'string')).toBe(true);
+ });
+ });
+
+ // ---------------------------------------------------------------------------
+ // Watermark bounding
+ // ---------------------------------------------------------------------------
+
+ describe('watermark-bounded sweep', () => {
+ const CHAT_PAGE = {
+ items: [
+ {
+ id: 'chat-1',
+ accountID: 'acct-a',
+ network: 'Example Net',
+ title: 'Example Chat',
+ type: 'single',
+ unreadCount: 1,
+ lastActivity: '2026-09-02T10:00:00.000Z',
+ participants: { hasMore: false, total: 1, items: [{ id: 'user-1', fullName: 'Alice Example', phoneNumber: '+15550100001' }] },
+ },
+ {
+ id: 'chat-2',
+ accountID: 'acct-a',
+ network: 'Example Net',
+ title: 'Older Chat',
+ type: 'group',
+ unreadCount: 0,
+ lastActivity: '2026-08-01T00:00:00.000Z',
+ participants: { hasMore: true, total: 42, items: [] },
+ },
+ {
+ id: 'chat-3',
+ accountID: 'acct-a',
+ network: 'Example Net',
+ title: 'Oldest Chat',
+ type: 'single',
+ unreadCount: 0,
+ lastActivity: '2026-07-01T00:00:00.000Z',
+ participants: { hasMore: false, total: 0, items: [] },
+ },
+ ],
+ hasMore: true,
+ oldestCursor: 'chats-page-2',
+ };
+
+ it('pages only the chats that are newer than their watermark', async () => {
+ storedCursorRows = [
+ { chat_id: 'chat-1', cursor: 'cur-chat-1', last_activity: '2026-09-01T00:00:00.000Z' },
+ { chat_id: 'chat-2', cursor: 'cur-chat-2', last_activity: '2026-08-01T00:00:00.000Z' },
+ { chat_id: 'chat-3', cursor: 'cur-chat-3', last_activity: '2026-07-01T00:00:00.000Z' },
+ ];
+ installFetch({
+ chatPages: [CHAT_PAGE, { items: [], hasMore: false }],
+ messagePages: {
+ 'chat-1': {
+ items: [{
+ id: 'msg-1', chatID: 'chat-1', accountID: 'acct-a', senderID: 'user-1', senderName: 'Alice Example',
+ timestamp: '2026-09-02T10:00:00.000Z', sortKey: '0001', text: 'hello',
+ }],
+ hasMore: false,
+ newestCursor: 'cur-chat-1-next',
+ },
+ },
+ });
+
+ const result = await runBeeperSweep({ reason: 'manual' });
+
+ // chat-2 and chat-3 both sit exactly on their watermarks, so neither is
+ // paged for messages — but neither ends the walk, and the sweep stops on
+ // the next page instead, which asks for nothing at all.
+ expect(result).toMatchObject({ skipped: false, accounts: 1, chats: 1, messages: 1, failedAccounts: 0 });
+ expect(messageRequests()).toHaveLength(1);
+ expect(new URL(messageRequests()[0]).pathname).toBe('/v1/chats/chat-1/messages');
+ expect(chatsRequests()).toHaveLength(2);
+ });
+
+ // The truncation contract (`sweepChat` withholding the watermark) and the old
+ // "stop at the first caught-up chat" rule cancelled each other out: the list
+ // is ordered by last activity, not by eligibility, so in the steady state a
+ // truncated chat sat below chats that were caught up and was never reached
+ // again. Its backlog was stranded until unrelated activity moved it back to
+ // the top of the list.
- it('walks past a caught-up chat to a truncated one below it, then stops on a page that needs nothing', async () => {
++ it('walks past a caught-up page to resume a truncated chat on an older page', async () => {
+ const chatRow = (id, lastActivity) => ({
+ id,
+ accountID: 'acct-a',
+ network: 'Example Net',
+ title: `Example Chat ${id}`,
+ type: 'single',
+ lastActivity,
+ participants: { hasMore: false, total: 0, items: [] },
+ });
+ storedCursorRows = [
+ // Caught up: its watermark equals its current activity.
+ { chat_id: 'chat-caught-up', cursor: 'cur-caught-up', last_activity: '2026-09-02T10:00:00.000Z' },
+ // Truncated on an earlier pass: the cursor advanced, the watermark did
+ // not, so it is still eligible — and it sorts BELOW the caught-up chat.
+ { chat_id: 'chat-truncated', cursor: 'cur-truncated', last_activity: '2026-08-01T00:00:00.000Z' },
+ { chat_id: 'chat-quiet', cursor: 'cur-quiet', last_activity: '2026-07-01T00:00:00.000Z' },
+ ];
+ installFetch({
+ chatPages: [
+ {
- items: [chatRow('chat-caught-up', '2026-09-02T10:00:00.000Z'), chatRow('chat-truncated', '2026-09-01T00:00:00.000Z')],
++ items: [chatRow('chat-caught-up', '2026-09-02T10:00:00.000Z')],
+ hasMore: true,
+ oldestCursor: 'chats-page-2',
+ },
- { items: [chatRow('chat-quiet', '2026-07-01T00:00:00.000Z')], hasMore: true, oldestCursor: 'chats-page-3' },
++ { items: [chatRow('chat-truncated', '2026-09-01T00:00:00.000Z'), chatRow('chat-quiet', '2026-07-01T00:00:00.000Z')], hasMore: false },
+ ],
+ messagePages: {
+ 'chat-truncated': {
+ items: [{ id: 'msg-b', senderID: 'user-1', text: 'Example message', timestamp: '2026-09-01T00:00:00.000Z' }],
+ hasMore: false,
+ newestCursor: 'cur-truncated-next',
+ },
+ },
+ });
+
+ const result = await runBeeperSweep({ reason: 'manual' });
+
+ expect(result).toMatchObject({ skipped: false, chats: 1, messages: 1, failedChats: 0 });
+ expect(messageRequests()).toHaveLength(1);
+ expect(new URL(messageRequests()[0]).pathname).toBe('/v1/chats/chat-truncated/messages');
- // Page two asked for nothing, so the walk ends there rather than running
- // out the 20-page budget — the page is the terminator, not the chat.
++ // A fully caught-up first page must not hide a backlog on the second.
+ expect(chatsRequests()).toHaveLength(2);
+ });
+
+ it('sends accountIDs, and resumes each chat forward from its stored opaque cursor', async () => {
+ storedCursorRows = [{ chat_id: 'chat-1', cursor: 'cur-chat-1', last_activity: '2026-09-01T00:00:00.000Z' }];
+ installFetch({
+ chatPages: [{ ...CHAT_PAGE, items: [CHAT_PAGE.items[0]], hasMore: false }],
+ messagePages: { 'chat-1': { items: [], hasMore: false } },
+ });
+
+ await runBeeperSweep({ reason: 'manual' });
+
+ const chatParams = new URL(chatsRequests()[0]).searchParams;
+ expect(chatParams.getAll('accountIDs')).toEqual(['acct-a']);
+ expect(chatParams.get('direction')).toBe('before');
+
+ const messageParams = new URL(messageRequests()[0]).searchParams;
+ expect(messageParams.get('cursor')).toBe('cur-chat-1');
+ expect(messageParams.get('direction')).toBe('after');
+ });
+
+ it('takes only the newest page for a chat it has never swept — a first sweep is not a history backfill', async () => {
+ installFetch({
+ chatPages: [{ items: [CHAT_PAGE.items[0]], hasMore: false }],
+ messagePages: {
+ 'chat-1': {
+ items: [{ id: 'msg-1', senderID: 'user-1', timestamp: '2026-09-02T10:00:00.000Z', sortKey: '0001', text: 'hi' }],
+ hasMore: true,
+ oldestCursor: 'older-page',
+ newestCursor: 'cur-newest',
+ },
+ },
+ });
+
+ await runBeeperSweep({ reason: 'manual' });
+
+ // hasMore is true and there IS an older page, but a never-swept chat takes
+ // exactly one page and anchors its cursor at the newest message.
+ expect(messageRequests()).toHaveLength(1);
+ const params = new URL(messageRequests()[0]).searchParams;
+ expect(params.get('cursor')).toBeNull();
+ expect(params.get('direction')).toBe('before');
+ });
+
+ it('relates senders and participants through beeperTribe rather than writing identity rows itself', async () => {
+ installFetch({
+ chatPages: [{ items: [CHAT_PAGE.items[0]], hasMore: false }],
+ messagePages: {
+ 'chat-1': {
+ items: [
+ { id: 'msg-1', senderID: 'user-1', senderName: 'Alice Example', timestamp: '2026-09-02T10:00:00.000Z', sortKey: '1', text: 'hi' },
+ { id: 'msg-2', senderID: 'u-self', isSender: true, timestamp: '2026-09-02T10:01:00.000Z', sortKey: '2', text: 'hey' },
+ ],
+ hasMore: false,
+ newestCursor: 'cur-newest',
+ },
+ },
+ });
+
+ await runBeeperSweep({ reason: 'manual' });
+
+ expect(upsertParticipantMock).toHaveBeenCalledWith(expect.objectContaining({
+ sourceUserId: 'user-1', handle: '+15550100001', observedVia: 'participant-list',
+ }));
+ expect(upsertParticipantMock).toHaveBeenCalledWith(expect.objectContaining({
+ sourceUserId: 'u-self', observedVia: 'message-sender',
+ }));
+ // A message the user SENT is not contact from anyone, so it never becomes a
+ // touchpoint candidate.
+ const [candidates] = logSenderTouchpointsMock.mock.calls[0];
+ expect(candidates.map((c) => c.senderId)).toEqual(['user-1']);
+ });
+ });
+
+ // ---------------------------------------------------------------------------
+ // The transaction boundary — the point of the module
+ // ---------------------------------------------------------------------------
+
+ describe('cursor transactionality', () => {
+ const ONE_CHAT = {
+ items: [{
+ id: 'chat-1',
+ accountID: 'acct-a',
+ network: 'Example Net',
+ title: 'Example Chat',
+ type: 'single',
+ unreadCount: 0,
+ lastActivity: '2026-09-02T10:00:00.000Z',
+ participants: { hasMore: false, total: 0, items: [] },
+ }],
+ hasMore: false,
+ };
+ const ONE_MESSAGE = {
+ 'chat-1': {
+ items: [{ id: 'msg-1', senderID: 'user-1', timestamp: '2026-09-02T10:00:00.000Z', sortKey: '1', text: 'hello' }],
+ hasMore: false,
+ newestCursor: 'cur-advanced',
+ },
+ };
+
+ it('commits message rows, attachment rows and the cursor in one transaction, cursor last', async () => {
+ installFetch({
+ chatPages: [ONE_CHAT],
+ messagePages: {
+ 'chat-1': {
+ ...ONE_MESSAGE['chat-1'],
+ items: [{
+ ...ONE_MESSAGE['chat-1'].items[0],
+ attachments: [{
+ type: 'img',
+ id: 'mxc://example.invalid/abc',
+ srcURL: '/tmp/should-never-be-persisted.png',
+ mimeType: 'image/png',
+ fileName: 'photo.png',
+ fileSize: 2048,
+ size: { width: 800, height: 600 },
+ }],
+ }],
+ },
+ },
+ });
+
+ await runBeeperSweep({ reason: 'manual' });
+
+ expect(txCalls[0]).toBe('BEGIN');
+ expect(txCalls.at(-1)).toBe('COMMIT');
+ const messageIndex = txCalls.findIndex((sql) => sql.includes('INSERT INTO beeper_messages'));
+ const attachmentIndex = txCalls.findIndex((sql) => sql.includes('INSERT INTO beeper_attachments'));
+ const cursorIndex = txCalls.findIndex((sql) => sql.includes('INSERT INTO beeper_sync_cursors'));
+ expect(messageIndex).toBeGreaterThan(0);
+ expect(attachmentIndex).toBeGreaterThan(messageIndex);
+ expect(cursorIndex).toBeGreaterThan(attachmentIndex);
+ });
+
+ it('persists isSender on the message row, and never downgrades a stored TRUE', async () => {
+ installFetch({
+ chatPages: [ONE_CHAT],
+ messagePages: {
+ 'chat-1': {
+ ...ONE_MESSAGE['chat-1'],
+ items: [{ ...ONE_MESSAGE['chat-1'].items[0], isSender: true }],
+ },
+ },
+ });
+
+ await runBeeperSweep({ reason: 'manual' });
+
+ const insert = txWrites.find(({ text }) => text.includes('INSERT INTO beeper_messages'));
+ expect(insert).toBeTruthy();
+ expect(insert.params.at(-1)).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
+ // stored TRUE survives a second sweep lives in `beeperSync.db.test.js`.
+ expect(insert.text).toContain('is_sender = beeper_messages.is_sender OR EXCLUDED.is_sender');
+ });
+
+ it('leaves the cursor unmoved when a row write throws before the commit', async () => {
+ txFailPattern = /INSERT INTO beeper_messages/;
+ installFetch({ chatPages: [ONE_CHAT], messagePages: ONE_MESSAGE });
+
+ const result = await runBeeperSweep({ reason: 'manual' });
+
+ expect(txCalls).toContain('BEGIN');
+ expect(txCalls).toContain('ROLLBACK');
+ expect(txCalls).not.toContain('COMMIT');
+ // The whole point: nothing ever tried to move the cursor, so the next sweep
+ // refetches exactly the same window.
+ expect(txCalls.some((sql) => sql.includes('beeper_sync_cursors'))).toBe(false);
+ expect(dbCalls.some(({ text }) => /UPDATE beeper_sync_cursors|INSERT INTO beeper_sync_cursors/.test(text))).toBe(false);
+ // One broken chat is isolated to itself: the account keeps its pass and the
+ // sweep still resolves, with the failure surfaced as `failedChats`.
+ expect(result).toMatchObject({
+ skipped: false, failedAccounts: 0, failedChats: 1, messages: 0,
+ });
+ });
+
+ it('rolls the rows back too when the cursor write itself throws', async () => {
+ txFailPattern = /beeper_sync_cursors/;
+ installFetch({ chatPages: [ONE_CHAT], messagePages: ONE_MESSAGE });
+
+ await runBeeperSweep({ reason: 'manual' });
+
+ expect(txCalls).toContain('ROLLBACK');
+ expect(txCalls).not.toContain('COMMIT');
+ });
+
+ it('never persists an attachment srcURL — only durable reference metadata', async () => {
+ const rows = normalizeAttachmentRows({
+ attachments: [{
+ type: 'img',
+ id: 'mxc://example.invalid/abc',
+ srcURL: '/tmp/decays.png',
+ posterImg: '/tmp/poster.png',
+ mimeType: 'image/png',
+ fileName: 'photo.png',
+ fileSize: 2048,
+ size: { width: 800, height: 600 },
+ }],
+ });
+ expect(rows).toEqual([{
+ idx: 0, mxcId: 'mxc://example.invalid/abc', mimeType: 'image/png',
+ byteLength: 2048, fileName: 'photo.png', width: 800, height: 600,
+ }]);
+ });
+ });
+
+ // ---------------------------------------------------------------------------
+ // Truncated forward walk — the watermark must not outrun the fetch
+ // ---------------------------------------------------------------------------
+
+ // A chat further behind than MAX_MESSAGE_PAGES_PER_CHAT is the one case where
+ // the cursor advances but the chat is NOT caught up. Committing its current
+ // `lastActivity` as the watermark would make the two timestamps equal, so
+ // `chatNeedsSweep` would return false, `sweepAccount` would treat that as
+ // "watermark reached", and the un-fetched newest messages would never arrive
+ // until unrelated activity moved the chat again — the mirror showing a stale
+ // last message indefinitely. The watermark therefore stays put (null into the
+ // COALESCE) while the cursor moves, so the next pass resumes mid-backlog.
+ describe('a chat with more new messages than the page cap', () => {
+ const CHAT_ID = 'chat-backlog';
+ const CHAT_ACTIVITY = '2026-09-02T10:00:00.000Z';
+ const STORED_WATERMARK = '2026-09-01T00:00:00.000Z';
+
+ const chatPage = () => ({
+ items: [{
+ id: CHAT_ID,
+ accountID: 'acct-a',
+ network: 'Example Net',
+ title: 'Example Backlog Chat',
+ type: 'single',
+ lastActivity: CHAT_ACTIVITY,
+ participants: { hasMore: false, total: 1, items: [{ id: 'user-1', fullName: 'Alice Example' }] },
+ }],
+ hasMore: false,
+ });
+
+ // Every message page reports `hasMore: true` and a fresh `newestCursor`, so
+ // the forward walk can only ever stop by running out of page budget.
+ function installEndlessBacklogFetch() {
+ let messagePageIndex = 0;
+ const fetchMock = vi.fn(async (url) => {
+ fetchedUrls.push(url);
+ const parsed = new URL(url);
+ if (parsed.pathname === '/v1/accounts') return jsonResponse(ACCOUNTS);
+ if (parsed.pathname === '/v1/bridges') return jsonResponse(BRIDGES);
+ if (parsed.pathname === '/v1/chats') return jsonResponse(chatPage());
+ if (/\/messages$/.test(parsed.pathname)) {
+ messagePageIndex++;
+ return jsonResponse({
+ items: [{
+ id: `msg-${messagePageIndex}`,
+ senderID: 'user-1',
+ text: 'Example message',
+ timestamp: '2026-09-02T09:00:00.000Z',
+ sortKey: `${messagePageIndex}`,
+ }],
+ hasMore: true,
+ newestCursor: `cursor-${messagePageIndex}`,
+ });
+ }
+ throw new Error(`unexpected fetch: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ }
+
+ it('leaves last_activity unchanged on the first pass and resumes from the advanced cursor on the second', async () => {
+ storedCursorRows = [{ chat_id: CHAT_ID, cursor: 'cursor-0', last_activity: STORED_WATERMARK }];
+ installEndlessBacklogFetch();
+
+ const first = await runBeeperSweep({ reason: 'manual' });
+
+ // Pass one stopped at the cap, so it walked exactly MAX_MESSAGE_PAGES_PER_CHAT
+ // message pages and wrote a row per page.
+ expect(messageRequests()).toHaveLength(10);
+ expect(first).toMatchObject({ skipped: false, chats: 1, messages: 10 });
+ // The cursor moved; the watermark did NOT. A null here is what makes the
+ // existing `COALESCE(EXCLUDED.last_activity, beeper_sync_cursors.last_activity)`
+ // keep the stored value instead of jumping to the chat's current activity.
+ const committed = committedCursorRow();
+ expect(committed.cursor).toBe('cursor-10');
+ expect(committed.lastActivity).toBeNull();
+ expect(committed.lastActivity).not.toBe(CHAT_ACTIVITY);
+
+ // Now play the database's part: the cursor took EXCLUDED, the watermark
+ // kept its old value through the COALESCE.
+ fetchedUrls.length = 0;
+ txWrites.length = 0;
+ storedCursorRows = [{ chat_id: CHAT_ID, cursor: committed.cursor, last_activity: STORED_WATERMARK }];
+
+ const second = await runBeeperSweep({ reason: 'manual' });
+
+ // The chat is still newer than its watermark, so pass two sweeps it again
+ // rather than deciding the account walk had reached the watermark.
+ expect(second).toMatchObject({ skipped: false, chats: 1, messages: 10 });
+ const firstMessageRequest = new URL(messageRequests()[0]);
+ expect(firstMessageRequest.searchParams.get('cursor')).toBe('cursor-10');
+ expect(firstMessageRequest.searchParams.get('direction')).toBe('after');
+ });
+
+ it('does commit the watermark once the walk actually reaches the end', async () => {
+ storedCursorRows = [{ chat_id: CHAT_ID, cursor: 'cursor-0', last_activity: STORED_WATERMARK }];
+ installFetch({
+ chatPages: [chatPage()],
+ messagePages: {
+ [CHAT_ID]: {
+ items: [{ id: 'msg-1', senderID: 'user-1', text: 'Example message', timestamp: '2026-09-02T09:00:00.000Z' }],
+ hasMore: false,
+ newestCursor: 'cursor-final',
+ },
+ },
+ });
+
+ await runBeeperSweep({ reason: 'manual' });
+
+ expect(committedCursorRow()).toEqual({ cursor: 'cursor-final', lastActivity: CHAT_ACTIVITY });
+ });
+ });
+
+ // ---------------------------------------------------------------------------
+ // A forward walk that stalls is truncated too, not finished
+ // ---------------------------------------------------------------------------
+
+ // The page budget is not the only way a forward walk can end short of the
+ // newest message. A server that answers `hasMore: true` and then hands back no
+ // usable cursor — a null one, or the very cursor it was just given — leaves
+ // exactly the same state: messages exist that this pass never fetched. Reading
+ // that as a clean end committed the chat's current activity as its watermark,
+ // so `chatNeedsSweep` marked the chat caught up and everything past the stall
+ // was lost.
+ describe('a forward walk the server stalls with hasMore but no usable cursor', () => {
+ const CHAT_ID = 'chat-stalled';
+ const CHAT_ACTIVITY = '2026-09-02T10:00:00.000Z';
+ const STORED_CURSOR = 'cur-stored';
+ const STORED_WATERMARK = '2026-09-01T00:00:00.000Z';
+
+ const chatPage = () => ({
+ items: [{
+ id: CHAT_ID,
+ accountID: 'acct-a',
+ network: 'Example Net',
+ title: 'Example Stalled Chat',
+ type: 'single',
+ lastActivity: CHAT_ACTIVITY,
+ participants: { hasMore: false, total: 0, items: [] },
+ }],
+ hasMore: false,
+ });
+
+ const messagePage = (newestCursor) => ({
+ items: [{ id: 'msg-1', senderID: 'user-1', text: 'Example message', timestamp: '2026-09-02T09:00:00.000Z', sortKey: '1' }],
+ hasMore: true,
+ newestCursor,
+ });
+
+ it.each([
+ ['a null newestCursor', null],
+ ['the cursor it was handed', STORED_CURSOR],
+ ])('holds the watermark back when the page answers hasMore with %s', async (_label, newestCursor) => {
+ storedCursorRows = [{ chat_id: CHAT_ID, cursor: STORED_CURSOR, last_activity: STORED_WATERMARK }];
+ installFetch({ chatPages: [chatPage()], messagePages: { [CHAT_ID]: messagePage(newestCursor) } });
+
+ await runBeeperSweep({ reason: 'manual' });
+
+ // The walk asked once, could not continue, and did NOT reach the newest
+ // message — so a null watermark rides into the COALESCE and the stored one
+ // survives.
+ expect(messageRequests()).toHaveLength(1);
+ expect(committedCursorRow().lastActivity).toBeNull();
+ expect(committedCursorRow().lastActivity).not.toBe(CHAT_ACTIVITY);
+
+ // Which is what keeps the chat eligible: the database kept the old
+ // watermark, so the next pass still sees the chat as moved.
+ expect(chatNeedsSweep({ lastActivity: CHAT_ACTIVITY }, { lastActivity: STORED_WATERMARK })).toBe(true);
+ });
+
+ it('still commits the watermark when the stall is on a first-sweep anchor walk', async () => {
+ // A chat with no stored cursor takes the newest page ONLY and is never
+ // trying to reach the end, so its `hasMore: true` is expected rather than a
+ // truncation — the anchor is exactly what it went to fetch.
+ installFetch({ chatPages: [chatPage()], messagePages: { [CHAT_ID]: messagePage(null) } });
+
+ await runBeeperSweep({ reason: 'manual' });
+
+ expect(committedCursorRow().lastActivity).toBe(CHAT_ACTIVITY);
+ });
+ });
+
+ // ---------------------------------------------------------------------------
+ // #81: a first-page anchor fetch that comes back empty is retried once, not
+ // silently marked done — not a message-kind filter (there is none in
+ // `beeperClient.js`) and not the sweep/page budget (it only bounds the
+ // forward `'after'` catch-up walk on a chat that already has a cursor). The
+ // old code simply committed `normalized.lastActivity` on ANY first-page
+ // result, empty or not, so a chat that got nothing back on its one shot never
+ // got a second look. This retry covers a chat whose activity IS real but
+ // whose first page still came back empty (a transient fetch hiccup, or a
+ // history-less chat gaining its first-ever activity right as it enters the
+ // mirror) — NOT the population the read-only live-instance investigation on
+ // fork issue #81 actually observed empty (chats Beeper itself never reports
+ // activity for at all, so `chatNeedsSweep` never re-selects them regardless
+ // of this retry). That population's reported symptom — empty rows sorting
+ // above recent threads — is fixed by the sort fallback in
+ // `beeperConversations.js`, not by this retry.
+ // ---------------------------------------------------------------------------
+
+ describe('#81 — first page comes back with zero messages', () => {
+ const CHAT_ID = 'chat-empty-first-page';
+ const CHAT_ACTIVITY = '2026-09-02T10:00:00.000Z';
+
+ const chatPage = () => ({
+ items: [{
+ id: CHAT_ID,
+ accountID: 'acct-a',
+ network: 'Example Net',
+ title: 'Example Chat',
+ type: 'single',
+ lastActivity: CHAT_ACTIVITY,
+ participants: { hasMore: false, total: 0, items: [] },
+ }],
+ hasMore: false,
+ });
+
+ it('withholds the cursor and watermark on a never-swept chat whose first page returns nothing, instead of marking it done', async () => {
+ storedCursorRows = [];
+ installFetch({
+ chatPages: [chatPage()],
+ messagePages: { [CHAT_ID]: { items: [], hasMore: false } },
+ });
+
+ const result = await runBeeperSweep({ reason: 'manual' });
+
+ expect(messageRequests()).toHaveLength(1);
+ expect(result).toMatchObject({ skipped: false, chats: 1, messages: 0 });
+ // Both withheld — the OLD code committed `normalized.lastActivity`
+ // unconditionally here, which is exactly what marked the chat
+ // permanently done on one empty page.
+ expect(committedCursorRow()).toEqual({ cursor: null, lastActivity: null });
+ expect(console.warn).not.toHaveBeenCalled();
+ });
+
+ it('retries a chat left in the withheld state and commits normally once messages actually come back', async () => {
+ // The state a withheld first pass leaves behind: a cursor row that exists
+ // but carries neither a cursor nor a watermark — the storage-free "already
+ // retried once" marker `sweepChat` reads back.
+ storedCursorRows = [{ chat_id: CHAT_ID, cursor: null, last_activity: null }];
+ installFetch({
+ chatPages: [chatPage()],
+ messagePages: {
+ [CHAT_ID]: {
+ items: [{
+ id: 'msg-1', senderID: 'user-1', text: 'Example message',
+ timestamp: '2026-09-02T09:59:00.000Z', sortKey: '1',
+ }],
+ hasMore: false,
+ newestCursor: 'cursor-retry',
+ },
+ },
+ });
+
+ await runBeeperSweep({ reason: 'manual' });
+
+ // Retried the SAME first-page fetch (no stored cursor to walk forward
+ // from), and this time it worked — commits like any other first sweep.
+ const firstMessageRequest = new URL(messageRequests()[0]);
+ expect(firstMessageRequest.searchParams.get('direction')).toBe('before');
+ expect(committedCursorRow()).toEqual({ cursor: 'cursor-retry', lastActivity: CHAT_ACTIVITY });
+ expect(console.warn).not.toHaveBeenCalled();
+ });
+
+ it('gives up and logs once when the retry is ALSO empty, so the chat is not re-swept forever', async () => {
+ storedCursorRows = [{ chat_id: CHAT_ID, cursor: null, last_activity: null }];
+ installFetch({
+ chatPages: [chatPage()],
+ messagePages: { [CHAT_ID]: { items: [], hasMore: false } },
+ });
+
+ await runBeeperSweep({ reason: 'manual' });
+
+ // The real (non-null) watermark commits this time, so `chatNeedsSweep`
+ // reaches the same steady state a genuinely history-less chat already
+ // does — no more retries — and exactly one warn line names the chat
+ // (id only, never content).
+ expect(committedCursorRow()).toEqual({ cursor: null, lastActivity: CHAT_ACTIVITY });
+ expect(chatNeedsSweep({ lastActivity: CHAT_ACTIVITY }, { lastActivity: CHAT_ACTIVITY })).toBe(false);
+ expect(console.warn).toHaveBeenCalledTimes(1);
+ expect(console.warn).toHaveBeenCalledWith(expect.stringContaining(CHAT_ID));
+ });
+
+ it('does not withhold when the first page returns a message, even with hasMore/newestCursor absent', async () => {
+ // Guards the boundary: `emptyFirstPage` must key on `messages.length`, not
+ // on the presence of a cursor — a first page can legitimately answer
+ // `hasMore: false` with no `newestCursor` at all once it has content.
+ storedCursorRows = [];
+ installFetch({
+ chatPages: [chatPage()],
+ messagePages: {
+ [CHAT_ID]: {
+ items: [{ id: 'msg-1', senderID: 'user-1', text: 'hi', timestamp: '2026-09-02T09:59:00.000Z', sortKey: '1' }],
+ hasMore: false,
+ },
+ },
+ });
+
+ await runBeeperSweep({ reason: 'manual' });
+
+ expect(committedCursorRow()).toEqual({ cursor: null, lastActivity: CHAT_ACTIVITY });
+ expect(console.warn).not.toHaveBeenCalled();
+ });
+ });
+
+ // ---------------------------------------------------------------------------
+ // Failure isolation
+ // ---------------------------------------------------------------------------
+
+ describe('failure isolation', () => {
+ const chatRow = (id, lastActivity) => ({
+ id,
+ accountID: 'acct-a',
+ network: 'Example Net',
+ title: `Example Chat ${id}`,
+ type: 'single',
+ lastActivity,
+ participants: { hasMore: false, total: 0, items: [] },
+ });
+
+ it('keeps walking an account after one chat throws, so a broken chat cannot starve the ones below it', async () => {
+ const fetchMock = vi.fn(async (url) => {
+ fetchedUrls.push(url);
+ const parsed = new URL(url);
+ if (parsed.pathname === '/v1/accounts') return jsonResponse(ACCOUNTS);
+ if (parsed.pathname === '/v1/bridges') return jsonResponse(BRIDGES);
+ if (parsed.pathname === '/v1/chats') {
+ return jsonResponse({
+ items: [chatRow('chat-broken', '2026-09-02T10:00:00.000Z'), chatRow('chat-ok', '2026-09-02T09:00:00.000Z')],
+ hasMore: false,
+ });
+ }
+ const match = parsed.pathname.match(/^\/v1\/chats\/([^/]+)\/messages$/);
+ if (match && decodeURIComponent(match[1]) === 'chat-broken') {
+ return { ok: false, status: 502, text: async () => '{"error":"bridge down"}' };
+ }
+ if (match) {
+ return jsonResponse({
+ items: [{ id: 'msg-ok', senderID: 'user-9', text: 'Example message', timestamp: '2026-09-02T09:00:00.000Z' }],
+ hasMore: false,
+ newestCursor: 'cursor-ok',
+ });
+ }
+ throw new Error(`unexpected fetch: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ const result = await runBeeperSweep({ reason: 'manual' });
+
+ expect(result).toMatchObject({
+ skipped: false, failedAccounts: 0, failedChats: 1, chats: 1, messages: 1,
+ });
+ expect(messageRequests().some((url) => url.includes('chat-ok'))).toBe(true);
+ });
+
+ it('throws when every account fails, so the scheduler records a failed run instead of a green one', async () => {
+ const fetchMock = vi.fn(async (url) => {
+ fetchedUrls.push(url);
+ const parsed = new URL(url);
+ if (parsed.pathname === '/v1/accounts') return jsonResponse(ACCOUNTS);
+ if (parsed.pathname === '/v1/bridges') return jsonResponse(BRIDGES);
+ if (parsed.pathname === '/v1/chats') return { ok: false, status: 502, text: async () => '{"error":"down"}' };
+ throw new Error(`unexpected fetch: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ await expect(runBeeperSweep({ reason: 'scheduler' })).rejects.toMatchObject({ code: 'SWEEP_FAILED' });
+ });
+
+ it('still resolves when there are no accounts at all', async () => {
+ const fetchMock = vi.fn(async (url) => {
+ fetchedUrls.push(url);
+ const parsed = new URL(url);
+ if (parsed.pathname === '/v1/accounts') return jsonResponse([]);
+ if (parsed.pathname === '/v1/bridges') return jsonResponse({ items: [] });
+ throw new Error(`unexpected fetch: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ await expect(runBeeperSweep({ reason: 'manual' }))
+ .resolves.toMatchObject({ skipped: false, accounts: 0, failedAccounts: 0 });
+ });
+ });
+
+ describe('re-entrancy', () => {
+ it('refuses to start a second sweep while one is in flight', async () => {
+ installFetch({ chatPages: [{ items: [], hasMore: false }] });
+
+ const first = runBeeperSweep({ reason: 'scheduler' });
+ const second = await runBeeperSweep({ reason: 'socket-reconnect' });
+ const firstResult = await first;
+
+ expect(second).toMatchObject({ skipped: true, reason: 'socket-reconnect' });
+ expect(firstResult.skipped).toBe(false);
+ });
+
+ it('releases the guard after a failing sweep so the next one can run', async () => {
+ getSettingsMock.mockResolvedValue({ beeper: {} });
+ installFetch();
+ await expect(runBeeperSweep({ reason: 'manual' })).rejects.toThrow();
+
+ getSettingsMock.mockResolvedValue({ beeper: { token: 'test-token' } });
+ installFetch({ chatPages: [{ items: [], hasMore: false }] });
+ await expect(runBeeperSweep({ reason: 'manual' })).resolves.toMatchObject({ skipped: false });
+ });
+ });
+
+ // ---------------------------------------------------------------------------
+ // Normalizers
+ // ---------------------------------------------------------------------------
+
+ describe('normalizers', () => {
+ it('never carries loginID into an account row', () => {
+ const row = normalizeAccountRow({
+ accountID: 'acct-a',
+ loginID: '+15550100001',
+ network: 'Example Net',
+ status: 'connected',
+ bridgeId: 'bridge-1',
+ user: { fullName: 'Example Owner' },
+ });
+ expect(row).toEqual({
+ accountId: 'acct-a', network: 'Example Net', displayName: 'Example Owner',
+ status: 'connected', bridgeId: 'bridge-1',
+ });
+ expect(JSON.stringify(row)).not.toContain('5550100001');
+ });
+
+ // Live /v1/accounts items carry `bridge` as an OBJECT { id, type, provider
+ // }, never a string, and an account absent from every /v1/bridges
+ // items[].accounts[] entry leaves the join's `bridgeId` null — the object
+ // must be narrowed to `.id`, not coerced whole (String() on an object
+ // produces the literal text "[object Object]").
+ it('reads bridgeId off the raw bridge object when the bridge join has no match', () => {
+ const row = normalizeAccountRow({
+ accountID: 'acct-b',
+ network: 'Example Net',
+ status: 'connected',
+ bridgeId: null,
+ bridge: { id: 'bridge-2', type: 'example', provider: 'exampleprovider' },
+ user: { fullName: 'Example Owner' },
+ });
+ expect(row.bridgeId).toBe('bridge-2');
+ });
+
+ it('records an unsend as an observation-time tombstone, never as a removal', () => {
+ const row = normalizeMessageRow(
+ { id: 'msg-1', senderID: 'user-1', isDeleted: true, text: '', timestamp: '2026-09-01T00:00:00.000Z', sortKey: '1' },
+ '2026-09-02T12:00:00.000Z',
+ );
+ expect(row.unsentAt).toBe('2026-09-02T12:00:00.000Z');
+ expect(row.id).toBe('msg-1');
+ });
+
+ // Direction is the ONLY thing a chat surface cannot reconstruct from the rest
+ // of the row: `accounts[].user.id` differs from `senderID` on every network
+ // (#2), so there is nothing to compare a sender against. It has to be
+ // mirrored from the API's own `isSender`.
+ it('mirrors isSender, and reads an omitted field as inbound rather than undefined', () => {
+ const sent = normalizeMessageRow(
+ { id: 'msg-1', senderID: 'user-me', text: 'placeholder', isSender: true },
+ '2026-09-02T12:00:00.000Z',
+ );
+ const received = normalizeMessageRow(
+ { id: 'msg-2', senderID: 'user-1', text: 'placeholder' },
+ '2026-09-02T12:00:00.000Z',
+ );
+ expect(sent.isSender).toBe(true);
+ expect(received.isSender).toBe(false);
+ });
+
+ it('reads an edit off editedTimestamp and leaves unsentAt null', () => {
+ const row = normalizeMessageRow(
+ { id: 'msg-1', text: 'fixed', editedTimestamp: '2026-09-02T09:00:00.000Z', timestamp: '2026-09-01T00:00:00.000Z' },
+ '2026-09-02T12:00:00.000Z',
+ );
+ expect(row.editedAt).toBe('2026-09-02T09:00:00.000Z');
+ expect(row.unsentAt).toBeNull();
+ });
+
+ // Case-insensitivity (RFC 2045) means a bridge is free to send `Image/JPEG`
+ // or `IMAGE/jpeg` — the stored value has to be lowercased so it matches what
+ // `beeperAttachmentPaths.MIRRORED_MIME_TYPES` and the client's `isImage()`
+ // check both compare against.
+ it('lowercases a mixed-case declared mimeType before it is stored', () => {
+ const rows = normalizeAttachmentRows({
+ attachments: [{
+ type: 'img', id: 'mxc://example.invalid/mixed-case', mimeType: 'Image/JPEG', fileName: 'photo.jpg',
+ }],
+ });
+ expect(rows[0].mimeType).toBe('image/jpeg');
+ });
+
+ it('chatNeedsSweep keeps "never swept", "swept but silent" and "moved" apart', () => {
+ expect(chatNeedsSweep({ lastActivity: null }, undefined)).toBe(true);
+ expect(chatNeedsSweep({ lastActivity: null }, { lastActivity: null })).toBe(false);
+ expect(chatNeedsSweep({ lastActivity: '2026-09-02T00:00:00.000Z' }, { lastActivity: null })).toBe(true);
+ expect(chatNeedsSweep({ lastActivity: '2026-09-02T00:00:00.000Z' }, { lastActivity: '2026-09-01T00:00:00.000Z' })).toBe(true);
+ expect(chatNeedsSweep({ lastActivity: '2026-09-01T00:00:00.000Z' }, { lastActivity: '2026-09-01T00:00:00.000Z' })).toBe(false);
+ });
+ });
diff --cc server/services/beeperTribe.db.test.js
index 0000000000,b15a6bd6b5..c28f66a534
mode 000000,100644..100644
--- a/server/services/beeperTribe.db.test.js
+++ b/server/services/beeperTribe.db.test.js
@@@ -1,0 -1,577 +1,600 @@@
+ /**
+ * Postgres-backed tests for Beeper ↔ Tribe identity linking (#34), proving the
+ * issue's own Acceptance criteria against real constraints (FK cascade, the
+ * `tribe_identities` UNIQUE (kind, network, handle) index, the
+ * `(person_id, dedupe_key)` touchpoint dedupe) rather than mocked SQL:
+ *
+ * - A counterparty with a phone links to an existing Tribe person without
+ * creating a duplicate.
+ * - A counterparty with no durable identifier links by hand and survives a
+ * re-sync.
+ * - A group conversation creates touchpoints for senders only, and never
+ * for a truncated roster.
+ *
+ * Plus #96's own criterion, which needs a real cascade to prove: a hand-made
+ * link on a participant with NO durable handle survives a purge + resweep,
+ * because it is claimed in `tribe_identities` under `kind='beeper-user'`
+ * (account id + raw `source_user_id`) rather than only cached on the mirror row.
+ *
+ * `*.db.test.js` → runs ONLY via `npm run test:db` against `portos_test`
+ * (registered in vitest.config.db.js's DB_TEST_INCLUDE — a `<name>.db.test.js`
+ * file is not auto-globbed). Every fixture uses placeholder names/handles per
+ * root AGENTS.md Sensitive Data & Privacy — no real handle, name, or phone.
+ */
+ import { describe, it, expect, afterAll } from 'vitest';
+ import { checkHealth, ensureSchema, close, query } from '../lib/db.js';
+ import { requireDbOrSkip } from '../lib/dbTestGate.js';
+ import * as tribe from './tribe.js';
+ import * as tribeIdentities from './tribeIdentities.js';
+ import * as beeperTribe from './beeperTribe.js';
+
+ let dbReady = false;
+ let skipReason = '';
+ {
+ const health = await checkHealth().catch((e) => ({ connected: false, error: e?.message }));
+ if (!health.connected) {
+ skipReason = `Postgres not reachable (${health.error || 'no connection'})`;
+ } else {
+ await ensureSchema().catch(() => {});
+ dbReady = true;
+ }
+ }
+ const runDb = requireDbOrSkip('services/beeperTribe.db.test', dbReady, skipReason);
+
+ const nonce = `beepertribe-test-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
+ const ACCOUNT_ID = nonce;
+ const createdPersonIds = [];
+
+ afterAll(async () => {
+ if (dbReady) {
+ // Cascades through conversations/messages/participants/cursors.
+ await query('DELETE FROM beeper_accounts WHERE account_id = $1', [ACCOUNT_ID]).catch(() => {});
+ // tribe_identities cascades off tribe_people, but delete people explicitly
+ // to also clean up their touchpoints.
+ for (const id of createdPersonIds) {
+ // eslint-disable-next-line no-await-in-loop -- small fixed teardown list
+ await query('DELETE FROM tribe_people WHERE id = $1', [id]).catch(() => {});
+ }
+ await close();
+ }
+ });
+
+ async function makeAccount() {
+ await query(
+ `INSERT INTO beeper_accounts (account_id, network, display_name, status, bridge_id)
+ VALUES ($1, 'Example Network', 'Example Account', 'connected', 'example-bridge')
+ ON CONFLICT (account_id) DO NOTHING`,
+ [ACCOUNT_ID],
+ );
+ }
+
+ async function makeConversation(sourceChatId, { isGroup = false, network = 'whatsapp' } = {}) {
+ const { rows } = await query(
+ `INSERT INTO beeper_conversations (account_id, network, source_chat_id, title, type, is_group)
+ VALUES ($1, $2, $3, 'Example Chat', $4, $5)
+ RETURNING id`,
+ [ACCOUNT_ID, network, sourceChatId, isGroup ? 'group' : 'single', isGroup],
+ );
+ return rows[0].id;
+ }
+
+ async function makePerson(name) {
+ const person = await tribe.createPerson({ name });
+ createdPersonIds.push(person.id);
+ return person;
+ }
+
+ describe.skipIf(!runDb)('beeperTribe (#34)', () => {
+ it('a counterparty with a phone links to an existing Tribe person without creating a duplicate', async () => {
+ await makeAccount();
+ const conversationId = await makeConversation(`${nonce}-phone-chat`);
+ const personName = `${nonce} Example Phone Person`;
+
+ // Existing Tribe person already known via, say, iMessage/Contacts.
+ const person = await tribe.createPerson({ name: personName, phones: ['+15550100001'] });
+ createdPersonIds.push(person.id);
+
+ // Beeper hands us a participant whose `handle` is that same phone
+ // (User.phoneNumber), never having been linked through Beeper before.
+ const participant = await beeperTribe.upsertParticipant({
+ conversationId,
+ sourceUserId: 'wa-user-1',
+ displayName: personName,
+ handle: '+1 (555) 010-0001',
+ observedVia: 'message-sender',
+ });
+
+ // Auto-resolved on upsert — no manual link needed, and no new person made.
+ expect(participant.tribePersonId).toBe(person.id);
+ const peopleNamed = await query(
+ `SELECT COUNT(*)::int AS n FROM tribe_people WHERE name = $1`,
+ [personName],
+ );
+ expect(peopleNamed.rows[0].n).toBe(1);
+ });
+
+ it('a counterparty with no durable identifier links by hand and survives a re-sync', async () => {
+ await makeAccount();
+ const conversationId = await makeConversation(`${nonce}-nohandle-chat`);
+ const person = await makePerson('Example No-Handle Person');
+
+ // First sync: no phone, no username (the ~13% case — e.g. Facebook/Slack).
+ const first = await beeperTribe.upsertParticipant({
+ conversationId,
+ sourceUserId: 'fb-user-1',
+ displayName: 'Example No-Handle Person',
+ handle: '',
+ observedVia: 'message-sender',
+ });
+ expect(first.tribePersonId).toBeNull();
+
+ // The user links by hand.
+ const linked = await beeperTribe.linkParticipant({
+ conversationId, sourceUserId: 'fb-user-1', personId: person.id,
+ });
+ expect(linked.tribePersonId).toBe(person.id);
+
+ // A re-sync re-upserts the same participant row (same display name/handle,
+ // simulating the ingestion sweep re-observing this counterparty).
+ const resynced = await beeperTribe.upsertParticipant({
+ conversationId,
+ sourceUserId: 'fb-user-1',
+ displayName: 'Example No-Handle Person',
+ handle: '',
+ observedVia: 'message-sender',
+ });
+ expect(resynced.tribePersonId).toBe(person.id);
+ });
+
+ it('a durable USERNAME handle claims a tribe_identities row scoped to its OWN conversation network, and resolves a second participant presenting it', async () => {
+ await makeAccount();
+ // network comes from the conversation row, never from a caller argument
+ // (#34 review) — created here as 'discord' so the claim below is scoped
+ // to it.
+ const conversationId = await makeConversation(`${nonce}-handle-chat`, { network: 'discord' });
+ const person = await makePerson('Example Handle Person');
+
+ await beeperTribe.upsertParticipant({
+ conversationId,
+ sourceUserId: 'dc-user-1',
+ displayName: 'Example Handle Person',
+ handle: '@example_handle',
+ observedVia: 'message-sender',
+ });
+ const linked = await beeperTribe.linkParticipant({
+ conversationId, sourceUserId: 'dc-user-1', personId: person.id,
+ });
+ expect(linked.tribePersonId).toBe(person.id);
+ expect(linked.displacedPersonId).toBeNull();
+
+ const identities = await tribeIdentities.listIdentitiesForPerson(person.id);
+ expect(identities).toContainEqual(expect.objectContaining({
+ kind: 'handle', network: 'discord', handle: 'example_handle',
+ }));
+
+ // A second, DIFFERENT conversation's participant, ALSO on 'discord',
+ // presents the identical handle — it should auto-resolve to the same
+ // person without a manual link.
+ const otherConversationId = await makeConversation(`${nonce}-handle-chat-2`, { network: 'discord' });
+ const secondParticipant = await beeperTribe.upsertParticipant({
+ conversationId: otherConversationId,
+ sourceUserId: 'dc-user-1-again',
+ displayName: 'Example Handle Person',
+ handle: '@Example_Handle',
+ observedVia: 'message-sender',
+ });
+ expect(secondParticipant.tribePersonId).toBe(person.id);
+ });
+
+ it('scopes a username claim to its network — the SAME username on a DIFFERENT network never collides with a different person', async () => {
+ await makeAccount();
+ const discordPerson = await makePerson('Example Discord Namesake');
+ const slackPerson = await makePerson('Example Slack Namesake');
+
+ const discordConversationId = await makeConversation(`${nonce}-namesake-discord`, { network: 'discord' });
+ await beeperTribe.upsertParticipant({
+ conversationId: discordConversationId,
+ sourceUserId: 'discord-namesake-1',
+ displayName: 'Example Discord Namesake',
+ handle: '@example_namesake',
+ observedVia: 'message-sender',
+ });
+ await beeperTribe.linkParticipant({
+ conversationId: discordConversationId, sourceUserId: 'discord-namesake-1', personId: discordPerson.id,
+ });
+
+ const slackConversationId = await makeConversation(`${nonce}-namesake-slack`, { network: 'slack' });
+ const slackParticipant = await beeperTribe.upsertParticipant({
+ conversationId: slackConversationId,
+ sourceUserId: 'slack-namesake-1',
+ displayName: 'Example Slack Namesake',
+ handle: '@example_namesake',
+ observedVia: 'message-sender',
+ });
+ // Same literal handle, different network — must NOT auto-resolve to the
+ // Discord person; it must stay unlinked until claimed on its own network.
+ expect(slackParticipant.tribePersonId).toBeNull();
+
+ const linkedSlack = await beeperTribe.linkParticipant({
+ conversationId: slackConversationId, sourceUserId: 'slack-namesake-1', personId: slackPerson.id,
+ });
+ expect(linkedSlack.tribePersonId).toBe(slackPerson.id);
+ expect(linkedSlack.displacedPersonId).toBeNull();
+
+ const discordIdentities = await tribeIdentities.listIdentitiesForPerson(discordPerson.id);
+ expect(discordIdentities).toContainEqual(expect.objectContaining({
+ kind: 'handle', network: 'discord', handle: 'example_namesake',
+ }));
+ const slackIdentities = await tribeIdentities.listIdentitiesForPerson(slackPerson.id);
+ expect(slackIdentities).toContainEqual(expect.objectContaining({
+ kind: 'handle', network: 'slack', handle: 'example_namesake',
+ }));
+ });
+
+ it('enforces UNIQUE (kind, network, handle) semantics via linkIdentity re-link (moves ownership, no duplicate row, and reports the displaced person)', async () => {
+ const personA = await makePerson('Example Identity Owner A');
+ const personB = await makePerson('Example Identity Owner B');
+
+ const firstLink = await tribeIdentities.linkIdentity({ personId: personA.id, kind: 'handle', network: 'slack', handle: 'example-owner' });
+ expect(firstLink.displacedPersonId).toBeNull();
+ const relinked = await tribeIdentities.linkIdentity({ personId: personB.id, kind: 'handle', network: 'slack', handle: 'example-owner' });
+ expect(relinked.personId).toBe(personB.id);
+ expect(relinked.displacedPersonId).toBe(personA.id);
+
+ const { rows } = await query(
+ `SELECT COUNT(*)::int AS n FROM tribe_identities WHERE kind = 'handle' AND network = 'slack' AND handle = 'example-owner'`,
+ );
+ expect(rows[0].n).toBe(1);
+ });
+
+ it('refuses to write a kind=\'handle\' identity with no network (the inert-row hazard)', async () => {
+ const person = await makePerson('Example No-Network Person');
+ await expect(tribeIdentities.linkIdentity({
+ personId: person.id, kind: 'handle', network: '', handle: 'example-orphan',
+ })).rejects.toThrow();
+ });
+
+ it('refuses to link a soft-deleted person, and resolution/touchpoints treat them as unlinked', async () => {
+ await makeAccount();
+ const conversationId = await makeConversation(`${nonce}-deleted-chat`, { network: 'discord' });
+ const person = await makePerson('Example Deleted Person');
+
+ await beeperTribe.upsertParticipant({
+ conversationId,
+ sourceUserId: 'deleted-user-1',
+ displayName: 'Example Deleted Person',
+ handle: '@example_deleted',
+ observedVia: 'message-sender',
+ });
+ const linked = await beeperTribe.linkParticipant({
+ conversationId, sourceUserId: 'deleted-user-1', personId: person.id,
+ });
+ expect(linked.tribePersonId).toBe(person.id);
+
+ const deleted = await tribe.deletePerson(person.id);
+ expect(deleted).toBe(true);
+
+ // A further link attempt against the now-deleted person is refused, even
+ // though the FK alone would still permit it (soft delete only).
+ await expect(beeperTribe.linkParticipant({
+ conversationId, sourceUserId: 'deleted-user-1', personId: person.id,
+ })).rejects.toThrow();
+
+ // Resolution — both the cached column and a fresh tribe_identities lookup
+ // — no longer returns the deleted person.
+ expect(await beeperTribe.resolveParticipantPerson({ conversationId, sourceUserId: 'deleted-user-1' })).toBeNull();
+
+ const before = await tribe.listTouchpoints(person.id);
+ const result = await beeperTribe.logSenderTouchpoints([
+ { conversationId, senderId: 'deleted-user-1', sentAt: new Date().toISOString(), network: 'discord' },
+ ]);
+ expect(result.matched).toBe(0);
+ expect(result.created).toBe(0);
+ const after = await tribe.listTouchpoints(person.id);
+ expect(after).toHaveLength(before.length);
+ });
+
++ it('replaces a soft-deleted cached person on resync and preserves the replacement link', async () => {
++ await makeAccount();
++ const conversationId = await makeConversation(`${nonce}-replacement-chat`);
++ const phone = '+15550100077';
++ const original = await tribe.createPerson({ name: 'Example Original Person', phones: [phone] });
++ createdPersonIds.push(original.id);
++ const input = {
++ conversationId, sourceUserId: 'replacement-user', handle: phone,
++ displayName: 'Example Participant', observedVia: 'message-sender',
++ };
++ expect((await beeperTribe.upsertParticipant(input)).tribePersonId).toBe(original.id);
++ await tribe.deletePerson(original.id);
++
++ const replacement = await tribe.createPerson({ name: 'Example Replacement Person', phones: [phone] });
++ createdPersonIds.push(replacement.id);
++ expect((await beeperTribe.upsertParticipant(input)).tribePersonId).toBe(replacement.id);
++ expect((await beeperTribe.getParticipant(conversationId, input.sourceUserId)).tribePersonId).toBe(replacement.id);
++
++ const other = await makePerson('Example Other Person');
++ await tribeIdentities.linkIdentity({ personId: other.id, kind: 'phone', handle: phone });
++ expect((await beeperTribe.upsertParticipant(input)).tribePersonId).toBe(replacement.id);
++ });
++
+ it('lets an explicit tribe_identities claim outrank a STALE cached tribe_person_id', async () => {
+ await makeAccount();
+ const conversationId = await makeConversation(`${nonce}-stale-cache-chat`);
+ const cachedPerson = await makePerson('Example Stale Cache Person');
+ const claimingPerson = await makePerson('Example Claiming Person');
+
+ // The participant's cache is auto-filled from the LEGACY tribe_people
+ // phones[] axis onto the wrong person (the pre-#34 matching path).
+ await beeperTribe.upsertParticipant({
+ conversationId,
+ sourceUserId: 'stale-cache-user-1',
+ displayName: 'Example Stale Cache Person',
+ handle: '+1 (555) 010-0055',
+ observedVia: 'message-sender',
+ });
+ await query(
+ `UPDATE beeper_participants SET tribe_person_id = $3
+ WHERE conversation_id = $1 AND source_user_id = $2`,
+ [conversationId, 'stale-cache-user-1', cachedPerson.id],
+ );
+
+ // The user then explicitly claims that phone for somebody else.
+ await tribeIdentities.linkIdentity({
+ personId: claimingPerson.id, kind: 'phone', network: '', handle: '+15550100055',
+ });
+
+ // tribe_identities is the truth for a DURABLE handle — the cache column is
+ // authoritative only where no durable handle exists (#10), so the claim wins.
+ expect(await beeperTribe.resolveParticipantPerson({
+ conversationId, sourceUserId: 'stale-cache-user-1',
+ })).toBe(claimingPerson.id);
+ });
+
+ it('clears the displaced person\'s OTHER participant caches when linkParticipant moves a handle', async () => {
+ await makeAccount();
+ const firstConversationId = await makeConversation(`${nonce}-move-chat-1`, { network: 'discord' });
+ const secondConversationId = await makeConversation(`${nonce}-move-chat-2`, { network: 'discord' });
+ const originalOwner = await makePerson('Example Original Owner');
+ const newOwner = await makePerson('Example New Owner');
+
+ await beeperTribe.upsertParticipant({
+ conversationId: firstConversationId,
+ sourceUserId: 'move-user-1',
+ displayName: 'Example Original Owner',
+ handle: '@example_moved',
+ observedVia: 'message-sender',
+ });
+ await beeperTribe.linkParticipant({
+ conversationId: firstConversationId, sourceUserId: 'move-user-1', personId: originalOwner.id,
+ });
+
+ // A second conversation's participant presents the same handle and
+ // auto-resolves (and caches) onto the original owner.
+ const second = await beeperTribe.upsertParticipant({
+ conversationId: secondConversationId,
+ sourceUserId: 'move-user-2',
+ displayName: 'Example Original Owner',
+ handle: '@Example_Moved',
+ observedVia: 'message-sender',
+ });
+ expect(second.tribePersonId).toBe(originalOwner.id);
+
+ // The user re-links the handle to someone else — an ownership move.
+ const moved = await beeperTribe.linkParticipant({
+ conversationId: firstConversationId, sourceUserId: 'move-user-1', personId: newOwner.id,
+ });
+ expect(moved.displacedPersonId).toBe(originalOwner.id);
+
+ // The OTHER conversation's stale cache is cleared and now resolves to the
+ // new owner instead of permanently attributing messages to the displaced one.
+ const refreshed = await beeperTribe.getParticipant(secondConversationId, 'move-user-2');
+ expect(refreshed.tribePersonId).toBeNull();
+ expect(await beeperTribe.resolveParticipantPerson({
+ conversationId: secondConversationId, sourceUserId: 'move-user-2',
+ })).toBe(newOwner.id);
+ });
+
+ it('links a username-bearing participant on a network-less conversation by cache alone, instead of failing', async () => {
+ await makeAccount();
+ // beeper_conversations.network is NOT NULL DEFAULT '' — a conversation can
+ // legitimately arrive with no network, and such a participant must not
+ // become wholly unlinkable (#34 review).
+ const conversationId = await makeConversation(`${nonce}-no-network-chat`, { network: '' });
+ const person = await makePerson('Example No-Network Handle Person');
+
+ await beeperTribe.upsertParticipant({
+ conversationId,
+ sourceUserId: 'no-network-user-1',
+ displayName: 'Example No-Network Handle Person',
+ handle: '@example_no_network',
+ observedVia: 'message-sender',
+ });
+ const linked = await beeperTribe.linkParticipant({
+ conversationId, sourceUserId: 'no-network-user-1', personId: person.id,
+ });
+ expect(linked.tribePersonId).toBe(person.id);
+
+ // No inert unscoped kind='handle' row was written — the network the
+ // username would need is exactly what this conversation lacks. The
+ // account-scoped beeper-user claim (#96) is unaffected by that: a
+ // conversation always has an account, so this link is durable anyway.
+ const identities = await tribeIdentities.listIdentitiesForPerson(person.id);
+ expect(identities).toEqual([expect.objectContaining({
+ kind: 'beeper-user', network: ACCOUNT_ID, handle: 'no-network-user-1',
+ })]);
+ });
+
+ it('does not wipe a durable handle when a later sweep re-observes the participant without one', async () => {
+ await makeAccount();
+ const conversationId = await makeConversation(`${nonce}-handle-keep-chat`, { network: 'discord' });
+
+ await beeperTribe.upsertParticipant({
+ conversationId,
+ sourceUserId: 'handle-keep-user-1',
+ displayName: 'Example Handle Keeper',
+ handle: '@example_keeper',
+ observedVia: 'message-sender',
+ });
+ // A truncated participant-list observation carries no phone/username.
+ const resynced = await beeperTribe.upsertParticipant({
+ conversationId,
+ sourceUserId: 'handle-keep-user-1',
+ displayName: 'Example Handle Keeper',
+ handle: '',
+ observedVia: 'participant-list',
+ });
+ expect(resynced.handle).toBe('@example_keeper');
+ });
+
+ // ── #96: a manual link survives a purge + resweep ────────────────────────
+ // The purge is the real one (`DELETE FROM beeper_conversations`), so the
+ // participant row and its `tribe_person_id` cache genuinely cascade away;
+ // the resweep is modelled by re-creating the conversation under a NEW
+ // PortOS UUID (a purge drops the sync cursor, so a resweep never matches
+ // the old row) with the SAME account and source_user_id.
+ it('re-links a hand-linked handle-less participant after a purge + resweep, on the first re-observation', async () => {
+ await makeAccount();
+ const conversationId = await makeConversation(`${nonce}-purge-chat`, { network: 'facebook' });
+ const person = await makePerson('Example Purged Person');
+
+ await beeperTribe.upsertParticipant({
+ conversationId,
+ sourceUserId: 'fb-purge-user-1',
+ displayName: 'Example Purged Person',
+ handle: '',
+ observedVia: 'message-sender',
+ });
+ const linked = await beeperTribe.linkParticipant({
+ conversationId, sourceUserId: 'fb-purge-user-1', personId: person.id,
+ });
+ expect(linked.tribePersonId).toBe(person.id);
+
+ // The durable half of that link — no handle classified, so this is the
+ // ONLY record of it that can outlive the row.
+ const identities = await tribeIdentities.listIdentitiesForPerson(person.id);
+ expect(identities).toContainEqual(expect.objectContaining({
+ kind: 'beeper-user', network: ACCOUNT_ID, handle: 'fb-purge-user-1',
+ }));
+
+ await query('DELETE FROM beeper_conversations WHERE id = $1', [conversationId]);
+ const gone = await query(
+ 'SELECT COUNT(*)::int AS n FROM beeper_participants WHERE conversation_id = $1',
+ [conversationId],
+ );
+ expect(gone.rows[0].n).toBe(0);
+
+ const resweptConversationId = await makeConversation(`${nonce}-purge-chat-reswept`, { network: 'facebook' });
+ expect(resweptConversationId).not.toBe(conversationId);
+ const reswept = await beeperTribe.upsertParticipant({
+ conversationId: resweptConversationId,
+ sourceUserId: 'fb-purge-user-1',
+ displayName: 'Example Purged Person',
+ handle: '',
+ observedVia: 'message-sender',
+ });
+ expect(reswept.tribePersonId).toBe(person.id);
+ });
+
+ it('is a no-op when a hand-linked participant is re-linked to the SAME person', async () => {
+ await makeAccount();
+ const conversationId = await makeConversation(`${nonce}-relink-same-chat`, { network: 'facebook' });
+ const person = await makePerson('Example Relink Same Person');
+
+ await beeperTribe.upsertParticipant({
+ conversationId, sourceUserId: 'fb-relink-user-1', displayName: 'Example Relink Same Person', handle: '', observedVia: 'message-sender',
+ });
+ await beeperTribe.linkParticipant({
+ conversationId, sourceUserId: 'fb-relink-user-1', personId: person.id,
+ });
+ const again = await beeperTribe.linkParticipant({
+ conversationId, sourceUserId: 'fb-relink-user-1', personId: person.id,
+ });
+ expect(again.tribePersonId).toBe(person.id);
+ expect(again.displacedPersonId).toBeNull();
+
+ // No duplicate claim — UNIQUE (kind, network, handle) upserted in place.
+ const { rows } = await query(
+ `SELECT COUNT(*)::int AS n FROM tribe_identities
+ WHERE kind = 'beeper-user' AND network = $1 AND handle = 'fb-relink-user-1'`,
+ [ACCOUNT_ID],
+ );
+ expect(rows[0].n).toBe(1);
+ });
+
+ it('moves the beeper-user claim and clears the displaced caches when the same participant is re-linked to somebody else', async () => {
+ await makeAccount();
+ const firstConversationId = await makeConversation(`${nonce}-relink-move-1`, { network: 'facebook' });
+ const secondConversationId = await makeConversation(`${nonce}-relink-move-2`, { network: 'facebook' });
+ const originalOwner = await makePerson('Example Beeper-User Original Owner');
+ const newOwner = await makePerson('Example Beeper-User New Owner');
+
+ await beeperTribe.upsertParticipant({
+ conversationId: firstConversationId, sourceUserId: 'fb-move-user-1', displayName: 'Example Beeper-User Original Owner', handle: '', observedVia: 'message-sender',
+ });
+ await beeperTribe.linkParticipant({
+ conversationId: firstConversationId, sourceUserId: 'fb-move-user-1', personId: originalOwner.id,
+ });
+
+ // The SAME Beeper user in a second chat on the same account auto-resolves
+ // through the claim alone — there is no handle to match on.
+ const second = await beeperTribe.upsertParticipant({
+ conversationId: secondConversationId, sourceUserId: 'fb-move-user-1', displayName: 'Example Beeper-User Original Owner', handle: '', observedVia: 'message-sender',
+ });
+ expect(second.tribePersonId).toBe(originalOwner.id);
+
+ const moved = await beeperTribe.linkParticipant({
+ conversationId: firstConversationId, sourceUserId: 'fb-move-user-1', personId: newOwner.id,
+ });
+ expect(moved.displacedPersonId).toBe(originalOwner.id);
+
+ const refreshed = await beeperTribe.getParticipant(secondConversationId, 'fb-move-user-1');
+ expect(refreshed.tribePersonId).toBeNull();
+ expect(await beeperTribe.resolveParticipantPerson({
+ conversationId: secondConversationId, sourceUserId: 'fb-move-user-1',
+ })).toBe(newOwner.id);
+
+ const originalIdentities = await tribeIdentities.listIdentitiesForPerson(originalOwner.id);
+ expect(originalIdentities).toHaveLength(0);
+ });
+
+ it('a group conversation creates touchpoints for senders only, never for a truncated roster', async () => {
+ await makeAccount();
+ const conversationId = await makeConversation(`${nonce}-group-chat`, { isGroup: true });
+
+ const sender = await makePerson('Example Group Sender');
+ const rosterOnly = await makePerson('Example Roster-Only Person');
+
+ // The sender messaged and is linked.
+ await beeperTribe.upsertParticipant({
+ conversationId, sourceUserId: 'group-sender-1', displayName: 'Example Group Sender', handle: '', observedVia: 'message-sender',
+ });
+ await beeperTribe.linkParticipant({ conversationId, sourceUserId: 'group-sender-1', personId: sender.id });
+
+ // A second person is on the (truncated) participant roster but NEVER sent
+ // a message in this batch — logSenderTouchpoints must never touch them,
+ // because it never enumerates beeper_participants at all.
+ await beeperTribe.upsertParticipant({
+ conversationId, sourceUserId: 'group-roster-only-1', displayName: 'Example Roster-Only Person', handle: '', observedVia: 'participant-list',
+ });
+ await beeperTribe.linkParticipant({ conversationId, sourceUserId: 'group-roster-only-1', personId: rosterOnly.id });
+
+ const before = await tribe.listTouchpoints(rosterOnly.id);
+ expect(before).toHaveLength(0);
+
+ const result = await beeperTribe.logSenderTouchpoints([
+ { conversationId, senderId: 'group-sender-1', sentAt: new Date().toISOString(), network: 'whatsapp' },
+ { conversationId, senderId: 'group-sender-1', sentAt: new Date().toISOString(), network: 'whatsapp' }, // same sender, same day — dedupes
+ ]);
+ expect(result.created).toBe(1);
+ expect(result.matched).toBe(2);
+
+ const senderTouchpoints = await tribe.listTouchpoints(sender.id);
+ expect(senderTouchpoints).toHaveLength(1);
+ expect(senderTouchpoints[0].source).toBe('message');
+
+ // The roster-only person, despite being linked and present in
+ // beeper_participants, never sent a message — no touchpoint for them.
+ const after = await tribe.listTouchpoints(rosterOnly.id);
+ expect(after).toHaveLength(0);
+ });
+ });
diff --cc server/services/beeperTribe.js
index 0000000000,33f969ea33..65384e5aaa
mode 000000,100644..100644
--- a/server/services/beeperTribe.js
+++ b/server/services/beeperTribe.js
@@@ -1,0 -1,730 +1,741 @@@
+ /**
+ * Beeper ↔ Tribe identity linking (#34, decided on #10, built on the schema
+ * from #27/PR42). Relates a `beeper_participants` row to a `tribe_people`
+ * row via the split-by-durability design:
+ *
+ * - A durable handle (a phone, ~81% of one-to-one counterparties, or a
+ * network username, ~6%) resolves through `tribe_identities` — see
+ * `server/services/tribeIdentities.js` — PLUS, for a phone specifically,
+ * the existing Tribe phone matcher (`tribeMatch.js`/`tribe.listPeople()`),
+ * since a WhatsApp/Signal/Google-Messages phone is very plausibly already
+ * on a Tribe person from calendar/iMessage/Contacts. Resolution never
+ * creates a person — only matches an existing one — so the auto path can
+ * never produce a duplicate.
+ * - No durable handle at all (~13%) has nothing HANDLE-shaped to resolve
+ * against, so every EXPLICIT link (`linkParticipant` /
+ * `createPersonAndLinkParticipant`) also claims a `kind='beeper-user'`
+ * identity keyed on the participant's own account and Beeper user id (see
+ * `beeperUserScopeFor`), and `beeper_participants.tribe_person_id` drops
+ * to being a pure cache for that case too.
+ *
+ * `kind='beeper-user'` OVERLOADS the existing `UNIQUE (kind, network, handle)`
+ * index rather than adding a column (#96): `network` carries the participant's
+ * `beeper_conversations.account_id` and `handle` carries its raw
+ * `source_user_id`. That pair is Beeper's own per-account `User.id`, stable
+ * across resweeps, where the mirror's `conversation_id` is a PortOS UUID
+ * re-minted by every purge — so the claim survives a purge + resweep by
+ * construction (`tribe_identities` has no FK onto anything Beeper-side).
+ * The ACCOUNT, not the network, is the scope: two bridge accounts on the same
+ * network mint their own independent user-id space. The overload is documented
+ * on the table itself in `server/lib/db/schema/tribe.js`; a `source_user_id`
+ * is an opaque id, so it is stored RAW and never routed through
+ * `classifyNetworkHandle` (which exists for phones/usernames only).
+ *
+ * `upsertParticipant` is the participant-row writer the ingestion sweep (#32)
+ * calls on every sync pass — its ON CONFLICT clause deliberately never
+ * touches `tribe_person_id`, so a manual link on the 13%-no-handle case
+ * survives every re-sync (#34 acceptance); its post-insert auto-resolve is
+ * what re-fills the cache from the `beeper-user` claim after a purge (#96).
+ *
+ * Touchpoints: `logSenderTouchpoints` relates a GROUP conversation by message
+ * SENDER only — Beeper's participant roster truncates (20/100, no cursor) so
+ * it is never a complete membership list; iterating it to log touchpoints for
+ * everyone "in" a group would silently invent contact with people who never
+ * actually messaged. A message's `senderID` is always a real, present
+ * participant, so deriving touchpoints from messages (never from the roster)
+ * is correct for a 1:1 chat too, not just a group.
+ */
+ import { ensureSchema, query } from '../lib/db.js';
+ import { ServerError } from '../lib/errorHandler.js';
+ import {
+ classifyNetworkHandle, buildPersonMatchIndex, matchPerson, resolveLinkedPersonId,
+ } from '../lib/tribeMatch.js';
+ import * as tribe from './tribe.js';
+ import * as tribeIdentities from './tribeIdentities.js';
+
-async function ensureReady() {
- await ensureSchema();
++let schemaReady;
++function ensureReady() {
++ schemaReady ??= ensureSchema().catch((error) => {
++ schemaReady = null;
++ throw error;
++ });
++ return schemaReady;
+ }
+
+ function rowToParticipant(row) {
+ if (!row) return null;
+ return {
+ conversationId: row.conversation_id,
+ sourceUserId: row.source_user_id,
+ displayName: row.display_name || '',
+ handle: row.handle || '',
+ // Deliberately NULLed when the cached link points at a soft-deleted Tribe
+ // person (`tp.deleted`, joined below) — `tribe.deletePerson` never fires
+ // the FK's ON DELETE CASCADE (it's a soft delete), so the raw column can
+ // point at a person who no longer counts as one. Callers (below, and
+ // upsertParticipant's "still empty" check) then correctly treat this
+ // participant as unlinked rather than resolving onto a deleted person.
+ // `resolveLinkedPersonId` (`lib/tribeMatch.js`) is the SAME predicate
+ // `beeperConversations.js`'s conversation/list shaper applies to this same
+ // column, so the two cannot drift onto different answers again.
+ tribePersonId: resolveLinkedPersonId(row.tribe_person_id, row.tribe_person_deleted),
+ // The Beeper NETWORK this participant's conversation belongs to — joined
+ // from beeper_conversations.network, never client-supplied (#34 review:
+ // a caller-supplied network let a username-shaped handle be linked under
+ // the wrong scope, or with none at all). Authoritative scope for a
+ // kind='handle' tribe_identities claim.
+ network: row.network || '',
+ // The Beeper ACCOUNT this participant's conversation belongs to, joined
+ // from beeper_conversations.account_id — likewise never client-supplied.
+ // Authoritative scope for the kind='beeper-user' claim (#96): a
+ // `source_user_id` is only unique within one bridge account, and the
+ // account survives a purge + resweep where the conversation id does not.
+ accountId: row.account_id || '',
+ observedVia: row.observed_via,
+ createdAt: row.created_at?.toISOString?.() ?? row.created_at,
+ updatedAt: row.updated_at?.toISOString?.() ?? row.updated_at,
+ };
+ }
+
+ export async function getParticipant(conversationId, sourceUserId) {
+ await ensureReady();
+ const result = await query(
+ `SELECT p.*, c.network, c.account_id, tp.deleted AS tribe_person_deleted
+ FROM beeper_participants p
+ JOIN beeper_conversations c ON c.id = p.conversation_id
+ LEFT JOIN tribe_people tp ON tp.id = p.tribe_person_id
+ WHERE p.conversation_id = $1 AND p.source_user_id = $2`,
+ [conversationId, sourceUserId],
+ );
+ return rowToParticipant(result.rows[0]);
+ }
+
+ /**
+ * The `tribe_identities` scope a participant's handle claims, or `null` when
+ * the handle is absent/unclassifiable or (for a username) its conversation
+ * carries no network — a `kind='handle'` row is meaningless without one, and
+ * `tribeIdentities` refuses to write or resolve it. Shared by
+ * `resolveParticipantPerson` and `linkParticipant` so the read and the write
+ * agree on exactly which participants have a DURABLE identity.
+ */
+ function identityScopeFor(participant) {
+ if (!participant?.handle) return null;
+ const classified = classifyNetworkHandle(participant.handle);
+ if (!classified) return null;
+ const network = classified.kind === 'phone' ? '' : (participant.network || '');
+ if (classified.kind === 'handle' && !network) return null;
+ return { kind: classified.kind, network, handle: classified.handle };
+ }
+
+ /** The `tribe_identities` kind that carries a Beeper `User.id` claim (#96). */
+ export const BEEPER_USER_KIND = 'beeper-user';
+
+ /**
+ * The `tribe_identities` scope a participant's BEEPER USER ID claims — the
+ * durable key every participant has, handle or not (#96). Overloads the
+ * existing `UNIQUE (kind, network, handle)` index: `network` is the
+ * participant's own `beeper_conversations.account_id` and `handle` is its raw
+ * `source_user_id` (an opaque id — never normalized, never classified).
+ *
+ * Keyed on the ACCOUNT rather than the network because a `source_user_id` is
+ * only unique within one bridge account, and joined server-side from the
+ * participant's own conversation, never caller-supplied — the same rule
+ * `identityScopeFor` follows for `network`. Returns `null` when either half is
+ * missing (an account-less conversation cannot exist through the FK, but an
+ * unscoped claim is the inert-row hazard `linkIdentity` refuses, so this
+ * never manufactures one). Shared by `resolveParticipantPerson` and
+ * `linkParticipant` so the read and the write agree on the key.
+ */
+ function beeperUserScopeFor(participant) {
+ const network = participant?.accountId || '';
+ const handle = participant?.sourceUserId || '';
+ if (!network || !handle) return null;
+ return { kind: BEEPER_USER_KIND, network, handle };
+ }
+
+ /**
+ * Resolve a participant to a Tribe person WITHOUT writing anything. Never
+ * creates a person.
+ *
+ * Order — CLASSIFY FIRST, and let a durable handle's `tribe_identities` claim
+ * outrank the cache column (#34 review): `beeper_participants.tribe_person_id`
+ * is a CACHE, authoritative **only** where no durable handle exists (the ~13%
+ * with neither a phone nor a username). Reading it first made it authoritative
+ * for 100% and froze the truth table out of every already-cached row — a cache
+ * auto-filled from the legacy `tribe_people.phones[]` axis would permanently
+ * outrank a later explicit claim on the same phone, and after `linkParticipant`
+ * moves ownership of a handle, every OTHER participant row carrying it would
+ * keep resolving to the displaced person. So:
+ *
+ * 1. `tribe_identities` — the user's OWN explicit Beeper link, the truth for
+ * any handle that classifies into a resolvable scope.
+ * 2. the `kind='beeper-user'` claim on this participant's own
+ * (account, `source_user_id`) — the same explicit link recorded durably
+ * for a participant with NO classifiable handle (#96). Below the handle
+ * claim because a handle can be re-pointed at a different person on its
+ * own axis, and above the cache for the same reason the handle claim is:
+ * the claim is the record of an explicit user action, the column is a
+ * cache that a purge deletes and a resweep re-mints empty.
+ * 3. the cache column — still the next-best answer for a durable handle
+ * nobody has claimed yet, and for a row auto-resolved but never claimed
+ * (it is a manual link, so it outranks the legacy array below). Null'd
+ * when it points at a soft-deleted person — see `rowToParticipant`.
+ * 4. for a phone specifically, the existing Tribe phone matcher — a
+ * WhatsApp/Signal counterpart's phone is plausibly already on a Tribe
+ * person from iMessage/Contacts with no Beeper claim recorded yet.
+ *
+ * Returns `null` when nothing matches.
+ *
+ * `personIndex` is an optional pre-built `buildPersonMatchIndex(...)` result
+ * — pass one when resolving many participants in a batch (`logSenderTouchpoints`
+ * below) so the phone fallback doesn't reload and reindex every Tribe person
+ * once per participant.
+ */
+ export async function resolveParticipantPerson({ conversationId, sourceUserId }, personIndex = null) {
+ const participant = await getParticipant(conversationId, sourceUserId);
+ if (!participant) return null;
+
+ const scope = identityScopeFor(participant);
+ if (scope) {
+ const via = await tribeIdentities.resolvePersonByIdentity(scope);
+ if (via) return via;
+ }
+
+ const beeperUserScope = beeperUserScopeFor(participant);
+ if (beeperUserScope) {
+ const viaBeeperUser = await tribeIdentities.resolvePersonByIdentity(beeperUserScope);
+ if (viaBeeperUser) return viaBeeperUser;
+ }
+
+ if (participant.tribePersonId) return participant.tribePersonId;
+
+ if (scope?.kind === 'phone') {
+ const index = personIndex || buildPersonMatchIndex(await tribe.listPeople());
+ const viaTribePhone = matchPerson({ phone: scope.handle }, index);
+ if (viaTribePhone) return viaTribePhone;
+ }
+
+ return null;
+ }
+
+ /**
+ * Load and index the Tribe roster ONCE, for a caller (a sweep pass in
+ * `beeperSync.js`) about to resolve MANY participants and wants to hand the
+ * same `personIndex` to every `upsertParticipant` call rather than let each
+ * one reload and reindex every Tribe person for itself. Mirrors the batching
+ * `logSenderTouchpoints` already does internally for its own candidate list.
+ */
+ export async function loadRosterIndex() {
+ return buildPersonMatchIndex(await tribe.listPeople());
+ }
+
+ /**
+ * Insert-or-refresh a participant row. The `ON CONFLICT` update list
+ * deliberately EXCLUDES `tribe_person_id` — a re-sync must never clobber a
+ * manual link (#34 acceptance: "a counterparty with no durable identifier
+ * links by hand and survives a re-sync"). After the write, opportunistically
+ * auto-resolves and fills the cache ONLY when it is still empty — never
+ * overrides an existing link, manual or previously auto-resolved.
+ *
+ * `handle` is COALESCE-guarded rather than overwritten (#34 review): a later
+ * sweep that observes the same counterparty WITHOUT a handle (Beeper omits
+ * `phoneNumber`/`username` on a truncated roster entry, and a participant-list
+ * observation carries less than a message-sender one) must not wipe a durable
+ * handle — that handle IS the `tribe_identities` axis, so erasing it would
+ * silently demote the participant to the no-durable-identifier case and strand
+ * the identity claim. A genuinely new, non-empty handle still replaces it.
+ *
+ * `personIndex` is the SAME optional pre-built `buildPersonMatchIndex(...)`
+ * result `resolveParticipantPerson` and `logSenderTouchpoints` accept — pass
+ * one (via `loadRosterIndex` below) when a caller will call this once per
+ * participant in a sweep pass, so the phone fallback doesn't reload and
+ * reindex the whole Tribe roster on every single participant. `null` falls
+ * back to `resolveParticipantPerson`'s own per-call load, unchanged.
+ */
+ export async function upsertParticipant({
+ conversationId, sourceUserId, displayName = '', handle = '', observedVia, personIndex = null,
+ }) {
+ if (!conversationId || !sourceUserId) {
+ throw new ServerError('conversationId and sourceUserId are required', { status: 400, code: 'BAD_REQUEST' });
+ }
+ if (observedVia !== 'participant-list' && observedVia !== 'message-sender') {
+ throw new ServerError("observedVia must be 'participant-list' or 'message-sender'", { status: 400, code: 'BAD_REQUEST' });
+ }
+ await ensureReady();
+ await query(
+ `INSERT INTO beeper_participants (conversation_id, source_user_id, display_name, handle, observed_via)
+ VALUES ($1, $2, $3, $4, $5)
+ ON CONFLICT (conversation_id, source_user_id)
+ DO UPDATE SET display_name = EXCLUDED.display_name,
+ handle = COALESCE(NULLIF(EXCLUDED.handle, ''), beeper_participants.handle),
+ observed_via = EXCLUDED.observed_via, updated_at = NOW()`,
+ [conversationId, sourceUserId, displayName, handle, observedVia],
+ ).catch((err) => {
+ if (err?.code === '23503') throw new ServerError('Conversation not found', { status: 404 });
+ throw err;
+ });
+
+ const participant = await getParticipant(conversationId, sourceUserId);
+ // Gated on the cache being empty ONLY (#96). It used to also require the
+ // row's own handle, on the reasoning that a handle-less participant had
+ // nothing to resolve against — true until the `kind='beeper-user'` claim
+ // existed, and the reason a hand-linked Messenger participant came back
+ // unlinked after a purge + resweep: the resweep re-minted the row with a
+ // NULL cache and the auto-resolve that would have re-filled it never ran.
+ // The extra cost for a genuinely unclaimed handle-less participant is one
+ // indexed `tribe_identities` lookup; the phone matcher (the expensive leg)
+ // still only runs for a phone-shaped handle.
++ // A soft-deleted owner is unlinked in the read model even while its raw FK
++ // remains. Apply the same rule to the write, preserving only live links.
+ if (!participant.tribePersonId) {
+ const resolved = await resolveParticipantPerson({ conversationId, sourceUserId }, personIndex);
+ if (resolved) {
+ await query(
+ `UPDATE beeper_participants SET tribe_person_id = $3, updated_at = NOW()
- WHERE conversation_id = $1 AND source_user_id = $2 AND tribe_person_id IS NULL`,
++ WHERE conversation_id = $1 AND source_user_id = $2
++ AND (tribe_person_id IS NULL OR EXISTS (
++ SELECT 1 FROM tribe_people tp
++ WHERE tp.id = beeper_participants.tribe_person_id AND tp.deleted = TRUE
++ ))`,
+ [conversationId, sourceUserId, resolved],
+ );
+ return getParticipant(conversationId, sourceUserId);
+ }
+ }
+ return participant;
+ }
+
+ /**
+ * After `tribeIdentities.linkIdentity` MOVES a durable identity from one
+ * person to another, null the now-stale `beeper_participants.tribe_person_id`
+ * cache on every OTHER row that presents the same identity and still points
+ * at the displaced person (#34 review). Without this the displaced person
+ * keeps owning those rows: the read path no longer resolves through them
+ * (`resolveParticipantPerson` consults `tribe_identities` first), but the
+ * column is what a participant listing renders and what the "still empty"
+ * gate in `upsertParticipant` reads, so a stale cache would show — and
+ * re-assert — the wrong person with no unlink UI to correct it.
+ *
+ * Candidates are filtered in JS rather than SQL because the stored `handle`
+ * is RAW (`+1 (555) 010-0001`, `@Example_Handle`) while the identity is
+ * normalized; `classifyNetworkHandle` is the only correct comparator, and the
+ * candidate set is just the displaced person's own linked rows.
+ */
+ async function clearDisplacedParticipantCaches(displacedPersonId, scope) {
+ const { rows } = await query(
+ `SELECT p.conversation_id, p.source_user_id, p.handle, c.network
+ FROM beeper_participants p
+ JOIN beeper_conversations c ON c.id = p.conversation_id
+ WHERE p.tribe_person_id = $1 AND p.handle <> ''`,
+ [displacedPersonId],
+ );
+ const stale = rows.filter((row) => {
+ const rowScope = identityScopeFor({ handle: row.handle, network: row.network || '' });
+ return rowScope
+ && rowScope.kind === scope.kind
+ && rowScope.network === scope.network
+ && rowScope.handle === scope.handle;
+ });
+ for (const row of stale) {
+ // eslint-disable-next-line no-await-in-loop -- one displaced person's own rows carrying one handle; a handful at most
+ await query(
+ `UPDATE beeper_participants SET tribe_person_id = NULL, updated_at = NOW()
+ WHERE conversation_id = $1 AND source_user_id = $2 AND tribe_person_id = $3`,
+ [row.conversation_id, row.source_user_id, displacedPersonId],
+ );
+ }
+ return stale.length;
+ }
+
+ /**
+ * The `kind='beeper-user'` counterpart of `clearDisplacedParticipantCaches`
+ * (#96): after a re-link MOVES a (account, `source_user_id`) claim to another
+ * person, null the now-stale cache on every OTHER conversation's row for the
+ * SAME Beeper user under the SAME account that still points at the displaced
+ * person. Same rationale as the handle version — the read path stops
+ * resolving through those rows, but the column is what a participant listing
+ * renders and what `upsertParticipant`'s "still empty" gate reads.
+ *
+ * One statement rather than the handle version's filter-in-JS pass: the match
+ * here is an exact column comparison (a `source_user_id` is opaque and stored
+ * raw), so no normalizing comparator is needed.
+ */
+ async function clearDisplacedBeeperUserCaches(displacedPersonId, scope) {
+ const result = await query(
+ `UPDATE beeper_participants p SET tribe_person_id = NULL, updated_at = NOW()
+ FROM beeper_conversations c
+ WHERE c.id = p.conversation_id
+ AND p.tribe_person_id = $1 AND c.account_id = $2 AND p.source_user_id = $3`,
+ [displacedPersonId, scope.network, scope.handle],
+ );
+ return result.rowCount ?? 0;
+ }
+
+ /**
+ * Explicit link — the inline thread-participant action (#10 decision 4).
+ * ALWAYS claims a `kind='beeper-user'` identity on the participant's own
+ * (account, `source_user_id`) so the link survives a purge + resweep (#96),
+ * and when the participant carries a durable handle ALSO claims that in
+ * `tribe_identities` so the next participant (in this or another
+ * conversation) presenting the same handle auto-resolves without another
+ * manual click. `network` is never accepted as an argument — a `kind='handle'`
+ * claim is scoped to the participant's OWN conversation's
+ * `beeper_conversations.network`, joined server-side by `getParticipant`,
+ * never a caller-supplied value (#34 review — a client-supplied network let a
+ * handle be linked under the wrong scope, or with none at all).
+ *
+ * Refuses to link a soft-deleted `personId` (`tribeIdentities.assertPersonLinkable`)
+ * BEFORE the handle branch, so the no-durable-handle case — where
+ * `linkIdentity` is never called — is covered too. Returns
+ * `{ ...participant, displacedPersonId }`: when the handle was already
+ * claimed by a DIFFERENT person, that person's id, so the ownership move
+ * (silent at the DB/audit-trigger level — see `tribeIdentities.linkIdentity`)
+ * is surfaced to the caller instead.
+ *
+ * A username-bearing participant whose conversation carries NO network
+ * (`beeper_conversations.network` is `NOT NULL DEFAULT ''`) falls through to
+ * the cache-only write rather than throwing (#34 review): `linkIdentity`
+ * rightly refuses an unscoped `kind='handle'` row, but propagating that 400
+ * made such a participant WHOLLY unlinkable, when the no-durable-handle path
+ * handles the very same situation fine by writing only the cache. Nothing
+ * durable can be recorded, so the cache is the truth here — exactly the role
+ * `resolveParticipantPerson` reserves for it.
+ */
+ export async function linkParticipant({
+ conversationId, sourceUserId, personId, source = 'user',
+ }) {
+ if (!personId) throw new ServerError('personId is required', { status: 400, code: 'BAD_REQUEST' });
+ await ensureReady();
+ await tribeIdentities.assertPersonLinkable(personId);
+ const participant = await getParticipant(conversationId, sourceUserId);
+ if (!participant) throw new ServerError('Participant not found', { status: 404 });
+
+ let displacedPersonId = null;
+ const scope = identityScopeFor(participant);
+ if (scope) {
+ const identity = await tribeIdentities.linkIdentity({ personId, ...scope, source });
+ displacedPersonId = identity.displacedPersonId;
+ if (displacedPersonId) await clearDisplacedParticipantCaches(displacedPersonId, scope);
+ }
+
+ // ALWAYS claim the beeper-user identity too (#96) — this is the half that
+ // makes a manual link durable for a participant with no classifiable
+ // handle, and it costs nothing for one that has both. Idempotent: re-linking
+ // the same participant to the same person re-writes the same row and
+ // displaces nobody. A handle-claim displacement is reported in preference to
+ // this one when the two disagree, because the handle axis is the one a
+ // second participant elsewhere can also present.
+ const beeperUserScope = beeperUserScopeFor(participant);
+ if (beeperUserScope) {
+ const identity = await tribeIdentities.linkIdentity({ personId, ...beeperUserScope, source });
+ if (identity.displacedPersonId) {
+ await clearDisplacedBeeperUserCaches(identity.displacedPersonId, beeperUserScope);
+ displacedPersonId = displacedPersonId || identity.displacedPersonId;
+ }
+ }
+
+ const result = await query(
+ `UPDATE beeper_participants SET tribe_person_id = $3, updated_at = NOW()
+ WHERE conversation_id = $1 AND source_user_id = $2
+ RETURNING *`,
+ [conversationId, sourceUserId, personId],
+ ).catch((err) => {
+ if (err?.code === '23503') throw new ServerError('Person not found', { status: 404 });
+ throw err;
+ });
+ return { ...rowToParticipant(result.rows[0]), displacedPersonId };
+ }
+
+ /**
+ * Release a participant's link to whichever Tribe person currently owns it
+ * (#97 part B) — the unlink half `linkParticipant` has never had a
+ * counterpart for. Deletes every `tribe_identities` claim THAT PERSON holds
+ * for this participant: the handle claim from `identityScopeFor`, when the
+ * handle classifies, and the `kind='beeper-user'` claim from
+ * `beeperUserScopeFor`, which almost every participant carries regardless of
+ * handle. Each DELETE is filtered on `person_id = <that person>`, so a claim
+ * someone ELSE now holds on the same handle or beeper-user pair — moved
+ * there by a later link elsewhere — is never touched.
+ *
+ * Nulls the participant's own cache column and, via the same
+ * `clearDisplacedParticipantCaches`/`clearDisplacedBeeperUserCaches` helpers
+ * a displaced-owner re-link already uses, every OTHER participant row those
+ * claims were backing — the unlinked person simply stands in as the
+ * "displaced" one here. A trailing explicit UPDATE guarantees THIS row ends
+ * up NULL regardless of whether either reuse call happened to cover it (it
+ * only fires when its own DELETE actually removed a claim) — a stale cache
+ * with no backing identity claim at all must still clear.
+ *
+ * Idempotent: a participant with no `tribePersonId` is a 200 no-op —
+ * `{ participant, unlinkedPersonId: null, removedClaims: 0 }` — rather than
+ * an error, matching `linkParticipant`'s own "last explicit action wins"
+ * posture. Throws 404 only when the participant row itself does not exist.
+ */
+ export async function unlinkParticipant({ conversationId, sourceUserId }) {
+ await ensureReady();
+ const participant = await getParticipant(conversationId, sourceUserId);
+ if (!participant) throw new ServerError('Participant not found', { status: 404 });
+
+ const personId = participant.tribePersonId;
+ if (!personId) {
+ return { participant, unlinkedPersonId: null, removedClaims: 0 };
+ }
+
+ let removedClaims = 0;
+
+ const scope = identityScopeFor(participant);
+ if (scope) {
+ const result = await query(
+ `DELETE FROM tribe_identities WHERE person_id = $1 AND kind = $2 AND network = $3 AND handle = $4`,
+ [personId, scope.kind, scope.network, scope.handle],
+ );
+ const deleted = result.rowCount ?? 0;
+ removedClaims += deleted;
+ if (deleted) await clearDisplacedParticipantCaches(personId, scope);
+ }
+
+ const beeperUserScope = beeperUserScopeFor(participant);
+ if (beeperUserScope) {
+ const result = await query(
+ `DELETE FROM tribe_identities WHERE person_id = $1 AND kind = $2 AND network = $3 AND handle = $4`,
+ [personId, beeperUserScope.kind, beeperUserScope.network, beeperUserScope.handle],
+ );
+ const deleted = result.rowCount ?? 0;
+ removedClaims += deleted;
+ if (deleted) await clearDisplacedBeeperUserCaches(personId, beeperUserScope);
+ }
+
+ // Belt-and-braces: null THIS participant's own cache regardless of whether
+ // either reuse call above happened to cover it (both are gated on their
+ // own DELETE having actually removed a row).
+ await query(
+ `UPDATE beeper_participants SET tribe_person_id = NULL, updated_at = NOW()
+ WHERE conversation_id = $1 AND source_user_id = $2 AND tribe_person_id = $3`,
+ [conversationId, sourceUserId, personId],
+ );
+
+ const updated = await getParticipant(conversationId, sourceUserId);
+ return { participant: updated, unlinkedPersonId: personId, removedClaims };
+ }
+
+ /**
+ * Create a new Tribe person from a participant's own display name and link
+ * it — the other half of #10 decision 4 ("can also create a new Tribe
+ * person"). Never invoked automatically; always an explicit user action. The
+ * network named in `notes` (display only) is the participant's OWN
+ * conversation's network, joined server-side — never caller-supplied.
+ *
+ * Delegates the whole write to `linkParticipant`, so the new person gets the
+ * same durable `kind='beeper-user'` claim any hand-link does (#96).
+ */
+ export async function createPersonAndLinkParticipant({
+ conversationId, sourceUserId, name, ring = 'tribe', relationship = '', source = 'user',
+ }) {
+ const participant = await getParticipant(conversationId, sourceUserId);
+ if (!participant) throw new ServerError('Participant not found', { status: 404 });
+ const personName = String(name || participant.displayName || '').trim();
+ if (!personName) throw new ServerError('name is required', { status: 400, code: 'BAD_REQUEST' });
+
+ const person = await tribe.createPerson({
+ name: personName,
+ ring,
+ relationship,
+ // Just "Imported from Beeper" (#99) — the network used to be baked into
+ // this string because there was nowhere else to show it; now the Tribe
+ // person form's "Linked on Beeper" block reads it from the identity read
+ // model instead (`listPersonIdentitiesWithConversations` below), so a
+ // second network linked later no longer leaves a stale first-network
+ // mention sitting in Notes. Existing notes are left untouched (no
+ // migration) — only new imports get the shorter text.
+ notes: 'Imported from Beeper',
+ channel: 'Beeper',
+ });
+ const { displacedPersonId, ...linked } = await linkParticipant({
+ conversationId, sourceUserId, personId: person.id, source,
+ });
+ return {
+ person, participant: linked, created: true, displacedPersonId: displacedPersonId || null,
+ };
+ }
+
+ /**
+ * Relate a batch of Beeper messages to Tribe by SENDER only — never by
+ * iterating `beeper_participants` (which can be a truncated roster). Each
+ * candidate is `{ conversationId, senderId, sentAt, network, channel }`.
+ * Dedupe key is `beeper:<YYYY-MM-DD>`, matching #10 decision "daily Tribe
+ * touchpoints are written; there is no per-message activity event."
+ * Returns `{ created, matched }` (mirrors `tribe.autoLogTouchpoints`'s shape).
+ */
+ export async function logSenderTouchpoints(candidates = []) {
+ if (!Array.isArray(candidates) || candidates.length === 0) return { created: 0, matched: 0 };
+ await ensureReady();
+
+ // Built ONCE for the whole batch and threaded through resolveParticipantPerson's
+ // phone fallback (mirrors tribe.autoLogTouchpoints), rather than every
+ // resolution reloading and reindexing every Tribe person from scratch.
+ const personIndex = buildPersonMatchIndex(await tribe.listPeople());
+
+ // Memoize the participant -> person resolution per (conversationId,
+ // senderId) within this batch, so a burst of messages from the same sender
+ // resolves once, not per message. Day-level dedupe is NOT reimplemented
+ // here: tribe.autoCreateTouchpoint's (person_id, dedupe_key) partial unique
+ // index already collapses a same-day repeat into a harmless no-op insert.
+ const personCache = new Map();
+ let created = 0;
+ let matched = 0;
+ for (const c of candidates) {
+ if (!c?.conversationId || !c?.senderId || !c?.sentAt) continue;
+ const cacheKey = `${c.conversationId} ${c.senderId}`;
+ if (!personCache.has(cacheKey)) {
+ // eslint-disable-next-line no-await-in-loop -- resolving one sender at a time; batch sizes here are one sync sweep, not a bulk import
+ personCache.set(cacheKey, await resolveParticipantPerson(
+ { conversationId: c.conversationId, sourceUserId: c.senderId },
+ personIndex,
+ ));
+ }
+ const personId = personCache.get(cacheKey);
+ if (!personId) continue;
+ matched++;
+ // Normalize to an ISO date before slicing — String(c.sentAt) on a live
+ // Date OBJECT (as opposed to an already-ISO string) yields its
+ // toString() form ("Wed Sep 03 2026 ..."), whose first 10 characters are
+ // NOT a date, silently breaking the `beeper:<day>` dedupe key. Falls back
+ // to the old slice for a value Date can't parse, rather than throwing.
+ const parsedSentAt = new Date(c.sentAt);
+ const day = Number.isNaN(parsedSentAt.getTime())
+ ? String(c.sentAt).slice(0, 10)
+ : parsedSentAt.toISOString().slice(0, 10);
+ // eslint-disable-next-line no-await-in-loop -- same reason as above
+ const touchpoint = await tribe.autoCreateTouchpoint(personId, {
+ happenedAt: c.sentAt,
+ channel: c.channel || (c.network ? `Beeper (${c.network})` : 'Beeper'),
+ summary: '',
+ source: 'message',
+ dedupeKey: `beeper:${day}`,
+ metadata: { network: c.network || '', conversationId: c.conversationId },
+ });
+ if (touchpoint) created++;
+ }
+ return { created, matched };
+ }
+
+ /** Shape one `beeper_participants` row (joined to its conversation) into the
+ * conversation reference the Tribe person read model exposes per identity
+ * (#99): the PortOS conversation id `/messages/beeper/<conversationId>`
+ * expects, the conversation's network + title, its account, and this
+ * participant's own display name so the client can render "network ·
+ * handle-or-display-name" without a second round trip. */
+ function rowToConversationRef(row) {
+ return {
+ conversationId: row.conversation_id,
+ network: row.network || '',
+ title: row.title || '',
+ accountId: row.account_id || '',
+ displayName: row.display_name || '',
+ };
+ }
+
+ /**
+ * The Beeper conversations one `tribe_identities` claim appears in (#99).
+ *
+ * A `kind='beeper-user'` claim joins `beeper_participants` on
+ * `source_user_id = handle` through `beeper_conversations` on
+ * `account_id = network` — `beeperUserScopeFor`'s own key, the durable pair
+ * that survives a purge + resweep, so it finds every conversation for that
+ * Beeper user even one synced after the claim was made.
+ *
+ * A `kind='handle'`/`'phone'` claim instead reads the resolved participant
+ * CACHE (`beeper_participants.tribe_person_id = personId`) rather than
+ * re-deriving the handle scope per participant row with `identityScopeFor`:
+ * the ingestion sweep's `upsertParticipant` already keeps that column in
+ * sync with `tribe_identities` for every synced participant, so the cache is
+ * already the correct, much simpler answer to "which conversations is this
+ * identity seen in" (#99 decision — documented here rather than mirroring
+ * `clearDisplacedParticipantCaches`'s per-row reclassification). A `phone`
+ * claim is network-less by design, so it reads the cache unscoped by
+ * network; a `handle` claim additionally filters to its own network, since
+ * the same cached person can hold claims on more than one network.
+ *
+ * A purged conversation or a participant row nulled by a later re-link
+ * simply produces no row here — no special-casing needed.
+ */
+ async function conversationsForIdentity(personId, identity) {
+ if (identity.kind === BEEPER_USER_KIND) {
+ const { rows } = await query(
+ `SELECT p.conversation_id, p.display_name, c.network, c.title, c.account_id
+ FROM beeper_participants p
+ JOIN beeper_conversations c ON c.id = p.conversation_id
+ WHERE c.account_id = $1 AND p.source_user_id = $2
+ ORDER BY c.last_activity DESC NULLS LAST`,
+ [identity.network, identity.handle],
+ );
+ return rows.map(rowToConversationRef);
+ }
+
+ const params = [personId];
+ let networkFilter = '';
+ if (identity.kind === 'handle' && identity.network) {
+ networkFilter = 'AND c.network = $2';
+ params.push(identity.network);
+ }
+ const { rows } = await query(
+ `SELECT p.conversation_id, p.display_name, c.network, c.title, c.account_id
+ FROM beeper_participants p
+ JOIN beeper_conversations c ON c.id = p.conversation_id
+ WHERE p.tribe_person_id = $1 ${networkFilter}
+ ORDER BY c.last_activity DESC NULLS LAST`,
+ params,
+ );
+ return rows.map(rowToConversationRef);
+ }
+
+ /**
+ * The Tribe person form's "Linked on Beeper" block (#99): every durable
+ * identity claim for a person, each carrying the Beeper conversations that
+ * identity appears in (see `conversationsForIdentity`). Lives here rather
+ * than in `tribe.js` so the generic person read model stays Beeper-agnostic
+ * — `tribe.js` is already imported BY this module, so the reverse would be
+ * circular — and is called from the route only, on the single-person read.
+ * `tribe.listPeople` (the roster) never pays this join's cost; it has no
+ * reason to render per-person identity chips.
+ *
+ * Returns `[]` for a person with no claims.
+ */
+ export async function listPersonIdentitiesWithConversations(personId) {
+ await ensureReady();
+ const identities = await tribeIdentities.listIdentitiesForPerson(personId);
+ if (identities.length === 0) return [];
+ const results = [];
+ for (const identity of identities) {
+ // eslint-disable-next-line no-await-in-loop -- one person's own identities, a handful at most
+ const conversations = await conversationsForIdentity(personId, identity);
+ results.push({ ...identity, conversations });
+ }
+ return results;
+ }
+
+ /**
+ * Unlink (delete) one identity claim (#99) — the Tribe person form's
+ * per-identity "Unlink" action. Deletes the durable row via
+ * `tribeIdentities.unlinkIdentity`, then reuses the SAME displaced-cache
+ * clearers a re-link uses (`clearDisplacedParticipantCaches` /
+ * `clearDisplacedBeeperUserCaches`) to null `beeper_participants.tribe_person_id`
+ * on every participant row that claim was backing — passing the just-deleted
+ * claim's OWN `personId` as the "displaced" person, since removing a claim
+ * displaces it from everyone who was resolving through it.
+ *
+ * Returns the deleted identity, or `null` when `id` is unknown (the route
+ * turns that into a 404).
+ */
+ export async function unlinkIdentity(id) {
+ await ensureReady();
+ const identity = await tribeIdentities.unlinkIdentity(id);
+ if (!identity) return null;
+ const scope = { kind: identity.kind, network: identity.network, handle: identity.handle };
+ if (identity.kind === BEEPER_USER_KIND) {
+ await clearDisplacedBeeperUserCaches(identity.personId, scope);
+ } else {
+ await clearDisplacedParticipantCaches(identity.personId, scope);
+ }
+ return identity;
+ }
diff --cc server/services/beeperTribe.test.js
index 0000000000,457a830d62..5652aab09e
mode 000000,100644..100644
--- a/server/services/beeperTribe.test.js
+++ b/server/services/beeperTribe.test.js
@@@ -1,0 -1,775 +1,789 @@@
+ /**
+ * Mocked-Postgres unit tests for the Beeper ↔ Tribe RESOLUTION ORDER (#34
+ * review). The behavioral acceptance criteria live in `beeperTribe.db.test.js`
+ * against a real database; this file exists because that suite runs only under
+ * `npm run test:db`, so the ordering regression it guards — a cached
+ * `beeper_participants.tribe_person_id` outranking an explicit
+ * `tribe_identities` claim — would otherwise not be caught by the default
+ * `npm --prefix server test` runner at all.
+ *
+ * The design contract being pinned (#10, "both stores, split by durability"):
+ * `tribe_identities` is the truth for any DURABLE handle; the participant
+ * cache column is authoritative ONLY where no durable handle exists.
+ *
+ * Postgres is mocked with in-memory maps that interpret the exact SQL shapes
+ * `beeperTribe.js` / `tribeIdentities.js` issue, so the tests fail if either
+ * the order OR the SQL changes. Every fixture uses placeholder handles and
+ * 555-01xx numbers per root AGENTS.md Sensitive Data & Privacy.
+ */
+ import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+ const db = {
+ people: new Map(), // id -> { deleted }
+ conversations: new Map(), // id -> { network, accountId }
+ participants: new Map(), // `${conversationId}|${sourceUserId}` -> row
+ identities: new Map(), // `${kind}|${network}|${handle}` -> person_id
+ };
+ const seenSql = [];
+
+ const pKey = (c, s) => `${c}|${s}`;
+ const iKey = (k, n, h) => `${k}|${n}|${h}`;
+ // The conversation columns beeperTribe joins server-side: `network` scopes a
+ // kind='handle' claim, `account_id` scopes the kind='beeper-user' one (#96).
+ const convo = (id) => db.conversations.get(id) ?? { network: '', accountId: '' };
+
+ function participantRow(row) {
+ const c = convo(row.conversation_id);
+ return {
+ ...row,
+ network: c.network,
+ account_id: c.accountId,
+ tribe_person_deleted: row.tribe_person_id ? !!db.people.get(row.tribe_person_id)?.deleted : null,
+ };
+ }
+
+ vi.mock('../lib/db.js', () => ({
+ ensureSchema: vi.fn(async () => {}),
+ query: vi.fn(async (sql, params = []) => {
+ seenSql.push(sql);
+ const s = sql.replace(/\s+/g, ' ').trim();
+
+ if (/^SELECT p\.\*, c\.network, c\.account_id, tp\.deleted/.test(s)) {
+ const row = db.participants.get(pKey(params[0], params[1]));
+ return { rows: row ? [participantRow(row)] : [] };
+ }
+ if (/^SELECT ti\.person_id FROM tribe_identities/.test(s)) {
+ const personId = db.identities.get(iKey(params[0], params[1], params[2]));
+ const alive = personId && !db.people.get(personId)?.deleted;
+ return { rows: alive ? [{ person_id: personId }] : [] };
+ }
+ if (/^SELECT person_id FROM tribe_identities WHERE kind/.test(s)) {
+ const personId = db.identities.get(iKey(params[0], params[1], params[2]));
+ return { rows: personId ? [{ person_id: personId }] : [] };
+ }
+ if (/^SELECT deleted FROM tribe_people WHERE id/.test(s)) {
+ const person = db.people.get(params[0]);
+ return { rows: person ? [{ deleted: person.deleted }] : [] };
+ }
+ if (/^SELECT p\.conversation_id, p\.source_user_id, p\.handle, c\.network/.test(s)) {
+ const rows = [...db.participants.values()]
+ .filter((r) => r.tribe_person_id === params[0] && r.handle !== '')
+ .map((r) => ({
+ conversation_id: r.conversation_id,
+ source_user_id: r.source_user_id,
+ handle: r.handle,
+ network: convo(r.conversation_id).network,
+ }));
+ return { rows };
+ }
+ if (/^INSERT INTO tribe_identities/.test(s)) {
+ const [personId, kind, network, handle, source] = params;
+ db.identities.set(iKey(kind, network, handle), personId);
+ return {
+ rows: [{
+ id: `identity-${kind}-${network}-${handle}`,
+ person_id: personId,
+ kind,
+ network,
+ handle,
+ source,
+ linked_at: '2026-01-01T00:00:00.000Z',
+ created_at: '2026-01-01T00:00:00.000Z',
+ }],
+ };
+ }
+ if (/^INSERT INTO beeper_participants/.test(s)) {
+ const [conversationId, sourceUserId, displayName, handle, observedVia] = params;
+ const key = pKey(conversationId, sourceUserId);
+ const existing = db.participants.get(key);
+ if (existing) {
+ // Honor the REAL ON CONFLICT clause: a durable handle survives an
+ // empty re-observation only while the COALESCE guard is in the SQL.
+ const guarded = /COALESCE\(NULLIF\(EXCLUDED\.handle, ''\), beeper_participants\.handle\)/.test(s);
+ db.participants.set(key, {
+ ...existing,
+ display_name: displayName,
+ handle: guarded ? (handle || existing.handle) : handle,
+ observed_via: observedVia,
+ });
+ } else {
+ db.participants.set(key, {
+ conversation_id: conversationId,
+ source_user_id: sourceUserId,
+ display_name: displayName,
+ handle,
+ observed_via: observedVia,
+ tribe_person_id: null,
+ });
+ }
+ return { rows: [] };
+ }
+ // The kind='beeper-user' displaced-cache clear (#96) — matches on the
+ // conversation's ACCOUNT plus the raw source_user_id, in one statement.
+ if (/^UPDATE beeper_participants p SET tribe_person_id = NULL/.test(s)) {
+ const [displacedPersonId, accountId, sourceUserId] = params;
+ let rowCount = 0;
+ for (const row of db.participants.values()) {
+ if (row.tribe_person_id !== displacedPersonId) continue;
+ if (row.source_user_id !== sourceUserId) continue;
+ if (convo(row.conversation_id).accountId !== accountId) continue;
+ row.tribe_person_id = null;
+ rowCount++;
+ }
+ return { rows: [], rowCount };
+ }
+ if (/^UPDATE beeper_participants SET tribe_person_id = NULL/.test(s)) {
+ const row = db.participants.get(pKey(params[0], params[1]));
+ if (row && row.tribe_person_id === params[2]) row.tribe_person_id = null;
+ return { rows: [] };
+ }
+ if (/^UPDATE beeper_participants SET tribe_person_id = \$3/.test(s)) {
+ const row = db.participants.get(pKey(params[0], params[1]));
+ if (!row) return { rows: [] };
- if (/AND tribe_person_id IS NULL/.test(s) && row.tribe_person_id) return { rows: [] };
++ if (/tribe_person_id IS NULL OR EXISTS/.test(s)
++ && row.tribe_person_id && !db.people.get(row.tribe_person_id)?.deleted) return { rows: [] };
+ row.tribe_person_id = params[2];
+ return { rows: [participantRow(row)] };
+ }
+ // unlinkParticipant's claim releases (#97 part B) — deletes ONLY when the
+ // claim is still owned by the given person, mirroring the real SQL's own
+ // `person_id = $1` filter; a claim someone else now holds returns rowCount 0.
+ if (/^DELETE FROM tribe_identities WHERE person_id/.test(s)) {
+ const [personId, kind, network, handle] = params;
+ const key = iKey(kind, network, handle);
+ if (db.identities.get(key) !== personId) return { rows: [], rowCount: 0 };
+ db.identities.delete(key);
+ return { rows: [], rowCount: 1 };
+ }
+ throw new Error(`unmocked SQL: ${s.slice(0, 120)}`);
+ }),
+ }));
+
+ const listPeople = vi.fn(async () => []);
+ vi.mock('./tribe.js', () => ({
+ listPeople: (...args) => listPeople(...args),
+ createPerson: vi.fn(),
+ autoCreateTouchpoint: vi.fn(),
+ }));
+
-const { query } = await import('../lib/db.js');
++const { query, ensureSchema } = await import('../lib/db.js');
+ const beeperTribe = await import('./beeperTribe.js');
+ const tribeService = await import('./tribe.js');
+
+ const CONVERSATION = '00000000-0000-4000-8000-000000000001';
+ const OTHER_CONVERSATION = '00000000-0000-4000-8000-000000000002';
+ const CACHED_PERSON = '11111111-1111-4111-8111-111111111111';
+ const CLAIMING_PERSON = '22222222-2222-4222-8222-222222222222';
+ const LEGACY_PHONE_PERSON = '33333333-3333-4333-8333-333333333333';
+ const PHONE_RAW = '+1 (555) 010-0001';
+ const PHONE_NORMALIZED = '+15550100001';
+ const ACCOUNT_ID = 'example-account-1';
+
+ function seedPerson(id) {
+ db.people.set(id, { deleted: false });
+ return id;
+ }
+
+ function seedConversation(conversationId, network = 'discord', accountId = ACCOUNT_ID) {
+ db.conversations.set(conversationId, { network, accountId });
+ }
+
+ function seedParticipant({
+ conversationId = CONVERSATION, sourceUserId = 'user-1', handle = '', tribePersonId = null,
+ network = 'discord', accountId = ACCOUNT_ID, displayName = 'Example Person', observedVia = 'message-sender',
+ } = {}) {
+ seedConversation(conversationId, network, accountId);
+ db.participants.set(pKey(conversationId, sourceUserId), {
+ conversation_id: conversationId,
+ source_user_id: sourceUserId,
+ display_name: displayName,
+ handle,
+ observed_via: observedVia,
+ tribe_person_id: tribePersonId,
+ });
+ }
+
+ beforeEach(() => {
+ db.people.clear();
+ db.conversations.clear();
+ db.participants.clear();
+ db.identities.clear();
+ seenSql.length = 0;
+ listPeople.mockClear();
+ listPeople.mockResolvedValue([]);
+ query.mockClear();
+ seedPerson(CACHED_PERSON);
+ seedPerson(CLAIMING_PERSON);
+ seedPerson(LEGACY_PHONE_PERSON);
+ });
+
+ describe('resolveParticipantPerson resolution order (#34 review)', () => {
++ it('reuses initialized schema across repeated participant ingestion', async () => {
++ seedConversation(CONVERSATION, 'whatsapp');
++ const input = {
++ conversationId: CONVERSATION, sourceUserId: 'schema-user',
++ handle: PHONE_RAW, observedVia: 'message-sender',
++ };
++ await beeperTribe.upsertParticipant(input);
++ const initializations = ensureSchema.mock.calls.length;
++ await beeperTribe.upsertParticipant(input);
++ await beeperTribe.resolveParticipantPerson(input);
++ expect(ensureSchema).toHaveBeenCalledTimes(initializations);
++ });
++
+ it('lets an explicit tribe_identities claim beat a stale cached tribe_person_id (phone)', async () => {
+ seedParticipant({ handle: PHONE_RAW, tribePersonId: CACHED_PERSON, network: 'whatsapp' });
+ db.identities.set(iKey('phone', '', PHONE_NORMALIZED), CLAIMING_PERSON);
+
+ expect(await beeperTribe.resolveParticipantPerson({
+ conversationId: CONVERSATION, sourceUserId: 'user-1',
+ })).toBe(CLAIMING_PERSON);
+ });
+
+ it('lets an explicit tribe_identities claim beat a stale cached tribe_person_id (network username)', async () => {
+ seedParticipant({ handle: '@Example_Handle', tribePersonId: CACHED_PERSON, network: 'discord' });
+ db.identities.set(iKey('handle', 'discord', 'example_handle'), CLAIMING_PERSON);
+
+ expect(await beeperTribe.resolveParticipantPerson({
+ conversationId: CONVERSATION, sourceUserId: 'user-1',
+ })).toBe(CLAIMING_PERSON);
+ });
+
+ it('keeps the cache authoritative when NO durable handle exists (the ~13% case)', async () => {
+ seedParticipant({ handle: '', tribePersonId: CACHED_PERSON });
+
+ expect(await beeperTribe.resolveParticipantPerson({
+ conversationId: CONVERSATION, sourceUserId: 'user-1',
+ })).toBe(CACHED_PERSON);
+ });
+
+ it('keeps the cache authoritative for a username on a network-less conversation (nothing durable to claim)', async () => {
+ seedParticipant({ handle: '@example_handle', tribePersonId: CACHED_PERSON, network: '' });
+ // A same-named claim on a REAL network must not leak into the unscoped row.
+ db.identities.set(iKey('handle', 'discord', 'example_handle'), CLAIMING_PERSON);
+
+ expect(await beeperTribe.resolveParticipantPerson({
+ conversationId: CONVERSATION, sourceUserId: 'user-1',
+ })).toBe(CACHED_PERSON);
+ });
+
+ it('falls back to the cache for a durable handle nobody has claimed, before the legacy phone array', async () => {
+ seedParticipant({ handle: PHONE_RAW, tribePersonId: CACHED_PERSON, network: 'whatsapp' });
+ listPeople.mockResolvedValue([{ id: LEGACY_PHONE_PERSON, name: 'Example Legacy', phones: [PHONE_NORMALIZED] }]);
+
+ expect(await beeperTribe.resolveParticipantPerson({
+ conversationId: CONVERSATION, sourceUserId: 'user-1',
+ })).toBe(CACHED_PERSON);
+ });
+
+ it('falls back to the legacy Tribe phone matcher only when neither an identity nor a cache answers', async () => {
+ seedParticipant({ handle: PHONE_RAW, tribePersonId: null, network: 'whatsapp' });
+ listPeople.mockResolvedValue([{ id: LEGACY_PHONE_PERSON, name: 'Example Legacy', phones: [PHONE_NORMALIZED] }]);
+
+ expect(await beeperTribe.resolveParticipantPerson({
+ conversationId: CONVERSATION, sourceUserId: 'user-1',
+ })).toBe(LEGACY_PHONE_PERSON);
+ });
+
+ // #96 — the beeper-user claim sits between the handle claim and the cache.
+ it('lets a beeper-user claim beat a stale cached tribe_person_id when no handle classifies', async () => {
+ seedParticipant({ handle: '', tribePersonId: CACHED_PERSON, network: 'facebook' });
+ db.identities.set(iKey('beeper-user', ACCOUNT_ID, 'user-1'), CLAIMING_PERSON);
+
+ expect(await beeperTribe.resolveParticipantPerson({
+ conversationId: CONVERSATION, sourceUserId: 'user-1',
+ })).toBe(CLAIMING_PERSON);
+ });
+
+ it('lets the HANDLE claim outrank the beeper-user claim when the two disagree', async () => {
+ seedParticipant({ handle: '@example_handle', network: 'discord' });
+ db.identities.set(iKey('handle', 'discord', 'example_handle'), CLAIMING_PERSON);
+ db.identities.set(iKey('beeper-user', ACCOUNT_ID, 'user-1'), CACHED_PERSON);
+
+ expect(await beeperTribe.resolveParticipantPerson({
+ conversationId: CONVERSATION, sourceUserId: 'user-1',
+ })).toBe(CLAIMING_PERSON);
+ });
+
+ it('scopes the beeper-user claim to the ACCOUNT — the same source_user_id under another account never resolves', async () => {
+ seedParticipant({ handle: '', network: 'facebook', accountId: 'example-account-2' });
+ db.identities.set(iKey('beeper-user', ACCOUNT_ID, 'user-1'), CLAIMING_PERSON);
+
+ expect(await beeperTribe.resolveParticipantPerson({
+ conversationId: CONVERSATION, sourceUserId: 'user-1',
+ })).toBeNull();
+ });
+
+ it('returns null for an unknown participant', async () => {
+ expect(await beeperTribe.resolveParticipantPerson({
+ conversationId: CONVERSATION, sourceUserId: 'nobody',
+ })).toBeNull();
+ });
+ });
+
+ describe('linkParticipant', () => {
+ it('nulls the displaced person\'s other participant caches on an ownership move, so they stop resolving to them', async () => {
+ // Two conversations on the same network, both presenting the same handle;
+ // the first is already cached onto CACHED_PERSON.
+ seedParticipant({
+ conversationId: OTHER_CONVERSATION, sourceUserId: 'user-elsewhere',
+ handle: '@Example_Handle', tribePersonId: CACHED_PERSON, network: 'discord',
+ });
+ seedParticipant({ handle: '@example_handle', tribePersonId: CACHED_PERSON, network: 'discord' });
+ db.identities.set(iKey('handle', 'discord', 'example_handle'), CACHED_PERSON);
+
+ const linked = await beeperTribe.linkParticipant({
+ conversationId: CONVERSATION, sourceUserId: 'user-1', personId: CLAIMING_PERSON,
+ });
+ expect(linked.displacedPersonId).toBe(CACHED_PERSON);
+
+ // The OTHER conversation's row no longer points at the displaced person...
+ expect(db.participants.get(pKey(OTHER_CONVERSATION, 'user-elsewhere')).tribe_person_id).toBeNull();
+ // ...and now resolves through the identity claim to the new owner.
+ expect(await beeperTribe.resolveParticipantPerson({
+ conversationId: OTHER_CONVERSATION, sourceUserId: 'user-elsewhere',
+ })).toBe(CLAIMING_PERSON);
+ });
+
+ it('leaves a displaced person\'s UNRELATED participant rows alone', async () => {
+ seedParticipant({
+ conversationId: OTHER_CONVERSATION, sourceUserId: 'user-elsewhere',
+ handle: '@different_handle', tribePersonId: CACHED_PERSON, network: 'discord',
+ });
+ seedParticipant({ handle: '@example_handle', tribePersonId: CACHED_PERSON, network: 'discord' });
+ db.identities.set(iKey('handle', 'discord', 'example_handle'), CACHED_PERSON);
+
+ await beeperTribe.linkParticipant({
+ conversationId: CONVERSATION, sourceUserId: 'user-1', personId: CLAIMING_PERSON,
+ });
+ expect(db.participants.get(pKey(OTHER_CONVERSATION, 'user-elsewhere')).tribe_person_id).toBe(CACHED_PERSON);
+ });
+
+ it('writes the cache instead of throwing 400 when a username-bearing participant has no conversation network', async () => {
+ seedParticipant({ handle: '@example_handle', network: '' });
+
+ const linked = await beeperTribe.linkParticipant({
+ conversationId: CONVERSATION, sourceUserId: 'user-1', personId: CLAIMING_PERSON,
+ });
+ expect(linked.tribePersonId).toBe(CLAIMING_PERSON);
+ expect(linked.displacedPersonId).toBeNull();
+ // No inert, unscoped kind='handle' row was written — the ONLY claim is the
+ // account-scoped beeper-user one (#96), which needs no conversation network.
+ expect([...db.identities.keys()]).toEqual([iKey('beeper-user', ACCOUNT_ID, 'user-1')]);
+ });
+
+ // #96 — the durable half for a participant with NO classifiable handle. The
+ // claim is keyed on the conversation's ACCOUNT and the raw source_user_id,
+ // both joined server-side, so it survives the purge that deletes the
+ // participant row (and its cache column) outright.
+ it('claims a beeper-user identity on the conversation account for a participant with no handle at all', async () => {
+ seedParticipant({ handle: '', network: 'facebook' });
+
+ const linked = await beeperTribe.linkParticipant({
+ conversationId: CONVERSATION, sourceUserId: 'user-1', personId: CLAIMING_PERSON,
+ });
+ expect(linked.tribePersonId).toBe(CLAIMING_PERSON);
+ expect(db.identities.get(iKey('beeper-user', ACCOUNT_ID, 'user-1'))).toBe(CLAIMING_PERSON);
+ // The account, not the network — two bridge accounts on one network mint
+ // independent source_user_id spaces.
+ expect(db.identities.has(iKey('beeper-user', 'facebook', 'user-1'))).toBe(false);
+ });
+
+ it('claims the beeper-user identity ALONGSIDE the handle claim when the participant has both', async () => {
+ seedParticipant({ handle: '@example_handle', network: 'discord' });
+
+ await beeperTribe.linkParticipant({
+ conversationId: CONVERSATION, sourceUserId: 'user-1', personId: CLAIMING_PERSON,
+ });
+ expect(db.identities.get(iKey('handle', 'discord', 'example_handle'))).toBe(CLAIMING_PERSON);
+ expect(db.identities.get(iKey('beeper-user', ACCOUNT_ID, 'user-1'))).toBe(CLAIMING_PERSON);
+ });
+
+ it('is a no-op when the same participant is re-linked to the same person', async () => {
+ seedParticipant({ handle: '', network: 'facebook' });
+
+ await beeperTribe.linkParticipant({
+ conversationId: CONVERSATION, sourceUserId: 'user-1', personId: CLAIMING_PERSON,
+ });
+ const again = await beeperTribe.linkParticipant({
+ conversationId: CONVERSATION, sourceUserId: 'user-1', personId: CLAIMING_PERSON,
+ });
+ expect(again.tribePersonId).toBe(CLAIMING_PERSON);
+ expect(again.displacedPersonId).toBeNull();
+ // One claim, not two — the UNIQUE (kind, network, handle) upsert path.
+ expect([...db.identities.keys()]).toEqual([iKey('beeper-user', ACCOUNT_ID, 'user-1')]);
+ });
+
+ it('moves the beeper-user claim and clears the displaced person\'s caches on a re-link to somebody else', async () => {
+ // The SAME Beeper user, under the same account, in two conversations.
+ seedParticipant({ handle: '', network: 'facebook' });
+ seedParticipant({ conversationId: OTHER_CONVERSATION, sourceUserId: 'user-1', handle: '', network: 'facebook' });
+
+ await beeperTribe.linkParticipant({
+ conversationId: CONVERSATION, sourceUserId: 'user-1', personId: CACHED_PERSON,
+ });
+ // The second conversation's row caches onto the same person on its next
+ // observation, through the claim alone (no handle to match on).
+ const second = await beeperTribe.upsertParticipant({
+ conversationId: OTHER_CONVERSATION, sourceUserId: 'user-1', handle: '', observedVia: 'message-sender',
+ });
+ expect(second.tribePersonId).toBe(CACHED_PERSON);
+
+ const moved = await beeperTribe.linkParticipant({
+ conversationId: CONVERSATION, sourceUserId: 'user-1', personId: CLAIMING_PERSON,
+ });
+ expect(moved.displacedPersonId).toBe(CACHED_PERSON);
+ expect(db.identities.get(iKey('beeper-user', ACCOUNT_ID, 'user-1'))).toBe(CLAIMING_PERSON);
+ // The other conversation's stale cache is cleared and re-resolves to the
+ // new owner rather than permanently attributing the thread to the old one.
+ expect(db.participants.get(pKey(OTHER_CONVERSATION, 'user-1')).tribe_person_id).toBeNull();
+ expect(await beeperTribe.resolveParticipantPerson({
+ conversationId: OTHER_CONVERSATION, sourceUserId: 'user-1',
+ })).toBe(CLAIMING_PERSON);
+ });
+
+ it('still claims a phone identity on a network-less conversation (phones are network-less by design)', async () => {
+ seedParticipant({ handle: PHONE_RAW, network: '' });
+
+ await beeperTribe.linkParticipant({
+ conversationId: CONVERSATION, sourceUserId: 'user-1', personId: CLAIMING_PERSON,
+ });
+ expect(db.identities.get(iKey('phone', '', PHONE_NORMALIZED))).toBe(CLAIMING_PERSON);
+ });
+ });
+
+ describe('unlinkParticipant (#97 part B)', () => {
+ it('removes both claims the linked person holds for this participant and nulls its own cache', async () => {
+ seedParticipant({ handle: '@example_handle', network: 'discord', tribePersonId: CLAIMING_PERSON });
+ db.identities.set(iKey('handle', 'discord', 'example_handle'), CLAIMING_PERSON);
+ db.identities.set(iKey('beeper-user', ACCOUNT_ID, 'user-1'), CLAIMING_PERSON);
+
+ const result = await beeperTribe.unlinkParticipant({ conversationId: CONVERSATION, sourceUserId: 'user-1' });
+
+ expect(result.unlinkedPersonId).toBe(CLAIMING_PERSON);
+ expect(result.removedClaims).toBe(2);
+ expect(result.participant.tribePersonId).toBeNull();
+ expect(db.identities.has(iKey('handle', 'discord', 'example_handle'))).toBe(false);
+ expect(db.identities.has(iKey('beeper-user', ACCOUNT_ID, 'user-1'))).toBe(false);
+ expect(db.participants.get(pKey(CONVERSATION, 'user-1')).tribe_person_id).toBeNull();
+ });
+
+ it('nulls every other participant row the released claims were backing', async () => {
+ seedParticipant({ handle: '@example_handle', network: 'discord', tribePersonId: CLAIMING_PERSON });
+ seedParticipant({
+ conversationId: OTHER_CONVERSATION, sourceUserId: 'user-elsewhere',
+ handle: '@example_handle', tribePersonId: CLAIMING_PERSON, network: 'discord',
+ });
+ db.identities.set(iKey('handle', 'discord', 'example_handle'), CLAIMING_PERSON);
+ db.identities.set(iKey('beeper-user', ACCOUNT_ID, 'user-1'), CLAIMING_PERSON);
+
+ await beeperTribe.unlinkParticipant({ conversationId: CONVERSATION, sourceUserId: 'user-1' });
+
+ expect(db.participants.get(pKey(OTHER_CONVERSATION, 'user-elsewhere')).tribe_person_id).toBeNull();
+ });
+
+ it('never touches another person\'s claim on the same handle', async () => {
+ // The handle claim has already moved to CACHED_PERSON (a later link
+ // elsewhere); this participant's own cache is stale, still pointing at
+ // the old owner.
+ seedParticipant({ handle: '@example_handle', network: 'discord', tribePersonId: CLAIMING_PERSON });
+ db.identities.set(iKey('handle', 'discord', 'example_handle'), CACHED_PERSON);
+ db.identities.set(iKey('beeper-user', ACCOUNT_ID, 'user-1'), CLAIMING_PERSON);
+
+ const result = await beeperTribe.unlinkParticipant({ conversationId: CONVERSATION, sourceUserId: 'user-1' });
+
+ // Only the beeper-user claim (still CLAIMING_PERSON's) was removed — the
+ // handle claim, now owned by CACHED_PERSON, is untouched.
+ expect(result.removedClaims).toBe(1);
+ expect(db.identities.get(iKey('handle', 'discord', 'example_handle'))).toBe(CACHED_PERSON);
+ expect(db.identities.has(iKey('beeper-user', ACCOUNT_ID, 'user-1'))).toBe(false);
+ // The participant's own stale cache still clears via the trailing
+ // belt-and-braces UPDATE, even though the handle DELETE was a no-op.
+ expect(db.participants.get(pKey(CONVERSATION, 'user-1')).tribe_person_id).toBeNull();
+ });
+
+ it('is a 200 no-op for an already-unlinked participant, touching no claims', async () => {
+ seedParticipant({ handle: '@example_handle', network: 'discord', tribePersonId: null });
+ db.identities.set(iKey('handle', 'discord', 'example_handle'), CLAIMING_PERSON);
+
+ const result = await beeperTribe.unlinkParticipant({ conversationId: CONVERSATION, sourceUserId: 'user-1' });
+
+ expect(result.unlinkedPersonId).toBeNull();
+ expect(result.removedClaims).toBe(0);
+ // Someone else's still-active claim on this same handle is left alone.
+ expect(db.identities.get(iKey('handle', 'discord', 'example_handle'))).toBe(CLAIMING_PERSON);
+ });
+
+ it('throws 404 for an unknown participant', async () => {
+ await expect(beeperTribe.unlinkParticipant({
+ conversationId: CONVERSATION, sourceUserId: 'nobody',
+ })).rejects.toMatchObject({ status: 404 });
+ });
+
+ it('unlinks a participant with no classifiable handle via the beeper-user claim alone', async () => {
+ seedParticipant({ handle: '', network: 'facebook', tribePersonId: CLAIMING_PERSON });
+ db.identities.set(iKey('beeper-user', ACCOUNT_ID, 'user-1'), CLAIMING_PERSON);
+
+ const result = await beeperTribe.unlinkParticipant({ conversationId: CONVERSATION, sourceUserId: 'user-1' });
+
+ expect(result.removedClaims).toBe(1);
+ expect(db.identities.has(iKey('beeper-user', ACCOUNT_ID, 'user-1'))).toBe(false);
+ expect(db.participants.get(pKey(CONVERSATION, 'user-1')).tribe_person_id).toBeNull();
+ });
+ });
+
+ describe('upsertParticipant handle preservation', () => {
+ it('guards the ON CONFLICT handle update with COALESCE/NULLIF', async () => {
+ seedConversation(CONVERSATION, 'discord');
+ await beeperTribe.upsertParticipant({
+ conversationId: CONVERSATION, sourceUserId: 'user-1', handle: '@example_handle', observedVia: 'message-sender',
+ });
+ const insert = seenSql.find((sql) => /INSERT INTO beeper_participants/.test(sql));
+ expect(insert.replace(/\s+/g, ' ')).toContain(
+ "handle = COALESCE(NULLIF(EXCLUDED.handle, ''), beeper_participants.handle)",
+ );
+ });
+
+ it('does not wipe a durable handle when the same participant is re-observed without one', async () => {
+ seedParticipant({ handle: '@example_handle', network: 'discord' });
+
+ const resynced = await beeperTribe.upsertParticipant({
+ conversationId: CONVERSATION,
+ sourceUserId: 'user-1',
+ displayName: 'Example Person',
+ handle: '',
+ observedVia: 'participant-list',
+ });
+ expect(resynced.handle).toBe('@example_handle');
+ });
+
+ it('replaces the stored handle when a new, non-empty one is observed', async () => {
+ seedParticipant({ handle: '@old_handle', network: 'discord' });
+
+ const resynced = await beeperTribe.upsertParticipant({
+ conversationId: CONVERSATION,
+ sourceUserId: 'user-1',
+ displayName: 'Example Person',
+ handle: '@new_handle',
+ observedVia: 'message-sender',
+ });
+ expect(resynced.handle).toBe('@new_handle');
+ });
+ });
+
+ // The audit's roster-reload finding: `upsertParticipant`'s phone-match
+ // fallback used to reload and reindex the ENTIRE Tribe roster once per
+ // participant, so a sweep with N participants across a handful of chats made
+ // N (or more) identical `tribe.listPeople()` calls for the same unchanging
+ // roster. `personIndex` lets a caller (`beeperSync.js`'s sweep pass, via
+ // `loadRosterIndex`) build the index once and hand it to every
+ // `upsertParticipant` call.
+ describe('upsertParticipant — roster hoisting: personIndex loaded once, not once per participant', () => {
+ const rosterPeople = () => ([
+ { id: CACHED_PERSON, name: 'Example One', phones: ['+15550100011'] },
+ { id: CLAIMING_PERSON, name: 'Example Two', phones: ['+15550100022'] },
+ { id: LEGACY_PHONE_PERSON, name: 'Example Three', phones: ['+15550100033'] },
+ ]);
+
+ it('reuses one caller-supplied personIndex across N participants instead of reloading the roster per participant', async () => {
+ seedConversation(CONVERSATION, 'whatsapp');
+ listPeople.mockResolvedValue(rosterPeople());
+
+ // The one load a whole sweep pass is meant to do, built up front —
+ // mirrors `loadRosterIndex()` being called once in `beeperSync.js`.
+ const personIndex = await beeperTribe.loadRosterIndex();
+ expect(listPeople).toHaveBeenCalledTimes(1);
+
+ const participants = [
+ { sourceUserId: 'user-1', handle: '+1 (555) 010-0011', expected: CACHED_PERSON },
+ { sourceUserId: 'user-2', handle: '+1 (555) 010-0022', expected: CLAIMING_PERSON },
+ { sourceUserId: 'user-3', handle: '+1 (555) 010-0033', expected: LEGACY_PHONE_PERSON },
+ ];
+
+ for (const p of participants) {
+ // eslint-disable-next-line no-await-in-loop -- sequential upserts mirroring the sweep's own per-chat loop
+ const result = await beeperTribe.upsertParticipant({
+ conversationId: CONVERSATION,
+ sourceUserId: p.sourceUserId,
+ handle: p.handle,
+ observedVia: 'message-sender',
+ personIndex,
+ });
+ // The linking result is UNCHANGED: every participant still resolves to
+ // the right person through the shared index.
+ expect(result.tribePersonId).toBe(p.expected);
+ }
+
+ // The roster was loaded ONCE, up front — never again across all 3 upserts.
+ expect(listPeople).toHaveBeenCalledTimes(1);
+ });
+
+ it('falls back to one reload per call with no personIndex supplied — the old, unchanged default', async () => {
+ seedConversation(CONVERSATION, 'whatsapp');
+ listPeople.mockResolvedValue(rosterPeople());
+
+ const first = await beeperTribe.upsertParticipant({
+ conversationId: CONVERSATION, sourceUserId: 'user-1', handle: '+1 (555) 010-0011', observedVia: 'message-sender',
+ });
+ const second = await beeperTribe.upsertParticipant({
+ conversationId: CONVERSATION, sourceUserId: 'user-2', handle: '+1 (555) 010-0022', observedVia: 'message-sender',
+ });
+
+ expect(first.tribePersonId).toBe(CACHED_PERSON);
+ expect(second.tribePersonId).toBe(CLAIMING_PERSON);
+ expect(listPeople).toHaveBeenCalledTimes(2);
+ });
+ });
+
+ describe('createPersonAndLinkParticipant notes text (#99)', () => {
+ it('no longer bakes the network into the Notes string', async () => {
+ seedParticipant({ network: 'discord', displayName: 'Example Person', handle: '' });
+ tribeService.createPerson.mockResolvedValue({ id: CLAIMING_PERSON, name: 'Example Person' });
+
+ await beeperTribe.createPersonAndLinkParticipant({
+ conversationId: CONVERSATION, sourceUserId: 'user-1',
+ });
+
+ expect(tribeService.createPerson).toHaveBeenCalledWith(expect.objectContaining({
+ notes: 'Imported from Beeper',
+ channel: 'Beeper',
+ }));
+ });
+ });
+
+ describe('listPersonIdentitiesWithConversations (#99)', () => {
+ it('returns an empty array for a person with no identity claims, without a second query', async () => {
+ query.mockImplementationOnce(async (sql) => {
+ expect(sql).toContain('FROM tribe_identities WHERE person_id = $1');
+ return { rows: [] };
+ });
+
+ const result = await beeperTribe.listPersonIdentitiesWithConversations(CLAIMING_PERSON);
+
+ expect(result).toEqual([]);
+ expect(query).toHaveBeenCalledTimes(1);
+ });
+
+ it('attaches conversations to a beeper-user claim via the account/source-user join', async () => {
+ query.mockImplementationOnce(async () => ({
+ rows: [{
+ id: 'identity-1', person_id: CLAIMING_PERSON, kind: 'beeper-user', network: ACCOUNT_ID, handle: 'user-1',
+ source: 'user', linked_at: '2026-01-01T00:00:00.000Z', created_at: '2026-01-01T00:00:00.000Z',
+ }],
+ }));
+ query.mockImplementationOnce(async (sql, params) => {
+ expect(sql).toContain('c.account_id = $1 AND p.source_user_id = $2');
+ expect(params).toEqual([ACCOUNT_ID, 'user-1']);
+ return {
+ rows: [{
+ conversation_id: CONVERSATION, display_name: 'Example Person', network: 'whatsapp',
+ title: 'Example Thread', account_id: ACCOUNT_ID,
+ }],
+ };
+ });
+
+ const result = await beeperTribe.listPersonIdentitiesWithConversations(CLAIMING_PERSON);
+
+ expect(result).toEqual([{
+ id: 'identity-1', personId: CLAIMING_PERSON, kind: 'beeper-user', network: ACCOUNT_ID, handle: 'user-1',
+ source: 'user', linkedAt: '2026-01-01T00:00:00.000Z', createdAt: '2026-01-01T00:00:00.000Z',
+ conversations: [{
+ conversationId: CONVERSATION, network: 'whatsapp', title: 'Example Thread',
+ accountId: ACCOUNT_ID, displayName: 'Example Person',
+ }],
+ }]);
+ });
+
+ it('attaches conversations to a handle claim via the resolved participant cache, scoped by network', async () => {
+ query.mockImplementationOnce(async () => ({
+ rows: [{
+ id: 'identity-2', person_id: CLAIMING_PERSON, kind: 'handle', network: 'whatsapp', handle: 'ada',
+ source: 'user', linked_at: '2026-01-01T00:00:00.000Z', created_at: '2026-01-01T00:00:00.000Z',
+ }],
+ }));
+ query.mockImplementationOnce(async (sql, params) => {
+ expect(sql).toContain('p.tribe_person_id = $1');
+ expect(sql).toContain('c.network = $2');
+ expect(params).toEqual([CLAIMING_PERSON, 'whatsapp']);
+ return { rows: [] }; // a purged conversation / no cached row yet — an empty list, not an error
+ });
+
+ const result = await beeperTribe.listPersonIdentitiesWithConversations(CLAIMING_PERSON);
+
+ expect(result[0].conversations).toEqual([]);
+ });
+
+ it('reads a phone claim un-scoped by network (phones are network-less by design)', async () => {
+ query.mockImplementationOnce(async () => ({
+ rows: [{
+ id: 'identity-3', person_id: CLAIMING_PERSON, kind: 'phone', network: '', handle: PHONE_NORMALIZED,
+ source: 'user', linked_at: '2026-01-01T00:00:00.000Z', created_at: '2026-01-01T00:00:00.000Z',
+ }],
+ }));
+ query.mockImplementationOnce(async (sql, params) => {
+ expect(sql).not.toContain('c.network = $2');
+ expect(params).toEqual([CLAIMING_PERSON]);
+ return {
+ rows: [{
+ conversation_id: OTHER_CONVERSATION, display_name: 'Example Person', network: 'imessage',
+ title: '', account_id: '',
+ }],
+ };
+ });
+
+ const result = await beeperTribe.listPersonIdentitiesWithConversations(CLAIMING_PERSON);
+
+ expect(result[0].conversations).toEqual([{
+ conversationId: OTHER_CONVERSATION, network: 'imessage', title: '', accountId: '', displayName: 'Example Person',
+ }]);
+ });
+ });
+
+ describe('unlinkIdentity (#99)', () => {
+ it('returns null for an unknown identity id (the route turns this into 404)', async () => {
+ query.mockImplementationOnce(async (sql) => {
+ expect(sql).toContain('DELETE FROM tribe_identities WHERE id = $1');
+ return { rows: [] };
+ });
+
+ const result = await beeperTribe.unlinkIdentity('missing-id');
+
+ expect(result).toBeNull();
+ });
+
+ it('deletes a beeper-user claim and nulls the cached participant rows for that account/user', async () => {
+ seedParticipant({
+ conversationId: CONVERSATION, sourceUserId: 'user-1', tribePersonId: CLAIMING_PERSON,
+ network: 'whatsapp', accountId: ACCOUNT_ID,
+ });
+ query.mockImplementationOnce(async () => ({
+ rows: [{
+ id: 'identity-1', person_id: CLAIMING_PERSON, kind: 'beeper-user', network: ACCOUNT_ID, handle: 'user-1',
+ source: 'user', linked_at: '2026-01-01T00:00:00.000Z', created_at: '2026-01-01T00:00:00.000Z',
+ }],
+ }));
+
+ const result = await beeperTribe.unlinkIdentity('identity-1');
+
+ expect(result).toMatchObject({ id: 'identity-1', personId: CLAIMING_PERSON, kind: 'beeper-user' });
+ expect(db.participants.get(pKey(CONVERSATION, 'user-1')).tribe_person_id).toBeNull();
+ });
+
+ it('deletes a handle claim and nulls the cached participant rows matching its scope', async () => {
+ seedParticipant({
+ conversationId: CONVERSATION, sourceUserId: 'user-1', handle: '@ada', tribePersonId: CLAIMING_PERSON,
+ network: 'discord',
+ });
+ query.mockImplementationOnce(async () => ({
+ rows: [{
+ id: 'identity-2', person_id: CLAIMING_PERSON, kind: 'handle', network: 'discord', handle: 'ada',
+ source: 'user', linked_at: '2026-01-01T00:00:00.000Z', created_at: '2026-01-01T00:00:00.000Z',
+ }],
+ }));
+
+ const result = await beeperTribe.unlinkIdentity('identity-2');
+
+ expect(result).toMatchObject({ id: 'identity-2', personId: CLAIMING_PERSON, kind: 'handle' });
+ expect(db.participants.get(pKey(CONVERSATION, 'user-1')).tribe_person_id).toBeNull();
+ });
+ });
diff --cc server/services/bootstrap.js
index 00e10e5d33,2527fe4cc4..e705d3b02b
--- a/server/services/bootstrap.js
+++ b/server/services/bootstrap.js
@@@ -83,9 -83,11 +83,12 @@@ import { initVoiceTimers } from './voic
import { startBackupScheduler } from './backupScheduler.js';
import { startPrivacyRecheckScheduler } from './privacyRecheckScheduler.js';
import { startQuotaBurnScheduler } from './quotaBurnRunner.js';
+import { startMaintenanceRunScheduler } from './maintenanceRun.js';
import { startSeriesAutopilotScheduler } from './seriesAutopilotScheduler.js';
import { startCommissionScheduler } from './creativeCommissions/scheduler.js';
+ import { startBeeperScheduler } from './beeperScheduler.js';
+ import { reconcileOutboxOnBoot } from './beeperOutbox.js';
+ import { startBeeperSocket, stopBeeperSocket } from './beeperSocket.js';
import { startImessageScheduler } from './imessageScheduler.js';
import { startSignalScheduler } from './signalScheduler.js';
import { startSpotifyScheduler } from './spotifyScheduler.js';
diff --cc server/services/tribeIdentities.js
index 0000000000,107d29ee31..68cb554e61
mode 000000,100644..100644
--- a/server/services/tribeIdentities.js
+++ b/server/services/tribeIdentities.js
@@@ -1,0 -1,172 +1,177 @@@
+ /**
+ * Tribe network-scoped identities (#34, decided on #10) — CRUD over
+ * `tribe_identities`: `person_id`, `kind`, `network`, `handle`, `source`,
+ * `linked_at`, `UNIQUE (kind, network, handle)`.
+ *
+ * This is the durable-handle "truth" half of #10's split-by-durability
+ * design. The other half — `beeper_participants.tribe_person_id` as a cache
+ * authoritative only when no durable handle exists — lives in
+ * `server/services/beeperTribe.js`, which is also this table's only caller
+ * today. Kept as its own service (rather than folded into `beeperTribe.js`)
+ * because `tribe_identities` is Tribe-domain, not Beeper-domain — the same
+ * table is the documented landing spot for a future Signal retrofit (#16,
+ * deferred, not built here).
+ *
+ * INTENTIONALLY MACHINE-LOCAL — same ADR as the rest of Tribe
+ * (docs/decisions/2026-06-26-tribe-and-universe-runs-local.md). No sync hook
+ * here by design, consistent with tribe.js.
+ */
+ import { ensureSchema, query } from '../lib/db.js';
+ import { ServerError } from '../lib/errorHandler.js';
+
+ /**
+ * Kinds whose `handle` is only meaningful inside a scope, so a row with an
+ * empty `network` is inert (no lookup can ever match it) and a cross-scope
+ * collision on `UNIQUE (kind, network, handle)` would silently steal another
+ * person's claim. `'handle'` scopes a username to a Beeper NETWORK;
+ * `'beeper-user'` scopes a raw `source_user_id` to a Beeper ACCOUNT (#96 —
+ * see the overload note in server/lib/db/schema/tribe.js). `'phone'` is
+ * deliberately absent: the same number means the same person everywhere.
+ */
+ const NETWORK_SCOPED_KINDS = new Set(['handle', 'beeper-user']);
+
-async function ensureReady() {
- await ensureSchema();
++let schemaReady;
++function ensureReady() {
++ schemaReady ??= ensureSchema().catch((error) => {
++ schemaReady = null;
++ throw error;
++ });
++ return schemaReady;
+ }
+
+ export function rowToIdentity(row) {
+ return {
+ id: row.id,
+ personId: row.person_id,
+ kind: row.kind,
+ network: row.network || '',
+ handle: row.handle,
+ source: row.source || '',
+ linkedAt: row.linked_at?.toISOString?.() ?? row.linked_at,
+ createdAt: row.created_at?.toISOString?.() ?? row.created_at,
+ };
+ }
+
+ /**
+ * Look up the Tribe person currently claiming a `(kind, network, handle)`
+ * identity, or `null`. `network` defaults to `''` (the network-less scope
+ * `classifyNetworkHandle`'s `'phone'` kind uses — the same phone number means
+ * the same person regardless of which network reported it). A `kind='handle'`
+ * or `kind='beeper-user'` identity is always scoped (`NETWORK_SCOPED_KINDS`) —
+ * an empty network can never resolve one, since `linkIdentity` refuses to
+ * write such a row (see below).
+ *
+ * Joined against `tribe_people` and filtered to `deleted = FALSE`:
+ * `tribe.deletePerson` is a SOFT delete, so `ON DELETE CASCADE` on this
+ * table's `person_id` FK never fires for it, and an unfiltered lookup would
+ * keep resolving a Beeper participant onto a person the user deleted.
+ */
+ export async function resolvePersonByIdentity({ kind, network = '', handle }) {
+ if (!kind || !handle) return null;
+ if (NETWORK_SCOPED_KINDS.has(kind) && !network) return null;
+ await ensureReady();
+ const result = await query(
+ `SELECT ti.person_id
+ FROM tribe_identities ti
+ JOIN tribe_people tp ON tp.id = ti.person_id
+ WHERE ti.kind = $1 AND ti.network = $2 AND ti.handle = $3 AND tp.deleted = FALSE`,
+ [kind, network, handle],
+ );
+ return result.rows[0]?.person_id || null;
+ }
+
+ /**
+ * Confirm a person exists and is not soft-deleted before letting them claim
+ * an identity or a `beeper_participants` link. The `tribe_people` FK alone
+ * does not block linking to a soft-deleted person — `tribe.deletePerson` is
+ * `UPDATE ... SET deleted = TRUE`, not a hard delete, so the row (and its FK)
+ * still exists. Exported so `server/services/beeperTribe.js` can run the same
+ * check before writing `beeper_participants.tribe_person_id`, including the
+ * no-durable-handle case where `linkIdentity` below is never reached.
+ */
+ export async function assertPersonLinkable(personId) {
+ await ensureReady();
+ const result = await query(`SELECT deleted FROM tribe_people WHERE id = $1`, [personId]);
+ const row = result.rows[0];
+ if (!row || row.deleted) throw new ServerError('Person not found', { status: 404 });
+ }
+
+ export async function listIdentitiesForPerson(personId) {
+ await ensureReady();
+ const result = await query(
+ `SELECT * FROM tribe_identities WHERE person_id = $1 ORDER BY linked_at DESC`,
+ [personId],
+ );
+ return result.rows.map(rowToIdentity);
+ }
+
+ /**
+ * Claim a `(kind, network, handle)` identity for a person. Re-linking an
+ * already-claimed identity to a DIFFERENT person moves ownership (`DO UPDATE`)
+ * rather than erroring — there is no unlink UI yet (#10's "Not yet specified"
+ * list), and a single-user install has no concurrent-writer race to defend
+ * against (root AGENTS.md Security Model), so "the last explicit link wins"
+ * is the simplest correct behavior until an unlink/merge flow exists. Because
+ * that move is silent at the database level (the audit trigger on this table
+ * only captures hard deletes — there is no `deleted` column to tombstone-flip
+ * on — so a `person_id` UPDATE leaves no `record_audit` row either), the
+ * returned identity carries `displacedPersonId`: the id of whoever previously
+ * owned this exact identity, or `null` on a fresh claim / a re-link to the
+ * SAME person. Callers (`beeperTribe.linkParticipant`, the `/beeper/link*`
+ * routes) surface it so an ownership move is never silent to the user.
+ *
+ * `network` is required for every scoped kind (`NETWORK_SCOPED_KINDS`:
+ * `'handle'`, `'beeper-user'`) — a scoped identity claimed with no scope is
+ * the inert-row / cross-scope-collision hazard this function exists to
+ * prevent (see server/routes/tribe.js's `beeperLinkSchema` comment).
+ * `kind='phone'` stays network-less by design.
+ */
+ export async function linkIdentity({
+ personId, kind, network = '', handle, source = '',
+ }) {
+ if (!personId) throw new ServerError('personId is required', { status: 400, code: 'BAD_REQUEST' });
+ if (!kind || !handle) throw new ServerError('kind and handle are required', { status: 400, code: 'BAD_REQUEST' });
+ if (NETWORK_SCOPED_KINDS.has(kind) && !network) {
+ throw new ServerError(`network is required to link a ${kind} identity`, { status: 400, code: 'BAD_REQUEST' });
+ }
+ await ensureReady();
+ await assertPersonLinkable(personId);
+
+ const existing = await query(
+ `SELECT person_id FROM tribe_identities WHERE kind = $1 AND network = $2 AND handle = $3`,
+ [kind, network, handle],
+ );
+ const previousPersonId = existing.rows[0]?.person_id || null;
+
+ const result = await query(
+ `INSERT INTO tribe_identities (person_id, kind, network, handle, source, linked_at)
+ VALUES ($1, $2, $3, $4, $5, NOW())
+ ON CONFLICT (kind, network, handle)
+ DO UPDATE SET person_id = EXCLUDED.person_id, source = EXCLUDED.source, linked_at = NOW()
+ RETURNING *`,
+ [personId, kind, network, handle, source],
+ ).catch((err) => {
+ if (err?.code === '23503') throw new ServerError('Person not found', { status: 404 });
+ throw err;
+ });
+ const displacedPersonId = previousPersonId && previousPersonId !== personId ? previousPersonId : null;
+ return { ...rowToIdentity(result.rows[0]), displacedPersonId };
+ }
+
+ /**
+ * Delete one identity claim by id (#99 — the Tribe person form's per-identity
+ * "Unlink" action). Pure `tribe_identities` deletion only — clearing the
+ * `beeper_participants.tribe_person_id` cache that claim was backing is
+ * `beeperTribe.unlinkIdentity`'s job, not this module's: this file stays
+ * Beeper-agnostic (see file header), and `beeperTribe.js` already owns the
+ * cache-clearing helpers (`clearDisplacedParticipantCaches` /
+ * `clearDisplacedBeeperUserCaches`) a re-link uses for the same reason.
+ *
+ * Returns the deleted identity, or `null` when `id` does not exist (the
+ * route turns that into a 404).
+ */
+ export async function unlinkIdentity(id) {
+ await ensureReady();
+ const result = await query(`DELETE FROM tribe_identities WHERE id = $1 RETURNING *`, [id]);
+ return result.rows[0] ? rowToIdentity(result.rows[0]) : null;
+ }