Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: add a beeper desktop bridge as a third comms chat source
tzioupc7afe0909e4f
diff --git a/AGENTS.md b/AGENTS.mdindex b4d458d528..ad210b143d 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -123,6 +123,8 @@ Client- and server-specific conventions live in nested memory files that load wh**Feature groups bucket related features under one toggle, additively.** `INSTANCE_FEATURE_GROUPS` in `server/lib/instanceFeatureRegistry.js` declares the groups (today: `comms`, holding FaceTime Audio, iMessage, Signal, X, Stacker News and Beeper); a feature joins one by carrying `group: '<groupId>'` on its descriptor, which is the whole edit. `resolveOne` in `server/services/instanceFeatures.js` resolves a grouped feature as **its own stored override → the group flag → the detector → `defaultEnabled`**: an explicit per-feature override always wins, and only a feature left on "inherit" answers to its group (group off hides it, group on hands it straight back to its normal resolution). Setting an override back to inherit deletes the stored key rather than writing a third sentinel, so it reads exactly like a feature nobody ever touched. **A group's own `enabled` defaults to `true` when no group state is stored** — that default is the parity guarantee: an install with no `instanceFeatureGroups` in settings resolves every member exactly as it did before the group existed, so registering a group is never a silent hide and needs no settings migration. Malformed group settings fail toward `false`, matching the per-feature override's own posture. An ungrouped feature is completely unaffected.+**A feature toggle that arms background work must reconcile that work at toggle time, not only at boot.** A subsystem gated on "feature on AND credential present" and started once in `services/bootstrap.js` is silently wrong the moment either half of that gate moves at runtime: on a live install, storing a Beeper credential left the realtime transport down and no sweep registered for 48 minutes, until a restart — and the mirror-image gap left a socket relaying on a token a disconnect had just revoked. Give the subsystem one idempotent `reconcile…()` that reads the gate and moves everything to match it, and call it from every path that can move the gate (each credential write, the feature toggle, the group toggle, disconnect). Make repeat calls no-ops rather than re-registrations — re-`schedule()`ing an existing event resets `nextRunAt` a full interval out, so an unrelated toggle would keep pushing the next run away — serialize overlapping calls on one tail, and log transitions only, so an install that has never enabled the feature still narrates nothing. `server/services/beeperArming.js` is the worked example.+### Slashdo Commands (`lib/slashdo`)PortOS bundles [slashdo](https://github.com/atomantic/slashdo) as a git submodule at `lib/slashdo`, providing slash commands (`/do:next`, `/do:review`, `/do:pr`, `/do:push`, `/do:release`, …) without a separate global install. The `.claude/commands/do/` symlinks expose them as project-level slash commands. `/do:next` claims the next PLAN.md item (or GitHub issue with `--issues`) in an isolated worktree and ships a PR. CoS agents use the shared slashdo renderer: file-tool hosts receive a short entrypoint with supporting files read by phase; `loadSlashdoCommand(name)` from `server/services/subAgentSpawner.js` remains the eager, self-contained form for other consumers.diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex 40b5261e0b..749d388889 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -215,6 +215,7 @@ export const NAV_PRESENTATION = {'/cos/jobs': { icon: Bot },'/cos/tasks': { icon: FileText },'/cos/workflow': { icon: ChartGantt },+ '/messages/beeper': { icon: MessageCircle },'/messages/config': { icon: Settings },'/messages/contacts': { icon: Users },'/messages/drafts': { icon: FilePen },diff --git a/client/src/components/Layout.test.jsx b/client/src/components/Layout.test.jsxindex 78c1a3f12c..b5475507c9 100644--- a/client/src/components/Layout.test.jsx+++ b/client/src/components/Layout.test.jsx@@ -65,6 +65,7 @@ const allFeaturesOn = () => [{ id: 'gsd', label: 'GSD', enabled: true },{ id: 'openclaw', label: 'OpenClaw', enabled: true },{ id: 'health', label: 'Health tracking', enabled: true },+ { id: 'beeper', label: 'Beeper', enabled: true },];const featureMock = vi.hoisted(() => ({ features: null }));@@ -148,7 +149,7 @@ describe('Layout — manifest-derived sidebar structure', () => {expect(NAV_PRESENTATION[p], `missing NAV_PRESENTATION for digital twin tab ${p}`).toBeDefined();}- const messageTabs = ['inbox', 'drafts', 'imessage', 'signal', 'contacts', 'sync', 'config'];+ const messageTabs = ['inbox', 'drafts', 'imessage', 'signal', 'beeper', 'contacts', 'sync', 'config'];for (const tab of messageTabs) {const p = `/messages/${tab}`;expect(NAV_PRESENTATION[p], `missing NAV_PRESENTATION for message tab ${p}`).toBeDefined();@@ -330,6 +331,37 @@ describe('Layout — instance feature gating', () => {});});+describe('Layout — Comms section (Beeper)', () => {+ // #30 / real-browser pass: the Beeper row never rendered in the sidebar Comms+ // section, feature on or off, because NAV_PRESENTATION had no '/messages/beeper'+ // key. navRowForPath() throws the other way around — for a NAV_PRESENTATION+ // path with no matching NAV_COMMANDS entry — so a path missing from+ // NAV_PRESENTATION itself never reaches navRowForPath at all (presentedNavRows+ // only maps over NAV_PRESENTATION's own keys), and the row was silently absent+ // rather than a crash.+ it('lists Beeper in the Comms section alongside the other messaging rows when the feature is on', async () => {+ await renderLayout('/messages/inbox');++ const beeper = screen.getByRole('link', { name: 'Beeper' });+ expect(beeper).toHaveAttribute('href', '/messages/beeper');+ // Same section as its siblings, not a stray top-level row.+ expect(screen.getByRole('link', { name: 'Signal' })).toBeTruthy();+ expect(screen.getByRole('link', { name: 'iMessage' })).toBeTruthy();+ });++ it('drops only the Beeper row when the beeper feature is off, keeping the rest of Comms', async () => {+ featureMock.features = allFeaturesOn()+ .map((f) => (f.id === 'beeper' ? { ...f, enabled: false } : f));++ await renderLayout('/messages/inbox');++ expect(screen.queryByRole('link', { name: 'Beeper' })).toBeNull();+ expect(screen.getByRole('link', { name: 'Signal' })).toBeTruthy();+ expect(screen.getByRole('link', { name: 'iMessage' })).toBeTruthy();+ expect(screen.getByRole('link', { name: 'Inbox' })).toBeTruthy();+ });+});+describe('Layout — System Resources location state', () => {it('keeps Dev Tools expanded and System Resources active on every subtab', async () => {await renderLayout('/system-resources/storage');diff --git a/client/src/components/messages/BeeperTab.jsx b/client/src/components/messages/BeeperTab.jsxnew file mode 100644index 0000000000..92316d0b48--- /dev/null+++ b/client/src/components/messages/BeeperTab.jsx@@ -0,0 +1,173 @@+import {+ useCallback, useEffect, useRef, useState,+} from 'react';+import { useParams, useSearchParams } from 'react-router';+import toast from '../ui/Toast';+import Drawer from '../Drawer';+import useDrawerTab from '../../hooks/useDrawerTab';+import useBeeperRealtime from '../../hooks/useBeeperRealtime';+import useMounted from '../../hooks/useMounted';+import { getBeeperStatus } from '../../services/api';+import BeeperChatSurface from './beeper/BeeperChatSurface';+import BeeperSettingsPanel from './beeper/BeeperSettingsPanel';++/**+ * Comms → Messages → Beeper. The page shell for the chat surface (#35).+ *+ * It owns exactly two things the surface and the settings panel must share:+ *+ * 1. **The page-level realtime subscription.** `useBeeperRealtime` pairs its+ * own `beeper:subscribe`/`beeper:unsubscribe` per mount, and several+ * subscribers may be live at once — `useBeeperOutbox`, reached through+ * `BeeperChatSurface`, mounts its own instance to refetch the outbox on a+ * `message.upserted` invalidation (`client/src/hooks/README.md` sanctions+ * this). This is the ONE that owns the status card: its liveness snapshot+ * plus an invalidation counter (and the frames behind it, for+ * `BeeperChatSurface`'s own frame-scoped thread refetch) are handed down+ * as props, so the settings drawer never needs a subscription of its own.+ * Sweep state (`sweep`) and `tokenConfigured` ride the same status fetch+ * (#80) — no second poller, and every invalidation frame the sweep itself+ * fires as it goes (see `beeperSync.js`) refreshes it here too.+ * 2. **The settings drawer.** #30's status card is not removed by the chat+ * surface landing — it moves behind a header action, deep-linked as+ * `?settings=1` exactly like the iMessage ingestion drawer, so ⌘K and voice+ * can open it and an actionable fault still has a home that is not a+ * global banner.+ *+ * The open conversation is the route param on `/messages/beeper/:conversationId`+ * (Messages routes it as the shared `:chatKey` segment), never local state.+ */++// The OAuth 2.0 error codes Beeper's own consent screen can send back,+// mapped to a plain sentence rather than shown raw — the bare code read as+// implementation detail with no remedy. An unrecognized code still gets a+// generic sentence rather than disappearing, with the raw code kept as a+// trailing parenthetical either way so the exact server-reported reason is+// never lost, only never led with.+const OAUTH_ERROR_SENTENCES = {+ access_denied: 'Beeper connect was not approved',+ invalid_scope: 'Beeper could not grant the access PortOS asked for',+ server_error: 'Beeper reported a server error during connect',+};+const oauthErrorSentence = (code) => `${OAUTH_ERROR_SENTENCES[code] || 'Beeper connect failed'} (${code})`;++export default function BeeperTab() {+ const { chatKey } = useParams();+ const [settingsParam, setSettingsParam] = useDrawerTab('settings', null, ['1']);+ // `invalidationSeq` is the "something changed, re-read the mirror" pulse —+ // still a bare counter, because the list/networks refetch it drives (design+ // decision: other chats' previews and unread counts always refresh) needs no+ // frame detail. `invalidationFramesRef` rides alongside it as a MAILBOX, not+ // React state: `BeeperChatSurface` needs each frame's own `chatID` to decide+ // whether the OPEN THREAD is in scope for a refetch (audit cluster 07,+ // findings PERF-6/BEEP-5) — a counter alone cannot tell "another chat+ // changed" from "this one did". It is a ref rather than state because the+ // surface drains it itself once it has scheduled a refetch for everything+ // currently in it, so relaying frames down costs no extra render and needs+ // no hand-back of "how many did you consume".+ const invalidationFramesRef = useRef([]);+ const [invalidationSeq, setInvalidationSeq] = useState(0);++ const mountedRef = useMounted();+ const onInvalidate = useCallback((frame) => {+ invalidationFramesRef.current.push(frame ?? null);+ setInvalidationSeq((seq) => seq + 1);+ }, []);+ const { realtime, seedRealtime } = useBeeperRealtime({ onInvalidate });++ // The outbound runaway breaker's read model (#36, decided on #8). The+ // composer disables Send off this — the SAME status the settings drawer's+ // `BeeperOutboxBreakerBanner` already reads — rather than a second banner on+ // the chat surface, which #12 decision 4 reserves for the settings card.+ const [breaker, setBreaker] = useState(null);++ // Sweep visibility (#80): running/idle, started/finished, accounts done of+ // the total, chats and messages mirrored so far — the list header's+ // "Syncing… N of M accounts" / "Last synced HH:MM" strip reads this, and+ // `tokenConfigured` is what the empty state branches on instead of+ // `networks.length` alone. Both ride the SAME status fetch as `realtime`+ // and `breaker` below, reusing the existing mount + invalidation-frame+ // triggers rather than adding a second poller — a sweep's own per-account+ // progress reaches here because `beeperSync.js` fires an invalidation frame+ // as it goes (see beeperSync.js's `emitSweepInvalidation`).+ const [sweep, setSweep] = useState(null);+ const [tokenConfigured, setTokenConfigured] = useState(false);++ // Seeded from the page, not from the settings drawer: `beeper:subscribe`+ // does not push the current transport state, and the drawer's own status+ // fetch only runs once it is opened — so without this the rail's dot would+ // stay blank on a healthy install until something changed. The breaker flag+ // rides the same fetch for the same reason: the composer needs it before the+ // user has ever opened the settings drawer.+ const seedStatus = useCallback(() => {+ getBeeperStatus({ silent: true })+ .then((status) => {+ if (!mountedRef.current) return;+ if (status?.realtime) seedRealtime(status.realtime);+ setBreaker(status?.outbox?.breaker || null);+ setSweep(status?.sweep || null);+ setTokenConfigured(status?.tokenConfigured === true);+ })+ .catch(() => {});+ }, [seedRealtime, mountedRef]);++ // Re-read on the invalidation counter, not only at mount. `seedStatus` is a+ // stable callback, so keying the effect on it alone made this a MOUNT-TIME+ // SNAPSHOT: a breaker that trips during the session (a send loop, three+ // refused sends in a row) never reached the composer, which stayed live+ // against a server that would refuse every send until a human cleared it —+ // and the only way to see the truth was a page reload. The counter is the+ // one "something moved" signal this page already owns.+ useEffect(() => { seedStatus(); }, [seedStatus, invalidationSeq]);++ // Beeper redirects the BROWSER back to this PAGE after consent (#31), not to+ // the settings drawer — so the outcome flag is read here, where something is+ // always mounted, rather than in the panel that only exists while the drawer+ // is open. The server callback already exchanged the code and vaulted the+ // token; all that arrives is the outcome. Report it once, then strip it so a+ // reload doesn't repeat the toast, and on a FAILURE open the settings drawer+ // in the same URL write, because that is where the connect card that fixes it+ // lives.+ const [searchParams, setSearchParams] = useSearchParams();+ const oauthConnected = searchParams.get('beeperConnected');+ const oauthError = searchParams.get('beeperOauthError');+ useEffect(() => {+ if (!oauthConnected && !oauthError) return;+ if (oauthError) toast.error(oauthErrorSentence(oauthError));+ else {+ toast.success('Beeper connected');+ seedStatus();+ }+ setSearchParams((prev) => {+ const next = new URLSearchParams(prev);+ next.delete('beeperConnected');+ next.delete('beeperOauthError');+ if (oauthError) next.set('settings', '1');+ return next;+ }, { replace: true });+ }, [oauthConnected, oauthError, setSearchParams, seedStatus]);++ return (+ <div className="h-full min-h-0">+ <BeeperChatSurface+ conversationId={chatKey || null}+ realtime={realtime}+ invalidationSeq={invalidationSeq}+ invalidationFrames={invalidationFramesRef}+ breaker={breaker}+ sweep={sweep}+ tokenConfigured={tokenConfigured}+ onOpenSettings={() => setSettingsParam('1')}+ />++ <Drawer+ open={settingsParam === '1'}+ onClose={() => setSettingsParam(null)}+ title="Beeper Settings"+ size="md"+ >+ <BeeperSettingsPanel realtime={realtime} onRealtimeSeed={seedRealtime} onBreakerCleared={seedStatus} />+ </Drawer>+ </div>+ );+}diff --git a/client/src/components/messages/BeeperTab.test.jsx b/client/src/components/messages/BeeperTab.test.jsxnew file mode 100644index 0000000000..e4b240529d--- /dev/null+++ b/client/src/components/messages/BeeperTab.test.jsx@@ -0,0 +1,1598 @@+import {+ afterEach, beforeEach, describe, expect, it, vi,+} from 'vitest';+import {+ act, cleanup, fireEvent, render, screen, waitFor, within,+} from '@testing-library/react';+import { MemoryRouter, Route, Routes } from 'react-router';++/**+ * The Beeper chat surface (#35), tested at the page boundary — the same seam a+ * user reaches it through, so the rail, the list, the thread, the URL contract+ * and the realtime wiring are exercised together rather than one prop at a time.+ *+ * EVERY fixture value below is invented: placeholder names, `example.com`+ * handles and 555-01xx numbers per root AGENTS.md Sensitive Data & Privacy. The+ * last test in this file is a guard that keeps it that way — no value from a+ * running instance may ever be pasted in here.+ */++const api = vi.hoisted(() => ({+ getBeeperStatus: vi.fn(),+ syncBeeperNow: vi.fn(),+ getBeeperNetworks: vi.fn(),+ getBeeperConversations: vi.fn(),+ getBeeperConversation: vi.fn(),+ getBeeperMessages: vi.fn(),+ setBeeperConversationArchived: vi.fn(),+ setBeeperConversationLowPriority: vi.fn(),+ // The LOCAL "seen in PortOS" watermark (#83) — never a Beeper write.+ markBeeperConversationSeen: vi.fn(),+ linkBeeperParticipant: vi.fn(),+ createTribePersonFromBeeper: vi.fn(),+ unlinkBeeperParticipant: vi.fn(),+ getTribePeople: vi.fn(),+ // Reached through the settings drawer. Declared here because+ // `BeeperSettingsPanel` imports them at module load, whether or not a test+ // opens the drawer — a named import missing from the mock throws.+ getSettings: vi.fn(),+ updateSettings: vi.fn(),+ checkBeeperConnection: vi.fn(),+ startBeeperOAuth: vi.fn(),+ saveBeeperToken: vi.fn(),+ disconnectBeeper: vi.fn(),+ // Attachment byte mirror (#37). `beeperAttachmentUrl` is called during+ // render, so it must return a string rather than a mock's `undefined`.+ beeperAttachmentUrl: vi.fn((messageId, idx) => `/api/beeper/attachments/${messageId}/${idx}`),+ fetchBeeperAttachment: vi.fn(),+ setBeeperAttachmentKeep: vi.fn(),+ getBeeperAttachmentSummary: vi.fn(),+ backfillBeeperAttachments: vi.fn(),+ purgeBeeperConversation: vi.fn(),+}));+// The composer's send lifecycle (#36) reaches the server through+// `apiBeeper.js` directly — a DIFFERENT module specifier than the `api.js`+// barrel every other call in this file goes through — so `useBeeperOutbox`+// needs its own mock rather than riding along on `api` above.+const apiBeeper = vi.hoisted(() => ({+ listOutboxEntries: vi.fn(),+ createOutboxEntry: vi.fn(),+ sendOutboxEntry: vi.fn(),+ discardOutboxEntry: vi.fn(),+}));+const toast = vi.hoisted(() => Object.assign(vi.fn(), { error: vi.fn(), success: vi.fn() }));+const socketMock = vi.hoisted(() => {+ const handlers = new Map();+ const emitted = [];+ return {+ handlers,+ emitted,+ socket: {+ on: (event, fn) => {+ if (!handlers.has(event)) handlers.set(event, new Set());+ handlers.get(event).add(fn);+ },+ off: (event, fn) => { handlers.get(event)?.delete(fn); },+ emit: (event, payload) => { emitted.push([event, payload]); },+ },+ };+});++vi.mock('../../services/api', () => api);+vi.mock('../../services/apiBeeper', () => apiBeeper);+vi.mock('../ui/Toast', () => ({ default: toast }));+vi.mock('../../services/socket', () => ({ default: socketMock.socket }));++const BeeperTab = (await import('./BeeperTab')).default;++const CONV_A = '11111111-1111-4111-8111-111111111111';+const CONV_B = '22222222-2222-4222-8222-222222222222';++// Nine networks, matching the outlier install #9 warns the design must not be+// tuned for. Ids only — the surface renders whatever the mirror reports.+const NINE_NETWORKS = [+ 'whatsapp', 'telegram', 'discord', 'signal', 'instagram', 'slack', 'x', 'facebook', 'googlemessages',+].map((network, index) => ({ network, conversationCount: 1, unreadCount: index, unreadConversations: 1, accountIds: [`acct-example-${index}`], lastActivity: '2026-09-01T10:00:00.000Z' }));++const conversation = (overrides = {}) => ({+ id: CONV_A,+ accountId: 'acct-example-0',+ network: 'examplenet',+ sourceChatId: 'chat-example-1',+ title: 'Example Conversation',+ type: 'single',+ isGroup: false,+ isPinned: false,+ isArchived: false,+ isLowPriority: false,+ isMuted: false,+ lastActivity: '2026-09-01T10:00:00.000Z',+ unreadCount: 0,+ lastMessage: null,+ participants: [],+ hasMoreParticipants: false,+ ...overrides,+});++const renderTab = (initialPath = '/messages/beeper') => render(+ <MemoryRouter initialEntries={[initialPath]}>+ <Routes>+ <Route path="/messages/:tab" element={<BeeperTab />} />+ <Route path="/messages/:tab/:chatKey" element={<BeeperTab />} />+ </Routes>+ </MemoryRouter>,+);++beforeEach(() => {+ vi.clearAllMocks();+ socketMock.handlers.clear();+ socketMock.emitted.length = 0;+ api.getBeeperStatus.mockResolvedValue({ tokenConfigured: true, reachable: true, accounts: [], realtime: { state: 'connected' } });+ api.syncBeeperNow.mockResolvedValue({ skipped: false, accounts: 0, chats: 0, messages: 0 });+ api.getBeeperNetworks.mockResolvedValue({ networks: [] });+ api.getBeeperConversations.mockResolvedValue({ conversations: [], nextCursor: null });+ api.getBeeperConversation.mockResolvedValue(conversation());+ api.getBeeperMessages.mockResolvedValue({ messages: [], nextCursor: null });+ api.markBeeperConversationSeen.mockResolvedValue(conversation());+ api.getTribePeople.mockResolvedValue([]);+ apiBeeper.listOutboxEntries.mockResolvedValue({ entries: [] });+ apiBeeper.discardOutboxEntry.mockResolvedValue(undefined);+ api.getSettings.mockResolvedValue({ beeper: { enabled: false, intervalMinutes: 5, baseUrl: 'http://127.0.0.1:23373', attachmentBudgetGb: 5 } });+ api.getBeeperAttachmentSummary.mockResolvedValue({+ budgetBytes: 5 * 1024 * 1024 * 1024, usedBytes: 0, storedFiles: 0, pendingCount: 0, pendingBytes: 0,+ pendingUnknownCount: 0, overCapCount: 0, unavailableCount: 0, keptCount: 0, totalCount: 0, maxBytes: 32 * 1024 * 1024,+ });+});++afterEach(cleanup);++describe('deep linking', () => {+ it('opens the conversation directly on a cold load of its URL', async () => {+ api.getBeeperNetworks.mockResolvedValue({ networks: [NINE_NETWORKS[0]] });+ api.getBeeperConversations.mockResolvedValue({ conversations: [conversation()], nextCursor: null });+ api.getBeeperConversation.mockResolvedValue(conversation({ title: 'Example Deep Link' }));+ api.getBeeperMessages.mockResolvedValue({+ messages: [{ id: 'm1', conversationId: CONV_A, senderId: 'user-1', body: 'Placeholder message body', sentAt: '2026-09-01T10:00:00.000Z', attachments: [] }],+ nextCursor: null,+ });++ renderTab(`/messages/beeper/${CONV_A}`);++ expect(await screen.findByText('Placeholder message body')).toBeInTheDocument();+ expect(api.getBeeperConversation).toHaveBeenCalledWith(CONV_A, { silent: true });+ // The list is fetched for the same scope, so the surface is whole rather+ // than a bare thread with no way back.+ expect(api.getBeeperConversations).toHaveBeenCalled();+ });++ it('renders a not-found state for a stale conversation id instead of an empty thread', async () => {+ api.getBeeperConversation.mockRejectedValue(Object.assign(new Error('Conversation not found'), { status: 404 }));+ renderTab(`/messages/beeper/${CONV_B}`);+ expect(await screen.findByText('Conversation not found')).toBeInTheDocument();+ });++ // The regression the reviewer found: an `apiCore` failure with no `.status`+ // (503 unreachable, 500, offline) leaves the detail null and the error set,+ // and the thread's "Pick a conversation" early return used to sit AHEAD of+ // the error branch — so a URL that names a conversation rendered as if+ // nothing were selected. Every fetch behind it is `{ silent: true }`, so+ // there was no toast either: the failure was completely invisible.+ it('renders the thread error with a Retry when a deep link fails, never "Pick a conversation"', async () => {+ api.getBeeperConversation.mockRejectedValue(new Error('Beeper request failed: connection refused'));+ api.getBeeperMessages.mockRejectedValue(new Error('Beeper request failed: connection refused'));+ renderTab(`/messages/beeper/${CONV_B}`);++ expect(await screen.findByText('Could not open this conversation')).toBeInTheDocument();+ expect(screen.getByText('Beeper request failed: connection refused')).toBeInTheDocument();+ expect(screen.queryByText('Pick a conversation')).toBeNull();+ expect(screen.queryByText('Conversation not found')).toBeNull();++ // Retry re-reads the mirror rather than leaving the pane stuck.+ const calls = api.getBeeperConversation.mock.calls.length;+ fireEvent.click(screen.getByRole('button', { name: /Retry/ }));+ await waitFor(() => expect(api.getBeeperConversation.mock.calls.length).toBeGreaterThan(calls));+ });++ it('scopes the list from the URL, so a shared link reopens the same scope', async () => {+ renderTab('/messages/beeper?scope=net:whatsapp&unread=1');+ await waitFor(() => expect(api.getBeeperConversations).toHaveBeenCalledWith(+ { unreadOnly: true, network: 'whatsapp', archived: false },+ { silent: true },+ ));+ });+});++describe('rendering at every install size', () => {+ it('renders with zero conversations, and says an empty list is often correct when networks are mirrored and the list loaded fine', async () => {+ api.getBeeperNetworks.mockResolvedValue({ networks: [NINE_NETWORKS[0]] });+ renderTab();+ expect(await screen.findByText('Nothing here')).toBeInTheDocument();+ expect(screen.getByText(/often correct rather than broken/)).toBeInTheDocument();+ expect(screen.queryByTestId('network-badge')).toBeNull();+ });++ it('drops the per-row network badge inside a single-network scope', async () => {+ api.getBeeperNetworks.mockResolvedValue({ networks: [NINE_NETWORKS[0]] });+ api.getBeeperConversations.mockResolvedValue({+ conversations: [conversation({ network: 'whatsapp' })],+ nextCursor: null,+ });++ renderTab('/messages/beeper?scope=net:whatsapp');++ expect(await screen.findByText('Example Conversation')).toBeInTheDocument();+ // The rail already states the network, so the badge would be noise — the+ // one conditional rule #9 says a from-scratch design would have got wrong.+ expect(screen.queryByTestId('network-badge')).toBeNull();+ });++ it('badges every row in the unified inbox, at nine networks', async () => {+ api.getBeeperNetworks.mockResolvedValue({ networks: NINE_NETWORKS });+ api.getBeeperConversations.mockResolvedValue({+ conversations: NINE_NETWORKS.map((entry, index) => conversation({+ id: `4444444${index}-4444-4444-8444-444444444444`,+ network: entry.network,+ title: `Example Conversation ${index}`,+ })),+ nextCursor: null,+ });++ renderTab();++ expect(await screen.findByText('Example Conversation 0')).toBeInTheDocument();+ expect(screen.getAllByTestId('network-badge')).toHaveLength(9);+ // One rail entry per mirrored network, and no hardcoded roster anywhere.+ expect(screen.getByRole('button', { name: 'WhatsApp' })).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Google Messages' })).toBeInTheDocument();+ });++ it('renders a network the client has no logo for rather than dropping it', async () => {+ api.getBeeperNetworks.mockResolvedValue({ networks: [{ network: 'somenewbridge', unreadCount: 0, conversationCount: 1, accountIds: [] }] });+ renderTab();+ expect(await screen.findByRole('button', { name: 'somenewbridge' })).toBeInTheDocument();+ });+});++/**+ * Audit cluster 08 (A11Y-3): the empty conversation list always stated+ * "{networks.length} network(s) mirrored ... often correct rather than+ * broken", even when the networks fetch had failed (networks lands at []+ * either way) — rendering "0 networks mirrored" as settled fact directly+ * under the visible error banner it contradicted. The fix branches the+ * second paragraph on whether anything is actually known to be wrong or+ * filtered, rather than always reciting the same reassurance.+ */+describe('the honest empty state (A11Y-3)', () => {+ it('shows no networks-mirrored reassurance and offers the settings link when no networks are mirrored and Beeper is not connected', async () => {+ // #80: the empty state branches on `tokenConfigured`, not on+ // `networks.length` alone — the settings-link copy this test pins is the+ // NOT-CONNECTED branch, so it needs a not-connected status.+ api.getBeeperStatus.mockResolvedValue({ tokenConfigured: false, reachable: null, accounts: [], realtime: null });+ api.getBeeperNetworks.mockRejectedValue(new Error('network fetch failed'));+ renderTab();+ await screen.findByText('Nothing here');+ expect(screen.queryByText(/network.*mirrored/i)).toBeNull();+ expect(screen.getByRole('button', { name: /open beeper settings/i })).toBeInTheDocument();+ });++ it('names the unread filter instead of the reassurance when unreadOnly is on', async () => {+ api.getBeeperNetworks.mockResolvedValue({ networks: [NINE_NETWORKS[0]] });+ renderTab('/messages/beeper?unread=1');+ await screen.findByText('Nothing here');+ expect(screen.getByText(/filter is on/i)).toBeInTheDocument();+ expect(screen.queryByText(/often correct rather than broken/)).toBeNull();+ });++ it('suppresses the reassurance entirely when the conversation list itself failed to load', async () => {+ api.getBeeperNetworks.mockResolvedValue({ networks: [NINE_NETWORKS[0]] });+ api.getBeeperConversations.mockRejectedValue(new Error('Could not load conversations'));+ renderTab();+ await screen.findByText('Nothing here');+ expect(screen.queryByText(/network.*mirrored/i)).toBeNull();+ expect(screen.queryByText(/often correct rather than broken/)).toBeNull();+ expect(screen.queryByText(/nothing is mirrored yet/i)).toBeNull();+ expect(screen.queryByRole('button', { name: /open beeper settings/i })).toBeNull();+ });++ // The other half of #80's branch: connected but nothing mirrored yet is a+ // DIFFERENT state from never-connected, and used to render the same+ // "connect a network" prompt to a user who already had.+ it('says a first sync is in progress, with no settings link, when Beeper is connected but nothing is mirrored yet', async () => {+ api.getBeeperStatus.mockResolvedValue({ tokenConfigured: true, reachable: true, accounts: [], realtime: null });+ api.getBeeperNetworks.mockResolvedValue({ networks: [] });+ renderTab();+ await screen.findByText('Nothing here');+ expect(screen.getByText(/first sync in progress/i)).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: /open beeper settings/i })).toBeNull();+ });+});++/**+ * "Sync now" (#79): the list-header refresh action used to call only+ * `loadList()`/`loadNetworks()` — both pure SELECTs against the mirror — so+ * clicking it never actually triggered a sweep. It now runs one sweep first.+ */+describe('Sync now', () => {+ it('runs a sweep, then refetches the list and the networks', async () => {+ api.getBeeperNetworks.mockResolvedValue({ networks: [NINE_NETWORKS[0]] });+ renderTab();+ await screen.findByText('Nothing here');+ api.getBeeperConversations.mockClear();+ api.getBeeperNetworks.mockClear();++ fireEvent.click(screen.getByRole('button', { name: /sync now/i }));++ await waitFor(() => expect(api.syncBeeperNow).toHaveBeenCalledTimes(1));+ await waitFor(() => expect(api.getBeeperConversations).toHaveBeenCalled());+ expect(api.getBeeperNetworks).toHaveBeenCalled();+ // The sweep must land BEFORE the refetch, or the refetch could race a+ // sweep that has not written anything yet.+ const [syncOrder] = api.syncBeeperNow.mock.invocationCallOrder;+ const [listOrder] = api.getBeeperConversations.mock.invocationCallOrder;+ expect(syncOrder).toBeLessThan(listOrder);+ });++ it('still refetches, without an error toast, when the sweep reports skipped: true', async () => {+ api.syncBeeperNow.mockResolvedValue({ skipped: true });+ renderTab();+ await screen.findByText('Nothing here');+ api.getBeeperConversations.mockClear();++ fireEvent.click(screen.getByRole('button', { name: /sync now/i }));++ await waitFor(() => expect(api.getBeeperConversations).toHaveBeenCalled());+ expect(toast.error).not.toHaveBeenCalled();+ });++ it('toasts and still re-enables the button when the sweep request itself fails', async () => {+ api.syncBeeperNow.mockRejectedValue(new Error('Beeper sweep failed for all 3 accounts'));+ renderTab();+ await screen.findByText('Nothing here');++ const button = screen.getByRole('button', { name: /sync now/i });+ fireEvent.click(button);++ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Beeper sweep failed for all 3 accounts'));+ expect(button).toBeEnabled();+ });+});++/**+ * The list header's sweep-visibility strip (#80): "Syncing… N of M accounts"+ * while a sweep runs, "Last synced HH:MM" once idle. Both ride the same+ * `GET /api/beeper/status` fetch `realtime`/`breaker` already used, seeded at+ * mount — no separate polling loop.+ */+describe('the syncing / last-synced strip', () => {+ it('shows "Syncing… N of M accounts" while a sweep is running', async () => {+ api.getBeeperStatus.mockResolvedValue({+ tokenConfigured: true, reachable: true, accounts: [], realtime: null,+ sweep: {+ running: true, startedAt: '2026-09-05T10:00:00.000Z', finishedAt: null, reason: 'scheduler',+ accountsDone: 3, accountsTotal: 9, chats: 40, messages: 812,+ },+ });+ renderTab();+ expect(await screen.findByText('Syncing… 3 of 9 accounts')).toBeInTheDocument();+ });++ it('shows "Last synced HH:MM" once idle, formatted from finishedAt', async () => {+ api.getBeeperStatus.mockResolvedValue({+ tokenConfigured: true, reachable: true, accounts: [], realtime: null,+ sweep: {+ running: false, startedAt: '2026-09-05T10:00:00.000Z', finishedAt: '2026-09-05T10:04:00.000Z', reason: 'manual',+ accountsDone: 9, accountsTotal: 9, chats: 210, messages: 4032,+ },+ });+ renderTab();+ expect(await screen.findByText(/Last synced \d{1,2}:\d{2}/)).toBeInTheDocument();+ });++ it('shows neither line before any sweep has ever run', async () => {+ api.getBeeperStatus.mockResolvedValue({ tokenConfigured: true, reachable: true, accounts: [], realtime: null, sweep: null });+ renderTab();+ await screen.findByText('Nothing here');+ expect(screen.queryByText(/Syncing…/)).toBeNull();+ expect(screen.queryByText(/Last synced/)).toBeNull();+ });+});++/**+ * Audit cluster 08 (A11Y-6): the list-error banner carried no role, and+ * `getBeeperConversations` is fetched silent, so a screen-reader user got no+ * signal that the list had failed to load.+ */+describe('the conversation list error banner is announced', () => {+ it('exposes the list-fetch failure with role="alert"', async () => {+ api.getBeeperConversations.mockRejectedValue(new Error('Could not load conversations'));+ renderTab();++ expect(await screen.findByText('Could not load conversations')).toHaveAttribute('role', 'alert');+ });+});++describe('message direction', () => {+ it('puts own messages on the other side of the thread, from the mirrored isSender', async () => {+ api.getBeeperConversation.mockResolvedValue(conversation({+ title: 'Example Contact',+ participants: [{ sourceUserId: 'user-1', displayName: 'Sam Example', handle: '', tribePersonId: null, tribePersonName: null, observedVia: 'participant-list' }],+ }));+ api.getBeeperMessages.mockResolvedValue({+ messages: [+ { id: 'm2', conversationId: CONV_A, senderId: 'user-me', body: 'Placeholder outbound', sentAt: '2026-09-01T10:00:00.000Z', isSender: true, attachments: [] },+ { id: 'm1', conversationId: CONV_A, senderId: 'user-1', body: 'Placeholder inbound', sentAt: '2026-09-01T09:00:00.000Z', isSender: false, attachments: [] },+ ],+ nextCursor: null,+ });++ renderTab(`/messages/beeper/${CONV_A}`);++ await screen.findByText('Placeholder outbound');+ const bubbles = screen.getAllByTestId('beeper-message');+ // Rendered oldest-first, so the inbound one comes first.+ expect(bubbles.map((node) => node.dataset.direction)).toEqual(['in', 'out']);+ // An own message carries no sender name — the reference's shape, and the+ // reason direction has to be mirrored rather than guessed from senderId.+ expect(within(bubbles[1]).queryByText('user-me')).toBeNull();+ expect(within(bubbles[0]).getByText('Sam Example')).toBeInTheDocument();+ });++ it('renders a message with no direction as inbound rather than as unknown', async () => {+ api.getBeeperMessages.mockResolvedValue({+ messages: [{ id: 'm1', conversationId: CONV_A, senderId: 'user-1', body: 'Placeholder body', sentAt: '2026-09-01T09:00:00.000Z', attachments: [] }],+ nextCursor: null,+ });+ renderTab(`/messages/beeper/${CONV_A}`);+ await screen.findByText('Placeholder body');+ expect(screen.getByTestId('beeper-message').dataset.direction).toBe('in');+ });+});++describe('the pinned grid is Beeper’s own isPinned, mirrored', () => {+ it('lifts pinned conversations into the grid without any local pin state', async () => {+ api.getBeeperConversations.mockResolvedValue({+ conversations: [+ conversation({ id: CONV_A, title: 'Example Pinned', isPinned: true }),+ conversation({ id: CONV_B, title: 'Example Unpinned' }),+ ],+ nextCursor: null,+ });+ renderTab();++ await screen.findByText('Example Unpinned');+ // The grid renders the first word of a pinned title; the row list still+ // holds both. Nothing in the client can pin — there is no such control.+ expect(screen.getAllByText('Example').length).toBeGreaterThan(0);+ expect(screen.queryByRole('button', { name: /^Pin/ })).toBeNull();+ });+});++describe('deferred controls render inert rather than absent', () => {+ it('disables Requests, Later, add-scope and the overflow menu, each saying it is not available yet', async () => {+ renderTab();+ await screen.findByText('Nothing here');++ for (const label of ['Requests', 'Later', 'Add scope', 'More scope options']) {+ const control = screen.getByRole('button', { name: label });+ expect(control).toBeDisabled();+ expect(control).toHaveAttribute('title', `${label} — not available yet`);+ }+ });++ it('keeps the two wired scopes live', async () => {+ renderTab();+ await screen.findByText('Nothing here');+ expect(screen.getByRole('button', { name: 'Archive' })).toBeEnabled();+ expect(screen.getByRole('button', { name: 'Low priority' })).toBeEnabled();+ });+});++/**+ * Audit cluster 08 (COPY-2): "not wired yet" is implementation vocabulary+ * leaking into shipped copy — the InertControl tooltip template and the+ * composer's attach button both used it. Upstream's own convention is+ * "Coming soon — …" (ImportTab.jsx); this file's fix lands on+ * "not available yet" / "aren't supported yet" instead. Scans the rendered+ * DOM rather than one control at a time, so a leftover site anywhere would+ * still fail this even if a future edit missed it.+ */+describe('no leftover "not wired" copy anywhere in the surface', () => {+ it('renders no title or text containing "not wired", across the rail and the composer', async () => {+ api.getBeeperConversation.mockResolvedValue(conversation({ title: 'Example Contact', network: 'whatsapp' }));+ renderTab(`/messages/beeper/${CONV_A}`);+ await screen.findByLabelText('Message Example Contact on WhatsApp');++ const titled = [...document.querySelectorAll('[title]')].map((el) => el.getAttribute('title') || '');+ expect(titled.some((title) => title.toLowerCase().includes('not wired'))).toBe(false);+ expect(document.body.textContent.toLowerCase()).not.toContain('not wired');+ });+});++/**+ * Audit cluster 08 (COPY-3): the scope heading rendered a ChevronDown inside+ * a non-interactive span, implying a scope-picker menu that does not exist —+ * against the file's own docstring ("an inert control that looks live is+ * worse than an absent one"). The fix drops the chevron outright.+ */+describe('the scope heading has no control that looks interactive but has no handler', () => {+ it('renders the scope label with no chevron or icon beside it', async () => {+ renderTab();+ await screen.findByText('Nothing here');+ const label = screen.getByText('Inbox');+ expect(label.parentElement.querySelector('svg')).toBeNull();+ });+});++describe('the composer', () => {+ it('names the network it would send on and keeps the draft buffer', async () => {+ api.getBeeperConversation.mockResolvedValue(conversation({ network: 'whatsapp', title: 'Example Contact' }));+ renderTab(`/messages/beeper/${CONV_A}`);++ const composer = await screen.findByLabelText('Message Example Contact on WhatsApp');+ expect(composer).toHaveAttribute('placeholder', 'Message Example Contact on WhatsApp');+ });++ it('disables Send while the draft is empty', async () => {+ api.getBeeperConversation.mockResolvedValue(conversation({ network: 'whatsapp', title: 'Example Contact' }));+ renderTab(`/messages/beeper/${CONV_A}`);++ const send = await screen.findByRole('button', { name: 'Send' });+ // aria-disabled (A11Y-5), not the native disabled attribute — the button+ // must stay focusable so focus survives a mid-send disable.+ expect(send).toHaveAttribute('aria-disabled', 'true');+ expect(send).not.toHaveAttribute('disabled');+ expect(send.getAttribute('title')).toBe('Type a message to send');+ });+});++// The composer's send lifecycle (#53, wired on the durable outbox from #36).+// `useBeeperOutbox` has its own thorough unit coverage+// (`hooks/useBeeperOutbox.test.jsx`) — what matters HERE is that the composer+// wires the right props to it and renders what it reports, at the same page+// boundary the rest of this file tests through.+describe('the composer sends', () => {+ const OUTBOUND_TEXT = 'Placeholder outbound text';++ const openComposer = async (overrides = {}) => {+ api.getBeeperConversation.mockResolvedValue(conversation({ network: 'whatsapp', title: 'Example Contact', ...overrides }));+ renderTab(`/messages/beeper/${CONV_A}`);+ const composer = await screen.findByLabelText('Message Example Contact on WhatsApp');+ fireEvent.change(composer, { target: { value: OUTBOUND_TEXT } });+ return composer;+ };++ it('enqueues a send through the outbox with the right payload — one row, one send call', async () => {+ apiBeeper.createOutboxEntry.mockResolvedValue({ id: 'outbox-1', conversationId: CONV_A, body: OUTBOUND_TEXT, state: 'approved' });+ apiBeeper.sendOutboxEntry.mockResolvedValue({ id: 'outbox-1', conversationId: CONV_A, body: OUTBOUND_TEXT, state: 'awaiting-confirmation' });+ const composer = await openComposer();++ fireEvent.click(screen.getByRole('button', { name: 'Send' }));++ await waitFor(() => expect(apiBeeper.createOutboxEntry).toHaveBeenCalledWith(CONV_A, OUTBOUND_TEXT, { silent: true }));+ expect(apiBeeper.createOutboxEntry).toHaveBeenCalledTimes(1);+ await waitFor(() => expect(apiBeeper.sendOutboxEntry).toHaveBeenCalledWith('outbox-1', { confirmFirstContact: false }, { silent: true }));+ expect(apiBeeper.sendOutboxEntry).toHaveBeenCalledTimes(1);+ // `onSent` clears the draft buffer once the send is accepted.+ await waitFor(() => expect(composer).toHaveValue(''));+ });++ it('renders the pending row while the send is in flight', async () => {+ apiBeeper.createOutboxEntry.mockResolvedValue({ id: 'outbox-1', conversationId: CONV_A, body: OUTBOUND_TEXT, state: 'approved' });+ apiBeeper.sendOutboxEntry.mockReturnValue(new Promise(() => {})); // never settles within this test+ await openComposer();++ fireEvent.click(screen.getByRole('button', { name: 'Send' }));++ const row = await screen.findByTestId('beeper-outbox-row');+ expect(row).toHaveAttribute('data-state', 'approved');+ expect(within(row).getByText(OUTBOUND_TEXT)).toBeInTheDocument();+ expect(within(row).getByText('Sending…')).toBeInTheDocument();+ });++ it('shows the real mirrored message once an entry is confirmed, with no duplicate pending row', async () => {+ apiBeeper.listOutboxEntries.mockResolvedValue({+ entries: [{ id: 'outbox-1', conversationId: CONV_A, body: OUTBOUND_TEXT, state: 'sent', messageId: 'msg-final-1' }],+ });+ api.getBeeperMessages.mockResolvedValue({+ messages: [{+ id: 'msg-final-1', conversationId: CONV_A, senderId: 'user-me', body: OUTBOUND_TEXT,+ sentAt: '2026-09-01T10:00:00.000Z', isSender: true, attachments: [],+ }],+ nextCursor: null,+ });+ api.getBeeperConversation.mockResolvedValue(conversation({ network: 'whatsapp', title: 'Example Contact' }));++ renderTab(`/messages/beeper/${CONV_A}`);++ await screen.findByText(OUTBOUND_TEXT);+ expect(screen.queryByTestId('beeper-outbox-row')).toBeNull();+ expect(screen.getAllByText(OUTBOUND_TEXT)).toHaveLength(1);+ });++ it('shows Retry on a failed send and leaves the composer text intact — never re-sent automatically', async () => {+ apiBeeper.createOutboxEntry.mockResolvedValue({ id: 'outbox-1', conversationId: CONV_A, body: OUTBOUND_TEXT, state: 'approved' });+ apiBeeper.sendOutboxEntry.mockRejectedValue(Object.assign(new Error('Beeper request failed: connection refused'), { code: 'NETWORK_ERROR' }));+ apiBeeper.listOutboxEntries.mockResolvedValue({+ entries: [{ id: 'outbox-1', conversationId: CONV_A, body: OUTBOUND_TEXT, state: 'failed', errorCode: 'NETWORK_ERROR' }],+ });+ const composer = await openComposer();++ fireEvent.click(screen.getByRole('button', { name: 'Send' }));++ const row = await screen.findByTestId('beeper-outbox-row');+ await waitFor(() => expect(row).toHaveAttribute('data-state', 'failed'));+ expect(within(row).getByRole('button', { name: 'Retry' })).toBeInTheDocument();+ expect(apiBeeper.sendOutboxEntry).toHaveBeenCalledTimes(1);+ expect(composer).toHaveValue(OUTBOUND_TEXT);+ });++ it('surfaces a first-contact refusal as an inline confirmation naming the network and recipient, then resends the SAME row', async () => {+ apiBeeper.createOutboxEntry.mockResolvedValue({ id: 'outbox-1', conversationId: CONV_A, body: OUTBOUND_TEXT, state: 'approved' });+ apiBeeper.sendOutboxEntry+ .mockRejectedValueOnce(Object.assign(+ new Error('This is the first message PortOS has ever sent to this conversation'),+ { code: 'FIRST_CONTACT_CONFIRMATION_REQUIRED' },+ ))+ .mockResolvedValueOnce({ id: 'outbox-1', conversationId: CONV_A, body: OUTBOUND_TEXT, state: 'awaiting-confirmation' });+ await openComposer();++ fireEvent.click(screen.getByRole('button', { name: 'Send' }));++ // A question, not an error.+ expect(await screen.findByText(/first message PortOS has sent to Example Contact on WhatsApp/)).toBeInTheDocument();+ expect(toast.error).not.toHaveBeenCalled();++ fireEvent.click(screen.getByRole('button', { name: 'Send anyway' }));++ expect(apiBeeper.createOutboxEntry).toHaveBeenCalledTimes(1);+ await waitFor(() => expect(apiBeeper.sendOutboxEntry).toHaveBeenLastCalledWith(+ 'outbox-1', { confirmFirstContact: true }, { silent: true },+ ));+ expect(apiBeeper.sendOutboxEntry).toHaveBeenCalledTimes(2);+ await waitFor(() => expect(screen.queryByText(/send it\?/)).toBeNull());+ });++ // The reviewer's blocker on #53: repro was open a conversation PortOS has+ // never sent to, type, Send, then Cancel on the inline confirmation. The row+ // used to stay `approved` and unrendered-as-cancelled, so it fell into+ // OutboxRow's default branch and rendered a permanent "Sending…" bubble —+ // reappearing on every reload because GET /outbox returns approved rows, with+ // no dismiss control and no way back. Cancel must discard the row outright.+ it('discards the pending bubble on Cancel — no phantom "Sending…" row left behind', async () => {+ apiBeeper.createOutboxEntry.mockResolvedValue({ id: 'outbox-1', conversationId: CONV_A, body: OUTBOUND_TEXT, state: 'approved' });+ apiBeeper.sendOutboxEntry.mockRejectedValueOnce(Object.assign(+ new Error('This is the first message PortOS has ever sent to this conversation'),+ { code: 'FIRST_CONTACT_CONFIRMATION_REQUIRED' },+ ));+ const composer = await openComposer();++ fireEvent.click(screen.getByRole('button', { name: 'Send' }));+ expect(await screen.findByText(/first message PortOS has sent to Example Contact on WhatsApp/)).toBeInTheDocument();+ expect(await screen.findByTestId('beeper-outbox-row')).toBeInTheDocument();++ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));++ await waitFor(() => expect(apiBeeper.discardOutboxEntry).toHaveBeenCalledWith('outbox-1', { silent: true }));+ // The question closes, the phantom bubble is gone, and the composer text is+ // untouched — Cancel only withdraws the send, it does not clear the draft.+ await waitFor(() => expect(screen.queryByText(/send it\?/)).toBeNull());+ expect(screen.queryByTestId('beeper-outbox-row')).toBeNull();+ expect(composer).toHaveValue(OUTBOUND_TEXT);++ // A GET /outbox after the cancel (e.g. a reload) no longer returns the row.+ apiBeeper.listOutboxEntries.mockResolvedValue({ entries: [] });+ expect(apiBeeper.sendOutboxEntry).toHaveBeenCalledTimes(1);+ });++ it('submits once from ⌘/Ctrl+Enter and once from a click inside the same render — the hook latch', async () => {+ apiBeeper.createOutboxEntry.mockResolvedValue({ id: 'outbox-1', conversationId: CONV_A, body: OUTBOUND_TEXT, state: 'approved' });+ apiBeeper.sendOutboxEntry.mockResolvedValue({ id: 'outbox-1', conversationId: CONV_A, body: OUTBOUND_TEXT, state: 'awaiting-confirmation' });+ const composer = await openComposer();+ const send = screen.getByRole('button', { name: 'Send' });++ await act(async () => {+ fireEvent.keyDown(composer, { key: 'Enter', metaKey: true });+ fireEvent.click(send);+ await Promise.resolve();+ });++ await waitFor(() => expect(apiBeeper.createOutboxEntry).toHaveBeenCalledTimes(1));+ expect(apiBeeper.sendOutboxEntry).toHaveBeenCalledTimes(1);+ });++ it('disables Send while the runaway breaker is tripped, even with a non-empty draft, and points at Settings', async () => {+ api.getBeeperStatus.mockResolvedValue({+ tokenConfigured: true,+ reachable: true,+ accounts: [],+ realtime: { state: 'connected' },+ outbox: { breaker: { tripped: true, reason: 'synthetic loop', trippedAt: '2026-09-01T09:00:00.000Z' } },+ });+ const composer = await openComposer();++ const send = screen.getByRole('button', { name: 'Send' });+ // aria-disabled (A11Y-5): the button stays focusable — clicking it is a+ // no-op because handleSendClick itself checks canSend, not because the+ // click never reaches the handler.+ await waitFor(() => expect(send).toHaveAttribute('aria-disabled', 'true'));+ expect(send.getAttribute('title')).toMatch(/runaway breaker/);+ expect(composer).toHaveValue(OUTBOUND_TEXT);++ fireEvent.click(send);+ expect(apiBeeper.createOutboxEntry).not.toHaveBeenCalled();+ });++ // The breaker is PROCESS state that can trip mid-session — a send loop, or+ // three refused sends in a row — and the composer's gate used to be a+ // mount-time snapshot: `seedStatus` ran once and never again, so the Send+ // button stayed live against a server that would refuse every send until a+ // human cleared it, and only a page reload showed the truth.+ it('disables Send for a breaker that trips after mount, with no page reload', async () => {+ const status = (breaker) => ({+ tokenConfigured: true, reachable: true, accounts: [], realtime: { state: 'connected' }, outbox: { breaker },+ });+ api.getBeeperStatus.mockResolvedValue(status({ tripped: false, reason: null, trippedAt: null }));+ await openComposer();++ const send = screen.getByRole('button', { name: 'Send' });+ await waitFor(() => expect(send).toHaveAttribute('aria-disabled', 'false'));++ api.getBeeperStatus.mockResolvedValue(status({ tripped: true, reason: 'synthetic loop', trippedAt: '2026-09-01T09:00:00.000Z' }));+ act(() => {+ for (const fn of socketMock.handlers.get('beeper:invalidate') || []) {+ fn({ kind: 'message.upserted', chatID: 'chat-example-1', ids: ['m1'], seq: 7 });+ }+ });++ await waitFor(() => expect(send).toHaveAttribute('aria-disabled', 'true'));+ expect(send.getAttribute('title')).toMatch(/runaway breaker/);+ expect(send.getAttribute('title')).toContain('synthetic loop');+ });+});++describe('realtime', () => {+ // TWO subscriptions on the same shared socket, not one: the page's own+ // `useBeeperRealtime` (drives the rail's liveness dot and invalidation+ // refetches) and the one `useBeeperOutbox` opens internally (#53, wired on+ // #36's design) so the composer's send confirmation reacts to+ // `message.upserted` without waiting on the page's debounced refetch. Both+ // emit `beeper:subscribe` at mount and on every reconnect. Server-side this+ // is a no-op redundancy, not a bug: `beeperSubscribers` is a `Set` keyed on+ // the physical socket, so a second subscribe from the same socket dedupes,+ // and both hook instances share BeeperChatSurface's mount lifecycle, so+ // there is no unmount race where one instance's `beeper:unsubscribe` could+ // kill the other's subscription out from under it.+ it('subscribes on both realtime hooks and RE-SUBSCRIBES on every socket connect, so a reconnect is not silently dead', async () => {+ renderTab();+ await screen.findByText('Nothing here');+ expect(socketMock.emitted.filter(([event]) => event === 'beeper:subscribe')).toHaveLength(2);++ act(() => { for (const fn of socketMock.handlers.get('connect') || []) fn(); });+ expect(socketMock.emitted.filter(([event]) => event === 'beeper:subscribe')).toHaveLength(4);+ });++ it('refetches the list and the open thread after an invalidation frame', async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ try {+ renderTab(`/messages/beeper/${CONV_A}`);+ // Settle every mount fetch inside act() before measuring — otherwise the+ // refetch assertion races the initial load rather than the frame.+ await act(async () => { await vi.advanceTimersByTimeAsync(0); });+ await act(async () => {});+ const listCalls = api.getBeeperConversations.mock.calls.length;+ const threadCalls = api.getBeeperMessages.mock.calls.length;++ act(() => {+ for (const fn of socketMock.handlers.get('beeper:invalidate') || []) {+ fn({ kind: 'message.upserted', chatID: 'chat-example-1', ids: ['m1'], seq: 4 });+ }+ });+ await act(async () => { await vi.advanceTimersByTimeAsync(400); });++ expect(api.getBeeperConversations.mock.calls.length).toBeGreaterThan(listCalls);+ expect(api.getBeeperMessages.mock.calls.length).toBeGreaterThan(threadCalls);+ } finally {+ vi.useRealTimers();+ }+ });++ // PERF-6/BEEP-5: the open thread used to refetch on ANY frame, discarding+ // paged-in history for traffic in some other chat entirely — `onInvalidate`+ // ignored the frame `useBeeperRealtime` already handed it. The list and+ // networks still refetch unconditionally (their previews/unread counts DO+ // change for any chat); only the thread refetch is now frame-scoped.+ it('does not refetch the open thread on an invalidation frame for another chat', async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ try {+ renderTab(`/messages/beeper/${CONV_A}`);+ await act(async () => { await vi.advanceTimersByTimeAsync(0); });+ await act(async () => {});+ const listCalls = api.getBeeperConversations.mock.calls.length;+ const threadCalls = api.getBeeperMessages.mock.calls.length;++ act(() => {+ for (const fn of socketMock.handlers.get('beeper:invalidate') || []) {+ // CONV_A's fixture sourceChatId is 'chat-example-1' — this names a+ // different chat entirely.+ fn({ kind: 'message.upserted', chatID: 'chat-some-other-chat', ids: ['m9'], seq: 5 });+ }+ });+ await act(async () => { await vi.advanceTimersByTimeAsync(2000); });++ expect(api.getBeeperConversations.mock.calls.length).toBeGreaterThan(listCalls);+ expect(api.getBeeperMessages.mock.calls.length).toBe(threadCalls);+ } finally {+ vi.useRealTimers();+ }+ });++ it('refetches the open thread on a frame naming its chat, or with no chatID at all', async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ try {+ renderTab(`/messages/beeper/${CONV_A}`);+ await act(async () => { await vi.advanceTimersByTimeAsync(0); });+ await act(async () => {});++ let threadCalls = api.getBeeperMessages.mock.calls.length;+ act(() => {+ for (const fn of socketMock.handlers.get('beeper:invalidate') || []) {+ fn({ kind: 'message.upserted', chatID: 'chat-example-1', ids: ['m1'], seq: 6 });+ }+ });+ await act(async () => { await vi.advanceTimersByTimeAsync(2000); });+ expect(api.getBeeperMessages.mock.calls.length).toBeGreaterThan(threadCalls);++ // A frame this vague (no chatID at all) could be about anything, so the+ // safe read is "maybe this thread" rather than "not this thread".+ threadCalls = api.getBeeperMessages.mock.calls.length;+ act(() => {+ for (const fn of socketMock.handlers.get('beeper:invalidate') || []) {+ fn({ kind: 'chat.upserted', chatID: null, ids: [], seq: 7 });+ }+ });+ await act(async () => { await vi.advanceTimersByTimeAsync(2000); });+ expect(api.getBeeperMessages.mock.calls.length).toBeGreaterThan(threadCalls);+ } finally {+ vi.useRealTimers();+ }+ });++ // PERF-6/BEEP-5, the additive half: a frame in scope must not replace the+ // thread wholesale — that discards whatever "Load earlier messages" already+ // paged in and resets the cursor. The fix fetches just the first page and+ // merges it into the HEAD by id.+ it('merges an in-scope invalidation refetch into the head, keeping paged-in history and the cursor', async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ try {+ const newest = {+ id: 'm1', conversationId: CONV_A, senderId: 'user-1', body: 'Placeholder newest message',+ sentAt: '2026-09-01T10:00:00.000Z', attachments: [],+ };+ const older = {+ id: 'm-older', conversationId: CONV_A, senderId: 'user-1', body: 'Placeholder older message',+ sentAt: '2026-09-01T08:00:00.000Z', attachments: [],+ };+ api.getBeeperMessages.mockResolvedValueOnce({ messages: [newest], nextCursor: 'cursor-1' });+ renderTab(`/messages/beeper/${CONV_A}`);+ await screen.findByText('Placeholder newest message');++ api.getBeeperMessages.mockResolvedValueOnce({ messages: [older], nextCursor: null });+ fireEvent.click(screen.getByRole('button', { name: 'Load earlier messages' }));+ await screen.findByText('Placeholder older message');++ // The refresh brings back an UPDATED copy of the same newest message —+ // same id, new body — and nothing else new.+ api.getBeeperMessages.mockResolvedValueOnce({+ messages: [{ ...newest, body: 'Placeholder newest message, edited' }],+ nextCursor: 'should-be-ignored-by-a-head-only-merge',+ });+ act(() => {+ for (const fn of socketMock.handlers.get('beeper:invalidate') || []) {+ fn({ kind: 'message.upserted', chatID: 'chat-example-1', ids: ['m1'], seq: 9 });+ }+ });+ await act(async () => { await vi.advanceTimersByTimeAsync(2000); });++ expect(await screen.findByText('Placeholder newest message, edited')).toBeInTheDocument();+ // Updated in place, not duplicated.+ expect(screen.queryByText('Placeholder newest message')).toBeNull();+ // The paged-in older message survives the merge.+ expect(screen.getByText('Placeholder older message')).toBeInTheDocument();+ // The cursor from the additive refresh is ignored — it was already+ // nulled by the earlier "Load earlier messages" and stays that way.+ expect(screen.queryByRole('button', { name: 'Load earlier messages' })).toBeNull();+ } finally {+ vi.useRealTimers();+ }+ });++ // PERF-10: the debounce had no maximum wait, so a sustained frame stream —+ // each one arriving inside the previous frame's 350ms coalescing window —+ // reset it forever and the view never refreshed at all.+ it('still refetches within the bounded max wait despite a sustained stream of invalidation frames', async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ try {+ renderTab(`/messages/beeper/${CONV_A}`);+ await act(async () => { await vi.advanceTimersByTimeAsync(0); });+ await act(async () => {});+ const listCalls = api.getBeeperConversations.mock.calls.length;++ // A frame every 200ms, well inside the 350ms debounce, for 2.4s total —+ // past the 2s ceiling.+ for (let i = 0; i < 12; i += 1) {+ act(() => {+ for (const fn of socketMock.handlers.get('beeper:invalidate') || []) {+ fn({ kind: 'message.upserted', chatID: 'chat-example-1', ids: [`m${i}`], seq: i + 1 });+ }+ });+ // eslint-disable-next-line no-await-in-loop+ await act(async () => { await vi.advanceTimersByTimeAsync(200); });+ }++ expect(api.getBeeperConversations.mock.calls.length).toBeGreaterThan(listCalls);+ } finally {+ vi.useRealTimers();+ }+ });++ it('renders the liveness dot from the transport state and never as offline before it reports', async () => {+ api.getBeeperStatus.mockResolvedValue({ tokenConfigured: true, reachable: true, accounts: [], realtime: null });+ renderTab();+ await screen.findByText('Nothing here');+ expect(screen.queryByTestId('connection-status-dot')).toBeNull();++ act(() => {+ for (const fn of socketMock.handlers.get('beeper:realtime') || []) fn({ state: 'connected' });+ });+ expect(await screen.findByTestId('connection-status-dot')).toHaveAttribute('data-status', 'connected');+ });+});++describe('thread pagination', () => {+ it('sends the cursor on the second call and renders both pages', async () => {+ api.getBeeperMessages.mockResolvedValueOnce({+ messages: [{ id: 'm1', conversationId: CONV_A, senderId: 'user-1', body: 'Placeholder page one', sentAt: '2026-09-01T10:00:00.000Z', attachments: [] }],+ nextCursor: 'cursor-1',+ });+ renderTab(`/messages/beeper/${CONV_A}`);+ await screen.findByText('Placeholder page one');++ api.getBeeperMessages.mockResolvedValueOnce({+ messages: [{ id: 'm0', conversationId: CONV_A, senderId: 'user-1', body: 'Placeholder page two', sentAt: '2026-09-01T09:00:00.000Z', attachments: [] }],+ nextCursor: null,+ });+ fireEvent.click(screen.getByRole('button', { name: 'Load earlier messages' }));++ await screen.findByText('Placeholder page two');+ expect(api.getBeeperMessages).toHaveBeenLastCalledWith(CONV_A, { cursor: 'cursor-1' }, { silent: true });+ expect(screen.getByText('Placeholder page one')).toBeInTheDocument();+ // The cursor came back null, so there is nothing further to page in.+ expect(screen.queryByRole('button', { name: 'Load earlier messages' })).toBeNull();+ });++ // Finding T3: the thread-pagination generation guard used to return early+ // on a stale response WITHOUT clearing `loadingMore`, so "Load earlier+ // messages" rendered permanently disabled from that point on — even for a+ // conversation switched to AFTER the stale request was issued.+ it('leaves Load-more enabled on the new conversation when an old load-more resolves after a conversation switch', async () => {+ api.getBeeperConversations.mockResolvedValue({+ conversations: [+ conversation({ id: CONV_A, title: 'Example A', sourceChatId: 'chat-example-1' }),+ conversation({ id: CONV_B, title: 'Example B', sourceChatId: 'chat-example-2' }),+ ],+ nextCursor: null,+ });+ api.getBeeperConversation.mockImplementation((id) => Promise.resolve(+ id === CONV_B+ ? conversation({ id: CONV_B, title: 'Example B', sourceChatId: 'chat-example-2' })+ : conversation({ id: CONV_A, title: 'Example A', sourceChatId: 'chat-example-1' }),+ ));++ let releaseOldPage;+ const oldPage = new Promise((resolve) => { releaseOldPage = resolve; });+ api.getBeeperMessages.mockImplementation((id, opts) => {+ if (id === CONV_A && !opts?.cursor) {+ return Promise.resolve({+ messages: [{ id: 'm1', conversationId: CONV_A, senderId: 'user-1', body: 'Placeholder A newest', sentAt: '2026-09-01T10:00:00.000Z', attachments: [] }],+ nextCursor: 'cursor-a',+ });+ }+ if (id === CONV_A && opts?.cursor === 'cursor-a') return oldPage;+ if (id === CONV_B) {+ return Promise.resolve({+ messages: [{ id: 'm2', conversationId: CONV_B, senderId: 'user-1', body: 'Placeholder B newest', sentAt: '2026-09-01T09:00:00.000Z', attachments: [] }],+ nextCursor: 'cursor-b',+ });+ }+ return Promise.resolve({ messages: [], nextCursor: null });+ });++ renderTab(`/messages/beeper/${CONV_A}`);+ await screen.findByText('Placeholder A newest');++ fireEvent.click(screen.getByRole('button', { name: 'Load earlier messages' }));+ await waitFor(() => expect(api.getBeeperMessages).toHaveBeenLastCalledWith(CONV_A, { cursor: 'cursor-a' }, { silent: true }));++ // Switch conversations while A's load-more is still in flight.+ fireEvent.click(screen.getByText('Example B'));+ await screen.findByText('Placeholder B newest');+ const loadMoreForB = await screen.findByRole('button', { name: 'Load earlier messages' });++ releaseOldPage({+ messages: [{ id: 'm-old', conversationId: CONV_A, senderId: 'user-1', body: 'Placeholder A older', sentAt: '2026-09-01T08:00:00.000Z', attachments: [] }],+ nextCursor: null,+ });+ // The finally clause must clear `loadingMore` even though the generation+ // guard drops the stale response itself.+ await waitFor(() => expect(loadMoreForB).toBeEnabled());+ expect(screen.queryByText('Placeholder A older')).toBeNull();+ });+});++describe('list pagination (Load more)', () => {+ // Finding T5: `loadMoreConversations` had no in-flight latch — mirroring+ // `submittingRef` in `useBeeperOutbox.js` — so two clicks landing inside one+ // render both read "not loading yet" and both fired the same cursor page.+ it('issues exactly one extra page request when Load more is clicked twice inside one act()', async () => {+ api.getBeeperConversations+ .mockResolvedValueOnce({ conversations: [conversation({ id: CONV_A, title: 'Example A' })], nextCursor: 'cursor-1' })+ .mockResolvedValueOnce({ conversations: [conversation({ id: CONV_B, title: 'Example B' })], nextCursor: null });++ renderTab();+ await screen.findByText('Example A');+ const loadMore = screen.getByRole('button', { name: 'Load more' });++ await act(async () => {+ fireEvent.click(loadMore);+ fireEvent.click(loadMore);+ await Promise.resolve();+ });++ await screen.findByText('Example B');+ // One mount-time load plus exactly one page fetch — not two.+ expect(api.getBeeperConversations).toHaveBeenCalledTimes(2);+ expect(screen.getAllByText('Example B')).toHaveLength(1);+ });+});++describe('the two wired rail controls', () => {+ it('archives through the API and reflects the value the server returned', async () => {+ api.getBeeperConversation.mockResolvedValue(conversation({ title: 'Example Contact' }));+ api.setBeeperConversationArchived.mockResolvedValue(conversation({ title: 'Example Contact', isArchived: true }));+ renderTab(`/messages/beeper/${CONV_A}`);++ const button = await screen.findByRole('button', { name: 'Archive', hidden: false });+ // Two controls carry the Archive name (the rail scope and the thread+ // action); the thread action is the one inside the header row.+ const threadArchive = screen.getAllByRole('button', { name: 'Archive' }).at(-1);+ expect(button).toBeTruthy();+ act(() => { threadArchive.click(); });++ await waitFor(() => expect(api.setBeeperConversationArchived).toHaveBeenCalledWith(CONV_A, true, { silent: true }));+ expect(await screen.findByRole('button', { name: 'Unarchive' })).toBeInTheDocument();+ });++ it('reports a failed write once and does not retry it', async () => {+ api.getBeeperConversation.mockResolvedValue(conversation({ title: 'Example Contact' }));+ api.setBeeperConversationLowPriority.mockRejectedValue(+ Object.assign(new Error('Beeper request failed: connection refused'), { status: 503, context: { retryable: false } }),+ );+ renderTab(`/messages/beeper/${CONV_A}`);++ const button = await screen.findByRole('button', { name: 'Low priority', hidden: false });+ const threadControl = screen.getAllByRole('button', { name: 'Low priority' }).at(-1);+ expect(button).toBeTruthy();+ act(() => { threadControl.click(); });++ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Beeper request failed: connection refused'));+ expect(api.setBeeperConversationLowPriority).toHaveBeenCalledTimes(1);+ });+});++// The LOCAL "seen in PortOS" watermark (#83) — the fix for opening an unread+// thread leaving its badge untouched. This NEVER reaches Beeper: no PATCH,+// no read receipt — see `markBeeperConversationSeen` (`apiBeeper.js`) and its+// server-side `markConversationSeen`.+describe('the local "seen in PortOS" watermark (#83)', () => {+ it('clears the row\'s own badge on open and calls the local mark-seen endpoint, never a Beeper write', async () => {+ api.getBeeperConversations.mockResolvedValue({+ conversations: [conversation({ title: 'Example Unread', unreadCount: 3 })],+ nextCursor: null,+ });+ api.getBeeperConversation.mockResolvedValue(conversation({ title: 'Example Unread', unreadCount: 3 }));++ renderTab();++ const row = (await screen.findByText('Example Unread')).closest('button');+ expect(within(row).getByText('3')).toBeInTheDocument();++ fireEvent.click(row);++ await waitFor(() => expect(api.markBeeperConversationSeen).toHaveBeenCalledWith(CONV_A, { silent: true }));+ // Optimistic: the row's own badge is gone as soon as the thread has+ // loaded, without waiting on the mark-seen POST's own round trip.+ await waitFor(() => expect(within(row).queryByText('3')).toBeNull());+ // Never a write to Beeper — this is a local read-model change only.+ expect(api.setBeeperConversationArchived).not.toHaveBeenCalled();+ expect(api.setBeeperConversationLowPriority).not.toHaveBeenCalled();+ });++ it('re-marks seen when a new message lands in the thread that is already open', async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ try {+ renderTab(`/messages/beeper/${CONV_A}`);+ await act(async () => { await vi.advanceTimersByTimeAsync(0); });+ await act(async () => {});+ await waitFor(() => expect(api.markBeeperConversationSeen).toHaveBeenCalledWith(CONV_A, { silent: true }));+ api.markBeeperConversationSeen.mockClear();++ api.getBeeperMessages.mockResolvedValueOnce({+ messages: [{+ id: 'm-new', conversationId: CONV_A, senderId: 'user-1', body: 'Placeholder new message',+ sentAt: '2026-09-01T11:00:00.000Z', attachments: [],+ }],+ nextCursor: null,+ });+ act(() => {+ for (const fn of socketMock.handlers.get('beeper:invalidate') || []) {+ fn({ kind: 'message.upserted', chatID: 'chat-example-1', ids: ['m-new'], seq: 10 });+ }+ });+ await act(async () => { await vi.advanceTimersByTimeAsync(2000); });++ await waitFor(() => expect(api.markBeeperConversationSeen).toHaveBeenCalledWith(CONV_A, { silent: true }));+ } finally {+ vi.useRealTimers();+ }+ });++ // PR 86's sweep emits an invalidation frame with `chatID: null` once per+ // account, which this surface's debounce treats as "could be about+ // anything" and refetches the open thread regardless — so a refetch that+ // comes back with nothing genuinely new (an UPDATED copy of an+ // already-rendered message, e.g. an edit or the eventual `message.upserted`+ // confirmation of a message already on screen) must not re-POST mark-seen.+ // Without this a multi-account sweep would fire one no-op mark-seen call+ // per account for a thread with nothing new in it.+ it('does not re-mark seen when an invalidation refetch returns only already-known messages', async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ try {+ const known = {+ id: 'm1', conversationId: CONV_A, senderId: 'user-1', body: 'Placeholder known message',+ sentAt: '2026-09-01T10:00:00.000Z', attachments: [],+ };+ api.getBeeperMessages.mockResolvedValue({ messages: [known], nextCursor: null });++ renderTab(`/messages/beeper/${CONV_A}`);+ await act(async () => { await vi.advanceTimersByTimeAsync(0); });+ await act(async () => {});+ await waitFor(() => expect(api.markBeeperConversationSeen).toHaveBeenCalledWith(CONV_A, { silent: true }));+ api.markBeeperConversationSeen.mockClear();++ // Same id back, just an updated body — not new activity.+ api.getBeeperMessages.mockResolvedValueOnce({+ messages: [{ ...known, body: 'Placeholder known message, edited' }],+ nextCursor: null,+ });+ act(() => {+ for (const fn of socketMock.handlers.get('beeper:invalidate') || []) {+ fn({ kind: 'chat.upserted', chatID: null, ids: [], seq: 11 });+ }+ });+ await act(async () => { await vi.advanceTimersByTimeAsync(2000); });++ expect(api.markBeeperConversationSeen).not.toHaveBeenCalled();+ } finally {+ vi.useRealTimers();+ }+ });++ it('does not let a failed mark-seen call break opening the thread', async () => {+ api.markBeeperConversationSeen.mockRejectedValue(new Error('offline'));+ api.getBeeperConversation.mockResolvedValue(conversation({ title: 'Example Contact' }));+ renderTab(`/messages/beeper/${CONV_A}`);+ expect(await screen.findByText('Example Contact')).toBeInTheDocument();+ });+});++describe('the inline Tribe link action', () => {+ it('links a participant to an existing Tribe person', async () => {+ api.getTribePeople.mockResolvedValue([{ id: '55555555-5555-4555-8555-555555555555', name: 'Alex Example' }]);+ api.getBeeperConversation.mockResolvedValue(conversation({+ title: 'Example Contact',+ participants: [{ sourceUserId: 'user-1', displayName: 'Sam Example', handle: '+15550100', tribePersonId: null, tribePersonName: null, observedVia: 'participant-list' }],+ }));+ api.linkBeeperParticipant.mockResolvedValue({ participant: {}, displacedPersonId: null });++ renderTab(`/messages/beeper/${CONV_A}`);++ const peopleToggle = await screen.findByRole('button', { name: 'People' });+ act(() => { peopleToggle.click(); });+ // The search-first picker (#98 part B) replaced the `<select>` + Link+ // button: opening the results and clicking a match IS the link action.+ const picker = await screen.findByLabelText('Link Sam Example to a Tribe person');+ act(() => { picker.focus(); });+ const result = await screen.findByRole('option', { name: 'Alex Example' });+ act(() => { fireEvent.mouseDown(result); });++ await waitFor(() => expect(api.linkBeeperParticipant).toHaveBeenCalledWith(+ { conversationId: CONV_A, sourceUserId: 'user-1', personId: '55555555-5555-4555-8555-555555555555' },+ { silent: true },+ ));+ });++ // Fork issue #97 part A: "Create new…" opens the confirm-and-rename form+ // instead of posting immediately — this pins the wiring from the form's+ // Create button all the way down to `createTribePersonFromBeeper`.+ it('creates a Tribe person with the edited name, ring and relationship from the confirm-and-rename form', async () => {+ api.getTribePeople.mockResolvedValue([]);+ api.getBeeperConversation.mockResolvedValue(conversation({+ title: 'Example Contact',+ participants: [{ sourceUserId: 'user-1', displayName: 'Sam Example', handle: '', tribePersonId: null, tribePersonName: null, observedVia: 'participant-list' }],+ }));+ api.createTribePersonFromBeeper.mockResolvedValue({+ person: { id: 'new-person-1', name: 'Corrected Name' },+ participant: {},+ created: true,+ displacedPersonId: null,+ });++ renderTab(`/messages/beeper/${CONV_A}`);++ const peopleToggle = await screen.findByRole('button', { name: 'People' });+ act(() => { peopleToggle.click(); });+ const picker = await screen.findByLabelText('Link Sam Example to a Tribe person');+ act(() => { picker.focus(); });+ const createNew = await screen.findByRole('option', { name: /Create new/ });+ act(() => { fireEvent.mouseDown(createNew); });++ const nameInput = await screen.findByLabelText('Name');+ act(() => { fireEvent.change(nameInput, { target: { value: 'Corrected Name' } }); });+ act(() => { fireEvent.change(screen.getByLabelText('Ring'), { target: { value: 'core' } }); });+ act(() => { fireEvent.change(screen.getByLabelText('Relationship'), { target: { value: 'Neighbor' } }); });+ act(() => { fireEvent.click(screen.getByRole('button', { name: 'Create' })); });++ await waitFor(() => expect(api.createTribePersonFromBeeper).toHaveBeenCalledWith(+ { conversationId: CONV_A, sourceUserId: 'user-1', name: 'Corrected Name', ring: 'core', relationship: 'Neighbor' },+ { silent: true },+ ));+ });+});++// Fork issue #97 part B: Change/Unlink on an already-linked participant.+describe('the inline Tribe unlink/change actions', () => {+ it('unlinks a linked participant', async () => {+ api.getTribePeople.mockResolvedValue([{ id: '55555555-5555-4555-8555-555555555555', name: 'Alex Example' }]);+ api.getBeeperConversation.mockResolvedValue(conversation({+ title: 'Example Contact',+ participants: [{+ sourceUserId: 'user-1', displayName: 'Sam Example', handle: '+15550100',+ tribePersonId: '55555555-5555-4555-8555-555555555555', tribePersonName: 'Alex Example', observedVia: 'participant-list',+ }],+ }));+ api.unlinkBeeperParticipant.mockResolvedValue({+ participant: {}, unlinkedPersonId: '55555555-5555-4555-8555-555555555555', removedClaims: 2,+ });++ renderTab(`/messages/beeper/${CONV_A}`);++ const peopleToggle = await screen.findByRole('button', { name: 'People' });+ act(() => { peopleToggle.click(); });+ const unlinkButton = await screen.findByRole('button', { name: 'Unlink' });+ act(() => { unlinkButton.click(); });++ await waitFor(() => expect(api.unlinkBeeperParticipant).toHaveBeenCalledWith(+ { conversationId: CONV_A, sourceUserId: 'user-1' },+ { silent: true },+ ));+ });++ it('re-links via a single POST /tribe/beeper/link call when Change picks a different person', async () => {+ api.getTribePeople.mockResolvedValue([+ { id: '55555555-5555-4555-8555-555555555555', name: 'Alex Example' },+ { id: '66666666-6666-4666-8666-666666666666', name: 'Blair Sample' },+ ]);+ api.getBeeperConversation.mockResolvedValue(conversation({+ title: 'Example Contact',+ participants: [{+ sourceUserId: 'user-1', displayName: 'Sam Example', handle: '+15550100',+ tribePersonId: '55555555-5555-4555-8555-555555555555', tribePersonName: 'Alex Example', observedVia: 'participant-list',+ }],+ }));+ api.linkBeeperParticipant.mockResolvedValue({ participant: {}, displacedPersonId: null });++ renderTab(`/messages/beeper/${CONV_A}`);++ const peopleToggle = await screen.findByRole('button', { name: 'People' });+ act(() => { peopleToggle.click(); });+ const changeButton = await screen.findByRole('button', { name: 'Change' });+ act(() => { changeButton.click(); });+ const picker = await screen.findByLabelText('Link Sam Example to a Tribe person');+ act(() => { picker.focus(); });+ const result = await screen.findByRole('option', { name: 'Blair Sample' });+ act(() => { fireEvent.mouseDown(result); });++ await waitFor(() => expect(api.linkBeeperParticipant).toHaveBeenCalledWith(+ { conversationId: CONV_A, sourceUserId: 'user-1', personId: '66666666-6666-4666-8666-666666666666' },+ { silent: true },+ ));+ expect(api.unlinkBeeperParticipant).not.toHaveBeenCalled();+ });+});++// Beeper's consent screen redirects the BROWSER back to this page, never to+// the settings drawer, so the page shell — not the panel inside the drawer —+// is what has to read the outcome off the URL (#31).+describe('the OAuth outcome carried back on the URL', () => {+ it('reports a successful connect', async () => {+ renderTab('/messages/beeper?beeperConnected=1');+ await waitFor(() => expect(toast.success).toHaveBeenCalledWith('Beeper connected'));+ expect(toast.error).not.toHaveBeenCalled();+ });++ it('reports a mapped failure sentence for access_denied, with the code only as a parenthetical, and opens the settings drawer', async () => {+ renderTab('/messages/beeper?beeperOauthError=access_denied');+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Beeper connect was not approved (access_denied)'));+ expect(await screen.findByRole('heading', { name: 'Beeper Settings' })).toBeInTheDocument();+ });++ it('falls back to a generic sentence plus the code for an unrecognized OAuth error', async () => {+ renderTab('/messages/beeper?beeperOauthError=temporarily_unavailable');+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Beeper connect failed (temporarily_unavailable)'));+ });+});++// The lazy attachment mirror (#37) at the page boundary: what the thread+// renders, and what the purge confirmation demands before it deletes bytes.+describe('attachment mirror', () => {+ const imageAttachment = (overrides = {}) => ({+ messageId: 'm1',+ idx: 0,+ mxcId: 'mxc://example.invalid/abc',+ mimeType: 'image/png',+ fileName: 'example.png',+ byteLength: 2048,+ width: null,+ height: null,+ stored: false,+ keep: false,+ unavailable: false,+ overCap: false,+ maxBytes: 32 * 1024 * 1024,+ ...overrides,+ });++ const withAttachment = (attachment) => {+ api.getBeeperConversations.mockResolvedValue({ conversations: [conversation()], nextCursor: null });+ api.getBeeperMessages.mockResolvedValue({+ messages: [{+ id: 'm1', conversationId: CONV_A, senderId: 'user-1', body: 'Placeholder body',+ sentAt: '2026-09-01T10:00:00.000Z', attachments: [attachment],+ }],+ nextCursor: null,+ });+ };++ it('renders an image lazily against the mirror route — the request IS the fetch-on-view', async () => {+ withAttachment(imageAttachment());+ renderTab(`/messages/beeper/${CONV_A}`);++ const image = await screen.findByAltText('example.png');+ expect(image).toHaveAttribute('src', '/api/beeper/attachments/m1/0');+ expect(image).toHaveAttribute('loading', 'lazy');+ });++ it('renders an over-cap attachment as a placeholder naming the size, with "Fetch anyway"', async () => {+ withAttachment(imageAttachment({ byteLength: 40 * 1024 * 1024, overCap: true }));+ api.fetchBeeperAttachment.mockResolvedValue(imageAttachment({ byteLength: 40 * 1024 * 1024, overCap: true, stored: true }));+ renderTab(`/messages/beeper/${CONV_A}`);++ expect(await screen.findByText(/Larger than the 32 MB mirror limit/)).toBeInTheDocument();+ // Nothing was downloaded on render — the placeholder is not an <img>.+ expect(screen.queryByAltText('example.png')).not.toBeInTheDocument();++ fireEvent.click(screen.getByRole('button', { name: /Fetch anyway/i }));+ await waitFor(() => expect(api.fetchBeeperAttachment).toHaveBeenCalledWith('m1', 0, { silent: true }));+ expect(await screen.findByAltText('example.png')).toBeInTheDocument();+ });++ it('renders an unavailable attachment as a reference and never re-requests it', async () => {+ withAttachment(imageAttachment({ unavailable: true, unavailableReason: 'Failed to download asset' }));+ renderTab(`/messages/beeper/${CONV_A}`);++ expect(await screen.findByText(/Beeper can no longer supply this file/)).toBeInTheDocument();+ expect(screen.queryByAltText('example.png')).not.toBeInTheDocument();+ expect(api.fetchBeeperAttachment).not.toHaveBeenCalled();+ });++ it('renders a video as a generic tile rather than an inline player', async () => {+ withAttachment(imageAttachment({ mimeType: 'video/mp4', fileName: 'example.mp4' }));+ renderTab(`/messages/beeper/${CONV_A}`);++ const link = await screen.findByRole('link', { name: 'example.mp4' });+ expect(link).toHaveAttribute('href', '/api/beeper/attachments/m1/0');+ expect(document.querySelector('video')).toBeNull();+ });++ it('locks one attachment against eviction through the keep toggle', async () => {+ withAttachment(imageAttachment());+ api.setBeeperAttachmentKeep.mockResolvedValue(imageAttachment({ keep: true }));+ renderTab(`/messages/beeper/${CONV_A}`);++ fireEvent.click(await screen.findByRole('button', { name: /Keep this attachment/i }));+ await waitFor(() => expect(api.setBeeperAttachmentKeep).toHaveBeenCalledWith('m1', 0, true, { silent: true }));+ expect(await screen.findByRole('button', { name: /Stop keeping this attachment/i })).toBeInTheDocument();+ });+});++describe('purging one conversation mirror', () => {+ const openThread = async () => {+ api.getBeeperConversations.mockResolvedValue({ conversations: [conversation()], nextCursor: null });+ api.getBeeperConversation.mockResolvedValue(conversation({ attachmentBytes: 4 * 1024 * 1024, attachmentFiles: 3 }));+ renderTab(`/messages/beeper/${CONV_A}`);+ fireEvent.click(await screen.findByRole('button', { name: /^Purge$/ }));+ };++ it('names the conversation and the byte count, and demands the typed word first', async () => {+ await openThread();+ expect(await screen.findByText('Purge this mirror')).toBeInTheDocument();+ expect(screen.getByText(/4 MB of mirrored attachment bytes/)).toBeInTheDocument();+ expect(screen.getByText(/across 3 file\(s\)/)).toBeInTheDocument();++ const confirm = screen.getByRole('button', { name: /Purge mirror/i });+ expect(confirm).toBeDisabled();+ fireEvent.change(screen.getByLabelText(/Type purge to confirm/i), { target: { value: 'nope' } });+ expect(confirm).toBeDisabled();+ expect(api.purgeBeeperConversation).not.toHaveBeenCalled();+ });++ it('purges on the typed confirmation and returns to the list', async () => {+ api.purgeBeeperConversation.mockResolvedValue({+ purged: true, conversationId: CONV_A, messagesRemoved: 12, filesRemoved: 3, bytesFreed: 4194304,+ });+ await openThread();+ fireEvent.change(await screen.findByLabelText(/Type purge to confirm/i), { target: { value: 'purge' } });+ fireEvent.click(screen.getByRole('button', { name: /Purge mirror/i }));++ await waitFor(() => expect(api.purgeBeeperConversation).toHaveBeenCalledWith(CONV_A, { silent: true }));+ expect(await screen.findByText('Pick a conversation')).toBeInTheDocument();+ });++ // CLIENT SEC-2: an unsent draft is written straight to localStorage as the+ // composer changes (`portos-beeper-drafts`), independent of the server-side+ // mirror. A purge only deletes the mirror's messages, so nothing else ever+ // clears that draft entry once its conversation is gone — it would sit in+ // localStorage forever otherwise.+ it('deletes the conversation draft from localStorage on a successful purge', async () => {+ api.getBeeperConversations.mockResolvedValue({ conversations: [conversation()], nextCursor: null });+ api.getBeeperConversation.mockResolvedValue(conversation());+ api.purgeBeeperConversation.mockResolvedValue({+ purged: true, conversationId: CONV_A, messagesRemoved: 12, filesRemoved: 3, bytesFreed: 4194304,+ });+ renderTab(`/messages/beeper/${CONV_A}`);++ const composer = await screen.findByLabelText(/^Message Example Conversation/);+ fireEvent.change(composer, { target: { value: 'Placeholder unsent draft' } });+ await waitFor(() => {+ const stored = JSON.parse(window.localStorage.getItem('portos-beeper-drafts') || '{}');+ expect(stored[CONV_A]).toBe('Placeholder unsent draft');+ });++ fireEvent.click(screen.getByRole('button', { name: /^Purge$/ }));+ fireEvent.change(await screen.findByLabelText(/Type purge to confirm/i), { target: { value: 'purge' } });+ fireEvent.click(screen.getByRole('button', { name: /Purge mirror/i }));++ await waitFor(() => expect(api.purgeBeeperConversation).toHaveBeenCalledWith(CONV_A, { silent: true }));+ await waitFor(() => {+ const stored = JSON.parse(window.localStorage.getItem('portos-beeper-drafts') || '{}');+ expect(stored[CONV_A]).toBeUndefined();+ });+ });+});++// Final live pass: some networks deliver HTML message bodies (Discord, Matrix)+// and the mirror stores what the source sent, so the rail row rendered the tags+// as literal text under the conversation title.+describe('the rail preview', () => {+ it('shows an HTML last message as text, with no tags', async () => {+ api.getBeeperConversations.mockResolvedValue({+ conversations: [conversation({+ lastMessage: {+ id: 'm1', body: '<p>hello <strong>there</strong></p>', isSender: false, isUnsent: false,+ },+ })],+ nextCursor: null,+ });++ renderTab();++ expect(await screen.findByText('hello there')).toBeInTheDocument();+ expect(screen.queryByText(/<strong>/)).not.toBeInTheDocument();+ });++ it('leaves a plain last message alone but decodes its entities', async () => {+ api.getBeeperConversations.mockResolvedValue({+ conversations: [conversation({+ lastMessage: { id: 'm1', body: 'salt & pepper', isSender: false, isUnsent: false },+ })],+ nextCursor: null,+ });++ renderTab();++ expect(await screen.findByText('salt & pepper')).toBeInTheDocument();+ });++ // #81: a chat with no mirrored message yet used to read as "No messages+ // mirrored yet" whether it was genuinely history-less or simply not caught+ // up — indistinguishable from a stale placeholder, and sorted at the top by+ // recency regardless. `lastActivity` is Beeper's own chat-level watermark,+ // mirrored independently of message content, so a recent one with no+ // `lastMessage` is the one signal that the row is still syncing.+ it('shows "Syncing…" for a conversation with recent activity and no mirrored message yet', async () => {+ api.getBeeperConversations.mockResolvedValue({+ conversations: [conversation({+ lastMessage: null,+ lastActivity: new Date(Date.now() - 5 * 60 * 1000).toISOString(),+ })],+ nextCursor: null,+ });++ renderTab();++ expect(await screen.findByText('Syncing…')).toBeInTheDocument();+ expect(screen.queryByText('No messages mirrored yet')).not.toBeInTheDocument();+ });++ it('keeps the honest "No messages mirrored yet" copy when there is no mirrored message and no recent activity', async () => {+ api.getBeeperConversations.mockResolvedValue({+ conversations: [conversation({+ lastMessage: null,+ lastActivity: '2020-01-01T00:00:00.000Z',+ })],+ nextCursor: null,+ });++ renderTab();++ expect(await screen.findByText('No messages mirrored yet')).toBeInTheDocument();+ expect(screen.queryByText('Syncing…')).not.toBeInTheDocument();+ });++ it('keeps the honest empty copy when there is neither a mirrored message nor any activity at all', async () => {+ api.getBeeperConversations.mockResolvedValue({+ conversations: [conversation({ lastMessage: null, lastActivity: null })],+ nextCursor: null,+ });++ renderTab();++ expect(await screen.findByText('No messages mirrored yet')).toBeInTheDocument();+ });+});++// A guard, not a formality: this file is the one place a real conversation,+// handle or contact name could slip into a PUBLIC repo while developing against+// a live install (root AGENTS.md, Sensitive Data & Privacy).+//+// It scans this file's own SOURCE rather than a hand-listed set of fixtures.+// Most fixtures here are written inline inside a single test — participants,+// messages, Tribe people, network rosters — so a guard that enumerates the two+// shared ones stops guarding the moment somebody pastes a third.+describe('fixture hygiene', () => {+ it('carries no value that could have come from a running instance', async () => {+ const { readFileSync } = await import('node:fs');+ const source = readFileSync(new URL(import.meta.url), 'utf8');+ // Everything above this block. The patterns below necessarily spell out+ // the shapes they forbid, so scanning them would fail on the guard itself.+ const corpus = source.slice(0, source.indexOf("describe('fixture hygiene'"));+ // No e164-looking number outside the reserved 555-01xx block, no email+ // outside example.com, no bare hostname, no absolute home path.+ expect(corpus).not.toMatch(/\+(?!1555010)\d{7,}/);+ expect(corpus).not.toMatch(/@(?!example\.com)[\w.-]+\.[a-z]{2,}/i);+ expect(corpus).not.toMatch(/\.ts\.net|\.local\b/);+ expect(corpus).not.toMatch(/\/(?:home|Users)\/[a-z]/i);+ // Every human-readable label is explicitly a placeholder.+ expect(conversation().title).toMatch(/Example/);+ });+});diff --git a/client/src/components/messages/beeper/BeeperAttachment.jsx b/client/src/components/messages/beeper/BeeperAttachment.jsxnew file mode 100644index 0000000000..d315d21f28--- /dev/null+++ b/client/src/components/messages/beeper/BeeperAttachment.jsx@@ -0,0 +1,301 @@+import {+ useEffect, useRef, useState,+} from 'react';+import { Download, FileText, Loader2, Lock, LockOpen, Paperclip, Video } from 'lucide-react';+import toast from '../../ui/Toast';+import { useLockToggle } from '../../../hooks/useLockToggle';+import { formatBytes } from '../../../utils/formatters';+import {+ beeperAttachmentUrl, fetchBeeperAttachment, setBeeperAttachmentKeep,+} from '../../../services/api';++/**+ * One attachment inside a mirrored Beeper message (#37, decided on #13).+ *+ * **The `<img>` IS the lazy mirror.** `beeperAttachmentUrl` points at an+ * authenticated `/api/beeper/...` route that fetches the bytes from Beeper on a+ * miss and serves them from disk afterwards, so `loading="lazy"` is the whole+ * "download on first human view" rule: nothing is transferred for a thread+ * nobody scrolls to, and nothing needs a second mechanism to decide when a+ * view happened. A bulk backfill exists, but it is a user action behind a+ * consent step in the settings drawer, never something a render kicks off.+ *+ * Four states, and none of them is a spinner over an empty box:+ *+ * - **Over cap.** A known size above the 32 MiB ceiling renders a labelled+ * placeholder that NAMES the size and offers "Fetch anyway". The row is+ * never dropped — #13 is explicit that an over-cap attachment keeps its+ * metadata and its escape hatch.+ * - **Unavailable.** Beeper answers `502` for media the source network has+ * aged out; the mirror stamps that as terminal, so this renders the+ * reference and says why rather than retrying on every paint.+ * - **Failed to load.** Any other fetch failure degrades to the same+ * reference-only row — an attachment that cannot be shown is still a fact+ * about the conversation.+ * - **Video renders a generic tile** rather than an inline player: the+ * mirror has no poster frame (`posterImg` was populated on zero attachments+ * in the live probe) and autoplaying a 30 MB file inside a thread is not+ * what opening a chat should cost.+ *+ * The `keep` lock is the per-attachment exemption from least-recently-viewed+ * eviction — the shared `useLockToggle` optimistic-PATCH shape, so it behaves+ * like every other lock in PortOS.+ */++const isImage = (mimeType) => String(mimeType || '').startsWith('image/') && !String(mimeType).includes('svg');+const isVideo = (mimeType) => String(mimeType || '').startsWith('video/');++const sizeLabel = (bytes) => (bytes === null || bytes === undefined ? 'size unknown' : formatBytes(bytes));++// The wrapper style that reserves an image attachment's box before it loads.+//+// Exported and pure because the width it computes is a `min()`, and the client+// test environment (happy-dom since upstream v2.60.0) drops any declaration+// whose value is a `min()` — the property never reaches the style attribute, so+// a DOM assertion cannot see it in either direction. Asserting the function+// keeps the cap under test rather than trading it for a value the test+// environment happens to serialize: `min()` is what a real browser needs here.+export const hasImageDimensions = (row) => Number.isFinite(row.width) && row.width > 0+ && Number.isFinite(row.height) && row.height > 0;++export const reservedBoxStyle = (row, imgLoaded) => {+ if (!hasImageDimensions(row)) return !imgLoaded ? { width: '8rem', height: '8rem' } : undefined;+ return {+ aspectRatio: `${row.width} / ${row.height}`,+ width: `min(${row.width}px, calc(16rem * ${(row.width / row.height).toFixed(4)}))`,+ maxWidth: '100%',+ };+};++function KeepButton({ attachment, busy, onToggle }) {+ const locked = attachment.keep === true;+ return (+ <button+ type="button"+ disabled={busy}+ onClick={() => onToggle(locked)}+ title={locked+ ? 'Kept — exempt from the attachment budget’s eviction'+ : 'Keep these bytes even when the attachment budget evicts older ones'}+ aria-label={locked ? 'Stop keeping this attachment' : 'Keep this attachment'}+ className="inline-flex min-h-[24px] shrink-0 items-center rounded px-1 text-gray-400 transition-colors hover:text-port-accent disabled:opacity-40"+ >+ {busy ? <Loader2 size={11} className="animate-spin" /> : (locked ? <Lock size={11} className="text-port-accent" /> : <LockOpen size={11} />)}+ </button>+ );+}++/** The reference-only row — the honest fallback for every state without bytes. */+function ReferenceRow({ attachment, note, action, keepControl }) {+ return (+ <div className="mt-1 rounded border border-dashed border-port-border px-2 py-1.5 text-[11px] text-gray-400">+ <div className="flex items-center gap-1.5">+ <Paperclip size={11} className="shrink-0" />+ <span className="min-w-0 flex-1 truncate">+ {attachment.fileName || attachment.mimeType || 'Attachment'}+ </span>+ <span className="shrink-0 text-gray-500">{sizeLabel(attachment.byteLength)}</span>+ {keepControl}+ </div>+ {note && <p className="pt-1 text-[10px] text-gray-500">{note}</p>}+ {action}+ </div>+ );+}++export default function BeeperAttachment({ attachment, onUpdated }) {+ // Local state so a successful "Fetch anyway" swaps the placeholder for the+ // real thing immediately, rather than waiting on a thread refetch (the+ // client convention: update local state after a mutation).+ const [row, setRow] = useState(attachment);+ const [fetching, setFetching] = useState(false);+ const [loadFailed, setLoadFailed] = useState(false);+ // Tracks the in-flight image fetch (#37): the mirror can take up to the 60s+ // server timeout on first view, and an `<img>` with no bytes yet collapses to+ // a 2x2px box for the whole wait — this drives the reserved-space skeleton+ // below instead.+ const [imgLoaded, setImgLoaded] = useState(false);+ const imgRef = useRef(null);+ // The image identity, not the attachment object's identity. A thread+ // refetch (BeeperChatSurface.jsx) and the keep toggle (onUpdated ->+ // applyAttachmentUpdate) both hand down a new-but-equal attachment object+ // for the SAME image. `<img>` keeps its key and `src` across that, so React+ // reuses the same DOM node and no second `load` event fires — resetting+ // `imgLoaded` on every attachment change left the image stuck at+ // `opacity-0` behind a permanent skeleton. Only reset the load state when+ // the image itself changes.+ const identityRef = useRef(null);+ const identity = `${attachment.messageId}:${attachment.idx}`;+ useEffect(() => {+ setRow(attachment);+ if (identityRef.current !== identity) {+ identityRef.current = identity;+ setLoadFailed(false);+ setImgLoaded(false);+ }+ }, [attachment, identity]);++ // Resync from the `<img>` element's own load state rather than trusting+ // React state alone: seeds `imgLoaded` back to true for a reused node whose+ // image was already loaded (the reset above deliberately skips it), and+ // covers a new node whose image happens to finish before this effect runs.+ useEffect(() => {+ if (imgRef.current?.complete && imgRef.current.naturalWidth > 0) {+ setImgLoaded(true);+ }+ }, [row]);++ const applyUpdate = (updated) => {+ setRow(updated);+ onUpdated?.(updated);+ };++ const { busy: keepBusy, toggle: toggleKeep } = useLockToggle({+ patchFn: (next) => setBeeperAttachmentKeep(row.messageId, row.idx, next, { silent: true }),+ onSuccess: (updated) => applyUpdate(updated),+ lockedMessage: 'Attachment kept — the budget will not evict it',+ unlockedMessage: 'Attachment no longer kept',+ errorMessage: 'Could not update the attachment lock',+ });+ const keepControl = <KeepButton attachment={row} busy={keepBusy} onToggle={toggleKeep} />;++ const url = beeperAttachmentUrl(row.messageId, row.idx);++ const handleForceFetch = async () => {+ setFetching(true);+ const updated = await fetchBeeperAttachment(row.messageId, row.idx, { silent: true })+ .catch((err) => {+ toast.error(err?.message || 'Could not fetch this attachment');+ return null;+ });+ setFetching(false);+ if (!updated) return;+ setLoadFailed(false);+ applyUpdate(updated);+ };++ // Over cap and not yet mirrored: the placeholder names the cost before the+ // user decides to pay it.+ if (row.overCap && !row.stored) {+ return (+ <ReferenceRow+ attachment={row}+ keepControl={keepControl}+ note={`Larger than the ${formatBytes(row.maxBytes)} mirror limit — not downloaded automatically.`}+ action={(+ <button+ type="button"+ onClick={handleForceFetch}+ disabled={fetching}+ className="mt-1 inline-flex min-h-[28px] items-center gap-1.5 rounded border border-port-border px-2 text-[11px] text-gray-200 transition-colors hover:border-port-accent disabled:opacity-40"+ >+ {fetching ? <Loader2 size={11} className="animate-spin" /> : <Download size={11} />}+ Fetch anyway+ </button>+ )}+ />+ );+ }++ if (row.unavailable && !row.stored) {+ return (+ <ReferenceRow+ attachment={row}+ keepControl={keepControl}+ note="Beeper can no longer supply this file — the network it came from has aged it out."+ />+ );+ }++ if (loadFailed) {+ return (+ <ReferenceRow+ attachment={row}+ keepControl={keepControl}+ note="Could not load these bytes from Beeper right now."+ action={(+ <button+ type="button"+ onClick={handleForceFetch}+ disabled={fetching}+ className="mt-1 inline-flex min-h-[28px] items-center gap-1.5 rounded border border-port-border px-2 text-[11px] text-gray-200 transition-colors hover:border-port-accent disabled:opacity-40"+ >+ {fetching ? <Loader2 size={11} className="animate-spin" /> : <Download size={11} />}+ Retry+ </button>+ )}+ />+ );+ }++ if (isImage(row.mimeType)) {+ // Attachments carry size.width/size.height from the sweep (`beeperSync.js`+ // normalizeAttachment) as plain `width`/`height` fields once persisted.+ //+ // The native width/height attributes are NOT enough to reserve the box in a+ // real browser: the image carries `w-auto` and Tailwind's preflight sets+ // `height: auto`, and an explicit CSS `width`/`height` beats the+ // presentational attributes — so an unloaded image is 0x0 and the absolutely+ // positioned skeleton has nothing to fill. The WRAPPER therefore carries an+ // explicit `aspect-ratio` plus the width the loaded image will actually+ // occupy: its natural width, capped by the `max-h-64` the image is bound to+ // (so a tall image reserves the height it will really take) and by+ // `max-w-full` at the bubble edge. Without dimensions (older rows, or a+ // network that never reported size) the skeleton keeps the fixed neutral+ // box, so the layout still does not collapse to nothing.+ const hasDims = hasImageDimensions(row);+ const reservedBox = reservedBoxStyle(row, imgLoaded);+ return (+ <div className="mt-1">+ <div+ className="relative w-fit max-w-full overflow-hidden rounded-lg border border-port-border"+ style={reservedBox}+ >+ {!imgLoaded && (+ <div+ data-testid="attachment-skeleton"+ aria-hidden="true"+ className="absolute inset-0 animate-pulse bg-port-bg/60"+ />+ )}+ <img+ ref={imgRef}+ src={url}+ alt={row.fileName || 'Attachment'}+ loading="lazy"+ width={hasDims ? row.width : undefined}+ height={hasDims ? row.height : undefined}+ onLoad={() => setImgLoaded(true)}+ onError={() => setLoadFailed(true)}+ className={`block max-h-64 w-auto max-w-full rounded-lg object-contain transition-opacity duration-150 ${imgLoaded ? 'opacity-100' : 'opacity-0'}`}+ />+ </div>+ <div className="flex items-center gap-1.5 pt-0.5 text-[10px] text-gray-500">+ <span className="min-w-0 flex-1 truncate">{row.fileName || row.mimeType}</span>+ <span className="shrink-0">{sizeLabel(row.byteLength)}</span>+ {keepControl}+ </div>+ </div>+ );+ }++ // Video and everything else: a generic tile that names the file and opens it+ // on demand. The link is what triggers the mirror for these — nothing is+ // downloaded just because the thread scrolled past.+ const Icon = isVideo(row.mimeType) ? Video : FileText;+ return (+ <div className="mt-1 flex items-center gap-1.5 rounded border border-port-border bg-port-bg/40 px-2 py-1.5 text-[11px] text-gray-300">+ <Icon size={13} className="shrink-0 text-gray-400" />+ <a+ href={url}+ target="_blank"+ rel="noreferrer"+ className="min-w-0 flex-1 truncate transition-colors hover:text-port-accent"+ >+ {row.fileName || (isVideo(row.mimeType) ? 'Video' : row.mimeType || 'Attachment')}+ </a>+ <span className="shrink-0 text-gray-500">{sizeLabel(row.byteLength)}</span>+ {keepControl}+ </div>+ );+}diff --git a/client/src/components/messages/beeper/BeeperAttachment.test.jsx b/client/src/components/messages/beeper/BeeperAttachment.test.jsxnew file mode 100644index 0000000000..26dda6380f--- /dev/null+++ b/client/src/components/messages/beeper/BeeperAttachment.test.jsx@@ -0,0 +1,156 @@+import { describe, it, expect, vi, afterEach } from 'vitest';+import { render, screen, fireEvent, cleanup } from '@testing-library/react';++/**+ * The lazily-mirrored image attachment (#37, real-browser pass): while bytes+ * are in flight the `<img>` used to collapse to a 2x2px box (`complete: false`)+ * for the whole fetch — up to the 60s server timeout — before the onError path+ * ever rendered the reference row. This locks the reserved-space skeleton that+ * fills that gap, plus the load and error outcomes either side of it.+ */++const api = vi.hoisted(() => ({+ beeperAttachmentUrl: vi.fn((messageId, idx) => `/api/beeper/attachments/${messageId}/${idx}`),+ fetchBeeperAttachment: vi.fn(),+ setBeeperAttachmentKeep: vi.fn(),+}));+vi.mock('../../../services/api', () => api);++const toast = vi.hoisted(() => ({ error: vi.fn(), success: vi.fn() }));+vi.mock('../../ui/Toast', () => ({ default: toast }));++import BeeperAttachment, { reservedBoxStyle } from './BeeperAttachment';++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++const baseAttachment = {+ messageId: 'msg-1',+ idx: 0,+ mimeType: 'image/png',+ fileName: 'photo.png',+ byteLength: 204800,+ overCap: false,+ unavailable: false,+ stored: true,+};++describe('BeeperAttachment — image load lifecycle', () => {+ it('reserves space with a neutral skeleton while the mirror fetch is in flight, sized from width/height', () => {+ render(<BeeperAttachment attachment={{ ...baseAttachment, width: 800, height: 600 }} />);++ const skeleton = screen.getByTestId('attachment-skeleton');+ expect(skeleton).toBeTruthy();++ const img = screen.getByRole('img', { name: 'photo.png' });+ // Native width/height attributes reserve the real aspect ratio before load.+ expect(img).toHaveAttribute('width', '800');+ expect(img).toHaveAttribute('height', '600');+ // Hidden (opacity-0) until it loads, but still mounted so the fetch fires.+ expect(img.className).toContain('opacity-0');+ });++ it('falls back to a fixed neutral box when no width/height is known', () => {+ render(<BeeperAttachment attachment={{ ...baseAttachment, width: null, height: null }} />);++ expect(screen.getByTestId('attachment-skeleton')).toBeTruthy();+ const img = screen.getByRole('img', { name: 'photo.png' });+ expect(img).not.toHaveAttribute('width');+ expect(img).not.toHaveAttribute('height');+ });++ // The real-browser follow-up to the test above: the width/height attributes+ // alone reserve nothing, because the image carries `w-auto` and preflight's+ // `height: auto`, and an explicit CSS width beats a presentational attribute+ // — so an unloaded image is 0x0 and the absolute skeleton has nothing to+ // fill. jsdom cannot measure layout, so what is asserted here is that the+ // wrapper declares the box: an aspect-ratio and a width capped by the+ // `max-h-64` the image is bound to.+ it('reserves the box on the wrapper with an explicit aspect-ratio when dimensions are known', () => {+ render(<BeeperAttachment attachment={{ ...baseAttachment, width: 800, height: 600 }} />);++ const wrapper = screen.getByTestId('attachment-skeleton').parentElement;+ const style = wrapper.getAttribute('style') || '';+ expect(style).toContain('aspect-ratio: 800 / 600');+ expect(style).toContain('max-width: 100%');+ });++ // The width cap is asserted on the pure helper rather than the rendered+ // style attribute: happy-dom drops any declaration whose value is a `min()`,+ // so `width` never reaches the DOM here even though a real browser applies+ // it. Trading the `min()` for something the test environment serializes+ // would change real behaviour to suit the test, so the function is the seam.+ it('caps the reserved width at the natural width and the max-h-64 bound', () => {+ expect(reservedBoxStyle({ width: 800, height: 600 }, false)).toEqual({+ aspectRatio: '800 / 600',+ // 16rem * (800/600) = the width a 4:3 image takes once max-h-64 binds.+ width: 'min(800px, calc(16rem * 1.3333))',+ maxWidth: '100%',+ });+ });++ it('reserves the fixed neutral box from the helper when dimensions are unknown', () => {+ expect(reservedBoxStyle({ width: null, height: null }, false)).toEqual({ width: '8rem', height: '8rem' });+ // Once loaded there is nothing left to reserve — the image is its own box.+ expect(reservedBoxStyle({ width: null, height: null }, true)).toBeUndefined();+ });++ it('keeps the fixed neutral box, and no aspect-ratio, when dimensions are unknown', () => {+ render(<BeeperAttachment attachment={{ ...baseAttachment, width: null, height: null }} />);++ const style = screen.getByTestId('attachment-skeleton').parentElement.getAttribute('style') || '';+ expect(style).not.toContain('aspect-ratio');+ expect(style).toContain('8rem');+ });++ it('hugs the image with a w-fit wrapper rather than stretching to the bubble width', () => {+ render(<BeeperAttachment attachment={{ ...baseAttachment, width: 800, height: 600 }} />);++ const skeleton = screen.getByTestId('attachment-skeleton');+ const wrapper = skeleton.parentElement;+ expect(wrapper.className).toContain('w-fit');+ });++ it('keeps the loaded image visible when the attachment object is replaced but the image identity is unchanged', () => {+ // A thread refetch or the keep toggle's applyAttachmentUpdate hands down a+ // new-but-equal attachment object for the same messageId/idx. The `<img>`+ // keeps its key and `src`, so React reuses the same DOM node and no+ // second `load` event fires — the load state must survive the swap.+ const { rerender } = render(<BeeperAttachment attachment={{ ...baseAttachment, width: 800, height: 600 }} />);++ const img = screen.getByRole('img', { name: 'photo.png' });+ fireEvent.load(img);+ expect(img.className).toContain('opacity-100');++ rerender(<BeeperAttachment attachment={{ ...baseAttachment, width: 800, height: 600, keep: true }} />);++ const after = screen.getByRole('img', { name: 'photo.png' });+ expect(after).toBe(img);+ expect(screen.queryByTestId('attachment-skeleton')).toBeNull();+ expect(after.className).toContain('opacity-100');+ });++ it('swaps the skeleton for the image once it loads', () => {+ render(<BeeperAttachment attachment={{ ...baseAttachment, width: 800, height: 600 }} />);++ const img = screen.getByRole('img', { name: 'photo.png' });+ fireEvent.load(img);++ expect(screen.queryByTestId('attachment-skeleton')).toBeNull();+ expect(img.className).toContain('opacity-100');+ });++ it('renders the reference row with a retry action on load failure, never a stuck skeleton', () => {+ render(<BeeperAttachment attachment={{ ...baseAttachment, width: 800, height: 600 }} />);++ const img = screen.getByRole('img', { name: 'photo.png' });+ fireEvent.error(img);++ expect(screen.queryByTestId('attachment-skeleton')).toBeNull();+ expect(screen.queryByRole('img')).toBeNull();+ expect(screen.getByText(/Could not load these bytes from Beeper/i)).toBeTruthy();+ expect(screen.getByRole('button', { name: /Retry/i })).toBeTruthy();+ });+});diff --git a/client/src/components/messages/beeper/BeeperChatSurface.jsx b/client/src/components/messages/beeper/BeeperChatSurface.jsxnew file mode 100644index 0000000000..eb59cade0b--- /dev/null+++ b/client/src/components/messages/beeper/BeeperChatSurface.jsx@@ -0,0 +1,1063 @@+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('') });++ 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 --git a/client/src/components/messages/beeper/BeeperCreatePersonForm.jsx b/client/src/components/messages/beeper/BeeperCreatePersonForm.jsxnew file mode 100644index 0000000000..4071bf4e7f--- /dev/null+++ b/client/src/components/messages/beeper/BeeperCreatePersonForm.jsx@@ -0,0 +1,112 @@+import { useRef, useState } from 'react';+import { Loader2 } from 'lucide-react';+import { RINGS } from '../../../lib/tribe.js';++/**+ * The inline "Create new…" form for a Beeper participant row (fork issue #97+ * part A). Replaces the old immediate-create path: `BeeperPersonPicker`'s+ * "Create new…" row used to call straight through to+ * `POST /tribe/beeper/link-new` with the participant's own display name —+ * for a network where that name is a handle or a nickname, the person got+ * created under the wrong name with no chance to correct it before the+ * record existed.+ *+ * This form IS that chance. It posts nothing itself — only `onCreate` does,+ * and only when Create is pressed (or Enter is hit with a non-blank name);+ * Cancel (or Escape) discards it and returns the row to the picker.+ *+ * `RINGS` is the exact same list (`client/src/lib/tribe.js`) the Tribe+ * page's own person editor renders its ring `<select>` from, so a person+ * created here looks identical to one created on the Tribe page rather than+ * inventing a second, driftable copy of the ring options.+ */+export default function BeeperCreatePersonForm({+ participant, onCreate, onCancel, disabled = false,+}) {+ const initialName = participant.displayName || participant.handle || '';+ const [name, setName] = useState(initialName);+ const [ring, setRing] = useState('tribe');+ const [relationship, setRelationship] = useState('');+ // Native `autoFocus` (below) fires once, on this element's own mount — the+ // form is a fresh subtree every time the row switches into 'create' mode,+ // so there is no need for a ref+effect dance to refocus on every render.+ const nameRef = useRef(null);++ const trimmedName = name.trim();+ const canCreate = trimmedName.length > 0 && !disabled;++ const submit = () => {+ if (!canCreate) return;+ onCreate({ name: trimmedName, ring, relationship: relationship.trim() });+ };++ // Enter/Escape are handled once on the wrapping group rather than on each+ // field individually — bubbling keydown covers the name field, the ring+ // select and the relationship field alike, so Enter submits and Escape+ // cancels no matter which of the three currently has focus.+ const handleKeyDown = (event) => {+ if (event.key === 'Enter') {+ event.preventDefault();+ submit();+ } else if (event.key === 'Escape') {+ event.preventDefault();+ onCancel();+ }+ };++ return (+ <div+ role="group"+ aria-label={`Create a Tribe person from ${participant.displayName || participant.sourceUserId}`}+ className="flex min-w-0 flex-1 flex-wrap items-center gap-1.5"+ onKeyDown={handleKeyDown}+ >+ <input+ ref={nameRef}+ type="text"+ value={name}+ onChange={(event) => setName(event.target.value)}+ disabled={disabled}+ autoFocus+ required+ placeholder="Name"+ aria-label="Name"+ className="min-w-0 flex-1 rounded border border-port-border bg-port-bg px-1.5 py-1 text-[11px] text-gray-200 placeholder:text-gray-500 focus:outline-none disabled:opacity-50"+ />+ <select+ value={ring}+ onChange={(event) => setRing(event.target.value)}+ disabled={disabled}+ aria-label="Ring"+ className="shrink-0 rounded border border-port-border bg-port-bg px-1 py-1 text-[11px] text-gray-200 focus:outline-none disabled:opacity-50"+ >+ {RINGS.map((option) => <option key={option.id} value={option.id}>{option.label}</option>)}+ </select>+ <input+ type="text"+ value={relationship}+ onChange={(event) => setRelationship(event.target.value)}+ disabled={disabled}+ placeholder="Relationship (optional)"+ aria-label="Relationship"+ className="min-w-0 flex-1 rounded border border-port-border bg-port-bg px-1.5 py-1 text-[11px] text-gray-200 placeholder:text-gray-500 focus:outline-none disabled:opacity-50"+ />+ <button+ type="button"+ onClick={submit}+ disabled={!canCreate}+ aria-label="Create"+ className="shrink-0 rounded border border-port-accent px-2 py-1 text-[11px] text-port-accent transition-colors hover:bg-port-accent/10 disabled:cursor-not-allowed disabled:opacity-40"+ >+ {disabled ? <Loader2 size={11} className="animate-spin" /> : 'Create'}+ </button>+ <button+ type="button"+ onClick={onCancel}+ className="shrink-0 text-[11px] text-gray-400 transition-colors hover:text-gray-200"+ >+ Cancel+ </button>+ </div>+ );+}diff --git a/client/src/components/messages/beeper/BeeperCreatePersonForm.test.jsx b/client/src/components/messages/beeper/BeeperCreatePersonForm.test.jsxnew file mode 100644index 0000000000..e347c9572b--- /dev/null+++ b/client/src/components/messages/beeper/BeeperCreatePersonForm.test.jsx@@ -0,0 +1,126 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { cleanup, fireEvent, render, screen } from '@testing-library/react';+import BeeperCreatePersonForm from './BeeperCreatePersonForm';++/**+ * The confirm-and-rename form "Create new…" opens instead of posting+ * immediately (fork issue #97 part A). Wiring from `BeeperThread` into this+ * component is covered in `BeeperThread.test.jsx`; these pin the form's own+ * contract in isolation.+ */++const PARTICIPANT = { sourceUserId: 'user-1', displayName: 'Sam Example', handle: '+15550100' };++const renderForm = (overrides = {}) => {+ const props = {+ participant: PARTICIPANT,+ onCreate: vi.fn(),+ onCancel: vi.fn(),+ ...overrides,+ };+ const utils = render(<BeeperCreatePersonForm {...props} />);+ return { ...utils, props };+};++afterEach(cleanup);++describe('BeeperCreatePersonForm — prefill and fields', () => {+ it('prefills the name from the participant\'s display name, editable', () => {+ renderForm();+ const nameInput = screen.getByLabelText('Name');+ expect(nameInput).toHaveValue('Sam Example');++ fireEvent.change(nameInput, { target: { value: 'Corrected Name' } });+ expect(nameInput).toHaveValue('Corrected Name');+ });++ it('falls back to the handle when there is no display name', () => {+ renderForm({ participant: { sourceUserId: 'user-2', displayName: '', handle: '@example_handle' } });+ expect(screen.getByLabelText('Name')).toHaveValue('@example_handle');+ });++ it('defaults the ring to tribe and offers every RINGS option', () => {+ renderForm();+ const ringSelect = screen.getByLabelText('Ring');+ expect(ringSelect).toHaveValue('tribe');+ expect(screen.getByRole('option', { name: 'Support' })).toBeInTheDocument();+ expect(screen.getByRole('option', { name: 'Core' })).toBeInTheDocument();+ expect(screen.getByRole('option', { name: 'Tribe' })).toBeInTheDocument();+ expect(screen.getByRole('option', { name: 'Village' })).toBeInTheDocument();+ expect(screen.getByRole('option', { name: 'External' })).toBeInTheDocument();+ });++ it('starts with an empty, optional relationship field', () => {+ renderForm();+ expect(screen.getByLabelText('Relationship')).toHaveValue('');+ });+});++describe('BeeperCreatePersonForm — Create', () => {+ it('is disabled while the name is blank', () => {+ renderForm({ participant: { sourceUserId: 'user-3', displayName: '', handle: '' } });+ expect(screen.getByRole('button', { name: 'Create' })).toBeDisabled();+ });++ it('calls onCreate with the trimmed name, ring and relationship, and only on Create', () => {+ const onCreate = vi.fn();+ renderForm({ onCreate });++ fireEvent.change(screen.getByLabelText('Name'), { target: { value: ' Corrected Name ' } });+ fireEvent.change(screen.getByLabelText('Ring'), { target: { value: 'core' } });+ fireEvent.change(screen.getByLabelText('Relationship'), { target: { value: ' Neighbor ' } });+ expect(onCreate).not.toHaveBeenCalled();++ fireEvent.click(screen.getByRole('button', { name: 'Create' }));++ expect(onCreate).toHaveBeenCalledWith({ name: 'Corrected Name', ring: 'core', relationship: 'Neighbor' });+ });++ it('is disabled while a link is in flight, and never calls onCreate from a click', () => {+ const onCreate = vi.fn();+ renderForm({ onCreate, disabled: true });++ const createButton = screen.getByRole('button', { name: 'Create' });+ expect(createButton).toBeDisabled();+ fireEvent.click(createButton);+ expect(onCreate).not.toHaveBeenCalled();+ });++ it('submits on Enter from the name field', () => {+ const onCreate = vi.fn();+ renderForm({ onCreate });++ fireEvent.keyDown(screen.getByLabelText('Name'), { key: 'Enter' });++ expect(onCreate).toHaveBeenCalledWith({ name: 'Sam Example', ring: 'tribe', relationship: '' });+ });++ it('does not submit on Enter while the name is blank', () => {+ const onCreate = vi.fn();+ renderForm({ onCreate, participant: { sourceUserId: 'user-4', displayName: '', handle: '' } });++ fireEvent.keyDown(screen.getByLabelText('Name'), { key: 'Enter' });++ expect(onCreate).not.toHaveBeenCalled();+ });+});++describe('BeeperCreatePersonForm — Cancel', () => {+ it('calls onCancel on click', () => {+ const onCancel = vi.fn();+ renderForm({ onCancel });++ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));++ expect(onCancel).toHaveBeenCalled();+ });++ it('calls onCancel on Escape from any field', () => {+ const onCancel = vi.fn();+ renderForm({ onCancel });++ fireEvent.keyDown(screen.getByLabelText('Relationship'), { key: 'Escape' });++ expect(onCancel).toHaveBeenCalled();+ });+});diff --git a/client/src/components/messages/beeper/BeeperNetworkLogo.jsx b/client/src/components/messages/beeper/BeeperNetworkLogo.jsxnew file mode 100644index 0000000000..6244407bf9--- /dev/null+++ b/client/src/components/messages/beeper/BeeperNetworkLogo.jsx@@ -0,0 +1,233 @@+/**+ * Network marks for the Beeper chat surface (#35), ported from the #9+ * prototype's `beeperNetworkLogos.jsx`.+ *+ * Inline SVG because PortOS pulls no external brand assets, and simplified+ * because these are read at 14–26px in the rail and as ~15px badges on a row,+ * where silhouette and colour carry recognition rather than detail.+ *+ * **The map is a rendering hint, never a roster.** The rail and the badges are+ * driven by whatever networks the mirror actually holds — #9 records that the+ * development machine's nine networks are an outlier (today's free tier caps a+ * new account at five, and most installs have one), so a network PortOS has+ * never heard of must still render. That is what `Fallback` is for, and it is+ * why nothing in this file is ever used to decide WHICH networks exist.+ */++const Wrap = ({ size, rounded, bg, children, title }) => (+ <span+ role="img"+ aria-label={title}+ title={title}+ className="inline-flex shrink-0 items-center justify-center overflow-hidden"+ style={{ width: size, height: size, borderRadius: rounded ? size * 0.28 : '50%', background: bg }}+ >+ {children}+ </span>+);++const svg = (children, extra = {}) => (+ <svg viewBox="0 0 24 24" width="66%" height="66%" fill="none" {...extra}>{children}</svg>+);++const MARKS = {+ whatsapp: ({ size }) => (+ <Wrap size={size} bg="#25D366" title="WhatsApp">+ {svg(+ <path+ fill="#fff"+ d="M12 2a10 10 0 0 0-8.6 15.1L2 22l5-1.3A10 10 0 1 0 12 2Zm5.1 14c-.2.6-1.2 1.2-1.7 1.2-.5 0-1 .2-3.2-.7-2.7-1.1-4.4-3.9-4.5-4.1-.1-.2-1-1.4-1-2.6s.6-1.8.9-2.1c.2-.2.5-.3.7-.3h.5c.2 0 .4 0 .6.5l.8 2c.1.2.1.4 0 .5l-.3.5-.4.4c-.1.1-.3.3-.1.6.2.3.8 1.3 1.7 2.1 1.1 1 2 1.3 2.3 1.4.3.1.4.1.6-.1l.8-1c.2-.2.4-.2.6-.1l2 .9c.2.1.4.2.4.3.1.1.1.6-.1 1.2Z"+ />,+ )}+ </Wrap>+ ),+ googlemessages: ({ size }) => (+ <Wrap size={size} bg="#1A73E8" title="Google Messages">+ {svg(+ <path+ fill="#fff"+ d="M12 3C6.9 3 3 6.6 3 11c0 2.5 1.3 4.7 3.3 6.2V22l3.6-2.1c.7.1 1.4.2 2.1.2 5.1 0 9-3.6 9-8.1S17.1 3 12 3Z"+ />,+ )}+ </Wrap>+ ),+ discord: ({ size }) => (+ <Wrap size={size} rounded bg="#5865F2" title="Discord">+ {svg(+ <path+ fill="#fff"+ d="M19.3 6.4A15 15 0 0 0 15.6 5.3l-.2.4a13 13 0 0 1 3.3 1.6 12.4 12.4 0 0 0-9.4 0 13 13 0 0 1 3.3-1.6l-.3-.4a15 15 0 0 0-3.7 1.1C5.4 9.7 4.9 12.9 5.1 16a15 15 0 0 0 4.6 2.3l.9-1.4a9.7 9.7 0 0 1-1.5-.7l.4-.3a10.6 10.6 0 0 0 9.2 0l.4.3c-.5.3-1 .5-1.5.7l.9 1.4a15 15 0 0 0 4.6-2.3c.3-3.6-.5-6.8-2.8-9.6ZM9.7 14.2c-.9 0-1.6-.8-1.6-1.8s.7-1.8 1.6-1.8 1.7.8 1.6 1.8c0 1-.7 1.8-1.6 1.8Zm5.9 0c-.9 0-1.6-.8-1.6-1.8s.7-1.8 1.6-1.8 1.7.8 1.6 1.8c0 1-.7 1.8-1.6 1.8Z"+ />,+ )}+ </Wrap>+ ),+ facebook: ({ size }) => (+ <Wrap size={size} bg="#0866FF" title="Messenger">+ {svg(+ <path+ fill="#fff"+ d="M12 3c-5 0-8.8 3.6-8.8 8.4 0 2.7 1.2 5.1 3.2 6.7v3.3l3-1.6c.8.2 1.7.3 2.6.3 5 0 8.8-3.6 8.8-8.4S17 3 12 3Zm.9 11.2-2.3-2.4-4.3 2.4 4.7-5 2.4 2.4L17.6 9l-4.7 5.2Z"+ />,+ )}+ </Wrap>+ ),+ // Signal's real mark is a dotted/dashed ring, not a speech bubble — drawn as+ // a stroked circle with a dash pattern so it stays unmistakable from the+ // solid Google Messages bubble at rail size (#84).+ signal: ({ size }) => (+ <Wrap size={size} bg="#3A76F0" title="Signal">+ {svg(+ <circle+ cx="12"+ cy="12"+ r="7.6"+ fill="none"+ stroke="#fff"+ strokeWidth="2.4"+ strokeLinecap="round"+ strokeDasharray="2.6 3.4"+ />,+ )}+ </Wrap>+ ),+ // Beeper's own mark, for chats Beeper attributes to itself rather than a+ // bridged network (#84) — a four-point sparkle keeps the silhouette+ // distinct from every rounded/circular network bubble above.+ beeper: ({ size }) => (+ <Wrap size={size} rounded bg="#7C5CFC" title="Beeper">+ {svg(+ <path+ fill="#fff"+ d="M12 2.3c.7 3.6 1.7 4.6 5.3 5.3-3.6.7-4.6 1.7-5.3 5.3-.7-3.6-1.7-4.6-5.3-5.3 3.6-.7 4.6-1.7 5.3-5.3Zm6.8 10.4c.4 1.9.9 2.4 2.9 2.8-2 .4-2.5.9-2.9 2.8-.4-1.9-.9-2.4-2.9-2.8 2-.4 2.5-.9 2.9-2.8Z"+ />,+ )}+ </Wrap>+ ),+ instagram: ({ size }) => (+ <span+ role="img"+ aria-label="Instagram"+ title="Instagram"+ className="inline-flex shrink-0 items-center justify-center"+ style={{+ width: size,+ height: size,+ borderRadius: size * 0.28,+ background: 'radial-gradient(circle at 30% 107%, #fdf497 0%, #fd5949 45%, #d6249f 60%, #285AEB 90%)',+ }}+ >+ {svg(+ <>+ <rect x="3.5" y="3.5" width="17" height="17" rx="5" stroke="#fff" strokeWidth="2" />+ <circle cx="12" cy="12" r="4" stroke="#fff" strokeWidth="2" />+ <circle cx="17.2" cy="6.8" r="1.2" fill="#fff" />+ </>,+ )}+ </span>+ ),+ telegram: ({ size }) => (+ <Wrap size={size} bg="#29A9EB" title="Telegram">+ {svg(<path fill="#fff" d="M21 5.2 3.6 11.4c-.9.3-.9.9-.1 1.1l4.4 1.4 1.7 5.1c.2.6.4.7.9.3l2.4-2 4.6 3.4c.8.5 1.3.2 1.5-.8l2.7-12.6c.2-1-.4-1.5-1.2-1.1ZM9.6 14l8.4-5.3c.4-.2.8 0 .4.3l-7.1 6.4-.3 3-1.4-4.4Z" />)}+ </Wrap>+ ),+ slack: ({ size }) => (+ <Wrap size={size} rounded bg="#fff" title="Slack">+ {svg(+ <>+ <path fill="#36C5F0" d="M6.8 14.3a2 2 0 1 1-2-2h2v2Zm1 0a2 2 0 0 1 4 0v5a2 2 0 1 1-4 0v-5Z" />+ <path fill="#2EB67D" d="M9.8 6.6a2 2 0 1 1 2-2v2h-2Zm0 1a2 2 0 0 1 0 4h-5a2 2 0 1 1 0-4h5Z" />+ <path fill="#ECB22E" d="M17.2 9.6a2 2 0 1 1 2 2h-2v-2Zm-1 0a2 2 0 0 1-4 0v-5a2 2 0 1 1 4 0v5Z" />+ <path fill="#E01E5A" d="M14.2 17.3a2 2 0 1 1-2 2v-2h2Zm0-1a2 2 0 0 1 0-4h5a2 2 0 1 1 0 4h-5Z" />+ </>,+ )}+ </Wrap>+ ),+ x: ({ size }) => (+ <Wrap size={size} bg="#000" title="X">+ {svg(<path fill="#fff" d="M17.5 3h2.9l-6.3 7.2L21.6 21h-5.8l-4.5-5.9L6 21H3.1l6.7-7.7L2.7 3h5.9l4.1 5.4L17.5 3Zm-1 16.2h1.6L7.6 4.7H5.9l10.6 14.5Z" />)}+ </Wrap>+ ),+};++// Display names for the ids above. A network absent from this map falls back+// to its raw id rather than to a guess.+const LABELS = {+ whatsapp: 'WhatsApp',+ googlemessages: 'Google Messages',+ discord: 'Discord',+ facebook: 'Messenger',+ signal: 'Signal',+ instagram: 'Instagram',+ telegram: 'Telegram',+ slack: 'Slack',+ x: 'X',+ beeper: 'Beeper',+};++/** Any network PortOS has no mark for still renders: initial on a neutral chip. */+const Fallback = ({ size, label }) => (+ <Wrap size={size} rounded bg="#4b5563" title={label}>+ <span style={{ fontSize: size * 0.5, color: '#fff', fontWeight: 700 }}>{(label || '?')[0].toUpperCase()}</span>+ </Wrap>+);++// Beeper's Facebook/Messenger bridge reports several distinct ids for the+// same one `facebook` mark and label depending on bridge generation and+// login mode (#84): the legacy bridge, its Go rewrite, and the+// Messenger-mode login all land on the same network. Keyed post-normalize+// (lowercase, punctuation stripped), so "Facebook Go" and "facebook-go" both+// match `facebookgo`.+const NETWORK_ALIASES = {+ facebookgo: 'facebook',+ messenger: 'facebook',+ messengergo: 'facebook',+};++// The live Facebook-bridge display string has never been observed directly+// (no fixture in this repo, none in any captured log, live mirror off+// limits), so rather than guess one more exact spelling for `NETWORK_ALIASES`+// above, this ordered contains-rule against the normalized id is what makes+// the mapping robust to whichever spelling ("Facebook Messenger",+// "Messenger (Go)", ...) the bridge actually emits — checked only after the+// exact map so a future precise alias still wins.+const NETWORK_ALIAS_RULES = [+ [/facebook|messenger/, 'facebook'],+];++// Beeper reports a network as a lowercase id; normalize defensively so a+// bridge that reports "WhatsApp" or "google-messages" still finds its mark+// instead of silently degrading to the initial chip, then fold known aliases+// onto the one id each has a mark/label for.+const normalize = (network) => {+ const raw = String(network || '').toLowerCase().replace(/[^a-z0-9]/g, '');+ if (NETWORK_ALIASES[raw]) return NETWORK_ALIASES[raw];+ const rule = NETWORK_ALIAS_RULES.find(([pattern]) => pattern.test(raw));+ return rule ? rule[1] : raw;+};++/** A human label for a network id, for the composer, the header and titles. */+export const networkLabel = (network) => LABELS[normalize(network)] || network || 'Unknown network';++// A network id PortOS has no mark for is expected (#9: the roster is+// whatever the mirror holds, never a hardcoded list) but should still be+// visible to a developer diagnosing why a network fell back to a letter+// chip. Log it once per normalized id, dev-only, so a rail full of one+// unrecognized network doesn't spam the console on every render.+const loggedUnknownNetworks = new Set();++function logUnknownNetworkOnce(rawNetwork, normalized) {+ if (!import.meta.env.DEV) return;+ if (!normalized || loggedUnknownNetworks.has(normalized)) return;+ loggedUnknownNetworks.add(normalized);+ console.warn(`⚠️ Beeper network "${rawNetwork}" (normalized "${normalized}") has no rail mark — falling back to a letter chip`);+}++export default function NetworkLogo({ network, label, size = 16 }) {+ const normalized = normalize(network);+ const Mark = MARKS[normalized];+ if (!Mark) {+ logUnknownNetworkOnce(network, normalized);+ return <Fallback size={size} label={label || networkLabel(network)} />;+ }+ return <Mark size={size} />;+}diff --git a/client/src/components/messages/beeper/BeeperNetworkLogo.test.jsx b/client/src/components/messages/beeper/BeeperNetworkLogo.test.jsxnew file mode 100644index 0000000000..c1f70c3caa--- /dev/null+++ b/client/src/components/messages/beeper/BeeperNetworkLogo.test.jsx@@ -0,0 +1,149 @@+import {+ afterEach, describe, expect, it, vi,+} from 'vitest';+import { cleanup, render, screen } from '@testing-library/react';+import NetworkLogo, { networkLabel } from './BeeperNetworkLogo';++/**+ * #84: the Google Messages and Signal marks were both solid blue speech+ * bubbles, indistinguishable at rail size; Facebook and Beeper fell back to+ * grey letter chips because the ids Beeper actually emits for those two+ * ("facebookgo"/"messenger" for Facebook, and Beeper's own network) never+ * normalized onto a key `MARKS` held a mark for.+ *+ * These tests pin: distinct silhouettes for Google Messages vs. Signal, a+ * Beeper mark, every Facebook/Messenger alias resolving to the one+ * `facebook` mark and label, the letter-chip fallback for a truly unknown+ * id, and the once-per-id dev-only console log that makes that fallback+ * visible without spamming.+ */++afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+});++describe('BeeperNetworkLogo — Google Messages vs. Signal', () => {+ it('renders Google Messages as a filled speech-bubble path', () => {+ render(<NetworkLogo network="googlemessages" />);+ const mark = screen.getByRole('img', { name: 'Google Messages' });+ expect(mark.querySelector('path')).toBeTruthy();+ expect(mark.querySelector('circle')).toBeNull();+ });++ it('renders Signal as a dashed/dotted ring, not a speech bubble', () => {+ render(<NetworkLogo network="signal" />);+ const mark = screen.getByRole('img', { name: 'Signal' });+ const ring = mark.querySelector('circle');+ expect(ring).toBeTruthy();+ // A dotted/dashed circle, not a solid one — the silhouette that actually+ // distinguishes it from Google Messages' bubble.+ expect(ring).toHaveAttribute('stroke-dasharray');+ expect(ring).toHaveAttribute('fill', 'none');+ expect(mark.querySelector('path')).toBeNull();+ });+});++describe('BeeperNetworkLogo — Beeper mark', () => {+ const beeperIds = ['beeper', 'Beeper'];++ it.each(beeperIds)('renders a dedicated Beeper mark instead of falling back for %s', (rawId) => {+ render(<NetworkLogo network={rawId} />);+ const mark = screen.getByRole('img', { name: 'Beeper' });+ expect(mark.querySelector('path')).toBeTruthy();+ // Not the neutral grey fallback chip's single-letter span.+ expect(mark.querySelector('span')).toBeNull();+ });++ it('exposes "Beeper" through networkLabel', () => {+ expect(networkLabel('beeper')).toBe('Beeper');+ });+});++describe('BeeperNetworkLogo — Facebook/Messenger id normalisation', () => {+ const aliases = [+ 'facebook',+ 'facebookgo',+ 'messenger',+ 'messengergo',+ 'Facebook Go',+ 'MESSENGER',+ // Beeper reports a display name, not a stable id, and the live+ // Facebook-bridge string has never been observed (#84) — these pin the+ // contains-rule fallback (`NETWORK_ALIAS_RULES`) that catches whichever+ // spelling the bridge actually emits, none of which hit the exact map.+ 'Facebook Messenger',+ 'facebook-messenger',+ 'Facebook (Go)',+ 'Messenger (Go)',+ ];++ it.each(aliases)('resolves %s to the Messenger mark', (rawId) => {+ render(<NetworkLogo network={rawId} />);+ const mark = screen.getByRole('img', { name: 'Messenger' });+ expect(mark.querySelector('path')).toBeTruthy();+ expect(mark.querySelector('span')).toBeNull();+ });++ it('labels every alias "Messenger" via networkLabel', () => {+ for (const rawId of aliases) {+ expect(networkLabel(rawId)).toBe('Messenger');+ }+ });+});++describe('BeeperNetworkLogo — unknown network fallback', () => {+ it('renders the letter-chip fallback for a network with no mark', () => {+ render(<NetworkLogo network="threema-unmapped-1" />);+ const chip = screen.getByRole('img', { name: 'threema-unmapped-1' });+ expect(chip.textContent).toBe('T');+ });++ it('prefers an explicit label prop over the raw id on the fallback chip', () => {+ render(<NetworkLogo network="threema-unmapped-2" label="Threema" />);+ const chip = screen.getByRole('img', { name: 'Threema' });+ expect(chip.textContent).toBe('T');+ });+});++describe('BeeperNetworkLogo — dev-only once-per-id unknown network log', () => {+ it('logs an unknown id once, even across repeated renders of the same id', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ render(<NetworkLogo network="unmapped-dev-log-a" />);+ render(<NetworkLogo network="unmapped-dev-log-a" />);+ render(<NetworkLogo network="unmapped-dev-log-a" />);++ const hits = warn.mock.calls.filter(([msg]) => msg.includes('unmapped-dev-log-a'));+ expect(hits).toHaveLength(1);+ });++ it('logs a different unknown id independently of one already logged', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ render(<NetworkLogo network="unmapped-dev-log-b" />);+ render(<NetworkLogo network="unmapped-dev-log-c" />);++ const bHits = warn.mock.calls.filter(([msg]) => msg.includes('unmapped-dev-log-b'));+ const cHits = warn.mock.calls.filter(([msg]) => msg.includes('unmapped-dev-log-c'));+ expect(bHits).toHaveLength(1);+ expect(cHits).toHaveLength(1);+ });++ it('does not log for a network that resolves to a known mark', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ render(<NetworkLogo network="whatsapp" />);+ render(<NetworkLogo network="facebookgo" />);+ expect(warn).not.toHaveBeenCalled();+ });++ it('stays silent outside development', () => {+ const originalDev = import.meta.env.DEV;+ import.meta.env.DEV = false;+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ try {+ render(<NetworkLogo network="unmapped-dev-log-prod-guard" />);+ expect(warn).not.toHaveBeenCalled();+ } finally {+ import.meta.env.DEV = originalDev;+ }+ });+});diff --git a/client/src/components/messages/beeper/BeeperOutboxBreakerBanner.jsx b/client/src/components/messages/beeper/BeeperOutboxBreakerBanner.jsxnew file mode 100644index 0000000000..c040f2a796--- /dev/null+++ b/client/src/components/messages/beeper/BeeperOutboxBreakerBanner.jsx@@ -0,0 +1,61 @@+import { useState } from 'react';+import { Loader2, ShieldAlert } from 'lucide-react';+import Banner from '../../ui/Banner';+import toast from '../../ui/Toast';+import { clearOutboxBreaker } from '../../../services/api';++/**+ * The runaway breaker, on the settings card and nowhere else (#36, decided on+ * #8 decision 4 and #12's two-surfaces rule).+ *+ * The breaker trips when sends arrive faster than a human produces them — a+ * software loop, not a busy conversation. It blocks every further send until a+ * person clears it here: there is no timed recovery anywhere in the send path,+ * because a breaker that resets itself is a delay rather than a breaker.+ *+ * It renders where actionable Beeper faults already render, never as a global+ * banner: a user who is not sending anything has nothing to act on.+ *+ * @param {object} props+ * @param {object|null} props.breaker `status.outbox.breaker` from GET /api/beeper/status.+ * @param {() => void} [props.onCleared] refetch hook for the parent's status.+ */+export default function BeeperOutboxBreakerBanner({ breaker, onCleared }) {+ const [clearing, setClearing] = useState(false);+ if (!breaker?.tripped) return null;++ const handleClear = async () => {+ setClearing(true);+ const result = await clearOutboxBreaker({ silent: true }).catch((err) => {+ toast.error(err?.message || 'Could not clear the send breaker');+ return null;+ });+ setClearing(false);+ if (!result) return;+ toast.success('Beeper sending re-enabled');+ onCleared?.();+ };++ return (+ <Banner+ tone="error"+ icon={ShieldAlert}+ size="md"+ title="Beeper sending is blocked"+ actions={(+ <button+ type="button"+ onClick={handleClear}+ disabled={clearing}+ className="inline-flex items-center gap-1.5 rounded px-2 py-1 text-xs text-port-error hover:bg-port-error/20 disabled:opacity-40"+ >+ {clearing ? <Loader2 size={12} className="animate-spin" /> : null}+ {clearing ? 'Clearing…' : 'Clear breaker'}+ </button>+ )}+ >+ The runaway breaker tripped ({breaker.reason || 'unexpected send rate'}). No message has been sent since,+ and nothing is retried automatically. Check what was sending before clearing this.+ </Banner>+ );+}diff --git a/client/src/components/messages/beeper/BeeperPersonPicker.jsx b/client/src/components/messages/beeper/BeeperPersonPicker.jsxnew file mode 100644index 0000000000..09ca3302d2--- /dev/null+++ b/client/src/components/messages/beeper/BeeperPersonPicker.jsx@@ -0,0 +1,210 @@+import { useEffect, useId, useMemo, useRef, useState } from 'react';+import { createPortal } from 'react-dom';+import { Search, UserPlus } from 'lucide-react';+import usePopoverPosition, { VIEWPORT_PADDING } from '../../../hooks/usePopoverPosition.js';++// Matches the list's old `w-48` — kept as a JS constant now that width is set+// via `usePopoverPosition` instead of a Tailwind width utility.+const LIST_WIDTH = 192;++/**+ * Search-first Tribe-person picker for the Beeper participant-linking path+ * (#98 part B). It replaces the bare full-roster `<select>` `ParticipantRow`+ * used to render in `BeeperThread.jsx` — a plain dropdown does not scale past+ * a handful of names, and it gave no way to type-to-find.+ *+ * The roster (`people`) is loaded once per chat surface already+ * (`BeeperChatSurface.jsx`'s `people` state, `api.getTribePeople({ silent: true })`+ * with no `?search=` param) — filtering it client-side here avoids adding a+ * network round-trip per keystroke for a list this surface already holds in+ * full. The filter itself is still debounced (≥200ms) so a fast typist does+ * not re-run it on every keystroke; the server's own `?search=` param+ * (`GET /tribe/people`) stays available for a future caller with a roster+ * too large to hold client-side.+ *+ * Selecting a result IS the link action — there is no separate "Link" button+ * to press afterwards, unlike the `<select>` this replaces. "Create new…" is+ * always the LAST row, below every match, and calls the exact same+ * `onCreateNew` callback the old "New" button called — #97 changes what that+ * callback DOES (a confirm-and-rename form instead of an immediate create),+ * not this wiring.+ *+ * `autoFocus` (#97 part B) is only ever passed `true` from "Change" on an+ * already-linked participant row, so re-pointing a link opens straight into+ * a focused, ready-to-type input rather than requiring an extra click.+ *+ * The results list is portaled to `document.body` and fixed-positioned via+ * `usePopoverPosition` (#105): `BeeperThread.jsx` renders this inside a+ * `max-h-40 overflow-y-auto` participants roster, and an absolutely+ * positioned child cannot escape an `overflow: auto` ancestor — the list was+ * extending that roster's own scroll area instead of floating over it. This+ * is a combobox, not a menu: focus never leaves the input while the list is+ * open, so closing is still driven by `onBlur` (`closeList`) exactly as+ * before, and every pointer target inside the portaled list (not just each+ * row) calls `preventDefault` on `mousedown` so clicking anywhere in it —+ * padding, the "No matches" row, the scrollbar — counts as inside the picker+ * rather than blurring the input out from under a would-be selection.+ */+export default function BeeperPersonPicker({+ id,+ label,+ people,+ onSelectPerson,+ onCreateNew,+ disabled = false,+ placeholder = 'Link to…',+ autoFocus = false,+}) {+ const [query, setQuery] = useState('');+ const [debouncedQuery, setDebouncedQuery] = useState('');+ const [open, setOpen] = useState(false);+ const [activeIndex, setActiveIndex] = useState(0);+ const listboxId = useId();+ const optionId = (index) => `${listboxId}-option-${index}`;+ const wrapperRef = useRef(null);++ useEffect(() => {+ const timer = setTimeout(() => setDebouncedQuery(query), 200);+ return () => clearTimeout(timer);+ }, [query]);++ const matches = useMemo(() => {+ const needle = debouncedQuery.trim().toLowerCase();+ const list = needle+ ? (people || []).filter((person) => (person.name || '').toLowerCase().includes(needle))+ : (people || []);+ // A ceiling, not a hint that more exist — keeps a very large roster from+ // rendering an unbounded results list.+ return list.slice(0, 50);+ }, [people, debouncedQuery]);++ // "Create new…" is always present and always LAST; the row count for+ // keyboard purposes is every match plus that one trailing row.+ const createNewIndex = matches.length;+ const rowCount = matches.length + 1;++ // Right-aligned below the input (flipping above only when there's no room+ // below), re-measured whenever the match count changes the list's height —+ // typing can grow or shrink it between "No matches" and a full page of+ // rows — so an above/below flip made while the list was short doesn't+ // paint stale once it grows.+ const { popoverRef: listRef, style: listStyle } = usePopoverPosition({+ open,+ width: LIST_WIDTH,+ minWidth: LIST_WIDTH,+ gap: 4,+ position: 'below',+ anchorRef: wrapperRef,+ contentDeps: [matches.length],+ });++ const closeList = () => { setOpen(false); setActiveIndex(0); };++ const selectRow = (index) => {+ if (index === createNewIndex) onCreateNew();+ else if (matches[index]) onSelectPerson(matches[index].id);+ setQuery('');+ closeList();+ };++ const handleKeyDown = (event) => {+ if (event.key === 'ArrowDown') {+ event.preventDefault();+ if (!open) { setOpen(true); return; }+ setActiveIndex((index) => (index + 1) % rowCount);+ } else if (event.key === 'ArrowUp') {+ event.preventDefault();+ if (!open) { setOpen(true); return; }+ setActiveIndex((index) => (index - 1 + rowCount) % rowCount);+ } else if (event.key === 'Enter') {+ if (!open) return;+ event.preventDefault();+ selectRow(activeIndex);+ } else if (event.key === 'Escape' && open) {+ event.preventDefault();+ closeList();+ }+ };++ return (+ <div className="relative min-w-[9rem] max-w-[12rem]" ref={wrapperRef}>+ {label && <label htmlFor={id} className="sr-only">{label}</label>}+ <div className="flex items-center gap-1 rounded border border-port-border bg-port-bg px-1.5 py-1">+ <Search size={11} className="shrink-0 text-gray-500" aria-hidden="true" />+ <input+ id={id}+ type="text"+ role="combobox"+ aria-expanded={open}+ aria-controls={listboxId}+ aria-autocomplete="list"+ aria-activedescendant={open ? optionId(activeIndex) : undefined}+ disabled={disabled}+ autoFocus={autoFocus}+ value={query}+ onChange={(event) => { setQuery(event.target.value); setActiveIndex(0); setOpen(true); }}+ onFocus={() => setOpen(true)}+ onBlur={closeList}+ onKeyDown={handleKeyDown}+ placeholder={placeholder}+ className="min-w-0 flex-1 bg-transparent text-[11px] text-gray-200 placeholder:text-gray-500 focus:outline-none disabled:opacity-50"+ />+ </div>+ {open && createPortal(+ <ul+ ref={listRef}+ id={listboxId}+ role="listbox"+ // The input owns focus the whole time this is open (see the class+ // doc comment) — any pointerdown here must not blur it, or the+ // input's own `onBlur` would close the list before a click on it+ // could land. Each row below already prevents default for the+ // same reason; this catches everything else in the portal (padding,+ // "No matches", the scrollbar).+ onMouseDown={(event) => event.preventDefault()}+ className="fixed z-[100] max-h-48 overflow-y-auto rounded border border-port-border bg-port-card py-1 shadow-lg"+ style={{+ left: listStyle?.left ?? `${VIEWPORT_PADDING}px`,+ top: listStyle?.top ?? `${VIEWPORT_PADDING}px`,+ width: listStyle?.width ?? `${LIST_WIDTH}px`,+ visibility: listStyle ? 'visible' : 'hidden',+ }}+ >+ {matches.length === 0 && (+ <li className="px-2 py-1 text-[11px] text-gray-500">No matches</li>+ )}+ {matches.map((person, index) => (+ <li+ key={person.id}+ id={optionId(index)}+ role="option"+ aria-selected={index === activeIndex}+ // `onMouseDown` with `preventDefault`, not `onClick`: a click+ // fires AFTER the input's own `onBlur`, which would have+ // already closed (and unmounted) this list.+ onMouseDown={(event) => { event.preventDefault(); selectRow(index); }}+ className={`cursor-pointer truncate px-2 py-1 text-[11px] ${+ index === activeIndex ? 'bg-port-accent/20 text-white' : 'text-gray-200'+ }`}+ >+ {person.name}+ </li>+ ))}+ <li+ id={optionId(createNewIndex)}+ role="option"+ aria-selected={createNewIndex === activeIndex}+ onMouseDown={(event) => { event.preventDefault(); selectRow(createNewIndex); }}+ className={`flex items-center gap-1 border-t border-port-border/60 px-2 py-1 text-[11px] ${+ createNewIndex === activeIndex ? 'bg-port-accent/20 text-white' : 'text-gray-300'+ }`}+ >+ <UserPlus size={10} aria-hidden="true" />+ Create new…+ </li>+ </ul>,+ document.body,+ )}+ </div>+ );+}diff --git a/client/src/components/messages/beeper/BeeperPersonPicker.test.jsx b/client/src/components/messages/beeper/BeeperPersonPicker.test.jsxnew file mode 100644index 0000000000..24d942ea1f--- /dev/null+++ b/client/src/components/messages/beeper/BeeperPersonPicker.test.jsx@@ -0,0 +1,256 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import {+ cleanup, fireEvent, render, screen, waitFor,+} from '@testing-library/react';+import BeeperPersonPicker from './BeeperPersonPicker';++/**+ * The search-first Tribe-person picker (#98 part B) that replaces the bare+ * full-roster `<select>` `ParticipantRow` used to render — wiring tests for+ * it as used from `BeeperThread` live in `BeeperThread.test.jsx`; these pin+ * the component's own filtering, debounce and keyboard contract in isolation.+ */++const PEOPLE = [+ { id: 'p1', name: 'Alex Example' },+ { id: 'p2', name: 'Blair Sample' },+ { id: 'p3', name: 'Casey Placeholder' },+];++const renderPicker = (overrides = {}) => {+ const props = {+ id: 'picker-1',+ label: 'Link Sam Example to a Tribe person',+ people: PEOPLE,+ onSelectPerson: vi.fn(),+ onCreateNew: vi.fn(),+ ...overrides,+ };+ const utils = render(<BeeperPersonPicker {...props} />);+ return { ...utils, props };+};++afterEach(cleanup);++describe('BeeperPersonPicker — opening and closing', () => {+ it('renders no listbox until the input is focused', () => {+ renderPicker();+ expect(screen.queryByRole('listbox')).not.toBeInTheDocument();++ fireEvent.focus(screen.getByLabelText('Link Sam Example to a Tribe person'));+ expect(screen.getByRole('listbox')).toBeInTheDocument();+ });++ it('closes the listbox on blur', () => {+ renderPicker();+ const input = screen.getByLabelText('Link Sam Example to a Tribe person');+ fireEvent.focus(input);+ expect(screen.getByRole('listbox')).toBeInTheDocument();++ fireEvent.blur(input);+ expect(screen.queryByRole('listbox')).not.toBeInTheDocument();+ });+});++describe('BeeperPersonPicker — filtering', () => {+ it('shows every person with an empty query', () => {+ renderPicker();+ fireEvent.focus(screen.getByLabelText('Link Sam Example to a Tribe person'));++ expect(screen.getByRole('option', { name: 'Alex Example' })).toBeInTheDocument();+ expect(screen.getByRole('option', { name: 'Blair Sample' })).toBeInTheDocument();+ expect(screen.getByRole('option', { name: 'Casey Placeholder' })).toBeInTheDocument();+ });++ // The filter is debounced (>=200ms) rather than applied on every keystroke.+ it('filters case-insensitively by substring, after the debounce settles', async () => {+ renderPicker();+ const input = screen.getByLabelText('Link Sam Example to a Tribe person');+ fireEvent.focus(input);+ fireEvent.change(input, { target: { value: 'bla' } });++ await waitFor(() => {+ expect(screen.getByRole('option', { name: 'Blair Sample' })).toBeInTheDocument();+ expect(screen.queryByRole('option', { name: 'Alex Example' })).not.toBeInTheDocument();+ });+ });++ it('shows "No matches" for a query nothing matches, with "Create new…" still last', async () => {+ renderPicker();+ const input = screen.getByLabelText('Link Sam Example to a Tribe person');+ fireEvent.focus(input);+ fireEvent.change(input, { target: { value: 'zzz-nobody' } });++ await waitFor(() => expect(screen.getByText('No matches')).toBeInTheDocument());+ const options = screen.getAllByRole('option');+ expect(options).toHaveLength(1);+ expect(options[0]).toHaveTextContent('Create new…');+ });+});++describe('BeeperPersonPicker — selection', () => {+ it('calls onSelectPerson with the person id when a result is clicked, and closes the list', () => {+ const onSelectPerson = vi.fn();+ renderPicker({ onSelectPerson });+ fireEvent.focus(screen.getByLabelText('Link Sam Example to a Tribe person'));++ fireEvent.mouseDown(screen.getByRole('option', { name: 'Blair Sample' }));++ expect(onSelectPerson).toHaveBeenCalledWith('p2');+ expect(screen.queryByRole('listbox')).not.toBeInTheDocument();+ });++ it('always renders "Create new…" as the LAST option, after every match', () => {+ renderPicker();+ fireEvent.focus(screen.getByLabelText('Link Sam Example to a Tribe person'));++ const options = screen.getAllByRole('option');+ expect(options).toHaveLength(PEOPLE.length + 1);+ expect(options[options.length - 1]).toHaveTextContent('Create new…');+ expect(options.slice(0, -1).map((o) => o.textContent)).toEqual(PEOPLE.map((p) => p.name));+ });++ it('calls onCreateNew (never onSelectPerson) when "Create new…" is chosen', () => {+ const onSelectPerson = vi.fn();+ const onCreateNew = vi.fn();+ renderPicker({ onSelectPerson, onCreateNew });+ fireEvent.focus(screen.getByLabelText('Link Sam Example to a Tribe person'));++ const options = screen.getAllByRole('option');+ fireEvent.mouseDown(options[options.length - 1]);++ expect(onCreateNew).toHaveBeenCalledTimes(1);+ expect(onSelectPerson).not.toHaveBeenCalled();+ });+});++describe('BeeperPersonPicker — keyboard navigation', () => {+ it('ArrowDown/ArrowUp move the highlighted option, tracked via aria-activedescendant', () => {+ renderPicker();+ const input = screen.getByLabelText('Link Sam Example to a Tribe person');+ fireEvent.focus(input);++ const first = screen.getByRole('option', { name: 'Alex Example' });+ expect(input).toHaveAttribute('aria-activedescendant', first.id);++ fireEvent.keyDown(input, { key: 'ArrowDown' });+ const second = screen.getByRole('option', { name: 'Blair Sample' });+ expect(input).toHaveAttribute('aria-activedescendant', second.id);+ expect(second).toHaveAttribute('aria-selected', 'true');++ fireEvent.keyDown(input, { key: 'ArrowUp' });+ expect(input).toHaveAttribute('aria-activedescendant', first.id);+ });++ it('wraps from the last row ("Create new…") back to the first match on ArrowDown', () => {+ renderPicker();+ const input = screen.getByLabelText('Link Sam Example to a Tribe person');+ fireEvent.focus(input);++ for (let i = 0; i < PEOPLE.length; i += 1) fireEvent.keyDown(input, { key: 'ArrowDown' });+ expect(screen.getByRole('option', { name: /Create new/ })).toHaveAttribute('aria-selected', 'true');++ fireEvent.keyDown(input, { key: 'ArrowDown' });+ expect(screen.getByRole('option', { name: 'Alex Example' })).toHaveAttribute('aria-selected', 'true');+ });++ it('Enter selects the highlighted option', () => {+ const onSelectPerson = vi.fn();+ renderPicker({ onSelectPerson });+ const input = screen.getByLabelText('Link Sam Example to a Tribe person');+ fireEvent.focus(input);+ fireEvent.keyDown(input, { key: 'ArrowDown' });+ fireEvent.keyDown(input, { key: 'Enter' });++ expect(onSelectPerson).toHaveBeenCalledWith('p2');+ });++ it('Escape closes the list without selecting anything', () => {+ const onSelectPerson = vi.fn();+ const onCreateNew = vi.fn();+ renderPicker({ onSelectPerson, onCreateNew });+ const input = screen.getByLabelText('Link Sam Example to a Tribe person');+ fireEvent.focus(input);+ fireEvent.keyDown(input, { key: 'Escape' });++ expect(screen.queryByRole('listbox')).not.toBeInTheDocument();+ expect(onSelectPerson).not.toHaveBeenCalled();+ expect(onCreateNew).not.toHaveBeenCalled();+ });++ it('ArrowDown on a closed list opens it without moving the highlight yet', () => {+ renderPicker();+ const input = screen.getByLabelText('Link Sam Example to a Tribe person');+ expect(screen.queryByRole('listbox')).not.toBeInTheDocument();++ fireEvent.keyDown(input, { key: 'ArrowDown' });+ expect(screen.getByRole('listbox')).toBeInTheDocument();+ });+});++describe('BeeperPersonPicker — disabled state', () => {+ it('disables the input while a link is in flight', () => {+ renderPicker({ disabled: true });+ expect(screen.getByLabelText('Link Sam Example to a Tribe person')).toBeDisabled();+ });+});++/**+ * #105: the results list used to render `absolute`, positioned inside the+ * component's own `relative` wrapper — fine on its own, but wherever a caller+ * nests the picker inside an `overflow: auto` ancestor (the Beeper+ * participants roster, `BeeperThread.jsx`), an absolutely positioned child+ * cannot escape that ancestor's clipping and instead extends its scrollable+ * area. The list now portals to `document.body` and is fixed-positioned off+ * the input's own rect (`usePopoverPosition`) so no ancestor can clip it.+ * "Keyboard path still selects" and "Escape closes" are exercised above+ * already (they never depended on the list's DOM location) and stayed green+ * through this change — these add the portal-specific coverage.+ */+describe('BeeperPersonPicker — portaled results list (#105)', () => {+ it('renders the results list outside the input wrapper, as a child of document.body', () => {+ const { container } = renderPicker();+ fireEvent.focus(screen.getByLabelText('Link Sam Example to a Tribe person'));++ const listbox = screen.getByRole('listbox');+ expect(container.contains(listbox)).toBe(false);+ expect(document.body.contains(listbox)).toBe(true);+ });++ it('still selects on a click inside the portaled list', () => {+ const onSelectPerson = vi.fn();+ renderPicker({ onSelectPerson });+ fireEvent.focus(screen.getByLabelText('Link Sam Example to a Tribe person'));++ const option = screen.getByRole('option', { name: 'Blair Sample' });+ // Confirms the click actually exercised the portal, not some fallback.+ expect(document.body.contains(option)).toBe(true);+ fireEvent.mouseDown(option);++ expect(onSelectPerson).toHaveBeenCalledWith('p2');+ expect(screen.queryByRole('listbox')).not.toBeInTheDocument();+ });++ it('closes on an outside click: mousedown outside is not swallowed as "inside the picker"', () => {+ renderPicker();+ const input = screen.getByLabelText('Link Sam Example to a Tribe person');+ fireEvent.focus(input);+ expect(screen.getByRole('listbox')).toBeInTheDocument();++ // This is a combobox, not a menu — the input keeps focus the whole time,+ // so closing is driven by its own `onBlur`, not a global outside-click+ // listener. A real outside click's mousedown moves the browser's focus+ // away from the input, which is what fires that blur; happy-dom moves+ // `document.activeElement` on `fireEvent.mousedown` (confirmed: it lands+ // on `document.body`) without also dispatching the `blur` event a real+ // browser would, so both are fired here to model that one user gesture.+ // The regression this guards against: the portaled list's own+ // `mousedown` handler (added for #105 so a click *inside* it doesn't+ // blur the input away from under a selection) must not be broad enough+ // to also swallow a `mousedown` that lands elsewhere, like this one.+ fireEvent.mouseDown(document.body);+ fireEvent.blur(input);++ expect(screen.queryByRole('listbox')).not.toBeInTheDocument();+ });+});diff --git a/client/src/components/messages/beeper/BeeperSettingsPanel.jsx b/client/src/components/messages/beeper/BeeperSettingsPanel.jsxnew file mode 100644index 0000000000..ec760cbbf4--- /dev/null+++ b/client/src/components/messages/beeper/BeeperSettingsPanel.jsx@@ -0,0 +1,937 @@+import { useCallback, useEffect, useState } from 'react';+import { Save, Loader2, MessageCircle, ShieldCheck, ShieldAlert, RefreshCw, Clock, Link2, Unlink, HardDrive, Download } from 'lucide-react';+import toast from '../../ui/Toast';+import Modal from '../../ui/Modal';+import BrailleSpinner from '../../BrailleSpinner';+import { useBeeperSettings } from '../../../hooks/useBeeperSettings';+import useMounted from '../../../hooks/useMounted';+import ConnectionStatusDot from '../../ui/ConnectionStatusDot';+import BeeperOutboxBreakerBanner from './BeeperOutboxBreakerBanner';+import { formatBytes, formatClockTime } from '../../../utils/formatters';+import {+ getBeeperStatus, checkBeeperConnection, startBeeperOAuth, saveBeeperToken, disconnectBeeper,+ getBeeperAttachmentSummary, backfillBeeperAttachments,+} from '../../../services/api';++// The Beeper connection story (#30 + #31, fork issue #1): ingestion settings,+// the tri-state status card, the connect flow, token expiry, and the read-only+// account roster #27's schema mirrors. #35 turned `/messages/beeper` into the+// chat surface itself, so this MOVED off the page body and into a settings+// drawer over it — the same treatment iMessage gives its own ingestion config+// (`?settings=1`). It is reachable, not removed: an actionable fault renders+// HERE and never as a global banner (#12 decision 4).+//+// Two connect paths, both first-class (#11 decision 3): OAuth, which PortOS+// runs itself, and pasting a token, which is the only way to get one that never+// expires. Neither ever puts a token value into this component's state beyond+// the paste field the user typed it into, and no response here carries one.+// The OAuth *outcome* is read off the URL by the page shell, which is mounted+// whether or not this drawer is open — Beeper's consent screen redirects the+// browser back to the page, not to the drawer.+//+// `realtime` is a PROP, not a subscription this panel opens itself. Several+// Beeper surfaces may each pair their own useBeeperRealtime subscribe/+// unsubscribe (client/src/hooks/README.md sanctions this — see+// useBeeperOutbox, mounted inside BeeperChatSurface); the page-level instance+// in BeeperTab is the one that owns the status card, so this drawer just+// reads what it's handed rather than opening a second one.+export default function BeeperSettingsPanel({ realtime: realtimeProp = null, onRealtimeSeed, onBreakerCleared }) {+ const {+ loading: settingsLoading, form, setForm, saving, dirty, save, loadFailed: settingsLoadFailed,+ } = useBeeperSettings();+ const [status, setStatus] = useState(null);+ // Distinguishes "the GET failed" from "the GET succeeded and says no token+ // is configured" — the absent-vs-empty rule (root AGENTS.md). Collapsing+ // both into `status = null` would tell a working-token install to+ // "Connect Beeper" just because the status request itself errored.+ const [statusError, setStatusError] = useState(null);+ const [statusLoading, setStatusLoading] = useState(true);+ const [statusRetrying, setStatusRetrying] = useState(false);+ const [checking, setChecking] = useState(false);+ const [connecting, setConnecting] = useState(false);+ const [pastedToken, setPastedToken] = useState('');+ const [savingToken, setSavingToken] = useState(false);+ const [confirmingDisconnect, setConfirmingDisconnect] = useState(false);+ const [disconnecting, setDisconnecting] = useState(false);+ const mountedRef = useMounted();++ const loadStatus = useCallback(async () => {+ const [result, error] = await getBeeperStatus({ silent: true })+ .then((value) => [value, null])+ .catch((err) => [null, err]);+ if (!mountedRef.current) return;+ setStatus(result);+ setStatusError(error ? (error?.message || 'Could not read Beeper status') : null);+ setStatusLoading(false);+ }, []);++ useEffect(() => {+ loadStatus();+ }, [loadStatus]);++ // Transport liveness (#33). The socket is the live source; the status GET+ // carries the same snapshot, handed up so the dot is right before the first+ // socket frame lands.+ useEffect(() => {+ if (status?.realtime) onRealtimeSeed?.(status.realtime);+ }, [status?.realtime, onRealtimeSeed]);++ const retryStatus = async () => {+ setStatusRetrying(true);+ await loadStatus();+ if (mountedRef.current) setStatusRetrying(false);+ };++ const handleSave = async () => {+ if (!await save()) return;+ toast.success('Saved');+ loadStatus();+ };++ // Write paths never retry — a repeat exchange burns an already-used+ // authorization code — so each of these reports its failure once and stops.+ // `silent: true` because the catch owns the toast (client/src/AGENTS.md).+ const handleConnect = async () => {+ setConnecting(true);+ const result = await startBeeperOAuth({ silent: true })+ .catch((err) => ({ error: err?.message || 'Could not start the Beeper connect flow' }));+ if (!mountedRef.current) return;+ setConnecting(false);+ if (result?.error || !result?.authorizationUrl) {+ toast.error(result?.error || 'Could not start the Beeper connect flow');+ return;+ }+ window.open(result.authorizationUrl, '_blank', 'noopener');+ toast.success('Approve the request in the opened Beeper window');+ };++ const handleSaveToken = async (event) => {+ event.preventDefault();+ const token = pastedToken.trim();+ if (!token) return;+ setSavingToken(true);+ const result = await saveBeeperToken(token, { silent: true })+ .catch((err) => ({ error: err?.message || 'Could not save that Beeper token' }));+ if (!mountedRef.current) return;+ setSavingToken(false);+ if (result?.error) {+ toast.error(result.error);+ return;+ }+ setPastedToken('');+ toast.success('Beeper token saved');+ loadStatus();+ };++ const handleDisconnect = async () => {+ setDisconnecting(true);+ const result = await disconnectBeeper({ silent: true })+ .catch((err) => ({ error: err?.message || 'Could not disconnect Beeper' }));+ if (!mountedRef.current) return;+ setDisconnecting(false);+ setConfirmingDisconnect(false);+ if (result?.error) {+ toast.error(result.error);+ return;+ }+ toast.success('Beeper disconnected');+ loadStatus();+ };++ const connect = {+ onConnect: handleConnect,+ connecting,+ token: pastedToken,+ onTokenChange: setPastedToken,+ onSaveToken: handleSaveToken,+ savingToken,+ onDisconnect: handleDisconnect,+ disconnecting,+ confirmingDisconnect,+ onConfirmDisconnect: setConfirmingDisconnect,+ };++ const handleCheck = async () => {+ setChecking(true);+ const result = await checkBeeperConnection({ silent: true }).catch((err) => ({ ok: false, error: err?.message || 'Could not reach Beeper Desktop' }));+ setChecking(false);+ if (result?.reachable) {+ toast.success(`Beeper Desktop reachable${result.info?.app?.version ? ` — v${result.info.app.version}` : ''}`);+ } else {+ toast.error(result?.error || 'Could not reach Beeper Desktop');+ }+ loadStatus();+ };++ if (settingsLoading) return <BrailleSpinner text="Loading Beeper settings" />;++ // A failed GET must never render as though it read DEFAULTS off this+ // install — `form`/`saved` inside the hook are the hardcoded fallback, not+ // this install's actual config, so hiding the ingestion form (rather than+ // showing it "successfully" pre-filled with defaults) and refusing Save is+ // what keeps a retry from PUTting those defaults over whatever is really+ // stored.+ if (settingsLoadFailed) {+ return (+ <div className="bg-port-card border border-port-error/40 rounded-lg p-4 sm:p-6">+ <div className="flex items-center gap-2 mb-2">+ <ShieldAlert size={16} className="text-port-error" />+ <h3 className="text-sm font-semibold text-white">Could not load Beeper settings</h3>+ </div>+ <p className="text-sm text-port-error">+ Reload the page and try again — saving now would overwrite the stored configuration with defaults.+ </p>+ </div>+ );+ }++ return (+ <div className="space-y-6">+ <div className="bg-port-card border border-port-border rounded-lg p-4 sm:p-6">+ <div className="flex items-center gap-2 mb-2">+ <MessageCircle size={16} className="text-port-accent" />+ <h3 className="text-lg font-semibold text-white">Beeper ingestion</h3>+ </div>+ <p className="text-sm text-gray-400 mb-4">+ Talks to the local Beeper Desktop API (default <code className="text-gray-300">{form.baseUrl}</code>) to+ mirror bridged-network conversations — WhatsApp, Discord, Telegram, Instagram, X, Slack, and more —+ into PortOS. Machine-local; nothing federates to peers. Connecting is handled by the card below —+ the credential is encrypted at rest and never stored in settings.+ </p>++ <div className="space-y-3">+ <label htmlFor="beeper-enabled" className="flex items-center gap-2 text-sm text-gray-200 cursor-pointer">+ <input+ id="beeper-enabled"+ type="checkbox"+ checked={form.enabled}+ onChange={(e) => setForm((prev) => ({ ...prev, enabled: e.target.checked }))}+ className="w-4 h-4 accent-port-accent"+ />+ Enable scheduled Beeper sync+ </label>++ <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">+ <div>+ <label htmlFor="beeper-interval" className="block text-xs uppercase tracking-wider text-gray-500 mb-1">+ Sync interval (minutes)+ </label>+ <input+ id="beeper-interval"+ type="number"+ min={1}+ max={1440}+ value={form.intervalMinutes}+ onChange={(e) => setForm((prev) => ({ ...prev, intervalMinutes: e.target.value }))}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"+ />+ </div>+ <div>+ <label htmlFor="beeper-budget" className="block text-xs uppercase tracking-wider text-gray-500 mb-1">+ Attachment budget (GB)+ </label>+ <input+ id="beeper-budget"+ type="number"+ min={0.1}+ step={0.1}+ max={1000}+ value={form.attachmentBudgetGb}+ onChange={(e) => setForm((prev) => ({ ...prev, attachmentBudgetGb: e.target.value }))}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"+ />+ </div>+ <div className="sm:col-span-1">+ <label htmlFor="beeper-base-url" className="block text-xs uppercase tracking-wider text-gray-500 mb-1">+ Base URL+ </label>+ <input+ id="beeper-base-url"+ type="text"+ value={form.baseUrl}+ onChange={(e) => setForm((prev) => ({ ...prev, baseUrl: e.target.value }))}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm font-mono"+ />+ </div>+ </div>++ {/* Loopback-only by default (SEC-2) — a non-loopback base URL would+ carry the Beeper access token off this machine on every request. */}+ <label htmlFor="beeper-allow-non-loopback" className="flex items-start gap-2 text-sm text-gray-200 cursor-pointer">+ <input+ id="beeper-allow-non-loopback"+ type="checkbox"+ checked={form.allowNonLoopbackBaseUrl}+ onChange={(e) => setForm((prev) => ({ ...prev, allowNonLoopbackBaseUrl: e.target.checked }))}+ className="w-4 h-4 mt-0.5 accent-port-accent"+ />+ <span>+ Allow a non-loopback base URL+ <span className="block text-xs text-gray-500">+ Off by default — a non-loopback address sends the Beeper access token off this machine on every request.+ </span>+ </span>+ </label>++ <div className="pt-1">+ <button+ type="button"+ onClick={handleSave}+ disabled={!dirty || saving}+ className="inline-flex items-center justify-center gap-2 min-h-[40px] px-4 py-2 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded-lg text-sm transition-colors disabled:opacity-40 disabled:cursor-not-allowed"+ >+ {saving ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />}+ {saving ? 'Saving…' : 'Save'}+ </button>+ </div>+ </div>+ </div>++ {/* The outbound runaway breaker (#36) — an actionable fault, so it renders+ on this settings surface with the other actionable faults rather than+ on the chat surface or as a global banner. Absent entirely unless it+ has actually tripped. `onBreakerCleared` (from `BeeperTab`) refreshes+ the page-level snapshot the composer reads, so Send re-enables the+ moment this clears rather than waiting on the composer's own next+ status fetch. */}+ <BeeperOutboxBreakerBanner+ breaker={status?.outbox?.breaker}+ onCleared={() => { loadStatus(); onBreakerCleared?.(); }}+ />++ <AttachmentMirrorCard budgetGb={form.attachmentBudgetGb} settingsDirty={dirty || saving} />++ {statusLoading ? (+ <BrailleSpinner text="Checking Beeper status" />+ ) : (+ <BeeperStatusCard+ status={status}+ realtime={realtimeProp || status?.realtime || null}+ error={statusError}+ connect={connect}+ checking={checking}+ onCheck={handleCheck}+ checkDisabled={dirty || saving}+ onRetryStatus={retryStatus}+ retryingStatus={statusRetrying}+ />+ )}+ </div>+ );+}++// The two connect paths, side by side rather than one behind the other (#11+// decision 3): OAuth is the quick path, pasting is the durable one, because+// Beeper's own UI can mint a token that never expires and nothing in the OAuth+// surface accepts a lifetime. The pasted value goes straight to the vaulted+// write path — it is never echoed back, never stored in settings, and never+// read back into this field.+function BeeperConnectPanel({ connect, submitLabel = 'Connect Beeper' }) {+ return (+ <div className="space-y-4">+ <div>+ <button+ type="button"+ onClick={connect.onConnect}+ disabled={connect.connecting}+ className="inline-flex items-center justify-center gap-2 min-h-[40px] px-4 py-2 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded-lg text-sm transition-colors disabled:opacity-40 disabled:cursor-not-allowed"+ >+ {connect.connecting ? <Loader2 size={14} className="animate-spin" /> : <Link2 size={14} />}+ {connect.connecting ? 'Opening Beeper…' : submitLabel}+ </button>+ <p className="text-xs text-gray-500 mt-1.5">+ Opens Beeper's approval screen and asks for read and send access. Tokens issued this way expire.+ </p>+ </div>++ <form onSubmit={connect.onSaveToken} className="space-y-2 border-t border-port-border pt-4">+ <label htmlFor="beeper-token" className="block text-xs uppercase tracking-wider text-gray-500">+ Or paste an access token+ </label>+ <p className="text-xs text-gray-500">+ Beeper's own settings can mint a token that never expires — the one credential the approval+ flow above cannot produce. PortOS stores it encrypted and never shows it again.+ </p>+ <div className="flex flex-col sm:flex-row gap-2">+ <input+ id="beeper-token"+ type="password"+ autoComplete="off"+ spellCheck={false}+ value={connect.token}+ onChange={(e) => connect.onTokenChange(e.target.value)}+ placeholder="Access token"+ className="flex-1 min-w-0 px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm font-mono"+ />+ <button+ type="submit"+ disabled={!connect.token.trim() || connect.savingToken}+ className="inline-flex items-center justify-center gap-2 min-h-[40px] px-4 py-2 bg-port-bg border border-port-border hover:border-port-accent text-gray-200 rounded-lg text-sm transition-colors disabled:opacity-40 disabled:cursor-not-allowed"+ >+ {connect.savingToken ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />}+ {connect.savingToken ? 'Saving…' : 'Save token'}+ </button>+ </div>+ </form>+ </div>+ );+}++// Inline two-step confirmation — no window.confirm (client/src/AGENTS.md).+// Disconnecting revokes the credential where the authorization server supports+// it and always deletes the local copy, so it is worth a deliberate second+// click but not a modal.+function DisconnectButton({ connect }) {+ if (!connect.confirmingDisconnect) {+ return (+ <button+ type="button"+ onClick={() => connect.onConfirmDisconnect(true)}+ className="inline-flex items-center justify-center gap-2 min-h-[36px] px-3 py-1.5 bg-port-bg border border-port-border hover:border-port-error text-gray-300 rounded-lg text-xs transition-colors"+ >+ <Unlink size={12} />+ Disconnect+ </button>+ );+ }+ return (+ <div className="flex flex-wrap items-center gap-2">+ <span className="text-xs text-gray-400">Forget this Beeper credential?</span>+ <button+ type="button"+ onClick={connect.onDisconnect}+ disabled={connect.disconnecting}+ className="inline-flex items-center justify-center gap-2 min-h-[36px] px-3 py-1.5 bg-port-error/20 hover:bg-port-error/30 text-port-error-text rounded-lg text-xs transition-colors disabled:opacity-40"+ >+ {connect.disconnecting ? <Loader2 size={12} className="animate-spin" /> : <Unlink size={12} />}+ {connect.disconnecting ? 'Disconnecting…' : 'Yes, disconnect'}+ </button>+ <button+ type="button"+ onClick={() => connect.onConfirmDisconnect(false)}+ disabled={connect.disconnecting}+ className="min-h-[36px] px-3 py-1.5 text-xs text-gray-400 hover:text-gray-200 transition-colors disabled:opacity-40"+ >+ Cancel+ </button>+ </div>+ );+}++// Shown whenever a stored token is inside the expiry warning window,+// regardless of whether Beeper Desktop is currently reachable — an expired+// token is exactly as actionable on an unreachable install as on a+// connected one, so this renders in both the `reachable === false` and+// `reachable === true` branches below.+function TokenExpiryNotice({ status }) {+ if (!status?.tokenExpiringSoon) return null;+ const days = status.tokenExpiresInDays;+ const label = Number.isFinite(days) && days <= 0+ ? 'Token has expired — reconnect to keep syncing.'+ : `Token expires in ${days} day(s) — reconnect soon.`;+ return (+ <p className="text-xs text-port-warning flex items-center gap-1.5">+ <Clock size={12} />+ {label}+ </p>+ );+}++// The granted-scopes line (fork issue #78): sits beside `TokenExpiryNotice`+// for the same reason — a read-only grant is exactly the kind of thing that+// should be visible on the card BEFORE a send fails, not discovered from the+// error it causes. `tokenScopes` is always an array (`[]` when unknown), the+// absent-vs-empty rule applied to a source rather than a value: a pasted+// token (#11 decision 3) never carries scopes back from Beeper's own paste+// UI, so `[]` there is honest and gets said out loud; `[]` from anywhere else+// (the legacy plaintext path) has nothing worth claiming, so this renders+// nothing rather than a bogus "no scopes granted" line.+function TokenScopesNotice({ status }) {+ const scopes = Array.isArray(status?.tokenScopes) ? status.tokenScopes : [];+ if (scopes.length === 0) {+ if (status?.tokenSource !== 'pasted') return null;+ return (+ <p className="text-xs text-gray-500">Scopes unknown (pasted token).</p>+ );+ }+ const readOnly = !scopes.includes('write');+ return (+ <div className="space-y-1">+ <p className="text-xs text-gray-500">Scopes: {scopes.join(', ')}</p>+ {readOnly && (+ <p className="text-xs text-port-warning flex items-center gap-1.5">+ <ShieldAlert size={12} />+ Read-only grant — sending will fail.+ </p>+ )}+ </div>+ );+}++// The transport liveness row (#33 decision 4): a Moltworld-shape dot, and — on+// the same card, never in a global banner — the one `app.state` value a human+// has to act on. Rendered in EVERY branch where a token is configured, not only+// the reachable one: the HTTP probe failing is exactly when the socket's own+// liveness and its `needs-login` remedy are worth reading. `initializing` is deliberately absent from the actionable set:+// it was measured lying for 105 continuous seconds on a fully working install,+// so surfacing it would train the user to ignore this line.+const APP_STATE_REMEDY = {+ 'needs-login': 'Beeper Desktop needs you to sign in again.',+ 'needs-verification': 'Beeper Desktop needs this device verified.',+ 'needs-secrets': 'Beeper Desktop is missing its encryption secrets.',+ 'needs-cross-signing-setup': 'Beeper Desktop needs cross-signing set up.',+};++// The transport stood down because Beeper answered the upgrade with 401/403.+// Reconnecting could only ever produce the same answer, so the fix is a human's.+const TOKEN_REJECTED_REMEDY = 'Beeper Desktop rejected the stored token — reconnect Beeper.';++// `showRemedy` exists for the one card that IS the remedy: the expired-token+// branch below already says "reconnect Beeper" in its heading, its body and its+// button, and a token that expired is exactly the token the transport's own+// 401 stand-down reports as `authRejected` — so the dot still belongs there+// (it corroborates that the socket is down for that reason and not looping),+// while a fourth copy of the same instruction does not.+function BeeperRealtimeRow({ realtime, showRemedy = true }) {+ // `null` = the transport has not reported yet. Never rendered as offline.+ if (!realtime?.state) return null;+ const remedy = !showRemedy ? null : (realtime.authRejected+ ? TOKEN_REJECTED_REMEDY+ : (realtime.appStateActionable ? APP_STATE_REMEDY[realtime.appState] : null));+ return (+ <div className="space-y-1">+ <ConnectionStatusDot status={realtime.state} label="Realtime:" />+ {remedy && (+ <p className="text-xs text-port-warning flex items-center gap-1.5">+ <ShieldAlert size={12} />+ {remedy}+ </p>+ )}+ </div>+ );+}++/**+ * The sweep-visibility row (#80), rendered in EVERY reachability state+ * alongside `BeeperRealtimeRow` — the drawer card's own copy of the same+ * "Syncing… N of M accounts" / "Last synced HH:MM" strip the chat surface's+ * list header shows, so a user who opened settings instead of the chat+ * surface still sees whether ingestion is doing anything. `null` (no sweep+ * has ever run on this install) renders nothing, same absent-vs-never rule+ * `BeeperRealtimeRow` follows for a transport that has not reported yet.+ */+function SweepStatusRow({ 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 (+ <p className="text-xs text-gray-400 flex items-center gap-1.5">+ <Loader2 size={12} className="animate-spin" />+ {total === null ? 'Syncing…' : `Syncing… ${done} of ${total} account${total === 1 ? '' : 's'}`}+ </p>+ );+ }+ if (!sweep.finishedAt) return null;+ return (+ <p className="text-xs text-gray-500">+ Last synced {formatClockTime(sweep.finishedAt, { seconds: false })}+ </p>+ );+}++/**+ * The mirrored account roster (#30), rendered in EVERY reachability state.+ *+ * These rows come from `beeper_accounts` — PortOS's own mirror — not from a+ * live call, which is the whole reason #27 stores them: the card is supposed to+ * render with Beeper Desktop closed. Hiding the roster whenever the probe fails+ * threw away information the install already had and made an unreachable app+ * look like an empty one, so reachability is stated on its own line above and+ * the roster stands beside it.+ *+ * Read-only by design: it never offers to add a network. Joined by `accountId`,+ * never by `network`.+ *+ * `accounts: null` (paired with `error`) is a FAILED mirror read, distinct+ * from `accounts: []` (a successful read that legitimately found none yet) —+ * the absent-vs-empty sentinel (root AGENTS.md). Collapsing the two would show+ * "No accounts mirrored yet" for a DB hiccup, which reads as a healthy,+ * disconnected-feeling install rather than the unknown state it actually is.+ */+function AccountRoster({ accounts, error }) {+ if (error) {+ return (+ <div className="space-y-1.5">+ <p className="text-[11px] uppercase tracking-wide text-gray-500">Mirrored accounts</p>+ <p role="alert" data-testid="beeper-roster-unknown" className="text-sm text-port-error">{error}</p>+ </div>+ );+ }+ const rows = Array.isArray(accounts) ? accounts : [];+ return (+ <div className="space-y-1.5">+ <p className="text-[11px] uppercase tracking-wide text-gray-500">Mirrored accounts</p>+ {rows.length === 0 ? (+ <p data-testid="beeper-roster-empty" className="text-sm text-gray-500">No accounts mirrored yet.</p>+ ) : (+ <ul data-testid="beeper-roster" className="space-y-1.5">+ {rows.map((account) => (+ <li key={account.accountId} className="flex items-center justify-between text-sm text-gray-300 border-t border-port-border pt-1.5 first:border-t-0 first:pt-0">+ <span>{account.displayName || account.accountId}</span>+ <span className="text-xs text-gray-500 uppercase">{account.network || '—'}</span>+ </li>+ ))}+ </ul>+ )}+ </div>+ );+}++// Every state the status card can be in, decided at fork issue #11 and+// carried into #30's Acceptance criteria. `reachable` is read with strict+// equality throughout (`=== false` / `=== true` / `=== null`) — never+// truthiness — so the absent-vs-empty sentinel (`null` = not yet probed)+// can never fall through to the "offline" branch. A failed status fetch is+// handled by the `error` branch immediately below, before any of this ever+// runs, so a broken GET can never collapse into "no token configured".+function BeeperStatusCard({+ status, realtime, error, connect, checking, onCheck, checkDisabled, onRetryStatus, retryingStatus,+}) {+ if (error) {+ return (+ <div className="bg-port-card border border-port-error/40 rounded-lg p-4 sm:p-6">+ <div className="flex items-center gap-2 mb-2">+ <ShieldAlert size={16} className="text-port-error" />+ <h3 className="text-sm font-semibold text-white">Could not read Beeper status</h3>+ </div>+ <p role="alert" className="text-sm text-port-error">{error}</p>+ <button+ type="button"+ onClick={onRetryStatus}+ disabled={retryingStatus}+ className="mt-3 inline-flex items-center justify-center gap-2 min-h-[40px] px-4 py-2 bg-port-bg border border-port-border hover:border-port-accent text-gray-200 rounded-lg text-sm transition-colors disabled:opacity-40"+ >+ {retryingStatus ? <Loader2 size={14} className="animate-spin" /> : <RefreshCw size={14} />}+ Retry+ </button>+ </div>+ );+ }++ if (!status?.tokenConfigured) {+ return (+ <div className="bg-port-card border border-port-border rounded-lg p-4 sm:p-6">+ <div className="flex items-center gap-2 mb-2">+ <MessageCircle size={16} className="text-gray-400" />+ <h3 className="text-sm font-semibold text-white">Connect Beeper</h3>+ </div>+ <p className="text-sm text-gray-400 mb-4">+ Beeper is a local desktop app that bridges WhatsApp, Discord, Telegram, and other networks into one+ API on this machine — PortOS talks to it over loopback, never over the network.+ </p>+ <BeeperConnectPanel connect={connect} />+ </div>+ );+ }++ // An expired credential is its own state, not a generic API failure: there is+ // no refresh grant anywhere in Beeper's OAuth metadata, so the only way+ // forward is connecting again. Checked BEFORE reachability so a user whose+ // token lapsed while Beeper Desktop happens to be closed still gets the+ // action that fixes it rather than "unreachable".+ if (status.tokenExpired) {+ return (+ <div className="bg-port-card border border-port-warning/40 rounded-lg p-4 sm:p-6">+ <div className="flex items-center gap-2 mb-2">+ <Clock size={16} className="text-port-warning" />+ <h3 className="text-sm font-semibold text-white">Beeper token expired</h3>+ </div>+ <p className="text-sm text-gray-400 mb-4">+ Beeper issues no refresh grant, so an expired token is reconnected rather than renewed.+ </p>+ <div className="mb-3"><BeeperRealtimeRow realtime={realtime} showRemedy={false} /></div>+ <BeeperConnectPanel connect={connect} submitLabel="Reconnect Beeper" />+ <div className="mt-4 border-t border-port-border pt-3">+ <DisconnectButton connect={connect} />+ </div>+ </div>+ );+ }++ if (status.reachable === false) {+ return (+ <div className="bg-port-card border border-port-error/40 rounded-lg p-4 sm:p-6">+ <div className="flex items-center gap-2 mb-2">+ <ShieldAlert size={16} className="text-port-error" />+ <h3 className="text-sm font-semibold text-white">Beeper Desktop unreachable</h3>+ </div>+ <p className="text-sm text-port-error">{status.lastProbeError || 'Could not reach Beeper Desktop.'}</p>+ <p className="text-xs text-gray-500 mt-1">Checked against {status.baseUrl}.</p>+ <TokenExpiryNotice status={status} />+ <TokenScopesNotice status={status} />+ <div className="mt-2"><BeeperRealtimeRow realtime={realtime} /></div>+ <div className="mt-1"><SweepStatusRow sweep={status.sweep} /></div>+ {/* The mirror still knows which accounts exist even with Beeper closed. */}+ <div className="mt-3"><AccountRoster accounts={status.accounts} error={status.accountsError} /></div>+ <div className="mt-3 flex flex-wrap items-center gap-2">+ <button+ type="button"+ onClick={onCheck}+ disabled={checking || checkDisabled}+ title={checkDisabled ? 'Save your changes before rechecking' : undefined}+ className="inline-flex items-center justify-center gap-2 min-h-[40px] px-4 py-2 bg-port-bg border border-port-border hover:border-port-accent text-gray-200 rounded-lg text-sm transition-colors disabled:opacity-40"+ >+ {checking ? <Loader2 size={14} className="animate-spin" /> : <RefreshCw size={14} />}+ Retry+ </button>+ <DisconnectButton connect={connect} />+ </div>+ </div>+ );+ }++ if (status.reachable === true) {+ // Fork issue #61, decision 7: a probe timeout shortly after Beeper+ // Desktop proved itself alive (a real API call, or a live socket ping)+ // stays on THIS card — `reachable` never flips to false for it — with an+ // inline note naming the latency, rather than jumping to the unreachable/+ // actionable-fault card below. The empty-state ("Connect Beeper") and+ // Retry-button branches never see `probeState` at all, so neither can flip+ // on a slow probe.+ const isSlow = status.probeState === 'slow';+ return (+ <div className="bg-port-card border border-port-success/40 rounded-lg p-4 sm:p-6 space-y-3">+ <div className="flex items-center gap-2">+ <ShieldCheck size={16} className="text-port-success" />+ <h3 className="text-sm font-semibold text-white">Beeper Desktop connected</h3>+ {status.appVersion && <span className="text-xs text-gray-500">v{status.appVersion}</span>}+ </div>+ {isSlow && (+ <p className="text-xs text-port-warning flex items-center gap-1.5">+ <Clock size={12} />+ Slow to respond{Number.isFinite(status.probeLatencyMs) ? ` (${status.probeLatencyMs}ms)` : ''} — Beeper Desktop is up but answered the last check slowly.+ </p>+ )}+ <TokenExpiryNotice status={status} />+ <TokenScopesNotice status={status} />+ <BeeperRealtimeRow realtime={realtime} />+ <SweepStatusRow sweep={status.sweep} />+ <AccountRoster accounts={status.accounts} error={status.accountsError} />+ <div className="flex flex-wrap items-center gap-2">+ <button+ type="button"+ onClick={onCheck}+ disabled={checking || checkDisabled}+ title={checkDisabled ? 'Save your changes before rechecking' : undefined}+ className="inline-flex items-center justify-center gap-2 min-h-[36px] px-3 py-1.5 bg-port-bg border border-port-border hover:border-port-accent text-gray-200 rounded-lg text-xs transition-colors disabled:opacity-40"+ >+ {checking ? <Loader2 size={12} className="animate-spin" /> : <RefreshCw size={12} />}+ Recheck+ </button>+ <DisconnectButton connect={connect} />+ </div>+ </div>+ );+ }++ // reachable === null: a token is configured but the probe never ran (a+ // transient gap between saving settings and the status refresh landing).+ // Neutral, never rendered as offline.+ return (+ <div className="bg-port-card border border-port-border rounded-lg p-4 sm:p-6 space-y-2">+ <div className="flex items-center gap-2">+ <Loader2 size={16} className="text-gray-400 animate-spin" />+ <h3 className="text-sm font-semibold text-white">Checking Beeper Desktop…</h3>+ </div>+ <BeeperRealtimeRow realtime={realtime} />+ <SweepStatusRow sweep={status.sweep} />+ <AccountRoster accounts={status.accounts} error={status.accountsError} />+ </div>+ );+}++/**+ * The attachment byte mirror's own card (#37): what is on disk against the+ * budget, and the ONE place a bulk backfill can be started.+ *+ * The backfill is gated behind a consent modal that names the count and the+ * byte size first. That is the root AGENTS.md no-unbidden-work policy applied+ * to bytes rather than to LLM calls, and it is the same split as+ * `meatspacePostDrillCache` / `CacheFillConsentModal`: the incremental+ * fetch-on-view needs no prompt because the user opened the thread, while a+ * from-zero batch of thousands of files does.+ *+ * "Mirror all" gates on the SAVED budget, not the form input: the server reads+ * `settings.beeper.attachmentBudgetGb` when it decides where to stop, so+ * running with an unsaved number would silently use the old one.+ */+function AttachmentMirrorCard({ budgetGb, settingsDirty }) {+ const [summary, setSummary] = useState(null);+ const [summaryError, setSummaryError] = useState(null);+ const [loading, setLoading] = useState(true);+ const [consentOpen, setConsentOpen] = useState(false);+ const [running, setRunning] = useState(false);+ const mountedRef = useMounted();++ const loadSummary = useCallback(async () => {+ const [result, error] = await getBeeperAttachmentSummary({ silent: true })+ .then((value) => [value, null])+ .catch((err) => [null, err]);+ if (!mountedRef.current) return;+ setSummary(result);+ // "The request failed" and "the mirror is empty" are different answers, and+ // only one of them means the numbers below are trustworthy.+ setSummaryError(error ? (error?.message || 'Could not read the attachment mirror') : null);+ setLoading(false);+ }, []);++ useEffect(() => { loadSummary(); }, [loadSummary]);++ const handleBackfill = async () => {+ setConsentOpen(false);+ setRunning(true);+ const result = await backfillBeeperAttachments({}, { silent: true }).catch((err) => {+ toast.error(err?.message || 'Attachment backfill failed');+ return null;+ });+ if (!mountedRef.current) return;+ setRunning(false);+ if (result) {+ toast.success(+ `Mirrored ${result.fetched} attachment(s)${result.failed ? `, ${result.failed} unavailable` : ''}`+ + `${result.stoppedForBudget ? ' — stopped at the disk budget' : ''}`,+ );+ }+ loadSummary();+ };++ if (loading) return <BrailleSpinner text="Reading the attachment mirror" />;++ const budgetBytes = summary?.budgetBytes || 0;+ const usedBytes = summary?.usedBytes || 0;+ const usedPercent = budgetBytes > 0 ? Math.min(100, Math.round((usedBytes / budgetBytes) * 100)) : 0;+ const pending = summary?.pendingCount || 0;++ return (+ <div className="bg-port-card border border-port-border rounded-lg p-4 sm:p-6 space-y-3">+ <div className="flex items-center gap-2">+ <HardDrive size={16} className="text-port-accent" />+ <h3 className="text-lg font-semibold text-white">Attachment mirror</h3>+ </div>+ <p className="text-sm text-gray-400">+ Attachment bytes are downloaded when you first open the thread that shows them, kept under the+ {' '}{budgetGb} GB budget above, and evicted least-recently-viewed first — never a file Beeper can no+ longer re-supply, and never one you locked. Photos and files stay on this machine.+ </p>++ {summaryError ? (+ <p className="text-xs text-port-error">{summaryError}</p>+ ) : (+ <>+ <div>+ <div className="flex items-center justify-between text-xs text-gray-400">+ <span>{formatBytes(usedBytes)} of {formatBytes(budgetBytes)}</span>+ <span>{summary?.storedFiles || 0} file(s) mirrored</span>+ </div>+ <div className="mt-1 h-1.5 w-full overflow-hidden rounded-full bg-port-bg">+ <div className="h-full rounded-full bg-port-accent" style={{ width: `${usedPercent}%` }} />+ </div>+ </div>++ <div className="grid grid-cols-2 gap-2 sm:grid-cols-4">+ <Stat label="Not mirrored" value={pending} />+ <Stat label="Kept" value={summary?.keptCount || 0} />+ <Stat label="Over limit" value={summary?.overCapCount || 0} />+ <Stat label="Unavailable" value={summary?.unavailableCount || 0} />+ </div>++ <div className="flex flex-wrap items-center gap-2 pt-1">+ <button+ type="button"+ onClick={() => setConsentOpen(true)}+ disabled={running || pending === 0 || settingsDirty}+ title={settingsDirty ? 'Save your settings first — the backfill reads the saved budget' : undefined}+ className="inline-flex items-center justify-center gap-2 min-h-[36px] px-3 py-1.5 bg-port-bg border border-port-border hover:border-port-accent text-gray-200 rounded-lg text-xs transition-colors disabled:opacity-40"+ >+ {running ? <Loader2 size={12} className="animate-spin" /> : <Download size={12} />}+ {running ? 'Mirroring…' : 'Mirror all attachments'}+ </button>+ <button+ type="button"+ onClick={loadSummary}+ className="inline-flex items-center justify-center gap-2 min-h-[36px] px-3 py-1.5 text-gray-400 hover:text-gray-200 rounded-lg text-xs transition-colors"+ >+ <RefreshCw size={12} />+ Refresh+ </button>+ </div>+ </>+ )}++ <BackfillConsentModal+ open={consentOpen}+ summary={summary}+ onCancel={() => setConsentOpen(false)}+ onConfirm={handleBackfill}+ />+ </div>+ );+}++function Stat({ label, value }) {+ return (+ <div className="rounded border border-port-border bg-port-bg/50 px-2 py-1.5">+ <p className="text-[11px] uppercase tracking-wide text-gray-500">{label}</p>+ <p className="text-sm text-gray-200">{value}</p>+ </div>+ );+}++/**+ * Names the cost before the transfer starts: how many attachments, how many+ * bytes, and — separately — how many the bridge never reported a size for, so+ * the total is never quietly presented as complete when it isn't.+ */+function BackfillConsentModal({ open, summary, onCancel, onConfirm }) {+ if (!open || !summary) return null;+ const unknown = summary.pendingUnknownCount || 0;+ return (+ <Modal open={open} onClose={onCancel} size="sm" ariaLabel="Mirror all Beeper attachments">+ <div className="bg-port-card border border-port-border rounded-lg p-5 space-y-4">+ <div className="flex items-center gap-2">+ <Download size={18} className="text-port-accent" />+ <h3 className="text-white font-medium">Mirror all attachments?</h3>+ </div>+ <p className="text-sm text-gray-400">+ PortOS will download <span className="text-gray-200">{summary.pendingCount} attachment(s)</span>+ {' '}from Beeper Desktop — about <span className="text-gray-200">{formatBytes(summary.pendingBytes)}</span>+ {unknown > 0 && <> plus {unknown} whose size Beeper did not report</>}.+ {' '}It stops when the mirror reaches its {formatBytes(summary.budgetBytes)} budget, skips anything over+ {' '}{formatBytes(summary.maxBytes)}, and runs one file at a time so Beeper Desktop stays usable.+ </p>+ <p className="text-xs text-gray-500">+ You do not need this to read attachments: opening a thread mirrors what it shows. This is for having+ them all on disk in advance.+ </p>+ <div className="flex flex-wrap justify-end gap-2">+ <button+ type="button"+ onClick={onCancel}+ className="min-h-[36px] px-3 text-xs text-gray-400 transition-colors hover:text-gray-200"+ >+ Cancel+ </button>+ <button+ type="button"+ onClick={onConfirm}+ className="inline-flex min-h-[36px] items-center gap-1.5 rounded-lg bg-port-accent/20 px-3 text-xs text-port-accent transition-colors hover:bg-port-accent/30"+ >+ <Download size={12} />+ Mirror {summary.pendingCount} attachment(s)+ </button>+ </div>+ </div>+ </Modal>+ );+}diff --git a/client/src/components/messages/beeper/BeeperSettingsPanel.test.jsx b/client/src/components/messages/beeper/BeeperSettingsPanel.test.jsxnew file mode 100644index 0000000000..943981f721--- /dev/null+++ b/client/src/components/messages/beeper/BeeperSettingsPanel.test.jsx@@ -0,0 +1,632 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';++const api = vi.hoisted(() => ({+ getSettings: vi.fn(),+ updateSettings: vi.fn(),+ getBeeperStatus: vi.fn(),+ checkBeeperConnection: vi.fn(),+ startBeeperOAuth: vi.fn(),+ saveBeeperToken: vi.fn(),+ disconnectBeeper: vi.fn(),+ getBeeperAttachmentSummary: vi.fn(),+ backfillBeeperAttachments: vi.fn(),+}));+const toast = vi.hoisted(() => Object.assign(vi.fn(), { error: vi.fn(), success: vi.fn() }));++vi.mock('../../../services/api', () => api);+vi.mock('../../ui/Toast', () => ({ default: toast }));++const BeeperSettingsPanel = (await import('./BeeperSettingsPanel')).default;++const BASE_SETTINGS = { beeper: { enabled: false, intervalMinutes: 5, baseUrl: 'http://127.0.0.1:23373', attachmentBudgetGb: 5 } };++// No router: the panel takes `realtime` as a prop and reads nothing off the+// URL — the OAuth outcome flag is the page shell's job, covered by the page's+// own suite.+const renderPanel = (props = {}) => render(<BeeperSettingsPanel {...props} />);++const BASE_ATTACHMENT_SUMMARY = {+ budgetBytes: 5 * 1024 * 1024 * 1024,+ usedBytes: 1024 * 1024,+ storedFiles: 2,+ pendingCount: 0,+ pendingBytes: 0,+ pendingUnknownCount: 0,+ overCapCount: 0,+ unavailableCount: 0,+ keptCount: 0,+ totalCount: 2,+ maxBytes: 32 * 1024 * 1024,+};++beforeEach(() => {+ vi.clearAllMocks();+ api.getSettings.mockResolvedValue(BASE_SETTINGS);+ api.getBeeperAttachmentSummary.mockResolvedValue(BASE_ATTACHMENT_SUMMARY);+});++// The three states decided at fork issue #11 and carried into #30's+// Acceptance criteria, plus the defensive fourth (absent-vs-empty sentinel).+describe('BeeperSettingsPanel — status card states', () => {+ it('offers both connect paths and nothing else when no token is configured', async () => {+ api.getBeeperStatus.mockResolvedValue({+ tokenConfigured: false, reachable: null, lastProbeError: null, accounts: [],+ });+ renderPanel();++ expect(await screen.findByRole('heading', { name: 'Connect Beeper' })).toBeInTheDocument();+ // Both paths are first-class (#11 decision 3), so both are on screen at once.+ expect(screen.getByRole('button', { name: 'Connect Beeper' })).not.toBeDisabled();+ expect(screen.getByLabelText('Or paste an access token')).toBeInTheDocument();+ expect(screen.queryByText('Beeper Desktop unreachable')).toBeNull();+ expect(screen.queryByText('Beeper Desktop connected')).toBeNull();+ expect(screen.queryByText('Checking Beeper Desktop…')).toBeNull();+ });++ it('renders the actionable-fault card with a Retry when a token is present but unreachable', async () => {+ api.getBeeperStatus.mockResolvedValue({+ tokenConfigured: true, reachable: false, lastProbeError: 'Beeper request failed: connection refused', baseUrl: 'http://127.0.0.1:23373', accounts: [],+ });+ renderPanel();++ expect(await screen.findByText('Beeper Desktop unreachable')).toBeInTheDocument();+ expect(screen.getByText('Beeper request failed: connection refused')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: /Retry/ })).toBeInTheDocument();+ });++ it('renders the connected state with an empty roster when the mirror holds no accounts', async () => {+ api.getBeeperStatus.mockResolvedValue({+ tokenConfigured: true, reachable: true, lastProbeError: null, appVersion: '4.3.73', accounts: [],+ });+ renderPanel();++ expect(await screen.findByText('Beeper Desktop connected')).toBeInTheDocument();+ expect(screen.getByTestId('beeper-roster-empty')).toBeInTheDocument();+ });++ // Fork issue #78: the granted scopes render beside the expiry line, and a+ // grant that includes `write` gets no read-only warning.+ it('renders the granted scopes on the connected card', async () => {+ api.getBeeperStatus.mockResolvedValue({+ tokenConfigured: true, reachable: true, lastProbeError: null, accounts: [],+ tokenScopes: ['read', 'write'],+ });+ renderPanel();++ expect(await screen.findByText('Beeper Desktop connected')).toBeInTheDocument();+ expect(screen.getByText('Scopes: read, write')).toBeInTheDocument();+ expect(screen.queryByText(/read-only grant/i)).toBeNull();+ });++ // A grant missing `write` is exactly the read-only-token case #78 exists to+ // surface BEFORE a send fails, not after.+ it('warns that sending will fail when the grant is missing the write scope', async () => {+ api.getBeeperStatus.mockResolvedValue({+ tokenConfigured: true, reachable: true, lastProbeError: null, accounts: [],+ tokenScopes: ['read'],+ });+ renderPanel();++ expect(await screen.findByText('Scopes: read')).toBeInTheDocument();+ expect(screen.getByText('Read-only grant — sending will fail.')).toBeInTheDocument();+ });++ // A pasted token (#11 decision 3) never carries scopes back from Beeper's+ // own paste UI, so an empty array there is said out loud rather than+ // rendered as if nothing were known.+ it('says scopes are unknown for a pasted token with no scopes', async () => {+ api.getBeeperStatus.mockResolvedValue({+ tokenConfigured: true, tokenSource: 'pasted', reachable: true, lastProbeError: null, accounts: [],+ tokenScopes: [],+ });+ renderPanel();++ expect(await screen.findByText('Beeper Desktop connected')).toBeInTheDocument();+ expect(screen.getByText('Scopes unknown (pasted token).')).toBeInTheDocument();+ });++ // An empty scopes array from anywhere else (the legacy plaintext path) has+ // nothing worth claiming — this must not render a bogus "no scopes" line.+ it('renders nothing for an empty scopes list that is not a pasted token', async () => {+ api.getBeeperStatus.mockResolvedValue({+ tokenConfigured: true, tokenSource: 'legacy-settings', reachable: true, lastProbeError: null, accounts: [],+ tokenScopes: [],+ });+ renderPanel();++ expect(await screen.findByText('Beeper Desktop connected')).toBeInTheDocument();+ expect(screen.queryByText(/Scopes/)).toBeNull();+ });++ // The drawer card's own copy of the list header's sweep-visibility strip+ // (#80) — same status payload, different surface.+ it('shows a running sweep on the drawer card', async () => {+ api.getBeeperStatus.mockResolvedValue({+ tokenConfigured: true, reachable: true, lastProbeError: null, accounts: [],+ sweep: {+ running: true, startedAt: '2026-09-05T10:00:00.000Z', finishedAt: null, reason: 'scheduler',+ accountsDone: 3, accountsTotal: 9, chats: 40, messages: 812,+ },+ });+ renderPanel();++ expect(await screen.findByText('Syncing… 3 of 9 accounts')).toBeInTheDocument();+ });++ it('shows the last-synced time on the drawer card once idle', async () => {+ api.getBeeperStatus.mockResolvedValue({+ tokenConfigured: true, reachable: true, lastProbeError: null, accounts: [],+ sweep: {+ running: false, startedAt: '2026-09-05T10:00:00.000Z', finishedAt: '2026-09-05T10:04:00.000Z', reason: 'manual',+ accountsDone: 9, accountsTotal: 9, chats: 210, messages: 4032,+ },+ });+ renderPanel();++ expect(await screen.findByText(/Last synced \d{1,2}:\d{2}/)).toBeInTheDocument();+ });++ // The mirrored roster comes from `beeper_accounts`, not from a live call —+ // which is why #27 stores it. Hiding it whenever the probe fails threw away+ // what the install already knew and made an unreachable app look like an+ // empty one, so reachability is stated on its own line and the roster stands+ // beside it in every reachability state.+ it('keeps the mirrored roster on screen while Beeper Desktop is unreachable', async () => {+ api.getBeeperStatus.mockResolvedValue({+ tokenConfigured: true,+ reachable: false,+ lastProbeError: 'Beeper request failed: connection refused',+ baseUrl: 'http://127.0.0.1:23373',+ accounts: [{ accountId: 'acc1', displayName: 'Example WhatsApp', network: 'whatsapp' }],+ });+ renderPanel();++ expect(await screen.findByText('Beeper Desktop unreachable')).toBeInTheDocument();+ expect(screen.getByText('Example WhatsApp')).toBeInTheDocument();+ expect(screen.getByText('whatsapp')).toBeInTheDocument();+ });++ it('keeps the mirrored roster on screen while the probe has not run yet', async () => {+ api.getBeeperStatus.mockResolvedValue({+ tokenConfigured: true,+ reachable: null,+ lastProbeError: null,+ accounts: [{ accountId: 'acc1', displayName: 'Example WhatsApp', network: 'whatsapp' }],+ });+ renderPanel();++ expect(await screen.findByText('Checking Beeper Desktop…')).toBeInTheDocument();+ expect(screen.getByText('Example WhatsApp')).toBeInTheDocument();+ });++ it('renders the connected state with the account roster when accounts are mirrored', async () => {+ api.getBeeperStatus.mockResolvedValue({+ tokenConfigured: true, reachable: true, lastProbeError: null, accounts: [+ { accountId: 'acc1', displayName: 'Example WhatsApp', network: 'whatsapp' },+ ],+ });+ renderPanel();++ expect(await screen.findByText('Example WhatsApp')).toBeInTheDocument();+ expect(screen.getByText('whatsapp')).toBeInTheDocument();+ });++ it('renders the transport liveness dot from the status payload, with its actionable app.state remedy (#33)', async () => {+ api.getBeeperStatus.mockResolvedValue({+ tokenConfigured: true,+ reachable: true,+ lastProbeError: null,+ accounts: [],+ realtime: {+ state: 'reconnecting', lastEventAt: null, lastPingAt: null, appState: 'needs-login', appStateActionable: true,+ },+ });+ renderPanel();++ await screen.findByText('Beeper Desktop connected');+ expect(screen.getByTestId('connection-status-dot')).toHaveAttribute('data-status', 'reconnecting');+ expect(screen.getByText('Beeper Desktop needs you to sign in again.')).toBeInTheDocument();+ });++ it('renders the liveness row while Beeper Desktop is unreachable — the probe failing is when it matters', async () => {+ // The HTTP probe and the WebSocket are different transports: hiding the dot+ // and its remedy inside the reachable branch hid them exactly when a human+ // needed them.+ api.getBeeperStatus.mockResolvedValue({+ tokenConfigured: true,+ reachable: false,+ lastProbeError: 'Beeper request failed: connection refused',+ baseUrl: 'http://127.0.0.1:23373',+ accounts: [],+ realtime: {+ state: 'connecting', lastEventAt: null, lastPingAt: null, appState: 'needs-login', appStateActionable: true,+ },+ });+ renderPanel();++ await screen.findByText('Beeper Desktop unreachable');+ expect(screen.getByTestId('connection-status-dot')).toHaveAttribute('data-status', 'connecting');+ expect(screen.getByText('Beeper Desktop needs you to sign in again.')).toBeInTheDocument();+ });++ it('names the remedy when Beeper rejected the stored token (#33)', async () => {+ api.getBeeperStatus.mockResolvedValue({+ tokenConfigured: true,+ reachable: null,+ lastProbeError: null,+ accounts: [],+ realtime: {+ state: 'down', lastEventAt: null, lastPingAt: null, appState: null, appStateActionable: false, authRejected: true,+ },+ });+ renderPanel();++ await screen.findByText('Checking Beeper Desktop…');+ expect(screen.getByTestId('connection-status-dot')).toHaveAttribute('data-status', 'down');+ expect(screen.getByText('Beeper Desktop rejected the stored token — reconnect Beeper.')).toBeInTheDocument();+ });++ // #31's expired-token card and #33's 401 stand-down describe the same+ // credential from two transports, so they have to read as one story: the dot+ // corroborates that the socket is down for that reason (and not looping),+ // while the "reconnect Beeper" instruction is said once, by the card.+ it('shows the transport down on the expired-token card without repeating its remedy', async () => {+ api.getBeeperStatus.mockResolvedValue({+ tokenConfigured: true,+ reachable: null,+ lastProbeError: null,+ accounts: [],+ tokenExpired: true,+ tokenExpiresAt: '2020-01-01T00:00:00.000Z',+ realtime: {+ state: 'down', lastEventAt: null, lastPingAt: null, appState: null, appStateActionable: false, authRejected: true,+ },+ });+ renderPanel();++ await screen.findByText('Beeper token expired');+ expect(screen.getByTestId('connection-status-dot')).toHaveAttribute('data-status', 'down');+ expect(screen.getByRole('button', { name: 'Reconnect Beeper' })).toBeInTheDocument();+ expect(screen.queryByText('Beeper Desktop rejected the stored token — reconnect Beeper.')).toBeNull();+ });++ it('renders no liveness row at all when the transport has never reported', async () => {+ // `realtime` absent is not-yet-known, never "offline" — the same+ // absent-vs-empty rule the `reachable` tri-state follows.+ api.getBeeperStatus.mockResolvedValue({+ tokenConfigured: true, reachable: true, lastProbeError: null, accounts: [],+ });+ renderPanel();++ await screen.findByText('Beeper Desktop connected');+ expect(screen.queryByTestId('connection-status-dot')).toBeNull();+ });++ // The absent-vs-empty sentinel (#30 Acceptance): reachable:null must never+ // render as offline, even in the (normally unreachable) case where a token+ // is configured but the probe never ran.+ it('never renders reachable:null as offline', async () => {+ api.getBeeperStatus.mockResolvedValue({+ tokenConfigured: true, reachable: null, lastProbeError: null, accounts: [],+ });+ renderPanel();++ expect(await screen.findByText('Checking Beeper Desktop…')).toBeInTheDocument();+ expect(screen.queryByText('Beeper Desktop unreachable')).toBeNull();+ });++ // The absent-vs-empty rule (root AGENTS.md line 233): a status fetch that+ // itself fails must never collapse into "no token configured" — an+ // install with a working token whose status request errors would+ // otherwise be silently told to connect.+ it('never renders "Connect Beeper" when the status fetch itself rejects', async () => {+ api.getBeeperStatus.mockRejectedValue(new Error('network down'));+ renderPanel();++ expect(await screen.findByText('Could not read Beeper status')).toBeInTheDocument();+ expect(screen.getByText('network down')).toBeInTheDocument();+ expect(screen.queryByRole('heading', { name: 'Connect Beeper' })).toBeNull();+ expect(screen.getByRole('button', { name: /Retry/ })).toBeInTheDocument();+ });++ // Fork issue #61, decision 7: a probe timeout shortly after a real Beeper+ // success stays on the connected card with a latency note, never the+ // unreachable/actionable-fault card, and never touches the empty-state+ // ("Connect Beeper") or the Retry-button branch.+ it('renders the slow probe state on the connected card, with its latency, instead of the unreachable card', async () => {+ api.getBeeperStatus.mockResolvedValue({+ tokenConfigured: true, reachable: true, probeState: 'slow', probeLatencyMs: 3000, lastProbeError: null, accounts: [],+ });+ renderPanel();++ expect(await screen.findByText('Beeper Desktop connected')).toBeInTheDocument();+ expect(screen.getByText(/Slow to respond \(3000ms\)/)).toBeInTheDocument();+ expect(screen.queryByText('Beeper Desktop unreachable')).toBeNull();+ // The connected card's action is "Recheck", never the unreachable card's+ // "Retry" — a slow probe must not borrow that copy or its gating.+ expect(screen.queryByRole('button', { name: /Retry/ })).toBeNull();+ expect(screen.getByRole('button', { name: /Recheck/ })).toBeInTheDocument();+ });++ it('renders the ordinary connected card with no slow note for probeState:ok', async () => {+ api.getBeeperStatus.mockResolvedValue({+ tokenConfigured: true, reachable: true, probeState: 'ok', probeLatencyMs: 8, lastProbeError: null, accounts: [],+ });+ renderPanel();++ expect(await screen.findByText('Beeper Desktop connected')).toBeInTheDocument();+ expect(screen.queryByText(/Slow to respond/)).toBeNull();+ });++ // A failed accounts read is a different, unknown state from a legitimately+ // empty roster — collapsing them would show "No accounts mirrored yet" for+ // a DB hiccup.+ it('shows the account roster as unknown, not empty, when the mirror read failed', async () => {+ api.getBeeperStatus.mockResolvedValue({+ tokenConfigured: true, reachable: true, lastProbeError: null, accounts: null, accountsError: 'Could not read the mirrored account roster',+ });+ renderPanel();++ expect(await screen.findByText('Beeper Desktop connected')).toBeInTheDocument();+ expect(screen.getByTestId('beeper-roster-unknown')).toHaveTextContent('Could not read the mirrored account roster');+ expect(screen.queryByTestId('beeper-roster-empty')).toBeNull();+ });+});++/**+ * Audit cluster 08 (A11Y-6): both inline error paragraphs on this panel+ * carried no role, and the fetches behind them are silent, so a+ * screen-reader user got no signal that the status read or the account+ * roster read had failed.+ */+describe('BeeperSettingsPanel — inline errors are announced', () => {+ it('exposes the status-fetch failure with role="alert"', async () => {+ api.getBeeperStatus.mockRejectedValue(new Error('network down'));+ renderPanel();++ expect(await screen.findByText('network down')).toHaveAttribute('role', 'alert');+ });++ it('exposes the account-roster failure with role="alert"', async () => {+ api.getBeeperStatus.mockResolvedValue({+ tokenConfigured: true, reachable: true, lastProbeError: null, accounts: null, accountsError: 'Could not read the mirrored account roster',+ });+ renderPanel();++ expect(await screen.findByTestId('beeper-roster-unknown')).toHaveAttribute('role', 'alert');+ });+});++describe('BeeperSettingsPanel — settings', () => {+ it('saves the complete settings slice and disables Save until dirty', async () => {+ api.getBeeperStatus.mockResolvedValue({ tokenConfigured: false, reachable: null, accounts: [] });+ api.updateSettings.mockResolvedValue({+ beeper: {+ enabled: true, intervalMinutes: 5, baseUrl: 'http://127.0.0.1:23373', attachmentBudgetGb: 5, allowNonLoopbackBaseUrl: false,+ },+ });+ renderPanel();++ // Exact, not /Save/: the connect card's "Save token" is on screen too.+ const saveButton = await screen.findByRole('button', { name: 'Save' });+ expect(saveButton).toBeDisabled();++ fireEvent.click(screen.getByLabelText('Enable scheduled Beeper sync'));+ expect(saveButton).not.toBeDisabled();++ fireEvent.click(saveButton);+ await waitFor(() => expect(api.updateSettings).toHaveBeenCalledWith({+ beeper: {+ enabled: true, intervalMinutes: 5, baseUrl: 'http://127.0.0.1:23373', attachmentBudgetGb: 5, allowNonLoopbackBaseUrl: false,+ },+ }));+ expect(toast.success).toHaveBeenCalled();+ });++ // SEC-2: the opt-in is off by default and never inferred from the baseUrl+ // text — it has to be an explicit, separate checkbox flip.+ it('carries the non-loopback opt-in as its own explicit field', async () => {+ api.getBeeperStatus.mockResolvedValue({ tokenConfigured: false, reachable: null, accounts: [] });+ api.updateSettings.mockResolvedValue({+ beeper: {+ enabled: false, intervalMinutes: 5, baseUrl: 'http://127.0.0.1:23373', attachmentBudgetGb: 5, allowNonLoopbackBaseUrl: true,+ },+ });+ renderPanel();++ const checkbox = await screen.findByLabelText(/Allow a non-loopback base URL/);+ expect(checkbox).not.toBeChecked();++ fireEvent.click(checkbox);+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));++ await waitFor(() => expect(api.updateSettings).toHaveBeenCalledWith({+ beeper: {+ enabled: false, intervalMinutes: 5, baseUrl: 'http://127.0.0.1:23373', attachmentBudgetGb: 5, allowNonLoopbackBaseUrl: true,+ },+ }));+ });++ it('disables Retry while the form has unsaved edits, per the save-gating convention', async () => {+ api.getBeeperStatus.mockResolvedValue({+ tokenConfigured: true, reachable: false, lastProbeError: 'refused', baseUrl: 'http://127.0.0.1:23373', accounts: [],+ });+ renderPanel();++ await screen.findByText('Beeper Desktop unreachable');+ const retryButton = screen.getByRole('button', { name: /Retry/ });+ expect(retryButton).not.toBeDisabled();++ fireEvent.click(screen.getByLabelText('Enable scheduled Beeper sync'));+ expect(retryButton).toBeDisabled();+ });++ // The regression: a failed settings GET used to fall through to DEFAULTS+ // silently, so the form rendered as though it had read this install's real+ // config — and the next Save PUT those defaults over whatever was actually+ // stored. The card must show the failure instead of the (wrong) form.+ it('shows the load-failed card instead of the form when settings fail to load, and never offers Save', async () => {+ api.getSettings.mockRejectedValue(new Error('network error'));+ api.getBeeperStatus.mockResolvedValue({ tokenConfigured: false, reachable: null, accounts: [] });+ renderPanel();++ expect(await screen.findByText('Could not load Beeper settings')).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Save' })).toBeNull();+ expect(screen.queryByLabelText('Enable scheduled Beeper sync')).toBeNull();+ });+});++describe('BeeperSettingsPanel — the connect flow (#31)', () => {+ beforeEach(() => {+ api.getBeeperStatus.mockResolvedValue({+ tokenConfigured: false, reachable: null, lastProbeError: null, accounts: [],+ });+ });++ it('opens the authorization URL the server minted, rather than building one client-side', async () => {+ const open = vi.spyOn(window, 'open').mockImplementation(() => null);+ api.startBeeperOAuth.mockResolvedValue({ authorizationUrl: 'http://127.0.0.1:23373/oauth/authorize?state=s' });+ renderPanel();++ fireEvent.click(await screen.findByRole('button', { name: 'Connect Beeper' }));+ await waitFor(() => expect(open).toHaveBeenCalledWith('http://127.0.0.1:23373/oauth/authorize?state=s', '_blank', 'noopener'));+ expect(api.startBeeperOAuth).toHaveBeenCalledWith({ silent: true });+ open.mockRestore();+ });++ // Write paths never auto-retry (the connect exchange burns a single-use+ // code): one call, one toast, and no second attempt.+ it('reports a failed connect once and does not retry', async () => {+ api.startBeeperOAuth.mockRejectedValue(new Error('Beeper authorization-server metadata unavailable (404)'));+ renderPanel();++ fireEvent.click(await screen.findByRole('button', { name: 'Connect Beeper' }));+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Beeper authorization-server metadata unavailable (404)'));+ expect(api.startBeeperOAuth).toHaveBeenCalledTimes(1);+ });++ it('posts a pasted token, clears the field, and refreshes status', async () => {+ api.saveBeeperToken.mockResolvedValue({ tokenConfigured: true, tokenExpiresAt: null, tokenSource: 'pasted' });+ renderPanel();++ const input = await screen.findByLabelText('Or paste an access token');+ expect(input).toHaveAttribute('type', 'password');+ fireEvent.change(input, { target: { value: 'example-beeper-token' } });+ fireEvent.click(screen.getByRole('button', { name: /Save token/ }));++ await waitFor(() => expect(api.saveBeeperToken).toHaveBeenCalledWith('example-beeper-token', { silent: true }));+ await waitFor(() => expect(input).toHaveValue(''));+ expect(api.getBeeperStatus).toHaveBeenCalledTimes(2);+ });++ it('keeps Save token disabled until something is typed', async () => {+ renderPanel();+ const save = await screen.findByRole('button', { name: /Save token/ });+ expect(save).toBeDisabled();+ fireEvent.change(screen.getByLabelText('Or paste an access token'), { target: { value: 'example-beeper-token' } });+ expect(save).not.toBeDisabled();+ });++});++// An expired credential is its own state: Beeper issues no refresh grant, so+// the only action that helps is connecting again — never a generic error.+describe('BeeperSettingsPanel — expired token', () => {+ it('renders the reconnect path rather than the unreachable or connected card', async () => {+ api.getBeeperStatus.mockResolvedValue({+ tokenConfigured: true, tokenSource: 'oauth', tokenExpired: true, tokenExpiringSoon: true,+ tokenExpiresAt: '2026-01-01T00:00:00.000Z', tokenExpiresInDays: -3,+ reachable: false, lastProbeError: 'connection refused', accounts: [],+ });+ renderPanel();++ expect(await screen.findByText('Beeper token expired')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Reconnect Beeper' })).toBeInTheDocument();+ expect(screen.queryByText('Beeper Desktop unreachable')).toBeNull();+ });+});++describe('BeeperSettingsPanel — disconnect', () => {+ beforeEach(() => {+ api.getBeeperStatus.mockResolvedValue({+ tokenConfigured: true, tokenSource: 'pasted', reachable: true, lastProbeError: null, accounts: [],+ });+ });++ // No window.confirm anywhere in the client — the confirmation is inline.+ it('confirms inline before disconnecting', async () => {+ api.disconnectBeeper.mockResolvedValue({ deleted: true, tokenConfigured: false });+ renderPanel();++ fireEvent.click(await screen.findByRole('button', { name: /Disconnect/ }));+ expect(screen.getByText('Forget this Beeper credential?')).toBeInTheDocument();+ expect(api.disconnectBeeper).not.toHaveBeenCalled();++ fireEvent.click(screen.getByRole('button', { name: /Yes, disconnect/ }));+ await waitFor(() => expect(api.disconnectBeeper).toHaveBeenCalledWith({ silent: true }));+ await waitFor(() => expect(api.getBeeperStatus).toHaveBeenCalledTimes(2));+ });++ it('cancels without calling the API', async () => {+ renderPanel();+ fireEvent.click(await screen.findByRole('button', { name: /Disconnect/ }));+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));+ expect(screen.queryByText('Forget this Beeper credential?')).toBeNull();+ expect(api.disconnectBeeper).not.toHaveBeenCalled();+ });+});++// The attachment mirror card (#37). The bulk backfill is the one path here+// that moves gigabytes, so what is pinned is that it cannot start without a+// consent step that states the cost.+describe('BeeperSettingsPanel — attachment mirror', () => {+ beforeEach(() => {+ api.getBeeperStatus.mockResolvedValue({+ tokenConfigured: true, tokenSource: 'pasted', reachable: true, lastProbeError: null, accounts: [],+ });+ });++ it('renders the disk picture without starting anything', async () => {+ renderPanel();+ expect(await screen.findByText('Attachment mirror')).toBeInTheDocument();+ expect(screen.getByText(/of 5 GB/)).toBeInTheDocument();+ expect(api.backfillBeeperAttachments).not.toHaveBeenCalled();+ });++ it('names the count and the byte size before the backfill runs, and only then runs it', async () => {+ api.getBeeperAttachmentSummary.mockResolvedValue({+ ...BASE_ATTACHMENT_SUMMARY, pendingCount: 12, pendingBytes: 4 * 1024 * 1024, pendingUnknownCount: 3,+ });+ api.backfillBeeperAttachments.mockResolvedValue({ fetched: 12, failed: 0, bytes: 4194304, stoppedForBudget: false });+ renderPanel();++ fireEvent.click(await screen.findByRole('button', { name: /Mirror all attachments/i }));+ // The modal states BOTH numbers, and the unknown-size tail separately+ // rather than folding it into the total as zero.+ expect(await screen.findByText('Mirror all attachments?')).toBeInTheDocument();+ expect(screen.getAllByText(/12 attachment\(s\)/).length).toBeGreaterThan(0);+ expect(screen.getByText(/4 MB/)).toBeInTheDocument();+ expect(screen.getByText(/3 whose size Beeper did not report/)).toBeInTheDocument();+ expect(api.backfillBeeperAttachments).not.toHaveBeenCalled();++ fireEvent.click(screen.getByRole('button', { name: /Mirror 12 attachment/i }));+ await waitFor(() => expect(api.backfillBeeperAttachments).toHaveBeenCalledTimes(1));+ });++ it('cancels the consent modal without transferring anything', async () => {+ api.getBeeperAttachmentSummary.mockResolvedValue({ ...BASE_ATTACHMENT_SUMMARY, pendingCount: 4, pendingBytes: 2048 });+ renderPanel();+ fireEvent.click(await screen.findByRole('button', { name: /Mirror all attachments/i }));+ fireEvent.click(await screen.findByRole('button', { name: /^Cancel$/ }));+ await waitFor(() => expect(screen.queryByText(/Mirror all attachments\?/)).not.toBeInTheDocument());+ expect(api.backfillBeeperAttachments).not.toHaveBeenCalled();+ });++ it('reports a failed summary read instead of rendering zeros as the truth', async () => {+ api.getBeeperAttachmentSummary.mockRejectedValue(new Error('Database unavailable'));+ renderPanel();+ expect(await screen.findByText('Database unavailable')).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: /Mirror all attachments/i })).not.toBeInTheDocument();+ });+});diff --git a/client/src/components/messages/beeper/BeeperThread.jsx b/client/src/components/messages/beeper/BeeperThread.jsxnew file mode 100644index 0000000000..30189f0df6--- /dev/null+++ b/client/src/components/messages/beeper/BeeperThread.jsx@@ -0,0 +1,955 @@+import { useEffect, useMemo, useRef, useState } from 'react';+import {+ ArrowLeft, Archive, BellOff, ChevronDown, Loader2, Plus, RefreshCw, Send, Trash2, UserPlus, Users,+} from 'lucide-react';+import NetworkLogo, { networkLabel } from './BeeperNetworkLogo';+import BeeperAttachment from './BeeperAttachment';+import BeeperPersonPicker from './BeeperPersonPicker';+import BeeperCreatePersonForm from './BeeperCreatePersonForm';+import InlineConfirmRow from '../../ui/InlineConfirmRow';+import { decodeHtmlEntities, parseMessageBody } from '../../../lib/beeperMessageBody';+import { formatBytes } from '../../../utils/formatters';++/**+ * Thread + composer + the inline Tribe-linking action, for the Beeper chat+ * surface (#35). Structure ported from the #9 prototype (`BeeperSurface.jsx`):+ * date-separator pills, sender avatars, deleted-message placeholders, and a+ * composer that names the network it would send on.+ *+ * Two things this deliberately does NOT do:+ *+ * - **It does not treat an empty thread as an error or as loading.** History+ * depth varies enormously per network (#3), so a mirrored conversation with+ * no messages is frequently the true answer. It says that, rather than+ * spinning forever or rendering a fault.+ * - **It does not name the transport.** #9 wants "… on Google Messages (RCS)";+ * the mirror carries `network` but not `transport` (#27), so the label stops+ * at the network rather than inventing one.+ *+ * Sending itself (#53, wired on the durable outbox from #36) is a thin layer+ * over `onSend`/`confirmAndSend`/`cancelConfirmation`/`retryOutboxEntry`/+ * `dismissOutboxEntry`, which the surface supplies from `useBeeperOutbox`.+ * This component owns none of the send lifecycle — it only renders what the+ * hook reports: the pending/failed/stalled rows in `outboxEntries` (filtered on+ * STATE, so a settled `sent` entry shows once as the real mirrored message and+ * never as a second bubble — including when its message has aged out of the+ * loaded page), and the inline first-contact question when `confirmation` is+ * set. Nothing here ever retries a send that touched the+ * wire on its own; a `failed` row's "Retry" composes a NEW outbox entry with+ * the same text, exactly like typing it again, because Beeper has no+ * idempotency key and a client-driven resend of the same row would risk a+ * duplicate real message. A stalled `approved` row (PR #60 blocker 1 — a+ * send refused before the server could even claim the row, most often+ * `OUTBOX_BREAKER_OPEN`) is the opposite case: nothing touched the wire, so+ * its "Retry" re-dispatches the SAME row, and it also gets a "Dismiss" to+ * give up on it — the original bug was this state having neither.+ *+ * Direction comes from the mirrored `isSender`, never from comparing+ * `senderId` against the local user — `accounts[].user.id` differs from+ * `senderID` on every network (#2), so there is nothing to compare against.+ * Own messages sit right-aligned with no sender name and no avatar, the+ * reference interface's shape.+ */++/**+ * One message body.+ *+ * Two shapes arrive from Beeper and both are handled here. A PLAIN body is a+ * text node with its entities decoded (#59: an ampersand was rendering as the+ * five-character `&`, because `normalizeMessageRow` stores what the source+ * sent and some bridges send entity-encoded text). An HTML body — 26% of+ * messages on a real install, Discord and Matrix — is parsed into an+ * allowlisted block/span model by `lib/beeperMessageBody.js` and rendered as+ * React elements, since rendering it as a text node showed the tags literally.+ *+ * Nothing here ever reaches `dangerouslySetInnerHTML`: every branch produces+ * elements and text nodes, so a tag outside the allowlist cannot execute, load+ * or style anything.+ */+function MessageBody({ body }) {+ const blocks = parseMessageBody(body);+ if (blocks === null) return <p className="whitespace-pre-wrap break-words">{decodeHtmlEntities(body)}</p>;+ return blocks.map((block, blockIndex) => {+ const spans = block.spans.map((span, spanIndex) => {+ const key = `${blockIndex}-${spanIndex}`;+ let node = span.text;+ if (span.bold) node = <strong className="font-semibold">{node}</strong>;+ if (span.italic) node = <em className="italic">{node}</em>;+ if (span.href) {+ node = (+ <a+ href={span.href}+ target="_blank"+ rel="noopener noreferrer"+ className="text-port-accent underline underline-offset-2"+ >+ {node}+ </a>+ );+ }+ return <span key={key}>{node}</span>;+ });+ return block.type === 'quote'+ ? (+ <blockquote key={blockIndex} className="my-1 border-l-2 border-port-border pl-2 whitespace-pre-wrap break-words text-gray-300">+ {spans}+ </blockquote>+ )+ : <p key={blockIndex} className="whitespace-pre-wrap break-words">{spans}</p>;+ });+}++const dayLabel = (iso) => {+ if (!iso) return 'Unknown date';+ const date = new Date(iso);+ const days = Math.floor((Date.now() - date.getTime()) / 86400000);+ if (days === 0) return 'Today';+ if (days === 1) return 'Yesterday';+ if (days < 7) return date.toLocaleDateString([], { weekday: 'long' });+ return date.toLocaleDateString([], { day: 'numeric', month: 'short', year: 'numeric' });+};++const clockTime = (iso) => (iso ? new Date(iso).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : '');++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>+ );+}++/**+ * A participant row with the inline "Link to Tribe person" action from #34.+ * Three shapes in one control, all local to this row's own `mode` state:+ *+ * - **`create`** (#97 part A) — the picker's "Create new…" no longer posts+ * on click; it opens `BeeperCreatePersonForm` in its place, a+ * confirm-and-rename step. Only that form's own Create button calls+ * `onCreateAndLink`; Cancel returns to the picker.+ * - **picker** — either the row's natural unlinked state, or a linked row+ * that clicked "Change" (#97 part B). Choosing a result IS the link+ * action (unchanged from #98); on a linked row a "Cancel" link (absent+ * when the row was never linked — there is nothing to cancel back to)+ * returns to the "Linked · …" display without linking anyone.+ * - **linked view** — `tribePersonId` present and `mode !== 'picker'`:+ * states who it is (a link straight to the person's Tribe page, #98 part+ * C) plus "Change" (reopens the picker, pre-focused) and "Unlink"+ * (`onUnlink`, #97 part B).+ *+ * `mode` resets to the natural view whenever the participant's OWN linked+ * state changes out from under it — a link/unlink completing, or any other+ * cause of a thread refetch — so a stale open form/picker never survives a+ * refresh showing a DIFFERENT link state than the one the row was left open+ * on.+ */+function ParticipantRow({+ participant, people, linking, onLink, onCreateAndLink, onUnlink, onOpenPerson,+}) {+ const pickerId = `beeper-link-${participant.sourceUserId}`;+ const name = participant.displayName || participant.handle || participant.sourceUserId;+ const linkedId = participant.tribePersonId || null;+ const [mode, setMode] = useState('view');++ const prevLinkedRef = useRef(linkedId);+ useEffect(() => {+ if (prevLinkedRef.current !== linkedId) {+ prevLinkedRef.current = linkedId;+ setMode('view');+ }+ }, [linkedId]);++ if (mode === 'create') {+ return (+ <li className="py-1">+ <BeeperCreatePersonForm+ participant={participant}+ disabled={linking}+ onCreate={(fields) => onCreateAndLink(participant, fields)}+ onCancel={() => setMode('view')}+ />+ </li>+ );+ }++ const showPicker = !linkedId || mode === 'picker';+ if (showPicker) {+ return (+ <li className="flex flex-wrap items-center gap-2 py-1 text-xs text-gray-300">+ <Avatar name={participant.displayName || participant.handle} size={22} />+ <span className="min-w-0 flex-1 truncate">{name}</span>+ <BeeperPersonPicker+ id={pickerId}+ label={`Link ${participant.displayName || participant.sourceUserId} to a Tribe person`}+ people={people}+ disabled={linking}+ autoFocus={mode === 'picker'}+ onSelectPerson={(personId) => { onLink(participant, personId); setMode('view'); }}+ onCreateNew={() => setMode('create')}+ />+ {linkedId && (+ <button+ type="button"+ onClick={() => setMode('view')}+ className="shrink-0 text-[11px] text-gray-400 transition-colors hover:text-gray-200 hover:underline"+ >+ Cancel+ </button>+ )}+ {linking && <Loader2 size={11} className="shrink-0 animate-spin text-gray-400" />}+ </li>+ );+ }++ return (+ <li className="flex items-center gap-2 py-1 text-xs text-gray-300">+ <Avatar name={participant.displayName || participant.handle} size={22} />+ <span className="min-w-0 flex-1 truncate">{name}</span>+ {participant.tribePersonName ? (+ <button+ type="button"+ onClick={() => onOpenPerson(participant.tribePersonId)}+ className="shrink-0 truncate text-[11px] text-port-success underline-offset-2 hover:underline"+ >+ {`Linked · ${participant.tribePersonName}`}+ </button>+ ) : (+ <span className="shrink-0 truncate text-[11px] text-port-success">Linked</span>+ )}+ <button+ type="button"+ onClick={() => setMode('picker')}+ disabled={linking}+ className="shrink-0 text-[11px] text-gray-400 transition-colors hover:text-gray-200 hover:underline disabled:opacity-40"+ >+ Change+ </button>+ <button+ type="button"+ onClick={() => onUnlink(participant)}+ disabled={linking}+ className="shrink-0 text-[11px] text-gray-400 transition-colors hover:text-port-error hover:underline disabled:opacity-40"+ >+ Unlink+ </button>+ {linking && <Loader2 size={11} className="shrink-0 animate-spin text-gray-400" />}+ </li>+ );+}++/**+ * The exact sentence shown for a send the server found stranded in `sending` at+ * boot (`SEND_INTERRUPTED`, written by `reconcileOutboxOnBoot` in+ * `server/services/beeperOutbox.js`, which owns the identical literal — the two+ * bundles cannot share a module, so they share a test instead).+ *+ * It deliberately does not claim a delivery verdict. The POST was in flight+ * when the process died, so whether it landed is unknowable from here; the copy+ * points at the chat, because looking is the only thing that actually answers+ * it, and Retry composes a new message rather than resending that one.+ */+const SEND_INTERRUPTED_COPY = 'Delivery unconfirmed: PortOS restarted mid-send. Check the chat before retrying.';++/** The outbox states that still have something to say above the composer. */+const RENDERED_OUTBOX_STATES = new Set(['approved', 'sending', 'awaiting-confirmation', 'failed']);++/**+ * The counterpart participant in a 1:1 chat (never called for a group chat —+ * see `TitleTribeChip` below, which branches on `conversation.isGroup` first).+ *+ * There is no per-participant self/is-sender marker anywhere in the mirrored+ * schema to filter by: `shapeParticipant` (`server/services/beeperConversations.js`)+ * carries `sourceUserId`/`displayName`/`handle`/`tribePersonId`/`tribePersonName`+ * only, and `isSender` exists solely on MESSAGES, never on a participant row+ * (see the `MessageBody`/`OutboxRow` docs above). No account user id is+ * exposed to the client either. What IS true, straight from how the roster is+ * built (`normalizeParticipants` in `server/services/beeperSync.js` maps+ * `chat.participants.items` verbatim, and Beeper's own `items` for a `single`+ * chat never includes the local account's own user — see the 1:1 fixtures in+ * `beeperSync.test.js`, always exactly one item): a 1:1 conversation's roster+ * IS the counterpart, in full. So the rule here is simply "the first — and by+ * construction, only — participant"; if a 1:1 conversation's roster somehow+ * carried more than one row (a shape Beeper's own contract for a `single`+ * chat does not produce), the first is still used as the best-effort answer+ * rather than declining to render a chip at all.+ */+const oneToOneCounterpart = (conversation) => (conversation?.participants || [])[0] || null;++/**+ * The Tribe link beside the thread title (#98 part A). Whether this reads as+ * a 1:1 chat or a group chat comes from the mirrored `conversation.isGroup`+ * (`beeperSync.js`'s `normalizeChat` sets it straight from Beeper's own+ * `chat.type === 'group'`), never from participant count — the participant+ * subset is truncated (`hasMoreParticipants`) and can legitimately read back+ * as a single row for a group Beeper only handed one member over.+ *+ * A group chat's affordance is honest about being a subset, not a total:+ * Beeper's `Chat` payload carries no total-member count independent of the+ * (truncated) roster PortOS stores, so the count shown is `participants.length`+ * with a trailing `+` when `hasMoreParticipants` is set — the same qualifier+ * the People drawer's own heading already uses just below.+ */+function TitleTribeChip({ conversation, onOpenParticipants, onOpenPerson }) {+ if (conversation.isGroup) {+ const count = (conversation.participants || []).length;+ const label = `${count}${conversation.hasMoreParticipants ? '+' : ''} ${count === 1 ? 'person' : 'people'}`;+ return (+ <button+ type="button"+ onClick={onOpenParticipants}+ className="inline-flex shrink-0 items-center gap-1 rounded-full border border-port-border px-2 py-0.5 text-[10px] text-gray-300 transition-colors hover:border-port-accent hover:text-white"+ >+ <Users size={10} aria-hidden="true" />+ {label}+ </button>+ );+ }++ const counterpart = oneToOneCounterpart(conversation);+ if (counterpart?.tribePersonId) {+ return (+ <button+ type="button"+ onClick={() => onOpenPerson(counterpart.tribePersonId)}+ className="inline-flex shrink-0 items-center gap-1 rounded-full border border-port-success/40 px-2 py-0.5 text-[10px] text-port-success transition-colors hover:border-port-success"+ >+ {`${counterpart.tribePersonName || 'Linked'} · Tribe`}+ </button>+ );+ }++ return (+ <button+ type="button"+ onClick={onOpenParticipants}+ className="inline-flex shrink-0 items-center gap-1 rounded-full border border-dashed border-port-border px-2 py-0.5 text-[10px] text-gray-400 transition-colors hover:border-port-accent hover:text-gray-200"+ >+ <UserPlus size={10} aria-hidden="true" />+ Link to Tribe+ </button>+ );+}++/**+ * One outbox row — a send that has not yet been confirmed by the mirror, or+ * one that failed. Always outbound (right-aligned, no avatar), matching the+ * bubble a mirrored `isSender` message renders, so a pending send does not+ * visually jump when it swaps for the real thing.+ *+ * Only ONE of the four outcomes below spins, and the spinner is the exception+ * rather than the default. Every state that will not change on its own — a+ * failure, an interrupted send, an unconfirmed one, a refused one — resolves to+ * a terminal line that says what happened, because a spinner for a state+ * nothing can ever advance is a lie the user cannot dismiss, and it survives+ * every reload.+ *+ * `approved` is normally in flight for the moment between the create and+ * send requests (`sending` is true). If it is STILL `approved` once nothing+ * is actively sending — and it is not the row a first-contact confirmation+ * is currently asking about — the send was refused before the server could+ * even claim the row, most often `OUTBOX_BREAKER_OPEN` (#36). Left alone+ * that renders as a permanent "Sending…" phantom that survives reload (PR+ * #60 blocker 1), so it gets the same "stalled" treatment as `failed`: a+ * reason, a Retry, and — since nothing here was ever posted to Beeper — a+ * Dismiss that gives up on it outright.+ *+ * The two Retries are not the same action, and the breaker splits them (PR+ * #60 blocker 2). A `failed` row's Retry composes a NEW entry through the+ * composer's own send path, which the breaker blocks exactly as it blocks+ * Send — so with the breaker tripped that button is disabled and carries the+ * same reason as the Send button, rather than staying live and doing nothing.+ * A `stalled` row's Retry re-dispatches the existing row: the server decides,+ * and its 429 toasts, so it stays enabled.+ */+function OutboxRow({+ entry, sending, isConfirming, onRetry, onDismiss, breakerTripped, breakerReason,+}) {+ const failed = entry.state === 'failed';+ const interrupted = failed && entry.errorCode === 'SEND_INTERRUPTED';+ // Recorded by the server's 30s fallback when it could not find the message it+ // had just sent. The row stays `awaiting-confirmation` on purpose — the send+ // may well have been delivered, and marking it failed would invite the one+ // mistake that cannot be taken back — so this reads as "sent, unconfirmed",+ // carries the reason the server recorded, and offers NO Retry. It never+ // changes on its own, so it must never spin.+ const unresolved = !failed && entry.errorCode === 'CONFIRMATION_UNRESOLVED';+ const stalled = entry.state === 'approved' && !sending && !isConfirming;+ const blocked = failed || stalled;+ const confirming = entry.state === 'awaiting-confirmation' || entry.state === 'sent';+ const retryBlocked = breakerTripped && !stalled;+ const outcome = blocked ? (failed ? 'failed' : 'stalled') : (unresolved ? 'unconfirmed' : 'pending');+ // An interrupted send gets the copy verbatim and nothing else: prefixing+ // "Not delivered" would assert a verdict the crash destroyed the evidence for.+ let blockedReason = 'Not sent — the send was refused';+ if (interrupted) blockedReason = SEND_INTERRUPTED_COPY;+ else if (failed) blockedReason = `Not delivered${entry.errorMessage ? ` — ${entry.errorMessage}` : ''}`;+ return (+ <div+ data-testid="beeper-outbox-row"+ data-state={entry.state}+ data-outcome={outcome}+ className="flex items-end justify-end gap-2"+ >+ <div+ className={`max-w-[75%] rounded-2xl px-3 py-2 text-sm text-gray-100 ${+ blocked ? 'border border-port-error/40 bg-port-error/10' : 'bg-port-accent/25'+ }`}+ >+ <p className="whitespace-pre-wrap break-words">{entry.body}</p>+ <span className="mt-0.5 flex items-center justify-end gap-1.5 text-[10px]">+ {blocked && (+ <>+ <span className="text-port-error">{blockedReason}</span>+ <button+ type="button"+ onClick={() => onRetry(entry)}+ disabled={retryBlocked}+ title={retryBlocked ? breakerReason : undefined}+ className="rounded px-1 py-0.5 text-port-accent transition-colors hover:underline disabled:cursor-not-allowed disabled:text-gray-500 disabled:no-underline disabled:hover:no-underline"+ >+ Retry+ </button>+ {stalled && (+ <button+ type="button"+ onClick={() => onDismiss(entry)}+ className="rounded px-1 py-0.5 text-gray-400 transition-colors hover:underline"+ >+ Dismiss+ </button>+ )}+ </>+ )}+ {unresolved && (+ <span className="text-port-warning">+ {`Sent, unconfirmed${entry.errorMessage ? ` — ${entry.errorMessage}` : ''}`}+ </span>+ )}+ {!blocked && !unresolved && (+ <span className="flex items-center gap-1 text-gray-400">+ <Loader2 size={10} className="animate-spin" />+ {confirming ? 'Confirming…' : 'Sending…'}+ </span>+ )}+ </span>+ </div>+ </div>+ );+}++export default function BeeperThread({+ conversation,+ messages,+ loading,+ error,+ hasMore,+ loadingMore,+ onLoadMore,+ draft,+ onDraftChange,+ outboxEntries = [],+ sending = false,+ confirmation = null,+ onSend,+ confirmAndSend,+ cancelConfirmation,+ retryOutboxEntry,+ dismissOutboxEntry,+ breaker = null,+ people,+ linkingId,+ onLinkParticipant,+ onCreateAndLinkParticipant,+ onUnlinkParticipant,+ onOpenTribePerson,+ onBack,+ onRetry,+ onArchive,+ onLowPriority,+ onPurge,+ purging,+ onAttachmentUpdated,+ writePending,+}) {+ const [peopleOpen, setPeopleOpen] = useState(false);+ const [purgeOpen, setPurgeOpen] = useState(false);+ const [purgeConfirmation, setPurgeConfirmation] = useState('');+ const bottomRef = useRef(null);++ // Newest-first from the API (the order a chat surface pages in); oldest-first+ // for display. Reversing here rather than server-side keeps the cursor+ // semantics honest: the API never pretends the oldest message is one call away.+ const ordered = useMemo(() => [...messages].reverse(), [messages]);+ const senderName = useMemo(() => {+ const map = new Map();+ for (const participant of conversation?.participants || []) {+ map.set(participant.sourceUserId, participant.tribePersonName || participant.displayName || participant.handle || '');+ }+ return map;+ }, [conversation?.participants]);++ // Outbox rows still worth showing: anything the mirror has not caught up+ // with yet, decided on the entry's own STATE rather than on whether its+ // message happens to be in the page currently loaded. `sent` is settled —+ // the mirrored message IS the record of it — and `GET /outbox` returns up to+ // 50 entries in every state, so a `sent` entry whose message had aged out of+ // the newest page used to render forever as a spinning bubble with old text.+ // `draft` is excluded for the same reason it has no writer: it is not a send.+ // `entries` arrives newest-first (the server's own order, preserved through+ // every client-side prepend); reversed to read oldest-first like `ordered`.+ const visibleOutbox = useMemo(() => {+ const mirroredIds = new Set(messages.map((message) => message.id));+ return [...outboxEntries]+ .filter((entry) => RENDERED_OUTBOX_STATES.has(entry.state))+ // The tiebreak, not the rule: an `awaiting-confirmation` row the sweep+ // already mirrored would otherwise show twice, once as each.+ .filter((entry) => !(entry.messageId && mirroredIds.has(entry.messageId)))+ .reverse();+ }, [outboxEntries, messages]);++ const trimmedDraft = draft.trim();+ const breakerTripped = Boolean(breaker?.tripped);+ const canSend = trimmedDraft.length > 0 && !sending && !breakerTripped;+ const sendDisabledReason = breakerTripped+ ? `Beeper sending is blocked by the runaway breaker (${breaker?.reason || 'unexpected send rate'}) — clear it in Beeper settings.`+ : (trimmedDraft.length === 0 ? 'Type a message to send' : undefined);++ const handleSendClick = () => { if (canSend) onSend(draft); };+ // Bare Enter stays a newline (the textarea is multi-line); ⌘/Ctrl+Enter is+ // the send shortcut, matching the reference interface and #53's spec.+ const handleComposerKeyDown = (event) => {+ if ((event.metaKey || event.ctrlKey) && event.key === 'Enter') {+ event.preventDefault();+ handleSendClick();+ }+ };+ // A failed row's only recovery: compose the SAME text again as a brand new+ // outbox entry. Never a resend of the failed row — see the file docstring.+ // A stalled `approved` row (PR #60 blocker 1) is the opposite case: nothing+ // ever reached Beeper for it, so retrying re-sends the SAME row instead —+ // composing a new one on every click would just manufacture more phantoms+ // while the breaker stays tripped.+ //+ // `clearsDraft: false` on the failed-row path: that send is the OLD row's+ // text, not what is in the composer. Clearing on its success would throw+ // away a message typed while the failed row sat above it — and drop it from+ // storage too, since the surface's `setDraft('')` deletes the persisted+ // entry. Only the composer's own Send clears the composer.+ const handleRetry = (entry) => {+ if (entry.state === 'approved') { retryOutboxEntry?.(entry); return; }+ if (!breakerTripped) onSend(entry.body, { clearsDraft: false });+ };+ const handleDismiss = (entry) => { dismissOutboxEntry?.(entry); };++ // Scrolls to the bottom only when what is actually AT the bottom changed —+ // the newest mirrored message, or (once one exists) the newest pending+ // send — or the conversation itself changed. Tracked in a ref rather than+ // read off `ordered.length`/`visibleOutbox.length` as dependencies (the+ // original bug, PERF-8/A11Y-2): "Load earlier messages" only grows `ordered`+ // by prepending OLDER messages, which changes `ordered.length` on every+ // click without moving `ordered[ordered.length - 1]` — the newest message —+ // at all, so keying on the length alone yanked the reader back to the+ // bottom on every page-in of history. `ordered` is oldest-first (see+ // above), so its newest entry is the LAST one; outbox rows render after it+ // and are the true bottom while a send is still pending.+ const latestBottomRef = useRef(null);+ useEffect(() => {+ const newestMessageId = ordered.length ? ordered[ordered.length - 1].id : null;+ const newestOutboxId = visibleOutbox.length ? visibleOutbox[visibleOutbox.length - 1].id : null;+ const bottomKey = `${conversation?.id ?? ''}:${newestOutboxId ?? ''}:${newestMessageId ?? ''}`;+ if (latestBottomRef.current === bottomKey) return;+ latestBottomRef.current = bottomKey;+ bottomRef.current?.scrollIntoView({ block: 'end' });+ }, [conversation?.id, ordered, visibleOutbox]);++ // A typed confirmation must never survive the conversation it was typed for:+ // switching threads with the panel open would otherwise leave a primed Purge+ // button pointing at a different chat.+ //+ // Keyed on a CHANGE of id, not on the id as a dependency: a refetch that+ // momentarily resolves `conversation` to null (a reload, a failed poll) would+ // otherwise fire this twice and silently close a panel the user is typing+ // into — the value is discarded on a real switch, never on a re-render.+ const purgeConversationRef = useRef(null);+ useEffect(() => {+ const id = conversation?.id || null;+ if (!id || purgeConversationRef.current === id) return;+ purgeConversationRef.current = id;+ setPurgeOpen(false);+ setPurgeConfirmation('');+ }, [conversation?.id]);++ // Order matters, and this is the whole reason these three are separate+ // branches: `loading` and `error` are both reachable with NO conversation —+ // a cold deep link whose detail fetch fails (503, 500, offline) leaves+ // `conversation` null and `error` set. Answering that with "Pick a+ // conversation" renders a named URL as if nothing were selected, with no+ // error and no way back: every fetch behind this passes `{ silent: true }`,+ // so there is no toast either. "Pick a conversation" is only correct when+ // nothing is selected, nothing is in flight, and nothing went wrong.+ if (!conversation && error) {+ return (+ <div className="flex h-full flex-col items-center justify-center gap-2 p-6 text-center">+ <p className="text-sm text-gray-300">Could not open this conversation</p>+ <p role="alert" className="max-w-sm text-[11px] text-port-error">{error}</p>+ <div className="mt-1 flex flex-wrap items-center justify-center gap-2">+ {onRetry && (+ <button+ type="button"+ onClick={onRetry}+ disabled={loading}+ className="inline-flex min-h-[36px] items-center gap-1.5 rounded-lg border border-port-border px-3 text-xs text-gray-200 transition-colors hover:border-port-accent disabled:opacity-40"+ >+ {loading ? <Loader2 size={12} className="animate-spin" /> : <RefreshCw size={12} />}+ Retry+ </button>+ )}+ <button+ type="button"+ onClick={onBack}+ className="min-h-[36px] rounded-lg px-3 text-xs text-gray-400 transition-colors hover:text-gray-200"+ >+ Back to conversations+ </button>+ </div>+ </div>+ );+ }++ if (!conversation && loading) {+ return (+ <div className="flex h-full items-center justify-center p-6 text-center text-xs text-gray-500">+ Loading conversation…+ </div>+ );+ }++ if (!conversation) {+ return (+ <div className="flex h-full items-center justify-center p-6 text-center text-sm text-gray-500">+ Pick a conversation+ </div>+ );+ }++ let lastDay = null;++ return (+ <div className="flex h-full min-h-0 flex-col">+ <div className="flex shrink-0 items-center gap-2 border-b border-port-border px-3 py-2">+ <button+ type="button"+ onClick={onBack}+ aria-label="Back to conversations"+ className="inline-flex min-h-[44px] min-w-[44px] items-center justify-center rounded p-1.5 text-gray-400 hover:text-white md:hidden"+ >+ <ArrowLeft size={16} />+ </button>+ <Avatar name={conversation.title} size={28} />+ <div className="min-w-0">+ <p className="flex items-center gap-1 text-sm text-white">+ <span className="truncate">{conversation.title || 'Untitled conversation'}</span>+ {conversation.isMuted && <BellOff size={11} className="shrink-0 text-gray-500" />}+ <TitleTribeChip+ conversation={conversation}+ onOpenParticipants={() => setPeopleOpen((open) => !open)}+ onOpenPerson={onOpenTribePerson}+ />+ </p>+ <p className="truncate text-[11px] text-gray-500">{networkLabel(conversation.network)}</p>+ </div>+ <div className="ml-auto flex shrink-0 items-center gap-1">+ <button+ type="button"+ disabled={writePending}+ onClick={() => onArchive(!conversation.isArchived)}+ title={conversation.isArchived ? 'Unarchive in Beeper' : 'Archive in Beeper'}+ className="inline-flex min-h-[32px] items-center gap-1 rounded border border-port-border px-2 text-[11px] text-gray-300 transition-colors hover:border-port-accent disabled:opacity-40"+ >+ <Archive size={12} />+ {conversation.isArchived ? 'Unarchive' : 'Archive'}+ </button>+ <button+ type="button"+ disabled={writePending}+ onClick={() => onLowPriority(!conversation.isLowPriority)}+ title={conversation.isLowPriority ? 'Restore normal priority in Beeper' : 'Mark low priority in Beeper'}+ className="inline-flex min-h-[32px] items-center gap-1 rounded border border-port-border px-2 text-[11px] text-gray-300 transition-colors hover:border-port-accent disabled:opacity-40"+ >+ <ChevronDown size={12} />+ {conversation.isLowPriority ? 'Normal' : 'Low priority'}+ </button>+ <button+ type="button"+ onClick={() => setPeopleOpen((open) => !open)}+ aria-expanded={peopleOpen}+ className="inline-flex min-h-[32px] items-center gap-1 rounded border border-port-border px-2 text-[11px] text-gray-300 transition-colors hover:border-port-accent"+ >+ <Users size={12} />+ People+ </button>+ {onPurge && (+ <button+ type="button"+ onClick={() => setPurgeOpen((open) => !open)}+ aria-expanded={purgeOpen}+ title="Delete this conversation's PortOS mirror — Beeper keeps the chat"+ className="inline-flex min-h-[32px] items-center gap-1 rounded border border-port-border px-2 text-[11px] text-gray-300 transition-colors hover:border-port-error hover:text-port-error"+ >+ <Trash2 size={12} />+ Purge+ </button>+ )}+ </div>+ </div>++ {peopleOpen && (+ <div className="shrink-0 border-b border-port-border bg-port-bg/60 px-3 py-2">+ {/* Beeper truncates a participant list at 20 (list) / 100 (single+ GET) with no participants endpoint and no cursor, so this is a+ subset by construction — saying so beats implying a roster. */}+ <p className="pb-1 text-[11px] uppercase tracking-wide text-gray-500">+ Participants{conversation.hasMoreParticipants ? ' (partial — Beeper truncates long rosters)' : ''}+ </p>+ {(conversation.participants || []).length === 0 ? (+ <p className="text-xs text-gray-500">No participants mirrored yet.</p>+ ) : (+ <ul data-testid="beeper-participants-roster" className="max-h-40 divide-y divide-port-border/40 overflow-y-auto">+ {conversation.participants.map((participant) => (+ <ParticipantRow+ key={participant.sourceUserId}+ participant={participant}+ people={people}+ linking={linkingId === participant.sourceUserId}+ onLink={onLinkParticipant}+ onCreateAndLink={onCreateAndLinkParticipant}+ onUnlink={onUnlinkParticipant}+ onOpenPerson={onOpenTribePerson}+ />+ ))}+ </ul>+ )}+ </div>+ )}++ {/* The purge confirmation is TYPED, in-drawer, and names both the+ conversation and the bytes it is about to free (#13) — not a+ `window.confirm`, which the client conventions forbid and which could+ not state either fact. It is also explicit that this is a LOCAL+ purge: Beeper still has the chat, and the next sweep re-mirrors it. */}+ {purgeOpen && onPurge && (+ <div className="shrink-0 border-b border-port-error/40 bg-port-error/5 px-3 py-2">+ <p className="text-[11px] uppercase tracking-wide text-port-error">Purge this mirror</p>+ <p className="pt-1 text-xs text-gray-300">+ Deletes PortOS’s copy of <span className="text-white">{conversation.title || 'this conversation'}</span>+ {' '}— its messages, participants and{' '}+ {formatBytes(conversation.attachmentBytes || 0)} of mirrored attachment bytes+ {conversation.attachmentFiles ? ` across ${conversation.attachmentFiles} file(s)` : ''}.+ </p>+ <p className="pt-1 text-[11px] text-gray-500">+ Beeper itself is untouched: the chat stays on its network, and the next sync will mirror it again.+ </p>+ <div className="flex flex-wrap items-center gap-2 pt-2">+ <label htmlFor="beeper-purge-confirm" className="text-[11px] text-gray-400">+ Type <span className="font-mono text-gray-200">purge</span> to confirm+ </label>+ <input+ id="beeper-purge-confirm"+ type="text"+ value={purgeConfirmation}+ onChange={(event) => setPurgeConfirmation(event.target.value)}+ autoComplete="off"+ className="w-28 rounded border border-port-border bg-port-bg px-2 py-1 text-xs text-white"+ />+ <button+ type="button"+ disabled={purgeConfirmation.trim().toLowerCase() !== 'purge' || purging}+ onClick={() => onPurge()}+ className="inline-flex min-h-[32px] items-center gap-1.5 rounded border border-port-error px-2 text-[11px] text-port-error transition-colors hover:bg-port-error/10 disabled:opacity-40"+ >+ {purging ? <Loader2 size={11} className="animate-spin" /> : <Trash2 size={11} />}+ Purge mirror+ </button>+ <button+ type="button"+ onClick={() => { setPurgeOpen(false); setPurgeConfirmation(''); }}+ className="min-h-[32px] px-2 text-[11px] text-gray-400 transition-colors hover:text-gray-200"+ >+ Cancel+ </button>+ </div>+ </div>+ )}++ <div className="min-h-0 flex-1 space-y-1.5 overflow-y-auto px-3 py-3">+ {hasMore && (+ <div className="pb-2 text-center">+ <button+ type="button"+ onClick={onLoadMore}+ disabled={loadingMore}+ className="inline-flex min-h-[32px] items-center gap-1.5 rounded-full border border-port-border px-3 text-[11px] text-gray-300 transition-colors hover:border-port-accent disabled:opacity-40"+ >+ {loadingMore ? <Loader2 size={11} className="animate-spin" /> : null}+ Load earlier messages+ </button>+ </div>+ )}++ {error && <p role="alert" className="py-2 text-center text-xs text-port-error">{error}</p>}++ {loading && ordered.length === 0 && (+ <p className="py-6 text-center text-xs text-gray-500">Loading messages…</p>+ )}++ {/* An empty thread is a legitimate steady state, not a spinner and not+ an error — history depth varies enormously per network. Gated on+ `visibleOutbox` too: the very first message to a brand-new,+ genuinely-empty conversation is itself a pending outbox row, and+ that is not "no messages mirrored yet" either. */}+ {!loading && !error && ordered.length === 0 && visibleOutbox.length === 0 && (+ <div className="flex h-full flex-col items-center justify-center gap-1 p-6 text-center">+ <p className="text-sm text-gray-300">No messages mirrored yet</p>+ <p className="max-w-sm text-[11px] text-gray-500">+ How much history a bridge hands over varies enormously between networks — some backfill years,+ some only what has arrived since you connected. An empty thread here is often correct rather than broken.+ </p>+ </div>+ )}++ {ordered.map((message) => {+ const day = dayLabel(message.sentAt);+ const showDay = day !== lastDay;+ lastDay = day;+ const name = senderName.get(message.senderId) || message.senderId || 'Unknown sender';+ const out = message.isSender === true;+ return (+ <div key={message.id}>+ {showDay && (+ <p className="py-2 text-center">+ <span className="rounded-full bg-port-card px-2.5 py-0.5 text-[11px] text-gray-400">{day}</span>+ </p>+ )}+ <div+ data-testid="beeper-message"+ data-direction={out ? 'out' : 'in'}+ className={`flex items-end gap-2 ${out ? 'justify-end' : 'justify-start'}`}+ >+ {!out && <Avatar name={name} size={26} />}+ <div className={`max-w-[75%] rounded-2xl px-3 py-2 text-sm text-gray-100 ${out ? 'bg-port-accent/25' : 'bg-port-card'}`}>+ {!out && <p className="mb-0.5 text-[11px] font-medium text-port-accent">{name}</p>}+ {message.unsentAt ? (+ <p className="flex items-center gap-1.5 italic text-gray-500">+ <Trash2 size={12} /> This message was unsent+ </p>+ ) : (+ <MessageBody body={message.body} />+ )}+ {/* Bytes arrive on first view through the mirror route, not+ with the message payload — see BeeperAttachment. */}+ {(message.attachments || []).map((attachment) => (+ <BeeperAttachment+ key={`${message.id}-${attachment.idx}`}+ attachment={attachment}+ onUpdated={onAttachmentUpdated+ ? (updated) => onAttachmentUpdated(message.id, updated)+ : undefined}+ />+ ))}+ <span className="mt-0.5 flex items-center justify-end gap-1 text-[10px] text-gray-500">+ {clockTime(message.sentAt)}+ {message.editedAt && <span>· edited</span>}+ </span>+ </div>+ </div>+ </div>+ );+ })}++ {/* Pending/failed sends. Not yet in `messages` — that arrives only+ once the mirror has caught up (#53, on the outbox from #36). */}+ {visibleOutbox.map((entry) => (+ <OutboxRow+ key={entry.id}+ entry={entry}+ sending={sending}+ isConfirming={confirmation?.entry?.id === entry.id}+ onRetry={handleRetry}+ onDismiss={handleDismiss}+ breakerTripped={breakerTripped}+ breakerReason={sendDisabledReason}+ />+ ))}++ <div ref={bottomRef} />+ </div>++ {/* First-contact confirmation (#8 decision 5, wired on #53): PortOS has+ never completed a send to this conversation, so the server refused+ and asked. Inline, never `window.confirm` — client conventions. */}+ {confirmation && (+ <InlineConfirmRow+ variant="separator"+ tone="warning"+ autoFocus+ aria-label={`Confirm sending the first message to ${conversation.title || 'this contact'}`}+ question={`This is the first message PortOS has sent to ${conversation.title || 'this contact'} on ${networkLabel(conversation.network)} — send it?`}+ confirmText="Send anyway"+ cancelText="Cancel"+ onConfirm={confirmAndSend}+ onCancel={cancelConfirmation}+ />+ )}++ <div className="flex shrink-0 items-center gap-2 border-t border-port-border p-2.5">+ <button+ type="button"+ aria-label="Attach a file"+ title="Attachments aren't supported yet"+ disabled+ className="shrink-0 rounded-full p-2 text-gray-600"+ >+ <Plus size={17} />+ </button>+ <div className="flex flex-1 items-center gap-2 rounded-full border border-port-border bg-port-card px-3 py-1.5">+ <NetworkLogo network={conversation.network} size={15} />+ <label htmlFor="beeper-composer" className="sr-only">+ Message {conversation.title} on {networkLabel(conversation.network)}+ </label>+ <textarea+ id="beeper-composer"+ rows={1}+ value={draft}+ onChange={(event) => onDraftChange(event.target.value)}+ onKeyDown={handleComposerKeyDown}+ placeholder={`Message ${conversation.title || 'this chat'} on ${networkLabel(conversation.network)}`}+ className="min-w-0 flex-1 resize-none bg-transparent text-sm text-white placeholder:text-gray-500 focus:outline-none"+ />+ </div>+ <button+ type="button"+ onClick={handleSendClick}+ aria-disabled={!canSend}+ aria-label="Send"+ title={sendDisabledReason}+ className="shrink-0 rounded-full bg-port-accent p-2 text-port-bg transition-colors hover:bg-port-accent/85 aria-disabled:cursor-not-allowed aria-disabled:bg-port-accent/40 aria-disabled:hover:bg-port-accent/40"+ >+ {sending ? <Loader2 size={15} className="animate-spin" /> : <Send size={15} />}+ </button>+ </div>+ </div>+ );+}diff --git a/client/src/components/messages/beeper/BeeperThread.test.jsx b/client/src/components/messages/beeper/BeeperThread.test.jsxnew file mode 100644index 0000000000..120ad5388f--- /dev/null+++ b/client/src/components/messages/beeper/BeeperThread.test.jsx@@ -0,0 +1,901 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import {+ cleanup, fireEvent, render, screen, within,+} from '@testing-library/react';+import BeeperThread from './BeeperThread';++/**+ * PR #60 blocker 1: `OutboxRow` had no branch for the `approved` state — only+ * `failed` and `awaiting-confirmation`/`sent` — so a row left `approved` by a+ * refused send (most often `OUTBOX_BREAKER_OPEN`, #36) rendered as a+ * permanent spinner-plus-"Sending…" bubble with no Retry and no dismiss.+ * PR #60 blocker 2: with the breaker tripped, a `failed` row's Retry stayed+ * enabled and did nothing at all — that path composes a new entry through the+ * same send the breaker blocks.+ *+ * These tests exercise `OutboxRow` through the real component rather than in+ * isolation, since the "stalled vs. actively sending" distinction is read+ * off sibling props (`sending`, `confirmation`) it does not own itself.+ */++const CONVERSATION = {+ id: 'convo-1',+ title: 'Example Contact',+ network: 'whatsapp',+ participants: [],+};++const BASE_PROPS = {+ conversation: CONVERSATION,+ messages: [],+ loading: false,+ error: null,+ hasMore: false,+ loadingMore: false,+ onLoadMore: vi.fn(),+ draft: '',+ onDraftChange: vi.fn(),+ outboxEntries: [],+ sending: false,+ confirmation: null,+ onSend: vi.fn(),+ confirmAndSend: vi.fn(),+ cancelConfirmation: vi.fn(),+ retryOutboxEntry: vi.fn(),+ dismissOutboxEntry: vi.fn(),+ breaker: null,+ people: [],+ linkingId: null,+ onLinkParticipant: vi.fn(),+ onCreateAndLinkParticipant: vi.fn(),+ onUnlinkParticipant: vi.fn(),+ onOpenTribePerson: vi.fn(),+ onBack: vi.fn(),+ onRetry: null,+ onArchive: vi.fn(),+ onLowPriority: vi.fn(),+ onPurge: null,+ purging: false,+ onAttachmentUpdated: vi.fn(),+ writePending: false,+};++const OUTBOX_ENTRY = { id: 'outbox-1', state: 'approved', body: 'hello there' };+const FAILED_ENTRY = {+ id: 'outbox-2', state: 'failed', body: 'hello there', errorMessage: 'Network error',+};+const TRIPPED_BREAKER = { tripped: true, reason: 'too many sends' };++// The server's own copy for a send interrupted by a restart, repeated here on+// purpose: client and server cannot share a module, so this literal and+// `SEND_INTERRUPTED_MESSAGE` in `server/services/beeperOutbox.js` are pinned by+// a test on each side rather than by an import.+const SEND_INTERRUPTED_COPY = 'Delivery unconfirmed: PortOS restarted mid-send. Check the chat before retrying.';+const UNRESOLVED_REASON = 'Beeper reported no matching message within 30s — it may still have been delivered, so it was not re-sent.';++// A send that settled long ago. `GET /outbox` returns up to 50 entries in every+// state, so its mirrored message is routinely older than the newest page.+const SENT_ENTRY = {+ id: 'outbox-3', state: 'sent', body: 'settled long ago', messageId: 'msg-aged-out',+};+const UNRESOLVED_ENTRY = {+ id: 'outbox-4',+ state: 'awaiting-confirmation',+ body: 'hello there',+ errorCode: 'CONFIRMATION_UNRESOLVED',+ errorMessage: UNRESOLVED_REASON,+};+const INTERRUPTED_ENTRY = {+ id: 'outbox-5',+ state: 'failed',+ body: 'hello there',+ errorCode: 'SEND_INTERRUPTED',+ errorMessage: SEND_INTERRUPTED_COPY,+};++const renderThread = (overrides = {}) => render(<BeeperThread {...BASE_PROPS} {...overrides} />);++afterEach(cleanup);++describe('BeeperThread — outbox row states', () => {+ it('offers Retry and Dismiss on a stalled approved row instead of a permanent spinner', () => {+ renderThread({ outboxEntries: [OUTBOX_ENTRY], sending: false });++ const row = screen.getByTestId('beeper-outbox-row');+ expect(row).toHaveAttribute('data-state', 'approved');+ expect(screen.getByRole('button', { name: 'Retry' })).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Dismiss' })).toBeInTheDocument();+ expect(screen.queryByText('Sending…')).not.toBeInTheDocument();+ });++ it('still shows the sending spinner, not Retry/Dismiss, while an approved row is actually in flight', () => {+ renderThread({ outboxEntries: [OUTBOX_ENTRY], sending: true });++ expect(screen.getByText('Sending…')).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Retry' })).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Dismiss' })).not.toBeInTheDocument();+ });++ it('still shows the sending spinner while the same row is the subject of a pending first-contact confirmation', () => {+ renderThread({+ outboxEntries: [OUTBOX_ENTRY],+ sending: false,+ confirmation: { entry: OUTBOX_ENTRY, message: 'first contact' },+ });++ expect(screen.getByText('Sending…')).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Retry' })).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Dismiss' })).not.toBeInTheDocument();+ });++ // Retrying a stalled row must re-dispatch the SAME row (via the hook's+ // `retry`), never compose a new one through `onSend` — that would+ // manufacture a fresh phantom on every click while the breaker stays+ // tripped, the failure mode the reviewer flagged.+ it('retries a stalled row in place, never composing a new one via onSend', () => {+ const retryOutboxEntry = vi.fn();+ const onSend = vi.fn();+ renderThread({+ outboxEntries: [OUTBOX_ENTRY], sending: false, retryOutboxEntry, onSend,+ });++ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));++ expect(retryOutboxEntry).toHaveBeenCalledWith(OUTBOX_ENTRY);+ expect(onSend).not.toHaveBeenCalled();+ });++ it('dismisses a stalled row on request', () => {+ const dismissOutboxEntry = vi.fn();+ renderThread({ outboxEntries: [OUTBOX_ENTRY], sending: false, dismissOutboxEntry });++ fireEvent.click(screen.getByRole('button', { name: 'Dismiss' }));++ expect(dismissOutboxEntry).toHaveBeenCalledWith(OUTBOX_ENTRY);+ });++ // The failed row's text is NOT the composer's draft, so this send must not+ // clear the composer on success — a message typed while the failed row sat+ // above it would be discarded, and dropped from storage with it.+ it('composes a new entry via onSend when retrying a failed row, without clearing the draft', () => {+ const onSend = vi.fn();+ const retryOutboxEntry = vi.fn();+ renderThread({ outboxEntries: [FAILED_ENTRY], onSend, retryOutboxEntry });++ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));++ expect(onSend).toHaveBeenCalledWith('hello there', { clearsDraft: false });+ expect(retryOutboxEntry).not.toHaveBeenCalled();+ expect(screen.queryByRole('button', { name: 'Dismiss' })).not.toBeInTheDocument();+ });++ // A failed row's Retry composes a new entry through the same send path the+ // breaker blocks, so with the breaker tripped it can only fail. It used to+ // stay enabled and silently do nothing (PR #60 blocker 2).+ it("disables a failed row's Retry while the breaker is tripped, with the Send button's reason", () => {+ const onSend = vi.fn();+ renderThread({ outboxEntries: [FAILED_ENTRY], breaker: TRIPPED_BREAKER, onSend });++ const retry = screen.getByRole('button', { name: 'Retry' });+ const sendTitle = screen.getByRole('button', { name: 'Send' }).getAttribute('title');+ expect(retry).toBeDisabled();+ expect(retry).toHaveAttribute('title', sendTitle);+ expect(sendTitle).toContain('too many sends');++ fireEvent.click(retry);+ expect(onSend).not.toHaveBeenCalled();+ });++ // The stalled row is the opposite case: nothing has reached Beeper for it,+ // the server decides whether to refuse it again, and its 429 toasts. So+ // that Retry stays live even with the breaker tripped.+ it("leaves a stalled row's Retry enabled while the breaker is tripped", () => {+ const retryOutboxEntry = vi.fn();+ renderThread({ outboxEntries: [OUTBOX_ENTRY], breaker: TRIPPED_BREAKER, retryOutboxEntry });++ const retry = screen.getByRole('button', { name: 'Retry' });+ expect(retry).toBeEnabled();++ fireEvent.click(retry);+ expect(retryOutboxEntry).toHaveBeenCalledWith(OUTBOX_ENTRY);+ });+});++/**+ * Every outbox state that cannot change on its own has to READ as finished. The+ * three below could each hold a spinner forever: a settled `sent` row whose+ * message had aged out of the loaded page, a send the server could not confirm,+ * and a send a restart interrupted. None of them will ever advance, so none of+ * them may spin — and none may lose that property on a remount, which is the+ * shape a reload takes.+ */+describe('BeeperThread — terminal outbox states never spin', () => {+ it('renders no bubble for a settled sent entry whose mirrored message is not in the loaded page', () => {+ const { container } = renderThread({ outboxEntries: [SENT_ENTRY], messages: [] });++ expect(screen.queryByTestId('beeper-outbox-row')).toBeNull();+ expect(screen.queryByText('settled long ago')).toBeNull();+ expect(container.querySelector('.animate-spin')).toBeNull();+ });++ // The mirrored-id check survives as the tiebreak for the one case it is still+ // the right answer for: a row still in flight that the sweep already mirrored.+ it('drops an awaiting-confirmation row the sweep has already mirrored', () => {+ const mirrored = {+ id: 'msg-mirrored', body: 'hello there', sentAt: '2026-09-01T10:00:00.000Z', isSender: true, senderId: 'user-me',+ };+ renderThread({+ outboxEntries: [{ ...UNRESOLVED_ENTRY, errorCode: null, errorMessage: null, messageId: 'msg-mirrored' }],+ messages: [mirrored],+ });++ expect(screen.queryByTestId('beeper-outbox-row')).toBeNull();+ expect(screen.getByTestId('beeper-message')).toBeInTheDocument();+ });++ it('renders an unconfirmed send as terminal, carrying the reason the server recorded', () => {+ const { container } = renderThread({ outboxEntries: [UNRESOLVED_ENTRY] });++ const row = screen.getByTestId('beeper-outbox-row');+ expect(row).toHaveAttribute('data-outcome', 'unconfirmed');+ expect(within(row).getByText(`Sent, unconfirmed — ${UNRESOLVED_REASON}`)).toBeInTheDocument();+ expect(screen.queryByText('Confirming…')).toBeNull();+ expect(container.querySelector('.animate-spin')).toBeNull();+ // No Retry: the message may well have been delivered, and a resend is the+ // one mistake that cannot be taken back.+ expect(screen.queryByRole('button', { name: 'Retry' })).toBeNull();+ });++ it('renders an interrupted send with the exact copy and the usual failed-row Retry', () => {+ const onSend = vi.fn();+ const { container } = renderThread({ outboxEntries: [INTERRUPTED_ENTRY], onSend });++ const row = screen.getByTestId('beeper-outbox-row');+ expect(row).toHaveAttribute('data-outcome', 'failed');+ expect(within(row).getByText(SEND_INTERRUPTED_COPY)).toBeInTheDocument();+ expect(container.querySelector('.animate-spin')).toBeNull();++ fireEvent.click(within(row).getByRole('button', { name: 'Retry' }));+ // Retry composes a NEW entry from that row's text, exactly like any other+ // failed row — never a resend of a POST whose outcome is unknown.+ expect(onSend).toHaveBeenCalledWith('hello there', { clearsDraft: false });+ });++ it('keeps both terminal states across a remount, the shape a reload takes', () => {+ const first = renderThread({ outboxEntries: [UNRESOLVED_ENTRY, INTERRUPTED_ENTRY] });+ expect(screen.getAllByTestId('beeper-outbox-row')).toHaveLength(2);+ first.unmount();++ const { container } = renderThread({ outboxEntries: [UNRESOLVED_ENTRY, INTERRUPTED_ENTRY] });++ // Rendered oldest-last: `entries` arrives newest-first and is reversed.+ expect(screen.getAllByTestId('beeper-outbox-row').map((row) => row.dataset.outcome))+ .toEqual(['failed', 'unconfirmed']);+ expect(within(screen.getAllByTestId('beeper-outbox-row')[0]).getByText(SEND_INTERRUPTED_COPY)).toBeInTheDocument();+ expect(container.querySelector('.animate-spin')).toBeNull();+ });+});++/**+ * Final live pass: some networks (Discord, Matrix — 26% of messages on a real+ * install) deliver HTML bodies, and the mirror stores what the source sent, so+ * the bubble rendered the tags literally. The allowlisted subset is parsed and+ * rendered as elements; nothing reaches `dangerouslySetInnerHTML`.+ */+describe('BeeperThread — message bodies', () => {+ const message = (body) => ({+ id: 'msg-1', body, sentAt: '2026-09-01T10:00:00.000Z', isSender: false, senderId: 'user-1',+ });++ it('renders an HTML body as elements rather than showing the tags', () => {+ renderThread({ messages: [message('<p>hello <strong>there</strong></p><p>second line</p>')] });++ const bubble = screen.getByTestId('beeper-message');+ expect(bubble).toHaveTextContent('hello there');+ expect(bubble).toHaveTextContent('second line');+ expect(bubble.textContent).not.toContain('<p>');+ expect(bubble.textContent).not.toContain('<strong>');+ expect(bubble.querySelector('strong')).toBeInTheDocument();+ });++ it('renders a blockquote and a link, and refuses a non-http scheme', () => {+ renderThread({+ messages: [message('<blockquote>quoted</blockquote><p><a href="https://example.com">ok</a> <a href="javascript:alert(1)">no</a></p>')],+ });++ const bubble = screen.getByTestId('beeper-message');+ expect(bubble.querySelector('blockquote')).toHaveTextContent('quoted');+ const links = bubble.querySelectorAll('a');+ expect(links).toHaveLength(1);+ expect(links[0]).toHaveAttribute('href', 'https://example.com');+ expect(bubble).toHaveTextContent('no');+ });++ it('keeps a plain body on the text-node path with its entities decoded (#59)', () => {+ renderThread({ messages: [message('salt & pepper — 5 < 6')] });++ expect(screen.getByTestId('beeper-message')).toHaveTextContent('salt & pepper — 5 < 6');+ });+});++/**+ * Audit cluster 05 (Tribe linkage): the server used to leak `tribePersonId`/+ * `tribePersonName` for a participant whose Tribe person had been+ * soft-deleted, so this row's `if (participant.tribePersonId)` branch read it+ * as still linked and rendered "Linked · <deleted person>" with no way back —+ * the re-link `<select>`/buttons never appeared. The server fix (parity test+ * in `server/services/beeperConversations.test.js`) now sends such a+ * participant with `tribePersonId: null` and no `tribePersonName`, exactly+ * like a participant that was never linked at all. This pins the client's+ * side of that contract: given that shape, the People drawer must render the+ * re-link control, never a dead "Linked" label.+ */+describe('BeeperThread — participant Tribe link display', () => {+ const PEOPLE = [{ id: 'person-1', name: 'Alex Example' }];++ const openPeopleDrawer = () => fireEvent.click(screen.getByRole('button', { name: 'People' }));++ it('renders the re-link control, not a dead "Linked" label, for a participant whose Tribe person was soft-deleted', () => {+ renderThread({+ conversation: {+ ...CONVERSATION,+ participants: [{+ sourceUserId: 'user-1',+ displayName: 'Sam Example',+ handle: '+15550100',+ tribePersonId: null,+ tribePersonName: null,+ observedVia: 'participant-list',+ }],+ },+ people: PEOPLE,+ });++ openPeopleDrawer();++ expect(screen.queryByText(/^Linked/)).not.toBeInTheDocument();+ expect(screen.getByLabelText('Link Sam Example to a Tribe person')).toBeInTheDocument();+ // The picker replaces the old `<select>` + Link button — no such button+ // remains, and there is no separate "Link" step: picking a result IS it.+ expect(screen.queryByRole('button', { name: 'Link' })).not.toBeInTheDocument();+ expect(document.querySelector('select')).toBeNull();+ });++ it('still shows the Linked label (and no re-link control) for a participant with an active link', () => {+ renderThread({+ conversation: {+ ...CONVERSATION,+ participants: [{+ sourceUserId: 'user-1',+ displayName: 'Sam Example',+ handle: '+15550100',+ tribePersonId: 'person-1',+ tribePersonName: 'Alex Example',+ observedVia: 'participant-list',+ }],+ },+ people: PEOPLE,+ });++ openPeopleDrawer();++ expect(screen.getByText('Linked · Alex Example')).toBeInTheDocument();+ expect(screen.queryByLabelText('Link Sam Example to a Tribe person')).not.toBeInTheDocument();+ });++ // #98 part C: the "Linked · <name>" row is a link straight to the Tribe+ // page (`?person=<id>`), the same deep link the title chip uses.+ it('jumps to the linked person\'s Tribe page when "Linked · <name>" is clicked', () => {+ const onOpenTribePerson = vi.fn();+ renderThread({+ conversation: {+ ...CONVERSATION,+ participants: [{+ sourceUserId: 'user-1',+ displayName: 'Sam Example',+ handle: '+15550100',+ tribePersonId: 'person-1',+ tribePersonName: 'Alex Example',+ observedVia: 'participant-list',+ }],+ },+ people: PEOPLE,+ onOpenTribePerson,+ });++ openPeopleDrawer();+ fireEvent.click(screen.getByText('Linked · Alex Example'));++ expect(onOpenTribePerson).toHaveBeenCalledWith('person-1');+ });+});++/**+ * Findings PERF-8/A11Y-2: the scroll-to-bottom effect keyed on `ordered.length`+ * directly, which "Load earlier messages" changes on every click (it only+ * prepends OLDER messages) — so every page-in yanked the reader back to the+ * newest message. The fix tracks the newest message actually on screen in a+ * ref and scrolls only when THAT changes (or the conversation does).+ */+/**+ * Audit cluster 08 (A11Y-5): the first-contact confirmation used to reveal+ * with no `autoFocus` and no accessible name, and the Send button dropped+ * itself to `disabled` mid-send — moving focus to `<body>` — so neither a+ * keyboard nor a screen-reader user was ever told the row had appeared.+ * `InlineConfirmRow` already supports `autoFocus` (see+ * `ui/UnsavedChangesConfirm.jsx`, the sibling caller); the fix wires it here+ * and swaps the Send button's `disabled` for `aria-disabled` so a mid-send+ * state change never steals focus away from it.+ */+describe('BeeperThread — first-contact confirmation is accessible', () => {+ it('moves focus into the revealed row and names the conversation as its accessible name', () => {+ renderThread({+ outboxEntries: [OUTBOX_ENTRY],+ confirmation: { entry: OUTBOX_ENTRY, message: 'first contact' },+ });++ const row = screen.getByLabelText(/Confirm sending the first message/);+ expect(row).toHaveFocus();+ expect(row).toHaveAccessibleName(expect.stringContaining('Example Contact'));+ });++ it('keeps focus on Send when it becomes aria-disabled mid-send, never the native disabled attribute', () => {+ const { rerender } = renderThread({ draft: 'hello', sending: false });+ const send = screen.getByRole('button', { name: 'Send' });+ send.focus();+ expect(send).toHaveFocus();++ rerender(<BeeperThread {...BASE_PROPS} draft="hello" sending />);++ const sendAfter = screen.getByRole('button', { name: 'Send' });+ expect(sendAfter).toHaveAttribute('aria-disabled', 'true');+ expect(sendAfter).not.toHaveAttribute('disabled');+ expect(sendAfter).toHaveFocus();+ });+});++/**+ * Audit cluster 08 (A11Y-6): the inline error paragraphs carried no role, and+ * every fetch behind them passes `{ silent: true }`, so a screen-reader user+ * got no signal at all when the thread failed to open or a fetch behind an+ * already-open thread errored.+ */+describe('BeeperThread — inline errors are announced', () => {+ it('exposes the could-not-open error as an alert', () => {+ renderThread({ conversation: null, error: 'Could not reach the mirror' });+ expect(screen.getByText('Could not reach the mirror')).toHaveAttribute('role', 'alert');+ });++ it('exposes the in-thread error banner as an alert', () => {+ renderThread({ error: 'Could not load newer messages' });+ expect(screen.getByText('Could not load newer messages')).toHaveAttribute('role', 'alert');+ });+});++describe('BeeperThread — scroll anchoring', () => {+ const olderMessage = (id, sentAt) => ({+ id, body: `Placeholder body ${id}`, sentAt, isSender: false, senderId: 'user-1', attachments: [],+ });++ it('leaves the scroll position on the fetched history when older messages page in', () => {+ const scrollSpy = vi.spyOn(Element.prototype, 'scrollIntoView').mockImplementation(() => {});+ const newest = olderMessage('m2', '2026-09-01T10:00:00.000Z');+ const { rerender } = renderThread({ messages: [newest], hasMore: true });+ const callsAfterMount = scrollSpy.mock.calls.length;+ expect(callsAfterMount).toBeGreaterThan(0);++ // Exactly what `loadMoreMessages` does on the real component: an OLDER+ // page appended to the TAIL of `messages` — the newest entry (and its id)+ // is untouched.+ const olderPage = olderMessage('m1', '2026-09-01T09:00:00.000Z');+ rerender(<BeeperThread {...BASE_PROPS} messages={[newest, olderPage]} hasMore={false} />);++ expect(scrollSpy.mock.calls.length).toBe(callsAfterMount);+ scrollSpy.mockRestore();+ });++ it('still scrolls to the bottom when a genuinely new newest message arrives', () => {+ const scrollSpy = vi.spyOn(Element.prototype, 'scrollIntoView').mockImplementation(() => {});+ const first = olderMessage('m1', '2026-09-01T09:00:00.000Z');+ const { rerender } = renderThread({ messages: [first] });+ const callsAfterMount = scrollSpy.mock.calls.length;++ // A brand new message is NEWEST-first, so it lands at index 0.+ const brandNew = olderMessage('m2', '2026-09-01T10:00:00.000Z');+ rerender(<BeeperThread {...BASE_PROPS} messages={[brandNew, first]} />);++ expect(scrollSpy.mock.calls.length).toBeGreaterThan(callsAfterMount);+ scrollSpy.mockRestore();+ });++ it('scrolls on a conversation switch even when the newest message id is unchanged', () => {+ const scrollSpy = vi.spyOn(Element.prototype, 'scrollIntoView').mockImplementation(() => {});+ const shared = olderMessage('m1', '2026-09-01T09:00:00.000Z');+ const { rerender } = renderThread({ messages: [shared] });+ const callsAfterMount = scrollSpy.mock.calls.length;++ rerender(<BeeperThread {...BASE_PROPS} conversation={{ ...CONVERSATION, id: 'convo-2' }} messages={[shared]} />);++ expect(scrollSpy.mock.calls.length).toBeGreaterThan(callsAfterMount);+ scrollSpy.mockRestore();+ });+});++/**+ * #98 part A: the Tribe link beside the thread title. A 1:1 chat (the fork+ * `isGroup` field, mirrored from Beeper's own `chat.type`) shows the+ * counterpart's link state; a group chat shows a participant-count chip+ * instead, regardless of how many rows happen to be linked.+ */+describe('BeeperThread — title Tribe chip', () => {+ const linkedParticipant = {+ sourceUserId: 'user-1', displayName: 'Sam Example', handle: '+15550100', tribePersonId: 'person-1', tribePersonName: 'Alex Example',+ };+ const unlinkedParticipant = {+ sourceUserId: 'user-1', displayName: 'Sam Example', handle: '+15550100', tribePersonId: null, tribePersonName: null,+ };++ it('shows "<name> · Tribe" for a linked 1:1 counterpart, and navigates on click', () => {+ const onOpenTribePerson = vi.fn();+ renderThread({+ conversation: { ...CONVERSATION, isGroup: false, participants: [linkedParticipant] },+ onOpenTribePerson,+ });++ const chip = screen.getByRole('button', { name: 'Alex Example · Tribe' });+ fireEvent.click(chip);+ expect(onOpenTribePerson).toHaveBeenCalledWith('person-1');+ });++ it('shows "Link to Tribe" for an unlinked 1:1 counterpart, opening the participants panel on click', () => {+ renderThread({+ conversation: { ...CONVERSATION, isGroup: false, participants: [unlinkedParticipant] },+ });++ expect(screen.queryByText(/Participants/)).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: /Link to Tribe/ }));+ expect(screen.getByText(/^Participants/)).toBeInTheDocument();+ });++ it('shows a participant-count chip for a group chat, never a per-person link state', () => {+ renderThread({+ conversation: {+ ...CONVERSATION,+ isGroup: true,+ participants: [linkedParticipant, unlinkedParticipant],+ },+ });++ expect(screen.getByRole('button', { name: '2 people' })).toBeInTheDocument();+ expect(screen.queryByText(/Tribe$/)).not.toBeInTheDocument();+ expect(screen.queryByText(/Link to Tribe/)).not.toBeInTheDocument();+ });++ it('marks a group-count chip partial ("+") when Beeper truncated the roster', () => {+ renderThread({+ conversation: {+ ...CONVERSATION, isGroup: true, participants: [linkedParticipant], hasMoreParticipants: true,+ },+ });++ expect(screen.getByRole('button', { name: '1+ person' })).toBeInTheDocument();+ });++ it('opens the participants panel from the group chip, the same panel the People button opens', () => {+ renderThread({+ conversation: { ...CONVERSATION, isGroup: true, participants: [linkedParticipant] },+ });++ fireEvent.click(screen.getByRole('button', { name: '1 person' }));+ expect(screen.getByText(/^Participants/)).toBeInTheDocument();+ });+});++/**+ * #98 part B: the search-first person picker replacing the old `<select>` in+ * the unlinked-participant row. These exercise it through `BeeperThread`+ * (rather than `BeeperPersonPicker` in isolation) for the wiring — that+ * selecting a result calls `onLinkParticipant` and that "Create new…" calls+ * `onCreateAndLinkParticipant` exactly like the old "New" button did. The+ * picker's own filtering/keyboard behavior is covered in+ * `BeeperPersonPicker.test.jsx`.+ */+describe('BeeperThread — participant picker wiring', () => {+ const PARTICIPANT = { sourceUserId: 'user-1', displayName: 'Sam Example', handle: '+15550100', tribePersonId: null };+ const PEOPLE = [{ id: 'person-1', name: 'Alex Example' }, { id: 'person-2', name: 'Blair Sample' }];++ const openDrawerAndFocusPicker = () => {+ fireEvent.click(screen.getByRole('button', { name: 'People' }));+ const input = screen.getByLabelText('Link Sam Example to a Tribe person');+ fireEvent.focus(input);+ return input;+ };++ it('links directly on selecting a result — no separate Link button', () => {+ const onLinkParticipant = vi.fn();+ renderThread({+ conversation: { ...CONVERSATION, participants: [PARTICIPANT] },+ people: PEOPLE,+ onLinkParticipant,+ });++ openDrawerAndFocusPicker();+ fireEvent.mouseDown(screen.getByRole('option', { name: 'Alex Example' }));++ expect(onLinkParticipant).toHaveBeenCalledWith(PARTICIPANT, 'person-1');+ });++ it('puts "Create new…" last, after every match, and opens the confirm-and-rename form instead of creating immediately (#97 part A)', () => {+ const onCreateAndLinkParticipant = vi.fn();+ renderThread({+ conversation: { ...CONVERSATION, participants: [PARTICIPANT] },+ people: PEOPLE,+ onCreateAndLinkParticipant,+ });++ openDrawerAndFocusPicker();+ const options = screen.getAllByRole('option');+ expect(options[options.length - 1]).toHaveTextContent('Create new…');++ fireEvent.mouseDown(options[options.length - 1]);++ // No immediate post — the form takes the picker's place instead,+ // prefilled from the participant's own display name.+ expect(onCreateAndLinkParticipant).not.toHaveBeenCalled();+ expect(screen.getByLabelText('Name')).toHaveValue('Sam Example');+ });++ it('is keyboard-navigable: ArrowDown cycles results, Enter selects the highlighted one', () => {+ const onLinkParticipant = vi.fn();+ renderThread({+ conversation: { ...CONVERSATION, participants: [PARTICIPANT] },+ people: PEOPLE,+ onLinkParticipant,+ });++ const input = openDrawerAndFocusPicker();+ // Starts on the first match (index 0); one ArrowDown moves to the second.+ fireEvent.keyDown(input, { key: 'ArrowDown' });+ fireEvent.keyDown(input, { key: 'Enter' });++ expect(onLinkParticipant).toHaveBeenCalledWith(PARTICIPANT, 'person-2');+ });++ it('closes the results on Escape without linking anyone', () => {+ const onLinkParticipant = vi.fn();+ renderThread({+ conversation: { ...CONVERSATION, participants: [PARTICIPANT] },+ people: PEOPLE,+ onLinkParticipant,+ });++ const input = openDrawerAndFocusPicker();+ expect(screen.getByRole('listbox')).toBeInTheDocument();+ fireEvent.keyDown(input, { key: 'Escape' });++ expect(screen.queryByRole('listbox')).not.toBeInTheDocument();+ expect(onLinkParticipant).not.toHaveBeenCalled();+ });++ it('no full-roster <select> remains anywhere in the drawer', () => {+ renderThread({+ conversation: { ...CONVERSATION, participants: [PARTICIPANT] },+ people: PEOPLE,+ });++ fireEvent.click(screen.getByRole('button', { name: 'People' }));+ expect(document.querySelector('select')).toBeNull();+ });++ // #105: the roster `<ul>` (`max-h-40 … overflow-y-auto`) clips an+ // absolutely positioned child, so the results list used to extend that+ // scroll container instead of floating over it — nearly invisible on a+ // 1:1 chat. `BeeperPersonPicker` now portals it to `document.body`, which+ // this pins from the roster's side: the listbox must never be a DOM+ // descendant of the roster, portaled or not.+ it('renders the results listbox outside the participants roster, not clipped by its scroll container', () => {+ renderThread({+ conversation: { ...CONVERSATION, participants: [PARTICIPANT] },+ people: PEOPLE,+ });++ openDrawerAndFocusPicker();++ const roster = screen.getByTestId('beeper-participants-roster');+ const listbox = screen.getByRole('listbox');+ expect(roster.contains(listbox)).toBe(false);+ expect(document.body.contains(listbox)).toBe(true);+ });+});++/**+ * Fork issue #97 part A: the confirm-and-rename form "Create new…" opens+ * instead of posting immediately. The form's own field/keyboard contract is+ * pinned in isolation in `BeeperCreatePersonForm.test.jsx`; these cover the+ * wiring from the row into it and back.+ */+describe('BeeperThread — create-person form wiring', () => {+ const PARTICIPANT = { sourceUserId: 'user-1', displayName: 'Sam Example', handle: '+15550100', tribePersonId: null };+ const PEOPLE = [{ id: 'person-1', name: 'Alex Example' }];++ const openForm = () => {+ fireEvent.click(screen.getByRole('button', { name: 'People' }));+ const input = screen.getByLabelText('Link Sam Example to a Tribe person');+ fireEvent.focus(input);+ const options = screen.getAllByRole('option');+ fireEvent.mouseDown(options[options.length - 1]);+ };++ it('calls onCreateAndLinkParticipant with the edited name, ring and relationship only on Create', () => {+ const onCreateAndLinkParticipant = vi.fn();+ renderThread({+ conversation: { ...CONVERSATION, participants: [PARTICIPANT] },+ people: PEOPLE,+ onCreateAndLinkParticipant,+ });++ openForm();+ fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'Corrected Name' } });+ fireEvent.change(screen.getByLabelText('Ring'), { target: { value: 'core' } });+ fireEvent.change(screen.getByLabelText('Relationship'), { target: { value: 'Neighbor' } });+ expect(onCreateAndLinkParticipant).not.toHaveBeenCalled();++ fireEvent.click(screen.getByRole('button', { name: 'Create' }));++ expect(onCreateAndLinkParticipant).toHaveBeenCalledWith(+ PARTICIPANT,+ { name: 'Corrected Name', ring: 'core', relationship: 'Neighbor' },+ );+ });++ it('returns to the picker on Cancel, without creating anyone', () => {+ const onCreateAndLinkParticipant = vi.fn();+ renderThread({+ conversation: { ...CONVERSATION, participants: [PARTICIPANT] },+ people: PEOPLE,+ onCreateAndLinkParticipant,+ });++ openForm();+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));++ expect(onCreateAndLinkParticipant).not.toHaveBeenCalled();+ expect(screen.getByLabelText('Link Sam Example to a Tribe person')).toBeInTheDocument();+ expect(screen.queryByLabelText('Name')).not.toBeInTheDocument();+ });++ it('submits on Enter and cancels on Escape', () => {+ const onCreateAndLinkParticipant = vi.fn();+ renderThread({+ conversation: { ...CONVERSATION, participants: [PARTICIPANT] },+ people: PEOPLE,+ onCreateAndLinkParticipant,+ });++ openForm();+ fireEvent.keyDown(screen.getByLabelText('Name'), { key: 'Escape' });+ const picker = screen.getByLabelText('Link Sam Example to a Tribe person');+ expect(picker).toBeInTheDocument();++ // The drawer stays open across Escape — reopen the form without+ // re-toggling the People button, which would otherwise close it.+ fireEvent.focus(picker);+ const options = screen.getAllByRole('option');+ fireEvent.mouseDown(options[options.length - 1]);+ fireEvent.keyDown(screen.getByLabelText('Name'), { key: 'Enter' });+ expect(onCreateAndLinkParticipant).toHaveBeenCalledWith(+ PARTICIPANT,+ { name: 'Sam Example', ring: 'tribe', relationship: '' },+ );+ });+});++/**+ * Fork issue #97 part B: Change and Unlink on an already-linked participant+ * row — the "Linked · <name>" label used to be the whole story, with no way+ * back from a mistaken or outdated link.+ */+describe('BeeperThread — change and unlink a linked participant', () => {+ const LINKED_PARTICIPANT = {+ sourceUserId: 'user-1', displayName: 'Sam Example', handle: '+15550100',+ tribePersonId: 'person-1', tribePersonName: 'Alex Example',+ };+ const PEOPLE = [{ id: 'person-1', name: 'Alex Example' }, { id: 'person-2', name: 'Blair Sample' }];++ const openPeopleDrawer = () => fireEvent.click(screen.getByRole('button', { name: 'People' }));++ it('offers Change and Unlink beside the Linked label', () => {+ renderThread({+ conversation: { ...CONVERSATION, participants: [LINKED_PARTICIPANT] },+ people: PEOPLE,+ });++ openPeopleDrawer();++ expect(screen.getByText('Linked · Alex Example')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Change' })).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Unlink' })).toBeInTheDocument();+ });++ it('opens the picker, pre-focused, on Change — selecting a person re-links via onLinkParticipant', () => {+ const onLinkParticipant = vi.fn();+ renderThread({+ conversation: { ...CONVERSATION, participants: [LINKED_PARTICIPANT] },+ people: PEOPLE,+ onLinkParticipant,+ });++ openPeopleDrawer();+ fireEvent.click(screen.getByRole('button', { name: 'Change' }));++ const picker = screen.getByLabelText('Link Sam Example to a Tribe person');+ expect(picker).toHaveFocus();++ fireEvent.mouseDown(screen.getByRole('option', { name: 'Blair Sample' }));+ expect(onLinkParticipant).toHaveBeenCalledWith(LINKED_PARTICIPANT, 'person-2');+ });++ it('returns to the Linked label on Cancel from the Change picker', () => {+ renderThread({+ conversation: { ...CONVERSATION, participants: [LINKED_PARTICIPANT] },+ people: PEOPLE,+ });++ openPeopleDrawer();+ fireEvent.click(screen.getByRole('button', { name: 'Change' }));+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));++ expect(screen.getByText('Linked · Alex Example')).toBeInTheDocument();+ });++ it('opens the create-person form from "Create new…" inside the Change picker too', () => {+ renderThread({+ conversation: { ...CONVERSATION, participants: [LINKED_PARTICIPANT] },+ people: PEOPLE,+ });++ openPeopleDrawer();+ fireEvent.click(screen.getByRole('button', { name: 'Change' }));+ const options = screen.getAllByRole('option');+ fireEvent.mouseDown(options[options.length - 1]);++ expect(screen.getByLabelText('Name')).toHaveValue('Sam Example');+ });++ it('calls onUnlinkParticipant with the participant on Unlink', () => {+ const onUnlinkParticipant = vi.fn();+ renderThread({+ conversation: { ...CONVERSATION, participants: [LINKED_PARTICIPANT] },+ people: PEOPLE,+ onUnlinkParticipant,+ });++ openPeopleDrawer();+ fireEvent.click(screen.getByRole('button', { name: 'Unlink' }));++ expect(onUnlinkParticipant).toHaveBeenCalledWith(LINKED_PARTICIPANT);+ });++ it('resets an open Change picker back to view when the participant\'s own linked state changes', () => {+ const { rerender } = renderThread({+ conversation: { ...CONVERSATION, participants: [LINKED_PARTICIPANT] },+ people: PEOPLE,+ });++ openPeopleDrawer();+ fireEvent.click(screen.getByRole('button', { name: 'Change' }));+ expect(screen.getByLabelText('Link Sam Example to a Tribe person')).toBeInTheDocument();++ rerender(<BeeperThread+ {...BASE_PROPS}+ conversation={{+ ...CONVERSATION,+ participants: [{ ...LINKED_PARTICIPANT, tribePersonId: 'person-2', tribePersonName: 'Blair Sample' }],+ }}+ people={PEOPLE}+ />);++ expect(screen.getByText('Linked · Blair Sample')).toBeInTheDocument();+ expect(screen.queryByLabelText('Link Sam Example to a Tribe person')).not.toBeInTheDocument();+ });+});diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex 0dd1150ebf..41c3ce00e9 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -56,6 +56,8 @@ export { default as useMusicVideoModelSettings } from './useMusicVideoModelSettiexport { default as useMusicVideoRenderJob } from './useMusicVideoRenderJob.js';export { default as useMusicVideoSceneMedia } from './useMusicVideoSceneMedia.js';export { default as useMusicVideoYoutubeImport } from './useMusicVideoYoutubeImport.js';+export { default as useBeeperOutbox } from './useBeeperOutbox.js';+export { default as useBeeperRealtime } from './useBeeperRealtime.js';export { default as useMoltworldWs } from './useMoltworldWs.js';export { default as useCharacterAugmentation } from './useCharacterAugmentation.js';export { default as useMounted } from './useMounted.js';@@ -89,6 +91,7 @@ export { default as useWakeLock } from './useWakeLock.js';export { default as useYoutubeIngest } from './useYoutubeIngest.js';export { default as useYoutubeTrackImport } from './useYoutubeTrackImport.js';export * from './useSyncSourceSettings.js';+export * from './useBeeperSettings.js';export { default as useReferenceAudioImport } from './useReferenceAudioImport.js';export { default as useMidiTranscription } from './useMidiTranscription.js';export { default as useMidiNotes } from './useMidiNotes.js';diff --git a/client/src/hooks/useBeeperOutbox.js b/client/src/hooks/useBeeperOutbox.jsnew file mode 100644index 0000000000..e0779f3500--- /dev/null+++ b/client/src/hooks/useBeeperOutbox.js@@ -0,0 +1,235 @@+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+ * 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 refresh = useCallback(async () => {+ if (!conversationId) {+ setEntries([]);+ return;+ }+ const result = await listOutboxEntries(conversationId, { silent: true }).catch(() => null);+ if (!mountedRef.current) 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]);++ useEffect(() => {+ 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;+ 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;+ 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]);++ // `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 (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]);++ /** 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 (err) {+ toast.error(err.message || 'Could not discard the message');+ await refresh();+ return;+ }+ setEntries((prev) => prev.filter((row) => row.id !== entry.id));+ }, [refresh]);++ /** 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 --git a/client/src/hooks/useBeeperOutbox.test.jsx b/client/src/hooks/useBeeperOutbox.test.jsxnew file mode 100644index 0000000000..abdfac4c14--- /dev/null+++ b/client/src/hooks/useBeeperOutbox.test.jsx@@ -0,0 +1,285 @@+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');+ });++ // `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 --git a/client/src/hooks/useBeeperRealtime.js b/client/src/hooks/useBeeperRealtime.jsnew file mode 100644index 0000000000..c27bcb37c4--- /dev/null+++ b/client/src/hooks/useBeeperRealtime.js@@ -0,0 +1,85 @@+import { useCallback, useEffect, useRef, useState } from 'react';+import socket from '../services/socket';++/**+ * Subscribe to the server's Beeper realtime relay (fork issue #33, decided on #12).+ *+ * The frames are INVALIDATION ONLY — `{ kind, chatID, ids, seq, ts }`, never+ * message bodies, display names or handles. A consumer reacts by refetching from+ * the PortOS API, which is the read path for the mirror; that is what keeps+ * "displayed" implying "persisted" and keeps a wrong broadcast leaking a UUID+ * instead of a conversation.+ *+ * **The subscription is re-emitted on every `connect`, not just at mount.** The+ * server rebuilds an empty per-socket subscriber Set on reconnect, so a one-shot+ * emit at mount goes permanently dead after a laptop sleep — the scar tissue+ * carried by `useMoltworldWs` and `ChiefOfStaff` for the same reason.+ *+ * One global subscription with client-side filtering, matching every other+ * subscriber namespace: per-conversation subscribe would drag in pending-request+ * generation tracking for a volume problem a single-user localhost install does+ * not have.+ *+ * @param {object} [options]+ * @param {(frame: object) => void} [options.onInvalidate] called per invalidation frame.+ */+export default function useBeeperRealtime({ onInvalidate } = {}) {+ // `null` = the server has not spoken yet (not-yet-known), distinct from a+ // reported `down`. A card must not render "offline" for a question it has+ // never asked.+ const [realtime, setRealtime] = useState(null);+ const [lastInvalidation, setLastInvalidation] = useState(null);++ // The callback rides a ref so a caller passing an inline arrow does not+ // re-run the effect — which would tear down and re-emit the subscription on+ // every render.+ const onInvalidateRef = useRef(onInvalidate);+ onInvalidateRef.current = onInvalidate;+ // Once the socket has spoken it is the fresher source, so a later status+ // refetch must not overwrite it with what the HTTP snapshot happened to hold.+ const socketSpokeRef = useRef(false);++ useEffect(() => {+ const subscribe = () => socket.emit('beeper:subscribe');+ subscribe();+ socket.on('connect', subscribe);++ const handleInvalidate = (frame) => {+ setLastInvalidation(frame ?? null);+ onInvalidateRef.current?.(frame);+ };+ // Validate shape, not truthiness: `state` is the whole point of the frame,+ // and an absent/malformed payload must preserve the previous snapshot+ // rather than blanking the dot.+ const handleState = (state) => {+ if (!state || typeof state.state !== 'string') return;+ socketSpokeRef.current = true;+ setRealtime(state);+ };++ socket.on('beeper:invalidate', handleInvalidate);+ socket.on('beeper:realtime', handleState);++ return () => {+ socket.off('connect', subscribe);+ socket.off('beeper:invalidate', handleInvalidate);+ socket.off('beeper:realtime', handleState);+ socket.emit('beeper:unsubscribe');+ };+ }, []);++ // Seed the liveness state from a status payload the caller already fetched+ // (`GET /api/beeper/status` carries `realtime`), so the dot is correct before+ // the first socket frame arrives rather than blank until something changes.+ const seedRealtime = useCallback((state) => {+ if (socketSpokeRef.current) return;+ if (state && typeof state.state === 'string') setRealtime(state);+ }, []);++ return {+ realtime,+ connectionState: realtime?.state ?? null,+ lastInvalidation,+ seedRealtime,+ };+}diff --git a/client/src/hooks/useBeeperRealtime.test.jsx b/client/src/hooks/useBeeperRealtime.test.jsxnew file mode 100644index 0000000000..b19896abaa--- /dev/null+++ b/client/src/hooks/useBeeperRealtime.test.jsx@@ -0,0 +1,93 @@+import {+ describe, it, expect, vi, beforeEach, afterEach,+} from 'vitest';+import { renderHook, act, cleanup } from '@testing-library/react';++// Mock the socket singleton so the test can drive the handlers the hook+// registers and observe the subscriptions it emits.+const handlers = new Map();+const emitted = [];+vi.mock('../services/socket', () => ({+ default: {+ on: (event, fn) => {+ if (!handlers.has(event)) handlers.set(event, new Set());+ handlers.get(event).add(fn);+ },+ off: (event, fn) => { handlers.get(event)?.delete(fn); },+ emit: (event, payload) => { emitted.push([event, payload]); },+ },+}));++const useBeeperRealtime = (await import('./useBeeperRealtime.js')).default;++const fire = (event, payload) => act(() => {+ for (const fn of [...(handlers.get(event) || [])]) fn(payload);+});++describe('useBeeperRealtime', () => {+ beforeEach(() => { handlers.clear(); emitted.length = 0; });+ afterEach(cleanup);++ it('subscribes at mount and RE-SUBSCRIBES on every socket connect', () => {+ // The server rebuilds an empty per-socket subscriber Set on reconnect, so a+ // one-shot emit at mount leaves the surface permanently dead after a+ // laptop sleep — the same scar `useMoltworldWs` carries.+ renderHook(() => useBeeperRealtime());+ expect(emitted.filter(([event]) => event === 'beeper:subscribe')).toHaveLength(1);++ fire('connect');+ fire('connect');+ expect(emitted.filter(([event]) => event === 'beeper:subscribe')).toHaveLength(3);+ });++ it('unsubscribes and detaches every listener on unmount', () => {+ const { unmount } = renderHook(() => useBeeperRealtime());+ unmount();+ expect(emitted.some(([event]) => event === 'beeper:unsubscribe')).toBe(true);+ expect(handlers.get('beeper:invalidate')?.size ?? 0).toBe(0);+ expect(handlers.get('beeper:realtime')?.size ?? 0).toBe(0);+ expect(handlers.get('connect')?.size ?? 0).toBe(0);+ });++ it('hands each invalidation frame to the caller and keeps the last one', () => {+ const onInvalidate = vi.fn();+ const { result } = renderHook(() => useBeeperRealtime({ onInvalidate }));++ const frame = { kind: 'message.upserted', chatID: 'chat-1', ids: ['m1'], seq: 3, ts: null };+ fire('beeper:invalidate', frame);++ expect(onInvalidate).toHaveBeenCalledWith(frame);+ expect(result.current.lastInvalidation).toEqual(frame);+ });++ it('does not re-subscribe when the caller passes a new inline callback each render', () => {+ const { rerender } = renderHook(() => useBeeperRealtime({ onInvalidate: () => {} }));+ rerender();+ rerender();+ expect(emitted.filter(([event]) => event === 'beeper:subscribe')).toHaveLength(1);+ });++ it('starts at null (not-yet-known) and never reports a state the server has not sent', () => {+ const { result } = renderHook(() => useBeeperRealtime());+ expect(result.current.connectionState).toBeNull();++ fire('beeper:realtime', { state: 'connected', lastEventAt: null, lastPingAt: null });+ expect(result.current.connectionState).toBe('connected');++ // A malformed frame preserves the last good snapshot rather than blanking+ // the dot (validate shape, not truthiness).+ fire('beeper:realtime', {});+ expect(result.current.connectionState).toBe('connected');+ });++ it('seeds from the status payload, and stops seeding once the socket has spoken', () => {+ const { result } = renderHook(() => useBeeperRealtime());++ act(() => result.current.seedRealtime({ state: 'down' }));+ expect(result.current.connectionState).toBe('down');++ fire('beeper:realtime', { state: 'connected' });+ act(() => result.current.seedRealtime({ state: 'down' }));+ expect(result.current.connectionState).toBe('connected');+ });+});diff --git a/client/src/hooks/useBeeperSettings.js b/client/src/hooks/useBeeperSettings.jsnew file mode 100644index 0000000000..05b6e8013f--- /dev/null+++ b/client/src/hooks/useBeeperSettings.js@@ -0,0 +1,110 @@+import { useEffect, useState } from 'react';+import { getSettings, updateSettings } from '../services/api';++export const BEEPER_DEFAULT_BASE_URL = 'http://127.0.0.1:23373';++const DEFAULTS = {+ enabled: false,+ intervalMinutes: 5,+ baseUrl: BEEPER_DEFAULT_BASE_URL,+ attachmentBudgetGb: 5,+ // Loopback-only by default (SEC-2, server/lib/mediaValidation.js): a+ // non-loopback baseUrl is prefixed onto every Beeper API call AND the+ // realtime WebSocket URL with the vault-stored access token attached, so+ // off is the only safe default — this is an explicit opt-in, never inferred+ // from the baseUrl the user typed.+ allowNonLoopbackBaseUrl: false,+};++// `value === ''` (a cleared field) falls back to the default; any other+// numeric-looking input — including a typed `0` — is clamped to the schema+// bounds instead. `Number(x) || fallback` would treat a typed 0 as falsy+// and silently substitute the default, masking the user's actual input.+const toFiniteNumber = (value, fallback) => {+ if (value === '' || value === null || value === undefined) return fallback;+ const num = Number(value);+ return Number.isFinite(num) ? num : fallback;+};+const clampInterval = (value) => Math.max(1, Math.min(1440, Math.floor(toFiniteNumber(value, DEFAULTS.intervalMinutes))));+const clampBudget = (value) => Math.max(0.1, Math.min(1000, toFiniteNumber(value, DEFAULTS.attachmentBudgetGb)));++// settings.beeper.{enabled,intervalMinutes,baseUrl,attachmentBudgetGb,+// allowNonLoopbackBaseUrl} — the ingestion + connection config this slice's+// Comms → Beeper card edits (#30). Deliberately never reads or writes+// `token`/`tokenExpiresAt`: the server strips the token from every+// GET /api/settings response and rejects a `beeper` PUT that includes one.+// The credential lives encrypted in Postgres and is written only through the+// dedicated connect routes (#31) — the Beeper card's Connect / paste /+// Disconnect actions, never this settings save.+//+// `save()` always PUTs the complete five-field object, never a diff — same+// convention as `useSyncSourceSettings` for iMessage/Signal/Spotify/YouTube —+// so a partial edit can never silently drop a sibling field on the server's+// generic top-level shallow merge.+export function useBeeperSettings() {+ const [loading, setLoading] = useState(true);+ const [form, setForm] = useState(DEFAULTS);+ const [saved, setSaved] = useState(DEFAULTS);+ const [saving, setSaving] = useState(false);+ // Distinguishes "the GET failed" from "the GET succeeded and returned no+ // beeper config yet" (a fresh install, which legitimately falls through to+ // DEFAULTS). Collapsing the two — the empty `.catch(() => {})` this replaced+ // — left `form`/`saved` holding DEFAULTS as though they were this install's+ // stored config, so the very next Save PUT those defaults over whatever was+ // actually there. `save()` below refuses while this is true; the card is the+ // one that turns it into a visible failure (root AGENTS.md, absent-vs-empty).+ const [loadFailed, setLoadFailed] = useState(false);++ useEffect(() => {+ let active = true;+ getSettings({ silent: true })+ .then((settings) => {+ if (!active) return;+ const config = settings?.beeper || {};+ const next = {+ enabled: typeof config.enabled === 'boolean' ? config.enabled : DEFAULTS.enabled,+ intervalMinutes: Number.isFinite(config.intervalMinutes) ? config.intervalMinutes : DEFAULTS.intervalMinutes,+ baseUrl: typeof config.baseUrl === 'string' && config.baseUrl ? config.baseUrl : DEFAULTS.baseUrl,+ attachmentBudgetGb: Number.isFinite(config.attachmentBudgetGb) ? config.attachmentBudgetGb : DEFAULTS.attachmentBudgetGb,+ allowNonLoopbackBaseUrl: typeof config.allowNonLoopbackBaseUrl === 'boolean'+ ? config.allowNonLoopbackBaseUrl : DEFAULTS.allowNonLoopbackBaseUrl,+ };+ setForm(next);+ setSaved(next);+ setLoadFailed(false);+ })+ .catch(() => { if (active) setLoadFailed(true); })+ .finally(() => { if (active) setLoading(false); });+ return () => { active = false; };+ }, []);++ const dirty = Object.keys(DEFAULTS).some((key) => String(form[key]) !== String(saved[key]));++ const save = async () => {+ // Refuse rather than PUT: `form`/`saved` are still DEFAULTS here, not this+ // install's actual config, so writing them would overwrite whatever is+ // really stored the moment the failed GET is retried and the card is+ // dismissed.+ if (loadFailed) return false;+ const next = {+ enabled: form.enabled,+ intervalMinutes: clampInterval(form.intervalMinutes),+ attachmentBudgetGb: clampBudget(form.attachmentBudgetGb),+ baseUrl: (form.baseUrl || '').trim() || DEFAULTS.baseUrl,+ allowNonLoopbackBaseUrl: Boolean(form.allowNonLoopbackBaseUrl),+ };+ setSaving(true);+ const settings = await updateSettings({ beeper: next }).catch(() => null);+ setSaving(false);+ if (!settings) return false;+ setForm(next);+ setSaved(next);+ return true;+ };++ return {+ loading, form, setForm, saving, dirty, save, loadFailed,+ };+}++export default useBeeperSettings;diff --git a/client/src/hooks/useBeeperSettings.test.js b/client/src/hooks/useBeeperSettings.test.jsnew file mode 100644index 0000000000..f95ffc57b5--- /dev/null+++ b/client/src/hooks/useBeeperSettings.test.js@@ -0,0 +1,56 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { renderHook, waitFor, act } from '@testing-library/react';++const api = vi.hoisted(() => ({ getSettings: vi.fn(), updateSettings: vi.fn() }));+vi.mock('../services/api', () => api);++import { useBeeperSettings, BEEPER_DEFAULT_BASE_URL } from './useBeeperSettings.js';++beforeEach(() => {+ vi.clearAllMocks();+});++describe('useBeeperSettings', () => {+ it('loads the stored config and allows a normal save', async () => {+ api.getSettings.mockResolvedValue({+ beeper: {+ enabled: true, intervalMinutes: 10, baseUrl: 'http://127.0.0.1:23373', attachmentBudgetGb: 8, allowNonLoopbackBaseUrl: false,+ },+ });+ api.updateSettings.mockResolvedValue({ beeper: {} });++ const { result } = renderHook(() => useBeeperSettings());+ await waitFor(() => expect(result.current.loading).toBe(false));++ expect(result.current.loadFailed).toBe(false);+ expect(result.current.form.enabled).toBe(true);+ expect(result.current.form.intervalMinutes).toBe(10);++ let saved;+ await act(async () => { saved = await result.current.save(); });+ expect(saved).toBe(true);+ expect(api.updateSettings).toHaveBeenCalledTimes(1);+ });++ // The regression this exists for: an empty `.catch(() => {})` used to turn a+ // failed settings GET into a card silently showing DEFAULTS, and the next+ // Save PUT those defaults over whatever config was actually stored. The hook+ // must hold a distinguishable load-failed state and refuse Save from it.+ it('leaves loadFailed:true after a failed GET and refuses Save — no PUT of default values', async () => {+ api.getSettings.mockRejectedValue(new Error('network error'));++ const { result } = renderHook(() => useBeeperSettings());+ await waitFor(() => expect(result.current.loading).toBe(false));++ expect(result.current.loadFailed).toBe(true);+ // The DEFAULTS a caller might otherwise mistake for "this install's saved+ // config" are still what `form` holds — proving the refusal below is load+ // bearing rather than incidental.+ expect(result.current.form.baseUrl).toBe(BEEPER_DEFAULT_BASE_URL);++ let saved;+ await act(async () => { saved = await result.current.save(); });+ expect(saved).toBe(false);+ expect(api.updateSettings).not.toHaveBeenCalled();+ });+});diff --git a/client/src/lib/beeperMessageBody.js b/client/src/lib/beeperMessageBody.jsnew file mode 100644index 0000000000..682a3063c9--- /dev/null+++ b/client/src/lib/beeperMessageBody.js@@ -0,0 +1,191 @@+/**+ * Beeper message bodies: entity decoding, and the small HTML subset some+ * networks deliver (fork issue #1, final live pass).+ *+ * Beeper hands PortOS a message body verbatim, and on a real install 26% of+ * them are HTML — Discord and Matrix mostly, with paragraphs, line breaks,+ * blockquotes, bold, italic and links. `normalizeMessageRow` persists that+ * string as it arrives (correct: the mirror stores what the source said), and+ * the thread rendered it as a text node, so the tags showed up literally in the+ * bubble and in the rail preview.+ *+ * PortOS has no HTML sanitizer for this shape. The Messages inbox renders full+ * email documents in a sandboxed iframe (`MessageDetail.jsx`'s `SafeHtmlBody`),+ * which is the right tool for a whole document and the wrong one for a chat+ * bubble — one iframe per message in a scrolling list, with no intrinsic+ * height. So instead of injecting HTML anywhere, this module PARSES the+ * allowlisted subset into a plain data model and the caller renders it as React+ * elements. Nothing here ever reaches `dangerouslySetInnerHTML`, so a tag+ * outside the allowlist cannot execute, load, or style anything — it is simply+ * dropped, keeping its text.+ *+ * The allowlist is exactly what was observed: `p`, `div`, `br`, `blockquote`,+ * `strong`/`b`, `em`/`i`, `a[href]`. Everything else contributes its text and+ * nothing more.+ *+ * A body with none of those tags is NOT HTML and is left alone —+ * `parseMessageBody` answers `null` — so a plain message reading `5 < 6` or+ * `<3` renders exactly as it did before, through `decodeHtmlEntities` on its+ * own (the #59 fix).+ */++import { isHttpUrl } from '../utils/urlNormalize.js';++// Mirrors `server/lib/xmlEntities.js` `decodeXmlEntities` (also privately+// mirrored by `client/src/lib/tabNotation.js`). Keep the three in sync.+const NAMED_ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'" };+// `decodeXmlEntities` takes an `extraEntities` map for exactly this case; the+// client copy inlines its one extra rather than growing a parameter. ` `+// is routine in the HTML bodies below and decodes to U+00A0, written as an+// escape so the source never carries an invisible non-breaking space.+const HTML_ENTITIES = { ...NAMED_ENTITIES, nbsp: '\u00a0' };+const ENTITY_RE = /&(#x[0-9a-fA-F]+|#[0-9]+|[a-zA-Z][a-zA-Z0-9]*);/g;++/**+ * Beeper Desktop delivers entity-encoded text for some bridged networks, so the+ * decode happens on the way OUT to the DOM. Everything decoded here is rendered+ * as a text node, so decoding only changes which characters are shown — it can+ * never introduce markup.+ */+export const decodeHtmlEntities = (str) => {+ if (typeof str !== 'string' || str.indexOf('&') === -1) return str;+ return str.replace(ENTITY_RE, (match, code) => {+ if (code[0] === '#') {+ const cp = code[1] === 'x' || code[1] === 'X'+ ? parseInt(code.slice(2), 16)+ : parseInt(code.slice(1), 10);+ return cp >= 0 && cp <= 0x10ffff ? String.fromCodePoint(cp) : match;+ }+ // `Object.hasOwn` rather than `in`: `&constructor;` must stay literal.+ return Object.hasOwn(HTML_ENTITIES, code) ? HTML_ENTITIES[code] : match;+ });+};++// The tags that mean anything here. `div` joins the block set because Matrix+// bodies wrap lines in one; anything absent from both sets keeps its text and+// loses its markup.+const BLOCK_TAGS = new Set(['p', 'div', 'blockquote']);+const INLINE_MARKS = { strong: 'bold', b: 'bold', em: 'italic', i: 'italic' };+// The full tag-name surface the parser dispatches on: BLOCK_TAGS, INLINE_MARKS,+// plus the two handled by name below (`br`, `a`). Exported so a test can pin+// the module docblock's allowlist sentence to this set instead of the two+// drifting apart again (audit cluster 10, finding F10).+export const ALL_ALLOWED_TAGS = new Set(['br', 'a', ...BLOCK_TAGS, ...Object.keys(INLINE_MARKS)]);+const HTML_TAG_RE = /<\/?(p|div|br|blockquote|strong|b|em|i|a)(\s[^>]*)?\/?>/i;+// A tag name must follow `<` immediately, and an attribute run may not contain+// another `<` — otherwise `a < b and <p>x</p>` parses as one enormous `<b …>`+// tag and turns the whole message bold.+const TOKEN_RE = /<\/?([a-zA-Z][a-zA-Z0-9]*)((?:"[^"]*"|'[^']*'|[^>"'<])*)\/?>/g;+const HREF_RE = /\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i;++/** Whether a body carries any of the tags this module understands. */+export const looksLikeHtmlBody = (body) => typeof body === 'string' && HTML_TAG_RE.test(body);++const emptyBlock = (type) => ({ type, spans: [] });++function pushText(block, text, marks) {+ if (!text) return;+ const last = block.spans[block.spans.length - 1];+ // Merge into the previous span when the marks match, so `<b>a</b><b>b</b>`+ // is one span rather than two adjacent identical ones.+ if (last && last.bold === marks.bold && last.italic === marks.italic && last.href === marks.href) {+ last.text += text;+ return;+ }+ block.spans.push({ text, bold: marks.bold, italic: marks.italic, href: marks.href });+}++const blockHasText = (block) => block.spans.some((span) => span.text.trim() !== '');++/**+ * Parse the allowlisted HTML subset into blocks of marked spans.+ *+ * @param {string} body+ * @returns {Array<{type: 'paragraph'|'quote', spans: Array<{text: string, bold: boolean, italic: boolean, href: string|null}>}>|null}+ * `null` when the body carries none of the allowlisted tags — the caller then+ * keeps its existing plain-text path.+ */+export function parseMessageBody(body) {+ if (!looksLikeHtmlBody(body)) return null;++ const blocks = [];+ let current = emptyBlock('paragraph');+ let bold = 0;+ let italic = 0;+ let quote = 0;+ const hrefStack = [];++ const marks = () => ({+ bold: bold > 0,+ italic: italic > 0,+ href: hrefStack.length > 0 ? hrefStack[hrefStack.length - 1] : null,+ });++ const flush = () => {+ if (blockHasText(current)) blocks.push(current);+ current = emptyBlock(quote > 0 ? 'quote' : 'paragraph');+ };++ let cursor = 0;+ TOKEN_RE.lastIndex = 0;+ let match = TOKEN_RE.exec(body);+ while (match !== null) {+ pushText(current, decodeHtmlEntities(body.slice(cursor, match.index)), marks());+ cursor = match.index + match[0].length;++ const tag = match[1].toLowerCase();+ const closing = match[0][1] === '/';+ const attrs = match[2] || '';++ if (tag === 'br') {+ // A newline in the text, not a block boundary: the renderer keeps+ // `whitespace-pre-wrap`, so one `<br>` is one line break inside the+ // paragraph it appeared in.+ pushText(current, '\n', marks());+ } else if (BLOCK_TAGS.has(tag)) {+ if (tag === 'blockquote') quote += closing ? -1 : 1;+ if (quote < 0) quote = 0;+ flush();+ } else if (Object.hasOwn(INLINE_MARKS, tag)) {+ const mark = INLINE_MARKS[tag];+ if (mark === 'bold') bold = closing ? Math.max(0, bold - 1) : bold + 1;+ else italic = closing ? Math.max(0, italic - 1) : italic + 1;+ } else if (tag === 'a') {+ if (closing) hrefStack.pop();+ else {+ const href = HREF_RE.exec(attrs);+ const value = decodeHtmlEntities((href?.[1] ?? href?.[2] ?? href?.[3] ?? '').trim());+ // http(s) only — the same rule `utils/urlNormalize.js` `isHttpUrl`+ // states, so a `javascript:` or `data:` href becomes plain text rather+ // than a clickable link.+ hrefStack.push(isHttpUrl(value) ? value : null);+ }+ }+ // Any other tag: dropped, its text already kept.++ match = TOKEN_RE.exec(body);+ }+ pushText(current, decodeHtmlEntities(body.slice(cursor)), marks());+ flush();++ // An HTML body with no text at all (`<p></p>`) is an empty message, not a+ // broken one — the caller renders the same empty bubble it would for `''`.+ return blocks;+}++/**+ * The rail preview: one line, tags gone, entities decoded. Line breaks and+ * block boundaries collapse to single spaces because the row truncates to one+ * line; a quoted block keeps a `>` so a reply preview still reads as a reply.+ */+export function messagePreviewText(body) {+ const blocks = parseMessageBody(body);+ if (blocks === null) return decodeHtmlEntities(body);+ return blocks+ .map((block) => {+ const text = block.spans.map((span) => span.text).join('').replace(/\s+/g, ' ').trim();+ return block.type === 'quote' && text ? `> ${text}` : text;+ })+ .filter(Boolean)+ .join(' ');+}diff --git a/client/src/lib/beeperMessageBody.test.js b/client/src/lib/beeperMessageBody.test.jsnew file mode 100644index 0000000000..abebea6ec9--- /dev/null+++ b/client/src/lib/beeperMessageBody.test.js@@ -0,0 +1,173 @@+import { readFileSync } from 'fs';+import { dirname, join } from 'path';+import { fileURLToPath } from 'url';+import { describe, expect, it } from 'vitest';+import {+ ALL_ALLOWED_TAGS, decodeHtmlEntities, messagePreviewText, parseMessageBody,+} from './beeperMessageBody';++const MODULE_FILE = join(dirname(fileURLToPath(import.meta.url)), 'beeperMessageBody.js');++/**+ * #35 real-browser pass (#59): a message body containing an ampersand rendered+ * as the five-character HTML entity `&` in the thread bubble. Beeper+ * Desktop delivers entity-encoded text for some bridged networks; PortOS itself+ * never escapes on the way in (`beeperSync.js` `normalizeMessageRow` passes+ * `message.text` through unchanged), so decoding belongs on the way out to the+ * DOM — as a plain text node, never `dangerouslySetInnerHTML`.+ */+describe('decodeHtmlEntities', () => {+ it('decodes the five predefined named entities', () => {+ expect(decodeHtmlEntities('&')).toBe('&');+ expect(decodeHtmlEntities('<')).toBe('<');+ expect(decodeHtmlEntities('>')).toBe('>');+ expect(decodeHtmlEntities('"')).toBe('"');+ expect(decodeHtmlEntities(''')).toBe("'");+ });++ it('decodes a realistic sentence with an ampersand', () => {+ expect(decodeHtmlEntities('salt & pepper')).toBe('salt & pepper');+ });++ it('decodes to a non-breaking space, the one entity beyond the server five', () => {+ expect(decodeHtmlEntities('one two')).toBe('one\u00a0two');+ });++ it('leaves a plain string with no entities untouched', () => {+ expect(decodeHtmlEntities('no entities here')).toBe('no entities here');+ });++ it('is double-decode-safe: &lt; decodes to <, never <', () => {+ expect(decodeHtmlEntities('&lt;')).toBe('<');+ });++ it('leaves an unknown named entity and an out-of-range numeric ref untouched', () => {+ expect(decodeHtmlEntities('&zzz;')).toBe('&zzz;');+ expect(decodeHtmlEntities('�')).toBe('�');+ });++ it('does not resolve inherited Object.prototype properties as entities', () => {+ // Untrusted remote chat text can contain literally anything. A lookup that+ // walks the prototype chain renders `&constructor;` as a stringified+ // built-in instead of leaving it alone.+ expect(decodeHtmlEntities('&constructor;')).toBe('&constructor;');+ expect(decodeHtmlEntities('&toString;')).toBe('&toString;');+ expect(decodeHtmlEntities('&hasOwnProperty;')).toBe('&hasOwnProperty;');+ });++ it('passes through non-string and empty input unchanged', () => {+ expect(decodeHtmlEntities(undefined)).toBe(undefined);+ expect(decodeHtmlEntities(null)).toBe(null);+ expect(decodeHtmlEntities('')).toBe('');+ });+});++/**+ * The final live pass: 26% of message bodies on a real install are HTML+ * (Discord and Matrix), and the mirror stores what the source sent — so the+ * thread and the rail preview showed the tags literally.+ */+describe('parseMessageBody', () => {+ const textOf = (blocks) => blocks.map((b) => b.spans.map((s) => s.text).join('')).join('\n');++ it('answers null for a plain body, so the caller keeps its text-node path', () => {+ expect(parseMessageBody('just a message')).toBeNull();+ expect(parseMessageBody('salt & pepper')).toBeNull();+ // A comparison and an emoticon are not markup.+ expect(parseMessageBody('5 < 6 and <3')).toBeNull();+ expect(parseMessageBody('')).toBeNull();+ expect(parseMessageBody(null)).toBeNull();+ });++ it('splits paragraphs into blocks and keeps <br> as a line break inside one', () => {+ expect(textOf(parseMessageBody('<p>first</p><p>second<br>third</p>')))+ .toBe('first\nsecond\nthird');+ });++ it('marks bold and italic spans without losing the surrounding text', () => {+ const [block] = parseMessageBody('<p>plain <strong>bold</strong> and <em>italic</em></p>');+ expect(block.spans).toEqual([+ { text: 'plain ', bold: false, italic: false, href: null },+ { text: 'bold', bold: true, italic: false, href: null },+ { text: ' and ', bold: false, italic: false, href: null },+ { text: 'italic', bold: false, italic: true, href: null },+ ]);+ });++ it('keeps an http(s) link and drops a scheme that is not one', () => {+ const [ok] = parseMessageBody('<p>see <a href="https://example.com/x">this</a></p>');+ expect(ok.spans.find((span) => span.text === 'this').href).toBe('https://example.com/x');++ // A `javascript:` href becomes plain text rather than a clickable link.+ const [bad] = parseMessageBody('<p><a href="javascript:alert(1)">click</a></p>');+ expect(bad.spans).toEqual([{ text: 'click', bold: false, italic: false, href: null }]);+ });++ it('renders a blockquote as its own quote block', () => {+ const blocks = parseMessageBody('<blockquote>quoted line</blockquote><p>reply</p>');+ expect(blocks.map((block) => block.type)).toEqual(['quote', 'paragraph']);+ expect(textOf(blocks)).toBe('quoted line\nreply');+ });++ it('drops a tag outside the allowlist but keeps its text', () => {+ // No allowlisted tag can execute, load or style anything, because nothing+ // here is ever handed to `dangerouslySetInnerHTML` — an unknown tag simply+ // contributes its text.+ expect(textOf(parseMessageBody('<p>before<script>alert(1)</script>after</p>')))+ .toBe('beforealert(1)after');+ expect(textOf(parseMessageBody('<p>an <img src="x" onerror="alert(1)"> image</p>')))+ .toBe('an image');+ });++ it('decodes entities inside an HTML body, and only after the tags are split off', () => {+ // `<b>` is text the sender typed, not a tag — it must survive as text.+ expect(textOf(parseMessageBody('<p>salt & pepper <b></p>')))+ .toBe('salt & pepper <b>');+ });++ it('survives unbalanced markup rather than swallowing the rest of the message', () => {+ expect(textOf(parseMessageBody('<p>open <strong>bold</p><p>next</p>')))+ .toBe('open bold\nnext');+ expect(textOf(parseMessageBody('</strong></blockquote><p>still here</p>')))+ .toBe('still here');+ });++ it('returns no blocks for an HTML body with no text at all', () => {+ expect(parseMessageBody('<p></p>')).toEqual([]);+ });+});++/**+ * Pins the module docblock's allowlist sentence to the tag set the parser+ * actually dispatches on, so the two cannot drift apart again the way they+ * did when `div` joined BLOCK_TAGS without the sentence naming it (audit+ * cluster 10, finding F10).+ */+describe('docblock allowlist', () => {+ it('names exactly the tags the parser treats as meaningful', () => {+ const source = readFileSync(MODULE_FILE, 'utf8');+ const sentence = source.match(/The allowlist is exactly what was observed:([^.]*)\./);+ expect(sentence).not.toBeNull();+ const namedTags = new Set(+ [...sentence[1].matchAll(/`([^`]+)`/g)]+ .flatMap((match) => match[1].split('/'))+ .map((tag) => tag.replace(/\[.*\]$/, '')),+ );+ expect(namedTags).toEqual(ALL_ALLOWED_TAGS);+ });+});++describe('messagePreviewText', () => {+ it('flattens an HTML body to one line for the rail row', () => {+ expect(messagePreviewText('<p>first</p><p>second<br>third</p>')).toBe('first second third');+ });++ it('keeps a quote marker so a reply preview still reads as a reply', () => {+ expect(messagePreviewText('<blockquote>them</blockquote><p>me</p>')).toBe('> them me');+ });++ it('leaves a plain body to the entity decoder alone', () => {+ expect(messagePreviewText('salt & pepper')).toBe('salt & pepper');+ expect(messagePreviewText('')).toBe('');+ });+});diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 2c8490a527..97122a919b 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -23,6 +23,7 @@ export * from './universeStylePreset.js';// === Pipeline / image-gen defaults ===export * from './autopilotMilestones.js';export * from './beatColors.js';+export * from './beeperMessageBody.js';export * from './beatGrid.js';export * from './bibleLimits.js';export * from './characterEvolution.js';diff --git a/client/src/pages/Messages.jsx b/client/src/pages/Messages.jsxindex ebfcdc1967..f5654553ed 100644--- a/client/src/pages/Messages.jsx+++ b/client/src/pages/Messages.jsx@@ -1,11 +1,13 @@import { useNavigate, useParams } from 'react-router';-import { Mail, RefreshCw, Settings, MessageSquare, Users } from 'lucide-react';+import { Mail, RefreshCw, Settings, MessageSquare, MessageCircle, Users } from 'lucide-react';import { useState, useEffect, useCallback } from 'react';import * as api from '../services/api';import PageSkeleton from '../components/ui/PageSkeleton';import PageHeader from '../components/PageHeader';import TabPills from '../components/ui/TabPills';import { useValidTab } from '../hooks/useValidTab';+import { useInstanceFeatures } from '../hooks/useInstanceFeatures.js';+import { filterNavByFeatures } from '../lib/navFeatures.js';import InboxTab from '../components/messages/InboxTab';import ConfigTab from '../components/messages/ConfigTab';@@ -13,6 +15,7 @@ import DraftsTab from '../components/messages/DraftsTab';import SyncTab from '../components/messages/SyncTab';import IMessageTab from '../components/messages/IMessageTab';import SignalTab from '../components/messages/SignalTab';+import BeeperTab from '../components/messages/BeeperTab';import ContactsTab from '../components/messages/ContactsTab';import { getPageNavTabs } from '../../../server/lib/navManifest.js';import { buildPageNavTabs } from '../lib/pageNavTabs.js';@@ -21,12 +24,19 @@ import { buildPageNavTabs } from '../lib/pageNavTabs.js';// id/label/order — this page owns how each tab looks and behaves.// `fullBleed: true` — tab owns internal scroll/height; Messages skips padded overflow wrapper.// `needsAccounts: true` — tab renders the account list, so it waits for that fetch.+// `recordParam: true` — tab uses the shared `/messages/:tab/:chatKey` second+// segment to carry ITS open record in the URL (iMessage a chat key, Beeper a+// conversation id). Declared here rather than as a hardcoded tab name below, so+// a third tab that deep-links a record does not have to be remembered twice.+// `feature` is NOT declared here: it rides through from the manifest entry via+// `getPageNavTabs`, so the pill and the sidebar gate on one field.// Throws at import time if the manifest and this map drift.const TAB_PRESENTATION = {inbox: { icon: Mail, needsAccounts: true },drafts: { icon: Mail, needsAccounts: true },- imessage: { icon: MessageSquare, fullBleed: true },+ imessage: { icon: MessageSquare, fullBleed: true, recordParam: true },signal: { icon: MessageSquare },+ beeper: { icon: MessageCircle, fullBleed: true, recordParam: true },contacts: { icon: Users },sync: { icon: RefreshCw, needsAccounts: true },config: { icon: Settings, needsAccounts: true },@@ -35,6 +45,7 @@ const TAB_PRESENTATION = {export const TABS = buildPageNavTabs(getPageNavTabs('messages'), TAB_PRESENTATION, 'Messages');const FULL_BLEED_TAB_IDS = new Set(TABS.filter((t) => t.fullBleed).map((t) => t.id));+const RECORD_PARAM_TAB_IDS = new Set(TABS.filter((t) => t.recordParam).map((t) => t.id));// iMessage and Contacts read no account data, so gating them on the accounts// fetch would only serialize their own requests behind an unrelated one and@@ -47,6 +58,11 @@ export default function Messages() {const { chatKey } = useParams();const activeTab = useValidTab(TABS, 'inbox');const fullBleed = FULL_BLEED_TAB_IDS.has(activeTab);+ // Gate the Beeper pill on the instance feature the same way the sidebar does+ // (#30): the route stays live for a direct link/bookmark/voice nav, but the+ // tab strip itself must not offer a way to navigate to a disabled feature.+ const { isFeatureEnabled } = useInstanceFeatures();+ const visibleTabs = filterNavByFeatures(TABS, isFeatureEnabled);// `null` = the account list never loaded (request failed) — deliberately distinct// from `[]`, which means "loaded, and there genuinely are no accounts". The inbox// empty state branches on that difference to avoid telling a user to add an@@ -74,10 +90,11 @@ export default function Messages() {fetchAccounts();}, [fetchAccounts]);- // Deep-link cleanup: only the imessage tab uses :chatKey. Drop a stale second- // segment if the user lands on e.g. /messages/inbox/<something>.+ // Deep-link cleanup: only the tabs that declare `recordParam` use the shared+ // :chatKey segment. Drop a stale second segment if the user lands on e.g.+ // /messages/inbox/<something>.useEffect(() => {- if (chatKey && activeTab !== 'imessage') {+ if (chatKey && !RECORD_PARAM_TAB_IDS.has(activeTab)) {navigate(`/messages/${activeTab}`, { replace: true });}}, [chatKey, activeTab, navigate]);@@ -100,6 +117,8 @@ export default function Messages() {return <IMessageTab />;case 'signal':return <SignalTab />;+ case 'beeper':+ return <BeeperTab />;case 'contacts':return <ContactsTab />;default:@@ -118,7 +137,7 @@ export default function Messages() {bodyClassName="p-4"titleWidthClass="w-36"showSubtitle- tabs={TABS.length}+ tabs={visibleTabs.length}cards={3}sidebar={false}/>@@ -131,14 +150,23 @@ export default function Messages() {icon={Mail}title="Messages"subtitle="Unified email and messaging management"- actions={loading ? null : (+ // #35 real-browser pass: this counts the email-style provider accounts+ // (Gmail/Outlook/Teams — `api.getMessageAccounts()`) that Inbox/Drafts/+ // Sync/Config act on. It is unrelated to Beeper's own account roster+ // (`beeper_accounts`, shown inside its own settings drawer) or to any+ // other bridge tab's accounts, so it read "0 accounts" while the Beeper+ // mirror held nine — correct for what it measures, misleading shown on+ // a tab it says nothing about. Scope it to the tabs that actually use+ // this fetch, same `ACCOUNT_TAB_IDS` gate the loading skeleton already+ // keys off, rather than teaching it a second "accounts" meaning.+ actions={loading || !ACCOUNT_TAB_IDS.has(activeTab) ? null : (<span className="text-sm text-gray-500">{accounts === null ? 'Accounts unavailable' : `${accounts.length} accounts`}</span>)}/>- <TabPills tabs={TABS} activeTab={activeTab} onChange={handleTabChange} ariaLabel="Messages sections" />+ <TabPills tabs={visibleTabs} activeTab={activeTab} onChange={handleTabChange} ariaLabel="Messages sections" /><div className={`flex-1 min-h-0 ${fullBleed ? 'overflow-hidden' : 'overflow-auto p-4'}`}>{renderTabContent()}diff --git a/client/src/pages/Messages.test.jsx b/client/src/pages/Messages.test.jsxindex c5052e1c3c..977549308f 100644--- a/client/src/pages/Messages.test.jsx+++ b/client/src/pages/Messages.test.jsx@@ -1,16 +1,173 @@-import { describe, it } from 'vitest';-import { TABS } from './Messages';+/**+ * Messages page — Beeper tab visibility (#30, real-browser pass) and the+ * manifest ↔ presentation sync guard (#6365).+ *+ * TABS in Messages.jsx is now derived from the nav manifest's+ * `tabGroup: 'messages'`, so the tab-strip render must filter it through the+ * same instance-feature hook the sidebar uses (`useInstanceFeatures` ++ * `filterNavByFeatures`) or the Beeper pill shows — and is clickable — even+ * when the instance feature is off. The `feature` field rides through from the+ * manifest entry via `getPageNavTabs`, so the pill and the sidebar gate on one+ * field rather than two.+ */++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { render, screen } from '@testing-library/react';+import { MemoryRouter, Route, Routes } from 'react-router';import { expectPageNavTabs } from '../test/pageNavTabAssertions.js';+vi.mock('../components/messages/InboxTab', () => ({ default: () => <div>inbox panel</div> }));+vi.mock('../components/messages/ConfigTab', () => ({ default: () => <div>config panel</div> }));+vi.mock('../components/messages/DraftsTab', () => ({ default: () => <div>drafts panel</div> }));+vi.mock('../components/messages/SyncTab', () => ({ default: () => <div>sync panel</div> }));+vi.mock('../components/messages/IMessageTab', () => ({ default: () => <div>imessage panel</div> }));+vi.mock('../components/messages/SignalTab', () => ({ default: () => <div>signal panel</div> }));+vi.mock('../components/messages/BeeperTab', () => ({ default: () => <div>beeper panel</div> }));+vi.mock('../components/messages/ContactsTab', () => ({ default: () => <div>contacts panel</div> }));++const featureMock = vi.hoisted(() => ({ features: [{ id: 'beeper', label: 'Beeper', enabled: true }] }));++vi.mock('../services/api', () => ({+ getMessageAccounts: vi.fn(() => Promise.resolve([])),+ getInstanceFeatures: vi.fn(() => Promise.resolve({ features: featureMock.features })),+}));++import { __resetInstanceFeatureCache } from '../hooks/useInstanceFeatures.js';+import Messages, { TABS } from './Messages';++beforeEach(() => {+ __resetInstanceFeatureCache();+ featureMock.features = [{ id: 'beeper', label: 'Beeper', enabled: true }];+});++afterEach(() => {+ vi.clearAllMocks();+});++const renderAt = (path) => render(+ <MemoryRouter initialEntries={[path]}>+ <Routes>+ <Route path="/messages/:tab" element={<Messages />} />+ <Route path="/messages/:tab/:chatKey" element={<Messages />} />+ </Routes>+ </MemoryRouter>,+);++describe('Messages — Beeper tab gating', () => {+ it('shows the Beeper pill in the tab strip when the beeper feature is on', async () => {+ renderAt('/messages/inbox');++ const beeper = await screen.findByRole('tab', { name: /Beeper/i });+ expect(beeper).toBeTruthy();+ });++ it('hides the Beeper pill from the tab strip when the beeper feature is off', async () => {+ featureMock.features = [{ id: 'beeper', label: 'Beeper', enabled: false }];++ renderAt('/messages/inbox');++ // Other Comms pills stay put — only Beeper drops.+ expect(await screen.findByRole('tab', { name: /^Signal$/i })).toBeTruthy();+ expect(screen.queryByRole('tab', { name: /Beeper/i })).toBeNull();+ });++ it('still renders the Beeper panel for a direct/bookmarked link even with the feature off', async () => {+ featureMock.features = [{ id: 'beeper', label: 'Beeper', enabled: false }];++ renderAt('/messages/beeper');++ expect(await screen.findByText('beeper panel')).toBeTruthy();+ });+});++describe('Messages — Comms group gating (iMessage, Signal)', () => {+ // F3: iMessage and Signal joined the Comms group's nav-manifest gate (#40)+ // but the Messages tab strip only tagged the Beeper row with `feature`, so+ // the pills stayed visible and clickable with the group off — the exact+ // inconsistency the Beeper pill's own comment says must not exist.+ it('hides the iMessage and Signal pills from the tab strip when the comms group is off', async () => {+ featureMock.features = [+ { id: 'imessage', label: 'iMessage', enabled: false },+ { id: 'signal', label: 'Signal', enabled: false },+ { id: 'beeper', label: 'Beeper', enabled: false },+ ];++ renderAt('/messages/inbox');++ // A non-comms pill stays put as the control.+ expect(await screen.findByRole('tab', { name: 'Inbox' })).toBeTruthy();+ expect(screen.queryByRole('tab', { name: /iMessage/i })).toBeNull();+ expect(screen.queryByRole('tab', { name: /^Signal$/i })).toBeNull();+ });++ it('shows only the Signal pill when iMessage is overridden off and Signal is on', async () => {+ featureMock.features = [+ { id: 'imessage', label: 'iMessage', enabled: false },+ { id: 'signal', label: 'Signal', enabled: true },+ ];++ renderAt('/messages/inbox');++ expect(await screen.findByRole('tab', { name: /^Signal$/i })).toBeTruthy();+ expect(screen.queryByRole('tab', { name: /iMessage/i })).toBeNull();+ });++ // Parity with Beeper (#30/#40): the feature gates the tab strip and the+ // sidebar, never the <Route> itself, so a direct/bookmarked visit still+ // renders the tab body while the feature is off — see the equivalent Beeper+ // case in 'Messages — Beeper tab gating' above. iMessage matches that+ // existing behavior rather than gaining a new, stricter route-level gate.+ it('still renders the iMessage panel for a direct/bookmarked link even with the feature off', async () => {+ featureMock.features = [{ id: 'imessage', label: 'iMessage', enabled: false }];++ renderAt('/messages/imessage');++ expect(await screen.findByText('imessage panel')).toBeTruthy();+ });+});++describe('Messages — header account count scope (#30/#35)', () => {+ // The header's "N accounts" reads the generic email-provider account list+ // (Gmail/Outlook/Teams), not Beeper's own roster — it must not render on a+ // tab that has nothing to do with that list, or it reads as a (wrong) Beeper+ // account count. #35 real-browser pass: it showed "0 accounts" on the Beeper+ // tab while the Beeper mirror held nine.+ it('does not show the provider-account count on the Beeper tab', async () => {+ renderAt('/messages/beeper');++ await screen.findByText('beeper panel');+ expect(screen.queryByText(/accounts?$/i)).toBeNull();+ });++ it('still shows the provider-account count on tabs that use it (Inbox)', async () => {+ renderAt('/messages/inbox');++ await screen.findByText('inbox panel');+ expect(await screen.findByText('0 accounts')).toBeTruthy();+ });+});+// Messages derives its tab bar from the nav manifest's `tabGroup: 'messages'`// (#6365) — this pins that TABS stays in sync (id, label, declaration order)// and that every manifest tab has a presentation entry (icon, plus the-// `fullBleed`/`needsAccounts` flags) in Messages.jsx, which would otherwise-// only surface as a thrown import-time error.+// `fullBleed`/`needsAccounts`/`recordParam` flags) in Messages.jsx, which would+// otherwise only surface as a thrown import-time error. Beeper (#30) sits+// between Signal and Contacts, the position its manifest row declares.describe('Messages TABS ↔ nav manifest', () => {it('renders the messages tabGroup in page order with a presentation entry each', () => {expectPageNavTabs(TABS, [- 'inbox:Inbox', 'drafts:Drafts', 'imessage:iMessage', 'signal:Signal', 'contacts:Contacts', 'sync:Sync', 'config:Config',+ 'inbox:Inbox', 'drafts:Drafts', 'imessage:iMessage', 'signal:Signal', 'beeper:Beeper', 'contacts:Contacts', 'sync:Sync', 'config:Config',]);});++ // The gating tests above depend on the manifest, not a local array, carrying+ // `feature` — pin that so a manifest row losing the field fails here rather+ // than silently un-gating a pill.+ it('carries the comms feature ids through from the manifest', () => {+ const byId = Object.fromEntries(TABS.map((tab) => [tab.id, tab.feature]));+ expect(byId.imessage).toBe('imessage');+ expect(byId.signal).toBe('signal');+ expect(byId.beeper).toBe('beeper');+ expect(byId.inbox).toBeUndefined();+ });});diff --git a/client/src/pages/Tribe.jsx b/client/src/pages/Tribe.jsxindex 3606510b52..657ce8ee79 100644--- a/client/src/pages/Tribe.jsx+++ b/client/src/pages/Tribe.jsx@@ -1,5 +1,5 @@import { useEffect, useMemo, useRef, useState } from 'react';-import { useSearchParams } from 'react-router';+import { Link, useSearchParams } from 'react-router';import {AlertTriangle,Calendar,@@ -163,7 +163,7 @@ function RingMeter({ ring, contacts, active, onClick }) {);}-function ContactCard({ contact, active, onSelect, onLogTouch }) {+function ContactCard({ contact, active, onSelect, onLogTouch, cardRef }) {const ring = ringFor(contact.ring);const energy = energyFor(contact.energy);const status = contactStatus(contact);@@ -171,6 +171,7 @@ function ContactCard({ contact, active, onSelect, onLogTouch }) {return (<article+ ref={cardRef}className={`w-full text-left border rounded p-4 transition-colors bg-port-card ${active ? 'border-port-accent/70 ring-1 ring-port-accent/30' : 'border-port-border hover:border-port-accent/40'}`}@@ -564,6 +565,95 @@ function TouchpointsPanel({ personId }) {);}+// One "Linked on Beeper" chip per identity claim (#99). The network shown is+// the CONVERSATION's network for a beeper-user claim (the claim's own+// `network` column is a Beeper ACCOUNT id, not a network name — see #96), the+// claim's own `network` for a handle claim, and the literal 'phone' for a+// phone claim (phones are network-less by design). The label is the+// participant's display name for a beeper-user claim (its `handle` is an+// opaque source_user_id, not human-readable) and the durable handle itself+// for a handle/phone claim. Every conversation the identity appears in gets+// its own thread link, ordered most-recent-first by the server.+function BeeperIdentityChip({ identity, onUnlink }) {+ const conversations = identity.conversations || [];+ const isBeeperUser = identity.kind === 'beeper-user';+ const network = identity.kind === 'phone'+ ? 'phone'+ : isBeeperUser+ ? (conversations[0]?.network || identity.network || 'beeper')+ : (identity.network || 'beeper');+ const label = isBeeperUser ? (conversations[0]?.displayName || identity.handle) : identity.handle;++ return (+ <div className="flex flex-wrap items-center gap-1.5 rounded-full border border-port-border bg-port-bg px-3 py-1.5 text-xs text-gray-300">+ <span className="font-medium text-white">{network}</span>+ <span className="text-gray-600">·</span>+ <span className="max-w-[10rem] truncate" title={label}>{label}</span>+ {conversations.map((conversation) => (+ <Link+ key={conversation.conversationId}+ to={`/messages/beeper/${conversation.conversationId}`}+ title={conversation.title ? `Open "${conversation.title}"` : 'Open Beeper thread'}+ aria-label={conversation.title ? `Open "${conversation.title}"` : 'Open Beeper thread'}+ className="text-port-accent hover:underline"+ >+ <MessageCircle size={13} aria-hidden="true" />+ </Link>+ ))}+ <button+ type="button"+ onClick={onUnlink}+ title="Unlink"+ aria-label={`Unlink ${label}`}+ className="text-gray-500 hover:text-rose-300"+ >+ <X size={12} aria-hidden="true" />+ </button>+ </div>+ );+}++// The Tribe person form's "Linked on Beeper" block (#99). The roster row from+// `getTribePeople` never carries `identities` — that join only runs on the+// single-person read (`GET /tribe/people/:id`) — so this fetches the full+// person on mount/personId change, the same pattern `MemoryLinksPanel` and+// `TouchpointsPanel` already use. Renders nothing when the person has no+// Beeper claims (no empty heading).+function BeeperIdentitiesPanel({ personId }) {+ const [identities, setIdentities] = useState([]);++ useEffect(() => {+ if (!personId) { setIdentities([]); return; }+ let cancelled = false;+ api.getTribePerson(personId, { silent: true })+ .then((person) => { if (!cancelled) setIdentities(person?.identities || []); })+ .catch(() => { if (!cancelled) setIdentities([]); });+ return () => { cancelled = true; };+ }, [personId]);++ const unlink = async (identityId) => {+ const result = await api.unlinkBeeperIdentity(identityId, { silent: true }).catch((err) => {+ toast.error(err.message || 'Failed to unlink Beeper identity');+ return null;+ });+ if (!result?.success) return;+ setIdentities((current) => current.filter((identity) => identity.id !== identityId));+ };++ if (identities.length === 0) return null;++ return (+ <section className="mt-4 border border-port-border bg-port-card rounded p-4">+ <h2 className="text-sm font-semibold text-white">Linked on Beeper</h2>+ <div className="mt-3 flex flex-wrap gap-2">+ {identities.map((identity) => (+ <BeeperIdentityChip key={identity.id} identity={identity} onUnlink={() => unlink(identity.id)} />+ ))}+ </div>+ </section>+ );+}+function EmptyState({ onNew }) {return (<div className="flex min-h-[280px] flex-col items-center justify-center rounded border border-dashed border-port-border bg-port-card/60 p-8 text-center">@@ -1061,6 +1151,45 @@ export default function Tribe() {cadenceDays: contact.cadenceDays || ringFor(contact.ring).cadenceDays,});+ // Deep link from Beeper's Tribe chip and linked-participant rows (#98 part+ // C): `?person=<id>` selects that Tribe person on the Circle tab, the exact+ // same path a click on their card takes (`selectContact`), and scrolls the+ // card into view — the `OutreachQueue`'s `?outreach=` handling above is the+ // sibling pattern this follows.+ //+ // `appliedPersonRef` fires this at most once per distinct `person` value —+ // never on every `contacts` refresh a `tribe:changed` broadcast triggers —+ // but still re-fires "on load AND when the param changes" per the spec,+ // since a change to `personParam` itself resets it. An id the roster does+ // not recognize (deleted, or someone else's stale bookmark) is marked+ // applied and otherwise ignored: no error toast, since nothing here is a+ // genuine fault to report.+ const personParam = searchParams.get('person');+ const appliedPersonRef = useRef(null);+ const pendingScrollPersonRef = useRef(null);+ const cardRefs = useRef({});++ useEffect(() => {+ if (!personParam) { appliedPersonRef.current = null; return; }+ if (appliedPersonRef.current === personParam || loading) return;+ const target = contacts.find((contact) => contact.id === personParam);+ appliedPersonRef.current = personParam;+ if (!target) return;+ selectContact(target);+ setActiveTab('circle');+ pendingScrollPersonRef.current = personParam;+ }, [personParam, contacts, loading]);++ useEffect(() => {+ if (!pendingScrollPersonRef.current || activeTab !== 'circle') return;+ const id = pendingScrollPersonRef.current;+ const frame = requestAnimationFrame(() => {+ cardRefs.current[id]?.scrollIntoView({ behavior: 'smooth', block: 'center' });+ pendingScrollPersonRef.current = null;+ });+ return () => cancelAnimationFrame(frame);+ }, [activeTab, filteredContacts]);+const saveDraft = async () => {// Send only the editable fields the schema accepts. The PUT route rejects a// body `id` (`z.never()`) — it comes from the URL — and `lastContact` must be@@ -1309,6 +1438,7 @@ export default function Tribe() {active={selectedId === contact.id}onSelect={() => selectContact(contact)}onLogTouch={() => logTouch(contact.id)}+ cardRef={(el) => { cardRefs.current[contact.id] = el; }}/>))}{filteredContacts.length === 0 && (@@ -1332,6 +1462,7 @@ export default function Tribe() {nameInputRef={nameInputRef}formRef={formRef}/>+ {draft.id && <BeeperIdentitiesPanel personId={draft.id} />}{draft.id && <MemoryLinksPanel personId={draft.id} />}{draft.id && <TouchpointsPanel personId={draft.id} />}</aside>diff --git a/client/src/pages/Tribe.test.jsx b/client/src/pages/Tribe.test.jsxindex e1ca41698e..f94872c66e 100644--- a/client/src/pages/Tribe.test.jsx+++ b/client/src/pages/Tribe.test.jsx@@ -1,6 +1,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { render, screen, waitFor, fireEvent } from '@testing-library/react';-import { MemoryRouter, useLocation } from 'react-router';+import { MemoryRouter, useLocation, useSearchParams } from 'react-router';vi.mock('../services/api', () => ({getTribePeople: vi.fn(() => Promise.resolve({ people: [] })),@@ -10,6 +10,17 @@ vi.mock('../services/api', () => ({// Non-blocking duplicate-identifier report (#5908); defaults to clean so// tests unrelated to it never see the banner.getTribeDuplicateIdentifiers: vi.fn(() => Promise.resolve({ emails: [], phones: [] })),+ // Single-person read (#99) — the "Linked on Beeper" block's data source;+ // defaults to no identities so tests unrelated to it never see the block.+ getTribePerson: vi.fn(() => Promise.resolve({ identities: [] })),+ unlinkBeeperIdentity: vi.fn(() => Promise.resolve({ success: true })),+ // Circle tab's aside mounts MemoryLinksPanel/TouchpointsPanel once a+ // person is selected (`draft.id` set) — the `?person=` deep-link tests and+ // the "Linked on Beeper" tests below both select a real person, so these+ // need real (empty) defaults too.+ getTribeMemoryLinks: vi.fn(() => Promise.resolve({ links: [] })),+ getMemories: vi.fn(() => Promise.resolve({ memories: [] })),+ getTribeTouchpoints: vi.fn(() => Promise.resolve({ touchpoints: [] })),}));vi.mock('../services/socket', () => ({@@ -168,6 +179,73 @@ describe('Tribe care filter', () => {});});+/**+ * #98 part C: Beeper's Tribe chip and its participants-panel "Linked ·+ * <name>" rows deep-link here via `?person=<id>`. On load (and whenever the+ * param changes) the page takes the exact path a click on the person's own+ * `ContactCard` takes (`selectContact`) — switch to Circle, populate the+ * form — and scrolls that card into view. An id nothing recognizes (a+ * deleted person, or someone else's stale bookmark) is silently ignored:+ * PortOS never toasts an error for it.+ */+describe('Tribe person deep link (#98 part C)', () => {+ beforeEach(() => {+ api.getTribePeople.mockClear();+ api.getTribePeople.mockResolvedValue({ people: PEOPLE });+ window.localStorage.clear();+ });++ it('selects the named person, switches to Circle, and opens the form on their record', async () => {+ renderAt('/tribe?person=p2');++ await waitFor(() => expect(screen.getByTestId('location').textContent).toContain('tab=circle'));+ expect(screen.getByLabelText('Name')).toHaveValue('Sample Neighbor');+ // Circle-only content — proves the tab actually switched, not just the draft.+ expect(screen.getByPlaceholderText('Search relationships')).toBeInTheDocument();+ expect(screen.getByRole('heading', { name: 'Relationship' })).toBeInTheDocument();+ });++ it('scrolls the matching card into view', async () => {+ const scrollSpy = vi.spyOn(Element.prototype, 'scrollIntoView').mockImplementation(() => {});+ renderAt('/tribe?person=p2');++ await waitFor(() => expect(scrollSpy).toHaveBeenCalled());+ scrollSpy.mockRestore();+ });++ it('re-applies when the person param changes to a different id, without remounting the page', async () => {+ // `MemoryRouter`'s `initialEntries` is read once at construction, so+ // exercising a real in-place param change needs an in-tree navigator+ // rather than a fresh `render`/`rerender` with different entries.+ function ChangePersonButton() {+ const [, setPersonParams] = useSearchParams();+ return (+ <button type="button" onClick={() => setPersonParams({ person: 'p2' })}>+ Switch to p2+ </button>+ );+ }+ render(+ <MemoryRouter initialEntries={['/tribe?person=p1']}>+ <Tribe />+ <ChangePersonButton />+ </MemoryRouter>,+ );++ await waitFor(() => expect(screen.getByLabelText('Name')).toHaveValue('Example Person'));+ fireEvent.click(screen.getByRole('button', { name: 'Switch to p2' }));+ await waitFor(() => expect(screen.getByLabelText('Name')).toHaveValue('Sample Neighbor'));+ });++ it('ignores an id the roster does not recognize, with no error toast and no tab switch', async () => {+ renderAt('/tribe?person=does-not-exist');++ await screen.findByRole('group', { name: 'Care filter' }); // stayed on the default Care Queue tab+ expect(screen.queryByPlaceholderText('Search relationships')).toBeNull();+ expect(screen.queryByRole('alert')).toBeNull();+ });+});+describe('Tribe shared-identifier banner (#5908)', () => {beforeEach(() => {api.getTribePeople.mockClear();@@ -207,3 +285,67 @@ describe('Tribe shared-identifier banner (#5908)', () => {expect(screen.queryByText(/shared contact info/i)).toBeNull();});});++describe('Tribe "Linked on Beeper" block (#99)', () => {+ beforeEach(() => {+ api.getTribePeople.mockClear();+ api.getTribePeople.mockResolvedValue({ people: PEOPLE });+ api.getTribePerson.mockReset();+ api.getTribePerson.mockResolvedValue({ identities: [] });+ api.unlinkBeeperIdentity.mockReset();+ api.unlinkBeeperIdentity.mockResolvedValue({ success: true });+ window.localStorage.clear();+ });++ it('renders nothing when the selected person has no Beeper identities', async () => {+ renderAt('/tribe?tab=circle');+ fireEvent.click(await screen.findByText('Example Person'));+ await waitFor(() => expect(api.getTribePerson).toHaveBeenCalledWith('p1', { silent: true }));+ expect(screen.queryByText('Linked on Beeper')).toBeNull();+ });++ it('renders a chip per identity with its network + handle and a thread link', async () => {+ api.getTribePerson.mockResolvedValue({+ identities: [+ {+ id: 'identity-1', personId: 'p1', kind: 'beeper-user', network: 'account-1', handle: 'user-1',+ source: 'user', linkedAt: '2026-06-01T00:00:00.000Z',+ conversations: [{ conversationId: 'conv-1', network: 'whatsapp', title: 'Example Thread', accountId: 'account-1', displayName: 'Example Contact' }],+ },+ {+ id: 'identity-2', personId: 'p1', kind: 'handle', network: 'discord', handle: 'ada',+ source: 'user', linkedAt: '2026-06-01T00:00:00.000Z', conversations: [],+ },+ ],+ });++ renderAt('/tribe?tab=circle');+ fireEvent.click(await screen.findByText('Example Person'));++ expect(await screen.findByText('Linked on Beeper')).toBeTruthy();+ expect(screen.getByText('whatsapp')).toBeTruthy();+ expect(screen.getByText('Example Contact')).toBeTruthy();+ expect(screen.getByText('discord')).toBeTruthy();+ expect(screen.getByText('ada')).toBeTruthy();+ const threadLink = screen.getByRole('link', { name: /Open "Example Thread"/ });+ expect(threadLink.getAttribute('href')).toBe('/messages/beeper/conv-1');+ });++ it('unlinks an identity and removes its chip', async () => {+ api.getTribePerson.mockResolvedValue({+ identities: [{+ id: 'identity-1', personId: 'p1', kind: 'handle', network: 'discord', handle: 'ada',+ source: 'user', linkedAt: '2026-06-01T00:00:00.000Z', conversations: [],+ }],+ });++ renderAt('/tribe?tab=circle');+ fireEvent.click(await screen.findByText('Example Person'));+ await screen.findByText('Linked on Beeper');++ fireEvent.click(screen.getByRole('button', { name: 'Unlink ada' }));++ await waitFor(() => expect(api.unlinkBeeperIdentity).toHaveBeenCalledWith('identity-1', { silent: true }));+ await waitFor(() => expect(screen.queryByText('Linked on Beeper')).toBeNull());+ });+});diff --git a/client/src/services/README.md b/client/src/services/README.mdindex a33a6da4d5..b794f48f7a 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -91,6 +91,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiX.js` | X account diagnostics, public post metrics, review-gated drafts, and manual browser handoffs. || `apiContacts.js` | macOS Contacts sync + identity resolve + Tribe enrich (#2415). || `apiSignal.js` | Signal Desktop ingestion status / setup-check / sync. |+| `apiBeeper.js` | Beeper Desktop bridge: status card and live connectivity check (#30), the connect flow (#31) — OAuth start, paste-a-token, disconnect — the mirrored chat surface (#35): conversations, thread pages, rail networks, archive/low-priority — the durable send outbox (#36): create an entry, send it (with the first-contact confirmation), list a conversation's entries, clear the runaway breaker; write paths never retry — and the attachment byte mirror (#37): `beeperAttachmentUrl` (a relative `/api/...` src, so an `<img loading="lazy">` IS the fetch-on-view), `fetchBeeperAttachment` ("fetch anyway"), `setBeeperAttachmentKeep`, the backfill census + run, and the per-conversation mirror purge. || `apiSpotify.js` | Spotify OAuth + listening-history and playlist-library sync. || `apiYoutube.js` | YouTube watch-history scrape, playlist/video library sync, and setup check. || `apiPersonalities.js` | Agent personality profiles. |diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 2c236ee724..9f8cc46366 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -31,6 +31,7 @@ export * from './apiStackerNews.js';export * from './apiX.js';export * from './apiContacts.js';export * from './apiSignal.js';+export * from './apiBeeper.js';export * from './apiSpotify.js';export * from './apiYoutube.js';export * from './apiCalendar.js';diff --git a/client/src/services/apiBeeper.js b/client/src/services/apiBeeper.jsnew file mode 100644index 0000000000..46ee4cf868--- /dev/null+++ b/client/src/services/apiBeeper.js@@ -0,0 +1,178 @@+import { API_BASE, request } from './apiCore.js';++// Beeper Desktop bridge — status card (#30). Read-only connection status+// (token-configured flag, never the token; tri-state reachability; the+// account roster mirrored from beeper_accounts) plus a live "Retry" check.+// Ingestion + connection settings (enabled/intervalMinutes/baseUrl/+// attachmentBudgetGb) go through the generic getSettings/updateSettings pair+// in apiSystem.js, same as iMessage/Signal — this file covers only what+// those don't.+export const getBeeperStatus = (options = {}) => request('/beeper/status', options);+export const checkBeeperConnection = (options = {}) => request('/beeper/status/check', { method: 'POST', ...options });++// The "Sync now" list-header action (#79). Runs one watermark-bounded sweep+// immediately rather than waiting out the configured interval; the server+// reports `skipped: true` instead of an error when a sweep is already in+// flight. The caller re-fetches the list and networks once this resolves —+// this call alone never refreshes anything the surface renders.+export const syncBeeperNow = (options = {}) => request('/beeper/sync', { method: 'POST', ...options });++// ---------------------------------------------------------------------------+// Chat surface (#35) — everything below reads the PortOS MIRROR, not Beeper.+// The sweep (#32) and the socket relay (#33) keep the mirror current, so the+// list stays correct with Beeper Desktop closed and a socket invalidation frame+// costs one local query rather than an upstream fan-out.+// ---------------------------------------------------------------------------++const queryString = (params) => {+ const qs = new URLSearchParams();+ for (const [key, value] of Object.entries(params)) {+ if (value === undefined || value === null || value === '') continue;+ qs.set(key, String(value));+ }+ const encoded = qs.toString();+ return encoded ? `?${encoded}` : '';+};++// `unreadOnly` / `archived` / `lowPriority` are omitted when undefined and sent+// as the literal "true"/"false" otherwise: the server reads an absent filter as+// "do not filter", which is a different query from `false`.+export const getBeeperConversations = ({+ network, unreadOnly, archived, lowPriority, limit, cursor,+} = {}, options = {}) =>+ request(`/beeper/conversations${queryString({ network, unreadOnly, archived, lowPriority, limit, cursor })}`, options);++export const getBeeperConversation = (conversationId, options = {}) =>+ request(`/beeper/conversations/${encodeURIComponent(conversationId)}`, options);++export const getBeeperMessages = (conversationId, { limit, cursor } = {}, options = {}) =>+ request(`/beeper/conversations/${encodeURIComponent(conversationId)}/messages${queryString({ limit, cursor })}`, options);++export const getBeeperNetworks = (options = {}) => request('/beeper/networks', options);++// The two rail controls #9 wired. Both are WRITES to Beeper: they never retry,+// and their thrown error carries `context.retryable === false` so no caller can+// invent one on an API with no idempotency key.+export const setBeeperConversationArchived = (conversationId, archived, options = {}) =>+ request(`/beeper/conversations/${encodeURIComponent(conversationId)}/archive`, {+ method: 'POST',+ body: JSON.stringify({ archived }),+ ...options,+ });++export const setBeeperConversationLowPriority = (conversationId, lowPriority, options = {}) =>+ request(`/beeper/conversations/${encodeURIComponent(conversationId)}/low-priority`, {+ method: 'POST',+ body: JSON.stringify({ lowPriority }),+ ...options,+ });++// The LOCAL "seen in PortOS" watermark (#83) — the opposite shape from the two+// above: it never reaches Beeper. No body: the server stamps `seen_at` from+// its own clock. Called when a thread is opened and, cheaply, again when a+// new message lands in the open thread.+export const markBeeperConversationSeen = (conversationId, options = {}) =>+ request(`/beeper/conversations/${encodeURIComponent(conversationId)}/seen`, {+ method: 'POST',+ ...options,+ });++// Connect flow (#31). PortOS runs OAuth itself (PKCE S256, dynamic client+// registration); `startBeeperOAuth` returns the authorization URL for the+// browser to open, and the redirect lands on the server callback, never here.+// Pasting a token is a first-class alternative — Beeper's own UI can mint a+// no-expiry token and the OAuth surface accepts no lifetime at all. None of+// these ever return a token value: the client only ever sees `tokenConfigured`,+// `tokenExpiresAt` and `tokenSource`.+//+// The browser sends its OWN origin, because the server cannot derive it: under+// the Vite dev proxy (`changeOrigin: true`, no `x-forwarded-*`) the request+// arrives carrying the API's origin on the API port, so the consent redirect+// went to a host the TLS certificate does not cover and the user landed on a+// certificate error. The server validates the value against the hosts this+// install answers on and falls back to the request origin when it does not+// recognize it.+export const startBeeperOAuth = (options = {}) => request('/beeper/oauth/start', {+ method: 'POST',+ body: JSON.stringify({ origin: window.location.origin }),+ ...options,+});+export const saveBeeperToken = (token, options = {}) => request('/beeper/token', { method: 'POST', body: JSON.stringify({ token }), ...options });+export const disconnectBeeper = (options = {}) => request('/beeper/token', { method: 'DELETE', ...options });++// ---------------------------------------------------------------------------+// Attachment byte mirror (#37)+// ---------------------------------------------------------------------------++/**+ * The `src` for one attachment's BYTES. A relative `/api/...` path, never an+ * absolute URL: PortOS is routinely reached over Tailscale from another+ * machine, and a hardcoded origin would point that browser at its own laptop.+ *+ * Requesting this URL is what triggers the mirror. The bytes are fetched from+ * Beeper on a miss and served from disk afterwards, so an `<img loading="lazy">`+ * pointed here IS the "download on first human view" rule — nothing else has to+ * decide when a view happened.+ */+export const beeperAttachmentUrl = (messageId, idx) =>+ `${API_BASE}/beeper/attachments/${encodeURIComponent(messageId)}/${encodeURIComponent(idx)}`;++// The over-cap placeholder's "fetch anyway", and the only path that retries an+// attachment Beeper previously refused. Returns the refreshed row, not bytes.+export const fetchBeeperAttachment = (messageId, idx, options = {}) =>+ request(`/beeper/attachments/${encodeURIComponent(messageId)}/${encodeURIComponent(idx)}/fetch`, {+ method: 'POST',+ ...options,+ });++// The per-attachment keep lock (the `useLockToggle` optimistic-PATCH shape):+// exempt this one from least-recently-viewed eviction.+export const setBeeperAttachmentKeep = (messageId, idx, keep, options = {}) =>+ request(`/beeper/attachments/${encodeURIComponent(messageId)}/${encodeURIComponent(idx)}`, {+ method: 'PATCH',+ body: JSON.stringify({ keep }),+ ...options,+ });++// The census the bulk-backfill consent modal must state before it runs, plus+// the budget/usage picture the settings card renders.+export const getBeeperAttachmentSummary = (options = {}) => request('/beeper/attachments/summary', options);++// The bulk backfill itself — only ever called after the consent modal.+export const backfillBeeperAttachments = (body = {}, options = {}) =>+ request('/beeper/attachments/backfill', { method: 'POST', body: JSON.stringify(body), ...options });++// Purge ONE conversation's mirror (messages, participants, attachment rows and+// the bytes). PortOS-local: Beeper still has the chat. The caller gates this+// behind a typed confirmation naming the conversation and the byte count.+export const purgeBeeperConversation = (conversationId, options = {}) =>+ request(`/beeper/conversations/${encodeURIComponent(conversationId)}`, { method: 'DELETE', ...options });++// Outbound outbox (#36, decided on #8). Two calls for the two-step send, plus+// the breaker reset — every one of them a WRITE, and none of them ever retried:+// Beeper has no idempotency key on send, so a client-side retry is a second+// real message to a real person. The server marks these `retryable: false` in+// the error envelope for the same reason; nothing here re-issues a request.+//+// `confirmFirstContact` is passed explicitly and only when the user has+// answered an inline confirmation. It is a gate, not a hint: the server refuses+// the first outbound message to a conversation without it.+export const listOutboxEntries = (conversationId, options = {}) => request(`/beeper/outbox?conversationId=${encodeURIComponent(conversationId)}`, options);+export const createOutboxEntry = (conversationId, body, options = {}) => request('/beeper/outbox', {+ method: 'POST',+ body: JSON.stringify({ conversationId, body }),+ ...options,+});+export const sendOutboxEntry = (id, { confirmFirstContact = false } = {}, options = {}) => request(`/beeper/outbox/${encodeURIComponent(id)}/send`, {+ method: 'POST',+ body: JSON.stringify({ confirmFirstContact }),+ ...options,+});+export const clearOutboxBreaker = (options = {}) => request('/beeper/outbox/breaker/clear', { method: 'POST', ...options });+// Discard a row the human declined to send — the first-contact confirmation's+// "Cancel" (#53). Only an `approved` row (nothing has POSTed to Beeper for it+// yet) is discardable.+export const discardOutboxEntry = (id, options = {}) => request(`/beeper/outbox/${encodeURIComponent(id)}`, {+ method: 'DELETE',+ ...options,+});diff --git a/client/src/services/apiTribe.js b/client/src/services/apiTribe.jsindex 75bec21ba8..cd9bff73db 100644--- a/client/src/services/apiTribe.js+++ b/client/src/services/apiTribe.js@@ -13,6 +13,12 @@ export const getTribePeople = (options = {}) => {export const getTribeDuplicateIdentifiers = (options = {}) =>request('/tribe/duplicate-identifiers', { silent: options.silent });+// Single-person read (#99) — the roster row from `getTribePeople` never carries+// `identities` (that join only runs on this single-person read), so the person+// form fetches this on select to render the "Linked on Beeper" block.+export const getTribePerson = (id, options = {}) =>+ request(`/tribe/people/${id}`, { silent: options.silent });+export const getTribeCareSummary = (options = {}) => {const params = new URLSearchParams();if (options.limit) params.set('limit', String(options.limit));@@ -73,3 +79,38 @@ export const generateTribeOutreachDraft = (seed, options = {}) =>body: JSON.stringify(seed),...options,});++// Beeper participant → Tribe person (#34), called from the inline action on a+// thread participant (#35). `linkBeeperParticipant` never creates a person;+// `createTribePersonFromBeeper` does both in one step. The server derives the+// identity's network from the participant's own conversation — it is+// deliberately not a client-supplied field.+export const linkBeeperParticipant = ({ conversationId, sourceUserId, personId }, options = {}) =>+ request('/tribe/beeper/link', {+ method: 'POST',+ body: JSON.stringify({ conversationId, sourceUserId, personId }),+ ...options,+ });++export const createTribePersonFromBeeper = ({ conversationId, sourceUserId, name, ring, relationship }, options = {}) =>+ request('/tribe/beeper/link-new', {+ method: 'POST',+ body: JSON.stringify({ conversationId, sourceUserId, name, ring, relationship }),+ ...options,+ });++// Remove one Beeper identity claim from a person (#99) — the person form's+// "Linked on Beeper" block. `identityId` is a `tribe_identities.id` from that+// person's `identities[]`, not a participant key.+export const unlinkBeeperIdentity = (identityId, options = {}) =>+ request(`/tribe/beeper/identities/${identityId}`, { method: 'DELETE', ...options });++// Release a participant's link to whichever Tribe person currently owns it+// (#97 part B) — the counterpart `linkBeeperParticipant` never had. Idempotent:+// unlinking an already-unlinked participant is a 200 no-op, never an error.+export const unlinkBeeperParticipant = ({ conversationId, sourceUserId }, options = {}) =>+ request('/tribe/beeper/link', {+ method: 'DELETE',+ body: JSON.stringify({ conversationId, sourceUserId }),+ ...options,+ });diff --git a/docs/features/beeper.md b/docs/features/beeper.mdnew file mode 100644index 0000000000..4928a9e75c--- /dev/null+++ b/docs/features/beeper.md@@ -0,0 +1,779 @@+# Beeper++PortOS mirrors the chats a local [Beeper Desktop](https://www.beeper.com/) install already+bridges — WhatsApp, Discord, Telegram, and whatever else the user has connected — into its own+PostgreSQL store, renders them at **Comms > Beeper** (`/messages/beeper`), and can send one+message at a time through a human-gated outbox. Every request goes to Beeper Desktop's own local+HTTP and WebSocket API, on loopback by default. Nothing about the mirror crosses the federation+layer, and PortOS never talks to Beeper's cloud.++The feature is off by default and ships no credential. It becomes reachable only once the+**Beeper** instance feature is on and a token has been stored.++## What it talks to++Beeper Desktop exposes a local HTTP + WebSocket API. PortOS defaults to+`http://127.0.0.1:23373` (`DEFAULT_BASE_URL` in `server/services/beeperClient.js`), and+`settings.beeper.baseUrl` makes that editable for an install listening somewhere else. The+loopback literal rather than `localhost` is deliberate: a dual-stack box may resolve `localhost`+to `::1` first.++**`baseUrl` is loopback-only by default.** Every request carries `Authorization: Bearer+<vault-stored token>`, and `baseUrl` is prefixed onto both the REST calls and the realtime+WebSocket URL — a value pointed at an attacker-controlled host would turn one settings write into+a credential exfiltration. `beeperSettingsSchema` (`server/lib/mediaValidation.js`) refuses a+non-loopback `baseUrl` unless the sibling field `allowNonLoopbackBaseUrl` is explicitly set to+`true` (default `false`), and `normalizeBaseUrl` in `server/services/beeperClient.js` re-applies+the identical check on every read — `settings.json` is not schema-validated when it is loaded, so+a hand-edited file is a second path to the same value the PUT route already refuses; a value that+fails either check falls back to the shipped loopback default rather than reaching a request. The+settings drawer exposes the opt-in as a checkbox beside the Base URL field for the rare install+that genuinely runs Beeper Desktop on another machine.++The client is raw `fetch`, deliberately **not** `@beeper/desktop-api`: the published SDK lags+the live API and exposes no `Account.status`, no `loginID`, and no `/v1/bridges`. `GET /v1/spec`+on the running instance is the reference the client was written against. `server/lib/safeUrlFetch.js`+cannot wrap it — that helper blocks loopback in both postures by design, and this API *is* a+loopback service — so every call goes through `fetchWithTimeout` directly, the same way the+Ollama and LM Studio integrations do.++The endpoints the shipped feature actually calls:++| Beeper endpoint | Used for |+| --- | --- |+| `GET /v1/info` | Liveness probe (it also answers unauthenticated, which is why it is the probe and not a credential check) and the `endpoints.oauth.introspection_endpoint` fallback |+| `GET /v1/accounts`, `GET /v1/bridges` | The account roster, joined into `beeper_accounts` |+| `GET /v1/chats?accountIDs=…` | Conversation ingestion, newest-first |+| `GET /v1/chats/{chatID}/messages` | Message ingestion, and the outbox's confirmation fallback |+| `GET /v1/chats/{chatID}/messages/{messageID}` | The outbox's confirmation fallback |+| `POST /v1/chats/{chatID}/messages` | The one send call, reached only from the outbox |+| `PATCH /v1/chats/{chatID}` | The Archive and Low priority rail controls |+| `GET`/`HEAD /v1/assets/serve` | The attachment mirror — the stream and its size pre-flight |+| `WS /v1/ws` | The realtime transport |+| `/.well-known/oauth-authorization-server` and the endpoints it advertises | Connect and disconnect |++`beeperClient.js` wraps more of the API than the features currently reach — chat and message+search, read/unread state, reactions, edit and delete, `POST /v1/assets/download`, and the+single-chat GET all have wrappers and tests but no caller in a shipped feature path.++Live verification against a real instance was done on **Beeper Desktop 4.3.89**; the+"[What is not verified live](#what-is-not-verified-live)" section below says what that pass did+and did not cover.++Two non-obvious response shapes the client encodes, both confirmed live:++- `GET`/`HEAD /v1/assets/serve` answers **502**, not 404, for media the source network has aged+ out. A generic "5xx is transient" retry policy would loop forever on it, so an asset-endpoint+ 502 maps to a terminal `ASSET_UNAVAILABLE`.+- `POST /v1/assets/download` does *not* share that. It answers **200** with `{ error: "…" }` and+ no `srcURL`, so `downloadAsset` validates the 200 body itself and converges on the same+ terminal error.++Reads may retry once on a replayable connection failure. **Writes never retry** — Beeper has no+idempotency key on send, so a retried POST delivers a second real message to a real person.+`allowRetry` is off by default on every request for exactly that reason, and a thrown+`BeeperApiError` carries a `retryable` flag callers key on rather than re-deriving from the+status code.++**The liveness probe caps at 3s** (`DEFAULT_PROBE_TIMEOUT_MS` in `server/services/beeperClient.js`+— fork issue #61, decision 7; raised from 1s after that turned out too tight for a briefly-busy+Beeper Desktop). A probe *timeout* specifically — never a fast refusal, which still means+"unreachable" immediately — is ambiguous alone: nothing distinguishes "briefly slow" from+"actually closed" by timing. Paired with a Beeper call that succeeded recently (a real API request+through this client, or the realtime socket receiving a fresh ping) within `RECENT_SUCCESS_WINDOW_MS`+(60s, same file), it reports `probeState: 'slow'` instead — `reachable` **stays `true`**, and the+status card renders the connected card with the measured `probeLatencyMs` rather than jumping to+the unreachable/actionable-fault card. With no recent activity, or for any other failure shape, a+genuinely closed Beeper Desktop still reaches `probeState: 'unreachable'` (and `reachable: false`)+on the very first probe. `reachable: null` (no token configured, the probe never ran) keeps its own+distinct meaning throughout and never collapses into `slow`.++## Setup++1. In **Settings > Features**, make sure the **Comms** group is on and turn on **Beeper**.+ Beeper is off by default and has no auto-detector — a token-presence gate cannot bootstrap+ the very screen that sets the token.+2. Open **Comms > Beeper**, then the settings drawer from the header action+ (deep-linked as `?settings=1`, so ⌘K and voice can open it directly).+3. Connect: either **Connect Beeper** (OAuth) or paste a token from Beeper Desktop's own UI.+ Both are first-class; see below.+4. Turn on **Enable scheduled Beeper sync** and save. Nothing is ingested until this is on.+5. Optionally adjust the sweep interval, the base URL, and the attachment disk budget in the+ same drawer.++The settings the drawer writes are `settings.beeper.{enabled, intervalMinutes, baseUrl,+attachmentBudgetGb, allowNonLoopbackBaseUrl}` — `enabled` false, 5 minutes, the loopback default,+5 GB, and the non-loopback opt-in off. The schema (`beeperSettingsSchema`) is `.strict()` and has+no token field at all, so a credential can never ride the generic settings route.++Storing a credential, flipping the Beeper feature or the Comms group, or saving a change to+**Enable scheduled Beeper sync** itself, arms or disarms both the sweep scheduler and the+realtime transport immediately — `reconcileBeeperIngestion()` in `server/services/beeperArming.js`+is called from every one of those paths, so no restart is needed and a disconnect stops the relay+rather than leaving it running on a revoked token. **Arming also runs one sweep right away**+(fork issue #79): before this, connecting (or turning a toggle on) registered the interval timer+but the mirror stayed empty until a full interval had elapsed. Changing just the sync interval —+no toggle flip — takes effect the same way, without a restart: `PUT /api/settings` restarts the+scheduler's registration when `beeper.intervalMinutes` changes on its own (see+[The mirror](#the-mirror) below).++**Beeper also bridges iMessage and Signal.** An install that keeps the built-in iMessage or+Signal reader enabled *and* connects the same account through Beeper sees those conversations+twice, once per source. This version builds no cross-source exclusion or dedupe; pick one reader+per network in Settings > Features (the Comms group's per-feature overrides exist for exactly+this) and the mirror stays single-sourced.++## Connecting++**OAuth is run by PortOS itself.** Beeper Desktop's authorization-server metadata advertises a+`registration_endpoint`, `token_endpoint_auth_methods_supported: ["none"]` and+`code_challenge_methods_supported: ["S256"]`, so PortOS registers itself as a *public* client by+dynamic registration (client name `PortOS`, `token_endpoint_auth_method: none`) and runs+authorization-code + PKCE S256 with a `state` parameter. Both scopes (`read write`) are+requested in one authorization — a second consent round trip in the middle of composing a+message is worse than one prompt at setup.++The PKCE verifier never leaves the server. Pending authorizations live in memory keyed by+`state`, expire after ten minutes, and carry the endpoints discovered when the flow started, so+a base-URL change mid-flow cannot steer the callback at a different token endpoint. Every+discovered endpoint is re-validated against the configured base URL: a metadata document naming+a different host or port is refused outright (the loopback spellings count as one host), which+is what keeps a user-editable base URL from becoming a way to POST the authorization code+off-box.++The redirect URI is built from the browser's own `window.location.origin`, which the client+sends with `POST /api/beeper/oauth/start`. That is untrusted input — whatever lands in+`redirect_uri` is where the authorization code is sent — so `server/lib/beeperOAuthOrigin.js`+accepts it only as a bare `http(s)` origin whose host is a loopback spelling, the host the+request arrived on, or a host named by the configured `PORTOS_UI_URL`/`PORTOS_API_URL`. The port+is deliberately not pinned, because the UI and the API are different ports of one install.+Anything else is refused, warned about *without* logging the value, and falls back to the+request-derived origin. This exists because under the Vite dev proxy the request-derived origin+is the API origin, not the UI origin the browser is actually on.++`GET /api/beeper/oauth/callback` is hit by a browser redirect, not by the SPA, so every outcome+renders as a redirect back to `/messages/beeper` with a flag the tab toasts. The authorization+code is exchanged server-side and never reaches the client.++**Pasting a token is a first-class alternative, not a fallback.** Nothing in the OAuth surface+accepts a lifetime, while Beeper's own UI can mint a no-expiry token — and there is no+`refresh_token` grant anywhere in the metadata, so an expired token is re-connected, never+refreshed. A pasted token is verified before it is stored: RFC 7662 introspection when an+introspection endpoint is discoverable (from the metadata document, or failing that from+`/v1/info`'s `endpoints.oauth.introspection_endpoint`, validated through the same same-host+check), otherwise a call that requires the bearer. A token the server refuses is never stored.++**Where the credential lives.** One row, `id = 'default'`, in `beeper_credentials`: AES-256-GCM+ciphertext via `server/lib/vaultCrypto.js`, decrypted only at the moment of use. The token+grants read *and* send across every bridged network and `DELETE /v1/chats/…/messages/…` defaults+to unsending for everyone, so it does not follow the plaintext-settings precedent that root+`AGENTS.md`'s free-service carve-out covers. The token value is never logged, never put into an+error message, and never returned to a route: `GET /api/beeper/status` reports presence, expiry,+provenance and granted scopes only.++The honest limit, stated rather than overclaimed: `ensureVaultKey()` writes the vault key to the+install-root `.env`, on the same disk as the ciphertext. That bounds database dumps, backup+snapshots and accidental echoes. It does not defend against an attacker who already has+filesystem access.++A legacy plaintext `settings.beeper.token` from the original client survives as a **read-only**+fallback so an install that hand-edited one keeps working; nothing writes it.++**Disconnect** (`DELETE /api/beeper/token`) revokes at the authorization server first when the+credential came from OAuth and a revocation endpoint is advertised, then deletes the local copy+either way — a user asking to disconnect must always end up disconnected. It is idempotent, and+it disarms the sweep and the socket.++## The Comms feature group++`beeper` is one of six features in the **Comms** group (`facetime`, `imessage`, `signal`, `x`,+`stacker-news`, `beeper`), declared in `server/lib/instanceFeatureRegistry.js` as a plain `group: 'comms'` on the+feature descriptor. Settings > Features renders the group toggle and each member's own+tri-state override.++Resolution order for a grouped feature (`resolveOne` in `server/services/instanceFeatures.js`):++1. **The feature's own stored override wins**, on or off. Setting it back to "inherit"+ (`null`) drops the stored key entirely rather than writing a third sentinel.+2. **Otherwise the group decides.** Group off hides every member that has not overridden on;+ group on hands the feature back to its own normal resolution.+3. **Then the detector**, when the feature has one.+4. **Then `defaultEnabled`.**++A group's own `enabled` flag defaults to **true** when no group state is stored, so registering+the group never hid a feature an existing install already saw and no settings write was needed+to preserve the previous behaviour. Malformed settings fail toward `false` for both the feature+override and the group flag — untrustworthy settings must not be read as a confident "on".++Beeper itself declares no detector by design, and `defaultEnabled: false`.++The gate is applied to navigation, never to routes: with the feature off, the sidebar row and+the Messages tab pill disappear and `⌘K`/voice stop offering it, but `/messages/beeper` keeps+resolving so a bookmark or a direct link still works.++## The mirror++Ingestion is an HTTP sweep, not a socket feed. Beeper's WebSocket is at-most-once with no replay+on reconnect and drops events during hydration while the connection still looks healthy, so a+poll that ran only when the socket was down would be asleep during two of the three loss paths.+The socket makes ingestion *prompt*; the sweep makes it *complete*, and it runs unconditionally+on its own timer.++`server/services/beeperScheduler.js` is the fifth instance of the shared `createSyncScheduler`,+alongside iMessage, Signal, Spotify and YouTube. It is gated twice, and the two flags are+deliberately different things:++- `isBeeperIngestionArmed()` — the **instance feature** plus a stored token. Checked silently: a+ fresh install with the feature off narrates nothing it does not have.+- `settings.beeper.enabled` — the **user's ingestion opt-in**, re-read on every tick, so+ turning it off mid-session stops runs without a restart.++The registered event's own first tick lands one interval after registration, never at boot — a+process restart never fires a network sweep by itself, and neither does a plain re-registration+(the interval-change path below re-registers without touching this). Fork issue #79's fix sits+ONE layer up: `beeperArming.js`'s `reconcileBeeperIngestion()` fires `runBeeperSweep({ reason:+'arm' })` directly, fire-and-forget, whenever a reconcile is the one that newly registers the+scheduler — connecting, or turning the Beeper feature or the sync toggle on — never on the boot+call in `bootstrap.js`, which never reaches that reconcile at all. So a fresh arm gets one sweep+right away and the registered interval fires on its own schedule after that, unaffected.++The interval itself is read fresh at every *registration*, but a **running** registration does not+notice a settings change mid-flight — changing `intervalMinutes` alone used to take effect only at+the next process restart. `restartBeeperScheduler()` (`server/services/beeperScheduler.js`) is the+fix: cancel the current registration and register a fresh one, which reads+`getBeeperSyncConfig()` again. `PUT /api/settings` calls it when a save changes+`beeper.intervalMinutes` without also flipping `enabled`. An `enabled` flip alone does not always+get a fresh registration: a true→false save deliberately leaves the scheduler registered (it just+gates per tick), so a false→true flip right after finds it already registered and+`reconcileBeeperIngestion()`'s own guard declines to re-register it. When that combination lands —+a flip on an already-registered scheduler, with the interval also changed in the same save — `PUT+/api/settings` restarts the scheduler explicitly too, right after reconciling, so the stale+interval does not survive (fork issue #94). Deliberately no immediate sweep on the restart path:+only arming kicks one, and firing a sweep on every interval edit would surprise a user who is just+tuning a number.++Per account, one sweep:++1. refreshes `beeper_accounts` from the live roster;+2. pages `GET /v1/chats?accountIDs=…` newest-first, sweeping every chat on the page that is newer+ than the stored `beeper_sync_cursors.last_activity` watermark, and **stops at the first page+ that asks for no sweep at all**. One caught-up chat does not end the walk: the list is ordered+ by last activity, not by eligibility, and 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: upserts the conversation, upserts participants, pages new messages+ forward from the stored opaque cursor, logs daily Tribe touchpoints, then commits message+ rows, attachment references and the cursor row in **one transaction**.++That transaction boundary is the point of the module: an interrupted sweep leaves the cursor+exactly where it was and the next sweep refetches the same window. Everything outside it — the+conversation upsert, the participant upserts, the touchpoint writes — is keyed, deduped and+ordered *before* the commit, so a crash can only cause repeated work, never lost work. Safety+caps bound one sweep's work at 20 chat pages per account and 10 message pages per chat; a chat+further behind than that keeps its advanced cursor *and* its old watermark, so it stays eligible+and finishes catching up on the next sweep instead of being skipped as caught-up.++No AI provider call happens anywhere on this path. Ingestion is deterministic.++**An empty first page is retried once, not marked done (#81).** A brand-new chat's first sweep+takes exactly one page in the newest-first (`before`) direction. The sweep withholds the cursor+and watermark the first time that page comes back with zero messages, so the next sweep retries+the same page; if the retry is *also* empty, the real watermark commits (so a genuinely+history-less chat still reaches a stable, not-re-swept state) and one warn-level log line records+it — chat id only, no content. **This retry does not reach every empty chat.**+`chatNeedsSweep` only re-selects a chat once Beeper reports it as active again, and a live-instance+investigation found its *entire observed population* of empty chats were ones Beeper itself never+reports any activity for at all — not a message-kind filter (there is none) and not the safety+caps above (they only bound the forward catch-up walk on a chat that already has a stored cursor).+Those chats are swept exactly once and then correctly left alone; the retry instead 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).++**Sort order: an activity-less chat sorts last, not by when the mirror happened to sweep it+(#81).** The list ordering used to fall back to the conversation row's `created_at` for a chat with+no real Beeper activity. Every row in a fresh mirror is minted in the same short sweep window, so a+whole batch of activity-less chats shared a recent `created_at` and sorted at the **top** of the+Inbox, above populated threads with older real activity — this, not a mirroring gap, is what+actually produced the reported symptom for the observed population above. The fallback is now+`'epoch'::timestamptz` instead of `created_at`: older than any real timestamp, so an activity-less+chat sorts **last** under the existing `DESC` order rather than wherever its row happened to be+created. The network rail's own last-activity aggregate is a plain `MAX(c.last_activity)` — no+`created_at` fallback and no epoch sentinel, since `MAX` already ignores `NULL`s and returns `NULL`+when every conversation in the network has none, which is the honest answer.++**The Inbox row while a chat is still catching up.** `beeper_conversations.last_activity` is+Beeper's own chat-level watermark, mirrored independently of whether any message has actually+been mirrored — so a row can carry a recent `last_activity` while `lastMessage` is still `null`.+Beeper's own `Chat` payload carries no preview or snippet text to show in that gap, so the rail+row (`BeeperChatSurface.jsx`) reads it off `last_activity` instead: a conversation with no+mirrored message and a `last_activity` inside the last 24 hours shows **"Syncing…"**; anything+older, or with no `last_activity` at all, keeps the honest **"No messages mirrored yet"** copy.+This only changes what an empty row *says*; the sort fix above is what changes *where* it sits.++**What is mirrored:** accounts, conversations, messages, participants, attachment *metadata* and+per-chat sync cursors, across eight `beeper_*` tables. **What is not:** `loginID` is stripped+from every account and bridge row before it reaches any caller (it is the bridge login+credential's own id — a phone number), and `activeAccountCount` is dropped because it is+documented to over-report. Beeper's own `isPinned` is mirrored rather than duplicated: PortOS+stores no pin of its own, and there is deliberately no route to set one. Deletions from the+source are tombstones, not removals — a message the source unsends keeps its row, body and+attachments and gains `unsent_at`.++**Tribe linking** relates a `beeper_participants` row to a `tribe_people` row by durability of+handle: a phone or a network username resolves through `tribe_identities` (plus the existing+Tribe phone matcher for a phone), and resolution only ever *matches* an existing person, never+creates one, so the automatic path cannot produce a duplicate. A participant with no durable+handle is linked by hand, and the participant upsert never touches `tribe_person_id`, so a+manual link survives every re-sync. Group touchpoints are derived from message **senders**, never+from the participant roster, because Beeper truncates that roster (20 in a list, 100 on a single+GET, no cursor) and iterating it would invent contact with people who never messaged.++**Every manual link is durable across a purge + resweep**, including for the roughly one in eight+counterparties Beeper reports neither a phone nor a username for. Linking claims a+`kind='beeper-user'` row in `tribe_identities` keyed on the participant's own Beeper **account id+and user id** (`beeper_conversations.account_id` + `beeper_participants.source_user_id`, both+joined server-side, never client-supplied) — a pair Beeper keeps stable across resweeps, where+the mirror's own `conversation_id` is a PortOS UUID re-minted by every purge. `tribe_identities`+has no foreign key onto anything Beeper-side, so purging a conversation cannot cascade the link+away with the participant row; the first re-observation after the resweep re-fills+`tribe_person_id` from the claim. Resolution order is: the handle claim, then the beeper-user+claim, then the cached column, then the legacy Tribe phone matcher. Re-linking the same+participant to the same person is a no-op; re-linking to somebody else moves the claim and clears+the displaced person's stale caches, the same "last explicit link wins" rule the handle axis+follows. Installs that made such links before this shipped are promoted by an idempotent backfill+that runs with the boot-time schema DDL (soft-deleted people are skipped).++**The Tribe link surfaces beside the thread title** (fork issue #98), not only inside the+participants drawer. `BeeperThread.jsx`'s header renders a small chip next to the title, branching+on the mirrored `conversation.isGroup` (Beeper's own `chat.type === 'group'`), never on+participant count:++- **1:1** (`isGroup: false`) — the counterpart is simply the conversation's own participant list+ (see `oneToOneCounterpart` in `BeeperThread.jsx`: Beeper's own roster for a `single` chat never+ includes the local account's user, so the roster IS the counterpart; there is no per-participant+ self/`isSender` marker anywhere in the mirrored schema to check instead, and no account user id+ reaches the client). Linked shows **"<name> · Tribe"** and clicking it opens `/tribe?person=<id>`+ directly; unlinked shows **"Link to Tribe"**, which opens the participants drawer (the same panel+ the existing "People" button opens).+- **Group** (`isGroup: true`) — a participant-count chip (e.g. "6 people", or "20+ people" once+ `hasMoreParticipants` is set, matching the drawer's own truncation caveat), which also opens the+ drawer. A group never shows a single link state — there is no one counterpart to link.++**The participant-linking control is a search-first picker**, not a full-roster `<select>`.+`BeeperPersonPicker.jsx` (beside `BeeperThread.jsx`, with its own test file) is a combobox: type to+filter (client-side, debounced ≥200ms, over the roster the surface already loads once per mount —+the server's `GET /tribe/people?search=` param stays available for a future caller with a roster+too large to hold client-side), navigate results with ArrowUp/ArrowDown, and Enter/click selects.+Selecting a result **is** the link action — there is no separate "Link" button afterwards. **"Create+new…" is always the picker's last row**, below every match, and opens `BeeperCreatePersonForm.jsx`+(beside `BeeperThread.jsx`, its own component with its own test file) in place of the picker (fork+issue #97 part A) rather than posting immediately: a name input prefilled from the participant's own+`displayName || handle` (editable, required), a ring `<select>` built from the same `RINGS` list+(`client/src/lib/tribe.js`) the Tribe page's own person editor renders, and an optional relationship+input. Enter submits, Escape cancels. Only its Create button — disabled while the name is blank or a+link is in flight — calls `onCreateAndLinkParticipant` with `{ name, ring, relationship }`, the exact+fields `POST /tribe/beeper/link-new`'s `beeperCreateAndLinkSchema` already accepted; Cancel returns+to the picker having posted nothing.++**A linked participant offers Change and Unlink, not just a static label** (fork issue #97 part B) —+until now, a mistaken "New" or a wrong pick from the picker was permanent from this panel. Both sit+beside the "Linked · <name>" row (`ParticipantRow`'s own `mode` state in `BeeperThread.jsx`):++- **Change** reopens the exact same search-first picker in the row, pre-focused (`autoFocus` on+ `BeeperPersonPicker`), so re-pointing the link is a single selection; "Create new…" inside it opens+ the same confirm-and-rename form as the unlinked path. Choosing a person calls the SAME+ `onLinkParticipant` / `POST /tribe/beeper/link` a fresh link uses — verified safe to reuse rather+ than unlink-then-link: `linkParticipant`'s `tribe_identities` writes are `ON CONFLICT ... DO+ UPDATE`s that move the SAME row's `person_id` in place, so re-linking to someone else leaves no+ stale claim on the old person for this participant. "The last explicit link wins" already meant one+ row per identity, never two, so a plain re-link is a complete, correct Change on its own.+- **Unlink** calls the new `DELETE /tribe/beeper/link` (body `{ conversationId, sourceUserId }`) →+ `beeperTribe.unlinkParticipant`, which deletes every `tribe_identities` claim the CURRENTLY-linked+ person holds for this participant — the handle claim from `identityScopeFor` and/or the+ `kind='beeper-user'` claim from `beeperUserScopeFor` — each filtered on that person's own id, so a+ claim someone else now holds on the same handle is never touched. It then nulls the participant's+ own cache column and every other participant row those claims were backing, reusing the same+ `clearDisplacedParticipantCaches`/`clearDisplacedBeeperUserCaches` helpers a displaced-owner re-link+ already relies on, with the unlinked person simply standing in as the "displaced" one. Idempotent:+ unlinking an already-unlinked participant is a 200 no-op (`unlinkedPersonId: null`), and a genuine+ unlink emits the same `tribe:changed` socket event the link routes do.++**`Tribe.jsx` accepts a `?person=<id>` deep link.** On load, and whenever the param changes, the+page switches to the Circle tab, selects that person through the exact same path a click on their+`ContactCard` takes (`selectContact`), and scrolls the card into view — the same shape the existing+`?outreach=<conversationKey>` deep link (Care Queue) already uses. An id the roster does not+recognize (a deleted person, or a stale bookmark) is silently ignored, with no error toast. Both the+title chip's linked state and the participants drawer's "Linked · <name>" row (now a link, not plain+text) point here.++**The Tribe person form shows every linked identity.** `GET /tribe/people/:id` (only the+single-person read — the roster never pays this join) attaches `identities: [{ kind, network,+handle, linkedAt, source, conversations }]`, one entry per `tribe_identities` claim, each carrying+the Beeper conversations it appears in. A `beeper-user` claim's conversations come from joining+`beeper_participants`/`beeper_conversations` on the claim's own (account, `source_user_id`) key;+a `handle`/`phone` claim's come from the resolved participant cache+(`beeper_participants.tribe_person_id`), scoped to the claim's network for a `handle` and+left unscoped for a network-less `phone`. A purged conversation or a participant whose cache was+cleared by a later re-link simply contributes no conversation entry — nothing to special-case. The+Tribe person form's "Linked on Beeper" block renders one chip per identity — network plus handle+or participant display name — each conversation linking to `/messages/beeper/<conversationId>`,+with an Unlink action (`DELETE /tribe/beeper/identities/:identityId`) that removes the claim and+nulls the cache rows it was backing. Notes no longer carries the network: a fresh Beeper import+sets `notes` to the plain "Imported from Beeper" and leaves the network entirely to this block, so+a second network linked later never leaves a stale first-network mention behind (existing notes+are untouched).++### Unread badge++`beeper_conversations.unread_count` is Beeper's own count, mirrored verbatim and overwritten+wholesale by every sweep — so opening a thread in PortOS cannot clear it by zeroing that column+directly; the very next sweep would put it right back. Fork issue #83's fix is a second, LOCAL+column instead: `seen_at`, stamped with the server's own clock (`markConversationSeen` in+`server/services/beeperConversations.js`) when the chat surface opens a thread, and again, cheaply,+whenever a new message lands in a thread that is already open. Every read path that shows an+unread count — the row badge, `unreadOnly` in `GET /api/beeper/conversations`, and both aggregates+`GET /api/beeper/networks` returns — treats a conversation as read when `seen_at` is at or after+its own `COALESCE(last_activity, created_at)`, and as unread again the moment newer activity lands,+with no separate bookkeeping. Because the comparison happens at read time against a column the+sweep never touches, the watermark survives every sweep by construction rather than by racing one.++**This never writes to Beeper.** `POST /api/beeper/conversations/:id/seen` is a pure local update —+no `PATCH`, no read receipt, nothing that reaches the source network or shows up on another device+signed into the same account. A settings toggle to *also* send a real read receipt through Beeper's+own API is deliberately out of scope for this change; `markConversationSeen` carries a `TODO(#83)`+at the seam where that PATCH-then-mirror write would go, gated behind its own consent step and+defaulting off, the same way the Archive and Low priority rail controls are wired today.++### Attachments++The byte mirror is **lazy**. Ingestion writes the attachment's metadata and its durable `mxc_id`+reference; the bytes arrive only when a human opens the thread that shows them. A mirrored+account's attachment history runs to gigabytes, and fetching all of it is a transfer nobody+asked for. A bulk backfill exists, but it is a user action behind a consent step that names the+count and the byte size first, and it stops at the disk budget rather than blowing through it.++Files are **content-addressed** at `data/beeper/attachments/<sha256[0..2]>/<sha256>.<ext>`, so+one photo forwarded into four chats is one file and four rows — which is why every deletion path+runs a reference check before unlinking. The extension is cosmetic: `GET /v1/assets/serve` sends+no `Content-Type` at all, so the row stores Beeper's declared `mimeType` and the serving route is+handed that explicitly rather than letting anything be sniffed out of a filename.++- **Per-attachment ceiling: 32 MiB** (`BEEPER_ATTACHMENT_MAX_BYTES`), matching the ceiling PortOS+ already uses for a single federated media asset. It is a named constant, not a setting: an+ over-cap attachment is not lost, it keeps its row and offers "fetch anyway", which is the+ escape hatch a knob would otherwise have been. The cap is enforced at the `HEAD` pre-flight+ *and* mid-stream, because a bridge that declines to report `Content-Length` would otherwise get+ an unbounded write past a ceiling the pre-flight could not see.+- **Disk budget: `settings.beeper.attachmentBudgetGb`**, 5 GB by default, 0.1–1000 accepted.+- **Eviction** is least-recently-viewed, at most 50 candidates per sweep, and it skips anything+ the user locked with `keep`. Before evicting, it `HEAD`s the source: a 502 means Beeper can no+ longer supply the file, so the local copy is the last one in existence and is **kept**+ regardless of age and stamped `unavailable_at` so nothing re-probes it. Any *other* probe+ failure (Beeper closed, a transport blip) stops the sweep rather than evicting on an unanswered+ question, and a row with no `mxc_id` is never a candidate at all, because eviction is only safe+ when the file can be fetched again.+- The same six-hourly sweep also runs an orphan backstop (a file no row points at, a row whose+ file is gone, an abandoned `.partial` older than an hour). It runs whether or not scheduled+ sync is on, because bytes already on disk still count against the budget.+- A stalled transfer is bounded by **silence**, not elapsed time: 60 seconds without a chunk+ aborts, so a slow but progressing 32 MiB download is never cut off and a dead one is.++Bytes are served from an authenticated `/api/` route (`GET /api/beeper/attachments/:messageId/:idx`),+never a static `data/` mount — message media is PII and the store is a pile of hashes that a+directory mount would expose without the row-level check the route performs.++**Data Manager's `beeper` category (`server/services/dataManager.js`) is size-only** —+`deletable: false`, no `purgeScope`. `data/beeper/` holds one subdirectory, `attachments/`, so the+generic purge control was never actually reachable: a category-wide wipe needs `purgeScope:+'category'`, and the per-item form refuses a directory entry outright (it removes a single file+and never recurses). Reclaiming space runs through the two paths above that reference-check+before touching a byte instead: the attachment budget sweep (least-recently-viewed eviction,+bounded by `settings.beeper.attachmentBudgetGb`) and the per-conversation purge+(`DELETE /api/beeper/conversations/:id`, content-addressed so a photo forwarded into other chats+survives one conversation being purged).++### Realtime++`server/services/beeperSocket.js` holds one long-lived WebSocket from the PortOS server to+`/v1/ws`. The browser cannot hold it: Beeper binds to loopback with CORS locked to the machine,+and a browser cannot set an `Authorization` header on `new WebSocket()`. It uses the `ws`+package rather than Node's built-in WebSocket because a protocol-level server ping is the only+liveness signal Beeper offers and the built-in does not surface ping frames to application code.++On `ready` the transport sends one `subscriptions.set` for `chatIDs: ['*']` plus app state, and+never re-subscribes per conversation: `subscriptions.set` replaces state wholesale and the window+during a re-set is dark, so scoping it would manufacture a loss window on exactly the event you+most want to catch.++- **Silence watchdog:** 75 seconds (2.5 missed server pings) without any inbound signal tears the+ socket down and reconnects. Reconnect backoff runs from 1 s to a 60 s ceiling; after the first+ three attempts only every tenth is logged, because Beeper Desktop simply being closed is the+ common case.+- **The socket asks the sweep to run early** on the three occasions frames could have been lost:+ a reconnect, a `seq` gap, and a recovery from an actionable `app.state`. The first connection of+ a process is not a reconnect and fires nothing.+- **It is never gated on `app.state`.** A live probe caught `initializing` reported for 105+ continuous seconds while every bridged account was connected and a chat page returned in+ 230 ms. It is a display input for the status card, never a gate.+- The transport arms on the feature-plus-token gate alone, without the ingestion opt-in: holding+ the socket open writes nothing, and the liveness dot it feeds is precisely the surface a user+ needs while deciding whether to turn ingestion on. With the ingestion toggle off it connects,+ subscribes and relays invalidations, and writes no conversation or message body.++**The relay to the browser is invalidation-only.** `server/services/beeperSocketEvents.js` is a+leaf event bus; `socket.js` bridges it onto Socket.IO and broadcasts to the `beeper` subscriber+set — never `io.emit`, because the peer relay opens a Socket.IO client to every online peer and a+global emit would cross the wire to other installs. Frames carry ids, kinds and transport+liveness. They never carry message bodies, display names or handles; the browser refetches from+the PortOS mirror, which is the read path.++### Sweep visibility and the list header++Before fork issue #80, nothing on screen distinguished "connected, first sync running" from+"nothing connected" — the empty inbox told a user who had just connected nine accounts to go+connect one. Two pieces close that gap:++- **`server/services/beeperSweepProgress.js`** is a small standalone leaf module (same reason+ `beeperSocketEvents.js` is one: a read-only status route has no business importing the sweep's+ whole DB/HTTP dependency graph just to report a few numbers) holding one in-memory, process-wide+ snapshot: `running`, `startedAt`, `finishedAt`, `reason`, `accountsDone`, `accountsTotal`,+ `chats`, `messages`. `executeSweep` in `beeperSync.js` updates it as it goes — `running: true`+ before the first HTTP call, `accountsTotal` once the roster is known, `accountsDone`/`chats`/+ `messages` after every account, `running: false` in a `finally` so a thrown `NOT_CONFIGURED` or+ `SWEEP_FAILED` still flips it back. `beeperStatus.js` reads it into `GET /api/beeper/status`'s+ `sweep` field (see [API surface](#api-surface)).+- **The sweep fires an invalidation frame** — the exact `{ kind, chatID, ids, seq, ts }` shape+ #33's realtime relay already uses, with `kind: 'beeper-sweep'` and `chatID: null` — once the+ account count is known and again after every account finishes, reusing `beeperSocketEvents`+ rather than opening a second channel. `BeeperTab.jsx` already re-fetches `GET+ /api/beeper/status` on every invalidation frame (the same fetch that seeds the realtime dot and+ the outbox breaker flag), so the list header's strip and the settings drawer's status card both+ move as the sweep progresses with no separate poller anywhere.++The list header (`BeeperChatSurface.jsx`) renders `"Syncing… N of M accounts"` while `sweep.running`+is true and `"Last synced HH:MM"` (from `sweep.finishedAt`) once idle; nothing before a sweep has+ever run. The settings drawer's status card shows the identical two lines beside the realtime dot.+The empty state also branches on `tokenConfigured` rather than on `networks.length` alone:+connected but nothing mirrored yet reads **"First sync in progress"**; never connected keeps the+"Open Beeper settings" prompt.++**"Sync now"** replaces what used to be a plain refresh button (fork issue #79): the list header's+icon button now calls `POST /api/beeper/sync` first and re-fetches the conversation list and the+network rail once that resolves (`skipped: true` — a sweep already in flight, most likely the+scheduled one — still triggers the re-fetch, since whatever that sweep already wrote is worth+showing).++## Sending++There is exactly one send path and it is a human one, in two steps and two routes, mirroring the+email drafts surface: `POST /api/beeper/outbox` records the approved text, `POST /api/beeper/outbox/:id/send`+performs the POST to Beeper. No scheduler, no agent, no voice tool and no Chief-of-Staff tool+reaches either — `server/services/beeperOutboxHumanGate.test.js` asserts that structurally rather+than leaving it to convention. There is no AI drafting and no AI review anywhere on this path.++Send also needs the `write` scope on the stored token. Connect requests both scopes, and Beeper's+consent screen is where the user grants them; a token granted `read` only makes Beeper refuse the+POST with a 403, which the client maps to a terminal `FORBIDDEN`. The outbox row fails in place and+nothing is retried or sent. That is the operator's switch for keeping send off entirely while the+read side keeps working.++Four rules the outbox exists to enforce:++1. **The durable row is written before the POST**, so intent survives a crash between the click+ and the send. 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, so a retry delivers+ a second real message. A transport failure leaves exactly one row in `failed`, with its code+ and message, and no second POST. Re-sending means composing a *new* row from a new human+ action; the failed one stays visible.+3. **Confirmation is a resolve, never a re-send.** The send answers only+ `{ chatID, pendingMessageID }`, so the row confirms on the relayed `message.upserted`+ invalidation, with a 30-second fallback to `GET /v1/chats/{chatID}/messages/{messageID}`.+ Neither path sends anything.+4. **A runaway breaker, not a rate quota.** Every send is one human click, so a quota paces+ someone already paced. The breaker catches the failure this design cannot otherwise see — a+ software loop: more than 10 sends in a rolling 60 seconds, or 3 consecutive failures. Only a+ human clears it (`POST /api/beeper/outbox/breaker/clear`); a breaker that clears itself is a+ delay, not a breaker.++**A restart mid-flight** is reconciled at boot, because `sending` and `awaiting-confirmation` are+exit-only through in-memory state (the pending map, its timer, the socket listener) and no route+can move a row out of either. `reconcileOutboxOnBoot()` runs once per server start from+`bootstrap.js`, regardless of whether the Beeper feature is armed — a stranded send is stranded+either way. A row left in `sending` becomes `failed` with `SEND_INTERRUPTED`, because the POST's+outcome is genuinely unknowable and rule 2 has no crash exception: nothing re-POSTs it, and the+user's recovery is the ordinary failed-row Retry, which composes a new row. A row left in+`awaiting-confirmation` has its lookup re-armed from the row's own `chat_id`, `pending_message_id`+and `body` — a resolve on both paths, never a send. Terminal rows are untouched, and a second call+finds nothing left to do.++**First contact** to a conversation is refused with a coded 409 unless `confirmFirstContact` is+explicitly true. It keys on either of two sources of outbound history, scoped to the one+conversation being sent to: a mirrored message with `is_sender` true (sent from any client, not+just this PortOS install), or a prior outbox row that reached Beeper — `sent`,+`awaiting-confirmation` or `sending` — not `sent` alone, so an unconfirmed-but-delivered send does+not re-ask a question that must fire exactly once. Either source alone is enough to count as known;+the confirmation is reserved for a chat neither source has any outbound history for. The composer+renders it inline, naming the network and the recipient — never a `window.confirm`. Cancelling+discards the row through `DELETE /api/beeper/outbox/:id`, which only accepts a row still in+`approved` (nothing has been POSTed for it, so this is a local record removal, never an unsend);+anything further along answers 409.++**What the composer shows.** Outbox rows render inline with the mirrored messages, filtered on the+entry's STATE: a settled `sent` row is dropped outright, because the mirrored message is the+record of it — filtering on "is its message in the page I happen to have loaded" instead left a+long-settled send rendering forever as a spinning bubble with old text, since `GET /outbox`+returns up to 50 entries in every state. Only a send that can still change spins. Everything else+is terminal and says so:++- **Failed** — "Not delivered", with the recorded error and **Retry**, which composes a brand-new+ entry with the same text rather than resending the failed one.+- **Interrupted by a restart** (`SEND_INTERRUPTED`) — "Delivery unconfirmed: PortOS restarted+ mid-send. Check the chat before retrying.", with the same Retry. It does not claim a delivery+ verdict, because there isn't one.+- **Sent, unconfirmed** (`CONFIRMATION_UNRESOLVED`) — the reason the 30-second fallback recorded,+ and no Retry: the message may well have been delivered, and a resend is the one mistake that+ cannot be taken back.+- **Stranded in `approved`** (most often the breaker was tripped when the send was attempted) —+ **Retry**, which re-dispatches that same row because nothing ever touched the wire for it, and+ **Dismiss**, which discards it.++Send is disabled and names the reason while the breaker is tripped — re-read whenever the mirror+signals a change, so a breaker that trips mid-session reaches the composer without a reload; the+breaker's own banner stays in the settings drawer rather than appearing a second time on the chat+surface.++## Purge and disconnect++`DELETE /api/beeper/conversations/:id` purges one conversation's mirror: messages, participants,+attachment rows, and the bytes those rows were holding — with the attachment reference check run+*first*, while the rows it checks against still exist, so a photo forwarded into three other+chats survives. The conversation row and its sync cursor go together in one transaction. It is+local only: Beeper still has the chat, and the next sweep will mirror it again. The client gates+it behind a typed confirmation naming the conversation and the byte count.++Disconnecting deletes the credential (revoking it first where possible) and disarms both the+sweep and the socket. It does not purge the mirror.++## Privacy model++The Beeper mirror holds full message bodies and attachment metadata from every connected network.+It is machine-local, and that is enforced structurally rather than by convention:++- **No `beeper` kind is exposed to peer-sync subscriptions**, no `beeper` wire-schema category is+ declared, no `beeper` dataSync snapshot category exists, and no `beeper_*` table carries the+ `sync_sequence` column that federation is built on.+- **`data/beeper/` never enters the media-library federation walk.** That walk is the other way+ `data/` bytes reach a peer — it walks whole directories rather than record kinds, so none of the+ schema or subscription guards above cover it.+- All of that is pinned by `server/services/sharing/beeperNeverFederates.test.js`, which asserts+ each list is still recognizably populated (so a collapsed list cannot satisfy an empty filter),+ and carries a bypass probe that plants violations to prove the predicates actually fire.+- Attachment bytes are served from an authenticated API route with a row-level check, never a+ static directory mount.+- The realtime relay is invalidation-only and broadcast to the Beeper subscriber set alone, so no+ message content reaches Socket.IO at all — let alone the peer relay.+- The access token is AES-256-GCM ciphertext in Postgres, exposed to any client as presence,+ expiry and provenance and never as a value.++**What leaves the machine:** requests to Beeper Desktop on loopback (or on the configured base+URL), and the one `POST` per message the user explicitly sends. **What never does:** the mirror,+its attachments, the token, and anything on the Socket.IO relay.++## API surface++25 routes under `/api/beeper`, all mounted from `server/routes/beeper.js`.++| Method | Route | What it does |+| --- | --- | --- |+| `GET` | `/api/beeper/status` | The status card's read model: token presence/expiry/provenance/`tokenScopes` (array of strings, `[]` when unknown — a pasted token, fork issue #78), a cached reachability probe, the account roster, realtime state, outbox breaker, sweep progress (`sweep: { running, startedAt, finishedAt, reason, accountsDone, accountsTotal, chats, messages }`, fork issue #80) |+| `POST` | `/api/beeper/status/check` | Live uncached probe with a coded error per failure mode |+| `POST` | `/api/beeper/sync` | Run one watermark-bounded sweep now; a sweep already in flight reports `skipped: true` |+| `GET` | `/api/beeper/conversations` | Rail list for one scope (network, unread-only, archived, low-priority), cursor-paginated |+| `GET` | `/api/beeper/networks` | The rail's scope list, derived from the mirror |+| `GET` | `/api/beeper/conversations/:id` | One conversation with its mirrored participant subset; 404 at `severity: 'warning'` for a stale deep link |+| `GET` | `/api/beeper/conversations/:id/messages` | Cursor-paginated messages, newest first |+| `POST` | `/api/beeper/conversations/:id/archive` | Archive control — PATCHes Beeper first, mirrors the answer second |+| `POST` | `/api/beeper/conversations/:id/low-priority` | Low priority control, same shape |+| `POST` | `/api/beeper/conversations/:id/seen` | The local "seen in PortOS" watermark — never a Beeper write |+| `DELETE` | `/api/beeper/conversations/:id` | Purge one conversation's local mirror and its bytes |+| `GET` | `/api/beeper/attachments/summary` | Counts, bytes and the budget picture the consent step and the card need |+| `POST` | `/api/beeper/attachments/backfill` | Bulk-mirror reference-only attachments, stopping at the budget |+| `GET` | `/api/beeper/attachments/:messageId/:idx` | The bytes, from disk, fetched on a miss |+| `POST` | `/api/beeper/attachments/:messageId/:idx/fetch` | "Fetch anyway" for an over-cap row, and the only retry of a refused one |+| `PATCH` | `/api/beeper/attachments/:messageId/:idx` | The per-attachment `keep` lock |+| `POST` | `/api/beeper/oauth/start` | Discover, dynamically register, mint the PKCE authorization URL |+| `GET` | `/api/beeper/oauth/callback` | Browser redirect target; exchanges the code server-side and redirects back to the tab |+| `POST` | `/api/beeper/token` | Store a pasted token after verifying it |+| `DELETE` | `/api/beeper/token` | Disconnect: revoke where possible, then delete locally |+| `GET` | `/api/beeper/outbox` | One conversation's outbox history, newest first |+| `POST` | `/api/beeper/outbox` | Step one — the durable row |+| `POST` | `/api/beeper/outbox/:id/send` | Step two — the send |+| `DELETE` | `/api/beeper/outbox/:id` | Discard an `approved` row; 409 on anything further along |+| `POST` | `/api/beeper/outbox/breaker/clear` | The runaway breaker's only reset |++Socket.IO events:++| Event | Direction | Payload |+| --- | --- | --- |+| `beeper:subscribe` | client → server | Join the Beeper broadcast set (re-emitted on every socket `connect`) |+| `beeper:unsubscribe` | client → server | Leave it |+| `beeper:invalidate` | server → Beeper subscribers | `{ kind, chatID, ids, seq, ts }` — ids and kinds only, never content. `kind: 'beeper-sweep'` (`chatID: null`) is the sweep's own progress frame, fork issue #80 |+| `beeper:realtime` | server → Beeper subscribers | The transport liveness snapshot: `state`, `lastEventAt`, `lastPingAt`, `reconnectAttempts`, `appState`, `appStateActionable`, `authRejected` |++Both surfaces publish as **generated** contract entries. The committed+`apiRouteCatalog.generated.json` is gone: `server/lib/apiRouteGraph.js` now scans the mounted+route graph in memory on the first `/api/api-docs/*` request, and `socketEventInventory.js` does+the same for Socket.IO events, so `/api/beeper/*` and `beeper:*` are discovered from the mounted+router and the emit sites rather than from a checked-in file — nothing to regenerate when a+Beeper route is added. `/api/beeper` still appears in `docs/API.md`'s route-domain index, and+neither `server/lib/apiOperationContracts.js` nor+`server/lib/socketEventContracts.js` models any Beeper operation or event — so the catalog and+spec endpoints listed in [API_TOOL_CONTRACT.md](../API_TOOL_CONTRACT.md) report every one of them+with `contractStatus: "generated"` (path parameters and a default response, no richer modeled+contract).++## What is not verified live++Live probing of a real Beeper Desktop (4.3.89 on the most recent pass) established the+authorization-server metadata document, `/v1/info`'s advertised introspection endpoint, the+`POST /v1/assets/download` 200-with-`{error}` shape, the 502-on-missing-asset behaviour of+`GET`/`HEAD /v1/assets/serve`, `serve` sending no `Content-Type`, the `/v1/accounts` `bridge`+object shape, and a 105-second `app.state`/ping probe of `/v1/ws`.++A later end-to-end pass against the same instance, on the build that includes the upstream+merge, exercised the OAuth connect flow (dynamic registration, consent, the redirect landing on+the UI origin, disconnect revoking at the authorization server), realtime domain frames through+the shipped transport after an in-session connect, sends through the outbox on several networks+each resolved by its confirmation frame, the list header's "Syncing… N of M accounts" strip moving+during a multi-account sweep, the Low priority rail control's `PATCH`, attachments, and a purge. The+Tribe linking surface (title chip, search-first picker, create-and-link, change, unlink, and the+Tribe page's linked-handles block) was exercised by hand on a real install.++The following have **not** been observed against a real instance, and rest on unit, route and+component tests plus static analysis:++- **The `HEAD /v1/assets/serve` pre-flight and byte fidelity.** Whether the instance reports a+ usable `Content-Length` on `HEAD`, and whether a mirrored file is byte-identical to the source,+ have not been checked. (The 502 behaviour on both methods has.)+- **The in-flight image placeholder in a real browser.** jsdom cannot measure layout, so the+ tests pin the declared `aspect-ratio` and width, not the reserved box. Someone should watch a+ thread with an uncached image load in Chrome and confirm nothing reflows.+- **The conversation-not-found 404's `severity: 'warning'` path** was verified by the server+ suite and by static analysis of the socket and hook chain, not observed running.+- **A durable Tribe identity claim surviving a purge followed by a resweep** rests on the db+ tests and on one backfill run against a single real install; nobody has purged and resweeped a+ linked install by hand since.++## Files++- `server/services/beeperClient.js` — the HTTP client, pagination, error mapping, asset streaming+- `server/services/beeperOAuth.js`, `beeperCredentials.js` — connect, disconnect, the vault+- `server/services/beeperSync.js`, `beeperScheduler.js`, `beeperArming.js` — the sweep and its gates+- `server/services/beeperSweepProgress.js` — the sweep-progress leaf module `beeperStatus.js` reads+- `server/services/beeperSocket.js`, `beeperSocketEvents.js` — the realtime transport and its bus+- `server/services/beeperConversations.js`, `beeperAttachments.js`, `beeperAttachmentGc.js` — the read model, the byte mirror, the housekeeping sweep+- `server/services/beeperOutbox.js`, `beeperStatus.js`, `beeperTribe.js` — sending, the status card, identity linking+- `server/lib/db/schema/beeper.js` — the eight `beeper_*` tables+- `server/routes/beeper.js` — every route above+- `client/src/components/messages/BeeperTab.jsx` and `components/messages/beeper/` — the chat surface, thread, composer, attachments, settings drawer+- `server/services/sharing/beeperNeverFederates.test.js` — the federation guarddiff --git a/scripts/migrations/335-tribe-identities-table.js b/scripts/migrations/335-tribe-identities-table.jsnew file mode 100644index 0000000000..2d7d2c3c9d--- /dev/null+++ b/scripts/migrations/335-tribe-identities-table.js@@ -0,0 +1,29 @@+/**+ * Registration stub for the `tribe_identities` table (#34, decided on #10).+ *+ * The actual DDL — `CREATE TABLE IF NOT EXISTS tribe_identities` (person_id,+ * kind, network, handle, source, linked_at, UNIQUE (kind, network, handle))+ * plus `idx_tribe_identities_person` — is idempotent and lives in+ * `ensureSchema()` (`server/lib/db/schema/tribe.js`), which runs at server+ * boot AFTER the DB pool is up, and the fresh-install seed+ * (`server/scripts/init-db.sql`). The `scripts/migrations/` runner executes+ * BEFORE the pool is initialized, so a DDL statement cannot live here — the+ * same reason migrations 048-052, 108, 161, and 163+ * (`scripts/migrations/163-tribe-people-phones.js`) are boot-time ++ * stub-registered.+ *+ * This stub exists so the new-table change is *registered the standard way*:+ * it lands in `data/migrations.applied.json` so the migration ledger and+ * `git log` show when `tribe_identities` was introduced. The table is+ * additive (a brand-new, machine-local store) and no backfill is possible —+ * there is no pre-existing local source of network-scoped handles anywhere in+ * PortOS (#10 resolution) — so this stub has nothing to transform.+ *+ * No-op + idempotent: nothing to do here.+ */++export default {+ async up() {+ console.log('🪪 tribe_identities: table + index created idempotently by ensureSchema at boot; nothing to do in the file runner');+ },+};diff --git a/scripts/migrations/336-beeper-outbox-table.js b/scripts/migrations/336-beeper-outbox-table.jsnew file mode 100644index 0000000000..d9757c3315--- /dev/null+++ b/scripts/migrations/336-beeper-outbox-table.js@@ -0,0 +1,25 @@+/**+ * Registration stub for the `beeper_outbox` table (#36, decided on #8).+ *+ * The DDL — `CREATE TABLE IF NOT EXISTS beeper_outbox` plus+ * `idx_beeper_outbox_conversation_state` — is idempotent and lives in+ * `ensureSchema()` (`server/lib/db/schema/beeper.js`), which runs at server+ * boot AFTER the DB pool is up, and in the fresh-install seed+ * (`server/scripts/init-db.sql`). The `scripts/migrations/` runner executes+ * BEFORE the pool is initialized, so a DDL statement cannot live here — the+ * same reason migration 335 (`tribe_identities`) is boot-time + stub-registered.+ *+ * This stub exists so the new-table change is registered the standard way: it+ * lands in `data/migrations.applied.json`, so the ledger and `git log` show+ * when the outbox was introduced. The table is additive and machine-local, and+ * there is nothing to backfill — PortOS has never sent a Beeper message, so no+ * install has outbound history to migrate.+ *+ * No-op + idempotent: nothing to do here.+ */++export default {+ async up() {+ console.log('🫧 beeper_outbox: table + index created idempotently by ensureSchema at boot; nothing to do in the file runner');+ },+};diff --git a/server/index.js b/server/index.jsindex 9828479a2f..4ba5432d53 100644--- a/server/index.js+++ b/server/index.js@@ -57,6 +57,7 @@ import timelineRoutes from './routes/timeline.js';import imessageRoutes from './routes/imessage.js';import contactsRoutes from './routes/contacts.js';import signalRoutes from './routes/signal.js';+import beeperRoutes from './routes/beeper.js';import spotifyRoutes from './routes/spotify.js';import youtubeRoutes from './routes/youtube.js';import notificationsRoutes from './routes/notifications.js';@@ -342,6 +343,7 @@ app.use('/api/timeline', timelineRoutes);app.use('/api/imessage', imessageRoutes);app.use('/api/contacts', contactsRoutes);app.use('/api/signal', signalRoutes);+app.use('/api/beeper', beeperRoutes);app.use('/api/spotify', spotifyRoutes);app.use('/api/youtube', youtubeRoutes);app.use('/api/notifications', notificationsRoutes);diff --git a/server/lib/beeperAttachmentPaths.js b/server/lib/beeperAttachmentPaths.jsnew file mode 100644index 0000000000..d4de7afd4a--- /dev/null+++ b/server/lib/beeperAttachmentPaths.js@@ -0,0 +1,114 @@+/**+ * Pure layout rules for the Beeper attachment byte mirror (#37, decided on+ * #13). No I/O — the service (`services/beeperAttachments.js`), the serving+ * route and the GC sweep all derive the same path from the same two facts, so+ * the rule lives in one place rather than three.+ *+ * **Content-addressed.** A mirrored file is `<sha256[0..2]>/<sha256>.<ext>`+ * under `PATHS.beeperAttachments`. The prefix directory keeps a five-figure+ * attachment count off one inode-heavy directory, and addressing by hash means+ * the same photo forwarded into four chats occupies one file — which is also+ * why every deletion path has to run a reference check before unlinking (three+ * other rows may still point at it).+ *+ * **The extension is cosmetic, never the type.** `GET /v1/assets/serve` sends+ * no `Content-Type` at all (probed on a live install, #13), so the mirror+ * stores Beeper's declared `mimeType` in the row and serves from THAT. The+ * extension exists so a file recovered from a backup is still openable by+ * hand; `serveLocalFile` is handed an explicit `contentType` so it can never+ * be sniffed back out of the filename.+ */++/**+ * The per-attachment ceiling, matching `FEDERATED_MEDIA_ASSET_MAX_BYTES` in+ * `federatedMediaWire.js` — the other place PortOS decided how large a single+ * mirrored asset may be. A named constant, deliberately NOT a setting: a+ * measured attachment mix is overwhelmingly small files with a thin tail over+ * this line, so a knob here would be one nobody needs and one more value the+ * budget sweep has to reason about. An over-cap attachment is not lost — it+ * keeps its row and offers "fetch anyway", which is the escape hatch a setting+ * would otherwise have been.+ */+export const BEEPER_ATTACHMENT_MAX_BYTES = 32 * 1024 * 1024;++// Deliberately small: the extension is a convenience for a human browsing a+// restored backup, not a type declaration, so an unknown mime just gets `bin`.+const MIME_EXTENSIONS = new Map([+ ['image/jpeg', 'jpg'],+ ['image/jpg', 'jpg'],+ ['image/png', 'png'],+ ['image/gif', 'gif'],+ ['image/webp', 'webp'],+ ['image/heic', 'heic'],+ ['image/avif', 'avif'],+ ['image/svg+xml', 'svg'],+ ['video/mp4', 'mp4'],+ ['video/quicktime', 'mov'],+ ['video/webm', 'webm'],+ ['audio/mpeg', 'mp3'],+ ['audio/mp4', 'm4a'],+ ['audio/ogg', 'ogg'],+ ['audio/wav', 'wav'],+ ['application/pdf', 'pdf'],+ ['text/plain', 'txt'],+]);++/**+ * The media types the mirror knows how to store, as a Set — the keys of+ * `MIME_EXTENSIONS` above, exported so the serving pipeline can BOUND the+ * `contentType` override rather than echo it.+ *+ * The declared type on a mirrored attachment is written by a remote sender, and+ * the mirror is served from the authenticated dashboard origin, so a type+ * outside this set is served as `application/octet-stream` instead+ * (`serveLocalFile` in `lib/uploads.js`). Reusing the extension table's keys+ * keeps the two answers in lockstep: a type the mirror cannot even name a file+ * for is not a type it should be declaring on the wire either.+ */+export const MIRRORED_MIME_TYPES = new Set(MIME_EXTENSIONS.keys());++const SHA256_PATTERN = /^[0-9a-f]{64}$/;+const EXTENSION_PATTERN = /^[a-z0-9]{1,8}$/;++/**+ * The stored extension for one attachment: the declared mime first, then the+ * source file name's own suffix, then `bin`.+ *+ * The file name is NOT trusted as a path — only its trailing `[a-z0-9]{1,8}`+ * run is read, so a name carrying separators, dots or a traversal segment can+ * never reach the filesystem through here.+ */+export function attachmentExtension({ mimeType, fileName } = {}) {+ const mime = String(mimeType || '').trim().toLowerCase().split(';')[0];+ const known = MIME_EXTENSIONS.get(mime);+ if (known) return known;+ const suffix = String(fileName || '').trim().toLowerCase().split('.').pop() || '';+ return EXTENSION_PATTERN.test(suffix) ? suffix : 'bin';+}++/**+ * `<sha256[0..2]>/<sha256>.<ext>` — the store-relative path for one mirrored+ * attachment. Returns `null` for anything that is not a lowercase 64-hex+ * digest, so a caller can never build a path out of a half-computed hash.+ */+export function attachmentRelativePath(sha256, extension = 'bin') {+ const digest = String(sha256 || '').trim().toLowerCase();+ if (!SHA256_PATTERN.test(digest)) return null;+ const ext = EXTENSION_PATTERN.test(String(extension || '')) ? extension : 'bin';+ return `${digest.slice(0, 2)}/${digest}.${ext}`;+}++/**+ * Whether a stored `local_path` still looks like something this layout wrote.+ *+ * The value comes out of Postgres rather than off a request, but it is the one+ * DB column that becomes a filesystem path, and a mirror row is written by+ * whatever version of PortOS was running at the time. Validating the SHAPE+ * (prefix dir matches the digest, no separators beyond the one, no traversal)+ * is cheaper than reasoning about which past version could have written what.+ */+export function isSafeAttachmentRelativePath(relativePath) {+ const value = String(relativePath || '');+ const match = /^([0-9a-f]{2})\/([0-9a-f]{64})\.([a-z0-9]{1,8})$/.exec(value);+ return Boolean(match) && match[2].startsWith(match[1]);+}diff --git a/server/lib/beeperOAuthOrigin.js b/server/lib/beeperOAuthOrigin.jsnew file mode 100644index 0000000000..b75048261a--- /dev/null+++ b/server/lib/beeperOAuthOrigin.js@@ -0,0 +1,132 @@+/**+ * Which origin the Beeper OAuth `redirect_uri` may be built from (fork issue+ * #1, final live pass).+ *+ * The redirect URI used to be derived from `req.protocol` + `req.headers.host`+ * alone. Under the Vite dev proxy that is wrong in the one way that breaks the+ * flow: the proxy sets `changeOrigin: true` and forwards no `x-forwarded-*`, so+ * the server sees its OWN origin — the HTTPS API on the API port — rather than+ * the UI origin the browser is actually on. Beeper's consent screen then+ * redirects the browser to a host the TLS certificate does not cover (a+ * Tailscale cert covers `<machine>.<tailnet>.ts.net` and nothing else), so the+ * user lands on a certificate error even though the exchange completed.+ *+ * The browser knows its own origin, so it sends it. That makes it UNTRUSTED+ * input — whatever ends up in `redirect_uri` is where Beeper sends the+ * authorization code — so it is validated here rather than used as given:+ *+ * - It has to be a bare `http(s)` origin: scheme, host, optional port, and+ * nothing else. A value carrying a path, a query, credentials or a+ * trailing slash is not an origin and is refused rather than trimmed.+ * - Its HOST has to be one PortOS already answers on: a loopback spelling,+ * the host this very request arrived on, or a host named by the install's+ * configured UI/API origins (`PORTOS_UI_URL` / `PORTOS_API_URL`, both+ * env-overridable in `ports.js`). The PORT is deliberately not pinned:+ * the UI and the API are different ports of the same install, which is the+ * whole case this exists for.+ *+ * Anything else is refused and the caller falls back to the request-derived+ * origin — the previous behaviour, so a rejected value never leaves the user+ * worse off than before.+ *+ * Pure: no I/O, no request object, nothing to mock.+ */++// `localhost`, `127.0.0.1` and `::1` are the same host wearing different+// spellings — a dual-stack box resolves them differently, and Beeper's own base+// URL defaults to `127.0.0.1` for exactly that reason.+const LOOPBACK_HOSTNAMES = new Set(['localhost', '127.0.0.1', '::1', '[::1]']);++// Exported so other Beeper-facing modules that make the same "is this+// loopback" decision (the `settings.beeper.baseUrl` gate, #30/SEC-2; the OAuth+// token-endpoint host pin, SEC-3) reuse this one predicate rather than each+// keeping their own copy of the loopback-spelling list.+export const isLoopbackHostname = (hostname) => LOOPBACK_HOSTNAMES.has(String(hostname).toLowerCase())+ // 127.0.0.0/8 is all loopback, not just .0.1.+ || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(String(hostname));++/**+ * Parse a browser-supplied origin string. Returns the `URL`, or `null` when the+ * value is anything other than a bare `http(s)://host[:port]`.+ */+export function parseBrowserOrigin(value) {+ if (typeof value !== 'string' || !value.trim()) return null;+ const trimmed = value.trim();+ let url;+ try {+ url = new URL(trimmed);+ } catch {+ return null;+ }+ if (!['http:', 'https:'].includes(url.protocol)) return null;+ if (!url.hostname) return null;+ // `URL.origin` normalizes away a path, a query, a fragment and credentials —+ // so demanding the input equal it is one check for all four.+ if (url.origin !== trimmed) return null;+ return url;+}++/** The hostname of an origin-ish string, lowercased, or `null`. */+export function hostnameOf(value) {+ const url = parseBrowserOrigin(value) || (() => {+ try {+ return new URL(String(value));+ } catch {+ return null;+ }+ })();+ return url?.hostname ? url.hostname.toLowerCase() : null;+}++/**+ * Decide which origin the redirect URI is built from.+ *+ * @param {object} options+ * @param {string} [options.clientOrigin] - `window.location.origin`, as sent by the browser.+ * @param {string} [options.requestOrigin] - The origin derived from the request headers (the fallback).+ * @param {string[]} [options.configuredOrigins] - Origins this install is configured to serve on.+ * @returns {{origin: string|null, source: 'client'|'request'|'none', rejectedClientOrigin: boolean}}+ */+export function resolveOAuthOrigin({ clientOrigin, requestOrigin, configuredOrigins = [] } = {}) {+ const parsed = parseBrowserOrigin(clientOrigin);+ if (!parsed) {+ return {+ origin: requestOrigin || null,+ source: requestOrigin ? 'request' : 'none',+ // Only a value that was actually SENT counts as rejected; an omitted one+ // is just an older client.+ rejectedClientOrigin: typeof clientOrigin === 'string' && clientOrigin.trim().length > 0,+ };+ }++ const hostname = parsed.hostname.toLowerCase();+ const loopback = isLoopbackHostname(hostname);++ // An https→http downgrade of the redirect origin: the request reached this+ // install over TLS, but the browser-supplied origin proposes handing the+ // authorization code back over plaintext HTTP on a non-loopback host — a+ // network attacker on that path could otherwise intercept the code. The+ // loopback branch is exempt: Beeper Desktop and the Vite dev proxy both+ // round-trip through plain `http://127.0.0.1`/`localhost` even when the API+ // itself terminates TLS, and loopback traffic never leaves the machine.+ const requestIsHttps = parseBrowserOrigin(requestOrigin)?.protocol === 'https:';+ if (!loopback && requestIsHttps && parsed.protocol === 'http:') {+ return {+ origin: requestOrigin || null,+ source: requestOrigin ? 'request' : 'none',+ rejectedClientOrigin: true,+ };+ }++ const allowedHostnames = new Set(+ [requestOrigin, ...configuredOrigins].map(hostnameOf).filter(Boolean),+ );+ if (loopback || allowedHostnames.has(hostname)) {+ return { origin: parsed.origin, source: 'client', rejectedClientOrigin: false };+ }+ return {+ origin: requestOrigin || null,+ source: requestOrigin ? 'request' : 'none',+ rejectedClientOrigin: true,+ };+}diff --git a/server/lib/beeperOAuthOrigin.test.js b/server/lib/beeperOAuthOrigin.test.jsnew file mode 100644index 0000000000..8bcba58c32--- /dev/null+++ b/server/lib/beeperOAuthOrigin.test.js@@ -0,0 +1,114 @@+import { describe, it, expect } from 'vitest';+import { parseBrowserOrigin, resolveOAuthOrigin } from './beeperOAuthOrigin.js';++// Placeholders throughout — never a host observed on a real install.+const REQUEST_ORIGIN = 'https://localhost:5555';+const CONFIGURED = ['http://localhost:5554', 'https://host-example.example-tailnet.ts.net:5555'];++describe('parseBrowserOrigin', () => {+ it('accepts a bare http(s) origin and refuses anything carrying more than one', () => {+ expect(parseBrowserOrigin('http://localhost:5554')?.origin).toBe('http://localhost:5554');+ expect(parseBrowserOrigin('https://example.com')?.origin).toBe('https://example.com');+ // A trailing slash, a path, a query, credentials and a non-http scheme are+ // all "not an origin" — refused rather than trimmed into one, because the+ // value ends up in `redirect_uri`.+ expect(parseBrowserOrigin('http://localhost:5554/')).toBeNull();+ expect(parseBrowserOrigin('http://localhost:5554/api/beeper')).toBeNull();+ expect(parseBrowserOrigin('http://localhost:5554?next=/x')).toBeNull();+ expect(parseBrowserOrigin('http://user:pass@localhost:5554')).toBeNull();+ expect(parseBrowserOrigin('javascript:alert(1)')).toBeNull();+ expect(parseBrowserOrigin('file:///etc/hosts')).toBeNull();+ expect(parseBrowserOrigin('not a url')).toBeNull();+ expect(parseBrowserOrigin('')).toBeNull();+ expect(parseBrowserOrigin(undefined)).toBeNull();+ });+});++describe('resolveOAuthOrigin', () => {+ // The bug this exists for: under the Vite dev proxy the request arrives with+ // the API's own origin on the API port, so the consent redirect landed the+ // browser on a host the TLS certificate does not cover.+ it('prefers a loopback browser origin over the API origin the proxy makes the request look like', () => {+ expect(resolveOAuthOrigin({+ clientOrigin: 'http://localhost:5554',+ requestOrigin: REQUEST_ORIGIN,+ configuredOrigins: CONFIGURED,+ })).toEqual({ origin: 'http://localhost:5554', source: 'client', rejectedClientOrigin: false });+ });++ it('accepts every loopback spelling, since a dual-stack box resolves them differently', () => {+ for (const origin of ['http://127.0.0.1:5554', 'http://[::1]:5554', 'https://127.0.0.5:8443']) {+ expect(resolveOAuthOrigin({ clientOrigin: origin, requestOrigin: REQUEST_ORIGIN }))+ .toMatchObject({ origin, source: 'client' });+ }+ });++ it('accepts a different port on the host the request itself arrived on', () => {+ // UI and API are different ports of one install — pinning the port would+ // reject exactly the case this fix exists for.+ expect(resolveOAuthOrigin({+ clientOrigin: 'https://host-example.example-tailnet.ts.net:5554',+ requestOrigin: 'https://host-example.example-tailnet.ts.net:5555',+ })).toMatchObject({ origin: 'https://host-example.example-tailnet.ts.net:5554', source: 'client' });+ });++ it('accepts a host named by the configured UI/API origins', () => {+ expect(resolveOAuthOrigin({+ clientOrigin: 'https://host-example.example-tailnet.ts.net:5554',+ requestOrigin: REQUEST_ORIGIN,+ configuredOrigins: CONFIGURED,+ })).toMatchObject({ origin: 'https://host-example.example-tailnet.ts.net:5554', source: 'client' });+ });++ // An https→http downgrade of the redirect origin: the request itself+ // reached this install over TLS, so a client-supplied origin proposing to+ // hand the authorization code back over plaintext HTTP is refused even+ // though the host is otherwise recognized.+ it('refuses an http origin on a non-loopback host when the request arrived over https', () => {+ expect(resolveOAuthOrigin({+ clientOrigin: 'http://host-example.example-tailnet.ts.net:5554',+ requestOrigin: 'https://host-example.example-tailnet.ts.net:5555',+ configuredOrigins: CONFIGURED,+ })).toEqual({+ origin: 'https://host-example.example-tailnet.ts.net:5555',+ source: 'request',+ rejectedClientOrigin: true,+ });+ });++ it('still accepts an http origin on a loopback host even when the request arrived over https', () => {+ expect(resolveOAuthOrigin({+ clientOrigin: 'http://localhost:5554',+ requestOrigin: REQUEST_ORIGIN,+ configuredOrigins: CONFIGURED,+ })).toEqual({ origin: 'http://localhost:5554', source: 'client', rejectedClientOrigin: false });+ });++ it('refuses an unrecognized host and falls back to the request origin', () => {+ // Whatever lands in `redirect_uri` is where Beeper sends the authorization+ // code, so an origin this install does not answer on is never used.+ expect(resolveOAuthOrigin({+ clientOrigin: 'https://example.com',+ requestOrigin: REQUEST_ORIGIN,+ configuredOrigins: CONFIGURED,+ })).toEqual({ origin: REQUEST_ORIGIN, source: 'request', rejectedClientOrigin: true });+ });++ it('refuses a malformed origin and falls back', () => {+ expect(resolveOAuthOrigin({+ clientOrigin: 'http://localhost:5554/api/beeper/oauth/callback',+ requestOrigin: REQUEST_ORIGIN,+ })).toEqual({ origin: REQUEST_ORIGIN, source: 'request', rejectedClientOrigin: true });+ });++ it('falls back silently when no origin was sent at all', () => {+ // An older client is not a rejection — there is nothing to warn about.+ expect(resolveOAuthOrigin({ requestOrigin: REQUEST_ORIGIN }))+ .toEqual({ origin: REQUEST_ORIGIN, source: 'request', rejectedClientOrigin: false });+ });++ it('reports no origin when neither source produced one', () => {+ expect(resolveOAuthOrigin({}))+ .toEqual({ origin: null, source: 'none', rejectedClientOrigin: false });+ });+});diff --git a/server/lib/db.catalogDdlParity.test.js b/server/lib/db.catalogDdlParity.test.jsindex 185c33269a..44d4e03996 100644--- a/server/lib/db.catalogDdlParity.test.js+++ b/server/lib/db.catalogDdlParity.test.js@@ -153,6 +153,25 @@ function extractTypeCheckSet(source) {);}+// Pull the `<column> IN (...)` literal set out of one table's CHECK, from+// whichever of the two DDL sources is passed in. Used to pin a closed+// PortOS-owned state machine (e.g. beeper_outbox.state) so a value silently+// added to one file's CHECK but not the other — or dropped from both without+// anyone deciding to — surfaces here instead of at a runtime INSERT.+function extractCheckInSet(source, table, column) {+ const body = extractCreateTable(source, table);+ if (!body) return null;+ const re = new RegExp(`CHECK\\s*\\(\\s*${column}\\s+IN\\s*\\(([^)]*)\\)\\s*\\)`, 'i');+ const m = re.exec(body);+ if (!m) return null;+ return new Set(+ m[1]+ .split(',')+ .map((s) => s.replace(/['"\s]/g, ''))+ .filter(Boolean),+ );+}+// Pull the `payload->>'<key>'` identifiers from the `search_tsv` generated// expression. Both files repeat them in the same per-line shape; we just// collect the set across the whole source.@@ -444,6 +463,87 @@ describe('catalog DDL parity (init-db.sql ↔ db.js ensureSchema)', () => {});}+ // Beeper mirror (#27 + #35) — eight machine-local tables that ship in BOTH+ // sources. `beeper_messages.is_sender` is the reason this block exists: a+ // column present on one side only would leave every EXISTING install with a+ // thread that has one side (init-db.sql runs on fresh provisioning alone),+ // and the additive `ALTER TABLE … ADD COLUMN IF NOT EXISTS` that backfills it+ // is asserted separately below, because a CREATE TABLE match alone would pass+ // while pre-existing installs never got the column.+ for (const { table, idxPrefix } of [+ { table: 'beeper_accounts', idxPrefix: null },+ { table: 'beeper_credentials', idxPrefix: null },+ { table: 'beeper_conversations', idxPrefix: 'idx_beeper_conversations_' },+ { table: 'beeper_participants', idxPrefix: 'idx_beeper_participants_' },+ { table: 'beeper_messages', idxPrefix: 'idx_beeper_messages_' },+ { table: 'beeper_attachments', idxPrefix: 'idx_beeper_attachments_' },+ { table: 'beeper_sync_cursors', idxPrefix: null },+ { table: 'beeper_outbox', idxPrefix: 'idx_beeper_outbox_' },+ ]) {+ it(`${table} has the same columns${idxPrefix ? ' and indexes' : ''} in both files`, () => {+ const sqlBody = extractCreateTable(INIT_SQL, table);+ const jsBody = extractCreateTable(DB_JS, table);+ expect(sqlBody, `init-db.sql missing CREATE TABLE ${table}`).toBeTruthy();+ expect(jsBody, `db/schema/beeper.js missing CREATE TABLE ${table}`).toBeTruthy();+ expect([...new Set(extractColumnNames(sqlBody))].sort())+ .toEqual([...new Set(extractColumnNames(jsBody))].sort());+ if (!idxPrefix) return;+ const sqlIdx = extractIndexNames(INIT_SQL, idxPrefix);+ const jsIdx = extractIndexNames(DB_JS, idxPrefix);+ expect([...sqlIdx].sort()).toEqual([...jsIdx].sort());+ expect(sqlIdx.size).toBeGreaterThan(0);+ });+ }++ // LENS-7: beeper_outbox's `state` CHECK is PortOS's own send-lifecycle state+ // machine (not a Beeper vocabulary), so — unlike beeper_conversations.type —+ // a new state SHOULD cost a two-file schema change. Pin the literal set so a+ // value added to one file's CHECK and not the other (or silently dropped+ // from both) fails here rather than at a runtime INSERT.+ it('beeper_outbox.state CHECK literal set is pinned and matches in both files', () => {+ const expected = new Set(['draft', 'approved', 'sending', 'awaiting-confirmation', 'sent', 'failed']);+ const sqlSet = extractCheckInSet(INIT_SQL, 'beeper_outbox', 'state');+ const jsSet = extractCheckInSet(DB_JS, 'beeper_outbox', 'state');+ expect(sqlSet, 'init-db.sql missing beeper_outbox.state CHECK').not.toBeNull();+ expect(jsSet, 'db/schema/beeper.js missing beeper_outbox.state CHECK').not.toBeNull();+ expect(sqlSet).toEqual(expected);+ expect(jsSet).toEqual(expected);+ });++ // LENS-7: tribe_identities (server/lib/db/schema/tribe.js) is what a durable+ // Beeper handle claim (kind='handle') resolves against — the same drift risk+ // as the beeper_* block above (a column or index added to one DDL source+ // only), so it gets its own parity assertion.+ it('tribe_identities has the same columns and indexes in both files', () => {+ const sqlBody = extractCreateTable(INIT_SQL, 'tribe_identities');+ const jsBody = extractCreateTable(DB_JS, 'tribe_identities');+ expect(sqlBody, 'init-db.sql missing CREATE TABLE tribe_identities').toBeTruthy();+ expect(jsBody, 'db/schema/tribe.js missing CREATE TABLE tribe_identities').toBeTruthy();+ expect([...new Set(extractColumnNames(sqlBody))].sort())+ .toEqual([...new Set(extractColumnNames(jsBody))].sort());+ const sqlIdx = extractIndexNames(INIT_SQL, 'idx_tribe_identities_');+ const jsIdx = extractIndexNames(DB_JS, 'idx_tribe_identities_');+ expect([...sqlIdx].sort()).toEqual([...jsIdx].sort());+ expect(sqlIdx.size).toBeGreaterThan(0);+ });++ // Every column a beeper_* table gained after its first ship needs an+ // additive ALTER on the upgrade path too — a fresh install gets it from the+ // CREATE above, an existing one only from here.+ it('beeper_* additive columns carry an ALTER TABLE for existing installs', () => {+ for (const { table, columns } of [+ { table: 'beeper_messages', columns: ['is_sender'] },+ { table: 'beeper_attachments', columns: ['local_path', 'fetched_at', 'unavailable_at', 'fetch_error'] },+ { table: 'beeper_conversations', columns: ['seen_at'] },+ ]) {+ for (const column of columns) {+ const re = new RegExp(`ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS ${column}\\b`, 'i');+ expect(re.test(DB_JS), `db/schema/beeper.js missing the additive ALTER for ${table}.${column}`).toBe(true);+ expect(extractCreateTable(INIT_SQL, table)).toContain(column);+ }+ }+ });+// Versioned DB-migration tracker (#1029) — non-`catalog_`-prefixed table in// BOTH DDL sources (base schema), so it gets its own column parity assertion.// No secondary index, nothing to compare there.diff --git a/server/lib/db/schema/README.md b/server/lib/db/schema/README.mdindex 883b9b3e19..66565d2c66 100644--- a/server/lib/db/schema/README.md+++ b/server/lib/db/schema/README.md@@ -19,7 +19,7 @@ Parity with `server/scripts/init-db.sql` (the fresh-install path) is locked by| Module | Export(s) | Domain ||---|---|---|| `core.js` | `coreDdl` | Memory sync columns + the `schema_migrations` version tracker |-| `tribe.js` | `tribeDdl` | Tribe CRM — people, touchpoints, memory links (machine-local) |+| `tribe.js` | `tribeDdl` | Tribe CRM — people, network-scoped identities (`tribe_identities`, the durable-handle truth table behind Beeper linking), touchpoints, memory links (machine-local) || `humanActivity.js` | `humanActivityDdl` | Human-activity timeline event store (machine-local) || `post.js` | `postDdl` | MeatSpace POST normalized runs and attempts (machine-local) || `commissions.js` | `commissionsDdl` | Creative Commissions + feedback (machine-local) |@@ -35,6 +35,7 @@ Parity with `server/scripts/init-db.sql` (the fresh-install path) is locked by| `privacy.js` | `privacyDdl` | Privacy suite — vault, consents, orgs, brokers, change events || `stackerNews.js` | `stackerNewsDdl` | Stacker News accounts, territories, untrusted-content analyses, and review-gated actions || `x.js` | `xDdl` | X account diagnostics, public post metrics, and review-gated drafts |+| `beeper.js` | `beeperDdl` | Beeper conversation mirror — accounts, the vault-encrypted access credential, conversations, messages, participants, attachment metadata, sync cursors, and the outbound send outbox (machine-local, never federated) || `audit.js` | `auditDdl`, `auditedTables`, `buildAuditTriggers()` | `record_audit` table/function + per-table audit triggers |### Composer (`index.js`)@@ -42,7 +43,7 @@ Parity with `server/scripts/init-db.sql` (the fresh-install path) is locked by- `buildUpgradeDdl()` → phase-1 list (`core` → `tribe` → `humanActivity` → `post` → `commissions` → `userActions` → `aiGraph`).- `buildCatalogDdl()` → phase-2 list (`catalog` → `media` → `catalogUserTypes` →`universes` → `library` → `pipeline` → `writersRoom` → `lora` → `privacy` → `stackerNews` → `x` →- `audit` DDL → audit triggers).+ `beeper` → `audit` DDL → audit triggers).`ensureSchemaImpl()` calls these two builders and runs each list through`pool.query` in order.diff --git a/server/lib/db/schema/audit.js b/server/lib/db/schema/audit.jsindex e645c6b4c8..0b4196b6e9 100644--- a/server/lib/db/schema/audit.js+++ b/server/lib/db/schema/audit.js@@ -91,6 +91,7 @@ export const auditedTables = ['writers_room_draft_versions', 'catalog_ingredients', 'catalog_scraps','catalog_user_types', 'creative_director_projects', 'threejs_models', 'image_to_3d_models', 'sprite_records', 'games', 'mood_boards', 'fableloom_stories','lora_training_runs', 'authors', 'artists', 'albums', 'tracks', 'tribe_people', 'tribe_touchpoints',+ 'tribe_identities',];// Build the per-table DROP/CREATE audit-trigger statements in the originaldiff --git a/server/lib/db/schema/beeper.db.test.js b/server/lib/db/schema/beeper.db.test.jsnew file mode 100644index 0000000000..41f18dc054--- /dev/null+++ b/server/lib/db/schema/beeper.db.test.js@@ -0,0 +1,392 @@+/**+ * Postgres-backed tests for the Beeper conversation-mirror schema (#27):+ * - ensureSchema() creates every beeper_* table and is idempotent on re-run+ * - the full FK chain (account → conversation → message → participant →+ * attachment, plus the sync-cursor row) inserts and cascade-deletes cleanly+ * - the `observed_via` CHECK constraint rejects an out-of-set value+ * - `UNIQUE (account_id, source_chat_id)` holds on beeper_conversations+ * - `beeper_credentials` (#31) stores one row keyed on a fixed id, accepts a+ * NULL expiry (the no-expiry pasted token), and rejects an unknown `source`+ * - `beeper_outbox` (#36) accepts every state of PortOS's own send machine,+ * rejects one outside it, and cascade-deletes with its conversation+ * - the `kind='beeper-user'` backfill (#96) promotes a pre-existing cached+ * link to a durable claim, skips soft-deleted people, and is idempotent+ *+ * `*.db.test.js` → runs ONLY via `npm run test:db` against `portos_test`, never+ * the real `portos` DB (the db.js runner guard + the suite skip below enforce+ * this). The DB is shared across worktrees, so every row created here uses a+ * per-run nonce and the whole chain is torn down in afterAll via one cascade+ * delete on the account row.+ */+import { describe, it, expect, afterAll } from 'vitest';+import { checkHealth, ensureSchema, close, query } from '../../db.js';+import { requireDbOrSkip } from '../../dbTestGate.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('lib/db/schema/beeper.db.test', dbReady, skipReason);++const nonce = `beeper-test-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;+const ACCOUNT_ID = nonce;++afterAll(async () => {+ if (dbReady) {+ // ON DELETE CASCADE on every child FK means this one delete tears down+ // the conversation, message, participant, attachment, and cursor rows+ // inserted below.+ await query('DELETE FROM beeper_accounts WHERE account_id = $1', [ACCOUNT_ID]).catch(() => {});+ await close();+ }+});++describe.skipIf(!runDb)('beeper conversation-mirror schema (#27)', () => {+ it('ensureSchema() is idempotent on re-run', async () => {+ await expect(ensureSchema()).resolves.not.toThrow();+ });++ it('creates every beeper_* table', async () => {+ const { rows } = await query(+ `SELECT table_name FROM information_schema.tables+ WHERE table_schema = 'public' AND table_name LIKE 'beeper_%'+ ORDER BY table_name`,+ );+ expect(rows.map((r) => r.table_name)).toEqual([+ 'beeper_accounts',+ 'beeper_attachments',+ 'beeper_conversations',+ 'beeper_credentials',+ 'beeper_messages',+ 'beeper_outbox',+ 'beeper_participants',+ 'beeper_sync_cursors',+ ]);+ });++ it('inserts the full account → conversation → message → participant → attachment chain and cascade-deletes it', async () => {+ await query(+ `INSERT INTO beeper_accounts (account_id, network, display_name, status, bridge_id)+ VALUES ($1, 'Example Network', 'Example Account', 'connected', 'example-bridge')`,+ [ACCOUNT_ID],+ );++ const { rows: convRows } = await query(+ `INSERT INTO beeper_conversations+ (account_id, network, source_chat_id, title, type, is_group, unread_count)+ VALUES ($1, 'Example Network', 'chat-1', 'Example Chat', 'single', FALSE, 2)+ RETURNING id`,+ [ACCOUNT_ID],+ );+ const conversationId = convRows[0].id;++ await query(+ `INSERT INTO beeper_messages (id, conversation_id, sender_id, body, sort_key)+ VALUES ($1, $2, 'user-1', 'hello from a test', '1')`,+ [`msg-${nonce}`, conversationId],+ );++ await query(+ `INSERT INTO beeper_participants+ (conversation_id, source_user_id, display_name, handle, observed_via)+ VALUES ($1, 'user-1', 'Example User', '@example', 'message-sender')`,+ [conversationId],+ );++ await query(+ `INSERT INTO beeper_attachments+ (conversation_id, message_id, idx, mxc_id, mime_type, file_name)+ VALUES ($1, $2, 0, 'mxc://example/abc', 'image/png', 'photo.png')`,+ [conversationId, `msg-${nonce}`],+ );++ await query(+ `INSERT INTO beeper_sync_cursors (account_id, chat_id, cursor)+ VALUES ($1, 'chat-1', 'opaque-cursor-value')`,+ [ACCOUNT_ID],+ );++ const before = await query('SELECT COUNT(*)::int AS n FROM beeper_messages WHERE conversation_id = $1', [conversationId]);+ expect(before.rows[0].n).toBe(1);++ // Deleting the account should cascade through every child table.+ await query('DELETE FROM beeper_accounts WHERE account_id = $1', [ACCOUNT_ID]);++ const afterConv = await query('SELECT COUNT(*)::int AS n FROM beeper_conversations WHERE id = $1', [conversationId]);+ const afterMsg = await query('SELECT COUNT(*)::int AS n FROM beeper_messages WHERE conversation_id = $1', [conversationId]);+ const afterPart = await query('SELECT COUNT(*)::int AS n FROM beeper_participants WHERE conversation_id = $1', [conversationId]);+ const afterAttach = await query('SELECT COUNT(*)::int AS n FROM beeper_attachments WHERE conversation_id = $1', [conversationId]);+ const afterCursor = await query('SELECT COUNT(*)::int AS n FROM beeper_sync_cursors WHERE account_id = $1', [ACCOUNT_ID]);+ expect(afterConv.rows[0].n).toBe(0);+ expect(afterMsg.rows[0].n).toBe(0);+ expect(afterPart.rows[0].n).toBe(0);+ expect(afterAttach.rows[0].n).toBe(0);+ expect(afterCursor.rows[0].n).toBe(0);+ });++ // #31's vaulted credential. Ciphertext is opaque to the DB, so this covers+ // only what the SCHEMA promises: one row per install (PRIMARY KEY on the+ // fixed id, upsert-replaced), a nullable expiry meaning "never expires", and+ // a provenance CHECK that refuses an unclassified credential.+ it('holds exactly one beeper_credentials row, with a nullable expiry and a checked source', async () => {+ const credentialId = `cred-${nonce}`;+ await query(+ `INSERT INTO beeper_credentials (id, token_enc, token_expires_at, scopes, source, client_id)+ VALUES ($1, 'v1:iv:tag:ct', NULL, 'read write', 'pasted', '')`,+ [credentialId],+ );+ await query(+ `INSERT INTO beeper_credentials (id, token_enc, token_expires_at, scopes, source, client_id)+ VALUES ($1, 'v1:iv2:tag2:ct2', NOW() + INTERVAL '1 day', 'read write', 'oauth', 'client-1')+ ON CONFLICT (id) DO UPDATE SET+ token_enc = EXCLUDED.token_enc,+ token_expires_at = EXCLUDED.token_expires_at,+ source = EXCLUDED.source,+ client_id = EXCLUDED.client_id`,+ [credentialId],+ );+ const { rows } = await query('SELECT * FROM beeper_credentials WHERE id = $1', [credentialId]);+ expect(rows).toHaveLength(1);+ expect(rows[0].source).toBe('oauth');+ expect(rows[0].token_expires_at).not.toBeNull();++ await expect(+ query(+ `INSERT INTO beeper_credentials (id, token_enc, source) VALUES ($1, 'v1:x:y:z', 'guessed')`,+ [`${credentialId}-bad`],+ ),+ ).rejects.toThrow();++ await query('DELETE FROM beeper_credentials WHERE id = $1', [credentialId]);+ });++ // #36's outbound outbox. The CHECK is the schema's half of "a failed send is+ // never re-sent in place": every state the send path can reach is in the set,+ // and anything else — including a hopeful `queued` from a later refactor —+ // fails loudly at the boundary instead of quietly bypassing the send gate.+ it('accepts every outbox state, rejects one outside the set, and cascades with its conversation', async () => {+ await query(+ `INSERT INTO beeper_accounts (account_id, network, display_name, status, bridge_id)+ VALUES ($1, 'Example Network', 'Example Account', 'connected', 'example-bridge')`,+ [ACCOUNT_ID],+ );+ const { rows: convRows } = await query(+ `INSERT INTO beeper_conversations (account_id, network, source_chat_id, title, type)+ VALUES ($1, 'Example Network', 'chat-outbox', 'Example Chat', 'single')+ RETURNING id`,+ [ACCOUNT_ID],+ );+ const conversationId = convRows[0].id;++ for (const state of ['draft', 'approved', 'sending', 'awaiting-confirmation', 'sent', 'failed']) {+ // eslint-disable-next-line no-await-in-loop -- ordered inserts, one per state+ await query(+ `INSERT INTO beeper_outbox (conversation_id, chat_id, body, state)+ VALUES ($1, 'chat-outbox', 'placeholder body', $2)`,+ [conversationId, state],+ );+ }++ await expect(+ query(+ `INSERT INTO beeper_outbox (conversation_id, chat_id, body, state)+ VALUES ($1, 'chat-outbox', 'placeholder body', 'queued')`,+ [conversationId],+ ),+ ).rejects.toThrow();++ const before = await query('SELECT COUNT(*)::int AS n FROM beeper_outbox WHERE conversation_id = $1', [conversationId]);+ expect(before.rows[0].n).toBe(6);++ await query('DELETE FROM beeper_accounts WHERE account_id = $1', [ACCOUNT_ID]);+ const after = await query('SELECT COUNT(*)::int AS n FROM beeper_outbox WHERE conversation_id = $1', [conversationId]);+ expect(after.rows[0].n).toBe(0);+ });++ it('rejects a participant observed_via outside the participant-list/message-sender set', async () => {+ await query(+ `INSERT INTO beeper_accounts (account_id, network, display_name, status, bridge_id)+ VALUES ($1, 'Example Network', 'Example Account', 'connected', 'example-bridge')`,+ [ACCOUNT_ID],+ );+ const { rows: convRows } = await query(+ `INSERT INTO beeper_conversations (account_id, network, source_chat_id, title, type)+ VALUES ($1, 'Example Network', 'chat-bad-observed', 'Example Chat', 'single')+ RETURNING id`,+ [ACCOUNT_ID],+ );+ await expect(+ query(+ `INSERT INTO beeper_participants (conversation_id, source_user_id, observed_via)+ VALUES ($1, 'user-1', 'guessed')`,+ [convRows[0].id],+ ),+ ).rejects.toThrow();+ await query('DELETE FROM beeper_accounts WHERE account_id = $1', [ACCOUNT_ID]);+ });++ // #96 — the one backfill statement at the end of `beeperDdl`, which promotes+ // every pre-existing hand-made link (cached only on the mirror row, and so+ // destroyed by a purge) to a durable `kind='beeper-user'` claim. Runs on+ // every boot, so idempotence is the contract, not a nicety.+ describe('the beeper-user backfill (#96)', () => {+ const runBackfill = async () => {+ const { beeperDdl } = await import('./beeper.js');+ const statements = beeperDdl.filter((sql) => /INSERT INTO tribe_identities/.test(sql));+ expect(statements, 'beeperDdl no longer carries the beeper-user backfill').toHaveLength(1);+ await query(statements[0]);+ };++ // The statement's own guard is global — "any beeper-user claim exists"+ // means this install is already past the one-shot promotion — so a fixture+ // must start from a database where nothing has been promoted yet. Cheap+ // and safe: this is portos_test, and every claim these suites write is+ // torn down with its person.+ const clearClaims = () => query(`DELETE FROM tribe_identities WHERE kind = 'beeper-user'`);++ it('promotes a cached link to a claim, skips soft-deleted people, and re-runs cleanly', async () => {+ await clearClaims();+ await query(+ `INSERT INTO beeper_accounts (account_id, network, display_name, status, bridge_id)+ VALUES ($1, 'Example Network', 'Example Account', 'connected', 'example-bridge')`,+ [ACCOUNT_ID],+ );+ const { rows: convRows } = await query(+ `INSERT INTO beeper_conversations (account_id, network, source_chat_id, title, type)+ VALUES ($1, 'Example Network', 'chat-backfill', 'Example Chat', 'single')+ RETURNING id`,+ [ACCOUNT_ID],+ );+ const conversationId = convRows[0].id;++ const { rows: peopleRows } = await query(+ `INSERT INTO tribe_people (name) VALUES ($1), ($2) RETURNING id, name`,+ [`${nonce} Example Live Person`, `${nonce} Example Removed Person`],+ );+ const live = peopleRows.find((r) => r.name.endsWith('Live Person')).id;+ const removed = peopleRows.find((r) => r.name.endsWith('Removed Person')).id;+ await query('UPDATE tribe_people SET deleted = TRUE WHERE id = $1', [removed]);++ // Three pre-#96 rows: one hand-linked, one linked to a soft-deleted+ // person, one never linked at all.+ await query(+ `INSERT INTO beeper_participants (conversation_id, source_user_id, display_name, handle, tribe_person_id, observed_via)+ VALUES ($1, 'backfill-user-live', 'Example Live Person', '', $2, 'message-sender'),+ ($1, 'backfill-user-removed', 'Example Removed Person', '', $3, 'message-sender'),+ ($1, 'backfill-user-unlinked', 'Example Unlinked Person', '', NULL, 'message-sender')`,+ [conversationId, live, removed],+ );++ await runBackfill();++ const claims = async (sourceUserId) => {+ const { rows } = await query(+ `SELECT person_id FROM tribe_identities+ WHERE kind = 'beeper-user' AND network = $1 AND handle = $2`,+ [ACCOUNT_ID, sourceUserId],+ );+ return rows;+ };+ expect(await claims('backfill-user-live')).toEqual([{ person_id: live }]);+ expect(await claims('backfill-user-removed')).toEqual([]);+ expect(await claims('backfill-user-unlinked')).toEqual([]);++ // Idempotent: a second run (ensureSchema re-runs the whole DDL on every+ // call, not just per boot) neither errors nor duplicates the claim.+ await expect(runBackfill()).resolves.not.toThrow();+ expect(await claims('backfill-user-live')).toEqual([{ person_id: live }]);++ // …and it never re-points a claim the app owns: once any beeper-user+ // claim exists this install is past the promotion, so a link the user+ // has since moved by hand stays moved.+ await query('UPDATE tribe_people SET deleted = FALSE WHERE id = $1', [removed]);+ await query(+ `UPDATE tribe_identities SET person_id = $1, source = 'user'+ WHERE kind = 'beeper-user' AND network = $2 AND handle = 'backfill-user-live'`,+ [removed, ACCOUNT_ID],+ );+ await runBackfill();+ expect(await claims('backfill-user-live')).toEqual([{ person_id: removed }]);++ await query('DELETE FROM tribe_people WHERE id = ANY($1::uuid[])', [[live, removed]]);+ await query('DELETE FROM beeper_accounts WHERE account_id = $1', [ACCOUNT_ID]);+ });++ it('picks the most recently updated link when one Beeper user was hand-linked to two people', async () => {+ await clearClaims();+ await query(+ `INSERT INTO beeper_accounts (account_id, network, display_name, status, bridge_id)+ VALUES ($1, 'Example Network', 'Example Account', 'connected', 'example-bridge')`,+ [ACCOUNT_ID],+ );+ const conversationIds = [];+ for (const chat of ['chat-backfill-dupe-1', 'chat-backfill-dupe-2']) {+ // eslint-disable-next-line no-await-in-loop -- two ordered fixture inserts+ const { rows } = await query(+ `INSERT INTO beeper_conversations (account_id, network, source_chat_id, title, type)+ VALUES ($1, 'Example Network', $2, 'Example Chat', 'single')+ RETURNING id`,+ [ACCOUNT_ID, chat],+ );+ conversationIds.push(rows[0].id);+ }+ const { rows: peopleRows } = await query(+ `INSERT INTO tribe_people (name) VALUES ($1), ($2) RETURNING id, name`,+ [`${nonce} Example Claimed Person`, `${nonce} Example Other Person`],+ );+ const claimed = peopleRows.find((r) => r.name.endsWith('Claimed Person')).id;+ const other = peopleRows.find((r) => r.name.endsWith('Other Person')).id;++ // The SAME Beeper user hand-linked to two different people in two+ // conversations — the ambiguity the DISTINCT ON resolves, and the case+ // that would otherwise make one statement insert the same+ // (kind, network, handle) twice. The older row is the one that must lose.+ await query(+ `INSERT INTO beeper_participants (conversation_id, source_user_id, display_name, handle, tribe_person_id, observed_via, updated_at)+ VALUES ($1, 'backfill-user-dupe', 'Example Other Person', '', $3, 'message-sender', NOW() - INTERVAL '1 day'),+ ($2, 'backfill-user-dupe', 'Example Claimed Person', '', $4, 'message-sender', NOW())`,+ [conversationIds[0], conversationIds[1], other, claimed],+ );++ await expect(runBackfill()).resolves.not.toThrow();++ const { rows } = await query(+ `SELECT person_id, source FROM tribe_identities+ WHERE kind = 'beeper-user' AND network = $1 AND handle = 'backfill-user-dupe'`,+ [ACCOUNT_ID],+ );+ expect(rows).toEqual([{ person_id: claimed, source: 'backfill' }]);++ await query('DELETE FROM tribe_people WHERE id = ANY($1::uuid[])', [[claimed, other]]);+ await query('DELETE FROM beeper_accounts WHERE account_id = $1', [ACCOUNT_ID]);+ });+ });++ it('enforces UNIQUE (account_id, source_chat_id) on beeper_conversations', async () => {+ await query(+ `INSERT INTO beeper_accounts (account_id, network, display_name, status, bridge_id)+ VALUES ($1, 'Example Network', 'Example Account', 'connected', 'example-bridge')`,+ [ACCOUNT_ID],+ );+ await query(+ `INSERT INTO beeper_conversations (account_id, network, source_chat_id, title, type)+ VALUES ($1, 'Example Network', 'chat-dupe', 'Example Chat', 'single')`,+ [ACCOUNT_ID],+ );+ await expect(+ query(+ `INSERT INTO beeper_conversations (account_id, network, source_chat_id, title, type)+ VALUES ($1, 'Example Network', 'chat-dupe', 'Example Chat Again', 'single')`,+ [ACCOUNT_ID],+ ),+ ).rejects.toThrow();+ await query('DELETE FROM beeper_accounts WHERE account_id = $1', [ACCOUNT_ID]);+ });+});diff --git a/server/lib/db/schema/beeper.js b/server/lib/db/schema/beeper.jsnew file mode 100644index 0000000000..01b3d22e52--- /dev/null+++ b/server/lib/db/schema/beeper.js@@ -0,0 +1,357 @@+// Beeper conversation mirror DDL (#27). Machine-local mirror of the Beeper+// Desktop API (accounts, conversations, messages, participants, attachment+// metadata, and per-chat sync cursors), plus two tables that are not mirror+// data: the credential vault (`beeper_credentials`, #31) and the send outbox+// (`beeper_outbox`). Carries the schema decisions from the Beeper wayfinder+// map (#1); rationale lives on #7 (store shape), #10 (Tribe handles), #12+// (transport), #13 (attachments) — not repeated here.+//+// NEVER FEDERATED — enforced by beeperNeverFederates.test.js. No table here+// gets a `sync_sequence` column, a PEER_SUBSCRIBABLE_KINDS entry, a dataSync+// snapshot category, or a PORTOS_SCHEMA_VERSIONS entry.+//+// Deletions from the source are tombstones, not removals: a message the+// source unsends keeps its row, body, and attachments and gains `unsent_at`+// — the column is named for what the source actually reports, and an archive+// that quietly forgets a caption while keeping its photo is not trustworthy.+// Because the inbound tombstone is `unsent_at`, the federation guard keys on+// `sync_sequence` alone and needs no soft-delete exemption. See the ADR+// landing alongside #7 for the full argument.+export const beeperDdl = [+ // The account roster the settings card renders from with Beeper closed+ // (#11 left the store to this issue). `loginID` is never stored — it is+ // the bridge login credential's own id, not something PortOS needs to+ // read a chat.+ `CREATE TABLE IF NOT EXISTS beeper_accounts (+ account_id TEXT PRIMARY KEY,+ network TEXT NOT NULL DEFAULT '',+ display_name TEXT NOT NULL DEFAULT '',+ status TEXT NOT NULL DEFAULT '',+ bridge_id TEXT NOT NULL DEFAULT '',+ last_seen_at TIMESTAMPTZ,+ created_at TIMESTAMPTZ DEFAULT NOW(),+ updated_at TIMESTAMPTZ DEFAULT NOW()+ )`,++ // The ONE Beeper credential this install holds (#31). AES-256-GCM ciphertext+ // via `server/lib/vaultCrypto.js` — never `settings.json`, never a plaintext+ // file, never a log line. Single-row by construction (`id = 'default'`),+ // because PortOS models one Beeper account per install (#1 charting decision+ // 8); a second row would silently create a second identity no surface can+ // choose between.+ //+ // `token_expires_at NULL` means "never expires" — the state only Beeper's own+ // UI can mint, and the reason pasting a token is a first-class alternative to+ // OAuth rather than a fallback (#11 decision 3). There is no refresh grant, so+ // an expired token is re-connected, never refreshed. `scopes` and `client_id`+ // are stored for the disconnect-time revocation call, and are NEVER surfaced+ // to a client payload; `client_id` is a public-client identifier from dynamic+ // registration, not a secret, and is empty for a pasted token.+ `CREATE TABLE IF NOT EXISTS beeper_credentials (+ id TEXT PRIMARY KEY,+ token_enc TEXT NOT NULL,+ token_expires_at TIMESTAMPTZ,+ scopes TEXT NOT NULL DEFAULT '',+ source TEXT NOT NULL DEFAULT 'pasted' CHECK (source IN ('oauth','pasted')),+ client_id TEXT NOT NULL DEFAULT '',+ created_at TIMESTAMPTZ DEFAULT NOW(),+ updated_at TIMESTAMPTZ DEFAULT NOW()+ )`,++ // Synthetic UUID primary key so a later cross-network merge never has to+ // repoint every child row — `source_chat_id` is the Beeper-side identity.+ // Pin/archive/mute/low-priority/unread state is Beeper's own state, mirrored+ // read-only; PortOS never invents a second source of truth for it. `type`+ // is intentionally unconstrained: db.catalogDdlParity.test.js forbids a+ // hardcoded enum constraint on any `type` column in this schema (the same+ // rule that keeps catalog_ingredients.type app-layer-gated), so a new+ // Beeper chat type never needs a two-file migration to accept.+ `CREATE TABLE IF NOT EXISTS beeper_conversations (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ account_id TEXT NOT NULL REFERENCES beeper_accounts (account_id) ON DELETE CASCADE,+ network TEXT NOT NULL DEFAULT '',+ source_chat_id TEXT NOT NULL,+ title TEXT NOT NULL DEFAULT '',+ type TEXT NOT NULL DEFAULT 'single',+ is_group BOOLEAN NOT NULL DEFAULT FALSE,+ is_pinned BOOLEAN NOT NULL DEFAULT FALSE,+ is_archived BOOLEAN NOT NULL DEFAULT FALSE,+ is_low_priority BOOLEAN NOT NULL DEFAULT FALSE,+ is_muted BOOLEAN NOT NULL DEFAULT FALSE,+ last_activity TIMESTAMPTZ,+ unread_count INTEGER NOT NULL DEFAULT 0,+ seen_at TIMESTAMPTZ,+ created_at TIMESTAMPTZ DEFAULT NOW(),+ updated_at TIMESTAMPTZ DEFAULT NOW(),+ UNIQUE (account_id, source_chat_id)+ )`,+ // Additive, for an install whose `beeper_conversations` predates the+ // column — same shape as `beeper_messages.is_sender` below. `seen_at` is+ // the LOCAL "seen in PortOS" watermark (#83), and unlike every other column+ // on this row it is never written by the sweep (`upsertConversation` in+ // beeperSync.js never touches it) and never mirrored from Beeper: opening a+ // thread stamps it with `NOW()` (`beeperConversations.markConversationSeen`)+ // and nothing else does. The read model compares it against+ // `COALESCE(last_activity, created_at)` at every surface that shows an+ // unread badge (`shapeConversation`, `listConversations`'s `unreadOnly`+ // filter, `listNetworks`'s aggregates) — `seen_at >= that activity` means+ // "nothing has landed since the user last opened this", which is what+ // survives the sweep overwriting `unread_count` wholesale on every run: a+ // watermark that instead zeroed `unread_count` directly would be reverted+ // by the very next sweep, and one that lived only in the browser would not+ // reach the rail aggregates or a second device. NULL means "never opened in+ // PortOS", which reads as unread whenever Beeper's own `unread_count` says+ // so. This NEVER writes to Beeper — no read receipt crosses the wire; a+ // settings toggle to also send one is out of scope here (see the TODO on+ // `markConversationSeen`).+ `ALTER TABLE beeper_conversations ADD COLUMN IF NOT EXISTS seen_at TIMESTAMPTZ`,+ // `idx_beeper_conversations_account_activity (account_id, last_activity DESC)`+ // served no query: listConversations (services/beeperConversations.js) has+ // no account_id filter, and its ORDER BY / keyset walk sorts on+ // `COALESCE(last_activity, created_at)`, never the raw column — so every+ // page was an unindexed sort. Repointed at the expression the keyset walk+ // actually uses (audit cluster 06, indexes and query plans).+ `DROP INDEX IF EXISTS idx_beeper_conversations_account_activity`,+ // #81: `COALESCE(last_activity, created_at)` fell back to the MIRROR ROW's+ // mint time for a chat with no real Beeper activity, not to "this chat has+ // no activity" — so a batch of chats swept (and left activity-less) in the+ // same pass sorted at the TOP of the Inbox by their shared, recent+ // `created_at`, exactly the symptom #81 reported. `'epoch'::timestamptz` is+ // the sentinel that fixes it: it keeps the row-value keyset tuple shape (a+ // real `NULLS LAST` cannot — see `listConversations`), and being older than+ // any real timestamp sorts every activity-less chat LAST under `DESC`+ // instead of wherever its row happened to be minted.+ `DROP INDEX IF EXISTS idx_beeper_conversations_activity_keyset`,+ `CREATE INDEX IF NOT EXISTS idx_beeper_conversations_activity_epoch_keyset ON beeper_conversations ((COALESCE(last_activity, 'epoch'::timestamptz)) DESC, id DESC)`,++ // Keyed on Beeper's own message id (TEXT — bridges do not guarantee a UUID+ // shape). Full bodies persist machine-local, per the store ADR.+ //+ // `is_sender` mirrors the API's own `Message.isSender` and is the ONLY+ // reliable way to tell an outbound message from an inbound one: `senderID`+ // cannot be compared against the local user, because `accounts[].user.id`+ // differs from `senderID` on every network (#2). Without the column a chat+ // surface has to guess which side of the thread a message belongs on, and a+ // guess is wrong on exactly the networks that matter most.+ `CREATE TABLE IF NOT EXISTS beeper_messages (+ id TEXT PRIMARY KEY,+ conversation_id UUID NOT NULL REFERENCES beeper_conversations (id) ON DELETE CASCADE,+ sender_id TEXT NOT NULL DEFAULT '',+ body TEXT NOT NULL DEFAULT '',+ sent_at TIMESTAMPTZ,+ edited_at TIMESTAMPTZ,+ unsent_at TIMESTAMPTZ,+ sort_key TEXT NOT NULL DEFAULT '',+ is_sender BOOLEAN NOT NULL DEFAULT FALSE,+ created_at TIMESTAMPTZ DEFAULT NOW(),+ updated_at TIMESTAMPTZ DEFAULT NOW()+ )`,+ // Additive, for an install whose `beeper_messages` predates the column —+ // `CREATE TABLE IF NOT EXISTS` is a no-op there, so the inline declaration+ // above only reaches a FRESH install. Same shape as catalog.js's+ // `chunk_index` / `parent_scrap_id`, and the reason the default is FALSE+ // rather than NULL: an unbackfilled row renders as inbound, which is the+ // right way round for a mirror that is mostly other people's messages.+ `ALTER TABLE beeper_messages ADD COLUMN IF NOT EXISTS is_sender BOOLEAN NOT NULL DEFAULT FALSE`,+ // `idx_beeper_messages_conversation_sort (conversation_id, sort_key)` served+ // no query — `sort_key` is written on ingest and never read back. A thread+ // page (listMessages) and the "latest message" LATERAL each conversation+ // row's list preview needs (listConversations) both order on+ // `COALESCE(sent_at, created_at) DESC, id DESC` within one `conversation_id`,+ // so ONE index serves both call sites (audit cluster 06).+ `DROP INDEX IF EXISTS idx_beeper_messages_conversation_sort`,+ `CREATE INDEX IF NOT EXISTS idx_beeper_messages_conversation_order ON beeper_messages (conversation_id, (COALESCE(sent_at, created_at)) DESC, id DESC)`,++ // `observed_via` is required, not cosmetic: the Beeper API's participant+ // lists truncate (20 in a chat listing, 100 in a single-chat GET) with no+ // participants endpoint and no cursor, so a row set is always a possible+ // subset. Without this column a half-empty roster reads as a complete one.+ // `tribe_person_id` is nullable and ON DELETE SET NULL — removing a Tribe+ // person un-links the handle rather than deleting the mirrored participant.+ `CREATE TABLE IF NOT EXISTS beeper_participants (+ conversation_id UUID NOT NULL REFERENCES beeper_conversations (id) ON DELETE CASCADE,+ source_user_id TEXT NOT NULL,+ display_name TEXT NOT NULL DEFAULT '',+ handle TEXT NOT NULL DEFAULT '',+ tribe_person_id UUID REFERENCES tribe_people (id) ON DELETE SET NULL,+ observed_via TEXT NOT NULL CHECK (observed_via IN ('participant-list','message-sender')),+ created_at TIMESTAMPTZ DEFAULT NOW(),+ updated_at TIMESTAMPTZ DEFAULT NOW(),+ PRIMARY KEY (conversation_id, source_user_id)+ )`,+ `CREATE INDEX IF NOT EXISTS idx_beeper_participants_tribe_person ON beeper_participants (tribe_person_id) WHERE tribe_person_id IS NOT NULL`,++ // `(conversation_id, message_id, idx)` addresses one attachment within a+ // message's attachment array. `mxc_id` is the source attachment identifier+ // (typically an mxc:// URL) and the DURABLE reference the byte mirror (#37)+ // resolves against `GET /v1/assets/serve`; `srcURL` is NEVER persisted here —+ // it carries its own documented decay warning and is only a cache-state hint,+ // not a durable reference. `keep` exempts an attachment from the least-+ // recently-viewed eviction that bounds the on-disk byte budget.+ `CREATE TABLE IF NOT EXISTS beeper_attachments (+ conversation_id UUID NOT NULL REFERENCES beeper_conversations (id) ON DELETE CASCADE,+ message_id TEXT NOT NULL REFERENCES beeper_messages (id) ON DELETE CASCADE,+ idx INTEGER NOT NULL,+ mxc_id TEXT,+ mime_type TEXT NOT NULL DEFAULT '',+ byte_length BIGINT,+ file_name TEXT NOT NULL DEFAULT '',+ width INTEGER,+ height INTEGER,+ last_viewed_at TIMESTAMPTZ,+ keep BOOLEAN NOT NULL DEFAULT FALSE,+ local_path TEXT,+ fetched_at TIMESTAMPTZ,+ unavailable_at TIMESTAMPTZ,+ fetch_error TEXT,+ created_at TIMESTAMPTZ DEFAULT NOW(),+ updated_at TIMESTAMPTZ DEFAULT NOW(),+ PRIMARY KEY (conversation_id, message_id, idx)+ )`,+ // Every attachment route addresses one row by `(message_id, idx)`+ // (`beeperAttachments.js`'s `loadRow`, `setAttachmentKeep`, `markUnavailable`,+ // the acquire/release paths) — the PK above leads with `conversation_id`,+ // which none of those callers have on hand, so every lookup scanned the+ // table. Leads with `message_id` to match the actual access pattern (audit+ // cluster 06).+ `CREATE INDEX IF NOT EXISTS idx_beeper_attachments_message ON beeper_attachments (message_id, idx)`,+ // The byte-mirror columns (#37), declared inline above for a fresh install+ // and added here for one whose `beeper_attachments` predates them —+ // `CREATE TABLE IF NOT EXISTS` is a no-op on an existing table, the same+ // reason `beeper_messages.is_sender` carries an ALTER of its own.+ //+ // `local_path` is the store-relative path of the mirrored bytes+ // (`<sha256 prefix>/<sha256>.<ext>`), NULL while only the reference is held;+ // that NULL is the lazy mirror's whole state machine, so it is never+ // defaulted to ''. `unavailable_at`/`fetch_error` record a TERMINAL refusal+ // from the source (`GET /v1/assets/serve` answers 502 for media the network+ // has aged out, mapped to ASSET_UNAVAILABLE) — it is what stops a re-fetch+ // loop on every render AND what exempts the row from eviction, because bytes+ // Beeper can no longer supply are the only copy left.+ `ALTER TABLE beeper_attachments ADD COLUMN IF NOT EXISTS local_path TEXT`,+ `ALTER TABLE beeper_attachments ADD COLUMN IF NOT EXISTS fetched_at TIMESTAMPTZ`,+ `ALTER TABLE beeper_attachments ADD COLUMN IF NOT EXISTS unavailable_at TIMESTAMPTZ`,+ `ALTER TABLE beeper_attachments ADD COLUMN IF NOT EXISTS fetch_error TEXT`,+ // `sha256` was written on every fetch (`ensureAttachmentBytes`) but never+ // read back anywhere — the content-addressed path is built from the hash+ // `streamAssetToStore` just computed, not from this column. Dropped; the+ // sha256 VALUE stays in use for the content-addressed path (`local_path`),+ // only the column goes (audit cluster 06 decision 3).+ `ALTER TABLE beeper_attachments DROP COLUMN IF EXISTS sha256`,+ `DROP INDEX IF EXISTS idx_beeper_attachments_sha256`,+ // The budget sweep sums mirrored bytes (`idx_beeper_attachments_local`) and+ // walks least-recently-viewed first among rows that HAVE bytes on disk+ // (`idx_beeper_attachments_eviction_candidates`) — `evictToBudget`'s+ // candidate query filters `local_path IS NOT NULL AND keep = FALSE AND+ // unavailable_at IS NULL AND mxc_id IS NOT NULL` and orders by+ // `last_viewed_at ASC NULLS FIRST, fetched_at ASC NULLS FIRST` (a+ // never-viewed row is the BEST eviction candidate, not the worst — it is+ // ordered first on purpose). The old index below was predicated on+ // `keep = FALSE` alone (no `local_path IS NOT NULL`, so a bytes-less row+ // could rank into the scan) with the btree default NULLS LAST for an+ // ascending column, the opposite of what the query asks for — it could not+ // serve this ORDER BY at all. Predicate and NULLS placement now match the+ // query exactly (audit cluster 06).+ `CREATE INDEX IF NOT EXISTS idx_beeper_attachments_local ON beeper_attachments (local_path) WHERE local_path IS NOT NULL`,+ `DROP INDEX IF EXISTS idx_beeper_attachments_eviction`,+ `CREATE INDEX IF NOT EXISTS idx_beeper_attachments_eviction_candidates ON beeper_attachments (last_viewed_at ASC NULLS FIRST, fetched_at ASC NULLS FIRST) WHERE keep = FALSE AND local_path IS NOT NULL`,++ // `chat_id` is the Beeper-side chat id (matches `source_chat_id` above),+ // not the synthetic `beeper_conversations.id` — the backfill sweep calls+ // the upstream List Messages API by the source's own id, and a cursor can+ // exist before the conversation row does. Rows and cursor commit in one+ // transaction with whatever sync wrote them (app-level contract; this+ // table only defines the shape).+ `CREATE TABLE IF NOT EXISTS beeper_sync_cursors (+ account_id TEXT NOT NULL REFERENCES beeper_accounts (account_id) ON DELETE CASCADE,+ chat_id TEXT NOT NULL,+ cursor TEXT,+ last_activity TIMESTAMPTZ,+ last_swept_at TIMESTAMPTZ,+ PRIMARY KEY (account_id, chat_id)+ )`,++ // The outbound OUTBOX (#36, decided on #8). A row is written BEFORE the+ // `POST /v1/chats/{chatID}/messages` that sends it, so intent survives a+ // crash between the click and the POST, and one row is the serialization+ // point that stops a double-click double-posting.+ //+ // `chat_id` is denormalized from `beeper_conversations.source_chat_id` at+ // creation: the send addresses Beeper's own chat id, and the row must stay+ // readable as a record of what was sent even if the mirror row is later+ // resweep-replaced. `pending_message_id` is what the async send returns;+ // `message_id` is the resolved id the confirmation (socket `message.upserted`+ // or the 30s `GET` fallback) settles on. They are DISTINCT columns because a+ // send that never confirms must stay distinguishable from one that did.+ //+ // The state CHECK is deliberate — unlike `beeper_conversations.type`, these+ // values are PortOS's own state machine, not a Beeper vocabulary that can+ // grow upstream, so a new state SHOULD cost a schema change. `draft` has no+ // writer in the MVP (#8 decision 7 keeps the composer buffer client-side);+ // it is the state a later persisted/AI-assisted draft would occupy, and the+ // send gate keys on `approved` so nothing can send from it.+ //+ // A failed row is never retried and never mutated back into a sendable+ // state: Beeper has no idempotency key on send, so re-sending is a NEW row+ // and the failed one stays visible.+ `CREATE TABLE IF NOT EXISTS beeper_outbox (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ conversation_id UUID NOT NULL REFERENCES beeper_conversations (id) ON DELETE CASCADE,+ chat_id TEXT NOT NULL,+ body TEXT NOT NULL,+ state TEXT NOT NULL DEFAULT 'draft' CHECK (state IN ('draft','approved','sending','awaiting-confirmation','sent','failed')),+ pending_message_id TEXT,+ message_id TEXT,+ error_code TEXT,+ error_message TEXT,+ created_at TIMESTAMPTZ DEFAULT NOW(),+ approved_at TIMESTAMPTZ,+ sent_at TIMESTAMPTZ,+ updated_at TIMESTAMPTZ DEFAULT NOW()+ )`,+ `CREATE INDEX IF NOT EXISTS idx_beeper_outbox_conversation_state ON beeper_outbox (conversation_id, state, created_at DESC)`,++ // #96 backfill — one idempotent statement, LAST in this array because it+ // reads both `beeper_participants` (created above) and `tribe_identities`+ // (created in the phase-1 `tribeDdl` list, which `ensureSchemaImpl` runs in+ // full before this one).+ //+ // Every link an existing install made by hand before `kind='beeper-user'`+ // existed lives ONLY in the `beeper_participants.tribe_person_id` cache, so+ // the next purge + resweep would still lose it. This promotes each of those+ // to a durable claim. It is not in `server/scripts/init-db.sql`: that file+ // provisions a FRESH database, where there is no participant row to+ // promote, and the parity test (`server/lib/db.catalogDdlParity.test.js`)+ // compares table/index/trigger shape, which this statement does not touch.+ //+ // - The `NOT EXISTS` guard makes it ONE-SHOT. `ensureSchema()` does not+ // memoize (it only collapses concurrent callers), and every beeperTribe+ // service call re-runs the whole list through `ensureReady()` — fine for+ // a list of no-op DDL parses, not for a join across the participant+ // mirror. The guard is an uncorrelated subquery, so the planner+ // evaluates it once as a one-time filter and skips the scan entirely+ // the moment ANY beeper-user claim exists. The app writes one on every+ // link from here on, so "a claim exists" is exactly "this install is+ // past the promotion", and the catch-up never needs to run again.+ // - `ON CONFLICT DO NOTHING` keeps it safe even if that guard is ever+ // loosened: it never overwrites a claim the app has since written —+ // `linkParticipant` is the authority, this is only a catch-up.+ // - `DISTINCT ON` + `ORDER BY updated_at DESC` picks ONE row per+ // (account, source_user_id) deterministically when the same Beeper user+ // was hand-linked to different people in different conversations: the+ // most recently touched link wins, matching the table's own+ // "last explicit link wins" semantics.+ // - the `tribe_people` join drops soft-deleted persons (`tribe.deletePerson`+ // never fires the FK cascade), so a purge does not resurrect a link to+ // somebody the user deleted.+ `INSERT INTO tribe_identities (person_id, kind, network, handle, source, linked_at)+ SELECT DISTINCT ON (c.account_id, p.source_user_id)+ p.tribe_person_id, 'beeper-user', c.account_id, p.source_user_id, 'backfill', NOW()+ FROM beeper_participants p+ JOIN beeper_conversations c ON c.id = p.conversation_id+ JOIN tribe_people tp ON tp.id = p.tribe_person_id AND tp.deleted = FALSE+ WHERE p.tribe_person_id IS NOT NULL AND c.account_id <> ''+ AND NOT EXISTS (SELECT 1 FROM tribe_identities WHERE kind = 'beeper-user')+ ORDER BY c.account_id, p.source_user_id, p.updated_at DESC+ ON CONFLICT (kind, network, handle) DO NOTHING`,+];diff --git a/server/lib/db/schema/index.js b/server/lib/db/schema/index.jsindex ef0cfb4980..ed39f8bc93 100644--- a/server/lib/db/schema/index.js+++ b/server/lib/db/schema/index.js@@ -30,6 +30,7 @@ import { loraDdl } from './lora.js';import { privacyDdl } from './privacy.js';import { stackerNewsDdl } from './stackerNews.js';import { xDdl } from './x.js';+import { beeperDdl } from './beeper.js';import { auditDdl, auditedTables, buildAuditTriggers } from './audit.js';export {@@ -51,6 +52,7 @@ export {privacyDdl,stackerNewsDdl,xDdl,+ beeperDdl,auditDdl,auditedTables,buildAuditTriggers,@@ -74,6 +76,8 @@ export function buildUpgradeDdl() {// Phase 2 — the `catalogDDL` list: catalog + all creative-app tables, then the// record_audit table/function, then the per-table audit triggers. catalog_user_types// is threaded in AFTER the media block to match its original position (see catalog.js).+// `beeperDdl` is appended after `xDdl` (#27) — same external-mirror shape as+// stackerNews/x, added last of that group, before the audit block.export function buildCatalogDdl() {return [...catalogDdl,@@ -87,6 +91,7 @@ export function buildCatalogDdl() {...privacyDdl,...stackerNewsDdl,...xDdl,+ ...beeperDdl,...auditDdl,...buildAuditTriggers(),];diff --git a/server/lib/db/schema/schema.test.js b/server/lib/db/schema/schema.test.jsindex 6c353ffc81..59f013acd2 100644--- a/server/lib/db/schema/schema.test.js+++ b/server/lib/db/schema/schema.test.js@@ -28,6 +28,7 @@ const DOMAIN_ARRAYS = ['coreDdl', 'tribeDdl', 'humanActivityDdl', 'postDdl', 'commissionsDdl', 'userActionsDdl', 'aiGraphDdl','catalogDdl', 'catalogUserTypesDdl', 'mediaDdl', 'universesDdl','libraryDdl', 'pipelineDdl', 'writersRoomDdl', 'loraDdl', 'privacyDdl', 'stackerNewsDdl', 'xDdl',+ 'beeperDdl','auditDdl',];@@ -65,6 +66,7 @@ describe('db/schema barrel + composer (#2832)', () => {...schema.privacyDdl,...schema.stackerNewsDdl,...schema.xDdl,+ ...schema.beeperDdl,...schema.auditDdl,...buildAuditTriggers(),];diff --git a/server/lib/db/schema/tribe.js b/server/lib/db/schema/tribe.jsindex 63bbe0dbbd..ab3381116f 100644--- a/server/lib/db/schema/tribe.js+++ b/server/lib/db/schema/tribe.js@@ -59,4 +59,54 @@ export const tribeDdl = [PRIMARY KEY (person_id, memory_id))`,`CREATE INDEX IF NOT EXISTS idx_tribe_memory_links_memory ON tribe_memory_links (memory_id)`,+ // Network-scoped identity claims (#34, decided on #10) — the durable-handle+ // truth for matching an external counterpart (a Beeper participant today;+ // any future network-scoped source tomorrow) to a Tribe person. `kind`+ // distinguishes what TYPE of identifier `handle` is: 'phone' for a+ // phone-shaped handle (E.164-normalized, `network` left '' since the same+ // phone means the same person regardless of which network reported it) or+ // 'handle' for a network-specific username (network-scoped, so `network`+ // is required).+ //+ // `kind='beeper-user'` (#96) OVERLOADS the same three columns for the+ // participants Beeper reports neither a phone nor a username for: it+ // carries the participant's `beeper_conversations.account_id` in+ // `network` and its raw `beeper_participants.source_user_id` in `handle`.+ // That 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 a hand-made link recorded here outlives a purge + resweep+ // that deletes the `beeper_participants` cache row (`ON DELETE CASCADE`+ // off `beeper_conversations`). The ACCOUNT is the scope, not the network:+ // two bridge accounts on one network mint independent user-id spaces. The+ // overload is deliberate — no new column, no widened UNIQUE, and the same+ // `(kind, network, handle)` lookup serves it — and the writer/reader pair+ // lives in `server/services/beeperTribe.js` (`beeperUserScopeFor`).+ // A `source_user_id` is opaque, so it is stored RAW: unlike a phone or a+ // username it is never normalized by `server/lib/tribeMatch.js`.+ //+ // This also leaves room for a later `kind='email'` /+ // consolidation of the legacy tribe_people.emails[]/phones[] arrays into+ // this table without a second schema decision (deferred, #10 decision 7 —+ // not done here). A handle is lowercased, trimmed, leading '@' stripped+ // before it reaches this table (see server/lib/tribeMatch.js).+ // ON DELETE CASCADE: a HARD delete of a Tribe person also removes their+ // claimed identities, so a later re-link starts clean rather than+ // colliding on UNIQUE (kind, network, handle) with a stale row. The app's+ // only delete path (tribe.deletePerson) is a SOFT delete (`deleted =+ // TRUE`), which this cascade does NOT fire on — resolvePersonByIdentity+ // and resolveParticipantPerson (server/services/beeperTribe.js) instead+ // filter `tribe_people.deleted = FALSE` explicitly, and linkIdentity /+ // linkParticipant refuse to claim/link a soft-deleted personId.+ `CREATE TABLE IF NOT EXISTS tribe_identities (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ person_id UUID NOT NULL REFERENCES tribe_people(id) ON DELETE CASCADE,+ kind TEXT NOT NULL,+ network TEXT NOT NULL DEFAULT '',+ handle TEXT NOT NULL,+ source TEXT NOT NULL DEFAULT '',+ linked_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ created_at TIMESTAMPTZ DEFAULT NOW(),+ UNIQUE (kind, network, handle)+ )`,+ `CREATE INDEX IF NOT EXISTS idx_tribe_identities_person ON tribe_identities (person_id)`,];diff --git a/server/lib/index.js b/server/lib/index.jsindex 5bc9d471c3..bb618b7b43 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -305,6 +305,8 @@ export * from './persistentMindUsageLimit.js';export * from './agentScratchPaths.js';export * from './agentSentinel.js';export * from './bareUrl.js';+export * from './beeperAttachmentPaths.js';+export * from './beeperOAuthOrigin.js';export * from './bashResolver.js';export * from './branchUpstreamGuard.js';export * from './bufferedSpawn.js';diff --git a/server/lib/mediaValidation.js b/server/lib/mediaValidation.jsindex 3f21689ea2..b9c55e967c 100644--- a/server/lib/mediaValidation.js+++ b/server/lib/mediaValidation.js@@ -14,6 +14,7 @@ import { ASSESSABLE_RUNTIMES } from './localProviderRuntime.js';import { SWEEP_SCOPES } from './localModelAssessment.js';import { CAPABILITY_TEST_IDS } from './modelCapabilityTests.js';import { HF_REPO_ID_RE } from './huggingfaceLora.js';+import { isLoopbackHostname, parseBrowserOrigin } from './beeperOAuthOrigin.js';// iMessage ingestion config (#2151) — the `settings.imessage` slice. Sync is OFF// by default and only reads chat.db when enabled (needs macOS Full Disk Access).@@ -54,6 +55,106 @@ export const youtubeConfigSchema = z.object({intervalMinutes: z.number().int().min(1).max(1440).optional()});+// Beeper Desktop bridge ingestion + connection config (#30) — the+// `settings.beeper` slice. Sync is OFF by default and only talks to the local+// Beeper Desktop API (default http://127.0.0.1:23373) when enabled.+// Deliberately excludes `token`/`tokenExpiresAt`: the credential is stored+// AES-256-GCM encrypted in Postgres and written only through the connect routes+// (`beeperPastedTokenSchema` below, #31). This slice's Settings surface may show+// whether a token is configured but must never accept or persist one in+// plaintext. `.strict()` so a client attempting to+// smuggle a token through this generic route 400s instead of the value+// silently reaching disk.+// `baseUrl` is prefixed onto every Beeper API call AND the realtime WebSocket+// URL with `Authorization: Bearer <vault token>` attached (SEC-2) — so a value+// pointed at an attacker-controlled host turns one settings PUT into a+// credential exfiltration (SSRF). Loopback-only by default: `baseUrl` must+// parse as a bare `http(s)` origin (reusing `parseBrowserOrigin`, the same+// "not a path, not a query, not credentials" parser the OAuth redirect-origin+// gate uses) whose hostname is loopback (`isLoopbackHostname`, ditto reused+// rather than duplicated). `allowNonLoopbackBaseUrl` is the explicit opt-in+// for an install that genuinely runs Beeper Desktop elsewhere on the+// network — off by default, so the dangerous posture is never the shipped one.+// Both checks are re-applied inside `normalizeBaseUrl`+// (`server/services/beeperClient.js`) because `getSettings()` reads+// `settings.json` with no schema re-validation on read, so a hand-edited file+// is a second path to the same value this schema exists to block.+export const beeperSettingsSchema = z.object({+ enabled: z.boolean().optional(),+ intervalMinutes: z.number().int().min(1).max(1440).optional(),+ baseUrl: z.string().trim().min(1).max(500).optional(),+ attachmentBudgetGb: z.number().min(0.1).max(1000).optional(),+ allowNonLoopbackBaseUrl: z.boolean().optional(),+}).strict().superRefine((value, ctx) => {+ if (value.baseUrl === undefined) return;+ const parsed = parseBrowserOrigin(value.baseUrl);+ if (!parsed) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ['baseUrl'],+ message: 'baseUrl must be a bare http(s) origin (scheme, host, optional port — no path, query, or credentials)',+ });+ return;+ }+ if (!isLoopbackHostname(parsed.hostname) && value.allowNonLoopbackBaseUrl !== true) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ['baseUrl'],+ message: 'baseUrl must be a loopback origin unless allowNonLoopbackBaseUrl is set',+ });+ }+});++// Beeper connect flow (#31). The token NEVER rides the generic settings route+// (`beeperSettingsSchema` above is `.strict()` with no token field) — it is+// accepted here, on its own dedicated write path, and stored AES-256-GCM+// encrypted in Postgres by `services/beeperCredentials.js`. The upper bound is+// slack for an opaque bearer of unknown shape, not a claim about its format.+export const beeperPastedTokenSchema = z.object({+ token: z.string().trim().min(1).max(4096),+}).strict();++// The OAuth redirect target Beeper sends the browser back to. `state` is the+// PKCE-flow correlator minted by `startBeeperOAuth`; `code` is single-use. Both+// are validated before anything is looked up, and an authorization-server+// `error` is accepted so the callback can report a user-side denial instead of+// reading as a malformed request.+export const beeperOAuthCallbackSchema = z.object({+ code: z.string().trim().min(1).max(2048).optional(),+ state: z.string().trim().min(1).max(512).optional(),+ error: z.string().trim().max(256).optional(),+}).passthrough();++// The outbound outbox (#36, decided on #8). Two schemas for the two-step send:+// creating the row from the composer body, then sending it.+//+// `confirmFirstContact` is NOT a UI nicety riding on the request — it is the+// gate. The server refuses the first outbound message to a conversation unless+// it is explicitly `true`, so the flag has to survive validation as its own+// field rather than being inferred from anything else in the body. `.strict()`+// on both: an unrecognized field on a send request is a client bug worth a 400,+// not something to ignore on a path that talks to a real person.+export const beeperOutboxCreateSchema = z.object({+ conversationId: z.string().uuid(),+ body: z.string().min(1).max(10000),+}).strict();++export const beeperOutboxSendSchema = z.object({+ confirmFirstContact: z.boolean().optional(),+}).strict();++// The row id in the send path. Validated as a UUID before it reaches a query,+// so a malformed id answers 400 rather than a Postgres cast error rendered as+// a 500 — the same guard `routes/messages.js` puts on its draft ids.+export const beeperOutboxParamsSchema = z.object({+ id: z.string().uuid(),+}).strict();++export const beeperOutboxListSchema = z.object({+ conversationId: z.string().uuid(),+ limit: z.coerce.number().int().min(1).max(200).optional(),+}).strict();+// Shared LoRA-training parameter bounds — used by both the settings-slice// defaults and the per-run override on POST /api/lora-training/runs.const loraTrainingParamsSchema = z.object({diff --git a/server/lib/mediaValidation.test.js b/server/lib/mediaValidation.test.jsnew file mode 100644index 0000000000..25a22b0c76--- /dev/null+++ b/server/lib/mediaValidation.test.js@@ -0,0 +1,64 @@+import { describe, it, expect } from 'vitest';+import { beeperSettingsSchema } from './mediaValidation.js';++// SEC-2: `settings.beeper.baseUrl` is prefixed onto every Beeper API call AND+// the realtime WebSocket URL with `Authorization: Bearer <vault token>`+// attached, so a value pointed at an attacker-controlled host turns one+// settings PUT into a credential exfiltration (SSRF). Loopback-only by+// default; `allowNonLoopbackBaseUrl` is the explicit, off-by-default opt-in.+describe('beeperSettingsSchema — baseUrl (SEC-2)', () => {+ const parse = (baseUrl, extra = {}) => beeperSettingsSchema.safeParse({ baseUrl, ...extra });++ it('rejects a value that is not a URL at all', () => {+ expect(parse('not-a-url').success).toBe(false);+ });++ it('rejects a file: URL', () => {+ expect(parse('file:///etc/passwd').success).toBe(false);+ });++ it('rejects a non-http(s) scheme', () => {+ expect(parse('ftp://host').success).toBe(false);+ });++ it('rejects a bare hostname with no scheme', () => {+ expect(parse('example.com').success).toBe(false);+ });++ it('rejects a non-loopback http(s) origin without the opt-in', () => {+ expect(parse('https://example.com').success).toBe(false);+ expect(parse('http://example.com:23373').success).toBe(false);+ });++ it('accepts the shipped loopback default', () => {+ expect(parse('http://127.0.0.1:23373').success).toBe(true);+ });++ it('accepts every loopback spelling', () => {+ for (const origin of ['http://localhost:23373', 'http://127.0.0.5:8443', 'https://[::1]:23373']) {+ expect(parse(origin).success).toBe(true);+ }+ });++ it('accepts a non-loopback origin WITH the opt-in', () => {+ expect(parse('https://example.com', { allowNonLoopbackBaseUrl: true }).success).toBe(true);+ });++ it('still rejects a malformed value even with the opt-in set', () => {+ expect(parse('not-a-url', { allowNonLoopbackBaseUrl: true }).success).toBe(false);+ });++ it('rejects a bare origin carrying a path, query, or credentials', () => {+ expect(parse('http://127.0.0.1:23373/api').success).toBe(false);+ expect(parse('http://127.0.0.1:23373?x=1').success).toBe(false);+ expect(parse('http://user:[email protected]:23373').success).toBe(false);+ });++ it('is a no-op when baseUrl is absent — the field stays optional', () => {+ expect(beeperSettingsSchema.safeParse({ enabled: true }).success).toBe(true);+ });++ it('still rejects an unknown key (.strict())', () => {+ expect(beeperSettingsSchema.safeParse({ token: 'smuggled' }).success).toBe(false);+ });+});diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex 928672b857..d2ad20b523 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -156,6 +156,21 @@ const RAW_NAV_COMMANDS = [// pill is gated by the same field the sidebar reads.{ id: 'nav.messages.imessage', path: '/messages/imessage', label: 'iMessage', section: 'Comms', tabGroup: 'messages', tabId: 'imessage', feature: 'imessage', previousPaths: ['/imessage'], aliases: ['imessage', 'i-message', 'apple-messages', 'comms-imessage'], keywords: ['comms', 'imessage', 'sms', 'text messages', 'chat.db', 'blocklist', 'spam'] },{ id: 'nav.messages.signal', path: '/messages/signal', label: 'Signal', section: 'Comms', tabGroup: 'messages', tabId: 'signal', feature: 'signal', previousPaths: ['/settings/signal'], aliases: ['signal', 'signal-desktop', 'comms-signal', 'signal-settings'], keywords: ['comms', 'signal', 'signal desktop', 'messages', 'sqlcipher', 'chat', 'tribe', 'timeline', 'encrypted', 'keychain'] },+ // Beeper (#30, fork issue #1): a local Beeper Desktop bridge fronting+ // WhatsApp/Discord/Telegram/Instagram/X/Slack and more, joining the Comms+ // group #40 stood up. Off by default (no detector — #11) — the route keeps+ // resolving with the feature off, so bookmarks and voice ui_navigate still land.+ { id: 'nav.messages.beeper', path: '/messages/beeper', label: 'Beeper', section: 'Comms', tabGroup: 'messages', tabId: 'beeper', feature: 'beeper', aliases: ['beeper', 'beeper-chat', 'comms-beeper'], keywords: ['comms', 'beeper', 'bridge', 'whatsapp', 'discord', 'telegram', 'instagram', 'slack', 'chat', 'unified inbox'] },+ // #35 turned /messages/beeper into the chat surface itself, so the ingestion+ // settings + status card moved into a drawer over it (?settings=1) — the same+ // shape iMessage uses. The entry exists so "open beeper settings" still lands+ // on the card rather than on the conversation list. Like iMessage Settings it+ // carries no `tabId`: the drawer is not its own pill in the tab strip. The open+ // CONVERSATION is /messages/beeper/:conversationId and deliberately has no+ // entry of its own: NAV_COMMANDS enumerates navigable PAGES, and a per-record+ // path would need a parameter the fuzzy resolver has no way to supply+ // (iMessage's :chatKey is absent for the same reason).+ { id: 'nav.messages.beeper-settings', path: '/messages/beeper?settings=1', label: 'Beeper Settings', section: 'Comms', feature: 'beeper', aliases: ['beeper-settings', 'settings-beeper', 'beeper-sync'], keywords: ['beeper', 'settings', 'token', 'sync', 'bridge', 'status', 'connection', 'interval'] },{ id: 'nav.messages.contacts', path: '/messages/contacts', label: 'Contacts', section: 'Comms', tabGroup: 'messages', tabId: 'contacts', previousPaths: ['/settings/contacts'], aliases: ['contacts', 'address-book', 'comms-contacts', 'settings-contacts'], keywords: ['comms', 'contacts', 'address book', 'phone', 'email', 'tribe', 'imessage', 'names', 'resolve'] },// Ingestion config is a drawer over the iMessage manager (?settings=1), not a// Settings page — the settings-* aliases stay so "open iMessage settings" still lands.diff --git a/server/lib/tribeMatch.js b/server/lib/tribeMatch.jsindex ed0841c6ae..fcbf1e721d 100644--- a/server/lib/tribeMatch.js+++ b/server/lib/tribeMatch.js@@ -123,3 +123,91 @@ export function matchPeople(identities = [], index) {}return ids;}++// ---------------------------------------------------------------------------+// Network-scoped identity axis (#34, decided on #10) — the `tribe_identities`+// table's (kind, network, handle) key. This is a THIRD axis, deliberately+// separate from identityFromHandle above: identityFromHandle classifies a bare+// string of unknown provenance (an iMessage/Signal `chat.db` handle) by+// testing for `@`, which is exactly what makes it misclassify a Matrix-style+// id like `@discord_123:beeper.com` as an email (#15 — closed as+// "not reachable from any live iMessage/Signal caller", but explicitly+// deferred to this identity work rather than fixed in place).+//+// The functions below never see a raw source_user_id / Matrix id — callers+// pass an already-scoped Beeper `handle` value (`User.phoneNumber` or+// `User.username`, never `User.id`), so the `@`-vs-Matrix collision does not+// apply here. What DOES apply, and what these functions guard against, is+// #15's other finding: a digit-bearing (but non-phone) handle must never+// collapse into a fabricated E.164 key. `classifyNetworkHandle` only takes the+// phone branch when the value contains NO letters at all — a plausible+// phone-shaped string — never merely "has enough digits".+// ---------------------------------------------------------------------------++// Lowercase, trim, strip a leading '@' — the normalization #10 specifies for+// a network handle before it reaches tribe_identities.+export function normalizeNetworkHandle(value) {+ if (value == null) return '';+ return String(value).trim().toLowerCase().replace(/^@+/, '');+}++// A string is phone-SHAPED only when, after stripping spaces/hyphens/+// parens/dots and an optional leading '+', every remaining character is a+// digit. Any letter (a Discord/Slack/X username, "user5550100199") takes the+// 'handle' branch instead — the #15 hazard, guarded here rather than reusing+// normalizePhone's bare "strip everything but digits" behavior blind to+// letters.+const PHONE_SHAPE_RE = /^\+?[0-9]+$/;+// Real-world E.164 numbers run roughly 7-15 digits (a handful of short-country+// numbers, e.g. some Pacific island plans, are as short as 7). A shorter+// all-digit token (a PIN-like username) is refused as a phone rather than+// fabricating an implausible key — residual ambiguity for a genuinely long+// all-digit non-phone id (a full Discord snowflake) is an accepted,+// documented limit: nothing upstream is expected to feed one through `handle`+// (source_user_id carries those, and is never routed through this function).+const MIN_PHONE_DIGITS = 7;+const MAX_PHONE_DIGITS = 15;++/**+ * Classify an already network-scoped Beeper handle (`User.phoneNumber` or+ * `User.username` — never a bare `User.id` / Matrix id) into the+ * `tribe_identities` `{ kind, handle }` shape, or `null` for a blank value.+ * `kind` is `'phone'` (handle normalized E.164 via normalizePhone) or+ * `'handle'` (lowercased/trimmed/`@`-stripped username).+ */+export function classifyNetworkHandle(value) {+ const raw = value == null ? '' : String(value).trim();+ if (!raw) return null;+ const stripped = raw.replace(/[\s().-]/g, '');+ if (PHONE_SHAPE_RE.test(stripped)) {+ const digits = stripped.replace(/^\+/, '');+ if (digits.length >= MIN_PHONE_DIGITS && digits.length <= MAX_PHONE_DIGITS) {+ const phone = normalizePhone(stripped);+ if (phone) return { kind: 'phone', handle: phone };+ }+ }+ const handle = normalizeNetworkHandle(raw);+ return handle ? { kind: 'handle', handle } : null;+}++// ---------------------------------------------------------------------------+// Soft-delete parity — a `tribe_person_id` cache column reads as "linked"+// consistently everywhere a beeper_participants row is shaped.+// ---------------------------------------------------------------------------++/**+ * A `beeper_participants.tribe_person_id` cache column, plus the joined+ * `tribe_people.deleted` flag it was read alongside, collapsed to ONE answer.+ * `tribe.deletePerson` is a SOFT delete — it never fires the FK's ON DELETE+ * CASCADE — so the raw column can go on pointing at a person who no longer+ * counts as one. Every reader of a participant row (the conversation/list+ * shaper in `services/beeperConversations.js`, and `services/beeperTribe.js`'s+ * own row shaper) calls this SAME function so a soft-deleted link reads as+ * unlinked everywhere at once: `null`, never a dead id with no re-link+ * affordance in the UI. Extracted here rather than duplicated in both+ * services precisely because two independent copies had already drifted —+ * one nulled the id, the other did not.+ */+export function resolveLinkedPersonId(tribePersonId, tribePersonDeleted) {+ return tribePersonId && !tribePersonDeleted ? tribePersonId : null;+}diff --git a/server/lib/tribeMatch.test.js b/server/lib/tribeMatch.test.jsindex 8714542fc7..f7094554d2 100644--- a/server/lib/tribeMatch.test.js+++ b/server/lib/tribeMatch.test.js@@ -6,6 +6,8 @@ import {buildPersonMatchIndex,matchPerson,matchPeople,+ normalizeNetworkHandle,+ classifyNetworkHandle,} from './tribeMatch.js';const PEOPLE = [@@ -143,4 +145,46 @@ describe('tribeMatch', () => {expect(ids.size).toBe(0);});});++ describe('normalizeNetworkHandle', () => {+ it('lowercases, trims, and strips a leading @', () => {+ expect(normalizeNetworkHandle(' @Alice ')).toBe('alice');+ });+ it('strips only a leading @, not one mid-string', () => {+ expect(normalizeNetworkHandle('@user@example')).toBe('user@example');+ });+ it('returns empty string for nullish', () => {+ expect(normalizeNetworkHandle(null)).toBe('');+ expect(normalizeNetworkHandle(undefined)).toBe('');+ });+ });++ describe('classifyNetworkHandle', () => {+ it('classifies a bare 10-digit NANP number as phone', () => {+ expect(classifyNetworkHandle('5551234567')).toEqual({ kind: 'phone', handle: '+15551234567' });+ });+ it('classifies an E.164 number with punctuation as phone', () => {+ expect(classifyNetworkHandle('+1 (555) 010-0199')).toEqual({ kind: 'phone', handle: '+15550100199' });+ });+ it('classifies a username handle, stripping a leading @', () => {+ expect(classifyNetworkHandle('@ExampleUser')).toEqual({ kind: 'handle', handle: 'exampleuser' });+ });+ it('does NOT classify a digit-bearing username as a phone (#15 hazard, guarded)', () => {+ // A network username containing letters must never take the phone branch,+ // no matter how many digits it carries.+ expect(classifyNetworkHandle('user5550100199')).toEqual({ kind: 'handle', handle: 'user5550100199' });+ expect(classifyNetworkHandle('x5550100199')).toEqual({ kind: 'handle', handle: 'x5550100199' });+ });+ it('does not classify a too-short all-digit token as a phone', () => {+ expect(classifyNetworkHandle('4242')).toEqual({ kind: 'handle', handle: '4242' });+ });+ it('does not classify an implausibly long all-digit token (a snowflake shape) as a phone', () => {+ expect(classifyNetworkHandle('987654321098765432')).toEqual({ kind: 'handle', handle: '987654321098765432' });+ });+ it('returns null for a blank handle', () => {+ expect(classifyNetworkHandle('')).toBeNull();+ expect(classifyNetworkHandle(null)).toBeNull();+ expect(classifyNetworkHandle(undefined)).toBeNull();+ });+ });});diff --git a/server/routes/beeper.js b/server/routes/beeper.jsnew file mode 100644index 0000000000..1ef5d148dc--- /dev/null+++ b/server/routes/beeper.js@@ -0,0 +1,507 @@+import { Router } from 'express';+import { z } from 'zod';+import { asyncHandler, createServiceErrorMapper, ServerError } from '../lib/errorHandler.js';+import { resolveOAuthOrigin } from '../lib/beeperOAuthOrigin.js';+import { PORTOS_API_URL, PORTOS_UI_URL } from '../lib/portosUrls.js';+import { serveLocalFile } from '../lib/fileUtils.js';+import { basename, dirname } from 'path';+import {+ beeperOAuthCallbackSchema, beeperOutboxCreateSchema, beeperOutboxListSchema,+ beeperOutboxParamsSchema, beeperOutboxSendSchema, beeperPastedTokenSchema, validateRequest,+} from '../lib/validation.js';+import { getBeeperStatus, checkBeeperConnection } from '../services/beeperStatus.js';+import { completeBeeperOAuth, connectWithPastedToken, disconnectBeeper, startBeeperOAuth } from '../services/beeperOAuth.js';+import { runBeeperSweep } from '../services/beeperSync.js';+import {+ clearOutboxBreaker, createOutboxEntry, discardOutboxEntry, listOutboxEntries, sendOutboxEntry,+} from '../services/beeperOutbox.js';+import {+ listConversations,+ getConversation,+ listMessages,+ listNetworks,+ markConversationSeen,+ purgeConversation,+ setConversationArchived,+ setConversationLowPriority,+} from '../services/beeperConversations.js';+import {+ backfillAttachments,+ ensureAttachmentBytes,+ getAttachment,+ getAttachmentSummary,+ setAttachmentKeep,+} from '../services/beeperAttachments.js';++const router = Router();++// BeeperApiError#status can be 0 on a pure network failure (no HTTP response+// at all — see beeperClient.js's NETWORK_ERROR case), and `res.status(0)`+// crashes Express. This mapper NEVER passes the client's raw status through:+// every recognized code gets its own explicit HTTP status here, per the+// contract wave-one reviewers set for every Beeper route built on this client.+// The OAUTH_* codes (#31) join the same table rather than inventing a second+// one, so a connect failure renders through the client's existing handling.+const BEEPER_ERROR_STATUS = {+ NETWORK_ERROR: 503,+ NOT_CONFIGURED: 412,+ MALFORMED_RESPONSE: 502,+ ASSET_UNAVAILABLE: 404,+ // Every account failed in one sweep (#32). An upstream failure, not the+ // caller's, and worth retrying — it must not answer 200 with a quietly+ // non-zero `failedAccounts`.+ SWEEP_FAILED: 502,+ UNAUTHORIZED: 401,+ TOKEN_REQUIRED: 400,+ TOKEN_REJECTED: 401,+ OAUTH_INTROSPECTION_FAILED: 502,+ OAUTH_REDIRECT_URI_MISSING: 400,+ OAUTH_STATE_UNKNOWN: 400,+ OAUTH_DISCOVERY_FAILED: 502,+ OAUTH_DISCOVERY_INVALID: 502,+ OAUTH_REGISTRATION_FAILED: 502,+ OAUTH_EXCHANGE_FAILED: 502,+ // The attachment mirror (#37). An over-cap attachment is not an error the+ // user can fix by retrying — it is a deliberate refusal with a named escape+ // hatch ("fetch anyway"), so it gets its own status rather than riding on+ // 400. ATTACHMENT_DOWNLOAD_FAILED/ATTACHMENT_STORE_FAILED are local-side+ // failures of a fetch that Beeper itself answered.+ ATTACHMENT_TOO_LARGE: 413,+ ATTACHMENT_DOWNLOAD_FAILED: 502,+ ATTACHMENT_STORE_FAILED: 500,+ // Outbox (#36). Every one is a 4xx the composer renders inline: the entry is+ // gone, it is not in a sendable state, the first-contact confirmation has not+ // been given, or the runaway breaker is open and only a human closes it.+ OUTBOX_ENTRY_NOT_FOUND: 404,+ OUTBOX_INVALID_STATE: 409,+ OUTBOX_EMPTY_BODY: 400,+ FIRST_CONTACT_CONFIRMATION_REQUIRED: 409,+ OUTBOX_BREAKER_OPEN: 429,+ CONVERSATION_NOT_FOUND: 404,+ SEND_FAILED: 502,+};++// The one code whose envelope carries data the client can act on: an over-cap+// refusal states the size it measured and the ceiling it measured against, so+// a caller is not left to re-derive either. `createServiceErrorMapper` builds a+// FRESH ServerError, so a context the service attached is dropped unless it is+// rebuilt here; returning `undefined` for every other code leaves those+// envelopes exactly as they were.+const mapBeeperError = createServiceErrorMapper(BEEPER_ERROR_STATUS, (err) => (+ err?.code === 'ATTACHMENT_TOO_LARGE'+ ? { bytes: err?.context?.bytes, maxBytes: err?.context?.maxBytes }+ : undefined+));++// Write paths (connect / paste / disconnect) carry `retryable: false` into the+// error envelope. Beeper sends are non-idempotent and the connect exchange+// burns a single-use code, so a client that auto-retried either would do real+// damage — the flag is the contract the client keys on rather than re-deriving+// "is a 502 transient" for itself.+// The chat-surface writes (#35) go through the same mapper, so its table also+// carries every HTTP-derived code beeperClient's STATUS_TABLE can raise on a+// PATCH — an unmapped code would fall through as a raw BeeperApiError whose+// `status` can be 0.+const mapBeeperWriteError = createServiceErrorMapper({+ ...BEEPER_ERROR_STATUS,+ BAD_REQUEST: 400,+ FORBIDDEN: 403,+ NOT_FOUND: 404,+ CONFLICT: 409,+ VALIDATION_ERROR: 422,+ RATE_LIMITED: 429,+ INTERNAL_ERROR: 502,+ UPSTREAM_ERROR: 502,+ UNKNOWN_ERROR: 502,+}, () => ({ retryable: false }));++// OAuth must use the same public origin the browser used to reach this request,+// so the flow works over HTTPS, on a Tailscale hostname, or behind a proxy —+// never a hardcoded localhost. Same derivation as routes/spotify.js.+//+// It is the FALLBACK rather than the answer, because it is wrong under the Vite+// dev proxy: `changeOrigin: true` with no `x-forwarded-*` makes the server see+// its own HTTPS origin on the API port, and the consent redirect then lands the+// browser on a host the certificate does not cover. The browser sends its own+// `window.location.origin` instead, validated by `resolveOAuthOrigin`.+function requestOrigin(req) {+ const proto = (req.headers['x-forwarded-proto'] || req.protocol || 'http')+ .toString().split(',')[0].trim();+ const host = (req.headers['x-forwarded-host'] || req.headers.host || '')+ .toString().split(',')[0].trim();+ return ['http', 'https'].includes(proto) && host ? `${proto}://${host}` : null;+}++const redirectUriFrom = (origin) => (origin ? `${origin}/api/beeper/oauth/callback` : null);++// The browser's own origin. Optional, so an older client (or a caller with no+// window) still gets today's request-derived behaviour.+const oauthStartSchema = z.object({ origin: z.string().min(1).max(2048).optional() }).strict();++// GET /api/beeper/status — the status card's read model (#30): whether a+// token is configured (never the token), how it was obtained, its expiry, a+// cached-cheap reachability probe, and the read-only account roster mirrored+// from beeper_accounts.+router.get('/status', asyncHandler(async (_req, res) => {+ res.json(await getBeeperStatus());+}));++// POST /api/beeper/status/check — the status card's "Retry" action on the+// "token present, unreachable" state. Does a live, uncached probe and+// surfaces a real, coded error instead of GET /status's always-200 flattened+// `lastProbeError` string, so the client can render an actionable message+// per HTTP status (503 unreachable, 412 not configured, 502 malformed reply).+router.post('/status/check', asyncHandler(async (_req, res) => {+ const result = await checkBeeperConnection().catch((err) => { throw mapBeeperError(err); });+ res.json(result);+}));++// POST /api/beeper/sync — run one watermark-bounded ingestion sweep now+// (#32). The scheduled sweep is the normal path; this is the explicit+// user-triggered equivalent, for a user who has just connected a token or+// just changed a setting and does not want to wait out the interval. Deterministic+// ingestion only — no AI provider call — so it needs no consent step.+//+// A sweep already in flight is reported as `skipped: true` rather than queued+// or run concurrently; a missing token maps to 412 through the same coded+// mapper the status routes use, never a raw `status: 0`.+router.post('/sync', asyncHandler(async (_req, res) => {+ const result = await runBeeperSweep({ reason: 'manual' }).catch((err) => { throw mapBeeperError(err); });+ res.json(result);+}));++// ---------------------------------------------------------------------------+// Chat surface read model (#35) — served from the MIRROR, never from Beeper.+// ---------------------------------------------------------------------------++// A query-string boolean is a STRING, so `z.coerce.boolean()` is wrong here:+// it maps the literal "false" to `true`. Omission stays `undefined`, which the+// service reads as "do not filter on this at all" — a different query from+// `false` (root AGENTS.md, absent-vs-empty).+const queryBoolean = z.enum(['true', 'false']).transform((value) => value === 'true').optional();++const conversationListQuerySchema = z.object({+ network: z.string().min(1).max(100).optional(),+ unreadOnly: queryBoolean,+ archived: queryBoolean,+ lowPriority: queryBoolean,+ limit: z.coerce.number().int().min(1).max(200).optional(),+ cursor: z.string().max(500).optional(),+}).strict();++const messageListQuerySchema = z.object({+ limit: z.coerce.number().int().min(1).max(200).optional(),+ cursor: z.string().max(500).optional(),+}).strict();++const conversationParamsSchema = z.object({ id: z.string().guid() });++const archiveSchema = z.object({ archived: z.boolean() }).strict();+const lowPrioritySchema = z.object({ lowPriority: z.boolean() }).strict();++// GET /api/beeper/conversations — the rail's list for one scope. Filters are+// per-network and unread-only (#9's MVP scoping) plus the two system scopes+// the wired rail controls produce, archived and low-priority.+router.get('/conversations', asyncHandler(async (req, res) => {+ const filters = validateRequest(conversationListQuerySchema, req.query);+ res.json(await listConversations(filters));+}));++// GET /api/beeper/networks — the rail's scope list, derived from the mirror.+// Never a hardcoded network roster: #9 records that the development machine's+// account shape is an outlier, so the rail renders whatever data holds.+router.get('/networks', asyncHandler(async (_req, res) => {+ res.json({ networks: await listNetworks() });+}));++// GET /api/beeper/conversations/:id — one conversation with its full mirrored+// participant set. 404 when the id is unknown, so a stale deep link degrades to+// the surface's not-found state instead of an empty thread that looks live.+//+// The chat surface fetches this with `silent: true` and renders its own inline+// not-found state, and it re-fetches on every invalidation frame while the+// missing id stays selected — so this is a speculative, expected-high-volume+// 404, not an operator-actionable one. `severity: 'warning'` (mediaJobs.js's+// GET /:id pattern) keeps it out of the global toast and the server console+// via `useErrorNotifications` / `asyncHandler` while the body is unchanged:+// callers still get a 404 + NOT_FOUND code, and it still reaches errorEvents.+router.get('/conversations/:id', asyncHandler(async (req, res) => {+ const { id } = validateRequest(conversationParamsSchema, req.params);+ const conversation = await getConversation(id);+ if (!conversation) {+ throw new ServerError('Conversation not found', { status: 404, code: 'NOT_FOUND', severity: 'warning' });+ }+ res.json(conversation);+}));++// GET /api/beeper/conversations/:id/messages — cursor-paginated, newest first.+// An empty page is a legitimate answer, not an error: history depth varies+// enormously per network (#3), so the surface says so rather than spinning.+router.get('/conversations/:id/messages', asyncHandler(async (req, res) => {+ const { id } = validateRequest(conversationParamsSchema, req.params);+ const options = validateRequest(messageListQuerySchema, req.query);+ res.json(await listMessages(id, options));+}));++// POST /api/beeper/conversations/:id/archive — one of the two rail controls #9+// wired. Beeper owns `isArchived`, so this PATCHes Beeper first and mirrors the+// answer second; a failure leaves the mirror untouched.+router.post('/conversations/:id/archive', asyncHandler(async (req, res) => {+ const { id } = validateRequest(conversationParamsSchema, req.params);+ const { archived } = validateRequest(archiveSchema, req.body);+ const conversation = await setConversationArchived(id, archived)+ .catch((err) => { throw mapBeeperWriteError(err); });+ res.json(conversation);+}));++// POST /api/beeper/conversations/:id/low-priority — the other wired control.+// `isPinned` deliberately has no route: the pinned set is Beeper's own state,+// mirrored (#27), and a PortOS-local pin would be a second source of truth.+router.post('/conversations/:id/low-priority', asyncHandler(async (req, res) => {+ const { id } = validateRequest(conversationParamsSchema, req.params);+ const { lowPriority } = validateRequest(lowPrioritySchema, req.body);+ const conversation = await setConversationLowPriority(id, lowPriority)+ .catch((err) => { throw mapBeeperWriteError(err); });+ res.json(conversation);+}));++// POST /api/beeper/conversations/:id/seen — the LOCAL "seen in PortOS"+// watermark (#83), the fix for opening an unread thread leaving its badge+// untouched. Unlike archive/low-priority above, this NEVER calls Beeper: no+// PATCH, no read receipt, nothing that reaches the source network — just a+// local `seen_at` stamp the read model compares against the conversation's+// own activity (`markConversationSeen`). No request body: it is called with+// nothing to validate beyond the id, on every thread open and, cheaply, again+// when a new message lands in the open thread.+router.post('/conversations/:id/seen', asyncHandler(async (req, res) => {+ const { id } = validateRequest(conversationParamsSchema, req.params);+ const conversation = await markConversationSeen(id);+ res.json(conversation);+}));++// ---------------------------------------------------------------------------+// Attachment byte mirror (#37)+// ---------------------------------------------------------------------------++// `messageId` is Beeper's own message id (TEXT — bridges do not promise a UUID+// shape), so it is bounded and pattern-free rather than `.guid()`. It never+// becomes a path: the file is addressed by the sha256 the mirror computed.+const attachmentParamsSchema = z.object({+ messageId: z.string().min(1).max(500),+ idx: z.coerce.number().int().min(0).max(999),+});+const attachmentKeepSchema = z.object({ keep: z.boolean() }).strict();+const backfillSchema = z.object({ limit: z.number().int().min(1).max(5000).optional() }).strict();++// GET /api/beeper/attachments/summary — what the bulk-backfill consent step has+// to state before it runs (how many attachments, how many bytes, how many of+// unknown size) plus the budget picture the settings card renders. Declared+// BEFORE the `:messageId/:idx` routes so "summary" can never be read as a+// message id.+router.get('/attachments/summary', asyncHandler(async (_req, res) => {+ res.json(await getAttachmentSummary());+}));++// POST /api/beeper/attachments/backfill — mirror every reference-only+// attachment. A USER action, never automatic: the client gates it behind a+// consent modal naming the count and the byte size first (root AGENTS.md's+// no-unbidden-work policy, applied to bytes rather than to LLM calls), and the+// run stops at the disk budget instead of blowing through it.+router.post('/attachments/backfill', asyncHandler(async (req, res) => {+ const { limit } = validateRequest(backfillSchema, req.body ?? {});+ const result = await backfillAttachments({ limit }).catch((err) => { throw mapBeeperError(err); });+ res.json(result);+}));++// GET /api/beeper/attachments/:messageId/:idx — the BYTES, served from disk and+// fetched from Beeper on a miss. This is the lazy mirror's whole trigger: the+// thread renders the reference, the browser asks for it when it scrolls into+// view, and only then does anything leave the machine.+//+// An authenticated `/api/` route on `serveLocalFile` rather than a `/data/`+// static mount (#13): message media is PII, and the store is a content-addressed+// pile of hashes that a directory mount would expose without the row-level check+// this route does. `serveLocalFile` is handed an explicit `contentType` because+// the file's own extension is cosmetic — `GET /v1/assets/serve` sends no+// `Content-Type` at all, so Beeper's declared `mimeType` from the message+// payload is the only real answer.+//+// No `force` query param (SEC-4): this is a safe (GET) method, and+// `ensureAttachmentBytes` treats `force: true` as "raise the 32 MiB mirror+// ceiling AND clear a terminal `unavailable_at` refusal so it retries a source+// that already said no." Reading `force` off the query string here let a plain+// GET — no confirmation, no method-level intent — do both. `force: true`+// stays reachable ONLY through the dedicated+// `POST /attachments/:messageId/:idx/fetch` "fetch anyway" route below.+router.get('/attachments/:messageId/:idx', asyncHandler(async (req, res) => {+ const { messageId, idx } = validateRequest(attachmentParamsSchema, req.params);+ const resolved = await ensureAttachmentBytes(messageId, idx)+ .catch((err) => { throw mapBeeperError(err); });+ await serveLocalFile(res, dirname(resolved.filePath), basename(resolved.filePath), {+ contentType: resolved.mimeType,+ missingError: { message: 'Attachment bytes are not on this machine', code: 'NOT_ON_THIS_MACHINE' },+ });+}));++// POST /api/beeper/attachments/:messageId/:idx/fetch — the over-cap+// placeholder's "fetch anyway", and the one path that also retries an+// attachment the source previously refused. Returns the row rather than the+// bytes, so the surface can swap the placeholder for the real thing and let the+// GET above stream it.+router.post('/attachments/:messageId/:idx/fetch', asyncHandler(async (req, res) => {+ const { messageId, idx } = validateRequest(attachmentParamsSchema, req.params);+ await ensureAttachmentBytes(messageId, idx, { force: true })+ .catch((err) => { throw mapBeeperError(err); });+ res.json(await getAttachment(messageId, idx));+}));++// PATCH /api/beeper/attachments/:messageId/:idx — the per-attachment `keep`+// lock: exempt this one from least-recently-viewed eviction forever.+router.patch('/attachments/:messageId/:idx', asyncHandler(async (req, res) => {+ const { messageId, idx } = validateRequest(attachmentParamsSchema, req.params);+ const { keep } = validateRequest(attachmentKeepSchema, req.body);+ res.json(await setAttachmentKeep(messageId, idx, keep));+}));++// DELETE /api/beeper/conversations/:id — purge ONE conversation's mirror:+// messages, participants, attachment rows and the bytes those rows were+// holding. Local only — Beeper still has the chat, and the next sweep will+// mirror it again. The client gates this behind a typed confirmation naming the+// conversation and the byte count, never a `window.confirm`.+router.delete('/conversations/:id', asyncHandler(async (req, res) => {+ const { id } = validateRequest(conversationParamsSchema, req.params);+ res.json(await purgeConversation(id));+}));++// POST /api/beeper/oauth/start — discover, dynamically register PortOS as a+// public client, and mint the PKCE authorization URL the browser opens (#31).+// A POST because it registers a client and stores a pending authorization; the+// PKCE verifier never leaves the server.+router.post('/oauth/start', asyncHandler(async (req, res) => {+ const { origin: clientOrigin } = validateRequest(oauthStartSchema, req.body ?? {});+ const { origin, rejectedClientOrigin } = resolveOAuthOrigin({+ clientOrigin,+ requestOrigin: requestOrigin(req),+ configuredOrigins: [PORTOS_UI_URL, PORTOS_API_URL],+ });+ // Never interpolate the value: it is a host off the user's own machine or+ // tailnet, and this line can end up in a shared log.+ if (rejectedClientOrigin) {+ console.warn('⚠️ Beeper OAuth: browser origin is not one this install serves — using the request origin instead');+ }+ const result = await startBeeperOAuth({ redirectUri: redirectUriFrom(origin), clientUri: origin })+ .catch((err) => { throw mapBeeperWriteError(err); });+ res.json(result);+}));++// GET /api/beeper/oauth/callback — hit by a BROWSER redirect from Beeper's+// consent screen, not by the SPA, so every outcome renders as a redirect back+// to the Beeper tab (which toasts the params) instead of the JSON envelope the+// error middleware would send. The `code` never reaches the client: it is+// exchanged here and only the outcome flag rides the redirect.+router.get('/oauth/callback', asyncHandler(async (req, res) => {+ const tabUrl = (error) => (error+ ? `/messages/beeper?beeperOauthError=${encodeURIComponent(error)}`+ : '/messages/beeper?beeperConnected=1');+ // safeParse rather than validateRequest: a browser landing here must always+ // end up back on the tab with a readable message, never on the JSON error+ // envelope validateRequest's throw would render in the address bar.+ const parsed = beeperOAuthCallbackSchema.safeParse(req.query);+ if (!parsed.success) return res.redirect(tabUrl('Malformed OAuth callback'));+ const params = parsed.data;+ if (params.error) return res.redirect(tabUrl(params.error));+ if (!params.code || !params.state) return res.redirect(tabUrl('Missing authorization code or state'));++ const outcome = await completeBeeperOAuth({ code: params.code, state: params.state })+ .then((result) => ({ result }))+ .catch((err) => {+ // The redirect swallows the throw, so asyncHandler never logs it — keep+ // the failure visible here. `err.message` is built from an RFC 6749 error+ // code or an HTTP status; it never carries a token or a code.+ console.error(`❌ Beeper OAuth callback failed: ${err.message}`);+ return { error: err.message || 'Beeper OAuth callback failed' };+ });+ if (outcome.error) return res.redirect(tabUrl(outcome.error));+ console.log('🔗 Beeper OAuth callback completed, credential stored');+ res.redirect(tabUrl());+}));++// POST /api/beeper/token — the paste path (#11 decision 3), a first-class+// alternative to OAuth rather than a fallback: Beeper's own UI can mint a+// no-expiry token and the OAuth surface accepts no lifetime at all. Validated+// by RFC 7662 introspection (or, failing that, a call that requires the+// bearer) so a token the server refuses is never stored, then vaulted with+// whatever expiry introspection reported. The response carries presence,+// expiry and provenance — never the value.+router.post('/token', asyncHandler(async (req, res) => {+ const { token } = validateRequest(beeperPastedTokenSchema, req.body);+ const result = await connectWithPastedToken(token).catch((err) => { throw mapBeeperWriteError(err); });+ res.json(result);+}));++// DELETE /api/beeper/token — disconnect. Revokes at the authorization server+// when the credential came from OAuth and the server advertises a revocation+// endpoint, then deletes the vaulted copy either way. Idempotent.+router.delete('/token', asyncHandler(async (_req, res) => {+ const result = await disconnectBeeper().catch((err) => { throw mapBeeperWriteError(err); });+ res.json(result);+}));++// ---------------------------------------------------------------------------+// Outbox (#36, decided on #8) — the ONLY send path, and a human one.+//+// Two steps, two routes, two human actions, mirroring the email drafts surface+// (`POST /api/messages/drafts/:id/approve` then `.../send`): creating the entry+// records the approved text, sending it performs the POST. No scheduler, no+// agent, no voice tool and no CoS tool reaches either — asserted structurally+// by `beeperOutboxHumanGate.test.js`, not left to convention.+// ---------------------------------------------------------------------------++// GET /api/beeper/outbox?conversationId=… — the composer's own history for one+// conversation, newest first. Failed entries stay in it: a failed send is+// visible and never silently retried.+router.get('/outbox', asyncHandler(async (req, res) => {+ const params = validateRequest(beeperOutboxListSchema, req.query);+ res.json({ entries: await listOutboxEntries(params) });+}));++// POST /api/beeper/outbox — step one. Writes the durable row BEFORE anything is+// sent, so intent survives a crash between the click and the POST.+router.post('/outbox', asyncHandler(async (req, res) => {+ const input = validateRequest(beeperOutboxCreateSchema, req.body);+ const entry = await createOutboxEntry(input).catch((err) => { throw mapBeeperWriteError(err); });+ res.status(201).json(entry);+}));++// POST /api/beeper/outbox/:id/send — step two. `confirmFirstContact` must be+// explicitly true on the first outbound message to a conversation; without it+// the send is refused with a coded 409 the composer renders as an inline+// confirmation. A transport failure answers a coded error and leaves exactly+// one row in `failed` — the client never retries it (`retryable: false`), and+// re-sending means composing a new entry.+router.post('/outbox/:id/send', asyncHandler(async (req, res) => {+ const { id } = validateRequest(beeperOutboxParamsSchema, req.params);+ const { confirmFirstContact } = validateRequest(beeperOutboxSendSchema, req.body ?? {});+ const entry = await sendOutboxEntry(id, { confirmFirstContact: confirmFirstContact === true })+ .catch((err) => { throw mapBeeperWriteError(err); });+ res.json(entry);+}));++// DELETE /api/beeper/outbox/:id — discard a row the human declined to send:+// the first-contact confirmation's "Cancel" (#53). Only an `approved` row can+// be discarded — nothing has POSTed to Beeper for it yet, so this is a pure+// local record removal, never an unsend. Anything further along answers 409.+router.delete('/outbox/:id', asyncHandler(async (req, res) => {+ const { id } = validateRequest(beeperOutboxParamsSchema, req.params);+ await discardOutboxEntry(id).catch((err) => { throw mapBeeperWriteError(err); });+ res.status(204).send();+}));++// POST /api/beeper/outbox/breaker/clear — the runaway breaker's only reset.+// Deliberately a human HTTP action with no timed recovery anywhere: a breaker+// that clears itself is a delay, not a breaker.+router.post('/outbox/breaker/clear', asyncHandler(async (_req, res) => {+ res.json(clearOutboxBreaker());+}));++export default router;diff --git a/server/routes/beeper.load.test.js b/server/routes/beeper.load.test.jsnew file mode 100644index 0000000000..0561072567--- /dev/null+++ b/server/routes/beeper.load.test.js@@ -0,0 +1,34 @@+import { execFileSync } from 'child_process';+import { fileURLToPath, pathToFileURL } from 'url';+import { dirname, join } from 'path';+import { describe, expect, it } from 'vitest';++const HERE = dirname(fileURLToPath(import.meta.url));++// Boot guard, run in a real Node process. Vitest's module transform turns a+// missing named import into `undefined` instead of the SyntaxError Node throws,+// so the merge-forward of v2.60.0 (which moved PORTOS_UI_URL / PORTOS_API_URL+// from lib/ports.js to lib/portosUrls.js) passed the whole suite and crashed+// the real server at startup. Importing the router under Node's own ESM loader+// catches that class before pm2 does.+describe('routes/beeper.js loads under Node ESM', () => {+ it('imports without a linking error and exports a router', () => {+ const routerUrl = pathToFileURL(join(HERE, 'beeper.js')).href;+ const script = [+ `const mod = await import(${JSON.stringify(routerUrl)});`,+ "if (typeof mod.default !== 'function' || !Array.isArray(mod.default.stack)) {",+ " throw new Error('routes/beeper.js did not export an Express router');",+ '}',+ 'process.stdout.write(String(mod.default.stack.length));',+ 'process.exit(0);',+ ].join('\n');+ const out = execFileSync(process.execPath, ['--input-type=module', '-e', script], {+ cwd: HERE,+ env: { ...process.env, NODE_ENV: 'test' },+ encoding: 'utf8',+ stdio: ['ignore', 'pipe', 'pipe'],+ timeout: 60_000,+ });+ expect(Number(out)).toBeGreaterThan(20);+ });+});diff --git a/server/routes/beeper.test.js b/server/routes/beeper.test.jsnew file mode 100644index 0000000000..e78d81e652--- /dev/null+++ b/server/routes/beeper.test.js@@ -0,0 +1,887 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';++vi.mock('../services/beeperStatus.js', () => ({+ getBeeperStatus: vi.fn(),+ checkBeeperConnection: vi.fn(),+}));+vi.mock('../services/beeperOAuth.js', () => ({+ startBeeperOAuth: vi.fn(),+ completeBeeperOAuth: vi.fn(),+ connectWithPastedToken: vi.fn(),+ disconnectBeeper: vi.fn(),+}));+vi.mock('../services/beeperSync.js', () => ({ runBeeperSweep: vi.fn() }));+vi.mock('../services/beeperOutbox.js', () => ({+ createOutboxEntry: vi.fn(),+ sendOutboxEntry: vi.fn(),+ discardOutboxEntry: vi.fn(),+ listOutboxEntries: vi.fn(),+ clearOutboxBreaker: vi.fn(),+}));+vi.mock('../services/beeperConversations.js', () => ({+ listConversations: vi.fn(),+ getConversation: vi.fn(),+ listMessages: vi.fn(),+ listNetworks: vi.fn(),+ markConversationSeen: vi.fn(),+ purgeConversation: vi.fn(),+ setConversationArchived: vi.fn(),+ setConversationLowPriority: vi.fn(),+}));+vi.mock('../services/beeperAttachments.js', () => ({+ backfillAttachments: vi.fn(),+ ensureAttachmentBytes: vi.fn(),+ getAttachment: vi.fn(),+ getAttachmentSummary: vi.fn(),+ setAttachmentKeep: vi.fn(),+}));+// The bytes themselves are served by the shared `serveLocalFile` pipeline,+// whose behaviour (sanitize → containment → nosniff → sendFile) is covered by+// its own suite. What this file pins is what the ROUTE hands it: the resolved+// path, and the stored mimeType as an explicit `contentType` — because+// `GET /v1/assets/serve` sends no Content-Type and a hash-named file has no+// extension worth sniffing.+vi.mock('../lib/fileUtils.js', async (importOriginal) => ({+ ...(await importOriginal()),+ serveLocalFile: vi.fn(async (res) => res.json({ served: true })),+}));++import beeperRoutes from './beeper.js';+import { getBeeperStatus, checkBeeperConnection } from '../services/beeperStatus.js';+import {+ completeBeeperOAuth, connectWithPastedToken, disconnectBeeper, startBeeperOAuth,+} from '../services/beeperOAuth.js';+import { runBeeperSweep } from '../services/beeperSync.js';+import {+ clearOutboxBreaker, createOutboxEntry, discardOutboxEntry, listOutboxEntries, sendOutboxEntry,+} from '../services/beeperOutbox.js';+import {+ listConversations,+ getConversation,+ listMessages,+ listNetworks,+ markConversationSeen,+ purgeConversation,+ setConversationArchived,+ setConversationLowPriority,+} from '../services/beeperConversations.js';+import {+ backfillAttachments,+ ensureAttachmentBytes,+ getAttachment,+ getAttachmentSummary,+ setAttachmentKeep,+} from '../services/beeperAttachments.js';+import { serveLocalFile } from '../lib/fileUtils.js';+import { ServerError, errorEvents } from '../lib/errorHandler.js';+import { BeeperApiError } from '../services/beeperClient.js';++const buildApp = () => {+ const app = express();+ app.use(express.json());+ app.use('/api/beeper', beeperRoutes);+ // The OAuth callback answers a BROWSER with a redirect to the Beeper tab, and+ // the test harness follows redirects, so stand in for the SPA route and+ // report where the browser actually landed — the user-visible outcome.+ app.get('/messages/beeper', (req, res) => res.json({ landedOn: req.originalUrl }));+ return app;+};++describe('GET /api/beeper/status', () => {+ beforeEach(() => vi.clearAllMocks());++ it('returns the status payload as-is', async () => {+ vi.mocked(getBeeperStatus).mockResolvedValue({ tokenConfigured: false, reachable: null, accounts: [] });+ const res = await request(buildApp()).get('/api/beeper/status');+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ tokenConfigured: false, reachable: null, accounts: [] });+ });+});++// The wave-one reviewer contract this route exists to prove: every recognized+// BeeperApiError code maps to its own explicit HTTP status, and the mapper+// never lets a status:0 network-failure error reach res.status() raw (which+// would crash Express).+describe('POST /api/beeper/status/check — createServiceErrorMapper contract', () => {+ beforeEach(() => vi.clearAllMocks());++ it('maps NETWORK_ERROR (status:0 on the source error) to 503, not a raw 0', async () => {+ vi.mocked(checkBeeperConnection).mockRejectedValue(+ new BeeperApiError('Beeper request failed: connection refused', { status: 0, code: 'NETWORK_ERROR', retryable: false }),+ );+ const res = await request(buildApp()).post('/api/beeper/status/check');+ expect(res.status).toBe(503);+ expect(res.body.code).toBe('NETWORK_ERROR');+ });++ it('maps NOT_CONFIGURED to 412', async () => {+ vi.mocked(checkBeeperConnection).mockRejectedValue(+ new BeeperApiError('Beeper access token is not configured', { status: 401, code: 'NOT_CONFIGURED', retryable: false }),+ );+ const res = await request(buildApp()).post('/api/beeper/status/check');+ expect(res.status).toBe(412);+ expect(res.body.code).toBe('NOT_CONFIGURED');+ });++ it('maps MALFORMED_RESPONSE to 502', async () => {+ vi.mocked(checkBeeperConnection).mockRejectedValue(+ new BeeperApiError('Beeper API returned an unexpected /v1/info response shape', { status: 502, code: 'MALFORMED_RESPONSE', retryable: false }),+ );+ const res = await request(buildApp()).post('/api/beeper/status/check');+ expect(res.status).toBe(502);+ expect(res.body.code).toBe('MALFORMED_RESPONSE');+ });++ it('maps ASSET_UNAVAILABLE to 404', async () => {+ vi.mocked(checkBeeperConnection).mockRejectedValue(+ new BeeperApiError('Asset no longer available', { status: 502, code: 'ASSET_UNAVAILABLE', retryable: false }),+ );+ const res = await request(buildApp()).post('/api/beeper/status/check');+ expect(res.status).toBe(404);+ expect(res.body.code).toBe('ASSET_UNAVAILABLE');+ });++ it('resolves 200 with the connection result on success', async () => {+ vi.mocked(checkBeeperConnection).mockResolvedValue({ reachable: true, info: { app: { name: 'Beeper' } } });+ const res = await request(buildApp()).post('/api/beeper/status/check');+ expect(res.status).toBe(200);+ expect(res.body.reachable).toBe(true);+ });+});++// The manual run-now sweep (#32). The scheduled sweep is the normal path; this+// is the same work on demand, and it inherits the coded-error contract above+// rather than leaking a status:0 through to res.status().+describe('POST /api/beeper/sync', () => {+ beforeEach(() => vi.clearAllMocks());++ it('runs one sweep and returns its summary', async () => {+ vi.mocked(runBeeperSweep).mockResolvedValue({ skipped: false, accounts: 2, chats: 3, messages: 7, failedAccounts: 0, durationMs: 42 });+ const res = await request(buildApp()).post('/api/beeper/sync');+ expect(res.status).toBe(200);+ expect(res.body).toMatchObject({ skipped: false, chats: 3, messages: 7 });+ expect(vi.mocked(runBeeperSweep)).toHaveBeenCalledWith({ reason: 'manual' });+ });++ it('reports an already-running sweep as skipped rather than starting a second one', async () => {+ vi.mocked(runBeeperSweep).mockResolvedValue({ skipped: true, reason: 'manual', accounts: 0, chats: 0, messages: 0 });+ const res = await request(buildApp()).post('/api/beeper/sync');+ expect(res.status).toBe(200);+ expect(res.body.skipped).toBe(true);+ });++ it('maps a missing token to 412 through the same mapper, never a raw status', async () => {+ vi.mocked(runBeeperSweep).mockRejectedValue(+ new BeeperApiError('Beeper access token is not configured', { status: 401, code: 'NOT_CONFIGURED', retryable: false }),+ );+ const res = await request(buildApp()).post('/api/beeper/sync');+ expect(res.status).toBe(412);+ expect(res.body.code).toBe('NOT_CONFIGURED');+ });++ it('maps an unreachable Beeper Desktop (status:0) to 503', async () => {+ vi.mocked(runBeeperSweep).mockRejectedValue(+ new BeeperApiError('Beeper request failed: connection refused', { status: 0, code: 'NETWORK_ERROR', retryable: false }),+ );+ const res = await request(buildApp()).post('/api/beeper/sync');+ expect(res.status).toBe(503);+ });++ // A sweep in which every account failed throws SWEEP_FAILED rather than+ // resolving with a quietly non-zero `failedAccounts`, so this route reports+ // the failure instead of answering 200.+ it('maps an all-accounts-failed sweep to 502 rather than a 200 with a non-zero failedAccounts', async () => {+ vi.mocked(runBeeperSweep).mockRejectedValue(+ new BeeperApiError('Beeper sweep failed for all 3 accounts', { status: 502, code: 'SWEEP_FAILED', retryable: true }),+ );+ const res = await request(buildApp()).post('/api/beeper/sync');+ expect(res.status).toBe(502);+ expect(res.body.code).toBe('SWEEP_FAILED');+ });+});++// The connect flow (#31): OAuth start → browser callback → paste alternative →+// disconnect, each asserted at the route boundary with the services mocked.+describe('POST /api/beeper/oauth/start', () => {+ beforeEach(() => vi.clearAllMocks());++ it('builds the redirect URI from the request origin, not a hardcoded localhost', async () => {+ vi.mocked(startBeeperOAuth).mockResolvedValue({ authorizationUrl: 'http://127.0.0.1:23373/oauth/authorize?x=1', redirectUri: 'x', state: 's' });+ const res = await request(buildApp())+ .post('/api/beeper/oauth/start')+ .set('X-Forwarded-Proto', 'https')+ .set('X-Forwarded-Host', 'example.ts.net:5555');++ expect(res.status).toBe(200);+ expect(startBeeperOAuth).toHaveBeenCalledWith({+ redirectUri: 'https://example.ts.net:5555/api/beeper/oauth/callback',+ clientUri: 'https://example.ts.net:5555',+ });+ });++ // Under the Vite dev proxy (`changeOrigin: true`, no `x-forwarded-*`) the+ // request carries the API's own origin on the API port, so the derivation+ // above sent the browser to a host the TLS certificate does not cover. The+ // browser sends its own origin, and a recognized one wins.+ it('uses the browser origin the client sent when the request origin is the proxy target', async () => {+ vi.mocked(startBeeperOAuth).mockResolvedValue({ authorizationUrl: 'http://127.0.0.1:23373/oauth/authorize?x=1', redirectUri: 'x', state: 's' });+ const res = await request(buildApp())+ .post('/api/beeper/oauth/start')+ .set('X-Forwarded-Proto', 'https')+ .set('X-Forwarded-Host', 'localhost:5555')+ .send({ origin: 'http://localhost:5554' });++ expect(res.status).toBe(200);+ expect(startBeeperOAuth).toHaveBeenCalledWith({+ redirectUri: 'http://localhost:5554/api/beeper/oauth/callback',+ clientUri: 'http://localhost:5554',+ });+ });++ it('ignores a browser origin this install does not serve and falls back to the request origin', async () => {+ vi.mocked(startBeeperOAuth).mockResolvedValue({ authorizationUrl: 'http://127.0.0.1:23373/oauth/authorize?x=1', redirectUri: 'x', state: 's' });+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});++ const res = await request(buildApp())+ .post('/api/beeper/oauth/start')+ .set('X-Forwarded-Proto', 'https')+ .set('X-Forwarded-Host', 'example.ts.net:5555')+ .send({ origin: 'https://example.com' });++ expect(res.status).toBe(200);+ expect(startBeeperOAuth).toHaveBeenCalledWith({+ redirectUri: 'https://example.ts.net:5555/api/beeper/oauth/callback',+ clientUri: 'https://example.ts.net:5555',+ });+ // The warning never carries the value: it is a host off the user's own+ // machine or tailnet, and this line can end up in a shared log.+ expect(String(warn.mock.calls[0]?.[0])).not.toContain('example.com');+ warn.mockRestore();+ });++ it('rejects an unexpected body field rather than letting it through unvalidated', async () => {+ const res = await request(buildApp())+ .post('/api/beeper/oauth/start')+ .send({ origin: 'http://localhost:5554', unexpected: true });++ expect(res.status).toBe(400);+ expect(startBeeperOAuth).not.toHaveBeenCalled();+ });++ it('maps a discovery failure to 502 and marks it non-retryable', async () => {+ vi.mocked(startBeeperOAuth).mockRejectedValue(+ new BeeperApiError('Beeper authorization-server metadata unavailable (404)', { status: 502, code: 'OAUTH_DISCOVERY_FAILED', retryable: false }),+ );+ const res = await request(buildApp()).post('/api/beeper/oauth/start');+ expect(res.status).toBe(502);+ expect(res.body.code).toBe('OAUTH_DISCOVERY_FAILED');+ expect(res.body.context.retryable).toBe(false);+ });+});++describe('GET /api/beeper/oauth/callback', () => {+ beforeEach(() => vi.clearAllMocks());++ it('exchanges the code and redirects back to the Beeper tab', async () => {+ vi.mocked(completeBeeperOAuth).mockResolvedValue({ tokenConfigured: true, tokenSource: 'oauth', reachable: true });+ const res = await request(buildApp()).get('/api/beeper/oauth/callback?code=abc&state=xyz');+ expect(completeBeeperOAuth).toHaveBeenCalledWith({ code: 'abc', state: 'xyz' });+ expect(res.body.landedOn).toBe('/messages/beeper?beeperConnected=1');+ });++ // A browser lands here, so every outcome has to be a redirect the user can+ // read — never the JSON error envelope in the address bar.+ it('redirects with the reason when the exchange fails', async () => {+ vi.mocked(completeBeeperOAuth).mockRejectedValue(+ new BeeperApiError('Beeper token exchange failed (invalid_grant)', { status: 502, code: 'OAUTH_EXCHANGE_FAILED', retryable: false }),+ );+ const res = await request(buildApp()).get('/api/beeper/oauth/callback?code=abc&state=xyz');+ expect(res.body.landedOn).toContain('beeperOauthError=');+ expect(decodeURIComponent(res.body.landedOn)).toContain('invalid_grant');+ });++ it('redirects with the authorization server error when the user declines', async () => {+ const res = await request(buildApp()).get('/api/beeper/oauth/callback?error=access_denied');+ expect(decodeURIComponent(res.body.landedOn)).toContain('access_denied');+ expect(completeBeeperOAuth).not.toHaveBeenCalled();+ });++ it('redirects rather than 400s when code or state is missing', async () => {+ const res = await request(buildApp()).get('/api/beeper/oauth/callback?code=abc');+ expect(decodeURIComponent(res.body.landedOn)).toContain('Missing authorization code or state');+ });+});++describe('POST /api/beeper/token — the paste path', () => {+ beforeEach(() => vi.clearAllMocks());++ it('stores a pasted token and answers with presence, expiry and provenance only', async () => {+ vi.mocked(connectWithPastedToken).mockResolvedValue({+ tokenConfigured: true, tokenExpiresAt: null, tokenSource: 'pasted', reachable: true, lastProbeError: null,+ });+ const res = await request(buildApp()).post('/api/beeper/token').send({ token: 'example-beeper-token' });+ expect(res.status).toBe(200);+ expect(res.body).toEqual({+ tokenConfigured: true, tokenExpiresAt: null, tokenSource: 'pasted', reachable: true, lastProbeError: null,+ });+ });++ // Introspection says the token is not active: a 401 the client can act on,+ // marked non-retryable so nothing re-posts the same dead credential.+ it('maps a rejected token to 401 with retryable:false', async () => {+ vi.mocked(connectWithPastedToken).mockRejectedValue(+ new BeeperApiError('Beeper rejected that access token (introspection reports it is not active)', { status: 401, code: 'TOKEN_REJECTED', retryable: false }),+ );+ const res = await request(buildApp()).post('/api/beeper/token').send({ token: 'example-beeper-token' });+ expect(res.status).toBe(401);+ expect(res.body.code).toBe('TOKEN_REJECTED');+ expect(res.body.context.retryable).toBe(false);+ });++ it('400s on an empty token instead of reaching the service', async () => {+ const res = await request(buildApp()).post('/api/beeper/token').send({ token: ' ' });+ expect(res.status).toBe(400);+ expect(connectWithPastedToken).not.toHaveBeenCalled();+ });++ it('rejects unknown fields, so nothing else can ride this write path', async () => {+ const res = await request(buildApp()).post('/api/beeper/token').send({ token: 'example-beeper-token', expiresAt: '2099-01-01' });+ expect(res.status).toBe(400);+ expect(connectWithPastedToken).not.toHaveBeenCalled();+ });+});++describe('DELETE /api/beeper/token — disconnect', () => {+ beforeEach(() => vi.clearAllMocks());++ it('reports the disconnected state', async () => {+ vi.mocked(disconnectBeeper).mockResolvedValue({ deleted: true, tokenConfigured: false, tokenExpiresAt: null, tokenSource: null });+ const res = await request(buildApp()).delete('/api/beeper/token');+ expect(res.status).toBe(200);+ expect(res.body).toMatchObject({ deleted: true, tokenConfigured: false });+ });++ it('is idempotent when nothing was stored', async () => {+ vi.mocked(disconnectBeeper).mockResolvedValue({ deleted: false, tokenConfigured: false, tokenExpiresAt: null, tokenSource: null });+ const res = await request(buildApp()).delete('/api/beeper/token');+ expect(res.status).toBe(200);+ expect(res.body.deleted).toBe(false);+ });+});++// The #31 acceptance criterion, asserted rather than argued: "a grep of logs and+// of any client response for the token value returns nothing". This drives the+// whole connect → paste → status → disconnect surface with a known token value+// and greps every response body, every redirect Location, and everything the+// routes wrote to console.+describe('the token value never reaches a response or a log line', () => {+ const TOKEN = 'example-beeper-token-value-31';++ it('leaks nothing across connect, paste, status, check and disconnect', async () => {+ vi.clearAllMocks();+ const written = [];+ const capture = (...args) => written.push(args.map(String).join(' '));+ const logSpy = vi.spyOn(console, 'log').mockImplementation(capture);+ const errSpy = vi.spyOn(console, 'error').mockImplementation(capture);+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(capture);++ // Every mocked service behaves like the real one: it takes the token in and+ // hands back presence/expiry/provenance, never the value.+ vi.mocked(startBeeperOAuth).mockResolvedValue({ authorizationUrl: 'http://127.0.0.1:23373/oauth/authorize?state=s', redirectUri: 'r', state: 's' });+ vi.mocked(completeBeeperOAuth).mockResolvedValue({ tokenConfigured: true, tokenExpiresAt: null, tokenSource: 'oauth', reachable: true });+ vi.mocked(connectWithPastedToken).mockResolvedValue({ tokenConfigured: true, tokenExpiresAt: null, tokenSource: 'pasted', reachable: true });+ vi.mocked(getBeeperStatus).mockResolvedValue({ tokenConfigured: true, tokenExpiresAt: null, tokenSource: 'pasted', reachable: true, accounts: [] });+ vi.mocked(checkBeeperConnection).mockResolvedValue({ reachable: true, info: { app: { name: 'Beeper' } } });+ vi.mocked(disconnectBeeper).mockResolvedValue({ deleted: true, tokenConfigured: false });++ const app = buildApp();+ const responses = [+ await request(app).post('/api/beeper/oauth/start'),+ await request(app).get('/api/beeper/oauth/callback?code=abc&state=s'),+ await request(app).post('/api/beeper/token').send({ token: TOKEN }),+ await request(app).get('/api/beeper/status'),+ await request(app).post('/api/beeper/status/check'),+ await request(app).delete('/api/beeper/token'),+ ];++ logSpy.mockRestore();+ errSpy.mockRestore();+ warnSpy.mockRestore();++ for (const res of responses) {+ // Covers the redirect's landing URL too — the callback app above reports+ // it as `landedOn`, so a token smuggled into a query param would show up.+ expect(JSON.stringify(res.body ?? null)).not.toContain(TOKEN);+ expect(res.text || '').not.toContain(TOKEN);+ }+ expect(written.join('\n')).not.toContain(TOKEN);+ // The service DID receive it — this is a leak test, not a plumbing bug.+ expect(connectWithPastedToken).toHaveBeenCalledWith(TOKEN);+ });+});++// The outbox routes (#36). The service's own gates are covered in+// `services/beeperOutbox.test.js`; this pins the HTTP contract the composer+// codes against — validation, the coded 4xx map, and `retryable: false` on+// every write path so a client can never turn one refusal into two messages.+describe('POST /api/beeper/outbox — step one, create the entry', () => {+ beforeEach(() => vi.clearAllMocks());+ const CONVERSATION_ID = '11111111-1111-4111-8111-111111111111';++ it('creates an approved entry and answers 201', async () => {+ vi.mocked(createOutboxEntry).mockResolvedValue({ id: 'outbox-1', state: 'approved' });+ const res = await request(buildApp())+ .post('/api/beeper/outbox')+ .send({ conversationId: CONVERSATION_ID, body: 'hello there' });+ expect(res.status).toBe(201);+ expect(res.body).toEqual({ id: 'outbox-1', state: 'approved' });+ expect(createOutboxEntry).toHaveBeenCalledWith({ conversationId: CONVERSATION_ID, body: 'hello there' });+ });++ it('400s a malformed body without touching the service', async () => {+ const res = await request(buildApp()).post('/api/beeper/outbox').send({ body: 'no conversation' });+ expect(res.status).toBe(400);+ expect(createOutboxEntry).not.toHaveBeenCalled();+ });+});++describe('POST /api/beeper/outbox/:id/send — step two, the send', () => {+ beforeEach(() => vi.clearAllMocks());+ const ENTRY_ID = '44444444-4444-4444-8444-444444444444';++ it('400s a malformed entry id before it reaches a query', async () => {+ const res = await request(buildApp()).post('/api/beeper/outbox/not-a-uuid/send').send({});+ expect(res.status).toBe(400);+ expect(sendOutboxEntry).not.toHaveBeenCalled();+ });++ it('passes the first-contact confirmation through explicitly', async () => {+ vi.mocked(sendOutboxEntry).mockResolvedValue({ id: 'outbox-1', state: 'awaiting-confirmation' });+ const res = await request(buildApp())+ .post(`/api/beeper/outbox/${ENTRY_ID}/send`)+ .send({ confirmFirstContact: true });+ expect(res.status).toBe(200);+ expect(sendOutboxEntry).toHaveBeenCalledWith(ENTRY_ID, { confirmFirstContact: true });+ });++ it('defaults the confirmation to false when the field is absent', async () => {+ vi.mocked(sendOutboxEntry).mockResolvedValue({ id: 'outbox-1', state: 'awaiting-confirmation' });+ await request(buildApp()).post(`/api/beeper/outbox/${ENTRY_ID}/send`).send({});+ expect(sendOutboxEntry).toHaveBeenCalledWith(ENTRY_ID, { confirmFirstContact: false });+ });++ it('maps FIRST_CONTACT_CONFIRMATION_REQUIRED to a non-retryable 409', async () => {+ vi.mocked(sendOutboxEntry).mockRejectedValue(new BeeperApiError('confirm first contact', {+ status: 409, code: 'FIRST_CONTACT_CONFIRMATION_REQUIRED', retryable: false,+ }));+ const res = await request(buildApp()).post(`/api/beeper/outbox/${ENTRY_ID}/send`).send({});+ expect(res.status).toBe(409);+ expect(res.body.code).toBe('FIRST_CONTACT_CONFIRMATION_REQUIRED');+ expect(res.body.context.retryable).toBe(false);+ });++ it('maps the open breaker to 429 and a transport failure to a non-retryable 503', async () => {+ vi.mocked(sendOutboxEntry).mockRejectedValue(new BeeperApiError('breaker open', {+ status: 429, code: 'OUTBOX_BREAKER_OPEN', retryable: false,+ }));+ const blocked = await request(buildApp()).post(`/api/beeper/outbox/${ENTRY_ID}/send`).send({});+ expect(blocked.status).toBe(429);++ // status:0 on the source error — the mapper must never pass it through.+ vi.mocked(sendOutboxEntry).mockRejectedValue(new BeeperApiError('Beeper request failed', {+ status: 0, code: 'NETWORK_ERROR', retryable: false,+ }));+ const failed = await request(buildApp()).post(`/api/beeper/outbox/${ENTRY_ID}/send`).send({});+ expect(failed.status).toBe(503);+ expect(failed.body.context.retryable).toBe(false);+ });+});++// The reviewer's blocker on #53: cancelling the first-contact confirmation+// left the row `approved` and rendered forever — a phantom pending-send+// bubble with no route to remove it. This is the discard "Cancel" now calls.+describe('DELETE /api/beeper/outbox/:id — discard the "Cancel" path', () => {+ beforeEach(() => vi.clearAllMocks());+ const ENTRY_ID = '44444444-4444-4444-8444-444444444444';++ it('400s a malformed entry id before it reaches the service', async () => {+ const res = await request(buildApp()).delete('/api/beeper/outbox/not-a-uuid');+ expect(res.status).toBe(400);+ expect(discardOutboxEntry).not.toHaveBeenCalled();+ });++ it('discards and answers 204 with no content', async () => {+ vi.mocked(discardOutboxEntry).mockResolvedValue(undefined);+ const res = await request(buildApp()).delete(`/api/beeper/outbox/${ENTRY_ID}`);+ expect(res.status).toBe(204);+ expect(res.text).toBe('');+ expect(discardOutboxEntry).toHaveBeenCalledWith(ENTRY_ID);+ });++ it('maps an unknown entry to a non-retryable 404', async () => {+ vi.mocked(discardOutboxEntry).mockRejectedValue(new BeeperApiError('Outbox entry not found', {+ status: 404, code: 'OUTBOX_ENTRY_NOT_FOUND', retryable: false,+ }));+ const res = await request(buildApp()).delete(`/api/beeper/outbox/${ENTRY_ID}`);+ expect(res.status).toBe(404);+ expect(res.body.code).toBe('OUTBOX_ENTRY_NOT_FOUND');+ expect(res.body.context.retryable).toBe(false);+ });++ it('maps a row that has already left "approved" to a non-retryable 409', async () => {+ vi.mocked(discardOutboxEntry).mockRejectedValue(new BeeperApiError('already sent', {+ status: 409, code: 'OUTBOX_INVALID_STATE', retryable: false,+ }));+ const res = await request(buildApp()).delete(`/api/beeper/outbox/${ENTRY_ID}`);+ expect(res.status).toBe(409);+ expect(res.body.context.retryable).toBe(false);+ });+});++describe('GET /api/beeper/outbox and the breaker reset', () => {+ beforeEach(() => vi.clearAllMocks());++ it('lists one conversation\'s entries', async () => {+ vi.mocked(listOutboxEntries).mockResolvedValue([{ id: 'outbox-1', state: 'failed' }]);+ const res = await request(buildApp())+ .get('/api/beeper/outbox?conversationId=11111111-1111-4111-8111-111111111111');+ expect(res.status).toBe(200);+ expect(res.body.entries).toHaveLength(1);+ });++ it('clears the breaker on an explicit human POST', async () => {+ vi.mocked(clearOutboxBreaker).mockReturnValue({ tripped: false, reason: null });+ const res = await request(buildApp()).post('/api/beeper/outbox/breaker/clear');+ expect(res.status).toBe(200);+ expect(res.body.tripped).toBe(false);+ expect(clearOutboxBreaker).toHaveBeenCalledTimes(1);+ });+});++// ---------------------------------------------------------------------------+// Chat surface (#35)+// ---------------------------------------------------------------------------++const CONV_ID = '11111111-1111-4111-8111-111111111111';++describe('GET /api/beeper/conversations — filters', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.mocked(listConversations).mockResolvedValue({ conversations: [], nextCursor: null });+ });++ it('passes every supported filter through, with query-string booleans parsed as booleans', async () => {+ const res = await request(buildApp())+ .get('/api/beeper/conversations?network=examplenet&unreadOnly=true&archived=false&lowPriority=false&limit=25');+ expect(res.status).toBe(200);+ expect(listConversations).toHaveBeenCalledWith({+ network: 'examplenet', unreadOnly: true, archived: false, lowPriority: false, limit: 25,+ });+ });++ it('omits an absent filter entirely rather than defaulting it to false', async () => {+ await request(buildApp()).get('/api/beeper/conversations');+ expect(listConversations).toHaveBeenCalledWith({});+ });++ it('rejects a non-boolean filter value instead of coercing it', async () => {+ const res = await request(buildApp()).get('/api/beeper/conversations?archived=yes');+ expect(res.status).toBe(400);+ expect(listConversations).not.toHaveBeenCalled();+ });++ it('forwards the pagination cursor untouched', async () => {+ vi.mocked(listConversations).mockResolvedValue({ conversations: [], nextCursor: 'next-page-token' });+ const res = await request(buildApp()).get('/api/beeper/conversations?cursor=abc123');+ expect(listConversations).toHaveBeenCalledWith({ cursor: 'abc123' });+ expect(res.body.nextCursor).toBe('next-page-token');+ });+});++describe('GET /api/beeper/conversations/:id and its messages', () => {+ beforeEach(() => vi.clearAllMocks());++ it('404s an unknown conversation so a stale deep link degrades to not-found', async () => {+ vi.mocked(getConversation).mockResolvedValue(null);+ const res = await request(buildApp()).get(`/api/beeper/conversations/${CONV_ID}`);+ expect(res.status).toBe(404);+ // Standard error envelope: { error, code, timestamp } — same shape+ // errorMiddleware stamps everywhere else (regression for the hand-rolled+ // res.status(404).json(...) this route used to write itself).+ expect(res.body.code).toBe('NOT_FOUND');+ expect(typeof res.body.timestamp).toBe('number');+ });++ it('marks the 404 severity: warning (mediaJobs.js GET /:id pattern) so it still reaches errorEvents but skips the global toast and the server console.error', async () => {+ vi.mocked(getConversation).mockResolvedValue(null);+ const emit = vi.fn();+ const capturedErrors = [];+ const onError = (error) => capturedErrors.push(error);+ errorEvents.on('error', onError);+ const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ try {+ const app = buildApp();+ app.set('io', { emit });+ const res = await request(app).get(`/api/beeper/conversations/${CONV_ID}`);+ expect(res.status).toBe(404);+ // Still reaches the error broadcast — item 1's envelope/broadcast+ // contract is unchanged, only the presentation drops.+ expect(capturedErrors).toHaveLength(1);+ expect(capturedErrors[0].severity).toBe('warning');+ expect(emit).toHaveBeenCalledWith('error:occurred', expect.objectContaining({+ code: 'NOT_FOUND',+ severity: 'warning',+ }));+ // ...but does not write the server console.error a plain (non-warning)+ // error would — that log line, repeated on every ~350ms refetch of a+ // stale deep link, is exactly what this severity opts out of.+ expect(consoleErrorSpy).not.toHaveBeenCalled();+ } finally {+ errorEvents.off('error', onError);+ consoleErrorSpy.mockRestore();+ }+ });++ it('rejects a non-uuid conversation id before it reaches the store', async () => {+ const res = await request(buildApp()).get('/api/beeper/conversations/not-a-uuid');+ expect(res.status).toBe(400);+ expect(getConversation).not.toHaveBeenCalled();+ });++ it('paginates the thread and answers an empty page with 200, not an error', async () => {+ vi.mocked(listMessages).mockResolvedValue({ messages: [], nextCursor: null });+ const res = await request(buildApp()).get(`/api/beeper/conversations/${CONV_ID}/messages?limit=20&cursor=abc`);+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ messages: [], nextCursor: null });+ expect(listMessages).toHaveBeenCalledWith(CONV_ID, { limit: 20, cursor: 'abc' });+ });+});++describe('GET /api/beeper/networks', () => {+ it('returns the rail scopes derived from the mirror', async () => {+ vi.mocked(listNetworks).mockResolvedValue([{ network: 'examplenet', unreadCount: 2 }]);+ const res = await request(buildApp()).get('/api/beeper/networks');+ expect(res.status).toBe(200);+ expect(res.body.networks).toEqual([{ network: 'examplenet', unreadCount: 2 }]);+ });+});++// The two rail controls #9 wired. The contract worth pinning is not that they+// succeed but how they FAIL: a Beeper write has no idempotency key, so the+// error a client sees must never advertise retry-safety.+describe('archive / low-priority write paths', () => {+ beforeEach(() => vi.clearAllMocks());++ it('archives through the service and returns the updated conversation', async () => {+ vi.mocked(setConversationArchived).mockResolvedValue({ id: CONV_ID, isArchived: true });+ const res = await request(buildApp())+ .post(`/api/beeper/conversations/${CONV_ID}/archive`)+ .send({ archived: true });+ expect(res.status).toBe(200);+ expect(setConversationArchived).toHaveBeenCalledWith(CONV_ID, true);+ expect(res.body.isArchived).toBe(true);+ });++ it('sets low priority through the service', async () => {+ vi.mocked(setConversationLowPriority).mockResolvedValue({ id: CONV_ID, isLowPriority: true });+ const res = await request(buildApp())+ .post(`/api/beeper/conversations/${CONV_ID}/low-priority`)+ .send({ lowPriority: true });+ expect(res.status).toBe(200);+ expect(setConversationLowPriority).toHaveBeenCalledWith(CONV_ID, true);+ });++ it('rejects a missing/again non-boolean flag before any upstream write', async () => {+ const res = await request(buildApp())+ .post(`/api/beeper/conversations/${CONV_ID}/archive`)+ .send({ archived: 'yes' });+ expect(res.status).toBe(400);+ expect(setConversationArchived).not.toHaveBeenCalled();+ });++ it('maps a NETWORK_ERROR to 503 and reports retryable: false — never a raw status 0, never a retry hint', async () => {+ vi.mocked(setConversationArchived).mockRejectedValue(+ new BeeperApiError('Beeper request failed: connection refused', { status: 0, code: 'NETWORK_ERROR', retryable: false }),+ );+ const res = await request(buildApp())+ .post(`/api/beeper/conversations/${CONV_ID}/archive`)+ .send({ archived: true });+ expect(res.status).toBe(503);+ expect(res.body.code).toBe('NETWORK_ERROR');+ expect(res.body.context).toMatchObject({ retryable: false });+ });++ it('clamps an ordinarily-retryable upstream failure to retryable: false on a write path', async () => {+ vi.mocked(setConversationLowPriority).mockRejectedValue(+ new BeeperApiError('Too Many Requests', { status: 429, code: 'RATE_LIMITED', retryable: false }),+ );+ const res = await request(buildApp())+ .post(`/api/beeper/conversations/${CONV_ID}/low-priority`)+ .send({ lowPriority: true });+ expect(res.status).toBe(429);+ expect(res.body.context).toMatchObject({ retryable: false });+ });++ it('calls the upstream write exactly once — the route never retries', async () => {+ vi.mocked(setConversationArchived).mockRejectedValue(+ new BeeperApiError('Bad Gateway', { status: 502, code: 'UPSTREAM_ERROR', retryable: true }),+ );+ await request(buildApp())+ .post(`/api/beeper/conversations/${CONV_ID}/archive`)+ .send({ archived: false });+ expect(setConversationArchived).toHaveBeenCalledTimes(1);+ });+});++// The LOCAL "seen in PortOS" watermark (#83) — the opposite risk profile from+// the archive/low-priority block above: this route never reaches Beeper, so+// what's worth pinning is the id validation and that the service, not the+// route, decides the response shape.+describe('POST /api/beeper/conversations/:id/seen', () => {+ beforeEach(() => vi.clearAllMocks());++ it('marks the conversation seen through the service and returns the updated conversation', async () => {+ vi.mocked(markConversationSeen).mockResolvedValue({ id: CONV_ID, unreadCount: 0 });+ const res = await request(buildApp()).post(`/api/beeper/conversations/${CONV_ID}/seen`);+ expect(res.status).toBe(200);+ expect(markConversationSeen).toHaveBeenCalledWith(CONV_ID);+ expect(res.body).toEqual({ id: CONV_ID, unreadCount: 0 });+ });++ it('rejects a non-uuid conversation id before it reaches the service', async () => {+ const res = await request(buildApp()).post('/api/beeper/conversations/not-a-uuid/seen');+ expect(res.status).toBe(400);+ expect(markConversationSeen).not.toHaveBeenCalled();+ });++ it('404s an unknown conversation', async () => {+ vi.mocked(markConversationSeen).mockRejectedValue(+ new ServerError('Conversation not found', { status: 404, code: 'NOT_FOUND' }),+ );+ const res = await request(buildApp()).post(`/api/beeper/conversations/${CONV_ID}/seen`);+ expect(res.status).toBe(404);+ expect(res.body.code).toBe('NOT_FOUND');+ });+});++describe('attachment mirror routes (#37)', () => {+ beforeEach(() => vi.clearAllMocks());++ it('serves the bytes from disk with the STORED mime type, not the file extension', async () => {+ vi.mocked(ensureAttachmentBytes).mockResolvedValue({+ filePath: '/data/beeper/attachments/ab/abc.bin', mimeType: 'image/png', fileName: 'example.png', cached: true,+ });+ const res = await request(buildApp()).get('/api/beeper/attachments/msg-1/0');+ expect(res.status).toBe(200);+ expect(vi.mocked(ensureAttachmentBytes)).toHaveBeenCalledWith('msg-1', 0);+ const [, dir, filename, options] = vi.mocked(serveLocalFile).mock.calls[0];+ expect(dir).toBe('/data/beeper/attachments/ab');+ expect(filename).toBe('abc.bin');+ expect(options.contentType).toBe('image/png');+ });++ // SEC-4: GET is a safe method — no query param may raise the size ceiling or+ // clear a terminal refusal. `force=true` on the query string is simply+ // ignored (not rejected, since GET no longer parses `force` at all), and the+ // call into the service carries no `force` option regardless of what the+ // query string says.+ it('ignores a force=true query string — GET never asks the service to force a fetch', async () => {+ vi.mocked(ensureAttachmentBytes).mockResolvedValue({ filePath: '/x/y.bin', mimeType: '', fileName: '', cached: true });+ await request(buildApp()).get('/api/beeper/attachments/msg-1/0?force=true');+ expect(vi.mocked(ensureAttachmentBytes)).toHaveBeenCalledWith('msg-1', 0);+ });++ it('still answers 413 over-cap even with force=true on the query string — the ceiling is not bypassable from GET', async () => {+ vi.mocked(ensureAttachmentBytes).mockRejectedValue(new ServerError('Attachment is 40000000 bytes, over the 33554432-byte mirror ceiling', {+ status: 413, code: 'ATTACHMENT_TOO_LARGE', context: { bytes: 40000000, maxBytes: 33554432 },+ }));+ const res = await request(buildApp()).get('/api/beeper/attachments/msg-1/0?force=true');+ expect(res.status).toBe(413);+ expect(vi.mocked(ensureAttachmentBytes)).toHaveBeenCalledWith('msg-1', 0);+ });++ it('still answers 404 ASSET_UNAVAILABLE even with force=true on the query string — a safe method cannot clear the terminal refusal', async () => {+ vi.mocked(ensureAttachmentBytes).mockRejectedValue(new ServerError('Beeper can no longer supply this attachment', {+ status: 404, code: 'ASSET_UNAVAILABLE',+ }));+ const res = await request(buildApp()).get('/api/beeper/attachments/msg-1/0?force=true');+ expect(res.status).toBe(404);+ expect(res.body.code).toBe('ASSET_UNAVAILABLE');+ expect(vi.mocked(ensureAttachmentBytes)).toHaveBeenCalledWith('msg-1', 0);+ });++ it('answers an over-cap attachment with 413 and carries the measured size into the envelope', async () => {+ vi.mocked(ensureAttachmentBytes).mockRejectedValue(new ServerError('Attachment is 40000000 bytes, over the 33554432-byte mirror ceiling', {+ status: 413, code: 'ATTACHMENT_TOO_LARGE', context: { bytes: 40000000, maxBytes: 33554432 },+ }));+ const res = await request(buildApp()).get('/api/beeper/attachments/msg-1/0');+ expect(res.status).toBe(413);+ expect(res.body.code).toBe('ATTACHMENT_TOO_LARGE');+ // The mapper builds a fresh ServerError, so the size the service measured+ // reaches the client only because the mapper rebuilds the context.+ expect(res.body.context).toMatchObject({ bytes: 40000000, maxBytes: 33554432 });+ });++ it('maps a source that can no longer supply the asset to 404 ASSET_UNAVAILABLE, never a 502 retry', async () => {+ vi.mocked(ensureAttachmentBytes).mockRejectedValue(+ new BeeperApiError('Failed to download asset', { status: 502, code: 'ASSET_UNAVAILABLE', retryable: false }),+ );+ const res = await request(buildApp()).get('/api/beeper/attachments/msg-1/0');+ expect(res.status).toBe(404);+ expect(res.body.code).toBe('ASSET_UNAVAILABLE');+ });++ it('forces the fetch on "fetch anyway" and answers with the refreshed row', async () => {+ vi.mocked(ensureAttachmentBytes).mockResolvedValue({ filePath: '/x/y.png', mimeType: 'image/png', fileName: '', cached: false });+ vi.mocked(getAttachment).mockResolvedValue({ messageId: 'msg-1', idx: 0, stored: true, overCap: true });+ const res = await request(buildApp()).post('/api/beeper/attachments/msg-1/0/fetch');+ expect(res.status).toBe(200);+ expect(vi.mocked(ensureAttachmentBytes)).toHaveBeenCalledWith('msg-1', 0, { force: true });+ expect(res.body).toMatchObject({ stored: true, overCap: true });+ });++ it('toggles the keep lock', async () => {+ vi.mocked(setAttachmentKeep).mockResolvedValue({ messageId: 'msg-1', idx: 0, keep: true });+ const res = await request(buildApp())+ .patch('/api/beeper/attachments/msg-1/0')+ .send({ keep: true });+ expect(res.status).toBe(200);+ expect(vi.mocked(setAttachmentKeep)).toHaveBeenCalledWith('msg-1', 0, true);+ });++ it('rejects an unknown key on the keep body rather than ignoring it', async () => {+ const res = await request(buildApp())+ .patch('/api/beeper/attachments/msg-1/0')+ .send({ keep: true, evict: true });+ expect(res.status).toBe(400);+ expect(vi.mocked(setAttachmentKeep)).not.toHaveBeenCalled();+ });++ it('reports the backfill census without starting anything', async () => {+ vi.mocked(getAttachmentSummary).mockResolvedValue({+ budgetBytes: 5368709120, usedBytes: 1024, pendingCount: 12, pendingBytes: 4096, pendingUnknownCount: 1,+ });+ const res = await request(buildApp()).get('/api/beeper/attachments/summary');+ expect(res.status).toBe(200);+ expect(res.body).toMatchObject({ pendingCount: 12, pendingBytes: 4096, pendingUnknownCount: 1 });+ expect(vi.mocked(backfillAttachments)).not.toHaveBeenCalled();+ });++ it('runs the bulk backfill only on an explicit POST', async () => {+ vi.mocked(backfillAttachments).mockResolvedValue({ fetched: 3, failed: 1, bytes: 900, stoppedForBudget: false, requested: 4 });+ const res = await request(buildApp()).post('/api/beeper/attachments/backfill').send({});+ expect(res.status).toBe(200);+ expect(res.body).toMatchObject({ fetched: 3, failed: 1 });+ });++ it('purges one conversation mirror and reports the bytes it freed', async () => {+ vi.mocked(purgeConversation).mockResolvedValue({+ purged: true, conversationId: CONV_ID, messagesRemoved: 12, filesRemoved: 3, bytesFreed: 4096,+ });+ const res = await request(buildApp()).delete(`/api/beeper/conversations/${CONV_ID}`);+ expect(res.status).toBe(200);+ expect(res.body).toMatchObject({ purged: true, filesRemoved: 3, bytesFreed: 4096 });+ });+});diff --git a/server/routes/settings.js b/server/routes/settings.jsindex e7ede70985..0c57ad3a1e 100644--- a/server/routes/settings.js+++ b/server/routes/settings.js@@ -22,7 +22,7 @@ import { isPlainObject } from '../lib/objects.js';import { DEFAULT_UNTRUSTED_CONTENT_POLICY, untrustedContentSettingsSchema } from '../lib/untrustedContent.js';import { agentContextSettingsSchema } from '../lib/agentContextValidation.js';import { EFFORT_LEVELS } from '../lib/providerModels.js';-import { privateCredentialParamsSchema, privateCredentialInputSchema, backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, autofixerSettingsSchema, codeReviewSettingsSchema, locationSettingsSchema, hideFirstRunCardSchema, networkSetupPreferenceSchema, settingsEmbeddingsSchema, localLlmSettingsSchema, imessageConfigSchema, signalConfigSchema, spotifyConfigSchema, youtubeConfigSchema, apiAccessSettingsSchema, instanceFeatureSettingsSchema, instanceFeatureIdSchema, instanceFeatureUpdateSchema, instanceFeatureGroupSettingsSchema, instanceFeatureGroupIdSchema, instanceFeatureGroupUpdateSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, musicSettingsSchema, federationSettingsSchema, privacySettingsSchema, seriesAutopilotSettingsSchema, layeredIntelligenceSettingsSchema, imageGenGrokSettingsSchema, imageGenAgySettingsSchema, renderDefaultsSettingsSchema, videoGenSettingsSchema, subscriptionCostsMapSchema, usageApiBilledInstanceIdsSchema, namedOrchestrationProfileSchema, orchestrationProfilesSettingsSchema, validateRequest } from '../lib/validation.js';+import { privateCredentialParamsSchema, privateCredentialInputSchema, backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, autofixerSettingsSchema, codeReviewSettingsSchema, locationSettingsSchema, hideFirstRunCardSchema, networkSetupPreferenceSchema, settingsEmbeddingsSchema, localLlmSettingsSchema, imessageConfigSchema, signalConfigSchema, beeperSettingsSchema, spotifyConfigSchema, youtubeConfigSchema, apiAccessSettingsSchema, instanceFeatureSettingsSchema, instanceFeatureIdSchema, instanceFeatureUpdateSchema, instanceFeatureGroupSettingsSchema, instanceFeatureGroupIdSchema, instanceFeatureGroupUpdateSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, musicSettingsSchema, federationSettingsSchema, privacySettingsSchema, seriesAutopilotSettingsSchema, layeredIntelligenceSettingsSchema, imageGenGrokSettingsSchema, imageGenAgySettingsSchema, renderDefaultsSettingsSchema, videoGenSettingsSchema, subscriptionCostsMapSchema, usageApiBilledInstanceIdsSchema, namedOrchestrationProfileSchema, orchestrationProfilesSettingsSchema, validateRequest } from '../lib/validation.js';const router = Router();@@ -73,6 +73,16 @@ const redactExternalTokens = (settings) => {const { apiKey, ...rest } = next.civitai;next.civitai = rest;}+ // Beeper access token (#30/#31) — write-only, same posture as+ // imageGen.hfToken / civitai.apiKey above. Since #31 the live credential is+ // AES-256-GCM in `beeper_credentials`, not here; this strip covers the LEGACY+ // plaintext field, which `beeperCredentials.resolveBeeperToken` still reads as+ // a fallback for an install that hand-edited one. Nothing writes it, and it+ // must never be echoed back to the client on a settings GET.+ if (isPlainObject(next.beeper)) {+ const { token, ...rest } = next.beeper;+ next.beeper = rest;+ }return next;};@@ -111,6 +121,15 @@ const preserveExternallyOwnedKeys = (next, current) => {carryOver('imageGen', 'hfToken');carryOver('civitai', 'apiKey');carryOver('videoGen', 'acceptedModelTerms', { alwaysStored: true });+ // beeperSettingsSchema is `.strict()` with no `token`/`tokenExpiresAt`+ // field, so a valid `beeper` PUT through this route can never carry either+ // — without this, the generic top-level shallow merge (`{ ...current,+ // ...settingsPatch }`) would REPLACE `current.beeper` wholesale and silently+ // wipe out a legacy hand-edited token that `resolveBeeperToken` still falls+ // back to (#31's own credential lives in Postgres, out of reach of this+ // route entirely).+ carryOver('beeper', 'token');+ carryOver('beeper', 'tokenExpiresAt');return next;};@@ -221,20 +240,61 @@ router.post('/features/eidoverse/host', asyncHandler(async (_req, res) => {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) {+ 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 })+ .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 || {});- res.json(await updateInstanceFeature(featureId, enabled));+ const result = await updateInstanceFeature(featureId, enabled);+ if (featureId === 'beeper') await reconcileBeeperArming('feature-toggle');+ res.json(result);}));// PUT /api/settings/features/groups/:groupId (#40)router.put('/features/groups/:groupId', asyncHandler(async (req, res) => {const groupId = validateRequest(instanceFeatureGroupIdSchema, req.params.groupId);const { enabled } = validateRequest(instanceFeatureGroupUpdateSchema, req.body || {});- res.json(await updateInstanceFeatureGroup(groupId, enabled));+ const result = await updateInstanceFeatureGroup(groupId, enabled);+ if (groupId === BEEPER_FEATURE_GROUP) await reconcileBeeperArming('feature-group-toggle');+ res.json(result);}));// PUT /api/settings/ai-assignments/:id@@ -353,6 +413,20 @@ router.put('/', asyncHandler(async (req, res) => {if (req.body?.signal !== undefined) {validateRequest(signalConfigSchema.partial(), req.body.signal);}+ // Beeper Desktop bridge ingestion + connection config (#30) — validate the+ // slice when present so a malformed enabled/interval/baseUrl/budget can't+ // reach disk. `beeperSettingsSchema` is `.strict()` and deliberately has no+ // `token`/`tokenExpiresAt` field, so a client attempting to smuggle a token+ // through this generic route 400s instead of it silently reaching disk —+ // the credential's own write path is POST/DELETE /api/beeper/token (#31),+ // which stores it AES-256-GCM encrypted in Postgres. Used directly, NOT+ // `.partial()`: every field is already individually `.optional()` (so+ // `.partial()` was a no-op), and the schema's `superRefine` (SEC-2's+ // loopback-only `baseUrl` gate) returns a `ZodEffects`, which has no+ // `.partial()` method at all.+ if (req.body?.beeper !== undefined) {+ validateRequest(beeperSettingsSchema, req.body.beeper);+ }// Spotify ingestion config (#2152) — validate the slice when present so a// malformed enabled/interval can't reach disk and break the sync scheduler.if (req.body?.spotify !== undefined) {@@ -480,11 +554,54 @@ router.put('/', asyncHandler(async (req, res) => {// `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 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;+ 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');+ }if (subscriptionCostsPatch !== undefined) {const costs = await saveSubscriptionCosts(subscriptionCostsPatch, { actor: 'user' });merged = { ...merged, subscriptionCosts: costs };diff --git a/server/routes/settings.test.js b/server/routes/settings.test.jsindex ed201b47fd..cc7032dfba 100644--- a/server/routes/settings.test.js+++ b/server/routes/settings.test.js@@ -63,8 +63,31 @@ vi.mock('../services/eidoverseHost.js', () => ({vi.mock('../services/credentialInventory.js', () => ({getCredentialInventory: vi.fn(async () => ({ headline: 'Most of PortOS works with no key at all.', credentials: [] })),}));+// The Beeper feature toggle now reconciles the sweep + realtime transport+// against the gate it just moved (fork issue #1). Mocked here because the real+// module reaches the whole Beeper service graph; what a reconcile actually does+// is covered by services/beeperArming.test.js.+vi.mock('../services/beeperArming.js', () => ({+ reconcileBeeperIngestion: vi.fn(async () => ({ armed: false, changed: false })),+}));+// The interval-change half of fork issue #79: a Beeper save that changes only+// `intervalMinutes` restarts the scheduler directly rather than going through+// `reconcileBeeperIngestion` (that stays reserved for an `enabled` flip). Mocked+// for the same reason `beeperArming.js` is above — what a restart actually does+// is covered by services/beeperScheduler.test.js.+// `isBeeperSchedulerRegistered` defaults to `false` (mimicking a scheduler+// that was never registered) so the existing interval-change tests below,+// which never set this, keep exercising that path; the fork issue #94 test+// under "beeper sync-toggle arming" overrides it to `true` for the+// already-registered case.+vi.mock('../services/beeperScheduler.js', () => ({+ restartBeeperScheduler: vi.fn(async () => {}),+ isBeeperSchedulerRegistered: vi.fn(() => false),+}));import settingsRoutes from './settings.js';+import { reconcileBeeperIngestion } from '../services/beeperArming.js';+import { restartBeeperScheduler, isBeeperSchedulerRegistered } from '../services/beeperScheduler.js';import { updateSettingsWith } from '../services/settings.js';import { hasConfiguredInstances as hasConfiguredDatadogInstances } from '../services/datadog.js';import { hasConfiguredInstances as hasConfiguredJiraInstances } from '../services/jira.js';@@ -188,6 +211,11 @@ describe('Settings routes — instance feature participation', () => {expect(res.body.features).toContainEqual(expect.objectContaining({ id: 'gsd', enabled: false }));expect(res.body.features).toContainEqual(expect.objectContaining({ id: 'openclaw', enabled: false }));expect(res.body.features).toContainEqual(expect.objectContaining({ id: 'health', enabled: true }));+ // #40 — iMessage and Signal join the comms group, defaulting to enabled+ // with no settings write, exactly like an existing install saw before.+ expect(res.body.features).toContainEqual(expect.objectContaining({ id: 'imessage', enabled: true, group: 'comms' }));+ expect(res.body.features).toContainEqual(expect.objectContaining({ id: 'signal', enabled: true, group: 'comms' }));+ expect(res.body.groups).toContainEqual(expect.objectContaining({ id: 'comms', enabled: true }));});it('lists an integration-backed feature as auto-enabled when its detector finds configuration', async () => {@@ -229,6 +257,31 @@ describe('Settings routes — instance feature participation', () => {expect(res.status).toBe(200);expect(res.body.features).toContainEqual(expect.objectContaining({ id: 'post', enabled: false }));expect(store).toEqual({ theme: 'dark', instanceFeatures: { post: { enabled: false } } });+ // Only Beeper's own gate is reconciled; an unrelated toggle must not reach+ // into the Beeper service graph at all.+ expect(reconcileBeeperIngestion).not.toHaveBeenCalled();+ });++ // Fork issue #1, final live pass: the Beeper sweep + realtime transport arm on+ // the instance feature plus a token, and that gate was read at boot only — so+ // turning the feature on left both down until the next restart.+ it('reconciles Beeper ingestion when the Beeper feature is toggled', async () => {+ const res = await request(buildApp())+ .put('/api/settings/features/beeper')+ .send({ enabled: true });++ expect(res.status).toBe(200);+ expect(reconcileBeeperIngestion).toHaveBeenCalledWith({ reason: 'feature-toggle' });+ });++ // Beeper sits in the Comms group, so the group toggle moves the same gate.+ it('reconciles Beeper ingestion when the Comms group is toggled', async () => {+ const res = await request(buildApp())+ .put('/api/settings/features/groups/comms')+ .send({ enabled: false });++ expect(res.status).toBe(200);+ expect(reconcileBeeperIngestion).toHaveBeenCalledWith({ reason: 'feature-group-toggle' });});it('installs and explicitly enables Eidoverse from its consent endpoint', async () => {@@ -296,6 +349,96 @@ describe('Settings routes — instance feature participation', () => {expect(installEidoverse).not.toHaveBeenCalled();});+ it('clears a grouped feature override back to inherit with enabled: null', async () => {+ store = { instanceFeatures: { facetime: { enabled: true } } };++ const res = await request(buildApp())+ .put('/api/settings/features/facetime')+ .send({ enabled: null });++ expect(res.status).toBe(200);+ expect(store).toEqual({ instanceFeatures: {} });+ // This suite doesn't mock voice/facetimeBridge.js, so only the storage and+ // the no-longer-`explicit` source are pinned — the resolved boolean depends+ // on the real (unmocked) detector's answer on the machine running the test.+ const facetime = res.body.features.find((f) => f.id === 'facetime');+ expect(facetime.source).not.toBe('explicit');+ });++ it('uses iMessage as a grouped feature with no override to prove the same clear-to-inherit path on a feature with no detector', async () => {+ store = { instanceFeatures: { imessage: { enabled: false } } };++ const res = await request(buildApp())+ .put('/api/settings/features/imessage')+ .send({ enabled: null });++ expect(res.status).toBe(200);+ expect(store).toEqual({ instanceFeatures: {} });+ expect(res.body.features).toContainEqual(expect.objectContaining({ id: 'imessage', enabled: true, source: 'default' }));+ });++ it('toggles the comms feature group and reflects it on the group and member list', async () => {+ const res = await request(buildApp())+ .put('/api/settings/features/groups/comms')+ .send({ enabled: false });++ expect(res.status).toBe(200);+ expect(store).toEqual({ instanceFeatureGroups: { comms: { enabled: false } } });+ expect(res.body.groups).toContainEqual(expect.objectContaining({ id: 'comms', enabled: false }));+ expect(res.body.features).toContainEqual(expect.objectContaining({ id: 'imessage', enabled: false, source: 'group-off' }));+ });++ it('lets an explicit per-feature override outrank an off group', async () => {+ store = { instanceFeatureGroups: { comms: { enabled: false } } };++ const res = await request(buildApp())+ .put('/api/settings/features/imessage')+ .send({ enabled: true });++ expect(res.status).toBe(200);+ expect(res.body.features).toContainEqual(expect.objectContaining({ id: 'imessage', enabled: true, source: 'explicit' }));+ // Signal has no override of its own, so it stays hidden by the off group.+ expect(res.body.features).toContainEqual(expect.objectContaining({ id: 'signal', enabled: false, source: 'group-off' }));+ });++ it('rejects an unknown feature group id and a non-boolean group enabled value', async () => {+ const unknown = await request(buildApp())+ .put('/api/settings/features/groups/not-registered')+ .send({ enabled: false });+ const malformed = await request(buildApp())+ .put('/api/settings/features/groups/comms')+ .send({ enabled: 'false' });+ // Unlike the per-feature route, a group has no inherit state of its own —+ // null is rejected rather than treated as a third value.+ const nullEnabled = await request(buildApp())+ .put('/api/settings/features/groups/comms')+ .send({ enabled: null });++ expect(unknown.status).toBe(400);+ expect(malformed.status).toBe(400);+ expect(nullEnabled.status).toBe(400);+ expect(unknown.body.code).toBe('VALIDATION_ERROR');+ expect(malformed.body.code).toBe('VALIDATION_ERROR');+ expect(nullEnabled.body.code).toBe('VALIDATION_ERROR');+ });++ it('validates the instanceFeatureGroups slice on the generic settings PUT', async () => {+ const ok = await request(buildApp())+ .put('/api/settings')+ .send({ instanceFeatureGroups: { comms: { enabled: false } } });+ const malformed = await request(buildApp())+ .put('/api/settings')+ .send({ instanceFeatureGroups: { comms: { enabled: 'nope' } } });+ const unknownGroup = await request(buildApp())+ .put('/api/settings')+ .send({ instanceFeatureGroups: { 'not-a-group': { enabled: false } } });++ expect(ok.status).toBe(200);+ expect(store.instanceFeatureGroups).toEqual({ comms: { enabled: false } });+ expect(malformed.status).toBe(400);+ expect(unknownGroup.status).toBe(400);+ });+it('rejects unknown feature ids and malformed enabled values', async () => {const unknown = await request(buildApp()).put('/api/settings/features/not-registered')@@ -685,6 +828,244 @@ describe('Settings routes — videoGen slice (#3231 Phase 4)', () => {});});+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('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 --git a/server/routes/tribe.js b/server/routes/tribe.jsindex d31010b75f..498372fe9e 100644--- a/server/routes/tribe.js+++ b/server/routes/tribe.js@@ -6,6 +6,7 @@ import { validateRequest, parsePagination } from '../lib/validation.js';import { partialWithoutDefaults } from '../lib/zodCompat.js';import * as tribe from '../services/tribe.js';import * as tribeOutreach from '../services/tribeOutreach.js';+import * as beeperTribe from '../services/beeperTribe.js';const router = Router();@@ -60,6 +61,38 @@ const memoryLinkSchema = z.object({note: z.string().max(1000).optional().default(''),});+// Beeper participant → Tribe linking (#34). conversationId/sourceUserId+// identify the beeper_participants row. No `network` field here on purpose:+// it used to be client-supplied and scoped a username-shaped identity claim,+// but that let a request omit it (writing an inert kind='handle' row no+// later lookup can ever match) or spoof a WRONG network (silently stealing+// another person's claim on a UNIQUE (kind, network, handle) collision) —+// see server/services/beeperTribe.js. The network is now derived server-side+// from the participant's own beeper_conversations.network; a phone-shaped+// claim stays network-less (see server/lib/tribeMatch.js).+const beeperLinkSchema = z.object({+ conversationId: z.string().guid(),+ sourceUserId: z.string().min(1).max(500),+ personId: z.string().guid(),+});++// Unlink a Beeper participant from whichever Tribe person currently owns it+// (#97 part B). Same identifying pair as `beeperLinkSchema` — no `personId`+// here, since unlink releases whatever the participant is CURRENTLY linked+// to, and is a no-op rather than an error when that is nothing.+const beeperUnlinkSchema = z.object({+ conversationId: z.string().guid(),+ sourceUserId: z.string().min(1).max(500),+});++const beeperCreateAndLinkSchema = z.object({+ conversationId: z.string().guid(),+ sourceUserId: z.string().min(1).max(500),+ name: z.string().min(1).max(200).optional(),+ ring: ringSchema.optional().default('tribe'),+ relationship: z.string().max(200).optional().default(''),+});+// Outreach draft generation (#2158). The seed fields come from a detected// unanswered thread; the LLM call happens only on this explicit POST (user action)// per the AI-provider policy — never from the detection sweep.@@ -99,6 +132,7 @@ const guidParam = (label) => (req, res, next, value) => {};router.param('id', guidParam('person id'));router.param('memoryId', guidParam('memory id'));+router.param('identityId', guidParam('identity id'));router.get('/people', asyncHandler(async (req, res) => {const { search, ring } = validateRequest(listQuerySchema, req.query);@@ -150,10 +184,16 @@ router.post('/people', asyncHandler(async (req, res) => {res.status(201).json(person);}));+// `identities` (#99) is joined in here, not in `tribe.getPerson` itself —+// keeps the generic person read model Beeper-agnostic (see+// `beeperTribe.listPersonIdentitiesWithConversations`'s docblock) and keeps+// the join off `listPeople` (the roster), which never renders identity+// chips and shouldn't pay for the extra query per row.router.get('/people/:id', asyncHandler(async (req, res) => {const person = await tribe.getPerson(req.params.id);if (!person) throw new ServerError('Person not found', { status: 404 });- res.json(person);+ const identities = await beeperTribe.listPersonIdentitiesWithConversations(person.id);+ res.json({ ...person, identities });}));router.put('/people/:id', asyncHandler(async (req, res) => {@@ -210,4 +250,54 @@ router.delete('/people/:id/memories/:memoryId', asyncHandler(async (req, res) =>res.json({ success: true });}));+// Link a Beeper conversation participant to an EXISTING Tribe person — the+// inline thread-participant action decided on #10 (#34). Never creates a+// person; see POST /beeper/link-new for that. `displacedPersonId` is set+// when the participant's handle was already claimed by a DIFFERENT person —+// that ownership move is silent at the DB/audit-trigger level (see+// tribeIdentities.linkIdentity), so it is surfaced here instead.+router.post('/beeper/link', asyncHandler(async (req, res) => {+ const { conversationId, sourceUserId, personId } = validateRequest(beeperLinkSchema, req.body);+ const { displacedPersonId, ...participant } = await beeperTribe.linkParticipant({+ conversationId, sourceUserId, personId,+ });+ req.app.get('io')?.emit('tribe:changed', { personId });+ res.json({ participant, displacedPersonId: displacedPersonId || null });+}));++// Unlink a Beeper participant from whichever Tribe person currently owns it+// (#97 part B) — the counterpart POST /beeper/link never had. Idempotent: an+// already-unlinked participant is a 200 no-op with `unlinkedPersonId: null`.+// Releases every `tribe_identities` claim THAT person held for this+// participant (never one another person now holds on the same handle) and+// nulls the cache on this row and every other one those claims were backing+// — see `beeperTribe.unlinkParticipant`.+router.delete('/beeper/link', asyncHandler(async (req, res) => {+ const { conversationId, sourceUserId } = validateRequest(beeperUnlinkSchema, req.body);+ const { participant, unlinkedPersonId, removedClaims } = await beeperTribe.unlinkParticipant({+ conversationId, sourceUserId,+ });+ if (unlinkedPersonId) req.app.get('io')?.emit('tribe:changed', { personId: unlinkedPersonId });+ res.json({ participant, unlinkedPersonId, removedClaims });+}));++// Create a new Tribe person from a Beeper participant's own display name and+// link it in the same action — the other half of #10 decision 4.+router.post('/beeper/link-new', asyncHandler(async (req, res) => {+ const data = validateRequest(beeperCreateAndLinkSchema, req.body);+ const result = await beeperTribe.createPersonAndLinkParticipant(data);+ req.app.get('io')?.emit('tribe:changed', { personId: result.person.id });+ res.status(201).json(result);+}));++// Unlink one Beeper identity claim (#99) — the Tribe person form's+// per-identity "Unlink" action. `identityId` is the `tribe_identities.id`+// the person read model's `identities[]` carries, not a participant key.+router.delete('/beeper/identities/:identityId', asyncHandler(async (req, res) => {+ const identity = await beeperTribe.unlinkIdentity(req.params.identityId);+ if (!identity) throw new ServerError('Identity not found', { status: 404 });+ req.app.get('io')?.emit('tribe:changed', { personId: identity.personId });+ res.json({ success: true });+}));+export default router;diff --git a/server/routes/tribe.test.js b/server/routes/tribe.test.jsindex 4850839688..fd432d4e3a 100644--- a/server/routes/tribe.test.js+++ b/server/routes/tribe.test.js@@ -30,12 +30,23 @@ vi.mock('../services/tribeOutreach.js', () => ({generateOutreachDraft: vi.fn(),}));+vi.mock('../services/beeperTribe.js', () => ({+ linkParticipant: vi.fn(),+ unlinkParticipant: vi.fn(),+ createPersonAndLinkParticipant: vi.fn(),+ listPersonIdentitiesWithConversations: vi.fn(),+ unlinkIdentity: vi.fn(),+}));+import * as tribe from '../services/tribe.js';import * as tribeOutreach from '../services/tribeOutreach.js';+import * as beeperTribe from '../services/beeperTribe.js';const PERSON_ID = '11111111-1111-4111-8111-111111111111';const MEMORY_ID = '22222222-2222-4222-8222-222222222222';const ACCOUNT_ID = '33333333-3333-4333-8333-333333333333';+const CONVERSATION_ID = '55555555-5555-4555-8555-555555555555';+const IDENTITY_ID = '77777777-7777-4777-8777-777777777777';describe('Tribe Routes', () => {let app;@@ -270,6 +281,36 @@ describe('Tribe Routes', () => {const response = await request(app).get(`/api/tribe/people/${PERSON_ID}`);expect(response.status).toBe(404);+ expect(beeperTribe.listPersonIdentitiesWithConversations).not.toHaveBeenCalled();+ });++ it('merges the person read model with its linked Beeper identities (#99)', async () => {+ tribe.getPerson.mockResolvedValue({ id: PERSON_ID, name: 'Ada' });+ const identities = [+ {+ id: IDENTITY_ID, personId: PERSON_ID, kind: 'beeper-user', network: ACCOUNT_ID, handle: 'user-1',+ source: 'user', linkedAt: '2026-06-01T00:00:00.000Z',+ conversations: [{ conversationId: CONVERSATION_ID, network: 'whatsapp', title: 'Example Thread', accountId: ACCOUNT_ID, displayName: 'Example Person' }],+ },+ ];+ beeperTribe.listPersonIdentitiesWithConversations.mockResolvedValue(identities);++ const response = await request(app).get(`/api/tribe/people/${PERSON_ID}`);++ expect(response.status).toBe(200);+ expect(response.body.id).toBe(PERSON_ID);+ expect(response.body.identities).toEqual(identities);+ expect(beeperTribe.listPersonIdentitiesWithConversations).toHaveBeenCalledWith(PERSON_ID);+ });++ it('returns an empty identities array for a person with no Beeper claims', async () => {+ tribe.getPerson.mockResolvedValue({ id: PERSON_ID, name: 'Ada' });+ beeperTribe.listPersonIdentitiesWithConversations.mockResolvedValue([]);++ const response = await request(app).get(`/api/tribe/people/${PERSON_ID}`);++ expect(response.status).toBe(200);+ expect(response.body.identities).toEqual([]);});it('returns 404 when updating a missing person', async () => {@@ -339,4 +380,171 @@ describe('Tribe Routes', () => {expect(response.status).toBe(400);expect(tribeOutreach.generateOutreachDraft).not.toHaveBeenCalled();});++ describe('Beeper participant linking (#34)', () => {+ it('links a Beeper participant to an existing person', async () => {+ beeperTribe.linkParticipant.mockResolvedValue({+ conversationId: CONVERSATION_ID, sourceUserId: 'user-1', tribePersonId: PERSON_ID, displacedPersonId: null,+ });++ const response = await request(app)+ .post('/api/tribe/beeper/link')+ .send({ conversationId: CONVERSATION_ID, sourceUserId: 'user-1', personId: PERSON_ID });++ expect(response.status).toBe(200);+ expect(response.body.participant.tribePersonId).toBe(PERSON_ID);+ expect(response.body.displacedPersonId).toBeNull();+ // No `network` — it's derived server-side from the participant's own+ // conversation, never accepted from the request body (#34 review).+ expect(beeperTribe.linkParticipant).toHaveBeenCalledWith({+ conversationId: CONVERSATION_ID, sourceUserId: 'user-1', personId: PERSON_ID,+ });+ expect(emit).toHaveBeenCalledWith('tribe:changed', { personId: PERSON_ID });+ });++ it('surfaces a displaced person when the handle was already claimed by someone else', async () => {+ const OTHER_PERSON_ID = '66666666-6666-4666-8666-666666666666';+ beeperTribe.linkParticipant.mockResolvedValue({+ conversationId: CONVERSATION_ID, sourceUserId: 'user-1', tribePersonId: PERSON_ID, displacedPersonId: OTHER_PERSON_ID,+ });++ const response = await request(app)+ .post('/api/tribe/beeper/link')+ .send({ conversationId: CONVERSATION_ID, sourceUserId: 'user-1', personId: PERSON_ID });++ expect(response.status).toBe(200);+ expect(response.body.displacedPersonId).toBe(OTHER_PERSON_ID);+ expect(response.body.participant.displacedPersonId).toBeUndefined();+ });++ it('rejects a link request with a non-UUID personId', async () => {+ const response = await request(app)+ .post('/api/tribe/beeper/link')+ .send({ conversationId: CONVERSATION_ID, sourceUserId: 'user-1', personId: 'not-a-uuid' });++ expect(response.status).toBe(400);+ expect(beeperTribe.linkParticipant).not.toHaveBeenCalled();+ });++ it('unlinks a participant, removing its claims', async () => {+ beeperTribe.unlinkParticipant.mockResolvedValue({+ participant: { conversationId: CONVERSATION_ID, sourceUserId: 'user-1', tribePersonId: null },+ unlinkedPersonId: PERSON_ID,+ removedClaims: 2,+ });++ const response = await request(app)+ .delete('/api/tribe/beeper/link')+ .send({ conversationId: CONVERSATION_ID, sourceUserId: 'user-1' });++ expect(response.status).toBe(200);+ expect(response.body.participant.tribePersonId).toBeNull();+ expect(response.body.unlinkedPersonId).toBe(PERSON_ID);+ expect(response.body.removedClaims).toBe(2);+ expect(beeperTribe.unlinkParticipant).toHaveBeenCalledWith({+ conversationId: CONVERSATION_ID, sourceUserId: 'user-1',+ });+ expect(emit).toHaveBeenCalledWith('tribe:changed', { personId: PERSON_ID });+ });++ it('is a 200 no-op — with no socket emit — for an already-unlinked participant', async () => {+ beeperTribe.unlinkParticipant.mockResolvedValue({+ participant: { conversationId: CONVERSATION_ID, sourceUserId: 'user-1', tribePersonId: null },+ unlinkedPersonId: null,+ removedClaims: 0,+ });++ const response = await request(app)+ .delete('/api/tribe/beeper/link')+ .send({ conversationId: CONVERSATION_ID, sourceUserId: 'user-1' });++ expect(response.status).toBe(200);+ expect(response.body.unlinkedPersonId).toBeNull();+ expect(emit).not.toHaveBeenCalled();+ });++ it('surfaces a 404 for an unknown participant on unlink', async () => {+ const error = Object.assign(new Error('Participant not found'), { status: 404 });+ beeperTribe.unlinkParticipant.mockRejectedValue(error);++ const response = await request(app)+ .delete('/api/tribe/beeper/link')+ .send({ conversationId: CONVERSATION_ID, sourceUserId: 'ghost' });++ expect(response.status).toBe(404);+ });++ it('rejects an unlink request missing sourceUserId', async () => {+ const response = await request(app)+ .delete('/api/tribe/beeper/link')+ .send({ conversationId: CONVERSATION_ID });++ expect(response.status).toBe(400);+ expect(beeperTribe.unlinkParticipant).not.toHaveBeenCalled();+ });++ it('creates a new Tribe person from a participant and links it', async () => {+ beeperTribe.createPersonAndLinkParticipant.mockResolvedValue({+ person: { id: PERSON_ID, name: 'Example Person' },+ participant: { conversationId: CONVERSATION_ID, sourceUserId: 'user-2', tribePersonId: PERSON_ID },+ created: true,+ displacedPersonId: null,+ });++ const response = await request(app)+ .post('/api/tribe/beeper/link-new')+ .send({ conversationId: CONVERSATION_ID, sourceUserId: 'user-2', name: 'Example Person' });++ expect(response.status).toBe(201);+ expect(response.body.person.id).toBe(PERSON_ID);+ expect(response.body.displacedPersonId).toBeNull();+ // No `network` — it's derived server-side, never accepted from the+ // request body (#34 review).+ expect(beeperTribe.createPersonAndLinkParticipant).toHaveBeenCalledWith(expect.objectContaining({+ conversationId: CONVERSATION_ID, sourceUserId: 'user-2', name: 'Example Person',+ }));+ expect(beeperTribe.createPersonAndLinkParticipant).toHaveBeenCalledWith(+ expect.not.objectContaining({ network: expect.anything() }),+ );+ expect(emit).toHaveBeenCalledWith('tribe:changed', { personId: PERSON_ID });+ });++ it('rejects a create-and-link request missing sourceUserId', async () => {+ const response = await request(app)+ .post('/api/tribe/beeper/link-new')+ .send({ conversationId: CONVERSATION_ID, name: 'Example Person' });++ expect(response.status).toBe(400);+ expect(beeperTribe.createPersonAndLinkParticipant).not.toHaveBeenCalled();+ });+ });++ describe('Unlink a Beeper identity (#99)', () => {+ it('deletes the identity and emits a tribe change', async () => {+ beeperTribe.unlinkIdentity.mockResolvedValue({ id: IDENTITY_ID, personId: PERSON_ID, kind: 'handle', network: 'whatsapp', handle: 'ada' });++ const response = await request(app).delete(`/api/tribe/beeper/identities/${IDENTITY_ID}`);++ expect(response.status).toBe(200);+ expect(response.body).toEqual({ success: true });+ expect(beeperTribe.unlinkIdentity).toHaveBeenCalledWith(IDENTITY_ID);+ expect(emit).toHaveBeenCalledWith('tribe:changed', { personId: PERSON_ID });+ });++ it('returns 404 for an unknown identity id', async () => {+ beeperTribe.unlinkIdentity.mockResolvedValue(null);++ const response = await request(app).delete(`/api/tribe/beeper/identities/${IDENTITY_ID}`);++ expect(response.status).toBe(404);+ expect(emit).not.toHaveBeenCalledWith('tribe:changed', expect.anything());+ });++ it('rejects a non-UUID identity id with 400', async () => {+ const response = await request(app).delete('/api/tribe/beeper/identities/not-a-uuid');++ expect(response.status).toBe(400);+ expect(beeperTribe.unlinkIdentity).not.toHaveBeenCalled();+ });+ });});diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sqlindex 478a9b4ce6..9c9a20a689 100644--- a/server/scripts/init-db.sql+++ b/server/scripts/init-db.sql@@ -174,6 +174,21 @@ CREATE TABLE IF NOT EXISTS tribe_memory_links ();CREATE INDEX IF NOT EXISTS idx_tribe_memory_links_memory ON tribe_memory_links (memory_id);+-- Network-scoped identity claims (#34, decided on #10). Mirrors the block in+-- server/lib/db/schema/tribe.js — see there for the `kind` rationale.+CREATE TABLE IF NOT EXISTS tribe_identities (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ person_id UUID NOT NULL REFERENCES tribe_people(id) ON DELETE CASCADE,+ kind TEXT NOT NULL,+ network TEXT NOT NULL DEFAULT '',+ handle TEXT NOT NULL,+ source TEXT NOT NULL DEFAULT '',+ linked_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ created_at TIMESTAMPTZ DEFAULT NOW(),+ UNIQUE (kind, network, handle)+);+CREATE INDEX IF NOT EXISTS idx_tribe_identities_person ON tribe_identities (person_id);+-- Human activity timeline (#2150) — unified, machine-local event store fed by-- message/calendar syncs (later: iMessage, Spotify, YouTube, Signal). Metadata +-- short summary only; full bodies stay in per-source caches. Idempotent via the@@ -1633,6 +1648,180 @@ CREATE TABLE IF NOT EXISTS x_drafts ();CREATE INDEX IF NOT EXISTS idx_x_drafts_account_state ON x_drafts (account_id, state, created_at DESC);+-- Beeper conversation mirror (#27). Machine-local mirror of the Beeper Desktop+-- API — accounts, conversations, messages, participants, attachment metadata,+-- and per-chat sync cursors. NEVER FEDERATED: no sync_sequence column, no+-- PEER_SUBSCRIBABLE_KINDS entry, no dataSync category, no PORTOS_SCHEMA_VERSIONS+-- entry (guarded by server/services/sharing/beeperNeverFederates.test.js).+-- Deletions from the source are tombstones, not removals — a message the+-- source unsends keeps its row/body/attachments and gains `unsent_at` (never+-- `deleted_at`, which collides with the federation guard's column list).+-- Mirrors the beeper.js block in server/lib/db/schema/.+CREATE TABLE IF NOT EXISTS beeper_accounts (+ account_id TEXT PRIMARY KEY,+ network TEXT NOT NULL DEFAULT '',+ display_name TEXT NOT NULL DEFAULT '',+ status TEXT NOT NULL DEFAULT '',+ bridge_id TEXT NOT NULL DEFAULT '',+ last_seen_at TIMESTAMPTZ,+ created_at TIMESTAMPTZ DEFAULT NOW(),+ updated_at TIMESTAMPTZ DEFAULT NOW()+);+-- The ONE Beeper credential this install holds (#31), AES-256-GCM encrypted by+-- server/lib/vaultCrypto.js. Single-row by construction (id = 'default'): PortOS+-- models one Beeper account per install. token_expires_at NULL = never expires+-- (only Beeper's own UI can mint that); there is no refresh grant, so an expired+-- token is re-connected, never refreshed. scopes/client_id exist for the+-- disconnect-time revocation call and never reach a client payload.+CREATE TABLE IF NOT EXISTS beeper_credentials (+ id TEXT PRIMARY KEY,+ token_enc TEXT NOT NULL,+ token_expires_at TIMESTAMPTZ,+ scopes TEXT NOT NULL DEFAULT '',+ source TEXT NOT NULL DEFAULT 'pasted' CHECK (source IN ('oauth','pasted')),+ client_id TEXT NOT NULL DEFAULT '',+ created_at TIMESTAMPTZ DEFAULT NOW(),+ updated_at TIMESTAMPTZ DEFAULT NOW()+);+CREATE TABLE IF NOT EXISTS beeper_conversations (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ account_id TEXT NOT NULL REFERENCES beeper_accounts (account_id) ON DELETE CASCADE,+ network TEXT NOT NULL DEFAULT '',+ source_chat_id TEXT NOT NULL,+ title TEXT NOT NULL DEFAULT '',+ type TEXT NOT NULL DEFAULT 'single',+ is_group BOOLEAN NOT NULL DEFAULT FALSE,+ is_pinned BOOLEAN NOT NULL DEFAULT FALSE,+ is_archived BOOLEAN NOT NULL DEFAULT FALSE,+ is_low_priority BOOLEAN NOT NULL DEFAULT FALSE,+ is_muted BOOLEAN NOT NULL DEFAULT FALSE,+ last_activity TIMESTAMPTZ,+ unread_count INTEGER NOT NULL DEFAULT 0,+ -- LOCAL "seen in PortOS" watermark (#83). Never mirrored from Beeper and+ -- never written by the sweep — opening a thread stamps it with NOW(), and+ -- the read model compares it against COALESCE(last_activity, created_at)+ -- to decide whether the unread badge still shows. Mirrors the ALTER in+ -- server/lib/db/schema/beeper.js (for existing installs).+ seen_at TIMESTAMPTZ,+ created_at TIMESTAMPTZ DEFAULT NOW(),+ updated_at TIMESTAMPTZ DEFAULT NOW(),+ UNIQUE (account_id, source_chat_id)+);+-- Repointed at the ordering expression the keyset walk actually uses — no+-- query filters on account_id. #81: the ORDER BY / cursor predicate sort on+-- COALESCE(last_activity, 'epoch'::timestamptz), never the raw column and+-- never a created_at fallback — created_at is the MIRROR ROW's mint time,+-- not chat activity, so falling back to it sorted a batch of activity-less+-- chats swept in the same pass at the top of the Inbox by their shared,+-- recent creation time. The epoch sentinel keeps the row-value keyset tuple+-- shape (a real NULLS LAST cannot) while sorting every activity-less chat+-- LAST under DESC instead. Mirrors the block in server/lib/db/schema/beeper.js.+CREATE INDEX IF NOT EXISTS idx_beeper_conversations_activity_epoch_keyset ON beeper_conversations ((COALESCE(last_activity, 'epoch'::timestamptz)) DESC, id DESC);+CREATE TABLE IF NOT EXISTS beeper_messages (+ id TEXT PRIMARY KEY,+ conversation_id UUID NOT NULL REFERENCES beeper_conversations (id) ON DELETE CASCADE,+ sender_id TEXT NOT NULL DEFAULT '',+ body TEXT NOT NULL DEFAULT '',+ sent_at TIMESTAMPTZ,+ edited_at TIMESTAMPTZ,+ unsent_at TIMESTAMPTZ,+ sort_key TEXT NOT NULL DEFAULT '',+ -- Mirrors the API's own Message.isSender. senderID cannot be compared+ -- against the local user (accounts[].user.id differs from senderID on every+ -- network), so this is the only reliable inbound/outbound signal.+ is_sender BOOLEAN NOT NULL DEFAULT FALSE,+ created_at TIMESTAMPTZ DEFAULT NOW(),+ updated_at TIMESTAMPTZ DEFAULT NOW()+);+-- Repointed: sort_key is written on ingest and never read back. A thread page+-- and the "latest message" preview LATERAL both order on+-- COALESCE(sent_at, created_at) DESC, id DESC within one conversation_id, so+-- one index serves both (audit cluster 06). Mirrors beeper.js.+CREATE INDEX IF NOT EXISTS idx_beeper_messages_conversation_order ON beeper_messages (conversation_id, (COALESCE(sent_at, created_at)) DESC, id DESC);+CREATE TABLE IF NOT EXISTS beeper_participants (+ conversation_id UUID NOT NULL REFERENCES beeper_conversations (id) ON DELETE CASCADE,+ source_user_id TEXT NOT NULL,+ display_name TEXT NOT NULL DEFAULT '',+ handle TEXT NOT NULL DEFAULT '',+ tribe_person_id UUID REFERENCES tribe_people (id) ON DELETE SET NULL,+ observed_via TEXT NOT NULL CHECK (observed_via IN ('participant-list','message-sender')),+ created_at TIMESTAMPTZ DEFAULT NOW(),+ updated_at TIMESTAMPTZ DEFAULT NOW(),+ PRIMARY KEY (conversation_id, source_user_id)+);+CREATE INDEX IF NOT EXISTS idx_beeper_participants_tribe_person ON beeper_participants (tribe_person_id) WHERE tribe_person_id IS NOT NULL;+CREATE TABLE IF NOT EXISTS beeper_attachments (+ conversation_id UUID NOT NULL REFERENCES beeper_conversations (id) ON DELETE CASCADE,+ message_id TEXT NOT NULL REFERENCES beeper_messages (id) ON DELETE CASCADE,+ idx INTEGER NOT NULL,+ mxc_id TEXT,+ mime_type TEXT NOT NULL DEFAULT '',+ byte_length BIGINT,+ file_name TEXT NOT NULL DEFAULT '',+ width INTEGER,+ height INTEGER,+ last_viewed_at TIMESTAMPTZ,+ keep BOOLEAN NOT NULL DEFAULT FALSE,+ -- Byte-mirror columns (#37). `local_path` is the store-relative path of the+ -- mirrored bytes (`<sha256 prefix>/<sha256>.<ext>`), NULL while only the+ -- reference is held — that NULL is the lazy mirror's state machine, never ''.+ -- `unavailable_at`/`fetch_error` record a TERMINAL refusal from the source,+ -- which both stops a re-fetch loop and exempts the row from eviction.+ local_path TEXT,+ fetched_at TIMESTAMPTZ,+ unavailable_at TIMESTAMPTZ,+ fetch_error TEXT,+ created_at TIMESTAMPTZ DEFAULT NOW(),+ updated_at TIMESTAMPTZ DEFAULT NOW(),+ PRIMARY KEY (conversation_id, message_id, idx)+);+-- Every attachment route addresses one row by (message_id, idx) — the PK+-- above leads with conversation_id, which none of those callers have on+-- hand, so every lookup scanned the table (audit cluster 06).+CREATE INDEX IF NOT EXISTS idx_beeper_attachments_message ON beeper_attachments (message_id, idx);+CREATE INDEX IF NOT EXISTS idx_beeper_attachments_local ON beeper_attachments (local_path) WHERE local_path IS NOT NULL;+-- evictToBudget's candidate query filters local_path IS NOT NULL AND+-- keep = FALSE AND unavailable_at IS NULL AND mxc_id IS NOT NULL, and orders+-- by last_viewed_at ASC NULLS FIRST, fetched_at ASC NULLS FIRST (a+-- never-viewed row is the BEST eviction candidate, ordered first on purpose).+-- Predicate and NULLS placement match that query exactly (audit cluster 06).+-- `sha256` (and its index) is dropped, not shipped fresh: it was written on+-- every fetch but never read back — the content-addressed path is built from+-- the freshly computed hash, not from this column (decision 3).+CREATE INDEX IF NOT EXISTS idx_beeper_attachments_eviction_candidates ON beeper_attachments (last_viewed_at ASC NULLS FIRST, fetched_at ASC NULLS FIRST) WHERE keep = FALSE AND local_path IS NOT NULL;+CREATE TABLE IF NOT EXISTS beeper_sync_cursors (+ account_id TEXT NOT NULL REFERENCES beeper_accounts (account_id) ON DELETE CASCADE,+ chat_id TEXT NOT NULL,+ cursor TEXT,+ last_activity TIMESTAMPTZ,+ last_swept_at TIMESTAMPTZ,+ PRIMARY KEY (account_id, chat_id)+);++-- Outbound outbox (#36). A row is written BEFORE the send POST, so intent+-- survives a crash between the click and the POST and one row is the+-- serialization point that stops a double-click double-posting. `state` is+-- PortOS's own machine (not a Beeper vocabulary), so the CHECK is deliberate;+-- a failed row is never retried in place — a re-send is a NEW row, because+-- Beeper has no idempotency key on send. Mirrors the beeper.js block in+-- server/lib/db/schema/.+CREATE TABLE IF NOT EXISTS beeper_outbox (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ conversation_id UUID NOT NULL REFERENCES beeper_conversations (id) ON DELETE CASCADE,+ chat_id TEXT NOT NULL,+ body TEXT NOT NULL,+ state TEXT NOT NULL DEFAULT 'draft' CHECK (state IN ('draft','approved','sending','awaiting-confirmation','sent','failed')),+ pending_message_id TEXT,+ message_id TEXT,+ error_code TEXT,+ error_message TEXT,+ created_at TIMESTAMPTZ DEFAULT NOW(),+ approved_at TIMESTAMPTZ,+ sent_at TIMESTAMPTZ,+ updated_at TIMESTAMPTZ DEFAULT NOW()+);+CREATE INDEX IF NOT EXISTS idx_beeper_outbox_conversation_state ON beeper_outbox (conversation_id, state, created_at DESC);+-- Deletion audit log (incident #1248-follow-up). Append-only forensic trail of-- every tombstone / un-tombstone / hard-delete of user-authored records, written-- by a DB trigger so it captures deletions from ANY source (app, a test suite's@@ -1753,3 +1942,5 @@ DROP TRIGGER IF EXISTS trg_tribe_people_audit ON tribe_people;CREATE TRIGGER trg_tribe_people_audit AFTER UPDATE OR DELETE ON tribe_people FOR EACH ROW EXECUTE FUNCTION record_audit_log();DROP TRIGGER IF EXISTS trg_tribe_touchpoints_audit ON tribe_touchpoints;CREATE TRIGGER trg_tribe_touchpoints_audit AFTER UPDATE OR DELETE ON tribe_touchpoints FOR EACH ROW EXECUTE FUNCTION record_audit_log();+DROP TRIGGER IF EXISTS trg_tribe_identities_audit ON tribe_identities;+CREATE TRIGGER trg_tribe_identities_audit AFTER UPDATE OR DELETE ON tribe_identities FOR EACH ROW EXECUTE FUNCTION record_audit_log();diff --git a/server/services/beeperArming.js b/server/services/beeperArming.jsnew file mode 100644index 0000000000..85aa2bb41c--- /dev/null+++ b/server/services/beeperArming.js@@ -0,0 +1,128 @@+/**+ * 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);+ const next = tail.then(run, run);+ tail = next.then(() => {}, () => {});+ return next;+}++async function reconcileOnce(reason) {+ // 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.+ 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 --git a/server/services/beeperArming.test.js b/server/services/beeperArming.test.jsnew file mode 100644index 0000000000..1699e35372--- /dev/null+++ b/server/services/beeperArming.test.js@@ -0,0 +1,291 @@+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('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 --git a/server/services/beeperAttachmentGc.js b/server/services/beeperAttachmentGc.jsnew file mode 100644index 0000000000..b629193ae0--- /dev/null+++ b/server/services/beeperAttachmentGc.js@@ -0,0 +1,43 @@+/**+ * Scheduler registration for the Beeper attachment mirror sweep (#37).+ *+ * ONE sweep does both jobs #13 asked for, because they read the same two+ * lists: the disk budget (least-recently-viewed eviction, guarded by a HEAD so+ * a file Beeper can no longer supply is never the one thrown away) and the+ * orphan backstop (a file no row points at, a row whose file is gone, an+ * abandoned `.partial`). Splitting them would mean enumerating the store+ * twice on every tick for no behavioural gain.+ *+ * `createSweepScheduler` rather than `createSyncScheduler`: this is local+ * housekeeping over the mirror, not an ingestion pass, and it must run whether+ * or not `settings.beeper.enabled` is on — bytes already on disk still count+ * against the budget after a user turns scheduled sync off. It is gated only+ * by having a store at all: with no `data/beeper/attachments` and no rows the+ * sweep is two cheap queries and a failed `readdir`.+ *+ * The handler owns its rejections. A sweep runs outside the request lifecycle,+ * where an escaping rejection takes the process down (root AGENTS.md).+ */++import { createSweepScheduler } from './sweepScheduler.js';+import { sweepBeeperAttachments } from './beeperAttachments.js';++const SWEEP_INTERVAL_MS = 6 * 60 * 60 * 1000;+const INITIAL_DELAY_MS = 10 * 60 * 1000;++const runSweep = async () => {+ await sweepBeeperAttachments().catch((err) => {+ console.error(`❌ Beeper attachment sweep failed: ${err.message}`);+ });+};++export const {+ start: startBeeperAttachmentGc,+ stop: stopBeeperAttachmentGc,+} = createSweepScheduler({+ id: 'beeper-attachment-gc',+ intervalMs: SWEEP_INTERVAL_MS,+ initialDelayMs: INITIAL_DELAY_MS,+ handler: runSweep,+ source: 'beeperAttachmentGc',+});diff --git a/server/services/beeperAttachments.js b/server/services/beeperAttachments.jsnew file mode 100644index 0000000000..922db38975--- /dev/null+++ b/server/services/beeperAttachments.js@@ -0,0 +1,809 @@+/**+ * The Beeper attachment byte mirror (#37, decided on #13).+ *+ * **Lazy.** Ingestion (#32) writes the attachment's METADATA and its durable+ * `mxc_id` reference; the bytes arrive only when a human actually opens the+ * thread that shows them. A mirrored account's attachment history runs to+ * gigabytes, so "fetch everything on ingest" is a transfer nobody asked for —+ * the same reasoning root AGENTS.md applies to unbidden LLM calls, applied to+ * bytes. The bulk backfill exists, but it is a user action behind a consent+ * step that names the count and the size first.+ *+ * **Content-addressed, so deletion is never a one-liner.** Files live at+ * `data/beeper/attachments/<sha256[0..2]>/<sha256>.<ext>`+ * (`lib/beeperAttachmentPaths.js`), which means one photo forwarded into four+ * chats is one file and four rows. Every unlink path here therefore asks+ * "does any OTHER row still point at this path?" first — the shape+ * `chatgptImport.js` uses for its shared import assets.+ *+ * **A 502 is terminal, and it is also a keep.** `GET /v1/assets/serve` answers+ * `502` for media the source network has aged out, which `beeperClient` maps+ * to `ASSET_UNAVAILABLE`. Two consequences, and they pull in opposite+ * directions on purpose: the row is stamped `unavailable_at` so nothing+ * re-requests it on every render (the retry loop #13 called out), and a row+ * already holding bytes is exempted from eviction, because a file Beeper can+ * no longer supply is the last copy in existence.+ *+ * Nothing here ever sends anything through a messaging API.+ */++import { createHash, randomUUID } from 'crypto';+import { createWriteStream } from 'fs';+import { mkdir, link, rename, rm, readdir, stat, unlink } from 'fs/promises';+import { dirname, join } from 'path';+import { Readable } from 'stream';+import { pipeline } from 'stream/promises';+import { query } from '../lib/db.js';+import { ServerError } from '../lib/errorHandler.js';+import { PATHS, pathExists } from '../lib/fileUtils.js';+import {+ BEEPER_ATTACHMENT_MAX_BYTES,+ attachmentExtension,+ attachmentRelativePath,+ isSafeAttachmentRelativePath,+} from '../lib/beeperAttachmentPaths.js';+import { getSettings } from './settings.js';+import { fetchAssetStream, headAsset } from './beeperClient.js';++const BYTES_PER_GB = 1024 * 1024 * 1024;+const DEFAULT_BUDGET_GB = 5;+// Partial downloads land in their own subdirectory rather than beside the+// finished files: the store is enumerated by the orphan backstop and by the+// Data Manager, and a half-written `.partial` sitting in a hash-prefix dir+// would read as a corrupt mirror entry to both.+const TMP_DIR_NAME = '.tmp';+// A partial older than this is from a process that is no longer running: an+// in-flight transfer is abandoned after `STREAM_IDLE_TIMEOUT_MS` without a+// chunk, so nothing legitimate is still writing an hour-old `.partial`.+const TMP_MAX_AGE_MS = 60 * 60 * 1000;+// The stall guard for the BODY. `fetchWithTimeout`'s own budget covers only the+// response headers — it clears its abort timer once `fetch` resolves — so a+// source that answers and then goes silent mid-transfer would otherwise hold a+// half-written file and its socket open indefinitely. This timer is reset on+// every chunk, so it bounds SILENCE rather than the transfer: a slow but+// progressing 32 MiB download is never cut off, and a dead one is.+const STREAM_IDLE_TIMEOUT_MS = 60_000;+// One sweep evicts at most this many files. Each eviction costs a HEAD against+// Beeper Desktop, and a budget cut from 50 GB to 1 GB should not turn into a+// thousand-request burst inside one tick — the next sweep continues.+const MAX_EVICTIONS_PER_SWEEP = 50;++export const attachmentsRoot = () => PATHS.beeperAttachments;+const tmpRoot = () => join(attachmentsRoot(), TMP_DIR_NAME);++const notFound = () => new ServerError('Attachment not found', { status: 404, code: 'NOT_FOUND' });++const toIso = (value) => (value ? new Date(value).toISOString() : null);++/**+ * The client-facing shape of one attachment row.+ *+ * `stored` / `unavailable` / `overCap` are three separate booleans rather than+ * one status string because the surface renders three different things from+ * them and they are not mutually exclusive: an over-cap attachment that a user+ * fetched anyway is `stored: true, overCap: true`, and an unavailable one may+ * still be `stored: true` when the bytes landed before the source aged out.+ */+export function shapeAttachment(row) {+ const byteLength = row.byte_length === null || row.byte_length === undefined ? null : Number(row.byte_length);+ return {+ conversationId: row.conversation_id,+ messageId: row.message_id,+ idx: Number(row.idx) || 0,+ mxcId: row.mxc_id || null,+ mimeType: row.mime_type || '',+ fileName: row.file_name || '',+ byteLength,+ width: row.width === null || row.width === undefined ? null : Number(row.width),+ height: row.height === null || row.height === undefined ? null : Number(row.height),+ stored: Boolean(row.local_path),+ keep: row.keep === true,+ lastViewedAt: toIso(row.last_viewed_at),+ fetchedAt: toIso(row.fetched_at),+ unavailable: Boolean(row.unavailable_at),+ unavailableReason: row.fetch_error || null,+ // A KNOWN size over the ceiling. An unknown size (`null`) is deliberately+ // not over-cap: the HEAD pre-flight is what decides that case, and+ // rendering a placeholder for every attachment whose size the bridge+ // declined to report would hide most of the mirror behind a click.+ overCap: byteLength !== null && byteLength > BEEPER_ATTACHMENT_MAX_BYTES,+ maxBytes: BEEPER_ATTACHMENT_MAX_BYTES,+ };+}++async function loadRow(messageId, idx) {+ const result = await query(+ `SELECT * FROM beeper_attachments WHERE message_id = $1 AND idx = $2`,+ [messageId, Number(idx)],+ );+ return result?.rows?.[0] || null;+}++/** One attachment's current mirror state, or `null` when the id is unknown. */+export async function getAttachment(messageId, idx) {+ const row = await loadRow(messageId, idx);+ return row ? shapeAttachment(row) : null;+}++// ---------------------------------------------------------------------------+// Budget+// ---------------------------------------------------------------------------++async function resolveBudgetBytes() {+ const settings = await getSettings().catch(() => null);+ const configured = Number(settings?.beeper?.attachmentBudgetGb);+ const gb = Number.isFinite(configured) && configured > 0 ? configured : DEFAULT_BUDGET_GB;+ return Math.round(gb * BYTES_PER_GB);+}++/**+ * Bytes on disk, counted per DISTINCT `local_path`. Counting per ROW would+ * multiply a forwarded photo by the number of chats it landed in and report a+ * mirror several times its real size — the same dedupe that makes deletion+ * need a reference check makes accounting need a DISTINCT.+ */+async function storedBytes() {+ const result = await query(+ `SELECT COALESCE(SUM(byte_length), 0)::bigint AS bytes, COUNT(*)::int AS files+ FROM (+ SELECT DISTINCT ON (local_path) local_path, byte_length+ FROM beeper_attachments+ WHERE local_path IS NOT NULL+ ) unique_files`,+ );+ const row = result?.rows?.[0] || {};+ return { bytes: Number(row.bytes) || 0, files: Number(row.files) || 0 };+}++/**+ * What the bulk-backfill consent modal has to name before it runs, plus the+ * disk picture the settings card renders.+ *+ * `pendingUnknownBytes` is its own count on purpose: an attachment whose+ * `byte_length` the bridge never reported cannot be added to `pendingBytes`,+ * and folding it in as zero would let the modal promise "42 MB" for a transfer+ * that is actually unbounded (root AGENTS.md, absent-vs-empty).+ */+export async function getAttachmentSummary() {+ const [budgetBytes, stored, counts] = await Promise.all([+ resolveBudgetBytes(),+ storedBytes(),+ query(+ `SELECT+ COUNT(*) FILTER (WHERE local_path IS NULL AND unavailable_at IS NULL AND mxc_id IS NOT NULL+ AND (byte_length IS NULL OR byte_length <= $1))::int AS pending,+ COALESCE(SUM(byte_length) FILTER (WHERE local_path IS NULL AND unavailable_at IS NULL AND mxc_id IS NOT NULL+ AND byte_length IS NOT NULL AND byte_length <= $1), 0)::bigint AS pending_bytes,+ COUNT(*) FILTER (WHERE local_path IS NULL AND unavailable_at IS NULL AND mxc_id IS NOT NULL+ AND byte_length IS NULL)::int AS pending_unknown,+ COUNT(*) FILTER (WHERE byte_length > $1)::int AS over_cap,+ COUNT(*) FILTER (WHERE unavailable_at IS NOT NULL)::int AS unavailable,+ COUNT(*) FILTER (WHERE keep = TRUE)::int AS kept,+ COUNT(*)::int AS total+ FROM beeper_attachments`,+ [BEEPER_ATTACHMENT_MAX_BYTES],+ ),+ ]);+ const row = counts?.rows?.[0] || {};+ return {+ budgetBytes,+ usedBytes: stored.bytes,+ storedFiles: stored.files,+ pendingCount: Number(row.pending) || 0,+ pendingBytes: Number(row.pending_bytes) || 0,+ pendingUnknownCount: Number(row.pending_unknown) || 0,+ overCapCount: Number(row.over_cap) || 0,+ unavailableCount: Number(row.unavailable) || 0,+ keptCount: Number(row.kept) || 0,+ totalCount: Number(row.total) || 0,+ maxBytes: BEEPER_ATTACHMENT_MAX_BYTES,+ };+}++// ---------------------------------------------------------------------------+// Acquisition+// ---------------------------------------------------------------------------++const tooLarge = (bytes) => new ServerError(+ `Attachment is ${bytes} bytes, over the ${BEEPER_ATTACHMENT_MAX_BYTES}-byte mirror ceiling`,+ { status: 413, code: 'ATTACHMENT_TOO_LARGE', context: { bytes, maxBytes: BEEPER_ATTACHMENT_MAX_BYTES } },+);++/**+ * Stream one asset to disk, hashing as it goes, and finalize it into its+ * content-addressed home.+ *+ * The shape is `loras.js`'s `downloadToFile`: web stream → byte-counting+ * transform → `.partial` → atomic no-clobber `link()` finalize. The two+ * deltas are both consequences of content addressing — the destination is not+ * known until the last byte is hashed, and an `EEXIST` on the link is a+ * SUCCESS here (another row already mirrored these exact bytes) rather than+ * `loras`' "already installed" conflict.+ *+ * The cap is enforced mid-stream as well as at the HEAD, because a bridge that+ * declines to report `Content-Length` would otherwise get an unbounded write+ * past a ceiling the pre-flight could not see.+ */+async function streamAssetToStore(mxcId, { maxBytes, extension }) {+ // Abort on SILENCE, not on elapsed time — see STREAM_IDLE_TIMEOUT_MS. The+ // controller is handed to the client so the abort tears down the live socket,+ // not just this side's reader. `abort()` cannot throw, which matters because+ // the timer fires outside the request lifecycle.+ const controller = new AbortController();+ let idleTimer = null;+ const clearIdle = () => { if (idleTimer) clearTimeout(idleTimer); idleTimer = null; };+ const armIdle = () => {+ clearIdle();+ idleTimer = setTimeout(() => controller.abort(), STREAM_IDLE_TIMEOUT_MS);+ idleTimer.unref?.();+ };+ armIdle();++ const response = await fetchAssetStream(mxcId, { signal: controller.signal })+ .catch((err) => { clearIdle(); throw err; });+ // A 200 with no body at all: `Readable.fromWeb(null)` would throw a bare+ // TypeError from inside the store, which tells the surface nothing.+ if (!response.body) {+ clearIdle();+ throw new ServerError('Beeper returned no body for this attachment', {+ status: 502, code: 'ATTACHMENT_DOWNLOAD_FAILED',+ });+ }+ await mkdir(tmpRoot(), { recursive: true });+ const tmpPath = join(tmpRoot(), `${randomUUID()}.partial`);++ const hash = createHash('sha256');+ let received = 0;+ let exceeded = false;+ const counter = async function* counter(source) {+ for await (const chunk of source) {+ armIdle();+ received += chunk.length;+ if (received > maxBytes) {+ exceeded = true;+ // Abort the transfer rather than draining a file we have already+ // decided to refuse.+ throw tooLarge(received);+ }+ hash.update(chunk);+ yield chunk;+ }+ };++ const failure = await pipeline(+ Readable.fromWeb(response.body),+ counter,+ createWriteStream(tmpPath),+ ).then(() => null).catch((err) => err);+ clearIdle();++ if (failure) {+ await rm(tmpPath, { force: true }).catch(() => {});+ throw exceeded ? failure : new ServerError(+ `Attachment download failed: ${failure.message}`,+ { status: 502, code: 'ATTACHMENT_DOWNLOAD_FAILED' },+ );+ }++ const sha256 = hash.digest('hex');+ const relativePath = attachmentRelativePath(sha256, extension);+ const destPath = join(attachmentsRoot(), relativePath);+ await mkdir(dirname(destPath), { recursive: true });++ // `link` is atomic and fails with EEXIST rather than clobbering — which for+ // a content-addressed store means the bytes are already mirrored under+ // another row and this download was redundant, not a conflict.+ const linkError = await link(tmpPath, destPath).catch((err) => err);+ if (!linkError) {+ await unlink(tmpPath).catch(() => {});+ return { sha256, relativePath, bytes: received };+ }+ if (linkError.code === 'EEXIST') {+ await rm(tmpPath, { force: true }).catch(() => {});+ return { sha256, relativePath, bytes: received, deduped: true };+ }+ // EXDEV or a filesystem without hard links: rename is the portable fallback.+ const renameError = await rename(tmpPath, destPath).catch((err) => err);+ if (renameError) {+ await rm(tmpPath, { force: true }).catch(() => {});+ throw new ServerError(`Could not store attachment: ${renameError.message}`, {+ status: 500, code: 'ATTACHMENT_STORE_FAILED',+ });+ }+ return { sha256, relativePath, bytes: received };+}++async function markUnavailable(row, message) {+ await query(+ `UPDATE beeper_attachments+ SET unavailable_at = NOW(), fetch_error = $3, updated_at = NOW()+ WHERE message_id = $1 AND idx = $2`,+ [row.message_id, row.idx, String(message || '').slice(0, 500)],+ );+}++/**+ * Ensure one attachment's bytes are on disk and return where they are.+ *+ * `force` is the "fetch anyway" action from the over-cap placeholder, and it+ * is the ONLY thing that lifts the ceiling or retries a source that previously+ * refused. Every automatic path — a thread render, the backfill, the sweep —+ * runs without it, which is what keeps an aged-out attachment from being+ * re-requested on every paint.+ */+export async function ensureAttachmentBytes(messageId, idx, { force = false } = {}) {+ const row = await loadRow(messageId, idx);+ if (!row) throw notFound();++ if (row.local_path && isSafeAttachmentRelativePath(row.local_path)) {+ const filePath = join(attachmentsRoot(), row.local_path);+ if (await pathExists(filePath)) {+ await query(+ `UPDATE beeper_attachments SET last_viewed_at = NOW() WHERE message_id = $1 AND idx = $2`,+ [row.message_id, row.idx],+ );+ return { filePath, mimeType: row.mime_type || '', fileName: row.file_name || '', cached: true };+ }+ // The row claims bytes the disk no longer has (a Data Manager purge, a+ // restore from a backup that excluded them). Heal the row rather than+ // 404ing, then fall through and re-acquire.+ await query(+ `UPDATE beeper_attachments SET local_path = NULL, fetched_at = NULL, updated_at = NOW()+ WHERE message_id = $1 AND idx = $2`,+ [row.message_id, row.idx],+ );+ }++ if (!row.mxc_id) {+ throw new ServerError('Attachment has no source reference to fetch', {+ status: 404, code: 'ASSET_UNAVAILABLE',+ });+ }+ if (row.unavailable_at && !force) {+ throw new ServerError(row.fetch_error || 'Beeper can no longer supply this attachment', {+ status: 404, code: 'ASSET_UNAVAILABLE',+ });+ }++ const maxBytes = force ? Number.POSITIVE_INFINITY : BEEPER_ATTACHMENT_MAX_BYTES;+ const head = await headAsset(row.mxc_id).catch(async (err) => {+ if (err?.code === 'ASSET_UNAVAILABLE') await markUnavailable(row, err.message);+ throw err;+ });+ if (head.bytes !== null && head.bytes > maxBytes) {+ // Persist the size the HEAD just reported before refusing. Beeper does not+ // always populate `byte_length` on ingest, and an attachment whose size is+ // unknown is deliberately not `overCap` — so without this the surface+ // renders an `<img>`, takes the 413, and falls back to a generic "could not+ // load / Retry" whose retry runs with `force: true`: an unbounded download+ // behind a button that names neither the size nor the ceiling. With the+ // size stored, the next render is the real over-cap placeholder, which+ // states both.+ await query(+ `UPDATE beeper_attachments SET byte_length = $3, updated_at = NOW()+ WHERE message_id = $1 AND idx = $2`,+ [row.message_id, row.idx, head.bytes],+ );+ throw tooLarge(head.bytes);+ }++ const extension = attachmentExtension({ mimeType: row.mime_type, fileName: row.file_name });+ const stored = await streamAssetToStore(row.mxc_id, { maxBytes, extension }).catch(async (err) => {+ if (err?.code === 'ASSET_UNAVAILABLE') await markUnavailable(row, err.message);+ throw err;+ });++ // `sha256` is not persisted (audit cluster 06 decision 3): it was written+ // here but never read back — the content-addressed path is built from the+ // hash `streamAssetToStore` just computed, not from this column. The VALUE+ // stays in `stored.sha256` / `stored.relativePath` for that path; only the+ // column write goes.+ await query(+ `UPDATE beeper_attachments+ SET local_path = $3, byte_length = $4,+ fetched_at = NOW(), last_viewed_at = NOW(),+ unavailable_at = NULL, fetch_error = NULL, updated_at = NOW()+ WHERE message_id = $1 AND idx = $2`,+ [row.message_id, row.idx, stored.relativePath, stored.bytes],+ );+ console.log(`🫧 Beeper attachment mirrored: ${stored.bytes} bytes for message ${row.message_id}#${row.idx}${stored.deduped ? ' (deduped)' : ''}`);+ return {+ filePath: join(attachmentsRoot(), stored.relativePath),+ mimeType: row.mime_type || '',+ fileName: row.file_name || '',+ cached: false,+ // Whether this fetch's bytes were already on disk under another row+ // (`link()`'s EEXIST) — `backfillAttachments` uses it to adjust its+ // running byte total without re-querying the DISTINCT-on-`local_path`+ // total after every attachment.+ deduped: stored.deduped === true,+ };+}++/**+ * The per-attachment `keep` lock — the `useLockToggle` shape (#13): an+ * optimistic PATCH that exempts one attachment from least-recently-viewed+ * eviction forever, for the photo a user does not want the budget to decide+ * about.+ */+export async function setAttachmentKeep(messageId, idx, keep) {+ const result = await query(+ `UPDATE beeper_attachments SET keep = $3, updated_at = NOW()+ WHERE message_id = $1 AND idx = $2+ RETURNING *`,+ [messageId, Number(idx), keep === true],+ );+ const row = result?.rows?.[0];+ if (!row) throw notFound();+ return shapeAttachment(row);+}++// ---------------------------------------------------------------------------+// Bulk backfill (a USER action — the route gates it behind consent)+// ---------------------------------------------------------------------------++/**+ * Mirror the attachments that are still reference-only, oldest first.+ *+ * Sequential by construction. Beeper Desktop is one local process that may+ * itself be pulling each file off the network, and a parallel fan-out of a+ * few thousand requests is how a backfill turns into an outage of the app the+ * user is reading their messages in.+ *+ * Individual failures are COUNTED, not thrown: an aged-out attachment in the+ * middle of a 3,000-file run must not abandon the other 2,999, and each one+ * is stamped `unavailable_at` on the way past so the next run skips it.+ *+ * The running byte total is computed ONCE for the whole pass, then adjusted+ * in memory as bytes land — not re-queried before every attachment.+ * `storedBytes()` is a `DISTINCT ON (local_path)` scan of the full table, and+ * re-running it per attachment turned an N-attachment backfill into N scans of+ * a mirror that can hold tens of thousands of rows. `ensureAttachmentBytes`'s+ * `deduped` flag keeps the in-memory total exact: a fetch that lands on bytes+ * another row already mirrored (`link()`'s EEXIST) adds nothing to disk usage,+ * the same DISTINCT-on-`local_path` accounting `storedBytes()` itself does.+ */+export async function backfillAttachments({ limit = 500 } = {}) {+ const budgetBytes = await resolveBudgetBytes();+ const pending = await query(+ `SELECT message_id, idx FROM beeper_attachments+ WHERE local_path IS NULL AND unavailable_at IS NULL AND mxc_id IS NOT NULL+ AND (byte_length IS NULL OR byte_length <= $1)+ ORDER BY created_at ASC+ LIMIT $2`,+ [BEEPER_ATTACHMENT_MAX_BYTES, Math.max(1, Math.min(Number(limit) || 500, 5000))],+ );++ let used = (await storedBytes()).bytes;++ let fetched = 0;+ let failed = 0;+ let bytes = 0;+ let stoppedForBudget = false;+ for (const row of pending?.rows || []) {+ if (used >= budgetBytes) {+ stoppedForBudget = true;+ break;+ }+ const result = await ensureAttachmentBytes(row.message_id, row.idx)+ .then((value) => ({ value }))+ .catch((err) => ({ err }));+ if (result.err) {+ failed += 1;+ continue;+ }+ fetched += 1;+ const stat_ = await stat(result.value.filePath).catch(() => null);+ const size = stat_?.size || 0;+ bytes += size;+ if (!result.value.deduped) used += size;+ }+ console.log(`🫧 Beeper attachment backfill: ${fetched} mirrored, ${failed} unavailable${stoppedForBudget ? ', stopped at budget' : ''}`);+ return { fetched, failed, bytes, stoppedForBudget, requested: (pending?.rows || []).length };+}++// ---------------------------------------------------------------------------+// Eviction, orphan backstop, purge+// ---------------------------------------------------------------------------++/**+ * Drop one row's claim on its bytes, unlinking the file only when no OTHER row+ * still points at it (content addressing means several usually do).+ * @returns {Promise<{ removed: boolean, bytes: number, failed: boolean }>}+ */+async function releaseRowBytes(row) {+ const relativePath = row.local_path;+ await query(+ `UPDATE beeper_attachments SET local_path = NULL, fetched_at = NULL, updated_at = NOW()+ WHERE message_id = $1 AND idx = $2`,+ [row.message_id, row.idx],+ );+ return unlinkIfUnreferenced(relativePath);+}++/**+ * Unlink one stored file if — and only if — the reference check run RIGHT NOW+ * says nothing points at it. The freshness is the contract: every caller here+ * decided a file was unreferenced at some earlier point, and a dedupe fetch+ * landing on these exact bytes through `link()`'s EEXIST in between would leave+ * the row that just claimed them saying `stored: true` against a deleted file.+ *+ * `removed` is its own field rather than "bytes > 0" because a legitimately+ * empty file reclaims nothing and is still gone. `failed` is its own field+ * because a swallowed unlink error is the worst of the three outcomes: the row+ * has already given up its claim, so the bytes stay on disk with nothing left+ * pointing at them, counting against a budget that has just been told they were+ * reclaimed. ENOENT is not a failure — the file is gone, which is the outcome+ * asked for, and there are no bytes left to under-report.+ * @returns {Promise<{ removed: boolean, bytes: number, failed: boolean }>}+ */+async function unlinkIfUnreferenced(relativePath) {+ const untouched = { removed: false, bytes: 0, failed: false };+ if (!relativePath || !isSafeAttachmentRelativePath(relativePath)) return untouched;+ const others = await query(+ `SELECT 1 FROM beeper_attachments WHERE local_path = $1 LIMIT 1`,+ [relativePath],+ );+ if (others?.rows?.length) return untouched;+ const filePath = join(attachmentsRoot(), relativePath);+ const info = await stat(filePath).catch(() => null);+ const failure = await unlink(filePath).then(() => null).catch((err) => err);+ if (!failure) return { removed: true, bytes: info?.size || 0, failed: false };+ if (failure.code === 'ENOENT') return untouched;+ console.error(`❌ Beeper attachment unlink failed for ${relativePath}: ${failure.message}`);+ return { removed: false, bytes: 0, failed: true };+}++/**+ * Evict least-recently-viewed attachments until the mirror fits its budget.+ *+ * The guard is the part that matters: before evicting, HEAD the source. A+ * `502` means Beeper can no longer supply the file, so the local copy is the+ * only one left — it is KEPT regardless of age and stamped `unavailable_at`,+ * which also takes it out of every subsequent candidate query rather than+ * re-probing it each sweep.+ */+export async function evictToBudget() {+ const budgetBytes = await resolveBudgetBytes();+ let used = (await storedBytes()).bytes;+ if (used <= budgetBytes) return { evicted: 0, reclaimedBytes: 0, keptUnavailable: 0, overBudget: false };++ let evicted = 0;+ let reclaimedBytes = 0;+ let keptUnavailable = 0;+ let failedUnlinks = 0;+ for (let attempt = 0; attempt < MAX_EVICTIONS_PER_SWEEP && used > budgetBytes; attempt += 1) {+ const candidates = await query(+ // `mxc_id IS NOT NULL` is part of the eviction RULE, not an optimisation:+ // eviction is only ever safe because the file can be fetched again, and a+ // row with no source reference is precisely the one that could not be.+ // Filtering in the query (rather than skipping in the loop) also keeps+ // the loop from re-selecting the same unevictable row forever.+ `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 row = candidates?.rows?.[0];+ if (!row) break;++ const probe = await headAsset(row.mxc_id).then(() => null).catch((err) => err);+ if (probe?.code === 'ASSET_UNAVAILABLE') {+ await markUnavailable(row, probe.message);+ keptUnavailable += 1;+ continue;+ }+ // Any other probe failure (Beeper closed, a transport blip) is not+ // evidence the file is re-fetchable, so this sweep stops rather than+ // evicting on an unanswered question.+ if (probe) break;++ // `freed` is 0 when the unlink failed, so the reclaimed total never counts+ // bytes that are still on disk — and `used` does not drop either, which is+ // what keeps the loop from believing it has made room it has not made.+ const { bytes: freed, failed } = await releaseRowBytes(row);+ evicted += 1;+ if (failed) failedUnlinks += 1;+ reclaimedBytes += freed;+ used -= freed;+ }+ if (evicted > 0 || keptUnavailable > 0) {+ console.log(`🧹 Beeper attachment eviction: ${evicted} evicted, ${reclaimedBytes} bytes reclaimed, ${keptUnavailable} kept (source can no longer supply), ${failedUnlinks} unlink failure(s)`);+ }+ return { evicted, reclaimedBytes, keptUnavailable, failedUnlinks, overBudget: used > budgetBytes };+}++/**+ * Every file in the store, plus whether the listing actually COMPLETED.+ *+ * "The store could not be read" and "the store is empty" are the same value to+ * a `catch(() => [])` — and the row-healing half of the sweep below clears+ * `local_path` for every referenced path it did not see, so one EACCES on the+ * root, or a data volume that came back unmounted, would unlink every mirrored+ * row in the install from its bytes in a single pass. The `complete` flag is+ * the sentinel that keeps the two apart (root AGENTS.md, absent-vs-empty).+ *+ * A PARTIAL listing counts as incomplete for the same reason: a prefix+ * directory that cannot be read hides real files exactly as effectively as an+ * unreadable root does.+ */+async function listStoredFiles() {+ const root = attachmentsRoot();+ const prefixes = await readdir(root, { withFileTypes: true }).catch((err) => err);+ if (!Array.isArray(prefixes)) {+ console.error(`❌ Beeper attachment store could not be listed: ${prefixes.message}`);+ return { files: [], complete: false };+ }+ const files = [];+ let complete = true;+ for (const prefix of prefixes) {+ if (!prefix.isDirectory() || prefix.name === TMP_DIR_NAME) continue;+ const entries = await readdir(join(root, prefix.name)).catch((err) => err);+ if (!Array.isArray(entries)) {+ console.error(`❌ Beeper attachment store prefix ${prefix.name} could not be listed: ${entries.message}`);+ complete = false;+ continue;+ }+ for (const name of entries) files.push(`${prefix.name}/${name}`);+ }+ return { files, complete };+}++/**+ * The orphan backstop, which is deliberately the SAME sweep as the eviction+ * (#13): a file with no row pointing at it is unreachable and would otherwise+ * count against the budget forever, and a row pointing at a file the disk no+ * longer has renders as "mirrored" and then 404s.+ *+ * Both directions get healed here, plus abandoned `.tmp` partials from a+ * process that died mid-download.+ *+ * The row-healing direction is the destructive one, and it runs ONLY on a+ * listing that completed: a store that could not be read is not an empty store,+ * and treating it as one would clear every mirrored row's `local_path` at once.+ * Orphan removal is unaffected — it only ever touches files it actually saw.+ */+export async function sweepAttachmentOrphans() {+ // Create the root before listing it. On an install that has enabled Beeper+ // but never mirrored a byte the directory does not exist yet, and THAT ENOENT+ // really is "empty"; making it once means every later listing failure is a+ // genuine anomaly worth logging and refusing to act on.+ await mkdir(attachmentsRoot(), { recursive: true }).catch(() => {});+ const { files: onDisk, complete: storeListed } = await listStoredFiles();+ const referenced = await query(+ `SELECT DISTINCT local_path FROM beeper_attachments WHERE local_path IS NOT NULL`,+ );+ const referencedSet = new Set((referenced?.rows || []).map((row) => row.local_path));++ const sweepStart = Date.now();+ let orphansRemoved = 0;+ let failedUnlinks = 0;+ for (const relativePath of onDisk) {+ if (referencedSet.has(relativePath)) continue;+ // An age gate, because a file is linked into place a moment BEFORE its row+ // is updated to point at it: a fresh unreferenced file may be a download+ // finishing right now rather than an orphan. Anything older than the asset+ // request budget cannot be.+ const info = await stat(join(attachmentsRoot(), relativePath)).catch(() => null);+ if (!info || sweepStart - info.mtimeMs < TMP_MAX_AGE_MS) continue;+ // `referencedSet` is a SNAPSHOT taken before this loop started, and the+ // mtime gate only rules out a file being written right now — not a dedupe+ // fetch that landed on this exact OLD file through `link()`'s EEXIST while+ // the loop was working through the rest of the store. Re-ask the reference+ // question immediately before the unlink, or the row that just claimed+ // these bytes is left reporting `stored: true` against a deleted file.+ const { removed, failed } = await unlinkIfUnreferenced(relativePath);+ if (removed) orphansRemoved += 1;+ if (failed) failedUnlinks += 1;+ }++ const diskSet = new Set(onDisk);+ let healedRows = 0;+ if (!storeListed) {+ console.error('❌ Beeper attachment sweep: the store did not list completely — no row healed this pass');+ } else {+ const missing = [...referencedSet].filter((relativePath) => !diskSet.has(relativePath));+ if (missing.length > 0) {+ const result = await query(+ `UPDATE beeper_attachments SET local_path = NULL, fetched_at = NULL, updated_at = NOW()+ WHERE local_path = ANY($1::text[])`,+ [missing],+ );+ healedRows = result?.rowCount || 0;+ }+ }++ const now = Date.now();+ const partials = await readdir(tmpRoot()).catch(() => []);+ let partialsRemoved = 0;+ for (const name of partials) {+ const partialPath = join(tmpRoot(), name);+ const info = await stat(partialPath).catch(() => null);+ if (!info || now - info.mtimeMs < TMP_MAX_AGE_MS) continue;+ const failure = await unlink(partialPath).then(() => null).catch((err) => err);+ if (!failure) { partialsRemoved += 1; continue; }+ if (failure.code === 'ENOENT') continue;+ console.error(`❌ Beeper attachment partial unlink failed for ${name}: ${failure.message}`);+ failedUnlinks += 1;+ }++ // The failure count rides in the log line unconditionally: bytes that a+ // failed unlink left on disk are invisible everywhere else — nothing points+ // at them any more, and they still count against the budget.+ if (orphansRemoved || healedRows || partialsRemoved || failedUnlinks) {+ console.log(`🧹 Beeper attachment sweep: ${orphansRemoved} orphan file(s), ${healedRows} stale row(s), ${partialsRemoved} abandoned partial(s), ${failedUnlinks} unlink failure(s)`);+ }+ return { orphansRemoved, healedRows, partialsRemoved, failedUnlinks, storeListed };+}++/** One scheduler tick: budget first, then the orphan backstop. */+export async function sweepBeeperAttachments() {+ const eviction = await evictToBudget();+ const orphans = await sweepAttachmentOrphans();+ // Both halves unlink, so their tallies are summed rather than shadowed by the+ // spread.+ return {+ ...eviction,+ ...orphans,+ failedUnlinks: eviction.failedUnlinks + orphans.failedUnlinks,+ };+}++/**+ * Byte cleanup for a conversation whose mirror is being purged.+ *+ * Called BEFORE the rows go, because the reference check reads them: a file is+ * unlinked only once no row outside this conversation still points at it. The+ * caller deletes the conversation row afterwards and the FK cascade takes the+ * attachment rows with it.+ */+export async function purgeConversationAttachments(conversationId) {+ const owned = await query(+ `SELECT DISTINCT local_path FROM beeper_attachments+ WHERE conversation_id = $1 AND local_path IS NOT NULL`,+ [conversationId],+ );+ const paths = (owned?.rows || []).map((row) => row.local_path);+ if (paths.length === 0) return { removedFiles: 0, freedBytes: 0, failedUnlinks: 0 };++ // Drop this conversation's claims first so the shared-reference check below+ // sees only rows that will SURVIVE the purge.+ await query(+ `UPDATE beeper_attachments SET local_path = NULL, fetched_at = NULL, updated_at = NOW()+ WHERE conversation_id = $1 AND local_path IS NOT NULL`,+ [conversationId],+ );++ let removedFiles = 0;+ let freedBytes = 0;+ let failedUnlinks = 0;+ for (const relativePath of paths) {+ const { removed, bytes, failed } = await unlinkIfUnreferenced(relativePath);+ if (failed) failedUnlinks += 1;+ if (removed) {+ removedFiles += 1;+ freedBytes += bytes;+ }+ }+ // `freedBytes` counts only files actually gone, so the purge confirmation+ // never claims disk it did not reclaim; `failedUnlinks` is how the caller+ // learns the difference is real rather than an accounting slip.+ return { removedFiles, freedBytes, failedUnlinks };+}++/** Mirrored bytes a conversation is holding — what the purge confirmation names. */+export async function getConversationAttachmentBytes(conversationId) {+ const result = await query(+ `SELECT COALESCE(SUM(byte_length), 0)::bigint AS bytes, COUNT(*)::int AS files+ FROM (+ SELECT DISTINCT ON (local_path) local_path, byte_length+ FROM beeper_attachments+ WHERE conversation_id = $1 AND local_path IS NOT NULL+ ) unique_files`,+ [conversationId],+ );+ const row = result?.rows?.[0] || {};+ return { bytes: Number(row.bytes) || 0, files: Number(row.files) || 0 };+}diff --git a/server/services/beeperAttachments.test.js b/server/services/beeperAttachments.test.jsnew file mode 100644index 0000000000..ab3a59fb49--- /dev/null+++ b/server/services/beeperAttachments.test.js@@ -0,0 +1,725 @@+/**+ * Boundary tests for the Beeper attachment byte mirror (#37).+ *+ * Postgres is mocked at `query()` and the Beeper client at `headAsset` /+ * `fetchAssetStream`, but the FILESYSTEM is real (a temp `PATHS.data`): the+ * behaviour under test is what lands on disk and what the store does when+ * asked to give bytes back, and a mocked `fs` would only prove the mock. The+ * behavioural acceptance path against a real database is not covered here —+ * these are the byte-level contracts.+ *+ * Every fixture value is invented (placeholder ids, `example` names) per root+ * AGENTS.md Sensitive Data & Privacy — no value here came from a running+ * instance, and nothing here sends anything through a messaging API.+ */+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { mkdirSync, readdirSync, rmSync, utimesSync, writeFileSync, existsSync } from 'fs';+import { dirname, join } from 'path';+import { createTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';++const tempRoot = createTempDataRoot('portos-beeper-attachments-');++vi.mock('../lib/db.js', () => ({ query: vi.fn() }));+vi.mock('./settings.js', () => ({ getSettings: vi.fn() }));+// The client is mocked WHOLE rather than partially: importing the real module+// pulls in the vault-backed credential store, which reads `PATHS` at import+// time — before the hoisted temp-root mock below can answer. The service only+// ever branches on `err.code === 'ASSET_UNAVAILABLE'`, and that mapping (a 502+// from `serve` for media the network aged out) is pinned where it is decided,+// in `beeperClient.test.js`.+vi.mock('./beeperClient.js', () => {+ class MockBeeperApiError extends Error {+ constructor(message, { status = 500, code, retryable = false } = {}) {+ super(message);+ this.name = 'BeeperApiError';+ this.status = status;+ this.code = code;+ this.retryable = retryable;+ }+ }+ return { BeeperApiError: MockBeeperApiError, headAsset: vi.fn(), fetchAssetStream: vi.fn() };+});+vi.mock('../lib/fileUtils.js', async (importOriginal) =>+ makePathsProxy(await importOriginal(), { dataRoot: () => tempRoot }));++import { query } from '../lib/db.js';+import { getSettings } from './settings.js';+import { BeeperApiError, headAsset, fetchAssetStream } from './beeperClient.js';+import {+ attachmentsRoot,+ backfillAttachments,+ ensureAttachmentBytes,+ evictToBudget,+ getAttachment,+ getAttachmentSummary,+ purgeConversationAttachments,+ shapeAttachment,+ sweepAttachmentOrphans,+} from './beeperAttachments.js';++const CONV = '11111111-1111-4111-8111-111111111111';++const attachmentRow = (overrides = {}) => ({+ conversation_id: CONV,+ message_id: 'msg-example-1',+ idx: 0,+ mxc_id: 'mxc://example.invalid/abc',+ mime_type: 'image/png',+ byte_length: null,+ file_name: 'example.png',+ width: null,+ height: null,+ last_viewed_at: null,+ keep: false,+ local_path: null,+ fetched_at: null,+ unavailable_at: null,+ fetch_error: null,+ ...overrides,+});++// A `Response`-shaped fake whose `body` is a real web ReadableStream, because+// the mirror consumes it through `Readable.fromWeb` — a fake array would not+// exercise the byte counter that enforces the mid-stream ceiling.+const streamResponse = (chunks) => ({+ ok: true,+ status: 200,+ body: new ReadableStream({+ start(controller) {+ for (const chunk of chunks) controller.enqueue(chunk);+ controller.close();+ },+ }),+});++const unavailableError = () => new BeeperApiError('Failed to download asset: Transfer failed', {+ status: 502, code: 'ASSET_UNAVAILABLE', retryable: false,+});++/**+ * Answer `query()` from a table of SQL fragment → result, so a test states the+ * three or four statements it cares about instead of ordering every call.+ */+const respondTo = (table, fallback = { rows: [] }) => {+ vi.mocked(query).mockImplementation(async (sql) => {+ const flat = String(sql).replace(/\s+/g, ' ');+ for (const [fragment, result] of table) {+ if (flat.includes(fragment)) return typeof result === 'function' ? result(flat) : result;+ }+ return fallback;+ });+};++const storedFiles = () => {+ const root = attachmentsRoot();+ if (!existsSync(root)) return [];+ return readdirSync(root, { withFileTypes: true })+ .filter((entry) => entry.isDirectory() && entry.name !== '.tmp')+ .flatMap((entry) => readdirSync(join(root, entry.name)).map((name) => `${entry.name}/${name}`));+};++beforeEach(() => {+ vi.clearAllMocks();+ vi.mocked(getSettings).mockResolvedValue({ beeper: { attachmentBudgetGb: 5 } });+ rmSync(tempRoot, { recursive: true, force: true });+ mkdirSync(tempRoot, { recursive: true });+});++afterEach(() => rmSync(tempRoot, { recursive: true, force: true }));++describe('ensureAttachmentBytes — the lazy mirror', () => {+ it('downloads on first view, stores content-addressed, and serves from disk on the second', async () => {+ let row = attachmentRow();+ vi.mocked(query).mockImplementation(async (sql, params) => {+ const flat = String(sql).replace(/\s+/g, ' ');+ if (flat.includes('FROM beeper_attachments WHERE message_id')) return { rows: [row] };+ if (flat.includes('SET local_path = $3')) {+ // No `sha256` column write (audit cluster 06 decision 3) — the UPDATE+ // is `local_path, byte_length`, so `params` is 4-long.+ row = { ...row, local_path: params[2], byte_length: params[3] };+ return { rows: [] };+ }+ return { rows: [] };+ });+ vi.mocked(headAsset).mockResolvedValue({ bytes: 5 });+ vi.mocked(fetchAssetStream).mockResolvedValue(streamResponse([new Uint8Array([1, 2, 3, 4, 5])]));++ const first = await ensureAttachmentBytes('msg-example-1', 0);+ expect(first.cached).toBe(false);+ expect(first.mimeType).toBe('image/png');+ // `<sha256[0..2]>/<sha256>.png` — one file, addressed by content.+ expect(storedFiles()).toHaveLength(1);+ expect(storedFiles()[0]).toMatch(/^[0-9a-f]{2}\/[0-9a-f]{64}\.png$/);++ const second = await ensureAttachmentBytes('msg-example-1', 0);+ expect(second.cached).toBe(true);+ // The second open costs nothing upstream — no HEAD, no stream.+ expect(vi.mocked(fetchAssetStream)).toHaveBeenCalledTimes(1);+ expect(vi.mocked(headAsset)).toHaveBeenCalledTimes(1);+ });++ it('refuses an over-cap attachment at the HEAD pre-flight, before a byte moves', async () => {+ respondTo([['FROM beeper_attachments WHERE message_id', { rows: [attachmentRow()] }]]);+ vi.mocked(headAsset).mockResolvedValue({ bytes: 40 * 1024 * 1024 });++ await expect(ensureAttachmentBytes('msg-example-1', 0)).rejects.toMatchObject({+ code: 'ATTACHMENT_TOO_LARGE', status: 413, context: { bytes: 40 * 1024 * 1024, maxBytes: 32 * 1024 * 1024 },+ });+ expect(vi.mocked(fetchAssetStream)).not.toHaveBeenCalled();+ expect(storedFiles()).toEqual([]);+ });++ it('records the size the HEAD reported when it refuses, so the next render is the real placeholder', async () => {+ // A row the bridge never reported a size for is NOT `overCap`, so the+ // thread renders an <img>, takes the 413, and would otherwise fall into the+ // generic retry — whose retry forces an unbounded download behind a button+ // that names neither the size nor the ceiling.+ respondTo([['FROM beeper_attachments WHERE message_id', { rows: [attachmentRow({ byte_length: null })] }]]);+ vi.mocked(headAsset).mockResolvedValue({ bytes: 41 * 1024 * 1024 });++ await expect(ensureAttachmentBytes('msg-example-1', 0)).rejects.toMatchObject({ code: 'ATTACHMENT_TOO_LARGE' });+ const write = vi.mocked(query).mock.calls.find(([sql]) => String(sql).includes('SET byte_length = $3'));+ expect(write).toBeTruthy();+ expect(write[1]).toEqual(['msg-example-1', 0, 41 * 1024 * 1024]);+ });++ it('abandons a transfer that goes silent mid-stream instead of holding the file open', async () => {+ respondTo([['FROM beeper_attachments WHERE message_id', { rows: [attachmentRow()] }]]);+ vi.mocked(headAsset).mockResolvedValue({ bytes: 8 });+ // A body that emits one chunk and then never resolves again — the shape the+ // header-only fetch budget cannot see. The mirror's own idle abort is what+ // ends it; the signal it passes is the one under test.+ vi.mocked(fetchAssetStream).mockImplementation(async (_id, { signal } = {}) => ({+ ok: true,+ status: 200,+ body: new ReadableStream({+ start(controller) {+ controller.enqueue(new Uint8Array([1, 2, 3, 4]));+ signal?.addEventListener('abort', () => controller.error(new Error('aborted')), { once: true });+ },+ }),+ }));+ vi.useFakeTimers();+ const pending = ensureAttachmentBytes('msg-example-1', 0);+ const settled = pending.then(() => null).catch((err) => err);+ await vi.advanceTimersByTimeAsync(61_000);+ const failure = await settled;+ vi.useRealTimers();++ expect(failure).toMatchObject({ code: 'ATTACHMENT_DOWNLOAD_FAILED' });+ expect(storedFiles()).toEqual([]);+ expect(readdirSync(join(attachmentsRoot(), '.tmp'))).toEqual([]);+ });++ it('aborts mid-stream when the source declines to report a size and overruns the ceiling', async () => {+ respondTo([['FROM beeper_attachments WHERE message_id', { rows: [attachmentRow()] }]]);+ // `bytes: null` is "the server would not say" — which must not read as+ // zero and sail under the ceiling.+ vi.mocked(headAsset).mockResolvedValue({ bytes: null });+ const oversized = () => streamResponse(+ Array.from({ length: 34 }, () => new Uint8Array(1024 * 1024)),+ );+ vi.mocked(fetchAssetStream).mockImplementation(async () => oversized());++ await expect(ensureAttachmentBytes('msg-example-1', 0)).rejects.toMatchObject({+ code: 'ATTACHMENT_TOO_LARGE',+ });+ // Nothing finalized, and the partial is cleaned up rather than left to+ // count against the budget.+ expect(storedFiles()).toEqual([]);+ expect(readdirSync(join(attachmentsRoot(), '.tmp'))).toEqual([]);+ });++ it('lifts the ceiling only for an explicit "fetch anyway"', async () => {+ respondTo([['FROM beeper_attachments WHERE message_id', { rows: [attachmentRow({ byte_length: 40 * 1024 * 1024 })] }]]);+ vi.mocked(headAsset).mockResolvedValue({ bytes: 40 * 1024 * 1024 });+ vi.mocked(fetchAssetStream).mockResolvedValue(streamResponse([new Uint8Array(16)]));++ const result = await ensureAttachmentBytes('msg-example-1', 0, { force: true });+ expect(result.cached).toBe(false);+ expect(storedFiles()).toHaveLength(1);+ });++ it('stamps a 502 as terminal and never re-requests it on the next view', async () => {+ const calls = [];+ let row = attachmentRow();+ vi.mocked(query).mockImplementation(async (sql, params) => {+ const flat = String(sql).replace(/\s+/g, ' ');+ calls.push(flat);+ if (flat.includes('FROM beeper_attachments WHERE message_id')) return { rows: [row] };+ if (flat.includes('SET unavailable_at = NOW()')) {+ row = { ...row, unavailable_at: '2026-09-03T00:00:00.000Z', fetch_error: params[2] };+ return { rows: [] };+ }+ return { rows: [] };+ });+ vi.mocked(headAsset).mockRejectedValue(unavailableError());++ await expect(ensureAttachmentBytes('msg-example-1', 0)).rejects.toMatchObject({ code: 'ASSET_UNAVAILABLE' });+ expect(calls.some((sql) => sql.includes('SET unavailable_at = NOW()'))).toBe(true);++ await expect(ensureAttachmentBytes('msg-example-1', 0)).rejects.toMatchObject({+ code: 'ASSET_UNAVAILABLE', status: 404,+ });+ // The second view short-circuits on the stamp — one probe, not a loop.+ expect(vi.mocked(headAsset)).toHaveBeenCalledTimes(1);+ });++ it('never turns a malformed stored path into a filesystem read — it re-acquires instead', async () => {+ // `local_path` is a DB column that becomes a path, and a mirror row may have+ // been written by any past version of PortOS. A value that is not this+ // layout's own `<sha256[0..2]>/<sha256>.<ext>` is refused as a path outright+ // rather than resolved and stat-ed.+ let row = attachmentRow({ local_path: '../../../etc/hosts' });+ vi.mocked(query).mockImplementation(async (sql, params) => {+ const flat = String(sql).replace(/\s+/g, ' ');+ if (flat.includes('FROM beeper_attachments WHERE message_id')) return { rows: [row] };+ if (flat.includes('SET local_path = $3')) {+ row = { ...row, local_path: params[2] };+ return { rows: [] };+ }+ return { rows: [] };+ });+ vi.mocked(headAsset).mockResolvedValue({ bytes: 2 });+ vi.mocked(fetchAssetStream).mockResolvedValue(streamResponse([new Uint8Array([1, 2])]));++ const result = await ensureAttachmentBytes('msg-example-1', 0);+ expect(result.filePath.startsWith(attachmentsRoot())).toBe(true);+ expect(result.filePath).not.toContain('etc/hosts');+ });++ it('heals a row whose file was removed from under it instead of 404ing', async () => {+ let row = attachmentRow({ local_path: `aa/${'a'.repeat(64)}.png`, fetched_at: '2026-09-01T00:00:00.000Z' });+ const cleared = [];+ vi.mocked(query).mockImplementation(async (sql, params) => {+ const flat = String(sql).replace(/\s+/g, ' ');+ if (flat.includes('FROM beeper_attachments WHERE message_id')) return { rows: [row] };+ if (flat.includes('SET local_path = NULL')) {+ cleared.push(flat);+ row = { ...row, local_path: null };+ return { rows: [] };+ }+ if (flat.includes('SET local_path = $3')) return { rows: [] };+ return { rows: [] };+ });+ vi.mocked(headAsset).mockResolvedValue({ bytes: 3 });+ vi.mocked(fetchAssetStream).mockResolvedValue(streamResponse([new Uint8Array([9, 9, 9])]));++ const result = await ensureAttachmentBytes('msg-example-1', 0);+ expect(cleared.length).toBe(1);+ expect(result.cached).toBe(false);+ expect(storedFiles()).toHaveLength(1);+ });+});++// LENS-3/PERF-2: the PK on beeper_attachments leads with `conversation_id`,+// which every one of these lookups is written WITHOUT — this pins the query+// shape (`message_id` leading, matching `idx_beeper_attachments_message`) so+// a future edit can't silently regress it back onto a table scan. The actual+// plan is proven against a real index in beeperConversations.db.test.js.+describe('attachment lookups lead with message_id, matching the new index', () => {+ it('getAttachment queries WHERE message_id = $1 AND idx = $2, in that column order', async () => {+ respondTo([['FROM beeper_attachments WHERE message_id', { rows: [attachmentRow()] }]]);+ await getAttachment('msg-example-1', 0);+ const call = vi.mocked(query).mock.calls.find(([sql]) => String(sql).includes('FROM beeper_attachments WHERE message_id'));+ expect(call).toBeTruthy();+ expect(String(call[0]).replace(/\s+/g, ' ')).toContain('WHERE message_id = $1 AND idx = $2');+ });+});++describe('evictToBudget — least-recently-viewed, guarded by a HEAD', () => {+ const relPath = `aa/${'a'.repeat(64)}.png`;++ const seedFile = (relativePath, bytes = 16) => {+ mkdirSync(join(attachmentsRoot(), relativePath.split('/')[0]), { recursive: true });+ writeFileSync(join(attachmentsRoot(), relativePath), Buffer.alloc(bytes));+ };++ it('never offers a row with no source reference as a candidate', async () => {+ respondTo([['unique_files', { rows: [{ bytes: String(10 * 1024 * 1024 * 1024), files: 1 }] }]]);+ await evictToBudget();+ // Eviction is only safe because the bytes can be fetched again; a row with+ // no `mxc_id` is precisely the one that could not be, so it is filtered in+ // the candidate query rather than skipped after selection (which would+ // re-select it forever).+ const candidateSql = vi.mocked(query).mock.calls+ .map(([sql]) => String(sql).replace(/\s+/g, ' '))+ .find((sql) => sql.includes('ORDER BY last_viewed_at ASC NULLS FIRST'));+ expect(candidateSql).toContain('mxc_id IS NOT NULL');+ });++ it('does nothing while the mirror fits its budget', async () => {+ respondTo([['unique_files', { rows: [{ bytes: '1024', files: 1 }] }]]);+ const result = await evictToBudget();+ expect(result).toMatchObject({ evicted: 0, overBudget: false });+ expect(vi.mocked(headAsset)).not.toHaveBeenCalled();+ });++ it('evicts the least-recently-viewed file once the source confirms it is re-fetchable', async () => {+ seedFile(relPath);+ let used = 10 * 1024 * 1024 * 1024;+ let candidateRemaining = true;+ vi.mocked(query).mockImplementation(async (sql) => {+ const flat = String(sql).replace(/\s+/g, ' ');+ if (flat.includes('unique_files')) return { rows: [{ bytes: String(used), files: 1 }] };+ if (flat.includes('ORDER BY last_viewed_at ASC NULLS FIRST')) {+ return candidateRemaining+ ? { rows: [{ message_id: 'msg-example-1', idx: 0, mxc_id: 'mxc://example.invalid/abc', local_path: relPath, byte_length: 16 }] }+ : { rows: [] };+ }+ if (flat.includes('SET local_path = NULL')) { candidateRemaining = false; used = 0; return { rows: [] }; }+ if (flat.includes('WHERE local_path = $1 LIMIT 1')) return { rows: [] };+ return { rows: [] };+ });+ vi.mocked(headAsset).mockResolvedValue({ bytes: 16 });++ const result = await evictToBudget();+ expect(result.evicted).toBe(1);+ expect(existsSync(join(attachmentsRoot(), relPath))).toBe(false);+ });++ // LENS-4: the candidate index now orders `last_viewed_at ASC NULLS FIRST` —+ // a never-viewed attachment is the BEST eviction candidate (least, not most,+ // recently seen), and this pins that the service still evicts it cleanly+ // when the query hands one back, rather than choking on the `null`.+ it('evicts a never-viewed candidate (NULL last_viewed_at) exactly like any other', async () => {+ seedFile(relPath);+ let candidateRemaining = true;+ vi.mocked(query).mockImplementation(async (sql) => {+ const flat = String(sql).replace(/\s+/g, ' ');+ if (flat.includes('unique_files')) return { rows: [{ bytes: String(10 * 1024 * 1024 * 1024), files: 1 }] };+ if (flat.includes('ORDER BY last_viewed_at ASC NULLS FIRST')) {+ return candidateRemaining+ ? { rows: [{+ message_id: 'msg-example-1', idx: 0, mxc_id: 'mxc://example.invalid/abc',+ local_path: relPath, byte_length: 16, last_viewed_at: null,+ }] }+ : { rows: [] };+ }+ if (flat.includes('SET local_path = NULL')) { candidateRemaining = false; return { rows: [] }; }+ if (flat.includes('WHERE local_path = $1 LIMIT 1')) return { rows: [] };+ return { rows: [] };+ });+ vi.mocked(headAsset).mockResolvedValue({ bytes: 16 });++ const result = await evictToBudget();+ expect(result.evicted).toBe(1);+ expect(existsSync(join(attachmentsRoot(), relPath))).toBe(false);+ });++ it('KEEPS a file the source can no longer supply, and takes it out of future candidate queries', async () => {+ seedFile(relPath);+ const marked = [];+ vi.mocked(query).mockImplementation(async (sql) => {+ const flat = String(sql).replace(/\s+/g, ' ');+ if (flat.includes('unique_files')) return { rows: [{ bytes: String(10 * 1024 * 1024 * 1024), files: 1 }] };+ if (flat.includes('ORDER BY last_viewed_at ASC NULLS FIRST')) {+ return marked.length === 0+ ? { rows: [{ message_id: 'msg-example-1', idx: 0, mxc_id: 'mxc://example.invalid/abc', local_path: relPath, byte_length: 16 }] }+ : { rows: [] };+ }+ if (flat.includes('SET unavailable_at = NOW()')) { marked.push(flat); return { rows: [] }; }+ return { rows: [] };+ });+ vi.mocked(headAsset).mockRejectedValue(unavailableError());++ const result = await evictToBudget();+ expect(result).toMatchObject({ evicted: 0, keptUnavailable: 1 });+ expect(marked).toHaveLength(1);+ // The bytes Beeper can no longer supply are the last copy — still there.+ expect(existsSync(join(attachmentsRoot(), relPath))).toBe(true);+ });++ it('stops rather than evicting when the probe itself fails (Beeper closed)', async () => {+ seedFile(relPath);+ vi.mocked(query).mockImplementation(async (sql) => {+ const flat = String(sql).replace(/\s+/g, ' ');+ if (flat.includes('unique_files')) return { rows: [{ bytes: String(10 * 1024 * 1024 * 1024), files: 1 }] };+ if (flat.includes('ORDER BY last_viewed_at ASC NULLS FIRST')) {+ return { rows: [{ message_id: 'msg-example-1', idx: 0, mxc_id: 'mxc://example.invalid/abc', local_path: relPath, byte_length: 16 }] };+ }+ return { rows: [] };+ });+ vi.mocked(headAsset).mockRejectedValue(new BeeperApiError('Beeper asset request failed: connection refused', {+ status: 0, code: 'NETWORK_ERROR', retryable: false,+ }));++ const result = await evictToBudget();+ expect(result).toMatchObject({ evicted: 0, overBudget: true });+ expect(existsSync(join(attachmentsRoot(), relPath))).toBe(true);+ });+});++describe('the store is content-addressed, so every unlink is reference-checked', () => {+ const relPath = `cc/${'c'.repeat(64)}.png`;++ it('keeps a forwarded file that another conversation still points at', async () => {+ mkdirSync(join(attachmentsRoot(), 'cc'), { recursive: true });+ writeFileSync(join(attachmentsRoot(), relPath), Buffer.alloc(32));+ vi.mocked(query).mockImplementation(async (sql) => {+ const flat = String(sql).replace(/\s+/g, ' ');+ if (flat.includes('SELECT DISTINCT local_path FROM beeper_attachments WHERE conversation_id')) {+ return { rows: [{ local_path: relPath }] };+ }+ // A surviving row in ANOTHER conversation still points at these bytes.+ if (flat.includes('WHERE local_path = $1 LIMIT 1')) return { rows: [{ '?column?': 1 }] };+ return { rows: [] };+ });++ const result = await purgeConversationAttachments(CONV);+ expect(result).toEqual({ removedFiles: 0, freedBytes: 0, failedUnlinks: 0 });+ expect(existsSync(join(attachmentsRoot(), relPath))).toBe(true);+ });++ it('removes the file once nothing outside the purged conversation references it', async () => {+ mkdirSync(join(attachmentsRoot(), 'cc'), { recursive: true });+ writeFileSync(join(attachmentsRoot(), relPath), Buffer.alloc(32));+ vi.mocked(query).mockImplementation(async (sql) => {+ const flat = String(sql).replace(/\s+/g, ' ');+ if (flat.includes('SELECT DISTINCT local_path FROM beeper_attachments WHERE conversation_id')) {+ return { rows: [{ local_path: relPath }] };+ }+ return { rows: [] };+ });++ const result = await purgeConversationAttachments(CONV);+ expect(result).toMatchObject({ removedFiles: 1, freedBytes: 32, failedUnlinks: 0 });+ expect(existsSync(join(attachmentsRoot(), relPath))).toBe(false);+ });++ it('counts an unlink it could not perform instead of reporting the bytes as reclaimed', async () => {+ // A directory standing where the mirrored file should be: `unlink` refuses+ // it, which is the shape every un-unlinkable path takes — a read-only+ // mount, a permissions change, a handle the OS will not let go of.+ const blocked = `ab/${'ab'.repeat(32)}.png`;+ mkdirSync(join(attachmentsRoot(), blocked), { recursive: true });+ respondTo([+ ['SELECT DISTINCT local_path FROM beeper_attachments WHERE conversation_id', { rows: [{ local_path: blocked }] }],+ ]);+ const errors = [];+ const errorSpy = vi.spyOn(console, 'error').mockImplementation((line) => { errors.push(String(line)); });++ const result = await purgeConversationAttachments(CONV);++ // The row has already given up its claim, so nothing points at these bytes+ // any more. Reporting them as reclaimed is exactly how they vanish from the+ // budget while still sitting on the disk.+ expect(result).toEqual({ removedFiles: 0, freedBytes: 0, failedUnlinks: 1 });+ expect(existsSync(join(attachmentsRoot(), blocked))).toBe(true);+ expect(errors.some((line) => line.includes('unlink failed'))).toBe(true);+ errorSpy.mockRestore();+ });+});++describe('sweepAttachmentOrphans — the backstop, both directions', () => {+ it('removes a file no row points at and heals a row whose file is gone', async () => {+ const orphan = `ee/${'e'.repeat(64)}.png`;+ const missing = `11/${'1'.repeat(64)}.png`;+ mkdirSync(join(attachmentsRoot(), 'ee'), { recursive: true });+ writeFileSync(join(attachmentsRoot(), orphan), Buffer.alloc(8));+ // Backdated past the sweep's age gate: a file linked into place seconds ago+ // may be a download whose row update has not landed yet, so only an old+ // unreferenced file counts as an orphan.+ const hoursAgo = new Date(Date.now() - 4 * 60 * 60 * 1000);+ utimesSync(join(attachmentsRoot(), orphan), hoursAgo, hoursAgo);++ const healed = [];+ vi.mocked(query).mockImplementation(async (sql, params) => {+ const flat = String(sql).replace(/\s+/g, ' ');+ if (flat.includes('SELECT DISTINCT local_path FROM beeper_attachments WHERE local_path IS NOT NULL')) {+ return { rows: [{ local_path: missing }] };+ }+ if (flat.includes('WHERE local_path = ANY')) { healed.push(params[0]); return { rowCount: 1 }; }+ return { rows: [] };+ });++ const result = await sweepAttachmentOrphans();+ expect(result).toMatchObject({ orphansRemoved: 1, healedRows: 1 });+ expect(existsSync(join(attachmentsRoot(), orphan))).toBe(false);+ expect(healed[0]).toEqual([missing]);+ });++ it('spares a file that gained a reference between the snapshot and the unlink', async () => {+ const shared = `ff/${'f'.repeat(64)}.png`;+ mkdirSync(join(attachmentsRoot(), 'ff'), { recursive: true });+ writeFileSync(join(attachmentsRoot(), shared), Buffer.alloc(8));+ const hoursAgo = new Date(Date.now() - 4 * 60 * 60 * 1000);+ utimesSync(join(attachmentsRoot(), shared), hoursAgo, hoursAgo);++ // Unreferenced when the sweep took its snapshot, and claimed by the time+ // the unlink loop reaches it — a dedupe fetch that landed on these exact+ // bytes through link()'s EEXIST. The age gate cannot see that: the file is+ // genuinely old, it is the REFERENCE that is new.+ respondTo([+ ['SELECT DISTINCT local_path FROM beeper_attachments WHERE local_path IS NOT NULL', { rows: [] }],+ ['WHERE local_path = $1 LIMIT 1', { rows: [{ '?column?': 1 }] }],+ ]);++ const result = await sweepAttachmentOrphans();++ // Otherwise the row that just claimed these bytes reports `stored: true`+ // against a file that is gone.+ expect(result.orphansRemoved).toBe(0);+ expect(existsSync(join(attachmentsRoot(), shared))).toBe(true);+ });++ it('reads a store it cannot list as unreadable rather than empty, and heals no row', async () => {+ // The store root is replaced by a FILE, so every listing of it fails+ // (ENOTDIR) exactly the way an EACCES or a data volume that came back+ // unmounted would. A `catch(() => [])` reads that as "no files on disk" and+ // then clears every mirrored row's claim on its bytes in one pass.+ const root = attachmentsRoot();+ mkdirSync(dirname(root), { recursive: true });+ writeFileSync(root, Buffer.alloc(0));++ const referencedPath = `bb/${'b'.repeat(64)}.png`;+ const healed = [];+ vi.mocked(query).mockImplementation(async (sql, params) => {+ const flat = String(sql).replace(/\s+/g, ' ');+ if (flat.includes('SELECT DISTINCT local_path FROM beeper_attachments WHERE local_path IS NOT NULL')) {+ return { rows: [{ local_path: referencedPath }] };+ }+ if (flat.includes('WHERE local_path = ANY')) { healed.push(params[0]); return { rowCount: 1 }; }+ return { rows: [] };+ });+ const errors = [];+ const errorSpy = vi.spyOn(console, 'error').mockImplementation((line) => { errors.push(String(line)); });++ const result = await sweepAttachmentOrphans();++ expect(result).toMatchObject({ storeListed: false, healedRows: 0 });+ // Not one `local_path` cleared, and the failure is said out loud rather+ // than read as an empty store.+ expect(healed).toEqual([]);+ expect(errors.some((line) => line.includes('could not be listed'))).toBe(true);+ expect(errors.some((line) => line.includes('no row healed this pass'))).toBe(true);+ errorSpy.mockRestore();+ });++ it('names a failed unlink in the sweep log line rather than swallowing it', async () => {+ const blocked = `ba/${'ba'.repeat(32)}.png`;+ mkdirSync(join(attachmentsRoot(), blocked), { recursive: true });+ const hoursAgo = new Date(Date.now() - 4 * 60 * 60 * 1000);+ utimesSync(join(attachmentsRoot(), blocked), hoursAgo, hoursAgo);+ respondTo([['SELECT DISTINCT local_path FROM beeper_attachments WHERE local_path IS NOT NULL', { rows: [] }]]);+ const logs = [];+ const logSpy = vi.spyOn(console, 'log').mockImplementation((line) => { logs.push(String(line)); });+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});++ const result = await sweepAttachmentOrphans();++ // Swallowed, this is a sweep that reports "0 orphan file(s)" and stays+ // silent while the bytes it meant to reclaim are still there.+ expect(result).toMatchObject({ orphansRemoved: 0, failedUnlinks: 1 });+ expect(logs.some((line) => line.includes('1 unlink failure(s)'))).toBe(true);+ logSpy.mockRestore();+ errorSpy.mockRestore();+ });++ it('spares an unreferenced file young enough to be a download still finishing', async () => {+ const fresh = `dd/${'d'.repeat(64)}.png`;+ mkdirSync(join(attachmentsRoot(), 'dd'), { recursive: true });+ writeFileSync(join(attachmentsRoot(), fresh), Buffer.alloc(8));+ respondTo([['SELECT DISTINCT local_path FROM beeper_attachments WHERE local_path IS NOT NULL', { rows: [] }]]);++ const result = await sweepAttachmentOrphans();+ expect(result.orphansRemoved).toBe(0);+ expect(existsSync(join(attachmentsRoot(), fresh))).toBe(true);+ });+});++describe('the backfill census the consent step has to state', () => {+ it('counts unknown-size attachments separately instead of adding them as zero', async () => {+ respondTo([+ ['unique_files', { rows: [{ bytes: '2048', files: 2 }] }],+ ['COUNT(*) FILTER', { rows: [{ pending: 12, pending_bytes: '4096', pending_unknown: 3, over_cap: 1, unavailable: 2, kept: 1, total: 20 }] }],+ ]);+ const summary = await getAttachmentSummary();+ expect(summary).toMatchObject({+ usedBytes: 2048, pendingCount: 12, pendingBytes: 4096, pendingUnknownCount: 3, overCapCount: 1,+ });+ expect(summary.budgetBytes).toBe(5 * 1024 * 1024 * 1024);+ });++ it('counts a failed attachment and carries on through the rest of the run', async () => {+ const pending = [+ { message_id: 'msg-example-1', idx: 0 },+ { message_id: 'msg-example-2', idx: 0 },+ ];+ vi.mocked(query).mockImplementation(async (sql) => {+ const flat = String(sql).replace(/\s+/g, ' ');+ if (flat.includes('ORDER BY created_at ASC')) return { rows: pending };+ if (flat.includes('unique_files')) return { rows: [{ bytes: '0', files: 0 }] };+ if (flat.includes('FROM beeper_attachments WHERE message_id')) {+ return { rows: [attachmentRow({ message_id: 'msg-example-1' })] };+ }+ return { rows: [] };+ });+ vi.mocked(headAsset)+ .mockRejectedValueOnce(unavailableError())+ .mockResolvedValueOnce({ bytes: 4 });+ vi.mocked(fetchAssetStream).mockResolvedValue(streamResponse([new Uint8Array([7, 7, 7, 7])]));++ const result = await backfillAttachments({ limit: 10 });+ expect(result).toMatchObject({ requested: 2, fetched: 1, failed: 1, stoppedForBudget: false });+ });++ it('stops at the disk budget rather than blowing through it', async () => {+ vi.mocked(getSettings).mockResolvedValue({ beeper: { attachmentBudgetGb: 0.000001 } });+ vi.mocked(query).mockImplementation(async (sql) => {+ const flat = String(sql).replace(/\s+/g, ' ');+ if (flat.includes('ORDER BY created_at ASC')) return { rows: [{ message_id: 'msg-example-1', idx: 0 }] };+ if (flat.includes('unique_files')) return { rows: [{ bytes: '999999999', files: 9 }] };+ return { rows: [] };+ });++ const result = await backfillAttachments({});+ expect(result).toMatchObject({ fetched: 0, stoppedForBudget: true });+ expect(vi.mocked(fetchAssetStream)).not.toHaveBeenCalled();+ });++ // PERF-4: `storedBytes()` is a DISTINCT ON scan of the whole table — this+ // pins that a multi-attachment pass costs ONE such scan, not one per row.+ it('computes the byte-count total once per pass, not once per attachment', async () => {+ const pending = [+ { message_id: 'msg-example-1', idx: 0 },+ { message_id: 'msg-example-2', idx: 0 },+ { message_id: 'msg-example-3', idx: 0 },+ ];+ let uniqueFilesCalls = 0;+ vi.mocked(query).mockImplementation(async (sql) => {+ const flat = String(sql).replace(/\s+/g, ' ');+ if (flat.includes('ORDER BY created_at ASC')) return { rows: pending };+ if (flat.includes('unique_files')) {+ uniqueFilesCalls += 1;+ return { rows: [{ bytes: '0', files: 0 }] };+ }+ if (flat.includes('FROM beeper_attachments WHERE message_id')) return { rows: [attachmentRow()] };+ return { rows: [] };+ });+ vi.mocked(headAsset).mockResolvedValue({ bytes: 4 });+ vi.mocked(fetchAssetStream).mockImplementation(async () => streamResponse([new Uint8Array([1, 2, 3, 4])]));++ const result = await backfillAttachments({ limit: 10 });+ expect(result.fetched).toBe(3);+ expect(uniqueFilesCalls).toBe(1);+ });+});++describe('shapeAttachment', () => {+ it('reads an unknown byte length as unknown, never as over-cap', () => {+ expect(shapeAttachment(attachmentRow({ byte_length: null }))).toMatchObject({+ byteLength: null, overCap: false, stored: false, unavailable: false,+ });+ });++ it('separates "stored" from "unavailable" — a mirrored file whose source aged out is both', () => {+ const shaped = shapeAttachment(attachmentRow({+ local_path: `aa/${'a'.repeat(64)}.png`,+ unavailable_at: '2026-09-01T00:00:00.000Z',+ fetch_error: 'Failed to download asset',+ byte_length: 40 * 1024 * 1024,+ }));+ expect(shaped).toMatchObject({ stored: true, unavailable: true, overCap: true });+ });+});diff --git a/server/services/beeperClient.js b/server/services/beeperClient.jsnew file mode 100644index 0000000000..9c8b6c51db--- /dev/null+++ b/server/services/beeperClient.js@@ -0,0 +1,906 @@+/**+ * 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,+ 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}` },+ 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 --git a/server/services/beeperClient.test.js b/server/services/beeperClient.test.jsnew file mode 100644index 0000000000..cb845d20b0--- /dev/null+++ b/server/services/beeperClient.test.js@@ -0,0 +1,830 @@+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,+ 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('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 --git a/server/services/beeperConversations.db.test.js b/server/services/beeperConversations.db.test.jsnew file mode 100644index 0000000000..5a7609b848--- /dev/null+++ b/server/services/beeperConversations.db.test.js@@ -0,0 +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.+ *+ * `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+ * 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).+ * 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');+ 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 --git a/server/services/beeperConversations.js b/server/services/beeperConversations.jsnew file mode 100644index 0000000000..501b7a0437--- /dev/null+++ b/server/services/beeperConversations.js@@ -0,0 +1,623 @@+/**+ * Read model + wired rail controls for the Beeper chat surface (#35, design+ * decided on #9; store shape from #7/#27).+ *+ * **The mirror is the read path.** Nothing here calls Beeper to *read*: the+ * surface renders `beeper_conversations` / `beeper_messages` /+ * `beeper_participants`, which the sweep (#32) and the socket relay (#33)+ * keep current. That is what makes "displayed" imply "persisted", keeps the+ * list correct while Beeper Desktop is closed, and keeps the socket frames+ * invalidation-only — a refetch here is a local query, not a fan-out to the+ * upstream API.+ *+ * The two rail controls that are WIRED (#9: `Archive` and `Low priority`,+ * because `isArchived` and `isLowPriority` are real fields on every chat row)+ * are the one exception: they PATCH Beeper first and mirror the result second,+ * because Beeper owns that state. `isPinned` is deliberately NOT here — the+ * pinned set is Beeper's own, mirrored (#27), and a PortOS-local pin would be+ * a second source of truth for it.+ *+ * Writes NEVER retry. `beeperRequest`'s `allowRetry` already defaults to false+ * for exactly this reason, and the route surfaces `retryable: false` so a+ * client cannot invent a retry policy on top of an API with no idempotency key.+ */++import { query, withTransaction } from '../lib/db.js';+import { ServerError } from '../lib/errorHandler.js';+import { resolveLinkedPersonId } from '../lib/tribeMatch.js';+import { updateChat } from './beeperClient.js';+import {+ getConversationAttachmentBytes,+ purgeConversationAttachments,+ shapeAttachment,+} from './beeperAttachments.js';++// The list endpoint returns a PARTICIPANT SUBSET, never a roster. Beeper's own+// participant lists truncate at 20 (list) / 100 (single GET) with no+// participants endpoint and no cursor (#2), so a row set is always a possible+// subset — `beeper_participants.observed_via` records which. Capping here is+// therefore honest rather than lossy: the number is a row-budget for the list+// payload, and `hasMoreParticipants` says the cell is not the whole story.+const LIST_PARTICIPANT_CAP = 8;++const DEFAULT_CONVERSATION_LIMIT = 50;+const MAX_CONVERSATION_LIMIT = 200;+const DEFAULT_MESSAGE_LIMIT = 50;+const MAX_MESSAGE_LIMIT = 200;++// ---------------------------------------------------------------------------+// Cursors+// ---------------------------------------------------------------------------++/**+ * Keyset cursors, not offsets. An offset re-reads a window that shifted under+ * an incoming message and silently drops or repeats a row; the surface refetches+ * on every invalidation frame, so that shift is the normal case rather than a+ * rare one. The cursor carries the exact ordering tuple `(orderingTs, id)` the+ * ORDER BY uses, base64url-encoded so it is opaque to the client.+ */+export function encodeCursor(orderingTs, id) {+ if (!orderingTs || !id) return null;+ return Buffer.from(`${new Date(orderingTs).toISOString()}|${id}`, 'utf8').toString('base64url');+}++// `listConversations` binds the decoded id as `::uuid` (conversation ids are+// real Postgres uuids); `listMessages` binds it as `::text` (Beeper message+// ids are arbitrary bridge-assigned strings, never uuids). A hand-edited or+// truncated cursor whose `id` half is not a uuid used to sail through here and+// 500 on the Postgres cast instead of falling back to the first page, which+// contradicts this function's own contract of returning `null` for anything+// malformed. Callers that bind the id as `::uuid` pass `idPattern` so the+// SHAPE check happens here, once, rather than after a failed query.+const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++/**+ * `null` for anything unparseable — a stale or hand-edited cursor restarts the+ * page rather than 500ing, which is the same posture the rest of the surface+ * takes toward a deleted conversation id.+ *+ * @param {string} cursor+ * @param {{ idPattern?: RegExp }} [options] - When given, `id` must match it or+ * the cursor is treated as malformed (see `UUID_PATTERN` above).+ */+export function decodeCursor(cursor, { idPattern } = {}) {+ if (typeof cursor !== 'string' || !cursor) return null;+ const raw = Buffer.from(cursor, 'base64url').toString('utf8');+ const separator = raw.indexOf('|');+ if (separator <= 0) return null;+ const ts = raw.slice(0, separator);+ const id = raw.slice(separator + 1);+ if (!id || Number.isNaN(new Date(ts).getTime())) return null;+ if (idPattern && !idPattern.test(id)) return null;+ return { ts: new Date(ts).toISOString(), id };+}++// ---------------------------------------------------------------------------+// Row shaping+// ---------------------------------------------------------------------------++const toIso = (value) => (value ? new Date(value).toISOString() : null);++// LOCAL "seen in PortOS" watermark (#83). `row.seen_at` is stamped by+// `markConversationSeen` when a thread is opened here, and NEVER by the sweep+// (`beeperSync.js`'s `upsertConversation` writes every other column on this+// row from Beeper's own `Chat`, but not this one). A watermark at or after the+// conversation's own last activity means nothing has landed since the user+// last opened it, even though Beeper's mirrored `unread_count` — overwritten+// wholesale on every sweep — still says otherwise; new activity after the+// watermark reads as unread again with no extra bookkeeping. `created_at` is+// the fallback activity floor for a conversation the mirror has never dated.+function isSeenLocally(row) {+ if (!row.seen_at) return false;+ const activity = row.last_activity || row.created_at;+ if (!activity) return false;+ return new Date(row.seen_at).getTime() >= new Date(activity).getTime();+}++// The SQL twin of `isSeenLocally`, for the two queries that decide "is this+// genuinely unread" inside the database rather than after shaping a row in+// JS (`listConversations`'s `unreadOnly` filter and `listNetworks`'s+// aggregates, neither of which materializes a full `beeper_conversations`+// row per conversation). Kept as one string so the two call sites cannot+// drift onto different comparisons.+const UNSEEN_SQL = '(c.seen_at IS NULL OR c.seen_at < COALESCE(c.last_activity, c.created_at))';++function shapeConversation(row) {+ return {+ id: row.id,+ accountId: row.account_id,+ network: row.network || '',+ sourceChatId: row.source_chat_id,+ title: row.title || '',+ type: row.type || 'single',+ isGroup: row.is_group === true,+ isPinned: row.is_pinned === true,+ isArchived: row.is_archived === true,+ isLowPriority: row.is_low_priority === true,+ isMuted: row.is_muted === true,+ lastActivity: toIso(row.last_activity),+ unreadCount: isSeenLocally(row) ? 0 : (Number(row.unread_count) || 0),+ // `null` = this conversation has no mirrored message yet, which is+ // frequently CORRECT rather than pending: history depth varies enormously+ // per network (#3), so the surface says so instead of spinning.+ lastMessage: row.preview_id+ ? {+ id: row.preview_id,+ body: row.preview_unsent_at ? '' : (row.preview_body || ''),+ senderId: row.preview_sender_id || '',+ sentAt: toIso(row.preview_sent_at),+ isUnsent: Boolean(row.preview_unsent_at),+ isSender: row.preview_is_sender === true,+ }+ : null,+ participants: [],+ hasMoreParticipants: false,+ };+}++function shapeParticipant(row) {+ // `resolveLinkedPersonId` (`lib/tribeMatch.js`) is the SAME soft-delete+ // predicate `beeperTribe.js`'s own participant shaper applies to this same+ // column — extracted so the two cannot drift onto different answers again.+ // A soft-deleted Tribe person (`tribe.deletePerson` never fires the FK's ON+ // DELETE CASCADE) must read as fully unlinked here: `null` id AND no name,+ // so the thread's re-link control comes back instead of a dead+ // "Linked · <deleted person>" the user can never recover from.+ const tribePersonId = resolveLinkedPersonId(row.tribe_person_id, row.tribe_person_deleted);+ return {+ conversationId: row.conversation_id,+ sourceUserId: row.source_user_id,+ displayName: row.display_name || '',+ handle: row.handle || '',+ // The cache column from #27/#34. `null` means "not linked", never "no+ // person exists" — the inline link action on the thread is what resolves it.+ tribePersonId,+ tribePersonName: tribePersonId ? (row.tribe_person_name || null) : null,+ observedVia: row.observed_via || '',+ };+}++function shapeMessage(row) {+ return {+ id: row.id,+ conversationId: row.conversation_id,+ senderId: row.sender_id || '',+ // A tombstoned message keeps its row AND its body in the store (#7/#13);+ // the surface renders the placeholder instead, so the body is withheld+ // here rather than shipped to a client that must not display it.+ body: row.unsent_at ? '' : (row.body || ''),+ sentAt: toIso(row.sent_at),+ editedAt: toIso(row.edited_at),+ unsentAt: toIso(row.unsent_at),+ // Which side of the thread this belongs on, mirrored from the API's own+ // `Message.isSender` (#27's `is_sender`). Derived server-side and never+ // guessed from `senderId`: `accounts[].user.id` differs from `senderID` on+ // every network, so the client has nothing to compare against.+ isSender: row.is_sender === true,+ attachments: [],+ };+}++// Attachment rows are shaped by the mirror service that owns their lifecycle+// (`beeperAttachments.shapeAttachment`), not by a second copy here: the thread+// renders `stored` / `overCap` / `unavailable` / `keep` off the same payload+// the attachment routes return, and two shapers would drift the moment one+// gained a field.++const clampLimit = (value, fallback, max) => {+ const n = Number(value);+ if (!Number.isFinite(n)) return fallback;+ return Math.min(Math.max(Math.trunc(n), 1), max);+};++// ---------------------------------------------------------------------------+// Reads+// ---------------------------------------------------------------------------++/**+ * Attach the participant subset to a page of conversations in ONE extra query+ * rather than one per row. Ordering puts linked people first so the capped+ * subset shows the rows a Tribe link already resolved.+ */+async function attachParticipants(conversations, { cap = LIST_PARTICIPANT_CAP } = {}) {+ if (conversations.length === 0) return conversations;+ const ids = conversations.map((c) => c.id);+ const result = await query(+ `SELECT p.conversation_id, p.source_user_id, p.display_name, p.handle,+ p.tribe_person_id, p.observed_via, tp.name AS tribe_person_name,+ tp.deleted AS tribe_person_deleted+ FROM beeper_participants p+ LEFT JOIN tribe_people tp ON tp.id = p.tribe_person_id+ WHERE p.conversation_id = ANY($1::uuid[])+ ORDER BY p.conversation_id,+ (p.tribe_person_id IS NULL),+ p.display_name,+ p.source_user_id`,+ [ids],+ );+ const byConversation = new Map(ids.map((id) => [id, []]));+ for (const row of result?.rows || []) {+ byConversation.get(row.conversation_id)?.push(shapeParticipant(row));+ }+ return conversations.map((conversation) => {+ const all = byConversation.get(conversation.id) || [];+ return {+ ...conversation,+ participants: cap === null ? all : all.slice(0, cap),+ hasMoreParticipants: cap !== null && all.length > cap,+ };+ });+}++/**+ * One page of the conversation list, newest activity first.+ *+ * Every filter is TRI-STATE by omission: an absent `archived` means "do not+ * filter on archived at all", which is a different query from `archived:false`.+ * The rail's Inbox scope asks for `archived:false, lowPriority:false`; the+ * Archive and Low-priority scopes ask for the positive. Collapsing absent into+ * false would make the unified scope silently hide archived chats with no way+ * to ask for them (root AGENTS.md, absent-vs-empty).+ *+ * The page is fetched FIRST — filtered, ordered, and limited on+ * `idx_beeper_conversations_activity_epoch_keyset` alone — and the "last message"+ * preview is a SECOND query scoped to just that page's ids. Folding the+ * preview LATERAL into the same WHERE/ORDER BY/LIMIT query (the old shape) let+ * the planner evaluate it once per FILTERED conversation rather than once per+ * PAGE row; splitting the preview into its own query, batched over the page's+ * ids the way `attachParticipants` already batches participants, makes+ * "page-sized" a property of the SQL shape rather than a plan the optimizer+ * happens to choose (audit cluster 06, indexes and query plans).+ */+export async function listConversations({+ network, unreadOnly, archived, lowPriority, limit, cursor,+} = {}) {+ const pageSize = clampLimit(limit, DEFAULT_CONVERSATION_LIMIT, MAX_CONVERSATION_LIMIT);+ const params = [];+ const where = [];++ if (typeof network === 'string' && network) {+ params.push(network);+ where.push(`c.network = $${params.length}`);+ }+ // The LOCAL watermark (#83) gates `unreadOnly` the same way it gates the+ // badge: a conversation Beeper still reports as unread but that carries a+ // `seen_at` at or after its own last activity is not shown, because nothing+ // has landed here since it was opened in PortOS.+ if (unreadOnly === true) where.push(`c.unread_count > 0 AND ${UNSEEN_SQL}`);+ if (typeof archived === 'boolean') {+ params.push(archived);+ where.push(`c.is_archived = $${params.length}`);+ }+ if (typeof lowPriority === 'boolean') {+ params.push(lowPriority);+ where.push(`c.is_low_priority = $${params.length}`);+ }++ const decoded = decodeCursor(cursor, { idPattern: UUID_PATTERN });+ if (decoded) {+ params.push(decoded.ts, decoded.id);+ where.push(`(COALESCE(c.last_activity, 'epoch'::timestamptz), c.id) < ($${params.length - 1}::timestamptz, $${params.length}::uuid)`);+ }++ params.push(pageSize + 1);+ const pageResult = await query(+ // #81: falling back to `c.created_at` here sorted a chat with no real+ // Beeper activity by the MIRROR ROW's mint time, not by "this chat has no+ // activity" — a batch of chats swept (and left activity-less) in the same+ // pass shared a recent `created_at` and sorted at the TOP of the Inbox,+ // exactly the reported symptom. `'epoch'::timestamptz` sorts every+ // activity-less chat LAST instead: older than any real timestamp, so it+ // ranks last under `DESC`, while keeping the row-value keyset tuple shape+ // a real `NULLS LAST` cannot (the keyset predicate above needs a value to+ // compare against, not a null). Matches+ // `idx_beeper_conversations_activity_epoch_keyset`.+ `SELECT c.*, COALESCE(c.last_activity, 'epoch'::timestamptz) AS ordering_ts+ FROM beeper_conversations c+ ${where.length ? `WHERE ${where.join(' AND ')}` : ''}+ ORDER BY COALESCE(c.last_activity, 'epoch'::timestamptz) DESC, c.id DESC+ LIMIT $${params.length}`,+ params,+ );++ const rows = pageResult?.rows || [];+ const page = rows.slice(0, pageSize);+ const last = page[page.length - 1];+ // `null`, not an empty string: "there is no next page" is a different+ // answer from "here is a cursor that returns nothing".+ const nextCursor = rows.length > pageSize && last ? encodeCursor(last.ordering_ts, last.id) : null;++ if (page.length === 0) {+ return { conversations: [], nextCursor };+ }++ // Batched over the PAGE's ids, never the filtered set — this is what keeps+ // the preview lookup bounded to `pageSize` rows no matter how many+ // conversations the filters above matched.+ const previewResult = await query(+ `SELECT ids.conversation_id, lm.id AS preview_id, lm.body AS preview_body,+ lm.sender_id AS preview_sender_id, lm.sent_at AS preview_sent_at,+ lm.unsent_at AS preview_unsent_at, lm.is_sender AS preview_is_sender+ FROM unnest($1::uuid[]) AS ids(conversation_id)+ LEFT JOIN LATERAL (+ SELECT m.id, m.body, m.sender_id, m.sent_at, m.unsent_at, m.is_sender+ 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`,+ [page.map((row) => row.id)],+ );+ const previewByConversation = new Map(+ (previewResult?.rows || []).map((row) => [row.conversation_id, row]),+ );++ const conversations = await attachParticipants(+ page.map((row) => shapeConversation({ ...row, ...(previewByConversation.get(row.id) || {}) })),+ );+ return { conversations, nextCursor };+}++/** One conversation, with its FULL mirrored participant set (no list cap). */+export async function getConversation(conversationId) {+ const result = await query(+ `SELECT c.*,+ lm.id AS preview_id, lm.body AS preview_body, lm.sender_id AS preview_sender_id,+ lm.sent_at AS preview_sent_at, lm.unsent_at AS preview_unsent_at,+ lm.is_sender AS preview_is_sender+ FROM beeper_conversations c+ LEFT JOIN LATERAL (+ SELECT m.id, m.body, m.sender_id, m.sent_at, m.unsent_at, m.is_sender+ FROM beeper_messages m+ WHERE m.conversation_id = c.id+ ORDER BY COALESCE(m.sent_at, m.created_at) DESC, m.id DESC+ LIMIT 1+ ) lm ON TRUE+ WHERE c.id = $1`,+ [conversationId],+ );+ const row = result?.rows?.[0];+ if (!row) return null;+ const [conversation] = await attachParticipants([shapeConversation(row)], { cap: null });+ // The mirrored byte total rides on the SINGLE-conversation read only. It is+ // what the purge confirmation names ("… and 41.2 MB of mirrored+ // attachments"), and a typed confirmation that cannot state the cost is not+ // a confirmation; the list endpoint does not pay for it per row.+ const bytes = await getConversationAttachmentBytes(conversation.id);+ return { ...conversation, attachmentBytes: bytes.bytes, attachmentFiles: bytes.files };+}++/**+ * One page of a thread, NEWEST FIRST — the order a chat surface actually+ * consumes, because it renders the tail and pages backwards into history. The+ * client reverses for display; the API does not pretend the oldest message is+ * reachable in one call, because on several networks it is not.+ */+export async function listMessages(conversationId, { limit, cursor } = {}) {+ const pageSize = clampLimit(limit, DEFAULT_MESSAGE_LIMIT, MAX_MESSAGE_LIMIT);+ const params = [conversationId];+ let keyset = '';+ const decoded = decodeCursor(cursor);+ if (decoded) {+ params.push(decoded.ts, decoded.id);+ keyset = ` AND (COALESCE(m.sent_at, m.created_at), m.id) < ($2::timestamptz, $3::text)`;+ }+ params.push(pageSize + 1);++ const result = await query(+ `SELECT m.*, COALESCE(m.sent_at, m.created_at) AS ordering_ts+ FROM beeper_messages m+ WHERE m.conversation_id = $1${keyset}+ ORDER BY COALESCE(m.sent_at, m.created_at) DESC, m.id DESC+ LIMIT $${params.length}`,+ params,+ );+ const rows = result?.rows || [];+ const page = rows.slice(0, pageSize);+ const messages = page.map(shapeMessage);++ if (messages.length > 0) {+ const attachments = await query(+ `SELECT *+ FROM beeper_attachments+ WHERE conversation_id = $1 AND message_id = ANY($2::text[])+ ORDER BY message_id, idx`,+ [conversationId, messages.map((m) => m.id)],+ );+ const byMessage = new Map(messages.map((m) => [m.id, m]));+ for (const row of attachments?.rows || []) {+ byMessage.get(row.message_id)?.attachments.push(shapeAttachment(row));+ }+ }++ const last = page[page.length - 1];+ return {+ messages,+ nextCursor: rows.length > pageSize && last ? encodeCursor(last.ordering_ts, last.id) : null,+ };+}++/**+ * The rail's scope list: the networks actually present in the mirror, never a+ * hardcoded roster. #9 is explicit that the development machine's nine+ * networks are an outlier (today's free tier caps a new account at five, most+ * installs have one), so anything that enumerates networks reads them from+ * data — a network PortOS has never heard of still renders.+ *+ * Unread is aggregated over NON-ARCHIVED rows only: the rail badge answers+ * "how much is waiting in my inbox", and an archived chat is by definition not.+ *+ * Both aggregates also honour the LOCAL "seen in PortOS" watermark (#83) via+ * `UNSEEN_SQL`: a conversation the user has opened here, with nothing new+ * since, contributes 0 to `unread_count` and does not count toward+ * `unread_conversations`, even though Beeper's own mirrored `unread_count`+ * still says otherwise.+ */+export async function listNetworks() {+ const result = await query(+ // #81: `COALESCE(…, c.created_at)` reported a network holding only+ // activity-less chats as "active just now" (the mirror row's mint time),+ // not honestly having none. This is a plain MAX, not the page/keyset walk+ // above — MAX ignores NULLs and itself yields NULL when every row in the+ // group is NULL, which is already the honest value, so no sentinel is+ // needed (unlike the row-value keyset tuple in listConversations, this+ // aggregate never has to compare against a null).+ `SELECT c.network,+ COUNT(*)::int AS conversation_count,+ COALESCE(SUM(c.unread_count) FILTER (WHERE c.is_archived = FALSE AND ${UNSEEN_SQL}), 0)::int AS unread_count,+ COUNT(*) FILTER (WHERE c.unread_count > 0 AND c.is_archived = FALSE AND ${UNSEEN_SQL})::int AS unread_conversations,+ ARRAY_AGG(DISTINCT c.account_id) AS account_ids,+ MAX(c.last_activity) AS last_activity+ FROM beeper_conversations c+ WHERE c.network <> ''+ GROUP BY c.network+ ORDER BY c.network`,+ );+ return (result?.rows || []).map((row) => ({+ network: row.network,+ conversationCount: Number(row.conversation_count) || 0,+ unreadCount: Number(row.unread_count) || 0,+ unreadConversations: Number(row.unread_conversations) || 0,+ accountIds: Array.isArray(row.account_ids) ? row.account_ids.filter(Boolean) : [],+ lastActivity: toIso(row.last_activity),+ }));+}++// ---------------------------------------------------------------------------+// Local "seen" watermark (#83) — NOT a Beeper write+// ---------------------------------------------------------------------------++/**+ * Stamp the LOCAL "seen in PortOS" watermark on one conversation. Called when+ * the chat surface opens a thread (`BeeperChatSurface.jsx`'s `loadThread`) and,+ * cheaply, again when a new message lands in the open thread.+ *+ * This is the opposite shape from `setConversationFlag` below: it NEVER calls+ * Beeper. The reading model this decision shipped has no side effects on the+ * source network — no read receipt, no `PATCH`, nothing that could surprise+ * someone checking Beeper Desktop on another device. `seen_at` is set to+ * `NOW()` unconditionally rather than `GREATEST(seen_at, NOW())`: wall-clock+ * time only moves forward across calls to the same row, so the two are+ * equivalent here and the plain assignment says that more plainly.+ *+ * TODO(#83): a settings toggle to also send a real read receipt through+ * Beeper's own API is the natural next wave — it would PATCH-then-mirror the+ * same way `setConversationFlag` does, gated behind that toggle and its own+ * consent step, and default OFF. Out of scope for this change.+ */+export async function markConversationSeen(conversationId) {+ const found = await query(+ 'SELECT id FROM beeper_conversations WHERE id = $1',+ [conversationId],+ );+ if (!found?.rows?.[0]) throw new ServerError('Conversation not found', { status: 404, code: 'NOT_FOUND' });++ await query(+ 'UPDATE beeper_conversations SET seen_at = NOW(), updated_at = NOW() WHERE id = $1',+ [conversationId],+ );+ return getConversation(conversationId);+}++// ---------------------------------------------------------------------------+// Wired rail controls (#9: Archive and Low priority)+// ---------------------------------------------------------------------------++/**+ * The one write shape this slice has. Beeper owns the flag, so the order is+ * PATCH-then-mirror: a mirror row updated before the upstream call would show a+ * state the network never accepted, and the next sweep would silently revert it.+ *+ * The PATCH does not retry (`beeperRequest`'s default), and a failure+ * propagates as a coded `BeeperApiError` with the mirror untouched.+ *+ * The response is Beeper's updated `Chat`. It is read DEFENSIVELY: a bridge+ * that answers 200 with a body missing the flag must not blank the mirror, so+ * the requested value is the fallback — present-but-false is honoured, absent+ * is not.+ */+async function setConversationFlag(conversationId, field, column, value) {+ const found = await query(+ 'SELECT id, source_chat_id FROM beeper_conversations WHERE id = $1',+ [conversationId],+ );+ const row = found?.rows?.[0];+ if (!row) throw new ServerError('Conversation not found', { status: 404, code: 'NOT_FOUND' });++ const chat = await updateChat(row.source_chat_id, { [field]: value });+ const applied = typeof chat?.[field] === 'boolean' ? chat[field] : value;++ await query(+ `UPDATE beeper_conversations SET ${column} = $2, updated_at = NOW() WHERE id = $1`,+ [conversationId, applied],+ );+ console.log(`🫧 Beeper ${field}=${applied} on conversation ${conversationId}`);+ return getConversation(conversationId);+}++// ---------------------------------------------------------------------------+// Purge (#37) — the ONE destructive path over the mirror+// ---------------------------------------------------------------------------++/**+ * Delete one conversation's mirror: its messages, participants, attachment+ * rows AND the mirrored bytes those rows were holding.+ *+ * This is a PortOS-local purge and nothing else. It never touches Beeper: the+ * conversation stays exactly where it is on the source network, and the next+ * sweep will mirror it again unless the user also removes it there. That is+ * deliberate — "reclaim the disk this chat is using" and "delete this chat"+ * are different intentions, and only the first one is undoable.+ *+ * Order matters. `purgeConversationAttachments` runs FIRST, while the rows it+ * reference-checks against still exist: the store is content-addressed, so a+ * photo forwarded into three other chats must survive this one being purged.+ * The conversation row goes last and the FK cascade takes messages,+ * participants and attachment rows with it.+ */+export async function purgeConversation(conversationId) {+ const found = await query(+ 'SELECT id, title, account_id, source_chat_id FROM beeper_conversations WHERE id = $1',+ [conversationId],+ );+ const row = found?.rows?.[0];+ if (!row) throw new ServerError('Conversation not found', { status: 404, code: 'NOT_FOUND' });++ const bytes = await purgeConversationAttachments(conversationId);+ const messages = await query(+ 'SELECT COUNT(*)::int AS count FROM beeper_messages WHERE conversation_id = $1',+ [conversationId],+ );+ // The conversation row and its SYNC CURSOR go together, in one transaction.+ //+ // `beeper_sync_cursors` is keyed on Beeper's own `(account_id, chat_id)` and+ // carries an FK onto `beeper_accounts` alone, so the conversation's cascade+ // cannot reach it. Left behind, its `last_activity` watermark still says this+ // chat has not moved: `chatNeedsSweep` skips it, and once it does move,+ // `fetchNewMessages` walks forward from the surviving cursor and mirrors only+ // what arrives next. The purged history would never come back — the opposite+ // of what the typed confirmation promises the user before they confirm an+ // irreversible delete. Deleting the cursor is also the only thing that ever+ // removes one, so it stops orphan cursor rows accumulating.+ await withTransaction(async (client) => {+ await client.query('DELETE FROM beeper_conversations WHERE id = $1', [conversationId]);+ await client.query(+ 'DELETE FROM beeper_sync_cursors WHERE account_id = $1 AND chat_id = $2',+ [row.account_id, row.source_chat_id],+ );+ });+ console.log(`🫧 Beeper conversation mirror purged: ${conversationId} (${bytes.removedFiles} file(s), ${bytes.freedBytes} bytes, ${bytes.failedUnlinks} unlink failure(s))`);+ return {+ purged: true,+ conversationId,+ messagesRemoved: Number(messages?.rows?.[0]?.count) || 0,+ filesRemoved: bytes.removedFiles,+ bytesFreed: bytes.freedBytes,+ };+}++export const setConversationArchived = (conversationId, archived) =>+ setConversationFlag(conversationId, 'isArchived', 'is_archived', archived === true);++export const setConversationLowPriority = (conversationId, lowPriority) =>+ setConversationFlag(conversationId, 'isLowPriority', 'is_low_priority', lowPriority === true);diff --git a/server/services/beeperConversations.test.js b/server/services/beeperConversations.test.jsnew file mode 100644index 0000000000..6f96538957--- /dev/null+++ b/server/services/beeperConversations.test.js@@ -0,0 +1,668 @@+/**+ * Boundary tests for the Beeper chat-surface read model and the two wired rail+ * controls (#35). Postgres is mocked at `query()` and inspected as SQL text ++ * bind parameters, because the behaviour under test IS the query shape: which+ * filter reaches the WHERE clause, whether a keyset cursor is applied, and+ * whether the PATCH to Beeper happens before the mirror is touched.+ *+ * Every fixture value is invented (placeholder ids, `Example` names) per root+ * AGENTS.md Sensitive Data & Privacy — no value here came from a running+ * instance.+ */+import { describe, it, expect, vi, beforeEach } from 'vitest';++// `withTransaction` hands its callback a pg client; the fake records the+// statements the purge issues inside the transaction, which is exactly what the+// cursor-deletion contract below is about. `ensureSchema` is only needed below+// for the cross-module parity test, which imports the REAL `beeperTribe.js` to+// prove its shaper agrees with this file's own — `beeperTribe.js`'s+// `getParticipant` calls it before every query.+vi.mock('../lib/db.js', () => ({+ query: vi.fn(),+ withTransaction: vi.fn(),+ ensureSchema: vi.fn(async () => {}),+}));+vi.mock('./beeperClient.js', () => ({ updateChat: vi.fn() }));+// `beeperTribe.js` imports `./tribe.js` at the top level for its own+// touchpoint/roster logic, unrelated to the parity test below — stubbed so+// importing it here doesn't drag in tribe.js's own real (and much heavier)+// dependency chain.+vi.mock('./tribe.js', () => ({ listPeople: vi.fn(async () => []) }));++import { query, withTransaction } from '../lib/db.js';+import { updateChat } from './beeperClient.js';+import * as beeperTribe from './beeperTribe.js';+import {+ listConversations,+ getConversation,+ listMessages,+ listNetworks,+ markConversationSeen,+ purgeConversation,+ setConversationArchived,+ setConversationLowPriority,+ encodeCursor,+ decodeCursor,+} from './beeperConversations.js';++const CONV_A = '11111111-1111-4111-8111-111111111111';+const CONV_B = '22222222-2222-4222-8222-222222222222';++const conversationRow = (overrides = {}) => ({+ id: CONV_A,+ account_id: 'acct-example-1',+ network: 'examplenet',+ source_chat_id: 'chat-example-1',+ title: 'Example Conversation',+ type: 'single',+ is_group: false,+ is_pinned: false,+ is_archived: false,+ is_low_priority: false,+ is_muted: false,+ last_activity: '2026-09-01T10:00:00.000Z',+ created_at: '2026-08-01T10:00:00.000Z',+ unread_count: 2,+ // LOCAL "seen in PortOS" watermark (#83) — `null` by default (never opened+ // in PortOS), so the default fixture reads as unread exactly like it did+ // before the column existed.+ seen_at: null,+ ordering_ts: '2026-09-01T10:00:00.000Z',+ preview_id: null,+ ...overrides,+});++const flat = (sql) => sql.replace(/\s+/g, ' ').trim();+const callFor = (fragment) => vi.mocked(query).mock.calls.find(([sql]) => flat(sql).includes(fragment));++beforeEach(() => vi.clearAllMocks());++describe('listConversations — filters are tri-state by omission', () => {+ it('applies no archived/low-priority predicate when the caller omits them', async () => {+ vi.mocked(query).mockResolvedValue({ rows: [] });+ await listConversations({});+ const [sql, params] = vi.mocked(query).mock.calls[0];+ expect(flat(sql)).not.toContain('is_archived =');+ expect(flat(sql)).not.toContain('is_low_priority =');+ // The only bind is the page-size probe (limit + 1).+ expect(params).toEqual([51]);+ });++ it('applies `archived: false` as a real predicate, not as "no filter"', async () => {+ vi.mocked(query).mockResolvedValue({ rows: [] });+ await listConversations({ archived: false, lowPriority: false });+ const [sql, params] = vi.mocked(query).mock.calls[0];+ expect(flat(sql)).toContain('c.is_archived = $1');+ expect(flat(sql)).toContain('c.is_low_priority = $2');+ expect(params).toEqual([false, false, 51]);+ });++ it('scopes to one network and to unread rows, honouring the local seen watermark (#83)', async () => {+ vi.mocked(query).mockResolvedValue({ rows: [] });+ await listConversations({ network: 'examplenet', unreadOnly: true });+ const [sql, params] = vi.mocked(query).mock.calls[0];+ expect(flat(sql)).toContain('c.network = $1');+ // A conversation Beeper still reports unread does not count as+ // `unreadOnly` once its local `seen_at` catches up to its own activity.+ expect(flat(sql)).toContain(+ 'c.unread_count > 0 AND (c.seen_at IS NULL OR c.seen_at < COALESCE(c.last_activity, c.created_at))',+ );+ expect(params).toEqual(['examplenet', 51]);+ });+});++describe('listConversations — keyset pagination', () => {+ it('returns a nextCursor only when a further page exists, and resumes from it', async () => {+ const rows = Array.from({ length: 3 }, (_, i) => conversationRow({+ id: `3333333${i}-3333-4333-8333-333333333333`,+ last_activity: `2026-09-0${i + 1}T10:00:00.000Z`,+ ordering_ts: `2026-09-0${i + 1}T10:00:00.000Z`,+ }));+ // Page query, then the batched preview query, then attachParticipants —+ // three calls per listConversations() invocation since the preview LATERAL+ // was split out of the page query (audit cluster 06).+ vi.mocked(query)+ .mockResolvedValueOnce({ rows })+ .mockResolvedValueOnce({ rows: [] })+ .mockResolvedValueOnce({ rows: [] });++ const page = await listConversations({ limit: 2 });+ expect(page.conversations).toHaveLength(2);+ expect(page.nextCursor).toBe(encodeCursor(rows[1].ordering_ts, rows[1].id));++ vi.mocked(query).mockResolvedValue({ rows: [] });+ await listConversations({ limit: 2, cursor: page.nextCursor });+ const [sql, params] = vi.mocked(query).mock.calls[3];+ // #81: the epoch sentinel, not `c.created_at` — see the dedicated+ // ordering describe block below for why.+ expect(flat(sql)).toContain("(COALESCE(c.last_activity, 'epoch'::timestamptz), c.id) <");+ expect(params[0]).toBe(rows[1].ordering_ts);+ expect(params[1]).toBe(rows[1].id);+ });++ it('has no next page when the result is short', async () => {+ // Page query, then the batched preview query, then attachParticipants.+ vi.mocked(query)+ .mockResolvedValueOnce({ rows: [conversationRow()] })+ .mockResolvedValueOnce({ rows: [] })+ .mockResolvedValueOnce({ rows: [] });+ const page = await listConversations({ limit: 2 });+ expect(page.nextCursor).toBeNull();+ });++ it('restarts the page on an unparseable cursor instead of throwing', async () => {+ vi.mocked(query).mockResolvedValue({ rows: [] });+ await listConversations({ cursor: 'not-a-cursor' });+ const [sql] = vi.mocked(query).mock.calls[0];+ expect(flat(sql)).not.toContain('c.id) <');+ expect(decodeCursor('not-a-cursor')).toBeNull();+ });++ // A hand-edited (or truncated) cursor can decode cleanly — valid base64url,+ // a real timestamp, a non-empty id half — while that id half is not a uuid.+ // `c.id` is bound as `::uuid`, so this used to reach Postgres and 500 on the+ // cast, contradicting decodeCursor's own contract of returning null for+ // anything malformed. This is a shape a hand rolled cursor can produce even+ // though `encodeCursor` itself never emits one — no PortOS conversation id+ // is ever a non-uuid string.+ it('restarts the page rather than 500ing on a well-formed cursor whose id is not a uuid', async () => {+ const garbled = encodeCursor('2026-09-01T10:00:00.000Z', 'not-a-uuid');+ vi.mocked(query).mockResolvedValue({ rows: [] });++ await expect(listConversations({ cursor: garbled })).resolves.toMatchObject({ conversations: [] });+ const [sql] = vi.mocked(query).mock.calls[0];+ expect(flat(sql)).not.toContain('c.id) <');+ // decodeCursor is the shape-check boundary: with the uuid pattern the+ // conversation route applies, this decodes to null just like a garbled one.+ expect(decodeCursor(garbled, { idPattern: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i })).toBeNull();+ // Without a pattern (the shape `listMessages` uses — Beeper message ids are+ // arbitrary bridge strings, never uuids) the same cursor still decodes.+ expect(decodeCursor(garbled)).toEqual({ ts: '2026-09-01T10:00:00.000Z', id: 'not-a-uuid' });+ });+});++// #81: `COALESCE(c.last_activity, c.created_at)` fell back to the mirror+// row's mint time for a chat with no real Beeper activity, not to "this chat+// has no activity" — so a batch of chats swept (and left activity-less) in+// the same pass shared a recent `created_at` and sorted at the TOP of the+// Inbox, above populated threads with older real activity. This is what the+// read-only live-instance investigation on fork issue #81 (counts only)+// found driving the reported symptom for the observed population — the+// retry fix does not touch chats Beeper itself never reports activity for.+describe('listConversations — activity-less chats sort last, not by mint time', () => {+ it('sorts on the epoch sentinel, never on created_at, in the page query and ORDER BY', async () => {+ vi.mocked(query).mockResolvedValue({ rows: [] });+ await listConversations({});+ const [sql] = vi.mocked(query).mock.calls[0];+ const flatSql = flat(sql);+ expect(flatSql).toContain("COALESCE(c.last_activity, 'epoch'::timestamptz) AS ordering_ts");+ expect(flatSql).toContain("ORDER BY COALESCE(c.last_activity, 'epoch'::timestamptz) DESC, c.id DESC");+ expect(flatSql).not.toContain('c.created_at');+ });++ it('sorts on the same epoch sentinel in the keyset predicate', async () => {+ vi.mocked(query).mockResolvedValue({ rows: [] });+ await listConversations({ cursor: encodeCursor('2026-09-01T10:00:00.000Z', CONV_A) });+ const [sql] = vi.mocked(query).mock.calls[0];+ expect(flat(sql)).toContain("(COALESCE(c.last_activity, 'epoch'::timestamptz), c.id) <");+ });+});++describe('listConversations — row shaping', () => {+ it('caps the participant subset and says so, because a Beeper roster is always a possible subset', async () => {+ const participants = Array.from({ length: 10 }, (_, i) => ({+ conversation_id: CONV_A,+ source_user_id: `user-${i}`,+ display_name: `Example Person ${i}`,+ handle: `+15550100${i}`,+ tribe_person_id: null,+ observed_via: 'participant-list',+ tribe_person_name: null,+ }));+ vi.mocked(query)+ .mockResolvedValueOnce({ rows: [conversationRow()] }) // page+ .mockResolvedValueOnce({ rows: [] }) // preview+ .mockResolvedValueOnce({ rows: participants }); // participants++ const { conversations } = await listConversations({});+ expect(conversations[0].participants).toHaveLength(8);+ expect(conversations[0].hasMoreParticipants).toBe(true);+ expect(conversations[0].participants[0]).toMatchObject({ tribePersonId: null, observedVia: 'participant-list' });+ });++ it('withholds the body of a tombstoned preview while keeping the row', async () => {+ // The preview now comes back from a SEPARATE, page-scoped query — keyed+ // on `conversation_id`, matched to the page row by id (audit cluster 06).+ vi.mocked(query)+ .mockResolvedValueOnce({ rows: [conversationRow()] }) // page+ .mockResolvedValueOnce({+ rows: [{+ conversation_id: CONV_A,+ preview_id: 'msg-example-1',+ preview_body: 'placeholder body that must not ship',+ preview_sender_id: 'user-1',+ preview_sent_at: '2026-09-01T09:59:00.000Z',+ preview_unsent_at: '2026-09-01T10:00:00.000Z',+ }],+ }) // preview+ .mockResolvedValueOnce({ rows: [] }); // participants++ const { conversations } = await listConversations({});+ expect(conversations[0].lastMessage).toMatchObject({ id: 'msg-example-1', body: '', isUnsent: true });+ });++ it('carries the preview\'s direction, so the row can show its leading state chip', async () => {+ vi.mocked(query)+ .mockResolvedValueOnce({ rows: [conversationRow()] }) // page+ .mockResolvedValueOnce({+ rows: [{+ conversation_id: CONV_A,+ preview_id: 'msg-example-1',+ preview_body: 'placeholder body',+ preview_sender_id: 'user-me',+ preview_sent_at: '2026-09-01T09:59:00.000Z',+ preview_is_sender: true,+ }],+ }) // preview+ .mockResolvedValueOnce({ rows: [] }); // participants+ const { conversations } = await listConversations({});+ expect(conversations[0].lastMessage.isSender).toBe(true);+ });++ it('reports a conversation with no mirrored message as lastMessage: null, not as an empty string', async () => {+ vi.mocked(query)+ .mockResolvedValueOnce({ rows: [conversationRow()] }) // page+ .mockResolvedValueOnce({ rows: [] }) // preview+ .mockResolvedValueOnce({ rows: [] }); // participants+ const { conversations } = await listConversations({});+ expect(conversations[0].lastMessage).toBeNull();+ });++ // #81: the client's row preview falls back to "Syncing…" for a recent+ // `lastActivity` with no mirrored message, and to the honest "No messages+ // mirrored yet" otherwise (`BeeperChatSurface.jsx`'s `isRecentActivity`).+ // That fallback has nothing else to key on, so `lastActivity` must keep+ // passing through untouched — not coerced to the conversation's+ // `created_at`, not dropped — even while `lastMessage` stays `null`.+ it('still reports the conversation-level lastActivity alongside a null lastMessage, so the client can tell "still syncing" from "no history"', async () => {+ vi.mocked(query)+ .mockResolvedValueOnce({ rows: [conversationRow({ last_activity: '2026-09-02T09:00:00.000Z' })] }) // page+ .mockResolvedValueOnce({ rows: [] }) // preview+ .mockResolvedValueOnce({ rows: [] }); // participants+ const { conversations } = await listConversations({});+ expect(conversations[0]).toMatchObject({ lastMessage: null, lastActivity: '2026-09-02T09:00:00.000Z' });+ });++ // The LOCAL "seen in PortOS" watermark (#83) — `shapeConversation`'s own+ // logic, exercised through `listConversations` since the shaper is not+ // itself exported. Beeper's mirrored `unread_count` is deliberately left+ // non-zero on every row below: the watermark hides the badge at the READ+ // boundary, never by mutating what the sweep wrote.+ describe('the local "seen" watermark hides/shows the badge (#83)', () => {+ it('hides the badge when seen_at is at or after the conversation\'s last activity', async () => {+ vi.mocked(query)+ .mockResolvedValueOnce({+ rows: [conversationRow({ unread_count: 5, last_activity: '2026-09-01T10:00:00.000Z', seen_at: '2026-09-01T10:00:00.000Z' })],+ })+ .mockResolvedValueOnce({ rows: [] })+ .mockResolvedValueOnce({ rows: [] });+ const { conversations } = await listConversations({});+ expect(conversations[0].unreadCount).toBe(0);+ });++ it('shows the badge again once new activity lands after the watermark', async () => {+ vi.mocked(query)+ .mockResolvedValueOnce({+ rows: [conversationRow({ unread_count: 3, last_activity: '2026-09-01T12:00:00.000Z', seen_at: '2026-09-01T10:00:00.000Z' })],+ })+ .mockResolvedValueOnce({ rows: [] })+ .mockResolvedValueOnce({ rows: [] });+ const { conversations } = await listConversations({});+ expect(conversations[0].unreadCount).toBe(3);+ });++ it('reads a conversation never opened in PortOS (seen_at NULL) as whatever Beeper says', async () => {+ vi.mocked(query)+ .mockResolvedValueOnce({ rows: [conversationRow({ unread_count: 7, seen_at: null })] })+ .mockResolvedValueOnce({ rows: [] })+ .mockResolvedValueOnce({ rows: [] });+ const { conversations } = await listConversations({});+ expect(conversations[0].unreadCount).toBe(7);+ });+ });+});++describe('getConversation', () => {+ it('returns null for an unknown id so a stale deep link degrades to not-found', async () => {+ vi.mocked(query).mockResolvedValue({ rows: [] });+ expect(await getConversation(CONV_B)).toBeNull();+ });++ it('returns the full participant set with no cap', async () => {+ const participants = Array.from({ length: 12 }, (_, i) => ({+ conversation_id: CONV_A,+ source_user_id: `user-${i}`,+ display_name: `Example Person ${i}`,+ handle: '',+ tribe_person_id: null,+ observed_via: 'message-sender',+ tribe_person_name: null,+ }));+ vi.mocked(query)+ .mockResolvedValueOnce({ rows: [conversationRow()] })+ .mockResolvedValueOnce({ rows: participants });+ const conversation = await getConversation(CONV_A);+ expect(conversation.participants).toHaveLength(12);+ expect(conversation.hasMoreParticipants).toBe(false);+ });++ it('reads a soft-deleted Tribe link as fully unlinked — null id, no name, so the re-link control returns', async () => {+ vi.mocked(query)+ .mockResolvedValueOnce({ rows: [conversationRow()] })+ .mockResolvedValueOnce({+ rows: [{+ conversation_id: CONV_A,+ source_user_id: 'user-1',+ display_name: 'Sam Example',+ handle: '+15550100',+ tribe_person_id: 'deleted-person-1',+ observed_via: 'participant-list',+ tribe_person_name: 'Deleted Person',+ tribe_person_deleted: true,+ }],+ });+ const conversation = await getConversation(CONV_A);+ expect(conversation.participants[0]).toMatchObject({ tribePersonId: null, tribePersonName: null });+ });+});++// The audit's soft-deleted-link finding: `beeperConversations.js`'s own+// participant shaper used to leak `tribePersonId`/`tribePersonName` for a+// soft-deleted Tribe person while `beeperTribe.js`'s shaper already nulled the+// cached id. Both now call the SAME extracted predicate+// (`resolveLinkedPersonId` in `lib/tribeMatch.js`), and this test drives BOTH+// real code paths off the identical underlying row so a future edit that+// re-duplicates the logic in only one of them fails here first.+describe('parity: a soft-deleted Tribe link reads as unlinked from every shaper', () => {+ const DELETED_PERSON = 'deleted-person-1';++ const softDeletedConversationParticipantsRow = {+ conversation_id: CONV_A,+ source_user_id: 'user-1',+ display_name: 'Sam Example',+ handle: '+15550100',+ tribe_person_id: DELETED_PERSON,+ observed_via: 'participant-list',+ tribe_person_name: 'Deleted Person',+ tribe_person_deleted: true,+ };++ const softDeletedTribeParticipantRow = {+ conversation_id: CONV_A,+ source_user_id: 'user-1',+ display_name: 'Sam Example',+ handle: '+15550100',+ tribe_person_id: DELETED_PERSON,+ observed_via: 'participant-list',+ network: 'examplenet',+ tribe_person_deleted: true,+ created_at: '2026-09-01T10:00:00.000Z',+ updated_at: '2026-09-01T10:00:00.000Z',+ };++ it('agrees with beeperTribe.getParticipant: both null tribePersonId (and this file also nulls tribePersonName)', async () => {+ vi.mocked(query).mockImplementation(async (sql) => {+ const text = flat(sql);+ // beeperTribe.js's own participant shaper — the "list/preview path"+ // the audit found already correct.+ if (text.startsWith('SELECT p.*, c.network')) {+ return { rows: [softDeletedTribeParticipantRow] };+ }+ // This file's conversation/list participant shaper — the audit's+ // "conversation payload shaper" finding.+ if (text.includes('p.observed_via, tp.name AS tribe_person_name')) {+ return { rows: [softDeletedConversationParticipantsRow] };+ }+ if (text.startsWith('SELECT c.*') && text.includes('WHERE c.id = $1')) {+ return { rows: [conversationRow()] };+ }+ return { rows: [] };+ });++ const conversation = await getConversation(CONV_A);+ expect(conversation.participants[0]).toMatchObject({ tribePersonId: null, tribePersonName: null });++ const participant = await beeperTribe.getParticipant(CONV_A, 'user-1');+ expect(participant.tribePersonId).toBeNull();+ // The row's own network identity survives — re-linking still targets the+ // same participant rather than a dead end.+ expect(participant.sourceUserId).toBe('user-1');+ expect(participant.handle).toBe('+15550100');+ });+});++describe('listMessages', () => {+ it('pages newest-first with a keyset cursor and attaches attachment references', async () => {+ const rows = [+ { id: 'm2', conversation_id: CONV_A, sender_id: 'user-1', body: 'second', sent_at: '2026-09-01T10:00:00.000Z', created_at: '2026-09-01T10:00:00.000Z', ordering_ts: '2026-09-01T10:00:00.000Z' },+ { id: 'm1', conversation_id: CONV_A, sender_id: 'user-2', body: 'first', sent_at: '2026-09-01T09:00:00.000Z', created_at: '2026-09-01T09:00:00.000Z', ordering_ts: '2026-09-01T09:00:00.000Z' },+ ];+ vi.mocked(query)+ .mockResolvedValueOnce({ rows })+ .mockResolvedValueOnce({ rows: [{ message_id: 'm2', idx: 0, mxc_id: 'mxc://example/abc', mime_type: 'image/png', byte_length: '1024', file_name: 'example.png', width: 10, height: 10 }] });++ const page = await listMessages(CONV_A, { limit: 5 });+ const [sql] = vi.mocked(query).mock.calls[0];+ expect(flat(sql)).toContain('ORDER BY COALESCE(m.sent_at, m.created_at) DESC, m.id DESC');+ expect(page.messages.map((m) => m.id)).toEqual(['m2', 'm1']);+ // Shaped by `beeperAttachments.shapeAttachment`, so the thread sees the+ // mirror state (`stored` / `overCap` / `unavailable` / `keep`) on the same+ // payload the attachment routes return, not a second metadata-only shape.+ expect(page.messages[0].attachments).toMatchObject([+ {+ messageId: 'm2', idx: 0, mxcId: 'mxc://example/abc', mimeType: 'image/png',+ byteLength: 1024, fileName: 'example.png', width: 10, height: 10,+ stored: false, overCap: false, unavailable: false, keep: false,+ },+ ]);+ expect(page.nextCursor).toBeNull();+ });++ it('withholds a tombstoned body but keeps the message and its unsentAt', async () => {+ vi.mocked(query).mockResolvedValueOnce({+ rows: [{ id: 'm9', conversation_id: CONV_A, sender_id: 'user-1', body: 'placeholder body', sent_at: '2026-09-01T10:00:00.000Z', created_at: '2026-09-01T10:00:00.000Z', unsent_at: '2026-09-01T11:00:00.000Z', ordering_ts: '2026-09-01T10:00:00.000Z' }],+ }).mockResolvedValueOnce({ rows: [] });+ const page = await listMessages(CONV_A, {});+ expect(page.messages[0]).toMatchObject({ id: 'm9', body: '', unsentAt: '2026-09-01T11:00:00.000Z' });+ });++ it('carries the mirrored direction through, and reads a missing column as inbound', async () => {+ vi.mocked(query).mockResolvedValueOnce({+ rows: [+ { id: 'm2', conversation_id: CONV_A, sender_id: 'user-me', body: 'placeholder', sent_at: '2026-09-01T10:00:00.000Z', created_at: '2026-09-01T10:00:00.000Z', is_sender: true, ordering_ts: '2026-09-01T10:00:00.000Z' },+ { id: 'm1', conversation_id: CONV_A, sender_id: 'user-1', body: 'placeholder', sent_at: '2026-09-01T09:00:00.000Z', created_at: '2026-09-01T09:00:00.000Z', ordering_ts: '2026-09-01T09:00:00.000Z' },+ ],+ }).mockResolvedValueOnce({ rows: [] });+ const page = await listMessages(CONV_A, {});+ expect(page.messages.map((m) => m.isSender)).toEqual([true, false]);+ });++ it('answers an empty page rather than an error — an empty thread is often correct', async () => {+ vi.mocked(query).mockResolvedValueOnce({ rows: [] });+ await expect(listMessages(CONV_A, {})).resolves.toEqual({ messages: [], nextCursor: null });+ });+});++describe('listNetworks', () => {+ it('derives the rail scopes from the mirror and excludes archived rows from unread', async () => {+ vi.mocked(query).mockResolvedValue({+ rows: [{ network: 'examplenet', conversation_count: 3, unread_count: 4, unread_conversations: 2, account_ids: ['acct-example-1'], last_activity: '2026-09-01T10:00:00.000Z' }],+ });+ const networks = await listNetworks();+ const [sql] = vi.mocked(query).mock.calls[0];+ expect(flat(sql)).toContain('FILTER (WHERE c.is_archived = FALSE AND (c.seen_at IS NULL OR c.seen_at < COALESCE(c.last_activity, c.created_at)))');+ expect(networks).toEqual([{+ network: 'examplenet',+ conversationCount: 3,+ unreadCount: 4,+ unreadConversations: 2,+ accountIds: ['acct-example-1'],+ lastActivity: '2026-09-01T10:00:00.000Z',+ }]);+ });++ // #81: a network holding only activity-less chats used to report+ // `lastActivity` as "just now" (the fallback to created_at), not honestly+ // having none. Unlike listConversations' keyset walk, this is a plain MAX+ // over the group — MAX ignores NULLs and yields NULL when every row is+ // NULL, which is already the honest value, so no epoch sentinel is needed.+ it('aggregates the last-activity as a plain MAX, never falling back to created_at or an epoch sentinel', async () => {+ vi.mocked(query).mockResolvedValue({ rows: [] });+ await listNetworks();+ const [sql] = vi.mocked(query).mock.calls[0];+ const flatSql = flat(sql);+ expect(flatSql).toContain('MAX(c.last_activity) AS last_activity');+ // Narrowed to the `last_activity` aggregate expression itself (#83): the+ // seen watermark's `UNSEEN_SQL` guard legitimately references+ // `c.created_at` elsewhere in this same query, as the activity floor for+ // the two UNREAD aggregates — a blanket "the whole SQL never mentions+ // created_at" no longer holds, so this checks only the MAX(...) that+ // produces `last_activity`.+ const lastActivityExpr = /MAX\(([^)]*)\) AS last_activity/.exec(flatSql)?.[1];+ expect(lastActivityExpr).toBe('c.last_activity');+ expect(lastActivityExpr).not.toContain('COALESCE');+ expect(lastActivityExpr).not.toContain('epoch');+ });++ // The LOCAL "seen" watermark (#83) must gate BOTH aggregates the rail reads+ // — the summed `unread_count` and the `unread_conversations` count — not+ // just one of them, or a network chip and its own conversation count would+ // disagree about whether a just-opened thread is still unread.+ it('gates both the summed unread_count and the unread_conversations count on the watermark', async () => {+ vi.mocked(query).mockResolvedValue({ rows: [] });+ await listNetworks();+ const [sql] = vi.mocked(query).mock.calls[0];+ const text = flat(sql);+ expect(text).toContain(+ 'SUM(c.unread_count) FILTER (WHERE c.is_archived = FALSE AND (c.seen_at IS NULL OR c.seen_at < COALESCE(c.last_activity, c.created_at)))',+ );+ expect(text).toContain(+ 'COUNT(*) FILTER (WHERE c.unread_count > 0 AND c.is_archived = FALSE AND (c.seen_at IS NULL OR c.seen_at < COALESCE(c.last_activity, c.created_at)))',+ );+ });+});++describe('the two wired rail controls', () => {+ it('PATCHes Beeper BEFORE the mirror, and mirrors the value Beeper actually returned', async () => {+ vi.mocked(query)+ .mockResolvedValueOnce({ rows: [{ id: CONV_A, source_chat_id: 'chat-example-1' }] })+ .mockResolvedValueOnce({ rows: [] })+ .mockResolvedValueOnce({ rows: [conversationRow({ is_archived: true })] })+ .mockResolvedValueOnce({ rows: [] });+ vi.mocked(updateChat).mockResolvedValue({ id: 'chat-example-1', isArchived: true });++ const conversation = await setConversationArchived(CONV_A, true);+ expect(updateChat).toHaveBeenCalledWith('chat-example-1', { isArchived: true });+ const update = callFor('UPDATE beeper_conversations SET is_archived');+ expect(update[1]).toEqual([CONV_A, true]);+ expect(conversation.isArchived).toBe(true);+ });++ it('leaves the mirror untouched when the PATCH fails — no optimistic local state', async () => {+ vi.mocked(query).mockResolvedValueOnce({ rows: [{ id: CONV_A, source_chat_id: 'chat-example-1' }] });+ vi.mocked(updateChat).mockRejectedValue(Object.assign(new Error('Beeper request failed'), { code: 'NETWORK_ERROR' }));++ await expect(setConversationArchived(CONV_A, true)).rejects.toMatchObject({ code: 'NETWORK_ERROR' });+ expect(updateChat).toHaveBeenCalledTimes(1);+ expect(callFor('UPDATE beeper_conversations')).toBeUndefined();+ });++ it('falls back to the requested value when the bridge answers without the flag, rather than blanking it', async () => {+ vi.mocked(query)+ .mockResolvedValueOnce({ rows: [{ id: CONV_A, source_chat_id: 'chat-example-1' }] })+ .mockResolvedValueOnce({ rows: [] })+ .mockResolvedValueOnce({ rows: [conversationRow({ is_low_priority: true })] })+ .mockResolvedValueOnce({ rows: [] });+ vi.mocked(updateChat).mockResolvedValue({ id: 'chat-example-1' });++ await setConversationLowPriority(CONV_A, true);+ expect(callFor('UPDATE beeper_conversations SET is_low_priority')[1]).toEqual([CONV_A, true]);+ });++ it('404s on an unknown conversation without calling Beeper at all', async () => {+ vi.mocked(query).mockResolvedValueOnce({ rows: [] });+ await expect(setConversationArchived(CONV_B, true)).rejects.toMatchObject({ status: 404 });+ expect(updateChat).not.toHaveBeenCalled();+ });+});++// `markConversationSeen` (#83) — the LOCAL "seen in PortOS" watermark write.+// Unlike the two wired rail controls above, this never calls Beeper at all:+// there is no PATCH to assert an order against, only that an unknown id 404s+// before any UPDATE, and that a known one is stamped and re-read.+describe('markConversationSeen — the local watermark write, never a Beeper call', () => {+ it('stamps seen_at and returns the freshly-read conversation', async () => {+ vi.mocked(query)+ .mockResolvedValueOnce({ rows: [{ id: CONV_A }] }) // existence check+ .mockResolvedValueOnce({ rows: [] }) // the UPDATE+ .mockResolvedValueOnce({ rows: [conversationRow({ seen_at: '2026-09-01T10:00:00.000Z' })] }) // getConversation+ .mockResolvedValueOnce({ rows: [] }); // participants++ const conversation = await markConversationSeen(CONV_A);+ const update = callFor('UPDATE beeper_conversations SET seen_at = NOW()');+ expect(update[1]).toEqual([CONV_A]);+ expect(conversation.id).toBe(CONV_A);+ expect(updateChat).not.toHaveBeenCalled();+ });++ it('404s on an unknown conversation without writing anything', async () => {+ vi.mocked(query).mockResolvedValueOnce({ rows: [] });+ await expect(markConversationSeen(CONV_B)).rejects.toMatchObject({ status: 404, code: 'NOT_FOUND' });+ expect(callFor('UPDATE beeper_conversations')).toBeUndefined();+ expect(updateChat).not.toHaveBeenCalled();+ });+});++// The purge is the one destructive path over the mirror, and the sentence the+// user reads before confirming it promises the chat comes back on the next+// sync. That promise is only true if the sync cursor goes with the rows.+describe('purgeConversation', () => {+ const purgeQueries = () => vi.mocked(query).mock.calls.map(([sql]) => flat(sql));++ const stubPurgeReads = (row) => {+ vi.mocked(query).mockImplementation(async (sql) => {+ const text = flat(sql);+ if (text.includes('SELECT id, title, account_id, source_chat_id')) return { rows: [row] };+ if (text.includes('COUNT(*)::int AS count FROM beeper_messages')) return { rows: [{ count: 7 }] };+ return { rows: [] };+ });+ };++ it('deletes the conversation AND its sync cursor, in one transaction, keyed on Beeper\'s own ids', async () => {+ stubPurgeReads({ id: CONV_A, title: 'Example Conversation', account_id: 'acct-example-1', source_chat_id: 'chat-example-1' });+ const statements = [];+ vi.mocked(withTransaction).mockImplementation(async (fn) => fn({+ query: async (sql, params) => { statements.push([flat(sql), params]); return { rows: [] }; },+ }));++ const result = await purgeConversation(CONV_A);++ expect(statements.map(([sql]) => sql)).toEqual([+ 'DELETE FROM beeper_conversations WHERE id = $1',+ 'DELETE FROM beeper_sync_cursors WHERE account_id = $1 AND chat_id = $2',+ ]);+ // The cursor is keyed on the ACCOUNT id and the SOURCE chat id, never the+ // synthetic conversation uuid — its FK reaches beeper_accounts only, so the+ // conversation cascade cannot take it.+ expect(statements[1][1]).toEqual(['acct-example-1', 'chat-example-1']);+ expect(result).toMatchObject({ purged: true, conversationId: CONV_A, messagesRemoved: 7 });+ // Never a DELETE outside the transaction.+ expect(purgeQueries().some((sql) => sql.startsWith('DELETE'))).toBe(false);+ });++ it('404s an unknown id without deleting anything', async () => {+ vi.mocked(query).mockResolvedValue({ rows: [] });+ await expect(purgeConversation(CONV_B)).rejects.toMatchObject({ status: 404, code: 'NOT_FOUND' });+ expect(vi.mocked(withTransaction)).not.toHaveBeenCalled();+ });+});diff --git a/server/services/beeperCredentials.js b/server/services/beeperCredentials.jsnew file mode 100644index 0000000000..f319c23d0d--- /dev/null+++ b/server/services/beeperCredentials.js@@ -0,0 +1,149 @@+/**+ * Vaulted Beeper credential store (fork issue #31, decision 6 on #11).+ *+ * The Beeper access token grants read AND send across every network the user+ * has bridged, and `DELETE /v1/chats/…/messages/…` defaults to unsending for+ * everyone — so it does NOT follow the `civitai.apiKey` plaintext-settings+ * precedent that root AGENTS.md's free-service carve-out covers. It follows the+ * Stacker News contract instead: AES-256-GCM ciphertext in Postgres via+ * `lib/vaultCrypto.js`, decrypted only at the moment of use, exposed to any+ * client as a boolean plus an expiry and never as a value.+ *+ * Honest limit, stated rather than overclaimed: `ensureVaultKey()` writes the+ * key to the install-root `.env`, on the same disk as the ciphertext. This+ * bounds DB dumps, backup snapshots (`data/settings.json` rides into every+ * one; the vault key does not) and accidental echoes. It does not defend+ * against an attacker who already has filesystem access.+ *+ * ONE row, `id = 'default'`: PortOS models one Beeper account per install (#1+ * charting decision 8). Reads are honest about the difference between "no+ * credential" (`null`) and "a credential that cannot be read" — a row whose+ * ciphertext fails to decrypt throws out of `decryptValue` rather than+ * degrading to "not configured", per #11 decision 8 ("a local read that THROWS+ * on a malformed store rather than returning false"). Silently reporting+ * not-configured would send a connected install back through the connect flow+ * and mint a second credential over a vault key that merely went missing.+ */++import { query } from '../lib/db.js';+import { decryptValue, encryptValue, ensureVaultKey } from '../lib/vaultCrypto.js';+import { getSettings } from './settings.js';++const CREDENTIAL_ID = 'default';++/** How the stored token was obtained. Mirrors the `source` CHECK in the DDL. */+export const BEEPER_TOKEN_SOURCES = ['oauth', 'pasted'];++/** The legacy plaintext call site (#29). Read-only — see `resolveBeeperToken`. */+const LEGACY_TOKEN_SOURCE = 'legacy-settings';++function normalizeToken(value) {+ return typeof value === 'string' && value.trim() ? value.trim() : null;+}++function toIsoOrNull(value) {+ if (!value) return null;+ const date = value instanceof Date ? value : new Date(value);+ return Number.isNaN(date.getTime()) ? null : date.toISOString();+}++/**+ * The stored credential, decrypted — `{ token, tokenExpiresAt, tokenScopes,+ * tokenSource, clientId }` — or `null` when this install has never connected.+ *+ * Every caller of this is server-side. The token it returns must never be+ * logged, echoed into an error message, or serialized into a response.+ */+export async function readBeeperCredential() {+ const result = await query(+ `SELECT token_enc, token_expires_at, scopes, source, client_id+ FROM beeper_credentials WHERE id = $1`,+ [CREDENTIAL_ID],+ );+ const row = result?.rows?.[0];+ if (!row) return null;+ return {+ // Deliberately unguarded: a corrupt row or a rotated vault key throws here+ // (see the module header) instead of masquerading as "no token".+ token: decryptValue(row.token_enc),+ tokenExpiresAt: toIsoOrNull(row.token_expires_at),+ tokenScopes: row.scopes ? String(row.scopes).split(/\s+/).filter(Boolean) : [],+ tokenSource: row.source,+ clientId: row.client_id || '',+ };+}++/**+ * Encrypt and store the ONE credential, replacing whatever was there.+ *+ * `expiresAt: null` is a real value, not an absence — it is the no-expiry token+ * only Beeper's own UI can mint (#11 decision 3), and it must overwrite an+ * earlier OAuth expiry rather than inheriting it.+ */+export async function saveBeeperCredential({ token, expiresAt = null, scopes = [], source, clientId = '' }) {+ const value = normalizeToken(token);+ if (!value) throw new Error('saveBeeperCredential requires a non-empty token');+ if (!BEEPER_TOKEN_SOURCES.includes(source)) {+ throw new Error(`saveBeeperCredential requires source one of ${BEEPER_TOKEN_SOURCES.join('|')}`);+ }+ await ensureVaultKey();+ const scopeText = Array.isArray(scopes) ? scopes.join(' ') : String(scopes || '');+ await query(+ `INSERT INTO beeper_credentials (id, token_enc, token_expires_at, scopes, source, client_id)+ VALUES ($1, $2, $3, $4, $5, $6)+ ON CONFLICT (id) DO UPDATE SET+ token_enc = EXCLUDED.token_enc,+ token_expires_at = EXCLUDED.token_expires_at,+ scopes = EXCLUDED.scopes,+ source = EXCLUDED.source,+ client_id = EXCLUDED.client_id,+ updated_at = NOW()`,+ [CREDENTIAL_ID, encryptValue(value), toIsoOrNull(expiresAt), scopeText, source, clientId || ''],+ );+ // Provenance and expiry only — never the value, never a masked prefix of it.+ console.log(`🔐 Beeper credential stored (source=${source}, expires=${toIsoOrNull(expiresAt) || 'never'})`);+ return { tokenConfigured: true, tokenExpiresAt: toIsoOrNull(expiresAt), tokenSource: source };+}++/** Forget the stored credential. Idempotent — reports whether a row existed. */+export async function deleteBeeperCredential() {+ const result = await query('DELETE FROM beeper_credentials WHERE id = $1', [CREDENTIAL_ID]);+ const deleted = (result?.rowCount ?? 0) > 0;+ if (deleted) console.log('🔌 Beeper credential deleted (disconnected)');+ return { deleted, tokenConfigured: false, tokenExpiresAt: null, tokenSource: null };+}++/**+ * The ONE token resolver `beeperClient` calls. Vault first; the legacy+ * plaintext `settings.beeper.token` (#29's original call site) second, and for+ * READS ONLY — nothing in PortOS writes that field any more, and the settings+ * route strips it from every response while carrying a hand-written one over+ * an unrelated save. An install that hand-edited a token into `settings.json`+ * before #31 keeps working; a fresh connect lands in the vault instead.+ *+ * Returns `{ token, tokenExpiresAt, tokenScopes, tokenSource }`, or `null`+ * when neither store holds one — distinct from a throw, which means the+ * vault itself is unreadable and the caller must not treat it as "not+ * connected". `tokenScopes` is always an array, `[]` when unknown — a pasted+ * token (#78) and the legacy plaintext path both have nothing to report.+ */+export async function resolveBeeperToken() {+ const vaulted = await readBeeperCredential();+ if (vaulted?.token) {+ return {+ token: vaulted.token,+ tokenExpiresAt: vaulted.tokenExpiresAt,+ tokenScopes: vaulted.tokenScopes,+ tokenSource: vaulted.tokenSource,+ };+ }+ const settings = await getSettings().catch(() => null);+ const legacy = normalizeToken(settings?.beeper?.token);+ if (!legacy) return null;+ return {+ token: legacy,+ tokenExpiresAt: toIsoOrNull(settings?.beeper?.tokenExpiresAt),+ tokenScopes: [],+ tokenSource: LEGACY_TOKEN_SOURCE,+ };+}diff --git a/server/services/beeperCredentials.test.js b/server/services/beeperCredentials.test.jsnew file mode 100644index 0000000000..ff48b071ca--- /dev/null+++ b/server/services/beeperCredentials.test.js@@ -0,0 +1,142 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('../lib/db.js', () => ({ query: vi.fn() }));+vi.mock('../lib/vaultCrypto.js', () => ({+ ensureVaultKey: vi.fn().mockResolvedValue({ generated: false }),+ encryptValue: vi.fn(),+ decryptValue: vi.fn(),+}));+vi.mock('./settings.js', () => ({ getSettings: vi.fn() }));++import { query } from '../lib/db.js';+import { decryptValue, encryptValue, ensureVaultKey } from '../lib/vaultCrypto.js';+import { getSettings } from './settings.js';+import {+ deleteBeeperCredential, readBeeperCredential,+ resolveBeeperToken, saveBeeperCredential,+} from './beeperCredentials.js';++// A placeholder that is obviously not a real credential, per the repo's+// placeholders-only rule for anything that lands in a committed file.+const TOKEN = 'example-beeper-token';+const CIPHERTEXT = 'v1:aXY=:dGFn:Y3Q=';++beforeEach(() => {+ vi.clearAllMocks();+ vi.mocked(encryptValue).mockReturnValue(CIPHERTEXT);+ vi.mocked(decryptValue).mockReturnValue(TOKEN);+ vi.mocked(getSettings).mockResolvedValue({});+});++describe('saveBeeperCredential', () => {+ it('encrypts before writing and never puts the token in the row or the log', async () => {+ const logs = [];+ const logSpy = vi.spyOn(console, 'log').mockImplementation((line) => logs.push(String(line)));+ vi.mocked(query).mockResolvedValue({ rowCount: 1 });++ const result = await saveBeeperCredential({+ token: TOKEN, expiresAt: '2026-12-01T00:00:00.000Z', scopes: ['read', 'write'], source: 'oauth', clientId: 'client-1',+ });++ expect(ensureVaultKey).toHaveBeenCalled();+ expect(encryptValue).toHaveBeenCalledWith(TOKEN);+ const params = vi.mocked(query).mock.calls[0][1];+ expect(params).toContain(CIPHERTEXT);+ expect(params).not.toContain(TOKEN);+ expect(params).toContain('read write');+ expect(result).toEqual({ tokenConfigured: true, tokenExpiresAt: '2026-12-01T00:00:00.000Z', tokenSource: 'oauth' });+ expect(logs.join('\n')).not.toContain(TOKEN);+ logSpy.mockRestore();+ });++ // `expiresAt: null` is the no-expiry pasted token (#11 decision 3), a real+ // value that must overwrite an earlier OAuth expiry rather than be treated as+ // "field absent, keep what was there".+ it('stores a null expiry for a pasted token rather than inheriting the previous one', async () => {+ vi.mocked(query).mockResolvedValue({ rowCount: 1 });+ const result = await saveBeeperCredential({ token: TOKEN, expiresAt: null, scopes: [], source: 'pasted' });+ expect(vi.mocked(query).mock.calls[0][1][2]).toBeNull();+ expect(result.tokenExpiresAt).toBeNull();+ expect(result.tokenSource).toBe('pasted');+ });++ it('refuses an unknown provenance rather than writing an unclassified credential', async () => {+ await expect(saveBeeperCredential({ token: TOKEN, source: 'guessed' })).rejects.toThrow(/source/);+ expect(query).not.toHaveBeenCalled();+ });+});++describe('readBeeperCredential', () => {+ it('decrypts the stored row into token, expiry, scopes and provenance', async () => {+ vi.mocked(query).mockResolvedValue({+ rows: [{+ token_enc: CIPHERTEXT,+ token_expires_at: new Date('2026-12-01T00:00:00.000Z'),+ scopes: 'read write',+ source: 'oauth',+ client_id: 'client-1',+ }],+ });+ await expect(readBeeperCredential()).resolves.toEqual({+ token: TOKEN,+ tokenExpiresAt: '2026-12-01T00:00:00.000Z',+ tokenScopes: ['read', 'write'],+ tokenSource: 'oauth',+ clientId: 'client-1',+ });+ });++ it('returns null (never throws) when this install has never connected', async () => {+ vi.mocked(query).mockResolvedValue({ rows: [] });+ await expect(readBeeperCredential()).resolves.toBeNull();+ });++ // #11 decision 8: a local read THROWS on a malformed store rather than+ // returning false. Reporting "not configured" for a row that merely cannot be+ // decrypted would send a connected install back through connect and mint a+ // second credential over a vault key that only went missing.+ it('throws when the stored ciphertext cannot be decrypted, instead of reporting no credential', async () => {+ vi.mocked(query).mockResolvedValue({ rows: [{ token_enc: 'corrupt', source: 'oauth', scopes: '' }] });+ vi.mocked(decryptValue).mockImplementation(() => { throw new Error('Malformed vault ciphertext'); });+ await expect(readBeeperCredential()).rejects.toThrow(/vault ciphertext/);+ });+});++describe('resolveBeeperToken', () => {+ it('prefers the vaulted credential over anything in settings, scopes included', async () => {+ vi.mocked(query).mockResolvedValue({ rows: [{ token_enc: CIPHERTEXT, token_expires_at: null, scopes: 'read write', source: 'oauth', client_id: '' }] });+ vi.mocked(getSettings).mockResolvedValue({ beeper: { token: 'legacy-plaintext-token' } });+ await expect(resolveBeeperToken()).resolves.toMatchObject({ token: TOKEN, tokenSource: 'oauth', tokenScopes: ['read', 'write'] });+ expect(getSettings).not.toHaveBeenCalled();+ });++ // The #29 call site stays readable so an install that hand-edited a token+ // into settings.json before the vault existed keeps working. Nothing writes+ // it any more. It has no scopes to report — fork issue #78's "unknown"+ // sentinel, same as a pasted token.+ it('falls back to the legacy plaintext settings token for READS, with tokenScopes: []', async () => {+ vi.mocked(query).mockResolvedValue({ rows: [] });+ vi.mocked(getSettings).mockResolvedValue({+ beeper: { token: 'legacy-plaintext-token', tokenExpiresAt: '2026-12-01T00:00:00.000Z' },+ });+ await expect(resolveBeeperToken()).resolves.toEqual({+ token: 'legacy-plaintext-token',+ tokenExpiresAt: '2026-12-01T00:00:00.000Z',+ tokenScopes: [],+ tokenSource: 'legacy-settings',+ });+ });++ it('resolves null when neither store holds a credential', async () => {+ vi.mocked(query).mockResolvedValue({ rows: [] });+ await expect(resolveBeeperToken()).resolves.toBeNull();+ });+});++describe('deleteBeeperCredential', () => {+ it('reports what it removed and is idempotent', async () => {+ vi.mocked(query).mockResolvedValueOnce({ rowCount: 1 }).mockResolvedValueOnce({ rowCount: 0 });+ await expect(deleteBeeperCredential()).resolves.toMatchObject({ deleted: true, tokenConfigured: false });+ await expect(deleteBeeperCredential()).resolves.toMatchObject({ deleted: false, tokenConfigured: false });+ });+});diff --git a/server/services/beeperOAuth.js b/server/services/beeperOAuth.jsnew file mode 100644index 0000000000..718f763e4c--- /dev/null+++ b/server/services/beeperOAuth.js@@ -0,0 +1,479 @@+/**+ * 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';++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();++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);+ } 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 });+ }+ prunePending();+ const discovery = await discoverAuthorizationServer();+ const { clientId } = await registerOAuthClient({+ registrationEndpoint: discovery.registrationEndpoint, redirectUri, clientUri,+ });+ const { codeVerifier, codeChallenge } = createPkcePair();+ const state = base64url(randomBytes(24));+ pendingAuthorizations.set(state, {+ codeVerifier, clientId, redirectUri, createdAt: Date.now(),+ 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({+ token,+ expiresAt: expiryFromTokenResponse(body),+ scopes,+ source: 'oauth',+ clientId: pending.clientId,+ });++ await armIngestion('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 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({+ token: value, expiresAt: verified.expiresAt, scopes: verified.scopes, source: 'pasted',+ });+ await armIngestion('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 })+ .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() {+ 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');+ }+ 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 --git a/server/services/beeperOAuth.test.js b/server/services/beeperOAuth.test.jsnew file mode 100644index 0000000000..5b70305ced--- /dev/null+++ b/server/services/beeperOAuth.test.js@@ -0,0 +1,581 @@+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('./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 { 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(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`);+ 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' });+ });++ // 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);+ });++ 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' });+ });++ 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('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(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' });+ });+});diff --git a/server/services/beeperOutbox.js b/server/services/beeperOutbox.jsnew file mode 100644index 0000000000..c83da6c095--- /dev/null+++ b/server/services/beeperOutbox.js@@ -0,0 +1,725 @@+/**+ * 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;+ pending.resolving = true;++ const found = await lookupSentMessage(pending)+ .then((value) => ({ ok: true, value }))+ .catch((err) => ({ ok: false, err }));+ pending.resolving = false;++ 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],+ );+ 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 --git a/server/services/beeperOutbox.test.js b/server/services/beeperOutbox.test.jsnew file mode 100644index 0000000000..0559828d68--- /dev/null+++ b/server/services/beeperOutbox.test.js@@ -0,0 +1,793 @@+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('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 --git a/server/services/beeperOutboxHumanGate.test.js b/server/services/beeperOutboxHumanGate.test.jsnew file mode 100644index 0000000000..897681952b--- /dev/null+++ b/server/services/beeperOutboxHumanGate.test.js@@ -0,0 +1,102 @@+/**+ * Guard: the Beeper send path is reachable ONLY through a human HTTP route+ * (#36, decided on #8 decision 6).+ *+ * Upstream's posture is one send service with exactly one non-test caller — a+ * human route (`messageSender.sendDraft` ← `routes/messages.js`). Beeper is the+ * first chat channel where a programmatic send is technically possible at all,+ * so "no agent path" has to be asserted structurally rather than left to+ * convention: a `cosToolRegistry` entry, a voice tool, or a scheduler import+ * added later would each be a silent, real message to a real person.+ *+ * The assertion is deliberately blunt and source-level, in the shape of+ * `beeperNeverFederates.test.js`: it scans the whole server tree for importers+ * of `beeperOutbox.js` and for anything that names its send function, and pins+ * the importer set. Every filter is paired with a floor on the list it filters,+ * so a scan that silently found nothing (a moved directory, a renamed export)+ * fails instead of passing vacuously.+ */++import { describe, it, expect } from 'vitest';+import { readFileSync, readdirSync } from 'node:fs';+import { dirname, join, relative } from 'node:path';+import { fileURLToPath } from 'node:url';++const HERE = dirname(fileURLToPath(import.meta.url));+const SERVER_ROOT = join(HERE, '..');++function collectSources(dir, out = []) {+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ if (entry.name === 'node_modules' || entry.name.startsWith('.')) continue;+ const full = join(dir, entry.name);+ if (entry.isDirectory()) {+ collectSources(full, out);+ continue;+ }+ if (!entry.name.endsWith('.js')) continue;+ out.push({ path: relative(SERVER_ROOT, full), source: readFileSync(full, 'utf8') });+ }+ return out;+}++const SOURCES = collectSources(SERVER_ROOT);+const PRODUCTION_SOURCES = SOURCES.filter((file) => !file.path.endsWith('.test.js'));++// The send entry point, and the two service functions that reach it.+const SEND_SYMBOLS = ['sendOutboxEntry', 'createOutboxEntry'];++describe('beeper outbox has no agent-initiated send path (#36)', () => {+ it('scanned a recognizably complete server tree', () => {+ expect(SOURCES.length).toBeGreaterThan(200);+ expect(PRODUCTION_SOURCES.length).toBeGreaterThan(100);+ expect(PRODUCTION_SOURCES.some((file) => file.path === 'services/beeperOutbox.js')).toBe(true);+ });++ it('is imported for a send by exactly one production module: the human HTTP route', () => {+ const importers = PRODUCTION_SOURCES+ .filter((file) => file.path !== 'services/beeperOutbox.js')+ .filter((file) => /from '\.{1,2}\/(?:services\/)?beeperOutbox\.js'/.test(file.source))+ .map((file) => file.path)+ .sort();+ // Two non-send importers ride alongside the route, and the test below is+ // what keeps them non-send: `beeperStatus.js` reads the breaker's state for+ // the settings card, and `bootstrap.js` calls the boot reconcile, whose two+ // arms are a state write and a re-armed LOOKUP — neither reaches+ // `sendMessage`, which is why a crash mid-send can never resend itself.+ expect(importers).toEqual(['routes/beeper.js', 'services/beeperStatus.js', 'services/bootstrap.js']);+ });++ it('names the send functions in no production module but the route', () => {+ const callers = PRODUCTION_SOURCES+ .filter((file) => file.path !== 'services/beeperOutbox.js')+ .filter((file) => SEND_SYMBOLS.some((symbol) => file.source.includes(symbol)))+ .map((file) => file.path);+ expect(callers).toEqual(['routes/beeper.js']);+ });++ it('exposes no beeper tool to the CoS catalog or the voice surface', async () => {+ const { getCosToolCatalog } = await import('./cosToolRegistry.js');+ const catalog = getCosToolCatalog({ scope: 'all' });+ const names = JSON.stringify(catalog);+ expect(catalog.length ?? Object.keys(catalog).length).toBeGreaterThan(3);+ expect(/beeper/i.test(names)).toBe(false);+ });++ it('keeps "no external messaging" in the persistent-mind boundaries', async () => {+ const { PERSISTENT_MIND_TOOL_BOUNDARIES } = await import('../lib/persistentMindCapabilities.js');+ expect(PERSISTENT_MIND_TOOL_BOUNDARIES.length).toBeGreaterThan(2);+ expect(PERSISTENT_MIND_TOOL_BOUNDARIES.join(' ')).toContain('external messaging');+ });++ it('reaches the Beeper send API from the outbox service alone', () => {+ // Scoped to modules that import the Beeper CLIENT — `sendMessage` is a+ // common name (Telegram has its own), and this guard is about who can+ // reach `POST /v1/chats/{chatID}/messages`, not about the identifier.+ const senders = PRODUCTION_SOURCES+ .filter((file) => file.path !== 'services/beeperClient.js')+ .filter((file) => /from '\.{1,2}\/(?:services\/)?beeperClient\.js'/.test(file.source))+ .filter((file) => /\bsendMessage\b/.test(file.source))+ .map((file) => file.path);+ expect(senders).toEqual(['services/beeperOutbox.js']);+ });+});diff --git a/server/services/beeperScheduler.js b/server/services/beeperScheduler.jsnew file mode 100644index 0000000000..483ca5bc1e--- /dev/null+++ b/server/services/beeperScheduler.js@@ -0,0 +1,118 @@+/**+ * Beeper Ingestion Sweep Scheduler (#32, decided on #12).+ *+ * The fifth instance of `createSyncScheduler`, alongside iMessage, Signal,+ * Spotify and YouTube, so the per-tick `enabled` re-read and the self-healing+ * re-arm come free and `syncSchedulers.parity.test.js` pins this domain's id,+ * source and log line like every other.+ *+ * TWO gates, and they are not the same flag (#11 keeps them apart):+ * - `isBeeperIngestionArmed()` — the instance FEATURE plus a configured+ * token. Checked here, and SILENTLY: #32's acceptance is that with the+ * feature off or no token, nothing registers and nothing logs, so a fresh+ * install never narrates a feature it does not have.+ * - `settings.beeper.enabled` — the user's own "Enable scheduled Beeper+ * sync" toggle from the Comms → Beeper card. Handed to the factory as+ * `enabled`, so turning it off mid-session stops runs without a restart+ * and logs the same "disabled in settings" line every other domain does.+ *+ * `type: 'interval'` means the first run is one interval AFTER registration,+ * never at boot — intended: boot should not fire a network sweep.+ * `bootstrap.js` calls `startBeeperScheduler()` directly for exactly that+ * reason, never through `beeperArming.js`'s `reconcileBeeperIngestion()` — the+ * one and only place that kicks an immediate sweep on ARMING (fork issue #79)+ * is that reconcile, which runs only off a live trigger (connect, a feature+ * toggle, the sync toggle), never off boot. A throwing handler cannot kill the+ * interval either; `eventScheduler.runEvent` catches the rejection, records+ * the failed run and re-arms.+ *+ * The interval is read fresh at every REGISTRATION (the factory's documented+ * carry-over from the four hand-written originals still locks it between+ * registrations — a running interval does not notice a settings change+ * mid-flight). Fork issue #79's fix for "a new interval only takes effect+ * after a restart" is therefore `restartBeeperScheduler()` below: cancel the+ * current registration and register a fresh one, which reads+ * `getBeeperSyncConfig()` again and picks up whatever is stored right now.+ * `server/routes/settings.js` calls it when a save changes the interval+ * without an `enabled` flip, AND — fork issue #94 — when a flip and an+ * interval change land in the same save but the scheduler was already+ * registered going in (a true→false save leaves it registered; it only gates+ * per tick), because `reconcileBeeperIngestion()`'s own registration guard+ * (`!isBeeperSchedulerRegistered()`) then declines to re-register and the+ * stale `intervalMs` would otherwise survive.+ *+ * No LLM calls happen on this path — ingestion is deterministic — so the+ * no-cold-bootstrap AI policy does not gate it; the opt-in is about the user's+ * credential and intent.+ */++import { createSyncScheduler } from './createSettingsGatedSyncScheduler.js';+import { cancel, getEvent } from './eventScheduler.js';+import { getBeeperSyncConfig, isBeeperIngestionArmed, runBeeperSweep } from './beeperSync.js';++const SCHEDULER_EVENT_ID = 'beeper-sync';++const registerBeeperScheduler = createSyncScheduler({+ id: SCHEDULER_EVENT_ID,+ label: 'Beeper',+ icon: '🫧',+ source: 'beeperScheduler',+ getConfig: getBeeperSyncConfig,+ runSync: () => runBeeperSweep({ reason: 'scheduler' }),+});++/** Whether `beeper-sync` is currently registered with the event scheduler. */+export function isBeeperSchedulerRegistered() {+ return Boolean(getEvent(SCHEDULER_EVENT_ID));+}++/**+ * Start the Beeper ingestion sweep scheduler. Returns without registering —+ * and without logging — when the instance feature is off or no token is+ * configured.+ *+ * Registering again while `beeper-sync` is already scheduled is a no-op rather+ * than a re-`schedule()`: `eventScheduler.schedule` cancels and replaces an+ * event with the same id, which resets `nextRunAt` to a whole interval away. A+ * user toggling the Comms group twice would otherwise keep pushing the next+ * sweep out.+ */+export async function startBeeperScheduler() {+ if (isBeeperSchedulerRegistered()) return;+ if (!await isBeeperIngestionArmed()) return;+ await registerBeeperScheduler();+}++/**+ * Cancel the sweep scheduler — the disarm half (the feature turned off, the+ * credential deleted). Returns whether an event was actually cancelled, so the+ * caller can keep its logging to real transitions.+ */+export function stopBeeperScheduler() {+ return cancel(SCHEDULER_EVENT_ID);+}++/**+ * Cancel and re-register the sweep scheduler against whatever+ * `getBeeperSyncConfig()` reads right now — the interval-change half of fork+ * issue #79. `startBeeperScheduler()` deliberately no-ops once `beeper-sync`+ * is already registered (see its own docblock: a second `schedule()` call+ * resets `nextRunAt` a whole interval into the future, which is exactly wrong+ * for a toggle that did not touch the cadence). An interval change is the one+ * case that guard must NOT swallow, so this cancels first and lets+ * `startBeeperScheduler()` register fresh.+ *+ * Deliberately does not kick an immediate sweep — only ARMING does that+ * (`beeperArming.js`'s `reconcileBeeperIngestion()`). Changing the cadence of+ * an already-running scheduler is a different event, and firing a sweep on+ * every interval edit would surprise a user who is just tuning a number.+ *+ * A no-op, like `startBeeperScheduler()`, when the feature is off or no token+ * is configured: `stopBeeperScheduler()` cancels whatever was registered (or+ * nothing, harmlessly), and the re-registration attempt then declines the+ * same way `startBeeperScheduler()` always has.+ */+export async function restartBeeperScheduler() {+ stopBeeperScheduler();+ await startBeeperScheduler();+}diff --git a/server/services/beeperScheduler.test.js b/server/services/beeperScheduler.test.jsnew file mode 100644index 0000000000..6ae4827595--- /dev/null+++ b/server/services/beeperScheduler.test.js@@ -0,0 +1,175 @@+import {+ describe, it, expect, vi, beforeEach, afterEach,+} from 'vitest';++// The Beeper sweep scheduler's own gate (#32): the shared factory contract is+// pinned for every domain at once in syncSchedulers.parity.test.js, so this+// file covers only what is specific to Beeper — the feature+token gate that+// runs BEFORE the factory, and the interval surviving a throwing sweep.+const state = {+ armed: true,+ config: { enabled: true, intervalMinutes: 1 },+ sweep: vi.fn(async () => ({ skipped: false })),+};++vi.mock('./beeperSync.js', () => ({+ isBeeperIngestionArmed: async () => state.armed,+ getBeeperSyncConfig: async () => state.config,+ runBeeperSweep: (...args) => state.sweep(...args),+}));++const { startBeeperScheduler, restartBeeperScheduler } = await import('./beeperScheduler.js');+const { cancel, getEvent, getHistory } = 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: 1 };+ state.sweep = vi.fn(async () => ({ skipped: false }));+});++afterEach(() => {+ cancel('beeper-sync');+ vi.restoreAllMocks();+ vi.useRealTimers();+});++describe('startBeeperScheduler gating', () => {+ // #32 acceptance: "With the feature off, or with no token, nothing is+ // registered and nothing logs." Silence is the assertion — a fresh install+ // that has never opened the Beeper card must not narrate a feature it does+ // not have, which is why this gate sits ahead of the shared factory (whose+ // disabled path deliberately DOES log).+ it('registers nothing and logs nothing when the feature is off or no token is configured', async () => {+ state.armed = false;+ const logs = captureLogs();++ await startBeeperScheduler();++ expect(getEvent('beeper-sync')).toBeFalsy();+ expect(logs).toEqual([]);+ });++ it('registers nothing but DOES log when armed and the user turned scheduled sync off', async () => {+ state.config = { enabled: false, intervalMinutes: 5 };+ const logs = captureLogs();++ await startBeeperScheduler();++ expect(getEvent('beeper-sync')).toBeFalsy();+ expect(logs).toContain('🫧 Beeper sync scheduler: disabled in settings — skipping');+ });++ it('registers an interval that does not run at boot when armed and enabled', async () => {+ captureLogs();++ await startBeeperScheduler();++ const event = getEvent('beeper-sync');+ expect(event).toBeTruthy();+ expect(event.type).toBe('interval');+ expect(event.intervalMs).toBe(60_000);+ expect(state.sweep).not.toHaveBeenCalled();+ });+});++describe('the armed interval', () => {+ it('runs the sweep on each tick and keeps ticking after one throws', async () => {+ // Real eventScheduler, fake clock: a throwing handler must not cost the+ // schedule its re-arm (eventScheduler.runEvent catches and re-arms in its+ // `finally`). Proven by a SECOND tick after the first rejects, not by+ // trusting the contract — a sweep can throw on any pass (Beeper Desktop+ // quits mid-request) and an ingestion timer that dies on the first bad+ // pass silently stops archiving until the next server restart.+ vi.useFakeTimers();+ captureLogs();+ state.sweep = vi.fn()+ .mockRejectedValueOnce(new Error('Beeper request failed: ECONNREFUSED'))+ .mockResolvedValueOnce({ skipped: false });++ await startBeeperScheduler();++ await vi.advanceTimersByTimeAsync(60_000);+ expect(state.sweep).toHaveBeenCalledTimes(1);+ expect(state.sweep).toHaveBeenCalledWith({ reason: 'scheduler' });++ await vi.advanceTimersByTimeAsync(60_000);+ expect(state.sweep).toHaveBeenCalledTimes(2);+ expect(getEvent('beeper-sync').active).toBe(true);++ // getHistory() is newest-first: the failed pass is recorded, and the pass+ // AFTER it succeeded — the interval outlived the throw.+ const runs = getHistory({ eventId: 'beeper-sync' });+ expect(runs.map((entry) => entry.success)).toEqual([true, false]);+ });++ it('skips the run without calling the sweep when the toggle went off since registration', async () => {+ vi.useFakeTimers();+ const logs = captureLogs();++ await startBeeperScheduler();+ state.config = { enabled: false, intervalMinutes: 1 };++ await vi.advanceTimersByTimeAsync(60_000);++ expect(state.sweep).not.toHaveBeenCalled();+ expect(logs).toContain('🫧 Beeper sync scheduler: disabled since registration — skipping run');+ });+});++// Fork issue #79's "changing the interval takes effect without a restart":+// `startBeeperScheduler()` alone deliberately no-ops once `beeper-sync` is+// already registered (the test right above it pins that no-op), which is+// exactly why a plain interval change through it never took effect until the+// process restarted. `restartBeeperScheduler()` is the fix.+describe('restartBeeperScheduler', () => {+ it('cancels the current registration and re-registers with the interval getBeeperSyncConfig reads NOW', async () => {+ captureLogs();+ await startBeeperScheduler();+ expect(getEvent('beeper-sync').intervalMs).toBe(60_000);++ // This fails on the old code path (`startBeeperScheduler()` called a+ // second time): already registered, it would no-op and leave `intervalMs`+ // at 60_000 — the change stuck until a restart.+ state.config = { enabled: true, intervalMinutes: 10 };+ await restartBeeperScheduler();++ const event = getEvent('beeper-sync');+ expect(event).toBeTruthy();+ expect(event.intervalMs).toBe(10 * 60_000);+ });++ it('does not kick an immediate sweep on an interval change — only arming does that (beeperArming.js)', async () => {+ captureLogs();+ await startBeeperScheduler();+ state.config = { enabled: true, intervalMinutes: 10 };++ await restartBeeperScheduler();++ expect(state.sweep).not.toHaveBeenCalled();+ });++ it('registers fresh when nothing was registered yet, same as startBeeperScheduler', async () => {+ captureLogs();++ await restartBeeperScheduler();++ expect(getEvent('beeper-sync')).toBeTruthy();+ });++ it('is a no-op when the feature is off or no token is configured', async () => {+ state.armed = false;+ const logs = captureLogs();++ await restartBeeperScheduler();++ expect(getEvent('beeper-sync')).toBeFalsy();+ expect(logs).toEqual([]);+ });+});diff --git a/server/services/beeperSocket.js b/server/services/beeperSocket.jsnew file mode 100644index 0000000000..dbdf4bece5--- /dev/null+++ b/server/services/beeperSocket.js@@ -0,0 +1,574 @@+/**+ * Beeper realtime transport (#33, decided on #12).+ *+ * One long-lived WebSocket from the PortOS server to Beeper Desktop's local+ * `/v1/ws`. The browser cannot hold this connection itself — Beeper binds to+ * loopback with CORS locked to the machine, and a browser cannot set an+ * `Authorization` header on `new WebSocket()` — so the server owns the socket+ * and relays over Socket.IO (`socket.js`, the `beeper` subscriber set).+ *+ * **The `ws` package, not Node's built-in WHATWG `WebSocket`.** A live 105-second+ * probe (#12) recorded a protocol-level server ping at 10.5s and then every 30s,+ * which the research note said did not exist. That ping is the only liveness+ * signal Beeper offers, and the built-in WebSocket does not surface ping frames+ * to application code at all — which is why `moltworldWs.js` cannot be copied+ * here, only imitated. Its reconnect shape is still the model.+ *+ * **This socket is not the source of truth.** Delivery is at-most-once with no+ * replay on reconnect, `seq` is per connection, an event is silently skipped+ * when the message is not yet retrievable, and the window before+ * `subscriptions.updated` is dark. Correctness comes from #32's HTTP sweep; the+ * socket only makes ingestion prompt, and asks the sweep to run early on the+ * three occasions frames could have been lost:+ * - a reconnect (anything during the outage is gone),+ * - a `seq` gap (frames dropped while the socket still looked healthy),+ * - a recovery from an actionable `app.state` (the install was broken).+ *+ * **Never gated on `app.state`.** The probe measured it reporting `initializing`+ * for 105 continuous seconds while nine accounts were connected and a chat page+ * returned in 230ms. It is a display input for the settings card, never a gate.+ *+ * **Two gates, and the transport and the sweep sit behind different ones (#11).**+ * - `isBeeperIngestionArmed()` — the instance FEATURE plus a stored token —+ * arms the TRANSPORT. Holding the socket open writes nothing: it only feeds+ * the settings card's liveness dot and its actionable `app.state` line,+ * which is the surface a user needs precisely when they are deciding+ * whether to turn ingestion on. So the connection is deliberately kept.+ * - `settings.beeper.enabled` ("Enable scheduled Beeper sync", default OFF)+ * is the user's ingestion opt-in, and it gates every `runBeeperSweep` call+ * from here — re-read at EVERY trigger, exactly as+ * `createSettingsGatedSyncScheduler.js` re-reads it on every tick, so+ * flipping the toggle off mid-session stops sweeps without a restart.+ * With it off the socket connects, subscribes and relays invalidations, and+ * never writes a conversation or a message body to Postgres.+ *+ * Everything below runs OUTSIDE the Express request lifecycle — socket callbacks+ * and timers — so hook bodies catch and log rather than letting a throw take the+ * process down, per root AGENTS.md.+ */++import WebSocket from 'ws';+import { beeperSocketEvents } from './beeperSocketEvents.js';+import { DEFAULT_BASE_URL, resolveBeeperConfig } from './beeperClient.js';+import { getBeeperSyncConfig, isBeeperIngestionArmed, runBeeperSweep } from './beeperSync.js';++const LOG_PREFIX = '🫧 Beeper socket';++// 2.5 missed server pings. Tight enough that the liveness dot cannot lie for+// long, loose enough to survive one late ping (#12 decision 5).+export const SILENCE_TIMEOUT_MS = 75_000;+const BASE_RECONNECT_DELAY_MS = 1_000;+const MAX_RECONNECT_DELAY_MS = 60_000;++// Beeper Desktop simply being closed is the common case, and at the 60s ceiling+// an unbounded loop writes a line a minute forever. The first few attempts are+// the diagnostic ones; after that only every 10th is narrated.+const VERBOSE_RECONNECT_ATTEMPTS = 3;+const QUIET_RECONNECT_LOG_EVERY = 10;++// The four domain events, all with the same flat frame: `type`, `seq`, `ts`,+// `chatID`, `ids` required, `entries` OPTIONAL on every one of them (not only+// on deletes, as the research note recorded). `entries` is deliberately never+// read — see `toInvalidation` below.+const DOMAIN_EVENT_TYPES = new Set(['chat.upserted', 'chat.deleted', 'message.upserted', 'message.deleted']);++// The `app.state` values that mean a human has to do something. `initializing`+// and `needs-first-sync` are explicitly NOT in this set: the probe caught+// `initializing` lying for the whole session on a working install.+const ACTIONABLE_APP_STATES = new Set([+ 'needs-login', 'needs-cross-signing-setup', 'needs-verification', 'needs-secrets',+]);++const DEFAULT_RUNTIME = Object.freeze({+ now: () => Date.now(),+ setTimeout: (fn, ms) => setTimeout(fn, ms),+ clearTimeout: (handle) => clearTimeout(handle),+ random: () => Math.random(),+ createSocket: (url, options) => new WebSocket(url, options),+});++let runtime = { ...DEFAULT_RUNTIME };+let socket = null;+let watchdogTimer = null;+let reconnectTimer = null;+let reconnectAttempts = 0;+let connectionCount = 0;+let running = false;+let connectionState = 'down';+let lastEventAt = null;+let lastPingAt = null;+let lastSeq = null;+let appState = null;+let requestCounter = 0;+// Bumped by every `stopBeeperSocket()` so an in-flight `await` can tell that the+// session it belongs to was torn down while it was suspended.+let stopGeneration = 0;+let hasEverConnected = false;+let authRejected = false;++/**+ * `http://127.0.0.1:23373` → `ws://127.0.0.1:23373/v1/ws`. Exported for the+ * test; the path is not in Beeper's OpenAPI document, so it is hardcoded here+ * rather than discovered.+ */+export function beeperWebSocketUrl(baseUrl) {+ const trimmed = String(baseUrl || '').trim().replace(/\/+$/, '') || DEFAULT_BASE_URL;+ return `${trimmed.replace(/^https:\/\//i, 'wss://').replace(/^http:\/\//i, 'ws://')}/v1/ws`;+}++/**+ * The transport liveness snapshot. Four states, matching what the settings+ * card renders: `connected`, `connecting` (trying, never yet connected),+ * `reconnecting` (was connected, trying again), `down` (not armed, deliberately+ * stopped, or stood down after Beeper rejected the token).+ */+export function getBeeperRealtimeState() {+ return {+ state: connectionState,+ lastEventAt: lastEventAt === null ? null : new Date(lastEventAt).toISOString(),+ lastPingAt: lastPingAt === null ? null : new Date(lastPingAt).toISOString(),+ reconnectAttempts,+ appState,+ // The card's actionable-fault line: an `app.state` a human must act on.+ // Never `initializing`, which the probe proved is not evidence of anything.+ appStateActionable: appState !== null && ACTIONABLE_APP_STATES.has(appState),+ // Beeper answered the upgrade with 401/403: the stored token is not going+ // to start working, so the transport stood down rather than looping. The+ // settings card turns this into its own remedy line.+ authRejected,+ };+}++/** `connecting` until the first successful handshake of this session; `reconnecting` after. */+function pendingStateWord() {+ return hasEverConnected ? 'reconnecting' : 'connecting';+}++/**+ * The sweep's effective gate, re-read at EVERY trigger.+ *+ * `isBeeperIngestionArmed()` alone is only "may the sweep be armed at all"+ * (feature + token). The user's own `settings.beeper.enabled` opt-in is the+ * second gate, and `runBeeperSweep` does not check it itself — the scheduler+ * factory re-reads it on every tick for exactly this reason, so a socket+ * trigger re-reads it too and a mid-session toggle-off takes effect at once.+ */+async function isSweepEnabled() {+ if (!await isBeeperIngestionArmed()) return false;+ const { enabled } = await getBeeperSyncConfig();+ return enabled === true;+}++function emitState() {+ beeperSocketEvents.emit('state', getBeeperRealtimeState());+}++function setConnectionState(next) {+ if (connectionState === next) return;+ connectionState = next;+ console.log(`${LOG_PREFIX}: ${next}`);+ emitState();+}++function clearWatchdog() {+ if (watchdogTimer !== null) {+ runtime.clearTimeout(watchdogTimer);+ watchdogTimer = null;+ }+}++function clearReconnectTimer() {+ if (reconnectTimer !== null) {+ runtime.clearTimeout(reconnectTimer);+ reconnectTimer = null;+ }+}++/**+ * Re-arm the silence watchdog. Called from the connection attempt (so a+ * half-open TCP handshake trips too) and from every inbound signal — a ping+ * frame, a pong, or any message. `ws` auto-replies to a ping, so counting it as+ * liveness is exactly the measured heartbeat and needs no keepalive of our own.+ */+function armWatchdog() {+ clearWatchdog();+ watchdogTimer = runtime.setTimeout(() => {+ watchdogTimer = null;+ console.warn(`${LOG_PREFIX}: silent for ${SILENCE_TIMEOUT_MS / 1000}s — tearing down and reconnecting`);+ dropSocket();+ scheduleReconnect();+ }, SILENCE_TIMEOUT_MS);+ if (typeof watchdogTimer?.unref === 'function') watchdogTimer.unref();+}++function noteFrame() {+ lastEventAt = runtime.now();+ armWatchdog();+}++/**+ * Ask #32's watermark-bounded sweep to run now. Fire-and-forget with its own+ * catch: this is a timer/socket callback, so an unhandled rejection here would+ * be an unhandled rejection in the process, not a 500.+ */+function triggerSweep(reason) {+ Promise.resolve()+ .then(async () => {+ if (!await isSweepEnabled()) {+ // Debug level: with the toggle off this fires on every reconnect and+ // every seq gap, and it is the configured behaviour, not a fault.+ console.debug(`${LOG_PREFIX}: sweep (${reason}) skipped — scheduled Beeper sync is off`);+ return;+ }+ console.log(`${LOG_PREFIX}: requesting a sweep (${reason})`);+ await runBeeperSweep({ reason });+ })+ .catch((err) => console.error(`${LOG_PREFIX}: sweep (${reason}) failed: ${err?.message ?? err}`));+}++/**+ * Jittered exponential backoff: the delay lands in the top half of the+ * exponential window, so a fleet of retries cannot align on the same instant+ * and a single dead Beeper Desktop is not hammered at a fixed cadence.+ */+function nextReconnectDelayMs() {+ const capped = Math.min(BASE_RECONNECT_DELAY_MS * (2 ** reconnectAttempts), MAX_RECONNECT_DELAY_MS);+ return Math.round((capped / 2) + (runtime.random() * (capped / 2)));+}++/**+ * Whether this reconnect cycle gets logged. A closed Beeper Desktop reconnects+ * forever by design (it will be reopened), so the loop narrates the first few+ * attempts and then only every 10th.+ */+function shouldNarrateAttempt() {+ return reconnectAttempts <= VERBOSE_RECONNECT_ATTEMPTS+ || reconnectAttempts % QUIET_RECONNECT_LOG_EVERY === 0;+}++function scheduleReconnect() {+ if (!running) return;+ clearReconnectTimer();+ const delay = nextReconnectDelayMs();+ reconnectAttempts += 1;+ setConnectionState(pendingStateWord());+ if (shouldNarrateAttempt()) {+ console.log(`${LOG_PREFIX}: reconnecting in ${Math.round(delay / 1000)}s (attempt ${reconnectAttempts})`);+ }+ reconnectTimer = runtime.setTimeout(() => {+ reconnectTimer = null;+ // A rejected `connect()` (a credential read that throws — an unreadable+ // vault, not merely an absent token) must not silently end the reconnect+ // loop: without this catch the timer never fires again, yet+ // `getBeeperRealtimeState()` keeps reporting `reconnecting` for the life of+ // the process. Drop whatever half-open socket the attempt left behind and+ // schedule the next attempt exactly as a `close`/`error` event would.+ connect().catch((err) => {+ console.error(`${LOG_PREFIX}: reconnect failed: ${err?.message ?? err}`);+ dropSocket();+ scheduleReconnect();+ });+ }, delay);+ if (typeof reconnectTimer?.unref === 'function') reconnectTimer.unref();+}++function dropSocket() {+ clearWatchdog();+ const dying = socket;+ socket = null;+ if (!dying) return;+ dying.removeAllListeners?.();+ // `terminate()` is the `ws` escape hatch for a socket that may be half-open —+ // `close()` waits for a close handshake the dead peer will never send.+ if (typeof dying.terminate === 'function') dying.terminate();+ else dying.close?.();+}++// ---------------------------------------------------------------------------+// Frame handling+// ---------------------------------------------------------------------------++function toIsoTimestamp(value) {+ if (typeof value === 'number' && Number.isFinite(value)) return new Date(value).toISOString();+ if (typeof value !== 'string' || !value) return null;+ const parsed = new Date(value);+ return Number.isNaN(parsed.getTime()) ? null : parsed.toISOString();+}++/**+ * The invalidation frame the browser gets — ids and kinds ONLY (#12 decision 3).+ *+ * Fields are picked EXPLICITLY, never spread: a Beeper domain frame may carry a+ * hydrated `entries` array with full message text, sender display names and+ * network handles, and none of that may leave this machine. The browser refetches+ * from the PortOS mirror instead, which also keeps "displayed" implying+ * "persisted" — a payload relay can render a message the mirror never committed.+ *+ * `ids` are message ids for `message.*` and chat ids for `chat.*`, matching the+ * frame's own shape.+ */+export function toInvalidation(frame) {+ return {+ kind: frame?.type ?? null,+ chatID: typeof frame?.chatID === 'string' ? frame.chatID : null,+ ids: Array.isArray(frame?.ids) ? frame.ids.filter((id) => typeof id === 'string') : [],+ seq: Number.isFinite(frame?.seq) ? frame.seq : null,+ ts: toIsoTimestamp(frame?.ts),+ };+}++/**+ * `seq` is a per-connection counter that spans every event type (the probe saw+ * `app.state.updated` arrive as `seq: 1`), so a jump means frames were dropped+ * while the socket still looked perfectly healthy — the one loss mode a+ * reconnect-triggered sweep would never notice.+ */+function checkSequence(frame) {+ if (!Number.isFinite(frame?.seq)) return;+ const seq = frame.seq;+ if (lastSeq !== null && seq > lastSeq + 1) {+ console.warn(`${LOG_PREFIX}: seq gap (${lastSeq} → ${seq}) — frames were dropped`);+ triggerSweep('socket-seq-gap');+ }+ lastSeq = seq;+}++function handleAppState(frame) {+ const next = typeof frame?.appState?.state === 'string' ? frame.appState.state : null;+ if (next === null || next === appState) return;+ const wasActionable = appState !== null && ACTIONABLE_APP_STATES.has(appState);+ appState = next;+ emitState();+ // A recovery FROM an actionable state means the install was broken and is now+ // working — whatever arrived while it was broken was never delivered here.+ if (wasActionable && !ACTIONABLE_APP_STATES.has(next)) triggerSweep('socket-app-state-recovery');+}++function sendSubscription(target) {+ requestCounter += 1;+ // `["*"]` plus app state, never a scoped chat set: `subscriptions.set`+ // replaces state wholesale and the window during a re-`set` is dark, so+ // re-subscribing on every conversation change would manufacture a loss window+ // on exactly the event you most want to catch — a brand new conversation.+ target.send(JSON.stringify({+ type: 'subscriptions.set',+ requestID: `portos-${requestCounter}`,+ chatIDs: ['*'],+ app: { state: true },+ }));+}++function handleFrame(raw, target) {+ // External data from a local daemon — a parse guard is justified here (this+ // runs in a socket callback, outside any Express error middleware).+ let frame;+ try {+ frame = JSON.parse(raw);+ } catch {+ console.error(`${LOG_PREFIX}: unparseable frame discarded`);+ return;+ }+ if (!frame || typeof frame !== 'object') return;++ checkSequence(frame);++ if (frame.type === 'ready') {+ sendSubscription(target);+ return;+ }+ if (frame.type === 'subscriptions.updated') {+ hasEverConnected = true;+ setConnectionState('connected');+ // The first connection of a process is not a reconnect: boot arms the+ // transport, it does not fire a sweep (`type: 'interval'` in #32's+ // scheduler makes the same choice for the same reason).+ if (connectionCount > 1) triggerSweep('socket-reconnect');+ return;+ }+ if (frame.type === 'error') {+ // The code only. A Beeper `error` frame carries a free-text `message` that+ // is not ours to log.+ console.error(`${LOG_PREFIX}: protocol error (${frame.code || 'unknown'})`);+ return;+ }+ if (frame.type === 'app.state.updated') {+ handleAppState(frame);+ return;+ }+ if (DOMAIN_EVENT_TYPES.has(frame.type)) {+ beeperSocketEvents.emit('invalidate', toInvalidation(frame));+ }+}++// ---------------------------------------------------------------------------+// Connection lifecycle+// ---------------------------------------------------------------------------++async function connect() {+ if (!running || socket) return;+ const generation = stopGeneration;+ const { baseUrl, token } = await resolveBeeperConfig();+ // A `stopBeeperSocket()` (shutdown, token revoked) can land while the config+ // read is suspended. Without this the teardown is followed by a brand new+ // socket the shutdown path no longer knows about.+ if (!running || stopGeneration !== generation || socket) return;+ if (!token) {+ // The token went away mid-session (revoked, vault cleared). Stop rather+ // than loop against a socket that can only ever answer 401.+ console.warn(`${LOG_PREFIX}: no token configured — standing down`);+ stopBeeperSocket();+ return;+ }++ connectionCount += 1;+ lastSeq = null;+ setConnectionState(pendingStateWord());+ // Armed before the handshake so a half-open connect trips the watchdog too.+ armWatchdog();++ // The token rides the upgrade request's `Authorization` header and is never+ // logged, never placed in the URL, and never emitted to a browser.+ const instance = runtime.createSocket(beeperWebSocketUrl(baseUrl), {+ headers: { Authorization: `Bearer ${token}` },+ });+ socket = instance;++ const guard = (label, handler) => (...args) => {+ if (socket !== instance) return; // a superseded socket must not drive state+ try {+ handler(...args);+ } catch (err) {+ console.error(`${LOG_PREFIX}: ${label} handler failed: ${err?.message ?? err}`);+ }+ };++ instance.on('open', guard('open', () => {+ reconnectAttempts = 0;+ noteFrame();+ }));+ // `ws` exposes the protocol ping the built-in WebSocket hides, and auto-replies+ // pong. Measured cadence: 10.5s after open, then every 30s.+ //+ // No `emitState()` here (finding PERF-7): a bare ping changes nothing but+ // `lastPingAt`, which `getBeeperRealtimeState()` reads live off this+ // module's own variable — so `GET /api/beeper/status` and+ // `hasRecentBeeperActivity()` (`beeperStatus.js`) both still see a fresh+ // value with no broadcast involved. The socket-pushed `beeper:realtime`+ // payload is that same `getBeeperRealtimeState()` object, so it DOES carry+ // `lastPingAt` (and `lastEventAt`) — but no client reader renders either+ // timestamp from the push: the surfaces that consume the event+ // (`useBeeperRealtime.js` → the connection dot and the settings panel's+ // realtime row) read only `state`, `appState`, `appStateActionable` and+ // `authRejected`, none of which a plain ping changes. Broadcasting a+ // payload whose visible fields+ // read identically to the last one was pure re-render cost 2-3 times a+ // minute on every open tab, for nothing anyone could see change.+ // `noteFrame()` still re-arms the watchdog, so the ping continues to count+ // as liveness exactly as before.+ instance.on('ping', guard('ping', () => {+ lastPingAt = runtime.now();+ noteFrame();+ }));+ instance.on('pong', guard('pong', () => noteFrame()));+ instance.on('message', guard('message', (data) => {+ noteFrame();+ handleFrame(typeof data === 'string' ? data : String(data), instance);+ }));+ instance.on('error', guard('error', (err) => {+ if (shouldNarrateAttempt()) console.error(`${LOG_PREFIX}: connection error: ${err?.message ?? err}`);+ }));+ // A non-101 answer to the upgrade. 401/403 means the stored token is rejected,+ // not that Beeper is momentarily away: reconnecting can only produce the same+ // answer forever, so the transport stands down and the settings card carries+ // the remedy. `ws` routes this here instead of `error` because a listener is+ // attached; `dropSocket()` terminates the still-CONNECTING socket, which+ // aborts the underlying request.+ instance.on('unexpected-response', guard('unexpected-response', (_request, response) => {+ const status = response?.statusCode ?? null;+ if (status === 401 || status === 403) {+ console.error(`${LOG_PREFIX}: Beeper rejected the token (HTTP ${status}) — standing down`);+ stopBeeperSocket();+ authRejected = true;+ emitState();+ return;+ }+ if (shouldNarrateAttempt()) console.error(`${LOG_PREFIX}: unexpected upgrade response (HTTP ${status ?? 'unknown'})`);+ dropSocket();+ scheduleReconnect();+ }));+ instance.on('close', guard('close', (code) => {+ if (shouldNarrateAttempt()) console.log(`${LOG_PREFIX}: closed (code=${code ?? 'none'})`);+ dropSocket();+ scheduleReconnect();+ }));+}++/**+ * Arm the realtime transport at boot on the TRANSPORT gate — the instance+ * FEATURE on plus a token present, and never `app.state` — and just as SILENT+ * when it does not apply: a fresh install that has never opened the Beeper card+ * neither connects nor logs.+ *+ * Deliberately NOT gated on `settings.beeper.enabled`: the socket writes+ * nothing, and the liveness dot it feeds is what the settings card shows while+ * the user decides whether to enable ingestion. Every sweep it would request is+ * gated on that toggle instead (`isSweepEnabled`), re-read per trigger.+ *+ * `overrides` injects `{ now, setTimeout, clearTimeout, random, createSocket }`+ * so the watchdog and the backoff are provable without a real sleep.+ */+export async function startBeeperSocket(overrides = {}) {+ if (running) return false;+ const generation = stopGeneration;+ if (!await isBeeperIngestionArmed()) return false;+ // A stop landing during the gate read must not be undone by the start that+ // was already in flight when it arrived.+ if (stopGeneration !== generation || running) return false;+ runtime = { ...DEFAULT_RUNTIME, ...overrides };+ running = true;+ reconnectAttempts = 0;+ connectionCount = 0;+ hasEverConnected = false;+ authRejected = false;+ try {+ await connect();+ } catch (err) {+ // A credential read that throws (an unreadable vault, not merely an+ // absent token — #11 decision 8) rejects `connect()` before it ever+ // schedules a reconnect. Left at `running: true` with no timer behind it,+ // this is stuck for the life of the process: `isBeeperSocketRunning()`+ // says armed, the state stays whatever `pendingStateWord()` last set, and+ // no later reconcile call can re-arm it because `startBeeperSocket()`+ // declines whenever `running` is already true. Reset it here — guarded on+ // generation so a `stopBeeperSocket()` that landed while `connect()` was+ // suspended is not undone — so the next `reconcileBeeperIngestion()` call+ // (a credential re-saved, a feature retoggled) gets a fresh attempt.+ console.error(`${LOG_PREFIX}: initial connect failed: ${err?.message ?? err}`);+ if (stopGeneration === generation) running = false;+ }+ return true;+}++/** Whether the transport is armed (connected, connecting, or backing off). */+export function isBeeperSocketRunning() {+ return running;+}++/**+ * Tear the transport down (shutdown, a token that disappeared, or a rejected+ * one). Returns whether it was running, so a caller reconciling the arming gate+ * can log a real transition rather than every pass.+ */+export function stopBeeperSocket() {+ const wasRunning = running;+ running = false;+ stopGeneration += 1;+ clearReconnectTimer();+ dropSocket();+ reconnectAttempts = 0;+ lastSeq = null;+ hasEverConnected = false;+ setConnectionState('down');+ runtime = { ...DEFAULT_RUNTIME };+ return wasRunning;+}diff --git a/server/services/beeperSocket.test.js b/server/services/beeperSocket.test.jsnew file mode 100644index 0000000000..ada41acec7--- /dev/null+++ b/server/services/beeperSocket.test.js@@ -0,0 +1,676 @@+import {+ describe, it, expect, vi, beforeEach, afterEach,+} from 'vitest';++/**+ * The realtime transport (#33). Time is INJECTED throughout — the watchdog is a+ * 75-second contract and the backoff is a jittered exponential, and proving+ * either with a real sleep would put a minute-plus of wall clock into CI for+ * behaviour a fake clock pins exactly.+ *+ * The `ws` module is mocked at the boundary: these tests drive a fake socket's+ * `open` / `ping` / `message` / `close` events and assert what PortOS does with+ * them, not what `ws` does with a TCP stream.+ */++const createdSockets = [];++class FakeSocket {+ constructor(url, options) {+ this.url = url;+ this.options = options;+ this.sent = [];+ this.terminated = false;+ this.listeners = new Map();+ createdSockets.push(this);+ }++ on(event, handler) {+ if (!this.listeners.has(event)) this.listeners.set(event, []);+ this.listeners.get(event).push(handler);+ return this;+ }++ removeAllListeners() { this.listeners.clear(); }+ send(payload) { this.sent.push(payload); }+ terminate() { this.terminated = true; }+ close() { this.terminated = true; }++ fire(event, ...args) {+ for (const handler of [...(this.listeners.get(event) || [])]) handler(...args);+ }++ // Walk the documented handshake: open → ready → subscriptions.updated.+ handshake() {+ this.fire('open');+ this.fire('message', JSON.stringify({ type: 'ready', version: 1, chatIDs: [], app: { state: false } }));+ this.fire('message', JSON.stringify({ type: 'subscriptions.updated', requestID: 'r1', chatIDs: ['*'] }));+ }+}++vi.mock('ws', () => ({ default: FakeSocket }));++let armed = true;+// `settings.beeper.enabled` — the user's ingestion opt-in, DEFAULT OFF in+// production. Every test that expects a sweep has to turn it on, which is the+// point: the transport arms without it, the sweep never runs without it.+let syncEnabled = true;+let resolvedConfig = { baseUrl: 'http://127.0.0.1:23373', token: 'example-token' };+const sweeps = [];++vi.mock('./beeperSync.js', () => ({+ isBeeperIngestionArmed: vi.fn(async () => armed),+ getBeeperSyncConfig: vi.fn(async () => ({ enabled: syncEnabled, intervalMinutes: 5 })),+ runBeeperSweep: vi.fn(async ({ reason }) => { sweeps.push(reason); return { skipped: false }; }),+}));+vi.mock('./beeperClient.js', () => ({+ DEFAULT_BASE_URL: 'http://127.0.0.1:23373',+ resolveBeeperConfig: vi.fn(async () => resolvedConfig),+}));++const {+ startBeeperSocket, stopBeeperSocket, getBeeperRealtimeState, toInvalidation,+ beeperWebSocketUrl, SILENCE_TIMEOUT_MS,+} = await import('./beeperSocket.js');+const { beeperSocketEvents } = await import('./beeperSocketEvents.js');+const { isBeeperIngestionArmed } = await import('./beeperSync.js');+const { resolveBeeperConfig } = await import('./beeperClient.js');++// A controllable clock: timers are recorded rather than run, so a test advances+// exactly the one it cares about.+function makeClock() {+ const timers = new Map();+ let nextId = 1;+ let current = 0;+ return {+ timers,+ now: () => current,+ advance: (ms) => { current += ms; },+ setTimeout: (fn, ms) => {+ const id = nextId++;+ timers.set(id, { fn, ms });+ return id;+ },+ clearTimeout: (id) => { timers.delete(id); },+ // Run every timer scheduled for exactly `ms`, newest first.+ 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;+ },+ delaysFor: (predicate) => [...timers.values()].filter(predicate).map((timer) => timer.ms),+ };+}++let clock;+let random;++// The sweep gate is re-read asynchronously on every trigger, so a sweep now+// costs several microtask turns. Drain the whole queue instead of counting+// `Promise.resolve()`s.+const flush = () => new Promise((resolve) => setImmediate(resolve));++async function start(overrides = {}) {+ clock = makeClock();+ return startBeeperSocket({+ now: clock.now,+ setTimeout: clock.setTimeout,+ clearTimeout: clock.clearTimeout,+ random: () => random,+ ...overrides,+ });+}++const latest = () => createdSockets[createdSockets.length - 1];++describe('beeperSocket — arming gate', () => {+ beforeEach(() => {+ createdSockets.length = 0;+ sweeps.length = 0;+ armed = true;+ syncEnabled = true;+ random = 0.5;+ resolvedConfig = { baseUrl: 'http://127.0.0.1:23373', token: 'example-token' };+ });+ afterEach(() => { stopBeeperSocket(); vi.restoreAllMocks(); });++ it('opens one authenticated socket at the derived ws:// URL when the feature is on and a token is present', async () => {+ expect(await start()).toBe(true);+ expect(createdSockets).toHaveLength(1);+ expect(latest().url).toBe('ws://127.0.0.1:23373/v1/ws');+ expect(latest().options.headers.Authorization).toBe('Bearer example-token');+ });++ it('does not connect, and does not log, with the instance feature off', async () => {+ armed = false;+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ expect(await start()).toBe(false);+ expect(createdSockets).toHaveLength(0);+ expect(log).not.toHaveBeenCalled();+ expect(warn).not.toHaveBeenCalled();+ });++ it('does not connect, and does not log, with no token configured', async () => {+ // The gate is `isBeeperIngestionArmed`, which is token-aware — a fresh+ // install must neither open a reconnect loop against an absent localhost+ // port nor narrate a feature it does not have.+ armed = false;+ resolvedConfig = { baseUrl: 'http://127.0.0.1:23373', token: null };+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});+ expect(await start()).toBe(false);+ expect(createdSockets).toHaveLength(0);+ expect(log).not.toHaveBeenCalled();+ expect(vi.mocked(isBeeperIngestionArmed)).toHaveBeenCalled();+ });++ it('never gates on app.state: an install reporting `initializing` still connects and stays connected', async () => {+ await start();+ latest().handshake();+ latest().fire('message', JSON.stringify({ type: 'app.state.updated', seq: 1, ts: 1, appState: { state: 'initializing' } }));+ expect(getBeeperRealtimeState().state).toBe('connected');+ expect(sweeps).toEqual([]);+ });++ it('subscribes to ["*"] plus app state, never a scoped chat set', async () => {+ await start();+ latest().fire('open');+ latest().fire('message', JSON.stringify({ type: 'ready', version: 1, chatIDs: [] }));+ const frame = JSON.parse(latest().sent[0]);+ expect(frame.type).toBe('subscriptions.set');+ expect(frame.chatIDs).toEqual(['*']);+ expect(frame.app).toEqual({ state: true });+ });++ it('still connects with the ingestion toggle off — the transport is not the opt-in', async () => {+ // Documented decision (#11 two gates): the socket writes nothing, and the+ // liveness dot it feeds is what the settings card shows while the user is+ // deciding whether to enable ingestion. What the toggle gates is the sweep.+ syncEnabled = false;+ expect(await start()).toBe(true);+ latest().handshake();+ expect(createdSockets).toHaveLength(1);+ expect(getBeeperRealtimeState().state).toBe('connected');+ });++ it('reports `connecting`, not `reconnecting`, before it has ever connected', async () => {+ await start();+ expect(getBeeperRealtimeState().state).toBe('connecting');+ latest().handshake();+ expect(getBeeperRealtimeState().state).toBe('connected');+ latest().fire('close', 1006);+ expect(getBeeperRealtimeState().state).toBe('reconnecting');+ });++ it('never opens a socket when a stop lands during the arming gate read', async () => {+ // `stopBeeperSocket()` (shutdown) while `isBeeperIngestionArmed()` is still+ // suspended must not be undone by the start that was already in flight.+ const started = start();+ stopBeeperSocket();+ expect(await started).toBe(false);+ expect(createdSockets).toHaveLength(0);+ });++ it('never opens a socket when a stop lands during the config read', async () => {+ let release;+ const gate = new Promise((resolve) => { release = resolve; });+ vi.mocked(resolveBeeperConfig).mockImplementationOnce(async () => { await gate; return resolvedConfig; });++ const started = start();+ await flush(); // suspended inside connect()'s credential read+ stopBeeperSocket();+ release();+ await started;++ expect(createdSockets).toHaveLength(0);+ expect(getBeeperRealtimeState().state).toBe('down');+ });++ it('derives the ws URL from the configured base URL, wss:// for https', () => {+ expect(beeperWebSocketUrl('https://192.0.2.10:23373/')).toBe('wss://192.0.2.10:23373/v1/ws');+ expect(beeperWebSocketUrl('')).toBe('ws://127.0.0.1:23373/v1/ws');+ });+});++describe('beeperSocket — silence watchdog (injected time)', () => {+ beforeEach(() => {+ createdSockets.length = 0;+ sweeps.length = 0;+ armed = true;+ syncEnabled = true;+ random = 0.5;+ resolvedConfig = { baseUrl: 'http://127.0.0.1:23373', token: 'example-token' };+ vi.spyOn(console, 'warn').mockImplementation(() => {});+ vi.spyOn(console, 'log').mockImplementation(() => {});+ });+ afterEach(() => { stopBeeperSocket(); vi.restoreAllMocks(); });++ it('tears the connection down after 75s of total silence and schedules a reconnect', async () => {+ await start();+ latest().handshake();+ const first = latest();++ expect(clock.runTimersWithDelay(SILENCE_TIMEOUT_MS)).toBe(1);++ expect(first.terminated).toBe(true);+ expect(getBeeperRealtimeState().state).toBe('reconnecting');+ });++ it('counts a server ping as liveness, so a quiet-but-alive connection is never torn down', async () => {+ await start();+ latest().handshake();+ const first = latest();++ // The measured heartbeat: 10.5s after open, then every 30s. Each one+ // re-arms the watchdog, so the pre-ping timer is gone.+ for (const at of [10_500, 40_500, 70_500, 100_500]) {+ clock.advance(at - clock.now());+ first.fire('ping');+ }+ expect(clock.runTimersWithDelay(SILENCE_TIMEOUT_MS)).toBe(1); // exactly one live watchdog, re-armed+ expect(first.terminated).toBe(true); // ...and it only fires once nothing else arrives++ const state = getBeeperRealtimeState();+ expect(state.lastPingAt).toBe(new Date(100_500).toISOString());+ });++ // PERF-7: every 30s protocol ping used to call `emitState()` unconditionally,+ // re-broadcasting `beeper:realtime` — and re-rendering every open chat+ // surface — for a payload that reads identically to the last one, since a+ // bare ping changes nothing the payload carries except a timestamp no+ // socket listener even renders (`useBeeperRealtime.js`'s only client reads+ // `state`/`appState`/`authRejected`). The fix drops the `emitState()` call+ // from the ping handler outright, leaving liveness split across its two real+ // consumers: the watchdog (via `noteFrame()`) and the HTTP status route+ // (which reads `lastPingAt` straight off this module's own variable, not off+ // an emitted event).+ it('a protocol ping with no state change emits no state broadcast, though the watchdog still counts it and the status stays fresh', async () => {+ await start();+ latest().handshake();+ const first = latest();++ const broadcasts = [];+ const onState = (state) => broadcasts.push(state);+ beeperSocketEvents.on('state', onState);++ clock.advance(10_500);+ first.fire('ping');++ expect(broadcasts).toHaveLength(0);+ // `GET /api/beeper/status` reads this straight off the module, with no+ // broadcast in the path — it is fresh regardless of the assertion above.+ expect(getBeeperRealtimeState().lastPingAt).toBe(new Date(10_500).toISOString());+ // The watchdog still counted it: exactly one still-armed timer (the+ // ping's own re-arm via `noteFrame()`), not zero.+ expect(clock.runTimersWithDelay(SILENCE_TIMEOUT_MS)).toBe(1);++ beeperSocketEvents.off('state', onState);+ });++ it('reconnects with jitter inside the exponential window, never at a fixed cadence', async () => {+ await start();+ latest().handshake();++ random = 0; // bottom of the jitter window+ clock.runTimersWithDelay(SILENCE_TIMEOUT_MS);+ const [low] = clock.delaysFor((timer) => timer.ms !== SILENCE_TIMEOUT_MS);+ expect(low).toBe(500); // 1000ms base → [500, 1000]++ // Same attempt count, top of the window: a different delay, so two installs+ // (or two retries) cannot align.+ stopBeeperSocket();+ await start();+ latest().handshake();+ random = 0.999;+ clock.runTimersWithDelay(SILENCE_TIMEOUT_MS);+ const [high] = clock.delaysFor((timer) => timer.ms !== SILENCE_TIMEOUT_MS);+ expect(high).toBeGreaterThan(low);+ expect(high).toBeLessThanOrEqual(1000);+ });++ it('backs off exponentially while reconnects keep failing, and resets once one succeeds', async () => {+ await start();+ latest().handshake();+ random = 0; // pin the low bound of each window so the growth is readable++ const delays = [];+ // First trip is the watchdog; every retry after it dies before it opens.+ clock.runTimersWithDelay(SILENCE_TIMEOUT_MS);+ for (let attempt = 0; attempt < 4; attempt += 1) {+ const [delay] = clock.delaysFor((timer) => timer.ms !== SILENCE_TIMEOUT_MS);+ delays.push(delay);+ clock.runTimersWithDelay(delay); // fire the reconnect timer+ await flush();+ latest().fire('close', 1006); // the retry never got to `open`+ }+ expect(delays).toEqual([500, 1000, 2000, 4000]);+ expect(delays.every((delay) => delay <= 60_000)).toBe(true);++ // A connection that actually opens resets the ladder, so a long outage+ // followed by a brief blip does not inherit a minute-long delay.+ const [delay] = clock.delaysFor((timer) => timer.ms !== SILENCE_TIMEOUT_MS);+ clock.runTimersWithDelay(delay);+ await flush();+ latest().handshake();+ latest().fire('close', 1006);+ expect(clock.delaysFor((timer) => timer.ms !== SILENCE_TIMEOUT_MS)).toEqual([500]);+ });+});++describe('beeperSocket — sweep triggers', () => {+ beforeEach(() => {+ createdSockets.length = 0;+ sweeps.length = 0;+ armed = true;+ syncEnabled = true;+ random = 0.5;+ resolvedConfig = { baseUrl: 'http://127.0.0.1:23373', token: 'example-token' };+ vi.spyOn(console, 'warn').mockImplementation(() => {});+ vi.spyOn(console, 'log').mockImplementation(() => {});+ });+ afterEach(() => { stopBeeperSocket(); vi.restoreAllMocks(); });++ it('does not sweep on the first connection of the process — boot arms, it does not fire', async () => {+ await start();+ latest().handshake();+ await flush();+ expect(sweeps).toEqual([]);+ });++ it('sweeps once a RECONNECT is subscribed again, because nothing replays across the gap', async () => {+ await start();+ latest().handshake();++ latest().fire('close', 1006);+ const [delay] = clock.delaysFor((timer) => timer.ms !== SILENCE_TIMEOUT_MS);+ clock.runTimersWithDelay(delay);+ await flush();+ latest().handshake();+ await flush();++ expect(sweeps).toEqual(['socket-reconnect']);+ });++ it('sweeps on a seq gap — frames dropped while the socket still looked healthy', async () => {+ await start();+ latest().handshake();+ latest().fire('message', JSON.stringify({ type: 'message.upserted', seq: 4, ts: 1, chatID: 'chat-1', ids: ['m1'] }));+ latest().fire('message', JSON.stringify({ type: 'message.upserted', seq: 9, ts: 2, chatID: 'chat-1', ids: ['m2'] }));+ await flush();+ expect(sweeps).toEqual(['socket-seq-gap']);+ });++ it('does not sweep on a contiguous seq run', async () => {+ await start();+ latest().handshake();+ for (const seq of [2, 3, 4]) {+ latest().fire('message', JSON.stringify({ type: 'message.upserted', seq, ts: 1, chatID: 'chat-1', ids: ['m'] }));+ }+ await flush();+ expect(sweeps).toEqual([]);+ });++ it('sweeps when app.state RECOVERS from an actionable fault, but not on the way into one', async () => {+ await start();+ latest().handshake();+ const send = (state) => latest().fire('message', JSON.stringify({+ type: 'app.state.updated', seq: null, ts: 1, appState: { state },+ }));++ send('needs-login');+ await flush();+ expect(sweeps).toEqual([]);+ expect(getBeeperRealtimeState().appStateActionable).toBe(true);++ send('ready');+ await flush();+ expect(sweeps).toEqual(['socket-app-state-recovery']);+ expect(getBeeperRealtimeState().appStateActionable).toBe(false);+ });++ it('runs NO sweep on any of the three triggers while the ingestion toggle is off', async () => {+ // `isBeeperIngestionArmed()` (feature + token) is not the sweep's gate:+ // `settings.beeper.enabled` is, and `runBeeperSweep` does not check it+ // itself. With it off, a socket trigger must not write a single+ // conversation or message body to Postgres.+ syncEnabled = false;+ await start();+ latest().handshake();++ // 1. reconnect+ latest().fire('close', 1006);+ const [delay] = clock.delaysFor((timer) => timer.ms !== SILENCE_TIMEOUT_MS);+ clock.runTimersWithDelay(delay);+ await flush();+ latest().handshake();+ // 2. seq gap+ latest().fire('message', JSON.stringify({ type: 'message.upserted', seq: 4, ts: 1, chatID: 'chat-1', ids: ['m1'] }));+ latest().fire('message', JSON.stringify({ type: 'message.upserted', seq: 9, ts: 2, chatID: 'chat-1', ids: ['m2'] }));+ // 3. app.state recovery+ latest().fire('message', JSON.stringify({ type: 'app.state.updated', ts: 3, appState: { state: 'needs-login' } }));+ latest().fire('message', JSON.stringify({ type: 'app.state.updated', ts: 4, appState: { state: 'ready' } }));+ await flush();++ // `sweeps` is the mock's own per-test record: nothing reached the sweep.+ expect(sweeps).toEqual([]);+ });++ it('stops sweeping the moment the toggle is flipped off mid-session, without a restart', async () => {+ // The gate is re-read at every trigger, exactly as the scheduler factory+ // re-reads it on every tick.+ await start();+ latest().handshake();+ latest().fire('message', JSON.stringify({ type: 'message.upserted', seq: 4, ts: 1, chatID: 'chat-1', ids: ['m1'] }));+ latest().fire('message', JSON.stringify({ type: 'message.upserted', seq: 9, ts: 2, chatID: 'chat-1', ids: ['m2'] }));+ await flush();+ expect(sweeps).toEqual(['socket-seq-gap']);++ syncEnabled = false;+ latest().fire('message', JSON.stringify({ type: 'message.upserted', seq: 20, ts: 3, chatID: 'chat-1', ids: ['m3'] }));+ await flush();+ expect(sweeps).toEqual(['socket-seq-gap']);+ });+});++describe('beeperSocket — a closed Beeper Desktop, and a rejected token', () => {+ beforeEach(() => {+ createdSockets.length = 0;+ sweeps.length = 0;+ armed = true;+ syncEnabled = true;+ random = 0;+ resolvedConfig = { baseUrl: 'http://127.0.0.1:23373', token: 'example-token' };+ });+ afterEach(() => { stopBeeperSocket(); vi.restoreAllMocks(); });++ it('narrates the first few reconnect attempts, then only every tenth', async () => {+ // Beeper Desktop being closed reconnects forever by design — it will be+ // reopened — so the loop must not write a line a minute for the life of+ // the process.+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});+ vi.spyOn(console, 'error').mockImplementation(() => {});+ await start();++ latest().fire('close', 1006);+ for (let cycle = 0; cycle < 29; cycle += 1) {+ const [delay] = clock.delaysFor((timer) => timer.ms !== SILENCE_TIMEOUT_MS);+ clock.runTimersWithDelay(delay);+ await flush();+ latest().fire('close', 1006);+ }++ const lines = log.mock.calls.map(([line]) => String(line));+ const attempts = lines+ .filter((line) => line.includes('reconnecting in'))+ .map((line) => Number(line.match(/attempt (\d+)/)[1]));+ expect(attempts).toEqual([1, 2, 3, 10, 20, 30]);+ // 30 failed cycles, and the whole loop stays inside a handful of lines.+ expect(lines.length).toBeLessThanOrEqual(15);+ });++ it('stands down when Beeper rejects the token, instead of reconnecting forever', async () => {+ vi.spyOn(console, 'error').mockImplementation(() => {});+ vi.spyOn(console, 'log').mockImplementation(() => {});+ await start();++ latest().fire('unexpected-response', {}, { statusCode: 401 });++ const state = getBeeperRealtimeState();+ expect(state.state).toBe('down');+ expect(state.authRejected).toBe(true); // the settings card's remedy line+ expect(clock.timers.size).toBe(0); // no reconnect timer, no watchdog+ expect(createdSockets).toHaveLength(1);+ });++ it('keeps reconnecting for an upgrade failure that is not an auth rejection', async () => {+ vi.spyOn(console, 'error').mockImplementation(() => {});+ vi.spyOn(console, 'log').mockImplementation(() => {});+ await start();++ latest().fire('unexpected-response', {}, { statusCode: 503 });++ expect(getBeeperRealtimeState().authRejected).toBe(false);+ expect(getBeeperRealtimeState().state).toBe('connecting');+ expect(clock.delaysFor((timer) => timer.ms !== SILENCE_TIMEOUT_MS)).toEqual([500]);+ });+});++describe('beeperSocket — a connect() that rejects (an unreadable credential store)', () => {+ beforeEach(() => {+ createdSockets.length = 0;+ sweeps.length = 0;+ armed = true;+ syncEnabled = true;+ random = 0;+ resolvedConfig = { baseUrl: 'http://127.0.0.1:23373', token: 'example-token' };+ });+ afterEach(() => { stopBeeperSocket(); vi.restoreAllMocks(); });++ // Fork issue #1 (audit cluster 04, finding 2): a credential read that throws+ // — an unreadable vault, not merely an absent token, which resolves the+ // config with `token: null` and takes a different path entirely — used to+ // end the reconnect loop for the life of the process: the timer's own+ // `.catch()` only logged, so no further reconnect was ever scheduled, and+ // `getBeeperRealtimeState().state` stayed stuck reporting `reconnecting`+ // forever with nothing behind it.+ it('still schedules a reconnect after a rejected connect(), and a later successful connect() re-arms', async () => {+ vi.spyOn(console, 'error').mockImplementation(() => {});+ vi.spyOn(console, 'log').mockImplementation(() => {});+ await start();+ latest().handshake();++ // An ordinary drop starts a reconnect cycle; make the credential read+ // behind the NEXT attempt reject before it ever reaches the socket.+ latest().fire('close', 1006);+ vi.mocked(resolveBeeperConfig).mockRejectedValueOnce(new Error('Malformed vault ciphertext'));+ const [delay] = clock.delaysFor((timer) => timer.ms !== SILENCE_TIMEOUT_MS);+ clock.runTimersWithDelay(delay);+ await flush();++ // The rejected attempt never opened a socket, but the loop must not be+ // dead: the state still honestly says `reconnecting` (a real attempt IS+ // pending)...+ expect(createdSockets).toHaveLength(1);+ expect(getBeeperRealtimeState().state).toBe('reconnecting');+ // ...backed by an ACTUAL new reconnect timer — this is what the old code+ // failed to arm, leaving `reconnecting` reported with nothing behind it.+ const rescheduled = clock.delaysFor((timer) => timer.ms !== SILENCE_TIMEOUT_MS);+ expect(rescheduled.length).toBeGreaterThan(0);++ // The vault becomes readable again (or the token gets re-saved) before+ // the next attempt — the loop re-arms rather than staying stuck.+ clock.runTimersWithDelay(rescheduled[0]);+ await flush();+ latest().handshake();++ expect(getBeeperRealtimeState().state).toBe('connected');+ expect(createdSockets).toHaveLength(2);+ });++ // The other half of the same fix: `startBeeperSocket()`'s OWN `await+ // connect()` can reject too (the very first attempt, not a reconnect).+ // Left at `running: true` with nothing behind it, no later+ // `reconcileBeeperIngestion()` call could ever re-arm — `startBeeperSocket()`+ // declines outright whenever `running` is already true.+ it('resets running to false when the initial connect() rejects, so a later startBeeperSocket() call can retry', async () => {+ vi.spyOn(console, 'error').mockImplementation(() => {});+ vi.mocked(resolveBeeperConfig).mockRejectedValueOnce(new Error('Malformed vault ciphertext'));++ await start();+ expect(createdSockets).toHaveLength(0);++ // A later reconcile — the credential re-saved, a feature retoggled — must+ // get a genuine retry, not an immediate decline from a `running` flag+ // stuck true over a socket that was never actually opened.+ resolvedConfig = { baseUrl: 'http://127.0.0.1:23373', token: 'example-token' };+ expect(await start()).toBe(true);+ expect(createdSockets).toHaveLength(1);+ });+});++describe('beeperSocket — invalidation payloads carry no content', () => {+ beforeEach(() => {+ createdSockets.length = 0;+ sweeps.length = 0;+ armed = true;+ syncEnabled = true;+ random = 0.5;+ resolvedConfig = { baseUrl: 'http://127.0.0.1:23373', token: 'example-token' };+ vi.spyOn(console, 'log').mockImplementation(() => {});+ });+ afterEach(() => { stopBeeperSocket(); vi.restoreAllMocks(); });++ it('drops `entries` entirely — ids and kinds only, never bodies, names or handles', async () => {+ // `entries` is optional on ALL FOUR domain events, and when present it is+ // hydrated with the full message. Relaying it would put message content on+ // a Socket.IO channel; the browser refetches from the local mirror instead.+ const frame = {+ type: 'message.upserted',+ seq: 42,+ ts: '2026-05-06T20:20:12.497Z',+ chatID: 'chat-1',+ ids: ['msg-1'],+ entries: [{+ id: 'msg-1',+ text: 'secret message body',+ senderName: 'Alice Example',+ senderID: '[email protected]',+ }],+ };+ const emitted = toInvalidation(frame);+ expect(emitted).toEqual({+ kind: 'message.upserted', chatID: 'chat-1', ids: ['msg-1'], seq: 42, ts: '2026-05-06T20:20:12.497Z',+ });+ expect(JSON.stringify(emitted)).not.toContain('secret message body');+ expect(JSON.stringify(emitted)).not.toContain('Alice Example');+ expect(JSON.stringify(emitted)).not.toContain('example.com');+ });++ it('accepts both the epoch-ms and the ISO spelling of `ts`', () => {+ expect(toInvalidation({ type: 'chat.upserted', ts: 1739320000000, chatID: 'c', ids: [] }).ts)+ .toBe(new Date(1739320000000).toISOString());+ expect(toInvalidation({ type: 'chat.upserted', ts: 'not-a-date', chatID: 'c', ids: [] }).ts).toBeNull();+ });++ it('emits one invalidation per domain frame and nothing for control frames', async () => {+ const seen = [];+ const listener = (data) => seen.push(data);+ beeperSocketEvents.on('invalidate', listener);+ await start();+ latest().handshake();+ latest().fire('message', JSON.stringify({+ type: 'message.deleted', seq: 2, ts: 1, chatID: 'chat-1', ids: ['m1', 'm2'],+ }));+ beeperSocketEvents.off('invalidate', listener);++ expect(seen).toEqual([{ kind: 'message.deleted', chatID: 'chat-1', ids: ['m1', 'm2'], seq: 2, ts: new Date(1).toISOString() }]);+ });++ it('survives an unparseable frame without killing the connection', async () => {+ vi.spyOn(console, 'error').mockImplementation(() => {});+ await start();+ latest().handshake();+ latest().fire('message', 'not json at all');+ expect(getBeeperRealtimeState().state).toBe('connected');+ });+});diff --git a/server/services/beeperSocketEvents.js b/server/services/beeperSocketEvents.jsnew file mode 100644index 0000000000..820fce0a44--- /dev/null+++ b/server/services/beeperSocketEvents.js@@ -0,0 +1,18 @@+import { EventEmitter } from 'events';++/**+ * Leaf event bus for the Beeper realtime transport (#33, decided on #12).+ *+ * A standalone module for the same reason `instanceEvents.js` and+ * `imageGenEvents.js` are: `socket.js` subscribes to it at boot, and importing+ * `beeperSocket.js` there instead would drag the whole ingestion stack (the DB+ * pool, settings, the HTTP client) into every module that touches Socket.IO.+ *+ * Two events, both INVALIDATION-ONLY (#12 decision 3):+ * - `invalidate` — `{ kind, chatID, ids, seq, ts }`. Ids and kinds,+ * never message bodies, display names or handles. The browser refetches+ * from the PortOS mirror, which is the read path (#7).+ * - `state` — `{ state, lastEventAt, lastPingAt, ... }`, the transport+ * liveness snapshot the settings card's dot renders from.+ */+export const beeperSocketEvents = new EventEmitter();diff --git a/server/services/beeperStatus.js b/server/services/beeperStatus.jsnew file mode 100644index 0000000000..ec7995bd5d--- /dev/null+++ b/server/services/beeperStatus.js@@ -0,0 +1,231 @@+/**+ * Beeper status resolution for the Comms → Beeper status card (#30, fork+ * issue #1). Combines three things the card renders from:+ * - whether a token is configured (never the token itself — this module+ * resolves the vaulted credential store #31 through `resolveBeeperToken()`,+ * which DOES decrypt, specifically so a vault whose ciphertext cannot be+ * decrypted is noticed rather than reported as a healthy, connected+ * install (audit cluster 04, finding 1) — but never reads the decrypted+ * `token` field beyond the presence check itself);+ * - a liveness probe against the local Beeper Desktop API;+ * - the read-only account roster mirrored by fork issue #27's schema, so+ * the card renders something even with Beeper Desktop closed (accounts+ * survive from the last ingestion sweep, #32).+ *+ * Two flags stay distinct, per the fork issue #11 decision #30 carries+ * forward: the INSTANCE FEATURE (`instanceFeatureRegistry.js` `beeper`)+ * governs navigation; `settings.beeper.enabled` governs ingestion. This+ * module answers the connection/status question only.+ */+import { query } from '../lib/db.js';+import {+ probeBeeperInfo, getInfo, assertValidInfoResponse, BeeperApiError, resolveBeeperBaseUrl,+ hasRecentBeeperSuccess, RECENT_SUCCESS_WINDOW_MS,+} from './beeperClient.js';+import { getBeeperRealtimeState } from './beeperSocket.js';+import { getOutboxStatus } from './beeperOutbox.js';+import { resolveBeeperToken } from './beeperCredentials.js';+import { getBeeperSweepProgress } from './beeperSweepProgress.js';++const TOKEN_EXPIRY_WARNING_DAYS = 7;++// Expiry rides beside the token in the vault (#11 decision 10 — "stored beside+// the token and displayed without a network call"). There is no refresh grant,+// so `tokenExpired` is an actionable RE-CONNECT state, deliberately distinct+// from `tokenExpiringSoon`; a pasted no-expiry token (`tokenExpiresAt: null`)+// triggers neither, which is exactly why that path exists.+function tokenExpiryInfo(tokenExpiresAt) {+ if (typeof tokenExpiresAt !== 'string' || !tokenExpiresAt) {+ return { tokenExpiresAt: null, tokenExpiresInDays: null, tokenExpiringSoon: false, tokenExpired: false };+ }+ const expires = new Date(tokenExpiresAt);+ if (Number.isNaN(expires.getTime())) {+ return { tokenExpiresAt: null, tokenExpiresInDays: null, tokenExpiringSoon: false, tokenExpired: false };+ }+ const remainingMs = expires.getTime() - Date.now();+ const days = Math.ceil(remainingMs / (24 * 60 * 60 * 1000));+ return {+ tokenExpiresAt,+ tokenExpiresInDays: days,+ tokenExpiringSoon: days <= TOKEN_EXPIRY_WARNING_DAYS,+ tokenExpired: remainingMs <= 0,+ };+}++/**+ * The read-only account roster mirrored by fork issue #27's schema, so the+ * status card can render even with Beeper Desktop closed. Always an array —+ * an empty result is a trustworthy "no accounts synced yet", not a fault: the+ * ingestion sweep (#32) populates this table, so a fresh install sees `[]`+ * until its first sync pass completes.+ */+export async function listBeeperAccounts() {+ const result = await query(+ `SELECT account_id AS "accountId", network, display_name AS "displayName",+ status, bridge_id AS "bridgeId", last_seen_at AS "lastSeenAt"+ FROM beeper_accounts+ ORDER BY display_name ASC, account_id ASC`,+ );+ return Array.isArray(result?.rows) ? result.rows : [];+}++/**+ * Whether SOMETHING recently proved Beeper Desktop is actually up: a real API+ * call through `beeperClient.js`, or the realtime socket receiving a fresh+ * server ping (`beeperSocket.js`'s own ~10.5s-then-30s cadence). Fork issue+ * #61 decision 7 — paired with `RECENT_SUCCESS_WINDOW_MS` in `beeperClient.js`+ * so both signals share one window rather than each guessing its own.+ */+function hasRecentBeeperActivity() {+ if (hasRecentBeeperSuccess()) return true;+ const { lastPingAt } = getBeeperRealtimeState();+ if (!lastPingAt) return false;+ const pingedAt = new Date(lastPingAt).getTime();+ return Number.isFinite(pingedAt) && (Date.now() - pingedAt) <= RECENT_SUCCESS_WINDOW_MS;+}++/**+ * The full status payload the Comms → Beeper card renders from (#30). Never+ * throws — every sub-fetch degrades to its own "unknown" value so one failure+ * (a DB hiccup, Beeper Desktop closed) doesn't blank the whole card. Use+ * `checkBeeperConnection` below for an action that DOES throw a typed,+ * coded error (the card's "Retry" button on the unreachable state).+ *+ * `reachable` is a tri-state, never collapsed to a boolean: `true`/`false`+ * once probed, `null` when the probe was never attempted (no token+ * configured) — the absent-vs-empty sentinel from root AGENTS.md. `null`+ * must never render as offline; this function never lies and reports+ * `false` for a question it never asked. `probeState` ('ok' | 'slow' |+ * 'unreachable' | 'unknown') carries the finer-grained answer the card's+ * "slow" treatment reads from — see the timeout-vs-recent-success logic below.+ */+export async function getBeeperStatus() {+ // `resolveBeeperBaseUrl()`, never a raw `settings.beeper.baseUrl` read+ // (SEC-2): it re-applies the loopback-only gate `beeperSettingsSchema`+ // enforces on the PUT route, which a hand-edited `settings.json` can still+ // bypass on read. The probe and the payload's own `baseUrl` field both have+ // to report the SAME (validated) value the sweep and every other call+ // actually use.+ const resolvedBaseUrl = await resolveBeeperBaseUrl();+ // Deliberately NOT wrapped in a catch: an unreadable vault throws (#11+ // decision 8), and the card renders its "could not read status" branch+ // rather than telling a connected install to connect again. This has to be+ // `resolveBeeperToken()` (which decrypts the row), not a cheaper+ // presence-only read: a row whose ciphertext cannot be decrypted still has+ // a row, so a presence-only check can never notice a corrupt vault — which+ // is exactly how this used to report `tokenConfigured: true, reachable:+ // true` for a credential nobody could actually authenticate with. Never+ // reads `stored.token` beyond this line: only presence, source and expiry+ // ever reach the response below.+ const stored = await resolveBeeperToken();+ const credential = {+ tokenConfigured: Boolean(stored),+ tokenSource: stored?.tokenSource ?? null,+ tokenExpiresAt: stored?.tokenExpiresAt ?? null,+ // Granted scopes (fork issue #78) — an array of strings, `[]` when+ // unknown (a pasted token, or the legacy plaintext path). Read off+ // `resolveBeeperToken()` alongside source/expiry; never the token value.+ tokenScopes: Array.isArray(stored?.tokenScopes) ? stored.tokenScopes : [],+ };+ const expiry = tokenExpiryInfo(credential.tokenExpiresAt);++ const [probe, accountsResult] = await Promise.all([+ credential.tokenConfigured+ ? probeBeeperInfo({ baseUrl: resolvedBaseUrl })+ : Promise.resolve(null),+ listBeeperAccounts()+ .then((accounts) => ({ accounts, accountsError: null }))+ // A failed mirror read must not read as "no accounts mirrored yet" — that+ // is a legitimate, trustworthy empty result (see `listBeeperAccounts`+ // above), and a DB hiccup is not the same thing. `accounts: null` is the+ // absent-vs-empty sentinel: the card renders this as unknown, never as+ // zero accounts.+ .catch((err) => ({+ accounts: null,+ accountsError: err?.message || 'Could not read the mirrored account roster',+ })),+ ]);++ // Fork issue #61, decision 7. A probe TIMEOUT specifically (never a fast+ // refusal — `beeperClient.js` only sets `timedOut` on its own AbortController+ // firing) is ambiguous on its own: nothing distinguishes "briefly slow" from+ // "actually closed" by timing alone. Paired with something that recently+ // proved Beeper Desktop is up, it means "slow to answer this one bare check,"+ // not "gone" — `reachable` stays `true` and the card renders `slow` with the+ // latency instead of flipping to the unreachable/actionable-fault card. With+ // no recent activity (or for any other failure shape), a genuinely closed+ // Beeper Desktop still reaches `unreachable` on the very first probe — this+ // never delays that. `reachable: null` (no token, probe never attempted)+ // never reaches here at all, since `probe` is `null` in that case.+ let reachable = probe ? probe.reachable : null;+ let probeState = probe === null ? 'unknown' : (probe.reachable ? 'ok' : 'unreachable');+ if (probe && !probe.reachable && probe.timedOut && hasRecentBeeperActivity()) {+ reachable = true;+ probeState = 'slow';+ }++ return {+ tokenConfigured: credential.tokenConfigured,+ // 'oauth' | 'pasted' | 'legacy-settings' | null — provenance, never the+ // value.+ tokenSource: credential.tokenSource,+ // Fork issue #78: array of strings, `[]` when unknown (a pasted token+ // never carries scopes back from Beeper's own paste UI). Never the token+ // value itself — same provenance-only rule as `tokenSource` above.+ tokenScopes: credential.tokenScopes,+ baseUrl: resolvedBaseUrl,+ reachable,+ probeState,+ probeLatencyMs: probe?.latencyMs ?? null,+ lastProbeError: probe?.error ?? null,+ appVersion: probe?.info?.app?.version ?? null,+ ...expiry,+ // Transport liveness for the card's dot and its actionable-fault line+ // (#33): `connected | reconnecting | down`, plus the last frame and last+ // server ping. `appState` rides along because an actionable value+ // (`needs-login`, `needs-verification`, `needs-secrets`) is exactly what+ // the iMessage-shape card exists to surface — it is NEVER a gate, having+ // been measured reporting `initializing` for 105s on a working install.+ realtime: getBeeperRealtimeState(),+ // Outbound-send health (#36): the runaway breaker's state, and how many+ // sends are still awaiting confirmation. The breaker is the one fault here+ // that needs a human action, so it renders on the settings card the same+ // way an actionable transport fault does — never as a global banner.+ outbox: getOutboxStatus(),+ accounts: accountsResult.accounts,+ accountsError: accountsResult.accountsError,+ // Sweep visibility (#80): running/idle, started/finished, accounts done of+ // the total, chats and messages mirrored so far. Read from the standalone+ // `beeperSweepProgress.js` leaf module rather than `beeperSync.js` itself —+ // same reasoning as importing `beeperSocketEvents.js` instead of+ // `beeperSocket.js` above: a read-only status card has no business+ // dragging the whole sweep's DB/HTTP dependency graph in just to report a+ // few numbers.+ sweep: getBeeperSweepProgress(),+ };+}++/**+ * A live, uncached connectivity check — the card's "Retry" action on the+ * "token present, unreachable" state. Unlike `getBeeperStatus` (which always+ * resolves, via `probeBeeperInfo`'s own swallowed-error contract), this+ * THROWS a typed `BeeperApiError` so the route can map it to a real HTTP+ * status per fork-issue-#30-and-later's status-code contract instead of the+ * status route's flattened `lastProbeError` string.+ */+export async function checkBeeperConnection() {+ // Same reasoning as `getBeeperStatus()` above: `resolveBeeperToken()`+ // decrypts and so actually notices an unreadable vault, rather than reading+ // a row's mere presence and reporting a connected install as unconfigured.+ const stored = await resolveBeeperToken();+ if (!stored) {+ throw new BeeperApiError('Beeper access token is not configured', {+ status: 401, code: 'NOT_CONFIGURED', retryable: false,+ });+ }+ // `resolveBeeperBaseUrl()`, never a raw `settings.beeper.baseUrl` read — see+ // the same note on `getBeeperStatus` above (SEC-2).+ const info = await getInfo({ baseUrl: await resolveBeeperBaseUrl() });+ assertValidInfoResponse(info);+ return { reachable: true, info };+}diff --git a/server/services/beeperStatus.test.js b/server/services/beeperStatus.test.jsnew file mode 100644index 0000000000..10ed557f80--- /dev/null+++ b/server/services/beeperStatus.test.js@@ -0,0 +1,418 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('../lib/db.js', () => ({+ ensureSchema: vi.fn().mockResolvedValue(undefined),+ query: vi.fn(),+ withTransaction: vi.fn(),+}));+vi.mock('./settings.js', () => ({ getSettings: vi.fn() }));+// The realtime transport is a live long-lived socket; the status card only+// reads its snapshot, so the module is stubbed at that one function.+vi.mock('./beeperSocket.js', () => ({+ getBeeperRealtimeState: vi.fn(() => ({+ state: 'down', lastEventAt: null, lastPingAt: null, reconnectAttempts: 0, appState: null, appStateActionable: false, authRejected: false,+ })),+}));+// `beeperCredentials.js` runs FOR REAL here (against the mocked `query` and+// `vaultCrypto` below) — the #11-decision-8 guard this suite exists to prove+// ("an unreadable vault throws rather than reporting not-configured") lives+// inside that module, and mocking the module away (as this file used to) means+// the guard is never actually exercised.+vi.mock('../lib/vaultCrypto.js', () => ({+ ensureVaultKey: vi.fn().mockResolvedValue({ generated: false }),+ encryptValue: vi.fn(),+ decryptValue: vi.fn(),+}));+vi.mock('./beeperClient.js', async () => {+ const actual = await vi.importActual('./beeperClient.js');+ return { ...actual, probeBeeperInfo: vi.fn(), getInfo: vi.fn() };+});++import { query } from '../lib/db.js';+import { getSettings } from './settings.js';+import { decryptValue } from '../lib/vaultCrypto.js';+import { getBeeperRealtimeState } from './beeperSocket.js';+import {+ probeBeeperInfo, getInfo, BeeperApiError, __setLastBeeperSuccessAtForTests,+} from './beeperClient.js';+import { getBeeperStatus, checkBeeperConnection, listBeeperAccounts } from './beeperStatus.js';+import { getBeeperSweepProgress, updateBeeperSweepProgress, __resetBeeperSweepProgressForTests } from './beeperSweepProgress.js';++const DOWN_REALTIME_STATE = {+ state: 'down', lastEventAt: null, lastPingAt: null, reconnectAttempts: 0, appState: null, appStateActionable: false, authRejected: false,+};++// A placeholder that is obviously not a real credential (root AGENTS.md).+const TOKEN = 'example-beeper-token';+const CIPHERTEXT = 'v1:aXY=:dGFn:Y3Q=';++// `beeperCredentials.js` runs two different queries against the same mocked+// `query()` (the credential row, the account roster) — route each to its own+// fixture by sniffing the SQL text, the way a real Postgres client cannot.+function mockDb({ credentialRow = null, accountsRows = [], accountsError = null } = {}) {+ vi.mocked(query).mockImplementation(async (sql) => {+ const text = String(sql);+ if (text.includes('FROM beeper_credentials')) {+ return { rows: credentialRow ? [credentialRow] : [] };+ }+ if (text.includes('FROM beeper_accounts')) {+ if (accountsError) throw accountsError;+ return { rows: accountsRows };+ }+ return { rows: [] };+ });+}++const noCredential = (opts = {}) => mockDb({ credentialRow: null, ...opts });++const credential = ({+ tokenExpiresAt = null, tokenSource = 'oauth', scopes = '', ...opts+} = {}) => {+ vi.mocked(decryptValue).mockReturnValue(TOKEN);+ return mockDb({+ credentialRow: {+ token_enc: CIPHERTEXT, token_expires_at: tokenExpiresAt, scopes, source: tokenSource, client_id: '',+ },+ ...opts,+ });+};++const unreadableCredential = (opts = {}) => {+ vi.mocked(decryptValue).mockImplementation(() => { throw new Error('Malformed vault ciphertext'); });+ return mockDb({+ credentialRow: {+ token_enc: 'corrupt', token_expires_at: null, scopes: '', source: 'oauth', client_id: '',+ },+ ...opts,+ });+};++describe('listBeeperAccounts', () => {+ beforeEach(() => vi.clearAllMocks());++ it('returns the mirrored account roster', async () => {+ vi.mocked(query).mockResolvedValue({ rows: [{ accountId: 'acc1', network: 'whatsapp', displayName: 'Example', status: 'connected', bridgeId: 'b1', lastSeenAt: null }] });+ const accounts = await listBeeperAccounts();+ expect(accounts).toEqual([{ accountId: 'acc1', network: 'whatsapp', displayName: 'Example', status: 'connected', bridgeId: 'b1', lastSeenAt: null }]);+ });++ it('returns an empty array (a trustworthy "no accounts yet") rather than throwing on an unexpected result shape', async () => {+ vi.mocked(query).mockResolvedValue({});+ expect(await listBeeperAccounts()).toEqual([]);+ });+});++describe('getBeeperStatus', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ __setLastBeeperSuccessAtForTests(null);+ vi.mocked(getSettings).mockResolvedValue({});+ // `clearAllMocks()` resets call history, not a mock's return value —+ // reset this explicitly so the ping-recency test below can't leak its+ // override into a later test that assumes the default "never pinged" state.+ vi.mocked(getBeeperRealtimeState).mockReturnValue(DOWN_REALTIME_STATE);+ __resetBeeperSweepProgressForTests();+ });++ it('reports reachable:null (never false) and skips the probe entirely when no token is configured', async () => {+ noCredential();++ const status = await getBeeperStatus();++ expect(status.tokenConfigured).toBe(false);+ expect(status.reachable).toBeNull();+ expect(status.probeState).toBe('unknown');+ expect(status.tokenScopes).toEqual([]);+ expect(probeBeeperInfo).not.toHaveBeenCalled();+ });++ it('probes and reports reachable:true with account roster and app version when a token is configured and reachable', async () => {+ vi.mocked(getSettings).mockResolvedValue({ beeper: { baseUrl: 'http://127.0.0.1:23373' } });+ credential({ tokenSource: 'pasted', accountsRows: [{ accountId: 'acc1' }] });+ vi.mocked(probeBeeperInfo).mockResolvedValue({+ reachable: true, info: { app: { name: 'Beeper', version: '4.3.73' } }, error: null, timedOut: false, latencyMs: 8,+ });++ const status = await getBeeperStatus();++ expect(status.tokenConfigured).toBe(true);+ expect(status.reachable).toBe(true);+ expect(status.probeState).toBe('ok');+ expect(status.appVersion).toBe('4.3.73');+ expect(status.accounts).toEqual([{ accountId: 'acc1' }]);+ expect(status.accountsError).toBeNull();+ expect(probeBeeperInfo).toHaveBeenCalledWith({ baseUrl: 'http://127.0.0.1:23373' });+ // The transport snapshot the settings card's liveness dot renders from (#33).+ expect(status.realtime).toEqual(DOWN_REALTIME_STATE);+ });++ it('reports reachable:false with lastProbeError when a token is configured but unreachable', async () => {+ credential();+ vi.mocked(probeBeeperInfo).mockResolvedValue({+ reachable: false, info: null, error: 'connection refused', timedOut: false, latencyMs: 4,+ });++ const status = await getBeeperStatus();++ expect(status.reachable).toBe(false);+ expect(status.probeState).toBe('unreachable');+ expect(status.lastProbeError).toBe('connection refused');+ });++ // Fork issue #61, decision 7: a probe timeout with a recent successful+ // Beeper call is `slow`, not `unreachable` — `reachable` stays true.+ it('reports probeState:slow (reachable stays true) when a probe times out shortly after a real API success', async () => {+ credential();+ __setLastBeeperSuccessAtForTests(Date.now() - 5_000);+ vi.mocked(probeBeeperInfo).mockResolvedValue({+ reachable: false, info: null, error: 'Beeper request failed: aborted', timedOut: true, latencyMs: 3000,+ });++ const status = await getBeeperStatus();++ expect(status.reachable).toBe(true);+ expect(status.probeState).toBe('slow');+ expect(status.probeLatencyMs).toBe(3000);+ });++ it('reports probeState:slow when the realtime socket pinged recently, even with no recent API call', async () => {+ vi.mocked(getBeeperRealtimeState).mockReturnValue({+ ...DOWN_REALTIME_STATE, state: 'connected', lastPingAt: new Date(Date.now() - 10_000).toISOString(),+ });+ credential();+ vi.mocked(probeBeeperInfo).mockResolvedValue({+ reachable: false, info: null, error: 'timed out', timedOut: true, latencyMs: 3000,+ });++ const status = await getBeeperStatus();++ expect(status.reachable).toBe(true);+ expect(status.probeState).toBe('slow');+ });++ // A timeout with NO recent activity, and any non-timeout failure regardless+ // of recent activity, both stay `unreachable` — a genuinely closed Beeper+ // Desktop must still reach the unreachable card promptly.+ it('reports probeState:unreachable for a timeout with no recent Beeper activity', async () => {+ credential();+ vi.mocked(probeBeeperInfo).mockResolvedValue({+ reachable: false, info: null, error: 'timed out', timedOut: true, latencyMs: 3000,+ });++ const status = await getBeeperStatus();++ expect(status.reachable).toBe(false);+ expect(status.probeState).toBe('unreachable');+ });++ it('reports probeState:unreachable for a fast connection refusal even with a recent success', async () => {+ credential();+ __setLastBeeperSuccessAtForTests(Date.now() - 1_000);+ vi.mocked(probeBeeperInfo).mockResolvedValue({+ reachable: false, info: null, error: 'connection refused', timedOut: false, latencyMs: 3,+ });++ const status = await getBeeperStatus();++ expect(status.reachable).toBe(false);+ expect(status.probeState).toBe('unreachable');+ });++ // The bug this whole suite exists for: the credential layer used to be+ // checked only for a ROW's presence (`resolveBeeperTokenMeta`, which never+ // decrypts), so a vault whose ciphertext cannot be decrypted — the vault key+ // rotated or corrupted, the row otherwise intact — read as a perfectly+ // healthy, connected install instead of the documented "could not read+ // status" branch. Run against the REAL credentials layer (mocked only at+ // `query`/`vaultCrypto`), not a mock of `resolveBeeperTokenMeta` itself.+ it('propagates an unreadable vault rather than reporting tokenConfigured:true/reachable:true', async () => {+ unreadableCredential();++ await expect(getBeeperStatus()).rejects.toThrow(/vault ciphertext/);+ // The whole point: it never gets far enough to report a healthy probe.+ expect(probeBeeperInfo).not.toHaveBeenCalled();+ });++ // A failed accounts read must not collapse into "no accounts mirrored yet"+ // — that is `listBeeperAccounts`' own honest empty result, and a DB hiccup+ // reading it is a different, unknown state.+ it('reports a failed accounts read as unknown (accounts:null), distinct from a successful read of zero accounts', async () => {+ credential({ accountsError: new Error('db unavailable') });+ vi.mocked(probeBeeperInfo).mockResolvedValue({+ reachable: true, info: {}, error: null, timedOut: false, latencyMs: 5,+ });++ const failed = await getBeeperStatus();+ expect(failed.accounts).toBeNull();+ expect(failed.accountsError).toBe('db unavailable');++ credential({ accountsRows: [] });+ vi.mocked(probeBeeperInfo).mockResolvedValue({+ reachable: true, info: {}, error: null, timedOut: false, latencyMs: 5,+ });+ const empty = await getBeeperStatus();+ expect(empty.accounts).toEqual([]);+ expect(empty.accountsError).toBeNull();+ });++ it('warns when the stored token expiry is within 7 days', async () => {+ const soon = new Date(Date.now() + 3 * 24 * 60 * 60 * 1000).toISOString();+ credential({ tokenExpiresAt: soon });+ vi.mocked(probeBeeperInfo).mockResolvedValue({+ reachable: true, info: {}, error: null, timedOut: false, latencyMs: 5,+ });++ const status = await getBeeperStatus();+ expect(status.tokenExpiringSoon).toBe(true);+ });++ it('does not warn when the stored token expiry is far away', async () => {+ const far = new Date(Date.now() + 60 * 24 * 60 * 60 * 1000).toISOString();+ credential({ tokenExpiresAt: far });+ vi.mocked(probeBeeperInfo).mockResolvedValue({+ reachable: true, info: {}, error: null, timedOut: false, latencyMs: 5,+ });++ const status = await getBeeperStatus();+ expect(status.tokenExpiringSoon).toBe(false);+ });++ it('surfaces how the credential was obtained, and never anything else about it', async () => {+ credential({ tokenSource: 'pasted' });+ vi.mocked(probeBeeperInfo).mockResolvedValue({+ reachable: true, info: {}, error: null, timedOut: false, latencyMs: 5,+ });++ const status = await getBeeperStatus();+ expect(status.tokenSource).toBe('pasted');+ expect(Object.keys(status)).not.toContain('token');+ });++ // Fork issue #78: the credential row's `scopes` column reaches the status+ // payload as `tokenScopes`, the same array shape `beeperCredentials.js`+ // already parses it into — so a read-only grant is visible before a send+ // fails, and the raw token value never rides along with it.+ it('surfaces the granted OAuth scopes as an array, and never the token value', async () => {+ credential({ tokenSource: 'oauth', scopes: 'read write' });+ vi.mocked(probeBeeperInfo).mockResolvedValue({+ reachable: true, info: {}, error: null, timedOut: false, latencyMs: 5,+ });++ const status = await getBeeperStatus();+ expect(status.tokenScopes).toEqual(['read', 'write']);+ expect(JSON.stringify(status)).not.toContain(TOKEN);+ });++ // A pasted token (#11 decision 3) never carries scopes back from Beeper's+ // own paste UI — `beeperOAuth.js` stores `scopes: []` for that path — so the+ // status payload must report an honest empty array, never `null` or a+ // fabricated grant.+ it('reports an empty tokenScopes array for a pasted token', async () => {+ credential({ tokenSource: 'pasted', scopes: '' });+ vi.mocked(probeBeeperInfo).mockResolvedValue({+ reachable: true, info: {}, error: null, timedOut: false, latencyMs: 5,+ });++ const status = await getBeeperStatus();+ expect(status.tokenScopes).toEqual([]);+ });++ // There is no refresh grant, so an expired token is its own actionable+ // RE-CONNECT state, distinct from "expiring soon" and from any API failure.+ it('reports tokenExpired for a lapsed token, distinctly from tokenExpiringSoon', async () => {+ credential({ tokenExpiresAt: new Date(Date.now() - 60_000).toISOString() });+ vi.mocked(probeBeeperInfo).mockResolvedValue({+ reachable: true, info: {}, error: null, timedOut: false, latencyMs: 5,+ });++ const status = await getBeeperStatus();+ expect(status.tokenExpired).toBe(true);+ expect(status.tokenExpiringSoon).toBe(true);+ });++ it('leaves both expiry flags false for a no-expiry pasted token', async () => {+ credential({ tokenExpiresAt: null, tokenSource: 'pasted' });+ vi.mocked(probeBeeperInfo).mockResolvedValue({+ reachable: true, info: {}, error: null, timedOut: false, latencyMs: 5,+ });++ const status = await getBeeperStatus();+ expect(status.tokenExpired).toBe(false);+ expect(status.tokenExpiringSoon).toBe(false);+ expect(status.tokenExpiresAt).toBeNull();+ });++ // Sweep visibility (#80) — this fails on the old code, which had no `sweep`+ // key on the status payload at all.+ describe('sweep state', () => {+ it('reports an idle shape when no sweep has ever run', async () => {+ noCredential();++ const status = await getBeeperStatus();++ expect(status.sweep).toEqual({+ running: false, startedAt: null, finishedAt: null, reason: null,+ accountsDone: 0, accountsTotal: null, chats: 0, messages: 0,+ });+ });++ it('reports a running shape mid-sweep', async () => {+ noCredential();+ updateBeeperSweepProgress({+ running: true, startedAt: '2026-09-05T10:00:00.000Z', finishedAt: null, reason: 'scheduler',+ accountsDone: 2, accountsTotal: 9, chats: 40, messages: 812,+ });++ const status = await getBeeperStatus();++ expect(status.sweep).toMatchObject({+ running: true, accountsDone: 2, accountsTotal: 9, chats: 40, messages: 812,+ });+ });++ it('reports the last completed pass once a sweep has finished, not zeroed counts', async () => {+ noCredential();+ updateBeeperSweepProgress({+ running: false, startedAt: '2026-09-05T10:00:00.000Z', finishedAt: '2026-09-05T10:04:12.000Z',+ reason: 'manual', accountsDone: 9, accountsTotal: 9, chats: 210, messages: 4032,+ });++ const status = await getBeeperStatus();++ expect(status.sweep).toMatchObject({+ running: false, finishedAt: '2026-09-05T10:04:12.000Z', accountsDone: 9, accountsTotal: 9, chats: 210, messages: 4032,+ });+ });+ });+});++describe('checkBeeperConnection', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.mocked(getSettings).mockResolvedValue({});+ });++ it('throws a typed NOT_CONFIGURED BeeperApiError when no token is configured', async () => {+ noCredential();+ await expect(checkBeeperConnection()).rejects.toMatchObject({ code: 'NOT_CONFIGURED' });+ expect(getInfo).not.toHaveBeenCalled();+ });++ it('propagates a NETWORK_ERROR from a live probe', async () => {+ credential();+ vi.mocked(getInfo).mockRejectedValue(new BeeperApiError('Beeper request failed', { status: 0, code: 'NETWORK_ERROR', retryable: false }));+ await expect(checkBeeperConnection()).rejects.toMatchObject({ code: 'NETWORK_ERROR' });+ });++ it('throws MALFORMED_RESPONSE on an unexpected /v1/info shape', async () => {+ credential();+ vi.mocked(getInfo).mockResolvedValue({ unexpected: true });+ await expect(checkBeeperConnection()).rejects.toMatchObject({ code: 'MALFORMED_RESPONSE' });+ });++ it('resolves reachable:true on a well-shaped live probe', async () => {+ credential();+ vi.mocked(getInfo).mockResolvedValue({ app: { name: 'Beeper' }, server: { status: 'running' } });+ await expect(checkBeeperConnection()).resolves.toMatchObject({ reachable: true });+ });+});diff --git a/server/services/beeperSweepProgress.js b/server/services/beeperSweepProgress.jsnew file mode 100644index 0000000000..4d2dffdf41--- /dev/null+++ b/server/services/beeperSweepProgress.js@@ -0,0 +1,56 @@+/**+ * Beeper sweep progress — the leaf state `beeperStatus.js` and `beeperSync.js`+ * both touch (fork issue #80).+ *+ * A standalone module for the same reason `beeperSocketEvents.js` is one+ * (see that file's own docblock): the status route needs to know whether a+ * sweep is running without importing the sweep module itself, which would+ * drag the whole ingestion stack (the DB pool, the live HTTP client,+ * beeperTribe) into `beeperStatus.js` — a read-only status card has no+ * business loading any of that just to report a boolean and a few counts.+ *+ * One in-memory snapshot, process-wide — matches `eventScheduler`'s own+ * process-local state, and for the same reason nothing here needs to be+ * durable: a restart mid-sweep already loses the run itself, and the next+ * sweep starts a fresh pass regardless. `running` is the field every+ * consumer gates on; the rest describe the CURRENT pass while one is running,+ * and the LAST completed pass once it finishes — never reset back to zero the+ * instant a sweep ends, so the "Last synced" card still shows what actually+ * moved rather than blanking to zero.+ */++const initialSnapshot = () => ({+ running: false,+ startedAt: null,+ finishedAt: null,+ reason: null,+ accountsDone: 0,+ // `null`, not 0: the account roster isn't known until `refreshAccounts()`+ // resolves partway into the sweep, and "0 of 0" would misreport a sweep+ // that just hasn't counted its accounts yet as one with nothing to do.+ accountsTotal: null,+ chats: 0,+ messages: 0,+});++let snapshot = initialSnapshot();++/**+ * A read-only copy for a status payload. Always a fresh object — callers+ * must not mutate the result, and mutating it could never reach back into+ * the module's own state anyway.+ */+export function getBeeperSweepProgress() {+ return { ...snapshot };+}++/** Merge a partial update into the current snapshot; returns the new snapshot. */+export function updateBeeperSweepProgress(patch) {+ snapshot = { ...snapshot, ...patch };+ return snapshot;+}++/** Test-only reset, mirroring the reset helpers other leaf state modules expose. */+export function __resetBeeperSweepProgressForTests() {+ snapshot = initialSnapshot();+}diff --git a/server/services/beeperSync.db.test.js b/server/services/beeperSync.db.test.jsnew file mode 100644index 0000000000..fbfcbc558b--- /dev/null+++ b/server/services/beeperSync.db.test.js@@ -0,0 +1,339 @@+/**+ * Postgres-backed tests for the Beeper ingestion sweep (#32). The unit suite+ * (`beeperSync.test.js`) mocks the database, so the SQL itself — column names,+ * the `ON CONFLICT` targets, the FK ordering inside the transaction, and the+ * COALESCE guards that keep a body from being discarded by an unsend — is only+ * ever executed here, against real constraints.+ *+ * Covers:+ * - one sweep writes account, conversation, message, attachment and cursor+ * rows with the expected shapes;+ * - a re-observed message keeps its body and gains `unsent_at` (the source+ * tombstone is never a removal, #7/#13);+ * - the stored watermark stops the second sweep from re-paging an unchanged+ * chat;+ * - a sweep whose conversation is purged mid-flight commits no cursor row, so+ * a purge can never be silently undone by a resurrected watermark;+ * - a stored `is_sender` TRUE survives a later sweep whose payload omits the+ * optional field.+ *+ * `*.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 content.+ *+ * The credential path is the ONLY mocked part: the sweep resolves its token+ * through `beeperClient.resolveBeeperConfig`, which since #31 reads the+ * AES-256-GCM vault (`beeperCredentials.resolveBeeperToken`) with the legacy+ * plaintext `settings.beeper.token` as a read-only fallback. Both are stubbed+ * here so this suite never depends on whether `portos_test` happens to hold a+ * credential row, or on whether the vault key that encrypted it is still the+ * current one. Every other module in the graph — the Beeper client,+ * `beeperTribe`, `tribe`, `db` — is real.+ */+import {+ describe, it, expect, beforeAll, afterAll, vi,+} from 'vitest';+import { checkHealth, ensureSchema, close, query } from '../lib/db.js';+import { requireDbOrSkip } from '../lib/dbTestGate.js';++vi.mock('./settings.js', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...actual,+ getSettings: async () => ({ beeper: { baseUrl: 'http://127.0.0.1:23373' } }),+ };+});++vi.mock('./beeperCredentials.js', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...actual,+ resolveBeeperToken: async () => ({+ token: 'db-test-token', tokenExpiresAt: null, tokenSource: 'pasted',+ }),+ };+});++const { runBeeperSweep } = await import('./beeperSync.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/beeperSync.db.test', dbReady, skipReason);++const nonce = `beepersync-test-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;+const ACCOUNT_ID = nonce;+const CHAT_ID = `${nonce}-chat`;+const MESSAGE_ID = `${nonce}-msg`;++function jsonResponse(body) {+ return { ok: true, status: 200, text: async () => JSON.stringify(body) };+}++const ACCOUNTS = [{ accountID: ACCOUNT_ID, network: 'Example Net', user: { id: 'u-self', fullName: 'Example Owner' } }];+const BRIDGES = { items: [{ id: 'example-bridge', network: 'examplenet', status: 'connected', accounts: [{ accountID: ACCOUNT_ID }] }] };++function chatFixture(lastActivity) {+ return {+ id: CHAT_ID,+ accountID: ACCOUNT_ID,+ network: 'Example Net',+ title: 'Example Conversation',+ type: 'single',+ unreadCount: 2,+ isPinned: true,+ lastActivity,+ participants: {+ hasMore: false,+ total: 1,+ items: [{ id: `${nonce}-user`, fullName: 'Alice Example', username: 'alice_example' }],+ },+ };+}++function messageFixture({ isDeleted = false, text = 'Example message body' } = {}) {+ return {+ id: MESSAGE_ID,+ chatID: CHAT_ID,+ accountID: ACCOUNT_ID,+ senderID: `${nonce}-user`,+ senderName: 'Alice Example',+ timestamp: '2026-09-02T10:00:00.000Z',+ sortKey: '000000001',+ text: isDeleted ? '' : text,+ isDeleted: isDeleted || undefined,+ attachments: isDeleted ? [] : [{+ type: 'img',+ id: 'mxc://example.invalid/attachment-1',+ srcURL: '/tmp/decaying-local-path.png',+ mimeType: 'image/png',+ fileName: 'example.png',+ fileSize: 4096,+ size: { width: 640, height: 480 },+ }],+ };+}++/** Route a stubbed `fetch` for one sweep. Returns the recorded request URLs. */+function installFetch({ chats, messages }) {+ const urls = [];+ vi.stubGlobal('fetch', vi.fn(async (url) => {+ urls.push(url);+ const { pathname } = new URL(url);+ if (pathname === '/v1/accounts') return jsonResponse(ACCOUNTS);+ if (pathname === '/v1/bridges') return jsonResponse(BRIDGES);+ if (pathname === '/v1/chats') return jsonResponse(chats);+ if (/\/messages$/.test(pathname)) return jsonResponse(messages);+ throw new Error(`unexpected fetch: ${url}`);+ }));+ return urls;+}++beforeAll(async () => {+ if (!dbReady) return;+ await query('DELETE FROM beeper_accounts WHERE account_id = $1', [ACCOUNT_ID]).catch(() => {});+});++afterAll(async () => {+ vi.unstubAllGlobals();+ if (dbReady) {+ // Cascades through conversations / messages / attachments / participants /+ // cursors.+ await query('DELETE FROM beeper_accounts WHERE account_id = $1', [ACCOUNT_ID]).catch(() => {});+ await query('DELETE FROM tribe_people WHERE name = $1', ['Alice Example']).catch(() => {});+ await close();+ }+});++describe.skipIf(!runDb)('beeperSync against Postgres', () => {+ it('writes account, conversation, message, attachment and cursor rows in one sweep', async () => {+ installFetch({+ chats: { items: [chatFixture('2026-09-02T10:00:00.000Z')], hasMore: false },+ messages: { items: [messageFixture()], hasMore: false, newestCursor: 'cursor-after-first-sweep' },+ });++ const result = await runBeeperSweep({ reason: 'db-test' });+ expect(result).toMatchObject({ skipped: false, accounts: 1, chats: 1, messages: 1, failedAccounts: 0 });++ const account = await query('SELECT * FROM beeper_accounts WHERE account_id = $1', [ACCOUNT_ID]);+ expect(account.rows[0]).toMatchObject({+ network: 'Example Net', display_name: 'Example Owner', status: 'connected', bridge_id: 'example-bridge',+ });+ expect(account.rows[0].last_seen_at).toBeTruthy();++ const conversation = await query(+ 'SELECT * FROM beeper_conversations WHERE account_id = $1 AND source_chat_id = $2',+ [ACCOUNT_ID, CHAT_ID],+ );+ expect(conversation.rows[0]).toMatchObject({+ title: 'Example Conversation', type: 'single', is_group: false, is_pinned: true, unread_count: 2,+ });++ const message = await query('SELECT * FROM beeper_messages WHERE id = $1', [MESSAGE_ID]);+ expect(message.rows[0]).toMatchObject({+ conversation_id: conversation.rows[0].id,+ sender_id: `${nonce}-user`,+ body: 'Example message body',+ sort_key: '000000001',+ unsent_at: null,+ });++ const attachment = await query('SELECT * FROM beeper_attachments WHERE message_id = $1', [MESSAGE_ID]);+ expect(attachment.rows).toHaveLength(1);+ expect(attachment.rows[0]).toMatchObject({+ idx: 0, mxc_id: 'mxc://example.invalid/attachment-1', mime_type: 'image/png',+ file_name: 'example.png', width: 640, height: 480,+ });+ expect(String(attachment.rows[0].byte_length)).toBe('4096');+ // srcURL carries the spec's own "may be temporary" warning and has no+ // column here at all — nothing in the row may echo it.+ expect(JSON.stringify(attachment.rows[0])).not.toContain('decaying-local-path');++ const cursor = await query(+ 'SELECT * FROM beeper_sync_cursors WHERE account_id = $1 AND chat_id = $2',+ [ACCOUNT_ID, CHAT_ID],+ );+ expect(cursor.rows[0].cursor).toBe('cursor-after-first-sweep');+ expect(new Date(cursor.rows[0].last_activity).toISOString()).toBe('2026-09-02T10:00:00.000Z');++ const participant = await query(+ 'SELECT * FROM beeper_participants WHERE conversation_id = $1 AND source_user_id = $2',+ [conversation.rows[0].id, `${nonce}-user`],+ );+ expect(participant.rows[0]).toMatchObject({ display_name: 'Alice Example', handle: 'alice_example' });+ });++ it('keeps the body and stamps unsent_at when the source unsends the message', async () => {+ installFetch({+ chats: { items: [chatFixture('2026-09-03T10:00:00.000Z')], hasMore: false },+ messages: { items: [messageFixture({ isDeleted: true })], hasMore: false, newestCursor: 'cursor-after-second-sweep' },+ });++ await runBeeperSweep({ reason: 'db-test' });++ const message = await query('SELECT * FROM beeper_messages WHERE id = $1', [MESSAGE_ID]);+ // The archive keeps what the source forgot: a tombstone, never a removal.+ expect(message.rows[0].body).toBe('Example message body');+ expect(message.rows[0].unsent_at).toBeTruthy();+ });++ it('does not re-page a chat whose lastActivity has not passed the stored watermark', async () => {+ const urls = installFetch({+ chats: { items: [chatFixture('2026-09-03T10:00:00.000Z')], hasMore: false },+ messages: { items: [], hasMore: false },+ });++ const result = await runBeeperSweep({ reason: 'db-test' });++ expect(result).toMatchObject({ chats: 0, messages: 0 });+ expect(urls.filter((url) => /\/messages$/.test(new URL(url).pathname))).toHaveLength(0);+ });++ // `beeper_sync_cursors` has no FK onto `beeper_conversations`, so the purge's+ // own DELETE is the only thing that removes a cursor row. A sweep already in+ // flight when the purge commits used to re-insert one — a window with zero+ // messages still wrote it — and the resurrected watermark made the chat look+ // caught-up forever, so the purged history never came back.+ it('writes no cursor row for a conversation purged out from under the sweep', async () => {+ const purgedChatId = `${nonce}-chat-purged`;+ const purgedChat = {+ ...chatFixture('2026-09-04T10:00:00.000Z'),+ id: purgedChatId,+ // No participants: the roster upsert runs AFTER the message fetch and+ // carries its own FK onto the conversation, so a roster entry would fail+ // the chat before the commit under test is ever reached.+ participants: { hasMore: false, total: 0, items: [] },+ };+ // The message fetch is the seam. `sweepChat` has committed the conversation+ // by then and has not yet opened the commit transaction, so deleting the row+ // here reproduces a purge landing mid-sweep exactly.+ vi.stubGlobal('fetch', vi.fn(async (url) => {+ const { pathname } = new URL(url);+ if (pathname === '/v1/accounts') return jsonResponse(ACCOUNTS);+ if (pathname === '/v1/bridges') return jsonResponse(BRIDGES);+ if (pathname === '/v1/chats') return jsonResponse({ items: [purgedChat], hasMore: false });+ if (/\/messages$/.test(pathname)) {+ await query(+ 'DELETE FROM beeper_conversations WHERE account_id = $1 AND source_chat_id = $2',+ [ACCOUNT_ID, purgedChatId],+ );+ await query(+ 'DELETE FROM beeper_sync_cursors WHERE account_id = $1 AND chat_id = $2',+ [ACCOUNT_ID, purgedChatId],+ );+ return jsonResponse({ items: [], hasMore: false, newestCursor: 'cursor-after-purge' });+ }+ throw new Error(`unexpected fetch: ${url}`);+ }));++ await runBeeperSweep({ reason: 'db-test' });++ const conversation = await query(+ 'SELECT id FROM beeper_conversations WHERE account_id = $1 AND source_chat_id = $2',+ [ACCOUNT_ID, purgedChatId],+ );+ expect(conversation.rows).toHaveLength(0);+ const cursor = await query(+ 'SELECT * FROM beeper_sync_cursors WHERE account_id = $1 AND chat_id = $2',+ [ACCOUNT_ID, purgedChatId],+ );+ // Nothing resurrects the watermark, so the next sweep sees a never-swept+ // chat and mirrors it from scratch — what the purge confirmation promises.+ expect(cursor.rows).toHaveLength(0);+ });++ // `is_sender` is the only inbound/outbound signal a chat surface has —+ // `accounts[].user.id` differs from `senderID` on every network, so nothing+ // can be recomputed from the rest of the row. The unit suite can only assert+ // the upsert's SQL against a mocked client; the guarantee is a property of+ // the ROW after two sweeps, and that is what this pins.+ it('never downgrades a stored is_sender TRUE when a later sweep omits the field', async () => {+ const chatId = `${nonce}-chat-sender`;+ const messageId = `${nonce}-msg-sender`;+ const chatAt = (lastActivity) => ({+ ...chatFixture(lastActivity),+ id: chatId,+ participants: { hasMore: false, total: 0, items: [] },+ });+ const outbound = (withFlag) => ({+ id: messageId,+ chatID: chatId,+ accountID: ACCOUNT_ID,+ senderID: `${nonce}-self`,+ timestamp: '2026-09-05T10:00:00.000Z',+ sortKey: '000000002',+ text: 'Example outbound message',+ attachments: [],+ ...(withFlag ? { isSender: true } : {}),+ });++ installFetch({+ chats: { items: [chatAt('2026-09-05T10:00:00.000Z')], hasMore: false },+ messages: { items: [outbound(true)], hasMore: false, newestCursor: 'cursor-sender-1' },+ });+ await runBeeperSweep({ reason: 'db-test' });+ const first = await query('SELECT is_sender FROM beeper_messages WHERE id = $1', [messageId]);+ expect(first.rows[0].is_sender).toBe(true);++ // The field is optional on the inbound Message, and the normalizer reads an+ // omitted one as inbound — so a re-observation of the same message must not+ // flip a message the user actually sent onto the other side of the thread.+ installFetch({+ chats: { items: [chatAt('2026-09-06T10:00:00.000Z')], hasMore: false },+ messages: { items: [outbound(false)], hasMore: false, newestCursor: 'cursor-sender-2' },+ });+ await runBeeperSweep({ reason: 'db-test' });++ const second = await query('SELECT is_sender FROM beeper_messages WHERE id = $1', [messageId]);+ expect(second.rows[0].is_sender).toBe(true);+ });+});diff --git a/server/services/beeperSync.js b/server/services/beeperSync.jsnew file mode 100644index 0000000000..7996cfeb83--- /dev/null+++ b/server/services/beeperSync.js@@ -0,0 +1,880 @@+/**+ * 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+ * 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.+ */+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.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 --git a/server/services/beeperSync.test.js b/server/services/beeperSync.test.jsnew file mode 100644index 0000000000..b9fdd2dc54--- /dev/null+++ b/server/services/beeperSync.test.js@@ -0,0 +1,1113 @@+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 () => {+ 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')],+ hasMore: true,+ oldestCursor: 'chats-page-2',+ },+ { items: [chatRow('chat-quiet', '2026-07-01T00:00:00.000Z')], hasMore: true, oldestCursor: 'chats-page-3' },+ ],+ 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.+ 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 --git a/server/services/beeperTribe.db.test.js b/server/services/beeperTribe.db.test.jsnew file mode 100644index 0000000000..b15a6bd6b5--- /dev/null+++ b/server/services/beeperTribe.db.test.js@@ -0,0 +1,577 @@+/**+ * 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('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 --git a/server/services/beeperTribe.js b/server/services/beeperTribe.jsnew file mode 100644index 0000000000..33f969ea33--- /dev/null+++ b/server/services/beeperTribe.js@@ -0,0 +1,730 @@+/**+ * 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();+}++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.+ 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`,+ [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 --git a/server/services/beeperTribe.test.js b/server/services/beeperTribe.test.jsnew file mode 100644index 0000000000..457a830d62--- /dev/null+++ b/server/services/beeperTribe.test.js@@ -0,0 +1,775 @@+/**+ * 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: [] };+ 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 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('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 --git a/server/services/bootstrap.js b/server/services/bootstrap.jsindex fdbb0f7830..2527fe4cc4 100644--- a/server/services/bootstrap.js+++ b/server/services/bootstrap.js@@ -85,6 +85,9 @@ import { startPrivacyRecheckScheduler } from './privacyRecheckScheduler.js';import { startQuotaBurnScheduler } from './quotaBurnRunner.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';@@ -101,6 +104,7 @@ import { startOrphanShellGc } from './importerOrphanGc.js';import { startImageRefsGc } from './imageRefsGc.js';import { startImageCleanTmpGc } from './imageCleanTmpGc.js';import { startOrphanedPartialGc } from './orphanedPartialGc.js';+import { startBeeperAttachmentGc } from './beeperAttachmentGc.js';import { initBridge as initBrainMemoryBridge } from './brainMemoryBridge.js';import { initDrillCache } from './meatspacePostDrillCache.js';import { registerPostReminderSchedule } from './meatspacePostReminder.js';@@ -463,6 +467,26 @@ const startBackgroundServices = ({ spawnerReady, io }) => {// the signed-in history page in the managed browser when the user opts in via// Settings → YouTube (#2153).startYoutubeScheduler().catch(err => console.error(`❌ YouTube sync scheduler init failed: ${err.message}`));+ // Initialize the Beeper ingestion sweep — OFF by default; registers only when+ // the Beeper instance feature is on AND a token is configured, and then only+ // runs when `settings.beeper.enabled` is set (fork issue #32). Deliberately+ // NOT gated on Beeper's own `app.state`, which was measured reporting+ // `initializing` for 105s while every account was connected.+ startBeeperScheduler().catch(err => console.error(`❌ Beeper sync scheduler init failed: ${err.message}`));+ // Reconcile the outbox's two non-terminal states against the process that+ // just died: a row left in `sending` becomes a failed row the user can act on+ // (never an automatic resend — Beeper has no idempotency key), and a row left+ // in `awaiting-confirmation` gets its lookup re-armed, which reads and never+ // sends. Deliberately NOT on the ingestion gate above: a send stranded by a+ // restart is stranded whether or not scheduled sync is switched on, and it is+ // otherwise un-actionable forever, since nothing but this can move it.+ reconcileOutboxOnBoot().catch(err => console.error(`❌ Beeper outbox boot reconcile failed: ${err.message}`));+ // Arm the Beeper realtime transport on the SAME gate as the sweep above+ // (feature on + token present, never `app.state`) — one long-lived WebSocket+ // to the local Beeper Desktop whose only job is to make ingestion prompt+ // (fork issue #33). Correctness stays with the sweep: a reconnect, a `seq`+ // gap or an `app.state` recovery each ask it to run early.+ startBeeperSocket().catch(err => console.error(`❌ Beeper realtime transport init failed: ${err.message}`));// Periodically GC orphan zero-issue/zero-canon importer shells left by an// abandoned analyze (issue #727).startOrphanShellGc();@@ -479,6 +503,14 @@ const startBackgroundServices = ({ spawnerReady, io }) => {// like the other GCs — not part of the awaited warmStores pruneLegacyFiles// chain, so a large sweep cannot stall listen().startOrphanedPartialGc();+ // Periodically bound the Beeper attachment mirror: evict least-recently-viewed+ // bytes down to `settings.beeper.attachmentBudgetGb` (never evicting a file+ // Beeper can no longer re-supply, and never one the user locked with `keep`),+ // and heal the store both ways — orphan files no row points at, rows whose+ // file is gone, abandoned partials (fork issue #37). Housekeeping over local+ // bytes, so it is NOT gated on the ingestion toggle: turning scheduled sync+ // off does not make an over-budget mirror stop being over budget.+ startBeeperAttachmentGc();// Warm the catalog user-type registry from the user-type store (Postgres as of// #1001; the settings.json slice under the escape hatch) before any catalog// request can land, so user-defined types validate + mint ids immediately on@@ -918,6 +950,10 @@ export const registerShutdownHandlers = ({ io, httpServer, localHttpServer }) =>// Same reasoning for the hosted-session sweeper: a tick mid-shutdown would// emit into a namespace we are about to close.stopHostedSessionSweep();+ // And the Beeper transport: an open WebSocket is a live handle that would+ // hold the event loop past the last server close, and a reconnect firing+ // mid-shutdown would emit into a socket namespace we are about to close.+ stopBeeperSocket();// Diagnostic context for the shutdown trigger. ppid tells us whether the// signal came from PM2 (parent is the PM2 god process), a TTY (parent is// the user's shell), or some external orchestrator. pm_* env vars are setdiff --git a/server/services/sharing/beeperNeverFederates.test.js b/server/services/sharing/beeperNeverFederates.test.jsnew file mode 100644index 0000000000..e84a8b4c95--- /dev/null+++ b/server/services/sharing/beeperNeverFederates.test.js@@ -0,0 +1,129 @@+/**+ * Guard: Beeper conversation-mirror records must NEVER federate (#27, #28).+ *+ * The mirror holds full message bodies and attachment metadata pulled from+ * every connected network — exactly the shape of data the peer-sync PULL path+ * (`GET /api/peer-sync/record`) was never designed to carry safely. The store+ * decision (rationale on #7, ADR alongside it) settled this: these tables are+ * machine-local, full stop.+ *+ * Modeled directly on `privacyNeverFederates.test.js` (ADR+ * docs/decisions/2026-08-08-privacy-records-machine-local.md, #2148) — same+ * shape of guard, same reasoning. These assertions are cheap and blunt on+ * purpose: they match the string `beeper` broadly across each federation+ * surface, so a future `beeperConversation` or `beeperMessage` kind trips the+ * guard no matter what it is called.+ *+ * Every filter is paired with a floor on the list it filters. A federation+ * surface that collapsed to `[]` (a renamed export, a lazily-populated+ * registry read too early) would satisfy a bare `.filter(...).toEqual([])`+ * while guarding nothing, so each list must also still be recognizably+ * populated. Floors sit well under today's counts: they catch a collapse, not+ * ordinary growth or pruning of unrelated kinds.+ */++import { describe, it, expect } from 'vitest';+import { basename } from 'path';+import { PEER_SUBSCRIBABLE_KINDS } from './peerSyncShared.js';+import { PORTOS_SCHEMA_VERSIONS, NON_RECORD_SCHEMA_CATEGORIES } from '../../lib/schemaVersions.js';+import { beeperDdl } from '../../lib/db/schema/beeper.js';+import { mediaLibraryDirs } from './peerMediaLibrarySync.js';++const mentionsBeeper = (value) => /beeper/i.test(String(value));++// Columns that only exist to support cross-instance sync. A beeper table that+// grows one is either federating already or is being prepared to — both are+// the thing this design forbids. `sync_sequence` is the whole list: the Beeper+// schema uses `unsent_at` for the inbound source tombstone specifically so no+// exemption is needed here, and re-adding `deleted_at` would only make the+// guard fire on a future plain soft-delete column with no federation intent.+const FEDERATION_COLUMNS = ['sync_sequence'];++/**+ * A media-library walk entry that would carry a beeper directory to a peer.+ * The kind is matched broadly (a `beeperAttachments` kind trips it); the dir is+ * matched on its BASENAME only, because `mediaLibraryDirs()` entries are always+ * `<installRoot>/data/<kind>` — the last segment is the only part that names+ * the media kind. Matching any path segment instead would also fire on an+ * ANCESTOR directory that merely happens to be called `beeper` (a+ * `beeper/integration` worktree checked out under one), a false red that says+ * nothing about what federates. A `beeper`-prefixed basename still trips, so a+ * future `data/beeper-attachments` cannot slip in under a non-beeper kind.+ */+const namesBeeperMedia = ({ kind, dir }) => mentionsBeeper(kind)+ || /^beeper/i.test(basename(String(dir)));++/** The `CREATE TABLE beeper_*` statements, each a complete balanced string. */+const beeperCreateTableStatements = beeperDdl.filter(+ (stmt) => /CREATE TABLE IF NOT EXISTS beeper_/i.test(stmt),+);++describe('beeper conversation mirror never federates (#27)', () => {+ it('exposes no beeper kind to peer-sync subscriptions', () => {+ expect(PEER_SUBSCRIBABLE_KINDS.length).toBeGreaterThan(10);+ expect(PEER_SUBSCRIBABLE_KINDS.filter(mentionsBeeper)).toEqual([]);+ });++ it('declares no beeper wire-schema category', () => {+ expect(Object.keys(PORTOS_SCHEMA_VERSIONS).length).toBeGreaterThan(15);+ expect([...NON_RECORD_SCHEMA_CATEGORIES].length).toBeGreaterThan(1);+ expect(Object.keys(PORTOS_SCHEMA_VERSIONS).filter(mentionsBeeper)).toEqual([]);+ expect([...NON_RECORD_SCHEMA_CATEGORIES].filter(mentionsBeeper)).toEqual([]);+ });++ // Explicit timeout: the lazy import below resolves the whole dataSync+ // service graph INSIDE the test body (see privacyNeverFederates.test.js for+ // why that cost is paid here rather than at module load).+ it('declares no beeper dataSync snapshot category', async () => {+ const { getSupportedCategories } = await import('../dataSync.js');+ expect(getSupportedCategories().length).toBeGreaterThan(5);+ expect(getSupportedCategories().filter(mentionsBeeper)).toEqual([]);+ }, 30000);++ it('gives no beeper table a sync cursor column', () => {+ // Sanity: if the filter ever matches nothing the assertion below is+ // vacuous, so pin the table count we expect to be guarding. Eight since+ // #36 added `beeper_outbox` — an outbound message body is exactly as+ // machine-local as an inbound one, and the row also records that THIS+ // install sent it, which is nobody else's business either.+ expect(beeperCreateTableStatements).toHaveLength(8);+ for (const stmt of beeperCreateTableStatements) {+ const table = stmt.match(/beeper_[a-z_]+/i)?.[0];+ for (const column of FEDERATION_COLUMNS) {+ expect(`${table}:${stmt.includes(column)}`).toBe(`${table}:false`);+ }+ }+ });++ // The media-library manifest is the OTHER way `data/` bytes reach a peer: it+ // walks whole directories rather than record kinds, so no schema-version or+ // subscription guard above covers it. `mediaLibraryDirs()` is the list+ // `buildMediaLibraryManifest` walks, hence the list that decides what+ // crosses — asserting on it (not the exclude-pattern name map beside it,+ // which federates nothing) is what makes this guard real.+ it('carries no beeper directory into the media-library federation walk', () => {+ const dirs = mediaLibraryDirs();+ // Non-vacuity pin: image, video, audio, music.+ expect(dirs).toHaveLength(4);+ expect(dirs.filter(namesBeeperMedia)).toEqual([]);+ });++ // Bypass probe — proves the assertions above actually fire.+ it('the guard predicates reject a planted violation', () => {+ expect(['universe', 'beeperConversation'].filter(mentionsBeeper)).toEqual(['beeperConversation']);+ expect(+ ['CREATE TABLE IF NOT EXISTS beeper_conversations (id UUID, sync_sequence BIGINT)']+ .filter((s) => FEDERATION_COLUMNS.some((c) => s.includes(c))),+ ).toHaveLength(1);+ // The planted dir entry carries a NON-beeper kind, so only the basename+ // branch can catch it; the trailing entry pins that an ancestor named+ // `beeper` is not itself a violation.+ expect(+ [+ { kind: 'image', dir: '/data/images' },+ { kind: 'attachments', dir: '/data/beeper' },+ { kind: 'image', dir: '/beeper/integration/data/images' },+ ].filter(namesBeeperMedia),+ ).toEqual([{ kind: 'attachments', dir: '/data/beeper' }]);+ });+});diff --git a/server/services/socket.js b/server/services/socket.jsindex 8920a2a02b..1e0523466a 100644--- a/server/services/socket.js+++ b/server/services/socket.js@@ -10,6 +10,7 @@ import { scheduleEvents } from './automationScheduler.js';import { activityEvents } from './agentActivity.js';import { brainEvents } from './brainStorage.js';import { moltworldWsEvents } from './moltworldWs.js';+import { beeperSocketEvents } from './beeperSocketEvents.js';import { queueEvents } from './moltworldQueue.js';import { instanceEvents } from './instanceEvents.js';import { sanitizePeerForClient } from './instances.js';@@ -52,6 +53,10 @@ const agentSubscribers = new Set();const instanceSubscribers = new Set();// Store loop subscribersconst loopSubscribers = new Set();+// Store Beeper realtime subscribers (#33). Invalidation frames and transport+// liveness ONLY — see setupBeeperEventForwarding for why this may never be a+// global emit.+const beeperSubscribers = new Set();// Store io instance for broadcastinglet ioInstance = null;@@ -64,7 +69,7 @@ export function getIo() {return ioInstance;}-const ALL_SUBSCRIBER_SETS = [cosSubscribers, errorSubscribers, notificationSubscribers, agentSubscribers, instanceSubscribers, loopSubscribers];+const ALL_SUBSCRIBER_SETS = [cosSubscribers, errorSubscribers, notificationSubscribers, agentSubscribers, instanceSubscribers, loopSubscribers, beeperSubscribers];function broadcastToSet(set, event, data) {const disconnected = [];@@ -126,6 +131,7 @@ function registerSubscriptionHandlers(socket, _io) {registerSubscriber(socket, 'agents', agentSubscribers);registerSubscriber(socket, 'instances', instanceSubscribers);registerSubscriber(socket, 'loops', loopSubscribers);+ registerSubscriber(socket, 'beeper', beeperSubscribers);}function registerErrorHandlers(socket, io) {@@ -210,6 +216,7 @@ function setupEventForwarding() {setupProactiveSpeechForwarding();setupPersistentMindEventForwarding();setupCallStateEventForwarding();+ setupBeeperEventForwarding();}let persistentMindEventForwardingSetup = false;@@ -542,6 +549,25 @@ function setupUpdateEventForwarding() {// Broadcast to loop subscribers onlyfunction broadcastToLoops(event, data) { broadcastToSet(loopSubscribers, event, data); }+// Broadcast to Beeper subscribers only+function broadcastToBeeper(event, data) { broadcastToSet(beeperSubscribers, event, data); }++// Bridge the server's Beeper WebSocket onto Socket.IO (#33, decided on #12).+//+// THIS MUST NEVER BE `ioInstance.emit`. `peerSocketRelay.js` opens a Socket.IO+// CLIENT to every online peer, so a global emit crosses the wire to other+// installs — the boundary pinned at socket.test.js (#4694). Beeper message+// content is PII and machine-local (#7's ADR), so the frames here carry+// invalidation only: ids, kinds and transport liveness, never bodies, display+// names or handles. The browser refetches from the PortOS mirror.+let beeperForwardingSetup = false;+function setupBeeperEventForwarding() {+ if (beeperForwardingSetup) return;+ beeperForwardingSetup = true;+ beeperSocketEvents.on('invalidate', (data) => broadcastToBeeper('beeper:invalidate', data));+ beeperSocketEvents.on('state', (data) => broadcastToBeeper('beeper:realtime', data));+}+// Set up loop event forwarding (idempotent)let loopForwardingSetup = false;function setupLoopEventForwarding() {diff --git a/server/services/socket.test.js b/server/services/socket.test.jsindex cbeaa81642..9b65b614bd 100644--- a/server/services/socket.test.js+++ b/server/services/socket.test.js@@ -32,6 +32,12 @@ vi.mock('./agentActivity.js', () => ({ activityEvents: { on: vi.fn() } }));vi.mock('./brainStorage.js', () => ({ brainEvents: { on: vi.fn() } }));vi.mock('./moltworldWs.js', () => ({ moltworldWsEvents: { on: vi.fn() } }));vi.mock('./moltworldQueue.js', () => ({ queueEvents: { on: vi.fn() } }));+// The Beeper realtime bus is a real EventEmitter here — the relay boundary test+// below drives it directly to prove where its frames land (and where they don't).+vi.mock('./beeperSocketEvents.js', async () => {+ const { EventEmitter } = await import('events');+ return { beeperSocketEvents: new EventEmitter() };+});vi.mock('./instanceEvents.js', () => ({ instanceEvents: { on: vi.fn() } }));vi.mock('./review.js', () => ({ reviewEvents: { on: vi.fn() } }));vi.mock('./loops.js', () => ({ loopEvents: { on: vi.fn() } }));@@ -78,6 +84,7 @@ import { spawnPm2 } from './pm2.js';import { getAppById, notifyAppsChanged, resolvePm2HomeForProcess } from './apps.js';import { logAction } from './history.js';import { cosEvents } from './cosEvents.js';+import { beeperSocketEvents } from './beeperSocketEvents.js';import { mediaJobEvents } from './mediaJobQueue/index.js';import { audioGenEvents } from './audioGen/events.js';import { detachSocketSessions } from './shell.js';@@ -161,6 +168,8 @@ describe('socket.js — initSocket', () => {'instances:unsubscribe','loops:subscribe','loops:unsubscribe',+ 'beeper:subscribe',+ 'beeper:unsubscribe','error:recover','app:update','app:standardize',@@ -203,6 +212,35 @@ describe('socket.js — initSocket', () => {expect(Object.keys(socket.handlers)).not.toContain('build:identity');});+ // ===========================================================================+ // beeper:* — the Beeper relay boundary (#33, decided on #12)+ // ===========================================================================+ it('relays Beeper frames only to beeper subscribers, never through a global emit (#33)', () => {+ // Same federation boundary as the build:id test above, from the other+ // direction: `ioInstance.emit` reaches peerSocketRelay's client sockets, so+ // a global Beeper emit would push another install's frames onto this one's+ // wire. Message content is machine-local PII, so the relay is a subscriber+ // Set — and even the frames it carries are ids-only.+ const subscriber = makeSocket('beeper-sub');+ const bystander = makeSocket('beeper-bystander');+ createdSockets.push(subscriber, bystander);+ io.connect(subscriber);+ io.connect(bystander);+ subscriber.handlers['beeper:subscribe']();++ beeperSocketEvents.emit('invalidate', { kind: 'message.upserted', chatID: 'chat-1', ids: ['m1'], seq: 7, ts: null });+ beeperSocketEvents.emit('state', { state: 'connected', lastEventAt: null, lastPingAt: null });++ expect(subscriber.emitted.filter(([ev]) => ev === 'beeper:invalidate')).toHaveLength(1);+ expect(subscriber.emitted.filter(([ev]) => ev === 'beeper:realtime')).toHaveLength(1);+ // A connected socket that never subscribed sees nothing — that is what a+ // peer relay's socket looks like from here.+ expect(bystander.emitted.some(([ev]) => String(ev).startsWith('beeper:'))).toBe(false);+ // And nothing Beeper-shaped ever went through io.emit.+ expect(io.emitted.some(([ev]) => String(ev).startsWith('beeper:'))).toBe(false);+ expect(JSON.stringify(io.emitted)).not.toContain('chat-1');+ });+it('socket receives cos:subscribed ack after emitting cos:subscribe', () => {const socket = makeSocket('sub-1');io.connect(socket);diff --git a/server/services/syncSchedulers.parity.test.js b/server/services/syncSchedulers.parity.test.jsindex 737b7848bd..4232eb6ded 100644--- a/server/services/syncSchedulers.parity.test.js+++ b/server/services/syncSchedulers.parity.test.js@@ -1,28 +1,48 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-// Parity guard for the shared factory refactor (#4883): the four settings-gated+// Parity guard for the shared factory refactor (#4883): the settings-gated// ingestion schedulers now differ only in the options they hand// `createSyncScheduler`, which makes an id/emoji/source copy-paste swap between// domains invisible at a glance. Pin each domain's registered event here.+//+// Beeper (fork issue #32) is the fifth domain. It carries one extra gate the+// other four do not — the instance feature plus a configured token, checked+// before the factory ever runs — so `./beeperSync.js` is mocked with that gate+// already open here; `beeperScheduler.test.js` covers the closed cases.const scheduleMock = vi.fn();-vi.mock('./eventScheduler.js', () => ({ schedule: (...args) => scheduleMock(...args) }));+// `getEvent`/`cancel` are here for beeperScheduler's arm/disarm helpers, which+// ask the scheduler whether `beeper-sync` is already registered rather than+// keeping a second copy of that fact. Nothing is registered in this suite, so+// `getEvent` always answers null.+vi.mock('./eventScheduler.js', () => ({+ schedule: (...args) => scheduleMock(...args),+ getEvent: () => null,+ cancel: () => false,+}));const enabledConfig = async () => ({ enabled: true, intervalMinutes: 25 });vi.mock('./imessageSync.js', () => ({ getImessageConfig: enabledConfig, runSync: vi.fn() }));vi.mock('./signalSync.js', () => ({ getSignalConfig: enabledConfig, runSync: vi.fn() }));vi.mock('./spotifySync.js', () => ({ getSpotifyConfig: enabledConfig, runSync: vi.fn() }));vi.mock('./youtubeSync.js', () => ({ getYoutubeConfig: enabledConfig, runSync: vi.fn() }));+vi.mock('./beeperSync.js', () => ({+ getBeeperSyncConfig: enabledConfig,+ isBeeperIngestionArmed: async () => true,+ runBeeperSweep: vi.fn(),+}));const { startImessageScheduler } = await import('./imessageScheduler.js');const { startSignalScheduler } = await import('./signalScheduler.js');const { startSpotifyScheduler } = await import('./spotifyScheduler.js');const { startYoutubeScheduler } = await import('./youtubeScheduler.js');+const { startBeeperScheduler } = await import('./beeperScheduler.js');const DOMAINS = [{ name: 'iMessage', start: startImessageScheduler, id: 'imessage-sync', source: 'imessageScheduler', icon: '💬', label: 'iMessage' },{ name: 'Signal', start: startSignalScheduler, id: 'signal-sync', source: 'signalScheduler', icon: '🔒', label: 'Signal' },{ name: 'Spotify', start: startSpotifyScheduler, id: 'spotify-sync', source: 'spotifyScheduler', icon: '🎧', label: 'Spotify' },{ name: 'YouTube', start: startYoutubeScheduler, id: 'youtube-sync', source: 'youtubeScheduler', icon: '📺', label: 'YouTube' },+ { name: 'Beeper', start: startBeeperScheduler, id: 'beeper-sync', source: 'beeperScheduler', icon: '🫧', label: 'Beeper' },];beforeEach(() => {@@ -41,6 +61,10 @@ describe.each(DOMAINS)('$name sync scheduler', ({ start, id, source, icon, labelconst [event] = scheduleMock.mock.calls[0];expect(event.id).toBe(id);expect(event.metadata).toEqual({ source });+ // 'interval' means the first run lands one interval AFTER registration:+ // no ingestion sweep fires at boot, for any domain.+ expect(event.type).toBe('interval');+ expect(event.intervalMs).toBe(25 * 60 * 1000);expect(logs).toContain(`${icon} ${label} sync scheduler: registered every 25min`);});});diff --git a/server/services/tribeIdentities.js b/server/services/tribeIdentities.jsnew file mode 100644index 0000000000..107d29ee31--- /dev/null+++ b/server/services/tribeIdentities.js@@ -0,0 +1,172 @@+/**+ * 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();+}++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;+}diff --git a/server/vitest.config.db.js b/server/vitest.config.db.jsindex 9b61ebd27c..d7653c01fb 100644--- a/server/vitest.config.db.js+++ b/server/vitest.config.db.js@@ -32,6 +32,10 @@ export const DB_TEST_INCLUDE = ['services/providerGraphStore.db.test.js','services/catalogCanonProjection.test.js','services/catalogRefResolver.test.js',+ 'lib/db/schema/beeper.db.test.js',+ 'services/beeperConversations.db.test.js',+ 'services/beeperTribe.db.test.js',+ 'services/beeperSync.db.test.js','services/creativeDirector/projectsDB.test.js','services/musicVideo/projectsDB.test.js','routes/catalog.test.js',