Skip to content

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

fix(automation): keep runs inside their budgets and page activity safely

spacesdrivee72ce5d88258
diff --git a/backend/controllers/automationController.ts b/backend/controllers/automationController.ts
index 53ac872..aac09e3 100644
--- a/backend/controllers/automationController.ts
+++ b/backend/controllers/automationController.ts
@@ -3,6 +3,7 @@ import { jsonBody, queryParams } from '../middleware/validate.ts';
import {
parseActivityQuery, parseAutomationAccount, parseAutomationRule, parseAutomationRuleUpdate, parseAutomationTest, parseStatsQuery,
} from '../validators/automationValidators.ts';
+import { FREE_PLAN_SUBREQUESTS, REQUEST_SUBREQUESTS } from '../lib/automationDelivery.ts';
import type { SuccessMessageResponse } from '../../shared/types/domain.ts';
import type {
AutomationAccountResponse, AutomationActivityItemResponse, AutomationActivityResponse, AutomationOverviewResponse,
@@ -53,7 +54,7 @@ export const getAutomationStats = controller.createHandlers(queryParams(parseSta
// the item goes back in the queue and this request starts sending it, instead of waiting for the next sweep
export const retryAutomationActivity = controller.createHandlers(async c => {
const item = await servicesFor(c).automations.retry(c.get('userId'), pathParam(c, 'id'));
- inBackground(c, 'automation retry', services => services.automationProcessor.run({ ids: [item.id] }));
+ inBackground(c, 'automation retry', services => services.automationProcessor.run({ ids: [item.id], subrequests: FREE_PLAN_SUBREQUESTS - REQUEST_SUBREQUESTS }));
return c.json({ success: true, item } satisfies AutomationActivityItemResponse);
});
diff --git a/backend/controllers/instagramWebhookController.ts b/backend/controllers/instagramWebhookController.ts
index 2da4640..3fd9ca9 100644
--- a/backend/controllers/instagramWebhookController.ts
+++ b/backend/controllers/instagramWebhookController.ts
@@ -2,6 +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';
// called by Meta when the webhook is saved in its dashboard; the answer is the bare challenge, not JSON
export const verifyInstagramWebhook = controller.createHandlers(queryParams(parseWebhookVerification), async c => {
@@ -12,7 +13,9 @@ export const verifyInstagramWebhook = controller.createHandlers(queryParams(pars
// called by Meta, not a browser: verifyMetaWebhook has already checked the signature. The comments are stored before
// the 200, so Meta keeps retrying for 36 hours if storing fails; the replies go out after the response
export const receiveInstagramWebhook = controller.createHandlers(jsonBody(body => parseInstagramWebhook(body)), async c => {
- const { queuedIds } = await servicesFor(c).automationWebhook.ingest(c.req.valid('json'));
- if (queuedIds.length > 0) inBackground(c, 'automation replies', services => services.automationProcessor.run({ ids: queuedIds }));
+ const { queuedIds, subrequests } = await servicesFor(c).automationWebhook.ingest(c.req.valid('json'));
+ // the replies share this invocation's subrequests with the intake and the middleware before it
+ const left = FREE_PLAN_SUBREQUESTS - REQUEST_SUBREQUESTS - subrequests;
+ if (queuedIds.length > 0) inBackground(c, 'automation replies', services => services.automationProcessor.run({ ids: queuedIds, subrequests: left }));
return c.json({ success: true });
});
diff --git a/backend/jobs/scheduled.ts b/backend/jobs/scheduled.ts
index 07e8505..e84ea33 100644
--- a/backend/jobs/scheduled.ts
+++ b/backend/jobs/scheduled.ts
@@ -2,6 +2,7 @@ import { createServices } from '../container.ts';
import { getSupabase } from '../database/supabase.ts';
import { getRedis, getRateLimitRedis } from '../database/redis.ts';
import { readConfig } from '../lib/config.ts';
+import { FREE_PLAN_SUBREQUESTS } from '../lib/automationDelivery.ts';
import { createLogger } from '../lib/logger.ts';
import type { Services } from '../container.ts';
import type { Env } from '../types/env.ts';
@@ -14,8 +15,12 @@ export const DAILY_CRON = '0 0 * * *';
// the Cloudflare account's five cron triggers are all in use, so one trigger carries two jobs: due posts on the
// quarter hour, as before, and the comment reply queue on every run
const PUBLISH_EVERY_MINUTES = 15;
-// a run that published has spent part of its 50 subrequests, so the replies wait five minutes for the next run
+// a run that published has spent part of its 50 subrequests, so the replies wait five minutes for the next run;
+// one that had nothing to publish spent two (the due and stale lists) and sweeps a few
const SWEEP_AFTER_QUIET_PUBLISH = 3;
+const QUIET_PUBLISH_SUBREQUESTS = 2;
+// a sweep stops starting sends well before the 14 minute cron deadline
+const SWEEP_TIME_MS = 10 * 60 * 1000;
// a cron run gets its own id and a deadline under the Worker's 15 minute limit for scheduled events
const CRON_DEADLINE_MS = 14 * 60 * 1000;
@@ -34,8 +39,8 @@ export function cronPlan(cron: string, scheduledTime: number): CronPlan {
return new Date(scheduledTime).getUTCMinutes() % PUBLISH_EVERY_MINUTES === 0 ? 'publish_then_sweep' : 'sweep';
}
-async function sweepReplies(services: Services, context: RequestContext, limit?: number): Promise<void> {
- const run = await services.automationProcessor.run({ limit });
+async function sweepReplies(services: Services, context: RequestContext, limit?: number, spent = 0): Promise<void> {
+ const run = await services.automationProcessor.run({ limit, subrequests: FREE_PLAN_SUBREQUESTS - spent, timeBudgetMs: SWEEP_TIME_MS });
if (run.claimed > 0) context.log.info('automation sweep', { claimed: run.claimed, ...run.outcomes });
}
@@ -51,7 +56,7 @@ export async function runScheduledJob(cron: string, env: Env, scheduledTime = Da
} else if (plan === 'publish_then_sweep') {
const run = await services.scheduledPublisher.publishDue();
context.log.info('scheduled publish run', { processed: run.processed, failed: run.errors.length });
- if (run.processed === 0) await sweepReplies(services, context, SWEEP_AFTER_QUIET_PUBLISH);
+ if (run.processed === 0) await sweepReplies(services, context, SWEEP_AFTER_QUIET_PUBLISH, QUIET_PUBLISH_SUBREQUESTS);
} else if (plan === 'daily') {
await services.tokenRefresh.refreshExpiringInstagramTokens();
await services.retention.purge();
diff --git a/backend/lib/automationDelivery.ts b/backend/lib/automationDelivery.ts
index 1454430..c6eef73 100644
--- a/backend/lib/automationDelivery.ts
+++ b/backend/lib/automationDelivery.ts
@@ -12,6 +12,21 @@ export const CLAIM_LEASE_SECONDS = 20 * 60;
// five tries over about half an hour give a passing Instagram problem time to clear without retrying forever
export const MAX_SEND_ATTEMPTS = 5;
+// a webhook's background work has 30 seconds in all, so one send may take a third of it
+export const SEND_TIMEOUT_MS = 10_000;
+
+// the Workers Free plan allows 50 subrequests per invocation; a run that hits the cap cannot even record what happened
+export const FREE_PLAN_SUBREQUESTS = 50;
+// a request's own middleware and queries (authentication, rate limits, its writes) stay under this before background work starts
+export const REQUEST_SUBREQUESTS = 10;
+// reserve, send and finish; a reply stopped before sending costs one release instead
+export const SUBREQUESTS_PER_REPLY = 3;
+// background work after a response gets 25 seconds; a send starts only with its whole timeout and a margin left
+export const BACKGROUND_RUN_MS = 20_000;
+
+// new and retried jobs are due a little in the past, so a database clock slightly behind the Worker's still sees them as due
+export const DUE_NOW_SKEW_MS = 30_000;
+
// 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;
diff --git a/backend/repositories/automationCommentRepository.ts b/backend/repositories/automationCommentRepository.ts
index 56dd23a..341d69d 100644
--- a/backend/repositories/automationCommentRepository.ts
+++ b/backend/repositories/automationCommentRepository.ts
@@ -1,4 +1,5 @@
import { execute, maybeRow, rows } from './query.ts';
+import { DUE_NOW_SKEW_MS } from '../lib/automationDelivery.ts';
import type { FinishPlan, ReleasePlan, ReserveOutcome } from '../lib/automationDelivery.ts';
import type { SupabaseClient } from '../types/app.ts';
import type { AutomationActivityItem, AutomationCommentStatus, AutomationLimits, AutomationStats } from '../../shared/types/automation.ts';
@@ -86,14 +87,19 @@ export interface Reservation {
retryAt: string | null;
}
+// where the previous page ended; rows stored together share created_at, so the id breaks the tie
+export interface ActivityCursor {
+ createdAt: string;
+ id: string;
+}
+
export interface ActivityFilter {
accountId?: string;
ruleId?: string;
statuses?: AutomationCommentStatus[];
from?: string;
to?: string;
- // created_at of the last item on the previous page
- before?: string;
+ before?: ActivityCursor;
limit: number;
}
@@ -155,6 +161,7 @@ export interface AutomationCommentRepository {
reserve(id: string, attemptId: string, limits: AutomationLimits): Promise<Reservation>;
finish(id: string, attemptId: string, plan: FinishPlan): Promise<boolean>;
release(id: string, plan: ReleasePlan): Promise<boolean>;
+ returnUnstarted(ids: string[]): Promise<void>;
listForUser(userId: string, filter: ActivityFilter): Promise<AutomationActivityItem[]>;
findForUser(id: string, userId: string): Promise<AutomationActivityItem | null>;
requeueForUser(id: string, userId: string): Promise<AutomationActivityItem | null>;
@@ -252,7 +259,16 @@ export function createAutomationCommentRepository(db: SupabaseClient): Automatio
return released.length > 0;
},
- // newest first; a full page may have more after it, and the next page asks for rows before the last one's time
+ // a run that stops early gives back the jobs it claimed but never started, due again at once
+ async returnUnstarted(ids) {
+ await execute('automationComments.returnUnstarted', () => db
+ .from('automation_comments')
+ .update({ status: 'queued', claimed_at: null, next_attempt_at: new Date(Date.now() - DUE_NOW_SKEW_MS).toISOString() })
+ .in('id', ids)
+ .eq('status', 'processing'));
+ },
+
+ // newest first, then by id; a full page may have more after it, and the next one starts after its last row
async listForUser(userId, { accountId, ruleId, statuses, from, to, before, limit }) {
const found = await rows<AutomationCommentRow>('automationComments.listForUser', () => {
let query = db.from('automation_comments').select(COLUMNS).eq('user_id', userId);
@@ -261,8 +277,8 @@ export function createAutomationCommentRepository(db: SupabaseClient): Automatio
if (statuses?.length) query = query.in('status', statuses);
if (from) query = query.gte('created_at', from);
if (to) query = query.lt('created_at', to);
- if (before) query = query.lt('created_at', before);
- return query.order('created_at', { ascending: false }).limit(limit);
+ if (before) query = query.or(`created_at.lt."${before.createdAt}",and(created_at.eq."${before.createdAt}",id.lt."${before.id}")`);
+ return query.order('created_at', { ascending: false }).order('id', { ascending: false }).limit(limit);
});
return found.map(toItem);
},
@@ -280,9 +296,10 @@ export function createAutomationCommentRepository(db: SupabaseClient): Automatio
// checked in the update itself, so a job a sweep picked up in between is never sent twice
async requeueForUser(id, userId) {
const now = new Date().toISOString();
+ const due = new Date(Date.now() - DUE_NOW_SKEW_MS).toISOString();
const requeued = await rows<AutomationCommentRow>('automationComments.requeue', () => db
.from('automation_comments')
- .update({ status: 'queued', status_reason: 'retry', error_message: null, next_attempt_at: now, claimed_at: null })
+ .update({ status: 'queued', status_reason: 'retry', error_message: null, next_attempt_at: due, claimed_at: null })
.eq('id', id)
.eq('user_id', userId)
.in('status', RETRYABLE)
diff --git a/backend/services/automationProcessor.ts b/backend/services/automationProcessor.ts
index ca87714..6f23d39 100644
--- a/backend/services/automationProcessor.ts
+++ b/backend/services/automationProcessor.ts
@@ -1,5 +1,8 @@
import { sendPrivateReply } from './instagram/instagramMessaging.ts';
-import { CLAIM_LEASE_SECONDS, composeReply, finishPlan, readinessPlan, releasePlan } from '../lib/automationDelivery.ts';
+import {
+ BACKGROUND_RUN_MS, CLAIM_LEASE_SECONDS, FREE_PLAN_SUBREQUESTS, SEND_TIMEOUT_MS, SUBREQUESTS_PER_REPLY,
+ composeReply, finishPlan, readinessPlan, releasePlan,
+} from '../lib/automationDelivery.ts';
import { newRowId } from '../lib/ids.ts';
import { errorFields } from '../lib/logger.ts';
import type { AutomationCommentRepository, ClaimedComment } from '../repositories/automationCommentRepository.ts';
@@ -16,20 +19,28 @@ export interface AutomationProcessorDeps {
export interface ProcessOptions {
// only these comments, as a webhook just stored them; otherwise whatever is due
ids?: string[];
- // fewer than the configured batch, when a run has already spent part of its subrequests
+ // fewer than the configured batch
limit?: number;
+ // 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 ProcessRun {
claimed: number;
- // the status each claimed job ended in this run; gone means another run settled it first
- outcomes: Partial<Record<AutomationCommentStatus | 'gone' | 'error', number>>;
+ // the status each claimed job ended in this run; gone means another run settled it first, returned that it was
+ // handed back unstarted because the run ran out of time or subrequests
+ outcomes: Partial<Record<AutomationCommentStatus | 'gone' | 'returned' | 'error', number>>;
}
export interface AutomationProcessor {
run(options?: ProcessOptions): Promise<ProcessRun>;
}
+// a send needs its whole timeout plus a moment to record the answer
+const SEND_MARGIN_MS = 2_000;
+
// sends the private replies that are due, one at a time so each account's replies keep their order and the
// Worker's six open connections are never exceeded; every job is settled in the database before the next starts
export function createAutomationProcessor({ comments, automation, context }: AutomationProcessorDeps): AutomationProcessor {
@@ -53,7 +64,7 @@ export function createAutomationProcessor({ comments, automation, context }: Aut
}
// readinessPlan checked that the rule is on and the token is there
- const result = await sendPrivateReply(job.igUserId, job.accessToken!, job.commentId, composeReply(job.replyText!, job.linkUrl), signal);
+ const result = await sendPrivateReply(job.igUserId, job.accessToken!, job.commentId, composeReply(job.replyText!, job.linkUrl));
const plan = finishPlan(result, { attempts: job.attempts + 1, expiresAt: job.expiresAt }, Date.now());
await comments.finish(job.id, attemptId, plan);
log.info('automation reply settled', {
@@ -68,21 +79,42 @@ export function createAutomationProcessor({ comments, automation, context }: Aut
return plan.status;
}
+ // one update for every job the run will not start, so they are due again at once instead of after the lease
+ async function handBack(jobs: ClaimedComment[], outcomes: ProcessRun['outcomes']): Promise<void> {
+ if (jobs.length === 0) return;
+ try {
+ await comments.returnUnstarted(jobs.map(job => job.id));
+ outcomes.returned = jobs.length;
+ } catch (err) {
+ log.error('automation jobs not handed back', { count: jobs.length, ...errorFields(err) });
+ }
+ }
+
return {
- async run({ ids, limit } = {}) {
+ async run({ ids, limit, subrequests = FREE_PLAN_SUBREQUESTS, timeBudgetMs = BACKGROUND_RUN_MS } = {}) {
const outcomes: ProcessRun['outcomes'] = {};
if (automation.paused) {
log.info('automation paused on this instance; nothing sent');
return { claimed: 0, outcomes };
}
- const batch = Math.max(1, Math.min(limit ?? automation.batchSize, automation.batchSize));
+ const started = Date.now();
+ // the claim and one hand-back come first, then each reply needs its three calls
+ const affordable = Math.floor((subrequests - 2) / SUBREQUESTS_PER_REPLY);
+ const batch = Math.min(limit ?? automation.batchSize, automation.batchSize, affordable);
+ if (batch < 1) {
+ log.warn('automation run skipped: no subrequests left', { subrequests });
+ return { claimed: 0, outcomes };
+ }
// a sweep shares its batch between accounts; a webhook's own comments are all from the accounts it named
const perAccount = ids ? batch : Math.max(1, Math.ceil(batch / 2));
const jobs = await comments.claim({ limit: batch, perAccount, leaseSeconds: CLAIM_LEASE_SECONDS, ids });
- for (const job of jobs) {
- // a job left claimed is picked up again after its lease, so stopping early loses nothing
- if (signal.aborted) break;
+ for (const [index, job] of jobs.entries()) {
+ const timeLeft = timeBudgetMs - (Date.now() - started);
+ if (signal.aborted || timeLeft < SEND_TIMEOUT_MS + SEND_MARGIN_MS) {
+ await handBack(jobs.slice(index), outcomes);
+ break;
+ }
try {
const status = await settle(job);
outcomes[status] = (outcomes[status] ?? 0) + 1;
diff --git a/backend/services/automationService.ts b/backend/services/automationService.ts
index 5d5a424..436962f 100644
--- a/backend/services/automationService.ts
+++ b/backend/services/automationService.ts
@@ -228,7 +228,8 @@ export function createAutomationService(deps: AutomationServiceDeps): Automation
async activity(userId, query) {
const items = await comments.listForUser(userId, query);
- return { items, nextBefore: items.length === query.limit ? items[items.length - 1].createdAt : null };
+ const last = items[items.length - 1];
+ return { items, nextBefore: items.length === query.limit ? `${last.createdAt}|${last.id}` : null };
},
async stats(userId, query) {
diff --git a/backend/services/automationWebhookService.ts b/backend/services/automationWebhookService.ts
index ac1cde7..97ca962 100644
--- a/backend/services/automationWebhookService.ts
+++ b/backend/services/automationWebhookService.ts
@@ -1,5 +1,5 @@
import { pickRule } from '../lib/automationMatching.ts';
-import { expiresAtFor } from '../lib/automationDelivery.ts';
+import { DUE_NOW_SKEW_MS, expiresAtFor } from '../lib/automationDelivery.ts';
import { ForbiddenError, NotConfiguredError } from '../lib/errors.ts';
import { newRowId } from '../lib/ids.ts';
import { verifyTokenMatches } from '../lib/metaWebhookSignature.ts';
@@ -22,6 +22,8 @@ export interface IngestResult {
duplicates: number;
// the new comments that matched a rule, for the request to start sending right away
queuedIds: string[];
+ // database calls the intake made, which count against the request's subrequests
+ subrequests: number;
}
export interface AutomationWebhookService {
@@ -45,7 +47,7 @@ function newComment(event: InstagramCommentEvent, owner: WebhookRule, fields: Pi
// 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,
- nextAttemptAt: queued ? new Date().toISOString() : 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)),
...fields,
@@ -81,8 +83,10 @@ export function createAutomationWebhookService({ rules, comments, automation, co
for (const event of webhook.comments) byAccount.set(event.igUserId, [...(byAccount.get(event.igUserId) ?? []), event]);
const rows: NewAutomationComment[] = [];
+ let subrequests = 0;
for (const [igUserId, events] of byAccount) {
const accountRules = await rules.listEnabledForInstagramUser(igUserId);
+ subrequests++;
if (accountRules.length === 0) continue;
// one notification can repeat a comment; the first copy is the one kept
const seen = new Set<string>();
@@ -95,7 +99,8 @@ export function createAutomationWebhookService({ rules, comments, automation, co
const inserted = await comments.insertMany(rows);
const queuedIds = inserted.filter(row => row.status === 'queued').map(row => row.id);
- const result = { stored: inserted.length, duplicates: rows.length - inserted.length, queuedIds };
+ if (rows.length > 0) subrequests++;
+ const result = { stored: inserted.length, duplicates: rows.length - inserted.length, queuedIds, subrequests };
context.log.info('instagram webhook stored', {
comments: webhook.comments.length,
unsupported: webhook.unsupported,
diff --git a/backend/services/instagram/instagramMessaging.ts b/backend/services/instagram/instagramMessaging.ts
index 970bef9..a502a40 100644
--- a/backend/services/instagram/instagramMessaging.ts
+++ b/backend/services/instagram/instagramMessaging.ts
@@ -1,11 +1,10 @@
import { buildGraphUrl, igPost } from './instagramApi.ts';
import { UpstreamError, isAbortError } from '../../lib/errors.ts';
import { redactUrls } from '../../lib/redact.ts';
+import { SEND_TIMEOUT_MS } from '../../lib/automationDelivery.ts';
import type { SendResult } from '../../lib/automationDelivery.ts';
import type { InstagramApiErrorBody } from './instagramApi.ts';
-// a webhook's background work has 30 seconds in all, so one send may take a third of it
-const SEND_TIMEOUT_MS = 10_000;
// the Workers runtime refuses a fetch past the run's subrequest allowance before anything leaves
const SUBREQUEST_LIMIT = /too many subrequests/i;
// the webhook fields the automation needs; Instagram sends every field the app subscribes to in the Meta dashboard
@@ -21,16 +20,16 @@ interface SubscribeBody {
}
// 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
-export async function sendPrivateReply(igUserId: string, accessToken: string, commentId: string, text: string, signal?: AbortSignal): Promise<SendResult> {
- const timeout = AbortSignal.timeout(SEND_TIMEOUT_MS);
+// the request is never repeated here, since a repeat after a lost answer could message the person twice. Only its own
+// timeout can cut it off: the caller starts a send only with that much time left, so a run's deadline never makes one ambiguous
+export async function sendPrivateReply(igUserId: string, accessToken: string, commentId: string, text: string): Promise<SendResult> {
let response: Response;
try {
response = await fetch(buildGraphUrl(`/${igUserId}/messages`).toString(), {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${accessToken}` },
body: JSON.stringify({ recipient: { comment_id: commentId }, message: { text } }),
- signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
+ signal: AbortSignal.timeout(SEND_TIMEOUT_MS),
});
} catch (err) {
if (SUBREQUEST_LIMIT.test((err as Error).message ?? '')) return { kind: 'not_sent', message: 'this run reached its request limit' };
diff --git a/backend/tests/fixtures/fakeAutomationQueue.ts b/backend/tests/fixtures/fakeAutomationQueue.ts
index 307448d..8e61554 100644
--- a/backend/tests/fixtures/fakeAutomationQueue.ts
+++ b/backend/tests/fixtures/fakeAutomationQueue.ts
@@ -194,6 +194,12 @@ export function fakeAutomationQueue(rows: QueueRow[] = []): FakeQueue {
return true;
},
+ async returnUnstarted(ids) {
+ for (const row of rows) {
+ if (ids.includes(row.id) && row.status === 'processing') Object.assign(row, { status: 'queued', claimedAt: null, nextAttemptAt: iso(now() - 30_000) });
+ }
+ },
+
async listForUser() { return []; },
async findForUser() { return null; },
async requeueForUser() { return null; },
diff --git a/backend/tests/fixtures/fakeSupabase.ts b/backend/tests/fixtures/fakeSupabase.ts
index 236bcd9..61c9550 100644
--- a/backend/tests/fixtures/fakeSupabase.ts
+++ b/backend/tests/fixtures/fakeSupabase.ts
@@ -3,7 +3,7 @@ import type { SupabaseClient } from '../../types/app.ts';
export type Row = Record<string, unknown>;
-type Filter = [column: string, value: unknown, operator?: 'lte' | 'lt' | 'neq' | 'gte' | 'gt' | 'in'];
+type Filter = [column: string, value: unknown, operator?: 'lte' | 'lt' | 'neq' | 'gte' | 'gt' | 'in' | 'or'];
interface Action {
type: 'select' | 'update' | 'insert' | 'upsert' | 'delete' | 'rpc';
@@ -30,6 +30,7 @@ interface FakeQuery {
gte(column: string, value: unknown): FakeQuery;
gt(column: string, value: unknown): FakeQuery;
in(column: string, values: unknown[]): FakeQuery;
+ or(expression: string): FakeQuery;
order(): FakeQuery;
limit(count: number): FakeQuery;
single(): Promise<QueryResult>;
@@ -49,13 +50,45 @@ function copy<T>(value: T): T {
return value === undefined ? undefined as T : structuredClone(value);
}
-function matchesFilter(row: Row, [column, value, operator]: Filter) {
+// splits a PostgREST or() list at the commas outside quotes and parentheses
+function splitTopLevel(expression: string): string[] {
+ const parts: string[] = [];
+ let depth = 0;
+ let quoted = false;
+ let current = '';
+ for (const char of expression) {
+ if (char === '"') quoted = !quoted;
+ if (!quoted && char === '(') depth++;
+ if (!quoted && char === ')') depth--;
+ if (!quoted && depth === 0 && char === ',') {
+ parts.push(current);
+ current = '';
+ } else {
+ current += char;
+ }
+ }
+ return [...parts, current];
+}
+
+// the forms the repositories use: column.op."value" and and(...), any of them true
+function matchesOr(row: Row, expression: string): boolean {
+ return splitTopLevel(expression).some(part => {
+ if (part.startsWith('and(')) return splitTopLevel(part.slice(4, -1)).every(inner => matchesOr(row, inner));
+ const [, column, operator, raw] = /^(\w+)\.(eq|neq|lt|lte|gt|gte)\.(.*)$/.exec(part) ?? [];
+ if (!column) throw new Error(`fakeSupabase cannot read or() part ${part}`);
+ const value = raw.replace(/^"|"$/g, '');
+ return matchesFilter(row, [column, value, operator === 'eq' ? undefined : operator as Filter[2]]);
+ });
+}
+
+function matchesFilter(row: Row, [column, value, operator]: Filter): boolean {
if (operator === 'lte') return (row[column] as string) <= (value as string);
if (operator === 'lt') return row[column] != null && (row[column] as string) < (value as string);
if (operator === 'neq') return row[column] !== value;
if (operator === 'gte') return row[column] != null && (row[column] as string) >= (value as string);
if (operator === 'gt') return row[column] != null && (row[column] as string) > (value as string);
if (operator === 'in') return (value as unknown[]).includes(row[column]);
+ if (operator === 'or') return matchesOr(row, value as string);
return row[column] === value;
}
@@ -130,6 +163,10 @@ function queryBuilder(action: Action, run: Run): FakeQuery {
filters.push([column, values, 'in']);
return query;
},
+ or(expression: string) {
+ filters.push(['', expression, 'or']);
+ return query;
+ },
// rows come back in the order they were stored; tests that page seed rows newest first
order() { return query; },
limit(count: number) {
diff --git a/backend/tests/repositories/automationCommentRepository.test.ts b/backend/tests/repositories/automationCommentRepository.test.ts
index 3b97b6a..94e210e 100644
--- a/backend/tests/repositories/automationCommentRepository.test.ts
+++ b/backend/tests/repositories/automationCommentRepository.test.ts
@@ -92,12 +92,44 @@ describe('automation comment repository', () => {
test('activity filters by user first, then by every filter given', async () => {
const supabase = fakeSupabase([]);
- await createAutomationCommentRepository(supabase).listForUser('user-1', { accountId: 'ig1', statuses: ['failed', 'needs_review'], before: 'B', from: 'F', limit: 20 });
+ const before = { createdAt: '2026-10-16T10:00:00.123456+00:00', id: 'b' };
+ await createAutomationCommentRepository(supabase).listForUser('user-1', { accountId: 'ig1', statuses: ['failed', 'needs_review'], before, from: 'F', limit: 20 });
assert.deepEqual(supabase.calls[0].filters, [
- ['user_id', 'user-1'], ['account_id', 'ig1'], ['status', ['failed', 'needs_review'], 'in'], ['created_at', 'F', 'gte'], ['created_at', 'B', 'lt'],
+ ['user_id', 'user-1'], ['account_id', 'ig1'], ['status', ['failed', 'needs_review'], 'in'], ['created_at', 'F', 'gte'],
+ ['', 'created_at.lt."2026-10-16T10:00:00.123456+00:00",and(created_at.eq."2026-10-16T10:00:00.123456+00:00",id.lt."b")', 'or'],
]);
});
+ test('paging walks through comments stored in the same instant, without skipping or repeating any', async () => {
+ const same = '2026-10-16T10:00:00.123456+00:00';
+ // stored newest first, as the order by created_at desc, id desc returns them
+ const ids = ['e', 'd', 'c', 'b', 'a'];
+ const supabase = fakeSupabase([
+ ...ids.map(id => tableRow('automation_comments', { id, user_id: 'user-1', created_at: same })),
+ tableRow('automation_comments', { id: 'z', user_id: 'user-1', created_at: '2026-10-16T09:00:00+00:00' }),
+ ]);
+ const repo = createAutomationCommentRepository(supabase);
+ const seen: string[] = [];
+ let before: { createdAt: string; id: string } | undefined;
+ for (let page = 0; page < 4; page++) {
+ const items = await repo.listForUser('user-1', { before, limit: 2 });
+ seen.push(...items.map(item => item.id));
+ if (items.length < 2) break;
+ before = { createdAt: items[1].createdAt, id: items[1].id };
+ }
+ assert.deepEqual(seen, ['e', 'd', 'c', 'b', 'a', 'z']);
+ });
+
+ test('a run gives back only the jobs it still holds, due again at once', async () => {
+ const supabase = fakeSupabase([
+ tableRow('automation_comments', { id: 'held', status: 'processing', claimed_at: 'x' }),
+ tableRow('automation_comments', { id: 'sent', status: 'sending', claimed_at: 'x' }),
+ ]);
+ await createAutomationCommentRepository(supabase).returnUnstarted(['held', 'sent']);
+ assert.deepEqual(supabase.table.map(row => [row.id, row.status, row.claimed_at]), [['held', 'queued', null], ['sent', 'sending', 'x']]);
+ assert.ok(Date.parse(supabase.table[0].next_attempt_at as string) < Date.now());
+ });
+
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: {} });
diff --git a/backend/tests/routes/automationRoutes.test.ts b/backend/tests/routes/automationRoutes.test.ts
index af148b6..0cb0276 100644
--- a/backend/tests/routes/automationRoutes.test.ts
+++ b/backend/tests/routes/automationRoutes.test.ts
@@ -153,7 +153,7 @@ describe('automation routes', () => {
test('activity lists only the user\'s comments, newest page first', async () => {
const { body } = await call(server(), 'GET', '/automations/activity?status=failed,needs_review&limit=1');
assert.deepEqual(body.items.map((item: { id: string }) => item.id), ['failed-mine']);
- assert.equal(body.nextBefore, '2026-10-15T00:00:00Z');
+ assert.equal(body.nextBefore, '2026-10-15T00:00:00Z|failed-mine');
});
test('a failed reply can be retried once inside its 7 days; sent, expired and other users\' items cannot', async () => {
diff --git a/backend/tests/services/automationProcessor.test.ts b/backend/tests/services/automationProcessor.test.ts
index 23216c3..34dfb9b 100644
--- a/backend/tests/services/automationProcessor.test.ts
+++ b/backend/tests/services/automationProcessor.test.ts
@@ -266,13 +266,34 @@ describe('automation processor', () => {
assert.equal(sent.length, 0);
});
- test('a run whose deadline passed stops before the next job, leaving it for later', async () => {
+ test('a run whose deadline passed hands its jobs back unstarted, due again at once', async () => {
instagram();
const queue = fakeAutomationQueue([queueRow('a')]);
const controller = new AbortController();
controller.abort();
const run = await processor(queue, automation(), controller.signal).run();
- assert.equal(run.claimed, 1);
+ assert.deepEqual(run, { claimed: 1, outcomes: { returned: 1 } });
assert.equal(sent.length, 0);
+ assert.equal(statuses(queue).a, 'queued');
+ });
+
+ test('a send starts only with its whole timeout left, so the run deadline never makes one ambiguous', async () => {
+ instagram();
+ const queue = fakeAutomationQueue([queueRow('a'), queueRow('b')]);
+ const run = await processor(queue).run({ timeBudgetMs: 11_000 });
+ assert.deepEqual(run.outcomes, { returned: 2 });
+ assert.equal(sent.length, 0);
+ assert.deepEqual(Object.values(statuses(queue)), ['queued', 'queued']);
+ });
+
+ test('a run claims only as many replies as its subrequests can pay for, and none when they are spent', async () => {
+ instagram();
+ const queue = fakeAutomationQueue(Array.from({ length: 6 }, (_, i) => queueRow(`s${i}`)));
+ // the claim and a hand-back take two, each reply three: 11 subrequests pay for 3 replies
+ const run = await processor(queue).run({ ids: queue.rows.map(row => row.id), subrequests: 11 });
+ assert.equal(run.claimed, 3);
+ assert.equal(sent.length, 3);
+ assert.deepEqual(await processor(queue).run({ subrequests: 4 }), { claimed: 0, outcomes: {} });
+ assert.equal(queue.rows.filter(row => row.status === 'queued').length, 3);
});
});
diff --git a/backend/tests/services/automationWebhookService.test.ts b/backend/tests/services/automationWebhookService.test.ts
index bd0a80d..9cd1e81 100644
--- a/backend/tests/services/automationWebhookService.test.ts
+++ b/backend/tests/services/automationWebhookService.test.ts
@@ -57,6 +57,7 @@ describe('instagram webhook intake', () => {
]));
assert.equal(result.stored, 3);
assert.equal(result.queuedIds.length, 3);
+ assert.equal(result.subrequests, 2);
assert.deepEqual(queue.rows.map(row => [row.commentId, row.ruleId, row.status]), [['1', 'reel-a', 'queued'], ['2', 'reel-b', 'queued'], ['3', 'any', 'queued']]);
assert.equal(inserted[0][0].expiresAt, new Date(SENT_AT * 1000 + 7 * 24 * 60 * 60 * 1000).toISOString());
assert.equal(inserted[0][0].text, 'GUIDE please');
@@ -86,7 +87,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: [] });
+ assert.deepEqual(again, { stored: 0, duplicates: 2, queuedIds: [], subrequests: 2 });
assert.equal(queue.rows.length, 2);
});
@@ -100,7 +101,7 @@ 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: [] });
+ assert.deepEqual(result, { stored: 0, duplicates: 0, queuedIds: [], subrequests: 1 });
assert.deepEqual(inserted, [[]]);
});
diff --git a/backend/tests/validators/automationValidators.test.ts b/backend/tests/validators/automationValidators.test.ts
index 8bd5706..61f78d5 100644
--- a/backend/tests/validators/automationValidators.test.ts
+++ b/backend/tests/validators/automationValidators.test.ts
@@ -69,10 +69,12 @@ test('a test needs a sample comment besides the rule draft', () => {
});
test('activity filters are checked and dates normalised; the page size defaults to 50 and stops at 100', () => {
- assert.deepEqual(parseActivityQuery({ status: 'failed, needs_review,failed', from: '2026-10-01', before: '2026-10-10T00:00:00Z' }), {
+ assert.deepEqual(parseActivityQuery({ status: 'failed, needs_review,failed', from: '2026-10-01', before: '2026-10-10T00:00:00.123456+00:00|abc-1' }), {
accountId: undefined, ruleId: undefined, statuses: ['failed', 'needs_review'], from: '2026-10-01T00:00:00.000Z', to: undefined,
- before: '2026-10-10T00:00:00.000Z', limit: 50,
+ before: { createdAt: '2026-10-10T00:00:00.123456+00:00', id: 'abc-1' }, limit: 50,
});
+ assert.throws(() => parseActivityQuery({ before: '2026-10-10T00:00:00Z' }), /nextBefore value of the previous page/);
+ assert.throws(() => parseActivityQuery({ before: '2026-10-10T00:00:00Z|a",id.gt."0' }), /nextBefore value of the previous page/);
assert.equal(parseActivityQuery({ limit: '100' }).limit, 100);
assert.throws(() => parseActivityQuery({ limit: '101' }), /from 1 to 100/);
assert.throws(() => parseActivityQuery({ status: 'failed,lost' }), /status must be one of/);
diff --git a/backend/validators/automationValidators.ts b/backend/validators/automationValidators.ts
index e130452..a88dcb5 100644
--- a/backend/validators/automationValidators.ts
+++ b/backend/validators/automationValidators.ts
@@ -1,6 +1,7 @@
import { ValidationError } from '../lib/errors.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';
import type {
AutomationAccountRequest, AutomationCommentStatus, AutomationMatchMode, AutomationRuleRequest, AutomationRuleUpdateRequest,
AutomationTestRequest,
@@ -27,7 +28,7 @@ export interface ActivityQuery {
statuses?: AutomationCommentStatus[];
from?: string;
to?: string;
- before?: string;
+ before?: ActivityCursor;
limit: number;
}
@@ -124,6 +125,17 @@ function isoDate(query: Fields, field: string): string | undefined {
return new Date(time).toISOString();
}
+// the cursor is "<created_at as the API sent it>|<id>"; both go back into a filter, so only their own characters are allowed
+const CURSOR = /^(\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?(?:Z|[+-]\d{2}(?::?\d{2})?))\|([0-9A-Za-z_-]{1,64})$/;
+
+function cursor(query: Fields): ActivityCursor | undefined {
+ const value = optionalString(query, 'before');
+ if (!value) return undefined;
+ const match = CURSOR.exec(value);
+ if (!match) throw new ValidationError('before must be the nextBefore value of the previous page');
+ return { createdAt: match[1], id: match[2] };
+}
+
function statuses(query: Fields): AutomationCommentStatus[] | undefined {
const value = optionalString(query, 'status');
if (!value) return undefined;
@@ -191,7 +203,7 @@ export function parseActivityQuery(query: Fields): ActivityQuery {
statuses: statuses(query),
from: isoDate(query, 'from'),
to: isoDate(query, 'to'),
- before: isoDate(query, 'before'),
+ before: cursor(query),
limit,
};
}
diff --git a/docs/architecture/backend/CRON.md b/docs/architecture/backend/CRON.md
index 011fe77..4f811fd 100644
--- a/docs/architecture/backend/CRON.md
+++ b/docs/architecture/backend/CRON.md
@@ -69,7 +69,7 @@ The lease, attempt limit and failure rules live in `backend/lib/scheduledPublish
**Function:** `automationProcessor.run()` in `backend/services/automationProcessor.ts`
-Most private replies go out within seconds, from the webhook request itself (`docs/architecture/data-flows/AUTOMATION.md`). The sweep sends the rest: replies waiting for a retry, a cooldown or an hourly limit, replies a webhook could not finish, and jobs whose run stopped. It claims up to `AUTOMATION_BATCH_SIZE` due comments (10 by default), at most half of them from one account, and settles each one before the next. On the quarter-hour runs it sweeps only when publishing had nothing to do, and then only 3, because publishing spends part of the run's 50 subrequests. With nothing due, a sweep is one database call.
+Most private replies go out within seconds, from the webhook request itself (`docs/architecture/data-flows/AUTOMATION.md`). The sweep sends the rest: replies waiting for a retry, a cooldown or an hourly limit, replies a webhook could not finish, and jobs whose run stopped. It claims up to `AUTOMATION_BATCH_SIZE` due comments (10 by default), at most half of them from one account, and settles each one before the next. It has the run's 50 subrequests (48 after a publishing run with nothing due) and stops starting sends after 10 minutes, handing any unstarted job back to the queue. On the quarter-hour runs it sweeps only when publishing had nothing to do, and then only 3, because publishing spends part of the run's 50 subrequests. With nothing due, a sweep is one database call.
A run that stops is recovered by the next one: a comment left `processing` for more than 20 minutes is claimed again, and one left `sending` becomes `needs_review`, because its reply may have reached Instagram. `AUTOMATION_PAUSED=true` makes every sweep return without claiming anything.
diff --git a/docs/architecture/backend/ROUTES.md b/docs/architecture/backend/ROUTES.md
index be79f4a..70c4a70 100644
--- a/docs/architecture/backend/ROUTES.md
+++ b/docs/architecture/backend/ROUTES.md
@@ -168,7 +168,7 @@ Controllers call `AutomationService` (`services/automationService.ts`). Every ro
| DELETE | `/api/automations/rules/:id` | `automationController.deleteAutomationRule` | Delete a rule; its past comments keep their status |
| POST | `/api/automations/rules/:id/duplicate` | `automationController.duplicateAutomationRule` | Copy a rule, turned off, named "(copy)" |
| POST | `/api/automations/test` | `automationController.testAutomationRule` | Match a sample `comment` against a rule draft and return `{ matched, keyword, message, messageBytes, maxMessageBytes }`. Stores and sends nothing |
-| GET | `/api/automations/activity` | `automationController.listAutomationActivity` | Received comments, newest first. Query: `accountId`, `ruleId`, `status` (one or comma-separated), `from`, `to`, `before` (the previous page's `nextBefore`), `limit` (1 to 100, default 50) |
+| GET | `/api/automations/activity` | `automationController.listAutomationActivity` | Received comments, newest first. Query: `accountId`, `ruleId`, `status` (one or comma-separated), `from`, `to`, `before` (the previous page's `nextBefore`, an opaque `<created_at>|<id>` cursor, so comments stored in the same instant are neither skipped nor repeated), `limit` (1 to 100, default 50) |
| POST | `/api/automations/activity/:id/retry` | `automationController.retryAutomationActivity` | Put a failed, skipped or review item inside its 7 days back in the queue and start sending it; 409 for any other state |
| GET | `/api/automations/stats` | `automationController.getAutomationStats` | Comment counts by status and request counts by outcome. Query: `accountId`, `ruleId`, `from`, `to` (default the last 7 days) |
| PUT | `/api/automations/accounts/:accountId` | `automationController.updateAutomationAccount` | `{ paused }`: hold or release the account's replies; resuming also clears a hold the Worker set and sends held replies on the next run |
diff --git a/docs/architecture/data-flows/AUTOMATION.md b/docs/architecture/data-flows/AUTOMATION.md
index 3cda738..cf0da7c 100644
--- a/docs/architecture/data-flows/AUTOMATION.md
+++ b/docs/architecture/data-flows/AUTOMATION.md
@@ -75,11 +75,15 @@ If storing fails, the request fails with 5xx, and Meta delivers the notification
1. **Claim** (`claim_automation_comments`): due jobs (`queued` or `retry_wait` with `next_attempt_at <= now`) and jobs whose run stopped (`processing` for more than 20 minutes), oldest first, at most `perAccount` per account, locked with `FOR UPDATE SKIP LOCKED` so two runs never take the same job. The same call turns any `sending` job older than 20 minutes into `needs_review`. It returns the rule's reply and the account's token with each job.
2. **Check** (`readinessPlan`): an expired comment becomes `expired`, a rule that was turned off or removed `skipped`, an account without a token `failed`. No limit is spent on these.
3. **Reserve** (`reserve_automation_send`): one transaction under an advisory lock, so every Worker sees the same counts and two jobs cannot both take the last free send. In order: a paused account holds the job; an account cooldown waits for it; the commenter already got the daily number of replies from this account (counting other comments, not retries of this one) skips it; then the rule's, account's, user's and instance's hourly limits. When a scope is full, the job waits until the oldest send in that hour is an hour old. On success the job becomes `sending`, its attempts count goes up, and an `automation_attempts` row records the request before it leaves.
-4. **Send** (`sendPrivateReply`): `POST https://graph.instagram.com/v25.0/<ig-id>/messages` with `{ recipient: { comment_id }, message: { text } }` and the account's token as a Bearer header, 10 second timeout, never repeated inside the call.
+4. **Send** (`sendPrivateReply`): `POST https://graph.instagram.com/v25.0/<ig-id>/messages` with `{ recipient: { comment_id }, message: { text } }` and the account's token as a Bearer header, 10 second timeout, never repeated inside the call. Only that timeout can cut it off: a run starts a send only with the whole timeout and 2 seconds to spare, so the run's own deadline never turns a send into an unknown outcome.
5. **Finish** (`finish_automation_send`): records the outcome on the attempt and the comment in one transaction, and sets a cooldown or a hold on the account when the answer calls for one.
A database error on one job is logged and the run moves on; that job's claim or reservation expires and the recovery above picks it up.
+**Budgets.** Each run knows how many subrequests it may still make (the Workers Free plan allows 50 per invocation) and how long it may keep starting sends: a webhook's run gets what the request did not use (50, less 10 for the request's own middleware, less the intake's queries) and 20 seconds; a sweep gets 50 and 10 minutes. The claim takes only as many jobs as the budget pays for (one for the claim, one spare, three per reply). When time runs short or the run is cancelled, it hands every job it has not started back in one update (`returnUnstarted`: `processing` to `queued`, due at once), so they go out on the next run instead of waiting for the 20 minute lease.
+
+**Clocks.** New and retried jobs are due 30 seconds in the past, so a database clock slightly behind the Worker's still finds them due on the immediate run.
+
### What each answer does
| Instagram's answer | Comment | Attempt | Account |
@@ -102,7 +106,7 @@ A wait that would end after the 7 day window makes the comment `expired` instead
- A notification Meta delivers twice is stored once: `unique (ig_user_id, comment_id)`.
- A comment repeated inside one notification is stored once.
- Two runs never send the same job: the claim locks rows, and the reservation only moves a job this run holds.
-- A job whose run stopped before the request left is claimed again after its 20 minute lease.
+- A job a run claimed but did not start is handed back at once; one whose run died before the request left is claimed again after its 20 minute lease.
- A send that may have reached Instagram (timeout, lost connection, a run that stopped while `sending`) is never retried on its own. It shows as Needs review, and the owner decides after checking the conversation on Instagram. If they retry and the first reply did arrive, Instagram refuses a second private reply to the same comment (10900), and the comment is marked skipped.
- Delivery is at least once into the queue and at most once to Instagram without a person's decision. Instagram reports acceptance, not delivery or reading, so the dashboard says "Accepted by Instagram" and never "Delivered".
diff --git a/docs/workflows/TESTING.md b/docs/workflows/TESTING.md
index d2d0ae8..1527524 100644
--- a/docs/workflows/TESTING.md
+++ b/docs/workflows/TESTING.md
@@ -78,7 +78,7 @@ Scheduled publishing recovery has its own tests. `tests/lib/scheduledPublishing.
The database migrations have their own test. `tests/database/migrations.test.ts` reads `supabase/migrations/` and `supabase/rollbacks/` and checks that every file is named `<14 digit version>_<lowercase name>.sql` with a unique version, that the baseline files come before every change, that every change has a rollback with the same name and every rollback has its migration, that the baselines use only `if not exists` for tables, indexes and columns so they can run again, that every function a migration creates revokes execute from `public, anon, authenticated`, and that no file uses an em or en dash. It does not run the SQL; CI has no database. The migrations themselves were checked once on a local Postgres before the first push (ADR-038).
-Comment automation has its own tests. `tests/lib/automationMatching.test.ts` covers whole-word and exact matching, case, look-alike characters, literal punctuation in keywords, and that a comment on one reel never triggers a rule for another. `tests/lib/automationDelivery.test.ts` covers the Graph error classes, backoff with jitter, the cooldown from Meta's usage header, and what is recorded for each answer: accepted, rate limited, blocked, temporary errors up to the fifth try, already replied, a refused token (held), not allowed, no answer (needs review), and a request the runtime refused (not sent). `tests/lib/metaWebhookSignature.test.ts` checks signatures with either secret, changed bodies and malformed headers. `tests/fixtures/fakeAutomationQueue.ts` is an in-memory twin of the claim, reserve and finish functions, following the SQL's rules, and `tests/services/automationProcessor.test.ts` runs the processor against it: two comments at once, three reels with their own rules, two runs competing for the same jobs (each reply sent once), a burst over the batch and per-account fairness, a timeout that is never resent, a run that stopped before and during a send, a rate limit cooling one account while another keeps sending, the hourly and per-person limits, five temporary failures, a rule turned off, a deleted reel, an expired comment, a refused token holding the account, the instance pause, a database failure on one job and on the claim, and a run past its deadline. `tests/services/automationWebhookService.test.ts` covers intake: per-reel matching, unmatched comments kept without words, own comments, duplicates within and across notifications, accounts without rules, a failed insert, and the verify token. `tests/routes/instagramWebhookRoutes.test.ts` runs the public route end to end (challenge, signed comment stored then answered, duplicates, either secret, bad signatures, bad bodies, the 1 MB limit, a missing secret, a database failure), and `tests/routes/automationRoutes.test.ts` the user routes, including every route answering 404 for another user's rule, account or item. `tests/fixtures/metaWebhook.ts` signs notifications the way Meta does. The SQL functions cannot run in Node; they were checked on a local Postgres (PGlite) before the first push: deduplication, fair claims and lease recovery, each limit, pause and cooldown, a late answer for an interrupted send, stats, cascades, browser access and every rollback.
+Comment automation has its own tests. `tests/lib/automationMatching.test.ts` covers whole-word and exact matching, case, look-alike characters, literal punctuation in keywords, and that a comment on one reel never triggers a rule for another. `tests/lib/automationDelivery.test.ts` covers the Graph error classes, backoff with jitter, the cooldown from Meta's usage header, and what is recorded for each answer: accepted, rate limited, blocked, temporary errors up to the fifth try, already replied, a refused token (held), not allowed, no answer (needs review), and a request the runtime refused (not sent). `tests/lib/metaWebhookSignature.test.ts` checks signatures with either secret, changed bodies and malformed headers. `tests/fixtures/fakeAutomationQueue.ts` is an in-memory twin of the claim, reserve and finish functions, following the SQL's rules, and `tests/services/automationProcessor.test.ts` runs the processor against it: two comments at once, three reels with their own rules, two runs competing for the same jobs (each reply sent once), a burst over the batch and per-account fairness, a timeout that is never resent, a run that stopped before and during a send, a rate limit cooling one account while another keeps sending, the hourly and per-person limits, five temporary failures, a rule turned off, a deleted reel, an expired comment, a refused token holding the account, the instance pause, a database failure on one job and on the claim, a cancelled run and one without time for a whole send handing their jobs back unstarted, and a run claiming only what its subrequests pay for. `tests/services/automationWebhookService.test.ts` covers intake: per-reel matching, unmatched comments kept without words, own comments, duplicates within and across notifications, accounts without rules, a failed insert, and the verify token. `tests/repositories/automationCommentRepository.test.ts` pages through comments stored in the same instant without skipping or repeating one, and checks the hand-back of unstarted jobs. `tests/routes/instagramWebhookRoutes.test.ts` runs the public route end to end (challenge, signed comment stored then answered, duplicates, either secret, bad signatures, bad bodies, the 1 MB limit, a missing secret, a database failure), and `tests/routes/automationRoutes.test.ts` the user routes, including every route answering 404 for another user's rule, account or item. `tests/fixtures/metaWebhook.ts` signs notifications the way Meta does. The SQL functions cannot run in Node; they were checked on a local Postgres (PGlite) before the first push: deduplication, fair claims and lease recovery, each limit, pause and cooldown, a late answer for an interrupted send, stats, cascades, browser access and every rollback.
The Send Email hook has its own tests: `tests/lib/webhookSignature.test.ts` (valid, tampered, wrong-key, multi-signature and replayed requests), `tests/validators/authHookValidators.test.ts`, `tests/services/email/authEmails.test.ts` (the email for each action, the verify links, HTML escaping and the two Secure Email Change emails), `tests/repositories/emailQuotaRepository.test.ts` (daily and per-address caps, hashed keys, Redis failures), `tests/services/authEmailService.test.ts` (Resend requests, idempotency keys, the caps and Resend's own quota errors, skipped notices) and `tests/routes/authHookRoutes.test.ts` (the hook error shape, and the route answering unsigned calls with 401 in the full app). `tests/fixtures/authHook.ts` signs requests the way Supabase Auth does. The Lua claim script cannot run in Node; the repository test runs the same rules in memory. On the frontend, `tests/lib/authErrors.test.ts` covers when the sign-in page shows the daily cap warning and whether it offers Google, `tests/lib/emailAddress.test.ts` when an address looks complete enough to enable the Continue arrow, and `tests/lib/googleIdentity.test.ts` the label drawn on the Google button for each text option.
diff --git a/frontend/src/features/automations/useAutomationActivity.ts b/frontend/src/features/automations/useAutomationActivity.ts
index fc48a2c..2d657c3 100644
--- a/frontend/src/features/automations/useAutomationActivity.ts
+++ b/frontend/src/features/automations/useAutomationActivity.ts
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useState } from 'react';
+import { useCallback, useEffect, useRef, useState } from 'react';
import { useAppContext } from '../../context/AppContext';
import { api } from '../../services/api';
import { ACTIVITY_FILTERS, periodStart, summarizeStats } from './automationData.ts';
@@ -36,9 +36,13 @@ export function useAutomationActivity() {
const [retryingId, setRetryingId] = useState<string | null>(null);
// the time the list was read, so which items can be retried is decided against a fixed moment during render
const [checkedAt, setCheckedAt] = useState(() => Date.now());
+ // each load for new filters gets a number; an answer for an older one arrives too late and is dropped
+ const generation = useRef(0);
const load = useCallback(async () => {
+ const current = ++generation.current;
setLoading(true);
+ setNextBefore(null);
try {
const statsQuery = query({ ...filters, filter: 'all' });
statsQuery.delete('status');
@@ -47,14 +51,15 @@ export function useAutomationActivity() {
api.getAutomationActivity(query(filters)),
api.getAutomationStats(statsQuery),
]);
+ if (current !== generation.current) return;
setItems(page.items);
setNextBefore(page.nextBefore);
setSummary(summarizeStats(stats.stats));
setCheckedAt(Date.now());
} catch (err) {
- showToast(`Couldn't load the reply activity. ${(err as Error).message}`, 'error');
+ if (current === generation.current) showToast(`Couldn't load the reply activity. ${(err as Error).message}`, 'error');
} finally {
- setLoading(false);
+ if (current === generation.current) setLoading(false);
}
}, [filters, showToast]);
@@ -62,10 +67,12 @@ export function useAutomationActivity() {
const loadMore = useCallback(async () => {
if (!nextBefore) return;
+ const current = generation.current;
setLoadingMore(true);
try {
const page = await api.getAutomationActivity(query(filters, nextBefore));
- setItems(current => [...current, ...page.items]);
+ if (current !== generation.current) return;
+ setItems(existing => [...existing, ...page.items]);
setNextBefore(page.nextBefore);
} catch (err) {
showToast(`Couldn't load more activity. ${(err as Error).message}`, 'error');