Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: open new direct Beeper conversations without sending a message (#9985)

[._.]/ Adam Eivyfd40b0912f3e
diff --git a/client/src/components/messages/BeeperTab.jsx b/client/src/components/messages/BeeperTab.jsx
index 92316d0b48..f5f901095a 100644
--- a/client/src/components/messages/BeeperTab.jsx
+++ b/client/src/components/messages/BeeperTab.jsx
@@ -92,6 +92,7 @@ export default function BeeperTab() {
// as it goes (see beeperSync.js's `emitSweepInvalidation`).
const [sweep, setSweep] = useState(null);
const [tokenConfigured, setTokenConfigured] = useState(false);
+ const [accounts, setAccounts] = useState([]);
// Seeded from the page, not from the settings drawer: `beeper:subscribe`
// does not push the current transport state, and the drawer's own status
@@ -107,6 +108,7 @@ export default function BeeperTab() {
setBreaker(status?.outbox?.breaker || null);
setSweep(status?.sweep || null);
setTokenConfigured(status?.tokenConfigured === true);
+ setAccounts(Array.isArray(status?.accounts) ? status.accounts : []);
})
.catch(() => {});
}, [seedRealtime, mountedRef]);
@@ -157,6 +159,7 @@ export default function BeeperTab() {
breaker={breaker}
sweep={sweep}
tokenConfigured={tokenConfigured}
+ accounts={accounts}
onOpenSettings={() => setSettingsParam('1')}
/>
diff --git a/client/src/components/messages/BeeperTab.test.jsx b/client/src/components/messages/BeeperTab.test.jsx
index 66ca3f1ac6..133f27f7b1 100644
--- a/client/src/components/messages/BeeperTab.test.jsx
+++ b/client/src/components/messages/BeeperTab.test.jsx
@@ -60,6 +60,7 @@ const api = vi.hoisted(() => ({
// 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(() => ({
+ createBeeperConversation: vi.fn(),
listOutboxEntries: vi.fn(),
createOutboxEntry: vi.fn(),
sendOutboxEntry: vi.fn(),
@@ -1763,3 +1764,21 @@ it('reopens a shared Later URL with search and unread filters', async () => {
));
expect(screen.getByRole('button', { name: 'Later' })).toHaveAttribute('aria-pressed', 'true');
});
+
+it('opens a new direct conversation from the surface and navigates to its mirrored thread', async () => {
+ api.getBeeperStatus.mockResolvedValue({
+ tokenConfigured: true, accounts: [{ accountId: 'example-account', displayName: 'Example network' }],
+ });
+ apiBeeper.createBeeperConversation.mockResolvedValue({ id: CONV_A });
+ api.getBeeperConversation.mockResolvedValue(conversation());
+ api.getBeeperMessages.mockResolvedValue({ messages: [], nextCursor: null });
+ renderTab();
+ fireEvent.click(await screen.findByRole('button', { name: 'New conversation' }));
+ fireEvent.change(screen.getByLabelText('Recipient ID'), { target: { value: 'recipient-example' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Open conversation' }));
+ await waitFor(() => expect(api.getBeeperConversation).toHaveBeenCalledWith(CONV_A, { silent: true }));
+ expect(screen.queryByLabelText('Recipient ID')).toBeNull();
+ expect(apiBeeper.createBeeperConversation).toHaveBeenCalledWith({
+ accountId: 'example-account', participantId: 'recipient-example',
+ }, { silent: true });
+});
diff --git a/client/src/components/messages/beeper/BeeperChatSurface.jsx b/client/src/components/messages/beeper/BeeperChatSurface.jsx
index 2df6a30ba9..545c763d94 100644
--- a/client/src/components/messages/beeper/BeeperChatSurface.jsx
+++ b/client/src/components/messages/beeper/BeeperChatSurface.jsx
@@ -6,6 +6,7 @@ import {
} from 'lucide-react';
import NetworkLogo, { networkLabel } from './BeeperNetworkLogo';
import BeeperThread from './BeeperThread';
+import BeeperNewConversation from './BeeperNewConversation';
import ConnectionStatusDot from '../../ui/ConnectionStatusDot';
import toast from '../../ui/Toast';
import useMounted from '../../../hooks/useMounted';
@@ -30,8 +31,8 @@ import * as api from '../../../services/api';
* - **The rail includes each network the MIRROR holds and saved scopes.**
* Saved scopes retain named filters in machine-local settings.
* - **`Archive` and `Low priority` are wired**, because `isArchived` and
- * `isLowPriority` are real fields on every chat row. Requests, Later and
- * new conversation are omitted until they work (#9985) — an inert control
+ * `isLowPriority` are real fields on every chat row. Requests is omitted
+ * until its source state can be mirrored (#9985) — 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
@@ -48,8 +49,7 @@ import * as api from '../../../services/api';
* rendered over the newer one.
*/
-// Fixed system scopes. Requests and
-// new conversation are omitted until implemented
+// Fixed system scopes. Requests is omitted until implemented
// (tracked in the Beeper enhancements issue, #9985).
const SCOPE_EVENTS = ['beeper:invalidate'];
const SYSTEM_SCOPES = [
@@ -355,7 +355,7 @@ function ConversationRow({ conversation, unified, selected, onSelect }) {
export default function BeeperChatSurface({
conversationId = null, realtime = null, invalidationSeq = 0, invalidationFrames = null, breaker = null,
- sweep = null, tokenConfigured = false, onOpenSettings,
+ sweep = null, tokenConfigured = false, accounts = [], onOpenSettings,
}) {
const navigate = useNavigate();
const mountedRef = useMounted();
@@ -377,6 +377,7 @@ export default function BeeperChatSurface({
const searchRaw = searchParams.get('q') ?? savedScope?.filters.search ?? '';
const search = searchRaw.trim();
const [searchOpen, setSearchOpen] = useState(Boolean(search));
+ const [creatingConversation, setCreatingConversation] = useState(false);
const setSavedScopes = scopesResource.updateData;
const [scopeEditor, setScopeEditor] = useState(null);
const [scopeName, setScopeName] = useState('');
@@ -956,6 +957,13 @@ export default function BeeperChatSurface({
>
<Search size={15} />
</button>
+ {tokenConfigured && accounts.length > 0 && (
+ <button type="button" aria-label="New conversation" title="New conversation"
+ onClick={() => setCreatingConversation(true)}
+ className="inline-flex min-h-[44px] min-w-[44px] items-center justify-center rounded text-gray-500 hover:text-white">
+ <Plus size={15} />
+ </button>
+ )}
<button
type="button"
onClick={() => setParam('unread', unreadOnly ? (savedScope ? '0' : null) : '1')}
@@ -978,6 +986,11 @@ export default function BeeperChatSurface({
</button>
</div>
+ {creatingConversation && (
+ <BeeperNewConversation accounts={accounts} onCancel={() => setCreatingConversation(false)}
+ onCreated={(id) => { setCreatingConversation(false); navigate(`/messages/beeper/${encodeURIComponent(id)}`); }} />
+ )}
+
{scopeEditor && (
<form className="space-y-2 border-b border-port-border p-3" onSubmit={async (event) => {
event.preventDefault();
diff --git a/client/src/components/messages/beeper/BeeperNewConversation.jsx b/client/src/components/messages/beeper/BeeperNewConversation.jsx
new file mode 100644
index 0000000000..637f664e49
--- /dev/null
+++ b/client/src/components/messages/beeper/BeeperNewConversation.jsx
@@ -0,0 +1,64 @@
+import { useRef, useState } from 'react';
+import { createBeeperConversation } from '../../../services/apiBeeper';
+import useMounted from '../../../hooks/useMounted';
+
+export default function BeeperNewConversation({ accounts, onCreated, onCancel }) {
+ const [accountId, setAccountId] = useState(accounts[0]?.accountId || '');
+ const [participantId, setParticipantId] = useState('');
+ const [pending, setPending] = useState(false);
+ const [error, setError] = useState(null);
+ const inFlight = useRef(false);
+ const mounted = useMounted();
+ const accountExists = accounts.some((account) => account.accountId === accountId);
+
+ const submit = async (event) => {
+ event.preventDefault();
+ if (inFlight.current || !accountExists || !participantId.trim()) return;
+ inFlight.current = true;
+ setPending(true);
+ setError(null);
+ const result = await createBeeperConversation(
+ { accountId, participantId: participantId.trim() }, { silent: true },
+ ).catch((err) => {
+ if (mounted.current) setError(err?.message || 'Could not create conversation');
+ return null;
+ });
+ inFlight.current = false;
+ if (!mounted.current) return;
+ setPending(false);
+ if (result?.id) onCreated(result.id);
+ else if (result) setError('Beeper did not return a conversation. Sync before trying again.');
+ };
+
+ return (
+ <form onSubmit={submit} className="space-y-2 border-b border-port-border p-3">
+ <h3 className="text-sm font-medium">New conversation</h3>
+ <label htmlFor="beeper-new-account" className="block text-xs">Account</label>
+ <select id="beeper-new-account" value={accountId} disabled={pending}
+ onChange={(event) => setAccountId(event.target.value)}
+ className="w-full rounded border border-port-border bg-port-bg p-2 text-sm">
+ {accounts.map((account) => (
+ <option key={account.accountId} value={account.accountId}>
+ {account.displayName || account.network || account.accountId}
+ </option>
+ ))}
+ </select>
+ <label htmlFor="beeper-new-recipient" className="block text-xs">Recipient ID</label>
+ <input id="beeper-new-recipient" value={participantId} required maxLength={500} disabled={pending}
+ onChange={(event) => setParticipantId(event.target.value)}
+ className="w-full rounded border border-port-border bg-port-bg p-2 text-sm" />
+ <p className="text-xs text-gray-400">
+ Use the recipient’s user ID for this network. Opens a direct chat without sending a message.
+ Networks requiring a first message may reject creation.
+ </p>
+ {error && <p role="alert" className="text-xs text-port-error">{error}</p>}
+ <div className="flex flex-wrap gap-2">
+ <button type="submit" disabled={pending || !accountExists || !participantId.trim()}
+ className="min-h-[44px] rounded border border-port-border px-3 text-sm">
+ {pending ? 'Opening…' : 'Open conversation'}
+ </button>
+ <button type="button" disabled={pending} onClick={onCancel} className="min-h-[44px] px-3 text-sm">Cancel</button>
+ </div>
+ </form>
+ );
+}
diff --git a/client/src/components/messages/beeper/BeeperNewConversation.test.jsx b/client/src/components/messages/beeper/BeeperNewConversation.test.jsx
new file mode 100644
index 0000000000..eaa261dedb
--- /dev/null
+++ b/client/src/components/messages/beeper/BeeperNewConversation.test.jsx
@@ -0,0 +1,38 @@
+import { render, screen, fireEvent, waitFor, cleanup } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import BeeperNewConversation from './BeeperNewConversation';
+import { createBeeperConversation } from '../../../services/apiBeeper';
+
+vi.mock('../../../services/apiBeeper', () => ({ createBeeperConversation: vi.fn() }));
+const accounts = [{ accountId: 'example-account', displayName: 'Example network' }];
+beforeEach(() => vi.clearAllMocks());
+afterEach(cleanup);
+
+describe('new Beeper conversation', () => {
+ it('opens the returned mirror identity and submits no message content', async () => {
+ const onCreated = vi.fn();
+ createBeeperConversation.mockResolvedValue({ id: 'mirror-chat' });
+ render(<BeeperNewConversation accounts={accounts} onCreated={onCreated} onCancel={vi.fn()} />);
+ fireEvent.change(screen.getByLabelText('Recipient ID'), { target: { value: ' recipient-example ' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Open conversation' }));
+ await waitFor(() => expect(onCreated).toHaveBeenCalledWith('mirror-chat'));
+ expect(createBeeperConversation).toHaveBeenCalledWith({
+ accountId: 'example-account', participantId: 'recipient-example',
+ }, { silent: true });
+ });
+
+ it('keeps a failed creation visible and guards repeated submits while pending', async () => {
+ let reject;
+ createBeeperConversation.mockReturnValue(new Promise((_resolve, rejectRequest) => { reject = rejectRequest; }));
+ const onCreated = vi.fn();
+ render(<BeeperNewConversation accounts={accounts} onCreated={onCreated} onCancel={vi.fn()} />);
+ fireEvent.change(screen.getByLabelText('Recipient ID'), { target: { value: 'recipient-example' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Open conversation' }));
+ fireEvent.submit(screen.getByRole('button', { name: 'Opening…' }).closest('form'));
+ expect(createBeeperConversation).toHaveBeenCalledTimes(1);
+ reject(new Error('Network requires a first message'));
+ expect(await screen.findByRole('alert')).toHaveTextContent('Network requires a first message');
+ expect(onCreated).not.toHaveBeenCalled();
+ expect(screen.getByLabelText('Recipient ID')).toHaveValue('recipient-example');
+ });
+});
diff --git a/client/src/services/apiBeeper.js b/client/src/services/apiBeeper.js
index dee17e1783..cde3366998 100644
--- a/client/src/services/apiBeeper.js
+++ b/client/src/services/apiBeeper.js
@@ -181,3 +181,6 @@ export const updateBeeperScope = (id, scope, options = {}) => request(`/beeper/s
export const deleteBeeperScope = (id, options = {}) => request(`/beeper/scopes/${encodeURIComponent(id)}`, {
method: 'DELETE', ...options,
});
+
+export const createBeeperConversation = (input, options = {}) =>
+ request('/beeper/conversations', { ...options, method: 'POST', body: JSON.stringify(input) });
diff --git a/server/routes/beeper.js b/server/routes/beeper.js
index ec827a7107..4eab88d048 100644
--- a/server/routes/beeper.js
+++ b/server/routes/beeper.js
@@ -15,7 +15,7 @@ import {
} 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 { runBeeperSweep, createBeeperConversation } from '../services/beeperSync.js';
import {
clearOutboxBreaker, createOutboxEntry, discardOutboxEntry, reconcileOutboxEntry, listOutboxEntries, sendOutboxEntry,
} from '../services/beeperOutbox.js';
@@ -248,6 +248,17 @@ const conversationParamsSchema = z.object({ id: z.string().guid() });
const archiveSchema = z.object({ archived: z.boolean() }).strict();
const lowPrioritySchema = z.object({ lowPriority: z.boolean() }).strict();
+const createConversationSchema = z.object({
+ accountId: z.string().trim().min(1).max(200),
+ participantId: z.string().trim().min(1).max(500),
+}).strict();
+
+router.post('/conversations', asyncHandler(async (req, res) => {
+ const input = validateRequest(createConversationSchema, req.body);
+ const result = await createBeeperConversation(input).catch((err) => { throw mapBeeperError(err); });
+ res.status(201).json(result);
+}));
+
// 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.
diff --git a/server/routes/beeper.test.js b/server/routes/beeper.test.js
index 161b445c86..a5d2c0d1f0 100644
--- a/server/routes/beeper.test.js
+++ b/server/routes/beeper.test.js
@@ -16,7 +16,7 @@ vi.mock('../services/beeperOAuth.js', () => ({
connectWithPastedToken: vi.fn(),
disconnectBeeper: vi.fn(),
}));
-vi.mock('../services/beeperSync.js', () => ({ runBeeperSweep: vi.fn() }));
+vi.mock('../services/beeperSync.js', () => ({ runBeeperSweep: vi.fn(), createBeeperConversation: vi.fn() }));
vi.mock('../services/beeperOutbox.js', () => ({
createOutboxEntry: vi.fn(),
sendOutboxEntry: vi.fn(),
@@ -58,7 +58,7 @@ import { getBeeperStatus, checkBeeperConnection } from '../services/beeperStatus
import {
completeBeeperOAuth, connectWithPastedToken, disconnectBeeper, startBeeperOAuth,
} from '../services/beeperOAuth.js';
-import { runBeeperSweep } from '../services/beeperSync.js';
+import { runBeeperSweep, createBeeperConversation } from '../services/beeperSync.js';
import {
clearOutboxBreaker, createOutboxEntry, discardOutboxEntry, listOutboxEntries, sendOutboxEntry, reconcileOutboxEntry,
} from '../services/beeperOutbox.js';
@@ -959,3 +959,32 @@ describe('saved Beeper scopes routes', () => {
expect(settings.beeperSavedScopes).toBeUndefined();
});
});
+
+describe('new direct conversations', () => {
+ it('validates input before invoking creation and returns the mirrored identity', async () => {
+ vi.mocked(createBeeperConversation).mockResolvedValue({ id: CONV_ID });
+ const app = buildApp();
+ const result = await request(app).post('/api/beeper/conversations').send({
+ accountId: 'account-example', participantId: 'user-example',
+ });
+ expect(result.status).toBe(201);
+ expect(result.body).toEqual({ id: CONV_ID });
+ expect(createBeeperConversation).toHaveBeenCalledWith({
+ accountId: 'account-example', participantId: 'user-example',
+ });
+ vi.mocked(createBeeperConversation).mockClear();
+ const invalid = await request(app).post('/api/beeper/conversations').send({
+ accountId: 'account-example', participantId: ' ', messageText: 'must not send',
+ });
+ expect(invalid.status).toBe(400);
+ expect(createBeeperConversation).not.toHaveBeenCalled();
+ });
+
+ it('surfaces upstream failures without pretending a chat was created', async () => {
+ vi.mocked(createBeeperConversation).mockRejectedValue(new BeeperApiError('offline', { code: 'NETWORK_ERROR' }));
+ const result = await request(buildApp()).post('/api/beeper/conversations').send({
+ accountId: 'account-example', participantId: 'user-example',
+ });
+ expect(result.status).toBe(503);
+ });
+});
diff --git a/server/services/beeperClient.js b/server/services/beeperClient.js
index d702e46cf4..6da2642d03 100644
--- a/server/services/beeperClient.js
+++ b/server/services/beeperClient.js
@@ -515,6 +515,14 @@ export async function getChat(chatId, { baseUrl, token, timeoutMs } = {}) {
return beeperRequest(`/v1/chats/${encodeURIComponent(chatId)}`, { baseUrl, token, timeoutMs, allowRetry: true });
}
+/** Create a direct chat without sending a first message or retrying a write. */
+export async function createChat(accountID, participantID, options = {}) {
+ return beeperRequest('/v1/chats', {
+ ...options, method: 'POST',
+ body: { accountID, participantIDs: [participantID], type: 'single' },
+ });
+}
+
/** `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();
diff --git a/server/services/beeperSync.js b/server/services/beeperSync.js
index 375cca4a45..3ed81af493 100644
--- a/server/services/beeperSync.js
+++ b/server/services/beeperSync.js
@@ -86,6 +86,8 @@ import {
listChatsPage,
listMessagesPage,
getMessage,
+ getChat,
+ createChat,
} from './beeperClient.js';
import { upsertParticipant, logSenderTouchpoints, loadRosterIndex } from './beeperTribe.js';
import { isInstanceFeatureEnabled } from './instanceFeatures.js';
@@ -448,6 +450,29 @@ async function upsertConversation(chat) {
return result.rows[0]?.id ?? null;
}
+/** User-triggered direct-chat creation. Reuse the sweep's mirror writer. */
+export async function createBeeperConversation({ accountId, participantId }) {
+ // Require a mirrored account before a remote write: the conversation FK
+ // would otherwise fail after Beeper had already created the chat.
+ const account = await query('SELECT account_id FROM beeper_accounts WHERE account_id = $1', [accountId]);
+ if (!account.rows.length) throw new BeeperApiError('Unknown Beeper account', { status: 404, code: 'CONVERSATION_NOT_FOUND' });
+ const options = await resolveBeeperConfig();
+ const created = await createChat(accountId, participantId, options);
+ // Older Desktop versions return only chatID; newer ones return the Chat.
+ const sourceId = created?.id || created?.chatID;
+ if (typeof sourceId !== 'string' || !sourceId) {
+ throw new BeeperApiError('Beeper returned no chat ID', { code: 'MALFORMED_RESPONSE' });
+ }
+ const chat = await getChat(sourceId, options);
+ if (chat?.id !== sourceId || chat?.accountID !== accountId) {
+ throw new BeeperApiError('Beeper returned a mismatched chat', { code: 'MALFORMED_RESPONSE' });
+ }
+ const id = await upsertConversation(normalizeChatRow(chat));
+ if (!id) throw new BeeperApiError('Could not mirror the created chat', { code: 'MALFORMED_RESPONSE' });
+ beeperSocketEvents.emit('invalidate', { kind: 'chats', chatID: sourceId });
+ return { id };
+}
+
/** Shared transaction writer: source edit versions outrank fetch-start time.
* Tombstones are terminal and preserve the archived body and attachments.
*/
diff --git a/server/services/beeperSync.test.js b/server/services/beeperSync.test.js
index 1440f6ca9e..020c33ce43 100644
--- a/server/services/beeperSync.test.js
+++ b/server/services/beeperSync.test.js
@@ -83,6 +83,7 @@ vi.mock('./beeperTribe.js', () => ({
const {
runBeeperSweep,
+ createBeeperConversation,
reconcileBeeperEvent, isBeeperIngestionArmed, getBeeperSyncConfig, chatNeedsSweep,
normalizeAccountRow, normalizeMessageRow, normalizeAttachmentRows, DEFAULT_INTERVAL_MINUTES,
} = await import('./beeperSync.js');
@@ -1276,3 +1277,51 @@ describe('Later scope mirror', () => {
expect(messageRequests()).toHaveLength(0);
});
});
+
+describe('user-triggered direct chat creation', () => {
+ it.each(['modern', 'legacy'])('creates once and mirrors the retrieved chat (%s response)', async (version) => {
+ queryMock.mockResolvedValueOnce({ rows: [{ account_id: 'account-example' }] });
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(jsonResponse(version === 'modern'
+ ? { id: 'chat-example' } : { chatID: 'chat-example', status: 'created' }))
+ .mockResolvedValueOnce(jsonResponse({
+ id: 'chat-example', accountID: 'account-example', network: 'Example', title: 'Recipient',
+ }));
+ vi.stubGlobal('fetch', fetchMock);
+ const result = await createBeeperConversation({ accountId: 'account-example', participantId: 'user-example' });
+ expect(result).toEqual({ id: 'conv-chat-example' });
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({
+ accountID: 'account-example', participantIDs: ['user-example'], type: 'single',
+ });
+ expect(fetchMock.mock.calls[0][1].method).toBe('POST');
+ expect(dbCalls.find(({ text }) => text.includes('INSERT INTO beeper_conversations')).params.slice(0, 4))
+ .toEqual(['account-example', 'Example', 'chat-example', 'Recipient']);
+ });
+
+ it('rejects an unknown local account before any remote write', async () => {
+ const fetchMock = vi.fn();
+ vi.stubGlobal('fetch', fetchMock);
+ await expect(createBeeperConversation({ accountId: 'missing', participantId: 'user-example' }))
+ .rejects.toMatchObject({ code: 'CONVERSATION_NOT_FOUND' });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('rejects mismatched remote identity without inserting a mirror row', async () => {
+ queryMock.mockResolvedValueOnce({ rows: [{ account_id: 'account-example' }] });
+ vi.stubGlobal('fetch', vi.fn()
+ .mockResolvedValueOnce(jsonResponse({ id: 'chat-example' }))
+ .mockResolvedValueOnce(jsonResponse({ id: 'chat-example', accountID: 'wrong-account' })));
+ await expect(createBeeperConversation({ accountId: 'account-example', participantId: 'user-example' }))
+ .rejects.toMatchObject({ code: 'MALFORMED_RESPONSE' });
+ expect(dbCalls.some(({ text }) => text.includes('INSERT INTO beeper_conversations'))).toBe(false);
+ });
+
+ it('never retries a failed creation request', async () => {
+ queryMock.mockResolvedValueOnce({ rows: [{ account_id: 'account-example' }] });
+ const fetchMock = vi.fn().mockResolvedValue({ ok: false, status: 503, text: async () => JSON.stringify({ error: 'unavailable' }) });
+ vi.stubGlobal('fetch', fetchMock);
+ await expect(createBeeperConversation({ accountId: 'account-example', participantId: 'user-example' })).rejects.toThrow();
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+});