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), Targeting, 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. Physique targeting moves into its own Targeting card. It sends only reddit.physiqueTargeting, which the config route applies independently, so it cannot clobber the pacing card's fields. Turning screening on now warns that it will reduce how many posts qualify. 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. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
11b6300113
commit
c43e534cf1
36 files changed
+4414
-1632
No files matched your search
@@ -0,0 +1,184 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import '@testing-library/jest-dom/vitest';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { cleanup, render, screen, within } from '@testing-library/react';
|
||||
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 { createMemoryRouter, RouterProvider } from 'react-router-dom';
|
||||
import { AccountsPage } from '../../apps/dashboard/src/features/accounts/accounts-page.js';
|
||||
|
||||
const account = {
|
||||
accountId: '@t2_bot:reddit.com',
|
||||
redditUsername: 'example-account',
|
||||
matrixUserId: '@t2_bot:reddit.com',
|
||||
isRunning: true,
|
||||
status: 'authenticated',
|
||||
createdAt: 1,
|
||||
updatedAt: 2,
|
||||
lastImportedAt: 2,
|
||||
};
|
||||
|
||||
const server = setupServer(
|
||||
http.get('/api/login/status', () => HttpResponse.json({ ready: true, loggedIn: false, status: 'login-required' })),
|
||||
http.get('/api/accounts', () => HttpResponse.json([])),
|
||||
);
|
||||
|
||||
function renderAccounts() {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
|
||||
});
|
||||
const router = createMemoryRouter([{ path: '/accounts', element: <AccountsPage /> }], {
|
||||
initialEntries: ['/accounts'],
|
||||
});
|
||||
return render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<RouterProvider router={router} />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
function sessionDump() {
|
||||
return 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' });
|
||||
}
|
||||
|
||||
beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
server.resetHandlers();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
afterAll(() => server.close());
|
||||
|
||||
describe('accounts page', () => {
|
||||
it('reports the session state and how to fix it, without asking for credentials', async () => {
|
||||
renderAccounts();
|
||||
|
||||
expect(await screen.findByText('Login required')).toBeInTheDocument();
|
||||
expect(screen.getByRole('heading', { name: 'Getting a session dump' })).toBeInTheDocument();
|
||||
expect(screen.getByText(/contains login credentials/i)).toBeInTheDocument();
|
||||
// The dashboard never collects Reddit credentials itself.
|
||||
expect(screen.queryByRole('textbox', { name: /password/i })).not.toBeInTheDocument();
|
||||
expect(screen.queryByText(/noVNC/i)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls out paused accounts as needing a refreshed session', async () => {
|
||||
server.use(http.get('/api/accounts', () => HttpResponse.json([{ ...account, isRunning: false, status: 'login-required' }])));
|
||||
renderAccounts();
|
||||
|
||||
expect(await screen.findByText('One account is paused.')).toBeInTheDocument();
|
||||
expect(screen.getByText(/Other accounts keep running normally/)).toBeInTheDocument();
|
||||
expect(screen.getByText('Waiting for a refreshed session')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('says plainly when no accounts have been added', async () => {
|
||||
renderAccounts();
|
||||
|
||||
expect(await screen.findByText('No accounts yet')).toBeInTheDocument();
|
||||
expect(screen.queryByText(/accounts? is paused/)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('rejects a non-JSON session dump inline without sending a request', async () => {
|
||||
let importRequests = 0;
|
||||
server.use(
|
||||
http.post('/api/login/session-import', () => {
|
||||
importRequests += 1;
|
||||
return HttpResponse.json({ ok: true });
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
renderAccounts();
|
||||
|
||||
const broken = new File(['definitely not json'], 'broken.json', { type: 'application/json' });
|
||||
await user.upload(await screen.findByLabelText('Reddit session export'), broken);
|
||||
|
||||
expect(await screen.findByText(/isn't valid JSON/)).toBeInTheDocument();
|
||||
expect(importRequests).toBe(0);
|
||||
});
|
||||
|
||||
it('imports an extension dump and reflects the verified account', async () => {
|
||||
let statusRequests = 0;
|
||||
let importRequests = 0;
|
||||
server.use(
|
||||
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(statusRequests === 1 ? [] : [account])),
|
||||
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 });
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
renderAccounts();
|
||||
|
||||
await user.upload(await screen.findByLabelText('Reddit session export'), sessionDump());
|
||||
|
||||
expect(await screen.findByText(/Session imported and verified/)).toBeInTheDocument();
|
||||
expect(importRequests).toBe(1);
|
||||
expect(await screen.findByText('Authenticated')).toBeInTheDocument();
|
||||
|
||||
const link = screen.getAllByRole('link', { name: 'u/example-account' })[0];
|
||||
expect(link).toHaveAttribute('href', 'https://www.reddit.com/u/example-account');
|
||||
});
|
||||
|
||||
it('rechecks sessions on request', async () => {
|
||||
let statusRequests = 0;
|
||||
server.use(
|
||||
http.get('/api/login/status', () => {
|
||||
statusRequests += 1;
|
||||
return HttpResponse.json({ ready: true, loggedIn: false, status: 'login-required' });
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
renderAccounts();
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'Recheck accounts' }));
|
||||
expect(statusRequests).toBeGreaterThanOrEqual(2);
|
||||
});
|
||||
|
||||
it('shows a recoverable error when access cannot be checked', async () => {
|
||||
let requests = 0;
|
||||
server.use(
|
||||
http.get('/api/login/status', () => {
|
||||
requests += 1;
|
||||
return requests === 1
|
||||
? HttpResponse.json({ error: 'nope' }, { status: 500 })
|
||||
: HttpResponse.json({ ready: true, loggedIn: false, status: 'login-required' });
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
renderAccounts();
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('Reddit access unavailable');
|
||||
await user.click(screen.getByRole('button', { name: 'Retry access' }));
|
||||
expect(await screen.findByRole('region', { name: 'Reddit accounts' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('reports an account list failure separately from the session check', async () => {
|
||||
server.use(http.get('/api/accounts', () => HttpResponse.json({ error: 'nope' }, { status: 500 })));
|
||||
renderAccounts();
|
||||
|
||||
const region = await screen.findByRole('region', { name: 'Reddit accounts' });
|
||||
expect(within(region).getByRole('alert')).toHaveTextContent('Could not load Reddit accounts');
|
||||
// The page itself still renders, so the import button stays available.
|
||||
expect(screen.getByRole('button', { name: 'Add or refresh account' })).toBeEnabled();
|
||||
});
|
||||
});
|
||||
@@ -491,7 +491,7 @@ describe('ConversationsPage', () => {
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'New conversation' }));
|
||||
expect(await screen.findByText(/No running accounts/)).toBeInTheDocument();
|
||||
expect(screen.getByRole('link', { name: 'Settings' })).toHaveAttribute('href', '/settings');
|
||||
expect(screen.getByRole('link', { name: 'Accounts' })).toHaveAttribute('href', '/accounts');
|
||||
expect(screen.queryByRole('button', { name: 'Start conversation' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ import { SettingsRoute } from '../../apps/dashboard/src/features/settings/settin
|
||||
const config = {
|
||||
rateLimit: { minDelayBetweenMessagesMs: 300_000, maxMessagesPerHour: 8, jitterMs: 60_000 },
|
||||
browser: { dryRun: true },
|
||||
reddit: { prioritizeRecentPosts: false, recentWindowMinutes: 60, maxReadyCandidates: 25 },
|
||||
reddit: { prioritizeRecentPosts: false, recentWindowMinutes: 60, maxReadyCandidates: 25, physiqueTargeting: { enabled: false, minScore: 1, maxScore: 10 } },
|
||||
subreddits: [{ name: 'casualconversation', type: 'chat', weight: 2, tone: 'default' }],
|
||||
tones: ['default', 'dominant', 'submissive', 'playful', 'direct', 'gentle', 'kink-friendly', 'teasing'],
|
||||
};
|
||||
@@ -111,7 +111,7 @@ describe('push notification settings', () => {
|
||||
topic: 'redditbot-7f3a9c21',
|
||||
events: { imageReceived: true, replyReceived: true },
|
||||
});
|
||||
expect(await within(panel()).findByText('Notification settings saved.')).toBeInTheDocument();
|
||||
expect(await within(panel()).findByText('Notifications saved.')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('refuses to save an enabled configuration with no topic', async () => {
|
||||
@@ -148,7 +148,7 @@ describe('push notification settings', () => {
|
||||
renderSettings();
|
||||
await screen.findByRole('region', { name: 'Notifications' });
|
||||
|
||||
await user.click(within(panel()).getByRole('button', { name: /Send test notification/ }));
|
||||
await user.click(within(panel()).getByRole('button', { name: /Send test/ }));
|
||||
|
||||
expect(await within(panel()).findByText(/ntfy responded 403 Forbidden/)).toBeInTheDocument();
|
||||
});
|
||||
@@ -161,7 +161,7 @@ describe('push notification settings', () => {
|
||||
|
||||
await user.click(within(panel()).getByRole('checkbox', { name: /Sync failed/ }));
|
||||
|
||||
expect(within(panel()).getByRole('button', { name: /Send test notification/ })).toBeDisabled();
|
||||
expect(within(panel()).getByRole('button', { name: /Send test/ })).toBeDisabled();
|
||||
});
|
||||
|
||||
it('reports that an access token is configured without revealing it', async () => {
|
||||
|
||||
@@ -0,0 +1,346 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
createPacingDraft,
|
||||
createTargetingDraft,
|
||||
targetingRisks,
|
||||
validateTargetingDraft,
|
||||
estimateThroughput,
|
||||
pacingRisks,
|
||||
safetyRisks,
|
||||
validateAdvancedDraft,
|
||||
validatePacingDraft,
|
||||
type PacingDraft,
|
||||
} from '../../apps/dashboard/src/features/settings/settings-model.js';
|
||||
import {
|
||||
computeShares,
|
||||
formatShare,
|
||||
normaliseSubredditName,
|
||||
previewShare,
|
||||
validateSubredditDraft,
|
||||
createEmptySubredditDraft,
|
||||
type SubredditConfig,
|
||||
type SubredditDraft,
|
||||
} from '../../apps/dashboard/src/features/subreddits/subreddit-model.js';
|
||||
|
||||
function pacing(overrides: Partial<PacingDraft> = {}): PacingDraft {
|
||||
return {
|
||||
minDelayMinutes: '5',
|
||||
maxMessagesPerHour: '8',
|
||||
jitterSeconds: '60',
|
||||
prioritizeRecentPosts: false,
|
||||
recentWindowMinutes: '60',
|
||||
maxReadyCandidates: '25',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function subreddit(overrides: Partial<SubredditConfig> = {}): SubredditConfig {
|
||||
return {
|
||||
name: 'example',
|
||||
enabled: true,
|
||||
type: 'chat',
|
||||
tone: 'default',
|
||||
conversation: { mode: 'legacy', maxAutomatedTurns: 3, rapportTurnsBeforeMediaAsk: 3 },
|
||||
...overrides,
|
||||
} as SubredditConfig;
|
||||
}
|
||||
|
||||
function draft(overrides: Partial<SubredditDraft> = {}): SubredditDraft {
|
||||
return { ...createEmptySubredditDraft(), name: 'example', ...overrides };
|
||||
}
|
||||
|
||||
describe('createPacingDraft', () => {
|
||||
it('converts stored milliseconds into the units the operator types', () => {
|
||||
const result = createPacingDraft({
|
||||
rateLimit: { minDelayBetweenMessagesMs: 300_000, maxMessagesPerHour: 8, jitterMs: 90_000 },
|
||||
browser: { dryRun: true },
|
||||
reddit: { prioritizeRecentPosts: true, recentWindowMinutes: 45, maxReadyCandidates: 30, physiqueTargeting: { enabled: false, minScore: 1, maxScore: 10 } },
|
||||
subreddits: [],
|
||||
tones: [],
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
minDelayMinutes: '5',
|
||||
maxMessagesPerHour: '8',
|
||||
jitterSeconds: '90',
|
||||
prioritizeRecentPosts: true,
|
||||
recentWindowMinutes: '45',
|
||||
maxReadyCandidates: '30',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('validatePacingDraft', () => {
|
||||
it('converts back into milliseconds and omits keys it does not own', () => {
|
||||
const { payload, errors } = validatePacingDraft(pacing({ jitterSeconds: '30' }));
|
||||
|
||||
expect(errors).toEqual({});
|
||||
expect(payload).toEqual({
|
||||
rateLimit: { minDelayBetweenMessagesMs: 300_000, maxMessagesPerHour: 8, jitterMs: 30_000 },
|
||||
reddit: { prioritizeRecentPosts: false, recentWindowMinutes: 60, maxReadyCandidates: 25, physiqueTargeting: { enabled: false, minScore: 1, maxScore: 10 } },
|
||||
});
|
||||
});
|
||||
|
||||
it('collects every problem in one pass rather than one at a time', () => {
|
||||
const { payload, errors } = validatePacingDraft(pacing({
|
||||
minDelayMinutes: '',
|
||||
jitterSeconds: '-1',
|
||||
maxReadyCandidates: '0',
|
||||
}));
|
||||
|
||||
expect(payload).toBeUndefined();
|
||||
expect(Object.keys(errors).sort()).toEqual(['jitterSeconds', 'maxReadyCandidates', 'minDelayMinutes']);
|
||||
});
|
||||
|
||||
it('rejects a fractional hourly limit', () => {
|
||||
expect(validatePacingDraft(pacing({ maxMessagesPerHour: '2.5' })).errors)
|
||||
.toHaveProperty('maxMessagesPerHour');
|
||||
});
|
||||
});
|
||||
|
||||
describe('pacingRisks', () => {
|
||||
it('warns only when the limit both rises and clears the safe ceiling', () => {
|
||||
expect(pacingRisks(pacing({ maxMessagesPerHour: '21' }), pacing())).toHaveLength(1);
|
||||
expect(pacingRisks(pacing({ maxMessagesPerHour: '20' }), pacing())).toEqual([]);
|
||||
// Lowering an already-high limit is a de-escalation, not a risk.
|
||||
expect(pacingRisks(pacing({ maxMessagesPerHour: '30' }), pacing({ maxMessagesPerHour: '40' }))).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('safetyRisks', () => {
|
||||
it('warns only on the transition from dry run into live sending', () => {
|
||||
expect(safetyRisks({ dryRun: false }, { dryRun: true })).toHaveLength(1);
|
||||
expect(safetyRisks({ dryRun: true }, { dryRun: false })).toEqual([]);
|
||||
expect(safetyRisks({ dryRun: false }, { dryRun: false })).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('estimateThroughput', () => {
|
||||
it('reports the hourly cap when it binds before the delay', () => {
|
||||
const estimate = estimateThroughput(pacing({ minDelayMinutes: '5', jitterSeconds: '0' }));
|
||||
expect(estimate).toMatchObject({ effectivePerHour: 8, isDelayBound: false });
|
||||
});
|
||||
|
||||
it('reports the delay when it binds before the hourly cap', () => {
|
||||
const estimate = estimateThroughput(pacing({ minDelayMinutes: '30', jitterSeconds: '0' }));
|
||||
expect(estimate).toMatchObject({ effectivePerHour: 2, isDelayBound: true });
|
||||
});
|
||||
|
||||
it('counts average jitter as part of the spacing', () => {
|
||||
// 10 min delay plus 120s average jitter (half of 240) is 12 min spacing.
|
||||
const estimate = estimateThroughput(pacing({ minDelayMinutes: '10', jitterSeconds: '240' }));
|
||||
expect(estimate?.spacingLabel).toBe('about one every 12 min');
|
||||
expect(estimate?.effectivePerHour).toBe(5);
|
||||
});
|
||||
|
||||
it('gives up on unusable numbers rather than reporting nonsense', () => {
|
||||
expect(estimateThroughput(pacing({ minDelayMinutes: '' }))).toBeNull();
|
||||
expect(estimateThroughput(pacing({ maxMessagesPerHour: '0' }))).toBeNull();
|
||||
expect(estimateThroughput(pacing({ jitterSeconds: '-5' }))).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('validateTargetingDraft', () => {
|
||||
const base = { physiqueTargetingEnabled: true, physiqueMinScore: '3', physiqueMaxScore: '8' };
|
||||
|
||||
it('sends only the physique range, so sibling reddit fields survive', () => {
|
||||
expect(validateTargetingDraft(base).payload).toEqual({
|
||||
reddit: { physiqueTargeting: { enabled: true, minScore: 3, maxScore: 8 } },
|
||||
});
|
||||
});
|
||||
|
||||
it('allows a single-point range', () => {
|
||||
expect(validateTargetingDraft({ ...base, physiqueMinScore: '5', physiqueMaxScore: '5' }).errors).toEqual({});
|
||||
});
|
||||
|
||||
it('rejects an inverted range against the minimum field', () => {
|
||||
expect(validateTargetingDraft({ ...base, physiqueMinScore: '9', physiqueMaxScore: '2' }).errors)
|
||||
.toHaveProperty('physiqueMinScore', 'Minimum physique score cannot exceed maximum physique score.');
|
||||
});
|
||||
|
||||
it('rejects scores outside 1 to 10 and fractional scores', () => {
|
||||
expect(validateTargetingDraft({ ...base, physiqueMinScore: '0' }).errors).toHaveProperty('physiqueMinScore');
|
||||
expect(validateTargetingDraft({ ...base, physiqueMaxScore: '11' }).errors).toHaveProperty('physiqueMaxScore');
|
||||
expect(validateTargetingDraft({ ...base, physiqueMaxScore: '7.5' }).errors).toHaveProperty('physiqueMaxScore');
|
||||
});
|
||||
|
||||
it('requires both bounds', () => {
|
||||
const { errors } = validateTargetingDraft({ ...base, physiqueMinScore: '', physiqueMaxScore: '' });
|
||||
expect(Object.keys(errors).sort()).toEqual(['physiqueMaxScore', 'physiqueMinScore']);
|
||||
});
|
||||
|
||||
it('still validates the range while screening is disabled', () => {
|
||||
// The range persists while off, so a bad one must not be storable.
|
||||
expect(validateTargetingDraft({ physiqueTargetingEnabled: false, physiqueMinScore: '9', physiqueMaxScore: '2' }).payload)
|
||||
.toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('targetingRisks', () => {
|
||||
it('warns only when screening is being switched on', () => {
|
||||
const off = { physiqueTargetingEnabled: false, physiqueMinScore: '3', physiqueMaxScore: '8' };
|
||||
const on = { ...off, physiqueTargetingEnabled: true };
|
||||
expect(targetingRisks(on, off)).toHaveLength(1);
|
||||
expect(targetingRisks(off, on)).toEqual([]);
|
||||
// Editing the range of an already-active screen is not a new risk.
|
||||
expect(targetingRisks({ ...on, physiqueMinScore: '5' }, on)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('createTargetingDraft', () => {
|
||||
it('reads the nested physique contract into flat form fields', () => {
|
||||
const draft = createTargetingDraft({
|
||||
rateLimit: { minDelayBetweenMessagesMs: 0, maxMessagesPerHour: 1, jitterMs: 0 },
|
||||
browser: { dryRun: true },
|
||||
reddit: {
|
||||
prioritizeRecentPosts: false, recentWindowMinutes: 60, maxReadyCandidates: 25,
|
||||
physiqueTargeting: { enabled: true, minScore: 4, maxScore: 9 },
|
||||
},
|
||||
subreddits: [],
|
||||
tones: [],
|
||||
});
|
||||
expect(draft).toEqual({ physiqueTargetingEnabled: true, physiqueMinScore: '4', physiqueMaxScore: '9' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('validateAdvancedDraft', () => {
|
||||
it('accepts a JSON object', () => {
|
||||
expect(validateAdvancedDraft({ advancedConfigJson: '{"a":1}' }).payload).toEqual({ advanced: { a: 1 } });
|
||||
});
|
||||
|
||||
it('names the syntax problem rather than just failing', () => {
|
||||
const { errors } = validateAdvancedDraft({ advancedConfigJson: '{"a":' });
|
||||
expect(errors.advancedConfigJson).toMatch(/^Not valid JSON — /);
|
||||
});
|
||||
|
||||
it('refuses arrays, bare values and an emptied editor', () => {
|
||||
expect(validateAdvancedDraft({ advancedConfigJson: '[1]' }).errors.advancedConfigJson).toMatch(/JSON object/);
|
||||
expect(validateAdvancedDraft({ advancedConfigJson: '"text"' }).errors.advancedConfigJson).toMatch(/JSON object/);
|
||||
expect(validateAdvancedDraft({ advancedConfigJson: ' ' }).errors.advancedConfigJson).toMatch(/cannot be emptied/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('computeShares', () => {
|
||||
it('splits attention across enabled subreddits in proportion to weight', () => {
|
||||
const shares = computeShares([
|
||||
subreddit({ name: 'a', weight: 3 }),
|
||||
subreddit({ name: 'b', weight: 1 }),
|
||||
]);
|
||||
|
||||
expect(shares.get('a')?.share).toBeCloseTo(0.75);
|
||||
expect(shares.get('b')?.share).toBeCloseTo(0.25);
|
||||
});
|
||||
|
||||
it('treats a missing weight as the runtime default of 1', () => {
|
||||
const shares = computeShares([subreddit({ name: 'a' }), subreddit({ name: 'b' })]);
|
||||
|
||||
expect(shares.get('a')).toEqual({ effectiveWeight: 1, share: 0.5 });
|
||||
});
|
||||
|
||||
it('gives disabled subreddits no share and excludes them from the total', () => {
|
||||
const shares = computeShares([
|
||||
subreddit({ name: 'a', weight: 1 }),
|
||||
subreddit({ name: 'off', weight: 99, enabled: false }),
|
||||
]);
|
||||
|
||||
expect(shares.get('off')?.share).toBe(0);
|
||||
expect(shares.get('a')?.share).toBe(1);
|
||||
});
|
||||
|
||||
it('reports zero rather than dividing by zero when everything is disabled', () => {
|
||||
const shares = computeShares([subreddit({ name: 'a', enabled: false })]);
|
||||
expect(shares.get('a')?.share).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatShare', () => {
|
||||
it('keeps tiny but non-zero shares visible', () => {
|
||||
expect(formatShare(0.004)).toBe('<1%');
|
||||
expect(formatShare(0)).toBe('—');
|
||||
expect(formatShare(0.256)).toBe('26%');
|
||||
});
|
||||
});
|
||||
|
||||
describe('previewShare', () => {
|
||||
const existing = [subreddit({ name: 'a', weight: 1 }), subreddit({ name: 'b', weight: 1 })];
|
||||
|
||||
it('excludes the edited row from the baseline so its old weight is not counted twice', () => {
|
||||
// Editing 'a' up to weight 3 leaves 'b' at 1, so 'a' takes three quarters.
|
||||
expect(previewShare(draft({ name: 'a', weight: '3' }), existing, 'a')).toBeCloseTo(0.75);
|
||||
});
|
||||
|
||||
it('adds a brand new row on top of the existing total', () => {
|
||||
expect(previewShare(draft({ name: 'c', weight: '2' }), existing, null)).toBeCloseTo(0.5);
|
||||
});
|
||||
|
||||
it('is zero for a disabled or unusable weight', () => {
|
||||
expect(previewShare(draft({ name: 'a', weight: '1', enabled: false }), existing, 'a')).toBe(0);
|
||||
expect(previewShare(draft({ name: 'a', weight: '-2' }), existing, 'a')).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('normaliseSubredditName', () => {
|
||||
it('strips the prefix operators paste in', () => {
|
||||
expect(normaliseSubredditName(' r/Example ')).toBe('Example');
|
||||
expect(normaliseSubredditName('/r/example')).toBe('example');
|
||||
expect(normaliseSubredditName('example')).toBe('example');
|
||||
});
|
||||
});
|
||||
|
||||
describe('validateSubredditDraft', () => {
|
||||
it('keys errors by field name, with no array index to go stale', () => {
|
||||
const { errors } = validateSubredditDraft(draft({ name: '', weight: '0' }), []);
|
||||
expect(Object.keys(errors).sort()).toEqual(['name', 'weight']);
|
||||
});
|
||||
|
||||
it('rejects a duplicate name regardless of case', () => {
|
||||
expect(validateSubredditDraft(draft({ name: 'Example' }), ['example']).errors)
|
||||
.toHaveProperty('name', 'r/Example is already configured.');
|
||||
});
|
||||
|
||||
it('allows a name that only collides with the row being edited', () => {
|
||||
// The caller excludes the edited row from `takenNames`, so saving a
|
||||
// subreddit without renaming it is not a conflict.
|
||||
expect(validateSubredditDraft(draft({ name: 'example' }), []).errors).toEqual({});
|
||||
});
|
||||
|
||||
it('rejects names Reddit itself would not accept', () => {
|
||||
for (const name of ['a', 'has spaces', '_leading', 'way-too-long-for-reddit-to-accept']) {
|
||||
expect(validateSubredditDraft(draft({ name }), []).errors, name).toHaveProperty('name');
|
||||
}
|
||||
});
|
||||
|
||||
it('omits an empty weight and scripted message instead of sending blanks', () => {
|
||||
const { config } = validateSubredditDraft(draft({ weight: '', scripted: ' ' }), []);
|
||||
expect(config).not.toHaveProperty('weight');
|
||||
expect(config).not.toHaveProperty('scripted');
|
||||
});
|
||||
|
||||
it('normalises turn settings away for modes that do not use them', () => {
|
||||
const { config } = validateSubredditDraft(
|
||||
draft({ conversationMode: 'legacy', maxAutomatedTurns: '19', rapportTurnsBeforeMediaAsk: '17' }),
|
||||
[],
|
||||
);
|
||||
expect(config?.conversation).toEqual({ mode: 'legacy', maxAutomatedTurns: 3, rapportTurnsBeforeMediaAsk: 3 });
|
||||
});
|
||||
|
||||
it('requires rapport turns below the total budget for the hybrid mode', () => {
|
||||
const { errors } = validateSubredditDraft(
|
||||
draft({ conversationMode: 'r4r-media', maxAutomatedTurns: '4', rapportTurnsBeforeMediaAsk: '4' }),
|
||||
[],
|
||||
);
|
||||
expect(errors).toHaveProperty('rapportTurnsBeforeMediaAsk');
|
||||
});
|
||||
|
||||
it('rejects a turn budget above the configured maximum', () => {
|
||||
const { errors } = validateSubredditDraft(
|
||||
draft({ conversationMode: 'r4r', maxAutomatedTurns: '21' }),
|
||||
[],
|
||||
);
|
||||
expect(errors).toHaveProperty('maxAutomatedTurns');
|
||||
});
|
||||
|
||||
it('defaults a new subreddit to the mode that cannot send unattended', () => {
|
||||
expect(createEmptySubredditDraft().conversationMode).toBe('manual');
|
||||
});
|
||||
});
|
||||
+425
-518
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,600 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import '@testing-library/jest-dom/vitest';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { cleanup, render, screen, waitFor, within } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { HttpResponse, http } from 'msw';
|
||||
import { setupServer } from 'msw/node';
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { createMemoryRouter, RouterProvider } from 'react-router-dom';
|
||||
import { SubredditsPage } from '../../apps/dashboard/src/features/subreddits/subreddits-page.js';
|
||||
|
||||
const baseSubreddits = [
|
||||
{ name: 'casualconversation', type: 'chat', weight: 1, tone: 'default', enabled: true },
|
||||
{ name: 'r4r', type: 'chat', weight: 3, tone: 'playful', enabled: true, conversation: { mode: 'r4r', maxAutomatedTurns: 6, rapportTurnsBeforeMediaAsk: 3 } },
|
||||
{ name: 'sleepy', type: 'image', weight: 4, tone: 'gentle', enabled: false },
|
||||
];
|
||||
|
||||
const baseConfig = {
|
||||
rateLimit: { minDelayBetweenMessagesMs: 300_000, maxMessagesPerHour: 8, jitterMs: 60_000 },
|
||||
browser: { dryRun: true },
|
||||
reddit: { prioritizeRecentPosts: false, recentWindowMinutes: 60, maxReadyCandidates: 25, physiqueTargeting: { enabled: false, minScore: 1, maxScore: 10 } },
|
||||
subreddits: baseSubreddits,
|
||||
tones: ['default', 'dominant', 'submissive', 'playful', 'direct', 'gentle', 'kink-friendly', 'teasing'],
|
||||
};
|
||||
|
||||
const performance = [
|
||||
{ subreddit: 'casualconversation', totalSent: 40, totalResponses: 10, responseRate: 0.25, totalImages: 2, imageRate: 0.05 },
|
||||
{ subreddit: 'r4r', totalSent: 5, totalResponses: 4, responseRate: 0.8, totalImages: 0, imageRate: 0 },
|
||||
];
|
||||
|
||||
let config: Record<string, any> = structuredClone(baseConfig);
|
||||
/** Subreddit arrays received by PUT /api/config, in order. */
|
||||
let saved: any[][] = [];
|
||||
|
||||
const server = setupServer(
|
||||
http.get('/api/config', () => HttpResponse.json(config)),
|
||||
http.get('/api/analytics/by-subreddit', () => HttpResponse.json(performance)),
|
||||
http.put('/api/config', async ({ request }) => {
|
||||
const body = await request.json() as Record<string, any>;
|
||||
saved.push(body.subreddits);
|
||||
config = { ...config, subreddits: body.subreddits };
|
||||
return HttpResponse.json({
|
||||
success: true,
|
||||
config: { rateLimit: config.rateLimit, browser: config.browser, reddit: config.reddit },
|
||||
subreddits: config.subreddits,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
function renderSubreddits() {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
|
||||
});
|
||||
const router = createMemoryRouter([{ path: '/subreddits', element: <SubredditsPage /> }], {
|
||||
initialEntries: ['/subreddits'],
|
||||
});
|
||||
return render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<RouterProvider router={router} />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
async function findRows() {
|
||||
const list = await screen.findByRole('list', { name: 'Configured subreddits' });
|
||||
return within(list).getAllByRole('listitem');
|
||||
}
|
||||
|
||||
async function row(name: string) {
|
||||
const rows = await findRows();
|
||||
const match = rows.find((item) => rowName(item) === `r/${name}`);
|
||||
if (!match) throw new Error(`No row for r/${name}`);
|
||||
return match;
|
||||
}
|
||||
|
||||
/** The row's own name element, not its concatenated text content. */
|
||||
function rowName(item: HTMLElement): string {
|
||||
return within(item).getByRole('heading', { level: 3 }).textContent ?? '';
|
||||
}
|
||||
|
||||
async function rowOrder(): Promise<string[]> {
|
||||
return (await findRows()).map(rowName);
|
||||
}
|
||||
|
||||
/** Reads one metric from a row's definition list by its label. */
|
||||
function metric(item: HTMLElement, label: string): string {
|
||||
const term = within(item).getAllByRole('term').find((node) => node.textContent === label);
|
||||
if (!term) throw new Error(`No ${label} metric in row`);
|
||||
return term.parentElement?.querySelector('dd')?.textContent ?? '';
|
||||
}
|
||||
|
||||
async function openEditor(name: string) {
|
||||
await userEvent.setup().click(within(await row(name)).getByRole('button', { name: 'Edit' }));
|
||||
return screen.findByRole('dialog', { name: `r/${name}` });
|
||||
}
|
||||
|
||||
beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));
|
||||
beforeEach(() => {
|
||||
config = structuredClone(baseConfig);
|
||||
saved = [];
|
||||
});
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
server.resetHandlers();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
afterAll(() => server.close());
|
||||
|
||||
describe('subreddits page', () => {
|
||||
it('lists each subreddit with its share of polling, mode, and performance', async () => {
|
||||
renderSubreddits();
|
||||
const rows = await findRows();
|
||||
expect(rows).toHaveLength(3);
|
||||
|
||||
// Enabled weights are 1 and 3, so the shares are 25% and 75%. The disabled
|
||||
// row takes none of it despite having the largest weight.
|
||||
const casual = await row('casualconversation');
|
||||
expect(metric(casual, 'Share')).toContain('25%');
|
||||
expect(metric(casual, 'Sent')).toBe('40');
|
||||
expect(metric(casual, 'Replies')).toContain('25% rate');
|
||||
|
||||
expect(metric(await row('r4r'), 'Share')).toContain('75%');
|
||||
|
||||
const sleepy = await row('sleepy');
|
||||
expect(metric(sleepy, 'Share')).toBe('Off');
|
||||
expect(metric(sleepy, 'Sent')).toBe('—');
|
||||
expect(within(sleepy).getByText('Paused')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('summarises how many are polled and how many reply autonomously', async () => {
|
||||
renderSubreddits();
|
||||
await findRows();
|
||||
expect(screen.getByText('of 3 being polled')).toBeInTheDocument();
|
||||
expect(screen.getByText('replying autonomously')).toBeInTheDocument();
|
||||
expect(await row('r4r')).toHaveTextContent('Autonomous');
|
||||
});
|
||||
|
||||
it('orders by share by default and can be re-sorted', async () => {
|
||||
renderSubreddits();
|
||||
const user = userEvent.setup();
|
||||
|
||||
// Share order leads with the heaviest; name order is alphabetical. The
|
||||
// fixture makes the two orders differ so this proves the sort runs.
|
||||
expect(await rowOrder()).toEqual(['r/r4r', 'r/casualconversation', 'r/sleepy']);
|
||||
|
||||
await user.selectOptions(screen.getByRole('combobox', { name: 'Sort subreddits' }), 'Name');
|
||||
expect(await rowOrder()).toEqual(['r/casualconversation', 'r/r4r', 'r/sleepy']);
|
||||
|
||||
await user.selectOptions(screen.getByRole('combobox', { name: 'Sort subreddits' }), 'Messages sent');
|
||||
expect(await rowOrder()).toEqual(['r/casualconversation', 'r/r4r', 'r/sleepy']);
|
||||
});
|
||||
|
||||
it('filters the list by name', async () => {
|
||||
renderSubreddits();
|
||||
const user = userEvent.setup();
|
||||
await findRows();
|
||||
|
||||
await user.type(screen.getByRole('searchbox', { name: 'Filter subreddits by name' }), 'sleep');
|
||||
expect(await findRows()).toHaveLength(1);
|
||||
expect(screen.getByText('r/sleepy')).toBeInTheDocument();
|
||||
|
||||
await user.clear(screen.getByRole('searchbox', { name: 'Filter subreddits by name' }));
|
||||
await user.type(screen.getByRole('searchbox', { name: 'Filter subreddits by name' }), 'nothing');
|
||||
expect(await screen.findByText(/No subreddits match/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('commits the polling toggle immediately, without a save step', async () => {
|
||||
renderSubreddits();
|
||||
const user = userEvent.setup();
|
||||
const sleepy = await row('sleepy');
|
||||
|
||||
await user.click(within(sleepy).getByRole('checkbox', { name: 'Poll r/sleepy' }));
|
||||
|
||||
await waitFor(() => expect(saved).toHaveLength(1));
|
||||
expect(saved[0].find((item: any) => item.name === 'sleepy').enabled).toBe(true);
|
||||
// Enabling weight 4 alongside 3 and 1 rebalances every share.
|
||||
expect(metric(await row('sleepy'), 'Share')).toContain('50%');
|
||||
});
|
||||
|
||||
describe('editing one subreddit', () => {
|
||||
it('previews the share the chosen weight will actually produce', async () => {
|
||||
renderSubreddits();
|
||||
const dialog = await openEditor('casualconversation');
|
||||
const user = userEvent.setup();
|
||||
|
||||
expect(within(dialog).getByText('25%')).toBeInTheDocument();
|
||||
const weight = within(dialog).getByRole('spinbutton', { name: 'Weight' });
|
||||
await user.clear(weight);
|
||||
await user.type(weight, '3');
|
||||
expect(within(dialog).getByText('50%')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('saves only that subreddit and leaves the others untouched', async () => {
|
||||
renderSubreddits();
|
||||
const dialog = await openEditor('casualconversation');
|
||||
const user = userEvent.setup();
|
||||
|
||||
await user.selectOptions(within(dialog).getByRole('combobox', { name: 'Tone' }), 'direct');
|
||||
await user.click(within(dialog).getByRole('button', { name: 'Save subreddit' }));
|
||||
|
||||
await waitFor(() => expect(saved).toHaveLength(1));
|
||||
expect(saved[0]).toHaveLength(3);
|
||||
expect(saved[0][0]).toMatchObject({ name: 'casualconversation', tone: 'direct' });
|
||||
expect(saved[0][1]).toMatchObject({ name: 'r4r', tone: 'playful' });
|
||||
expect(saved[0][2]).toMatchObject({ name: 'sleepy', tone: 'gentle' });
|
||||
});
|
||||
|
||||
it('rejects a name that is already configured', async () => {
|
||||
renderSubreddits();
|
||||
const dialog = await openEditor('sleepy');
|
||||
const user = userEvent.setup();
|
||||
|
||||
const name = within(dialog).getByRole('textbox', { name: 'Subreddit name' });
|
||||
await user.clear(name);
|
||||
await user.type(name, 'R4R');
|
||||
await user.click(within(dialog).getByRole('button', { name: 'Save subreddit' }));
|
||||
|
||||
expect(within(dialog).getByText('r/R4R is already configured.')).toBeInTheDocument();
|
||||
expect(saved).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('rejects a name Reddit would not accept', async () => {
|
||||
renderSubreddits();
|
||||
const dialog = await openEditor('sleepy');
|
||||
const user = userEvent.setup();
|
||||
|
||||
const name = within(dialog).getByRole('textbox', { name: 'Subreddit name' });
|
||||
await user.clear(name);
|
||||
await user.type(name, 'has spaces');
|
||||
await user.click(within(dialog).getByRole('button', { name: 'Save subreddit' }));
|
||||
|
||||
expect(within(dialog).getByText(/2–21 letters, numbers or underscores/)).toBeInTheDocument();
|
||||
expect(saved).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('accepts a name pasted with its r/ prefix', async () => {
|
||||
renderSubreddits();
|
||||
const dialog = await openEditor('sleepy');
|
||||
const user = userEvent.setup();
|
||||
|
||||
const name = within(dialog).getByRole('textbox', { name: 'Subreddit name' });
|
||||
await user.clear(name);
|
||||
await user.type(name, 'r/quietplace');
|
||||
await user.click(within(dialog).getByRole('button', { name: 'Save subreddit' }));
|
||||
|
||||
await waitFor(() => expect(saved).toHaveLength(1));
|
||||
expect(saved[0].map((item: any) => item.name)).toContain('quietplace');
|
||||
});
|
||||
|
||||
it('rejects a weight of zero', async () => {
|
||||
renderSubreddits();
|
||||
const dialog = await openEditor('sleepy');
|
||||
const user = userEvent.setup();
|
||||
|
||||
const weight = within(dialog).getByRole('spinbutton', { name: 'Weight' });
|
||||
await user.clear(weight);
|
||||
await user.type(weight, '0');
|
||||
await user.click(within(dialog).getByRole('button', { name: 'Save subreddit' }));
|
||||
|
||||
expect(within(dialog).getByText('Weight must be a number greater than 0.')).toBeInTheDocument();
|
||||
expect(saved).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('conversation policy', () => {
|
||||
it('reveals the turn budget only for the autonomous modes', async () => {
|
||||
renderSubreddits();
|
||||
const dialog = await openEditor('casualconversation');
|
||||
const user = userEvent.setup();
|
||||
|
||||
expect(within(dialog).queryByRole('spinbutton', { name: 'Maximum automated turns' })).not.toBeInTheDocument();
|
||||
|
||||
await user.click(within(dialog).getByRole('radio', { name: /Autonomous conversation/ }));
|
||||
expect(within(dialog).getByRole('spinbutton', { name: 'Maximum automated turns' })).toBeInTheDocument();
|
||||
expect(within(dialog).queryByRole('spinbutton', { name: 'Rapport turns before the ask' })).not.toBeInTheDocument();
|
||||
|
||||
await user.click(within(dialog).getByRole('radio', { name: /then one media ask/ }));
|
||||
expect(within(dialog).getByRole('spinbutton', { name: 'Rapport turns before the ask' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('requires explicit confirmation before a subreddit replies autonomously', async () => {
|
||||
renderSubreddits();
|
||||
const dialog = await openEditor('casualconversation');
|
||||
const user = userEvent.setup();
|
||||
|
||||
await user.click(within(dialog).getByRole('radio', { name: /Autonomous conversation/ }));
|
||||
await user.click(within(dialog).getByRole('button', { name: 'Save subreddit' }));
|
||||
|
||||
expect(await screen.findByText(/r\/casualconversation will reply autonomously/)).toBeInTheDocument();
|
||||
expect(saved).toHaveLength(0);
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Apply risky settings' }));
|
||||
await waitFor(() => expect(saved).toHaveLength(1));
|
||||
expect(saved[0][0].conversation.mode).toBe('r4r');
|
||||
});
|
||||
|
||||
it('rejects rapport turns that are not lower than the total turn budget', async () => {
|
||||
renderSubreddits();
|
||||
const dialog = await openEditor('casualconversation');
|
||||
const user = userEvent.setup();
|
||||
|
||||
await user.click(within(dialog).getByRole('radio', { name: /then one media ask/ }));
|
||||
const total = within(dialog).getByRole('spinbutton', { name: 'Maximum automated turns' });
|
||||
await user.clear(total);
|
||||
await user.type(total, '4');
|
||||
const rapport = within(dialog).getByRole('spinbutton', { name: 'Rapport turns before the ask' });
|
||||
await user.clear(rapport);
|
||||
await user.type(rapport, '4');
|
||||
await user.click(within(dialog).getByRole('button', { name: 'Save subreddit' }));
|
||||
|
||||
expect(within(dialog).getByText('Rapport turns must be lower than the maximum automated turns.')).toBeInTheDocument();
|
||||
expect(saved).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('does not re-confirm a subreddit that was already autonomous', async () => {
|
||||
renderSubreddits();
|
||||
const dialog = await openEditor('r4r');
|
||||
const user = userEvent.setup();
|
||||
|
||||
const total = within(dialog).getByRole('spinbutton', { name: 'Maximum automated turns' });
|
||||
await user.clear(total);
|
||||
await user.type(total, '8');
|
||||
await user.click(within(dialog).getByRole('button', { name: 'Save subreddit' }));
|
||||
|
||||
await waitFor(() => expect(saved).toHaveLength(1));
|
||||
expect(screen.queryByText('Confirm risky settings')).not.toBeInTheDocument();
|
||||
expect(saved[0][1].conversation.maxAutomatedTurns).toBe(8);
|
||||
});
|
||||
|
||||
it('never prompts about a subreddit other than the one being edited', async () => {
|
||||
renderSubreddits();
|
||||
// r/r4r is autonomous. Editing an unrelated row must not surface its
|
||||
// policy for re-approval — the old array form confirmed by row index.
|
||||
const dialog = await openEditor('sleepy');
|
||||
const user = userEvent.setup();
|
||||
|
||||
await user.selectOptions(within(dialog).getByRole('combobox', { name: 'Tone' }), 'direct');
|
||||
await user.click(within(dialog).getByRole('button', { name: 'Save subreddit' }));
|
||||
|
||||
await waitFor(() => expect(saved).toHaveLength(1));
|
||||
expect(screen.queryByText('Confirm risky settings')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('adding and removing', () => {
|
||||
it('adds a subreddit through a dialog, defaulting to the safest policy', async () => {
|
||||
renderSubreddits();
|
||||
const user = userEvent.setup();
|
||||
await findRows();
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Add subreddit' }));
|
||||
const dialog = await screen.findByRole('dialog', { name: 'Add a subreddit' });
|
||||
expect(within(dialog).getByRole('radio', { name: /Manual only/ })).toBeChecked();
|
||||
|
||||
await user.type(within(dialog).getByRole('textbox', { name: 'Subreddit name' }), 'newplace');
|
||||
await user.click(within(dialog).getByRole('button', { name: 'Add subreddit' }));
|
||||
|
||||
await waitFor(() => expect(saved).toHaveLength(1));
|
||||
expect(saved[0]).toHaveLength(4);
|
||||
expect(saved[0][3]).toMatchObject({ name: 'newplace', conversation: { mode: 'manual' } });
|
||||
expect(await row('newplace')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('will not add a subreddit with no name', async () => {
|
||||
renderSubreddits();
|
||||
const user = userEvent.setup();
|
||||
await findRows();
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Add subreddit' }));
|
||||
const dialog = await screen.findByRole('dialog', { name: 'Add a subreddit' });
|
||||
await user.click(within(dialog).getByRole('button', { name: 'Add subreddit' }));
|
||||
|
||||
expect(within(dialog).getByText('Subreddit name is required.')).toBeInTheDocument();
|
||||
expect(saved).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('confirms a removal before dropping the subreddit', async () => {
|
||||
renderSubreddits();
|
||||
const user = userEvent.setup();
|
||||
await user.click(within(await row('sleepy')).getByRole('button', { name: 'Remove' }));
|
||||
|
||||
expect(await screen.findByRole('heading', { name: 'Stop using r/sleepy?' })).toBeInTheDocument();
|
||||
await user.click(screen.getByRole('button', { name: 'Keep it' }));
|
||||
expect(saved).toHaveLength(0);
|
||||
|
||||
await user.click(within(await row('sleepy')).getByRole('button', { name: 'Remove' }));
|
||||
await user.click(await screen.findByRole('button', { name: 'Remove subreddit' }));
|
||||
|
||||
await waitFor(() => expect(saved).toHaveLength(1));
|
||||
expect(saved[0].map((item: any) => item.name)).toEqual(['casualconversation', 'r4r']);
|
||||
});
|
||||
|
||||
it('refuses to remove the last remaining subreddit', async () => {
|
||||
config = { ...structuredClone(baseConfig), subreddits: [baseSubreddits[0]] };
|
||||
renderSubreddits();
|
||||
|
||||
const only = await row('casualconversation');
|
||||
expect(within(only).getByRole('button', { name: 'Remove' })).toBeDisabled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('bulk actions', () => {
|
||||
async function select(...names: string[]) {
|
||||
const user = userEvent.setup();
|
||||
for (const name of names) {
|
||||
await user.click(within(await row(name)).getByRole('checkbox', { name: `Select r/${name}` }));
|
||||
}
|
||||
return screen.getByRole('region', { name: 'Bulk actions' });
|
||||
}
|
||||
|
||||
it('stays hidden until something is selected', async () => {
|
||||
renderSubreddits();
|
||||
await findRows();
|
||||
expect(screen.queryByRole('region', { name: 'Bulk actions' })).not.toBeInTheDocument();
|
||||
|
||||
const bar = await select('sleepy');
|
||||
expect(within(bar).getByText('1 selected')).toBeInTheDocument();
|
||||
expect(within(bar).getByText('0 polling, 1 paused')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('pauses every selected subreddit in one write', async () => {
|
||||
renderSubreddits();
|
||||
const bar = await select('casualconversation', 'r4r');
|
||||
|
||||
await userEvent.setup().click(within(bar).getByRole('button', { name: 'Pause polling' }));
|
||||
|
||||
await waitFor(() => expect(saved).toHaveLength(1));
|
||||
expect(saved[0].map((item: any) => [item.name, item.enabled])).toEqual([
|
||||
['casualconversation', false],
|
||||
['r4r', false],
|
||||
['sleepy', false],
|
||||
]);
|
||||
});
|
||||
|
||||
it('offers only the action that would change something', async () => {
|
||||
renderSubreddits();
|
||||
const bar = await select('casualconversation');
|
||||
|
||||
// Already polling, so there is nothing for "Start polling" to do.
|
||||
expect(within(bar).getByRole('button', { name: 'Start polling' })).toBeDisabled();
|
||||
expect(within(bar).getByRole('button', { name: 'Pause polling' })).toBeEnabled();
|
||||
});
|
||||
|
||||
it('sets one tone across the selection', async () => {
|
||||
renderSubreddits();
|
||||
const bar = await select('casualconversation', 'sleepy');
|
||||
|
||||
await userEvent.setup().selectOptions(
|
||||
within(bar).getByRole('combobox', { name: 'Set tone for the selected subreddits' }),
|
||||
'direct',
|
||||
);
|
||||
|
||||
await waitFor(() => expect(saved).toHaveLength(1));
|
||||
expect(saved[0].map((item: any) => item.tone)).toEqual(['direct', 'playful', 'direct']);
|
||||
});
|
||||
|
||||
it('names every subreddit turning autonomous before applying it', async () => {
|
||||
renderSubreddits();
|
||||
const user = userEvent.setup();
|
||||
const bar = await select('casualconversation', 'r4r', 'sleepy');
|
||||
|
||||
await user.selectOptions(
|
||||
within(bar).getByRole('combobox', { name: 'Set conversation policy for the selected subreddits' }),
|
||||
'Autonomous conversation',
|
||||
);
|
||||
|
||||
// r/r4r is already autonomous, so only the other two are called out.
|
||||
const dialog = await screen.findByRole('dialog', { name: 'Confirm risky settings' });
|
||||
expect(within(dialog).getByText(/2 subreddits will reply autonomously/)).toBeInTheDocument();
|
||||
expect(within(dialog).getByText(/r\/casualconversation, r\/sleepy/)).toBeInTheDocument();
|
||||
expect(saved).toHaveLength(0);
|
||||
|
||||
await user.click(within(dialog).getByRole('button', { name: 'Apply risky settings' }));
|
||||
await waitFor(() => expect(saved).toHaveLength(1));
|
||||
expect(saved[0].every((item: any) => item.conversation.mode === 'r4r')).toBe(true);
|
||||
});
|
||||
|
||||
it('applies a non-autonomous policy without a confirmation step', async () => {
|
||||
renderSubreddits();
|
||||
const bar = await select('r4r');
|
||||
|
||||
await userEvent.setup().selectOptions(
|
||||
within(bar).getByRole('combobox', { name: 'Set conversation policy for the selected subreddits' }),
|
||||
'Manual only',
|
||||
);
|
||||
|
||||
await waitFor(() => expect(saved).toHaveLength(1));
|
||||
expect(screen.queryByText('Confirm risky settings')).not.toBeInTheDocument();
|
||||
expect(saved[0][1].conversation.mode).toBe('manual');
|
||||
});
|
||||
|
||||
it('keeps the hybrid mode valid when bulk-applied to a short turn budget', async () => {
|
||||
// r/casualconversation defaults to 3 total / 3 rapport, which the hybrid
|
||||
// mode rejects. A bulk change has no form to fix it, so it must normalise.
|
||||
renderSubreddits();
|
||||
const user = userEvent.setup();
|
||||
const bar = await select('casualconversation');
|
||||
|
||||
await user.selectOptions(
|
||||
within(bar).getByRole('combobox', { name: 'Set conversation policy for the selected subreddits' }),
|
||||
'Autonomous, then one media ask',
|
||||
);
|
||||
await user.click(await screen.findByRole('button', { name: 'Apply risky settings' }));
|
||||
|
||||
await waitFor(() => expect(saved).toHaveLength(1));
|
||||
const { maxAutomatedTurns, rapportTurnsBeforeMediaAsk } = saved[0][0].conversation;
|
||||
expect(rapportTurnsBeforeMediaAsk).toBeLessThan(maxAutomatedTurns);
|
||||
});
|
||||
|
||||
it('confirms a bulk removal and lists what will go', async () => {
|
||||
renderSubreddits();
|
||||
const user = userEvent.setup();
|
||||
const bar = await select('r4r', 'sleepy');
|
||||
|
||||
await user.click(within(bar).getByRole('button', { name: 'Remove' }));
|
||||
const dialog = await screen.findByRole('dialog', { name: 'Stop using 2 subreddits?' });
|
||||
expect(within(dialog).getByText('r/r4r')).toBeInTheDocument();
|
||||
expect(within(dialog).getByText('r/sleepy')).toBeInTheDocument();
|
||||
|
||||
await user.click(within(dialog).getByRole('button', { name: 'Remove subreddits' }));
|
||||
await waitFor(() => expect(saved).toHaveLength(1));
|
||||
expect(saved[0].map((item: any) => item.name)).toEqual(['casualconversation']);
|
||||
expect(screen.queryByRole('region', { name: 'Bulk actions' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('refuses to remove every subreddit at once', async () => {
|
||||
renderSubreddits();
|
||||
const bar = await select('casualconversation', 'r4r', 'sleepy');
|
||||
|
||||
const remove = within(bar).getByRole('button', { name: 'Remove' });
|
||||
expect(remove).toBeDisabled();
|
||||
expect(remove).toHaveAttribute('title', 'At least one subreddit must stay configured.');
|
||||
});
|
||||
|
||||
it('selects only the rows the filter is showing', async () => {
|
||||
renderSubreddits();
|
||||
const user = userEvent.setup();
|
||||
await findRows();
|
||||
|
||||
await user.type(screen.getByRole('searchbox', { name: 'Filter subreddits by name' }), 'r4r');
|
||||
await user.click(screen.getByRole('checkbox', { name: 'Select all 1 matching subreddits' }));
|
||||
|
||||
await user.clear(screen.getByRole('searchbox', { name: 'Filter subreddits by name' }));
|
||||
const bar = await screen.findByRole('region', { name: 'Bulk actions' });
|
||||
expect(within(bar).getByText('1 selected')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('selects and clears the whole list', async () => {
|
||||
renderSubreddits();
|
||||
const user = userEvent.setup();
|
||||
await findRows();
|
||||
|
||||
await user.click(screen.getByRole('checkbox', { name: 'Select all subreddits' }));
|
||||
const bar = await screen.findByRole('region', { name: 'Bulk actions' });
|
||||
expect(within(bar).getByText('3 selected')).toBeInTheDocument();
|
||||
|
||||
await user.click(within(bar).getByRole('button', { name: 'Clear' }));
|
||||
expect(screen.queryByRole('region', { name: 'Bulk actions' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('drops a removed subreddit from the selection', async () => {
|
||||
renderSubreddits();
|
||||
const user = userEvent.setup();
|
||||
await select('casualconversation', 'sleepy');
|
||||
|
||||
// Remove one of the selected rows through its own row control.
|
||||
await user.click(within(await row('sleepy')).getByRole('button', { name: 'Remove' }));
|
||||
await user.click(await screen.findByRole('button', { name: 'Remove subreddit' }));
|
||||
|
||||
await waitFor(() => expect(saved).toHaveLength(1));
|
||||
const bar = await screen.findByRole('region', { name: 'Bulk actions' });
|
||||
expect(within(bar).getByText('1 selected')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('still lists subreddits when performance data is unavailable', async () => {
|
||||
server.use(http.get('/api/analytics/by-subreddit', () => HttpResponse.json({ error: 'nope' }, { status: 500 })));
|
||||
renderSubreddits();
|
||||
|
||||
expect(await findRows()).toHaveLength(3);
|
||||
expect(await screen.findByText(/performance could not be loaded/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows a recoverable error when the configuration cannot be loaded', async () => {
|
||||
let requests = 0;
|
||||
server.use(
|
||||
http.get('/api/config', () => {
|
||||
requests += 1;
|
||||
return requests === 1 ? HttpResponse.json({ error: 'nope' }, { status: 500 }) : HttpResponse.json(config);
|
||||
}),
|
||||
);
|
||||
renderSubreddits();
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('Subreddits unavailable');
|
||||
await userEvent.setup().click(screen.getByRole('button', { name: 'Retry' }));
|
||||
expect(await findRows()).toHaveLength(3);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user