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): post public comment replies alongside private replies
spacesdrive3938a71d2d8f
diff --git a/backend/container.ts b/backend/container.tsindex 0977bae..7c3c45c 100644--- a/backend/container.ts+++ b/backend/container.ts@@ -9,6 +9,7 @@ import { createAutomationRuleRepository } from './repositories/automationRuleRepimport { createAutomationCommentRepository } from './repositories/automationCommentRepository.ts';import { createAutomationAccountRepository } from './repositories/automationAccountRepository.ts';import { createAutomationFollowupRepository } from './repositories/automationFollowupRepository.ts';+import { createAutomationPublicReplyRepository } from './repositories/automationPublicReplyRepository.ts';import { createAccountService } from './services/accountService.ts';import { createYouTubeAnalyticsService } from './services/youtubeAnalyticsService.ts';import { createInstagramAnalyticsService } from './services/instagramAnalyticsService.ts';@@ -26,6 +27,7 @@ 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 { createAutomationPublicReplyProcessor } from './services/automationPublicReplyProcessor.ts';import { createAutomationReconciler } from './services/automationReconciler.ts';import { createRetentionService } from './services/retentionService.ts';import type { AccountService } from './services/accountService.ts';@@ -45,6 +47,7 @@ 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 { AutomationPublicReplyProcessor } from './services/automationPublicReplyProcessor.ts';import type { AutomationReconciler } from './services/automationReconciler.ts';import type { RetentionService } from './services/retentionService.ts';import type { AppConfig } from './lib/config.ts';@@ -76,6 +79,7 @@ export interface Services {automationWebhook: AutomationWebhookService;automationProcessor: AutomationProcessor;automationFollowups: AutomationFollowupProcessor;+ automationPublicReplies: AutomationPublicReplyProcessor;automationReconciler: AutomationReconciler;retention: RetentionService;}@@ -92,6 +96,7 @@ export function createServices(clients: Clients, config: AppConfig, context: Reqconst comments = createAutomationCommentRepository(clients.supabase);const automationAccounts = createAutomationAccountRepository(clients.supabase);const followups = createAutomationFollowupRepository(clients.supabase);+ const publicReplies = createAutomationPublicReplyRepository(clients.supabase);const { automation } = config;const scheduledPublisher = createScheduledPublisher({ accounts, posts, context });return {@@ -108,11 +113,12 @@ 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, followups, automationAccounts, audit, automation, context }),+ automations: createAutomationService({ accounts, rules, comments, followups, publicReplies, 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 }),+ automationPublicReplies: createAutomationPublicReplyProcessor({ publicReplies, automation, context }),+ automationReconciler: createAutomationReconciler({ comments, publicReplies, context }),retention: createRetentionService({ comments, audit, context }),};}diff --git a/backend/controllers/automationController.ts b/backend/controllers/automationController.tsindex 15f5d28..8ae3cb9 100644--- a/backend/controllers/automationController.ts+++ b/backend/controllers/automationController.ts@@ -61,6 +61,14 @@ export const retryAutomationActivity = controller.createHandlers(async c => {return c.json({ success: true, item } satisfies AutomationActivityItemResponse);});+// only the public reply goes back in the queue, and this request starts posting it+export const retryAutomationPublicReply = controller.createHandlers(async c => {+ const { item, publicReplyId } = await servicesFor(c).automations.retryPublicReply(c.get('userId'), pathParam(c, 'id'));+ const subrequests = FREE_PLAN_SUBREQUESTS - REQUEST_SUBREQUESTS;+ inBackground(c, 'automation public reply retry', services => services.automationPublicReplies.run({ ids: [publicReplyId], subrequests }));+ return c.json({ success: true, item } satisfies AutomationActivityItemResponse);+});+export const updateAutomationAccount = controller.createHandlers(jsonBody(parseAutomationAccount), async c => {const account = await servicesFor(c).automations.setPaused(c.get('userId'), pathParam(c, 'accountId'), c.req.valid('json').paused);return c.json({ success: true, account } satisfies AutomationAccountResponse);diff --git a/backend/controllers/instagramWebhookController.ts b/backend/controllers/instagramWebhookController.tsindex 2ccc21c..a311903 100644--- a/backend/controllers/instagramWebhookController.ts+++ b/backend/controllers/instagramWebhookController.ts@@ -2,7 +2,7 @@ import { controller, inBackground, servicesFor } from './http.ts';import { jsonBody, queryParams } from '../middleware/validate.ts';import { parseWebhookVerification } from '../validators/automationValidators.ts';import { parseInstagramWebhook } from '../validators/instagramWebhookValidators.ts';-import { FREE_PLAN_SUBREQUESTS, REQUEST_SUBREQUESTS } from '../lib/automationDelivery.ts';+import { BACKGROUND_RUN_MS, FREE_PLAN_SUBREQUESTS, REQUEST_SUBREQUESTS } from '../lib/automationDelivery.ts';// called by Meta when the webhook is saved in its dashboard; the answer is the bare challenge, not JSONexport const verifyInstagramWebhook = controller.createHandlers(queryParams(parseWebhookVerification), async c => {@@ -11,15 +11,21 @@ export const verifyInstagramWebhook = controller.createHandlers(queryParams(pars});// 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 response+// before the 200, so Meta keeps retrying for 36 hours if storing fails; the replies go out after the response, private+// ones first, and anything this request cannot send waits for the next dispatchexport const receiveInstagramWebhook = controller.createHandlers(jsonBody(body => parseInstagramWebhook(body)), async c => {- const { queuedIds, followupIds, subrequests } = await servicesFor(c).automationWebhook.ingest(c.req.valid('json'));+ const { queuedIds, publicReplyIds, 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 || followupIds.length > 0) {+ if (queuedIds.length > 0 || followupIds.length > 0 || publicReplyIds.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) });+ // the three kinds share the background work's time as well as its subrequests+ const started = Date.now();+ const timeBudgetMs = () => BACKGROUND_RUN_MS - (Date.now() - started);+ let spent = 0;+ if (queuedIds.length > 0) spent += (await services.automationProcessor.run({ ids: queuedIds, subrequests: left, timeBudgetMs: timeBudgetMs() })).subrequests;+ if (followupIds.length > 0) spent += (await services.automationFollowups.run({ ids: followupIds, subrequests: left - spent, timeBudgetMs: timeBudgetMs() })).subrequests;+ if (publicReplyIds.length > 0) await services.automationPublicReplies.run({ ids: publicReplyIds, subrequests: left - spent, timeBudgetMs: timeBudgetMs() });});}return c.json({ success: true });diff --git a/backend/jobs/scheduled.ts b/backend/jobs/scheduled.tsindex 7e4ccca..14dfd88 100644--- a/backend/jobs/scheduled.ts+++ b/backend/jobs/scheduled.ts@@ -18,6 +18,9 @@ const PUBLISH_EVERY_MINUTES = 15;// 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 apartconst DISPATCH_TIME_MS = 50 * 1000;+// public replies always keep room for three a run, 180 an hour, above their default limit of 60, so private replies+// and follow-ups can never crowd them out+const PUBLIC_REPLY_SUBREQUESTS = 11;// the daily run refreshes tokens first; retention gets this many batches of the run's subrequestsconst RETENTION_BATCHES = 20;@@ -29,7 +32,7 @@ function cronContext(cron: string): RequestContext {return { requestId, signal: AbortSignal.timeout(CRON_DEADLINE_MS), log: createLogger({ requestId, cron }) };}-// dispatch sends due replies and follow-ups; publish sends due posts; reconcile expires, checks lost replies and reports+// dispatch sends due replies, follow-ups and public replies; publish sends due posts; reconcile expires, checks lost replies and reports// the queue's health; daily refreshes tokens and removes old dataexport type CronPlan = 'dispatch' | 'publish' | 'reconcile' | 'daily' | 'none';@@ -41,12 +44,20 @@ export function cronPlan(cron: string, scheduledTime: number): CronPlan {return new Date(scheduledTime).getUTCMinutes() % PUBLISH_EVERY_MINUTES === 0 ? 'publish' : 'reconcile';}-// private replies first, then follow-ups with what is left of the run's 50 subrequests+// private replies first, since Instagram allows them only for 7 days and a public reply often points to them, then+// follow-ups, then public replies with what is left of the run's 50 subrequests and timeasync 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 } });+ const started = Date.now();+ const timeLeft = () => DISPATCH_TIME_MS - (Date.now() - started);+ const replies = await services.automationProcessor.run({ subrequests: FREE_PLAN_SUBREQUESTS - PUBLIC_REPLY_SUBREQUESTS, timeBudgetMs: timeLeft() });+ const followups = await services.automationFollowups.run({ subrequests: FREE_PLAN_SUBREQUESTS - PUBLIC_REPLY_SUBREQUESTS - replies.subrequests, timeBudgetMs: timeLeft() });+ const publicReplies = await services.automationPublicReplies.run({ subrequests: FREE_PLAN_SUBREQUESTS - replies.subrequests - followups.subrequests, timeBudgetMs: timeLeft() });+ if (replies.claimed > 0 || followups.claimed > 0 || publicReplies.claimed > 0) {+ context.log.info('automation dispatch', {+ replies: { claimed: replies.claimed, ...replies.outcomes },+ followups: { claimed: followups.claimed, ...followups.outcomes },+ publicReplies: { claimed: publicReplies.claimed, ...publicReplies.outcomes },+ });}}diff --git a/backend/lib/automationDelivery.ts b/backend/lib/automationDelivery.tsindex 6f6d827..86d3058 100644--- a/backend/lib/automationDelivery.ts+++ b/backend/lib/automationDelivery.ts@@ -41,7 +41,7 @@ export const MAX_FOLLOW_REMINDERS = 2;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 week-const HOLD_RECHECK_MS = 15 * 60 * 1000;+export const HOLD_RECHECK_MS = 15 * 60 * 1000;// backoff: 1, 2, 4, 8 minutes, then at most an hour, plus up to 30 seconds so retries of one burst spread outconst BACKOFF_BASE_MS = 60 * 1000;@@ -49,11 +49,11 @@ const BACKOFF_MAX_MS = 60 * 60 * 1000;const BACKOFF_JITTER_MS = 30 * 1000;// the next sweep, when a run could not start the request-const NOT_SENT_RETRY_MS = 5 * 60 * 1000;+export const NOT_SENT_RETRY_MS = 5 * 60 * 1000;// used when Instagram limits the account without saying for how long-const DEFAULT_COOLDOWN_MS = 15 * 60 * 1000;+export const DEFAULT_COOLDOWN_MS = 15 * 60 * 1000;// code 368 is a temporary block for activity Instagram considers abusive, so the account rests for a day-const BLOCKED_COOLDOWN_MS = 24 * 60 * 60 * 1000;+export const BLOCKED_COOLDOWN_MS = 24 * 60 * 60 * 1000;// Graph API codes Meta documents for throttling: app, user, page and business use case limitsconst RATE_LIMIT_CODES = new Set([4, 17, 32, 613, 80002, 80006]);diff --git a/backend/lib/automationHealth.ts b/backend/lib/automationHealth.tsindex d309deb..f4d86ca 100644--- a/backend/lib/automationHealth.ts+++ b/backend/lib/automationHealth.ts@@ -10,6 +10,11 @@ export interface QueueHealth {stale: number;needsReview: number;followupsDue: number;+ // public replies under comments: due now, the oldest due, held by runs that stopped, and of unknown outcome+ publicDue: number;+ publicOldestDueAt: string | null;+ publicStale: number;+ publicNeedsReview: number;pausedAccounts: number;limitedAccounts: number;}@@ -20,5 +25,8 @@ export function healthWarning(health: QueueHealth, now: number): string | null {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`);+ const publicBehindMs = health.publicOldestDueAt ? now - Date.parse(health.publicOldestDueAt) : 0;+ if (publicBehindMs > BEHIND_AFTER_MS) problems.push(`the oldest due public reply has waited ${Math.round(publicBehindMs / 60_000)} minutes`);+ if (health.publicStale > 0) problems.push(`${health.publicStale} public replies are held by runs that stopped`);return problems.length > 0 ? `automation queue behind: ${problems.join('; ')}` : null;}diff --git a/backend/lib/automationPublicReply.ts b/backend/lib/automationPublicReply.tsnew file mode 100644index 0000000..35c5277--- /dev/null+++ b/backend/lib/automationPublicReply.ts@@ -0,0 +1,201 @@+import {+ BLOCKED_COOLDOWN_MS, DEFAULT_COOLDOWN_MS, HOLD_RECHECK_MS, MAX_SEND_ATTEMPTS, NOT_SENT_RETRY_MS, classifySendError, cooldownFromUsage, retryDelayMs,+} from './automationDelivery.ts';+import type { ReleasePlan, ReserveOutcome, SendErrorKind, SendResult } from './automationDelivery.ts';+import type { AutomationAttemptOutcome, AutomationPublicReplyStatus } from '../../shared/types/automation.ts';++// the rules for a public reply under a comment; the private reply's rules are in automationDelivery.ts++// a rule rotates between at most five texts, so a busy post does not fill with the same words+export const MAX_PUBLIC_REPLY_TEXTS = 5;+// Instagram allows 2,200 characters in a comment; a short reply reads as a person's and is less likely to look like spam+export const MAX_PUBLIC_REPLY_CHARS = 300;+// Instagram's older API refused comments with more than 4 hashtags or more than 1 link; the same bounds keep replies safe+const MAX_PUBLIC_HASHTAGS = 4;+const MAX_PUBLIC_LINKS = 1;++// reserve, send and finish+export const SUBREQUESTS_PER_PUBLIC_REPLY = 3;++// a lost answer is looked for five minutes after the attempt, then every five minutes; the comment's replies show up+// within seconds, so two checks that miss it mean it never arrived+export const PUBLIC_REVIEW_SETTLE_SECONDS = 5 * 60;+export const PUBLIC_REVIEW_RECHECK_SECONDS = 5 * 60;+export const PUBLIC_REVIEW_MAX_CHECKS = 3;+const RESEND_AFTER_CHECKS = 2;+// a reply is sent again at most once after a lost answer; a second lost answer is left to a person+const MAX_LOST_ANSWERS_BEFORE_RESEND = 1;+// each check reads up to two pages of replies and records what it found+export const MAX_REPLY_PAGES = 2;+export const SUBREQUESTS_PER_PUBLIC_REVIEW = MAX_REPLY_PAGES + 1;+export const PUBLIC_REVIEW_BATCH = 5;++// Graph API code 100 with subcode 33: the comment no longer exists or cannot be seen, as for a deleted or hidden comment+const MISSING_OBJECT_CODE = 100;+const MISSING_OBJECT_SUBCODE = 33;++const HASHTAG = /(^|\s)#[\p{L}\p{N}_]+/gu;+const LINK = /\bhttps?:\/\/\S+|\bwww\.\S+/gi;++// one claimed public reply, as the delivery rules need it; attempts already counts the send being settled+export interface PublicReplyJob {+ attempts: number;+ expiresAt: string;+}++// one finish_automation_public_reply call+export interface PublicFinishPlan {+ status: AutomationPublicReplyStatus;+ outcome: AutomationAttemptOutcome;+ reason: string | null;+ errorMessage: string | null;+ replyId: string | null;+ errorCode: number | null;+ errorSubcode: number | null;+ httpStatus: number | null;+ nextAttemptAt: string | null;+ cooldownUntil: string | null;+ cooldownReason: string | null;+ pauseReason: string | null;+}++export const PUBLIC_ERROR_MESSAGES: Record<SendErrorKind, string> = {+ rate_limited: 'Instagram is limiting this account\'s requests for now. The public reply goes out after the cooldown.',+ blocked: 'Instagram has temporarily blocked comments from this account. Public replies wait a day; check the account in the Instagram app. Private replies are not affected.',+ transient: 'Instagram had a temporary problem. The public reply is tried again.',+ already_replied: 'Instagram refused the public reply.',+ not_authorized: 'Instagram refused this account\'s permission to reply to comments. Replies are held: reconnect the account on the Accounts page, then resume it.',+ not_eligible: 'Instagram does not allow a public reply to this comment: it may be deleted or hidden, or on a live video.',+ refused: 'Instagram refused the public reply.',+};++const PUBLIC_LIMIT_MESSAGES: Partial<Record<ReserveOutcome, string>> = {+ cooldown: 'Waiting for Instagram\'s cooldown on this account\'s public replies to end.',+ account_limit: 'Waiting: this account reached its hourly limit for public replies.',+};++const PUBLIC_EXPIRED_MESSAGE = 'This public reply waited 7 days without going out, so Twiligent stopped trying.';++// what is wrong with one public reply text, or null when Instagram should take it+export function publicReplyTextProblem(text: string): string | null {+ if (text.length > MAX_PUBLIC_REPLY_CHARS) return `A public reply can be at most ${MAX_PUBLIC_REPLY_CHARS} characters`;+ if ((text.match(HASHTAG) ?? []).length > MAX_PUBLIC_HASHTAGS) return `A public reply can have at most ${MAX_PUBLIC_HASHTAGS} hashtags`;+ if ((text.match(LINK) ?? []).length > MAX_PUBLIC_LINKS) return `A public reply can have at most ${MAX_PUBLIC_LINKS} link; put the rest in the private reply`;+ return null;+}++// the same comment always gets the same text, so a redelivered notification and every check agree on the words;+// FNV-1a spreads neighbouring comment ids across the texts+export function pickPublicReplyText(texts: string[], commentId: string): string {+ let hash = 0x811c9dc5;+ for (let index = 0; index < commentId.length; index++) {+ hash ^= commentId.charCodeAt(index);+ hash = Math.imul(hash, 0x01000193) >>> 0;+ }+ return texts[hash % texts.length];+}++// a wait that ends after the reply's 7 days would only fail, so it expires instead+function waitUntil(at: number, job: PublicReplyJob, reason: string, message: string): Pick<PublicFinishPlan, 'status' | 'reason' | 'errorMessage' | 'nextAttemptAt'> {+ if (at >= Date.parse(job.expiresAt)) return { status: 'expired', reason: 'expired', errorMessage: PUBLIC_EXPIRED_MESSAGE, nextAttemptAt: null };+ return { status: 'retry_wait', reason, errorMessage: message, nextAttemptAt: new Date(at).toISOString() };+}++function emptyPlan(): Omit<PublicFinishPlan, 'status' | 'outcome'> {+ return {+ reason: null, errorMessage: null, replyId: null, errorCode: null, errorSubcode: null, httpStatus: null,+ nextAttemptAt: null, cooldownUntil: null, cooldownReason: null, pauseReason: null,+ };+}++// what to record for the answer to one public reply; accepted only when Instagram returned the new reply's id+export function publicFinishPlan(result: SendResult, job: PublicReplyJob, now: number, random: () => number = Math.random): PublicFinishPlan {+ if (result.kind === 'accepted') return { ...emptyPlan(), status: 'accepted', outcome: 'accepted', replyId: result.messageId };+ if (result.kind === 'not_sent') {+ return { ...emptyPlan(), ...waitUntil(now + NOT_SENT_RETRY_MS, job, 'not_sent', `The public reply was not sent (${result.message}). It is tried again on the next run.`), outcome: 'rejected' };+ }+ if (result.kind === 'ambiguous') {+ return {+ ...emptyPlan(),+ status: 'needs_review',+ outcome: 'ambiguous',+ reason: 'no_answer',+ errorMessage: `Instagram did not answer (${result.message}), so the public reply may or may not be there. Twiligent checks the comment's replies and sends it again only if it is not there.`,+ };+ }++ const details = { ...emptyPlan(), errorCode: result.code ?? null, errorSubcode: result.subcode ?? null, httpStatus: result.httpStatus };+ const kind: SendErrorKind = result.code === MISSING_OBJECT_CODE && result.subcode === MISSING_OBJECT_SUBCODE ? 'not_eligible' : classifySendError(result);+ const message = kind === 'refused' || kind === 'already_replied'+ ? `${PUBLIC_ERROR_MESSAGES.refused} ${result.message}`.trim().slice(0, 500)+ : PUBLIC_ERROR_MESSAGES[kind];++ if (kind === 'rate_limited' || kind === 'blocked') {+ const until = now + (kind === 'blocked' ? BLOCKED_COOLDOWN_MS : cooldownFromUsage(result.usageHeader));+ return {+ ...details,+ ...waitUntil(until, job, kind, message),+ outcome: kind === 'rate_limited' ? 'rate_limited' : 'rejected',+ cooldownUntil: new Date(until).toISOString(),+ cooldownReason: PUBLIC_ERROR_MESSAGES[kind],+ };+ }+ if (kind === 'transient' && job.attempts < MAX_SEND_ATTEMPTS) {+ return { ...details, ...waitUntil(now + retryDelayMs(job.attempts, random), job, kind, message), outcome: 'rejected' };+ }+ if (kind === 'not_eligible') return { ...details, status: 'skipped', outcome: 'rejected', reason: kind, errorMessage: message };+ if (kind === 'not_authorized') {+ // the token is the account's, so private replies are held too until the owner fixes the account+ return {+ ...details,+ status: 'queued',+ outcome: 'rejected',+ reason: 'paused',+ errorMessage: message,+ nextAttemptAt: new Date(now + HOLD_RECHECK_MS).toISOString(),+ pauseReason: PUBLIC_ERROR_MESSAGES.not_authorized,+ };+ }+ const finalMessage = kind === 'transient' ? `Instagram had a temporary problem. Sending stopped after ${MAX_SEND_ATTEMPTS} tries.` : message;+ return { ...details, status: 'failed', outcome: 'rejected', reason: kind, errorMessage: finalMessage };+}++// a claimed public reply that cannot go out as it is, checked before any limit is spent; null means it may go ahead+export function publicReadinessPlan(job: { ruleEnabled: boolean; accessToken: string | null; expiresAt: string }, now: number): ReleasePlan | null {+ if (now >= Date.parse(job.expiresAt)) return { status: 'expired', reason: 'expired', errorMessage: PUBLIC_EXPIRED_MESSAGE, nextAttemptAt: null };+ if (!job.ruleEnabled) {+ return { status: 'skipped', reason: 'rule_disabled', errorMessage: 'The rule, or its public reply, was turned off before the reply was sent.', 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;+}++// where a public reply goes when the reservation says no; null when it was sent (ok) or is no longer this run's (gone)+export function publicReleasePlan(outcome: ReserveOutcome, retryAt: string | null, job: PublicReplyJob, now: number): ReleasePlan | null {+ if (outcome === 'ok' || outcome === 'gone') return null;+ if (outcome === 'paused') {+ return { status: 'queued', reason: 'paused', errorMessage: 'Held while automation for this account is paused.', nextAttemptAt: new Date(now + HOLD_RECHECK_MS).toISOString() };+ }+ if (outcome === 'recipient_limit') {+ return { status: 'skipped', reason: outcome, errorMessage: 'This person already got a public reply on this post today, so no second one was sent.', nextAttemptAt: null };+ }+ const at = retryAt ? Date.parse(retryAt) : now + DEFAULT_COOLDOWN_MS;+ const message = PUBLIC_LIMIT_MESSAGES[outcome] ?? 'Waiting for a limit on public replies to free up.';+ const { status, reason, errorMessage, nextAttemptAt } = waitUntil(at, job, outcome, message);+ return { status, reason: reason ?? outcome, errorMessage, nextAttemptAt };+}++// whether a reply not found among the comment's replies goes out again: only when every reply was read, on enough+// checks minutes apart, and it was not already sent again once+export function shouldResend({ complete, checks, lostAnswers }: { complete: boolean; checks: number; lostAnswers: number }): boolean {+ return complete && checks >= RESEND_AFTER_CHECKS && lostAnswers <= MAX_LOST_ANSWERS_BEFORE_RESEND;+}++// what the person sees on a public reply that was looked for and not found, after this many checks+export function publicReviewNote({ complete, checks }: { complete: boolean; checks: number }): string {+ if (!complete) return 'Twiligent could not read every reply on this comment, so it does not send the public reply again. Check the comment on Instagram before you retry.';+ if (checks < PUBLIC_REVIEW_MAX_CHECKS) return 'Twiligent checked the comment\'s replies and did not find this public reply. It looks again in a few minutes.';+ return 'Twiligent checked the comment\'s replies several times and did not find this public reply. Check the comment on Instagram before you retry.';+}diff --git a/backend/lib/automationRules.ts b/backend/lib/automationRules.tsindex 6e1b223..68f525e 100644--- a/backend/lib/automationRules.ts+++ b/backend/lib/automationRules.ts@@ -8,6 +8,24 @@ export function keywordsProblem(matchMode: AutomationMatchMode, keywords: stringreturn keywords.length === 0 ? 'Add at least one keyword' : null;}+export interface ReplyActions {+ privateReplyEnabled: boolean;+ replyText: string;+ publicReplyEnabled: boolean;+ publicReplyTexts: string[];+ requireFollow: boolean;+}++// a rule answers with a private reply, a public reply or both, and each one it uses needs its text; the followers-only+// wait starts with the private reply. null means the actions fit together+export function replyActionsProblem(rule: ReplyActions): string | null {+ if (!rule.privateReplyEnabled && !rule.publicReplyEnabled) return 'Turn on the private reply, the public reply, or both';+ if (rule.privateReplyEnabled && !rule.replyText) return 'Write the reply to send';+ if (rule.publicReplyEnabled && rule.publicReplyTexts.length === 0) return 'Write at least one public reply';+ if (rule.requireFollow && !rule.privateReplyEnabled) return 'Sending the link only to followers needs the private reply. Turn it on, or turn off the followers-only option.';+ return null;+}+// both messages are needed before a rule can ask people to follow; null means the rule is completeexport function followTextsProblem(rule: { requireFollow: boolean; followPromptText: string | null; notFollowingText: string | null }): string | null {if (!rule.requireFollow) return null;diff --git a/backend/lib/config.ts b/backend/lib/config.tsindex f58feae..3e8ea41 100644--- a/backend/lib/config.ts+++ b/backend/lib/config.ts@@ -9,8 +9,10 @@ const CALLBACK_PATH = '/api/auth/instagram/callback';// Resend's free plan sends 100 emails a dayconst DEFAULT_EMAIL_DAILY_LIMIT = 100;// Instagram allows 750 private replies an hour per account for posts and reels; the default keeps well under it-const DEFAULT_AUTOMATION_LIMITS: AutomationLimits = { accountHourly: 200, userHourly: 500, globalHourly: 1000, recipientDaily: 3 };+const DEFAULT_AUTOMATION_LIMITS: AutomationLimits = { accountHourly: 200, userHourly: 500, globalHourly: 1000, recipientDaily: 3, publicAccountHourly: 60 };const INSTAGRAM_ACCOUNT_HOURLY_MAX = 750;+// Meta publishes no limit for comment replies but blocks accounts that comment like a bot, so the pace stays human+const PUBLIC_ACCOUNT_HOURLY_MAX = 200;// each reply costs three subrequests and a run gets 50 on the Workers Free plan, so 15 leaves room for the claimconst DEFAULT_AUTOMATION_BATCH_SIZE = 10;const MAX_AUTOMATION_BATCH_SIZE = 15;@@ -135,6 +137,7 @@ export function readAutomationConfig(env: Env): AutomationConfig {userHourly: positiveIntegerOf(env.AUTOMATION_USER_HOURLY_LIMIT, defaults.userHourly),globalHourly: positiveIntegerOf(env.AUTOMATION_GLOBAL_HOURLY_LIMIT, defaults.globalHourly),recipientDaily: positiveIntegerOf(env.AUTOMATION_RECIPIENT_DAILY_LIMIT, defaults.recipientDaily),+ publicAccountHourly: positiveIntegerOf(env.AUTOMATION_PUBLIC_ACCOUNT_HOURLY_LIMIT, defaults.publicAccountHourly, PUBLIC_ACCOUNT_HOURLY_MAX),},batchSize: positiveIntegerOf(env.AUTOMATION_BATCH_SIZE, DEFAULT_AUTOMATION_BATCH_SIZE, MAX_AUTOMATION_BATCH_SIZE),};diff --git a/backend/repositories/automationAccountRepository.ts b/backend/repositories/automationAccountRepository.tsindex a3ed702..da6ba5d 100644--- a/backend/repositories/automationAccountRepository.ts+++ b/backend/repositories/automationAccountRepository.ts@@ -10,6 +10,9 @@ interface AutomationAccountRow {subscribed_at: string | null;limited_until: string | null;subscribed_fields: string[] | null;+ public_cooldown_until: string | null;+ public_cooldown_reason: string | null;+ public_limited_until: string | null;}// an account has no row until its automation is paused, subscribed or cooled down; these are the defaults then@@ -23,9 +26,13 @@ export interface AutomationAccountControls {limitedUntil: string | null;// the webhook fields Instagram confirmed; null for a subscription made before fields were recordedsubscribedFields: string[] | null;+ // public replies cool down and fill up on their own+ publicCooldownUntil: string | null;+ publicCooldownReason: string | null;+ publicLimitedUntil: string | null;}-const COLUMNS = 'account_id, paused, paused_reason, cooldown_until, cooldown_reason, subscribed_at, limited_until, subscribed_fields';+const COLUMNS = 'account_id, paused, paused_reason, cooldown_until, cooldown_reason, subscribed_at, limited_until, subscribed_fields, public_cooldown_until, public_cooldown_reason, public_limited_until';function toControls(row: AutomationAccountRow): AutomationAccountControls {return {@@ -37,12 +44,16 @@ function toControls(row: AutomationAccountRow): AutomationAccountControls {subscribedAt: row.subscribed_at,limitedUntil: row.limited_until ?? null,subscribedFields: row.subscribed_fields ?? null,+ publicCooldownUntil: row.public_cooldown_until ?? null,+ publicCooldownReason: row.public_cooldown_reason ?? null,+ publicLimitedUntil: row.public_limited_until ?? null,};}export function defaultControls(accountId: string): AutomationAccountControls {return {accountId, paused: false, pausedReason: null, cooldownUntil: null, cooldownReason: null, subscribedAt: null, limitedUntil: null, subscribedFields: null,+ publicCooldownUntil: null, publicCooldownReason: null, publicLimitedUntil: null,};}@@ -63,7 +74,7 @@ export function createAutomationAccountRepository(db: SupabaseClient): Automatio.select(COLUMNS));const fallback: AutomationAccountRow = {account_id: accountId, paused: false, paused_reason: null, cooldown_until: null, cooldown_reason: null, subscribed_at: null,- limited_until: null, subscribed_fields: null, ...values,+ limited_until: null, subscribed_fields: null, public_cooldown_until: null, public_cooldown_reason: null, public_limited_until: null, ...values,};return toControls(saved[0] ?? fallback);}diff --git a/backend/repositories/automationCommentRepository.ts b/backend/repositories/automationCommentRepository.tsindex 584c178..ebc3eb5 100644--- a/backend/repositories/automationCommentRepository.ts+++ b/backend/repositories/automationCommentRepository.ts@@ -5,7 +5,7 @@ import type { QueueHealth } from '../lib/automationHealth.ts';import type { SupabaseClient } from '../types/app.ts';import type {AutomationActivityItem, AutomationCommentStatus, AutomationFollowupKind, AutomationFollowupStatus, AutomationGateStatus, AutomationLimits,- AutomationStats,+ AutomationPublicReplyStatus, AutomationStats,} from '../../shared/types/automation.ts';interface AutomationCommentRow {@@ -25,8 +25,21 @@ interface AutomationCommentRow {expires_at: string;created_at: string;gate_status: AutomationGateStatus | null;- // PostgREST embeds the comment's follow-ups through their foreign key+ // PostgREST embeds the comment's follow-ups and its public reply through their foreign keys; the public reply is+ // unique per comment, so it comes as one objectautomation_followups?: FollowupRow[] | null;+ automation_public_replies?: PublicReplyRow | PublicReplyRow[] | null;+}++interface PublicReplyRow {+ status: AutomationPublicReplyStatus;+ status_reason: string | null;+ error_message: string | null;+ reply_text: string;+ attempts: number;+ reply_id: string | null;+ next_attempt_at: string | null;+ accepted_at: string | null;}interface FollowupRow {@@ -71,11 +84,15 @@ interface QueueHealthRow {stale?: number;needs_review?: number;followups_due?: number;+ public_due?: number;+ public_oldest_due_at?: string | null;+ public_stale?: number;+ public_needs_review?: number;paused_accounts?: number;limited_accounts?: number;}-// a comment as the webhook stores it+// a comment as the webhook stores it, with the public reply its rule asks forexport interface NewAutomationComment {id: string;userId: string;@@ -87,11 +104,19 @@ export interface NewAutomationComment {fromId: string | null;fromUsername: string | null;text: string | null;- status: 'ignored' | 'queued';+ // skipped when the rule answers with a public reply only+ status: 'ignored' | 'queued' | 'skipped';statusReason: string | null;nextAttemptAt: string | null;notifiedAt: string;expiresAt: string;+ publicReply: { id: string; text: string } | null;+}++// what one store call added: the new comments, and the public replies queued for new or earlier copies of them+export interface StoredComments {+ inserted: NewAutomationComment[];+ publicReplyIds: string[];}// a job one run holds, with what it needs to send: the rule's reply and the account's token@@ -167,6 +192,12 @@ export interface ActivityFilter {limit: number;}+export interface ExpiredCounts {+ comments: number;+ followups: number;+ publicReplies: number;+}+export interface StatsFilter {from: string;to: string;@@ -177,7 +208,7 @@ 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, gate_status, automation_followups(status, kind, error_message, 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), automation_public_replies(status, status_reason, error_message, reply_text, attempts, reply_id, next_attempt_at, accepted_at)';// the latest follow-up, so the list shows where a followers-only reply standsfunction latestFollowup(rows: FollowupRow[] | null | undefined): AutomationActivityItem['followup'] {@@ -185,6 +216,21 @@ function latestFollowup(rows: FollowupRow[] | null | undefined): AutomationActivreturn latest ? { status: latest.status, kind: latest.kind, errorMessage: latest.error_message, createdAt: latest.created_at } : null;}+function publicReplyOf(embedded: AutomationCommentRow['automation_public_replies']): AutomationActivityItem['publicReply'] {+ const row = Array.isArray(embedded) ? embedded[0] : embedded;+ if (!row) return null;+ return {+ status: row.status,+ statusReason: row.status_reason,+ errorMessage: row.error_message,+ text: row.reply_text,+ attempts: row.attempts,+ replyId: row.reply_id,+ nextAttemptAt: row.next_attempt_at,+ acceptedAt: row.accepted_at,+ };+}+function toItem(row: AutomationCommentRow): AutomationActivityItem {return {id: row.id,@@ -204,6 +250,7 @@ function toItem(row: AutomationCommentRow): AutomationActivityItem {createdAt: row.created_at,gateStatus: row.gate_status ?? null,followup: latestFollowup(row.automation_followups),+ publicReply: publicReplyOf(row.automation_public_replies),};}@@ -235,6 +282,10 @@ function toHealth(row: QueueHealthRow): QueueHealth {stale: row.stale ?? 0,needsReview: row.needs_review ?? 0,followupsDue: row.followups_due ?? 0,+ publicDue: row.public_due ?? 0,+ publicOldestDueAt: row.public_oldest_due_at ?? null,+ publicStale: row.public_stale ?? 0,+ publicNeedsReview: row.public_needs_review ?? 0,pausedAccounts: row.paused_accounts ?? 0,limitedAccounts: row.limited_accounts ?? 0,};@@ -242,7 +293,7 @@ function toHealth(row: QueueHealthRow): QueueHealth {// 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[]>;+ store(comments: NewAutomationComment[]): Promise<StoredComments>;claim(options: ClaimOptions): Promise<ClaimedComment[]>;reserve(id: string, attemptId: string, limits: AutomationLimits, messageDigest?: string): Promise<Reservation>;finish(id: string, attemptId: string, plan: FinishPlan): Promise<boolean>;@@ -253,7 +304,7 @@ 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>;- expireDue(limit: number): Promise<{ comments: number; followups: number }>;+ expireDue(limit: number): Promise<ExpiredCounts>;reviewCandidates(options: ReviewCandidateOptions): Promise<ReviewCandidate[]>;recordReview(id: string, result: ReviewResult): Promise<boolean>;health(leaseSeconds: number): Promise<QueueHealth>;@@ -262,12 +313,12 @@ export interface AutomationCommentRepository {export function createAutomationCommentRepository(db: SupabaseClient): AutomationCommentRepository {return {- // the unique (ig_user_id, comment_id) drops a notification Meta delivered again; only new rows come back- async insertMany(comments) {- if (comments.length === 0) return [];- const inserted = await rows<{ id: string }>('automationComments.insertMany', () => db- .from('automation_comments')- .upsert(comments.map(comment => ({+ // one transaction for the comments and their public replies; the unique (ig_user_id, comment_id) drops a+ // notification Meta delivered again, so only new comments come back+ async store(comments) {+ if (comments.length === 0) return { inserted: [], publicReplyIds: [] };+ const { data } = await execute('automationComments.store', () => db.rpc('store_automation_comments', {+ p_comments: comments.map(comment => ({id: comment.id,user_id: comment.userId,account_id: comment.accountId,@@ -283,10 +334,13 @@ export function createAutomationCommentRepository(db: SupabaseClient): Automationext_attempt_at: comment.nextAttemptAt,notified_at: comment.notifiedAt,expires_at: comment.expiresAt,- })), { onConflict: 'ig_user_id,comment_id', ignoreDuplicates: true })- .select('id'));- const insertedIds = new Set(inserted.map(row => row.id));- return comments.filter(comment => insertedIds.has(comment.id));+ public_reply_id: comment.publicReply?.id ?? null,+ public_reply_text: comment.publicReply?.text ?? null,+ })),+ }));+ const result = (data ?? {}) as { comments?: { id: string }[]; public_replies?: string[] };+ const insertedIds = new Set((result.comments ?? []).map(row => row.id));+ return { inserted: comments.filter(comment => insertedIds.has(comment.id)), publicReplyIds: result.public_replies ?? [] };},async claim({ limit, perAccount, leaseSeconds, ids }) {@@ -419,14 +473,14 @@ export function createAutomationCommentRepository(db: SupabaseClient): Automatiop_account_id: accountId ?? null,p_rule_id: ruleId ?? null,}));- const stats = (data ?? {}) as Partial<AutomationStats>;- return { comments: stats.comments ?? {}, attempts: stats.attempts ?? {} };+ const stats = (data ?? {}) as Partial<AutomationStats> & { public_replies?: AutomationStats['publicReplies'] };+ return { comments: stats.comments ?? {}, publicReplies: stats.public_replies ?? {}, attempts: stats.attempts ?? {} };},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 };+ const counts = (data ?? {}) as { comments?: number; followups?: number; public_replies?: number };+ return { comments: counts.comments ?? 0, followups: counts.followups ?? 0, publicReplies: counts.public_replies ?? 0 };},async reviewCandidates({ limit, settleSeconds, maxChecks, recheckSeconds }) {diff --git a/backend/repositories/automationPublicReplyRepository.ts b/backend/repositories/automationPublicReplyRepository.tsnew file mode 100644index 0000000..105be5f--- /dev/null+++ b/backend/repositories/automationPublicReplyRepository.ts@@ -0,0 +1,228 @@+import { execute, rows } from './query.ts';+import { DUE_NOW_SKEW_MS } from '../lib/automationDelivery.ts';+import type { ReleasePlan, ReserveOutcome } from '../lib/automationDelivery.ts';+import type { PublicFinishPlan } from '../lib/automationPublicReply.ts';+import type { ClaimOptions, Reservation } from './automationCommentRepository.ts';+import type { SupabaseClient } from '../types/app.ts';+import type { AutomationPublicReplyStatus } from '../../shared/types/automation.ts';++interface ClaimedPublicReplyRow {+ id: string;+ user_id: string;+ account_id: string;+ rule_id: string | null;+ ig_user_id: string;+ comment_id: string;+ attempts: number;+ expires_at: string;+ reply_text: string;+ rule_enabled: boolean;+ access_token: string | null;+}++interface PublicReviewCandidateRow {+ id: string;+ ig_user_id: string;+ comment_id: string;+ started_at: string;+ message_digest: string | null;+ access_token: string | null;+ review_checks: number;+ ambiguous_attempts: number;+}++// a public reply one run holds, with its text and the account's token; ruleEnabled is false once the rule or its+// public reply was turned off+export interface ClaimedPublicReply {+ id: string;+ userId: string;+ accountId: string;+ ruleId: string | null;+ igUserId: string;+ commentId: string;+ attempts: number;+ expiresAt: string;+ replyText: string;+ ruleEnabled: boolean;+ accessToken: string | null;+}++// a public reply whose answer was lost, with what is needed to look for it among the comment's replies+export interface PublicReviewCandidate {+ id: string;+ igUserId: string;+ commentId: string;+ startedAt: string;+ messageDigest: string | null;+ accessToken: string | null;+ // checks made before this one, and how many sends of it had no answer+ reviewChecks: number;+ lostAnswers: number;+}++export interface PublicReviewCandidateOptions {+ limit: number;+ settleSeconds: number;+ maxChecks: number;+ recheckSeconds: number;+}++// what one look at the comment's replies found; a reply not found may go out again once+export type PublicReviewResult =+ | { found: true; replyId: string; sentAt: string }+ | { found: false; note: string | null; resend: boolean };++// a person may ask for these to be tried again; an expired one is too old to post+const RETRYABLE: AutomationPublicReplyStatus[] = ['failed', 'needs_review', 'skipped'];++function toClaimed(row: ClaimedPublicReplyRow): ClaimedPublicReply {+ return {+ id: row.id,+ userId: row.user_id,+ accountId: row.account_id,+ ruleId: row.rule_id,+ igUserId: row.ig_user_id,+ commentId: row.comment_id,+ attempts: row.attempts,+ expiresAt: row.expires_at,+ replyText: row.reply_text,+ ruleEnabled: row.rule_enabled,+ accessToken: row.access_token,+ };+}++// the public replies under comments; requeueForUser is scoped to the verified user, the others serve the webhook,+// the dispatch and the reconcile across all users+export interface AutomationPublicReplyRepository {+ claim(options: ClaimOptions): Promise<ClaimedPublicReply[]>;+ reserve(id: string, attemptId: string, accountLimit: number, messageDigest: string): Promise<Reservation>;+ finish(id: string, attemptId: string, plan: PublicFinishPlan): Promise<boolean>;+ release(id: string, plan: ReleasePlan): Promise<boolean>;+ returnUnstarted(ids: string[]): Promise<void>;+ reviewCandidates(options: PublicReviewCandidateOptions): Promise<PublicReviewCandidate[]>;+ recordReview(id: string, result: PublicReviewResult): Promise<boolean>;+ requeueForUser(commentRowId: string, userId: string): Promise<string | null>;+ releaseHeldForAccount(accountId: string, userId: string): Promise<void>;+}++export function createAutomationPublicReplyRepository(db: SupabaseClient): AutomationPublicReplyRepository {+ return {+ async claim({ limit, perAccount, leaseSeconds, ids }) {+ const { data } = await execute('automationPublicReplies.claim', () => db.rpc('claim_automation_public_replies', {+ p_limit: limit,+ p_per_account: perAccount,+ p_lease_seconds: leaseSeconds,+ p_ids: ids ?? null,+ }));+ return ((data ?? []) as ClaimedPublicReplyRow[]).map(toClaimed);+ },++ async reserve(id, attemptId, accountLimit, messageDigest) {+ const { data } = await execute('automationPublicReplies.reserve', () => db.rpc('reserve_automation_public_reply', {+ p_id: id,+ p_attempt_id: attemptId,+ p_account_limit: accountLimit,+ 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('automationPublicReplies.finish', () => db.rpc('finish_automation_public_reply', {+ 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_reply_id: plan.replyId,+ 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,+ }));+ return data === true;+ },++ // only a reply this run still holds is given back+ async release(id, plan) {+ const released = await rows<{ id: string }>('automationPublicReplies.release', () => db+ .from('automation_public_replies')+ .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('automationPublicReplies.returnUnstarted', () => db+ .from('automation_public_replies')+ .update({ status: 'queued', claimed_at: null, next_attempt_at: new Date(Date.now() - DUE_NOW_SKEW_MS).toISOString() })+ .in('id', ids)+ .eq('status', 'processing'));+ },++ async reviewCandidates({ limit, settleSeconds, maxChecks, recheckSeconds }) {+ const { data } = await execute('automationPublicReplies.reviewCandidates', () => db.rpc('automation_public_review_candidates', {+ p_limit: limit,+ p_settle_seconds: settleSeconds,+ p_max_checks: maxChecks,+ p_recheck_seconds: recheckSeconds,+ }));+ return ((data ?? []) as PublicReviewCandidateRow[]).map(row => ({+ id: row.id,+ igUserId: row.ig_user_id,+ commentId: row.comment_id,+ startedAt: row.started_at,+ messageDigest: row.message_digest,+ accessToken: row.access_token,+ reviewChecks: row.review_checks ?? 0,+ lostAnswers: row.ambiguous_attempts ?? 1,+ }));+ },++ // only a reply still waiting for review changes, so a person's retry in between is never undone+ async recordReview(id, result) {+ const { data } = await execute('automationPublicReplies.recordReview', () => db.rpc('record_automation_public_review', result.found+ ? { p_id: id, p_found: true, p_reply_id: result.replyId, p_sent_at: result.sentAt, p_note: null, p_resend: false }+ : { p_id: id, p_found: false, p_reply_id: null, p_sent_at: null, p_note: result.note, p_resend: result.resend }));+ return data === true;+ },++ // the comment's public reply goes back in the queue if it failed, was skipped or needs review and is not too+ // old; checked in the update itself, so one a run picked up in between is never posted twice+ async requeueForUser(commentRowId, userId) {+ const requeued = await rows<{ id: string }>('automationPublicReplies.requeue', () => db+ .from('automation_public_replies')+ .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('automation_comment_id', commentRowId)+ .eq('user_id', userId)+ .in('status', RETRYABLE)+ .gt('expires_at', new Date().toISOString())+ .select('id'));+ return requeued[0]?.id ?? null;+ },++ // public replies held by a pause go out on the next run once the account is resumed+ async releaseHeldForAccount(accountId, userId) {+ await execute('automationPublicReplies.releaseHeld', () => db+ .from('automation_public_replies')+ .update({ next_attempt_at: new Date().toISOString(), error_message: null })+ .eq('account_id', accountId)+ .eq('user_id', userId)+ .eq('status', 'queued')+ .eq('status_reason', 'paused'));+ },+ };+}diff --git a/backend/repositories/automationRuleRepository.ts b/backend/repositories/automationRuleRepository.tsindex e814bcf..cc70580 100644--- a/backend/repositories/automationRuleRepository.ts+++ b/backend/repositories/automationRuleRepository.ts@@ -10,8 +10,11 @@ interface AutomationRuleRow {match_mode: AutomationMatchMode;case_sensitive: boolean;media_ids: string[];+ private_reply_enabled: boolean;reply_text: string;link_url: string | null;+ public_reply_enabled: boolean;+ public_reply_texts: string[];enabled: boolean;hourly_limit: number | null;require_follow: boolean;@@ -21,7 +24,7 @@ interface AutomationRuleRow {updated_at: string;}-// a rule as the webhook needs it to match a comment, with the member and account it belongs to+// a rule as the webhook needs it to match a comment and queue its replies, with the member and account it belongs toexport interface WebhookRule {id: string;userId: string;@@ -30,6 +33,9 @@ export interface WebhookRule {matchMode: AutomationMatchMode;caseSensitive: boolean;mediaIds: string[];+ privateReplyEnabled: boolean;+ publicReplyEnabled: boolean;+ publicReplyTexts: string[];}interface WebhookRuleRow {@@ -40,11 +46,15 @@ interface WebhookRuleRow {match_mode: AutomationMatchMode;case_sensitive: boolean;media_ids: string[];+ // absent while the database still has the function from before public replies+ private_reply_enabled?: boolean;+ public_reply_enabled?: boolean;+ public_reply_texts?: string[];}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, require_follow, follow_prompt_text, not_following_text, created_at, updated_at';+const COLUMNS = 'id, account_id, name, keywords, match_mode, case_sensitive, media_ids, private_reply_enabled, reply_text, link_url, public_reply_enabled, public_reply_texts, enabled, hourly_limit, require_follow, follow_prompt_text, not_following_text, created_at, updated_at';function toRule(row: AutomationRuleRow): AutomationRule {return {@@ -55,8 +65,11 @@ function toRule(row: AutomationRuleRow): AutomationRule {matchMode: row.match_mode,caseSensitive: row.case_sensitive,mediaIds: row.media_ids,+ privateReplyEnabled: row.private_reply_enabled ?? true,replyText: row.reply_text,linkUrl: row.link_url,+ publicReplyEnabled: row.public_reply_enabled ?? false,+ publicReplyTexts: row.public_reply_texts ?? [],enabled: row.enabled,hourlyLimit: row.hourly_limit,requireFollow: row.require_follow ?? false,@@ -75,8 +88,11 @@ function toColumns(changes: AutomationRuleChanges): Record<string, unknown> {match_mode: changes.matchMode,case_sensitive: changes.caseSensitive,media_ids: changes.mediaIds,+ private_reply_enabled: changes.privateReplyEnabled,reply_text: changes.replyText,link_url: changes.linkUrl,+ public_reply_enabled: changes.publicReplyEnabled,+ public_reply_texts: changes.publicReplyTexts,enabled: changes.enabled,hourly_limit: changes.hourlyLimit,require_follow: changes.requireFollow,@@ -156,6 +172,9 @@ export function createAutomationRuleRepository(db: SupabaseClient): AutomationRumatchMode: row.match_mode,caseSensitive: row.case_sensitive,mediaIds: row.media_ids,+ privateReplyEnabled: row.private_reply_enabled ?? true,+ publicReplyEnabled: row.public_reply_enabled ?? false,+ publicReplyTexts: row.public_reply_texts ?? [],}));},};diff --git a/backend/routes/automationRoutes.ts b/backend/routes/automationRoutes.tsindex 8d7ce18..1fa8752 100644--- a/backend/routes/automationRoutes.ts+++ b/backend/routes/automationRoutes.ts@@ -1,7 +1,7 @@import { Hono } from 'hono';import {getAutomations, createAutomationRule, updateAutomationRule, duplicateAutomationRule, deleteAutomationRule, testAutomationRule,- listAutomationActivity, getAutomationStats, retryAutomationActivity, updateAutomationAccount, subscribeAutomationAccount,+ listAutomationActivity, getAutomationStats, retryAutomationActivity, retryAutomationPublicReply, updateAutomationAccount, subscribeAutomationAccount,} from '../controllers/automationController.ts';import type { AppEnv } from '../types/app.ts';@@ -15,6 +15,7 @@ router.post('/automations/rules/:id/duplicate', ...duplicateAutomationRule);router.post('/automations/test', ...testAutomationRule);router.get('/automations/activity', ...listAutomationActivity);router.post('/automations/activity/:id/retry', ...retryAutomationActivity);+router.post('/automations/activity/:id/public-reply/retry', ...retryAutomationPublicReply);router.get('/automations/stats', ...getAutomationStats);router.put('/automations/accounts/:accountId', ...updateAutomationAccount);router.post('/automations/accounts/:accountId/subscribe', ...subscribeAutomationAccount);diff --git a/backend/services/automationPublicReplyProcessor.ts b/backend/services/automationPublicReplyProcessor.tsnew file mode 100644index 0000000..b8264d9--- /dev/null+++ b/backend/services/automationPublicReplyProcessor.ts@@ -0,0 +1,124 @@+import { replyToComment } from './instagram/instagramComments.ts';+import { BACKGROUND_RUN_MS, CLAIM_LEASE_SECONDS, FREE_PLAN_SUBREQUESTS, SEND_TIMEOUT_MS, messageDigest } from '../lib/automationDelivery.ts';+import { SUBREQUESTS_PER_PUBLIC_REPLY, publicFinishPlan, publicReadinessPlan, publicReleasePlan } from '../lib/automationPublicReply.ts';+import { newRowId } from '../lib/ids.ts';+import { errorFields } from '../lib/logger.ts';+import type { AutomationPublicReplyRepository, ClaimedPublicReply } from '../repositories/automationPublicReplyRepository.ts';+import type { AutomationConfig } from '../lib/config.ts';+import type { RequestContext } from '../types/context.ts';+import type { AutomationPublicReplyStatus } from '../../shared/types/automation.ts';++export interface AutomationPublicReplyProcessorDeps {+ publicReplies: AutomationPublicReplyRepository;+ automation: AutomationConfig;+ context: RequestContext;+}++export interface PublicReplyProcessOptions {+ // only these public replies, as a webhook or a retry just queued them; otherwise whatever is due+ ids?: string[];+ // subrequests this run may still make, after what its invocation already spent+ subrequests?: number;+ // how long the run may keep starting sends+ timeBudgetMs?: number;+}++export interface PublicReplyRun {+ claimed: number;+ outcomes: Partial<Record<AutomationPublicReplyStatus | 'gone' | 'returned' | 'error', number>>;+ subrequests: number;+}++export interface AutomationPublicReplyProcessor {+ run(options?: PublicReplyProcessOptions): Promise<PublicReplyRun>;+}++// a send needs its whole timeout plus a moment to record the answer+const SEND_MARGIN_MS = 2_000;++// posts the public replies that are due, one at a time like private replies, each settled in the database before the+// next starts. It never reads or changes a comment's private reply, so one action failing never repeats the other+export function createAutomationPublicReplyProcessor({ publicReplies, automation, context }: AutomationPublicReplyProcessorDeps): AutomationPublicReplyProcessor {+ const { signal, log } = context;++ async function settle(job: ClaimedPublicReply, spend: () => void): Promise<AutomationPublicReplyStatus | 'gone'> {+ const now = Date.now();+ const notReady = publicReadinessPlan(job, now);+ if (notReady) {+ spend();+ await publicReplies.release(job.id, notReady);+ return notReady.status as AutomationPublicReplyStatus;+ }++ const attemptId = newRowId();+ spend();+ const reservation = await publicReplies.reserve(job.id, attemptId, automation.limits.publicAccountHourly, await messageDigest(job.replyText));+ if (reservation.outcome === 'gone') return 'gone';+ const delivery = { attempts: job.attempts + 1, expiresAt: job.expiresAt };+ const held = publicReleasePlan(reservation.outcome, reservation.retryAt, delivery, now);+ if (held) {+ spend();+ await publicReplies.release(job.id, held);+ return held.status as AutomationPublicReplyStatus;+ }++ spend();+ const result = await replyToComment(job.commentId, job.accessToken!, job.replyText);+ const plan = publicFinishPlan(result, delivery, Date.now());+ spend();+ await publicReplies.finish(job.id, attemptId, plan);+ log.info('automation public reply settled', {+ publicReplyId: job.id,+ accountId: job.accountId,+ ruleId: job.ruleId,+ status: plan.status,+ outcome: plan.outcome,+ errorCode: plan.errorCode,+ errorSubcode: plan.errorSubcode,+ });+ return plan.status;+ }++ // one update for every reply the run will not start, so they are due again at once instead of after the lease+ async function handBack(jobs: ClaimedPublicReply[], outcomes: PublicReplyRun['outcomes']): Promise<void> {+ if (jobs.length === 0) return;+ try {+ await publicReplies.returnUnstarted(jobs.map(job => job.id));+ outcomes.returned = jobs.length;+ } catch (err) {+ log.error('automation public replies not handed back', { count: jobs.length, ...errorFields(err) });+ }+ }++ return {+ async run({ ids, subrequests = FREE_PLAN_SUBREQUESTS, timeBudgetMs = BACKGROUND_RUN_MS } = {}) {+ const outcomes: PublicReplyRun['outcomes'] = {};+ if (automation.paused) 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+ const batch = Math.min(automation.batchSize, Math.floor((subrequests - 2) / SUBREQUESTS_PER_PUBLIC_REPLY));+ if (batch < 1) return { claimed: 0, outcomes, subrequests: 0 };+ let spent = 1;+ const spend = () => { spent++; };+ const jobs = await publicReplies.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, spend);+ outcomes[status] = (outcomes[status] ?? 0) + 1;+ } catch (err) {+ // one reply's database failure must not stop the others; its claim or reservation expires and recovers it+ outcomes.error = (outcomes.error ?? 0) + 1;+ log.error('automation public reply failed', { publicReplyId: job.id, accountId: job.accountId, ...errorFields(err) });+ }+ }+ return { claimed: jobs.length, outcomes, subrequests: spent };+ },+ };+}diff --git a/backend/services/automationReconciler.ts b/backend/services/automationReconciler.tsindex 2da396d..283125f 100644--- a/backend/services/automationReconciler.ts+++ b/backend/services/automationReconciler.ts@@ -1,23 +1,38 @@import { listConversationMessages } from './instagram/instagramMessaging.ts';+import { listCommentReplies } from './instagram/instagramComments.ts';import { CLAIM_LEASE_SECONDS, FREE_PLAN_SUBREQUESTS, messageDigest } from '../lib/automationDelivery.ts';import { healthWarning } from '../lib/automationHealth.ts';+import {+ PUBLIC_REVIEW_BATCH, PUBLIC_REVIEW_MAX_CHECKS, PUBLIC_REVIEW_RECHECK_SECONDS, PUBLIC_REVIEW_SETTLE_SECONDS, SUBREQUESTS_PER_PUBLIC_REVIEW,+ publicReviewNote, shouldResend,+} from '../lib/automationPublicReply.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 { AutomationCommentRepository, ExpiredCounts, ReviewCandidate, ReviewResult } from '../repositories/automationCommentRepository.ts';+import type { AutomationPublicReplyRepository, PublicReviewCandidate, PublicReviewResult } from '../repositories/automationPublicReplyRepository.ts';import type { QueueHealth } from '../lib/automationHealth.ts';import type { RequestContext } from '../types/context.ts';export interface AutomationReconcilerDeps {comments: AutomationCommentRepository;+ publicReplies: AutomationPublicReplyRepository;context: RequestContext;}+export interface ReviewCounts {+ found: number;+ notFound: number;+ failed: number;+}+export interface ReconcileRun {- expired: { comments: number; followups: number };- reviewed: { found: number; notFound: number; failed: number };+ expired: ExpiredCounts;+ reviewed: ReviewCounts;+ // public replies found, not found, failed to check, and sent again after the comment's replies showed it missing+ reviewedPublic: ReviewCounts & { resent: number };health: QueueHealth;}@@ -27,10 +42,15 @@ export interface AutomationReconciler {// overdue jobs settled per run; the rest wait five minutes, and a run that misses them leaves them unclaimable anywayconst EXPIRE_BATCH = 500;+// expiry, the health read and the private review's candidate list+const FIXED_SUBREQUESTS = 3;+// kept for the public review: its candidate list and a full batch of checks+const PUBLIC_REVIEW_SUBREQUESTS = 1 + PUBLIC_REVIEW_BATCH * SUBREQUESTS_PER_PUBLIC_REVIEW;-// 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 {+// the five minute job: expires what can no longer be sent, looks for lost replies and reports how the queue is doing.+// It never sends anything: a public reply it cannot find goes back in the queue for the dispatch, so it cannot race+// the dispatch into a second reply+export function createAutomationReconciler({ comments, publicReplies, context }: AutomationReconcilerDeps): AutomationReconciler {const { log, signal } = context;async function lookFor(candidate: ReviewCandidate): Promise<ReviewResult> {@@ -42,10 +62,10 @@ export function createAutomationReconciler({ comments, context }: AutomationRecoreturn 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;+ // private replies: returns the subrequests it made+ async function review(budget: number, reviewed: ReviewCounts): Promise<number> {+ const limit = Math.min(REVIEW_BATCH, Math.floor(budget / SUBREQUESTS_PER_REVIEW));+ if (limit < 1) return 0;const candidates = await comments.reviewCandidates({limit, settleSeconds: REVIEW_SETTLE_SECONDS, maxChecks: REVIEW_MAX_CHECKS, recheckSeconds: REVIEW_RECHECK_SECONDS,});@@ -65,19 +85,58 @@ export function createAutomationReconciler({ comments, context }: AutomationReco.catch(recordErr => log.error('automation review not recorded', { commentRowId: candidate.id, ...errorFields(recordErr) }));}}+ return candidates.length * SUBREQUESTS_PER_REVIEW;+ }++ async function lookForPublic(candidate: PublicReviewCandidate): Promise<PublicReviewResult> {+ if (!candidate.messageDigest || !candidate.accessToken) {+ return { found: false, note: 'Twiligent cannot recognise this public reply on Instagram. Check the comment before you retry.', resend: false };+ }+ const { replies, complete } = await listCommentReplies(candidate.commentId, candidate.accessToken, signal);+ const match = await findSentReply(replies, { igUserId: candidate.igUserId, startedAt: candidate.startedAt, digest: candidate.messageDigest }, messageDigest);+ if (match) return { found: true, replyId: match.id, sentAt: match.createdTime };+ const checks = candidate.reviewChecks + 1;+ const resend = shouldResend({ complete, checks, lostAnswers: candidate.lostAnswers });+ return { found: false, note: resend ? null : publicReviewNote({ complete, checks }), resend };+ }++ async function reviewPublic(budget: number): Promise<ReconcileRun['reviewedPublic']> {+ const reviewed = { found: 0, notFound: 0, failed: 0, resent: 0 };+ const limit = Math.min(PUBLIC_REVIEW_BATCH, Math.floor((budget - 1) / SUBREQUESTS_PER_PUBLIC_REVIEW));+ if (limit < 1) return reviewed;+ const candidates = await publicReplies.reviewCandidates({+ limit, settleSeconds: PUBLIC_REVIEW_SETTLE_SECONDS, maxChecks: PUBLIC_REVIEW_MAX_CHECKS, recheckSeconds: PUBLIC_REVIEW_RECHECK_SECONDS,+ });+ for (const candidate of candidates) {+ if (signal.aborted) break;+ try {+ const result = await lookForPublic(candidate);+ await publicReplies.recordReview(candidate.id, result);+ if (result.found) reviewed.found++;+ else if (result.resend) reviewed.resent++;+ else reviewed.notFound++;+ } catch (err) {+ reviewed.failed++;+ const reason = redactUrls((err as Error).message ?? 'unknown error').slice(0, 200);+ log.warn('automation public review check failed', { publicReplyId: candidate.id, ...errorFields(err) });+ await publicReplies.recordReview(candidate.id, { found: false, note: `Twiligent could not read the comment's replies on Instagram (${reason}). Check the comment yourself before you retry.`, resend: false })+ .catch(recordErr => log.error('automation public review not recorded', { publicReplyId: 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 reviewed = { found: 0, notFound: 0, failed: 0 };+ const privateSpent = await review(FREE_PLAN_SUBREQUESTS - FIXED_SUBREQUESTS - PUBLIC_REVIEW_SUBREQUESTS, reviewed);+ const reviewedPublic = await reviewPublic(FREE_PLAN_SUBREQUESTS - FIXED_SUBREQUESTS - privateSpent);const health = await comments.health(CLAIM_LEASE_SECONDS);- log.info('automation reconcile', { expired, reviewed, health: { ...health } });+ log.info('automation reconcile', { expired, reviewed, reviewedPublic, 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 };+ if (warning) log.warn(warning, { due: health.due, stale: health.stale, oldestDueAt: health.oldestDueAt, publicDue: health.publicDue });+ return { expired, reviewed, reviewedPublic, health };},};}diff --git a/backend/services/automationService.ts b/backend/services/automationService.tsindex 67304fa..10ddef0 100644--- a/backend/services/automationService.ts+++ b/backend/services/automationService.ts@@ -1,6 +1,6 @@import { subscribeToWebhooks } from './instagram/instagramMessaging.ts';import { coversMedia, ruleMatch } from '../lib/automationMatching.ts';-import { followTextsProblem, keywordsProblem } from '../lib/automationRules.ts';+import { followTextsProblem, keywordsProblem, replyActionsProblem } 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';@@ -10,6 +10,7 @@ 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 { AutomationPublicReplyRepository } from '../repositories/automationPublicReplyRepository.ts';import type { AutomationRuleRepository } from '../repositories/automationRuleRepository.ts';import type { AuditRepository } from '../repositories/auditRepository.ts';import type { WebhookField } from './instagram/instagramMessaging.ts';@@ -27,6 +28,7 @@ export interface AutomationServiceDeps {rules: AutomationRuleRepository;comments: AutomationCommentRepository;followups: AutomationFollowupRepository;+ publicReplies: AutomationPublicReplyRepository;automationAccounts: AutomationAccountRepository;audit: AuditRepository;automation: AutomationConfig;@@ -58,6 +60,12 @@ export interface RetryResult {followupId: string | null;}+// a retried public reply, to send right away+export interface PublicRetryResult {+ item: AutomationActivityItem;+ publicReplyId: string;+}+export interface AutomationService {overview(userId: string): Promise<AutomationOverview>;createRule(userId: string, input: AutomationRuleRequest): Promise<AutomationRule>;@@ -68,6 +76,7 @@ export interface AutomationService {activity(userId: string, query: ActivityQuery): Promise<ActivityPage>;stats(userId: string, query: StatsQuery): Promise<StatsPeriod>;retry(userId: string, commentRowId: string): Promise<RetryResult>;+ retryPublicReply(userId: string, commentRowId: string): Promise<PublicRetryResult>;setPaused(userId: string, accountId: string, paused: boolean): Promise<AutomationAccountState>;subscribe(userId: string, accountId: string): Promise<AutomationAccountState>;}@@ -97,6 +106,9 @@ function toState(account: Account, controls: AutomationAccountControls): AutomatsubscribedAt: controls.subscribedAt,limitedUntil: future(controls.limitedUntil),messagesSubscribed: subscribedFieldsOf(controls).includes('messages'),+ publicCooldownUntil: future(controls.publicCooldownUntil),+ publicCooldownReason: future(controls.publicCooldownUntil) ? controls.publicCooldownReason : null,+ publicLimitedUntil: future(controls.publicLimitedUntil),};}@@ -115,8 +127,18 @@ function checkFollowTexts(rule: { followPromptText: string | null; notFollowingT}}-// 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+// the private reply goes out as one Instagram message, so it is measured only when the rule sends it+function checkPrivateReply(rule: { privateReplyEnabled: boolean; replyText: string; linkUrl: string | null }): void {+ if (rule.privateReplyEnabled) checkMessageSize(rule.replyText, rule.linkUrl);+}++function checkActions(rule: Parameters<typeof replyActionsProblem>[0]): void {+ const problem = replyActionsProblem(rule);+ if (problem) throw new ValidationError(problem);+}++// what a rule will look like once saved, checked across fields: keywords against the match mode, the reply actions+// and the followers-only messages; switching to any comment clears the keywords, since such a rule takes nonefunction resolveChanges(current: AutomationRule, changes: AutomationRuleUpdateRequest): AutomationRuleUpdateRequest {const matchMode = changes.matchMode ?? current.matchMode;const resolved = { ...changes };@@ -129,6 +151,16 @@ function resolveChanges(current: AutomationRule, changes: AutomationRuleUpdateRefollowPromptText: resolved.followPromptText === undefined ? current.followPromptText : resolved.followPromptText,notFollowingText: resolved.notFollowingText === undefined ? current.notFollowingText : resolved.notFollowingText,};+ const actions = {+ privateReplyEnabled: resolved.privateReplyEnabled ?? current.privateReplyEnabled,+ replyText: resolved.replyText ?? current.replyText,+ linkUrl: resolved.linkUrl === undefined ? current.linkUrl : resolved.linkUrl,+ publicReplyEnabled: resolved.publicReplyEnabled ?? current.publicReplyEnabled,+ publicReplyTexts: resolved.publicReplyTexts ?? current.publicReplyTexts,+ requireFollow: merged.requireFollow,+ };+ checkActions(actions);+ checkPrivateReply(actions);const followProblem = followTextsProblem(merged);if (followProblem) throw new ValidationError(followProblem);checkFollowTexts(merged);@@ -143,7 +175,7 @@ function fieldsFor(accountRules: AutomationRule[]): WebhookField[] {// 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, followups, automationAccounts, audit, automation, context } = deps;+ const { accounts, rules, comments, followups, publicReplies, automationAccounts, audit, automation, context } = deps;async function instagramAccount(userId: string, accountId: string): Promise<Account> {const account = await accounts.findForUser(accountId, userId);@@ -224,7 +256,15 @@ export function createAutomationService(deps: AutomationServiceDeps): Automationasync createRule(userId, input) {const account = await instagramAccount(userId, input.accountId);- checkMessageSize(input.replyText, input.linkUrl ?? null);+ const actions = {+ privateReplyEnabled: input.privateReplyEnabled ?? true,+ replyText: input.replyText,+ linkUrl: input.linkUrl ?? null,+ publicReplyEnabled: input.publicReplyEnabled ?? false,+ publicReplyTexts: input.publicReplyTexts ?? [],+ };+ checkActions({ ...actions, requireFollow: input.requireFollow ?? false });+ checkPrivateReply(actions);const follow = {requireFollow: input.requireFollow ?? false,followPromptText: input.followPromptText ?? null,@@ -240,8 +280,7 @@ export function createAutomationService(deps: AutomationServiceDeps): AutomationmatchMode: input.matchMode ?? 'contains',caseSensitive: input.caseSensitive ?? false,mediaIds: input.mediaIds ?? [],- replyText: input.replyText,- linkUrl: input.linkUrl ?? null,+ ...actions,enabled: input.enabled ?? false,hourlyLimit: input.hourlyLimit ?? null,...follow,@@ -250,7 +289,10 @@ export function createAutomationService(deps: AutomationServiceDeps): Automation}, userId);await audit.recordForUser(userId, {action: 'automation_rule.created', subjectType: 'automation_rule', subjectId: rule.id,- details: { accountId: account.id, enabled: rule.enabled, matchMode: rule.matchMode, requireFollow: rule.requireFollow },+ details: {+ accountId: account.id, enabled: rule.enabled, matchMode: rule.matchMode, requireFollow: rule.requireFollow,+ privateReply: rule.privateReplyEnabled, publicReply: rule.publicReplyEnabled,+ },});if (rule.enabled) await ensureSubscribed(userId, account);return rule;@@ -258,7 +300,6 @@ 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 resolved = resolveChanges(current, changes);const rule = await rules.updateForUser(id, resolved, userId);if (!rule) throw new NotFoundError('Automation rule not found');@@ -303,7 +344,8 @@ export function createAutomationService(deps: AutomationServiceDeps): AutomationcaseSensitive: input.caseSensitive ?? false,mediaIds: input.mediaIds ?? [],};- const message = replyMessage({+ // a rule with no private reply sends no message, so there is nothing to measure+ const message = input.privateReplyEnabled === false ? '' : replyMessage({requireFollow: input.requireFollow ?? false,followPromptText: input.followPromptText ?? null,replyText: input.replyText,@@ -347,11 +389,30 @@ export function createAutomationService(deps: AutomationServiceDeps): Automationreturn { item: await comments.findForUser(commentRowId, userId) ?? existing, followupId };},+ // only the public reply goes back in the queue; the private reply keeps whatever state it has+ async retryPublicReply(userId, commentRowId) {+ const publicReplyId = await publicReplies.requeueForUser(commentRowId, userId);+ const item = await comments.findForUser(commentRowId, userId);+ if (!item) throw new NotFoundError('Activity item not found');+ if (!publicReplyId) {+ throw new ConflictError(item.publicReply+ ? 'Only a failed, skipped or review public reply inside its 7 days can be retried'+ : 'This comment has no public reply to retry');+ }+ await audit.recordForUser(userId, {+ action: 'automation_public_reply.retried', subjectType: 'automation_comment', subjectId: commentRowId, details: { publicReplyId },+ });+ return { item, publicReplyId };+ },+async setPaused(userId, accountId, paused) {const account = await instagramAccount(userId, accountId);const controls = await automationAccounts.setPausedForUser(account.id, userId, paused);// held replies go out on the next run instead of waiting for their next check- if (!paused) await comments.releaseHeldForAccount(account.id, userId);+ if (!paused) {+ await comments.releaseHeldForAccount(account.id, userId);+ await publicReplies.releaseHeldForAccount(account.id, userId);+ }await audit.recordForUser(userId, {action: paused ? 'automation_account.paused' : 'automation_account.resumed', subjectType: 'automation_account', subjectId: account.id,});diff --git a/backend/services/automationWebhookService.ts b/backend/services/automationWebhookService.tsindex 19365d7..8b2b4d5 100644--- a/backend/services/automationWebhookService.ts+++ b/backend/services/automationWebhookService.ts@@ -1,5 +1,6 @@import { pickRule } from '../lib/automationMatching.ts';import { DUE_NOW_SKEW_MS, expiresAtFor } from '../lib/automationDelivery.ts';+import { pickPublicReplyText } from '../lib/automationPublicReply.ts';import { ForbiddenError, NotConfiguredError } from '../lib/errors.ts';import { newRowId } from '../lib/ids.ts';import { verifyTokenMatches } from '../lib/metaWebhookSignature.ts';@@ -25,6 +26,8 @@ export interface IngestResult {duplicates: number;// the new comments that matched a rule, for the request to start sending right awayqueuedIds: string[];+ // the public replies queued under new comments, or under earlier copies that were missing one+ publicReplyIds: string[];// follow-ups for people who answered a followers-only replyfollowupIds: string[];// database calls the intake made, which count against the request's subrequests@@ -39,7 +42,10 @@ export interface AutomationWebhookService {// Instagram comments are at most 2,200 characters; the column has the same limitconst MAX_TEXT = 2200;-function newComment(event: InstagramCommentEvent, owner: WebhookRule, fields: Pick<NewAutomationComment, 'ruleId' | 'status' | 'statusReason'>): NewAutomationComment {+type CommentFields = Pick<NewAutomationComment, 'ruleId' | 'status' | 'statusReason'> & Partial<Pick<NewAutomationComment, 'publicReply'>>;++function newComment(event: InstagramCommentEvent, owner: WebhookRule, fields: CommentFields): NewAutomationComment {+ const matched = fields.ruleId !== null;const queued = fields.status === 'queued';return {id: newRowId(),@@ -50,23 +56,30 @@ function newComment(event: InstagramCommentEvent, owner: WebhookRule, fields: PimediaId: event.mediaId,fromId: event.fromId,// the words and the author are kept only for comments a rule answers- fromUsername: queued ? event.fromUsername : null,- text: queued ? event.text?.slice(0, MAX_TEXT) ?? null : null,+ fromUsername: matched ? event.fromUsername : null,+ text: matched ? event.text?.slice(0, MAX_TEXT) ?? null : null,nextAttemptAt: queued ? new Date(Date.now() - DUE_NOW_SKEW_MS).toISOString() : null,notifiedAt: new Date(event.notifiedAt).toISOString(),expiresAt: expiresAtFor(new Date(event.notifiedAt)),+ publicReply: null,...fields,};}-// the first rule of the oldest connected account owns a comment no rule answers, so it is still counted once+// the first rule of the oldest connected account owns a comment no rule answers, so it is still counted once. The+// account's own comments are never answered, which also keeps its public replies from answering themselvesfunction classify(event: InstagramCommentEvent, rules: WebhookRule[]): NewAutomationComment {const owner = rules[0];if (event.fromId !== null && event.fromId === event.igUserId) return newComment(event, owner, { ruleId: null, status: 'ignored', statusReason: 'own_comment' });if (!event.text) return newComment(event, owner, { ruleId: null, status: 'ignored', statusReason: 'no_text' });const match = pickRule(rules, event.text, event.mediaId);if (!match) return newComment(event, owner, { ruleId: null, status: 'ignored', statusReason: 'no_match' });- return newComment(event, match.rule, { ruleId: match.rule.id, status: 'queued', statusReason: null });+ const { rule } = match;+ const publicReply = rule.publicReplyEnabled && rule.publicReplyTexts.length > 0+ ? { id: newRowId(), text: pickPublicReplyText(rule.publicReplyTexts, event.commentId) }+ : null;+ if (!rule.privateReplyEnabled) return newComment(event, rule, { ruleId: rule.id, status: 'skipped', statusReason: 'private_reply_off', publicReply });+ return newComment(event, rule, { ruleId: rule.id, status: 'queued', statusReason: null, publicReply });}// stores what a webhook delivered before it is acknowledged; comments for accounts without an enabled rule are not kept@@ -104,7 +117,7 @@ export function createAutomationWebhookService({ rules, comments, followups, aut}}- const inserted = await comments.insertMany(rows);+ const { inserted, publicReplyIds } = await comments.store(rows);const queuedIds = inserted.filter(row => row.status === 'queued').map(row => row.id);if (rows.length > 0) subrequests++;@@ -117,7 +130,7 @@ export function createAutomationWebhookService({ rules, comments, followups, autsubrequests++;}- const result = { stored: inserted.length, duplicates: rows.length - inserted.length, queuedIds, followupIds, subrequests };+ const result = { stored: inserted.length, duplicates: rows.length - inserted.length, queuedIds, publicReplyIds, followupIds, subrequests };context.log.info('instagram webhook stored', {comments: webhook.comments.length,messages: webhook.messages.length,@@ -125,6 +138,7 @@ export function createAutomationWebhookService({ rules, comments, followups, autstored: result.stored,duplicates: result.duplicates,queued: queuedIds.length,+ publicReplies: publicReplyIds.length,followups: followupIds.length,});return result;diff --git a/backend/services/instagram/instagramComments.ts b/backend/services/instagram/instagramComments.tsnew file mode 100644index 0000000..2ba7403--- /dev/null+++ b/backend/services/instagram/instagramComments.ts@@ -0,0 +1,49 @@+import { igFetch } from './instagramApi.ts';+import { postOnce } from './instagramMessaging.ts';+import { MAX_REPLY_PAGES } from '../../lib/automationPublicReply.ts';+import type { SendResult } from '../../lib/automationDelivery.ts';+import type { ConversationMessage } from '../../lib/automationReview.ts';+import type { InstagramApiErrorBody } from './instagramApi.ts';++interface ReplyBody extends InstagramApiErrorBody {+ id?: string;+}++interface RepliesBody {+ data?: { id?: string; text?: string; timestamp?: string; from?: { id?: string } }[];+ paging?: { next?: string; cursors?: { after?: string } };+}++// the replies under one comment as far as they were read; complete is false when more pages were left unread+export interface CommentReplies {+ replies: ConversationMessage[];+ complete: boolean;+}++// Instagram returns at most this many replies a page+const REPLIES_PAGE = 50;++// one public reply under a comment; a reply to a reply lands in the top-level comment's thread. Accepted only when+// Instagram answers with the new reply's id, since nothing else shows the reply is there+export function replyToComment(commentId: string, accessToken: string, text: string): Promise<SendResult> {+ return postOnce<ReplyBody>(`/${commentId}/replies`, accessToken, { message: text }, body => (body.id+ ? { kind: 'accepted', messageId: body.id, recipientId: null }+ : { kind: 'ambiguous', message: 'its answer had no reply id' }));+}++// the replies under a comment, to find a public reply whose answer was lost; a read, so asking again is always safe+export async function listCommentReplies(commentId: string, accessToken: string, signal?: AbortSignal): Promise<CommentReplies> {+ const replies: ConversationMessage[] = [];+ let after: string | undefined;+ for (let page = 0; page < MAX_REPLY_PAGES; page++) {+ const params: Record<string, string> = { fields: 'id,text,timestamp,from', limit: String(REPLIES_PAGE), access_token: accessToken };+ if (after) params.after = after;+ const body = await igFetch<RepliesBody>(`/${commentId}/replies`, params, 0, signal);+ for (const reply of body.data ?? []) {+ if (reply.id && reply.timestamp) replies.push({ id: reply.id, createdTime: reply.timestamp, fromId: reply.from?.id ?? null, text: reply.text ?? null });+ }+ after = body.paging?.next ? body.paging.cursors?.after : undefined;+ if (!after) return { replies, complete: true };+ }+ return { replies, complete: false };+}diff --git a/backend/services/instagram/instagramMessaging.ts b/backend/services/instagram/instagramMessaging.tsindex e36ccce..4fd33ba 100644--- a/backend/services/instagram/instagramMessaging.ts+++ b/backend/services/instagram/instagramMessaging.ts@@ -36,16 +36,17 @@ 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 sendMessage(igUserId: string, accessToken: string, recipient: MessageRecipient, text: string): Promise<SendResult> {+// one POST to Instagram that 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 post+// 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. read turns a successful answer into the result+export async function postOnce<T extends InstagramApiErrorBody>(endpoint: string, accessToken: string, payload: unknown, read: (body: T) => SendResult): Promise<SendResult> {let response: Response;try {- response = await fetch(buildGraphUrl(`/${igUserId}/messages`).toString(), {+ response = await fetch(buildGraphUrl(endpoint).toString(), {method: 'POST',headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${accessToken}` },- body: JSON.stringify({ recipient, message: { text } }),+ body: JSON.stringify(payload),signal: AbortSignal.timeout(SEND_TIMEOUT_MS),});} catch (err) {@@ -54,16 +55,16 @@ export async function sendMessage(igUserId: string, accessToken: string, recipie}const usageHeader = response.headers.get('x-business-use-case-usage');- let body: SendBody;+ let body: T;try {- body = await response.json() as SendBody;+ body = await response.json() as T;} catch {- // an accepted request whose answer cannot be read may still have delivered the message+ // an accepted request whose answer cannot be read may still have gone throughif (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, recipientId: body.recipient_id ?? null };+ if (response.ok && !body.error) return read(body);const error = body.error ?? {};return {kind: 'error',@@ -75,6 +76,13 @@ export async function sendMessage(igUserId: string, accessToken: string, recipie};}+// a message to one person or a private reply to a comment+export function sendMessage(igUserId: string, accessToken: string, recipient: MessageRecipient, text: string): Promise<SendResult> {+ return postOnce<SendBody>(`/${igUserId}/messages`, accessToken, { recipient, message: { text } }, body => ({+ kind: 'accepted', messageId: body.message_id ?? null, recipientId: body.recipient_id ?? null,+ }));+}+// one private reply to a comment; Instagram allows one per comment, within 7 days of itexport function sendPrivateReply(igUserId: string, accessToken: string, commentId: string, text: string): Promise<SendResult> {return sendMessage(igUserId, accessToken, { comment_id: commentId }, text);diff --git a/backend/tests/fixtures/fakeAutomationQueue.ts b/backend/tests/fixtures/fakeAutomationQueue.tsindex 03a5f52..9ed7dad 100644--- a/backend/tests/fixtures/fakeAutomationQueue.ts+++ b/backend/tests/fixtures/fakeAutomationQueue.ts@@ -1,10 +1,13 @@// 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+// finish_automation_send, the follow-up and public reply functions, intake, 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 databaseimport 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';+import type { AutomationPublicReplyRepository, ClaimedPublicReply, PublicReviewResult } from '../../repositories/automationPublicReplyRepository.ts';+import type {+ AutomationCommentStatus, AutomationFollowupKind, AutomationFollowupStatus, AutomationGateStatus, AutomationPublicReplyStatus,+} from '../../../shared/types/automation.ts';export interface QueueRow {id: string;@@ -33,7 +36,8 @@ export interface QueueAttempt {id: string;commentRowId: string;followupId?: string;- kind?: 'private_reply' | 'followup';+ publicReplyId?: string;+ kind?: 'private_reply' | 'followup' | 'public_reply';userId: string;accountId: string;ruleId: string | null;@@ -52,6 +56,8 @@ export interface QueueRule {requireFollow?: boolean;followPromptText?: string | null;notFollowingText?: string | null;+ // the claim of a public reply sees the rule as on only while its public reply is on+ publicReplyEnabled?: boolean;}export interface QueueControls {@@ -59,6 +65,8 @@ export interface QueueControls {pausedReason: string | null;cooldownUntil: string | null;limitedUntil?: string | null;+ publicCooldownUntil?: string | null;+ publicLimitedUntil?: string | null;}export interface FollowupRow {@@ -80,10 +88,38 @@ export interface FollowupRow {windowExpiresAt: string;}+export interface PublicRow {+ id: string;+ userId: string;+ accountId: string;+ commentRowId: string;+ ruleId: string | null;+ igUserId: string;+ commentId: string;+ mediaId: string | null;+ fromId: string | null;+ replyText: string;+ status: AutomationPublicReplyStatus;+ statusReason: string | null;+ errorMessage: string | null;+ attempts: number;+ nextAttemptAt: string | null;+ claimedAt: string | null;+ replyId: string | null;+ acceptedAt: string | null;+ reviewChecks: number;+ expiresAt: string;+ createdAt: number;+}+export interface FakeQueue extends AutomationCommentRepository {rows: QueueRow[];attempts: QueueAttempt[];followupRows: FollowupRow[];+ publicRows: PublicRow[];+ publicReviews: { id: string; result: PublicReviewResult }[];+ // the same state seen through the public reply repository+ publicReplies: AutomationPublicReplyRepository;rules: Map<string, QueueRule>;controls: Map<string, QueueControls>;tokens: Map<string, string | null>;@@ -91,7 +127,7 @@ export interface FakeQueue extends AutomationCommentRepository {// the same state seen through the follow-up repositoryfollowups: AutomationFollowupRepository;// makes the next calls of one method throw, as a database outage would- failNext(method: 'claim' | 'reserve' | 'finish' | 'release' | 'insertForMessages', times?: number): void;+ failNext(method: 'claim' | 'reserve' | 'finish' | 'release' | 'insertForMessages' | 'store', times?: number): void;}const HOUR = 60 * 60 * 1000;@@ -114,13 +150,23 @@ export function followupRow(id: string, commentRowId: string, overrides: Partial};}-export function fakeAutomationQueue(rows: QueueRow[] = [], followupRows: FollowupRow[] = []): FakeQueue {+export function publicRow(id: string, commentRowId: string, overrides: Partial<PublicRow> = {}): PublicRow {+ return {+ id, userId: 'user-1', accountId: 'ig1', commentRowId, ruleId: 'rule-guide', igUserId: '1784', commentId: `c-${commentRowId}`, mediaId: 'M1',+ fromId: `fan-${commentRowId}`, replyText: 'Sent you a message', status: 'queued', statusReason: null, errorMessage: null, attempts: 0,+ nextAttemptAt: new Date(Date.now() - 1000).toISOString(), claimedAt: null, replyId: null, acceptedAt: null, reviewChecks: 0,+ expiresAt: new Date(Date.now() + 6 * 24 * HOUR).toISOString(), createdAt: Date.now(), ...overrides,+ };+}++export function fakeAutomationQueue(rows: QueueRow[] = [], followupRows: FollowupRow[] = [], publicRows: PublicRow[] = []): 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'] = [];+ const publicReviews: FakeQueue['publicReviews'] = [];function failing(method: string): void {const left = failures.get(method) ?? 0;@@ -172,6 +218,20 @@ export function fakeAutomationQueue(rows: QueueRow[] = [], followupRows: Followu}}+ function interruptPublic(staleBefore: number): void {+ for (const row of publicRows) {+ if (row.status === 'sending' && Date.parse(row.claimedAt!) < staleBefore) {+ Object.assign(row, { status: 'needs_review', statusReason: 'interrupted', claimedAt: null });+ attempts.filter(attempt => attempt.publicReplyId === row.id && attempt.outcome === 'sending').forEach(attempt => { attempt.outcome = 'ambiguous'; });+ }+ }+ }++ function openForPublic(accountId: string): boolean {+ const control = controls.get(accountId);+ return !control || (!control.paused && !later(control.publicCooldownUntil) && !later(control.publicLimitedUntil));+ }+function freeAt(window: QueueAttempt[], limit: number): string | null {return window.length >= limit ? iso(Math.min(...window.map(attempt => attempt.startedAt)) + HOUR) : null;}@@ -285,10 +345,126 @@ export function fakeAutomationQueue(rows: QueueRow[] = [], followupRows: Followu},};+ const publicReplies: AutomationPublicReplyRepository = {+ async claim({ limit, perAccount, leaseSeconds, ids }) {+ failing('claim');+ const staleBefore = now() - leaseSeconds * 1000;+ interruptPublic(staleBefore);+ const due = publicRows.filter(row => isDue(row, staleBefore) && (!ids || ids.includes(row.id)) && openForPublic(row.accountId));+ return turns(due, limit, perAccount).map((row): ClaimedPublicReply => {+ Object.assign(row, { status: 'processing', claimedAt: iso(now()) });+ const rule = row.ruleId ? rules.get(row.ruleId) : undefined;+ return {+ id: row.id, userId: row.userId, accountId: row.accountId, ruleId: row.ruleId, igUserId: row.igUserId, commentId: row.commentId,+ attempts: row.attempts, expiresAt: row.expiresAt, replyText: row.replyText,+ ruleEnabled: (rule?.enabled ?? false) && (rule?.publicReplyEnabled ?? true), accessToken: tokens.get(row.accountId) ?? null,+ };+ });+ },++ async reserve(id, attemptId, accountLimit, digest) {+ failing('reserve');+ const row = publicRows.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?.publicCooldownUntil)) return { outcome: 'cooldown', retryAt: control!.publicCooldownUntil! };+ const answered = publicRows.some(other => other.id !== row.id && other.accountId === row.accountId && row.fromId !== null+ && other.fromId === row.fromId && other.mediaId === row.mediaId && ['sending', 'accepted', 'needs_review'].includes(other.status)+ && other.createdAt > now() - 24 * HOUR);+ if (answered) return { outcome: 'recipient_limit', retryAt: null };+ const retryAt = freeAt(attempts.filter(attempt => attempt.kind === 'public_reply' && attempt.accountId === row.accountId && attempt.startedAt > now() - HOUR), accountLimit);+ if (retryAt) {+ controlsOf(row.accountId).publicLimitedUntil = retryAt;+ return { outcome: 'account_limit', retryAt };+ }+ Object.assign(row, { status: 'sending', claimedAt: iso(now()), attempts: row.attempts + 1 });+ attempts.push({+ id: attemptId, commentRowId: row.commentRowId, publicReplyId: row.id, kind: 'public_reply', userId: row.userId, accountId: row.accountId,+ ruleId: row.ruleId, recipientId: row.fromId, outcome: 'sending', digest, startedAt: now(),+ });+ return { outcome: 'ok', retryAt: null };+ },++ async finish(id, attemptId, plan) {+ failing('finish');+ const row = publicRows.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, replyId: plan.replyId ?? row.replyId,+ acceptedAt: plan.status === 'accepted' ? iso(now()) : row.acceptedAt, nextAttemptAt: plan.nextAttemptAt, claimedAt: null,+ });+ const attempt = attempts.find(candidate => candidate.id === attemptId && candidate.publicReplyId === id);+ if (attempt) attempt.outcome = plan.outcome;+ const control = controlsOf(row.accountId);+ if (plan.cooldownUntil && !(control.publicCooldownUntil && control.publicCooldownUntil > plan.cooldownUntil)) control.publicCooldownUntil = plan.cooldownUntil;+ if (plan.pauseReason) Object.assign(control, { paused: true, pausedReason: plan.pauseReason });+ return true;+ },++ async release(id, plan) {+ failing('release');+ const row = publicRows.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 publicRows) {+ if (ids.includes(row.id) && row.status === 'processing') Object.assign(row, { status: 'queued', claimedAt: null, nextAttemptAt: iso(now() - 30_000) });+ }+ },++ async reviewCandidates({ limit, maxChecks }) {+ return publicRows+ .filter(row => row.status === 'needs_review' && (row.statusReason === 'no_answer' || row.statusReason === 'interrupted') && row.reviewChecks < maxChecks)+ .slice(0, limit)+ .map(row => {+ const lost = attempts.filter(candidate => candidate.publicReplyId === row.id && candidate.outcome === 'ambiguous');+ const attempt = lost.at(-1);+ return {+ id: row.id, igUserId: row.igUserId, commentId: row.commentId, startedAt: iso(attempt?.startedAt ?? now()),+ messageDigest: attempt?.digest ?? null, accessToken: tokens.get(row.accountId) ?? null, reviewChecks: row.reviewChecks,+ lostAnswers: lost.length,+ };+ });+ },++ async recordReview(id, result) {+ publicReviews.push({ id, result });+ const row = publicRows.find(candidate => candidate.id === id && candidate.status === 'needs_review');+ if (!row) return false;+ if (result.found) {+ Object.assign(row, { status: 'accepted', statusReason: 'confirmed', errorMessage: null, replyId: result.replyId, acceptedAt: result.sentAt, reviewChecks: row.reviewChecks + 1 });+ const latest = attempts.filter(attempt => attempt.publicReplyId === id && attempt.outcome === 'ambiguous').at(-1);+ if (latest) latest.outcome = 'accepted';+ } else if (result.resend) {+ Object.assign(row, { status: 'queued', statusReason: 'resend_after_check', errorMessage: null, nextAttemptAt: iso(now()), claimedAt: null, reviewChecks: 0 });+ } else {+ Object.assign(row, { reviewChecks: row.reviewChecks + 1, errorMessage: result.note ?? row.errorMessage });+ }+ return true;+ },++ async requeueForUser(commentRowId, userId) {+ const row = publicRows.find(candidate => candidate.commentRowId === commentRowId && candidate.userId === userId);+ if (!row || !['failed', 'needs_review', 'skipped'].includes(row.status) || Date.parse(row.expiresAt) <= now()) return null;+ Object.assign(row, { status: 'queued', statusReason: 'retry', errorMessage: null, nextAttemptAt: iso(now() - 30_000), claimedAt: null });+ return row.id;+ },++ async releaseHeldForAccount() {},+ };+const queue: FakeQueue = {rows,attempts,followupRows,+ publicRows,+ publicReviews,+ publicReplies,rules,controls,tokens,@@ -296,7 +472,10 @@ export function fakeAutomationQueue(rows: QueueRow[] = [], followupRows: Followufollowups,failNext(method, times = 1) { failures.set(method, times); },- async insertMany(comments: NewAutomationComment[]) {+ // comments are unique per account and public replies per comment; a public reply joins the stored comment, new+ // or from an earlier copy, while the same rule answers it+ async store(comments: NewAutomationComment[]) {+ failing('store');const inserted = comments.filter(comment => !rows.some(row => row.igUserId === comment.igUserId && row.commentId === comment.commentId));for (const comment of inserted) {rows.push(queueRow(comment.id, {@@ -305,7 +484,18 @@ export function fakeAutomationQueue(rows: QueueRow[] = [], followupRows: FollowunextAttemptAt: comment.nextAttemptAt, expiresAt: comment.expiresAt,}));}- return inserted;+ const publicReplyIds: string[] = [];+ for (const comment of comments) {+ if (!comment.publicReply) continue;+ const stored = rows.find(row => row.igUserId === comment.igUserId && row.commentId === comment.commentId && row.ruleId === comment.ruleId);+ if (!stored || publicRows.some(row => row.commentRowId === stored.id)) continue;+ publicRows.push(publicRow(comment.publicReply.id, stored.id, {+ userId: stored.userId, accountId: stored.accountId, ruleId: stored.ruleId, igUserId: stored.igUserId, commentId: stored.commentId,+ mediaId: comment.mediaId, fromId: stored.fromId, replyText: comment.publicReply.text, nextAttemptAt: iso(now()), expiresAt: stored.expiresAt,+ }));+ publicReplyIds.push(comment.publicReply.id);+ }+ return { inserted, publicReplyIds };},async claim({ limit, perAccount, leaseSeconds, ids }) {@@ -332,7 +522,7 @@ export function fakeAutomationQueue(rows: QueueRow[] = [], followupRows: Followuconst control = controls.get(row.accountId);if (control?.paused) return { outcome: 'paused', retryAt: null };if (later(control?.cooldownUntil)) return { outcome: 'cooldown', retryAt: control!.cooldownUntil };- const replies = attempts.filter(attempt => attempt.kind !== 'followup');+ const replies = attempts.filter(attempt => attempt.kind === undefined || attempt.kind === 'private_reply');const otherReplies = new Set(replies.filter(attempt => attempt.accountId === row.accountId && attempt.recipientId === row.fromId&& attempt.startedAt > now() - 24 * HOUR && attempt.commentRowId !== row.id)@@ -394,7 +584,9 @@ export function fakeAutomationQueue(rows: QueueRow[] = [], followupRows: Followucomments.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 };+ const stale = publicRows.filter(row => (row.status === 'queued' || row.status === 'retry_wait') && Date.parse(row.expiresAt) <= now()).slice(0, limit);+ stale.forEach(row => Object.assign(row, { status: 'expired', statusReason: 'expired', nextAttemptAt: null }));+ return { comments: comments.length, followups: lapsed.length, publicReplies: stale.length };},async reviewCandidates({ limit, maxChecks }) {@@ -433,6 +625,10 @@ export function fakeAutomationQueue(rows: QueueRow[] = [], followupRows: Followustale: 0,needsReview: rows.filter(row => row.status === 'needs_review').length,followupsDue: followupRows.filter(row => row.status === 'queued' || row.status === 'retry_wait').length,+ publicDue: publicRows.filter(row => (row.status === 'queued' || row.status === 'retry_wait') && Date.parse(row.nextAttemptAt!) <= now()).length,+ publicOldestDueAt: null,+ publicStale: 0,+ publicNeedsReview: publicRows.filter(row => row.status === 'needs_review').length,pausedAccounts: [...controls.values()].filter(control => control.paused).length,limitedAccounts: [...controls.values()].filter(control => later(control.cooldownUntil) || later(control.limitedUntil)).length,};@@ -442,7 +638,7 @@ export function fakeAutomationQueue(rows: QueueRow[] = [], followupRows: Followuasync findForUser() { return null; },async requeueForUser() { return null; },async releaseHeldForAccount() {},- async statsForUser() { return { comments: {}, attempts: {} }; },+ async statsForUser() { return { comments: {}, publicReplies: {}, attempts: {} }; },async purgeCreatedBefore() { return 0; },};return queue;diff --git a/backend/tests/lib/automationHealth.test.ts b/backend/tests/lib/automationHealth.test.tsindex 5adceac..fa8140e 100644--- a/backend/tests/lib/automationHealth.test.ts+++ b/backend/tests/lib/automationHealth.test.ts@@ -4,7 +4,10 @@ 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 };+const HEALTHY: QueueHealth = {+ due: 0, oldestDueAt: null, waiting: 3, stale: 0, needsReview: 1, followupsDue: 0, publicDue: 0, publicOldestDueAt: null, publicStale: 0, publicNeedsReview: 0,+ pausedAccounts: 1, limitedAccounts: 0,+};test('a queue that keeps up gives no warning, whatever waits for later', () => {assert.equal(healthWarning(HEALTHY, NOW), null);diff --git a/backend/tests/lib/automationPublicReply.test.ts b/backend/tests/lib/automationPublicReply.test.tsnew file mode 100644index 0000000..6b1ed8a--- /dev/null+++ b/backend/tests/lib/automationPublicReply.test.ts@@ -0,0 +1,92 @@+import { test, describe } from 'node:test';+import assert from 'node:assert/strict';+import {+ PUBLIC_ERROR_MESSAGES, PUBLIC_REVIEW_MAX_CHECKS, pickPublicReplyText, publicFinishPlan, publicReadinessPlan, publicReleasePlan, publicReplyTextProblem,+ publicReviewNote, shouldResend,+} from '../../lib/automationPublicReply.ts';+import type { SendResult } from '../../lib/automationDelivery.ts';++const NOW = Date.parse('2026-10-16T12:00:00Z');+const JOB = { attempts: 1, expiresAt: '2026-10-20T12:00:00Z' };+const error = (fields: Partial<Extract<SendResult, { kind: 'error' }>>): SendResult => ({ kind: 'error', httpStatus: 400, message: 'Meta said no', usageHeader: null, ...fields });++describe('public reply rules', () => {+ test('one comment always gets the same text, and a busy post spreads across the texts', () => {+ const texts = ['One', 'Two', 'Three'];+ assert.equal(pickPublicReplyText(texts, '17890001'), pickPublicReplyText(texts, '17890001'));+ const used = new Set(Array.from({ length: 60 }, (_, index) => pickPublicReplyText(texts, `1789${index}`)));+ assert.deepEqual([...used].sort(), ['One', 'Three', 'Two']);+ assert.equal(pickPublicReplyText(['Only'], 'x'), 'Only');+ });++ test('a public reply text stays short, with at most four hashtags and one link', () => {+ assert.equal(publicReplyTextProblem('Sent you a message #guide'), null);+ assert.match(publicReplyTextProblem('x'.repeat(301))!, /300 characters/);+ assert.match(publicReplyTextProblem('#a #b #c #d #e')!, /4 hashtags/);+ assert.match(publicReplyTextProblem('see https://a.example and www.b.example')!, /1 link/);+ });++ test('a reply counts as posted only with the id Instagram gave it', () => {+ const plan = publicFinishPlan({ kind: 'accepted', messageId: 'reply-1', recipientId: null }, JOB, NOW);+ assert.deepEqual([plan.status, plan.outcome, plan.replyId], ['accepted', 'accepted', 'reply-1']);+ });++ test('a lost answer waits for the check of the comment\'s replies instead of a blind second post', () => {+ const plan = publicFinishPlan({ kind: 'ambiguous', message: 'the request timed out' }, JOB, NOW);+ assert.deepEqual([plan.status, plan.outcome, plan.reason], ['needs_review', 'ambiguous', 'no_answer']);+ assert.match(plan.errorMessage!, /checks the comment's replies and sends it again only if it is not there/);+ });++ test('a deleted or hidden comment is skipped; a limit cools down public replies only; a block rests them a day', () => {+ assert.deepEqual([publicFinishPlan(error({ code: 100, subcode: 33 }), JOB, NOW).status, publicFinishPlan(error({ code: 100, subcode: 33 }), JOB, NOW).reason], ['skipped', 'not_eligible']);+ const limited = publicFinishPlan(error({ code: 4 }), JOB, NOW);+ assert.deepEqual([limited.status, limited.outcome, limited.cooldownReason], ['retry_wait', 'rate_limited', PUBLIC_ERROR_MESSAGES.rate_limited]);+ const blocked = publicFinishPlan(error({ code: 368 }), JOB, NOW);+ assert.equal(Date.parse(blocked.cooldownUntil!) - NOW, 24 * 60 * 60 * 1000);+ assert.equal(blocked.status, 'retry_wait');+ assert.match(blocked.errorMessage!, /Private replies are not affected/);+ });++ test('a passing problem is retried a few times, then stops; a refused token holds the account', () => {+ const retry = publicFinishPlan(error({ code: 2, httpStatus: 500 }), JOB, NOW, () => 0);+ assert.deepEqual([retry.status, retry.nextAttemptAt], ['retry_wait', new Date(NOW + 60_000).toISOString()]);+ const stopped = publicFinishPlan(error({ code: 2, httpStatus: 500 }), { ...JOB, attempts: 5 }, NOW);+ assert.equal(stopped.status, 'failed');+ assert.match(stopped.errorMessage!, /Sending stopped after 5 tries/);+ const held = publicFinishPlan(error({ code: 190 }), JOB, NOW);+ assert.deepEqual([held.status, held.reason, held.pauseReason], ['queued', 'paused', PUBLIC_ERROR_MESSAGES.not_authorized]);+ const refused = publicFinishPlan(error({ code: 100, message: 'Invalid parameter' }), JOB, NOW);+ assert.deepEqual([refused.status, refused.errorMessage], ['failed', 'Instagram refused the public reply. Invalid parameter']);+ });++ test('a wait that would end after the 7 days expires the reply instead', () => {+ const plan = publicFinishPlan(error({ code: 368 }), { attempts: 1, expiresAt: new Date(NOW + 60_000).toISOString() }, NOW);+ assert.equal(plan.status, 'expired');+ });++ test('a reply is checked before any limit is spent: expired, turned off or without a token', () => {+ const ready = { ruleEnabled: true, accessToken: 'TOKEN', expiresAt: JOB.expiresAt };+ assert.equal(publicReadinessPlan(ready, NOW), null);+ assert.equal(publicReadinessPlan({ ...ready, expiresAt: '2026-10-16T11:00:00Z' }, NOW)!.status, 'expired');+ assert.equal(publicReadinessPlan({ ...ready, ruleEnabled: false }, NOW)!.reason, 'rule_disabled');+ assert.equal(publicReadinessPlan({ ...ready, accessToken: null }, NOW)!.reason, 'not_connected');+ });++ test('a person already answered on the post is skipped; a full account waits until a reply frees up', () => {+ assert.deepEqual(publicReleasePlan('recipient_limit', null, JOB, NOW)!.status, 'skipped');+ const full = publicReleasePlan('account_limit', '2026-10-16T12:30:00Z', JOB, NOW)!;+ assert.deepEqual([full.status, full.nextAttemptAt, full.errorMessage], ['retry_wait', '2026-10-16T12:30:00.000Z', 'Waiting: this account reached its hourly limit for public replies.']);+ assert.equal(publicReleasePlan('ok', null, JOB, NOW), null);+ assert.equal(publicReleasePlan('paused', null, JOB, NOW)!.reason, 'paused');+ });++ test('a reply missing from the comment goes out again once, only after every reply was read on two checks', () => {+ assert.equal(shouldResend({ complete: true, checks: 1, lostAnswers: 1 }), false);+ assert.equal(shouldResend({ complete: true, checks: 2, lostAnswers: 1 }), true);+ assert.equal(shouldResend({ complete: false, checks: 2, lostAnswers: 1 }), false);+ assert.equal(shouldResend({ complete: true, checks: 2, lostAnswers: 2 }), false);+ assert.match(publicReviewNote({ complete: true, checks: 1 }), /looks again in a few minutes/);+ assert.match(publicReviewNote({ complete: true, checks: PUBLIC_REVIEW_MAX_CHECKS }), /Check the comment on Instagram before you retry/);+ assert.match(publicReviewNote({ complete: false, checks: 1 }), /could not read every reply/);+ });+});diff --git a/backend/tests/lib/config.test.ts b/backend/tests/lib/config.test.tsindex 8c948b8..c2888f7 100644--- a/backend/tests/lib/config.test.ts+++ b/backend/tests/lib/config.test.ts@@ -46,14 +46,16 @@ test('automation limits fall back to their defaults when missing, malformed or overifyToken: undefined,appSecrets: [],paused: false,- limits: { accountHourly: 200, userHourly: 500, globalHourly: 1000, recipientDaily: 3 },+ limits: { accountHourly: 200, userHourly: 500, globalHourly: 1000, recipientDaily: 3, publicAccountHourly: 60 },batchSize: 10,});const set = config({AUTOMATION_ACCOUNT_HOURLY_LIMIT: ' 50 ', AUTOMATION_USER_HOURLY_LIMIT: 'lots', AUTOMATION_GLOBAL_HOURLY_LIMIT: '-1',- AUTOMATION_RECIPIENT_DAILY_LIMIT: '1.5', AUTOMATION_BATCH_SIZE: '4',+ AUTOMATION_RECIPIENT_DAILY_LIMIT: '1.5', AUTOMATION_BATCH_SIZE: '4', AUTOMATION_PUBLIC_ACCOUNT_HOURLY_LIMIT: '500',}).automation;- assert.deepEqual(set.limits, { accountHourly: 50, userHourly: 500, globalHourly: 1000, recipientDaily: 3 });+ // public replies stay at a human pace: 500 is over their cap of 200, so the default applies+ assert.deepEqual(set.limits, { accountHourly: 50, userHourly: 500, globalHourly: 1000, recipientDaily: 3, publicAccountHourly: 60 });+ assert.equal(config({ AUTOMATION_PUBLIC_ACCOUNT_HOURLY_LIMIT: '30' }).automation.limits.publicAccountHourly, 30);assert.equal(set.batchSize, 4);});diff --git a/backend/tests/repositories/automationCommentRepository.test.ts b/backend/tests/repositories/automationCommentRepository.test.tsindex 87e8d25..31e8e6a 100644--- a/backend/tests/repositories/automationCommentRepository.test.ts+++ b/backend/tests/repositories/automationCommentRepository.test.ts@@ -6,26 +6,29 @@ import type { Row } from '../fixtures/fakeSupabase.ts';import type { FinishPlan } from '../../lib/automationDelivery.ts';import type { NewAutomationComment } from '../../repositories/automationCommentRepository.ts';-const LIMITS = { accountHourly: 200, userHourly: 500, globalHourly: 1000, recipientDaily: 3 };+const LIMITS = { accountHourly: 200, userHourly: 500, globalHourly: 1000, recipientDaily: 3, publicAccountHourly: 60 };function newComment(id: string, commentId: string): NewAutomationComment {return {id, userId: 'user-1', accountId: 'ig1', ruleId: 'rule-1', igUserId: '1784', commentId, mediaId: '9', fromId: 'f', fromUsername: 'fan',text: 'GUIDE', status: 'queued', statusReason: null, nextAttemptAt: '2026-10-16T00:00:00Z', notifiedAt: '2026-10-16T00:00:00Z', expiresAt: '2026-10-23T00:00:00Z',+ publicReply: null,};}const rpcArgs = (supabase: ReturnType<typeof fakeSupabase>, name: string) => supabase.calls.find(call => call.type === 'rpc' && call.table === name)!.values as Row;describe('automation comment repository', () => {- test('storing comments ignores ones already stored for the same Instagram account and returns only the new ones', async () => {- const supabase = fakeSupabase([tableRow('automation_comments', { id: 'old', ig_user_id: '1784', comment_id: 'c1' })]);+ test('storing comments sends them with their public replies in one call and returns only what is new', async () => {+ const supabase = fakeSupabase([], {+ store_automation_comments: () => ({ comments: [{ id: 'b', status: 'queued' }], public_replies: ['pb'] }),+ });const repo = createAutomationCommentRepository(supabase);- const inserted = await repo.insertMany([newComment('a', 'c1'), newComment('b', 'c2')]);- assert.deepEqual(inserted.map(comment => comment.id), ['b']);- const call = supabase.calls[0];- assert.deepEqual([call.type, call.onConflict, call.ignoreDuplicates], ['upsert', 'ig_user_id,comment_id', true]);- assert.deepEqual(await repo.insertMany([]), []);+ const stored = await repo.store([newComment('a', 'c1'), { ...newComment('b', 'c2'), publicReply: { id: 'pb', text: 'Sent you a message' } }]);+ assert.deepEqual([stored.inserted.map(comment => comment.id), stored.publicReplyIds], [['b'], ['pb']]);+ const sent = (rpcArgs(supabase, 'store_automation_comments').p_comments as Row[]);+ assert.deepEqual(sent.map(row => [row.comment_id, row.public_reply_id, row.public_reply_text]), [['c1', null, null], ['c2', 'pb', 'Sent you a message']]);+ assert.deepEqual(await repo.store([]), { inserted: [], publicReplyIds: [] });assert.equal(supabase.calls.length, 1);});@@ -63,14 +66,14 @@ describe('automation comment repository', () => {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 }),+ expire_automation_jobs: () => ({ comments: 3, followups: 1, public_replies: 2 }),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(await repo.expireDue(500), { comments: 3, followups: 1, publicReplies: 2 });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 },@@ -79,7 +82,8 @@ describe('automation comment repository', () => {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,+ due: 4, oldestDueAt: 'O', waiting: 0, stale: 0, needsReview: 2, followupsDue: 0, publicDue: 0, publicOldestDueAt: null, publicStale: 0, publicNeedsReview: 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 });@@ -155,8 +159,8 @@ describe('automation comment repository', () => {});test('stats come from the database function, with empty groups when nothing happened', async () => {- const repo = createAutomationCommentRepository(fakeSupabase([], { automation_stats: () => ({ comments: { accepted: 2 } }) }));- assert.deepEqual(await repo.statsForUser('user-1', { from: 'F', to: 'T' }), { comments: { accepted: 2 }, attempts: {} });+ const repo = createAutomationCommentRepository(fakeSupabase([], { automation_stats: () => ({ comments: { accepted: 2 }, public_replies: { failed: 1 } }) }));+ assert.deepEqual(await repo.statsForUser('user-1', { from: 'F', to: 'T' }), { comments: { accepted: 2 }, publicReplies: { failed: 1 }, attempts: {} });});test('an activity item shows its followers-only wait and its latest follow-up', async () => {@@ -170,6 +174,23 @@ describe('automation comment repository', () => {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' });+ assert.equal(item.publicReply, null);+ });++ test('an activity item shows its public reply apart from the private one', async () => {+ const supabase = fakeSupabase([tableRow('automation_comments', {+ id: 'a', user_id: 'user-1', status: 'failed', error_message: 'private failed',+ automation_public_replies: {+ status: 'accepted', status_reason: null, error_message: null, reply_text: 'Sent you a message', attempts: 1, reply_id: 'r1',+ next_attempt_at: null, accepted_at: '2026-10-16T10:00:00Z',+ },+ })]);+ const [item] = await createAutomationCommentRepository(supabase).listForUser('user-1', { limit: 10 });+ assert.deepEqual([item.status, item.errorMessage], ['failed', 'private failed']);+ assert.deepEqual(item.publicReply, {+ status: 'accepted', statusReason: null, errorMessage: null, text: 'Sent you a message', attempts: 1, replyId: 'r1',+ nextAttemptAt: null, acceptedAt: '2026-10-16T10:00:00Z',+ });});test('a failed query becomes a DatabaseError', async () => {diff --git a/backend/tests/repositories/automationRuleRepository.test.ts b/backend/tests/repositories/automationRuleRepository.test.tsindex e4f5099..07e3ae8 100644--- a/backend/tests/repositories/automationRuleRepository.test.ts+++ b/backend/tests/repositories/automationRuleRepository.test.ts@@ -22,7 +22,7 @@ test('the webhook lookup maps the database function\'s rows to rules with theirautomation_rules_for_ig_user: () => [{ id: 'r', user_id: 'u', account_id: 'a', keywords: ['K'], match_mode: 'exact', case_sensitive: true, media_ids: ['1'] }],});assert.deepEqual(await createAutomationRuleRepository(supabase).listEnabledForInstagramUser('1784'), [- { id: 'r', userId: 'u', accountId: 'a', keywords: ['K'], matchMode: 'exact', caseSensitive: true, mediaIds: ['1'] },+ { id: 'r', userId: 'u', accountId: 'a', keywords: ['K'], matchMode: 'exact', caseSensitive: true, mediaIds: ['1'], privateReplyEnabled: true, publicReplyEnabled: false, publicReplyTexts: [] },]);assert.deepEqual(supabase.calls[0].values, { p_ig_user_id: '1784' });});diff --git a/backend/tests/routes/automationRoutes.test.ts b/backend/tests/routes/automationRoutes.test.tsindex 8bc0fa7..da053f3 100644--- a/backend/tests/routes/automationRoutes.test.ts+++ b/backend/tests/routes/automationRoutes.test.ts@@ -85,9 +85,9 @@ 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,+ limitedUntil: null, messagesSubscribed: false, publicCooldownUntil: null, publicCooldownReason: null, publicLimitedUntil: null,}]);- assert.deepEqual(body.settings, { webhookConfigured: true, paused: false, limits: { accountHourly: 200, userHourly: 500, globalHourly: 1000, recipientDaily: 3 } });+ assert.deepEqual(body.settings, { webhookConfigured: true, paused: false, limits: { accountHourly: 200, userHourly: 500, globalHourly: 1000, recipientDaily: 3, publicAccountHourly: 60 } });});test('creating an enabled rule saves it, asks Instagram for the account\'s comments and records both', async () => {@@ -245,10 +245,41 @@ describe('automation routes', () => {assert.equal((await call(target, 'POST', '/automations/activity/gated/retry')).status, 409);});+ test('a public reply is retried on its own, leaving the private reply as it is', async () => {+ const target = server(fakeSupabase([+ ...seed(),+ tableRow('automation_public_replies', { id: 'pub-1', user_id: 'user-1', automation_comment_id: 'accepted-mine', status: 'failed', expires_at: FUTURE, reply_text: 'Sent you a message', attempts: 5 }),+ tableRow('automation_public_replies', { id: 'pub-2', user_id: 'user-2', automation_comment_id: 'failed-theirs', status: 'failed', expires_at: FUTURE, reply_text: 'x', attempts: 1 }),+ ], { claim_automation_public_replies: () => [] }));+ const retried = await call(target, 'POST', '/automations/activity/accepted-mine/public-reply/retry');+ assert.equal(retried.status, 200);+ assert.equal(target.supabase.table.find(row => row.id === 'pub-1')!.status, 'queued');+ assert.equal(target.supabase.table.find(row => row.id === 'accepted-mine')!.status, 'accepted');+ assert.ok(target.supabase.calls.some(call => call.type === 'rpc' && call.table === 'claim_automation_public_replies'));+ assert.ok(audits(target.supabase).includes('automation_public_reply.retried'));+ assert.equal((await call(target, 'POST', '/automations/activity/accepted-mine/public-reply/retry')).status, 409);+ assert.equal((await call(target, 'POST', '/automations/activity/failed-mine/public-reply/retry')).body.message, 'This comment has no public reply to retry');+ assert.equal((await call(target, 'POST', '/automations/activity/failed-theirs/public-reply/retry')).status, 404);+ assert.equal(target.supabase.table.find(row => row.id === 'pub-2')!.status, 'failed');+ });++ test('a rule may reply only in public, and a rule that turns its private reply off must keep a public one', async () => {+ const target = server();+ const created = await call(target, 'POST', '/automations/rules', {+ accountId: 'ig1', name: 'Thanks', matchMode: 'any', keywords: [], privateReplyEnabled: false, publicReplyEnabled: true, publicReplyTexts: ['Thank you'],+ });+ assert.equal(created.status, 200);+ assert.deepEqual([created.body.rule.privateReplyEnabled, created.body.rule.replyText, created.body.rule.publicReplyTexts], [false, '', ['Thank you']]);+ const off = await call(target, 'PUT', '/automations/rules/rule-mine', { privateReplyEnabled: false });+ assert.deepEqual([off.status, off.body.message], [400, 'Turn on the private reply, the public reply, or both']);+ const swapped = await call(target, 'PUT', '/automations/rules/rule-mine', { privateReplyEnabled: false, publicReplyEnabled: true, publicReplyTexts: ['Sent'] });+ assert.deepEqual([swapped.status, swapped.body.rule.privateReplyEnabled, swapped.body.rule.replyText], [200, false, 'Here it is']);+ });+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');- assert.deepEqual(body.stats, { comments: { accepted: 1, failed: 0 }, attempts: { accepted: 1 } });+ assert.deepEqual(body.stats, { comments: { accepted: 1, failed: 0 }, publicReplies: {}, attempts: { accepted: 1 } });assert.equal(Date.parse(body.to) - Date.parse(body.from), 7 * 24 * 60 * 60 * 1000);const sent = target.supabase.calls.find(call => call.table === 'automation_stats')!.values as Row;assert.deepEqual([sent.p_user_id, sent.p_account_id, sent.p_rule_id], ['user-1', 'ig1', null]);diff --git a/backend/tests/routes/instagramWebhookRoutes.test.ts b/backend/tests/routes/instagramWebhookRoutes.test.tsindex 8730ae0..e7aa79c 100644--- a/backend/tests/routes/instagramWebhookRoutes.test.ts+++ b/backend/tests/routes/instagramWebhookRoutes.test.ts@@ -15,8 +15,45 @@ const SENT_AT = Math.floor(Date.now() / 1000);const inTable = (row: Row, name: string) => row._table === name;-// the queue functions, reduced to what one webhook request does: look up rules, claim its comments, reserve, finish+// the queue functions, reduced to what one webhook request does: look up rules, store, claim its comments, reserve, finishconst RPC: Record<string, RpcHandler> = {+ store_automation_comments: (args, table) => {+ const comments: Row[] = [];+ const publicReplies: string[] = [];+ for (const comment of args.p_comments as Row[]) {+ const { public_reply_id: publicReplyId, public_reply_text: publicReplyText, ...fields } = comment;+ let stored = table.find(row => inTable(row, 'automation_comments') && row.ig_user_id === fields.ig_user_id && row.comment_id === fields.comment_id);+ if (!stored) {+ stored = tableRow('automation_comments', fields);+ table.push(stored);+ comments.push({ id: fields.id, status: fields.status });+ }+ const answered = table.some(row => inTable(row, 'automation_public_replies') && row.automation_comment_id === stored.id);+ if (publicReplyId && stored.rule_id === fields.rule_id && !answered) {+ table.push(tableRow('automation_public_replies', { id: publicReplyId, automation_comment_id: stored.id, account_id: stored.account_id, comment_id: stored.comment_id, rule_id: stored.rule_id, reply_text: publicReplyText, status: 'queued' }));+ publicReplies.push(publicReplyId as string);+ }+ }+ return { comments, public_replies: publicReplies };+ },+ claim_automation_public_replies: (args, table) => table+ .filter(row => inTable(row, 'automation_public_replies') && row.status === 'queued' && (args.p_ids as string[]).includes(row.id as string))+ .map(row => {+ row.status = 'processing';+ return { ...row, ig_user_id: '1784', attempts: 0, expires_at: new Date(Date.now() + 60 * 60 * 1000).toISOString(), rule_enabled: true, access_token: 'TOKEN-1' };+ }),+ reserve_automation_public_reply: (args, table) => {+ const row = table.find(candidate => inTable(candidate, 'automation_public_replies') && candidate.id === args.p_id && candidate.status === 'processing');+ if (!row) return [{ outcome: 'gone', retry_at: null }];+ row.status = 'sending';+ return [{ outcome: 'ok', retry_at: null }];+ },+ finish_automation_public_reply: (args, table) => {+ const row = table.find(candidate => inTable(candidate, 'automation_public_replies') && candidate.id === args.p_id && candidate.status === 'sending');+ if (!row) return false;+ Object.assign(row, { status: args.p_status, reply_id: args.p_reply_id });+ return true;+ },automation_rules_for_ig_user: (args, table) => table.filter(row => inTable(row, 'automation_rules') && row.enabled).filter(row => table.some(account => inTable(account, 'accounts') && account.id === row.account_id && (account.data as Row).igUserId === args.p_ig_user_id)),@@ -152,6 +189,30 @@ describe('instagram webhook routes', () => {assert.equal(target.supabase.table.find(row => row.id === 'gated')!.gate_status, 'completed');});+ test('a rule with both replies posts the public reply even when the private reply fails, and a redelivery sends neither again', async () => {+ fetchMock?.restore();+ const posted: { path: string; body: Row }[] = [];+ fetchMock = installFetch(request => {+ const path = new URL(request.url).pathname;+ posted.push({ path, body: JSON.parse(request.body ?? '{}') as Row });+ if (path.endsWith('/messages')) return reply({ error: { message: 'Not allowed', code: 10, error_subcode: 2534022 } }, 400);+ return reply({ id: 'reply-1' });+ });+ const target = app(fakeSupabase(seed().map(row => (row.id === 'rule-1'+ ? { ...row, public_reply_enabled: true, public_reply_texts: ['Sent you a message'] }+ : row)), RPC));+ const body = JSON.stringify(commentNotification('1784', SENT_AT, [{ id: '555', text: 'GUIDE', mediaId: '9001' }]));+ const signature = await metaSignature('IGSECRET', body);+ assert.equal((await post(target, body, signature)).status, 200);+ assert.deepEqual(posted.map(request => request.path.replace(/^\/v[\d.]+/, '')), ['/1784/messages', '/555/replies']);+ assert.deepEqual(posted[1].body, { message: 'Sent you a message' });+ const comment = target.supabase.table.find(row => inTable(row, 'automation_comments'))!;+ const publicReply = target.supabase.table.find(row => inTable(row, 'automation_public_replies'))!;+ assert.deepEqual([comment.status, publicReply.status, publicReply.reply_id], ['failed', 'accepted', 'reply-1']);+ assert.equal((await post(target, body, signature)).status, 200);+ assert.equal(posted.length, 2);+ });+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/automationPublicReplyProcessor.test.ts b/backend/tests/services/automationPublicReplyProcessor.test.tsnew file mode 100644index 0000000..000ac1d--- /dev/null+++ b/backend/tests/services/automationPublicReplyProcessor.test.ts@@ -0,0 +1,166 @@+import { test, describe, beforeEach, afterEach, mock } from 'node:test';+import assert from 'node:assert/strict';+import { createAutomationPublicReplyProcessor } from '../../services/automationPublicReplyProcessor.ts';+import { createAutomationProcessor } from '../../services/automationProcessor.ts';+import { CLAIM_LEASE_SECONDS } 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 } from '../fixtures/fakeFetch.ts';+import { fakeAutomationQueue, publicRow, 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 Posted {+ path: string;+ body: Record<string, unknown>;+}++let fetchMock: FetchMock | null = null;+let posted: Posted[] = [];++// Instagram's comment replies and messages endpoints; a public reply is answered with its new id unless scripted+function instagram(script: Record<string, (count: number) => FakeReply | Error> = {}) {+ fetchMock = installFetch(request => {+ const path = new URL(request.url).pathname.replace(/^\/v[\d.]+/, '');+ posted.push({ path, body: JSON.parse(request.body ?? '{}') as Record<string, unknown> });+ const commentId = path.split('/')[1];+ const answer = script[commentId];+ if (answer) return answer(posted.filter(item => item.path === path).length);+ return path.endsWith('/replies') ? reply({ id: `reply-${commentId}` }) : reply({ recipient_id: 'r', message_id: `m-${commentId}` });+ });+}++const context = (signal = new AbortController().signal) => ({ requestId: 'req-test', signal, log: createLogger() });++function processor(queue: FakeQueue, env: Partial<Env> = {}) {+ return createAutomationPublicReplyProcessor({ publicReplies: queue.publicReplies, automation: readAutomationConfig(env as Env), context: context() });+}++// a matched comment whose private reply is still queued, with its public reply due+function both(id: string, overrides: Parameters<typeof publicRow>[2] = {}): FakeQueue {+ return fakeAutomationQueue([queueRow(id)], [], [publicRow(`pub-${id}`, id, overrides)]);+}++beforeEach(() => {+ posted = [];+ mockRowIds();+ mock.method(console, 'log', () => {});+ mock.method(console, 'warn', () => {});+ mock.method(console, 'error', () => {});+});+afterEach(() => {+ fetchMock?.restore();+ fetchMock = null;+ mock.restoreAll();+});++describe('automation public reply processor', () => {+ test('a due public reply is posted under its comment with its stored text, and the private reply is left alone', async () => {+ instagram();+ const queue = both('a');+ const run = await processor(queue).run();+ assert.deepEqual(run.outcomes, { accepted: 1 });+ assert.deepEqual(posted, [{ path: '/c-a/replies', body: { message: 'Sent you a message' } }]);+ assert.deepEqual([queue.publicRows[0].status, queue.publicRows[0].replyId], ['accepted', 'reply-c-a']);+ assert.deepEqual([queue.rows[0].status, queue.rows[0].attempts], ['queued', 0]);+ assert.deepEqual(queue.attempts.map(attempt => [attempt.kind, attempt.outcome, attempt.publicReplyId]), [['public_reply', 'accepted', 'pub-a']]);+ });++ test('a private reply that fails never repeats the public one, and a public one retried alone never repeats the private one', async () => {+ instagram({ '1784': () => reply({ error: { message: 'Not allowed', code: 10, error_subcode: 2534022 } }, 400) });+ const queue = both('a');+ const privateReplies = createAutomationProcessor({ comments: queue, automation: readAutomationConfig({} as Env), context: context() });+ await privateReplies.run();+ await processor(queue).run();+ assert.deepEqual([queue.rows[0].status, queue.publicRows[0].status], ['failed', 'accepted']);+ await privateReplies.run();+ await processor(queue).run();+ assert.deepEqual(posted.map(item => item.path), ['/1784/messages', '/c-a/replies']);++ fetchMock?.restore();+ posted = [];+ instagram({ 'c-b': count => (count === 1 ? reply({ error: { message: 'Invalid parameter', code: 100 } }, 400) : reply({ id: 'reply-b' })) });+ const other = both('b');+ await createAutomationProcessor({ comments: other, automation: readAutomationConfig({} as Env), context: context() }).run();+ await processor(other).run();+ assert.deepEqual([other.rows[0].status, other.publicRows[0].status], ['accepted', 'failed']);+ assert.equal(await other.publicReplies.requeueForUser('b', 'user-1'), 'pub-b');+ await processor(other).run();+ assert.deepEqual([other.rows[0].status, other.publicRows[0].status, other.publicRows[0].replyId], ['accepted', 'accepted', 'reply-b']);+ assert.deepEqual(posted.map(item => item.path), ['/1784/messages', '/c-b/replies', '/c-b/replies']);+ });++ test('a post whose answer is lost waits for the review and is never posted again by the dispatch', async () => {+ instagram({ 'c-a': () => new Error('connection reset') });+ const queue = both('a');+ await processor(queue).run();+ assert.deepEqual([queue.publicRows[0].status, queue.publicRows[0].statusReason], ['needs_review', 'no_answer']);+ assert.equal(queue.attempts[0].outcome, 'ambiguous');+ await processor(queue).run();+ assert.equal(posted.length, 1);+ });++ test('two runs at the same moment post each public reply once', async () => {+ instagram();+ const queue = fakeAutomationQueue(+ Array.from({ length: 8 }, (_, index) => queueRow(`c${index}`)),+ [],+ Array.from({ length: 8 }, (_, index) => publicRow(`p${index}`, `c${index}`, { fromId: `fan-${index}` })),+ );+ await Promise.all([processor(queue).run(), processor(queue).run()]);+ assert.equal(posted.length, 8);+ assert.equal(new Set(posted.map(item => item.path)).size, 8);+ assert.ok(queue.publicRows.every(row => row.status === 'accepted'));+ });++ test('a rate limit cools down public replies only; the account\'s private replies are still claimed', async () => {+ instagram({ 'c-a': () => reply({ error: { message: 'limited', code: 4 } }, 400) });+ const queue = fakeAutomationQueue([queueRow('a'), queueRow('b')], [], [publicRow('pub-a', 'a'), publicRow('pub-b', 'b', { fromId: 'other' })]);+ await processor(queue).run();+ const control = queue.controls.get('ig1')!;+ assert.ok(Date.parse(control.publicCooldownUntil!) > Date.now());+ assert.equal(control.cooldownUntil, null);+ assert.deepEqual(queue.publicRows.map(row => [row.status, row.statusReason]), [['retry_wait', 'rate_limited'], ['retry_wait', 'cooldown']]);+ assert.equal(posted.length, 1);+ assert.equal((await queue.publicReplies.claim({ limit: 5, perAccount: 5, leaseSeconds: CLAIM_LEASE_SECONDS })).length, 0);+ assert.equal((await queue.claim({ limit: 5, perAccount: 5, leaseSeconds: CLAIM_LEASE_SECONDS })).length, 2);+ });++ test('one person commenting twice on a post gets one public reply, and an account at its hourly limit waits', async () => {+ instagram();+ const repeat = fakeAutomationQueue([queueRow('a'), queueRow('b')], [], [+ publicRow('pub-a', 'a', { fromId: 'fan', createdAt: Date.now() - 1000 }),+ publicRow('pub-b', 'b', { fromId: 'fan' }),+ ]);+ await processor(repeat).run();+ assert.deepEqual(repeat.publicRows.map(row => [row.status, row.statusReason]), [['accepted', null], ['skipped', 'recipient_limit']]);++ const busy = fakeAutomationQueue([queueRow('a'), queueRow('b'), queueRow('c')], [], ['a', 'b', 'c'].map(id => publicRow(`pub-${id}`, id)));+ const run = await processor(busy, { AUTOMATION_PUBLIC_ACCOUNT_HOURLY_LIMIT: '2' }).run();+ assert.deepEqual(run.outcomes, { accepted: 2, retry_wait: 1 });+ assert.ok(Date.parse(busy.controls.get('ig1')!.publicLimitedUntil!) > Date.now());+ assert.equal(busy.controls.get('ig1')!.limitedUntil ?? null, null);+ });++ test('a rule whose public reply was turned off skips it without asking Instagram', async () => {+ instagram();+ const queue = both('a');+ queue.rules.get('rule-guide')!.publicReplyEnabled = false;+ await processor(queue).run();+ assert.deepEqual([queue.publicRows[0].status, queue.publicRows[0].statusReason, posted.length], ['skipped', 'rule_disabled', 0]);+ });++ test('a run that stopped while posting leaves the reply for the review, and a paused instance posts nothing', async () => {+ instagram();+ const queue = both('a', { status: 'sending', claimedAt: new Date(Date.now() - 2 * CLAIM_LEASE_SECONDS * 1000).toISOString() });+ queue.attempts.push({ id: 'att', commentRowId: 'a', publicReplyId: 'pub-a', kind: 'public_reply', userId: 'user-1', accountId: 'ig1', ruleId: 'rule-guide', recipientId: 'fan-a', outcome: 'sending', startedAt: Date.now() - 3_600_000 });+ await processor(queue).run();+ assert.deepEqual([queue.publicRows[0].status, queue.publicRows[0].statusReason, queue.attempts[0].outcome, posted.length], ['needs_review', 'interrupted', 'ambiguous', 0]);++ const paused = both('b');+ assert.deepEqual(await processor(paused, { AUTOMATION_PAUSED: 'true' }).run(), { claimed: 0, outcomes: {}, subrequests: 0 });+ assert.equal(posted.length, 0);+ });+});diff --git a/backend/tests/services/automationReconciler.test.ts b/backend/tests/services/automationReconciler.test.tsindex 2e1c9e7..22685cc 100644--- a/backend/tests/services/automationReconciler.test.ts+++ b/backend/tests/services/automationReconciler.test.ts@@ -4,7 +4,7 @@ import { createAutomationReconciler } from '../../services/automationReconciler.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 { fakeAutomationQueue, followupRow, publicRow, queueRow } from '../fixtures/fakeAutomationQueue.ts';import type { FakeQueue } from '../fixtures/fakeAutomationQueue.ts';import type { Logger } from '../../lib/logger.ts';@@ -43,7 +43,34 @@ async function lost(id: string): Promise<FakeQueue> {return queue;}-const reconciler = (queue: FakeQueue) => createAutomationReconciler({ comments: queue, context: { requestId: 'cron-test', signal: new AbortController().signal, log: logger() } });+const PUBLIC_TEXT = 'Sent you a message';++// the replies under a comment, one page or two, as Instagram lists them+function commentReplies(pages: { id: string; from: string; text: string }[][] | Error) {+ fetchMock = installFetch(request => {+ requests.push(request);+ if (pages instanceof Error) return pages;+ const after = new URL(request.url).searchParams.get('after');+ const index = after ? Number(after) : 0;+ const data = pages[index].map(item => ({ id: item.id, text: item.text, timestamp: new Date().toISOString(), from: { id: item.from } }));+ const next = index + 1 < pages.length ? { next: 'https://graph.instagram.com/next', cursors: { after: String(index + 1) } } : undefined;+ return reply({ data, paging: next });+ });+}++// a public reply whose answer was lost, after this many checks and lost answers+async function lostPublic(checks = 0, lostAnswers = 1): Promise<FakeQueue> {+ const queue = fakeAutomationQueue([queueRow('a', { status: 'accepted' })], [], [publicRow('pub-a', 'a', { status: 'needs_review', statusReason: 'no_answer', nextAttemptAt: null, reviewChecks: checks })]);+ for (let index = 0; index < lostAnswers; index++) {+ queue.attempts.push({+ id: `att-${index}`, commentRowId: 'a', publicReplyId: 'pub-a', kind: 'public_reply', userId: 'user-1', accountId: 'ig1', ruleId: 'rule-guide',+ recipientId: 'fan-a', outcome: 'ambiguous', digest: await messageDigest(PUBLIC_TEXT), startedAt: Date.now() - 10 * 60_000,+ });+ }+ return queue;+}++const reconciler = (queue: FakeQueue) => createAutomationReconciler({ comments: queue, publicReplies: queue.publicReplies, context: { requestId: 'cron-test', signal: new AbortController().signal, log: logger() } });beforeEach(() => {requests = [];@@ -105,8 +132,53 @@ describe('automation reconciler', () => {[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.deepEqual(run.expired, { comments: 1, followups: 1, publicReplies: 0 });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']);});++ test('a lost public reply found among the comment\'s replies becomes accepted with its id, on the second page too', async () => {+ commentReplies([[{ id: 'other', from: 'fan', text: PUBLIC_TEXT }], [{ id: 'reply-found', from: '1784', text: PUBLIC_TEXT }]]);+ const queue = await lostPublic();+ const run = await reconciler(queue).run();+ assert.deepEqual(run.reviewedPublic, { found: 1, notFound: 0, failed: 0, resent: 0 });+ assert.deepEqual([queue.publicRows[0].status, queue.publicRows[0].replyId, queue.attempts[0].outcome], ['accepted', 'reply-found', 'accepted']);+ assert.ok(requests.every(request => request.method === 'GET'));+ assert.equal(new URL(requests[0].url).pathname.replace(/^\/v[\d.]+/, ''), '/c-a/replies');+ });++ test('a public reply missing on two checks of every reply goes back in the queue once; nothing is posted from here', async () => {+ commentReplies([[{ id: 'other', from: '1784', text: 'Something else' }]]);+ const first = await lostPublic(0);+ await reconciler(first).run();+ assert.deepEqual([first.publicRows[0].status, first.publicRows[0].reviewChecks], ['needs_review', 1]);+ assert.match(first.publicRows[0].errorMessage!, /looks again in a few minutes/);+ const second = await lostPublic(1);+ const run = await reconciler(second).run();+ assert.deepEqual(run.reviewedPublic, { found: 0, notFound: 0, failed: 0, resent: 1 });+ assert.deepEqual([second.publicRows[0].status, second.publicRows[0].statusReason], ['queued', 'resend_after_check']);+ assert.ok(requests.every(request => request.method === 'GET'));+ });++ test('a public reply is not sent again when a page of replies was left unread or it was already sent again once', async () => {+ commentReplies([[{ id: 'x1', from: 'fan', text: 'hi' }], [{ id: 'x2', from: 'fan', text: 'hi' }], [{ id: 'x3', from: 'fan', text: 'hi' }]]);+ const unread = await lostPublic(1);+ await reconciler(unread).run();+ assert.equal(unread.publicRows[0].status, 'needs_review');+ assert.match(unread.publicRows[0].errorMessage!, /could not read every reply/);+ fetchMock?.restore();+ commentReplies([[]]);+ const again = await lostPublic(1, 2);+ await reconciler(again).run();+ assert.equal(again.publicRows[0].status, 'needs_review');+ });++ test('replies Instagram will not show count as a check that could not be made, and nothing is sent', async () => {+ commentReplies(new Error('connection reset'));+ const queue = await lostPublic();+ const run = await reconciler(queue).run();+ assert.deepEqual(run.reviewedPublic, { found: 0, notFound: 0, failed: 1, resent: 0 });+ assert.deepEqual([queue.publicRows[0].status, queue.publicRows[0].reviewChecks], ['needs_review', 1]);+ assert.match(queue.publicRows[0].errorMessage!, /could not read the comment's replies/);+ });});diff --git a/backend/tests/services/automationWebhookService.test.ts b/backend/tests/services/automationWebhookService.test.tsindex 0ba42e4..f5ffb0b 100644--- a/backend/tests/services/automationWebhookService.test.ts+++ b/backend/tests/services/automationWebhookService.test.ts@@ -14,11 +14,18 @@ import type { Env } from '../../types/env.ts';const SENT_AT = 1792152000;+const DM_ONLY = { privateReplyEnabled: true, publicReplyEnabled: false, publicReplyTexts: [] };+const RULES: Record<string, WebhookRule[]> = {'1784': [- { id: 'reel-a', userId: 'user-1', accountId: 'ig1', keywords: ['GUIDE'], matchMode: 'contains', caseSensitive: false, mediaIds: ['A'] },- { id: 'reel-b', userId: 'user-1', accountId: 'ig1', keywords: ['COURSE'], matchMode: 'contains', caseSensitive: false, mediaIds: ['B'] },- { id: 'any', userId: 'user-1', accountId: 'ig1', keywords: ['SOURCE'], matchMode: 'contains', caseSensitive: false, mediaIds: [] },+ { id: 'reel-a', userId: 'user-1', accountId: 'ig1', keywords: ['GUIDE'], matchMode: 'contains', caseSensitive: false, mediaIds: ['A'], ...DM_ONLY },+ { id: 'reel-b', userId: 'user-1', accountId: 'ig1', keywords: ['COURSE'], matchMode: 'contains', caseSensitive: false, mediaIds: ['B'], ...DM_ONLY },+ { id: 'any', userId: 'user-1', accountId: 'ig1', keywords: ['SOURCE'], matchMode: 'contains', caseSensitive: false, mediaIds: [], ...DM_ONLY },+ ],+ // one rule answers in both places, one only in public+ '2000': [+ { id: 'both', userId: 'user-1', accountId: 'ig2', keywords: ['GUIDE'], matchMode: 'contains', caseSensitive: false, mediaIds: [], privateReplyEnabled: true, publicReplyEnabled: true, publicReplyTexts: ['Sent you a message', 'Check your messages'] },+ { id: 'thanks', userId: 'user-1', accountId: 'ig2', keywords: [], matchMode: 'any', caseSensitive: false, mediaIds: [], privateReplyEnabled: false, publicReplyEnabled: true, publicReplyTexts: ['Thank you'] },],};@@ -29,7 +36,7 @@ function rulesRepository(): AutomationRuleRepository {let inserted: NewAutomationComment[][] = [];function service(queue: FakeQueue, env: Partial<Env> = {}) {- const comments = { ...queue, insertMany: async (rows: NewAutomationComment[]) => { inserted.push(rows); return queue.insertMany(rows); } };+ const comments = { ...queue, store: async (rows: NewAutomationComment[]) => { inserted.push(rows); return queue.store(rows); } };return createAutomationWebhookService({rules: rulesRepository(),comments,@@ -88,7 +95,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: [], followupIds: [], subrequests: 2 });+ assert.deepEqual(again, { stored: 0, duplicates: 2, queuedIds: [], publicReplyIds: [], followupIds: [], subrequests: 2 });assert.equal(queue.rows.length, 2);});@@ -130,13 +137,13 @@ describe('instagram webhook intake', () => {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: [], followupIds: [], subrequests: 1 });+ assert.deepEqual(result, { stored: 0, duplicates: 0, queuedIds: [], publicReplyIds: [], followupIds: [], subrequests: 1 });assert.deepEqual(inserted, [[]]);});test('a failed insert fails the intake, so the webhook answers with an error and Meta sends it again', async () => {const queue = fakeAutomationQueue();- const broken = { ...queue, insertMany: async () => { throw new Error('database unavailable'); } };+ const broken = { ...queue, store: async () => { throw new Error('database unavailable'); } };const intake = createAutomationWebhookService({rules: rulesRepository(), comments: broken, followups: queue.followups, automation: readAutomationConfig({} as Env),context: { requestId: 'req-test', signal: new AbortController().signal, log: createLogger() },@@ -152,4 +159,32 @@ describe('instagram webhook intake', () => {await assert.rejects(intake.challengeAnswer({ mode: 'subscribe', verifyToken: 'tok' }), /verify token does not match/);await assert.rejects(service(fakeAutomationQueue()).challengeAnswer({ mode: 'subscribe', verifyToken: 'tok', challenge: '1' }), /INSTAGRAM_WEBHOOK_VERIFY_TOKEN/);});++ test('a rule with both replies queues the private reply and one public reply with a text picked for the comment', async () => {+ const queue = fakeAutomationQueue();+ const result = await ingest(queue, commentNotification('2000', SENT_AT, [{ id: '77', text: 'guide please', mediaId: 'A' }]));+ assert.deepEqual([result.queuedIds.length, result.publicReplyIds.length], [1, 1]);+ assert.deepEqual([queue.rows[0].status, queue.publicRows[0].commentRowId], ['queued', queue.rows[0].id]);+ assert.ok(['Sent you a message', 'Check your messages'].includes(queue.publicRows[0].replyText));+ assert.equal(inserted[0][0].publicReply!.text, queue.publicRows[0].replyText);+ });++ test('a public-only rule keeps the comment, skips the private reply and queues the public one', async () => {+ const queue = fakeAutomationQueue();+ const result = await ingest(queue, commentNotification('2000', SENT_AT, [{ id: '78', text: 'love this', mediaId: 'A' }]));+ assert.deepEqual([result.queuedIds, result.publicReplyIds.length], [[], 1]);+ assert.deepEqual([queue.rows[0].status, queue.rows[0].statusReason, queue.publicRows[0].replyText], ['skipped', 'private_reply_off', 'Thank you']);+ assert.deepEqual([inserted[0][0].text, inserted[0][0].fromUsername], ['love this', 'fan_78']);+ });++ test('a public reply delivered back as the account\'s own comment is never answered, and a redelivery queues no second public reply', async () => {+ const queue = fakeAutomationQueue();+ const body = commentNotification('2000', SENT_AT, [{ id: '79', text: 'guide', mediaId: 'A' }]);+ await ingest(queue, body);+ const again = await ingest(queue, body);+ assert.deepEqual([again.stored, again.publicReplyIds], [0, []]);+ const own = await ingest(queue, commentNotification('2000', SENT_AT, [{ id: '80', text: 'Thank you', mediaId: 'A', fromId: '2000' }]));+ assert.deepEqual([own.queuedIds, own.publicReplyIds], [[], []]);+ assert.equal(queue.publicRows.length, 1);+ });});diff --git a/backend/tests/services/instagram/instagramComments.test.ts b/backend/tests/services/instagram/instagramComments.test.tsnew file mode 100644index 0000000..45bd150--- /dev/null+++ b/backend/tests/services/instagram/instagramComments.test.ts@@ -0,0 +1,62 @@+import { test, describe, afterEach } from 'node:test';+import assert from 'node:assert/strict';+import { listCommentReplies, replyToComment } from '../../../services/instagram/instagramComments.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 comment replies', () => {+ test('a public reply posts the text under the comment with the token in a header and keeps the new reply\'s id', async () => {+ const calls = answer(() => reply({ id: 'reply-1' }));+ assert.deepEqual(await replyToComment('c1', 'TOK', 'Sent you a message'), { kind: 'accepted', messageId: 'reply-1', recipientId: null });+ const request = calls.requests[0];+ assert.deepEqual([request.method, new URL(request.url).pathname, JSON.parse(request.body!)], ['POST', '/v25.0/c1/replies', { message: 'Sent you a message' }]);+ assert.equal((request.headers as Record<string, string>).Authorization, 'Bearer TOK');+ assert.equal(new URL(request.url).searchParams.has('access_token'), false);+ });++ test('an answer without an id, a timeout or a lost connection may have posted the reply, so none counts as sent', async () => {+ answer(() => reply({ success: true }));+ assert.deepEqual(await replyToComment('c1', 'TOK', 'x'), { kind: 'ambiguous', message: 'its answer had no reply id' });+ fetchMock!.restore();+ answer(() => new Error('connection reset'));+ assert.equal((await replyToComment('c1', 'TOK', 'x')).kind, 'ambiguous');+ });++ test('Instagram\'s refusal comes back with its code and a message free of addresses', async () => {+ answer(() => reply({ error: { message: 'Object does not exist, see https://developers.facebook.com/docs', code: 100, error_subcode: 33 } }, 400));+ const result = await replyToComment('c1', 'TOK', 'x');+ assert.deepEqual(result, { kind: 'error', code: 100, subcode: 33, httpStatus: 400, message: 'Object does not exist, see [url]', usageHeader: null });+ });++ test('the replies under a comment are read page by page, up to two pages, and say whether every reply was read', async () => {+ const pages = [+ { data: [{ id: 'r1', text: 'one', timestamp: '2026-10-16T10:00:00+0000', from: { id: '1784' } }], paging: { next: 'https://x', cursors: { after: 'A' } } },+ { data: [{ id: 'r2', text: 'two', timestamp: '2026-10-16T10:01:00+0000', from: { id: 'fan' } }] },+ ];+ const calls = answer(request => reply(new URL(request.url).searchParams.get('after') === 'A' ? pages[1] : pages[0]));+ const read = await listCommentReplies('c1', 'TOK');+ assert.deepEqual(read, {+ complete: true,+ replies: [+ { id: 'r1', createdTime: '2026-10-16T10:00:00+0000', fromId: '1784', text: 'one' },+ { id: 'r2', createdTime: '2026-10-16T10:01:00+0000', fromId: 'fan', text: 'two' },+ ],+ });+ assert.deepEqual(new URL(calls.requests[0].url).searchParams.get('fields'), 'id,text,timestamp,from');+ fetchMock!.restore();+ answer(() => reply({ data: [], paging: { next: 'https://x', cursors: { after: 'B' } } }));+ assert.equal((await listCommentReplies('c1', 'TOK')).complete, false);+ });+});diff --git a/backend/tests/validators/automationValidators.test.ts b/backend/tests/validators/automationValidators.test.tsindex 6b0af07..8b3e0d5 100644--- a/backend/tests/validators/automationValidators.test.ts+++ b/backend/tests/validators/automationValidators.test.ts@@ -10,11 +10,38 @@ const valid = { accountId: 'ig1', name: 'Guide', keywords: ['GUIDE'], replyText:test('a new rule gets its defaults: contains, ignoring case, every post, off, no link and no own limit', () => {assert.deepEqual(parseAutomationRule(valid), {accountId: 'ig1', name: 'Guide', keywords: ['GUIDE'], matchMode: 'contains', caseSensitive: false, mediaIds: [],- replyText: 'Here it is', linkUrl: null, enabled: false, hourlyLimit: null,+ privateReplyEnabled: true, replyText: 'Here it is', linkUrl: null, publicReplyEnabled: false, publicReplyTexts: [], enabled: false, hourlyLimit: null,requireFollow: false, followPromptText: null, notFollowingText: null,});});+test('a rule answers with a private reply, a public reply or both, and each one it uses needs its text', () => {+ const both = parseAutomationRule({ ...valid, publicReplyEnabled: true, publicReplyTexts: [' Sent you a message ', '', 'Sent you a message', 'Check your inbox'] });+ assert.deepEqual([both.privateReplyEnabled, both.publicReplyEnabled, both.publicReplyTexts], [true, true, ['Sent you a message', 'Check your inbox']]);+ const publicOnly = parseAutomationRule({ ...valid, replyText: undefined, privateReplyEnabled: false, publicReplyEnabled: true, publicReplyTexts: ['Thanks'] });+ assert.deepEqual([publicOnly.privateReplyEnabled, publicOnly.replyText], [false, '']);+ assert.throws(() => parseAutomationRule({ ...valid, privateReplyEnabled: false }), /private reply, the public reply, or both/);+ assert.throws(() => parseAutomationRule({ ...valid, replyText: '' }), /Write the reply to send/);+ assert.throws(() => parseAutomationRule({ ...valid, publicReplyEnabled: true }), /at least one public reply/);+ assert.throws(() => parseAutomationRule({ ...valid, privateReplyEnabled: false, publicReplyEnabled: true, publicReplyTexts: ['x'], requireFollow: true, followPromptText: 'f', notFollowingText: 'n' }), /needs the private reply/);+});++test('public replies stay short, with few hashtags and links, and at most five of them', () => {+ const rule = (texts: string[]) => parseAutomationRule({ ...valid, publicReplyEnabled: true, publicReplyTexts: texts });+ assert.throws(() => rule(['x'.repeat(301)]), /at most 300 characters/);+ assert.throws(() => rule(['#a #b #c #d #e']), /at most 4 hashtags/);+ assert.throws(() => rule(['https://a.example and https://b.example']), /at most 1 link/);+ assert.throws(() => rule(['1', '2', '3', '4', '5', '6']), /at most 5 public replies/);+ assert.deepEqual(rule(['#a #b #c #d https://a.example']).publicReplyTexts, ['#a #b #c #d https://a.example']);+ assert.throws(() => parseAutomationRule({ ...valid, publicReplyTexts: 'one' }), /publicReplyTexts must be a list of texts/);+});++test('an update may turn either reply on or off; the rule as a whole is checked by the service', () => {+ assert.deepEqual(parseAutomationRuleUpdate({ privateReplyEnabled: false, replyText: '', publicReplyEnabled: true, publicReplyTexts: ['Thanks'] }), {+ privateReplyEnabled: false, replyText: '', publicReplyEnabled: true, publicReplyTexts: ['Thanks'],+ });+});+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, []);diff --git a/backend/types/env.ts b/backend/types/env.tsindex 35be62e..dd696e9 100644--- a/backend/types/env.ts+++ b/backend/types/env.ts@@ -32,6 +32,8 @@ export interface Env {AUTOMATION_USER_HOURLY_LIMIT?: string;AUTOMATION_GLOBAL_HOURLY_LIMIT?: string;AUTOMATION_RECIPIENT_DAILY_LIMIT?: string;+ // public replies under comments per hour and account, 60 when missing, at most 200+ AUTOMATION_PUBLIC_ACCOUNT_HOURLY_LIMIT?: string;// replies sent by one webhook request or one sweepAUTOMATION_BATCH_SIZE?: string;}diff --git a/backend/validators/automationValidators.ts b/backend/validators/automationValidators.tsindex de534d2..4c4105d 100644--- a/backend/validators/automationValidators.ts+++ b/backend/validators/automationValidators.ts@@ -1,5 +1,6 @@import { ValidationError } from '../lib/errors.ts';-import { followTextsProblem, keywordsProblem } from '../lib/automationRules.ts';+import { followTextsProblem, keywordsProblem, replyActionsProblem } from '../lib/automationRules.ts';+import { MAX_PUBLIC_REPLY_TEXTS, publicReplyTextProblem } from '../lib/automationPublicReply.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';@@ -104,12 +105,26 @@ function mediaIds(body: Fields): string[] | undefined {return ids;}+// may be empty when the rule has no private reply; whether it is needed is checked with replyActionsProblemfunction replyText(body: Fields): string {- const value = requiredString(body, 'replyText', 'Write the reply to send');+ const value = optionalString(body, 'replyText') ?? '';if (value.length > MAX_REPLY) throw new ValidationError(`The reply can be at most ${MAX_REPLY} characters`);return value;}+// trimmed, without blanks or repeats; each text must be one Instagram takes as a comment+function publicReplyTexts(body: Fields): string[] | undefined {+ const list = optionalArray(body, 'publicReplyTexts', isString, 'texts');+ if (!list) return undefined;+ const texts = [...new Set(list.map(item => item.trim()).filter(Boolean))];+ if (texts.length > MAX_PUBLIC_REPLY_TEXTS) throw new ValidationError(`A rule can have at most ${MAX_PUBLIC_REPLY_TEXTS} public replies`);+ for (const text of texts) {+ const problem = publicReplyTextProblem(text);+ if (problem) throw new ValidationError(problem);+ }+ return texts;+}+// only https links without a user name or password, since the link goes to strangers in a private messagefunction linkUrl(body: Fields): string | null | undefined {if (!presentField(body, 'linkUrl')) return undefined;@@ -174,15 +189,18 @@ export function parseAutomationRule(body: Fields): AutomationRuleRequest {matchMode: mode,caseSensitive,mediaIds: mediaIds(body) ?? [],+ privateReplyEnabled: optionalBoolean(body, 'privateReplyEnabled') ?? true,replyText: replyText(body),linkUrl: linkUrl(body) ?? null,+ publicReplyEnabled: optionalBoolean(body, 'publicReplyEnabled') ?? false,+ publicReplyTexts: publicReplyTexts(body) ?? [],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);+ const problem = replyActionsProblem(rule) ?? followTextsProblem(rule);if (problem) throw new ValidationError(problem);return rule;}@@ -197,8 +215,11 @@ export function parseAutomationRuleUpdate(body: Fields): AutomationRuleUpdateReqif (presentField(body, 'matchMode')) changes.matchMode = matchMode(body);if (caseSensitive !== undefined) changes.caseSensitive = caseSensitive;if (presentField(body, 'mediaIds')) changes.mediaIds = mediaIds(body);+ if (presentField(body, 'privateReplyEnabled')) changes.privateReplyEnabled = optionalBoolean(body, 'privateReplyEnabled');if (presentField(body, 'replyText')) changes.replyText = replyText(body);if (presentField(body, 'linkUrl')) changes.linkUrl = linkUrl(body);+ if (presentField(body, 'publicReplyEnabled')) changes.publicReplyEnabled = optionalBoolean(body, 'publicReplyEnabled');+ if (presentField(body, 'publicReplyTexts')) changes.publicReplyTexts = publicReplyTexts(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');@@ -213,12 +234,16 @@ export function parseAutomationTest(body: Fields): AutomationTestRequest {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';+ const privateReplyEnabled = optionalBoolean(body, 'privateReplyEnabled') ?? true;+ const text = replyText(body);+ if (privateReplyEnabled && !text) throw new ValidationError('Write the reply to send');return {keywords: keywordsFor(mode, keywords(body, caseSensitive)),matchMode: mode,caseSensitive,mediaIds: mediaIds(body) ?? [],- replyText: replyText(body),+ privateReplyEnabled,+ replyText: text,linkUrl: linkUrl(body) ?? null,requireFollow: optionalBoolean(body, 'requireFollow') ?? false,followPromptText: followText(body, 'followPromptText', FOLLOW_PROMPT_LABEL) ?? null,diff --git a/shared/types/automation.ts b/shared/types/automation.tsindex b1f207d..183b9b2 100644--- a/shared/types/automation.ts+++ b/shared/types/automation.ts@@ -19,6 +19,9 @@ export type AutomationFollowupKind = 'link' | 'reminder';// a follow-up message moves through the same states as a reply, except ignoredexport type AutomationFollowupStatus = Exclude<AutomationCommentStatus, 'ignored'>;+// a public reply under the comment moves through the same states, apart from the private reply+export type AutomationPublicReplyStatus = Exclude<AutomationCommentStatus, 'ignored'>;+export interface AutomationRule {id: string;accountId: string;@@ -28,10 +31,15 @@ export interface AutomationRule {caseSensitive: boolean;// empty means every post and reel of the accountmediaIds: string[];+ // the private reply; empty when the rule only replies publicly+ privateReplyEnabled: boolean;replyText: string;linkUrl: string | null;+ // a public reply under the comment, one of these texts picked per comment+ publicReplyEnabled: boolean;+ publicReplyTexts: string[];enabled: boolean;- // null uses only the account's limit+ // null uses only the account's limit; it counts private replieshourlyLimit: number | null;// the private reply asks the person to follow and answer; the reply and link go out once Instagram says they followrequireFollow: boolean;@@ -49,8 +57,12 @@ export interface AutomationRuleRequest {matchMode?: AutomationMatchMode;caseSensitive?: boolean;mediaIds?: string[];+ privateReplyEnabled?: boolean;+ // may be empty when privateReplyEnabled is falsereplyText: string;linkUrl?: string | null;+ publicReplyEnabled?: boolean;+ publicReplyTexts?: string[];enabled?: boolean;hourlyLimit?: number | null;requireFollow?: boolean;@@ -75,6 +87,10 @@ export interface AutomationAccountState {limitedUntil: string | null;// Instagram also sends this account's messages, which followers-only rules needmessagesSubscribed: boolean;+ // public replies cool down and fill up apart from private replies+ publicCooldownUntil: string | null;+ publicCooldownReason: string | null;+ publicLimitedUntil: string | null;}export interface AutomationLimits {@@ -82,6 +98,8 @@ export interface AutomationLimits {userHourly: number;globalHourly: number;recipientDaily: number;+ // public replies an hour per account; Instagram publishes no number for them, so Twiligent keeps a human pace+ publicAccountHourly: number;}export interface AutomationSettings {@@ -111,6 +129,20 @@ export interface AutomationActivityItem {// followers-only rules: where the wait for the person's answer stands, and the latest message sent after itgateStatus: AutomationGateStatus | null;followup: AutomationFollowupState | null;+ // the public reply under the comment, when the rule asked for one+ publicReply: AutomationPublicReplyState | null;+}++export interface AutomationPublicReplyState {+ status: AutomationPublicReplyStatus;+ statusReason: string | null;+ errorMessage: string | null;+ text: string;+ attempts: number;+ // the id Instagram gave the reply, once it is known to be there+ replyId: string | null;+ nextAttemptAt: string | null;+ acceptedAt: string | null;}export interface AutomationFollowupState {@@ -122,6 +154,7 @@ export interface AutomationFollowupState {export interface AutomationStats {comments: Partial<Record<AutomationCommentStatus, number>>;+ publicReplies: Partial<Record<AutomationPublicReplyStatus, number>>;attempts: Partial<Record<AutomationAttemptOutcome, number>>;}@@ -145,6 +178,7 @@ export interface AutomationTestRequest {matchMode?: AutomationMatchMode;caseSensitive?: boolean;mediaIds?: string[];+ privateReplyEnabled?: boolean;replyText: string;linkUrl?: string | null;requireFollow?: boolean;@@ -171,7 +205,8 @@ export interface AutomationActivityResponse {nextBefore: string | null;}-// POST /api/automations/activity/:id/retry+// POST /api/automations/activity/:id/retry (the private reply or its follow-up) and+// POST /api/automations/activity/:id/public-reply/retry (the public reply alone)export interface AutomationActivityItemResponse {success: true;item: AutomationActivityItem;