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(automation): dispatch replies every minute, reconcile, follow gate and any-comment rules
spacesdrive6a8713cda5f9
diff --git a/backend/container.ts b/backend/container.tsindex 7fc229b..0977bae 100644--- a/backend/container.ts+++ b/backend/container.ts@@ -8,6 +8,7 @@ import { createAuditRepository } from './repositories/auditRepository.ts';import { createAutomationRuleRepository } from './repositories/automationRuleRepository.ts';import { createAutomationCommentRepository } from './repositories/automationCommentRepository.ts';import { createAutomationAccountRepository } from './repositories/automationAccountRepository.ts';+import { createAutomationFollowupRepository } from './repositories/automationFollowupRepository.ts';import { createAccountService } from './services/accountService.ts';import { createYouTubeAnalyticsService } from './services/youtubeAnalyticsService.ts';import { createInstagramAnalyticsService } from './services/instagramAnalyticsService.ts';@@ -24,6 +25,8 @@ import { createAuthEmailService } from './services/authEmailService.ts';import { createAutomationService } from './services/automationService.ts';import { createAutomationWebhookService } from './services/automationWebhookService.ts';import { createAutomationProcessor } from './services/automationProcessor.ts';+import { createAutomationFollowupProcessor } from './services/automationFollowupProcessor.ts';+import { createAutomationReconciler } from './services/automationReconciler.ts';import { createRetentionService } from './services/retentionService.ts';import type { AccountService } from './services/accountService.ts';import type { YouTubeAnalyticsService } from './services/youtubeAnalyticsService.ts';@@ -41,6 +44,8 @@ import type { AuthEmailService } from './services/authEmailService.ts';import type { AutomationService } from './services/automationService.ts';import type { AutomationWebhookService } from './services/automationWebhookService.ts';import type { AutomationProcessor } from './services/automationProcessor.ts';+import type { AutomationFollowupProcessor } from './services/automationFollowupProcessor.ts';+import type { AutomationReconciler } from './services/automationReconciler.ts';import type { RetentionService } from './services/retentionService.ts';import type { AppConfig } from './lib/config.ts';import type { RequestContext } from './types/context.ts';@@ -70,6 +75,8 @@ export interface Services {automations: AutomationService;automationWebhook: AutomationWebhookService;automationProcessor: AutomationProcessor;+ automationFollowups: AutomationFollowupProcessor;+ automationReconciler: AutomationReconciler;retention: RetentionService;}@@ -84,6 +91,7 @@ export function createServices(clients: Clients, config: AppConfig, context: Reqconst rules = createAutomationRuleRepository(clients.supabase);const comments = createAutomationCommentRepository(clients.supabase);const automationAccounts = createAutomationAccountRepository(clients.supabase);+ const followups = createAutomationFollowupRepository(clients.supabase);const { automation } = config;const scheduledPublisher = createScheduledPublisher({ accounts, posts, context });return {@@ -100,9 +108,11 @@ export function createServices(clients: Clients, config: AppConfig, context: Reqsettings: createSettingsService({ settings, config }),instagramConnect: createInstagramConnectService({ accounts, audit, config, context }),authEmail: createAuthEmailService({ quota: createEmailQuotaRepository(clients.rateLimitRedis), config, context }),- automations: createAutomationService({ accounts, rules, comments, automationAccounts, audit, automation, context }),- automationWebhook: createAutomationWebhookService({ rules, comments, automation, context }),+ automations: createAutomationService({ accounts, rules, comments, followups, automationAccounts, audit, automation, context }),+ automationWebhook: createAutomationWebhookService({ rules, comments, followups, automation, context }),automationProcessor: createAutomationProcessor({ comments, automation, context }),+ automationFollowups: createAutomationFollowupProcessor({ followups, automation, context }),+ automationReconciler: createAutomationReconciler({ comments, context }),retention: createRetentionService({ comments, audit, context }),};}diff --git a/backend/controllers/automationController.ts b/backend/controllers/automationController.tsindex aac09e3..15f5d28 100644--- a/backend/controllers/automationController.ts+++ b/backend/controllers/automationController.ts@@ -51,10 +51,13 @@ export const getAutomationStats = controller.createHandlers(queryParams(parseStareturn c.json({ success: true, ...period } satisfies AutomationStatsResponse);});-// the item goes back in the queue and this request starts sending it, instead of waiting for the next sweep+// the item goes back in the queue and this request starts sending it, instead of waiting for the next dispatchexport const retryAutomationActivity = controller.createHandlers(async c => {- const item = await servicesFor(c).automations.retry(c.get('userId'), pathParam(c, 'id'));- inBackground(c, 'automation retry', services => services.automationProcessor.run({ ids: [item.id], subrequests: FREE_PLAN_SUBREQUESTS - REQUEST_SUBREQUESTS }));+ const { item, followupId } = await servicesFor(c).automations.retry(c.get('userId'), pathParam(c, 'id'));+ const subrequests = FREE_PLAN_SUBREQUESTS - REQUEST_SUBREQUESTS;+ inBackground(c, 'automation retry', services => (followupId+ ? services.automationFollowups.run({ ids: [followupId], subrequests })+ : services.automationProcessor.run({ ids: [item.id], subrequests })));return c.json({ success: true, item } satisfies AutomationActivityItemResponse);});diff --git a/backend/controllers/instagramWebhookController.ts b/backend/controllers/instagramWebhookController.tsindex 3fd9ca9..2ccc21c 100644--- a/backend/controllers/instagramWebhookController.ts+++ b/backend/controllers/instagramWebhookController.ts@@ -10,12 +10,17 @@ export const verifyInstagramWebhook = controller.createHandlers(queryParams(parsreturn c.text(challenge);});-// called by Meta, not a browser: verifyMetaWebhook has already checked the signature. The comments are stored before-// the 200, so Meta keeps retrying for 36 hours if storing fails; the replies go out after the response+// called by Meta, not a browser: verifyMetaWebhook has already checked the signature. Comments and answers are stored+// before the 200, so Meta keeps retrying for 36 hours if storing fails; the messages go out after the responseexport const receiveInstagramWebhook = controller.createHandlers(jsonBody(body => parseInstagramWebhook(body)), async c => {- const { queuedIds, subrequests } = await servicesFor(c).automationWebhook.ingest(c.req.valid('json'));- // the replies share this invocation's subrequests with the intake and the middleware before it+ const { queuedIds, followupIds, subrequests } = await servicesFor(c).automationWebhook.ingest(c.req.valid('json'));+ // the sends share this invocation's subrequests with the intake and the middleware before itconst left = FREE_PLAN_SUBREQUESTS - REQUEST_SUBREQUESTS - subrequests;- if (queuedIds.length > 0) inBackground(c, 'automation replies', services => services.automationProcessor.run({ ids: queuedIds, subrequests: left }));+ if (queuedIds.length > 0 || followupIds.length > 0) {+ inBackground(c, 'automation replies', async services => {+ const replies = queuedIds.length > 0 ? await services.automationProcessor.run({ ids: queuedIds, subrequests: left }) : null;+ if (followupIds.length > 0) await services.automationFollowups.run({ ids: followupIds, subrequests: left - (replies?.subrequests ?? 0) });+ });+ }return c.json({ success: true });});diff --git a/backend/jobs/scheduled.ts b/backend/jobs/scheduled.tsindex e84ea33..7e4ccca 100644--- a/backend/jobs/scheduled.ts+++ b/backend/jobs/scheduled.ts@@ -9,18 +9,17 @@ import type { Env } from '../types/env.ts';import type { RequestContext } from '../types/context.ts';// must match the crons in wrangler.toml character for character+export const EVERY_MINUTE_CRON = '* * * * *';export const EVERY_FIVE_MINUTES_CRON = '*/5 * * * *';export const DAILY_CRON = '0 0 * * *';-// the Cloudflare account's five cron triggers are all in use, so one trigger carries two jobs: due posts on the-// quarter hour, as before, and the comment reply queue on every run+// due posts are published on the quarter hour, as before; the other five minute runs reconcile the reply queueconst PUBLISH_EVERY_MINUTES = 15;-// a run that published has spent part of its 50 subrequests, so the replies wait five minutes for the next run;-// one that had nothing to publish spent two (the due and stale lists) and sweeps a few-const SWEEP_AFTER_QUIET_PUBLISH = 3;-const QUIET_PUBLISH_SUBREQUESTS = 2;-// a sweep stops starting sends well before the 14 minute cron deadline-const SWEEP_TIME_MS = 10 * 60 * 1000;+// a dispatch stops starting sends well before the next minute's run, so runs rarely overlap; when they do, the claim's+// row locks keep them apart+const DISPATCH_TIME_MS = 50 * 1000;+// the daily run refreshes tokens first; retention gets this many batches of the run's subrequests+const RETENTION_BATCHES = 20;// a cron run gets its own id and a deadline under the Worker's 15 minute limit for scheduled eventsconst CRON_DEADLINE_MS = 14 * 60 * 1000;@@ -30,18 +29,25 @@ function cronContext(cron: string): RequestContext {return { requestId, signal: AbortSignal.timeout(CRON_DEADLINE_MS), log: createLogger({ requestId, cron }) };}-export type CronPlan = 'sweep' | 'publish_then_sweep' | 'daily' | 'none';+// dispatch sends due replies and follow-ups; publish sends due posts; reconcile expires, checks lost replies and reports+// the queue's health; daily refreshes tokens and removes old data+export type CronPlan = 'dispatch' | 'publish' | 'reconcile' | 'daily' | 'none';// which work a trigger firing at scheduledTime carriesexport function cronPlan(cron: string, scheduledTime: number): CronPlan {+ if (cron === EVERY_MINUTE_CRON) return 'dispatch';if (cron === DAILY_CRON) return 'daily';if (cron !== EVERY_FIVE_MINUTES_CRON) return 'none';- return new Date(scheduledTime).getUTCMinutes() % PUBLISH_EVERY_MINUTES === 0 ? 'publish_then_sweep' : 'sweep';+ return new Date(scheduledTime).getUTCMinutes() % PUBLISH_EVERY_MINUTES === 0 ? 'publish' : 'reconcile';}-async function sweepReplies(services: Services, context: RequestContext, limit?: number, spent = 0): Promise<void> {- const run = await services.automationProcessor.run({ limit, subrequests: FREE_PLAN_SUBREQUESTS - spent, timeBudgetMs: SWEEP_TIME_MS });- if (run.claimed > 0) context.log.info('automation sweep', { claimed: run.claimed, ...run.outcomes });+// private replies first, then follow-ups with what is left of the run's 50 subrequests+async function dispatch(services: Services, context: RequestContext): Promise<void> {+ const replies = await services.automationProcessor.run({ subrequests: FREE_PLAN_SUBREQUESTS, timeBudgetMs: DISPATCH_TIME_MS });+ const followups = await services.automationFollowups.run({ subrequests: FREE_PLAN_SUBREQUESTS - replies.subrequests, timeBudgetMs: DISPATCH_TIME_MS });+ if (replies.claimed > 0 || followups.claimed > 0) {+ context.log.info('automation dispatch', { replies: { claimed: replies.claimed, ...replies.outcomes }, followups: { claimed: followups.claimed, ...followups.outcomes } });+ }}// the cron entry point: the same services the API uses, built from the Worker env instead of a request@@ -49,18 +55,22 @@ export async function runScheduledJob(cron: string, env: Env, scheduledTime = Daconst context = cronContext(cron);const clients = { supabase: getSupabase(env), redis: getRedis(env), rateLimitRedis: getRateLimitRedis(env) };const services = createServices(clients, readConfig(env), context);+ const started = Date.now();const plan = cronPlan(cron, scheduledTime);- if (plan === 'sweep') {- await sweepReplies(services, context);- } else if (plan === 'publish_then_sweep') {+ if (plan === 'dispatch') {+ await dispatch(services, context);+ } else if (plan === 'publish') {const run = await services.scheduledPublisher.publishDue();context.log.info('scheduled publish run', { processed: run.processed, failed: run.errors.length });- if (run.processed === 0) await sweepReplies(services, context, SWEEP_AFTER_QUIET_PUBLISH, QUIET_PUBLISH_SUBREQUESTS);+ } else if (plan === 'reconcile') {+ await services.automationReconciler.run();} else if (plan === 'daily') {await services.tokenRefresh.refreshExpiringInstagramTokens();- await services.retention.purge();+ await services.retention.purge(Date.now(), { commentBatches: RETENTION_BATCHES });} else {context.log.warn('no job for this cron', { cron });+ return;}+ if (plan !== 'dispatch') context.log.info('cron run finished', { plan, durationMs: Date.now() - started });}diff --git a/backend/lib/automationDelivery.ts b/backend/lib/automationDelivery.tsindex c6eef73..6f6d827 100644--- a/backend/lib/automationDelivery.ts+++ b/backend/lib/automationDelivery.ts@@ -1,4 +1,6 @@-import type { AutomationAttemptOutcome, AutomationCommentStatus } from '../../shared/types/automation.ts';+import type {+ AutomationAttemptOutcome, AutomationCommentStatus, AutomationFollowupKind, AutomationGateStatus,+} from '../../shared/types/automation.ts';// Instagram refuses message text longer than 1,000 bytesexport const MAX_MESSAGE_BYTES = 1000;@@ -27,6 +29,17 @@ export const BACKGROUND_RUN_MS = 20_000;// new and retried jobs are due a little in the past, so a database clock slightly behind the Worker's still sees them as dueexport const DUE_NOW_SKEW_MS = 30_000;+// a follow-up costs the follow check as well as reserve, send and finish+export const SUBREQUESTS_PER_FOLLOWUP = 4;+// the follow check is a read and safe to ask again, so it gets less time than a send: both fit a webhook's 20 seconds+export const FOLLOW_CHECK_TIMEOUT_MS = 5_000;++// a person who does not follow yet is reminded at most twice, then the wait ends+export const MAX_FOLLOW_REMINDERS = 2;++// a follow check Instagram could not answer now is asked again on a later run+const FOLLOW_CHECK_RETRY_MS = 5 * 60 * 1000;+// a reply held by a pause is looked at again on a later sweep, not every five minutes for a weekconst HOLD_RECHECK_MS = 15 * 60 * 1000;@@ -68,7 +81,7 @@ export interface GraphSendError {// what one request to Instagram's messages endpoint came back as; ambiguous means it may have been delivered,// not_sent that the Worker refused to start the requestexport type SendResult =- | { kind: 'accepted'; messageId: string | null }+ | { kind: 'accepted'; messageId: string | null; recipientId: string | null }| ({ kind: 'error'; usageHeader: string | null } & GraphSendError)| { kind: 'ambiguous'; message: string }| { kind: 'not_sent'; message: string };@@ -77,9 +90,44 @@ export type SendResult =export interface DeliveryJob {attempts: number;expiresAt: string;+ // who the reply goes to when Instagram does not name them, and whether it starts a followers-only wait+ fromId?: string | null;+ awaitsReply?: boolean;+ // a follow-up's window is Instagram's 24 hours, not the 7 days of a private reply+ expiredMessage?: string;+}++// what Instagram said about whether the person follows the account; retry means it could not answer now+export type FollowCheck =+ | { kind: 'following' }+ | { kind: 'not_following' }+ | { kind: 'unverifiable'; message: string }+ | { kind: 'not_authorized'; message: string }+ | { kind: 'retry'; message: string };++// a claimed follow-up, as the follow-up rules need it+export interface FollowupJob {+ attempts: number;+ windowExpiresAt: string;+ ruleEnabled: boolean;+ requireFollow: boolean;+ gateStatus: AutomationGateStatus | null;+ gatePrompts: number;+ replyText: string | null;+ linkUrl: string | null;+ notFollowingText: string | null;+ accessToken: string | null;+}++// the message a follow check leads to, and what its acceptance does to the comment's wait+export interface FollowupMessage {+ kind: AutomationFollowupKind;+ text: string;+ gateStatus: AutomationGateStatus | null;+ countReminder: boolean;}-// one finish_automation_send call+// one finish_automation_send or finish_automation_followup callexport interface FinishPlan {status: AutomationCommentStatus;outcome: AutomationAttemptOutcome;@@ -93,6 +141,9 @@ export interface FinishPlan {cooldownUntil: string | null;cooldownReason: string | null;pauseReason: string | null;+ // who Instagram says received an accepted reply, and the followers-only wait it starts or ends+ recipientId: string | null;+ gateStatus: AutomationGateStatus | null;}// a job given back without sending: where it goes and why@@ -126,6 +177,7 @@ const LIMIT_MESSAGES: Record<Exclude<ReserveOutcome, 'ok' | 'gone' | 'paused' |};const EXPIRED_MESSAGE = 'The 7 days in which Instagram allows a private reply to this comment ran out.';+export const FOLLOWUP_EXPIRED_MESSAGE = 'The 24 hours in which Instagram allows a message after the person\'s reply ran out.';export function composeReply(replyText: string, linkUrl: string | null): string {return linkUrl ? `${replyText}\n\n${linkUrl}` : replyText;@@ -139,6 +191,17 @@ export function expiresAtFor(notifiedAt: Date): string {return new Date(notifiedAt.getTime() + REPLY_WINDOW_MS).toISOString();}+// sha-256 of the text sent, so a reply whose answer was lost can be recognised in the conversation later+export async function messageDigest(text: string): Promise<string> {+ const hash = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));+ return [...new Uint8Array(hash)].map(byte => byte.toString(16).padStart(2, '0')).join('');+}++// the private reply a job sends: the request to follow and answer for a followers-only rule, the reply and link otherwise+export function replyMessage(job: { requireFollow: boolean; followPromptText: string | null; replyText: string; linkUrl: string | null }): string {+ return job.requireFollow && job.followPromptText ? job.followPromptText : composeReply(job.replyText, job.linkUrl);+}+export function classifySendError({ code, subcode, httpStatus }: GraphSendError): SendErrorKind {if (httpStatus === 429 || (code !== undefined && RATE_LIMIT_CODES.has(code))) return 'rate_limited';if (code === 368) return 'blocked';@@ -175,20 +238,27 @@ export function cooldownFromUsage(usageHeader: string | null): number {function emptyPlan(): Omit<FinishPlan, 'status' | 'outcome'> {return {reason: null, errorMessage: null, messageId: null, errorCode: null, errorSubcode: null, httpStatus: null,- nextAttemptAt: null, cooldownUntil: null, cooldownReason: null, pauseReason: null,+ nextAttemptAt: null, cooldownUntil: null, cooldownReason: null, pauseReason: null, recipientId: null, gateStatus: null,};}// a wait that ends after Instagram's reply window would only fail, so the job expires insteadfunction waitUntil(at: number, job: DeliveryJob, reason: string, message: string): Pick<FinishPlan, 'status' | 'reason' | 'errorMessage' | 'nextAttemptAt'> {- if (at >= Date.parse(job.expiresAt)) return { status: 'expired', reason: 'expired', errorMessage: EXPIRED_MESSAGE, nextAttemptAt: null };+ if (at >= Date.parse(job.expiresAt)) return { status: 'expired', reason: 'expired', errorMessage: job.expiredMessage ?? EXPIRED_MESSAGE, nextAttemptAt: null };return { status: 'retry_wait', reason, errorMessage: message, nextAttemptAt: new Date(at).toISOString() };}// what to record for the answer to one sendexport function finishPlan(result: SendResult, job: DeliveryJob, now: number, random: () => number = Math.random): FinishPlan {if (result.kind === 'accepted') {- return { ...emptyPlan(), status: 'accepted', outcome: 'accepted', messageId: result.messageId };+ return {+ ...emptyPlan(),+ status: 'accepted',+ outcome: 'accepted',+ messageId: result.messageId,+ recipientId: result.recipientId ?? job.fromId ?? null,+ gateStatus: job.awaitsReply ? 'awaiting_reply' : null,+ };}if (result.kind === 'not_sent') {return { ...emptyPlan(), ...waitUntil(now + NOT_SENT_RETRY_MS, job, 'not_sent', `The reply was not sent (${result.message}). It is tried again on the next run.`), outcome: 'rejected' };@@ -265,3 +335,58 @@ export function releasePlan(outcome: ReserveOutcome, retryAt: string | null, jobconst { status, reason, errorMessage, nextAttemptAt } = waitUntil(at, job, outcome, LIMIT_MESSAGES[outcome]);return { status, reason: reason ?? outcome, errorMessage, nextAttemptAt };}++// a claimed follow-up that cannot go ahead, checked before Instagram is asked anything; null means it may+export function followupReadiness(job: FollowupJob, now: number): ReleasePlan | null {+ if (now >= Date.parse(job.windowExpiresAt)) return { status: 'expired', reason: 'expired', errorMessage: FOLLOWUP_EXPIRED_MESSAGE, nextAttemptAt: null };+ if (!job.ruleEnabled) {+ return { status: 'skipped', reason: 'rule_disabled', errorMessage: 'The rule was turned off or removed before the follow-up was sent.', nextAttemptAt: null };+ }+ if (!job.requireFollow) {+ return { status: 'skipped', reason: 'rule_changed', errorMessage: 'The rule no longer asks people to follow, so no follow-up was sent.', nextAttemptAt: null };+ }+ if (job.gateStatus !== 'awaiting_reply') {+ return { status: 'skipped', reason: 'answered', errorMessage: 'This person already got the link or every reminder.', nextAttemptAt: null };+ }+ if (!job.accessToken) {+ return { status: 'failed', reason: 'not_connected', errorMessage: 'The Instagram account has no access token. Reconnect it on the Accounts page, then retry.', nextAttemptAt: null };+ }+ return null;+}++// what the follow check leads to: a message to send, or why nothing is sent. Only a confirmed follow sends the link+export function followupMessage(check: FollowCheck, job: FollowupJob, now: number): { message: FollowupMessage } | { release: ReleasePlan } {+ if (check.kind === 'following') {+ return { message: { kind: 'link', text: composeReply(job.replyText ?? '', job.linkUrl), gateStatus: 'completed', countReminder: false } };+ }+ if (check.kind === 'not_following') {+ if (job.gatePrompts >= MAX_FOLLOW_REMINDERS || !job.notFollowingText) {+ return { release: { status: 'skipped', reason: 'reminders_used', errorMessage: 'This person does not follow the account and already got every reminder.', nextAttemptAt: null } };+ }+ const last = job.gatePrompts + 1 >= MAX_FOLLOW_REMINDERS;+ return { message: { kind: 'reminder', text: job.notFollowingText, gateStatus: last ? 'closed' : null, countReminder: true } };+ }+ if (check.kind === 'unverifiable') {+ return {+ release: {+ status: 'failed',+ reason: 'follow_unverifiable',+ errorMessage: `Instagram did not say whether this person follows the account (${check.message}), so the link was not sent.`.slice(0, 500),+ nextAttemptAt: null,+ },+ };+ }+ if (check.kind === 'not_authorized') {+ return {+ release: {+ status: 'failed',+ reason: 'not_authorized',+ errorMessage: 'Instagram refused this account\'s permission to check followers or send messages. Reconnect the account on the Accounts page, then retry.',+ nextAttemptAt: null,+ },+ };+ }+ const wait = waitUntil(now + FOLLOW_CHECK_RETRY_MS, { attempts: job.attempts, expiresAt: job.windowExpiresAt, expiredMessage: FOLLOWUP_EXPIRED_MESSAGE },+ 'follow_check', `Instagram could not answer the follow check (${check.message}). It is asked again in a few minutes.`);+ return { release: { status: wait.status, reason: wait.reason ?? 'follow_check', errorMessage: wait.errorMessage, nextAttemptAt: wait.nextAttemptAt } };+}diff --git a/backend/lib/automationHealth.ts b/backend/lib/automationHealth.tsnew file mode 100644index 0000000..d309deb--- /dev/null+++ b/backend/lib/automationHealth.ts@@ -0,0 +1,24 @@+// the reply queue's health, as the five minute run reads it, and the warnings worth a log line++// replies are dispatched every minute, so one due for this long means runs are not keeping up+export const BEHIND_AFTER_MS = 10 * 60 * 1000;++export interface QueueHealth {+ due: number;+ oldestDueAt: string | null;+ waiting: number;+ stale: number;+ needsReview: number;+ followupsDue: number;+ pausedAccounts: number;+ limitedAccounts: number;+}++// at most one line per run, however many things are wrong, so a large incident does not flood the logs+export function healthWarning(health: QueueHealth, now: number): string | null {+ const problems: string[] = [];+ const behindMs = health.oldestDueAt ? now - Date.parse(health.oldestDueAt) : 0;+ if (behindMs > BEHIND_AFTER_MS) problems.push(`the oldest due reply has waited ${Math.round(behindMs / 60_000)} minutes`);+ if (health.stale > 0) problems.push(`${health.stale} replies are held by runs that stopped`);+ return problems.length > 0 ? `automation queue behind: ${problems.join('; ')}` : null;+}diff --git a/backend/lib/automationMatching.ts b/backend/lib/automationMatching.tsindex 1b3cbae..c8fa88f 100644--- a/backend/lib/automationMatching.ts+++ b/backend/lib/automationMatching.ts@@ -7,9 +7,10 @@ export interface MatchableRule {mediaIds: string[];}+// keyword is null when an any-comment rule answeredexport interface RuleMatch<T extends MatchableRule> {rule: T;- keyword: string;+ keyword: string | null;}// what surrounds a comment's words without changing them: spaces, punctuation and emoji@@ -41,17 +42,30 @@ export function matchedKeyword(comment: string, rule: MatchableRule): string | nreturn null;}+// whether the rule answers this comment; an any-comment rule answers every comment with something in it+export function ruleMatch<T extends MatchableRule>(comment: string, rule: T): RuleMatch<T> | null {+ if (rule.matchMode === 'any') return normalize(comment, false) ? { rule, keyword: null } : null;+ const keyword = matchedKeyword(comment, rule);+ return keyword === null ? null : { rule, keyword };+}+export function coversMedia(rule: MatchableRule, mediaId: string | null): boolean {return rule.mediaIds.length === 0 || (mediaId !== null && rule.mediaIds.includes(mediaId));}-// a rule aimed at this post wins over a rule for every post; within each group the order given (oldest first) decides+// the more specific rule answers: rules for this post before rules for every post, and in each group keyword rules+// before any-comment rules+function rank(rule: MatchableRule): number {+ return (rule.mediaIds.length > 0 ? 0 : 2) + (rule.matchMode === 'any' ? 1 : 0);+}++// one rule answers a comment, so one comment never gets two replies; inside a rank the order given (oldest first) decidesexport function pickRule<T extends MatchableRule>(rules: T[], comment: string, mediaId: string | null): RuleMatch<T> | null {- const ordered = [...rules.filter(rule => rule.mediaIds.length > 0), ...rules.filter(rule => rule.mediaIds.length === 0)];- for (const rule of ordered) {+ const ordered = rules.map((rule, index) => ({ rule, index })).sort((a, b) => rank(a.rule) - rank(b.rule) || a.index - b.index);+ for (const { rule } of ordered) {if (!coversMedia(rule, mediaId)) continue;- const keyword = matchedKeyword(comment, rule);- if (keyword !== null) return { rule, keyword };+ const match = ruleMatch(comment, rule);+ if (match) return match;}return null;}diff --git a/backend/lib/automationReview.ts b/backend/lib/automationReview.tsnew file mode 100644index 0000000..1a84df2--- /dev/null+++ b/backend/lib/automationReview.ts@@ -0,0 +1,47 @@+// checking a reply whose answer was lost against the conversation on Instagram; nothing here ever sends++// a check waits this long after the attempt, so the conversation on Instagram has caught up+export const REVIEW_SETTLE_SECONDS = 5 * 60;+// each reply is looked for at most three times, half an hour apart, before it is left to a person+export const REVIEW_MAX_CHECKS = 3;+export const REVIEW_RECHECK_SECONDS = 30 * 60;+// each check costs two Instagram calls and one database call, and Instagram allows two conversation calls a second per account+export const REVIEW_BATCH = 4;+export const SUBREQUESTS_PER_REVIEW = 3;+// the Worker's clock and Instagram's can differ, so a message a little before the attempt still counts+const CLOCK_SLACK_MS = 2 * 60 * 1000;++export interface ConversationMessage {+ id: string;+ createdTime: string;+ fromId: string | null;+ text: string | null;+}++export interface SentReplyQuery {+ igUserId: string;+ startedAt: string;+ digest: string;+}++// the account's message with exactly the text that was sent, after the attempt started; null when there is none+export async function findSentReply(+ messages: ConversationMessage[],+ { igUserId, startedAt, digest }: SentReplyQuery,+ digestOf: (text: string) => Promise<string>,+): Promise<ConversationMessage | null> {+ const since = Date.parse(startedAt) - CLOCK_SLACK_MS;+ for (const message of messages) {+ if (message.fromId !== igUserId || message.text === null) continue;+ if (Date.parse(message.createdTime) < since) continue;+ if (await digestOf(message.text) === digest) return message;+ }+ return null;+}++// what the person sees on a reply that was looked for and not found, after this many checks+export function reviewNote(checks: number): string {+ const left = REVIEW_MAX_CHECKS - checks;+ const later = left > 0 ? ' Twiligent looks again later.' : '';+ return `Twiligent checked the conversation on Instagram and did not find this reply.${later} Check it yourself before you retry; Instagram refuses a second private reply to the same comment.`;+}diff --git a/backend/lib/automationRules.ts b/backend/lib/automationRules.tsnew file mode 100644index 0000000..6e1b223--- /dev/null+++ b/backend/lib/automationRules.ts@@ -0,0 +1,17 @@+import type { AutomationMatchMode } from '../../shared/types/automation.ts';++// checks a rule must pass as a whole, shared by the validators (a new rule) and the service (a rule after an update)++// a keyword rule needs a keyword and an any-comment rule takes none; null means the list fits the mode+export function keywordsProblem(matchMode: AutomationMatchMode, keywords: string[]): string | null {+ if (matchMode === 'any') return keywords.length > 0 ? 'A rule that answers any comment has no keywords. Remove them, or choose a keyword match.' : null;+ return keywords.length === 0 ? 'Add at least one keyword' : null;+}++// both messages are needed before a rule can ask people to follow; null means the rule is complete+export function followTextsProblem(rule: { requireFollow: boolean; followPromptText: string | null; notFollowingText: string | null }): string | null {+ if (!rule.requireFollow) return null;+ if (!rule.followPromptText) return 'Write the message that asks people to follow you and reply';+ if (!rule.notFollowingText) return 'Write the reminder for people who do not follow you yet';+ return null;+}diff --git a/backend/repositories/automationAccountRepository.ts b/backend/repositories/automationAccountRepository.tsindex fe617e7..a3ed702 100644--- a/backend/repositories/automationAccountRepository.ts+++ b/backend/repositories/automationAccountRepository.ts@@ -8,6 +8,8 @@ interface AutomationAccountRow {cooldown_until: string | null;cooldown_reason: string | null;subscribed_at: string | null;+ limited_until: string | null;+ subscribed_fields: string[] | null;}// an account has no row until its automation is paused, subscribed or cooled down; these are the defaults then@@ -18,9 +20,12 @@ export interface AutomationAccountControls {cooldownUntil: string | null;cooldownReason: string | null;subscribedAt: string | null;+ limitedUntil: string | null;+ // the webhook fields Instagram confirmed; null for a subscription made before fields were recorded+ subscribedFields: string[] | null;}-const COLUMNS = 'account_id, paused, paused_reason, cooldown_until, cooldown_reason, subscribed_at';+const COLUMNS = 'account_id, paused, paused_reason, cooldown_until, cooldown_reason, subscribed_at, limited_until, subscribed_fields';function toControls(row: AutomationAccountRow): AutomationAccountControls {return {@@ -30,11 +35,15 @@ function toControls(row: AutomationAccountRow): AutomationAccountControls {cooldownUntil: row.cooldown_until,cooldownReason: row.cooldown_reason,subscribedAt: row.subscribed_at,+ limitedUntil: row.limited_until ?? null,+ subscribedFields: row.subscribed_fields ?? null,};}export function defaultControls(accountId: string): AutomationAccountControls {- return { accountId, paused: false, pausedReason: null, cooldownUntil: null, cooldownReason: null, subscribedAt: null };+ return {+ accountId, paused: false, pausedReason: null, cooldownUntil: null, cooldownReason: null, subscribedAt: null, limitedUntil: null, subscribedFields: null,+ };}// every method is scoped to the verified user; the services check the account belongs to them before writing@@ -42,7 +51,7 @@ export interface AutomationAccountRepository {listForUser(userId: string): Promise<AutomationAccountControls[]>;findForUser(accountId: string, userId: string): Promise<AutomationAccountControls | null>;setPausedForUser(accountId: string, userId: string, paused: boolean): Promise<AutomationAccountControls>;- markSubscribedForUser(accountId: string, userId: string): Promise<AutomationAccountControls>;+ markSubscribedForUser(accountId: string, userId: string, fields: string[]): Promise<AutomationAccountControls>;}export function createAutomationAccountRepository(db: SupabaseClient): AutomationAccountRepository {@@ -53,7 +62,8 @@ export function createAutomationAccountRepository(db: SupabaseClient): Automatio.upsert({ account_id: accountId, user_id: userId, ...values }, { onConflict: 'account_id' }).select(COLUMNS));const fallback: AutomationAccountRow = {- account_id: accountId, paused: false, paused_reason: null, cooldown_until: null, cooldown_reason: null, subscribed_at: null, ...values,+ account_id: accountId, paused: false, paused_reason: null, cooldown_until: null, cooldown_reason: null, subscribed_at: null,+ limited_until: null, subscribed_fields: null, ...values,};return toControls(saved[0] ?? fallback);}@@ -80,6 +90,9 @@ export function createAutomationAccountRepository(db: SupabaseClient): Automatio// pausing or resuming by hand clears a hold the Worker set, because the owner has dealt with itsetPausedForUser: (accountId, userId, paused) => save('automationAccounts.setPaused', accountId, userId, { paused, paused_reason: null }),- markSubscribedForUser: (accountId, userId) => save('automationAccounts.markSubscribed', accountId, userId, { subscribed_at: new Date().toISOString() }),+ markSubscribedForUser: (accountId, userId, fields) => save('automationAccounts.markSubscribed', accountId, userId, {+ subscribed_at: new Date().toISOString(),+ subscribed_fields: fields,+ }),};}diff --git a/backend/repositories/automationCommentRepository.ts b/backend/repositories/automationCommentRepository.tsindex 341d69d..584c178 100644--- a/backend/repositories/automationCommentRepository.ts+++ b/backend/repositories/automationCommentRepository.ts@@ -1,8 +1,12 @@import { execute, maybeRow, rows } from './query.ts';import { DUE_NOW_SKEW_MS } from '../lib/automationDelivery.ts';import type { FinishPlan, ReleasePlan, ReserveOutcome } from '../lib/automationDelivery.ts';+import type { QueueHealth } from '../lib/automationHealth.ts';import type { SupabaseClient } from '../types/app.ts';-import type { AutomationActivityItem, AutomationCommentStatus, AutomationLimits, AutomationStats } from '../../shared/types/automation.ts';+import type {+ AutomationActivityItem, AutomationCommentStatus, AutomationFollowupKind, AutomationFollowupStatus, AutomationGateStatus, AutomationLimits,+ AutomationStats,+} from '../../shared/types/automation.ts';interface AutomationCommentRow {id: string;@@ -20,6 +24,16 @@ interface AutomationCommentRow {accepted_at: string | null;expires_at: string;created_at: string;+ gate_status: AutomationGateStatus | null;+ // PostgREST embeds the comment's follow-ups through their foreign key+ automation_followups?: FollowupRow[] | null;+}++interface FollowupRow {+ status: AutomationFollowupStatus;+ kind: AutomationFollowupKind | null;+ error_message: string | null;+ created_at: string;}interface ClaimedRow {@@ -36,6 +50,29 @@ interface ClaimedRow {reply_text: string | null;link_url: string | null;access_token: string | null;+ require_follow: boolean | null;+ follow_prompt_text: string | null;+}++interface ReviewCandidateRow {+ id: string;+ ig_user_id: string;+ from_id: string;+ started_at: string;+ message_digest: string | null;+ access_token: string | null;+ review_checks: number;+}++interface QueueHealthRow {+ due?: number;+ oldest_due_at?: string | null;+ waiting?: number;+ stale?: number;+ needs_review?: number;+ followups_due?: number;+ paused_accounts?: number;+ limited_accounts?: number;}// a comment as the webhook stores it@@ -72,8 +109,35 @@ export interface ClaimedComment {replyText: string | null;linkUrl: string | null;accessToken: string | null;+ // a followers-only rule sends its request to follow and answer instead of the reply+ requireFollow: boolean;+ followPromptText: string | null;+}++// a reply whose answer was lost, with what is needed to look for it in the conversation+export interface ReviewCandidate {+ id: string;+ igUserId: string;+ fromId: string;+ startedAt: string;+ messageDigest: string | null;+ accessToken: string | null;+ // checks made before this one+ reviewChecks: number;}+export interface ReviewCandidateOptions {+ limit: number;+ settleSeconds: number;+ maxChecks: number;+ recheckSeconds: number;+}++// what one look at the conversation found; a found reply carries its message id and time+export type ReviewResult =+ | { found: true; messageId: string; sentAt: string }+ | { found: false; note: string };+export interface ClaimOptions {limit: number;perAccount: number;@@ -113,7 +177,13 @@ export interface StatsFilter {// a person may ask for these to be tried again; an expired one can never be sentconst RETRYABLE: AutomationCommentStatus[] = ['failed', 'needs_review', 'skipped'];-const COLUMNS = 'id, account_id, rule_id, comment_id, media_id, from_username, text, status, status_reason, error_message, attempts, next_attempt_at, accepted_at, expires_at, created_at';+const COLUMNS = 'id, account_id, rule_id, comment_id, media_id, from_username, text, status, status_reason, error_message, attempts, next_attempt_at, accepted_at, expires_at, created_at, gate_status, automation_followups(status, kind, error_message, created_at)';++// the latest follow-up, so the list shows where a followers-only reply stands+function latestFollowup(rows: FollowupRow[] | null | undefined): AutomationActivityItem['followup'] {+ const latest = [...(rows ?? [])].sort((a, b) => b.created_at.localeCompare(a.created_at))[0];+ return latest ? { status: latest.status, kind: latest.kind, errorMessage: latest.error_message, createdAt: latest.created_at } : null;+}function toItem(row: AutomationCommentRow): AutomationActivityItem {return {@@ -132,6 +202,8 @@ function toItem(row: AutomationCommentRow): AutomationActivityItem {acceptedAt: row.accepted_at,expiresAt: row.expires_at,createdAt: row.created_at,+ gateStatus: row.gate_status ?? null,+ followup: latestFollowup(row.automation_followups),};}@@ -150,15 +222,29 @@ function toClaimed(row: ClaimedRow): ClaimedComment {replyText: row.reply_text,linkUrl: row.link_url,accessToken: row.access_token,+ requireFollow: row.require_follow ?? false,+ followPromptText: row.follow_prompt_text ?? null,+ };+}++function toHealth(row: QueueHealthRow): QueueHealth {+ return {+ due: row.due ?? 0,+ oldestDueAt: row.oldest_due_at ?? null,+ waiting: row.waiting ?? 0,+ stale: row.stale ?? 0,+ needsReview: row.needs_review ?? 0,+ followupsDue: row.followups_due ?? 0,+ pausedAccounts: row.paused_accounts ?? 0,+ limitedAccounts: row.limited_accounts ?? 0,};}-// methods named ...ForUser filter by the verified user id; insertMany, claim, reserve, finish, release and-// deleteCreatedBefore serve the webhook and the sweep across all users+// methods named ...ForUser filter by the verified user id; the others serve the webhook and the cron jobs across all usersexport interface AutomationCommentRepository {insertMany(comments: NewAutomationComment[]): Promise<NewAutomationComment[]>;claim(options: ClaimOptions): Promise<ClaimedComment[]>;- reserve(id: string, attemptId: string, limits: AutomationLimits): Promise<Reservation>;+ reserve(id: string, attemptId: string, limits: AutomationLimits, messageDigest?: string): Promise<Reservation>;finish(id: string, attemptId: string, plan: FinishPlan): Promise<boolean>;release(id: string, plan: ReleasePlan): Promise<boolean>;returnUnstarted(ids: string[]): Promise<void>;@@ -167,7 +253,11 @@ export interface AutomationCommentRepository {requeueForUser(id: string, userId: string): Promise<AutomationActivityItem | null>;releaseHeldForAccount(accountId: string, userId: string): Promise<void>;statsForUser(userId: string, filter: StatsFilter): Promise<AutomationStats>;- deleteCreatedBefore(cutoff: string): Promise<number>;+ expireDue(limit: number): Promise<{ comments: number; followups: number }>;+ reviewCandidates(options: ReviewCandidateOptions): Promise<ReviewCandidate[]>;+ recordReview(id: string, result: ReviewResult): Promise<boolean>;+ health(leaseSeconds: number): Promise<QueueHealth>;+ purgeCreatedBefore(cutoff: string, limit: number): Promise<number>;}export function createAutomationCommentRepository(db: SupabaseClient): AutomationCommentRepository {@@ -209,7 +299,7 @@ export function createAutomationCommentRepository(db: SupabaseClient): Automatioreturn ((data ?? []) as ClaimedRow[]).map(toClaimed);},- async reserve(id, attemptId, limits) {+ async reserve(id, attemptId, limits, messageDigest) {const { data } = await execute('automationComments.reserve', () => db.rpc('reserve_automation_send', {p_id: id,p_attempt_id: attemptId,@@ -217,6 +307,7 @@ export function createAutomationCommentRepository(db: SupabaseClient): Automatiop_user_limit: limits.userHourly,p_account_limit: limits.accountHourly,p_recipient_limit: limits.recipientDaily,+ p_message_digest: messageDigest ?? null,}));const [row] = (data ?? []) as { outcome: ReserveOutcome; retry_at: string | null }[];return row ? { outcome: row.outcome, retryAt: row.retry_at } : { outcome: 'gone', retryAt: null };@@ -238,6 +329,8 @@ export function createAutomationCommentRepository(db: SupabaseClient): Automatiop_cooldown_until: plan.cooldownUntil,p_cooldown_reason: plan.cooldownReason,p_pause_reason: plan.pauseReason,+ p_recipient_id: plan.recipientId,+ p_gate_status: plan.gateStatus,}));return data === true;},@@ -330,13 +423,47 @@ export function createAutomationCommentRepository(db: SupabaseClient): Automatioreturn { comments: stats.comments ?? {}, attempts: stats.attempts ?? {} };},- async deleteCreatedBefore(cutoff) {- const deleted = await rows<{ id: string }>('automationComments.deleteOld', () => db- .from('automation_comments')- .delete()- .lt('created_at', cutoff)- .select('id'));- return deleted.length;+ async expireDue(limit) {+ const { data } = await execute('automationComments.expireDue', () => db.rpc('expire_automation_jobs', { p_limit: limit }));+ const counts = (data ?? {}) as { comments?: number; followups?: number };+ return { comments: counts.comments ?? 0, followups: counts.followups ?? 0 };+ },++ async reviewCandidates({ limit, settleSeconds, maxChecks, recheckSeconds }) {+ const { data } = await execute('automationComments.reviewCandidates', () => db.rpc('automation_review_candidates', {+ p_limit: limit,+ p_settle_seconds: settleSeconds,+ p_max_checks: maxChecks,+ p_recheck_seconds: recheckSeconds,+ }));+ return ((data ?? []) as ReviewCandidateRow[]).map(row => ({+ id: row.id,+ igUserId: row.ig_user_id,+ fromId: row.from_id,+ startedAt: row.started_at,+ messageDigest: row.message_digest,+ accessToken: row.access_token,+ reviewChecks: row.review_checks ?? 0,+ }));+ },++ // only a comment still waiting for review changes, so a person's retry in between is never undone+ async recordReview(id, result) {+ const { data } = await execute('automationComments.recordReview', () => db.rpc('record_automation_review', result.found+ ? { p_id: id, p_found: true, p_message_id: result.messageId, p_sent_at: result.sentAt, p_note: null }+ : { p_id: id, p_found: false, p_message_id: null, p_sent_at: null, p_note: result.note }));+ return data === true;+ },++ async health(leaseSeconds) {+ const { data } = await execute('automationComments.health', () => db.rpc('automation_queue_health', { p_lease_seconds: leaseSeconds }));+ return toHealth((data ?? {}) as QueueHealthRow);+ },++ // one bounded batch per call, oldest first, so a long backlog never becomes one long delete+ async purgeCreatedBefore(cutoff, limit) {+ const { data } = await execute('automationComments.purge', () => db.rpc('purge_automation_comments', { p_before: cutoff, p_limit: limit }));+ return typeof data === 'number' ? data : 0;},};}diff --git a/backend/repositories/automationFollowupRepository.ts b/backend/repositories/automationFollowupRepository.tsnew file mode 100644index 0000000..1e1cb57--- /dev/null+++ b/backend/repositories/automationFollowupRepository.ts@@ -0,0 +1,203 @@+import { execute, rows } from './query.ts';+import { DUE_NOW_SKEW_MS } from '../lib/automationDelivery.ts';+import type { FinishPlan, ReleasePlan, ReserveOutcome } from '../lib/automationDelivery.ts';+import type { Reservation } from './automationCommentRepository.ts';+import type { SupabaseClient } from '../types/app.ts';+import type { AutomationFollowupKind, AutomationFollowupStatus, AutomationGateStatus } from '../../shared/types/automation.ts';++interface ClaimedFollowupRow {+ id: string;+ user_id: string;+ account_id: string;+ automation_comment_id: string;+ ig_user_id: string;+ recipient_id: string;+ attempts: number;+ window_expires_at: string;+ gate_status: AutomationGateStatus | null;+ gate_prompts: number;+ rule_enabled: boolean;+ require_follow: boolean;+ reply_text: string | null;+ link_url: string | null;+ not_following_text: string | null;+ access_token: string | null;+}++// a message from a person, as the webhook read it; its text is never kept+export interface IncomingMessage {+ // the follow-up row this message would become+ id: string;+ senderId: string;+ messageId: string;+ sentAt: string;+}++// a follow-up one run holds, with the rule's texts, the comment's wait and the account's token+export interface ClaimedFollowup {+ id: string;+ userId: string;+ accountId: string;+ commentRowId: string;+ igUserId: string;+ recipientId: string;+ attempts: number;+ windowExpiresAt: string;+ gateStatus: AutomationGateStatus | null;+ gatePrompts: number;+ ruleEnabled: boolean;+ requireFollow: boolean;+ replyText: string | null;+ linkUrl: string | null;+ notFollowingText: string | null;+ accessToken: string | null;+}++export interface FollowupClaimOptions {+ limit: number;+ leaseSeconds: number;+ ids?: string[];+}++// one finish_automation_followup call: a reply's plan plus whether a reminder was counted+export type FollowupFinishPlan = FinishPlan & { countReminder: boolean };++// a person may ask for these to be tried again+const RETRYABLE: AutomationFollowupStatus[] = ['failed', 'needs_review', 'skipped'];++function toClaimed(row: ClaimedFollowupRow): ClaimedFollowup {+ return {+ id: row.id,+ userId: row.user_id,+ accountId: row.account_id,+ commentRowId: row.automation_comment_id,+ igUserId: row.ig_user_id,+ recipientId: row.recipient_id,+ attempts: row.attempts,+ windowExpiresAt: row.window_expires_at,+ gateStatus: row.gate_status,+ gatePrompts: row.gate_prompts,+ ruleEnabled: row.rule_enabled,+ requireFollow: row.require_follow,+ replyText: row.reply_text,+ linkUrl: row.link_url,+ notFollowingText: row.not_following_text,+ accessToken: row.access_token,+ };+}++// the messages sent after a person answered a followers-only reply; requeueLatestForUser is scoped to the verified+// user, the others serve the webhook and the dispatch across all users+export interface AutomationFollowupRepository {+ insertForMessages(igUserId: string, messages: IncomingMessage[]): Promise<string[]>;+ claim(options: FollowupClaimOptions): Promise<ClaimedFollowup[]>;+ reserve(id: string, attemptId: string, kind: AutomationFollowupKind, messageDigest: string): Promise<Reservation>;+ finish(id: string, attemptId: string, plan: FollowupFinishPlan): Promise<boolean>;+ release(id: string, plan: ReleasePlan): Promise<boolean>;+ returnUnstarted(ids: string[]): Promise<void>;+ requeueLatestForUser(commentRowId: string, userId: string): Promise<string | null>;+}++export function createAutomationFollowupRepository(db: SupabaseClient): AutomationFollowupRepository {+ return {+ // messages from people nobody is waiting for, a message delivered again, or a second one while a follow-up is+ // open insert nothing; only the new follow-up ids come back+ async insertForMessages(igUserId, messages) {+ if (messages.length === 0) return [];+ const { data } = await execute('automationFollowups.insertForMessages', () => db.rpc('automation_followups_for_messages', {+ p_ig_user_id: igUserId,+ p_messages: messages.map(message => ({ id: message.id, sender_id: message.senderId, message_id: message.messageId, sent_at: message.sentAt })),+ }));+ return ((data ?? []) as { id: string }[]).map(row => row.id);+ },++ async claim({ limit, leaseSeconds, ids }) {+ const { data } = await execute('automationFollowups.claim', () => db.rpc('claim_automation_followups', {+ p_limit: limit,+ p_lease_seconds: leaseSeconds,+ p_ids: ids ?? null,+ }));+ return ((data ?? []) as ClaimedFollowupRow[]).map(toClaimed);+ },++ async reserve(id, attemptId, kind, messageDigest) {+ const { data } = await execute('automationFollowups.reserve', () => db.rpc('reserve_automation_followup', {+ p_id: id,+ p_attempt_id: attemptId,+ p_kind: kind,+ p_message_digest: messageDigest,+ }));+ const [row] = (data ?? []) as { outcome: ReserveOutcome; retry_at: string | null }[];+ return row ? { outcome: row.outcome, retryAt: row.retry_at } : { outcome: 'gone', retryAt: null };+ },++ async finish(id, attemptId, plan) {+ const { data } = await execute('automationFollowups.finish', () => db.rpc('finish_automation_followup', {+ p_id: id,+ p_attempt_id: attemptId,+ p_status: plan.status,+ p_outcome: plan.outcome,+ p_reason: plan.reason,+ p_error_message: plan.errorMessage,+ p_message_id: plan.messageId,+ p_error_code: plan.errorCode,+ p_error_subcode: plan.errorSubcode,+ p_http_status: plan.httpStatus,+ p_next_attempt_at: plan.nextAttemptAt,+ p_cooldown_until: plan.cooldownUntil,+ p_cooldown_reason: plan.cooldownReason,+ p_pause_reason: plan.pauseReason,+ p_gate_status: plan.gateStatus,+ p_count_reminder: plan.countReminder,+ }));+ return data === true;+ },++ // only a follow-up this run still holds is given back+ async release(id, plan) {+ const released = await rows<{ id: string }>('automationFollowups.release', () => db+ .from('automation_followups')+ .update({+ status: plan.status,+ status_reason: plan.reason,+ error_message: plan.errorMessage,+ next_attempt_at: plan.nextAttemptAt,+ claimed_at: null,+ })+ .eq('id', id)+ .eq('status', 'processing')+ .select('id'));+ return released.length > 0;+ },++ async returnUnstarted(ids) {+ await execute('automationFollowups.returnUnstarted', () => db+ .from('automation_followups')+ .update({ status: 'queued', claimed_at: null, next_attempt_at: new Date(Date.now() - DUE_NOW_SKEW_MS).toISOString() })+ .in('id', ids)+ .eq('status', 'processing'));+ },++ // the comment's newest follow-up goes back in the queue if it failed, was skipped or needs review and its window+ // is still open; checked in the update itself, so one a run picked up in between is never sent twice+ async requeueLatestForUser(commentRowId, userId) {+ const [latest] = await rows<{ id: string }>('automationFollowups.latest', () => db+ .from('automation_followups')+ .select('id')+ .eq('automation_comment_id', commentRowId)+ .eq('user_id', userId)+ .order('created_at', { ascending: false })+ .limit(1));+ if (!latest) return null;+ const requeued = await rows<{ id: string }>('automationFollowups.requeue', () => db+ .from('automation_followups')+ .update({ status: 'queued', status_reason: 'retry', error_message: null, next_attempt_at: new Date(Date.now() - DUE_NOW_SKEW_MS).toISOString(), claimed_at: null })+ .eq('id', latest.id)+ .eq('user_id', userId)+ .in('status', RETRYABLE)+ .gt('window_expires_at', new Date().toISOString())+ .select('id'));+ return requeued[0]?.id ?? null;+ },+ };+}diff --git a/backend/repositories/automationRuleRepository.ts b/backend/repositories/automationRuleRepository.tsindex 707eef5..e814bcf 100644--- a/backend/repositories/automationRuleRepository.ts+++ b/backend/repositories/automationRuleRepository.ts@@ -14,6 +14,9 @@ interface AutomationRuleRow {link_url: string | null;enabled: boolean;hourly_limit: number | null;+ require_follow: boolean;+ follow_prompt_text: string | null;+ not_following_text: string | null;created_at: string;updated_at: string;}@@ -41,7 +44,7 @@ interface WebhookRuleRow {export type AutomationRuleChanges = Partial<Omit<AutomationRule, 'id' | 'accountId' | 'createdAt' | 'updatedAt'>>;-const COLUMNS = 'id, account_id, name, keywords, match_mode, case_sensitive, media_ids, reply_text, link_url, enabled, hourly_limit, created_at, updated_at';+const COLUMNS = 'id, account_id, name, keywords, match_mode, case_sensitive, media_ids, reply_text, link_url, enabled, hourly_limit, require_follow, follow_prompt_text, not_following_text, created_at, updated_at';function toRule(row: AutomationRuleRow): AutomationRule {return {@@ -56,6 +59,9 @@ function toRule(row: AutomationRuleRow): AutomationRule {linkUrl: row.link_url,enabled: row.enabled,hourlyLimit: row.hourly_limit,+ requireFollow: row.require_follow ?? false,+ followPromptText: row.follow_prompt_text ?? null,+ notFollowingText: row.not_following_text ?? null,createdAt: row.created_at,updatedAt: row.updated_at,};@@ -73,6 +79,9 @@ function toColumns(changes: AutomationRuleChanges): Record<string, unknown> {link_url: changes.linkUrl,enabled: changes.enabled,hourly_limit: changes.hourlyLimit,+ require_follow: changes.requireFollow,+ follow_prompt_text: changes.followPromptText,+ not_following_text: changes.notFollowingText,};return Object.fromEntries(Object.entries(columns).filter(([, value]) => value !== undefined));}diff --git a/backend/server.ts b/backend/server.tsindex 5ce95ca..0aa8cd2 100644--- a/backend/server.ts+++ b/backend/server.ts@@ -6,7 +6,8 @@ import type { Env } from './types/env.ts';export default {fetch: app.fetch,- // wrangler.toml schedules: the reply queue every 5 minutes with due posts on the quarter hour, and daily upkeep+ // wrangler.toml schedules: the reply dispatch every minute, due posts on the quarter hour with queue checks on the+ // other five minute runs, and daily upkeepasync scheduled(event: ScheduledController, env: Env, ctx: ExecutionContext) {ctx.waitUntil(runScheduledJob(event.cron, env, event.scheduledTime));},diff --git a/backend/services/automationFollowupProcessor.ts b/backend/services/automationFollowupProcessor.tsnew file mode 100644index 0000000..a8b52b0--- /dev/null+++ b/backend/services/automationFollowupProcessor.ts@@ -0,0 +1,144 @@+import { readFollowStatus, sendMessage } from './instagram/instagramMessaging.ts';+import {+ BACKGROUND_RUN_MS, CLAIM_LEASE_SECONDS, DUE_NOW_SKEW_MS, FOLLOWUP_EXPIRED_MESSAGE, FOLLOW_CHECK_TIMEOUT_MS, FREE_PLAN_SUBREQUESTS, SEND_TIMEOUT_MS,+ SUBREQUESTS_PER_FOLLOWUP, finishPlan, followupMessage, followupReadiness, messageDigest, releasePlan,+} from '../lib/automationDelivery.ts';+import { newRowId } from '../lib/ids.ts';+import { errorFields } from '../lib/logger.ts';+import type { AutomationFollowupRepository, ClaimedFollowup } from '../repositories/automationFollowupRepository.ts';+import type { AutomationConfig } from '../lib/config.ts';+import type { RequestContext } from '../types/context.ts';+import type { AutomationFollowupStatus } from '../../shared/types/automation.ts';++export interface AutomationFollowupProcessorDeps {+ followups: AutomationFollowupRepository;+ automation: AutomationConfig;+ context: RequestContext;+}++export interface FollowupProcessOptions {+ // only these follow-ups, as a webhook just stored them; otherwise whatever is due+ ids?: string[];+ subrequests?: number;+ timeBudgetMs?: number;+}++export interface FollowupRun {+ claimed: number;+ outcomes: Partial<Record<AutomationFollowupStatus | 'gone' | 'returned' | 'error', number>>;+ subrequests: number;+}++export interface AutomationFollowupProcessor {+ run(options?: FollowupProcessOptions): Promise<FollowupRun>;+}++const SEND_MARGIN_MS = 2_000;++// answers people who replied to a followers-only private reply: Instagram is asked whether they follow the account,+// then the reply and link go to a follower and a reminder to anyone else. Nothing is sent when Instagram cannot say,+// and like private replies, a send whose answer is lost is never repeated without a person's decision+export function createAutomationFollowupProcessor({ followups, automation, context }: AutomationFollowupProcessorDeps): AutomationFollowupProcessor {+ const { signal, log } = context;++ async function settle(job: ClaimedFollowup, spend: () => void, timeLeft: () => number): Promise<AutomationFollowupStatus | 'gone' | 'returned'> {+ const notReady = followupReadiness(job, Date.now());+ if (notReady) {+ spend();+ await followups.release(job.id, notReady);+ return notReady.status as AutomationFollowupStatus;+ }++ spend();+ const check = await readFollowStatus(job.recipientId, job.accessToken!);+ const decision = followupMessage(check, job, Date.now());+ if ('release' in decision) {+ spend();+ await followups.release(job.id, decision.release);+ log.info('automation follow-up held', { followupId: job.id, accountId: job.accountId, follow: check.kind, status: decision.release.status });+ return decision.release.status as AutomationFollowupStatus;+ }++ // a slow check can leave too little time for the send's whole timeout; the job goes back unsent rather than risk an+ // unknown outcome, and the next run asks again+ if (signal.aborted || timeLeft() < SEND_TIMEOUT_MS + SEND_MARGIN_MS) {+ spend();+ await followups.release(job.id, { status: 'queued', reason: 'returned', errorMessage: null, nextAttemptAt: new Date(Date.now() - DUE_NOW_SKEW_MS).toISOString() });+ return 'returned';+ }++ const { message } = decision;+ const delivery = { attempts: job.attempts + 1, expiresAt: job.windowExpiresAt, expiredMessage: FOLLOWUP_EXPIRED_MESSAGE };+ const attemptId = newRowId();+ spend();+ const reservation = await followups.reserve(job.id, attemptId, message.kind, await messageDigest(message.text));+ if (reservation.outcome === 'gone') return 'gone';+ const held = releasePlan(reservation.outcome, reservation.retryAt, delivery, Date.now());+ if (held) {+ spend();+ await followups.release(job.id, held);+ return held.status as AutomationFollowupStatus;+ }++ spend();+ const result = await sendMessage(job.igUserId, job.accessToken!, { id: job.recipientId }, message.text);+ const plan = finishPlan(result, delivery, Date.now());+ const accepted = plan.status === 'accepted';+ spend();+ await followups.finish(job.id, attemptId, {+ ...plan,+ gateStatus: accepted ? message.gateStatus : null,+ countReminder: accepted && message.countReminder,+ });+ log.info('automation follow-up settled', {+ followupId: job.id,+ accountId: job.accountId,+ kind: message.kind,+ status: plan.status,+ outcome: plan.outcome,+ errorCode: plan.errorCode,+ });+ return plan.status as AutomationFollowupStatus;+ }++ async function handBack(jobs: ClaimedFollowup[], outcomes: FollowupRun['outcomes']): Promise<void> {+ if (jobs.length === 0) return;+ try {+ await followups.returnUnstarted(jobs.map(job => job.id));+ outcomes.returned = jobs.length;+ } catch (err) {+ log.error('automation follow-ups not handed back', { count: jobs.length, ...errorFields(err) });+ }+ }++ return {+ async run({ ids, subrequests = FREE_PLAN_SUBREQUESTS, timeBudgetMs = BACKGROUND_RUN_MS } = {}) {+ const outcomes: FollowupRun['outcomes'] = {};+ if (automation.paused) return { claimed: 0, outcomes, subrequests: 0 };+ const started = Date.now();+ const batch = Math.min(automation.batchSize, Math.floor((subrequests - 2) / SUBREQUESTS_PER_FOLLOWUP));+ if (batch < 1) return { claimed: 0, outcomes, subrequests: 0 };+ let spent = 1;+ const spend = () => { spent++; };+ const jobs = await followups.claim({ limit: batch, leaseSeconds: CLAIM_LEASE_SECONDS, ids });++ const timeLeft = () => timeBudgetMs - (Date.now() - started);+ for (const [index, job] of jobs.entries()) {+ // the follow check and the send each get their whole timeout+ if (signal.aborted || timeLeft() < FOLLOW_CHECK_TIMEOUT_MS + SEND_TIMEOUT_MS + SEND_MARGIN_MS) {+ spent++;+ await handBack(jobs.slice(index), outcomes);+ break;+ }+ try {+ const status = await settle(job, spend, timeLeft);+ outcomes[status] = (outcomes[status] ?? 0) + 1;+ } catch (err) {+ outcomes.error = (outcomes.error ?? 0) + 1;+ log.error('automation follow-up failed', { followupId: job.id, accountId: job.accountId, ...errorFields(err) });+ }+ }+ return { claimed: jobs.length, outcomes, subrequests: spent };+ },+ };+}diff --git a/backend/services/automationProcessor.ts b/backend/services/automationProcessor.tsindex 6f23d39..f8fe953 100644--- a/backend/services/automationProcessor.ts+++ b/backend/services/automationProcessor.ts@@ -1,7 +1,7 @@import { sendPrivateReply } from './instagram/instagramMessaging.ts';import {BACKGROUND_RUN_MS, CLAIM_LEASE_SECONDS, FREE_PLAN_SUBREQUESTS, SEND_TIMEOUT_MS, SUBREQUESTS_PER_REPLY,- composeReply, finishPlan, readinessPlan, releasePlan,+ finishPlan, messageDigest, readinessPlan, releasePlan, replyMessage,} from '../lib/automationDelivery.ts';import { newRowId } from '../lib/ids.ts';import { errorFields } from '../lib/logger.ts';@@ -32,6 +32,8 @@ export interface ProcessRun {// the status each claimed job ended in this run; gone means another run settled it first, returned that it was// handed back unstarted because the run ran out of time or subrequestsoutcomes: Partial<Record<AutomationCommentStatus | 'gone' | 'returned' | 'error', number>>;+ // subrequests the run made, so the rest of its invocation knows what is left+ subrequests: number;}export interface AutomationProcessor {@@ -46,26 +48,32 @@ const SEND_MARGIN_MS = 2_000;export function createAutomationProcessor({ comments, automation, context }: AutomationProcessorDeps): AutomationProcessor {const { signal, log } = context;- async function settle(job: ClaimedComment): Promise<AutomationCommentStatus | 'gone'> {+ async function settle(job: ClaimedComment, spend: () => void): Promise<AutomationCommentStatus | 'gone'> {const now = Date.now();const notReady = readinessPlan(job, now);if (notReady) {+ spend();await comments.release(job.id, notReady);return notReady.status;}+ // readinessPlan checked that the rule is on and the token is there+ const text = replyMessage({ requireFollow: job.requireFollow, followPromptText: job.followPromptText, replyText: job.replyText!, linkUrl: job.linkUrl });const attemptId = newRowId();- const reservation = await comments.reserve(job.id, attemptId, automation.limits);+ spend();+ const reservation = await comments.reserve(job.id, attemptId, automation.limits, await messageDigest(text));if (reservation.outcome === 'gone') return 'gone';const held = releasePlan(reservation.outcome, reservation.retryAt, job, now);if (held) {+ spend();await comments.release(job.id, held);return held.status;}- // readinessPlan checked that the rule is on and the token is there- const result = await sendPrivateReply(job.igUserId, job.accessToken!, job.commentId, composeReply(job.replyText!, job.linkUrl));- const plan = finishPlan(result, { attempts: job.attempts + 1, expiresAt: job.expiresAt }, Date.now());+ spend();+ const result = await sendPrivateReply(job.igUserId, job.accessToken!, job.commentId, text);+ const plan = finishPlan(result, { attempts: job.attempts + 1, expiresAt: job.expiresAt, fromId: job.fromId, awaitsReply: job.requireFollow }, Date.now());+ spend();await comments.finish(job.id, attemptId, plan);log.info('automation reply settled', {commentRowId: job.id,@@ -73,6 +81,7 @@ export function createAutomationProcessor({ comments, automation, context }: AutruleId: job.ruleId,status: plan.status,outcome: plan.outcome,+ followersOnly: job.requireFollow,errorCode: plan.errorCode,errorSubcode: plan.errorSubcode,});@@ -95,7 +104,7 @@ export function createAutomationProcessor({ comments, automation, context }: Autconst outcomes: ProcessRun['outcomes'] = {};if (automation.paused) {log.info('automation paused on this instance; nothing sent');- return { claimed: 0, outcomes };+ return { claimed: 0, outcomes, subrequests: 0 };}const started = Date.now();// the claim and one hand-back come first, then each reply needs its three calls@@ -103,20 +112,22 @@ export function createAutomationProcessor({ comments, automation, context }: Autconst batch = Math.min(limit ?? automation.batchSize, automation.batchSize, affordable);if (batch < 1) {log.warn('automation run skipped: no subrequests left', { subrequests });- return { claimed: 0, outcomes };+ return { claimed: 0, outcomes, subrequests: 0 };}- // a sweep shares its batch between accounts; a webhook's own comments are all from the accounts it named- const perAccount = ids ? batch : Math.max(1, Math.ceil(batch / 2));- const jobs = await comments.claim({ limit: batch, perAccount, leaseSeconds: CLAIM_LEASE_SECONDS, ids });+ let spent = 1;+ const spend = () => { spent++; };+ // accounts take turns inside the claim, so one account may fill the batch only when no other is waiting+ const jobs = await comments.claim({ limit: batch, perAccount: batch, leaseSeconds: CLAIM_LEASE_SECONDS, ids });for (const [index, job] of jobs.entries()) {const timeLeft = timeBudgetMs - (Date.now() - started);if (signal.aborted || timeLeft < SEND_TIMEOUT_MS + SEND_MARGIN_MS) {+ spent++;await handBack(jobs.slice(index), outcomes);break;}try {- const status = await settle(job);+ const status = await settle(job, spend);outcomes[status] = (outcomes[status] ?? 0) + 1;} catch (err) {// one job's database failure must not stop the others; its claim or reservation expires and recovers it@@ -124,7 +135,7 @@ export function createAutomationProcessor({ comments, automation, context }: Autlog.error('automation reply failed', { commentRowId: job.id, accountId: job.accountId, ...errorFields(err) });}}- return { claimed: jobs.length, outcomes };+ return { claimed: jobs.length, outcomes, subrequests: spent };},};}diff --git a/backend/services/automationReconciler.ts b/backend/services/automationReconciler.tsnew file mode 100644index 0000000..2da396d--- /dev/null+++ b/backend/services/automationReconciler.ts@@ -0,0 +1,83 @@+import { listConversationMessages } from './instagram/instagramMessaging.ts';+import { CLAIM_LEASE_SECONDS, FREE_PLAN_SUBREQUESTS, messageDigest } from '../lib/automationDelivery.ts';+import { healthWarning } from '../lib/automationHealth.ts';+import {+ REVIEW_BATCH, REVIEW_MAX_CHECKS, REVIEW_RECHECK_SECONDS, REVIEW_SETTLE_SECONDS, SUBREQUESTS_PER_REVIEW, findSentReply, reviewNote,+} from '../lib/automationReview.ts';+import { errorFields } from '../lib/logger.ts';+import { redactUrls } from '../lib/redact.ts';+import type { AutomationCommentRepository, ReviewCandidate, ReviewResult } from '../repositories/automationCommentRepository.ts';+import type { QueueHealth } from '../lib/automationHealth.ts';+import type { RequestContext } from '../types/context.ts';++export interface AutomationReconcilerDeps {+ comments: AutomationCommentRepository;+ context: RequestContext;+}++export interface ReconcileRun {+ expired: { comments: number; followups: number };+ reviewed: { found: number; notFound: number; failed: number };+ health: QueueHealth;+}++export interface AutomationReconciler {+ run(now?: number): Promise<ReconcileRun>;+}++// overdue jobs settled per run; the rest wait five minutes, and a run that misses them leaves them unclaimable anyway+const EXPIRE_BATCH = 500;++// the five minute job: expires what can no longer be sent, looks for lost replies in their conversations and reports how+// the queue is doing. It never sends anything, so it cannot race the dispatch into a second message+export function createAutomationReconciler({ comments, context }: AutomationReconcilerDeps): AutomationReconciler {+ const { log, signal } = context;++ async function lookFor(candidate: ReviewCandidate): Promise<ReviewResult> {+ if (!candidate.messageDigest || !candidate.accessToken) {+ return { found: false, note: 'This reply was sent before Twiligent could recognise it in the conversation. Check it on Instagram before you retry.' };+ }+ const messages = await listConversationMessages(candidate.igUserId, candidate.accessToken, candidate.fromId, signal);+ const match = await findSentReply(messages, { igUserId: candidate.igUserId, startedAt: candidate.startedAt, digest: candidate.messageDigest }, messageDigest);+ return match ? { found: true, messageId: match.id, sentAt: match.createdTime } : { found: false, note: reviewNote(candidate.reviewChecks + 1) };+ }++ async function review(budget: number): Promise<ReconcileRun['reviewed']> {+ const reviewed = { found: 0, notFound: 0, failed: 0 };+ const limit = Math.min(REVIEW_BATCH, Math.floor((budget - 1) / SUBREQUESTS_PER_REVIEW));+ if (limit < 1) return reviewed;+ const candidates = await comments.reviewCandidates({+ limit, settleSeconds: REVIEW_SETTLE_SECONDS, maxChecks: REVIEW_MAX_CHECKS, recheckSeconds: REVIEW_RECHECK_SECONDS,+ });+ for (const candidate of candidates) {+ if (signal.aborted) break;+ try {+ const result = await lookFor(candidate);+ await comments.recordReview(candidate.id, result);+ if (result.found) reviewed.found++;+ else reviewed.notFound++;+ } catch (err) {+ // an Instagram error is a check that could not be made; it counts, so a broken conversation is not asked forever+ reviewed.failed++;+ const reason = redactUrls((err as Error).message ?? 'unknown error').slice(0, 200);+ log.warn('automation review check failed', { commentRowId: candidate.id, ...errorFields(err) });+ await comments.recordReview(candidate.id, { found: false, note: `Twiligent could not read the conversation on Instagram (${reason}). Check it yourself before you retry.` })+ .catch(recordErr => log.error('automation review not recorded', { commentRowId: candidate.id, ...errorFields(recordErr) }));+ }+ }+ return reviewed;+ }++ return {+ async run(now = Date.now()) {+ const expired = await comments.expireDue(EXPIRE_BATCH);+ // expiry, the candidate list and the health read take three of the run's subrequests+ const reviewed = await review(FREE_PLAN_SUBREQUESTS - 3);+ const health = await comments.health(CLAIM_LEASE_SECONDS);+ log.info('automation reconcile', { expired, reviewed, health: { ...health } });+ const warning = healthWarning(health, now);+ if (warning) log.warn(warning, { due: health.due, stale: health.stale, oldestDueAt: health.oldestDueAt });+ return { expired, reviewed, health };+ },+ };+}diff --git a/backend/services/automationService.ts b/backend/services/automationService.tsindex 436962f..67304fa 100644--- a/backend/services/automationService.ts+++ b/backend/services/automationService.ts@@ -1,15 +1,18 @@-import { subscribeToComments } from './instagram/instagramMessaging.ts';-import { coversMedia, matchedKeyword } from '../lib/automationMatching.ts';-import { MAX_MESSAGE_BYTES, composeReply, messageBytes } from '../lib/automationDelivery.ts';-import { ConflictError, NotFoundError, ValidationError } from '../lib/errors.ts';+import { subscribeToWebhooks } from './instagram/instagramMessaging.ts';+import { coversMedia, ruleMatch } from '../lib/automationMatching.ts';+import { followTextsProblem, keywordsProblem } from '../lib/automationRules.ts';+import { MAX_MESSAGE_BYTES, composeReply, messageBytes, replyMessage } from '../lib/automationDelivery.ts';+import { ConflictError, NotFoundError, UpstreamError, ValidationError } from '../lib/errors.ts';import { newRowId } from '../lib/ids.ts';import { errorFields } from '../lib/logger.ts';import { defaultControls } from '../repositories/automationAccountRepository.ts';import type { AccountRepository } from '../repositories/accountRepository.ts';import type { AutomationAccountControls, AutomationAccountRepository } from '../repositories/automationAccountRepository.ts';import type { AutomationCommentRepository } from '../repositories/automationCommentRepository.ts';+import type { AutomationFollowupRepository } from '../repositories/automationFollowupRepository.ts';import type { AutomationRuleRepository } from '../repositories/automationRuleRepository.ts';import type { AuditRepository } from '../repositories/auditRepository.ts';+import type { WebhookField } from './instagram/instagramMessaging.ts';import type { ActivityQuery, StatsQuery } from '../validators/automationValidators.ts';import type { AutomationConfig } from '../lib/config.ts';import type { RequestContext } from '../types/context.ts';@@ -23,6 +26,7 @@ export interface AutomationServiceDeps {accounts: AccountRepository;rules: AutomationRuleRepository;comments: AutomationCommentRepository;+ followups: AutomationFollowupRepository;automationAccounts: AutomationAccountRepository;audit: AuditRepository;automation: AutomationConfig;@@ -48,6 +52,12 @@ export interface StatsPeriod {export type AutomationTestResult = Omit<AutomationTestResponse, 'success'>;+// a retried item, and the follow-up to send when the retry was for the message after the person's answer+export interface RetryResult {+ item: AutomationActivityItem;+ followupId: string | null;+}+export interface AutomationService {overview(userId: string): Promise<AutomationOverview>;createRule(userId: string, input: AutomationRuleRequest): Promise<AutomationRule>;@@ -57,7 +67,7 @@ export interface AutomationService {test(input: AutomationTestRequest): AutomationTestResult;activity(userId: string, query: ActivityQuery): Promise<ActivityPage>;stats(userId: string, query: StatsQuery): Promise<StatsPeriod>;- retry(userId: string, commentRowId: string): Promise<AutomationActivityItem>;+ retry(userId: string, commentRowId: string): Promise<RetryResult>;setPaused(userId: string, accountId: string, paused: boolean): Promise<AutomationAccountState>;subscribe(userId: string, accountId: string): Promise<AutomationAccountState>;}@@ -68,6 +78,13 @@ const DAY_MS = 24 * 60 * 60 * 1000;const MAX_NAME = 80;const COPY_SUFFIX = ' (copy)';+const future = (at: string | null) => (at && Date.parse(at) > Date.now() ? at : null);++// a subscription made before fields were recorded asked for comments only+function subscribedFieldsOf(controls: AutomationAccountControls): string[] {+ return controls.subscribedAt ? controls.subscribedFields ?? ['comments'] : [];+}+function toState(account: Account, controls: AutomationAccountControls): AutomationAccountState {return {accountId: account.id,@@ -75,9 +92,11 @@ function toState(account: Account, controls: AutomationAccountControls): AutomatprofilePictureUrl: account.profilePictureUrl ?? '',// a hold the Worker set shows as paused, with its reason in place of a cooldown reasonpaused: controls.paused,- cooldownUntil: controls.cooldownUntil && Date.parse(controls.cooldownUntil) > Date.now() ? controls.cooldownUntil : null,+ cooldownUntil: future(controls.cooldownUntil),cooldownReason: controls.pausedReason ?? controls.cooldownReason,subscribedAt: controls.subscribedAt,+ limitedUntil: future(controls.limitedUntil),+ messagesSubscribed: subscribedFieldsOf(controls).includes('messages'),};}@@ -88,9 +107,43 @@ function checkMessageSize(replyText: string, linkUrl: string | null): void {}}+// the request to follow and the reminder are sent as they are, so each must fit one Instagram message+function checkFollowTexts(rule: { followPromptText: string | null; notFollowingText: string | null }): void {+ for (const [label, text] of [['The message asking people to follow', rule.followPromptText], ['The reminder', rule.notFollowingText]] as const) {+ const bytes = text ? messageBytes(text) : 0;+ if (bytes > MAX_MESSAGE_BYTES) throw new ValidationError(`${label} is ${bytes} bytes; Instagram accepts at most ${MAX_MESSAGE_BYTES}. Shorten it.`);+ }+}++// what a rule will look like once saved, checked across fields: keywords against the match mode, and the+// followers-only messages; switching to any comment clears the keywords, since such a rule takes none+function resolveChanges(current: AutomationRule, changes: AutomationRuleUpdateRequest): AutomationRuleUpdateRequest {+ const matchMode = changes.matchMode ?? current.matchMode;+ const resolved = { ...changes };+ if (matchMode === 'any' && changes.keywords === undefined && current.keywords.length > 0) resolved.keywords = [];+ const keywords = resolved.keywords ?? current.keywords;+ const keywordProblem = keywordsProblem(matchMode, keywords);+ if (keywordProblem) throw new ValidationError(keywordProblem);+ const merged = {+ requireFollow: resolved.requireFollow ?? current.requireFollow,+ followPromptText: resolved.followPromptText === undefined ? current.followPromptText : resolved.followPromptText,+ notFollowingText: resolved.notFollowingText === undefined ? current.notFollowingText : resolved.notFollowingText,+ };+ const followProblem = followTextsProblem(merged);+ if (followProblem) throw new ValidationError(followProblem);+ checkFollowTexts(merged);+ return resolved;+}++// Instagram sends every message to the webhook once messages are subscribed, so they are asked for only while an+// enabled rule of the account needs them+function fieldsFor(accountRules: AutomationRule[]): WebhookField[] {+ return accountRules.some(rule => rule.enabled && rule.requireFollow) ? ['comments', 'messages'] : ['comments'];+}+// the user's rules, the controls of their Instagram accounts, and the API that lists, tests and retries repliesexport function createAutomationService(deps: AutomationServiceDeps): AutomationService {- const { accounts, rules, comments, automationAccounts, audit, automation, context } = deps;+ const { accounts, rules, comments, followups, automationAccounts, audit, automation, context } = deps;async function instagramAccount(userId: string, accountId: string): Promise<Account> {const account = await accounts.findForUser(accountId, userId);@@ -108,25 +161,43 @@ export function createAutomationService(deps: AutomationServiceDeps): Automationreturn toState(account, await automationAccounts.findForUser(account.id, userId) ?? defaultControls(account.id));}- async function subscribeAccount(userId: string, account: Account): Promise<AutomationAccountControls> {+ async function wantedFields(userId: string, accountId: string): Promise<WebhookField[]> {+ return fieldsFor((await rules.listForUser(userId)).filter(rule => rule.accountId === accountId));+ }++ // messages need the instagram_business_manage_messages permission and the field selected in the Meta dashboard;+ // when Instagram refuses them, comments alone still keep keyword rules working+ async function subscribeAccount(userId: string, account: Account, fields: WebhookField[]): Promise<AutomationAccountControls> {if (!account.accessToken || !account.igUserId) {throw new ValidationError('This Instagram account has no access token. Reconnect it on the Accounts page.');}- await subscribeToComments(account.igUserId, account.accessToken, context.signal);- const controls = await automationAccounts.markSubscribedForUser(account.id, userId);- await audit.recordForUser(userId, { action: 'automation_account.subscribed', subjectType: 'automation_account', subjectId: account.id });+ let granted = fields;+ try {+ await subscribeToWebhooks(account.igUserId, account.accessToken, fields, context.signal);+ } catch (err) {+ if (!fields.includes('messages') || !(err instanceof UpstreamError)) throw err;+ context.log.warn('message webhook subscription refused; comments only', { accountId: account.id, ...errorFields(err) });+ granted = ['comments'];+ await subscribeToWebhooks(account.igUserId, account.accessToken, granted, context.signal);+ }+ const controls = await automationAccounts.markSubscribedForUser(account.id, userId, granted);+ await audit.recordForUser(userId, {+ action: 'automation_account.subscribed', subjectType: 'automation_account', subjectId: account.id, details: { fields: granted },+ });return controls;}- // turning a rule on is also when Instagram is asked for the account's comments; if that fails the rule is still- // saved, and the page shows the account as not receiving comments with a button to try again+ // saving an enabled rule is also when Instagram is asked for the account's events; if that fails the rule is still+ // saved, and the page shows the account as not receiving comments or messages with a button to try againasync function ensureSubscribed(userId: string, account: Account): Promise<void> {- const controls = await automationAccounts.findForUser(account.id, userId);- if (controls?.subscribedAt) return;+ const controls = await automationAccounts.findForUser(account.id, userId) ?? defaultControls(account.id);+ const fields = await wantedFields(userId, account.id);+ const current = subscribedFieldsOf(controls);+ if (fields.length === current.length && fields.every(field => current.includes(field))) return;try {- await subscribeAccount(userId, account);+ await subscribeAccount(userId, account, fields);} catch (err) {- context.log.warn('comment webhook subscription failed', { accountId: account.id, ...errorFields(err) });+ context.log.warn('webhook subscription failed', { accountId: account.id, fields, ...errorFields(err) });}}@@ -154,12 +225,18 @@ export function createAutomationService(deps: AutomationServiceDeps): Automationasync createRule(userId, input) {const account = await instagramAccount(userId, input.accountId);checkMessageSize(input.replyText, input.linkUrl ?? null);+ const follow = {+ requireFollow: input.requireFollow ?? false,+ followPromptText: input.followPromptText ?? null,+ notFollowingText: input.notFollowingText ?? null,+ };+ checkFollowTexts(follow);const now = new Date().toISOString();const rule = await rules.create({id: newRowId(),accountId: account.id,name: input.name,- keywords: input.keywords,+ keywords: input.matchMode === 'any' ? [] : input.keywords,matchMode: input.matchMode ?? 'contains',caseSensitive: input.caseSensitive ?? false,mediaIds: input.mediaIds ?? [],@@ -167,12 +244,13 @@ export function createAutomationService(deps: AutomationServiceDeps): AutomationlinkUrl: input.linkUrl ?? null,enabled: input.enabled ?? false,hourlyLimit: input.hourlyLimit ?? null,+ ...follow,createdAt: now,updatedAt: now,}, userId);await audit.recordForUser(userId, {action: 'automation_rule.created', subjectType: 'automation_rule', subjectId: rule.id,- details: { accountId: account.id, enabled: rule.enabled },+ details: { accountId: account.id, enabled: rule.enabled, matchMode: rule.matchMode, requireFollow: rule.requireFollow },});if (rule.enabled) await ensureSubscribed(userId, account);return rule;@@ -181,13 +259,17 @@ export function createAutomationService(deps: AutomationServiceDeps): Automationasync updateRule(userId, id, changes) {const current = await ownedRule(userId, id);checkMessageSize(changes.replyText ?? current.replyText, changes.linkUrl === undefined ? current.linkUrl : changes.linkUrl);- const rule = await rules.updateForUser(id, changes, userId);+ const resolved = resolveChanges(current, changes);+ const rule = await rules.updateForUser(id, resolved, userId);if (!rule) throw new NotFoundError('Automation rule not found');await audit.recordForUser(userId, {action: 'automation_rule.updated', subjectType: 'automation_rule', subjectId: id,- details: { fields: Object.keys(changes), enabled: rule.enabled },+ details: { fields: Object.keys(resolved), enabled: rule.enabled },});- if (rule.enabled && !current.enabled) await ensureSubscribed(userId, await instagramAccount(userId, rule.accountId));+ // turning a rule on, or switching the followers-only option, can change the events the account needs+ if (rule.enabled !== current.enabled || rule.requireFollow !== current.requireFollow) {+ await ensureSubscribed(userId, await instagramAccount(userId, rule.accountId));+ }return rule;},@@ -221,9 +303,14 @@ export function createAutomationService(deps: AutomationServiceDeps): AutomationcaseSensitive: input.caseSensitive ?? false,mediaIds: input.mediaIds ?? [],};- const message = composeReply(input.replyText, input.linkUrl ?? null);- const keyword = coversMedia(rule, input.mediaId ?? null) ? matchedKeyword(input.comment, rule) : null;- return { matched: keyword !== null, keyword, message, messageBytes: messageBytes(message), maxMessageBytes: MAX_MESSAGE_BYTES };+ const message = replyMessage({+ requireFollow: input.requireFollow ?? false,+ followPromptText: input.followPromptText ?? null,+ replyText: input.replyText,+ linkUrl: input.linkUrl ?? null,+ });+ const match = coversMedia(rule, input.mediaId ?? null) ? ruleMatch(input.comment, rule) : null;+ return { matched: match !== null, keyword: match?.keyword ?? null, message, messageBytes: messageBytes(message), maxMessageBytes: MAX_MESSAGE_BYTES };},async activity(userId, query) {@@ -240,15 +327,24 @@ export function createAutomationService(deps: AutomationServiceDeps): Automationreturn { from, to, stats };},+ // a failed reply is retried itself; on an accepted followers-only reply, the retry is for the message after the+ // person's answerasync retry(userId, commentRowId) {const item = await comments.requeueForUser(commentRowId, userId);- if (!item) {- const existing = await comments.findForUser(commentRowId, userId);- if (!existing) throw new NotFoundError('Activity item not found');- throw new ConflictError('Only a failed, skipped or review item inside the 7 days Instagram allows can be retried');+ if (item) {+ await audit.recordForUser(userId, { action: 'automation_comment.retried', subjectType: 'automation_comment', subjectId: commentRowId });+ return { item, followupId: null };}- await audit.recordForUser(userId, { action: 'automation_comment.retried', subjectType: 'automation_comment', subjectId: commentRowId });- return item;+ const existing = await comments.findForUser(commentRowId, userId);+ if (!existing) throw new NotFoundError('Activity item not found');+ const followupId = existing.status === 'accepted' ? await followups.requeueLatestForUser(commentRowId, userId) : null;+ if (!followupId) {+ throw new ConflictError('Only a failed, skipped or review item inside the time Instagram allows can be retried: 7 days for a reply, 24 hours after the person\'s answer for a follow-up');+ }+ await audit.recordForUser(userId, {+ action: 'automation_comment.retried', subjectType: 'automation_comment', subjectId: commentRowId, details: { followupId },+ });+ return { item: await comments.findForUser(commentRowId, userId) ?? existing, followupId };},async setPaused(userId, accountId, paused) {@@ -264,7 +360,7 @@ export function createAutomationService(deps: AutomationServiceDeps): Automationasync subscribe(userId, accountId) {const account = await instagramAccount(userId, accountId);- await subscribeAccount(userId, account);+ await subscribeAccount(userId, account, await wantedFields(userId, account.id));return state(userId, account);},};diff --git a/backend/services/automationWebhookService.ts b/backend/services/automationWebhookService.tsindex 97ca962..19365d7 100644--- a/backend/services/automationWebhookService.ts+++ b/backend/services/automationWebhookService.ts@@ -8,11 +8,14 @@ import type { WebhookVerification } from '../validators/automationValidators.ts'import type { AutomationConfig } from '../lib/config.ts';import type { AutomationRuleRepository, WebhookRule } from '../repositories/automationRuleRepository.ts';import type { AutomationCommentRepository, NewAutomationComment } from '../repositories/automationCommentRepository.ts';+import type { AutomationFollowupRepository } from '../repositories/automationFollowupRepository.ts';+import type { InstagramMessageEvent } from '../validators/instagramWebhookValidators.ts';import type { RequestContext } from '../types/context.ts';export interface AutomationWebhookDeps {rules: AutomationRuleRepository;comments: AutomationCommentRepository;+ followups: AutomationFollowupRepository;automation: AutomationConfig;context: RequestContext;}@@ -22,6 +25,8 @@ export interface IngestResult {duplicates: number;// the new comments that matched a rule, for the request to start sending right awayqueuedIds: string[];+ // follow-ups for people who answered a followers-only reply+ followupIds: string[];// database calls the intake made, which count against the request's subrequestssubrequests: number;}@@ -65,7 +70,7 @@ function classify(event: InstagramCommentEvent, rules: WebhookRule[]): NewAutoma}// stores what a webhook delivered before it is acknowledged; comments for accounts without an enabled rule are not kept-export function createAutomationWebhookService({ rules, comments, automation, context }: AutomationWebhookDeps): AutomationWebhookService {+export function createAutomationWebhookService({ rules, comments, followups, automation, context }: AutomationWebhookDeps): AutomationWebhookService {return {// Meta checks the callback by sending the Verify Token from its dashboard and expects the challenge backasync challengeAnswer({ mode, verifyToken, challenge }) {@@ -81,6 +86,8 @@ export function createAutomationWebhookService({ rules, comments, automation, coasync ingest(webhook) {const byAccount = new Map<string, InstagramCommentEvent[]>();for (const event of webhook.comments) byAccount.set(event.igUserId, [...(byAccount.get(event.igUserId) ?? []), event]);+ const messagesByAccount = new Map<string, InstagramMessageEvent[]>();+ for (const event of webhook.messages) messagesByAccount.set(event.igUserId, [...(messagesByAccount.get(event.igUserId) ?? []), event]);const rows: NewAutomationComment[] = [];let subrequests = 0;@@ -100,13 +107,25 @@ export function createAutomationWebhookService({ rules, comments, automation, coconst inserted = await comments.insertMany(rows);const queuedIds = inserted.filter(row => row.status === 'queued').map(row => row.id);if (rows.length > 0) subrequests++;- const result = { stored: inserted.length, duplicates: rows.length - inserted.length, queuedIds, subrequests };++ // a message only matters when its sender is waiting on a followers-only reply; the database decides that in+ // one call per account, and messages delivered again insert nothing+ const followupIds: string[] = [];+ for (const [igUserId, events] of messagesByAccount) {+ const incoming = events.map(event => ({ id: newRowId(), senderId: event.senderId, messageId: event.messageId, sentAt: new Date(event.sentAt).toISOString() }));+ followupIds.push(...await followups.insertForMessages(igUserId, incoming));+ subrequests++;+ }++ const result = { stored: inserted.length, duplicates: rows.length - inserted.length, queuedIds, followupIds, subrequests };context.log.info('instagram webhook stored', {comments: webhook.comments.length,+ messages: webhook.messages.length,unsupported: webhook.unsupported,stored: result.stored,duplicates: result.duplicates,queued: queuedIds.length,+ followups: followupIds.length,});return result;},diff --git a/backend/services/instagram/instagramMessaging.ts b/backend/services/instagram/instagramMessaging.tsindex a502a40..e36ccce 100644--- a/backend/services/instagram/instagramMessaging.ts+++ b/backend/services/instagram/instagramMessaging.ts@@ -1,16 +1,21 @@-import { buildGraphUrl, igPost } from './instagramApi.ts';+import { buildGraphUrl, igFetch, igPost } from './instagramApi.ts';import { UpstreamError, isAbortError } from '../../lib/errors.ts';import { redactUrls } from '../../lib/redact.ts';-import { SEND_TIMEOUT_MS } from '../../lib/automationDelivery.ts';-import type { SendResult } from '../../lib/automationDelivery.ts';+import { FOLLOW_CHECK_TIMEOUT_MS, SEND_TIMEOUT_MS, classifySendError } from '../../lib/automationDelivery.ts';+import type { FollowCheck, SendResult } from '../../lib/automationDelivery.ts';+import type { ConversationMessage } from '../../lib/automationReview.ts';import type { InstagramApiErrorBody } from './instagramApi.ts';// the Workers runtime refuses a fetch past the run's subrequest allowance before anything leavesconst SUBREQUEST_LIMIT = /too many subrequests/i;-// the webhook fields the automation needs; Instagram sends every field the app subscribes to in the Meta dashboard-const SUBSCRIBED_FIELDS = 'comments';-interface PrivateReplyBody extends InstagramApiErrorBody {+// a private reply names the comment; a message inside the 24 hour window names the person+export type MessageRecipient = { comment_id: string } | { id: string };++// the webhook fields the automation can ask for; Instagram sends only the fields the app selected in the Meta dashboard+export type WebhookField = 'comments' | 'messages';++interface SendBody extends InstagramApiErrorBody {recipient_id?: string;message_id?: string;}@@ -19,16 +24,28 @@ interface SubscribeBody {success?: boolean;}+interface FollowStatusBody extends InstagramApiErrorBody {+ is_user_follow_business?: boolean;+}++interface ConversationListBody {+ data?: { id?: string }[];+}++interface ConversationBody {+ messages?: { data?: { id?: string; created_time?: string; from?: { id?: string }; message?: string }[] };+}+// answers instead of throwing, because each failure needs its code to decide between retrying, waiting and stopping;// the request is never repeated here, since a repeat after a lost answer could message the person twice. Only its own// timeout can cut it off: the caller starts a send only with that much time left, so a run's deadline never makes one ambiguous-export async function sendPrivateReply(igUserId: string, accessToken: string, commentId: string, text: string): Promise<SendResult> {+export async function sendMessage(igUserId: string, accessToken: string, recipient: MessageRecipient, text: string): Promise<SendResult> {let response: Response;try {response = await fetch(buildGraphUrl(`/${igUserId}/messages`).toString(), {method: 'POST',headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${accessToken}` },- body: JSON.stringify({ recipient: { comment_id: commentId }, message: { text } }),+ body: JSON.stringify({ recipient, message: { text } }),signal: AbortSignal.timeout(SEND_TIMEOUT_MS),});} catch (err) {@@ -37,16 +54,16 @@ export async function sendPrivateReply(igUserId: string, accessToken: string, co}const usageHeader = response.headers.get('x-business-use-case-usage');- let body: PrivateReplyBody;+ let body: SendBody;try {- body = await response.json() as PrivateReplyBody;+ body = await response.json() as SendBody;} catch {// an accepted request whose answer cannot be read may still have delivered the messageif (response.ok) return { kind: 'ambiguous', message: 'its answer could not be read' };return { kind: 'error', httpStatus: response.status, message: `HTTP ${response.status}`, usageHeader };}- if (response.ok && !body.error) return { kind: 'accepted', messageId: body.message_id ?? null };+ if (response.ok && !body.error) return { kind: 'accepted', messageId: body.message_id ?? null, recipientId: body.recipient_id ?? null };const error = body.error ?? {};return {kind: 'error',@@ -58,8 +75,54 @@ export async function sendPrivateReply(igUserId: string, accessToken: string, co};}-// asks Instagram to send this account's comments to the app's webhook-export async function subscribeToComments(igUserId: string, accessToken: string, signal?: AbortSignal): Promise<void> {- const result = await igPost<SubscribeBody>(`/${igUserId}/subscribed_apps`, { subscribed_fields: SUBSCRIBED_FIELDS, access_token: accessToken }, signal);+// one private reply to a comment; Instagram allows one per comment, within 7 days of it+export function sendPrivateReply(igUserId: string, accessToken: string, commentId: string, text: string): Promise<SendResult> {+ return sendMessage(igUserId, accessToken, { comment_id: commentId }, text);+}++// Instagram reports whether a person follows the account only after they have messaged it (User Profile API consent),+// so this is asked when they answer a followers-only reply; a read, so asking again is always safe+export async function readFollowStatus(igsid: string, accessToken: string): Promise<FollowCheck> {+ let response: Response;+ try {+ response = await fetch(buildGraphUrl(`/${igsid}`, { fields: 'is_user_follow_business' }).toString(), {+ headers: { Authorization: `Bearer ${accessToken}` },+ signal: AbortSignal.timeout(FOLLOW_CHECK_TIMEOUT_MS),+ });+ } catch (err) {+ return { kind: 'retry', message: isAbortError(err) ? 'the request timed out' : 'the connection failed' };+ }+ let body: FollowStatusBody;+ try {+ body = await response.json() as FollowStatusBody;+ } catch {+ return { kind: 'retry', message: `HTTP ${response.status}` };+ }+ if (response.ok && !body.error) {+ if (typeof body.is_user_follow_business === 'boolean') return { kind: body.is_user_follow_business ? 'following' : 'not_following' };+ return { kind: 'unverifiable', message: 'its answer had no follow status' };+ }+ const error = body.error ?? {};+ const message = redactUrls(error.message || body.error_message || `HTTP ${response.status}`);+ const kind = classifySendError({ code: error.code, subcode: error.error_subcode, httpStatus: response.status, message });+ if (kind === 'rate_limited' || kind === 'blocked' || kind === 'transient') return { kind: 'retry', message };+ if (kind === 'not_authorized') return { kind: 'not_authorized', message };+ return { kind: 'unverifiable', message };+}++// the account's latest messages with one person, newest first; Instagram returns the details of the 20 most recent+export async function listConversationMessages(igUserId: string, accessToken: string, igsid: string, signal?: AbortSignal): Promise<ConversationMessage[]> {+ const conversations = await igFetch<ConversationListBody>(`/${igUserId}/conversations`, { platform: 'instagram', user_id: igsid, access_token: accessToken }, 0, signal);+ const conversationId = conversations.data?.[0]?.id;+ if (!conversationId) return [];+ const conversation = await igFetch<ConversationBody>(`/${conversationId}`, { fields: 'messages{id,created_time,from,message}', access_token: accessToken }, 0, signal);+ return (conversation.messages?.data ?? [])+ .filter(message => message.id && message.created_time)+ .map(message => ({ id: message.id!, createdTime: message.created_time!, fromId: message.from?.id ?? null, text: message.message ?? null }));+}++// asks Instagram to send this account's events to the app's webhook; the list replaces what was asked before+export async function subscribeToWebhooks(igUserId: string, accessToken: string, fields: WebhookField[], signal?: AbortSignal): Promise<void> {+ const result = await igPost<SubscribeBody>(`/${igUserId}/subscribed_apps`, { subscribed_fields: fields.join(','), access_token: accessToken }, signal);if (result.success !== true) throw new UpstreamError('Instagram did not confirm the webhook subscription for this account. Try again in a moment.');}diff --git a/backend/services/retentionService.ts b/backend/services/retentionService.tsindex 7354045..8612873 100644--- a/backend/services/retentionService.ts+++ b/backend/services/retentionService.ts@@ -11,10 +11,17 @@ export interface RetentionDeps {export interface RetentionRun {comments: number;auditEvents: number;+ // more old comments are left for the next day's run+ commentsLeft: boolean;+}++export interface RetentionOptions {+ // database calls the run may make for comments, after the token refresh took its share+ commentBatches?: number;}export interface RetentionService {- purge(now?: number): Promise<RetentionRun>;+ purge(now?: number, options?: RetentionOptions): Promise<RetentionRun>;}const DAY_MS = 24 * 60 * 60 * 1000;@@ -22,14 +29,27 @@ const DAY_MS = 24 * 60 * 60 * 1000;export const COMMENT_RETENTION_DAYS = 90;// who connected, removed or changed what is kept a yearexport const AUDIT_RETENTION_DAYS = 365;+// one delete stays short however much built up; twenty batches clear 20,000 comments a day+export const COMMENT_PURGE_BATCH = 1000;+const DEFAULT_COMMENT_BATCHES = 20;-// the daily cron's deletes across all users; a comment's attempts go with it through the foreign key+// the daily cron's deletes across all users; a comment's attempts and follow-ups go with it through the foreign keysexport function createRetentionService({ comments, audit, context }: RetentionDeps): RetentionService {return {- async purge(now = Date.now()) {+ async purge(now = Date.now(), { commentBatches = DEFAULT_COMMENT_BATCHES } = {}) {+ const cutoff = new Date(now - COMMENT_RETENTION_DAYS * DAY_MS).toISOString();+ let deleted = 0;+ let commentsLeft = false;+ for (let batch = 0; batch < commentBatches; batch++) {+ const count = await comments.purgeCreatedBefore(cutoff, COMMENT_PURGE_BATCH);+ deleted += count;+ commentsLeft = count === COMMENT_PURGE_BATCH;+ if (!commentsLeft || context.signal.aborted) break;+ }const run = {- comments: await comments.deleteCreatedBefore(new Date(now - COMMENT_RETENTION_DAYS * DAY_MS).toISOString()),+ comments: deleted,auditEvents: await audit.deleteCreatedBefore(new Date(now - AUDIT_RETENTION_DAYS * DAY_MS).toISOString()),+ commentsLeft,};context.log.info('retention purge', { ...run });return run;diff --git a/backend/tests/fixtures/fakeAutomationQueue.ts b/backend/tests/fixtures/fakeAutomationQueue.tsindex 8e61554..03a5f52 100644--- a/backend/tests/fixtures/fakeAutomationQueue.ts+++ b/backend/tests/fixtures/fakeAutomationQueue.ts@@ -1,8 +1,10 @@-// an in-memory twin of claim_automation_comments, reserve_automation_send, finish_automation_send and the release update,-// following the same rules as the SQL in supabase/migrations (checked there on a local Postgres), so the processor can be-// run against concurrency, limits and crashes without a database-import type { AutomationCommentRepository, ClaimedComment, NewAutomationComment } from '../../repositories/automationCommentRepository.ts';-import type { AutomationCommentStatus } from '../../../shared/types/automation.ts';+// an in-memory twin of the reply queue's database functions (claim_automation_comments, reserve_automation_send,+// finish_automation_send, the follow-up functions, expiry and review) and the release updates, following the same rules+// as the SQL in supabase/migrations (checked there on a local Postgres), so the processors can be run against+// concurrency, limits and crashes without a database+import type { AutomationCommentRepository, ClaimedComment, NewAutomationComment, ReviewResult } from '../../repositories/automationCommentRepository.ts';+import type { AutomationFollowupRepository, ClaimedFollowup } from '../../repositories/automationFollowupRepository.ts';+import type { AutomationCommentStatus, AutomationFollowupKind, AutomationFollowupStatus, AutomationGateStatus } from '../../../shared/types/automation.ts';export interface QueueRow {id: string;@@ -19,17 +21,25 @@ export interface QueueRow {nextAttemptAt: string | null;claimedAt: string | null;messageId: string | null;+ acceptedAt: string | null;+ recipientId: string | null;+ gateStatus: AutomationGateStatus | null;+ gatePrompts: number;+ reviewChecks: number;expiresAt: string;}export interface QueueAttempt {id: string;commentRowId: string;+ followupId?: string;+ kind?: 'private_reply' | 'followup';userId: string;accountId: string;ruleId: string | null;recipientId: string | null;outcome: string;+ digest?: string | null;startedAt: number;}@@ -39,40 +49,78 @@ export interface QueueRule {replyText: string;linkUrl: string | null;hourlyLimit: number | null;+ requireFollow?: boolean;+ followPromptText?: string | null;+ notFollowingText?: string | null;}export interface QueueControls {paused: boolean;pausedReason: string | null;cooldownUntil: string | null;+ limitedUntil?: string | null;+}++export interface FollowupRow {+ id: string;+ userId: string;+ accountId: string;+ commentRowId: string;+ igUserId: string;+ recipientId: string;+ triggerMessageId: string;+ status: AutomationFollowupStatus;+ statusReason: string | null;+ errorMessage: string | null;+ kind: AutomationFollowupKind | null;+ attempts: number;+ nextAttemptAt: string | null;+ claimedAt: string | null;+ messageId: string | null;+ windowExpiresAt: string;}export interface FakeQueue extends AutomationCommentRepository {rows: QueueRow[];attempts: QueueAttempt[];+ followupRows: FollowupRow[];rules: Map<string, QueueRule>;controls: Map<string, QueueControls>;tokens: Map<string, string | null>;+ reviews: { id: string; result: ReviewResult }[];+ // the same state seen through the follow-up repository+ followups: AutomationFollowupRepository;// makes the next calls of one method throw, as a database outage would- failNext(method: 'claim' | 'reserve' | 'finish' | 'release', times?: number): void;+ failNext(method: 'claim' | 'reserve' | 'finish' | 'release' | 'insertForMessages', times?: number): void;}const HOUR = 60 * 60 * 1000;+const OPEN: AutomationFollowupStatus[] = ['queued', 'processing', 'retry_wait', 'sending'];export function queueRow(id: string, overrides: Partial<QueueRow> = {}): QueueRow {return {id, userId: 'user-1', accountId: 'ig1', ruleId: 'rule-guide', igUserId: '1784', commentId: `c-${id}`, fromId: `fan-${id}`,status: 'queued', statusReason: null, errorMessage: null, attempts: 0, nextAttemptAt: new Date(Date.now() - 1000).toISOString(),- claimedAt: null, messageId: null, expiresAt: new Date(Date.now() + 6 * 24 * HOUR).toISOString(), ...overrides,+ claimedAt: null, messageId: null, acceptedAt: null, recipientId: null, gateStatus: null, gatePrompts: 0, reviewChecks: 0,+ expiresAt: new Date(Date.now() + 6 * 24 * HOUR).toISOString(), ...overrides,+ };+}++export function followupRow(id: string, commentRowId: string, overrides: Partial<FollowupRow> = {}): FollowupRow {+ return {+ id, userId: 'user-1', accountId: 'ig1', commentRowId, igUserId: '1784', recipientId: `igsid-${commentRowId}`, triggerMessageId: `mid-${id}`,+ status: 'queued', statusReason: null, errorMessage: null, kind: null, attempts: 0, nextAttemptAt: new Date(Date.now() - 1000).toISOString(),+ claimedAt: null, messageId: null, windowExpiresAt: new Date(Date.now() + 23 * HOUR).toISOString(), ...overrides,};}-export function fakeAutomationQueue(rows: QueueRow[] = []): FakeQueue {+export function fakeAutomationQueue(rows: QueueRow[] = [], followupRows: FollowupRow[] = []): FakeQueue {const failures = new Map<string, number>();const rules = new Map<string, QueueRule>([['rule-guide', { id: 'rule-guide', enabled: true, replyText: 'Here is your guide', linkUrl: 'https://example.com/guide', hourlyLimit: null }]]);const controls = new Map<string, QueueControls>();const tokens = new Map<string, string | null>([['ig1', 'TOKEN-1'], ['ig2', 'TOKEN-2']]);const attempts: QueueAttempt[] = [];+ const reviews: FakeQueue['reviews'] = [];function failing(method: string): void {const left = failures.get(method) ?? 0;@@ -84,20 +132,168 @@ export function fakeAutomationQueue(rows: QueueRow[] = []): FakeQueue {const now = () => Date.now();const iso = (ms: number) => new Date(ms).toISOString();- const isDue = (row: QueueRow, staleBefore: number) =>+ const isDue = (row: { status: string; nextAttemptAt: string | null; claimedAt: string | null }, staleBefore: number) =>((row.status === 'queued' || row.status === 'retry_wait') && Date.parse(row.nextAttemptAt!) <= now())|| (row.status === 'processing' && Date.parse(row.claimedAt!) < staleBefore);+ const dueAt = (row: { nextAttemptAt: string | null; claimedAt: string | null }) => Date.parse(row.nextAttemptAt ?? row.claimedAt!);+ const later = (at: string | null | undefined) => !!at && Date.parse(at) > now();++ // paused, cooling and limited accounts are left out, as the claim functions do+ function open(accountId: string, limits = true): boolean {+ const control = controls.get(accountId);+ if (!control) return true;+ return !control.paused && !later(control.cooldownUntil) && !(limits && later(control.limitedUntil));+ }++ // each account's oldest due jobs, then accounts take turns: first jobs of every account, then second jobs, ...+ function turns<T extends { id: string; accountId: string; nextAttemptAt: string | null; claimedAt: string | null }>(due: T[], limit: number, perAccount: number): T[] {+ const byAccount = new Map<string, T[]>();+ for (const row of [...due].sort((a, b) => dueAt(a) - dueAt(b))) {+ const list = byAccount.get(row.accountId) ?? [];+ if (list.length < perAccount) list.push(row);+ byAccount.set(row.accountId, list);+ }+ const ranked = [...byAccount.values()].flatMap(list => list.map((row, place) => ({ row, place })));+ return ranked.sort((a, b) => a.place - b.place || dueAt(a.row) - dueAt(b.row)).slice(0, limit).map(entry => entry.row);+ }++ function interrupt(staleBefore: number): void {+ for (const row of rows) {+ if (row.status === 'sending' && Date.parse(row.claimedAt!) < staleBefore) {+ Object.assign(row, { status: 'needs_review', statusReason: 'interrupted', claimedAt: null });+ attempts.filter(attempt => attempt.commentRowId === row.id && !attempt.followupId && attempt.outcome === 'sending').forEach(attempt => { attempt.outcome = 'ambiguous'; });+ }+ }+ for (const row of followupRows) {+ if (row.status === 'sending' && Date.parse(row.claimedAt!) < staleBefore) {+ Object.assign(row, { status: 'needs_review', statusReason: 'interrupted', claimedAt: null });+ attempts.filter(attempt => attempt.followupId === row.id && attempt.outcome === 'sending').forEach(attempt => { attempt.outcome = 'ambiguous'; });+ }+ }+ }function freeAt(window: QueueAttempt[], limit: number): string | null {return window.length >= limit ? iso(Math.min(...window.map(attempt => attempt.startedAt)) + HOUR) : null;}+ function controlsOf(accountId: string): QueueControls {+ const control = controls.get(accountId) ?? { paused: false, pausedReason: null, cooldownUntil: null, limitedUntil: null };+ controls.set(accountId, control);+ return control;+ }++ function applyAccountEffects(accountId: string, plan: { cooldownUntil: string | null; pauseReason: string | null }): void {+ const control = controlsOf(accountId);+ if (plan.cooldownUntil) control.cooldownUntil = control.cooldownUntil && control.cooldownUntil > plan.cooldownUntil ? control.cooldownUntil : plan.cooldownUntil;+ if (plan.pauseReason) Object.assign(control, { paused: true, pausedReason: plan.pauseReason });+ }++ const followups: AutomationFollowupRepository = {+ async insertForMessages(igUserId, messages) {+ failing('insertForMessages');+ const created: string[] = [];+ for (const message of [...messages].sort((a, b) => a.sentAt.localeCompare(b.sentAt))) {+ const sentAt = Date.parse(message.sentAt);+ const waiting = rows+ .filter(row => row.igUserId === igUserId && row.recipientId === message.senderId && row.gateStatus === 'awaiting_reply'+ && Date.parse(row.acceptedAt!) <= sentAt + 60_000 && Date.parse(row.acceptedAt!) > sentAt - 7 * 24 * HOUR)+ .sort((a, b) => Date.parse(b.acceptedAt!) - Date.parse(a.acceptedAt!))[0];+ if (!waiting) continue;+ if (followupRows.some(row => row.igUserId === igUserId && row.triggerMessageId === message.messageId)) continue;+ if (followupRows.some(row => row.commentRowId === waiting.id && OPEN.includes(row.status))) continue;+ followupRows.push(followupRow(message.id, waiting.id, {+ userId: waiting.userId, accountId: waiting.accountId, igUserId, recipientId: waiting.recipientId!, triggerMessageId: message.messageId,+ nextAttemptAt: iso(now() - 30_000), windowExpiresAt: iso(sentAt + 24 * HOUR),+ }));+ created.push(message.id);+ }+ return created;+ },++ async claim({ limit, leaseSeconds, ids }) {+ failing('claim');+ const staleBefore = now() - leaseSeconds * 1000;+ interrupt(staleBefore);+ const due = followupRows.filter(row => isDue(row, staleBefore) && (!ids || ids.includes(row.id)) && open(row.accountId, false));+ return turns(due, limit, limit).map((row): ClaimedFollowup => {+ Object.assign(row, { status: 'processing', claimedAt: iso(now()) });+ const comment = rows.find(candidate => candidate.id === row.commentRowId)!;+ const rule = comment.ruleId ? rules.get(comment.ruleId) : undefined;+ return {+ id: row.id, userId: row.userId, accountId: row.accountId, commentRowId: row.commentRowId, igUserId: row.igUserId,+ recipientId: row.recipientId, attempts: row.attempts, windowExpiresAt: row.windowExpiresAt, gateStatus: comment.gateStatus,+ gatePrompts: comment.gatePrompts, ruleEnabled: rule?.enabled ?? false, requireFollow: rule?.requireFollow ?? false,+ replyText: rule?.replyText ?? null, linkUrl: rule?.linkUrl ?? null, notFollowingText: rule?.notFollowingText ?? null,+ accessToken: tokens.get(row.accountId) ?? null,+ };+ });+ },++ async reserve(id, attemptId, kind, digest) {+ failing('reserve');+ const row = followupRows.find(candidate => candidate.id === id && candidate.status === 'processing');+ if (!row) return { outcome: 'gone', retryAt: null };+ const control = controls.get(row.accountId);+ if (control?.paused) return { outcome: 'paused', retryAt: null };+ if (later(control?.cooldownUntil)) return { outcome: 'cooldown', retryAt: control!.cooldownUntil };+ const comment = rows.find(candidate => candidate.id === row.commentRowId)!;+ Object.assign(row, { status: 'sending', claimedAt: iso(now()), attempts: row.attempts + 1, kind });+ attempts.push({+ id: attemptId, commentRowId: row.commentRowId, followupId: row.id, kind: 'followup', userId: row.userId, accountId: row.accountId,+ ruleId: comment.ruleId, recipientId: row.recipientId, outcome: 'sending', digest, startedAt: now(),+ });+ return { outcome: 'ok', retryAt: null };+ },++ async finish(id, attemptId, plan) {+ failing('finish');+ const row = followupRows.find(candidate => candidate.id === id+ && (candidate.status === 'sending' || (candidate.status === 'needs_review' && candidate.statusReason === 'interrupted')));+ if (!row) return false;+ Object.assign(row, {+ status: plan.status, statusReason: plan.reason, errorMessage: plan.errorMessage, messageId: plan.messageId ?? row.messageId,+ nextAttemptAt: plan.nextAttemptAt, claimedAt: null,+ });+ const attempt = attempts.find(candidate => candidate.id === attemptId && candidate.followupId === id);+ if (attempt) attempt.outcome = plan.outcome;+ const comment = rows.find(candidate => candidate.id === row.commentRowId)!;+ comment.gateStatus = plan.gateStatus ?? comment.gateStatus;+ if (plan.countReminder) comment.gatePrompts++;+ applyAccountEffects(row.accountId, plan);+ return true;+ },++ async release(id, plan) {+ failing('release');+ const row = followupRows.find(candidate => candidate.id === id && candidate.status === 'processing');+ if (!row) return false;+ Object.assign(row, { status: plan.status, statusReason: plan.reason, errorMessage: plan.errorMessage, nextAttemptAt: plan.nextAttemptAt, claimedAt: null });+ return true;+ },++ async returnUnstarted(ids) {+ for (const row of followupRows) {+ if (ids.includes(row.id) && row.status === 'processing') Object.assign(row, { status: 'queued', claimedAt: null, nextAttemptAt: iso(now() - 30_000) });+ }+ },++ async requeueLatestForUser(commentRowId, userId) {+ const latest = followupRows.filter(row => row.commentRowId === commentRowId && row.userId === userId).at(-1);+ if (!latest || !['failed', 'needs_review', 'skipped'].includes(latest.status) || Date.parse(latest.windowExpiresAt) <= now()) return null;+ Object.assign(latest, { status: 'queued', statusReason: 'retry', errorMessage: null, nextAttemptAt: iso(now() - 30_000), claimedAt: null });+ return latest.id;+ },+ };+const queue: FakeQueue = {rows,attempts,+ followupRows,rules,controls,tokens,+ reviews,+ followups,failNext(method, times = 1) { failures.set(method, times); },async insertMany(comments: NewAutomationComment[]) {@@ -115,46 +311,34 @@ export function fakeAutomationQueue(rows: QueueRow[] = []): FakeQueue {async claim({ limit, perAccount, leaseSeconds, ids }) {failing('claim');const staleBefore = now() - leaseSeconds * 1000;- for (const row of rows) {- if (row.status === 'sending' && Date.parse(row.claimedAt!) < staleBefore) {- Object.assign(row, { status: 'needs_review', statusReason: 'interrupted', claimedAt: null });- attempts.filter(attempt => attempt.commentRowId === row.id && attempt.outcome === 'sending').forEach(attempt => { attempt.outcome = 'ambiguous'; });- }- }- const perAccountCount = new Map<string, number>();- const due = rows- .filter(row => isDue(row, staleBefore) && (!ids || ids.includes(row.id)))- .sort((a, b) => Date.parse(a.nextAttemptAt ?? a.claimedAt!) - Date.parse(b.nextAttemptAt ?? b.claimedAt!));- const claimed: ClaimedComment[] = [];- for (const row of due) {- if (claimed.length >= limit) break;- const taken = perAccountCount.get(row.accountId) ?? 0;- if (taken >= perAccount) continue;- perAccountCount.set(row.accountId, taken + 1);+ interrupt(staleBefore);+ const due = rows.filter(row => isDue(row, staleBefore) && (!ids || ids.includes(row.id)) && open(row.accountId));+ return turns(due, limit, perAccount).map((row): ClaimedComment => {Object.assign(row, { status: 'processing', claimedAt: iso(now()) });const rule = row.ruleId ? rules.get(row.ruleId) : undefined;- claimed.push({+ return {id: row.id, userId: row.userId, accountId: row.accountId, ruleId: row.ruleId, igUserId: row.igUserId, commentId: row.commentId,fromId: row.fromId, attempts: row.attempts, expiresAt: row.expiresAt, ruleEnabled: rule?.enabled ?? false,replyText: rule?.replyText ?? null, linkUrl: rule?.linkUrl ?? null, accessToken: tokens.get(row.accountId) ?? null,- });- }- return claimed;+ requireFollow: rule?.requireFollow ?? false, followPromptText: rule?.followPromptText ?? null,+ };+ });},- async reserve(id, attemptId, limits) {+ async reserve(id, attemptId, limits, digest) {failing('reserve');const row = rows.find(candidate => candidate.id === id && candidate.status === 'processing');if (!row) return { outcome: 'gone', retryAt: null };const control = controls.get(row.accountId);if (control?.paused) return { outcome: 'paused', retryAt: null };- if (control?.cooldownUntil && Date.parse(control.cooldownUntil) > now()) return { outcome: 'cooldown', retryAt: control.cooldownUntil };- const otherReplies = new Set(attempts+ if (later(control?.cooldownUntil)) return { outcome: 'cooldown', retryAt: control!.cooldownUntil };+ const replies = attempts.filter(attempt => attempt.kind !== 'followup');+ const otherReplies = new Set(replies.filter(attempt => attempt.accountId === row.accountId && attempt.recipientId === row.fromId&& attempt.startedAt > now() - 24 * HOUR && attempt.commentRowId !== row.id).map(attempt => attempt.commentRowId));if (row.fromId && otherReplies.size >= limits.recipientDaily) return { outcome: 'recipient_limit', retryAt: null };- const lastHour = attempts.filter(attempt => attempt.startedAt > now() - HOUR);+ const lastHour = replies.filter(attempt => attempt.startedAt > now() - HOUR);const ruleLimit = row.ruleId ? rules.get(row.ruleId)?.hourlyLimit ?? null : null;const scopes: [ReturnType<typeof freeAt>, 'rule_limit' | 'account_limit' | 'user_limit' | 'global_limit'][] = [[ruleLimit === null ? null : freeAt(lastHour.filter(attempt => attempt.ruleId === row.ruleId), ruleLimit), 'rule_limit'],@@ -162,9 +346,16 @@ export function fakeAutomationQueue(rows: QueueRow[] = []): FakeQueue {[freeAt(lastHour.filter(attempt => attempt.userId === row.userId), limits.userHourly), 'user_limit'],[freeAt(lastHour, limits.globalHourly), 'global_limit'],];- for (const [retryAt, outcome] of scopes) if (retryAt) return { outcome, retryAt };+ for (const [retryAt, outcome] of scopes) {+ if (!retryAt) continue;+ if (outcome === 'account_limit') controlsOf(row.accountId).limitedUntil = retryAt;+ return { outcome, retryAt };+ }Object.assign(row, { status: 'sending', claimedAt: iso(now()), attempts: row.attempts + 1 });- attempts.push({ id: attemptId, commentRowId: row.id, userId: row.userId, accountId: row.accountId, ruleId: row.ruleId, recipientId: row.fromId, outcome: 'sending', startedAt: now() });+ attempts.push({+ id: attemptId, commentRowId: row.id, kind: 'private_reply', userId: row.userId, accountId: row.accountId, ruleId: row.ruleId,+ recipientId: row.fromId, outcome: 'sending', digest: digest ?? null, startedAt: now(),+ });return { outcome: 'ok', retryAt: null };},@@ -175,14 +366,12 @@ export function fakeAutomationQueue(rows: QueueRow[] = []): FakeQueue {if (!row) return false;Object.assign(row, {status: plan.status, statusReason: plan.reason, errorMessage: plan.errorMessage, messageId: plan.messageId ?? row.messageId,- nextAttemptAt: plan.nextAttemptAt, claimedAt: null,+ acceptedAt: plan.status === 'accepted' ? iso(now()) : row.acceptedAt, recipientId: plan.recipientId ?? row.recipientId,+ gateStatus: plan.gateStatus ?? row.gateStatus, nextAttemptAt: plan.nextAttemptAt, claimedAt: null,});const attempt = attempts.find(candidate => candidate.id === attemptId && candidate.commentRowId === id);if (attempt) attempt.outcome = plan.outcome;- const control = controls.get(row.accountId) ?? { paused: false, pausedReason: null, cooldownUntil: null };- if (plan.cooldownUntil) control.cooldownUntil = control.cooldownUntil && control.cooldownUntil > plan.cooldownUntil ? control.cooldownUntil : plan.cooldownUntil;- if (plan.pauseReason) Object.assign(control, { paused: true, pausedReason: plan.pauseReason });- controls.set(row.accountId, control);+ applyAccountEffects(row.accountId, plan);return true;},@@ -200,12 +389,61 @@ export function fakeAutomationQueue(rows: QueueRow[] = []): FakeQueue {}},+ async expireDue(limit) {+ const comments = rows.filter(row => (row.status === 'queued' || row.status === 'retry_wait') && Date.parse(row.expiresAt) <= now()).slice(0, limit);+ comments.forEach(row => Object.assign(row, { status: 'expired', statusReason: 'expired', nextAttemptAt: null }));+ const lapsed = followupRows.filter(row => (row.status === 'queued' || row.status === 'retry_wait') && Date.parse(row.windowExpiresAt) <= now()).slice(0, limit);+ lapsed.forEach(row => Object.assign(row, { status: 'expired', statusReason: 'expired', nextAttemptAt: null }));+ return { comments: comments.length, followups: lapsed.length };+ },++ async reviewCandidates({ limit, maxChecks }) {+ return rows+ .filter(row => row.status === 'needs_review' && (row.statusReason === 'no_answer' || row.statusReason === 'interrupted') && row.fromId && row.reviewChecks < maxChecks)+ .slice(0, limit)+ .map(row => {+ const attempt = attempts.filter(candidate => candidate.commentRowId === row.id && candidate.outcome === 'ambiguous' && !candidate.followupId).at(-1);+ return {+ id: row.id, igUserId: row.igUserId, fromId: row.fromId!, startedAt: iso(attempt?.startedAt ?? now()),+ messageDigest: attempt?.digest ?? null, accessToken: tokens.get(row.accountId) ?? null, reviewChecks: row.reviewChecks,+ };+ });+ },++ async recordReview(id, result) {+ reviews.push({ id, result });+ const row = rows.find(candidate => candidate.id === id && candidate.status === 'needs_review');+ if (!row) return false;+ row.reviewChecks++;+ if (result.found) {+ Object.assign(row, { status: 'accepted', statusReason: 'confirmed', errorMessage: null, messageId: result.messageId, acceptedAt: result.sentAt });+ attempts.filter(attempt => attempt.commentRowId === id && attempt.outcome === 'ambiguous').forEach(attempt => { attempt.outcome = 'accepted'; });+ } else {+ row.errorMessage = result.note;+ }+ return true;+ },++ async health() {+ const due = rows.filter(row => (row.status === 'queued' || row.status === 'retry_wait') && Date.parse(row.nextAttemptAt!) <= now());+ return {+ due: due.length,+ oldestDueAt: due.length > 0 ? iso(Math.min(...due.map(row => Date.parse(row.nextAttemptAt!)))) : null,+ waiting: rows.filter(row => row.status === 'queued' || row.status === 'retry_wait').length,+ stale: 0,+ needsReview: rows.filter(row => row.status === 'needs_review').length,+ followupsDue: followupRows.filter(row => row.status === 'queued' || row.status === 'retry_wait').length,+ pausedAccounts: [...controls.values()].filter(control => control.paused).length,+ limitedAccounts: [...controls.values()].filter(control => later(control.cooldownUntil) || later(control.limitedUntil)).length,+ };+ },+async listForUser() { return []; },async findForUser() { return null; },async requeueForUser() { return null; },async releaseHeldForAccount() {},async statsForUser() { return { comments: {}, attempts: {} }; },- async deleteCreatedBefore() { return 0; },+ async purgeCreatedBefore() { return 0; },};return queue;}diff --git a/backend/tests/jobs/scheduled.test.ts b/backend/tests/jobs/scheduled.test.tsindex e57a0e2..ad287b7 100644--- a/backend/tests/jobs/scheduled.test.ts+++ b/backend/tests/jobs/scheduled.test.ts@@ -1,16 +1,20 @@import { test } from 'node:test';import assert from 'node:assert/strict';import { readFileSync } from 'node:fs';-import { DAILY_CRON, EVERY_FIVE_MINUTES_CRON, cronPlan } from '../../jobs/scheduled.ts';+import { DAILY_CRON, EVERY_FIVE_MINUTES_CRON, EVERY_MINUTE_CRON, cronPlan } from '../../jobs/scheduled.ts';const at = (time: string) => Date.parse(`2026-10-16T${time}:00Z`);-test('the five minute trigger publishes on the quarter hour and sweeps the reply queue on every other run', () => {- assert.equal(cronPlan(EVERY_FIVE_MINUTES_CRON, at('12:00')), 'publish_then_sweep');- assert.equal(cronPlan(EVERY_FIVE_MINUTES_CRON, at('12:15')), 'publish_then_sweep');- assert.equal(cronPlan(EVERY_FIVE_MINUTES_CRON, at('12:45')), 'publish_then_sweep');- assert.equal(cronPlan(EVERY_FIVE_MINUTES_CRON, at('12:05')), 'sweep');- assert.equal(cronPlan(EVERY_FIVE_MINUTES_CRON, at('12:50')), 'sweep');+test('the every minute trigger dispatches due replies and follow-ups at every minute', () => {+ for (const time of ['12:00', '12:01', '12:15', '23:59']) assert.equal(cronPlan(EVERY_MINUTE_CRON, at(time)), 'dispatch');+});++test('the five minute trigger publishes on the quarter hour and reconciles the reply queue on every other run', () => {+ assert.equal(cronPlan(EVERY_FIVE_MINUTES_CRON, at('12:00')), 'publish');+ assert.equal(cronPlan(EVERY_FIVE_MINUTES_CRON, at('12:15')), 'publish');+ assert.equal(cronPlan(EVERY_FIVE_MINUTES_CRON, at('12:45')), 'publish');+ assert.equal(cronPlan(EVERY_FIVE_MINUTES_CRON, at('12:05')), 'reconcile');+ assert.equal(cronPlan(EVERY_FIVE_MINUTES_CRON, at('12:50')), 'reconcile');});test('the daily trigger runs the upkeep and an unknown cron runs nothing', () => {@@ -20,6 +24,6 @@ test('the daily trigger runs the upkeep and an unknown cron runs nothing', () =>test('the crons in wrangler.toml are the ones the Worker dispatches', () => {const toml = readFileSync(new URL('../../wrangler.toml', import.meta.url), 'utf8');- assert.match(toml, /crons = \["\*\/5 \* \* \* \*", "0 0 \* \* \*"\]/);- assert.deepEqual([EVERY_FIVE_MINUTES_CRON, DAILY_CRON], ['*/5 * * * *', '0 0 * * *']);+ assert.match(toml, /crons = \["\* \* \* \* \*", "\*\/5 \* \* \* \*", "0 0 \* \* \*"\]/);+ assert.deepEqual([EVERY_MINUTE_CRON, EVERY_FIVE_MINUTES_CRON, DAILY_CRON], ['* * * * *', '*/5 * * * *', '0 0 * * *']);});diff --git a/backend/tests/lib/automationDelivery.test.ts b/backend/tests/lib/automationDelivery.test.tsindex fbef59c..5d9e582 100644--- a/backend/tests/lib/automationDelivery.test.ts+++ b/backend/tests/lib/automationDelivery.test.ts@@ -1,10 +1,10 @@import { test } from 'node:test';import assert from 'node:assert/strict';import {- MAX_SEND_ATTEMPTS, REPLY_WINDOW_MS, classifySendError, composeReply, cooldownFromUsage, expiresAtFor, finishPlan, messageBytes,- readinessPlan, releasePlan, retryDelayMs,+ MAX_FOLLOW_REMINDERS, MAX_SEND_ATTEMPTS, REPLY_WINDOW_MS, classifySendError, composeReply, cooldownFromUsage, expiresAtFor, finishPlan,+ followupMessage, followupReadiness, messageBytes, messageDigest, readinessPlan, releasePlan, replyMessage, retryDelayMs,} from '../../lib/automationDelivery.ts';-import type { SendResult } from '../../lib/automationDelivery.ts';+import type { FollowupJob, SendResult } from '../../lib/automationDelivery.ts';const NOW = Date.parse('2026-10-16T12:00:00Z');const MINUTE = 60 * 1000;@@ -12,6 +12,70 @@ const job = (attempts = 1, expiresIn = 6 * 24 * 60 * MINUTE) => ({ attempts, expconst graphError = (code: number | undefined, subcode?: number, httpStatus = 400, usageHeader: string | null = null): SendResult =>({ kind: 'error', code, subcode, httpStatus, message: 'Graph said no', usageHeader });+function followup(overrides: Partial<FollowupJob> = {}): FollowupJob {+ return {+ attempts: 0, windowExpiresAt: new Date(NOW + 20 * 60 * MINUTE).toISOString(), ruleEnabled: true, requireFollow: true, gateStatus: 'awaiting_reply',+ gatePrompts: 0, replyText: 'Here is your guide', linkUrl: 'https://example.com/g', notFollowingText: 'Follow first, then reply', accessToken: 'TOK',+ ...overrides,+ };+}++test('a followers-only rule\'s private reply is its request to follow and reply, never the link', () => {+ const job = { replyText: 'Here', linkUrl: 'https://e.com', followPromptText: 'Follow and reply' };+ assert.equal(replyMessage({ ...job, requireFollow: true }), 'Follow and reply');+ assert.equal(replyMessage({ ...job, requireFollow: false }), 'Here\n\nhttps://e.com');+});++test('the digest of a message is the hex sha-256 of its exact text', async () => {+ assert.equal(await messageDigest('abc'), 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad');+ assert.notEqual(await messageDigest('abc '), await messageDigest('abc'));+});++test('only a confirmed follower gets the reply and link, and that ends the wait', () => {+ assert.deepEqual(followupMessage({ kind: 'following' }, followup(), NOW), {+ message: { kind: 'link', text: 'Here is your guide\n\nhttps://example.com/g', gateStatus: 'completed', countReminder: false },+ });+});++test('someone who does not follow yet gets the reminder, and the last reminder ends the wait', () => {+ assert.deepEqual(followupMessage({ kind: 'not_following' }, followup(), NOW), {+ message: { kind: 'reminder', text: 'Follow first, then reply', gateStatus: null, countReminder: true },+ });+ assert.deepEqual(followupMessage({ kind: 'not_following' }, followup({ gatePrompts: MAX_FOLLOW_REMINDERS - 1 }), NOW), {+ message: { kind: 'reminder', text: 'Follow first, then reply', gateStatus: 'closed', countReminder: true },+ });+ const used = followupMessage({ kind: 'not_following' }, followup({ gatePrompts: MAX_FOLLOW_REMINDERS }), NOW);+ assert.equal('release' in used && used.release.reason, 'reminders_used');+});++test('when Instagram cannot say whether the person follows, nothing is sent and the reason is kept', () => {+ const unverifiable = followupMessage({ kind: 'unverifiable', message: 'User consent is required to access user profile' }, followup(), NOW);+ assert.ok('release' in unverifiable);+ assert.deepEqual([unverifiable.release.status, unverifiable.release.reason], ['failed', 'follow_unverifiable']);+ assert.match(unverifiable.release.errorMessage!, /User consent is required.*so the link was not sent/);+ const refused = followupMessage({ kind: 'not_authorized', message: 'invalid token' }, followup(), NOW);+ assert.ok('release' in refused && refused.release.reason === 'not_authorized');+});++test('a follow check Instagram could not answer now is asked again a few minutes later, or expires with the window', () => {+ const later = followupMessage({ kind: 'retry', message: 'timed out' }, followup(), NOW);+ assert.ok('release' in later);+ assert.deepEqual([later.release.status, later.release.nextAttemptAt], ['retry_wait', new Date(NOW + 5 * MINUTE).toISOString()]);+ const closing = followupMessage({ kind: 'retry', message: 'timed out' }, followup({ windowExpiresAt: new Date(NOW + MINUTE).toISOString() }), NOW);+ assert.ok('release' in closing);+ assert.equal(closing.release.status, 'expired');+ assert.match(closing.release.errorMessage!, /24 hours/);+});++test('a follow-up stops before asking Instagram when its window closed, its rule changed or the token is gone', () => {+ assert.equal(followupReadiness(followup(), NOW), null);+ assert.equal(followupReadiness(followup({ windowExpiresAt: new Date(NOW - 1).toISOString() }), NOW)?.status, 'expired');+ assert.equal(followupReadiness(followup({ ruleEnabled: false }), NOW)?.reason, 'rule_disabled');+ assert.equal(followupReadiness(followup({ requireFollow: false }), NOW)?.reason, 'rule_changed');+ assert.equal(followupReadiness(followup({ gateStatus: 'completed' }), NOW)?.reason, 'answered');+ assert.equal(followupReadiness(followup({ accessToken: null }), NOW)?.status, 'failed');+});+test('the reply puts the link on its own line after the text', () => {assert.equal(composeReply('Here it is', 'https://example.com/g'), 'Here it is\n\nhttps://example.com/g');assert.equal(composeReply('Here it is', null), 'Here it is');@@ -61,15 +125,23 @@ test('the cooldown follows Meta\'s usage header, and falls back to 15 minutes whassert.equal(cooldownFromUsage(JSON.stringify({ '1': [{ estimated_time_to_regain_access: 99999 }] })), 24 * 60 * MINUTE);});-test('an accepted send records Instagram\'s message id and nothing else', () => {- const plan = finishPlan({ kind: 'accepted', messageId: 'm1' }, job(), NOW);+test('an accepted send records Instagram\'s message id and recipient and nothing else', () => {+ const plan = finishPlan({ kind: 'accepted', messageId: 'm1', recipientId: 'igsid-1' }, job(), NOW);assert.equal(plan.status, 'accepted');assert.equal(plan.outcome, 'accepted');assert.equal(plan.messageId, 'm1');+ assert.equal(plan.recipientId, 'igsid-1');+ assert.equal(plan.gateStatus, null);assert.equal(plan.nextAttemptAt, null);assert.equal(plan.cooldownUntil, null);});+test('an accepted followers-only reply starts the wait for the person\'s answer, with the commenter as recipient when Instagram names none', () => {+ const plan = finishPlan({ kind: 'accepted', messageId: 'm1', recipientId: null }, { ...job(), fromId: 'fan', awaitsReply: true }, NOW);+ assert.equal(plan.recipientId, 'fan');+ assert.equal(plan.gateStatus, 'awaiting_reply');+});+test('a send with no answer is held for a person and never retried on its own', () => {const plan = finishPlan({ kind: 'ambiguous', message: 'the request timed out' }, job(), NOW);assert.equal(plan.status, 'needs_review');diff --git a/backend/tests/lib/automationHealth.test.ts b/backend/tests/lib/automationHealth.test.tsnew file mode 100644index 0000000..5adceac--- /dev/null+++ b/backend/tests/lib/automationHealth.test.ts@@ -0,0 +1,17 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { healthWarning } from '../../lib/automationHealth.ts';+import type { QueueHealth } from '../../lib/automationHealth.ts';++const NOW = Date.parse('2026-10-16T12:00:00Z');+const HEALTHY: QueueHealth = { due: 0, oldestDueAt: null, waiting: 3, stale: 0, needsReview: 1, followupsDue: 0, pausedAccounts: 1, limitedAccounts: 0 };++test('a queue that keeps up gives no warning, whatever waits for later', () => {+ assert.equal(healthWarning(HEALTHY, NOW), null);+ assert.equal(healthWarning({ ...HEALTHY, due: 4, oldestDueAt: '2026-10-16T11:55:00Z' }, NOW), null);+});++test('replies due for more than ten minutes, or held by stopped runs, give one warning line naming both', () => {+ const warning = healthWarning({ ...HEALTHY, due: 40, oldestDueAt: '2026-10-16T11:45:00Z', stale: 2 }, NOW);+ assert.equal(warning, 'automation queue behind: the oldest due reply has waited 15 minutes; 2 replies are held by runs that stopped');+});diff --git a/backend/tests/lib/automationMatching.test.ts b/backend/tests/lib/automationMatching.test.tsindex c794a5e..d67c6b3 100644--- a/backend/tests/lib/automationMatching.test.ts+++ b/backend/tests/lib/automationMatching.test.ts@@ -1,12 +1,38 @@import { test } from 'node:test';import assert from 'node:assert/strict';-import { coversMedia, matchedKeyword, pickRule } from '../../lib/automationMatching.ts';+import { coversMedia, matchedKeyword, pickRule, ruleMatch } from '../../lib/automationMatching.ts';import type { MatchableRule } from '../../lib/automationMatching.ts';function rule(overrides: Partial<MatchableRule> = {}): MatchableRule {return { keywords: ['GUIDE'], matchMode: 'contains', caseSensitive: false, mediaIds: [], ...overrides };}+test('an any-comment rule answers every comment with something in it, emoji included, and names no keyword', () => {+ const any = rule({ matchMode: 'any', keywords: [] });+ assert.deepEqual(ruleMatch('love this', any), { rule: any, keyword: null });+ assert.deepEqual(ruleMatch('🔥', any), { rule: any, keyword: null });+ assert.equal(ruleMatch(' ', any), null);+});++test('the most specific rule answers: this post\'s keyword rule, then this post\'s any-comment rule, then the same for every post', () => {+ const everyAny = rule({ matchMode: 'any', keywords: [] });+ const everyKeyword = rule({ keywords: ['GUIDE'] });+ const postAny = rule({ matchMode: 'any', keywords: [], mediaIds: ['C'] });+ const postKeyword = rule({ keywords: ['GUIDE'], mediaIds: ['C'] });+ const all = [everyAny, everyKeyword, postAny, postKeyword];+ assert.equal(pickRule(all, 'GUIDE', 'C')?.rule, postKeyword);+ assert.equal(pickRule(all, 'nice', 'C')?.rule, postAny);+ assert.equal(pickRule(all, 'GUIDE', 'D')?.rule, everyKeyword);+ assert.equal(pickRule(all, 'nice', 'D')?.rule, everyAny);+ assert.equal(pickRule([everyKeyword], 'nice', 'D'), null);+});++test('among rules of the same kind the oldest answers, so two copies of a rule never both reply', () => {+ const first = rule({ matchMode: 'any', keywords: [] });+ const second = rule({ matchMode: 'any', keywords: [] });+ assert.equal(pickRule([first, second], 'hello', '1')?.rule, first);+});+test('contains matches the keyword as a whole word anywhere in the comment, ignoring case', () => {assert.equal(matchedKeyword('Please send the guide!', rule()), 'GUIDE');assert.equal(matchedKeyword('GUIDE', rule()), 'GUIDE');diff --git a/backend/tests/lib/automationReview.test.ts b/backend/tests/lib/automationReview.test.tsnew file mode 100644index 0000000..ad27a9a--- /dev/null+++ b/backend/tests/lib/automationReview.test.ts@@ -0,0 +1,36 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { REVIEW_MAX_CHECKS, findSentReply, reviewNote } from '../../lib/automationReview.ts';+import { messageDigest } from '../../lib/automationDelivery.ts';+import type { ConversationMessage } from '../../lib/automationReview.ts';++const STARTED = '2026-10-16T10:00:00.000Z';++function message(id: string, fromId: string, text: string | null, createdTime = '2026-10-16T10:00:05+0000'): ConversationMessage {+ return { id, fromId, text, createdTime };+}++test('a lost reply is found when the account sent exactly that text after the attempt started', async () => {+ const digest = await messageDigest('Here is your guide\n\nhttps://example.com/g');+ const messages = [+ message('theirs', '77', 'Here is your guide\n\nhttps://example.com/g'),+ message('other', '1784', 'Thanks for asking'),+ message('mine', '1784', 'Here is your guide\n\nhttps://example.com/g'),+ ];+ assert.equal((await findSentReply(messages, { igUserId: '1784', startedAt: STARTED, digest }, messageDigest))?.id, 'mine');+});++test('the same text sent well before the attempt, or a different text, is not taken for the lost reply', async () => {+ const digest = await messageDigest('Here is your guide');+ const old = [message('earlier', '1784', 'Here is your guide', '2026-10-16T09:00:00+0000'), message('edited', '1784', 'Here is your guide!')];+ assert.equal(await findSentReply(old, { igUserId: '1784', startedAt: STARTED, digest }, messageDigest), null);+ // the clocks may differ a little, so a message a minute before the attempt still counts+ const close = [message('close', '1784', 'Here is your guide', '2026-10-16T09:59:00+0000')];+ assert.equal((await findSentReply(close, { igUserId: '1784', startedAt: STARTED, digest }, messageDigest))?.id, 'close');+});++test('the note says when Twiligent will look again and that Instagram refuses a second reply', () => {+ assert.match(reviewNote(1), /looks again later/);+ assert.doesNotMatch(reviewNote(REVIEW_MAX_CHECKS), /looks again later/);+ assert.match(reviewNote(REVIEW_MAX_CHECKS), /refuses a second private reply/);+});diff --git a/backend/tests/lib/automationRules.test.ts b/backend/tests/lib/automationRules.test.tsnew file mode 100644index 0000000..a6e746a--- /dev/null+++ b/backend/tests/lib/automationRules.test.ts@@ -0,0 +1,17 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { followTextsProblem, keywordsProblem } from '../../lib/automationRules.ts';++test('a keyword rule needs a keyword and an any-comment rule takes none', () => {+ assert.equal(keywordsProblem('contains', ['GUIDE']), null);+ assert.equal(keywordsProblem('exact', []), 'Add at least one keyword');+ assert.equal(keywordsProblem('any', []), null);+ assert.match(keywordsProblem('any', ['GUIDE'])!, /answers any comment has no keywords/);+});++test('a followers-only rule needs both of its messages; any other rule needs neither', () => {+ assert.equal(followTextsProblem({ requireFollow: false, followPromptText: null, notFollowingText: null }), null);+ assert.match(followTextsProblem({ requireFollow: true, followPromptText: null, notFollowingText: 'x' })!, /asks people to follow you and reply/);+ assert.match(followTextsProblem({ requireFollow: true, followPromptText: 'x', notFollowingText: null })!, /reminder/);+ assert.equal(followTextsProblem({ requireFollow: true, followPromptText: 'x', notFollowingText: 'y' }), null);+});diff --git a/backend/tests/repositories/automationCommentRepository.test.ts b/backend/tests/repositories/automationCommentRepository.test.tsindex 94e210e..87e8d25 100644--- a/backend/tests/repositories/automationCommentRepository.test.ts+++ b/backend/tests/repositories/automationCommentRepository.test.ts@@ -33,7 +33,7 @@ describe('automation comment repository', () => {const supabase = fakeSupabase([], {claim_automation_comments: () => [{id: 'a', user_id: 'user-1', account_id: 'ig1', rule_id: 'r', ig_user_id: '1784', comment_id: 'c', from_id: 'f', attempts: 2,- expires_at: 'E', rule_enabled: true, reply_text: 'T', link_url: null, access_token: 'TOK',+ expires_at: 'E', rule_enabled: true, reply_text: 'T', link_url: null, access_token: 'TOK', require_follow: true, follow_prompt_text: 'P',}],reserve_automation_send: () => [{ outcome: 'account_limit', retry_at: 'R' }],finish_automation_send: () => true,@@ -42,25 +42,49 @@ describe('automation comment repository', () => {const [claimed] = await repo.claim({ limit: 10, perAccount: 5, leaseSeconds: 1200 });assert.deepEqual(claimed, {id: 'a', userId: 'user-1', accountId: 'ig1', ruleId: 'r', igUserId: '1784', commentId: 'c', fromId: 'f', attempts: 2,- expiresAt: 'E', ruleEnabled: true, replyText: 'T', linkUrl: null, accessToken: 'TOK',+ expiresAt: 'E', ruleEnabled: true, replyText: 'T', linkUrl: null, accessToken: 'TOK', requireFollow: true, followPromptText: 'P',});assert.deepEqual(rpcArgs(supabase, 'claim_automation_comments'), { p_limit: 10, p_per_account: 5, p_lease_seconds: 1200, p_ids: null });- assert.deepEqual(await repo.reserve('a', 'att', LIMITS), { outcome: 'account_limit', retryAt: 'R' });+ assert.deepEqual(await repo.reserve('a', 'att', LIMITS, 'digest'), { outcome: 'account_limit', retryAt: 'R' });assert.deepEqual(rpcArgs(supabase, 'reserve_automation_send'), {- p_id: 'a', p_attempt_id: 'att', p_global_limit: 1000, p_user_limit: 500, p_account_limit: 200, p_recipient_limit: 3,+ p_id: 'a', p_attempt_id: 'att', p_global_limit: 1000, p_user_limit: 500, p_account_limit: 200, p_recipient_limit: 3, p_message_digest: 'digest',});const plan: FinishPlan = {status: 'retry_wait', outcome: 'rate_limited', reason: 'rate_limited', errorMessage: 'm', messageId: null, errorCode: 4, errorSubcode: null,- httpStatus: 400, nextAttemptAt: 'N', cooldownUntil: 'C', cooldownReason: 'why', pauseReason: null,+ httpStatus: 400, nextAttemptAt: 'N', cooldownUntil: 'C', cooldownReason: 'why', pauseReason: null, recipientId: 'igsid', gateStatus: 'awaiting_reply',};assert.equal(await repo.finish('a', 'att', plan), true);assert.deepEqual(rpcArgs(supabase, 'finish_automation_send'), {p_id: 'a', p_attempt_id: 'att', p_status: 'retry_wait', p_outcome: 'rate_limited', p_reason: 'rate_limited', p_error_message: 'm',p_message_id: null, p_error_code: 4, p_error_subcode: null, p_http_status: 400, p_next_attempt_at: 'N', p_cooldown_until: 'C',- p_cooldown_reason: 'why', p_pause_reason: null,+ p_cooldown_reason: 'why', p_pause_reason: null, p_recipient_id: 'igsid', p_gate_status: 'awaiting_reply',});});+ test('expiry, review, health and purge pass their bounds to the database functions and read the answers', async () => {+ const supabase = fakeSupabase([], {+ expire_automation_jobs: () => ({ comments: 3, followups: 1 }),+ automation_review_candidates: () => [{ id: 'a', ig_user_id: '1784', from_id: 'f', started_at: 'S', message_digest: 'd', access_token: 'TOK', review_checks: 1 }],+ record_automation_review: () => true,+ automation_queue_health: () => ({ due: 4, oldest_due_at: 'O', needs_review: 2 }),+ purge_automation_comments: () => 1000,+ });+ const repo = createAutomationCommentRepository(supabase);+ assert.deepEqual(await repo.expireDue(500), { comments: 3, followups: 1 });+ assert.deepEqual(rpcArgs(supabase, 'expire_automation_jobs'), { p_limit: 500 });+ assert.deepEqual(await repo.reviewCandidates({ limit: 4, settleSeconds: 300, maxChecks: 3, recheckSeconds: 1800 }), [+ { id: 'a', igUserId: '1784', fromId: 'f', startedAt: 'S', messageDigest: 'd', accessToken: 'TOK', reviewChecks: 1 },+ ]);+ assert.deepEqual(rpcArgs(supabase, 'automation_review_candidates'), { p_limit: 4, p_settle_seconds: 300, p_max_checks: 3, p_recheck_seconds: 1800 });+ assert.equal(await repo.recordReview('a', { found: true, messageId: 'm', sentAt: 'T' }), true);+ assert.deepEqual(rpcArgs(supabase, 'record_automation_review'), { p_id: 'a', p_found: true, p_message_id: 'm', p_sent_at: 'T', p_note: null });+ assert.deepEqual(await repo.health(1200), {+ due: 4, oldestDueAt: 'O', waiting: 0, stale: 0, needsReview: 2, followupsDue: 0, pausedAccounts: 0, limitedAccounts: 0,+ });+ assert.equal(await repo.purgeCreatedBefore('2026-07-01T00:00:00Z', 1000), 1000);+ assert.deepEqual(rpcArgs(supabase, 'purge_automation_comments'), { p_before: '2026-07-01T00:00:00Z', p_limit: 1000 });+ });+test('a reservation with no answer counts as gone, so the job is never sent', async () => {const repo = createAutomationCommentRepository(fakeSupabase([], { reserve_automation_send: () => [] }));assert.deepEqual(await repo.reserve('a', 'att', LIMITS), { outcome: 'gone', retryAt: null });@@ -135,13 +159,17 @@ describe('automation comment repository', () => {assert.deepEqual(await repo.statsForUser('user-1', { from: 'F', to: 'T' }), { comments: { accepted: 2 }, attempts: {} });});- test('retention deletes comments created before the cutoff across all users', async () => {- const supabase = fakeSupabase([- tableRow('automation_comments', { id: 'old', created_at: '2026-01-01T00:00:00Z' }),- tableRow('automation_comments', { id: 'new', created_at: '2026-10-01T00:00:00Z' }),- ]);- assert.equal(await createAutomationCommentRepository(supabase).deleteCreatedBefore('2026-07-01T00:00:00Z'), 1);- assert.deepEqual(supabase.table.map(row => row.id), ['new']);+ test('an activity item shows its followers-only wait and its latest follow-up', async () => {+ const supabase = fakeSupabase([tableRow('automation_comments', {+ id: 'a', user_id: 'user-1', status: 'accepted', gate_status: 'awaiting_reply',+ automation_followups: [+ { status: 'accepted', kind: 'reminder', error_message: null, created_at: '2026-10-16T10:00:00Z' },+ { status: 'failed', kind: null, error_message: 'not sent', created_at: '2026-10-16T11:00:00Z' },+ ],+ })]);+ const [item] = await createAutomationCommentRepository(supabase).listForUser('user-1', { limit: 10 });+ assert.equal(item.gateStatus, 'awaiting_reply');+ assert.deepEqual(item.followup, { status: 'failed', kind: null, errorMessage: 'not sent', createdAt: '2026-10-16T11:00:00Z' });});test('a failed query becomes a DatabaseError', async () => {diff --git a/backend/tests/repositories/automationFollowupRepository.test.ts b/backend/tests/repositories/automationFollowupRepository.test.tsnew file mode 100644index 0000000..cd8be95--- /dev/null+++ b/backend/tests/repositories/automationFollowupRepository.test.ts@@ -0,0 +1,79 @@+import { test, describe } from 'node:test';+import assert from 'node:assert/strict';+import { createAutomationFollowupRepository } from '../../repositories/automationFollowupRepository.ts';+import { fakeSupabase, tableRow } from '../fixtures/fakeSupabase.ts';+import type { Row } from '../fixtures/fakeSupabase.ts';+import type { FollowupFinishPlan } from '../../repositories/automationFollowupRepository.ts';++const FUTURE = new Date(Date.now() + 60 * 60 * 1000).toISOString();+const rpcArgs = (supabase: ReturnType<typeof fakeSupabase>, name: string) => supabase.calls.find(call => call.type === 'rpc' && call.table === name)!.values as Row;++describe('automation follow-up repository', () => {+ test('messages go to the database in one call per account, without their text, and only new follow-up ids come back', async () => {+ const supabase = fakeSupabase([], { automation_followups_for_messages: () => [{ id: 'fu-1' }] });+ const repo = createAutomationFollowupRepository(supabase);+ assert.deepEqual(await repo.insertForMessages('1784', [{ id: 'fu-1', senderId: '77', messageId: 'm1', sentAt: 'T' }]), ['fu-1']);+ assert.deepEqual(rpcArgs(supabase, 'automation_followups_for_messages'), {+ p_ig_user_id: '1784', p_messages: [{ id: 'fu-1', sender_id: '77', message_id: 'm1', sent_at: 'T' }],+ });+ assert.deepEqual(await repo.insertForMessages('1784', []), []);+ assert.equal(supabase.calls.length, 1);+ });++ test('claim, reserve and finish pass every field to the database functions', async () => {+ const supabase = fakeSupabase([], {+ claim_automation_followups: () => [{+ id: 'fu', user_id: 'u', account_id: 'ig1', automation_comment_id: 'c', ig_user_id: '1784', recipient_id: '77', attempts: 0,+ window_expires_at: 'W', gate_status: 'awaiting_reply', gate_prompts: 1, rule_enabled: true, require_follow: true, reply_text: 'R',+ link_url: 'L', not_following_text: 'N', access_token: 'TOK',+ }],+ reserve_automation_followup: () => [{ outcome: 'ok', retry_at: null }],+ finish_automation_followup: () => true,+ });+ const repo = createAutomationFollowupRepository(supabase);+ const [claimed] = await repo.claim({ limit: 5, leaseSeconds: 1200, ids: ['fu'] });+ assert.deepEqual(claimed, {+ id: 'fu', userId: 'u', accountId: 'ig1', commentRowId: 'c', igUserId: '1784', recipientId: '77', attempts: 0, windowExpiresAt: 'W',+ gateStatus: 'awaiting_reply', gatePrompts: 1, ruleEnabled: true, requireFollow: true, replyText: 'R', linkUrl: 'L', notFollowingText: 'N', accessToken: 'TOK',+ });+ assert.deepEqual(rpcArgs(supabase, 'claim_automation_followups'), { p_limit: 5, p_lease_seconds: 1200, p_ids: ['fu'] });+ assert.deepEqual(await repo.reserve('fu', 'att', 'link', 'd'), { outcome: 'ok', retryAt: null });+ assert.deepEqual(rpcArgs(supabase, 'reserve_automation_followup'), { p_id: 'fu', p_attempt_id: 'att', p_kind: 'link', p_message_digest: 'd' });+ const plan: FollowupFinishPlan = {+ status: 'accepted', outcome: 'accepted', reason: null, errorMessage: null, messageId: 'm', errorCode: null, errorSubcode: null, httpStatus: null,+ nextAttemptAt: null, cooldownUntil: null, cooldownReason: null, pauseReason: null, recipientId: null, gateStatus: 'completed', countReminder: false,+ };+ assert.equal(await repo.finish('fu', 'att', plan), true);+ assert.deepEqual(rpcArgs(supabase, 'finish_automation_followup'), {+ p_id: 'fu', p_attempt_id: 'att', p_status: 'accepted', p_outcome: 'accepted', p_reason: null, p_error_message: null, p_message_id: 'm',+ p_error_code: null, p_error_subcode: null, p_http_status: null, p_next_attempt_at: null, p_cooldown_until: null, p_cooldown_reason: null,+ p_pause_reason: null, p_gate_status: 'completed', p_count_reminder: false,+ });+ });++ test('a follow-up is released or handed back only while a run still holds it', async () => {+ const supabase = fakeSupabase([+ tableRow('automation_followups', { id: 'held', status: 'processing', claimed_at: 'x' }),+ tableRow('automation_followups', { id: 'sending', status: 'sending', claimed_at: 'x' }),+ ]);+ const repo = createAutomationFollowupRepository(supabase);+ const plan = { status: 'failed' as const, reason: 'follow_unverifiable', errorMessage: 'no', nextAttemptAt: null };+ assert.equal(await repo.release('held', plan), true);+ assert.equal(await repo.release('sending', plan), false);+ await repo.returnUnstarted(['sending']);+ assert.deepEqual(supabase.table.map(row => row.status), ['failed', 'sending']);+ });++ test('a retry requeues the comment\'s newest follow-up only if it failed, was skipped or needs review, inside its window, for its owner', async () => {+ const supabase = fakeSupabase([+ // newest first, as the query orders them+ tableRow('automation_followups', { id: 'new', automation_comment_id: 'c', user_id: 'user-1', status: 'needs_review', created_at: '2026-10-16T10:00:00Z', window_expires_at: FUTURE }),+ tableRow('automation_followups', { id: 'old', automation_comment_id: 'c', user_id: 'user-1', status: 'failed', created_at: '2026-10-16T09:00:00Z', window_expires_at: FUTURE }),+ ]);+ const repo = createAutomationFollowupRepository(supabase);+ assert.equal(await repo.requeueLatestForUser('c', 'user-2'), null);+ assert.equal(await repo.requeueLatestForUser('c', 'user-1'), 'new');+ assert.equal(await repo.requeueLatestForUser('c', 'user-1'), null);+ assert.deepEqual(supabase.table.map(row => row.status), ['queued', 'failed']);+ });+});diff --git a/backend/tests/repositories/automationRuleRepository.test.ts b/backend/tests/repositories/automationRuleRepository.test.tsindex 81d68cf..e4f5099 100644--- a/backend/tests/repositories/automationRuleRepository.test.ts+++ b/backend/tests/repositories/automationRuleRepository.test.ts@@ -34,7 +34,9 @@ test('pausing or resuming by hand creates the account\'s row once and clears a hassert.deepEqual([controls.paused, controls.pausedReason], [false, null]);assert.equal(supabase.calls[0].onConflict, 'account_id');assert.equal(supabase.table.filter(row => row._table === 'automation_accounts').length, 1);- assert.ok((await repo.markSubscribedForUser('ig2', 'user-1')).subscribedAt);+ const subscribed = await repo.markSubscribedForUser('ig2', 'user-1', ['comments', 'messages']);+ assert.ok(subscribed.subscribedAt);+ assert.deepEqual(subscribed.subscribedFields, ['comments', 'messages']);});test('audit events are written for the user and old ones are deleted by date', async () => {diff --git a/backend/tests/routes/automationRoutes.test.ts b/backend/tests/routes/automationRoutes.test.tsindex 0cb0276..8bc0fa7 100644--- a/backend/tests/routes/automationRoutes.test.ts+++ b/backend/tests/routes/automationRoutes.test.ts@@ -85,6 +85,7 @@ describe('automation routes', () => {assert.deepEqual(body.rules.map((rule: { id: string }) => rule.id), ['rule-mine']);assert.deepEqual(body.accounts, [{accountId: 'ig1', username: 'mine', profilePictureUrl: '', paused: false, cooldownUntil: null, cooldownReason: null, subscribedAt: null,+ limitedUntil: null, messagesSubscribed: false,}]);assert.deepEqual(body.settings, { webhookConfigured: true, paused: false, limits: { accountHourly: 200, userHourly: 500, globalHourly: 1000, recipientDaily: 3 } });});@@ -111,6 +112,58 @@ describe('automation routes', () => {assert.equal((await call(target, 'GET', '/automations')).body.accounts[0].subscribedAt, null);});+ test('a rule that answers any comment is saved without keywords, and switching a rule to it clears them', async () => {+ const target = server();+ const created = await call(target, 'POST', '/automations/rules', { accountId: 'ig1', name: 'Giveaway', matchMode: 'any', keywords: [], replyText: 'Thanks' });+ assert.deepEqual([created.status, created.body.rule.matchMode, created.body.rule.keywords], [200, 'any', []]);+ const switched = await call(target, 'PUT', '/automations/rules/rule-mine', { matchMode: 'any' });+ assert.deepEqual([switched.body.rule.matchMode, switched.body.rule.keywords], ['any', []]);+ const back = await call(target, 'PUT', '/automations/rules/rule-mine', { matchMode: 'contains' });+ assert.equal(back.status, 400);+ assert.equal(back.body.message, 'Add at least one keyword');+ });++ test('an enabled followers-only rule asks Instagram for the account\'s comments and messages', async () => {+ const target = server();+ const { status, body } = await call(target, 'POST', '/automations/rules', {+ accountId: 'ig1', name: 'Gate', keywords: ['GUIDE'], replyText: 'Here it is', linkUrl: 'https://example.com/g', enabled: true,+ requireFollow: true, followPromptText: 'Follow and reply to get it', notFollowingText: 'Follow first, then reply',+ });+ assert.equal(status, 200);+ assert.deepEqual([body.rule.requireFollow, body.rule.followPromptText], [true, 'Follow and reply to get it']);+ assert.equal(new URL(graph[0].url).searchParams.get('subscribed_fields'), 'comments,messages');+ assert.equal((await call(target, 'GET', '/automations')).body.accounts[0].messagesSubscribed, true);+ });++ test('when Instagram refuses messages, the account still gets comments and shows that follow checks cannot work', async () => {+ subscribeAnswer = () => reply({ error: { message: 'messages is not available for this app', code: 100 } }, 400);+ let calls = 0;+ fetchMock?.restore();+ fetchMock = installFetch(request => {+ graph.push(request);+ calls++;+ return calls === 1 ? subscribeAnswer() : reply({ success: true });+ });+ const target = server();+ await call(target, 'POST', '/automations/rules', {+ accountId: 'ig1', name: 'Gate', keywords: ['GUIDE'], replyText: 'x', enabled: true,+ requireFollow: true, followPromptText: 'Follow and reply', notFollowingText: 'Follow first',+ });+ assert.deepEqual(graph.map(request => new URL(request.url).searchParams.get('subscribed_fields')), ['comments,messages', 'comments']);+ const account = (await call(target, 'GET', '/automations')).body.accounts[0];+ assert.deepEqual([!!account.subscribedAt, account.messagesSubscribed], [true, false]);+ });++ test('turning the followers-only option off asks Instagram for comments only again', async () => {+ const target = server(fakeSupabase([+ ...seed().filter(row => row.id !== 'rule-mine'),+ ruleRow('rule-mine', 'user-1', 'ig1', { enabled: true, require_follow: true, follow_prompt_text: 'Follow', not_following_text: 'Follow first' }),+ tableRow('automation_accounts', { account_id: 'ig1', user_id: 'user-1', paused: false, subscribed_at: PAST, subscribed_fields: ['comments', 'messages'] }),+ ]));+ await call(target, 'PUT', '/automations/rules/rule-mine', { requireFollow: false });+ assert.equal(new URL(graph[0].url).searchParams.get('subscribed_fields'), 'comments');+ });+test('a rule can only use the user\'s own Instagram account', async () => {const target = server();for (const accountId of ['ig-theirs', 'yt1', 'missing']) {@@ -142,6 +195,13 @@ describe('automation routes', () => {assert.deepEqual(audits(target.supabase), ['automation_rule.updated', 'automation_rule.duplicated', 'automation_rule.deleted']);});+ test('testing an any-comment, followers-only draft matches any words and shows the request to follow, not the link', async () => {+ const { body } = await call(server(), 'POST', '/automations/test', {+ matchMode: 'any', keywords: [], replyText: 'Hi', linkUrl: 'https://e.com', requireFollow: true, followPromptText: 'Follow and reply', comment: 'love this',+ });+ assert.deepEqual([body.matched, body.keyword, body.message], [true, null, 'Follow and reply']);+ });+test('testing a rule draft shows whether a sample comment matches and the exact reply, and sends nothing', async () => {const { body } = await call(server(), 'POST', '/automations/test', { keywords: ['GUIDE'], replyText: 'Hi', linkUrl: 'https://e.com', comment: 'the guide please' });assert.deepEqual(body, { success: true, matched: true, keyword: 'GUIDE', message: 'Hi\n\nhttps://e.com', messageBytes: 17, maxMessageBytes: 1000 });@@ -169,6 +229,22 @@ describe('automation routes', () => {assert.ok(target.supabase.calls.some(call => call.type === 'rpc' && call.table === 'claim_automation_comments'));});+ test('on an accepted followers-only reply, retry sends the failed follow-up again inside its 24 hours', async () => {+ const target = server(fakeSupabase([+ ...seed(),+ commentRow('gated', 'user-1', 'accepted', { gate_status: 'awaiting_reply' }),+ tableRow('automation_followups', {+ id: 'fu-1', user_id: 'user-1', automation_comment_id: 'gated', status: 'failed', created_at: '2026-10-15T01:00:00Z',+ window_expires_at: FUTURE, next_attempt_at: null,+ }),+ ], { claim_automation_followups: () => [] }));+ const retried = await call(target, 'POST', '/automations/activity/gated/retry');+ assert.equal(retried.status, 200);+ assert.equal(target.supabase.table.find(row => row.id === 'fu-1')!.status, 'queued');+ assert.ok(target.supabase.calls.some(call => call.type === 'rpc' && call.table === 'claim_automation_followups'));+ assert.equal((await call(target, 'POST', '/automations/activity/gated/retry')).status, 409);+ });+test('stats default to the last 7 days and pass the filters on', async () => {const target = server();const { body } = await call(target, 'GET', '/automations/stats?accountId=ig1');diff --git a/backend/tests/routes/instagramWebhookRoutes.test.ts b/backend/tests/routes/instagramWebhookRoutes.test.tsindex 5b365b4..8730ae0 100644--- a/backend/tests/routes/instagramWebhookRoutes.test.ts+++ b/backend/tests/routes/instagramWebhookRoutes.test.ts@@ -40,6 +40,37 @@ const RPC: Record<string, RpcHandler> = {Object.assign(row, { status: args.p_status, message_id: args.p_message_id });return true;},+ // the follow-up functions, reduced the same way: a waiting comment's sender gets one follow-up+ automation_followups_for_messages: (args, table) => (args.p_messages as Row[]).flatMap(message => {+ const comment = table.find(row => inTable(row, 'automation_comments') && row.recipient_id === message.sender_id && row.gate_status === 'awaiting_reply');+ if (!comment) return [];+ table.push(tableRow('automation_followups', { id: message.id, automation_comment_id: comment.id, account_id: comment.account_id, recipient_id: message.sender_id, status: 'queued' }));+ return [{ id: message.id }];+ }),+ claim_automation_followups: (args, table) => table+ .filter(row => inTable(row, 'automation_followups') && row.status === 'queued' && (args.p_ids as string[]).includes(row.id as string))+ .map(row => {+ row.status = 'processing';+ const comment = table.find(candidate => inTable(candidate, 'automation_comments') && candidate.id === row.automation_comment_id)!;+ const rule = table.find(candidate => inTable(candidate, 'automation_rules') && candidate.id === comment.rule_id)!;+ return {+ ...row, ig_user_id: '1784', attempts: 0, window_expires_at: new Date(Date.now() + 60 * 60 * 1000).toISOString(), gate_status: comment.gate_status,+ gate_prompts: 0, rule_enabled: rule.enabled, require_follow: rule.require_follow, reply_text: rule.reply_text, link_url: rule.link_url,+ not_following_text: rule.not_following_text, access_token: 'TOKEN-1',+ };+ }),+ reserve_automation_followup: (args, table) => {+ const row = table.find(candidate => inTable(candidate, 'automation_followups') && candidate.id === args.p_id && candidate.status === 'processing')!;+ Object.assign(row, { status: 'sending', kind: args.p_kind });+ return [{ outcome: 'ok', retry_at: null }];+ },+ finish_automation_followup: (args, table) => {+ const row = table.find(candidate => inTable(candidate, 'automation_followups') && candidate.id === args.p_id)!;+ row.status = args.p_status;+ const comment = table.find(candidate => inTable(candidate, 'automation_comments') && candidate.id === row.automation_comment_id)!;+ comment.gate_status = args.p_gate_status ?? comment.gate_status;+ return true;+ },};function seed(): Row[] {@@ -59,6 +90,7 @@ beforeEach(() => {mock.method(console, 'warn', () => {});mock.method(console, 'error', () => {});fetchMock = installFetch(request => {+ if (request.method === 'GET') return reply({ is_user_follow_business: true });sends.push(request.body ?? '');return reply({ recipient_id: 'r', message_id: 'mid-1' });});@@ -103,6 +135,23 @@ describe('instagram webhook routes', () => {assert.deepEqual(JSON.parse(sends[0]), { recipient: { comment_id: '555' }, message: { text: 'Here it is\n\nhttps://example.com/g' } });});+ test('a signed message from someone waiting on a followers-only reply is answered with the link once they follow', async () => {+ const target = app(fakeSupabase([+ ...seed().map(row => (row.id === 'rule-1' ? { ...row, require_follow: true, follow_prompt_text: 'Follow and reply', not_following_text: 'Follow first' } : row)),+ tableRow('automation_comments', { id: 'gated', account_id: 'ig1', rule_id: 'rule-1', status: 'accepted', recipient_id: '77', gate_status: 'awaiting_reply' }),+ ], RPC));+ const body = JSON.stringify({+ object: 'instagram',+ entry: [{ id: '1784', time: SENT_AT, messaging: [{ sender: { id: '77' }, recipient: { id: '1784' }, timestamp: SENT_AT * 1000, message: { mid: 'm1', text: 'done' } }] }],+ });+ const result = await post(target, body, await metaSignature('IGSECRET', body));+ assert.equal(result.status, 200);+ assert.deepEqual(JSON.parse(sends[0]), { recipient: { id: '77' }, message: { text: 'Here it is\n\nhttps://example.com/g' } });+ const followup = target.supabase.table.find(row => inTable(row, 'automation_followups'))!;+ assert.deepEqual([followup.status, followup.kind], ['accepted', 'link']);+ assert.equal(target.supabase.table.find(row => row.id === 'gated')!.gate_status, 'completed');+ });+test('the same notification delivered twice sends one reply', async () => {const target = app();const body = JSON.stringify(commentNotification('1784', SENT_AT, [{ id: '555', text: 'GUIDE' }]));diff --git a/backend/tests/services/automationFollowupProcessor.test.ts b/backend/tests/services/automationFollowupProcessor.test.tsnew file mode 100644index 0000000..ba98ff0--- /dev/null+++ b/backend/tests/services/automationFollowupProcessor.test.ts@@ -0,0 +1,205 @@+import { test, describe, beforeEach, afterEach, mock } from 'node:test';+import assert from 'node:assert/strict';+import { createAutomationFollowupProcessor } from '../../services/automationFollowupProcessor.ts';+import { CLAIM_LEASE_SECONDS, MAX_FOLLOW_REMINDERS } from '../../lib/automationDelivery.ts';+import { readAutomationConfig } from '../../lib/config.ts';+import { createLogger } from '../../lib/logger.ts';+import { installFetch, reply } from '../fixtures/fakeFetch.ts';+import type { FakeReply, FetchMock, RecordedRequest } from '../fixtures/fakeFetch.ts';+import { fakeAutomationQueue, followupRow, queueRow } from '../fixtures/fakeAutomationQueue.ts';+import type { FakeQueue } from '../fixtures/fakeAutomationQueue.ts';+import { mockRowIds } from '../fixtures/rowIds.ts';+import type { Env } from '../../types/env.ts';++interface Sent {+ recipient: string;+ text: string;+}++let fetchMock: FetchMock | null = null;+let sent: Sent[] = [];+let checks: string[] = [];++// Instagram's profile and messages endpoints: who follows, and what each message send answers+function instagram(follows: Record<string, boolean | FakeReply | Error>, send: (body: Sent) => FakeReply | Error = () => reply({ recipient_id: 'x', message_id: 'mid' })) {+ fetchMock = installFetch((request: RecordedRequest) => {+ const url = new URL(request.url);+ if (request.method === 'GET') {+ const igsid = url.pathname.split('/')[2];+ checks.push(igsid);+ const answer = follows[igsid];+ if (answer instanceof Error || (typeof answer === 'object' && answer !== null)) return answer;+ return reply({ is_user_follow_business: answer ?? false, id: igsid });+ }+ const body = JSON.parse(request.body!) as { recipient: { id: string }; message: { text: string } };+ const message = { recipient: body.recipient.id, text: body.message.text };+ sent.push(message);+ return send(message);+ });+}++// a comment whose followers-only reply was accepted and now waits for the person, and the follow-up their answer made+function waiting(id: string, overrides: { gatePrompts?: number } = {}): FakeQueue {+ const queue = fakeAutomationQueue(+ [queueRow(id, { status: 'accepted', nextAttemptAt: null, acceptedAt: new Date(Date.now() - 60_000).toISOString(), recipientId: `igsid-${id}`, gateStatus: 'awaiting_reply', gatePrompts: overrides.gatePrompts ?? 0 })],+ [followupRow(`fu-${id}`, id)],+ );+ Object.assign(queue.rules.get('rule-guide')!, { requireFollow: true, followPromptText: 'Follow and reply', notFollowingText: 'Follow first, then reply' });+ return queue;+}++function processor(queue: FakeQueue, signal = new AbortController().signal) {+ return createAutomationFollowupProcessor({+ followups: queue.followups, automation: readAutomationConfig({} as Env), context: { requestId: 'req-test', signal, log: createLogger() },+ });+}++beforeEach(() => {+ sent = [];+ checks = [];+ mockRowIds();+ mock.method(console, 'log', () => {});+ mock.method(console, 'warn', () => {});+ mock.method(console, 'error', () => {});+});+afterEach(() => {+ fetchMock?.restore();+ fetchMock = null;+ mock.restoreAll();+});++describe('automation follow-up processor', () => {+ test('a person who follows the account gets the reply and link, and the comment\'s wait ends', async () => {+ instagram({ 'igsid-a': true });+ const queue = waiting('a');+ const run = await processor(queue).run();+ assert.deepEqual(run.outcomes, { accepted: 1 });+ assert.deepEqual(sent, [{ recipient: 'igsid-a', text: 'Here is your guide\n\nhttps://example.com/guide' }]);+ assert.deepEqual([queue.followupRows[0].kind, queue.rows[0].gateStatus], ['link', 'completed']);+ assert.deepEqual(queue.attempts.map(attempt => [attempt.kind, attempt.outcome]), [['followup', 'accepted']]);+ });++ test('someone who does not follow yet gets the reminder, counted, and the comment keeps waiting', async () => {+ instagram({ 'igsid-a': false });+ const queue = waiting('a');+ await processor(queue).run();+ assert.deepEqual(sent, [{ recipient: 'igsid-a', text: 'Follow first, then reply' }]);+ assert.deepEqual([queue.followupRows[0].kind, queue.rows[0].gatePrompts, queue.rows[0].gateStatus], ['reminder', 1, 'awaiting_reply']);+ });++ test('the last reminder ends the wait, so a later message from that person is not answered again', async () => {+ instagram({ 'igsid-a': false });+ const queue = waiting('a', { gatePrompts: MAX_FOLLOW_REMINDERS - 1 });+ await processor(queue).run();+ assert.equal(queue.rows[0].gateStatus, 'closed');+ assert.deepEqual(await queue.followups.insertForMessages('1784', [{ id: 'fu-next', senderId: 'igsid-a', messageId: 'mid-next', sentAt: new Date().toISOString() }]), []);+ });++ test('when Instagram cannot say whether the person follows, no message is sent and the reason is shown', async () => {+ instagram({ 'igsid-a': reply({ error: { message: 'User consent is required to access user profile', code: 230 } }, 400) });+ const queue = waiting('a');+ await processor(queue).run();+ assert.equal(sent.length, 0);+ assert.deepEqual([queue.followupRows[0].status, queue.followupRows[0].statusReason], ['failed', 'follow_unverifiable']);+ assert.match(queue.followupRows[0].errorMessage!, /link was not sent/);+ assert.equal(queue.attempts.length, 0);+ });++ test('a follow check Instagram limits or cannot answer now is asked again later, without sending', async () => {+ instagram({ 'igsid-a': reply({ error: { message: 'rate limited', code: 4 } }, 400), 'igsid-b': new Error('connection reset') });+ const queue = fakeAutomationQueue(+ [queueRow('a', { status: 'accepted', recipientId: 'igsid-a', gateStatus: 'awaiting_reply' }), queueRow('b', { status: 'accepted', recipientId: 'igsid-b', gateStatus: 'awaiting_reply' })],+ [followupRow('fu-a', 'a'), followupRow('fu-b', 'b')],+ );+ Object.assign(queue.rules.get('rule-guide')!, { requireFollow: true, notFollowingText: 'Follow first' });+ await processor(queue).run();+ assert.equal(sent.length, 0);+ assert.deepEqual(queue.followupRows.map(row => [row.status, row.statusReason]), [['retry_wait', 'follow_check'], ['retry_wait', 'follow_check']]);+ });++ test('a rule turned off, or no longer followers-only, skips the follow-up without asking Instagram', async () => {+ instagram({});+ const off = waiting('a');+ off.rules.get('rule-guide')!.enabled = false;+ await processor(off).run();+ const changed = waiting('b');+ changed.rules.get('rule-guide')!.requireFollow = false;+ await processor(changed).run();+ assert.deepEqual([off.followupRows[0].statusReason, changed.followupRows[0].statusReason], ['rule_disabled', 'rule_changed']);+ assert.deepEqual([checks.length, sent.length], [0, 0]);+ });++ test('a follow-up whose 24 hours ran out expires without a check or a send', async () => {+ instagram({ 'igsid-a': true });+ const queue = waiting('a');+ queue.followupRows[0].windowExpiresAt = new Date(Date.now() - 1000).toISOString();+ await processor(queue).run();+ assert.equal(queue.followupRows[0].status, 'expired');+ assert.deepEqual([checks.length, sent.length], [0, 0]);+ });++ test('a link whose answer is lost needs review and later runs never send it again', async () => {+ instagram({ 'igsid-a': true }, () => Object.assign(new Error('The operation was aborted due to timeout'), { name: 'TimeoutError' }));+ const queue = waiting('a');+ await processor(queue).run();+ assert.equal(queue.followupRows[0].status, 'needs_review');+ assert.equal(queue.rows[0].gateStatus, 'awaiting_reply');+ await processor(queue).run();+ assert.equal(sent.length, 1);+ });++ test('a run that stopped mid-send leaves the follow-up for review instead of a second send', async () => {+ instagram({ 'igsid-a': true });+ const stale = new Date(Date.now() - (CLAIM_LEASE_SECONDS + 60) * 1000).toISOString();+ const queue = waiting('a');+ Object.assign(queue.followupRows[0], { status: 'sending', claimedAt: stale, nextAttemptAt: null });+ queue.attempts.push({ id: 'old', commentRowId: 'a', followupId: 'fu-a', kind: 'followup', userId: 'user-1', accountId: 'ig1', ruleId: 'rule-guide', recipientId: 'igsid-a', outcome: 'sending', startedAt: Date.now() - 30 * 60_000 });+ await processor(queue).run();+ assert.deepEqual([queue.followupRows[0].status, queue.attempts[0].outcome, sent.length], ['needs_review', 'ambiguous', 0]);+ });++ test('a paused account\'s follow-ups wait, and two runs at once send each follow-up once', async () => {+ instagram({ 'igsid-a': true, 'igsid-b': true });+ const queue = fakeAutomationQueue(+ [queueRow('a', { status: 'accepted', recipientId: 'igsid-a', gateStatus: 'awaiting_reply' }), queueRow('b', { status: 'accepted', recipientId: 'igsid-b', gateStatus: 'awaiting_reply' })],+ [followupRow('fu-a', 'a'), followupRow('fu-b', 'b')],+ );+ Object.assign(queue.rules.get('rule-guide')!, { requireFollow: true, notFollowingText: 'Follow first' });+ queue.controls.set('ig1', { paused: true, pausedReason: null, cooldownUntil: null });+ assert.equal((await processor(queue).run()).claimed, 0);+ queue.controls.get('ig1')!.paused = false;+ await Promise.all([processor(queue).run(), processor(queue).run()]);+ assert.deepEqual(sent.map(item => item.recipient).sort(), ['igsid-a', 'igsid-b']);+ });++ test('a follow check slow enough to leave no time for the send hands the follow-up back unsent', async () => {+ mock.timers.enable({ apis: ['Date'], now: Date.now() });+ instagram({});+ fetchMock!.restore();+ fetchMock = installFetch(request => {+ if (request.method === 'GET') {+ // Instagram took 9 of the run's 20 seconds to answer, leaving less than a send's 10 second timeout and margin+ mock.timers.tick(9_000);+ return reply({ is_user_follow_business: true });+ }+ sent.push({ recipient: 'x', text: 'x' });+ return reply({ message_id: 'm' });+ });+ const queue = waiting('a');+ const run = await processor(queue).run({ timeBudgetMs: 20_000 });+ assert.deepEqual(run.outcomes, { returned: 1 });+ assert.equal(sent.length, 0);+ assert.deepEqual([queue.followupRows[0].status, queue.attempts.length], ['queued', 0]);+ });++ test('a run claims only the follow-ups its subrequests pay for, four each after the claim', async () => {+ instagram({ 'igsid-a': true, 'igsid-b': true });+ const queue = fakeAutomationQueue(+ [queueRow('a', { status: 'accepted', recipientId: 'igsid-a', gateStatus: 'awaiting_reply' }), queueRow('b', { status: 'accepted', recipientId: 'igsid-b', gateStatus: 'awaiting_reply' })],+ [followupRow('fu-a', 'a'), followupRow('fu-b', 'b')],+ );+ Object.assign(queue.rules.get('rule-guide')!, { requireFollow: true, notFollowingText: 'Follow first' });+ const run = await processor(queue).run({ subrequests: 6 });+ assert.deepEqual([run.claimed, run.subrequests, sent.length], [1, 5, 1]);+ });+});diff --git a/backend/tests/services/automationProcessor.test.ts b/backend/tests/services/automationProcessor.test.tsindex 34dfb9b..7e6440c 100644--- a/backend/tests/services/automationProcessor.test.ts+++ b/backend/tests/services/automationProcessor.test.ts@@ -73,7 +73,7 @@ describe('automation processor', () => {instagram();const queue = fakeAutomationQueue([queueRow('a'), queueRow('b')]);const run = await processor(queue).run();- assert.deepEqual(run, { claimed: 2, outcomes: { accepted: 2 } });+ assert.deepEqual(run, { claimed: 2, outcomes: { accepted: 2 }, subrequests: 7 });assert.deepEqual(sent.map(item => item.commentId).sort(), ['c-a', 'c-b']);assert.deepEqual(sent[0], { igUserId: '1784', commentId: 'c-a', text: 'Here is your guide\n\nhttps://example.com/guide', token: 'Bearer TOKEN-1' });assert.equal(queue.rows[0].messageId, 'm-c-a');@@ -107,15 +107,56 @@ describe('automation processor', () => {assert.equal(new Set(sent.map(item => item.commentId)).size, 8);});- test('a burst larger than the batch is spread over runs, and one busy account cannot take a sweep from another', async () => {+ test('a burst larger than the batch is spread over runs, and accounts take turns so a busy one cannot hold back another', async () => {instagram();- const busy = Array.from({ length: 12 }, (_, i) => queueRow(`busy${i}`));+ const busy = Array.from({ length: 12 }, (_, i) => queueRow(`busy${i}`, { nextAttemptAt: new Date(Date.now() - 60_000 + i).toISOString() }));const quiet = queueRow('quiet', { accountId: 'ig2', igUserId: '2000' });const queue = fakeAutomationQueue([...busy, quiet]);const run = await processor(queue, automation({ AUTOMATION_BATCH_SIZE: '4' })).run();- assert.equal(run.claimed, 3);- assert.ok(sent.some(item => item.commentId === 'c-quiet'));- assert.equal(queue.rows.filter(row => row.status === 'queued').length, 10);+ assert.equal(run.claimed, 4);+ assert.deepEqual(sent.map(item => item.commentId), ['c-busy0', 'c-quiet', 'c-busy1', 'c-busy2']);+ assert.equal(queue.rows.filter(row => row.status === 'queued').length, 9);+ });++ test('an account alone uses the whole batch', async () => {+ instagram();+ const queue = fakeAutomationQueue(Array.from({ length: 12 }, (_, i) => queueRow(`solo${i}`)));+ const run = await processor(queue, automation({ AUTOMATION_BATCH_SIZE: '10' })).run();+ assert.equal(run.claimed, 10);+ assert.equal(sent.length, 10);+ });++ test('a run reports the subrequests it made: the claim, then three for each reply', async () => {+ instagram();+ const queue = fakeAutomationQueue([queueRow('a'), queueRow('b')]);+ assert.equal((await processor(queue).run()).subrequests, 7);+ });++ test('every attempt keeps a digest of the exact text sent', async () => {+ instagram();+ const queue = fakeAutomationQueue([queueRow('a')]);+ await processor(queue).run();+ assert.match(queue.attempts[0].digest!, /^[0-9a-f]{64}$/);+ });++ test('a followers-only rule sends its request to follow and reply, and the comment then waits for the answer', async () => {+ instagram();+ const queue = fakeAutomationQueue([queueRow('gate')]);+ Object.assign(queue.rules.get('rule-guide')!, { requireFollow: true, followPromptText: 'Follow us and reply to get the guide', notFollowingText: 'Follow first' });+ await processor(queue).run();+ assert.equal(sent[0].text, 'Follow us and reply to get the guide');+ assert.deepEqual([queue.rows[0].status, queue.rows[0].gateStatus, queue.rows[0].recipientId], ['accepted', 'awaiting_reply', 'r']);+ });++ test('a paused account\'s replies are not claimed at all, and go out once it is resumed', async () => {+ instagram();+ const queue = fakeAutomationQueue([queueRow('held'), queueRow('other', { accountId: 'ig2', igUserId: '2000' })]);+ queue.controls.set('ig1', { paused: true, pausedReason: null, cooldownUntil: null });+ await processor(queue).run();+ assert.deepEqual(statuses(queue), { held: 'queued', other: 'accepted' });+ queue.controls.get('ig1')!.paused = false;+ await processor(queue).run();+ assert.equal(statuses(queue).held, 'accepted');});test('a webhook\'s own comments are claimed by id, all at once, leaving older jobs to the sweep', async () => {@@ -178,6 +219,24 @@ describe('automation processor', () => {assert.ok(Date.parse(queue.rows[2].nextAttemptAt!) > Date.now() + 59 * MINUTE);});+ test('a full account is marked until a send frees up, so later runs leave its waiting replies alone', async () => {+ instagram();+ const queue = fakeAutomationQueue(Array.from({ length: 5 }, (_, i) => queueRow(`b${i}`)));+ const config = automation({ AUTOMATION_ACCOUNT_HOURLY_LIMIT: '2', AUTOMATION_BATCH_SIZE: '3' });+ await processor(queue, config).run();+ assert.ok(Date.parse(queue.controls.get('ig1')!.limitedUntil!) > Date.now() + 59 * MINUTE);+ assert.deepEqual(await processor(queue, config).run(), { claimed: 0, outcomes: {}, subrequests: 1 });+ assert.deepEqual(queue.rows.slice(3).map(row => row.status), ['queued', 'queued']);+ });++ test('a follow-up does not count toward the account\'s private reply limit', async () => {+ instagram();+ const queue = fakeAutomationQueue([queueRow('a')]);+ queue.attempts.push({ id: 'f', commentRowId: 'x', followupId: 'fu', kind: 'followup', userId: 'user-1', accountId: 'ig1', ruleId: 'rule-guide', recipientId: 'p', outcome: 'accepted', startedAt: Date.now() });+ await processor(queue, automation({ AUTOMATION_ACCOUNT_HOURLY_LIMIT: '1' })).run();+ assert.equal(statuses(queue).a, 'accepted');+ });+test('a person who triggers many rules gets only the daily number of replies', async () => {instagram();const queue = fakeAutomationQueue(['r1', 'r2', 'r3', 'r4'].map(id => queueRow(id, { fromId: 'same-fan' })));@@ -235,14 +294,15 @@ describe('automation processor', () => {await processor(queue, automation({ AUTOMATION_BATCH_SIZE: '1' })).run();await processor(queue, automation({ AUTOMATION_BATCH_SIZE: '1' })).run();assert.equal(queue.controls.get('ig1')!.paused, true);- assert.deepEqual(queue.rows.map(row => [row.status, row.statusReason]), [['queued', 'paused'], ['queued', 'paused']]);+ // the held account is left out of later claims, so its second reply waits untouched+ assert.deepEqual(queue.rows.map(row => [row.status, row.statusReason]), [['queued', 'paused'], ['queued', null]]);assert.equal(sent.length, 1);});test('pausing this instance sends nothing and claims nothing', async () => {instagram();const queue = fakeAutomationQueue([queueRow('a')]);- assert.deepEqual(await processor(queue, automation({ AUTOMATION_PAUSED: 'true' })).run(), { claimed: 0, outcomes: {} });+ assert.deepEqual(await processor(queue, automation({ AUTOMATION_PAUSED: 'true' })).run(), { claimed: 0, outcomes: {}, subrequests: 0 });assert.equal(statuses(queue).a, 'queued');});@@ -272,7 +332,7 @@ describe('automation processor', () => {const controller = new AbortController();controller.abort();const run = await processor(queue, automation(), controller.signal).run();- assert.deepEqual(run, { claimed: 1, outcomes: { returned: 1 } });+ assert.deepEqual(run, { claimed: 1, outcomes: { returned: 1 }, subrequests: 2 });assert.equal(sent.length, 0);assert.equal(statuses(queue).a, 'queued');});@@ -293,7 +353,7 @@ describe('automation processor', () => {const run = await processor(queue).run({ ids: queue.rows.map(row => row.id), subrequests: 11 });assert.equal(run.claimed, 3);assert.equal(sent.length, 3);- assert.deepEqual(await processor(queue).run({ subrequests: 4 }), { claimed: 0, outcomes: {} });+ assert.deepEqual(await processor(queue).run({ subrequests: 4 }), { claimed: 0, outcomes: {}, subrequests: 0 });assert.equal(queue.rows.filter(row => row.status === 'queued').length, 3);});});diff --git a/backend/tests/services/automationReconciler.test.ts b/backend/tests/services/automationReconciler.test.tsnew file mode 100644index 0000000..2e1c9e7--- /dev/null+++ b/backend/tests/services/automationReconciler.test.ts@@ -0,0 +1,112 @@+import { test, describe, beforeEach, afterEach, mock } from 'node:test';+import assert from 'node:assert/strict';+import { createAutomationReconciler } from '../../services/automationReconciler.ts';+import { messageDigest } from '../../lib/automationDelivery.ts';+import { installFetch, reply } from '../fixtures/fakeFetch.ts';+import type { FetchMock, RecordedRequest } from '../fixtures/fakeFetch.ts';+import { fakeAutomationQueue, followupRow, queueRow } from '../fixtures/fakeAutomationQueue.ts';+import type { FakeQueue } from '../fixtures/fakeAutomationQueue.ts';+import type { Logger } from '../../lib/logger.ts';++const TEXT = 'Here is your guide\n\nhttps://example.com/guide';++let fetchMock: FetchMock | null = null;+let requests: RecordedRequest[] = [];+const lines: { level: string; message: string }[] = [];++// Instagram's conversations: the one with the person, and its messages as the account sent them+function conversation(messages: { id: string; from: string; message: string; created_time: string }[] | Error) {+ fetchMock = installFetch(request => {+ requests.push(request);+ if (messages instanceof Error) return messages;+ if (request.url.includes('/conversations')) return reply({ data: [{ id: 'conv-1' }] });+ return reply({ messages: { data: messages.map(item => ({ ...item, from: { id: item.from } })) }, id: 'conv-1' });+ });+}++function logger(): Logger {+ const log: Logger = {+ info: (message: string) => { lines.push({ level: 'info', message }); },+ warn: (message: string) => { lines.push({ level: 'warn', message }); },+ error: (message: string) => { lines.push({ level: 'error', message }); },+ with: () => log,+ } as unknown as Logger;+ return log;+}++async function lost(id: string): Promise<FakeQueue> {+ const queue = fakeAutomationQueue([queueRow(id, { status: 'needs_review', statusReason: 'no_answer', nextAttemptAt: null })]);+ queue.attempts.push({+ id: 'att', commentRowId: id, kind: 'private_reply', userId: 'user-1', accountId: 'ig1', ruleId: 'rule-guide', recipientId: `fan-${id}`,+ outcome: 'ambiguous', digest: await messageDigest(TEXT), startedAt: Date.now() - 10 * 60_000,+ });+ return queue;+}++const reconciler = (queue: FakeQueue) => createAutomationReconciler({ comments: queue, context: { requestId: 'cron-test', signal: new AbortController().signal, log: logger() } });++beforeEach(() => {+ requests = [];+ lines.length = 0;+});+afterEach(() => {+ fetchMock?.restore();+ fetchMock = null;+ mock.restoreAll();+});++describe('automation reconciler', () => {+ test('a lost reply found in the conversation becomes accepted, and nothing is ever sent', async () => {+ conversation([{ id: 'mid-found', from: '1784', message: TEXT, created_time: new Date().toISOString() }]);+ const queue = await lost('a');+ const run = await reconciler(queue).run();+ assert.deepEqual(run.reviewed, { found: 1, notFound: 0, failed: 0 });+ assert.deepEqual([queue.rows[0].status, queue.rows[0].messageId, queue.attempts[0].outcome], ['accepted', 'mid-found', 'accepted']);+ assert.ok(requests.every(request => request.method === 'GET'));+ assert.equal(new URL(requests[0].url).searchParams.get('user_id'), 'fan-a');+ });++ test('a lost reply that is not in the conversation stays for a person, with what was checked', async () => {+ conversation([{ id: 'other', from: '1784', message: 'Something else', created_time: new Date().toISOString() }]);+ const queue = await lost('a');+ const run = await reconciler(queue).run();+ assert.deepEqual(run.reviewed, { found: 0, notFound: 1, failed: 0 });+ assert.equal(queue.rows[0].status, 'needs_review');+ assert.match(queue.rows[0].errorMessage!, /did not find this reply\. Twiligent looks again later/);+ });++ test('a conversation Instagram will not show is recorded as a check that could not be made', async () => {+ conversation(new Error('connection reset'));+ const queue = await lost('a');+ const run = await reconciler(queue).run();+ assert.deepEqual(run.reviewed, { found: 0, notFound: 0, failed: 1 });+ assert.equal(queue.rows[0].status, 'needs_review');+ assert.match(queue.rows[0].errorMessage!, /could not read the conversation/);+ assert.equal(queue.rows[0].reviewChecks, 1);+ });++ test('a reply sent before digests were kept is not guessed at; it is left for a person without asking Instagram', async () => {+ conversation([]);+ const queue = await lost('a');+ queue.attempts[0].digest = null;+ await reconciler(queue).run();+ assert.equal(requests.length, 0);+ assert.match(queue.rows[0].errorMessage!, /before Twiligent could recognise it/);+ });++ test('overdue replies and follow-ups are expired in one call, and a queue that fell behind logs one warning', async () => {+ conversation([]);+ const queue = fakeAutomationQueue(+ [+ queueRow('late', { expiresAt: new Date(Date.now() - 1000).toISOString() }),+ queueRow('behind', { nextAttemptAt: new Date(Date.now() - 30 * 60_000).toISOString() }),+ queueRow('gated', { status: 'accepted', nextAttemptAt: null, gateStatus: 'awaiting_reply' }),+ ],+ [followupRow('fu-late', 'gated', { windowExpiresAt: new Date(Date.now() - 1000).toISOString() })],+ );+ const run = await reconciler(queue).run();+ assert.deepEqual(run.expired, { comments: 1, followups: 1 });+ assert.equal(queue.rows[0].status, 'expired');+ assert.deepEqual(lines.filter(line => line.level === 'warn').map(line => line.message), ['automation queue behind: the oldest due reply has waited 30 minutes']);+ });+});diff --git a/backend/tests/services/automationWebhookService.test.ts b/backend/tests/services/automationWebhookService.test.tsindex 9cd1e81..0ba42e4 100644--- a/backend/tests/services/automationWebhookService.test.ts+++ b/backend/tests/services/automationWebhookService.test.ts@@ -5,7 +5,7 @@ import { readAutomationConfig } from '../../lib/config.ts';import { createLogger } from '../../lib/logger.ts';import { parseInstagramWebhook } from '../../validators/instagramWebhookValidators.ts';import { commentNotification } from '../fixtures/metaWebhook.ts';-import { fakeAutomationQueue } from '../fixtures/fakeAutomationQueue.ts';+import { fakeAutomationQueue, queueRow } from '../fixtures/fakeAutomationQueue.ts';import type { FakeQueue } from '../fixtures/fakeAutomationQueue.ts';import { mockRowIds } from '../fixtures/rowIds.ts';import type { AutomationRuleRepository, WebhookRule } from '../../repositories/automationRuleRepository.ts';@@ -33,6 +33,7 @@ function service(queue: FakeQueue, env: Partial<Env> = {}) {return createAutomationWebhookService({rules: rulesRepository(),comments,+ followups: queue.followups,automation: readAutomationConfig(env as Env),context: { requestId: 'req-test', signal: new AbortController().signal, log: createLogger() },});@@ -87,7 +88,7 @@ describe('instagram webhook intake', () => {const body = commentNotification('1784', SENT_AT, [{ id: '1', text: 'GUIDE', mediaId: 'A' }, { id: '2', text: 'GUIDE', mediaId: 'A' }]);await ingest(queue, body);const again = await ingest(queue, body);- assert.deepEqual(again, { stored: 0, duplicates: 2, queuedIds: [], subrequests: 2 });+ assert.deepEqual(again, { stored: 0, duplicates: 2, queuedIds: [], followupIds: [], subrequests: 2 });assert.equal(queue.rows.length, 2);});@@ -98,10 +99,38 @@ describe('instagram webhook intake', () => {assert.equal(inserted[0].length, 1);});+ test('a message from someone waiting on a followers-only reply makes one follow-up; anyone else\'s makes none', async () => {+ const queue = fakeAutomationQueue([queueRow('gated', { status: 'accepted', nextAttemptAt: null, acceptedAt: new Date(SENT_AT * 1000 - 60_000).toISOString(), recipientId: '77', gateStatus: 'awaiting_reply' })]);+ const body = {+ object: 'instagram',+ entry: [{+ id: '1784',+ messaging: [+ { sender: { id: '77' }, recipient: { id: '1784' }, timestamp: SENT_AT * 1000, message: { mid: 'm1', text: 'done' } },+ { sender: { id: '77' }, recipient: { id: '1784' }, timestamp: SENT_AT * 1000 + 1, message: { mid: 'm2', text: 'hello?' } },+ { sender: { id: '99' }, recipient: { id: '1784' }, timestamp: SENT_AT * 1000, message: { mid: 'm3', text: 'hi' } },+ { sender: { id: '1784' }, recipient: { id: '77' }, timestamp: SENT_AT * 1000, message: { mid: 'm4', is_echo: true } },+ ],+ }],+ };+ const result = await ingest(queue, body);+ assert.equal(result.followupIds.length, 1);+ assert.deepEqual([result.stored, result.subrequests], [0, 1]);+ assert.deepEqual(queue.followupRows.map(row => [row.commentRowId, row.triggerMessageId, row.recipientId]), [['gated', 'm1', '77']]);+ assert.deepEqual((await ingest(queue, body)).followupIds, []);+ });++ test('a failed follow-up insert fails the intake, so Meta delivers the messages again', async () => {+ const queue = fakeAutomationQueue();+ queue.failNext('insertForMessages');+ const body = { object: 'instagram', entry: [{ id: '1784', messaging: [{ sender: { id: '77' }, timestamp: SENT_AT * 1000, message: { mid: 'm1' } }] }] };+ await assert.rejects(ingest(queue, body), /database unavailable during insertForMessages/);+ });+test('comments for an account with no enabled rule are not kept at all', async () => {const queue = fakeAutomationQueue();const result = await ingest(queue, commentNotification('5555', SENT_AT, [{ id: '1', text: 'GUIDE' }]));- assert.deepEqual(result, { stored: 0, duplicates: 0, queuedIds: [], subrequests: 1 });+ assert.deepEqual(result, { stored: 0, duplicates: 0, queuedIds: [], followupIds: [], subrequests: 1 });assert.deepEqual(inserted, [[]]);});@@ -109,7 +138,7 @@ describe('instagram webhook intake', () => {const queue = fakeAutomationQueue();const broken = { ...queue, insertMany: async () => { throw new Error('database unavailable'); } };const intake = createAutomationWebhookService({- rules: rulesRepository(), comments: broken, automation: readAutomationConfig({} as Env),+ rules: rulesRepository(), comments: broken, followups: queue.followups, automation: readAutomationConfig({} as Env),context: { requestId: 'req-test', signal: new AbortController().signal, log: createLogger() },});await assert.rejects(intake.ingest(parseInstagramWebhook(commentNotification('1784', SENT_AT, [{ id: '1', text: 'GUIDE', mediaId: 'A' }]))), /database unavailable/);diff --git a/backend/tests/services/instagram/instagramMessaging.test.ts b/backend/tests/services/instagram/instagramMessaging.test.tsnew file mode 100644index 0000000..06bb322--- /dev/null+++ b/backend/tests/services/instagram/instagramMessaging.test.ts@@ -0,0 +1,81 @@+import { test, describe, afterEach } from 'node:test';+import assert from 'node:assert/strict';+import { listConversationMessages, readFollowStatus, sendMessage, sendPrivateReply, subscribeToWebhooks } from '../../../services/instagram/instagramMessaging.ts';+import { installFetch, reply } from '../../fixtures/fakeFetch.ts';+import type { FetchMock, FakeReply, RecordedRequest } from '../../fixtures/fakeFetch.ts';++let fetchMock: FetchMock | null = null;++function answer(respond: (request: RecordedRequest) => FakeReply | Error): FetchMock {+ fetchMock = installFetch(respond);+ return fetchMock;+}++afterEach(() => {+ fetchMock?.restore();+ fetchMock = null;+});++describe('instagram messaging', () => {+ test('a private reply names the comment and a follow-up names the person; both keep who Instagram says received it', async () => {+ const calls = answer(() => reply({ recipient_id: 'igsid-1', message_id: 'mid-1' }));+ assert.deepEqual(await sendPrivateReply('1784', 'TOK', 'c1', 'Hi'), { kind: 'accepted', messageId: 'mid-1', recipientId: 'igsid-1' });+ assert.deepEqual(await sendMessage('1784', 'TOK', { id: 'igsid-1' }, 'Link'), { kind: 'accepted', messageId: 'mid-1', recipientId: 'igsid-1' });+ assert.deepEqual(calls.requests.map(request => JSON.parse(request.body!).recipient), [{ comment_id: 'c1' }, { id: 'igsid-1' }]);+ assert.equal((calls.requests[1].headers as Record<string, string>).Authorization, 'Bearer TOK');+ });++ test('the follow check reads is_user_follow_business with the token in a header, never in the address', async () => {+ const calls = answer(() => reply({ is_user_follow_business: true, id: 'igsid-1' }));+ assert.deepEqual(await readFollowStatus('igsid-1', 'TOK'), { kind: 'following' });+ const url = new URL(calls.requests[0].url);+ assert.deepEqual([url.pathname, url.searchParams.get('fields'), url.searchParams.has('access_token')], ['/v25.0/igsid-1', 'is_user_follow_business', false]);+ fetchMock!.restore();+ answer(() => reply({ is_user_follow_business: false }));+ assert.deepEqual(await readFollowStatus('igsid-1', 'TOK'), { kind: 'not_following' });+ });++ test('a follow check Instagram cannot answer is sorted into ask again, reconnect, or cannot tell', async () => {+ const cases: [FakeReply | Error, string][] = [+ [reply({ error: { message: 'User consent is required to access user profile', code: 230 } }, 400), 'unverifiable'],+ [reply({ id: 'igsid-1' }), 'unverifiable'],+ [reply({ error: { message: 'Invalid OAuth access token', code: 190 } }, 400), 'not_authorized'],+ [reply({ error: { message: 'Too many calls', code: 4 } }, 400), 'retry'],+ [reply({ error: { message: 'Service unavailable', code: 2 } }, 503), 'retry'],+ [new Error('connection reset'), 'retry'],+ ];+ for (const [outcome, kind] of cases) {+ answer(() => outcome);+ assert.equal((await readFollowStatus('igsid-1', 'TOK')).kind, kind);+ fetchMock!.restore();+ }+ });++ test('the conversation with a person is found by their id and read with the account\'s messages, newest first', async () => {+ const calls = answer(request => request.url.includes('/conversations')+ ? reply({ data: [{ id: 'conv-1' }] })+ : reply({ messages: { data: [{ id: 'm2', created_time: '2026-10-16T10:01:00+0000', from: { id: '1784' }, message: 'Hi' }, { id: 'bad' }] } }));+ assert.deepEqual(await listConversationMessages('1784', 'TOK', 'igsid-1'), [{ id: 'm2', createdTime: '2026-10-16T10:01:00+0000', fromId: '1784', text: 'Hi' }]);+ const first = new URL(calls.requests[0].url);+ assert.deepEqual([first.pathname, first.searchParams.get('user_id'), first.searchParams.get('platform')], ['/v25.0/1784/conversations', 'igsid-1', 'instagram']);+ assert.equal(new URL(calls.requests[1].url).pathname, '/v25.0/conv-1');+ assert.equal(calls.requests.length, 2);+ });++ test('a person with no conversation has no messages, and an Instagram error is thrown for the caller to record', async () => {+ answer(() => reply({ data: [] }));+ assert.deepEqual(await listConversationMessages('1784', 'TOK', 'igsid-1'), []);+ fetchMock!.restore();+ answer(() => reply({ error: { message: 'Unsupported get request', code: 100 } }, 400));+ await assert.rejects(listConversationMessages('1784', 'TOK', 'igsid-1'), /Unsupported get request/);+ });++ test('the webhook subscription sends the fields as one list and fails when Instagram does not confirm it', async () => {+ const calls = answer(() => reply({ success: true }));+ await subscribeToWebhooks('1784', 'TOK', ['comments', 'messages']);+ assert.equal(new URL(calls.requests[0].url).searchParams.get('subscribed_fields'), 'comments,messages');+ fetchMock!.restore();+ answer(() => reply({ success: false }));+ await assert.rejects(subscribeToWebhooks('1784', 'TOK', ['comments']), /did not confirm the webhook subscription/);+ });+});diff --git a/backend/tests/services/retentionService.test.ts b/backend/tests/services/retentionService.test.tsindex 057e099..75b12a1 100644--- a/backend/tests/services/retentionService.test.ts+++ b/backend/tests/services/retentionService.test.ts@@ -1,20 +1,40 @@import { test } from 'node:test';import assert from 'node:assert/strict';-import { AUDIT_RETENTION_DAYS, COMMENT_RETENTION_DAYS, createRetentionService } from '../../services/retentionService.ts';+import { AUDIT_RETENTION_DAYS, COMMENT_PURGE_BATCH, COMMENT_RETENTION_DAYS, createRetentionService } from '../../services/retentionService.ts';import type { AutomationCommentRepository } from '../../repositories/automationCommentRepository.ts';import type { AuditRepository } from '../../repositories/auditRepository.ts';+const NOW = Date.parse('2026-10-16T00:00:00Z');++function retention(batches: number[], cutoffs: Record<string, string[]> = { comments: [], audit: [] }) {+ const left = [...batches];+ const comments = {+ purgeCreatedBefore: async (cutoff: string, limit: number) => {+ assert.equal(limit, COMMENT_PURGE_BATCH);+ cutoffs.comments.push(cutoff);+ return left.shift() ?? 0;+ },+ } as unknown as AutomationCommentRepository;+ const audit = { deleteCreatedBefore: async (cutoff: string) => { cutoffs.audit.push(cutoff); return 1; } } as unknown as AuditRepository;+ const log = { info() {}, warn() {}, error() {}, with() { return log; } };+ return createRetentionService({ comments, audit, context: { requestId: 'r', signal: new AbortController().signal, log } });+}+test('comments older than 90 days and audit events older than a year are deleted each day', async () => {- const cutoffs: Record<string, string> = {};- const comments = { deleteCreatedBefore: async (cutoff: string) => { cutoffs.comments = cutoff; return 4; } } as unknown as AutomationCommentRepository;- const audit = { deleteCreatedBefore: async (cutoff: string) => { cutoffs.audit = cutoff; return 1; } } as unknown as AuditRepository;- const logged: unknown[] = [];- const log = { info: (...args: unknown[]) => logged.push(args), warn() {}, error() {}, with() { return log; } };- const now = Date.parse('2026-10-16T00:00:00Z');- const run = await createRetentionService({ comments, audit, context: { requestId: 'r', signal: new AbortController().signal, log } }).purge(now);- assert.deepEqual(run, { comments: 4, auditEvents: 1 });+ const cutoffs: Record<string, string[]> = { comments: [], audit: [] };+ const run = await retention([4], cutoffs).purge(NOW);+ assert.deepEqual(run, { comments: 4, auditEvents: 1, commentsLeft: false });assert.equal(COMMENT_RETENTION_DAYS, 90);assert.equal(AUDIT_RETENTION_DAYS, 365);- assert.deepEqual(cutoffs, { comments: '2026-07-18T00:00:00.000Z', audit: '2025-10-16T00:00:00.000Z' });- assert.equal(logged.length, 1);+ assert.deepEqual(cutoffs, { comments: ['2026-07-18T00:00:00.000Z'], audit: ['2025-10-16T00:00:00.000Z'] });+});++test('a large backlog is deleted in bounded batches until a batch comes back short', async () => {+ const run = await retention([COMMENT_PURGE_BATCH, COMMENT_PURGE_BATCH, 10]).purge(NOW);+ assert.deepEqual(run, { comments: 2 * COMMENT_PURGE_BATCH + 10, auditEvents: 1, commentsLeft: false });+});++test('a backlog larger than the day\'s batches is left for the next day and says so', async () => {+ const run = await retention(Array(5).fill(COMMENT_PURGE_BATCH)).purge(NOW, { commentBatches: 2 });+ assert.deepEqual(run, { comments: 2 * COMMENT_PURGE_BATCH, auditEvents: 1, commentsLeft: true });});diff --git a/backend/tests/validators/automationValidators.test.ts b/backend/tests/validators/automationValidators.test.tsindex 61f78d5..6b0af07 100644--- a/backend/tests/validators/automationValidators.test.ts+++ b/backend/tests/validators/automationValidators.test.ts@@ -11,9 +11,27 @@ test('a new rule gets its defaults: contains, ignoring case, every post, off, noassert.deepEqual(parseAutomationRule(valid), {accountId: 'ig1', name: 'Guide', keywords: ['GUIDE'], matchMode: 'contains', caseSensitive: false, mediaIds: [],replyText: 'Here it is', linkUrl: null, enabled: false, hourlyLimit: null,+ requireFollow: false, followPromptText: null, notFollowingText: null,});});+test('a rule that answers any comment takes no keywords, and a keyword rule still needs one', () => {+ assert.deepEqual(parseAutomationRule({ ...valid, matchMode: 'any', keywords: [] }).keywords, []);+ assert.deepEqual(parseAutomationRule({ ...valid, matchMode: 'any', keywords: undefined }).keywords, []);+ assert.throws(() => parseAutomationRule({ ...valid, matchMode: 'any' }), /answers any comment has no keywords/);+ assert.throws(() => parseAutomationRule({ ...valid, keywords: [] }), /Add at least one keyword/);+ assert.throws(() => parseAutomationTest({ matchMode: 'any', keywords: ['GUIDE'], replyText: 'Hi', comment: 'x' }), /answers any comment has no keywords/);+});++test('a followers-only rule needs both of its messages, each within Instagram\'s size, and keeps them trimmed', () => {+ const rule = parseAutomationRule({ ...valid, requireFollow: true, followPromptText: ' Follow and reply ', notFollowingText: 'Follow first' });+ assert.deepEqual([rule.requireFollow, rule.followPromptText, rule.notFollowingText], [true, 'Follow and reply', 'Follow first']);+ assert.throws(() => parseAutomationRule({ ...valid, requireFollow: true, notFollowingText: 'Follow first' }), /asks people to follow you and reply/);+ assert.throws(() => parseAutomationRule({ ...valid, requireFollow: true, followPromptText: 'Follow' }), /reminder for people who do not follow/);+ assert.throws(() => parseAutomationRule({ ...valid, requireFollow: true, followPromptText: 'x'.repeat(1001), notFollowingText: 'y' }), /at most 1000 characters/);+ assert.deepEqual(parseAutomationRuleUpdate({ requireFollow: false, followPromptText: '' }), { requireFollow: false, followPromptText: null });+});+test('keywords are trimmed, blanks dropped and repeats removed, ignoring case unless the rule is case sensitive', () => {assert.deepEqual(parseAutomationRule({ ...valid, keywords: [' guide ', 'GUIDE', '', 'Course'] }).keywords, ['guide', 'Course']);assert.deepEqual(parseAutomationRule({ ...valid, caseSensitive: true, keywords: ['guide', 'GUIDE'] }).keywords, ['guide', 'GUIDE']);@@ -50,7 +68,7 @@ test('the hourly limit is a whole number up to Instagram\'s 750, or null for nonassert.equal(parseAutomationRule({ ...valid, hourlyLimit: null }).hourlyLimit, null);assert.throws(() => parseAutomationRule({ ...valid, hourlyLimit: 751 }), /from 1 to 750/);assert.throws(() => parseAutomationRule({ ...valid, hourlyLimit: 2.5 }), /from 1 to 750/);- assert.throws(() => parseAutomationRule({ ...valid, matchMode: 'regex' }), /contains or exact/);+ assert.throws(() => parseAutomationRule({ ...valid, matchMode: 'regex' }), /contains, exact or any/);});test('an update keeps only the fields sent, can clear the link and the limit, and refuses an empty body', () => {diff --git a/backend/tests/validators/instagramWebhookValidators.test.ts b/backend/tests/validators/instagramWebhookValidators.test.tsindex 2fb8025..6e0f618 100644--- a/backend/tests/validators/instagramWebhookValidators.test.ts+++ b/backend/tests/validators/instagramWebhookValidators.test.ts@@ -4,7 +4,7 @@ import { parseInstagramWebhook } from '../../validators/instagramWebhookValidatoconst NOW = Date.parse('2026-10-16T12:00:00Z');-test('a comments notification becomes one event per comment, with the time Meta sent it', () => {+test('a comments notification becomes one event per comment, with the time Meta sent it, and no messages', () => {const parsed = parseInstagramWebhook({object: 'instagram',entry: [{@@ -21,6 +21,7 @@ test('a comments notification becomes one event per comment, with the time MetaigUserId: '1784', commentId: '555', text: 'GUIDE', fromId: '77', fromUsername: 'fan', mediaId: '9001',mediaProductType: 'REELS', parentId: '444', notifiedAt: 1792152000 * 1000,}],+ messages: [],unsupported: 0,});});@@ -43,7 +44,44 @@ test('other fields, messaging entries and comments without an id are counted and'junk',],}, NOW);- assert.deepEqual(parsed, { comments: [], unsupported: 5 });+ assert.deepEqual(parsed, { comments: [], messages: [], unsupported: 5 });+});++test('a person\'s message or button tap becomes a message event, without its text, at the time they sent it', () => {+ const parsed = parseInstagramWebhook({+ object: 'instagram',+ entry: [{+ id: '1784',+ time: 1,+ messaging: [+ { sender: { id: '77' }, recipient: { id: '1784' }, timestamp: NOW - 2000, message: { mid: 'm1', text: 'done, I follow you' } },+ { sender: { id: '78' }, recipient: { id: '1784' }, timestamp: NOW - 1000, postback: { mid: 'm2', payload: 'LINK' } },+ ],+ }],+ }, NOW);+ assert.deepEqual(parsed.messages, [+ { igUserId: '1784', senderId: '77', messageId: 'm1', sentAt: NOW - 2000 },+ { igUserId: '1784', senderId: '78', messageId: 'm2', sentAt: NOW - 1000 },+ ]);+ assert.equal(parsed.unsupported, 0);+ assert.equal(JSON.stringify(parsed).includes('I follow you'), false);+});++test('the account\'s own echoes, test messages and deleted messages are skipped without counting as unsupported', () => {+ const parsed = parseInstagramWebhook({+ object: 'instagram',+ entry: [{+ id: '1784',+ messaging: [+ { sender: { id: '1784' }, recipient: { id: '77' }, timestamp: NOW, message: { mid: 'e', is_echo: true } },+ { sender: { id: '77' }, timestamp: NOW, message: { mid: 's', is_self: true } },+ { sender: { id: '77' }, timestamp: NOW, message: { mid: 'd', is_deleted: true } },+ { sender: { id: '1784' }, timestamp: NOW, message: { mid: 'own' } },+ { sender: { id: '77' }, timestamp: NOW, message: { text: 'no id' } },+ ],+ }],+ }, NOW);+ assert.deepEqual(parsed, { comments: [], messages: [], unsupported: 1 });});test('a missing or future time falls back to now', () => {diff --git a/backend/validators/automationValidators.ts b/backend/validators/automationValidators.tsindex a88dcb5..de534d2 100644--- a/backend/validators/automationValidators.ts+++ b/backend/validators/automationValidators.ts@@ -1,4 +1,5 @@import { ValidationError } from '../lib/errors.ts';+import { followTextsProblem, keywordsProblem } from '../lib/automationRules.ts';import { isString, optionalArray, optionalBoolean, optionalNumber, optionalString, presentField, requiredString } from './fields.ts';import type { Fields } from './fields.ts';import type { ActivityCursor } from '../repositories/automationCommentRepository.ts';@@ -7,7 +8,7 @@ import type {AutomationTestRequest,} from '../../shared/types/automation.ts';-const MATCH_MODES: AutomationMatchMode[] = ['contains', 'exact'];+const MATCH_MODES: AutomationMatchMode[] = ['contains', 'exact', 'any'];const STATUSES: AutomationCommentStatus[] = ['ignored', 'queued', 'processing', 'retry_wait', 'sending', 'accepted', 'failed', 'needs_review', 'skipped', 'expired'];const MAX_NAME = 80;const MAX_KEYWORDS = 10;@@ -51,7 +52,8 @@ function name(body: Fields): string {return value;}-// trimmed, without blanks or repeats, so "guide" and "GUIDE " count once when matching ignores case+// trimmed, without blanks or repeats, so "guide" and "GUIDE " count once when matching ignores case; whether the+// list may be empty depends on the match mode, checked with keywordsProblemfunction keywords(body: Fields, caseSensitive: boolean): string[] {const list = optionalArray(body, 'keywords', isString, 'words') ?? [];const seen = new Set<string>();@@ -63,18 +65,36 @@ function keywords(body: Fields, caseSensitive: boolean): string[] {seen.add(key);kept.push(keyword);}- if (kept.length === 0) throw new ValidationError('Add at least one keyword');if (kept.length > MAX_KEYWORDS) throw new ValidationError(`A rule can have at most ${MAX_KEYWORDS} keywords`);return kept;}+function keywordsFor(mode: AutomationMatchMode, list: string[]): string[] {+ const problem = keywordsProblem(mode, list);+ if (problem) throw new ValidationError(problem);+ return list;+}+function matchMode(body: Fields): AutomationMatchMode | undefined {const value = optionalString(body, 'matchMode');if (!value) return undefined;- if (!MATCH_MODES.includes(value as AutomationMatchMode)) throw new ValidationError('matchMode must be contains or exact');+ if (!MATCH_MODES.includes(value as AutomationMatchMode)) throw new ValidationError('matchMode must be contains, exact or any');return value as AutomationMatchMode;}+// a followers-only message: absent leaves it as it is, empty clears it+function followText(body: Fields, field: 'followPromptText' | 'notFollowingText', label: string): string | null | undefined {+ if (!presentField(body, field)) return undefined;+ const value = optionalString(body, field)?.trim();+ if (!value) return null;+ if (value.length > MAX_REPLY) throw new ValidationError(`${label} can be at most ${MAX_REPLY} characters`);+ return value;+}++const FOLLOW_PROMPT_LABEL = 'The message asking people to follow and reply';+const NOT_FOLLOWING_LABEL = 'The reminder for people who do not follow yet';++function mediaIds(body: Fields): string[] | undefined {const list = optionalArray(body, 'mediaIds', isString, 'post ids');if (!list) return undefined;@@ -146,21 +166,29 @@ function statuses(query: Fields): AutomationCommentStatus[] | undefined {export function parseAutomationRule(body: Fields): AutomationRuleRequest {const caseSensitive = optionalBoolean(body, 'caseSensitive') ?? false;- return {+ const mode = matchMode(body) ?? 'contains';+ const rule = {accountId: requiredString(body, 'accountId', 'Choose the Instagram account'),name: name(body),- keywords: keywords(body, caseSensitive),- matchMode: matchMode(body) ?? 'contains',+ keywords: keywordsFor(mode, keywords(body, caseSensitive)),+ matchMode: mode,caseSensitive,mediaIds: mediaIds(body) ?? [],replyText: replyText(body),linkUrl: linkUrl(body) ?? null,enabled: optionalBoolean(body, 'enabled') ?? false,hourlyLimit: hourlyLimit(body) ?? null,+ requireFollow: optionalBoolean(body, 'requireFollow') ?? false,+ followPromptText: followText(body, 'followPromptText', FOLLOW_PROMPT_LABEL) ?? null,+ notFollowingText: followText(body, 'notFollowingText', NOT_FOLLOWING_LABEL) ?? null,};+ const problem = followTextsProblem(rule);+ if (problem) throw new ValidationError(problem);+ return rule;}-// only the fields present in the body change; accountId is ignored, a rule stays on its account+// only the fields present in the body change; accountId is ignored, a rule stays on its account. Rules that span+// fields, such as keywords for the match mode, are checked by the service against the rule as it will be savedexport function parseAutomationRuleUpdate(body: Fields): AutomationRuleUpdateRequest {const changes: AutomationRuleUpdateRequest = {};const caseSensitive = optionalBoolean(body, 'caseSensitive');@@ -173,6 +201,9 @@ export function parseAutomationRuleUpdate(body: Fields): AutomationRuleUpdateReqif (presentField(body, 'linkUrl')) changes.linkUrl = linkUrl(body);if (presentField(body, 'enabled')) changes.enabled = optionalBoolean(body, 'enabled');if (presentField(body, 'hourlyLimit')) changes.hourlyLimit = hourlyLimit(body);+ if (presentField(body, 'requireFollow')) changes.requireFollow = optionalBoolean(body, 'requireFollow');+ if (presentField(body, 'followPromptText')) changes.followPromptText = followText(body, 'followPromptText', FOLLOW_PROMPT_LABEL);+ if (presentField(body, 'notFollowingText')) changes.notFollowingText = followText(body, 'notFollowingText', NOT_FOLLOWING_LABEL);if (Object.keys(changes).length === 0) throw new ValidationError('Nothing to change: send at least one rule field');return changes;}@@ -181,13 +212,16 @@ export function parseAutomationTest(body: Fields): AutomationTestRequest {const caseSensitive = optionalBoolean(body, 'caseSensitive') ?? false;const comment = requiredString(body, 'comment', 'Type a sample comment to test');if (comment.length > MAX_TEST_COMMENT) throw new ValidationError(`A comment can be at most ${MAX_TEST_COMMENT} characters`);+ const mode = matchMode(body) ?? 'contains';return {- keywords: keywords(body, caseSensitive),- matchMode: matchMode(body) ?? 'contains',+ keywords: keywordsFor(mode, keywords(body, caseSensitive)),+ matchMode: mode,caseSensitive,mediaIds: mediaIds(body) ?? [],replyText: replyText(body),linkUrl: linkUrl(body) ?? null,+ requireFollow: optionalBoolean(body, 'requireFollow') ?? false,+ followPromptText: followText(body, 'followPromptText', FOLLOW_PROMPT_LABEL) ?? null,comment,mediaId: optionalString(body, 'mediaId') || undefined,};diff --git a/backend/validators/instagramWebhookValidators.ts b/backend/validators/instagramWebhookValidators.tsindex ba29c39..9721394 100644--- a/backend/validators/instagramWebhookValidators.ts+++ b/backend/validators/instagramWebhookValidators.ts@@ -17,8 +17,19 @@ export interface InstagramCommentEvent {notifiedAt: number;}+// a person's message or button tap in a conversation with a connected account; its text is not read+export interface InstagramMessageEvent {+ // the professional account that received it (the entry id)+ igUserId: string;+ senderId: string;+ messageId: string;+ // when the person sent it, in milliseconds+ sentAt: number;+}+export interface InstagramWebhook {comments: InstagramCommentEvent[];+ messages: InstagramMessageEvent[];// changes for other fields, or comments missing their id, which are acknowledged and droppedunsupported: number;}@@ -52,12 +63,34 @@ function comment(entryId: string, notifiedAt: number, value: Fields): InstagramC};}-// a body that is not an Instagram notification at all is refused; inside one, anything but a comment is skipped+// a message the person sent, or 'expected' for the account's own echoes, test messages and deletions, which are normal+// traffic once messages are subscribed but not answers; null for anything that cannot be used+function message(entryId: string, now: number, value: Fields): InstagramMessageEvent | 'expected' | null {+ const sender = isObject(value.sender) ? id(value.sender.id) : null;+ if (isObject(value.message) && (value.message.is_echo === true || value.message.is_self === true || value.message.is_deleted === true)) return 'expected';+ if (!sender) return null;+ if (sender === entryId) return 'expected';+ const sentAt = typeof value.timestamp === 'number' && value.timestamp > 0 ? Math.min(value.timestamp, now) : now;+ if (isObject(value.message)) {+ const { mid } = value.message;+ const messageId = typeof mid === 'string' && mid.length <= 512 ? mid : null;+ return messageId ? { igUserId: entryId, senderId: sender, messageId, sentAt } : null;+ }+ if (isObject(value.postback)) {+ const messageId = typeof value.postback.mid === 'string' && value.postback.mid.length <= 512 ? value.postback.mid : null;+ return messageId ? { igUserId: entryId, senderId: sender, messageId, sentAt } : null;+ }+ return null;+}++// a body that is not an Instagram notification at all is refused; inside one, anything but a comment or a person's+// message is skippedexport function parseInstagramWebhook(body: Fields, now = Date.now()): InstagramWebhook {if (body.object !== 'instagram') throw new ValidationError('Only Instagram webhook notifications are accepted here');if (!Array.isArray(body.entry)) throw new ValidationError('The notification has no entry list');const comments: InstagramCommentEvent[] = [];+ const messages: InstagramMessageEvent[] = [];let unsupported = 0;for (const entry of body.entry) {const entryId = isObject(entry) ? id(entry.id) : null;@@ -65,6 +98,15 @@ export function parseInstagramWebhook(body: Fields, now = Date.now()): Instagramunsupported++;continue;}+ // messaging events carry their own millisecond timestamps+ if (Array.isArray(entry.messaging)) {+ for (const event of entry.messaging) {+ const parsed = isObject(event) ? message(entryId, now, event) : null;+ if (parsed === null) unsupported++;+ else if (parsed !== 'expected') messages.push(parsed);+ }+ continue;+ }// time is in seconds; a missing or odd value falls back to now, and a reply sent after Instagram's window is refused thereconst sentAt = typeof entry.time === 'number' && entry.time > 0 ? Math.min(entry.time * 1000, now) : now;const changes = Array.isArray(entry.changes) ? entry.changes : [];@@ -77,5 +119,5 @@ export function parseInstagramWebhook(body: Fields, now = Date.now()): Instagramelse unsupported++;}}- return { comments, unsupported };+ return { comments, messages, unsupported };}diff --git a/backend/wrangler.toml b/backend/wrangler.tomlindex 94989a9..cc94b67 100644--- a/backend/wrangler.toml+++ b/backend/wrangler.toml@@ -3,4 +3,4 @@ main = "server.ts"compatibility_date = "2025-01-01"[triggers]-crons = ["*/5 * * * *", "0 0 * * *"]+crons = ["* * * * *", "*/5 * * * *", "0 0 * * *"]diff --git a/shared/types/automation.ts b/shared/types/automation.tsindex 732db61..b1f207d 100644--- a/shared/types/automation.ts+++ b/shared/types/automation.ts@@ -1,5 +1,6 @@-// how a rule's keywords are compared with a comment: anywhere as whole words, or as the whole comment-export type AutomationMatchMode = 'contains' | 'exact';+// how a rule's keywords are compared with a comment: anywhere as whole words, or as the whole comment; any answers+// every comment with text in it and has no keywords+export type AutomationMatchMode = 'contains' | 'exact' | 'any';// the life of a received comment; ignored ones matched no rule, the rest are reply jobsexport type AutomationCommentStatus =@@ -9,6 +10,15 @@ export type AutomationCommentStatus =// what one private reply request to Instagram ended asexport type AutomationAttemptOutcome = 'sending' | 'accepted' | 'rejected' | 'rate_limited' | 'ambiguous';+// a followers-only reply: waiting for the person to answer, link sent, or every reminder used+export type AutomationGateStatus = 'awaiting_reply' | 'completed' | 'closed';++// the message sent after the person answered: the reply and link once they follow, a reminder otherwise+export type AutomationFollowupKind = 'link' | 'reminder';++// a follow-up message moves through the same states as a reply, except ignored+export type AutomationFollowupStatus = Exclude<AutomationCommentStatus, 'ignored'>;+export interface AutomationRule {id: string;accountId: string;@@ -23,6 +33,10 @@ export interface AutomationRule {enabled: boolean;// null uses only the account's limithourlyLimit: number | null;+ // the private reply asks the person to follow and answer; the reply and link go out once Instagram says they follow+ requireFollow: boolean;+ followPromptText: string | null;+ notFollowingText: string | null;createdAt: string;updatedAt: string;}@@ -39,6 +53,9 @@ export interface AutomationRuleRequest {linkUrl?: string | null;enabled?: boolean;hourlyLimit?: number | null;+ requireFollow?: boolean;+ followPromptText?: string | null;+ notFollowingText?: string | null;}// body of PUT /api/automations/rules/:id; a rule stays on its account@@ -54,6 +71,10 @@ export interface AutomationAccountState {cooldownReason: string | null;// when Instagram confirmed it sends this account's comments to the webhooksubscribedAt: string | null;+ // the account reached its hourly reply limit; its replies wait until then+ limitedUntil: string | null;+ // Instagram also sends this account's messages, which followers-only rules need+ messagesSubscribed: boolean;}export interface AutomationLimits {@@ -87,6 +108,16 @@ export interface AutomationActivityItem {acceptedAt: string | null;expiresAt: string;createdAt: string;+ // followers-only rules: where the wait for the person's answer stands, and the latest message sent after it+ gateStatus: AutomationGateStatus | null;+ followup: AutomationFollowupState | null;+}++export interface AutomationFollowupState {+ status: AutomationFollowupStatus;+ kind: AutomationFollowupKind | null;+ errorMessage: string | null;+ createdAt: string;}export interface AutomationStats {@@ -116,6 +147,8 @@ export interface AutomationTestRequest {mediaIds?: string[];replyText: string;linkUrl?: string | null;+ requireFollow?: boolean;+ followPromptText?: string | null;comment: string;mediaId?: string;}@@ -123,9 +156,9 @@ export interface AutomationTestRequest {export interface AutomationTestResponse {success: true;matched: boolean;- // the keyword that matched, or null+ // the keyword that matched, or null, as for an any-comment rulekeyword: string | null;- // the private reply exactly as it would be sent+ // the private reply exactly as it would be sent; for a followers-only rule, the request to follow and answermessage: string;messageBytes: number;maxMessageBytes: number;diff --git a/supabase/migrations/20261016122100_create_automation_review_candidates_function.sql b/supabase/migrations/20261016122100_create_automation_review_candidates_function.sqlindex 00292f1..e38ada8 100644--- a/supabase/migrations/20261016122100_create_automation_review_candidates_function.sql+++ b/supabase/migrations/20261016122100_create_automation_review_candidates_function.sql@@ -13,13 +13,14 @@ returns table (from_id text,started_at timestamptz,message_digest text,- access_token text+ access_token text,+ review_checks integer)language sqlstableset search_path = ''as $$- select c.id, c.ig_user_id, c.from_id, t.started_at, t.message_digest, a.data ->> 'accessToken'+ select c.id, c.ig_user_id, c.from_id, t.started_at, t.message_digest, a.data ->> 'accessToken', c.review_checksfrom public.automation_comments cjoin lateral (select t.started_at, t.message_digest