refactor(dashboard): rethink settings, split out subreddits and accounts

The settings page had accumulated five tabs whose names no longer matched
their contents, three different save models, and the whole subreddit
configuration buried under a tab named after a checkbox.

Structure:
- Subreddits becomes its own page: a list showing each community's mode,
  tone, computed share of polling, and live sent/reply stats, with one
  subreddit edited at a time in a drawer.
- Accounts becomes its own page. It is session lifecycle, not config.
- Settings collapses to one scrolling page: Safety, Pacing (Monitoring and
  Rate limits merged), Notifications, Advanced.
- The sidebar is grouped, having gone from 9 to 11 destinations.

Saving:
- Every section owns its own draft, validation, risk gate and save via
  useConfigCard, submitting only the keys it owns. A syntax error in the
  advanced JSON can no longer block a rate-limit change, and enabling an
  autonomous policy is its own deliberate commit.
- UnsavedChangesProvider restores the leave-page guard across cards that no
  longer share a draft.

Subreddit editing:
- Errors are keyed by field name instead of array index, removing the
  defensive invalidation that existed because row indices shifted on add
  and remove. Confirming an autonomous mode can no longer be attributed to
  the wrong row.
- Weight is shown as the share it actually produces, live while editing.
- Bulk actions cover start/pause polling, tone, policy and removal, because
  production runs 30-40 subreddits and per-row editing does not scale.
  Bulk policy changes name every subreddit turning autonomous, and
  normalise the hybrid mode's turn budget, which has no form to catch it.

Also surfaces the effective sending rate, since the hourly limit and the
minimum delay both throttle and only the binding one matters.

Legacy ?section= links redirect or resolve to anchors.

Fixes found while verifying in a browser: a radio-card rule was shrinking
nested number inputs; .share-preview had no styles; the throughput readout
reported a rate from a blank field; and the reconcile logic warned about a
server change whenever a sibling card saved.

Tests: 116 files, 1105 passing (from 113, 1027). Adds subreddit, accounts
and model unit suites covering share maths, bulk normalisation and the
confirm-by-name behaviour.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Jamie BruntonandClaude Opus 5 committed 2026-08-11 09:00:40 +01:00
1 parent 7defff422d
commit 5a0846965a
35 files changed
+4129 -1530

No files matched your search

