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(automations): set up and follow public comment replies in the app
spacesdrive455c79130607
diff --git a/frontend/src/features/automations/AutomationActivity.tsx b/frontend/src/features/automations/AutomationActivity.tsxindex 69a5851..2e673ef 100644--- a/frontend/src/features/automations/AutomationActivity.tsx+++ b/frontend/src/features/automations/AutomationActivity.tsx@@ -1,4 +1,4 @@-import { History, RefreshCw, RotateCcw } from 'lucide-react';+import { History, MessageCircle, RefreshCw, RotateCcw, Send } 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';@@ -8,11 +8,12 @@ import FilterChips from '@/components/FilterChips';import RowAction from '@/components/RowAction';import SurfaceBox from '@/components/SurfaceBox';import { EmptyState } from '@/components/StateViews';+import type { ReactNode } from 'react';import { fmtDate, timeAgo } from '../../utils/formatters';-import { ACTIVITY_FILTERS, STATS_PERIODS, canRetry, gateDetail, statusDisplay } from './automationData.ts';-import type { ActivityFilter, StatsPeriod } from './automationData.ts';+import { ACTIVITY_FILTERS, STATS_PERIODS, canRetry, canRetryPublic, gateDetail, publicStatusDisplay, statusDisplay } from './automationData.ts';+import type { ActivityFilter, StatsPeriod, StatusDisplay } from './automationData.ts';import type { AutomationAccountState, AutomationActivityItem, AutomationRule } from '@shared/types/automation.ts';-import type { AutomationActivityState } from './useAutomationActivity';+import type { AutomationActivityState, RetryAction } from './useAutomationActivity';interface AutomationActivityProps {activity: AutomationActivityState;@@ -25,17 +26,47 @@ interface ActivityRowProps {now: number;ruleName: string | null;username: string;- retrying: boolean;+ // which of the item's replies is being retried, if any+ retrying: RetryAction | null;onRetry: (item: AutomationActivityItem) => void;+ onRetryPublic: (item: AutomationActivityItem) => void;+}++interface ReplyLineProps {+ icon: ReactNode;+ label: string;+ status: StatusDisplay;+ detail: string;+}++// one of a comment's replies: which one, where it stands and why+function ReplyLine({ icon, label, status, detail }: ReplyLineProps) {+ return (+ <div className="flex flex-col gap-1">+ <div className="flex flex-wrap items-center gap-1.5">+ <span className="flex items-center gap-1 text-caption text-ink-faint [&_svg]:size-3.5">{icon}{label}</span>+ <Badge variant={status.tone}>{status.label}</Badge>+ </div>+ <p className="text-small text-ink-muted">{detail}</p>+ </div>+ );}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);+function ActivityRow({ item, now, ruleName, username, retrying, onRetry, onRetryPublic }: ActivityRowProps) {const waitingUntil = item.nextAttemptAt && ['queued', 'retry_wait'].includes(item.status) ? `Next try ${fmtDate(item.nextAttemptAt)}` : null;+ const privateOff = item.status === 'skipped' && item.statusReason === 'private_reply_off';+ const privateDetail = privateOff+ ? 'This rule does not send a private reply.'+ : gateDetail(item) ?? item.errorMessage ?? waitingUntil ?? (item.acceptedAt ? `Accepted ${fmtDate(item.acceptedAt)}` : '-');+ const publicReply = item.publicReply;+ const publicWaiting = publicReply?.nextAttemptAt && ['queued', 'retry_wait'].includes(publicReply.status) ? `Next try ${fmtDate(publicReply.nextAttemptAt)}` : null;+ const publicDetail = publicReply+ ? publicReply.errorMessage ?? publicWaiting ?? (publicReply.acceptedAt ? `Posted ${fmtDate(publicReply.acceptedAt)}: ${publicReply.text}` : publicReply.text)+ : '';return (<TableRow><TableCell className="whitespace-nowrap text-small text-ink-muted" title={fmtDate(item.createdAt)}>{timeAgo(item.createdAt)}</TableCell>@@ -45,20 +76,34 @@ function ActivityRow({ item, now, ruleName, username, retrying, onRetry }: Activ{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">- {gateDetail(item) ?? item.errorMessage ?? waitingUntil ?? (item.acceptedAt ? `Accepted ${fmtDate(item.acceptedAt)}` : '-')}+ <TableCell className="min-w-72 max-w-md whitespace-normal">+ <div className="flex flex-col gap-2.5">+ {item.status === 'ignored' && <Badge variant="secondary" className="self-start">{statusDisplay(item).label}</Badge>}+ {item.status !== 'ignored' && (!privateOff || !publicReply) && <ReplyLine icon={<Send />} label="Private reply" status={statusDisplay(item)} detail={privateDetail} />}+ {publicReply && <ReplyLine icon={<MessageCircle />} label="Public reply" status={publicStatusDisplay(publicReply)} detail={publicDetail} />}+ </div></TableCell><TableCell className="text-right">- {canRetry(item, now) && (- <RowAction- label={item.status === 'needs_review' || item.followup?.status === 'needs_review' ? 'Send again after checking Instagram' : 'Try again'}- onClick={() => onRetry(item)}- disabled={retrying}- >- {retrying ? <Spinner /> : <RotateCcw />}- </RowAction>- )}+ <div className="flex justify-end gap-1">+ {canRetry(item, now) && (+ <RowAction+ label={item.status === 'needs_review' || item.followup?.status === 'needs_review' ? 'Send the private reply again after checking Instagram' : 'Try the private reply again'}+ onClick={() => onRetry(item)}+ disabled={retrying !== null}+ >+ {retrying === 'private' ? <Spinner /> : <RotateCcw />}+ </RowAction>+ )}+ {canRetryPublic(item, now) && (+ <RowAction+ label={publicReply?.status === 'needs_review' ? 'Post the public reply again after checking the comment' : 'Try the public reply again'}+ onClick={() => onRetryPublic(item)}+ disabled={retrying !== null}+ >+ {retrying === 'public' ? <Spinner /> : <MessageCircle />}+ </RowAction>+ )}+ </div></TableCell></TableRow>);@@ -75,7 +120,7 @@ export default function AutomationActivity({ activity, accounts, rules }: Automa<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>+ <p className="text-small text-ink-muted">Every comment received on an account with an active rule, and what happened to its private and public replies. The status filter follows the private reply.</p></div><Button size="sm" variant="ghost" onClick={activity.load}><RefreshCw data-icon="inline-start" />Refresh</Button></div>@@ -116,8 +161,7 @@ export default function AutomationActivity({ activity, accounts, rules }: Automa<TableHead>Account</TableHead><TableHead>Comment</TableHead><TableHead>Rule</TableHead>- <TableHead>Status</TableHead>- <TableHead>Details</TableHead>+ <TableHead>Replies</TableHead><TableHead className="text-right"><span className="sr-only">Actions</span></TableHead></TableRow></TableHeader>@@ -129,13 +173,14 @@ export default function AutomationActivity({ activity, accounts, rules }: Automanow={activity.checkedAt}ruleName={ruleName(item.ruleId)}username={username(item.accountId)}- retrying={activity.retryingId === item.id}+ retrying={activity.retrying?.id === item.id ? activity.retrying.action : null}onRetry={activity.retry}+ onRetryPublic={activity.retryPublic}/>))}{items.length === 0 && (<TableRow className="hover:bg-transparent">- <TableCell colSpan={7}>+ <TableCell colSpan={6}>{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." />}diff --git a/frontend/src/features/automations/AutomationMetrics.tsx b/frontend/src/features/automations/AutomationMetrics.tsxindex 17b1f98..564b7f1 100644--- a/frontend/src/features/automations/AutomationMetrics.tsx+++ b/frontend/src/features/automations/AutomationMetrics.tsx@@ -1,4 +1,4 @@-import { AlertTriangle, Clock, Gauge, MessageCircle, MessageSquareReply, Send } from 'lucide-react';+import { AlertTriangle, Clock, Gauge, MessageCircle, MessageSquareReply, MessagesSquare, Send } from 'lucide-react';import MetricBox from '@/components/MetricBox';import { fmtNumFull } from '../../utils/formatters';import type { AutomationSummary } from './automationData.ts';@@ -12,12 +12,13 @@ interface AutomationMetricsProps {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">+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4 2xl:grid-cols-7"><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 highlight loading={loading} icon={<Send />} label="Accepted by Instagram" value={value(summary?.accepted)} subtitle="Private replies; Instagram does not report reads" />+ <MetricBox small loading={loading} icon={<MessagesSquare />} label="Public replies posted" value={value(summary?.publicPosted)} subtitle="Under the comments" /><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={<AlertTriangle />} label="Needs attention" value={value(summary?.attention)} subtitle="Private or public, 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/AutomationRules.tsx b/frontend/src/features/automations/AutomationRules.tsxindex b47f822..f132520 100644--- a/frontend/src/features/automations/AutomationRules.tsx+++ b/frontend/src/features/automations/AutomationRules.tsx@@ -40,12 +40,19 @@ function RuleRow({ rule, username, busy, automations, onEdit, onDelete }: RuleRo{rule.matchMode === 'any'? <Badge variant="warning">Any comment</Badge>: rule.keywords.map(keyword => <Badge key={keyword} variant="secondary">{keyword}</Badge>)}+ {rule.privateReplyEnabled && <Badge variant="info">Private reply</Badge>}+ {rule.publicReplyEnabled && <Badge variant="info">Public reply</Badge>}{rule.requireFollow && <Badge variant="info">Followers only, testing</Badge>}</div><p className="text-small text-ink-muted">{matchModeLabel(rule)} · {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>+ {rule.privateReplyEnabled && <p className="line-clamp-2 max-w-2xl text-small text-ink">{rule.replyText}{rule.linkUrl ? ` ${rule.linkUrl}` : ''}</p>}+ {rule.publicReplyEnabled && (+ <p className="line-clamp-2 max-w-2xl text-small text-ink-muted">+ In public: {rule.publicReplyTexts[0]}{rule.publicReplyTexts.length > 1 ? ` (and ${rule.publicReplyTexts.length - 1} more wording${rule.publicReplyTexts.length > 2 ? 's' : ''})` : ''}+ </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">@@ -65,14 +72,14 @@ export default function AutomationRules({ rules, accounts, automations, onNew, oreturn (<SurfaceBoxtitle="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."+ subheader="A comment is answered by the first rule that matches it, in private, in public or both. Rules for chosen posts are checked before rules for every post.">{rules.length === 0 ? (<EmptyStatecompacticon={<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."+ description="Create a rule with a keyword, such as GUIDE, and how to answer anyone who comments it: a private reply, a public reply or both."action={<Button size="sm" onClick={onNew}><Plus data-icon="inline-start" />New rule</Button>}/>) : (diff --git a/frontend/src/features/automations/Automations.tsx b/frontend/src/features/automations/Automations.tsxindex ed58791..4a7e596 100644--- a/frontend/src/features/automations/Automations.tsx+++ b/frontend/src/features/automations/Automations.tsx@@ -29,7 +29,7 @@ export default function Automations() {const header = (<PageHeadertitle="Automations"- description="Send a private reply on Instagram when someone comments a keyword on your posts and reels."+ description="Answer comments on your posts and reels with a private reply, a public reply under the comment, or both."actions={overview && overview.accounts.length > 0 && (<Button onClick={() => rule.openNew(overview.accounts[0].accountId)}><Plus data-icon="inline-start" />New rule</Button>)}diff --git a/frontend/src/features/automations/RuleDialog.tsx b/frontend/src/features/automations/RuleDialog.tsxindex 1809d74..f745047 100644--- a/frontend/src/features/automations/RuleDialog.tsx+++ b/frontend/src/features/automations/RuleDialog.tsx@@ -1,4 +1,4 @@-import { Megaphone, UserCheck } from 'lucide-react';+import { Megaphone, MessageCircle, Send, UserCheck } from 'lucide-react';import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';@@ -12,7 +12,9 @@ import { FieldRow } from '@/components/DetailPanel';import AccountSelect from '@/components/AccountSelect';import RuleMediaPicker from './RuleMediaPicker';import RulePreview from './RulePreview';+import RulePublicReplies from './RulePublicReplies';import type { AutomationMatchMode } from '@shared/types/automation.ts';+import type { ReactNode } from 'react';import type { AppAccount } from '../../utils/formatters';import type { RuleScope } from './automationData.ts';import type { RuleFormState } from './useRuleForm';@@ -22,6 +24,16 @@ interface RuleDialogProps {igAccounts: AppAccount[];}+interface ReplySectionProps {+ id: string;+ icon: ReactNode;+ title: string;+ description: string;+ checked: boolean;+ onCheckedChange: (checked: boolean) => void;+ children: ReactNode;+}+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' },@@ -33,6 +45,20 @@ const SCOPES: { value: RuleScope; label: string }[] = [{ value: 'selected', label: 'Only the posts I choose' },];+// one way of answering, switched on and off on its own; its fields show only while it is on+function ReplySection({ id, icon, title, description, checked, onCheckedChange, children }: ReplySectionProps) {+ return (+ <div className="flex flex-col gap-3 rounded-card border border-line p-4">+ <label htmlFor={id} className="flex items-center justify-between gap-3 text-sm font-medium text-ink">+ <span className="flex items-center gap-2 [&_svg]:size-4 [&_svg]:text-ink-muted">{icon}{title}</span>+ <Switch id={id} checked={checked} onCheckedChange={onCheckedChange} />+ </label>+ <p className="text-small text-ink-muted">{description}</p>+ {checked && children}+ </div>+ );+}+export default function RuleDialog({ rule, igAccounts }: RuleDialogProps) {const { form, setField, saving } = rule;return (@@ -40,7 +66,7 @@ export default function RuleDialog({ rule, igAccounts }: RuleDialogProps) {<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 matches, Twiligent sends its author this private reply on Instagram.</DialogDescription>+ <DialogDescription>When a comment matches, Twiligent answers its author in a private message, publicly under the comment, or both.</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">@@ -69,11 +95,11 @@ export default function RuleDialog({ rule, igAccounts }: RuleDialogProps) {{form.matchMode === 'any' ? (<Alert variant="warning"><Megaphone />- <AlertTitle>Every comment gets this reply</AlertTitle>+ <AlertTitle>Every comment gets this answer</AlertTitle><AlertDescription>- Everyone who comments receives a private message, including people who did not ask for one, and a busy post reaches the- hourly limits sooner. Each person gets at most a few replies a day. Aim the rule at chosen posts to keep it small. A- keyword rule for the same post still answers first.+ Everyone who comments is answered, including people who did not ask, and a busy post reaches the hourly limits sooner.+ Each person gets at most a few private replies a day and one public reply per post a day. Aim the rule at chosen posts to+ keep it small. A keyword rule for the same post still answers first.</AlertDescription></Alert>) : (@@ -92,43 +118,66 @@ export default function RuleDialog({ rule, igAccounts }: RuleDialogProps) {</Select>{form.scope === 'selected' && <RuleMediaPicker media={rule.media} loading={rule.mediaLoading} selected={form.mediaIds} onToggle={rule.toggleMedia} />}</FieldRow>- <div className="flex flex-col gap-3 rounded-card border border-line p-4">- <label htmlFor="rule-follow" className="flex items-center justify-between gap-3 text-sm font-medium text-ink">- <span className="flex items-center gap-2">- <UserCheck className="size-4 text-ink-muted" />Send the link only to followers- <Badge variant="warning">Testing</Badge>- </span>- <Switch id="rule-follow" checked={form.requireFollow} onCheckedChange={checked => setField('requireFollow', checked)} />- </label>+ <ReplySection+ id="rule-private"+ icon={<Send />}+ title="Send a private reply"+ description="Instagram allows one private message per comment, within 7 days of it."+ checked={form.privateReplyEnabled}+ onCheckedChange={checked => setField('privateReplyEnabled', checked)}+ >+ <div className="flex flex-col gap-3 border-t border-divider pt-3">+ <label htmlFor="rule-follow" className="flex items-center justify-between gap-3 text-sm font-medium text-ink">+ <span className="flex items-center gap-2">+ <UserCheck className="size-4 text-ink-muted" />Send the link only to followers+ <Badge variant="warning">Testing</Badge>+ </span>+ <Switch id="rule-follow" checked={form.requireFollow} onCheckedChange={checked => setField('requireFollow', checked)} />+ </label>+ <p className="text-small text-ink-muted">+ Instagram tells Twiligent whether someone follows you only after they message you. With this on, the first reply asks them+ to follow and reply. When they reply, Twiligent asks Instagram, then sends the reply and link to followers and a reminder to+ everyone else, twice at most. If Instagram cannot say, nothing is sent.+ </p>+ <p className="text-small text-warning">+ This option is still being tested and may or may not work. It needs Instagram to send your account's messages to+ Twiligent, which Meta may not allow without extra app approval. Use a keyword rule when the link must arrive.+ </p>+ {form.requireFollow && (+ <>+ <FieldRow label="First reply" htmlFor="rule-follow-prompt" hint="Sent to everyone who comments. It has no link.">+ <Textarea id="rule-follow-prompt" rows={3} maxLength={1000} value={form.followPromptText} onChange={e => setField('followPromptText', e.target.value)} />+ </FieldRow>+ <FieldRow label="Reminder" htmlFor="rule-follow-reminder" hint="Sent when they reply but do not follow yet.">+ <Textarea id="rule-follow-reminder" rows={3} maxLength={1000} value={form.notFollowingText} onChange={e => setField('notFollowingText', e.target.value)} />+ </FieldRow>+ </>+ )}+ </div>+ <FieldRow label={form.requireFollow ? 'Reply for followers' : '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="Private 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>+ </ReplySection>+ <ReplySection+ id="rule-public"+ icon={<MessageCircle />}+ title="Reply publicly under the comment"+ description="Everyone can see it. One wording is picked for each comment, so a busy post does not fill with the same words, and each person gets at most one public reply per post a day."+ checked={form.publicReplyEnabled}+ onCheckedChange={checked => setField('publicReplyEnabled', checked)}+ >+ <RulePublicReplies texts={form.publicReplyTexts} onChange={texts => setField('publicReplyTexts', texts)} /><p className="text-small text-ink-muted">- Instagram tells Twiligent whether someone follows you only after they message you. With this on, the first reply asks them- to follow and reply. When they reply, Twiligent asks Instagram, then sends the reply and link to followers and a reminder to- everyone else, twice at most. If Instagram cannot say, nothing is sent.+ Keep it short and friendly, and leave the link for the private reply. The two are sent apart, so avoid promising a message:+ the private reply can fail on its own, for example when the person does not accept messages.</p>- <p className="text-small text-warning">- This option is still being tested and may or may not work. It needs Instagram to send your account's messages to- Twiligent, which Meta may not allow without extra app approval. Use a keyword rule when the link must arrive.- </p>- {form.requireFollow && (- <>- <FieldRow label="First reply" htmlFor="rule-follow-prompt" hint="Sent to everyone who comments. It has no link.">- <Textarea id="rule-follow-prompt" rows={3} maxLength={1000} value={form.followPromptText} onChange={e => setField('followPromptText', e.target.value)} />- </FieldRow>- <FieldRow label="Reminder" htmlFor="rule-follow-reminder" hint="Sent when they reply but do not follow yet.">- <Textarea id="rule-follow-reminder" rows={3} maxLength={1000} value={form.notFollowingText} onChange={e => setField('notFollowingText', e.target.value)} />- </FieldRow>- </>- )}- </div>- <FieldRow label={form.requireFollow ? 'Reply for followers' : '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>+ </ReplySection><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)} />diff --git a/frontend/src/features/automations/RulePreview.tsx b/frontend/src/features/automations/RulePreview.tsxindex ef53905..f38d1d4 100644--- a/frontend/src/features/automations/RulePreview.tsx+++ b/frontend/src/features/automations/RulePreview.tsx@@ -3,7 +3,7 @@ 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 { MAX_MESSAGE_BYTES, composeReply, messageBytes, publicReplyTexts } from './automationData.ts';import type { RuleFormState } from './useRuleForm';interface RulePreviewProps {@@ -18,28 +18,56 @@ function Bubble({ text, placeholder }: { text: string; placeholder: string }) {);}-// the private reply as the commenter would see it, and a match test that sends nothing+// the comment and the public reply under it, as they would read in the thread+function Thread({ comment, reply }: { comment: string; reply: string }) {+ return (+ <div className="flex flex-col gap-2 rounded-card bg-surface-raised px-3.5 py-3 text-sm shadow-xs">+ <p className="text-ink"><span className="font-semibold">commenter</span> {comment || <span className="text-ink-faint">Their comment</span>}</p>+ <p className="border-l-2 border-line pl-3 text-ink">+ <span className="font-semibold">you</span> {reply || <span className="text-ink-faint">Your public reply appears here</span>}+ </p>+ </div>+ );+}++// what the commenter would see in private and under their comment, and a match test that sends nothingexport default function RulePreview({ rule }: RulePreviewProps) {const { form, testResult } = rule;const message = composeReply(form.replyText, form.linkUrl);const bytes = messageBytes(message);+ const publicTexts = publicReplyTexts(form.publicReplyTexts);const canTest = rule.sampleComment.trim() && (form.matchMode === 'any' || form.keywordsText.trim());+ const answers = [form.privateReplyEnabled && (form.requireFollow ? 'the first private reply' : 'the private reply'), form.publicReplyEnabled && 'the public reply']+ .filter(Boolean)+ .join(' and ');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>- {form.requireFollow && (- <>- <p className="text-caption text-ink-faint">First reply, to everyone who comments</p>- <Bubble text={form.followPromptText.trim()} placeholder="Your request to follow appears here" />- <p className="text-caption text-ink-faint">After they reply, if Instagram says they follow</p>- </>- )}- <Bubble text={message} placeholder="Your reply appears here" />- <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>+ {form.publicReplyEnabled && (+ <div className="flex flex-col gap-2">+ <p className="text-small font-medium text-ink">Under the comment</p>+ <Thread comment={rule.sampleComment.trim()} reply={publicTexts[0] ?? ''} />+ {publicTexts.length > 1 && <p className="text-caption text-ink-faint">One of {publicTexts.length} wordings, picked for each comment.</p>}+ </div>+ )}+ {form.privateReplyEnabled && (+ <div className="flex flex-col gap-2">+ <p className="text-small font-medium text-ink">Private message</p>+ {form.requireFollow && (+ <>+ <p className="text-caption text-ink-faint">First reply, to everyone who comments</p>+ <Bubble text={form.followPromptText.trim()} placeholder="Your request to follow appears here" />+ <p className="text-caption text-ink-faint">After they reply, if Instagram says they follow</p>+ </>+ )}+ <Bubble text={message} placeholder="Your reply appears here" />+ <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>+ )}+ {!form.privateReplyEnabled && !form.publicReplyEnabled && (+ <p className="text-small text-ink-muted">Turn on the private reply, the public reply, or both, to see them here.</p>+ )}<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">@@ -52,11 +80,11 @@ export default function RulePreview({ rule }: RulePreviewProps) {{testResult && (<p role="status" className={cn('text-small', testResult.matched ? 'text-success' : 'text-ink-muted')}>{testResult.matched- ? `${testResult.keyword ? `Matches the keyword ${testResult.keyword}.` : 'This rule answers any comment.'} This comment would get the ${form.requireFollow ? 'first reply' : 'reply'} above.`- : 'No keyword matches this comment, so it would get no reply.'}+ ? `${testResult.keyword ? `Matches the keyword ${testResult.keyword}.` : 'This rule answers any comment.'} This comment would get ${answers || 'no answer'}.`+ : 'No keyword matches this comment, so it would get no answer.'}</p>)}- <p className="text-caption text-ink-faint">The test checks the match only. Nothing is sent.</p>+ <p className="text-caption text-ink-faint">The test checks the match only. Nothing is sent or posted.</p></div></div>);diff --git a/frontend/src/features/automations/RulePublicReplies.tsx b/frontend/src/features/automations/RulePublicReplies.tsxnew file mode 100644index 0000000..8070472--- /dev/null+++ b/frontend/src/features/automations/RulePublicReplies.tsx@@ -0,0 +1,51 @@+import { Plus, X } from 'lucide-react';+import { Button } from '@/components/ui/button';+import { Textarea } from '@/components/ui/textarea';+import RowAction from '@/components/RowAction';+import { cn } from '@/lib/utils';+import { MAX_PUBLIC_REPLY_CHARS, MAX_PUBLIC_REPLY_TEXTS, publicReplyTextProblem } from './automationData.ts';++interface RulePublicRepliesProps {+ texts: string[];+ onChange: (texts: string[]) => void;+}++// the public reply's texts, one picked for each comment; at least one field always stays+export default function RulePublicReplies({ texts, onChange }: RulePublicRepliesProps) {+ const update = (index: number, value: string) => onChange(texts.map((text, at) => (at === index ? value : text)));+ const remove = (index: number) => onChange(texts.filter((_, at) => at !== index));+ return (+ <div className="flex flex-col gap-2" role="group" aria-label="Public reply texts">+ {texts.map((text, index) => {+ const problem = text.trim() ? publicReplyTextProblem(text.trim()) : null;+ const id = `rule-public-${index}`;+ return (+ <div key={index} className="flex flex-col gap-1">+ <div className="flex items-start gap-1.5">+ <Textarea+ id={id}+ rows={2}+ maxLength={MAX_PUBLIC_REPLY_CHARS}+ value={text}+ onChange={e => update(index, e.target.value)}+ aria-label={texts.length > 1 ? `Public reply ${index + 1} of ${texts.length}` : 'Public reply'}+ aria-invalid={problem ? true : undefined}+ aria-describedby={problem ? `${id}-problem` : undefined}+ placeholder="Thanks for your comment."+ />+ {texts.length > 1 && <RowAction label={`Remove public reply ${index + 1}`} onClick={() => remove(index)}><X /></RowAction>}+ </div>+ <p id={`${id}-problem`} className={cn('text-caption', problem ? 'text-danger' : 'text-ink-faint')}>+ {problem ?? `${text.trim().length} of ${MAX_PUBLIC_REPLY_CHARS} characters`}+ </p>+ </div>+ );+ })}+ {texts.length < MAX_PUBLIC_REPLY_TEXTS && (+ <Button type="button" size="sm" variant="ghost" className="self-start" onClick={() => onChange([...texts, ''])}>+ <Plus data-icon="inline-start" />Add another wording+ </Button>+ )}+ </div>+ );+}diff --git a/frontend/src/features/automations/automationData.ts b/frontend/src/features/automations/automationData.tsindex 089a288..8fd043a 100644--- a/frontend/src/features/automations/automationData.ts+++ b/frontend/src/features/automations/automationData.ts@@ -1,6 +1,6 @@import type {- AutomationAccountState, AutomationActivityItem, AutomationCommentStatus, AutomationMatchMode, AutomationRule, AutomationRuleRequest,- AutomationStats,+ AutomationAccountState, AutomationActivityItem, AutomationCommentStatus, AutomationMatchMode, AutomationPublicReplyState, AutomationPublicReplyStatus,+ AutomationRule, AutomationRuleRequest, AutomationStats,} from '../../../../shared/types/automation.ts';export type BadgeTone = 'success' | 'destructive' | 'warning' | 'info' | 'secondary';@@ -24,6 +24,19 @@ export const STATUS_DISPLAY: Record<AutomationCommentStatus, StatusDisplay> = {expired: { label: 'Expired', tone: 'secondary' },};+// a public reply is accepted only with the id Instagram gave it, so it is shown as posted+export const PUBLIC_STATUS_DISPLAY: Record<AutomationPublicReplyStatus, StatusDisplay> = {+ queued: { label: 'Waiting', tone: 'warning' },+ processing: { label: 'Posting', tone: 'info' },+ retry_wait: { label: 'Trying again', tone: 'warning' },+ sending: { label: 'Posting', tone: 'info' },+ accepted: { label: 'Posted', tone: 'success' },+ failed: { label: 'Failed', tone: 'destructive' },+ needs_review: { label: 'Checking', 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 }> = {@@ -49,17 +62,27 @@ export const STATS_PERIODS: Record<StatsPeriod, { label: string; ms: number }> =export const MAX_MESSAGE_BYTES = 1000;const MAX_KEYWORDS = 10;const MAX_HOURLY_LIMIT = 750;+// the Worker's bounds for public replies: a few short texts, few hashtags and one link at most+export const MAX_PUBLIC_REPLY_TEXTS = 5;+export const MAX_PUBLIC_REPLY_CHARS = 300;+const MAX_PUBLIC_HASHTAGS = 4;+const MAX_PUBLIC_LINKS = 1;+const HASHTAG = /(^|\s)#[\p{L}\p{N}_]+/gu;+const LINK = /\bhttps?:\/\/\S+|\bwww\.\S+/gi;// Instagram allows a message for 24 hours after the person's reply, so a follow-up can be retried only inside itconst FOLLOWUP_WINDOW_MS = 24 * HOUR_MS;// where a followers-only rule starts; the owner edits both before savingexport const DEFAULT_FOLLOW_PROMPT = 'Thanks for your comment. Follow this account, then reply to this message and the link is on its way.';export const DEFAULT_NOT_FOLLOWING = 'It looks like you do not follow this account yet. Follow it, then reply here again and the link is on its way.';+// where a public reply starts; it says nothing about the private reply, which can fail on its own+export const DEFAULT_PUBLIC_REPLY = 'Thanks for your comment.';export interface AutomationSummary {received: number;matched: number;accepted: number;+ publicPosted: number;waiting: number;attention: number;rateLimited: number;@@ -76,8 +99,11 @@ export interface RuleForm {caseSensitive: boolean;scope: RuleScope;mediaIds: string[];+ privateReplyEnabled: boolean;replyText: string;linkUrl: string;+ publicReplyEnabled: boolean;+ publicReplyTexts: string[];hourlyLimit: string;enabled: boolean;requireFollow: boolean;@@ -94,6 +120,7 @@ type ActivityStatus = Pick<AutomationActivityItem, 'status' | 'statusReason'> &// a followers-only reply that Instagram accepted shows where the wait for the person stands, not just the first messageexport function statusDisplay(item: ActivityStatus): StatusDisplay {if (item.status === 'queued' && item.statusReason === 'paused') return { label: 'Held', tone: 'warning' };+ if (item.status === 'skipped' && item.statusReason === 'private_reply_off') return { label: 'Off', tone: 'secondary' };if (item.status !== 'accepted' || !item.gateStatus) return STATUS_DISPLAY[item.status];if (item.gateStatus === 'completed') return { label: 'Link sent', tone: 'success' };if (item.gateStatus === 'closed') return { label: 'Not following', tone: 'secondary' };@@ -112,18 +139,26 @@ export function gateDetail(item: Pick<AutomationActivityItem, 'status' | 'gateStreturn 'Asked them to follow and reply. When they reply, Instagram says whether they follow, and the link goes out if they do.';}-function count(stats: AutomationStats, statuses: AutomationCommentStatus[]): number {- return statuses.reduce((total, status) => total + (stats.comments[status] ?? 0), 0);+export function publicStatusDisplay(reply: Pick<AutomationPublicReplyState, 'status' | 'statusReason'>): StatusDisplay {+ if (reply.status === 'queued' && reply.statusReason === 'paused') return { label: 'Held', tone: 'warning' };+ return PUBLIC_STATUS_DISPLAY[reply.status];+}++function count(counts: Partial<Record<string, number>>, statuses: string[]): number {+ return statuses.reduce((total, status) => total + (counts[status] ?? 0), 0);}+// waiting and attention count both replies, so a failed public reply is not hidden by a private one that went outexport function summarizeStats(stats: AutomationStats): AutomationSummary {const received = Object.values(stats.comments).reduce((total, value) => total + (value ?? 0), 0);+ const publicReplies = stats.publicReplies ?? {};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!),+ publicPosted: publicReplies.accepted ?? 0,+ waiting: count(stats.comments, ACTIVITY_FILTERS.waiting.statuses!) + count(publicReplies, ACTIVITY_FILTERS.waiting.statuses!),+ attention: count(stats.comments, ACTIVITY_FILTERS.attention.statuses!) + count(publicReplies, ACTIVITY_FILTERS.attention.statuses!),rateLimited: stats.attempts.rate_limited ?? 0,};}@@ -142,14 +177,38 @@ export function matchModeLabel(rule: Pick<AutomationRule, 'matchMode' | 'caseSenconst RETRYABLE = ['failed', 'needs_review', 'skipped'];-// failed, skipped and review items can be tried again until Instagram's 7 days run out; on an accepted followers-only+// failed, skipped and review items can be tried again until Instagram's 7 days run out, except a private reply the rule+// does not send; on an accepted followers-only// reply, a failed follow-up can be tried again inside the 24 hours after the person's answer-export function canRetry(item: Pick<AutomationActivityItem, 'status' | 'expiresAt'> & Partial<Pick<AutomationActivityItem, 'followup'>>, now: number): boolean {+export function canRetry(+ item: Pick<AutomationActivityItem, 'status' | 'expiresAt'> & Partial<Pick<AutomationActivityItem, 'followup' | 'statusReason'>>,+ now: number,+): boolean {+ if (item.status === 'skipped' && item.statusReason === 'private_reply_off') return false;if (RETRYABLE.includes(item.status)) return Date.parse(item.expiresAt) > now;const followup = item.followup;return item.status === 'accepted' && !!followup && RETRYABLE.includes(followup.status) && Date.parse(followup.createdAt) + FOLLOWUP_WINDOW_MS > now;}+// a failed, skipped or unconfirmed public reply can be posted again until 7 days after the comment, whatever the+// private reply did+export function canRetryPublic(item: Pick<AutomationActivityItem, 'publicReply' | 'expiresAt'>, now: number): boolean {+ return !!item.publicReply && RETRYABLE.includes(item.publicReply.status) && Date.parse(item.expiresAt) > now;+}++// what is wrong with one public reply text, or null; the Worker checks the same+export function publicReplyTextProblem(text: string): string | null {+ if (text.length > MAX_PUBLIC_REPLY_CHARS) return `A public reply can be at most ${MAX_PUBLIC_REPLY_CHARS} characters`;+ if ((text.match(HASHTAG) ?? []).length > MAX_PUBLIC_HASHTAGS) return `A public reply can have at most ${MAX_PUBLIC_HASHTAGS} hashtags`;+ if ((text.match(LINK) ?? []).length > MAX_PUBLIC_LINKS) return `A public reply can have at most ${MAX_PUBLIC_LINKS} link; put the rest in the private reply`;+ return null;+}++// the public texts as they will be saved: trimmed, without blanks or repeats+export function publicReplyTexts(texts: string[]): string[] {+ return [...new Set(texts.map(text => text.trim()).filter(Boolean))];+}+// comma or line separated, trimmed, without blanks or repeatsexport function parseKeywords(text: string, caseSensitive: boolean): string[] {const seen = new Set<string>();@@ -175,7 +234,7 @@ export function messageBytes(message: string): number {export function emptyRuleForm(accountId: string): RuleForm {return {accountId, name: '', keywordsText: '', matchMode: 'contains', caseSensitive: false, scope: 'all', mediaIds: [],- replyText: '', linkUrl: '', hourlyLimit: '', enabled: true,+ privateReplyEnabled: true, replyText: '', linkUrl: '', publicReplyEnabled: false, publicReplyTexts: [DEFAULT_PUBLIC_REPLY], hourlyLimit: '', enabled: true,requireFollow: false, followPromptText: DEFAULT_FOLLOW_PROMPT, notFollowingText: DEFAULT_NOT_FOLLOWING,};}@@ -189,8 +248,11 @@ export function ruleToForm(rule: AutomationRule): RuleForm {caseSensitive: rule.caseSensitive,scope: rule.mediaIds.length > 0 ? 'selected' : 'all',mediaIds: rule.mediaIds,+ privateReplyEnabled: rule.privateReplyEnabled,replyText: rule.replyText,linkUrl: rule.linkUrl ?? '',+ publicReplyEnabled: rule.publicReplyEnabled,+ publicReplyTexts: rule.publicReplyTexts.length > 0 ? rule.publicReplyTexts : [DEFAULT_PUBLIC_REPLY],hourlyLimit: rule.hourlyLimit === null ? '' : String(rule.hourlyLimit),enabled: rule.enabled,requireFollow: rule.requireFollow,@@ -208,8 +270,12 @@ export function formToRequest(form: RuleForm): AutomationRuleRequest {matchMode: form.matchMode,caseSensitive: form.caseSensitive,mediaIds: form.scope === 'selected' ? form.mediaIds : [],+ privateReplyEnabled: form.privateReplyEnabled,replyText: form.replyText.trim(),linkUrl: form.linkUrl.trim() || null,+ publicReplyEnabled: form.publicReplyEnabled,+ // texts kept while the public reply is off come back when it is turned on again+ publicReplyTexts: publicReplyTexts(form.publicReplyTexts),enabled: form.enabled,hourlyLimit: form.hourlyLimit.trim() ? Number(form.hourlyLimit) : null,requireFollow: form.requireFollow,@@ -241,7 +307,8 @@ export function ruleFormProblem(form: RuleForm): string | null {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';+ if (!form.privateReplyEnabled && !form.publicReplyEnabled) return 'Turn on the private reply, the public reply, or both';+ if (form.privateReplyEnabled && !form.replyText.trim()) return 'Write the reply to send';const link = linkProblem(form.linkUrl);if (link) return link;const limit = form.hourlyLimit.trim();@@ -249,7 +316,17 @@ export function ruleFormProblem(form: RuleForm): string | null {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}`;+ if (form.privateReplyEnabled && bytes > MAX_MESSAGE_BYTES) return `The reply with its link is ${bytes} bytes; Instagram accepts at most ${MAX_MESSAGE_BYTES}`;+ if (form.publicReplyEnabled) {+ const texts = publicReplyTexts(form.publicReplyTexts);+ if (texts.length === 0) return 'Write at least one public reply';+ if (texts.length > MAX_PUBLIC_REPLY_TEXTS) return `A rule can have at most ${MAX_PUBLIC_REPLY_TEXTS} public replies`;+ for (const text of texts) {+ const problem = publicReplyTextProblem(text);+ if (problem) return problem;+ }+ }+ if (form.requireFollow && !form.privateReplyEnabled) return 'Sending the link only to followers needs the private reply. Turn it on, or turn off the followers-only option';if (form.requireFollow) {if (!form.followPromptText.trim()) return 'Write the message that asks people to follow you and reply';if (!form.notFollowingText.trim()) return 'Write the reminder for people who do not follow you yet';@@ -280,6 +357,16 @@ export function accountStatus(account: AutomationAccountState, now: number, needif (account.limitedUntil && Date.parse(account.limitedUntil) > now) {return { label: 'At its hourly limit', tone: 'warning', detail: 'This account sent its hourly number of replies. The rest go out as the hour frees up, within Instagram\'s 7 days.' };}+ if (account.publicCooldownUntil && Date.parse(account.publicCooldownUntil) > now) {+ return {+ label: 'Public replies cooling down',+ tone: 'warning',+ detail: account.publicCooldownReason ?? 'Instagram is limiting comments from this account for now. Private replies still go out.',+ };+ }+ if (account.publicLimitedUntil && Date.parse(account.publicLimitedUntil) > now) {+ return { label: 'Public replies at their hourly limit', tone: 'warning', detail: 'This account posted its hourly number of public replies. The rest go out as the hour frees up.' };+ }if (!account.subscribedAt) return { label: 'Not receiving comments', tone: 'warning', detail: 'Turn on comment events so Instagram sends this account\'s comments to Twiligent.' };if (needsMessages && !account.messagesSubscribed) {return {diff --git a/frontend/src/features/automations/useAutomationActivity.ts b/frontend/src/features/automations/useAutomationActivity.tsindex 2d657c3..4b4b0ce 100644--- a/frontend/src/features/automations/useAutomationActivity.ts+++ b/frontend/src/features/automations/useAutomationActivity.ts@@ -7,6 +7,8 @@ import type { AutomationActivityItem } from '@shared/types/automation.ts';const PAGE_SIZE = 50;+export type RetryAction = 'private' | 'public';+export interface ActivityFilters {filter: ActivityFilter;period: StatsPeriod;@@ -33,7 +35,7 @@ export function useAutomationActivity() {const [summary, setSummary] = useState<AutomationSummary | null>(null);const [loading, setLoading] = useState(true);const [loadingMore, setLoadingMore] = useState(false);- const [retryingId, setRetryingId] = useState<string | null>(null);+ const [retrying, setRetrying] = useState<{ id: string; action: RetryAction } | null>(null);// the time the list was read, so which items can be retried is decided against a fixed moment during renderconst [checkedAt, setCheckedAt] = useState(() => Date.now());// each load for new filters gets a number; an answer for an older one arrives too late and is dropped@@ -81,24 +83,28 @@ export function useAutomationActivity() {}}, [filters, nextBefore, showToast]);- const retry = useCallback(async (item: AutomationActivityItem) => {- setRetryingId(item.id);+ // the private reply (or its follow-up) and the public reply are retried apart; one never resends the other+ const retryAction = useCallback(async (item: AutomationActivityItem, action: RetryAction) => {+ setRetrying({ id: item.id, action });try {- const { item: queued } = await api.retryAutomationActivity(item.id);+ const { item: queued } = action === 'public' ? await api.retryAutomationPublicReply(item.id) : await api.retryAutomationActivity(item.id);setItems(current => current.map(entry => (entry.id === queued.id ? queued : entry)));- showToast('Reply queued to send again');+ showToast(action === 'public' ? 'Public reply queued to post again' : 'Reply queued to send again');} catch (err) {- showToast(`Couldn't retry the reply. ${(err as Error).message}`, 'error');+ showToast(`Couldn't retry the ${action === 'public' ? 'public reply' : 'reply'}. ${(err as Error).message}`, 'error');} finally {- setRetryingId(null);+ setRetrying(null);}}, [showToast]);+ const retry = useCallback((item: AutomationActivityItem) => retryAction(item, 'private'), [retryAction]);+ const retryPublic = useCallback((item: AutomationActivityItem) => retryAction(item, 'public'), [retryAction]);+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 };+ return { filters, setFilter, items, nextBefore, summary, loading, loadingMore, retrying, checkedAt, load, loadMore, retry, retryPublic };}export type AutomationActivityState = ReturnType<typeof useAutomationActivity>;diff --git a/frontend/src/features/automations/useRuleForm.ts b/frontend/src/features/automations/useRuleForm.tsindex 0c8e54b..71f68bc 100644--- a/frontend/src/features/automations/useRuleForm.ts+++ b/frontend/src/features/automations/useRuleForm.ts@@ -72,7 +72,7 @@ export function useRuleForm({ saveRule }: RuleFormDeps) {// the test checks the match; which posts the rule covers applies to real comments onlysetTestResult(await api.testAutomationRule({keywords: request.keywords, matchMode: request.matchMode, caseSensitive: request.caseSensitive,- replyText: request.replyText || TEST_REPLY_PLACEHOLDER, linkUrl: request.linkUrl, comment: sampleComment,+ privateReplyEnabled: request.privateReplyEnabled, replyText: request.replyText || TEST_REPLY_PLACEHOLDER, linkUrl: request.linkUrl, comment: sampleComment,requireFollow: request.requireFollow, followPromptText: request.followPromptText,}));} catch (err) {diff --git a/frontend/src/services/api.ts b/frontend/src/services/api.tsindex df8fbf4..e591aff 100644--- a/frontend/src/services/api.ts+++ b/frontend/src/services/api.ts@@ -197,6 +197,7 @@ export const api = {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' }),+ retryAutomationPublicReply: (id: string) => request<AutomationActivityItemResponse>(`/automations/activity/${id}/public-reply/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.tsindex a45d40e..c231b2e 100644--- a/frontend/tests/features/automations/automationData.test.ts+++ b/frontend/tests/features/automations/automationData.test.ts@@ -1,9 +1,9 @@import { test } from 'node:test';import assert from 'node:assert/strict';import {- ACTIVITY_FILTERS, DEFAULT_FOLLOW_PROMPT, DEFAULT_NOT_FOLLOWING, MAX_MESSAGE_BYTES, accountStatus, canRetry, composeReply, emptyRuleForm,- formToRequest, gateDetail, matchModeLabel, messageBytes, needsMessageEvents, parseKeywords, periodStart, ruleFormProblem, ruleScopeLabel,- ruleToForm, statusDisplay, summarizeStats,+ ACTIVITY_FILTERS, DEFAULT_FOLLOW_PROMPT, DEFAULT_NOT_FOLLOWING, DEFAULT_PUBLIC_REPLY, MAX_MESSAGE_BYTES, accountStatus, canRetry, canRetryPublic,+ composeReply, emptyRuleForm, formToRequest, gateDetail, matchModeLabel, messageBytes, needsMessageEvents, parseKeywords, periodStart,+ publicReplyTexts, publicStatusDisplay, 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';@@ -16,7 +16,7 @@ function form(overrides: Partial<RuleForm> = {}): RuleForm {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, requireFollow: true, followPromptText: 'Follow and reply',+ privateReplyEnabled: true, replyText: 'Here it is', linkUrl: 'https://example.com', publicReplyEnabled: true, publicReplyTexts: ['Thanks', 'Thank you'], enabled: false, hourlyLimit: 30, requireFollow: true, followPromptText: 'Follow and reply',notFollowingText: 'Follow first', createdAt: 'c', updatedAt: 'u',};@@ -48,9 +48,12 @@ test('the status filters cover every status exactly once, apart from All', () =>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 },+ publicReplies: { accepted: 4, failed: 1, queued: 2 },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 });+ }), { received: 14, matched: 9, accepted: 3, publicPosted: 4, waiting: 4, attention: 4, rateLimited: 4 });+ assert.deepEqual(summarizeStats({ comments: {}, publicReplies: {}, attempts: {} }), {+ received: 0, matched: 0, accepted: 0, publicPosted: 0, waiting: 0, attention: 0, rateLimited: 0,+ });});test('a period starts the right length of time before now', () => {@@ -98,12 +101,16 @@ 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,- requireFollow: true, followPromptText: 'Follow and reply', notFollowingText: 'Follow first',+ privateReplyEnabled: true, replyText: 'Here it is', linkUrl: 'https://example.com', publicReplyEnabled: true, publicReplyTexts: ['Thanks', 'Thank you'],+ hourlyLimit: '30', enabled: false, requireFollow: true, followPromptText: 'Follow and reply', notFollowingText: 'Follow first',});- const { accountId, name, keywords, matchMode, caseSensitive, mediaIds, replyText, linkUrl, enabled, hourlyLimit, requireFollow, followPromptText, notFollowingText } = rule;+ const {+ accountId, name, keywords, matchMode, caseSensitive, mediaIds, privateReplyEnabled, replyText, linkUrl, publicReplyEnabled, publicReplyTexts: texts,+ enabled, hourlyLimit, requireFollow, followPromptText, notFollowingText,+ } = rule;assert.deepEqual(formToRequest(editing), {- accountId, name, keywords, matchMode, caseSensitive, mediaIds, replyText, linkUrl, enabled, hourlyLimit, requireFollow, followPromptText, notFollowingText,+ accountId, name, keywords, matchMode, caseSensitive, mediaIds, privateReplyEnabled, replyText, linkUrl, publicReplyEnabled, publicReplyTexts: texts,+ enabled, hourlyLimit, requireFollow, followPromptText, notFollowingText,});});@@ -145,7 +152,7 @@ test('the form names the first thing to fix, in the order of the fields', () =>test('an account shows held, paused, cooling down, at its limit, not receiving, follow checks off or receiving, in that order', () => {const base: AutomationAccountState = {accountId: 'ig1', username: 'me', profilePictureUrl: '', paused: false, cooldownUntil: null, cooldownReason: null, subscribedAt: 'x',- limitedUntil: null, messagesSubscribed: false,+ limitedUntil: null, messagesSubscribed: false, publicCooldownUntil: null, publicCooldownReason: null, publicLimitedUntil: null,};assert.equal(accountStatus({ ...base, paused: true, cooldownReason: 'Reconnect it' }, NOW).label, 'Held');assert.equal(accountStatus({ ...base, paused: true }, NOW).label, 'Paused');@@ -155,6 +162,38 @@ test('an account shows held, paused, cooling down, at its limit, not receiving,assert.equal(accountStatus({ ...base, subscribedAt: null }, NOW).label, 'Not receiving comments');assert.equal(accountStatus(base, NOW, true).label, 'Follow checks off');assert.equal(accountStatus({ ...base, messagesSubscribed: true }, NOW, true).label, 'Receiving comments');+ assert.equal(accountStatus({ ...base, publicCooldownUntil: new Date(NOW + 1000).toISOString() }, NOW).label, 'Public replies cooling down');+ assert.equal(accountStatus({ ...base, publicLimitedUntil: new Date(NOW + 1000).toISOString() }, NOW).label, 'Public replies at their hourly limit');+});++test('a rule answers in private, in public or both, and each one it uses must be complete', () => {+ assert.deepEqual([emptyRuleForm('ig1').publicReplyEnabled, emptyRuleForm('ig1').publicReplyTexts], [false, [DEFAULT_PUBLIC_REPLY]]);+ assert.equal(ruleFormProblem(form({ privateReplyEnabled: false, publicReplyEnabled: false })), 'Turn on the private reply, the public reply, or both');+ assert.equal(ruleFormProblem(form({ privateReplyEnabled: false, replyText: '', publicReplyEnabled: true })), null);+ assert.equal(ruleFormProblem(form({ publicReplyEnabled: true, publicReplyTexts: [' ', ''] })), 'Write at least one public reply');+ assert.equal(ruleFormProblem(form({ publicReplyEnabled: true, publicReplyTexts: ['x'.repeat(301)] })), 'A public reply can be at most 300 characters');+ assert.equal(ruleFormProblem(form({ publicReplyEnabled: true, publicReplyTexts: ['#a #b #c #d #e'] })), 'A public reply can have at most 4 hashtags');+ assert.match(ruleFormProblem(form({ privateReplyEnabled: false, publicReplyEnabled: true, requireFollow: true }))!, /needs the private reply/);+ assert.equal(ruleFormProblem(form({ privateReplyEnabled: false, replyText: 'é'.repeat(600), publicReplyEnabled: true })), null);+ assert.deepEqual(publicReplyTexts([' Thanks ', '', 'Thanks', 'Thank you']), ['Thanks', 'Thank you']);+ assert.deepEqual(formToRequest(form({ publicReplyTexts: ['Thanks', ' '] })).publicReplyTexts, ['Thanks']);+});++test('a public reply shows as posted only once Instagram gave it an id, and is retried apart from the private reply', () => {+ assert.deepEqual(publicStatusDisplay({ status: 'accepted', statusReason: null }), { label: 'Posted', tone: 'success' });+ assert.deepEqual(publicStatusDisplay({ status: 'needs_review', statusReason: 'no_answer' }), { label: 'Checking', tone: 'warning' });+ assert.deepEqual(publicStatusDisplay({ status: 'queued', statusReason: 'paused' }), { label: 'Held', tone: 'warning' });+ assert.deepEqual(statusDisplay({ status: 'skipped', statusReason: 'private_reply_off' }), { label: 'Off', tone: 'secondary' });+ const future = new Date(NOW + 1000).toISOString();+ const reply = (status: 'failed' | 'accepted') => ({+ status, statusReason: null, errorMessage: null, text: 'Thanks', attempts: 1, replyId: null, nextAttemptAt: null, acceptedAt: null,+ });+ assert.equal(canRetryPublic({ publicReply: reply('failed'), expiresAt: future }, NOW), true);+ assert.equal(canRetryPublic({ publicReply: reply('accepted'), expiresAt: future }, NOW), false);+ assert.equal(canRetryPublic({ publicReply: reply('failed'), expiresAt: new Date(NOW).toISOString() }, NOW), false);+ assert.equal(canRetryPublic({ publicReply: null, expiresAt: future }, NOW), false);+ assert.equal(canRetry({ status: 'skipped', statusReason: 'private_reply_off', expiresAt: future }, NOW), false);+ assert.equal(canRetry({ status: 'skipped', statusReason: 'recipient_limit', expiresAt: future }, NOW), true);});test('an account needs message events only while one of its followers-only rules is on', () => {