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: save and manage named Beeper conversation scopes (#9985)

[._.]/ Adam Eivyd77d2090e6c9
diff --git a/client/src/components/messages/BeeperTab.test.jsx b/client/src/components/messages/BeeperTab.test.jsx
index 454a384c54..8c155c6479 100644
--- a/client/src/components/messages/BeeperTab.test.jsx
+++ b/client/src/components/messages/BeeperTab.test.jsx
@@ -20,6 +20,10 @@ import { awaitEnabled } from '../../test/enabledBarrier.js';
const api = vi.hoisted(() => ({
getBeeperStatus: vi.fn(),
+ getBeeperScopes: vi.fn(),
+ createBeeperScope: vi.fn(),
+ updateBeeperScope: vi.fn(),
+ deleteBeeperScope: vi.fn(),
syncBeeperNow: vi.fn(),
getBeeperNetworks: vi.fn(),
getBeeperConversations: vi.fn(),
@@ -149,6 +153,7 @@ const awaitThreadLoaded = () => screen.findAllByText('Example Conversation');
beforeEach(() => {
vi.clearAllMocks();
+ api.getBeeperScopes.mockResolvedValue({ scopes: [] });
socketMock.handlers.clear();
socketMock.emitted.length = 0;
api.getBeeperStatus.mockResolvedValue({ tokenConfigured: true, reachable: true, accounts: [], realtime: { state: 'connected' } });
@@ -526,11 +531,11 @@ describe('the pinned grid is Beeper’s own isPinned, mirrored', () => {
});
describe('unimplemented controls are absent rather than inert', () => {
- it('renders no Requests, Later, add-scope, overflow or new-conversation control', async () => {
+ it('renders no Requests, Later or new-conversation placeholder', async () => {
renderTab();
await screen.findByText('Nothing here');
- for (const label of ['Requests', 'Later', 'Add scope', 'More scope options', 'New conversation']) {
+ for (const label of ['Requests', 'Later', 'More scope options', 'New conversation']) {
expect(screen.queryByRole('button', { name: label })).toBeNull();
}
});
@@ -839,7 +844,7 @@ describe('realtime', () => {
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(); });
+ await act(async () => { for (const fn of socketMock.handlers.get('connect') || []) fn(); });
expect(socketMock.emitted.filter(([event]) => event === 'beeper:subscribe')).toHaveLength(4);
});
@@ -1671,3 +1676,52 @@ describe('fixture hygiene', () => {
expect(conversation().title).toMatch(/Example/);
});
});
+
+
+describe('saved conversation scopes', () => {
+ const saved = { id: CONV_B, name: 'Example focused scope', filters: { network: 'signal', archived: false, search: 'Example', unreadOnly: true } };
+
+ it('restores the persisted filter from a saved-scope deep link, then renames and deletes it', async () => {
+ api.getBeeperScopes.mockResolvedValue({ scopes: [saved] });
+ api.updateBeeperScope.mockResolvedValue({ ...saved, name: 'Renamed example' });
+ api.deleteBeeperScope.mockResolvedValue({ deleted: true });
+ renderTab(`/messages/beeper?scope=saved:${CONV_B}`);
+ await waitFor(() => expect(api.getBeeperConversations).toHaveBeenCalledWith(saved.filters, { silent: true }));
+ fireEvent.click(screen.getByRole('button', { name: 'More scope options' }));
+ fireEvent.change(screen.getByLabelText('Scope name'), { target: { value: 'Renamed example' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Save scope' }));
+ expect(await screen.findByRole('button', { name: 'Renamed example' })).toBeInTheDocument();
+ expect(api.updateBeeperScope).toHaveBeenCalledWith(CONV_B, { name: 'Renamed example', filters: saved.filters }, { silent: true });
+ fireEvent.click(screen.getByRole('button', { name: 'More scope options' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Delete scope' }));
+ await waitFor(() => expect(screen.queryByRole('button', { name: 'Renamed example' })).not.toBeInTheDocument());
+ await waitFor(() => expect(api.getBeeperConversations).toHaveBeenLastCalledWith({ archived: false, lowPriority: false }, { silent: true }));
+ });
+
+ it('reconciles saved scopes on remote invalidation and reports failed reads without inventing an empty set', async () => {
+ api.getBeeperScopes.mockRejectedValueOnce(new Error('Example read failure')).mockResolvedValue({ scopes: [saved] });
+ renderTab();
+ expect(await screen.findByText(/Could not load saved scopes/)).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'Retry scopes' }));
+ expect(await screen.findByRole('button', { name: saved.name })).toBeInTheDocument();
+ api.getBeeperScopes.mockResolvedValue({ scopes: [] });
+ await act(async () => {
+ for (const fn of socketMock.handlers.get('beeper:invalidate') || []) fn({ kind: 'scopes' });
+ });
+ await waitFor(() => expect(screen.queryByRole('button', { name: saved.name })).not.toBeInTheDocument());
+ });
+
+ it('saves the active query and keeps the editor open after a rejected write', async () => {
+ api.createBeeperScope.mockRejectedValueOnce(new Error('Example save failure')).mockResolvedValueOnce(saved);
+ renderTab('/messages/beeper?scope=net:signal&q=Example&unread=1');
+ await screen.findByRole('button', { name: 'Add scope' });
+ fireEvent.click(screen.getByRole('button', { name: 'Add scope' }));
+ fireEvent.change(screen.getByLabelText('Scope name'), { target: { value: saved.name } });
+ fireEvent.click(screen.getByRole('button', { name: 'Save scope' }));
+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Example save failure'));
+ expect(screen.getByLabelText('Scope name')).toHaveValue(saved.name);
+ fireEvent.click(screen.getByRole('button', { name: 'Save scope' }));
+ expect(await screen.findByRole('button', { name: saved.name })).toBeInTheDocument();
+ expect(api.createBeeperScope).toHaveBeenLastCalledWith({ name: saved.name, filters: saved.filters }, { silent: true });
+ });
+});
diff --git a/client/src/components/messages/beeper/BeeperChatSurface.jsx b/client/src/components/messages/beeper/BeeperChatSurface.jsx
index 26b2c70173..97c3f430ec 100644
--- a/client/src/components/messages/beeper/BeeperChatSurface.jsx
+++ b/client/src/components/messages/beeper/BeeperChatSurface.jsx
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router';
import {
- Archive, BellOff, Filter, Inbox, Loader2,
+ Archive, BellOff, Bookmark, Filter, Inbox, Loader2, MoreHorizontal, Plus,
RefreshCw, Search, Settings, TrendingDown, X,
} from 'lucide-react';
import NetworkLogo, { networkLabel } from './BeeperNetworkLogo';
@@ -9,6 +9,7 @@ import BeeperThread from './BeeperThread';
import ConnectionStatusDot from '../../ui/ConnectionStatusDot';
import toast from '../../ui/Toast';
import useMounted from '../../../hooks/useMounted';
+import { useSocketResource } from '../../../hooks/useSocketResource';
import useBeeperOutbox from '../../../hooks/useBeeperOutbox';
import { messagePreviewText } from '../../../lib/beeperMessageBody';
import { safeReadJsonStorage, safeWriteJsonStorage } from '../../../lib/safeStorage';
@@ -26,11 +27,10 @@ import * as api from '../../../services/api';
* 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.
+ * - **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, add-scope and
+ * `isLowPriority` are real fields on every chat row. Requests, Later and
* new conversation are omitted until they work (#9985) — an inert control
* that looks live is worse than an absent one.
* - **The pinned grid is Beeper's own `isPinned`, mirrored.** PortOS never
@@ -48,9 +48,10 @@ import * as api from '../../../services/api';
* rendered over the newer one.
*/
-// Fixed system scopes, in the reference's own order. Requests, Later, scope
-// management and new conversation are omitted until implemented
+// Fixed system scopes, in the reference's own order. Requests, Later and
+// new conversation are omitted until implemented
// (tracked in the Beeper enhancements issue, #9985).
+const SCOPE_EVENTS = ['beeper:invalidate'];
const SYSTEM_SCOPES = [
{ id: 'inbox', label: 'Inbox', icon: Inbox },
{ id: 'archive', label: 'Archive', icon: Archive },
@@ -173,7 +174,7 @@ function SyncStrip({ sweep }) {
/* ------------------------------------------------------------------ rail -- */
function Rail({
- networks, scope, onScope, totalUnread, onOpenSettings,
+ networks, scope, onScope, totalUnread, onOpenSettings, savedScopes, onAddScope,
}) {
const item = 'relative flex size-11 shrink-0 items-center justify-center rounded-xl transition';
return (
@@ -201,6 +202,16 @@ function Rail({
);
})}
+ {savedScopes.map((entry) => (
+ <button key={entry.id} type="button" title={entry.name} aria-label={entry.name}
+ aria-pressed={scope === `saved:${entry.id}`} onClick={() => onScope(`saved:${entry.id}`)}
+ className={`${item} ${scope === `saved:${entry.id}` ? 'bg-port-card text-white' : 'text-gray-500 hover:text-white'}`}>
+ <Bookmark size={19} />
+ </button>
+ ))}
+ <button type="button" title="Save current scope" aria-label="Add scope" onClick={onAddScope}
+ className={`${item} text-gray-500 hover:text-white`}><Plus size={19} /></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) => {
@@ -354,6 +365,18 @@ export default function BeeperChatSurface({
const search = searchRaw.trim();
const [searchOpen, setSearchOpen] = useState(Boolean(search));
+ const scopesResource = useSocketResource(async () => {
+ const data = await api.getBeeperScopes({ silent: true });
+ if (!Array.isArray(data?.scopes)) throw new Error('Invalid saved scopes response');
+ return data.scopes;
+ }, { events: SCOPE_EVENTS, matchesEvent: (payload) => payload?.kind === 'scopes' });
+ const savedScopes = scopesResource.data;
+ const setSavedScopes = scopesResource.updateData;
+ const [scopeEditor, setScopeEditor] = useState(null);
+ const [scopeName, setScopeName] = useState('');
+ const [scopeSaving, setScopeSaving] = useState(false);
+ const scopeWriteRef = useRef(false);
+
const [networks, setNetworks] = useState([]);
const [conversations, setConversations] = useState([]);
const [listCursor, setListCursor] = useState(null);
@@ -387,12 +410,15 @@ export default function BeeperChatSurface({
const listGenRef = useRef(0);
const threadGenRef = useRef(0);
- const scope = LIVE_SYSTEM_SCOPES.has(scopeParam) || scopeParam.startsWith(NETWORK_SCOPE_PREFIX)
+ const savedScope = savedScopes?.find((entry) => `saved:${entry.id}` === scopeParam);
+ const scope = savedScope || LIVE_SYSTEM_SCOPES.has(scopeParam) || scopeParam.startsWith(NETWORK_SCOPE_PREFIX)
? scopeParam
: 'inbox';
- const activeNetwork = scopeNetwork(scope);
+ const activeNetwork = savedScope?.filters.network || scopeNetwork(scope);
const unified = !activeNetwork;
- const filters = useMemo(() => filtersForScope(scope, unreadOnly, search), [scope, unreadOnly, search]);
+ const filters = useMemo(() => savedScope
+ ? { ...savedScope.filters, ...(unreadOnly ? { unreadOnly: true } : {}), ...(search ? { search } : {}) }
+ : filtersForScope(scope, unreadOnly, search), [savedScope, scope, unreadOnly, search]);
const setParam = useCallback((key, value) => {
setSearchParams((prev) => {
@@ -409,7 +435,9 @@ export default function BeeperChatSurface({
setNetworks(Array.isArray(data?.networks) ? data.networks : []);
}, [mountedRef]);
+ const scopePending = scopeParam.startsWith('saved:') && savedScopes === null;
const loadList = useCallback(async () => {
+ if (scopePending) return;
const generation = ++listGenRef.current;
setListLoading(true);
const [data, error] = await api.getBeeperConversations(filters, { silent: true })
@@ -424,7 +452,7 @@ export default function BeeperChatSurface({
setListCursor(data?.nextCursor || null);
}
setListLoading(false);
- }, [filters, mountedRef]);
+ }, [filters, mountedRef, scopePending]);
// "Sync now" (#79): the list-header action used to be a pure re-fetch of
// whatever the mirror already held (`loadList` + `loadNetworks`), which is
@@ -853,7 +881,7 @@ export default function BeeperChatSurface({
() => networks.reduce((sum, entry) => sum + (entry.unreadCount || 0), 0),
[networks],
);
- const scopeLabel = activeNetwork
+ const scopeLabel = savedScope ? savedScope.name : activeNetwork
? networkLabel(activeNetwork)
: (SYSTEM_SCOPES.find((entry) => entry.id === scope)?.label || 'Inbox');
@@ -862,7 +890,15 @@ export default function BeeperChatSurface({
<Rail
networks={networks}
scope={scope}
- onScope={(next) => setParam('scope', next)}
+ onScope={(next) => setSearchParams((prev) => {
+ const params = new URLSearchParams(prev);
+ params.set('scope', next);
+ params.delete('q');
+ params.delete('unread');
+ return params;
+ }, { replace: true })}
+ savedScopes={savedScopes || []}
+ onAddScope={() => { setScopeEditor({ filters }); setScopeName(''); }}
totalUnread={totalUnread}
onOpenSettings={onOpenSettings}
/>
@@ -892,6 +928,13 @@ export default function BeeperChatSurface({
than an absent one — the file's own governing rule. */}
<span className="truncate">{scopeLabel}</span>
</span>
+ {savedScope && (
+ <button type="button" aria-label="More scope options" title="More scope options"
+ onClick={() => { setScopeEditor(savedScope); setScopeName(savedScope.name); }}
+ className="inline-flex min-h-[44px] min-w-[44px] items-center justify-center text-gray-500 hover:text-white">
+ <MoreHorizontal size={15} />
+ </button>
+ )}
<button
type="button"
onClick={() => {
@@ -927,6 +970,58 @@ export default function BeeperChatSurface({
</button>
</div>
+ {scopeEditor && (
+ <form className="space-y-2 border-b border-port-border p-3" onSubmit={async (event) => {
+ event.preventDefault();
+ if (scopeWriteRef.current || !scopeName.trim()) return;
+ scopeWriteRef.current = true;
+ setScopeSaving(true);
+ const input = { name: scopeName.trim(), filters: scopeEditor.filters };
+ const result = await (scopeEditor.id
+ ? api.updateBeeperScope(scopeEditor.id, input, { silent: true })
+ : api.createBeeperScope(input, { silent: true })).catch((err) => {
+ toast.error(err?.message || 'Could not save scope'); return null;
+ });
+ scopeWriteRef.current = false;
+ if (!mountedRef.current) return;
+ setScopeSaving(false);
+ if (!result) return;
+ setSavedScopes((prev) => [...(prev || []).filter((entry) => entry.id !== result.id), result]);
+ setScopeEditor(null);
+ setSearchParams((prev) => {
+ const params = new URLSearchParams(prev);
+ params.set('scope', `saved:${result.id}`);
+ params.delete('q'); params.delete('unread');
+ return params;
+ }, { replace: true });
+ }}>
+ <label htmlFor="beeper-scope-name" className="block text-xs text-gray-300">Scope name</label>
+ <input id="beeper-scope-name" value={scopeName} maxLength={60} required
+ onChange={(event) => setScopeName(event.target.value)}
+ className="w-full rounded border border-port-border bg-port-bg p-2 text-sm text-white" />
+ <p className="text-[11px] text-gray-500">Saves this conversation filter, including search and unread preferences.</p>
+ <div className="flex flex-wrap gap-2 text-xs">
+ <button type="submit" disabled={scopeSaving} className="min-h-[36px] rounded border border-port-border px-2">Save scope</button>
+ <button type="button" disabled={scopeSaving} onClick={() => setScopeEditor(null)} className="min-h-[36px] px-2">Cancel</button>
+ {scopeEditor.id && <button type="button" disabled={scopeSaving} className="min-h-[36px] px-2 text-port-error"
+ onClick={async () => {
+ if (scopeWriteRef.current) return;
+ scopeWriteRef.current = true; setScopeSaving(true);
+ const id = scopeEditor.id;
+ const result = await api.deleteBeeperScope(id, { silent: true }).catch((err) => {
+ toast.error(err?.message || 'Could not delete scope'); return null;
+ });
+ scopeWriteRef.current = false;
+ if (!mountedRef.current) return;
+ setScopeSaving(false);
+ if (!result) return;
+ setSavedScopes((prev) => (prev || []).filter((entry) => entry.id !== id));
+ setScopeEditor(null); setParam('scope', 'inbox');
+ }}>Delete scope</button>}
+ </div>
+ </form>
+ )}
+
{searchOpen && (
<div className="relative shrink-0 px-3 pb-2">
<input
@@ -951,6 +1046,11 @@ export default function BeeperChatSurface({
</div>
)}
+ {scopesResource.error && (
+ <div role="alert" className="px-3 py-2 text-xs text-port-error">
+ Could not load saved scopes. <button type="button" onClick={scopesResource.refetch} className="underline">Retry scopes</button>
+ </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}
diff --git a/client/src/services/README.md b/client/src/services/README.md
index e695cc19a6..bc7550b06f 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -93,7 +93,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. |
+| `apiBeeper.js` | Beeper Desktop bridge: saved conversation scopes (list/create/update/delete); 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/apiBeeper.js b/client/src/services/apiBeeper.js
index d2ec32ba3c..66e9b20b20 100644
--- a/client/src/services/apiBeeper.js
+++ b/client/src/services/apiBeeper.js
@@ -169,3 +169,15 @@ export const discardOutboxEntry = (id, options = {}) => request(`/beeper/outbox/
/** Read delivery state and finish local persistence, without sending again. */
export const reconcileOutboxEntry = (id, options = {}) => request(`/beeper/outbox/${encodeURIComponent(id)}/reconcile`, { method: 'POST', ...options });
+
+// Saved machine-local conversation filters (#9985).
+export const getBeeperScopes = (options = {}) => request('/beeper/scopes', options);
+export const createBeeperScope = (scope, options = {}) => request('/beeper/scopes', {
+ method: 'POST', body: JSON.stringify(scope), ...options,
+});
+export const updateBeeperScope = (id, scope, options = {}) => request(`/beeper/scopes/${encodeURIComponent(id)}`, {
+ method: 'PATCH', body: JSON.stringify(scope), ...options,
+});
+export const deleteBeeperScope = (id, options = {}) => request(`/beeper/scopes/${encodeURIComponent(id)}`, {
+ method: 'DELETE', ...options,
+});
diff --git a/server/lib/mediaValidation.js b/server/lib/mediaValidation.js
index d101e20326..6196f92992 100644
--- a/server/lib/mediaValidation.js
+++ b/server/lib/mediaValidation.js
@@ -520,3 +520,18 @@ export const mediaCollectionBulkItemsSchema = z.object({
(d) => (Array.isArray(d.add) && d.add.length > 0) || (Array.isArray(d.remove) && d.remove.length > 0),
{ message: 'bulk update requires at least one item in add or remove' },
);
+
+// Bounded, machine-local Beeper view preferences; filters query the mirror.
+export const beeperScopeInputSchema = z.object({
+ name: z.string().trim().min(1).max(60),
+ filters: z.object({
+ network: z.string().trim().min(1).max(200).optional(),
+ archived: z.boolean().optional(),
+ lowPriority: z.boolean().optional(),
+ unreadOnly: z.boolean().optional(),
+ search: z.string().trim().max(200).optional(),
+ }).strict(),
+}).strict();
+export const beeperSavedScopesSchema = z.array(beeperScopeInputSchema.extend({
+ id: z.string().uuid(),
+})).max(50);
diff --git a/server/routes/beeper.js b/server/routes/beeper.js
index 64eef69fdd..c8649f635e 100644
--- a/server/routes/beeper.js
+++ b/server/routes/beeper.js
@@ -1,4 +1,7 @@
import { Router } from 'express';
+import { randomUUID } from 'node:crypto';
+import { beeperSocketEvents } from '../services/beeperSocketEvents.js';
+import { getSettings, updateSettingsWith } from '../services/settings.js';
import { z } from 'zod';
import { asyncHandler, createServiceErrorMapper, ServerError } from '../lib/errorHandler.js';
import { resolveOAuthOrigin } from '../lib/beeperOAuthOrigin.js';
@@ -7,6 +10,7 @@ import { serveLocalFile } from '../lib/fileUtils.js';
import { basename, dirname } from 'path';
import {
beeperOAuthCallbackSchema, beeperOutboxCreateSchema, beeperOutboxListSchema,
+ beeperScopeInputSchema, beeperSavedScopesSchema,
beeperOutboxParamsSchema, beeperOutboxSendSchema, beeperPastedTokenSchema, validateRequest,
} from '../lib/validation.js';
import { getBeeperStatus, checkBeeperConnection } from '../services/beeperStatus.js';
@@ -138,6 +142,49 @@ const redirectUriFrom = (origin) => (origin ? `${origin}/api/beeper/oauth/callba
// window) still gets today's request-derived behaviour.
const oauthStartSchema = z.object({ origin: z.string().min(1).max(2048).optional() }).strict();
+// Saved scopes are small machine-local view preferences in the existing
+// settings store. Each mutation reads within its write queue, preserving
+// concurrent changes to both scopes and unrelated connection settings.
+const scopesFrom = (settings) => validateRequest(beeperSavedScopesSchema, settings.beeperSavedScopes ?? []);
+const scopeIdSchema = z.object({ id: z.string().uuid() });
+
+router.get('/scopes', asyncHandler(async (_req, res) => {
+ res.json({ scopes: scopesFrom(await getSettings()) });
+}));
+
+router.post('/scopes', asyncHandler(async (req, res) => {
+ const input = validateRequest(beeperScopeInputSchema, req.body ?? {});
+ const scope = { id: randomUUID(), ...input };
+ await updateSettingsWith((current) => ({
+ ...current,
+ beeperSavedScopes: validateRequest(beeperSavedScopesSchema, [...scopesFrom(current), scope]),
+ }));
+ beeperSocketEvents.emit('invalidate', { kind: 'scopes' });
+ res.status(201).json(scope);
+}));
+
+router.patch('/scopes/:id', asyncHandler(async (req, res) => {
+ const { id } = validateRequest(scopeIdSchema, req.params);
+ const input = validateRequest(beeperScopeInputSchema, req.body ?? {});
+ const scope = { id, ...input };
+ await updateSettingsWith((current) => {
+ const scopes = scopesFrom(current);
+ if (!scopes.some((entry) => entry.id === id)) throw new ServerError('Scope not found', { status: 404, code: 'NOT_FOUND' });
+ return { ...current, beeperSavedScopes: scopes.map((entry) => entry.id === id ? scope : entry) };
+ });
+ beeperSocketEvents.emit('invalidate', { kind: 'scopes' });
+ res.json(scope);
+}));
+
+router.delete('/scopes/:id', asyncHandler(async (req, res) => {
+ const { id } = validateRequest(scopeIdSchema, req.params);
+ await updateSettingsWith((current) => ({
+ ...current, beeperSavedScopes: scopesFrom(current).filter((entry) => entry.id !== id),
+ }));
+ beeperSocketEvents.emit('invalidate', { kind: 'scopes' });
+ res.json({ deleted: true });
+}));
+
// 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
diff --git a/server/routes/beeper.test.js b/server/routes/beeper.test.js
index 173860f961..99de624ef1 100644
--- a/server/routes/beeper.test.js
+++ b/server/routes/beeper.test.js
@@ -2,6 +2,10 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
import express from 'express';
import { request } from '../lib/testHelper.js';
+vi.mock('../services/settings.js', () => ({ getSettings: vi.fn(), updateSettingsWith: vi.fn() }));
+import { getSettings, updateSettingsWith } from '../services/settings.js';
+import { beeperSocketEvents } from '../services/beeperSocketEvents.js';
+
vi.mock('../services/beeperStatus.js', () => ({
getBeeperStatus: vi.fn(),
checkBeeperConnection: vi.fn(),
@@ -910,3 +914,41 @@ describe('POST /api/beeper/outbox/:id/reconcile', () => {
expect(sendOutboxEntry).not.toHaveBeenCalled();
});
});
+
+
+describe('saved Beeper scopes routes', () => {
+ let settings;
+ const input = { name: 'Example unread scope', filters: { network: 'signal', unreadOnly: true, archived: false } };
+ beforeEach(() => {
+ settings = { beeper: { enabled: true, sendReadReceipts: false }, unrelated: 'preserved' };
+ vi.mocked(getSettings).mockImplementation(async () => settings);
+ vi.mocked(updateSettingsWith).mockImplementation(async (mutate) => { settings = await mutate(settings); return settings; });
+ });
+
+ it('creates, lists, renames and deletes a scope while preserving connection preferences', async () => {
+ const event = vi.fn();
+ beeperSocketEvents.on('invalidate', event);
+ try {
+ const app = buildApp();
+ expect((await request(app).get('/api/beeper/scopes')).body).toEqual({ scopes: [] });
+ const created = await request(app).post('/api/beeper/scopes').send(input);
+ expect(created.status).toBe(201);
+ const id = created.body.id;
+ expect((await request(app).get('/api/beeper/scopes')).body.scopes).toEqual([{ id, ...input }]);
+ const renamed = await request(app).patch(`/api/beeper/scopes/${id}`).send({ ...input, name: 'Renamed example' });
+ expect(renamed.body.name).toBe('Renamed example');
+ expect((await request(app).delete(`/api/beeper/scopes/${id}`)).status).toBe(200);
+ expect(settings).toEqual({ beeper: { enabled: true, sendReadReceipts: false }, unrelated: 'preserved', beeperSavedScopes: [] });
+ expect(event).toHaveBeenCalledTimes(3);
+ expect(event).toHaveBeenLastCalledWith({ kind: 'scopes' });
+ } finally { beeperSocketEvents.off('invalidate', event); }
+ });
+
+ it('rejects unbounded/foreign filters and missing rename targets before persisting', async () => {
+ const app = buildApp();
+ expect((await request(app).post('/api/beeper/scopes').send({ ...input, filters: { token: 'example' } })).status).toBe(400);
+ expect((await request(app).post('/api/beeper/scopes').send({ ...input, name: 'x'.repeat(61) })).status).toBe(400);
+ expect((await request(app).patch('/api/beeper/scopes/11111111-1111-4111-8111-111111111111').send(input)).status).toBe(404);
+ expect(settings.beeperSavedScopes).toBeUndefined();
+ });
+});
diff --git a/server/routes/settings.js b/server/routes/settings.js
index dd4f8c82ad..58348b17b9 100644
--- a/server/routes/settings.js
+++ b/server/routes/settings.js
@@ -26,7 +26,7 @@ import { storableAutoUpdateConfig } from '../lib/sharedSchemas.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, autoUpdateSettingsSchema, 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, imageGenFalSettingsSchema, renderDefaultsSettingsSchema, videoGenSettingsSchema, subscriptionCostsMapSchema, subscriptionPlanTiersMapSchema, usageApiBilledInstanceIdsSchema, namedOrchestrationProfileSchema, orchestrationProfilesSettingsSchema, harnessSettingsSchema, credentialBootstrapsSettingsSchema, validateRequest } from '../lib/validation.js';
+import { privateCredentialParamsSchema, privateCredentialInputSchema, backupConfigSchema, autoUpdateSettingsSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, autofixerSettingsSchema, codeReviewSettingsSchema, locationSettingsSchema, hideFirstRunCardSchema, networkSetupPreferenceSchema, settingsEmbeddingsSchema, localLlmSettingsSchema, imessageConfigSchema, signalConfigSchema, beeperSettingsSchema, beeperSavedScopesSchema, spotifyConfigSchema, youtubeConfigSchema, apiAccessSettingsSchema, instanceFeatureSettingsSchema, instanceFeatureIdSchema, instanceFeatureUpdateSchema, instanceFeatureGroupSettingsSchema, instanceFeatureGroupIdSchema, instanceFeatureGroupUpdateSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, musicSettingsSchema, federationSettingsSchema, privacySettingsSchema, seriesAutopilotSettingsSchema, layeredIntelligenceSettingsSchema, imageGenGrokSettingsSchema, imageGenAgySettingsSchema, imageGenFalSettingsSchema, renderDefaultsSettingsSchema, videoGenSettingsSchema, subscriptionCostsMapSchema, subscriptionPlanTiersMapSchema, usageApiBilledInstanceIdsSchema, namedOrchestrationProfileSchema, orchestrationProfilesSettingsSchema, harnessSettingsSchema, credentialBootstrapsSettingsSchema, validateRequest } from '../lib/validation.js';
const router = Router();
@@ -511,6 +511,9 @@ router.put('/', asyncHandler(async (req, res) => {
// `.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?.beeperSavedScopes !== undefined) {
+ validateRequest(beeperSavedScopesSchema, req.body.beeperSavedScopes);
+ }
if (req.body?.beeper !== undefined) {
validateRequest(beeperSettingsSchema, req.body.beeper);
}