+348 -472
View File
@@ -6,11 +6,11 @@ import { act, cleanup, render, screen, waitFor, within } from '@testing-library/
import userEvent from '@testing-library/user-event';
import { HttpResponse, http } from 'msw';
import { setupServer } from 'msw/node';
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import { createMemoryRouter, RouterProvider } from 'react-router-dom';
import { SettingsRoute } from '../../apps/dashboard/src/features/settings/settings-route.js';
const config = {
const baseConfig = {
rateLimit: { minDelayBetweenMessagesMs: 300_000, maxMessagesPerHour: 8, jitterMs: 60_000 },
browser: { dryRun: true },
reddit: { prioritizeRecentPosts: false, recentWindowMinutes: 60, maxReadyCandidates: 25 },
@@ -19,10 +19,58 @@ const config = {
advanced: { openrouter: { chatModel: 'example/chat-model' } },
};
const server = setupServer(http.get('/api/accounts', () => HttpResponse.json([])));
const pushSettings = {
enabled: false,
serverUrl: 'https://ntfy.sh',
topic: '',
priority: 'default',
events: {
imageReceived: true,
replyReceived: false,
messageFailed: false,
botStopped: false,
rateLimited: false,
sessionExpired: true,
syncFailed: false,
},
hasAuthToken: false,
};
function installConfigApi() {
server.use(http.get('/api/config', () => HttpResponse.json(config)));
let config: Record<string, unknown> = structuredClone(baseConfig);
/** Bodies received by PUT /api/config, in order. */
let saved: Record<string, unknown>[] = [];
const server = setupServer(
http.get('/api/config', () => HttpResponse.json(config)),
http.get('/api/push-notifications', () => HttpResponse.json(pushSettings)),
);
/** Applies a partial update the way the real endpoint does, and echoes it back. */
function installConfigWriter() {
server.use(
http.put('/api/config', async ({ request }) => {
const body = await request.json() as Record<string, any>;
saved.push(body);
config = {
...config,
rateLimit: { ...(config.rateLimit as object), ...(body.rateLimit ?? {}) },
browser: { ...(config.browser as object), ...(body.browser ?? {}) },
reddit: { ...(config.reddit as object), ...(body.reddit ?? {}) },
subreddits: body.subreddits ?? config.subreddits,
advanced: body.advanced ?? config.advanced,
};
return HttpResponse.json({
success: true,
config: {
rateLimit: config.rateLimit,
browser: config.browser,
reddit: config.reddit,
},
subreddits: config.subreddits,
advanced: config.advanced,
});
}),
);
}
function renderSettings(path = '/settings') {
@@ -32,6 +80,8 @@ function renderSettings(path = '/settings') {
const router = createMemoryRouter(
[
{ path: '/settings', element: <SettingsRoute /> },
{ path: '/subreddits', element: <h1>Subreddits page</h1> },
{ path: '/accounts', element: <h1>Accounts page</h1> },
{ path: '/elsewhere', element: <h1>Elsewhere</h1> },
],
{ initialEntries: [path] },
@@ -44,7 +94,19 @@ function renderSettings(path = '/settings') {
return { ...view, queryClient, router };
}
function card(name: string) {
return screen.getByRole('region', { name });
}
async function findCard(name: string) {
return screen.findByRole('region', { name });
}
beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));
beforeEach(() => {
config = structuredClone(baseConfig);
saved = [];
});
afterEach(() => {
cleanup();
server.resetHandlers();
@@ -52,26 +114,13 @@ afterEach(() => {
});
afterAll(() => server.close());
describe('settings and access', () => {
it('loads the requested route-friendly section and keeps section selection in the URL', async () => {
let resolveConfig: ((response: Response) => void) | undefined;
server.use(
http.get('/api/config', async ({ request }) => {
expect(request.credentials).toBe('same-origin');
return new Promise<Response>((resolve) => { resolveConfig = resolve; });
}),
);
const user = userEvent.setup();
const { router } = renderSettings('/settings?section=rate-limits');
describe('settings page', () => {
it('stacks every section on one page instead of hiding them behind tabs', async () => {
renderSettings();
expect(screen.getByRole('status', { name: 'Loading settings' })).toBeInTheDocument();
await waitFor(() => expect(resolveConfig).toBeTypeOf('function'));
resolveConfig?.(HttpResponse.json(config));
expect(await screen.findByRole('heading', { name: 'Rate limits' })).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Monitoring' }));
expect(screen.getByRole('heading', { name: 'Monitoring' })).toBeInTheDocument();
expect(router.state.location.search).toBe('?section=monitoring');
for (const name of ['Safety', 'Pacing', 'Notifications', 'Advanced']) {
expect(await findCard(name)).toBeInTheDocument();
}
});
it('shows a recoverable initial configuration error', async () => {
@@ -79,473 +128,300 @@ describe('settings and access', () => {
server.use(
http.get('/api/config', () => {
requests += 1;
return requests === 1
? HttpResponse.json({ error: 'Configuration unavailable' }, { status: 503 })
: HttpResponse.json(config);
return requests === 1 ? HttpResponse.json({ error: 'nope' }, { status: 500 }) : HttpResponse.json(config);
}),
);
const user = userEvent.setup();
renderSettings();
const alert = await screen.findByRole('alert');
expect(alert).toHaveTextContent('Configuration unavailable');
await user.click(within(alert).getByRole('button', { name: 'Retry settings' }));
expect(await screen.findByRole('heading', { name: 'Monitoring' })).toBeInTheDocument();
expect(await screen.findByRole('alert')).toHaveTextContent('Settings unavailable');
await user.click(screen.getByRole('button', { name: 'Retry settings' }));
expect(await findCard('Pacing')).toBeInTheDocument();
});
it('validates fields, warns about unsaved changes, and resets to persisted values', async () => {
installConfigApi();
let updateRequests = 0;
server.use(http.put('/api/config', () => {
updateRequests += 1;
return HttpResponse.json({ success: true, config, subreddits: config.subreddits });
}));
const user = userEvent.setup();
renderSettings('/settings?section=monitoring');
const recentWindow = await screen.findByRole('spinbutton', { name: 'Recent window in minutes' });
await user.clear(recentWindow);
await user.type(recentWindow, '0');
expect(screen.getByRole('status')).toHaveTextContent('You have unsaved changes.');
const beforeUnload = new Event('beforeunload', { cancelable: true });
window.dispatchEvent(beforeUnload);
expect(beforeUnload.defaultPrevented).toBe(true);
await user.click(screen.getByRole('button', { name: 'Save settings' }));
expect(screen.getByText('Recent window must be greater than 0 minutes.')).toBeInTheDocument();
expect(recentWindow).toHaveAttribute('aria-invalid', 'true');
expect(screen.getByText('Resolve 1 validation error before saving.')).toBeInTheDocument();
await waitFor(() => expect(recentWindow).toHaveFocus());
expect(updateRequests).toBe(0);
// Discarding a dirty draft requires explicit confirmation.
await user.click(screen.getByRole('button', { name: 'Reset changes' }));
const resetDialog = screen.getByRole('dialog', { name: 'Discard unsaved settings?' });
await user.click(within(resetDialog).getByRole('button', { name: 'Stay' }));
expect(recentWindow).toHaveValue(0);
await user.click(screen.getByRole('button', { name: 'Reset changes' }));
await user.click(within(screen.getByRole('dialog', { name: 'Discard unsaved settings?' })).getByRole('button', { name: 'Discard changes' }));
expect(recentWindow).toHaveValue(60);
expect(screen.queryByText('You have unsaved changes.')).not.toBeInTheDocument();
});
it('rejects blank numeric controls and invalid subreddit fields before transport', async () => {
installConfigApi();
let updateRequests = 0;
server.use(http.put('/api/config', () => {
updateRequests += 1;
return HttpResponse.json({ success: true });
}));
const user = userEvent.setup();
const { router } = renderSettings('/settings?section=rate-limits');
const minimumDelay = await screen.findByRole('spinbutton', { name: 'Minimum delay in minutes' });
await user.clear(minimumDelay);
await user.click(screen.getByRole('button', { name: 'Save settings' }));
expect(screen.getByText('Minimum delay is required.')).toBeInTheDocument();
expect(minimumDelay).toHaveAttribute('aria-invalid', 'true');
await user.click(screen.getByRole('button', { name: 'Behaviour' }));
expect(router.state.location.search).toBe('?section=behaviour');
const subredditName = screen.getByRole('textbox', { name: 'Subreddit 1 name' });
await user.clear(subredditName);
await user.click(screen.getByRole('button', { name: 'Save settings' }));
expect(screen.getByText('Subreddit name is required.')).toBeInTheDocument();
expect(subredditName).toHaveAttribute('aria-invalid', 'true');
await user.type(subredditName, 'example');
const weight = screen.getByRole('spinbutton', { name: 'Subreddit 1 weight' });
await user.clear(weight);
await user.type(weight, '-1');
await user.click(screen.getByRole('button', { name: 'Save settings' }));
expect(screen.getByText('Subreddit weight must be greater than 0.')).toBeInTheDocument();
expect(weight).toHaveAttribute('aria-invalid', 'true');
expect(updateRequests).toBe(0);
});
it('saves validated settings with pending and authoritative success states', async () => {
installConfigApi();
let requestBody: unknown;
let resolveUpdate: ((response: Response) => void) | undefined;
server.use(
http.put('/api/config', async ({ request }) => {
expect(request.credentials).toBe('same-origin');
requestBody = await request.json();
return new Promise<Response>((resolve) => { resolveUpdate = resolve; });
}),
);
const user = userEvent.setup();
renderSettings('/settings?section=monitoring');
const prioritize = await screen.findByRole('checkbox', { name: 'Prioritise recent posts' });
await user.click(prioritize);
await user.click(screen.getByRole('button', { name: 'Save settings' }));
expect(screen.getByRole('button', { name: 'Saving settings' })).toBeDisabled();
await waitFor(() => expect(resolveUpdate).toBeTypeOf('function'));
expect(requestBody).toMatchObject({ reddit: { prioritizeRecentPosts: true, recentWindowMinutes: 60, maxReadyCandidates: 25 } });
resolveUpdate?.(HttpResponse.json({
success: true,
config: {
rateLimit: config.rateLimit,
browser: config.browser,
reddit: { ...config.reddit, prioritizeRecentPosts: true },
},
subreddits: config.subreddits,
}));
expect(await screen.findByText('Settings saved.')).toBeInTheDocument();
expect(screen.queryByText('You have unsaved changes.')).not.toBeInTheDocument();
await user.click(prioritize);
expect(screen.getByText('You have unsaved changes.')).toBeInTheDocument();
expect(screen.queryByText('Settings saved.')).not.toBeInTheDocument();
});
it('validates subreddit rows and confirms disabling dry run before saving behaviour', async () => {
installConfigApi();
let updateRequests = 0;
server.use(
http.put('/api/config', async ({ request }) => {
updateRequests += 1;
const body = await request.json() as { browser: { dryRun: boolean }; subreddits: typeof config.subreddits };
return HttpResponse.json({
success: true,
config: { rateLimit: config.rateLimit, browser: body.browser, reddit: config.reddit },
subreddits: body.subreddits,
});
}),
);
const user = userEvent.setup();
renderSettings('/settings?section=behaviour');
await user.click(await screen.findByRole('button', { name: 'Add subreddit' }));
await user.type(screen.getByRole('textbox', { name: 'Subreddit 2 name' }), 'CasualConversation');
await user.click(screen.getByRole('button', { name: 'Save settings' }));
expect(screen.getByText('Subreddit names must be unique.')).toBeInTheDocument();
expect(updateRequests).toBe(0);
const secondName = screen.getByRole('textbox', { name: 'Subreddit 2 name' });
await user.clear(secondName);
await user.type(secondName, 'askreddit');
await user.click(screen.getByRole('checkbox', { name: 'Dry run mode' }));
await user.click(screen.getByRole('button', { name: 'Save settings' }));
const dialog = screen.getByRole('dialog', { name: 'Confirm risky settings' });
expect(dialog).toHaveTextContent('Automated messages will be sent to Reddit');
expect(updateRequests).toBe(0);
await user.click(within(dialog).getByRole('button', { name: 'Apply risky settings' }));
expect(await screen.findByText('Settings saved.')).toBeInTheDocument();
expect(updateRequests).toBe(1);
});
it('configures autonomous r4r per subreddit and requires explicit confirmation', async () => {
installConfigApi();
let requestBody: { subreddits: Array<{ conversation: { mode: string; maxAutomatedTurns: number; rapportTurnsBeforeMediaAsk: number } }> } | undefined;
server.use(http.put('/api/config', async ({ request }) => {
requestBody = await request.json() as typeof requestBody;
return HttpResponse.json({
success: true,
config: { rateLimit: config.rateLimit, browser: config.browser, reddit: config.reddit },
subreddits: requestBody?.subreddits ?? config.subreddits,
});
}));
const user = userEvent.setup();
renderSettings('/settings?section=behaviour');
const behaviour = await screen.findByRole('combobox', { name: 'Subreddit 1 conversation behaviour' });
expect(behaviour).toHaveValue('legacy');
expect(screen.queryByRole('spinbutton', { name: 'Subreddit 1 maximum automated turns' })).not.toBeInTheDocument();
await user.selectOptions(behaviour, 'r4r');
const maxTurns = screen.getByRole('spinbutton', { name: 'Subreddit 1 maximum automated turns' });
await user.clear(maxTurns);
await user.type(maxTurns, '7');
await user.click(screen.getByRole('button', { name: 'Save settings' }));
const dialog = screen.getByRole('dialog', { name: 'Confirm risky settings' });
expect(dialog).toHaveTextContent('Autonomous R4R will send conversational replies without approval');
expect(requestBody).toBeUndefined();
await user.click(within(dialog).getByRole('button', { name: 'Apply risky settings' }));
await waitFor(() => expect(requestBody?.subreddits[0].conversation).toEqual({
mode: 'r4r', maxAutomatedTurns: 7, rapportTurnsBeforeMediaAsk: 3,
}));
});
it('configures rapport and total turns for the autonomous hybrid mode', async () => {
installConfigApi();
let requestBody: {
subreddits: Array<{
conversation: { mode: string; maxAutomatedTurns: number; rapportTurnsBeforeMediaAsk: number };
}>;
} | undefined;
server.use(http.put('/api/config', async ({ request }) => {
requestBody = await request.json() as typeof requestBody;
return HttpResponse.json({
success: true,
config: { rateLimit: config.rateLimit, browser: config.browser, reddit: config.reddit },
subreddits: requestBody?.subreddits ?? config.subreddits,
});
}));
const user = userEvent.setup();
renderSettings('/settings?section=behaviour');
const behaviour = await screen.findByRole('combobox', { name: 'Subreddit 1 conversation behaviour' });
await user.selectOptions(behaviour, 'r4r-media');
const maxTurns = screen.getByRole('spinbutton', { name: 'Subreddit 1 maximum automated turns' });
const rapportTurns = screen.getByRole('spinbutton', { name: 'Subreddit 1 rapport turns before media ask' });
await user.click(screen.getByRole('button', { name: 'Save settings' }));
expect(screen.getByText('Rapport turns must be lower than the maximum automated turns.')).toBeInTheDocument();
expect(requestBody).toBeUndefined();
await user.clear(maxTurns);
await user.type(maxTurns, '6');
await user.clear(rapportTurns);
await user.type(rapportTurns, '3');
await user.click(screen.getByRole('button', { name: 'Save settings' }));
const dialog = screen.getByRole('dialog', { name: 'Confirm risky settings' });
expect(dialog).toHaveTextContent('hybrid mode can make one optional image request after rapport');
await user.click(within(dialog).getByRole('button', { name: 'Apply risky settings' }));
await waitFor(() => expect(requestBody?.subreddits[0].conversation).toEqual({
mode: 'r4r-media', maxAutomatedTurns: 6, rapportTurnsBeforeMediaAsk: 3,
}));
});
it('validates advanced application JSON before saving', async () => {
installConfigApi();
let updateRequests = 0;
server.use(http.put('/api/config', () => {
updateRequests += 1;
return HttpResponse.json({ success: true, config, subreddits: config.subreddits });
}));
const user = userEvent.setup();
renderSettings('/settings?section=behaviour');
const editor = await screen.findByRole('textbox', { name: 'Advanced configuration JSON' });
await user.clear(editor);
await user.type(editor, 'invalid');
await user.click(screen.getByRole('button', { name: 'Save settings' }));
expect(screen.getByText('Advanced configuration is not valid JSON.')).toBeInTheDocument();
expect(updateRequests).toBe(0);
});
it('confirms unusually large hourly limits', async () => {
installConfigApi();
let updateRequests = 0;
server.use(http.put('/api/config', () => {
updateRequests += 1;
return HttpResponse.json({ success: true, config, subreddits: config.subreddits });
}));
const user = userEvent.setup();
renderSettings('/settings?section=rate-limits');
const hourlyLimit = await screen.findByRole('spinbutton', { name: 'Maximum messages per hour' });
await user.clear(hourlyLimit);
await user.type(hourlyLimit, '50');
await user.click(screen.getByRole('button', { name: 'Save settings' }));
expect(screen.getByRole('dialog', { name: 'Confirm risky settings' })).toHaveTextContent('50 messages per hour');
expect(updateRequests).toBe(0);
});
it('confirms in-app navigation away from dirty settings and can discard the draft', async () => {
installConfigApi();
const user = userEvent.setup();
const { router } = renderSettings('/settings?section=monitoring');
const recentWindow = await screen.findByRole('spinbutton', { name: 'Recent window in minutes' });
await user.clear(recentWindow);
await user.type(recentWindow, '45');
await act(async () => { await router.navigate('/elsewhere'); });
const stayDialog = await screen.findByRole('dialog', { name: 'Discard unsaved settings?' });
await user.click(within(stayDialog).getByRole('button', { name: 'Stay' }));
expect(router.state.location.pathname).toBe('/settings');
expect(screen.getByRole('spinbutton', { name: 'Recent window in minutes' })).toHaveValue(45);
await act(async () => { await router.navigate('/elsewhere'); });
const discardDialog = await screen.findByRole('dialog', { name: 'Discard unsaved settings?' });
await user.click(within(discardDialog).getByRole('button', { name: 'Discard changes' }));
await waitFor(() => expect(router.state.location.pathname).toBe('/elsewhere'));
expect(screen.getByRole('heading', { name: 'Elsewhere' })).toBeInTheDocument();
});
it('requires confirmation for an autonomous mode on a renamed subreddit, matched by name not index', async () => {
const r4rConfig = {
...config,
subreddits: [{
name: 'casualconversation', type: 'chat', weight: 2, tone: 'default',
conversation: { mode: 'r4r', maxAutomatedTurns: 5, rapportTurnsBeforeMediaAsk: 3 },
}],
};
let updateRequests = 0;
server.use(
http.get('/api/config', () => HttpResponse.json(r4rConfig)),
http.put('/api/config', () => {
updateRequests += 1;
return HttpResponse.json({
success: true,
config: { rateLimit: config.rateLimit, browser: config.browser, reddit: config.reddit },
subreddits: r4rConfig.subreddits,
});
}),
);
const user = userEvent.setup();
renderSettings('/settings?section=behaviour');
// The persisted row is already r4r at index 0; giving the row a new name is
// equivalent to inserting a new r4r-enabled row, so it must be re-confirmed.
const name = await screen.findByRole('textbox', { name: 'Subreddit 1 name' });
await user.clear(name);
await user.type(name, 'brandnewplace');
await user.click(screen.getByRole('button', { name: 'Save settings' }));
const dialog = screen.getByRole('dialog', { name: 'Confirm risky settings' });
expect(dialog).toHaveTextContent('Autonomous R4R will send conversational replies without approval');
expect(updateRequests).toBe(0);
});
it('does not re-confirm an unchanged autonomous subreddit when a row before it is removed', async () => {
const twoSubredditConfig = {
...config,
subreddits: [
{ name: 'general', type: 'chat', weight: 1, tone: 'default', conversation: { mode: 'legacy', maxAutomatedTurns: 3, rapportTurnsBeforeMediaAsk: 3 } },
{ name: 'r4rlondon', type: 'chat', weight: 1, tone: 'default', conversation: { mode: 'r4r', maxAutomatedTurns: 5, rapportTurnsBeforeMediaAsk: 3 } },
],
};
let updateRequests = 0;
server.use(
http.get('/api/config', () => HttpResponse.json(twoSubredditConfig)),
http.put('/api/config', async ({ request }) => {
updateRequests += 1;
const body = await request.json() as { subreddits: typeof twoSubredditConfig.subreddits };
return HttpResponse.json({
success: true,
config: { rateLimit: config.rateLimit, browser: config.browser, reddit: config.reddit },
subreddits: body.subreddits,
});
}),
);
const user = userEvent.setup();
renderSettings('/settings?section=behaviour');
// Removing the first row shifts the r4r row to index 0; by-name matching
// must recognise it as already approved and save without a risk dialog.
await user.click(await screen.findByRole('button', { name: 'Remove subreddit 1' }));
await user.click(screen.getByRole('button', { name: 'Save settings' }));
expect(screen.queryByRole('dialog', { name: 'Confirm risky settings' })).not.toBeInTheDocument();
expect(await screen.findByText('Settings saved.')).toBeInTheDocument();
expect(updateRequests).toBe(1);
});
it('notices a server-side config change while the draft is dirty and loads it on reset', async () => {
installConfigApi();
const user = userEvent.setup();
const { queryClient } = renderSettings('/settings?section=monitoring');
const recentWindow = await screen.findByRole('spinbutton', { name: 'Recent window in minutes' });
await user.clear(recentWindow);
await user.type(recentWindow, '45');
act(() => {
queryClient.setQueryData(['dashboard', 'config'], {
...config,
reddit: { ...config.reddit, maxReadyCandidates: 99 },
subreddits: [{
name: 'casualconversation', type: 'chat', weight: 2, tone: 'default',
conversation: { mode: 'legacy', maxAutomatedTurns: 3, rapportTurnsBeforeMediaAsk: 3 },
}],
});
describe('legacy section links', () => {
it('redirects the subreddit tab to the subreddits page', async () => {
renderSettings('/settings?section=behaviour');
expect(await screen.findByRole('heading', { name: 'Subreddits page' })).toBeInTheDocument();
});
expect(await screen.findByText('Settings changed on the server — Reset to load them.')).toBeInTheDocument();
expect(recentWindow).toHaveValue(45);
it('redirects the access tab to the accounts page', async () => {
renderSettings('/settings?section=access');
expect(await screen.findByRole('heading', { name: 'Accounts page' })).toBeInTheDocument();
});
await user.click(screen.getByRole('button', { name: 'Reset changes' }));
await user.click(within(screen.getByRole('dialog', { name: 'Discard unsaved settings?' })).getByRole('button', { name: 'Discard changes' }));
expect(screen.getByRole('spinbutton', { name: 'Recent window in minutes' })).toHaveValue(60);
expect(screen.getByRole('spinbutton', { name: 'Maximum ready posts' })).toHaveValue(99);
it('keeps former in-page tabs on the settings page', async () => {
renderSettings('/settings?section=rate-limits');
expect(await findCard('Pacing')).toBeInTheDocument();
});
});
it('rejects a non-JSON session dump inline without sending a request', async () => {
let importRequests = 0;
server.use(
http.get('/api/config', () => HttpResponse.json(config)),
http.get('/api/login/status', () => HttpResponse.json({ ready: true, loggedIn: false, status: 'login-required' })),
http.post('/api/login/session-import', () => {
importRequests += 1;
return HttpResponse.json({ ok: true });
}),
);
const user = userEvent.setup();
renderSettings('/settings?section=access');
describe('pacing', () => {
it('reports the effective rate when the minimum delay is the binding limit', async () => {
renderSettings();
const pacing = await findCard('Pacing');
const brokenDump = new File(['definitely not json'], 'broken.json', { type: 'application/json' });
await user.upload(await screen.findByLabelText('Reddit session export'), brokenDump);
// 5 min minimum delay caps sending at 12/hr, below the 8/hr limit... so
// here the limit binds. Raise the delay and the readout should flip.
expect(pacing).toHaveTextContent('8 messages per hour');
expect(pacing).toHaveTextContent('the hourly limit is the binding limit');
expect(await screen.findByText(/isn't valid JSON/)).toBeInTheDocument();
expect(importRequests).toBe(0);
const user = userEvent.setup();
const delay = within(pacing).getByRole('spinbutton', { name: 'Minimum delay' });
await user.clear(delay);
await user.type(delay, '30');
expect(pacing).toHaveTextContent('2 messages per hour');
expect(pacing).toHaveTextContent('the minimum delay is the binding limit');
});
it('rejects blank and out-of-range values before sending anything', async () => {
installConfigWriter();
const user = userEvent.setup();
renderSettings();
const pacing = await findCard('Pacing');
await user.clear(within(pacing).getByRole('spinbutton', { name: 'Minimum delay' }));
const readyPosts = within(pacing).getByRole('spinbutton', { name: 'Maximum ready posts' });
await user.clear(readyPosts);
await user.type(readyPosts, '900');
await user.click(within(pacing).getByRole('button', { name: 'Save pacing' }));
expect(within(pacing).getByText('Minimum delay is required.')).toBeInTheDocument();
expect(within(pacing).getByText('Ready-post limit cannot exceed 500.')).toBeInTheDocument();
expect(saved).toHaveLength(0);
});
it('saves only the keys it owns, never the subreddit array', async () => {
installConfigWriter();
const user = userEvent.setup();
renderSettings();
const pacing = await findCard('Pacing');
const jitter = within(pacing).getByRole('spinbutton', { name: 'Random jitter' });
await user.clear(jitter);
await user.type(jitter, '90');
await user.click(within(pacing).getByRole('button', { name: 'Save pacing' }));
await waitFor(() => expect(saved).toHaveLength(1));
expect(saved[0]).toEqual({
rateLimit: { minDelayBetweenMessagesMs: 300_000, maxMessagesPerHour: 8, jitterMs: 90_000 },
reddit: { prioritizeRecentPosts: false, recentWindowMinutes: 60, maxReadyCandidates: 25 },
});
expect(saved[0]).not.toHaveProperty('subreddits');
expect(saved[0]).not.toHaveProperty('browser');
expect(await within(pacing).findByText('Pacing saved.')).toBeInTheDocument();
});
it('confirms an unusually large hourly limit before applying it', async () => {
installConfigWriter();
const user = userEvent.setup();
renderSettings();
const pacing = await findCard('Pacing');
const limit = within(pacing).getByRole('spinbutton', { name: 'Hourly limit' });
await user.clear(limit);
await user.type(limit, '60');
await user.click(within(pacing).getByRole('button', { name: 'Save pacing' }));
expect(await screen.findByText(/will allow 60 messages per hour/)).toBeInTheDocument();
expect(saved).toHaveLength(0);
await user.click(screen.getByRole('button', { name: 'Apply risky settings' }));
await waitFor(() => expect(saved).toHaveLength(1));
});
it('resets edits back to the persisted values', async () => {
const user = userEvent.setup();
renderSettings();
const pacing = await findCard('Pacing');
const limit = within(pacing).getByRole('spinbutton', { name: 'Hourly limit' });
await user.clear(limit);
await user.type(limit, '19');
expect(within(pacing).getByRole('status')).toHaveTextContent('Unsaved changes in this section.');
await user.click(within(pacing).getByRole('button', { name: 'Reset' }));
expect(limit).toHaveValue(8);
expect(within(pacing).getByText('Saved.')).toBeInTheDocument();
});
});
it('waits for and imports an extension dump without exposing credentials', async () => {
let statusRequests = 0;
let importRequests = 0;
server.use(
http.get('/api/config', () => HttpResponse.json(config)),
http.get('/api/login/status', () => {
statusRequests += 1;
return HttpResponse.json(statusRequests === 1
? { ready: true, loggedIn: false, status: 'login-required' }
: { ready: true, loggedIn: true, status: 'authenticated', username: 'example-account' });
}),
http.get('/api/accounts', () => HttpResponse.json([{
accountId: '@t2_bot:reddit.com', redditUsername: 'example-account', matrixUserId: '@t2_bot:reddit.com',
isRunning: true, status: 'authenticated', createdAt: 1, updatedAt: 2, lastImportedAt: 2,
}])),
http.post('/api/login/session-import', async ({ request }) => {
expect(request.credentials).toBe('same-origin');
const body = await request.json() as { cookies: unknown[]; matrix: { accessToken: string } };
expect(body.cookies).toHaveLength(1);
expect(body.matrix.accessToken).toBe('matrix-secret');
importRequests += 1;
return HttpResponse.json({ ok: true, status: 'authenticated', account: {
accountId: '@t2_bot:reddit.com', redditUsername: 'example-account', matrixUserId: '@t2_bot:reddit.com',
isRunning: true, status: 'authenticated', createdAt: 1, updatedAt: 2, lastImportedAt: 2,
} });
}),
);
describe('safety', () => {
it('states the current sending state before offering the switch', async () => {
renderSettings();
const safety = await findCard('Safety');
expect(within(safety).getByRole('status')).toHaveTextContent('No messages are being sent.');
expect(within(safety).getByText('Dry run')).toBeInTheDocument();
});
it('requires confirmation before dry run is turned off', async () => {
installConfigWriter();
const user = userEvent.setup();
renderSettings();
const safety = await findCard('Safety');
await user.click(within(safety).getByRole('checkbox', { name: 'Dry run mode' }));
await user.click(within(safety).getByRole('button', { name: 'Save safety' }));
expect(await screen.findByText(/Dry run is being turned off/)).toBeInTheDocument();
expect(saved).toHaveLength(0);
await user.click(screen.getByRole('button', { name: 'Apply risky settings' }));
await waitFor(() => expect(saved).toEqual([{ browser: { dryRun: false } }]));
expect(await within(safety).findByText('Sending live')).toBeInTheDocument();
});
it('does not re-confirm when dry run is left off', async () => {
config = { ...structuredClone(baseConfig), browser: { dryRun: false } };
installConfigWriter();
const user = userEvent.setup();
renderSettings();
const safety = await findCard('Safety');
// Toggle on and back off: the persisted value never allowed sending to
// start, so there is nothing to confirm.
await user.click(within(safety).getByRole('checkbox', { name: 'Dry run mode' }));
await user.click(within(safety).getByRole('checkbox', { name: 'Dry run mode' }));
expect(within(safety).getByRole('button', { name: 'Save safety' })).toBeDisabled();
});
});
describe('advanced', () => {
it('stays locked behind a deliberate step and lists what it holds', async () => {
renderSettings();
const advanced = await findCard('Advanced');
expect(within(advanced).getByText('Locked')).toBeInTheDocument();
expect(within(advanced).getByText('openrouter')).toBeInTheDocument();
expect(within(advanced).queryByRole('textbox')).not.toBeInTheDocument();
await userEvent.setup().click(within(advanced).getByRole('button', { name: 'Edit raw configuration' }));
expect(within(card('Advanced')).getByRole('textbox', { name: 'Advanced configuration (JSON)' })).toBeInTheDocument();
});
it('explains why the JSON is invalid instead of silently blocking', async () => {
installConfigWriter();
const user = userEvent.setup();
renderSettings();
await user.click(within(await findCard('Advanced')).getByRole('button', { name: 'Edit raw configuration' }));
const editor = within(card('Advanced')).getByRole('textbox', { name: 'Advanced configuration (JSON)' });
await user.clear(editor);
await user.type(editor, '{{"openrouter": ');
await user.click(within(card('Advanced')).getByRole('button', { name: 'Save advanced' }));
expect(within(card('Advanced')).getByText(/Not valid JSON/)).toBeInTheDocument();
expect(saved).toHaveLength(0);
});
it('rejects a JSON array, which would not merge as configuration', async () => {
installConfigWriter();
const user = userEvent.setup();
renderSettings();
await user.click(within(await findCard('Advanced')).getByRole('button', { name: 'Edit raw configuration' }));
const editor = within(card('Advanced')).getByRole('textbox', { name: 'Advanced configuration (JSON)' });
await user.clear(editor);
await user.type(editor, '[[1]');
await user.click(within(card('Advanced')).getByRole('button', { name: 'Save advanced' }));
expect(within(card('Advanced')).getByText(/must be a JSON object/)).toBeInTheDocument();
expect(saved).toHaveLength(0);
});
it('saves valid JSON on its own', async () => {
installConfigWriter();
const user = userEvent.setup();
renderSettings();
await user.click(within(await findCard('Advanced')).getByRole('button', { name: 'Edit raw configuration' }));
const editor = within(card('Advanced')).getByRole('textbox', { name: 'Advanced configuration (JSON)' });
await user.clear(editor);
await user.type(editor, '{{"openrouter": {{"chatModel": "other/model"}}');
await user.click(within(card('Advanced')).getByRole('button', { name: 'Save advanced' }));
await waitFor(() => expect(saved).toEqual([{ advanced: { openrouter: { chatModel: 'other/model' } } }]));
});
});
describe('card independence', () => {
it('lets pacing save while the advanced JSON is broken', async () => {
installConfigWriter();
const user = userEvent.setup();
renderSettings();
await user.click(within(await findCard('Advanced')).getByRole('button', { name: 'Edit raw configuration' }));
const editor = within(card('Advanced')).getByRole('textbox', { name: 'Advanced configuration (JSON)' });
await user.clear(editor);
await user.type(editor, 'not json at all');
const pacing = card('Pacing');
const jitter = within(pacing).getByRole('spinbutton', { name: 'Random jitter' });
await user.clear(jitter);
await user.type(jitter, '15');
await user.click(within(pacing).getByRole('button', { name: 'Save pacing' }));
await waitFor(() => expect(saved).toHaveLength(1));
expect(saved[0]).toHaveProperty('rateLimit');
expect(saved[0]).not.toHaveProperty('advanced');
expect(await within(card('Pacing')).findByText('Pacing saved.')).toBeInTheDocument();
});
it('does not report another card as changed on the server after a sibling saves', async () => {
installConfigWriter();
const user = userEvent.setup();
renderSettings();
const safety = await findCard('Safety');
// Leave pacing dirty, then save safety. Pacing must not claim the server
// moved underneath it: nothing it owns actually changed.
const limit = within(card('Pacing')).getByRole('spinbutton', { name: 'Hourly limit' });
await user.clear(limit);
await user.type(limit, '9');
await user.click(within(safety).getByRole('checkbox', { name: 'Dry run mode' }));
await user.click(within(safety).getByRole('button', { name: 'Save safety' }));
await user.click(await screen.findByRole('button', { name: 'Apply risky settings' }));
await waitFor(() => expect(saved).toHaveLength(1));
expect(within(card('Pacing')).queryByText(/Changed on the server/)).not.toBeInTheDocument();
expect(within(card('Pacing')).getByRole('spinbutton', { name: 'Hourly limit' })).toHaveValue(9);
});
it('flags a genuine server-side change and loads it on reset', async () => {
const user = userEvent.setup();
const { queryClient } = renderSettings();
const pacing = await findCard('Pacing');
const limit = within(pacing).getByRole('spinbutton', { name: 'Hourly limit' });
await user.clear(limit);
await user.type(limit, '11');
config = { ...structuredClone(baseConfig), rateLimit: { ...baseConfig.rateLimit, maxMessagesPerHour: 40 } };
await queryClient.refetchQueries({ queryKey: ['dashboard', 'config'] });
expect(await within(card('Pacing')).findByText(/Changed on the server/)).toBeInTheDocument();
await user.click(within(card('Pacing')).getByRole('button', { name: 'Reset' }));
expect(within(card('Pacing')).getByRole('spinbutton', { name: 'Hourly limit' })).toHaveValue(40);
});
});
it('confirms navigation away while any card is dirty, and can discard', async () => {
const user = userEvent.setup();
renderSettings('/settings?section=access');
const { router } = renderSettings();
const pacing = await findCard('Pacing');
expect(await screen.findByText('Login required')).toBeInTheDocument();
expect(screen.getByText(/waiting for a fresh session dump/i)).toBeInTheDocument();
expect(screen.queryByText(/noVNC/i)).not.toBeInTheDocument();
expect(screen.queryByRole('textbox', { name: /password/i })).not.toBeInTheDocument();
const jitter = within(pacing).getByRole('spinbutton', { name: 'Random jitter' });
await user.clear(jitter);
await user.type(jitter, '45');
const dump = new File([JSON.stringify({
cookies: [{ name: 'reddit_session', value: 'secret', domain: '.reddit.com', path: '/' }],
matrix: {
homeserver: 'https://matrix.redditspace.com', accessToken: 'matrix-secret',
userId: '@t2_bot:reddit.com', capturedAt: 1_700_000_000_000,
},
})], 'redditbot-session.json', { type: 'application/json' });
await user.upload(screen.getByLabelText('Reddit session export'), dump);
await act(() => router.navigate('/elsewhere'));
expect(await screen.findByRole('heading', { name: 'Leave without saving?' })).toBeInTheDocument();
expect(router.state.location.pathname).toBe('/settings');
expect(await screen.findByText('Reddit session imported and verified.')).toBeInTheDocument();
expect(importRequests).toBe(1);
expect(await screen.findByText('Authenticated')).toBeInTheDocument();
expect(screen.getAllByText(/u\/example-account/)).toHaveLength(2);
expect(screen.getAllByRole('link', { name: 'u/example-account' })[0]).toHaveAttribute(
'href',
'https://www.reddit.com/u/example-account',
);
await user.click(screen.getByRole('button', { name: 'Recheck accounts' }));
expect(statusRequests).toBeGreaterThanOrEqual(2);
await user.click(screen.getByRole('button', { name: 'Discard and leave' }));
await waitFor(() => expect(router.state.location.pathname).toBe('/elsewhere'));
});
});