Skip to content

Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.

feat(app): add the Automations page for comment-to-DM rules

spacesdrive38e5315aeeb5
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 15d6b51..feac71b 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -17,6 +17,7 @@ const VideoExplorer = lazy(() => import('./features/analytics/videos/VideoE
const ShortsExplorer = lazy(() => import('./features/analytics/shorts/ShortsExplorer'));
const ReelsExplorer = lazy(() => import('./features/analytics/reels/ReelsExplorer'));
const UploadContent = lazy(() => import('./features/publishing/UploadContent'));
+const Automations = lazy(() => import('./features/automations/Automations'));
const AccountManager = lazy(() => import('./features/accounts/AccountManager'));
const Settings = lazy(() => import('./features/settings/Settings'));
const RedditAnalytics = lazy(() => import('./features/analytics/reddit/RedditAnalytics'));
@@ -51,6 +52,7 @@ const router = createBrowserRouter([
{ path: 'shorts', element: <ShortsExplorer /> },
{ path: 'reels', element: <ReelsExplorer /> },
{ path: 'upload', element: <UploadContent /> },
+ { path: 'automations', element: <Automations /> },
{ path: 'accounts', element: <AccountManager /> },
{ path: 'settings', element: <Settings /> },
{ path: 'reddit/:id', element: <RedditAnalytics /> },
diff --git a/frontend/src/features/automations/AutomationAccounts.tsx b/frontend/src/features/automations/AutomationAccounts.tsx
new file mode 100644
index 0000000..79fc296
--- /dev/null
+++ b/frontend/src/features/automations/AutomationAccounts.tsx
@@ -0,0 +1,73 @@
+import { Radio } from 'lucide-react';
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import { Spinner } from '@/components/ui/spinner';
+import { Switch } from '@/components/ui/switch';
+import SurfaceBox from '@/components/SurfaceBox';
+import { AccountAvatar } from '@/components/platform';
+import { accountStatus } from './automationData.ts';
+import type { AutomationAccountState } from '@shared/types/automation.ts';
+import type { AppAccount } from '../../utils/formatters';
+import type { AutomationsState } from './useAutomations';
+
+interface AutomationAccountsProps {
+ accounts: AutomationAccountState[];
+ appAccounts: AppAccount[];
+ automations: AutomationsState;
+}
+
+interface AccountRowProps {
+ account: AutomationAccountState;
+ appAccount: AppAccount | undefined;
+ busy: boolean;
+ automations: AutomationsState;
+}
+
+function AccountRow({ account, appAccount, busy, automations }: AccountRowProps) {
+ const status = accountStatus(account, automations.checkedAt);
+ const switchId = `pause-${account.accountId}`;
+ return (
+ <li className="flex flex-col gap-3 py-4 first:pt-0 last:pb-0 sm:flex-row sm:items-center sm:justify-between">
+ <div className="flex min-w-0 items-start gap-3">
+ {appAccount && <AccountAvatar account={appAccount} size="sm" />}
+ <div className="flex min-w-0 flex-col gap-1">
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="truncate text-sm font-semibold text-ink">@{account.username}</span>
+ <Badge variant={status.tone}>{status.label}</Badge>
+ </div>
+ <p className="text-small text-ink-muted">{status.detail}</p>
+ </div>
+ </div>
+ <div className="flex shrink-0 items-center gap-3">
+ {!account.subscribedAt && (
+ <Button size="sm" variant="outline" onClick={() => automations.subscribeAccount(account)} disabled={busy}>
+ {busy ? <Spinner className="size-4" /> : <Radio data-icon="inline-start" />}
+ Turn on comment events
+ </Button>
+ )}
+ <label htmlFor={switchId} className="flex items-center gap-2 text-small text-ink-muted">
+ Replies
+ <Switch id={switchId} checked={!account.paused} disabled={busy} onCheckedChange={checked => automations.setAccountPaused(account, !checked)} />
+ </label>
+ </div>
+ </li>
+ );
+}
+
+export default function AutomationAccounts({ accounts, appAccounts, automations }: AutomationAccountsProps) {
+ return (
+ <SurfaceBox title="Instagram accounts" subheader="Pause an account to hold its replies. Comments keep arriving and wait for you to resume.">
+ <ul className="flex flex-col divide-y divide-divider">
+ {accounts.map(account => (
+ <AccountRow
+ key={account.accountId}
+ account={account}
+ appAccount={appAccounts.find(item => item.id === account.accountId)}
+ busy={automations.busyId === account.accountId}
+ automations={automations}
+ />
+ ))}
+ </ul>
+ </SurfaceBox>
+ );
+}
diff --git a/frontend/src/features/automations/AutomationActivity.tsx b/frontend/src/features/automations/AutomationActivity.tsx
new file mode 100644
index 0000000..7e69679
--- /dev/null
+++ b/frontend/src/features/automations/AutomationActivity.tsx
@@ -0,0 +1,152 @@
+import { History, RefreshCw, RotateCcw } from 'lucide-react';
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
+import { Spinner } from '@/components/ui/spinner';
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
+import FilterChips from '@/components/FilterChips';
+import RowAction from '@/components/RowAction';
+import SurfaceBox from '@/components/SurfaceBox';
+import { EmptyState } from '@/components/StateViews';
+import { fmtDate, timeAgo } from '../../utils/formatters';
+import { ACTIVITY_FILTERS, STATS_PERIODS, canRetry, statusDisplay } from './automationData.ts';
+import type { ActivityFilter, StatsPeriod } from './automationData.ts';
+import type { AutomationAccountState, AutomationActivityItem, AutomationRule } from '@shared/types/automation.ts';
+import type { AutomationActivityState } from './useAutomationActivity';
+
+interface AutomationActivityProps {
+ activity: AutomationActivityState;
+ accounts: AutomationAccountState[];
+ rules: AutomationRule[];
+}
+
+interface ActivityRowProps {
+ item: AutomationActivityItem;
+ now: number;
+ ruleName: string | null;
+ username: string;
+ retrying: boolean;
+ onRetry: (item: AutomationActivityItem) => void;
+}
+
+const ALL = 'all';
+const FILTER_OPTIONS = (Object.keys(ACTIVITY_FILTERS) as ActivityFilter[]).map(value => ({ value, label: ACTIVITY_FILTERS[value].label }));
+const PERIOD_OPTIONS = (Object.keys(STATS_PERIODS) as StatsPeriod[]).map(value => ({ value, label: STATS_PERIODS[value].label }));
+
+function ActivityRow({ item, now, ruleName, username, retrying, onRetry }: ActivityRowProps) {
+ const status = statusDisplay(item);
+ const waitingUntil = item.nextAttemptAt && ['queued', 'retry_wait'].includes(item.status) ? `Next try ${fmtDate(item.nextAttemptAt)}` : null;
+ return (
+ <TableRow>
+ <TableCell className="whitespace-nowrap text-small text-ink-muted" title={fmtDate(item.createdAt)}>{timeAgo(item.createdAt)}</TableCell>
+ <TableCell className="whitespace-nowrap text-small">@{username}</TableCell>
+ <TableCell className="min-w-56 max-w-sm whitespace-normal">
+ <p className="truncate text-sm text-ink">{item.text ?? <span className="text-ink-faint">Not kept for comments no rule answered</span>}</p>
+ {item.fromUsername && <p className="text-caption text-ink-faint">@{item.fromUsername}</p>}
+ </TableCell>
+ <TableCell className="whitespace-nowrap text-small text-ink-muted">{ruleName ?? '-'}</TableCell>
+ <TableCell><Badge variant={status.tone}>{status.label}</Badge></TableCell>
+ <TableCell className="min-w-64 max-w-md whitespace-normal text-small text-ink-muted">
+ {item.errorMessage ?? waitingUntil ?? (item.acceptedAt ? `Accepted ${fmtDate(item.acceptedAt)}` : '-')}
+ </TableCell>
+ <TableCell className="text-right">
+ {canRetry(item, now) && (
+ <RowAction label={item.status === 'needs_review' ? 'Send again after checking Instagram' : 'Try again'} onClick={() => onRetry(item)} disabled={retrying}>
+ {retrying ? <Spinner /> : <RotateCcw />}
+ </RowAction>
+ )}
+ </TableCell>
+ </TableRow>
+ );
+}
+
+export default function AutomationActivity({ activity, accounts, rules }: AutomationActivityProps) {
+ const { filters, setFilter, items } = activity;
+ const username = (accountId: string) => accounts.find(account => account.accountId === accountId)?.username ?? 'removed account';
+ const ruleName = (ruleId: string | null) => rules.find(rule => rule.id === ruleId)?.name ?? null;
+ const accountItems = [{ value: ALL, label: 'All accounts' }, ...accounts.map(account => ({ value: account.accountId, label: `@${account.username}` }))];
+ const ruleItems = [{ value: ALL, label: 'All rules' }, ...rules.map(rule => ({ value: rule.id, label: rule.name }))];
+ return (
+ <section className="flex flex-col gap-3">
+ <div className="flex flex-wrap items-end justify-between gap-3">
+ <div>
+ <h2 className="font-heading text-section font-semibold text-ink">Activity</h2>
+ <p className="text-small text-ink-muted">Every comment received on an account with an active rule, and what happened to its reply.</p>
+ </div>
+ <Button size="sm" variant="ghost" onClick={activity.load}><RefreshCw data-icon="inline-start" />Refresh</Button>
+ </div>
+ <div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
+ <FilterChips label="Status" options={FILTER_OPTIONS} value={filters.filter} onChange={value => setFilter('filter', value)} />
+ <div className="flex flex-wrap gap-2">
+ <Select value={filters.accountId || ALL} onValueChange={value => setFilter('accountId', !value || value === ALL ? '' : value)} items={accountItems}>
+ <SelectTrigger size="sm" className="w-44" aria-label="Account"><SelectValue /></SelectTrigger>
+ <SelectContent>
+ <SelectGroup>
+ {accountItems.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}
+ </SelectGroup>
+ </SelectContent>
+ </Select>
+ <Select value={filters.ruleId || ALL} onValueChange={value => setFilter('ruleId', !value || value === ALL ? '' : value)} items={ruleItems}>
+ <SelectTrigger size="sm" className="w-44" aria-label="Rule"><SelectValue /></SelectTrigger>
+ <SelectContent>
+ <SelectGroup>
+ {ruleItems.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}
+ </SelectGroup>
+ </SelectContent>
+ </Select>
+ <Select value={filters.period} onValueChange={value => value && setFilter('period', value as StatsPeriod)} items={PERIOD_OPTIONS}>
+ <SelectTrigger size="sm" className="w-40" aria-label="Period"><SelectValue /></SelectTrigger>
+ <SelectContent>
+ <SelectGroup>
+ {PERIOD_OPTIONS.map(option => <SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>)}
+ </SelectGroup>
+ </SelectContent>
+ </Select>
+ </div>
+ </div>
+ <SurfaceBox content={false} className="overflow-hidden">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>When</TableHead>
+ <TableHead>Account</TableHead>
+ <TableHead>Comment</TableHead>
+ <TableHead>Rule</TableHead>
+ <TableHead>Status</TableHead>
+ <TableHead>Details</TableHead>
+ <TableHead className="text-right"><span className="sr-only">Actions</span></TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {items.map(item => (
+ <ActivityRow
+ key={item.id}
+ item={item}
+ now={activity.checkedAt}
+ ruleName={ruleName(item.ruleId)}
+ username={username(item.accountId)}
+ retrying={activity.retryingId === item.id}
+ onRetry={activity.retry}
+ />
+ ))}
+ {items.length === 0 && (
+ <TableRow className="hover:bg-transparent">
+ <TableCell colSpan={7}>
+ {activity.loading
+ ? <div className="flex justify-center py-8"><Spinner className="size-5" /></div>
+ : <EmptyState compact icon={<History />} title="No activity for these filters" description="Comments appear here as Instagram sends them." />}
+ </TableCell>
+ </TableRow>
+ )}
+ </TableBody>
+ </Table>
+ </SurfaceBox>
+ {activity.nextBefore && (
+ <Button variant="outline" size="sm" className="self-center" onClick={activity.loadMore} disabled={activity.loadingMore}>
+ {activity.loadingMore && <Spinner className="size-4" />}
+ Show older activity
+ </Button>
+ )}
+ </section>
+ );
+}
diff --git a/frontend/src/features/automations/AutomationMetrics.tsx b/frontend/src/features/automations/AutomationMetrics.tsx
new file mode 100644
index 0000000..17b1f98
--- /dev/null
+++ b/frontend/src/features/automations/AutomationMetrics.tsx
@@ -0,0 +1,24 @@
+import { AlertTriangle, Clock, Gauge, MessageCircle, MessageSquareReply, Send } from 'lucide-react';
+import MetricBox from '@/components/MetricBox';
+import { fmtNumFull } from '../../utils/formatters';
+import type { AutomationSummary } from './automationData.ts';
+
+interface AutomationMetricsProps {
+ summary: AutomationSummary | null;
+ loading: boolean;
+}
+
+// counts for the chosen period, account and rule; accepted means Instagram took the reply, not that it was read
+export default function AutomationMetrics({ summary, loading }: AutomationMetricsProps) {
+ const value = (n: number | undefined) => (n === undefined ? '-' : fmtNumFull(n));
+ return (
+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-6">
+ <MetricBox small loading={loading} icon={<MessageCircle />} label="Comments received" value={value(summary?.received)} subtitle="On accounts with an active rule" />
+ <MetricBox small loading={loading} icon={<MessageSquareReply />} label="Keyword matches" value={value(summary?.matched)} subtitle="Comments a rule answered" />
+ <MetricBox small highlight loading={loading} icon={<Send />} label="Accepted by Instagram" value={value(summary?.accepted)} subtitle="Instagram does not report reads" />
+ <MetricBox small loading={loading} icon={<Clock />} label="Waiting" value={value(summary?.waiting)} subtitle="Queued, sending or trying again" />
+ <MetricBox small loading={loading} icon={<AlertTriangle />} label="Needs attention" value={value(summary?.attention)} subtitle="Failed or needs review" />
+ <MetricBox small loading={loading} icon={<Gauge />} label="Rate limited" value={value(summary?.rateLimited)} subtitle="Requests Instagram slowed down" />
+ </div>
+ );
+}
diff --git a/frontend/src/features/automations/AutomationNotices.tsx b/frontend/src/features/automations/AutomationNotices.tsx
new file mode 100644
index 0000000..7b1ecde
--- /dev/null
+++ b/frontend/src/features/automations/AutomationNotices.tsx
@@ -0,0 +1,39 @@
+import { AlertCircle, PauseCircle } from 'lucide-react';
+import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
+import { docsUrl } from '@/lib/docs';
+import type { AutomationSettings } from '@shared/types/automation.ts';
+
+interface AutomationNoticesProps {
+ settings: AutomationSettings;
+}
+
+// what the server is missing or holding back, before any rule can reply
+export default function AutomationNotices({ settings }: AutomationNoticesProps) {
+ return (
+ <>
+ {!settings.webhookConfigured && (
+ <Alert variant="warning">
+ <AlertCircle />
+ <AlertTitle>Comment events are not set up on this server</AlertTitle>
+ <AlertDescription>
+ Rules can be written, but no comment reaches Twiligent until the INSTAGRAM_WEBHOOK_VERIFY_TOKEN and INSTAGRAM_APP_SECRET Worker
+ secrets are set and the webhook is added in the Meta dashboard. Follow{' '}
+ <a href={docsUrl('/self-host/comment-automation')} target="_blank" rel="noopener noreferrer" className="font-semibold underline underline-offset-4">
+ Comment automation setup
+ </a>.
+ </AlertDescription>
+ </Alert>
+ )}
+ {settings.paused && (
+ <Alert variant="info">
+ <PauseCircle />
+ <AlertTitle>Replies are paused on this server</AlertTitle>
+ <AlertDescription>
+ Comments are still recorded, but nothing is sent while the AUTOMATION_PAUSED Worker variable is true. Replies go out once it is
+ removed, if the comment is still under Instagram&apos;s 7 days.
+ </AlertDescription>
+ </Alert>
+ )}
+ </>
+ );
+}
diff --git a/frontend/src/features/automations/AutomationRules.tsx b/frontend/src/features/automations/AutomationRules.tsx
new file mode 100644
index 0000000..8a192a9
--- /dev/null
+++ b/frontend/src/features/automations/AutomationRules.tsx
@@ -0,0 +1,92 @@
+import { Copy, ListChecks, Pencil, Plus, Trash2 } from 'lucide-react';
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import { Switch } from '@/components/ui/switch';
+import SurfaceBox from '@/components/SurfaceBox';
+import RowAction from '@/components/RowAction';
+import { EmptyState } from '@/components/StateViews';
+import { matchModeLabel, ruleScopeLabel } from './automationData.ts';
+import type { AutomationAccountState, AutomationRule } from '@shared/types/automation.ts';
+import type { AutomationsState } from './useAutomations';
+
+interface AutomationRulesProps {
+ rules: AutomationRule[];
+ accounts: AutomationAccountState[];
+ automations: AutomationsState;
+ onNew: () => void;
+ onEdit: (rule: AutomationRule) => void;
+ onDelete: (rule: AutomationRule) => void;
+}
+
+interface RuleRowProps {
+ rule: AutomationRule;
+ username: string;
+ busy: boolean;
+ automations: AutomationsState;
+ onEdit: (rule: AutomationRule) => void;
+ onDelete: (rule: AutomationRule) => void;
+}
+
+function RuleRow({ rule, username, busy, automations, onEdit, onDelete }: RuleRowProps) {
+ const switchId = `rule-${rule.id}`;
+ return (
+ <li className="flex flex-col gap-3 py-4 first:pt-0 last:pb-0 md:flex-row md:items-start md:justify-between">
+ <div className="flex min-w-0 flex-col gap-2">
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="text-sm font-semibold text-ink">{rule.name}</span>
+ <span className="text-caption text-ink-faint">@{username}</span>
+ </div>
+ <div className="flex flex-wrap gap-1.5" aria-label="Keywords">
+ {rule.keywords.map(keyword => <Badge key={keyword} variant="secondary">{keyword}</Badge>)}
+ </div>
+ <p className="text-small text-ink-muted">
+ {matchModeLabel(rule)} &middot; {ruleScopeLabel(rule)}{rule.hourlyLimit ? ` · at most ${rule.hourlyLimit} an hour` : ''}
+ </p>
+ <p className="line-clamp-2 max-w-2xl text-small text-ink">{rule.replyText}{rule.linkUrl ? ` ${rule.linkUrl}` : ''}</p>
+ </div>
+ <div className="flex shrink-0 items-center gap-1">
+ <label htmlFor={switchId} className="mr-2 flex items-center gap-2 text-small text-ink-muted">
+ {rule.enabled ? 'On' : 'Off'}
+ <Switch id={switchId} checked={rule.enabled} disabled={busy} onCheckedChange={checked => automations.setRuleEnabled(rule, checked)} />
+ </label>
+ <RowAction label="Edit rule" onClick={() => onEdit(rule)} disabled={busy}><Pencil /></RowAction>
+ <RowAction label="Copy rule" onClick={() => automations.duplicateRule(rule)} disabled={busy}><Copy /></RowAction>
+ <RowAction label="Delete rule" onClick={() => onDelete(rule)} disabled={busy} danger><Trash2 /></RowAction>
+ </div>
+ </li>
+ );
+}
+
+export default function AutomationRules({ rules, accounts, automations, onNew, onEdit, onDelete }: AutomationRulesProps) {
+ const username = (accountId: string) => accounts.find(account => account.accountId === accountId)?.username ?? 'removed account';
+ return (
+ <SurfaceBox
+ title="Rules"
+ subheader="A comment gets one private reply, from the first rule that matches it. Rules for chosen posts are checked before rules for every post."
+ >
+ {rules.length === 0 ? (
+ <EmptyState
+ compact
+ icon={<ListChecks />}
+ title="No rules yet"
+ description="Create a rule with a keyword, such as GUIDE, and the reply to send to anyone who comments it."
+ action={<Button size="sm" onClick={onNew}><Plus data-icon="inline-start" />New rule</Button>}
+ />
+ ) : (
+ <ul className="flex flex-col divide-y divide-divider">
+ {rules.map(rule => (
+ <RuleRow
+ key={rule.id}
+ rule={rule}
+ username={username(rule.accountId)}
+ busy={automations.busyId === rule.id}
+ automations={automations}
+ onEdit={onEdit}
+ onDelete={onDelete}
+ />
+ ))}
+ </ul>
+ )}
+ </SurfaceBox>
+ );
+}
diff --git a/frontend/src/features/automations/Automations.tsx b/frontend/src/features/automations/Automations.tsx
new file mode 100644
index 0000000..139776a
--- /dev/null
+++ b/frontend/src/features/automations/Automations.tsx
@@ -0,0 +1,96 @@
+import { useMemo, useState } from 'react';
+import { Link } from 'react-router-dom';
+import { MessageSquareReply, Plus } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import PageHeader from '@/components/PageHeader';
+import ConfirmDialog from '@/components/ConfirmDialog';
+import { EmptyState, ErrorState, PageSkeleton } from '@/components/StateViews';
+import { useAppContext } from '../../context/AppContext';
+import AutomationAccounts from './AutomationAccounts';
+import AutomationActivity from './AutomationActivity';
+import AutomationMetrics from './AutomationMetrics';
+import AutomationNotices from './AutomationNotices';
+import AutomationRules from './AutomationRules';
+import RuleDialog from './RuleDialog';
+import { useAutomationActivity } from './useAutomationActivity';
+import { useAutomations } from './useAutomations';
+import { useRuleForm } from './useRuleForm';
+import type { AutomationRule } from '@shared/types/automation.ts';
+
+export default function Automations() {
+ const { accounts } = useAppContext();
+ const igAccounts = useMemo(() => accounts.filter(account => account.platform === 'instagram'), [accounts]);
+ const automations = useAutomations();
+ const activity = useAutomationActivity();
+ const rule = useRuleForm({ saveRule: automations.saveRule });
+ const [pendingDelete, setPendingDelete] = useState<AutomationRule | null>(null);
+ const { overview } = automations;
+
+ const header = (
+ <PageHeader
+ title="Automations"
+ description="Send a private reply on Instagram when someone comments a keyword on your posts and reels."
+ actions={overview && overview.accounts.length > 0 && (
+ <Button onClick={() => rule.openNew(overview.accounts[0].accountId)}><Plus data-icon="inline-start" />New rule</Button>
+ )}
+ />
+ );
+
+ if (!overview && !automations.loadError) return <PageSkeleton metrics={3} />;
+
+ if (!overview) {
+ return (
+ <div className="flex flex-col gap-6">
+ {header}
+ <ErrorState title="Automations could not load" description={automations.loadError} onRetry={automations.load} />
+ </div>
+ );
+ }
+
+ if (overview.accounts.length === 0) {
+ return (
+ <div className="flex flex-col gap-6">
+ {header}
+ <EmptyState
+ icon={<MessageSquareReply />}
+ title="Connect an Instagram account first"
+ description="Automations reply from an Instagram professional account connected with Instagram sign-in."
+ action={<Button render={<Link to="/accounts?add=1" />}>Connect Instagram</Button>}
+ />
+ </div>
+ );
+ }
+
+ async function confirmDelete() {
+ if (pendingDelete && await automations.deleteRule(pendingDelete)) setPendingDelete(null);
+ }
+
+ return (
+ <div className="flex flex-col gap-6">
+ {header}
+ <AutomationNotices settings={overview.settings} />
+ <AutomationMetrics summary={activity.summary} loading={activity.loading && !activity.summary} />
+ <AutomationAccounts accounts={overview.accounts} appAccounts={igAccounts} automations={automations} />
+ <AutomationRules
+ rules={overview.rules}
+ accounts={overview.accounts}
+ automations={automations}
+ onNew={() => rule.openNew(overview.accounts[0].accountId)}
+ onEdit={rule.openEdit}
+ onDelete={setPendingDelete}
+ />
+ <AutomationActivity activity={activity} accounts={overview.accounts} rules={overview.rules} />
+ <RuleDialog rule={rule} igAccounts={igAccounts} />
+ <ConfirmDialog
+ open={Boolean(pendingDelete)}
+ onOpenChange={open => !open && setPendingDelete(null)}
+ title={`Delete ${pendingDelete?.name ?? 'this rule'}?`}
+ description="Comments stop getting this reply. Replies already sent stay sent, and the rule's past activity stays in the list."
+ confirmLabel="Delete rule"
+ busy={automations.busyId === pendingDelete?.id}
+ hold
+ onConfirm={confirmDelete}
+ />
+ </div>
+ );
+}
diff --git a/frontend/src/features/automations/RuleDialog.tsx b/frontend/src/features/automations/RuleDialog.tsx
new file mode 100644
index 0000000..9d12e03
--- /dev/null
+++ b/frontend/src/features/automations/RuleDialog.tsx
@@ -0,0 +1,103 @@
+import { Button } from '@/components/ui/button';
+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
+import { Input } from '@/components/ui/input';
+import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
+import { Spinner } from '@/components/ui/spinner';
+import { Switch } from '@/components/ui/switch';
+import { Textarea } from '@/components/ui/textarea';
+import { FieldRow } from '@/components/DetailPanel';
+import AccountSelect from '@/components/AccountSelect';
+import RuleMediaPicker from './RuleMediaPicker';
+import RulePreview from './RulePreview';
+import type { AutomationMatchMode } from '@shared/types/automation.ts';
+import type { AppAccount } from '../../utils/formatters';
+import type { RuleScope } from './automationData.ts';
+import type { RuleFormState } from './useRuleForm';
+
+interface RuleDialogProps {
+ rule: RuleFormState;
+ igAccounts: AppAccount[];
+}
+
+const MATCH_MODES: { value: AutomationMatchMode; label: string }[] = [
+ { value: 'contains', label: 'Anywhere in the comment, as a whole word' },
+ { value: 'exact', label: 'The whole comment, nothing else' },
+];
+
+const SCOPES: { value: RuleScope; label: string }[] = [
+ { value: 'all', label: 'Every post and reel' },
+ { value: 'selected', label: 'Only the posts I choose' },
+];
+
+export default function RuleDialog({ rule, igAccounts }: RuleDialogProps) {
+ const { form, setField, saving } = rule;
+ return (
+ <Dialog open={rule.open} onOpenChange={open => !saving && rule.setOpen(open)}>
+ <DialogContent className="max-h-[calc(100dvh-2rem)] overflow-y-auto sm:max-w-3xl">
+ <DialogHeader>
+ <DialogTitle>{rule.ruleId ? 'Edit rule' : 'New rule'}</DialogTitle>
+ <DialogDescription>When a comment contains a keyword, Twiligent sends its author this private reply on Instagram.</DialogDescription>
+ </DialogHeader>
+ <form id="automation-rule-form" onSubmit={rule.handleSubmit} className="grid gap-6 md:grid-cols-[minmax(0,1fr)_minmax(0,0.9fr)]">
+ <div className="flex flex-col gap-5">
+ <FieldRow label="Instagram account">
+ <AccountSelect accounts={igAccounts} value={form.accountId} onChange={value => setField('accountId', value)} disabled={Boolean(rule.ruleId)} />
+ </FieldRow>
+ <FieldRow label="Name" htmlFor="rule-name" hint="Only you see this.">
+ <Input id="rule-name" value={form.name} maxLength={80} onChange={e => setField('name', e.target.value)} placeholder="Free guide" />
+ </FieldRow>
+ <FieldRow label="Keywords" htmlFor="rule-keywords" hint="Separate keywords with commas. Up to 10.">
+ <Input id="rule-keywords" value={form.keywordsText} onChange={e => setField('keywordsText', e.target.value)} placeholder="GUIDE, LINK" />
+ </FieldRow>
+ <FieldRow label="Match">
+ <Select value={form.matchMode} onValueChange={value => value && setField('matchMode', value as AutomationMatchMode)} items={MATCH_MODES}>
+ <SelectTrigger className="w-full" aria-label="Match"><SelectValue /></SelectTrigger>
+ <SelectContent>
+ <SelectGroup>
+ {MATCH_MODES.map(mode => <SelectItem key={mode.value} value={mode.value}>{mode.label}</SelectItem>)}
+ </SelectGroup>
+ </SelectContent>
+ </Select>
+ <label htmlFor="rule-case" className="flex items-center justify-between gap-3 text-small text-ink-muted">
+ Match the letter case exactly
+ <Switch id="rule-case" checked={form.caseSensitive} onCheckedChange={checked => setField('caseSensitive', checked)} />
+ </label>
+ </FieldRow>
+ <FieldRow label="Posts">
+ <Select value={form.scope} onValueChange={value => value && setField('scope', value as RuleScope)} items={SCOPES}>
+ <SelectTrigger className="w-full" aria-label="Posts"><SelectValue /></SelectTrigger>
+ <SelectContent>
+ <SelectGroup>
+ {SCOPES.map(scope => <SelectItem key={scope.value} value={scope.value}>{scope.label}</SelectItem>)}
+ </SelectGroup>
+ </SelectContent>
+ </Select>
+ {form.scope === 'selected' && <RuleMediaPicker media={rule.media} loading={rule.mediaLoading} selected={form.mediaIds} onToggle={rule.toggleMedia} />}
+ </FieldRow>
+ <FieldRow label="Reply" htmlFor="rule-reply">
+ <Textarea id="rule-reply" rows={4} maxLength={1000} value={form.replyText} onChange={e => setField('replyText', e.target.value)} placeholder="Here is your guide. Enjoy it." />
+ </FieldRow>
+ <FieldRow label="Link" htmlFor="rule-link" hint="Optional. Added on its own line after the reply. Must start with https://">
+ <Input id="rule-link" type="url" inputMode="url" value={form.linkUrl} onChange={e => setField('linkUrl', e.target.value)} placeholder="https://example.com/guide" />
+ </FieldRow>
+ <FieldRow label="Replies an hour" htmlFor="rule-limit" hint="Optional. The account's own limit still applies; Instagram allows 750 an hour.">
+ <Input id="rule-limit" type="number" min={1} max={750} step={1} inputMode="numeric" value={form.hourlyLimit} onChange={e => setField('hourlyLimit', e.target.value)} placeholder="No limit for this rule" />
+ </FieldRow>
+ <label htmlFor="rule-enabled" className="flex items-center justify-between gap-3 text-sm font-medium text-ink">
+ Turn the rule on when saved
+ <Switch id="rule-enabled" checked={form.enabled} onCheckedChange={checked => setField('enabled', checked)} />
+ </label>
+ </div>
+ <RulePreview rule={rule} />
+ </form>
+ <DialogFooter>
+ <Button variant="outline" onClick={() => rule.setOpen(false)} disabled={saving}>Cancel</Button>
+ <Button type="submit" form="automation-rule-form" disabled={saving}>
+ {saving && <Spinner className="size-4" />}
+ {saving ? 'Saving' : rule.ruleId ? 'Save rule' : 'Create rule'}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/frontend/src/features/automations/RuleMediaPicker.tsx b/frontend/src/features/automations/RuleMediaPicker.tsx
new file mode 100644
index 0000000..03abf7d
--- /dev/null
+++ b/frontend/src/features/automations/RuleMediaPicker.tsx
@@ -0,0 +1,47 @@
+import { Check, ImageOff } from 'lucide-react';
+import { Spinner } from '@/components/ui/spinner';
+import { cn } from '@/lib/utils';
+import type { InstagramMedia } from '@shared/types/instagram.ts';
+
+interface RuleMediaPickerProps {
+ media: InstagramMedia[];
+ loading: boolean;
+ selected: string[];
+ onToggle: (id: string) => void;
+}
+
+// the account's recent posts and reels as a grid of toggles
+export default function RuleMediaPicker({ media, loading, selected, onToggle }: RuleMediaPickerProps) {
+ if (loading) return <div className="flex justify-center py-6"><Spinner className="size-5" /></div>;
+ if (media.length === 0) return <p className="text-small text-ink-muted">No posts found on this account yet.</p>;
+ return (
+ <div className="grid max-h-64 grid-cols-3 gap-2 overflow-y-auto sm:grid-cols-4" role="group" aria-label="Posts and reels">
+ {media.map(item => {
+ const active = selected.includes(item.id);
+ const image = item.thumbnailUrl || item.mediaUrl;
+ return (
+ <button
+ key={item.id}
+ type="button"
+ aria-pressed={active}
+ aria-label={item.caption ? item.caption.slice(0, 80) : `Post from ${new Date(item.timestamp).toLocaleDateString()}`}
+ onClick={() => onToggle(item.id)}
+ className={cn(
+ 'relative aspect-square overflow-hidden rounded-control border bg-surface-sunken transition-colors duration-(--duration-fast) focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring',
+ active ? 'border-brand ring-2 ring-brand' : 'border-line hover:border-line-strong',
+ )}
+ >
+ {image
+ ? <img src={image} alt="" className="size-full object-cover" loading="lazy" />
+ : <span className="flex size-full items-center justify-center text-ink-faint"><ImageOff className="size-5 stroke-[1.75]" /></span>}
+ {active && (
+ <span className="absolute top-1.5 right-1.5 flex size-5 items-center justify-center rounded-pill bg-brand text-on-brand">
+ <Check className="size-3.5 stroke-[2]" />
+ </span>
+ )}
+ </button>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/frontend/src/features/automations/RulePreview.tsx b/frontend/src/features/automations/RulePreview.tsx
new file mode 100644
index 0000000..5c0527a
--- /dev/null
+++ b/frontend/src/features/automations/RulePreview.tsx
@@ -0,0 +1,49 @@
+import { FlaskConical } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Spinner } from '@/components/ui/spinner';
+import { cn } from '@/lib/utils';
+import { MAX_MESSAGE_BYTES, composeReply, messageBytes } from './automationData.ts';
+import type { RuleFormState } from './useRuleForm';
+
+interface RulePreviewProps {
+ rule: RuleFormState;
+}
+
+// the private reply as the commenter would see it, and a keyword test that sends nothing
+export default function RulePreview({ rule }: RulePreviewProps) {
+ const { form, testResult } = rule;
+ const message = composeReply(form.replyText, form.linkUrl);
+ const bytes = messageBytes(message);
+ return (
+ <div className="flex flex-col gap-4 self-start rounded-card border border-line bg-surface-sunken p-4 md:sticky md:top-0">
+ <div className="flex flex-col gap-2">
+ <p className="text-small font-medium text-ink">Preview</p>
+ <div className="max-w-[85%] self-start rounded-card rounded-bl-row bg-surface-raised px-3.5 py-2.5 text-sm whitespace-pre-wrap text-ink shadow-xs">
+ {message || <span className="text-ink-faint">Your reply appears here</span>}
+ </div>
+ <p className={cn('text-caption', bytes > MAX_MESSAGE_BYTES ? 'text-danger' : 'text-ink-faint')}>
+ {bytes} of {MAX_MESSAGE_BYTES} bytes. Instagram sends one private reply per comment, within 7 days of it.
+ </p>
+ </div>
+ <div className="flex flex-col gap-2">
+ <label htmlFor="rule-test" className="text-small font-medium text-ink">Test a comment</label>
+ <div className="flex gap-2">
+ <Input id="rule-test" value={rule.sampleComment} onChange={e => rule.setSampleComment(e.target.value)} placeholder="Send me the guide" />
+ <Button type="button" variant="outline" onClick={rule.runTest} disabled={rule.testing || !rule.sampleComment.trim() || !form.keywordsText.trim()}>
+ {rule.testing ? <Spinner className="size-4" /> : <FlaskConical data-icon="inline-start" />}
+ Test
+ </Button>
+ </div>
+ {testResult && (
+ <p role="status" className={cn('text-small', testResult.matched ? 'text-success' : 'text-ink-muted')}>
+ {testResult.matched
+ ? `Matches the keyword ${testResult.keyword}. This comment would get the reply above.`
+ : 'No keyword matches this comment, so it would get no reply.'}
+ </p>
+ )}
+ <p className="text-caption text-ink-faint">The test checks the keywords only. Nothing is sent.</p>
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/features/automations/automationData.ts b/frontend/src/features/automations/automationData.ts
new file mode 100644
index 0000000..07d260a
--- /dev/null
+++ b/frontend/src/features/automations/automationData.ts
@@ -0,0 +1,228 @@
+import type {
+ AutomationAccountState, AutomationActivityItem, AutomationCommentStatus, AutomationMatchMode, AutomationRule, AutomationRuleRequest,
+ AutomationStats,
+} from '../../../../shared/types/automation.ts';
+
+export type BadgeTone = 'success' | 'destructive' | 'warning' | 'info' | 'secondary';
+
+export interface StatusDisplay {
+ label: string;
+ tone: BadgeTone;
+}
+
+// accepted means Instagram took the request; it does not report whether the person has read the message
+export const STATUS_DISPLAY: Record<AutomationCommentStatus, StatusDisplay> = {
+ ignored: { label: 'No match', tone: 'secondary' },
+ queued: { label: 'Waiting', tone: 'warning' },
+ processing: { label: 'Sending', tone: 'info' },
+ retry_wait: { label: 'Trying again', tone: 'warning' },
+ sending: { label: 'Sending', tone: 'info' },
+ accepted: { label: 'Accepted by Instagram', tone: 'success' },
+ failed: { label: 'Failed', tone: 'destructive' },
+ needs_review: { label: 'Needs review', tone: 'warning' },
+ skipped: { label: 'Skipped', tone: 'secondary' },
+ expired: { label: 'Expired', tone: 'secondary' },
+};
+
+export type ActivityFilter = 'all' | 'accepted' | 'waiting' | 'attention' | 'skipped' | 'ignored';
+
+export const ACTIVITY_FILTERS: Record<ActivityFilter, { label: string; statuses: AutomationCommentStatus[] | null }> = {
+ all: { label: 'All', statuses: null },
+ accepted: { label: 'Accepted', statuses: ['accepted'] },
+ waiting: { label: 'Waiting', statuses: ['queued', 'processing', 'retry_wait', 'sending'] },
+ attention: { label: 'Needs attention', statuses: ['failed', 'needs_review'] },
+ skipped: { label: 'Skipped or expired', statuses: ['skipped', 'expired'] },
+ ignored: { label: 'No match', statuses: ['ignored'] },
+};
+
+export type StatsPeriod = '24h' | '7d' | '30d';
+
+const HOUR_MS = 60 * 60 * 1000;
+
+export const STATS_PERIODS: Record<StatsPeriod, { label: string; ms: number }> = {
+ '24h': { label: 'Last 24 hours', ms: 24 * HOUR_MS },
+ '7d': { label: 'Last 7 days', ms: 7 * 24 * HOUR_MS },
+ '30d': { label: 'Last 30 days', ms: 30 * 24 * HOUR_MS },
+};
+
+// Instagram refuses message text longer than 1,000 bytes; the Worker checks the same
+export const MAX_MESSAGE_BYTES = 1000;
+const MAX_KEYWORDS = 10;
+const MAX_HOURLY_LIMIT = 750;
+
+export interface AutomationSummary {
+ received: number;
+ matched: number;
+ accepted: number;
+ waiting: number;
+ attention: number;
+ rateLimited: number;
+}
+
+export type RuleScope = 'all' | 'selected';
+
+// the rule dialog's fields, as typed; keywords and the limit stay text until saved
+export interface RuleForm {
+ accountId: string;
+ name: string;
+ keywordsText: string;
+ matchMode: AutomationMatchMode;
+ caseSensitive: boolean;
+ scope: RuleScope;
+ mediaIds: string[];
+ replyText: string;
+ linkUrl: string;
+ hourlyLimit: string;
+ enabled: boolean;
+}
+
+export function periodStart(period: StatsPeriod, now: number): string {
+ return new Date(now - STATS_PERIODS[period].ms).toISOString();
+}
+
+export function statusDisplay(item: Pick<AutomationActivityItem, 'status' | 'statusReason'>): StatusDisplay {
+ if (item.status === 'queued' && item.statusReason === 'paused') return { label: 'Held', tone: 'warning' };
+ return STATUS_DISPLAY[item.status];
+}
+
+function count(stats: AutomationStats, statuses: AutomationCommentStatus[]): number {
+ return statuses.reduce((total, status) => total + (stats.comments[status] ?? 0), 0);
+}
+
+export function summarizeStats(stats: AutomationStats): AutomationSummary {
+ const received = Object.values(stats.comments).reduce((total, value) => total + (value ?? 0), 0);
+ return {
+ received,
+ matched: received - (stats.comments.ignored ?? 0),
+ accepted: stats.comments.accepted ?? 0,
+ waiting: count(stats, ACTIVITY_FILTERS.waiting.statuses!),
+ attention: count(stats, ACTIVITY_FILTERS.attention.statuses!),
+ rateLimited: stats.attempts.rate_limited ?? 0,
+ };
+}
+
+export function ruleScopeLabel(rule: Pick<AutomationRule, 'mediaIds'>): string {
+ const posts = rule.mediaIds.length;
+ if (posts === 0) return 'All posts and reels';
+ return posts === 1 ? '1 selected post' : `${posts} selected posts`;
+}
+
+export function matchModeLabel(rule: Pick<AutomationRule, 'matchMode' | 'caseSensitive'>): string {
+ const mode = rule.matchMode === 'exact' ? 'Whole comment' : 'Anywhere in the comment';
+ return rule.caseSensitive ? `${mode}, same letter case` : mode;
+}
+
+// failed, skipped and review items can be tried again until Instagram's 7 days run out
+export function canRetry(item: Pick<AutomationActivityItem, 'status' | 'expiresAt'>, now: number): boolean {
+ return ['failed', 'needs_review', 'skipped'].includes(item.status) && Date.parse(item.expiresAt) > now;
+}
+
+// comma or line separated, trimmed, without blanks or repeats
+export function parseKeywords(text: string, caseSensitive: boolean): string[] {
+ const seen = new Set<string>();
+ const keywords: string[] = [];
+ for (const keyword of text.split(/[,\n]/).map(item => item.trim()).filter(Boolean)) {
+ const key = caseSensitive ? keyword : keyword.toLowerCase();
+ if (seen.has(key)) continue;
+ seen.add(key);
+ keywords.push(keyword);
+ }
+ return keywords;
+}
+
+export function composeReply(replyText: string, linkUrl: string): string {
+ const link = linkUrl.trim();
+ return link ? `${replyText.trim()}\n\n${link}` : replyText.trim();
+}
+
+export function messageBytes(message: string): number {
+ return new TextEncoder().encode(message).length;
+}
+
+export function emptyRuleForm(accountId: string): RuleForm {
+ return {
+ accountId, name: '', keywordsText: '', matchMode: 'contains', caseSensitive: false, scope: 'all', mediaIds: [],
+ replyText: '', linkUrl: '', hourlyLimit: '', enabled: true,
+ };
+}
+
+export function ruleToForm(rule: AutomationRule): RuleForm {
+ return {
+ accountId: rule.accountId,
+ name: rule.name,
+ keywordsText: rule.keywords.join(', '),
+ matchMode: rule.matchMode,
+ caseSensitive: rule.caseSensitive,
+ scope: rule.mediaIds.length > 0 ? 'selected' : 'all',
+ mediaIds: rule.mediaIds,
+ replyText: rule.replyText,
+ linkUrl: rule.linkUrl ?? '',
+ hourlyLimit: rule.hourlyLimit === null ? '' : String(rule.hourlyLimit),
+ enabled: rule.enabled,
+ };
+}
+
+export function formToRequest(form: RuleForm): AutomationRuleRequest {
+ return {
+ accountId: form.accountId,
+ name: form.name.trim(),
+ keywords: parseKeywords(form.keywordsText, form.caseSensitive),
+ matchMode: form.matchMode,
+ caseSensitive: form.caseSensitive,
+ mediaIds: form.scope === 'selected' ? form.mediaIds : [],
+ replyText: form.replyText.trim(),
+ linkUrl: form.linkUrl.trim() || null,
+ enabled: form.enabled,
+ hourlyLimit: form.hourlyLimit.trim() ? Number(form.hourlyLimit) : null,
+ };
+}
+
+function linkProblem(linkUrl: string): string | null {
+ const link = linkUrl.trim();
+ if (!link) return null;
+ try {
+ const url = new URL(link);
+ if (url.protocol !== 'https:') return 'The link must start with https://';
+ if (url.username || url.password) return 'The link cannot contain a user name or password';
+ } catch {
+ return 'The link must be a full address starting with https://';
+ }
+ return null;
+}
+
+// the first thing to fix before the rule can be saved, or null; the Worker checks the same rules again
+export function ruleFormProblem(form: RuleForm): string | null {
+ if (!form.accountId) return 'Choose the Instagram account';
+ if (!form.name.trim()) return 'Give the rule a name';
+ const keywords = parseKeywords(form.keywordsText, form.caseSensitive);
+ if (keywords.length === 0) return 'Add at least one keyword';
+ if (keywords.length > MAX_KEYWORDS) return `A rule can have at most ${MAX_KEYWORDS} keywords`;
+ if (form.scope === 'selected' && form.mediaIds.length === 0) return 'Choose at least one post, or answer comments on every post';
+ if (!form.replyText.trim()) return 'Write the reply to send';
+ const link = linkProblem(form.linkUrl);
+ if (link) return link;
+ const limit = form.hourlyLimit.trim();
+ if (limit && !(/^\d+$/.test(limit) && Number(limit) >= 1 && Number(limit) <= MAX_HOURLY_LIMIT)) {
+ return `The hourly limit must be a whole number from 1 to ${MAX_HOURLY_LIMIT}`;
+ }
+ const bytes = messageBytes(composeReply(form.replyText, form.linkUrl));
+ if (bytes > MAX_MESSAGE_BYTES) return `The reply with its link is ${bytes} bytes; Instagram accepts at most ${MAX_MESSAGE_BYTES}`;
+ return null;
+}
+
+export interface AccountStatus {
+ label: string;
+ tone: BadgeTone;
+ detail: string;
+}
+
+// what an account's automation is doing right now, from its controls
+export function accountStatus(account: AutomationAccountState, now: number): AccountStatus {
+ if (account.paused && account.cooldownReason) return { label: 'Held', tone: 'destructive', detail: account.cooldownReason };
+ if (account.paused) return { label: 'Paused', tone: 'secondary', detail: 'Comments are still recorded; replies wait until you resume, within Instagram\'s 7 days.' };
+ if (account.cooldownUntil && Date.parse(account.cooldownUntil) > now) {
+ return { label: 'Cooling down', tone: 'warning', detail: account.cooldownReason ?? 'Instagram is limiting replies from this account for now.' };
+ }
+ if (!account.subscribedAt) return { label: 'Not receiving comments', tone: 'warning', detail: 'Turn on comment events so Instagram sends this account\'s comments to Twiligent.' };
+ return { label: 'Receiving comments', tone: 'success', detail: 'New comments that match an active rule get a reply.' };
+}
diff --git a/frontend/src/features/automations/useAutomationActivity.ts b/frontend/src/features/automations/useAutomationActivity.ts
new file mode 100644
index 0000000..fc48a2c
--- /dev/null
+++ b/frontend/src/features/automations/useAutomationActivity.ts
@@ -0,0 +1,97 @@
+import { useCallback, useEffect, useState } from 'react';
+import { useAppContext } from '../../context/AppContext';
+import { api } from '../../services/api';
+import { ACTIVITY_FILTERS, periodStart, summarizeStats } from './automationData.ts';
+import type { ActivityFilter, AutomationSummary, StatsPeriod } from './automationData.ts';
+import type { AutomationActivityItem } from '@shared/types/automation.ts';
+
+const PAGE_SIZE = 50;
+
+export interface ActivityFilters {
+ filter: ActivityFilter;
+ period: StatsPeriod;
+ accountId: string;
+ ruleId: string;
+}
+
+function query(filters: ActivityFilters, before?: string): URLSearchParams {
+ const params = new URLSearchParams({ from: periodStart(filters.period, Date.now()), limit: String(PAGE_SIZE) });
+ const statuses = ACTIVITY_FILTERS[filters.filter].statuses;
+ if (statuses) params.set('status', statuses.join(','));
+ if (filters.accountId) params.set('accountId', filters.accountId);
+ if (filters.ruleId) params.set('ruleId', filters.ruleId);
+ if (before) params.set('before', before);
+ return params;
+}
+
+// the counts and the activity list share the period, account and rule filters
+export function useAutomationActivity() {
+ const { showToast } = useAppContext();
+ const [filters, setFilters] = useState<ActivityFilters>({ filter: 'all', period: '7d', accountId: '', ruleId: '' });
+ const [items, setItems] = useState<AutomationActivityItem[]>([]);
+ const [nextBefore, setNextBefore] = useState<string | null>(null);
+ const [summary, setSummary] = useState<AutomationSummary | null>(null);
+ const [loading, setLoading] = useState(true);
+ const [loadingMore, setLoadingMore] = useState(false);
+ const [retryingId, setRetryingId] = useState<string | null>(null);
+ // the time the list was read, so which items can be retried is decided against a fixed moment during render
+ const [checkedAt, setCheckedAt] = useState(() => Date.now());
+
+ const load = useCallback(async () => {
+ setLoading(true);
+ try {
+ const statsQuery = query({ ...filters, filter: 'all' });
+ statsQuery.delete('status');
+ statsQuery.delete('limit');
+ const [page, stats] = await Promise.all([
+ api.getAutomationActivity(query(filters)),
+ api.getAutomationStats(statsQuery),
+ ]);
+ setItems(page.items);
+ setNextBefore(page.nextBefore);
+ setSummary(summarizeStats(stats.stats));
+ setCheckedAt(Date.now());
+ } catch (err) {
+ showToast(`Couldn't load the reply activity. ${(err as Error).message}`, 'error');
+ } finally {
+ setLoading(false);
+ }
+ }, [filters, showToast]);
+
+ useEffect(() => { load(); }, [load]);
+
+ const loadMore = useCallback(async () => {
+ if (!nextBefore) return;
+ setLoadingMore(true);
+ try {
+ const page = await api.getAutomationActivity(query(filters, nextBefore));
+ setItems(current => [...current, ...page.items]);
+ setNextBefore(page.nextBefore);
+ } catch (err) {
+ showToast(`Couldn't load more activity. ${(err as Error).message}`, 'error');
+ } finally {
+ setLoadingMore(false);
+ }
+ }, [filters, nextBefore, showToast]);
+
+ const retry = useCallback(async (item: AutomationActivityItem) => {
+ setRetryingId(item.id);
+ try {
+ const { item: queued } = await api.retryAutomationActivity(item.id);
+ setItems(current => current.map(entry => (entry.id === queued.id ? queued : entry)));
+ showToast('Reply queued to send again');
+ } catch (err) {
+ showToast(`Couldn't retry the reply. ${(err as Error).message}`, 'error');
+ } finally {
+ setRetryingId(null);
+ }
+ }, [showToast]);
+
+ const setFilter = useCallback(<K extends keyof ActivityFilters>(key: K, value: ActivityFilters[K]) => {
+ setFilters(current => ({ ...current, [key]: value }));
+ }, []);
+
+ return { filters, setFilter, items, nextBefore, summary, loading, loadingMore, retryingId, checkedAt, load, loadMore, retry };
+}
+
+export type AutomationActivityState = ReturnType<typeof useAutomationActivity>;
diff --git a/frontend/src/features/automations/useAutomations.ts b/frontend/src/features/automations/useAutomations.ts
new file mode 100644
index 0000000..a8d60ad
--- /dev/null
+++ b/frontend/src/features/automations/useAutomations.ts
@@ -0,0 +1,121 @@
+import { useCallback, useEffect, useState } from 'react';
+import { useAppContext } from '../../context/AppContext';
+import { api } from '../../services/api';
+import { formToRequest } from './automationData.ts';
+import type { RuleForm } from './automationData.ts';
+import type { AutomationAccountState, AutomationOverviewResponse, AutomationRule } from '@shared/types/automation.ts';
+
+// the rules, the account controls and the server's settings, with every action that changes them
+export function useAutomations() {
+ const { showToast } = useAppContext();
+ const [overview, setOverview] = useState<AutomationOverviewResponse | null>(null);
+ const [loadError, setLoadError] = useState<string | null>(null);
+ const [busyId, setBusyId] = useState<string | null>(null);
+ // the time the overview was read, so cooldowns are compared with a fixed moment during render
+ const [checkedAt, setCheckedAt] = useState(() => Date.now());
+
+ const load = useCallback(async () => {
+ try {
+ setOverview(await api.getAutomations());
+ setCheckedAt(Date.now());
+ setLoadError(null);
+ } catch (err) {
+ setLoadError((err as Error).message);
+ }
+ }, []);
+
+ useEffect(() => { load(); }, [load]);
+
+ const replaceRule = useCallback((rule: AutomationRule) => {
+ setOverview(current => current && { ...current, rules: current.rules.some(item => item.id === rule.id)
+ ? current.rules.map(item => (item.id === rule.id ? rule : item))
+ : [...current.rules, rule] });
+ }, []);
+
+ const replaceAccount = useCallback((account: AutomationAccountState) => {
+ setOverview(current => current && { ...current, accounts: current.accounts.map(item => (item.accountId === account.accountId ? account : item)) });
+ }, []);
+
+ // saving can also subscribe the account, so the overview is read again to show it
+ const saveRule = useCallback(async (form: RuleForm, ruleId: string | null): Promise<boolean> => {
+ try {
+ const { accountId, ...changes } = formToRequest(form);
+ const { rule } = ruleId ? await api.updateAutomationRule(ruleId, changes) : await api.createAutomationRule({ accountId, ...changes });
+ replaceRule(rule);
+ showToast(ruleId ? 'Rule saved' : 'Rule created');
+ load();
+ return true;
+ } catch (err) {
+ showToast(`Couldn't save the rule. ${(err as Error).message}`, 'error');
+ return false;
+ }
+ }, [load, replaceRule, showToast]);
+
+ const setRuleEnabled = useCallback(async (rule: AutomationRule, enabled: boolean) => {
+ setBusyId(rule.id);
+ try {
+ replaceRule((await api.updateAutomationRule(rule.id, { enabled })).rule);
+ showToast(enabled ? `${rule.name} turned on` : `${rule.name} turned off`);
+ if (enabled) load();
+ } catch (err) {
+ showToast(`Couldn't ${enabled ? 'turn on' : 'turn off'} the rule. ${(err as Error).message}`, 'error');
+ } finally {
+ setBusyId(null);
+ }
+ }, [load, replaceRule, showToast]);
+
+ const duplicateRule = useCallback(async (rule: AutomationRule) => {
+ setBusyId(rule.id);
+ try {
+ replaceRule((await api.duplicateAutomationRule(rule.id)).rule);
+ showToast('Rule copied; the copy is off until you turn it on');
+ } catch (err) {
+ showToast(`Couldn't copy the rule. ${(err as Error).message}`, 'error');
+ } finally {
+ setBusyId(null);
+ }
+ }, [replaceRule, showToast]);
+
+ const deleteRule = useCallback(async (rule: AutomationRule): Promise<boolean> => {
+ setBusyId(rule.id);
+ try {
+ await api.deleteAutomationRule(rule.id);
+ setOverview(current => current && { ...current, rules: current.rules.filter(item => item.id !== rule.id) });
+ showToast('Rule deleted');
+ return true;
+ } catch (err) {
+ showToast(`Couldn't delete the rule. ${(err as Error).message}`, 'error');
+ return false;
+ } finally {
+ setBusyId(null);
+ }
+ }, [showToast]);
+
+ const setAccountPaused = useCallback(async (account: AutomationAccountState, paused: boolean) => {
+ setBusyId(account.accountId);
+ try {
+ replaceAccount((await api.setAutomationAccountPaused(account.accountId, paused)).account);
+ showToast(paused ? `Replies paused for @${account.username}` : `Replies resumed for @${account.username}`);
+ } catch (err) {
+ showToast(`Couldn't ${paused ? 'pause' : 'resume'} replies. ${(err as Error).message}`, 'error');
+ } finally {
+ setBusyId(null);
+ }
+ }, [replaceAccount, showToast]);
+
+ const subscribeAccount = useCallback(async (account: AutomationAccountState) => {
+ setBusyId(account.accountId);
+ try {
+ replaceAccount((await api.subscribeAutomationAccount(account.accountId)).account);
+ showToast(`Comment events turned on for @${account.username}`);
+ } catch (err) {
+ showToast(`Couldn't turn on comment events. ${(err as Error).message}`, 'error');
+ } finally {
+ setBusyId(null);
+ }
+ }, [replaceAccount, showToast]);
+
+ return { overview, loadError, busyId, checkedAt, load, saveRule, setRuleEnabled, duplicateRule, deleteRule, setAccountPaused, subscribeAccount };
+}
+
+export type AutomationsState = ReturnType<typeof useAutomations>;
diff --git a/frontend/src/features/automations/useRuleForm.ts b/frontend/src/features/automations/useRuleForm.ts
new file mode 100644
index 0000000..12d0220
--- /dev/null
+++ b/frontend/src/features/automations/useRuleForm.ts
@@ -0,0 +1,103 @@
+import { useCallback, useEffect, useState } from 'react';
+import type { FormEvent } from 'react';
+import { useAppContext } from '../../context/AppContext';
+import { api } from '../../services/api';
+import { emptyRuleForm, formToRequest, ruleFormProblem, ruleToForm } from './automationData.ts';
+import type { RuleForm } from './automationData.ts';
+import type { AutomationRule, AutomationTestResponse } from '@shared/types/automation.ts';
+import type { InstagramMedia } from '@shared/types/instagram.ts';
+
+// lets a keyword test run before the reply is written
+const TEST_REPLY_PLACEHOLDER = 'Your reply';
+
+interface RuleFormDeps {
+ saveRule: (form: RuleForm, ruleId: string | null) => Promise<boolean>;
+}
+
+// the rule dialog: which rule is open, its fields, the account's posts to aim it at, and a test that sends nothing
+export function useRuleForm({ saveRule }: RuleFormDeps) {
+ const { showToast } = useAppContext();
+ const [open, setOpen] = useState(false);
+ const [ruleId, setRuleId] = useState<string | null>(null);
+ const [form, setForm] = useState<RuleForm>(emptyRuleForm(''));
+ const [saving, setSaving] = useState(false);
+ const [media, setMedia] = useState<InstagramMedia[]>([]);
+ const [mediaLoading, setMediaLoading] = useState(false);
+ const [sampleComment, setSampleComment] = useState('');
+ const [testResult, setTestResult] = useState<AutomationTestResponse | null>(null);
+ const [testing, setTesting] = useState(false);
+
+ const openNew = useCallback((accountId: string) => {
+ setRuleId(null);
+ setForm(emptyRuleForm(accountId));
+ setSampleComment('');
+ setTestResult(null);
+ setOpen(true);
+ }, []);
+
+ const openEdit = useCallback((rule: AutomationRule) => {
+ setRuleId(rule.id);
+ setForm(ruleToForm(rule));
+ setSampleComment('');
+ setTestResult(null);
+ setOpen(true);
+ }, []);
+
+ const setField = useCallback(<K extends keyof RuleForm>(key: K, value: RuleForm[K]) => {
+ setForm(current => ({ ...current, [key]: value, ...(key === 'accountId' ? { mediaIds: [] } : {}) }));
+ setTestResult(null);
+ }, []);
+
+ const toggleMedia = useCallback((id: string) => {
+ setForm(current => ({ ...current, mediaIds: current.mediaIds.includes(id) ? current.mediaIds.filter(item => item !== id) : [...current.mediaIds, id] }));
+ setTestResult(null);
+ }, []);
+
+ // posts load only when the rule is aimed at chosen posts
+ useEffect(() => {
+ if (!open || form.scope !== 'selected' || !form.accountId) return;
+ let cancelled = false;
+ setMediaLoading(true);
+ api.getIGMedia(form.accountId)
+ .then(res => { if (!cancelled) setMedia(res.media); })
+ .catch(err => { if (!cancelled) showToast(`Couldn't load the account's posts. ${(err as Error).message}`, 'error'); })
+ .finally(() => { if (!cancelled) setMediaLoading(false); });
+ return () => { cancelled = true; };
+ }, [open, form.scope, form.accountId, showToast]);
+
+ const runTest = useCallback(async () => {
+ const request = formToRequest(form);
+ setTesting(true);
+ try {
+ // the test checks the keywords; which posts the rule covers applies to real comments only
+ setTestResult(await api.testAutomationRule({
+ keywords: request.keywords, matchMode: request.matchMode, caseSensitive: request.caseSensitive,
+ replyText: request.replyText || TEST_REPLY_PLACEHOLDER, linkUrl: request.linkUrl, comment: sampleComment,
+ }));
+ } catch (err) {
+ showToast(`Couldn't test the rule. ${(err as Error).message}`, 'error');
+ } finally {
+ setTesting(false);
+ }
+ }, [form, sampleComment, showToast]);
+
+ const handleSubmit = useCallback(async (event: FormEvent<HTMLFormElement>) => {
+ event.preventDefault();
+ const problem = ruleFormProblem(form);
+ if (problem) {
+ showToast(`Couldn't save the rule. ${problem}.`, 'error');
+ return;
+ }
+ setSaving(true);
+ const saved = await saveRule(form, ruleId);
+ setSaving(false);
+ if (saved) setOpen(false);
+ }, [form, ruleId, saveRule, showToast]);
+
+ return {
+ open, setOpen, ruleId, form, setField, toggleMedia, saving, media, mediaLoading,
+ sampleComment, setSampleComment, testResult, testing, runTest, openNew, openEdit, handleSubmit,
+ };
+}
+
+export type RuleFormState = ReturnType<typeof useRuleForm>;
diff --git a/frontend/src/layout/navigation.ts b/frontend/src/layout/navigation.ts
index b1e7c52..70d5bfd 100644
--- a/frontend/src/layout/navigation.ts
+++ b/frontend/src/layout/navigation.ts
@@ -1,5 +1,5 @@
import {
- LayoutDashboard, PlaySquare, Scissors, Clapperboard, MessagesSquare, Bookmark, Send, Users, Settings,
+ LayoutDashboard, PlaySquare, Scissors, Clapperboard, MessagesSquare, Bookmark, Send, MessageSquareReply, Users, Settings,
} from 'lucide-react';
import type { LucideIcon } from 'lucide-react';
@@ -42,7 +42,8 @@ export const NAV_GROUPS: NavGroup[] = [
{
label: 'Publishing',
items: [
- { path: '/upload', label: 'Publish', icon: Send },
+ { path: '/upload', label: 'Publish', icon: Send },
+ { path: '/automations', label: 'Automations', icon: MessageSquareReply },
],
},
{
diff --git a/frontend/src/services/api.ts b/frontend/src/services/api.ts
index 103e042..df8fbf4 100644
--- a/frontend/src/services/api.ts
+++ b/frontend/src/services/api.ts
@@ -13,6 +13,11 @@ import type {
InstagramPublishResponse, InstagramTokenRefreshResponse,
} from '@shared/types/instagram.ts';
import type { RedditCacheData, RedditPost } from '@shared/types/reddit.ts';
+import type {
+ AutomationAccountResponse, AutomationActivityItemResponse, AutomationActivityResponse, AutomationOverviewResponse,
+ AutomationRuleRequest, AutomationRuleResponse, AutomationRuleUpdateRequest, AutomationStatsResponse, AutomationTestRequest,
+ AutomationTestResponse,
+} from '@shared/types/automation.ts';
import type {
ResolveChannelResponse, YouTubeAnalyticsPayload, YouTubeComparisonResponse, YouTubeVideosResponse,
} from '@shared/types/youtube.ts';
@@ -182,4 +187,17 @@ export const api = {
deleteScheduledPost: (id: string) => request<SuccessMessageResponse>(`/scheduled-posts/${id}`, { method: 'DELETE' }),
deleteAllScheduledPosts: () => request<ScheduledPostDeleteAllResponse>('/scheduled-posts', { method: 'DELETE' }),
processScheduled: () => request<ScheduledPublishRunResponse>('/process-scheduled'),
+
+ // Comment-to-DM automation; activity and stats take filters as query parameters
+ getAutomations: () => request<AutomationOverviewResponse>('/automations'),
+ createAutomationRule: (data: AutomationRuleRequest) => request<AutomationRuleResponse>('/automations/rules', { method: 'POST', body: JSON.stringify(data) }),
+ updateAutomationRule: (id: string, data: AutomationRuleUpdateRequest) => request<AutomationRuleResponse>(`/automations/rules/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
+ duplicateAutomationRule: (id: string) => request<AutomationRuleResponse>(`/automations/rules/${id}/duplicate`, { method: 'POST' }),
+ deleteAutomationRule: (id: string) => request<SuccessMessageResponse>(`/automations/rules/${id}`, { method: 'DELETE' }),
+ testAutomationRule: (data: AutomationTestRequest) => request<AutomationTestResponse>('/automations/test', { method: 'POST', body: JSON.stringify(data) }),
+ getAutomationActivity: (query: URLSearchParams) => request<AutomationActivityResponse>(`/automations/activity?${query}`),
+ retryAutomationActivity: (id: string) => request<AutomationActivityItemResponse>(`/automations/activity/${id}/retry`, { method: 'POST' }),
+ getAutomationStats: (query: URLSearchParams) => request<AutomationStatsResponse>(`/automations/stats?${query}`),
+ setAutomationAccountPaused: (accountId: string, paused: boolean) => request<AutomationAccountResponse>(`/automations/accounts/${accountId}`, { method: 'PUT', body: JSON.stringify({ paused }) }),
+ subscribeAutomationAccount: (accountId: string) => request<AutomationAccountResponse>(`/automations/accounts/${accountId}/subscribe`, { method: 'POST' }),
};
diff --git a/frontend/tests/features/automations/automationData.test.ts b/frontend/tests/features/automations/automationData.test.ts
new file mode 100644
index 0000000..05f2669
--- /dev/null
+++ b/frontend/tests/features/automations/automationData.test.ts
@@ -0,0 +1,112 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import {
+ ACTIVITY_FILTERS, MAX_MESSAGE_BYTES, accountStatus, canRetry, composeReply, emptyRuleForm, formToRequest, matchModeLabel, messageBytes,
+ parseKeywords, periodStart, ruleFormProblem, ruleScopeLabel, ruleToForm, statusDisplay, summarizeStats,
+} from '../../../src/features/automations/automationData.ts';
+import type { RuleForm } from '../../../src/features/automations/automationData.ts';
+import type { AutomationAccountState, AutomationRule } from '../../../../shared/types/automation.ts';
+
+const NOW = Date.parse('2026-10-16T12:00:00Z');
+
+function form(overrides: Partial<RuleForm> = {}): RuleForm {
+ return { ...emptyRuleForm('ig1'), name: 'Guide', keywordsText: 'GUIDE', replyText: 'Here it is', ...overrides };
+}
+
+const rule: AutomationRule = {
+ id: 'r1', accountId: 'ig1', name: 'Guide', keywords: ['GUIDE', 'LINK'], matchMode: 'exact', caseSensitive: true, mediaIds: ['1', '2'],
+ replyText: 'Here it is', linkUrl: 'https://example.com', enabled: false, hourlyLimit: 30, createdAt: 'c', updatedAt: 'u',
+};
+
+test('accepted replies say Instagram accepted them, never that they were delivered or read', () => {
+ assert.equal(statusDisplay({ status: 'accepted', statusReason: null }).label, 'Accepted by Instagram');
+ assert.deepEqual(statusDisplay({ status: 'queued', statusReason: 'paused' }), { label: 'Held', tone: 'warning' });
+ assert.equal(statusDisplay({ status: 'needs_review', statusReason: 'no_answer' }).label, 'Needs review');
+});
+
+test('the status filters cover every status exactly once, apart from All', () => {
+ const covered = Object.values(ACTIVITY_FILTERS).flatMap(filter => filter.statuses ?? []);
+ assert.equal(new Set(covered).size, covered.length);
+ assert.equal(covered.length, 10);
+});
+
+test('stats become received, matched, accepted, waiting, attention and rate limited counts', () => {
+ assert.deepEqual(summarizeStats({
+ comments: { ignored: 5, accepted: 3, queued: 1, retry_wait: 1, failed: 2, needs_review: 1, skipped: 1 },
+ attempts: { rate_limited: 4, accepted: 3 },
+ }), { received: 14, matched: 9, accepted: 3, waiting: 2, attention: 3, rateLimited: 4 });
+ assert.deepEqual(summarizeStats({ comments: {}, attempts: {} }), { received: 0, matched: 0, accepted: 0, waiting: 0, attention: 0, rateLimited: 0 });
+});
+
+test('a period starts the right length of time before now', () => {
+ assert.equal(periodStart('24h', NOW), '2026-10-15T12:00:00.000Z');
+ assert.equal(periodStart('30d', NOW), '2026-09-16T12:00:00.000Z');
+});
+
+test('rule summaries name the posts covered and how keywords match', () => {
+ assert.equal(ruleScopeLabel({ mediaIds: [] }), 'All posts and reels');
+ assert.equal(ruleScopeLabel({ mediaIds: ['1'] }), '1 selected post');
+ assert.equal(ruleScopeLabel({ mediaIds: ['1', '2'] }), '2 selected posts');
+ assert.equal(matchModeLabel({ matchMode: 'contains', caseSensitive: false }), 'Anywhere in the comment');
+ assert.equal(matchModeLabel({ matchMode: 'exact', caseSensitive: true }), 'Whole comment, same letter case');
+});
+
+test('only failed, skipped and review items inside the 7 days offer a retry', () => {
+ const future = new Date(NOW + 1000).toISOString();
+ assert.equal(canRetry({ status: 'failed', expiresAt: future }, NOW), true);
+ assert.equal(canRetry({ status: 'needs_review', expiresAt: future }, NOW), true);
+ assert.equal(canRetry({ status: 'accepted', expiresAt: future }, NOW), false);
+ assert.equal(canRetry({ status: 'failed', expiresAt: new Date(NOW).toISOString() }, NOW), false);
+});
+
+test('keywords split on commas and new lines, without blanks or repeats', () => {
+ assert.deepEqual(parseKeywords(' GUIDE, guide ,\nLink,, ', false), ['GUIDE', 'Link']);
+ assert.deepEqual(parseKeywords('GUIDE, guide', true), ['GUIDE', 'guide']);
+});
+
+test('the preview puts the link on its own line and counts bytes as Instagram does', () => {
+ assert.equal(composeReply(' Hi ', ' https://e.com '), 'Hi\n\nhttps://e.com');
+ assert.equal(composeReply('Hi', ' '), 'Hi');
+ assert.equal(messageBytes('é'), 2);
+});
+
+test('a rule turns into its form and back without losing a field', () => {
+ const editing = ruleToForm(rule);
+ assert.deepEqual(editing, {
+ accountId: 'ig1', name: 'Guide', keywordsText: 'GUIDE, LINK', matchMode: 'exact', caseSensitive: true, scope: 'selected', mediaIds: ['1', '2'],
+ replyText: 'Here it is', linkUrl: 'https://example.com', hourlyLimit: '30', enabled: false,
+ });
+ const { accountId, name, keywords, matchMode, caseSensitive, mediaIds, replyText, linkUrl, enabled, hourlyLimit } = rule;
+ assert.deepEqual(formToRequest(editing), { accountId, name, keywords, matchMode, caseSensitive, mediaIds, replyText, linkUrl, enabled, hourlyLimit });
+});
+
+test('a rule for every post sends no post ids, and blank optional fields become null', () => {
+ const request = formToRequest(form({ scope: 'all', mediaIds: ['1'], linkUrl: ' ', hourlyLimit: '' }));
+ assert.deepEqual([request.mediaIds, request.linkUrl, request.hourlyLimit], [[], null, null]);
+});
+
+test('the form names the first thing to fix, in the order of the fields', () => {
+ assert.equal(ruleFormProblem(form()), null);
+ assert.equal(ruleFormProblem(form({ accountId: '' })), 'Choose the Instagram account');
+ assert.equal(ruleFormProblem(form({ name: ' ' })), 'Give the rule a name');
+ assert.equal(ruleFormProblem(form({ keywordsText: ', ,' })), 'Add at least one keyword');
+ assert.equal(ruleFormProblem(form({ keywordsText: Array.from({ length: 11 }, (_, i) => `k${i}`).join(',') })), 'A rule can have at most 10 keywords');
+ assert.equal(ruleFormProblem(form({ scope: 'selected' })), 'Choose at least one post, or answer comments on every post');
+ assert.equal(ruleFormProblem(form({ replyText: '' })), 'Write the reply to send');
+ assert.equal(ruleFormProblem(form({ linkUrl: 'http://e.com' })), 'The link must start with https://');
+ assert.equal(ruleFormProblem(form({ linkUrl: 'e.com' })), 'The link must be a full address starting with https://');
+ assert.equal(ruleFormProblem(form({ hourlyLimit: '0' })), 'The hourly limit must be a whole number from 1 to 750');
+ assert.equal(ruleFormProblem(form({ hourlyLimit: '2.5' })), 'The hourly limit must be a whole number from 1 to 750');
+ assert.match(ruleFormProblem(form({ replyText: 'é'.repeat(MAX_MESSAGE_BYTES / 2 + 1) }))!, /is 1002 bytes; Instagram accepts at most 1000/);
+});
+
+test('an account shows held, paused, cooling down, not receiving or receiving, in that order', () => {
+ const base: AutomationAccountState = {
+ accountId: 'ig1', username: 'me', profilePictureUrl: '', paused: false, cooldownUntil: null, cooldownReason: null, subscribedAt: 'x',
+ };
+ assert.equal(accountStatus({ ...base, paused: true, cooldownReason: 'Reconnect it' }, NOW).label, 'Held');
+ assert.equal(accountStatus({ ...base, paused: true }, NOW).label, 'Paused');
+ assert.equal(accountStatus({ ...base, cooldownUntil: new Date(NOW + 1000).toISOString() }, NOW).label, 'Cooling down');
+ assert.equal(accountStatus({ ...base, cooldownUntil: new Date(NOW - 1000).toISOString() }, NOW).label, 'Receiving comments');
+ assert.equal(accountStatus({ ...base, subscribedAt: null }, NOW).label, 'Not receiving comments');
+});