Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

feat(action-center): send a task to Content or the brand's webhook (#1082)

Cihan2f9677911067
diff --git a/server/.env.example b/server/.env.example
index 3382bcc37..66248eced 100644
--- a/server/.env.example
+++ b/server/.env.example
@@ -125,7 +125,8 @@ AI_VOLUME_MULTIPLIER=0.45
# RESEND_API_KEY=re_...
# RESEND_FROM_EMAIL="Ansvisor <[email protected]>"
-# Public URL of the web app, used for links in Daily Pulse emails
+# Public URL of the web app, used for links in Daily Pulse emails and in the
+# action_task.sent webhook (Action Center → Send to webhook)
# PUBLIC_APP_URL=https://app.example.com
diff --git a/server/src/lib/action-center/from-opportunity.js b/server/src/lib/action-center/from-opportunity.js
index 815f42fb7..dd48488e6 100644
--- a/server/src/lib/action-center/from-opportunity.js
+++ b/server/src/lib/action-center/from-opportunity.js
@@ -121,6 +121,11 @@ export async function sendToActionCenter(
opportunity,
{ assetKey = null, userId, readable = opportunity },
) {
+ // An opportunity a task was sent as (AC-004) is that action's work already:
+ // it opens the action rather than starting a second one for the same thing.
+ const from = opportunity.source_data?.fromAction?.actionId;
+ if (opportunity.source === 'action' && from) return { actionId: from, created: false };
+
const assets = opportunityAssets(readable);
const chosen = assetKey ? assets.filter((a) => a.key === assetKey) : assets;
if (!chosen.length) {
diff --git a/server/src/lib/action-center/from-opportunity.test.js b/server/src/lib/action-center/from-opportunity.test.js
index e4d2b331f..c2bcc3170 100644
--- a/server/src/lib/action-center/from-opportunity.test.js
+++ b/server/src/lib/action-center/from-opportunity.test.js
@@ -130,3 +130,20 @@ describe('actionPromptScope', () => {
});
});
});
+
+describe('an opportunity a task was sent as (AC-004)', () => {
+ it('opens the action it came from instead of starting a second one', async () => {
+ const { sendToActionCenter } = await import('./from-opportunity.js');
+ expect(
+ await sendToActionCenter(
+ {
+ id: 'o1',
+ brand_id: 'b1',
+ source: 'action',
+ source_data: { fromAction: { actionId: 'a1' } },
+ },
+ { userId: 'u1' },
+ ),
+ ).toEqual({ actionId: 'a1', created: false });
+ });
+});
diff --git a/server/src/lib/action-center/task-send.js b/server/src/lib/action-center/task-send.js
new file mode 100644
index 000000000..aa069b144
--- /dev/null
+++ b/server/src/lib/action-center/task-send.js
@@ -0,0 +1,314 @@
+/**
+ * Sending an Action Center task onward (AC-004): to Content as an
+ * opportunity, or to the brand's webhook.
+ *
+ * Send to Content takes a content task — where, why, how, done when — into
+ * Content Optimization, where a brief and a draft can be written for it. The
+ * opportunity is the task's, not a generation: it uses none of the monthly
+ * opportunity quota, and it points back at its action, so Content offers
+ * "Open in Actions" rather than a second action for the same work.
+ *
+ * Send to webhook posts the task to the brand's active webhooks, in the shape
+ * Content's opportunity.sent uses, for a workflow outside Ansvisor to pick up.
+ *
+ * Either way the task records where it went (details.sent), the action's
+ * History says so, and a task that has been sent survives "Regenerate tasks".
+ */
+
+import supabaseAdmin from '../../config/supabase.js';
+import { logger } from '../logger.js';
+import { dispatchBrandWebhook } from '../webhook-dispatch.js';
+import { ownDomainMatcher } from '../response-parser.js';
+import { OPPORTUNITY_ACTION_KIND } from './from-opportunity.js';
+
+export class TaskSendError extends Error {
+ constructor(code, message, status = 422) {
+ super(message);
+ this.code = code;
+ this.status = status;
+ }
+}
+
+/** The dashboard's origin, for links in what a webhook receives. */
+function appOrigin() {
+ const raw = process.env.PUBLIC_APP_URL || 'http://localhost:3000';
+ try {
+ return new URL(raw).origin;
+ } catch {
+ return raw.replace(/\/$/, '');
+ }
+}
+
+const text = (value) => (typeof value === 'string' ? value.trim() : '');
+
+/** A task and its action, with what sending needs to know about them. */
+export async function loadTask(taskId) {
+ const { data: task, error } = await supabaseAdmin
+ .from('action_tasks')
+ .select('id, action_id, task_key, title, status, details')
+ .eq('id', taskId)
+ .maybeSingle();
+ if (error) throw new Error(error.message);
+ if (!task) throw new TaskSendError('not_found', 'Task not found', 404);
+ const { data: action, error: actionError } = await supabaseAdmin
+ .from('actions')
+ .select(
+ 'id, action_no, brand_id, kind, category, impact, status, priority_score, priority_level',
+ )
+ .eq('id', task.action_id)
+ .single();
+ if (actionError) throw new Error(actionError.message);
+ return { task, action };
+}
+
+/**
+ * The brand's page a task's Where names, as a URL: "acme.example/pricing ·
+ * lost on ChatGPT" gives https://acme.example/pricing, and a bare path is on
+ * the brand's first domain. Null when Where names no page of the brand's.
+ */
+export function ownPageOf(where, brandDomains) {
+ const isOwn = ownDomainMatcher(brandDomains);
+ for (const token of text(where).split(/[\s·,;()]+/)) {
+ const cleaned = token.replace(/^["'“”]+|["'“”.]+$/g, '');
+ if (!cleaned) continue;
+ if (cleaned.startsWith('/') && cleaned.length > 1 && brandDomains[0]) {
+ const domain = String(brandDomains[0])
+ .replace(/^https?:\/\//, '')
+ .replace(/\/$/, '');
+ return `https://${domain}${cleaned}`;
+ }
+ if (/^(https?:\/\/)?([a-z0-9-]+\.)+[a-z]{2,}(\/\S*)?$/i.test(cleaned)) {
+ const url = /^https?:\/\//i.test(cleaned) ? cleaned : `https://${cleaned}`;
+ if (isOwn(url)) return url;
+ }
+ }
+ return null;
+}
+
+/**
+ * The opportunity a content task becomes. Its one asset is the page to work
+ * on, or a new page when Where names none of the brand's; the asset carries
+ * every field Content reads, `pages` included.
+ */
+export function opportunityFromTask({ task, title, action, brandDomains }) {
+ const d = task.details ?? {};
+ const page = ownPageOf(d.where, brandDomains);
+ const decision = page ? 'optimize' : 'create';
+ const targetPages = page ? [{ url: page, title: '' }] : [];
+ return {
+ brand_id: action.brand_id,
+ prompt_id: null,
+ title,
+ description: text(d.why) || null,
+ type: 'owned',
+ impact: action.impact,
+ opportunity_score: action.priority_score ?? 0,
+ status: 'new',
+ source: 'action',
+ decision,
+ source_data: {
+ targetPages,
+ assets: [
+ { key: 'a1', type: 'blog_post', channel: 'owned', decision, title, pages: targetPages },
+ ],
+ // Content's "Open in Actions": the action the task came from.
+ actions: { all: action.id },
+ fromAction: {
+ actionId: action.id,
+ actionNo: action.action_no,
+ taskId: task.id,
+ task: {
+ where: text(d.where),
+ why: text(d.why),
+ how: Array.isArray(d.how) ? d.how.map(text).filter(Boolean) : [],
+ doneWhen: text(d.doneWhen),
+ effort: text(d.effort),
+ role: text(d.role),
+ },
+ },
+ },
+ };
+}
+
+/**
+ * Record where the task went, merged into what it carries as it is now: a
+ * send can take seconds (a webhook), and an edit saved meanwhile must not be
+ * written over. Guarded on updated_at, and read again when it moved.
+ */
+async function markSent(taskId, to, value) {
+ for (let attempt = 0; attempt < 3; attempt += 1) {
+ const { data: row, error } = await supabaseAdmin
+ .from('action_tasks')
+ .select('details, updated_at')
+ .eq('id', taskId)
+ .maybeSingle();
+ if (error) throw new Error(error.message);
+ if (!row) return;
+ const details = { ...(row.details ?? {}) };
+ details.sent = { ...(details.sent ?? {}), [to]: value };
+ const { data: saved, error: saveError } = await supabaseAdmin
+ .from('action_tasks')
+ .update({ details, updated_at: new Date().toISOString() })
+ .eq('id', taskId)
+ .eq('updated_at', row.updated_at)
+ .select('id');
+ if (saveError) throw new Error(saveError.message);
+ if (saved?.length) return;
+ }
+ throw new Error('The task kept changing; the send was not recorded on it.');
+}
+
+/** The open opportunity a task was sent as, if any (00151 keeps it to one). */
+async function openOpportunityFor(taskId) {
+ const { data, error } = await supabaseAdmin
+ .from('content_opportunities')
+ .select('id')
+ .eq('source', 'action')
+ .eq('source_data->fromAction->>taskId', taskId)
+ .neq('status', 'archived')
+ .limit(1);
+ if (error) throw new Error(error.message);
+ return data?.[0]?.id ?? null;
+}
+
+/** The brand's domains, the primary one first: a bare path is on it. */
+async function brandDomainsOf(brandId) {
+ const { data } = await supabaseAdmin
+ .from('brand_domains')
+ .select('domain, is_primary')
+ .eq('brand_id', brandId);
+ return [...(data ?? [])]
+ .sort((a, b) => Number(Boolean(b.is_primary)) - Number(Boolean(a.is_primary)))
+ .map((d) => d.domain);
+}
+
+async function logSent(action, task, to, title, userId) {
+ const { error } = await supabaseAdmin.from('action_events').insert({
+ action_id: action.id,
+ event: 'task_sent',
+ data: { taskId: task.id, to, title },
+ actor_id: userId,
+ });
+ if (error) logger.warn({ err: error, taskId: task.id }, '[task-send] event insert failed');
+}
+
+/**
+ * Send a content task to Content as an opportunity. Sending it again returns
+ * the opportunity it already made, while that one is open; two sends at once
+ * make one (a unique index, 00151).
+ *
+ * @param {{ taskId: string, title: string, userId: string | null,
+ * loaded?: { task: object, action: object } }} input
+ * `title` is the task's text as the dashboard shows it: a library task's
+ * text is a template only the dashboard renders. `loaded` saves reading
+ * the task again when the caller already has.
+ * @returns {Promise<{ opportunityId: string, created: boolean }>}
+ */
+export async function sendTaskToContent({ taskId, title, userId, loaded }) {
+ const { task, action } = loaded ?? (await loadTask(taskId));
+ if (action.kind === OPPORTUNITY_ACTION_KIND) {
+ throw new TaskSendError('from_content', 'This action was sent from Content.');
+ }
+ if (task.details?.type !== 'content') {
+ throw new TaskSendError('not_content', 'Only a content task can be sent to Content.');
+ }
+ const name = text(task.title) || text(title);
+ if (!name) throw new TaskSendError('no_title', 'The task has no text to send.');
+
+ // Already in Content: say so, and make sure the task says so too (a send
+ // whose record failed is finished here rather than made twice).
+ const already = await openOpportunityFor(task.id);
+ if (already) {
+ if (task.details?.sent?.content?.opportunityId !== already) {
+ await markSent(task.id, 'content', { opportunityId: already, at: new Date().toISOString() });
+ }
+ return { opportunityId: already, created: false };
+ }
+
+ const row = opportunityFromTask({
+ task,
+ title: name.slice(0, 200),
+ action,
+ brandDomains: await brandDomainsOf(action.brand_id),
+ });
+ const { data: created, error } = await supabaseAdmin
+ .from('content_opportunities')
+ .insert(row)
+ .select('id')
+ .single();
+ if (error?.code === '23505') {
+ // Another send got there first.
+ const winner = await openOpportunityFor(task.id);
+ if (winner) {
+ await markSent(task.id, 'content', { opportunityId: winner, at: new Date().toISOString() });
+ return { opportunityId: winner, created: false };
+ }
+ }
+ if (error) throw new Error(error.message);
+
+ await markSent(task.id, 'content', { opportunityId: created.id, at: new Date().toISOString() });
+ await logSent(action, task, 'content', name, userId);
+ return { opportunityId: created.id, created: true };
+}
+
+/**
+ * Post a task to the brand's active webhooks as `action_task.sent`.
+ *
+ * @returns {Promise<{ delivered: number, failed: number }>}
+ */
+export async function sendTaskToWebhook({ taskId, title, userId, loaded }) {
+ const { task, action } = loaded ?? (await loadTask(taskId));
+ const name = text(task.title) || text(title);
+ if (!name) throw new TaskSendError('no_title', 'The task has no text to send.');
+
+ const [{ data: brand }, { data: domains }] = await Promise.all([
+ supabaseAdmin.from('brands').select('name, industry').eq('id', action.brand_id).single(),
+ supabaseAdmin
+ .from('brand_domains')
+ .select('domain, is_primary')
+ .eq('brand_id', action.brand_id),
+ ]);
+ const primary = (domains ?? []).find((d) => d.is_primary) ?? (domains ?? [])[0];
+ const d = task.details ?? {};
+
+ const { sent, failed } = await dispatchBrandWebhook(action.brand_id, {
+ event: 'action_task.sent',
+ task: {
+ id: task.id,
+ title: name,
+ status: task.status,
+ type: d.type ?? null,
+ where: text(d.where) || null,
+ why: text(d.why) || null,
+ how: Array.isArray(d.how) ? d.how : [],
+ done_when: text(d.doneWhen) || null,
+ effort: text(d.effort) || null,
+ role: text(d.role) || null,
+ },
+ action: {
+ id: action.id,
+ action_no: action.action_no,
+ kind: action.kind,
+ category: action.category,
+ impact: action.impact,
+ priority_score: action.priority_score,
+ priority_level: action.priority_level,
+ link: `${appOrigin()}/dashboard/action-center/actions?action=${action.id}`,
+ },
+ brand: {
+ name: brand?.name ?? null,
+ domain: primary?.domain ?? null,
+ industry: brand?.industry ?? null,
+ },
+ });
+
+ if (sent + failed === 0) {
+ throw new TaskSendError('no_webhook', 'This brand has no active webhook.', 409);
+ }
+ if (sent === 0) {
+ throw new TaskSendError('webhook_failed', "The webhook didn't accept the task.", 502);
+ }
+ await markSent(task.id, 'webhook', { at: new Date().toISOString(), delivered: sent, failed });
+ await logSent(action, task, 'webhook', name, userId);
+ return { delivered: sent, failed };
+}
diff --git a/server/src/lib/action-center/task-send.test.js b/server/src/lib/action-center/task-send.test.js
new file mode 100644
index 000000000..741231a87
--- /dev/null
+++ b/server/src/lib/action-center/task-send.test.js
@@ -0,0 +1,272 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * Sending a task onward (AC-004): the opportunity a content task becomes, a
+ * second send returning it, the webhook's answers, and the trail the task
+ * keeps.
+ */
+
+let db;
+let ops;
+
+/** A column, or a JSON path as PostgREST writes one ("source_data->fromAction->>taskId"). */
+const read = (row, col) => col.split(/->>?/).reduce((value, key) => value?.[key], row);
+
+function table(name) {
+ const q = { op: 'select', filters: [], payload: null, returning: false };
+ const rows = () => (db[name] ?? []).filter((row) => q.filters.every((test) => test(row)));
+ const run = (single) => {
+ if (q.op === 'select') {
+ const data = rows();
+ return { data: single ? (data[0] ?? null) : data, error: null };
+ }
+ ops.push({ table: name, op: q.op, payload: q.payload });
+ if (q.op === 'insert') {
+ // Another send's row, landing between this one's check and its insert.
+ if (name === 'content_opportunities' && db.raceRow) {
+ db[name].push(db.raceRow);
+ db.raceRow = null;
+ }
+ // 00151: one open opportunity per task.
+ const taskId = q.payload.source_data?.fromAction?.taskId;
+ if (
+ name === 'content_opportunities' &&
+ (db[name] ?? []).some(
+ (row) => row.source_data?.fromAction?.taskId === taskId && row.status !== 'archived',
+ )
+ ) {
+ return { data: null, error: { code: '23505', message: 'duplicate key' } };
+ }
+ const row = { id: `${name}-${(db[name] ?? []).length + 1}`, ...q.payload };
+ (db[name] ??= []).push(row);
+ return { data: single ? row : [row], error: null };
+ }
+ const matched = rows();
+ for (const row of matched) Object.assign(row, q.payload);
+ return { data: q.returning ? matched : null, error: null };
+ };
+ const chain = {
+ select: () => ((q.returning = q.op !== 'select'), chain),
+ eq: (col, value) => (q.filters.push((row) => read(row, col) === value), chain),
+ neq: (col, value) => (q.filters.push((row) => read(row, col) !== value), chain),
+ limit: () => chain,
+ insert: (payload) => ((q.op = 'insert'), (q.payload = payload), chain),
+ update: (payload) => ((q.op = 'update'), (q.payload = payload), chain),
+ maybeSingle: async () => run(true),
+ single: async () => run(true),
+ then: (resolve, reject) => Promise.resolve(run(false)).then(resolve, reject),
+ };
+ return chain;
+}
+
+vi.mock('../../config/supabase.js', () => ({ default: { from: (name) => table(name) } }));
+vi.mock('../logger.js', () => ({ logger: { warn: vi.fn(), error: vi.fn(), info: vi.fn() } }));
+const dispatchBrandWebhook = vi.fn();
+vi.mock('../webhook-dispatch.js', () => ({
+ dispatchBrandWebhook: (...args) => dispatchBrandWebhook(...args),
+}));
+vi.mock('./from-opportunity.js', () => ({ OPPORTUNITY_ACTION_KIND: 'content_opportunity' }));
+
+const { opportunityFromTask, ownPageOf, sendTaskToContent, sendTaskToWebhook } =
+ await import('./task-send.js');
+
+const details = {
+ where: 'acme.example/blog/shipping · lost on ChatGPT',
+ why: 'Cited #2 until Oct 12.',
+ how: ['Add a table.', 'Put "2026" in the title.'],
+ doneWhen: 'Cited again within 14 days.',
+ type: 'content',
+ effort: '~2h',
+ role: 'Content writer',
+ source: 'ai',
+};
+
+beforeEach(() => {
+ ops = [];
+ dispatchBrandWebhook.mockReset();
+ db = {
+ action_tasks: [
+ {
+ id: 't1',
+ action_id: 'a1',
+ task_key: null,
+ title: 'Add a 2026 table to /blog/shipping',
+ status: 'todo',
+ details: { ...details },
+ updated_at: '2026-10-16T09:00:00Z',
+ },
+ ],
+ actions: [
+ {
+ id: 'a1',
+ action_no: 12,
+ brand_id: 'b1',
+ kind: 'recover_lost_citations',
+ category: 'recover',
+ impact: 'high',
+ status: 'new',
+ priority_score: 84,
+ priority_level: 'high',
+ },
+ ],
+ brands: [{ id: 'b1', name: 'Acme Coffee', industry: 'Coffee' }],
+ brand_domains: [{ brand_id: 'b1', domain: 'acme.example', is_primary: true }],
+ content_opportunities: [],
+ };
+});
+
+describe('ownPageOf', () => {
+ it("finds the brand's page in Where, as a URL", () => {
+ expect(ownPageOf('acme.example/blog/shipping · lost on ChatGPT', ['acme.example'])).toBe(
+ 'https://acme.example/blog/shipping',
+ );
+ expect(ownPageOf('"/pricing" on Gemini', ['acme.example'])).toBe(
+ 'https://acme.example/pricing',
+ );
+ expect(ownPageOf('g2.com/categories/ai-rank-tracking', ['acme.example'])).toBeNull();
+ });
+});
+
+describe('opportunityFromTask', () => {
+ it('works on the named page, with every field Content reads, and points back at the action', () => {
+ const row = opportunityFromTask({
+ task: db.action_tasks[0],
+ title: 'Add a 2026 table to /blog/shipping',
+ action: db.actions[0],
+ brandDomains: ['acme.example'],
+ });
+ expect(row).toMatchObject({
+ source: 'action',
+ status: 'new',
+ type: 'owned',
+ impact: 'high',
+ opportunity_score: 84,
+ decision: 'optimize',
+ description: 'Cited #2 until Oct 12.',
+ });
+ expect(row.source_data.assets).toEqual([
+ {
+ key: 'a1',
+ type: 'blog_post',
+ channel: 'owned',
+ decision: 'optimize',
+ title: 'Add a 2026 table to /blog/shipping',
+ pages: [{ url: 'https://acme.example/blog/shipping', title: '' }],
+ },
+ ]);
+ expect(row.source_data.actions).toEqual({ all: 'a1' });
+ expect(row.source_data.fromAction).toMatchObject({ actionNo: 12, taskId: 't1' });
+ });
+});
+
+describe('sendTaskToContent', () => {
+ it('makes the opportunity, records it on the task and in History, and returns it on a second send', async () => {
+ const first = await sendTaskToContent({ taskId: 't1', title: '', userId: 'u1' });
+ expect(first).toEqual({ opportunityId: 'content_opportunities-1', created: true });
+ expect(db.action_tasks[0].details.sent.content.opportunityId).toBe('content_opportunities-1');
+ expect(ops.find((op) => op.table === 'action_events').payload).toMatchObject({
+ event: 'task_sent',
+ data: { taskId: 't1', to: 'content', title: 'Add a 2026 table to /blog/shipping' },
+ actor_id: 'u1',
+ });
+
+ const again = await sendTaskToContent({ taskId: 't1', title: '', userId: 'u1' });
+ expect(again).toEqual({ opportunityId: 'content_opportunities-1', created: false });
+ expect(db.content_opportunities).toHaveLength(1);
+ });
+
+ it('takes only a content task, and none from an action Content sent', async () => {
+ db.action_tasks[0].details.type = 'outreach';
+ await expect(sendTaskToContent({ taskId: 't1', title: '' })).rejects.toMatchObject({
+ code: 'not_content',
+ });
+ db.action_tasks[0].details.type = 'content';
+ db.actions[0].kind = 'content_opportunity';
+ await expect(sendTaskToContent({ taskId: 't1', title: '' })).rejects.toMatchObject({
+ code: 'from_content',
+ });
+ });
+
+ it("uses the drawer's text for a library task", async () => {
+ db.action_tasks[0].title = null;
+ await sendTaskToContent({ taskId: 't1', title: 'Refresh /blog/shipping', userId: null });
+ expect(db.content_opportunities[0].title).toBe('Refresh /blog/shipping');
+ });
+});
+
+describe('sendTaskToWebhook', () => {
+ it('posts the task as action_task.sent and records it', async () => {
+ dispatchBrandWebhook.mockResolvedValueOnce({ sent: 1, failed: 0 });
+ expect(await sendTaskToWebhook({ taskId: 't1', title: '', userId: 'u1' })).toEqual({
+ delivered: 1,
+ failed: 0,
+ });
+ const [brandId, payload] = dispatchBrandWebhook.mock.calls[0];
+ expect(brandId).toBe('b1');
+ expect(payload).toMatchObject({
+ event: 'action_task.sent',
+ task: { id: 't1', type: 'content', done_when: 'Cited again within 14 days.' },
+ action: { id: 'a1', action_no: 12, priority_score: 84 },
+ brand: { name: 'Acme Coffee', domain: 'acme.example' },
+ });
+ expect(payload.action.link).toMatch(/\/dashboard\/action-center\/actions\?action=a1$/);
+ expect(db.action_tasks[0].details.sent.webhook).toMatchObject({ delivered: 1 });
+ });
+
+ it('says when there is no webhook, or it refused the task, and records nothing', async () => {
+ dispatchBrandWebhook.mockResolvedValueOnce({ sent: 0, failed: 0 });
+ await expect(sendTaskToWebhook({ taskId: 't1', title: '' })).rejects.toMatchObject({
+ code: 'no_webhook',
+ status: 409,
+ });
+ dispatchBrandWebhook.mockResolvedValueOnce({ sent: 0, failed: 1 });
+ await expect(sendTaskToWebhook({ taskId: 't1', title: '' })).rejects.toMatchObject({
+ code: 'webhook_failed',
+ });
+ expect(db.action_tasks[0].details.sent).toBeUndefined();
+ });
+});
+
+describe('what the review found', () => {
+ it('makes one opportunity when two sends race, and the second finds it', async () => {
+ // The other send inserts between this one's check and its insert.
+ db.raceRow = {
+ id: 'o-race',
+ source: 'action',
+ status: 'new',
+ source_data: { fromAction: { taskId: 't1' } },
+ };
+ const result = await sendTaskToContent({ taskId: 't1', title: '', userId: 'u1' });
+ expect(result).toEqual({ opportunityId: 'o-race', created: false });
+ expect(db.content_opportunities).toHaveLength(1);
+ expect(db.action_tasks[0].details.sent.content.opportunityId).toBe('o-race');
+ });
+
+ it('keeps an edit saved while the task was being sent', async () => {
+ dispatchBrandWebhook.mockImplementationOnce(async () => {
+ // Someone edits the task while the webhook answers.
+ Object.assign(db.action_tasks[0], {
+ details: { ...db.action_tasks[0].details, where: 'acme.example/new-page' },
+ updated_at: '2026-10-16T09:00:05Z',
+ });
+ return { sent: 1, failed: 0 };
+ });
+ await sendTaskToWebhook({ taskId: 't1', title: '', userId: 'u1' });
+ expect(db.action_tasks[0].details).toMatchObject({
+ where: 'acme.example/new-page',
+ sent: { webhook: { delivered: 1 } },
+ });
+ });
+
+ it("puts a bare path on the brand's primary domain", async () => {
+ db.brand_domains = [
+ { brand_id: 'b1', domain: 'shop.acme.example', is_primary: false },
+ { brand_id: 'b1', domain: 'acme.example', is_primary: true },
+ ];
+ db.action_tasks[0].details.where = '/pricing on Gemini';
+ await sendTaskToContent({ taskId: 't1', title: '', userId: null });
+ expect(db.content_opportunities[0].source_data.targetPages).toEqual([
+ { url: 'https://acme.example/pricing', title: '' },
+ ]);
+ });
+});
diff --git a/server/src/lib/action-center/task-writer/index.js b/server/src/lib/action-center/task-writer/index.js
index cdda81857..efb23914d 100644
--- a/server/src/lib/action-center/task-writer/index.js
+++ b/server/src/lib/action-center/task-writer/index.js
@@ -72,11 +72,14 @@ export function isAnalysisTask(row) {
}
/**
- * Whether a rewrite keeps a task: one done or under way, and one a person
- * added — no template, not written by the model. Everything else is replaced.
+ * Whether a rewrite keeps a task: one done or under way, one sent to Content
+ * or a webhook, and one a person added — no template, not written by the
+ * model. Everything else is replaced.
*/
export function keepsTask(row) {
if (isAnalysisTask(row)) return false;
+ // Sent to Content or a webhook: the work has left the list's hands.
+ if (row.details?.sent) return true;
if (row.status === 'completed' || row.status === 'in_progress') return true;
return !row.task_key && row.details?.source !== 'ai';
}
diff --git a/server/src/lib/action-center/task-writer/index.test.js b/server/src/lib/action-center/task-writer/index.test.js
index 6b31424c5..0f3988c5c 100644
--- a/server/src/lib/action-center/task-writer/index.test.js
+++ b/server/src/lib/action-center/task-writer/index.test.js
@@ -185,6 +185,14 @@ describe('keepsTask', () => {
expect(keepsTask({ task_key: null, status: 'todo', details: { source: 'ai' } })).toBe(false);
expect(keepsTask({ task_key: 'analyze_citations', status: 'completed' })).toBe(false);
expect(keepsTask({ task_key: 'validate_citations', status: 'in_progress' })).toBe(false);
+ // Sent to Content or a webhook: kept, whatever its status.
+ expect(
+ keepsTask({
+ task_key: null,
+ status: 'todo',
+ details: { source: 'ai', sent: { webhook: {} } },
+ }),
+ ).toBe(true);
});
});
diff --git a/server/src/routes/action-center-tasks.test.js b/server/src/routes/action-center-tasks.test.js
index a09f7c0a8..ad13fa517 100644
--- a/server/src/routes/action-center-tasks.test.js
+++ b/server/src/routes/action-center-tasks.test.js
@@ -41,7 +41,17 @@ vi.mock('../lib/action-center/task-writer/index.js', () => ({
writeTasksForAction: (...args) => writeTasksForAction(...args),
}));
-const { regenerateTasks } = await import('./action-center.js');
+const loadTask = vi.fn();
+const sendTaskToContent = vi.fn();
+const sendTaskToWebhook = vi.fn();
+vi.mock('../lib/action-center/task-send.js', () => ({
+ TaskSendError: class extends Error {},
+ loadTask: (...args) => loadTask(...args),
+ sendTaskToContent: (...args) => sendTaskToContent(...args),
+ sendTaskToWebhook: (...args) => sendTaskToWebhook(...args),
+}));
+
+const { regenerateTasks, sendTask } = await import('./action-center.js');
beforeEach(() => {
enabled = true;
@@ -89,3 +99,32 @@ describe('regenerateTasks', () => {
});
});
});
+
+describe('sendTask', () => {
+ beforeEach(() => {
+ loadTask.mockReset().mockResolvedValue({ task: { id: 't1' }, action: { brand_id: 'b1' } });
+ sendTaskToContent.mockReset().mockResolvedValue({ opportunityId: 'o1', created: true });
+ sendTaskToWebhook.mockReset().mockResolvedValue({ delivered: 1, failed: 0 });
+ });
+
+ it("checks the caller's access to the task's brand before sending", async () => {
+ assertBrandAccess.mockRejectedValueOnce(Object.assign(new Error('Forbidden'), { status: 403 }));
+ await expect(sendTask('t1', { to: 'content' }, 'u1')).rejects.toThrow('Forbidden');
+ expect(assertBrandAccess).toHaveBeenCalledWith('b1', 'u1');
+ expect(sendTaskToContent).not.toHaveBeenCalled();
+ });
+
+ it('sends where it was asked, with the text the drawer shows', async () => {
+ expect(await sendTask('t1', { to: 'content', title: 'Refresh /a' }, 'u1')).toEqual({
+ opportunityId: 'o1',
+ created: true,
+ });
+ expect(sendTaskToContent).toHaveBeenCalledWith(
+ expect.objectContaining({ taskId: 't1', title: 'Refresh /a', userId: 'u1' }),
+ );
+ await sendTask('t1', { to: 'webhook' }, 'u1');
+ expect(sendTaskToWebhook).toHaveBeenCalledWith(
+ expect.objectContaining({ taskId: 't1', userId: 'u1' }),
+ );
+ });
+});
diff --git a/server/src/routes/action-center.js b/server/src/routes/action-center.js
index 7d8f13734..2779ac024 100644
--- a/server/src/routes/action-center.js
+++ b/server/src/routes/action-center.js
@@ -4,6 +4,12 @@ import supabaseAdmin from '../config/supabase.js';
import { assertBrandAccess } from '../lib/access.js';
import { rescoreActionsForSignal } from '../lib/action-center/priority-data.js';
import { PlanLimitError } from '../lib/plan-guard.js';
+import {
+ TaskSendError,
+ loadTask,
+ sendTaskToContent,
+ sendTaskToWebhook,
+} from '../lib/action-center/task-send.js';
import {
TaskWriterError,
isTaskWriterEnabled,
@@ -106,4 +112,39 @@ router.post('/actions/:id/tasks/regenerate', async (req, res) => {
}
});
+/**
+ * Sends a task onward (AC-004): to Content as an opportunity, or to the
+ * brand's webhook. `title` is the task's text as the dashboard shows it, for
+ * a library task whose text only the dashboard renders.
+ */
+export async function sendTask(taskId, { to, title }, userId) {
+ const loaded = await loadTask(taskId);
+ await assertBrandAccess(loaded.action.brand_id, userId);
+ return to === 'content'
+ ? sendTaskToContent({ taskId, title, userId, loaded })
+ : sendTaskToWebhook({ taskId, title, userId, loaded });
+}
+
+const sendTaskSchema = z.object({
+ to: z.enum(['content', 'webhook']),
+ title: z.string().max(200).optional(),
+});
+
+/** POST /api/action-center/tasks/:id/send */
+router.post('/tasks/:id/send', async (req, res) => {
+ const id = signalIdSchema.safeParse(req.params.id);
+ const body = sendTaskSchema.safeParse(req.body ?? {});
+ if (!id.success || !body.success) return res.status(400).json({ error: 'Invalid request' });
+ try {
+ return res.json(await sendTask(id.data, body.data, req.user.id));
+ } catch (error) {
+ const status = error.status;
+ if (!status) req.log.error({ err: error }, 'send action task error');
+ return res.status(status || 500).json({
+ error: status ? error.message : 'Failed to send the task.',
+ code: error instanceof TaskSendError ? error.code : null,
+ });
+ }
+});
+
export default router;
diff --git a/server/src/routes/content-brief-task.test.js b/server/src/routes/content-brief-task.test.js
new file mode 100644
index 000000000..5a807c4ae
--- /dev/null
+++ b/server/src/routes/content-brief-task.test.js
@@ -0,0 +1,53 @@
+import { describe, expect, it, vi } from 'vitest';
+
+/**
+ * A brief for an opportunity sent from an Action Center task (AC-004) is
+ * told what the task says: where, why, the steps and the check that closes it.
+ */
+
+vi.mock('../config/supabase.js', () => ({ default: { from: () => ({}) } }));
+vi.mock('../lib/prompt-clusters.js', () => ({ loadClusters: vi.fn() }));
+vi.mock('../lib/action-center/from-opportunity.js', () => ({
+ OPPORTUNITY_ACTION_KIND: 'content_opportunity',
+ sendToActionCenter: vi.fn(),
+}));
+vi.mock('../lib/ai-provider.js', () => ({ resolveModel: vi.fn() }));
+vi.mock('../lib/logger.js', () => {
+ const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), fatal: vi.fn() };
+ return { default: logger, logger };
+});
+
+const { briefTaskContext } = await import('./content.js');
+
+describe('briefTaskContext', () => {
+ it("gives the brief the task's target, reasons, steps and check", () => {
+ expect(
+ briefTaskContext({
+ fromAction: {
+ actionId: 'a1',
+ task: {
+ where: 'acme.example/pricing',
+ why: 'Cited #2 until Oct 12.',
+ how: ['Add a table.', 'Update the title.'],
+ doneWhen: 'Cited again within 14 days.',
+ },
+ },
+ }),
+ ).toBe(
+ [
+ '',
+ 'From an Action Center task:',
+ '- Where: acme.example/pricing',
+ '- Why: Cited #2 until Oct 12.',
+ '- Steps: 1) Add a table. 2) Update the title.',
+ '- Done when: Cited again within 14 days.',
+ '',
+ ].join('\n'),
+ );
+ });
+
+ it('says nothing for an opportunity no task sent', () => {
+ expect(briefTaskContext({ promptText: 'x' })).toBe('');
+ expect(briefTaskContext(undefined)).toBe('');
+ });
+});
diff --git a/server/src/routes/content.js b/server/src/routes/content.js
index fbc85d0e6..856a94b2c 100644
--- a/server/src/routes/content.js
+++ b/server/src/routes/content.js
@@ -1198,6 +1198,23 @@ Rules:
- The call to action should be specific and relevant to the content type.
- Target word count should be appropriate for the content type (e.g. blog post: 1500-3000, guide: 3000-5000).`;
+/**
+ * What a brief is told about the Action Center task an opportunity was sent
+ * from (AC-004): it does what the task says, where it says, until its check
+ * is met. Empty for an opportunity that wasn't.
+ */
+export function briefTaskContext(sourceData) {
+ const task = sourceData?.fromAction?.task;
+ if (!task) return '';
+ const lines = [
+ task.where && `- Where: ${task.where}`,
+ task.why && `- Why: ${task.why}`,
+ task.how?.length && `- Steps: ${task.how.map((step, i) => `${i + 1}) ${step}`).join(' ')}`,
+ task.doneWhen && `- Done when: ${task.doneWhen}`,
+ ].filter(Boolean);
+ return lines.length ? `\nFrom an Action Center task:\n${lines.join('\n')}\n` : '';
+}
+
/**
* Generate (or fetch) an AI brief for a content opportunity.
*
@@ -1303,6 +1320,8 @@ ${targetPages.map((p) => `- ${p.title || p.url} (${p.url})`).join('\n')}
? '\nDecision: create a new page; the site has none for this need.\n'
: '';
+ const taskContext = briefTaskContext(sourceData);
+
const clusterContext = sourceData.prompts?.length
? `
Questions this content must answer (the cluster's prompts):
@@ -1330,7 +1349,7 @@ Opportunity:
- Score: ${opportunity.opportunity_score}
Related Prompt: "${promptText}"
-${clusterContext}${decisionContext}Intent: ${sourceData.intent || 'unknown'}
+${clusterContext}${decisionContext}${taskContext}Intent: ${sourceData.intent || 'unknown'}
Est. AI Volume: ${sourceData.estAiVolume || 0}/mo
Current Visibility: ${sourceData.visibilityScore || 0}%
Competitor Gap: ${sourceData.competitorGap || 0}%
diff --git a/supabase/migrations/00151_opportunity_source_action.sql b/supabase/migrations/00151_opportunity_source_action.sql
new file mode 100644
index 000000000..f4ddbd729
--- /dev/null
+++ b/supabase/migrations/00151_opportunity_source_action.sql
@@ -0,0 +1,16 @@
+-- An opportunity can come from an Action Center task (AC-004): "Send to
+-- Content" on a content task makes one, with the task's target, reasons and
+-- steps, and a link back to the action it came from.
+
+alter table public.content_opportunities
+ drop constraint if exists content_opportunities_source_check;
+alter table public.content_opportunities
+ add constraint content_opportunities_source_check
+ check (source in ('system', 'manual', 'prompt', 'action'));
+
+-- One open opportunity per task: two sends at once (two tabs, two people)
+-- make one, and the second finds it. An archived one frees the task to be
+-- sent again.
+create unique index if not exists content_opportunities_action_task_idx
+ on public.content_opportunities ((source_data -> 'fromAction' ->> 'taskId'))
+ where source = 'action' and status <> 'archived';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index d5d4728e9..3c5fcc2c0 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -19031,6 +19031,26 @@ create index if not exists actions_tasks_pending_idx
comment on column public.action_tasks.details is
'What a task carries beyond its title: where, why, how, doneWhen, type, effort and role (AC-004), and for a task sent from the Improve tab its body, platform, platformLabel and sources (PROMPT-004). A written task also records source = ''ai'' and the evidence refs it rests on.';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00151_opportunity_source_action.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- An opportunity can come from an Action Center task (AC-004): "Send to
+-- Content" on a content task makes one, with the task's target, reasons and
+-- steps, and a link back to the action it came from.
+
+alter table public.content_opportunities
+ drop constraint if exists content_opportunities_source_check;
+alter table public.content_opportunities
+ add constraint content_opportunities_source_check
+ check (source in ('system', 'manual', 'prompt', 'action'));
+
+-- One open opportunity per task: two sends at once (two tabs, two people)
+-- make one, and the second finds it. An archived one frees the task to be
+-- sent again.
+create unique index if not exists content_opportunities_action_task_idx
+ on public.content_opportunities ((source_data -> 'fromAction' ->> 'taskId'))
+ where source = 'action' and status <> 'archived';
+
-- ─────────────────────────────────────────────────────────────────────────
-- migrations/00152_insights_topic_competitors_definer.sql
-- ─────────────────────────────────────────────────────────────────────────
diff --git a/web/messages/en.json b/web/messages/en.json
index a8405f183..ccf6095be 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -968,6 +968,8 @@
"taskHow": "How",
"taskDoneWhen": "Done when",
"taskEffort": "Effort",
+ "sentToContent": "Sent to Content",
+ "sentToWebhook": "Sent to the webhook",
"item": "Item",
"volume": "Volume",
"lostPage": "Lost page",
@@ -1146,6 +1148,7 @@
"task_deleted": "Task deleted",
"task_edited": "Task edited",
"tasks_generated": "{count, plural, one {# task} other {# tasks}} written from the action's evidence",
+ "task_sent": "{to, select, content {Sent to Content} webhook {Sent to the webhook} other {Sent}}: {title}",
"task_ran": "{task} — carried out automatically ({tool})",
"task_run_failed": "{task} — the automatic attempt failed; it needs doing by hand",
"task_awaiting_approval": "{task} — waiting for your approval before it reaches outside Ansvisor",
@@ -1161,6 +1164,22 @@
"skipReasonPlaceholder": "e.g. handled elsewhere, no longer relevant",
"skipConfirm": "Skip task",
"skipCancel": "Cancel",
+ "send": {
+ "sentToContent": "Sent to Content as an opportunity",
+ "alreadyInContent": "This task is already in Content",
+ "sentToWebhook": "Sent to the webhook",
+ "timeout": "Sending took too long. Please try again.",
+ "unreachable": "Couldn't reach the server. Please try again.",
+ "unauthenticated": "Your session has ended. Please sign in again.",
+ "errors": {
+ "not_found": "This task no longer exists.",
+ "from_content": "This action came from Content, so its tasks stay here.",
+ "not_content": "Only a content task can be sent to Content.",
+ "no_title": "The task needs text before it can be sent.",
+ "no_webhook": "This brand has no active webhook. Set one up in Content → Webhook Settings.",
+ "webhook_failed": "The webhook didn't accept the task. Check its settings and try again."
+ }
+ },
"regenerate": {
"button": "Regenerate tasks",
"confirm": "Write this action's tasks again from its evidence? Done, under-way and hand-added tasks stay.",
@@ -1201,7 +1220,13 @@
"save": "Save",
"cancel": "Cancel",
"empty": "No details yet: add where to do it, how, and when it counts as done.",
- "answerSource": "AI answer"
+ "answerSource": "AI answer",
+ "sendToContent": "Send to Content",
+ "sendToWebhook": "Send to webhook",
+ "sendToWebhookAgain": "Send to webhook again",
+ "sentToContent": "Sent to Content as an opportunity ·",
+ "openInContent": "Open",
+ "sentToWebhook": "Sent to the webhook on {date}"
},
"noSignalsOpportunity": "This action was sent from Content Optimization. Its evidence is the opportunity on the Overview tab, not detection signals.",
"opportunity": {
@@ -2553,18 +2578,23 @@
"groupNoTopic": "{count, plural, one {# prompt} other {# prompts}}",
"single": "Single prompt",
"groupHint": "Built for a group of related prompts that one piece of content can answer",
- "singleHint": "Built for one prompt"
+ "singleHint": "Built for one prompt",
+ "action": "From {ref}",
+ "actionNoRef": "From an action",
+ "actionHint": "Sent from an Action Center task"
},
"source": {
"label": "Source",
"system": "System",
"manual": "Manual",
- "prompt": "Prompt"
+ "prompt": "Prompt",
+ "action": "Action"
},
"sourceHint": {
"system": "Suggested automatically as tracking data comes in",
"manual": "Created with + New",
- "prompt": "Suggested from a prompt in the prompts table"
+ "prompt": "Suggested from a prompt in the prompts table",
+ "action": "Sent from a task in the Action Center"
},
"new": "New",
"newDone": "{generated, plural, =0 {No new opportunities} one {1 opportunity created} other {# opportunities created}}{duplicates, plural, =0 {} one { · 1 duplicate skipped (not counted)} other { · # duplicates skipped (not counted)}}",
@@ -2657,6 +2687,15 @@
},
"detail": {
"backToList": "Back to Opportunities",
+ "fromTask": {
+ "title": "From a task in {ref}",
+ "titleNoRef": "From an Action Center task",
+ "where": "Where",
+ "why": "Why",
+ "how": "How",
+ "doneWhen": "Done when",
+ "effort": "Effort"
+ },
"sourceData": "Source Data",
"relatedPrompt": "Related Prompt",
"estAiVolume": "Est. AI Volume",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx
index e6f84c38c..cea0cbff3 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx
@@ -125,7 +125,7 @@ const STATUS_VALUES = [
] as const;
const IMPACT_VALUES = ['all', 'high', 'medium', 'low'] as const;
const TYPE_VALUES = ['all', 'owned', 'earned'] as const;
-const SOURCE_VALUES = ['all', 'system', 'manual', 'prompt'] as const;
+const SOURCE_VALUES = ['all', 'system', 'manual', 'prompt', 'action'] as const;
const SUGGESTED_VALUES = ['all', 'month', 'last30', 'custom'] as const;
const URL_DEFAULTS = {
status: 'all',
@@ -299,7 +299,11 @@ function OpportunityScope({ opp }: { opp: ContentOpportunity }) {
? scope.topic
? t('group', { topic: scope.topic, count: scope.count })
: t('groupNoTopic', { count: scope.count })
- : t('single');
+ : scope.kind === 'action'
+ ? scope.actionNo !== null
+ ? t('action', { ref: `AC-${scope.actionNo}` })
+ : t('actionNoRef')
+ : t('single');
return (
<span
className={cn(
@@ -308,7 +312,7 @@ function OpportunityScope({ opp }: { opp: ContentOpportunity }) {
? 'bg-violet-50 text-violet-700 ring-violet-200 dark:bg-violet-950/40 dark:text-violet-300 dark:ring-violet-900'
: 'bg-muted text-foreground/80 ring-border',
)}
- title={group ? t('groupHint') : t('singleHint')}
+ title={group ? t('groupHint') : scope.kind === 'action' ? t('actionHint') : t('singleHint')}
>
{label}
</span>
@@ -1200,13 +1204,13 @@ export default function ContentPage() {
{(value) =>
value === 'all'
? t('filters.allSources')
- : t(`source.${value as 'system' | 'manual' | 'prompt'}`)
+ : t(`source.${value as 'system' | 'manual' | 'prompt' | 'action'}`)
}
</SelectValue>
</SelectTrigger>
<SelectContent>
<SelectItem value="all">{t('filters.allSources')}</SelectItem>
- {(['system', 'manual', 'prompt'] as const).map((value) => (
+ {(['system', 'manual', 'prompt', 'action'] as const).map((value) => (
<SelectItem key={value} value={value}>
<span className="flex flex-col">
<span>{t(`source.${value}`)}</span>
diff --git a/web/src/components/action-center/action-drawer.tsx b/web/src/components/action-center/action-drawer.tsx
index 7e4807ef4..81be9de48 100644
--- a/web/src/components/action-center/action-drawer.tsx
+++ b/web/src/components/action-center/action-drawer.tsx
@@ -74,7 +74,8 @@ import { actionStory } from '@/lib/action-center/story';
import { ImproveContext } from './improve-context';
import { TopicGapContext } from './topic-gap-context';
import { TopicOpportunityContext } from './topic-opportunity-context';
-import { TaskDetailForm, TaskDetailView, TaskTypeBadge } from './task-detail';
+import { TaskDetailForm, TaskDetailView, TaskTypeBadge, type TaskSendOptions } from './task-detail';
+import { hasActiveWebhook, sendActionTask } from '@/lib/actions/action-task-send';
import { RegenerateTasks, taskWriterEnabled } from './regenerate-tasks';
import { hasTaskSpec, type TaskDetailsEdit } from '@/lib/action-center/task-details';
import { ImproveOutcomeCard } from './improve-outcome-card';
@@ -121,6 +122,23 @@ export function ActionDrawer({
const [tab, setTab] = useState<DrawerTab>('overview');
const [detail, setDetail] = useState<ActionDetail | null>(null);
const [isBusy, setIsBusy] = useState(false);
+ const tSend = useTranslations('actionCenter.actionsPage.drawer.send');
+
+ // Whether a task can go to the brand's webhook (AC-004). Best effort: no
+ // answer is no button.
+ const [webhookReady, setWebhookReady] = useState(false);
+ useEffect(() => {
+ let cancelled = false;
+ hasActiveWebhook(brandId).then(
+ (ready) => {
+ if (!cancelled) setWebhookReady(ready);
+ },
+ () => undefined,
+ );
+ return () => {
+ cancelled = true;
+ };
+ }, [brandId]);
// Traceability: a signal card jumps to the Signals page with that signal's
// drawer open — the evidence must be one click from the action it created.
@@ -236,6 +254,35 @@ export function ActionDrawer({
? (action.payload.pages as unknown[]).filter((u): u is string => typeof u === 'string')
: [];
+ /** Send a task to Content or the webhook (AC-004), then reload to show where it went. */
+ const sendTask = async (taskId: string, text: string, to: 'content' | 'webhook') => {
+ setIsBusy(true);
+ try {
+ const result = await sendActionTask(taskId, to, text);
+ if ('error' in result) {
+ toast.error(
+ result.error !== 'server'
+ ? tSend(result.error)
+ : result.code && SEND_ERRORS.includes(result.code)
+ ? tSend(`errors.${result.code}`)
+ : result.message,
+ );
+ return;
+ }
+ toast.success(
+ result.to === 'webhook'
+ ? tSend('sentToWebhook')
+ : result.created
+ ? tSend('sentToContent')
+ : tSend('alreadyInContent'),
+ );
+ await load();
+ onChanged();
+ } finally {
+ setIsBusy(false);
+ }
+ };
+
/** Runs a change, then reloads; false when the change failed (and said so). */
const mutate = async (fn: () => Promise<void>): Promise<boolean> => {
setIsBusy(true);
@@ -538,6 +585,12 @@ export function ActionDrawer({
mutate(() => updateTaskDetails(brandId, action.id, task.id, edit))
}
onDelete={() => void mutate(() => deleteTask(brandId, action.id, task.id))}
+ send={{
+ // A content task, unless the action itself came from Content.
+ content: task.details?.type === 'content' && !opportunityId,
+ webhook: webhookReady,
+ onSend: (to) => void sendTask(task.id, taskText(task, tTasks), to),
+ }}
/>
))}
</div>
@@ -626,6 +679,16 @@ export function ActionDrawer({
type TaskTranslator = (key: string, values?: Record<string, string | number>) => string;
+/** Server reasons a send can fail for, worded in actionsPage.drawer.send.errors. */
+const SEND_ERRORS = [
+ 'not_found',
+ 'from_content',
+ 'not_content',
+ 'no_title',
+ 'no_webhook',
+ 'webhook_failed',
+];
+
/**
* One task: its text, type and status, opening onto its details (AC-004).
*
@@ -641,6 +704,7 @@ function TaskRow({
onStatusChange,
onEdit,
onDelete,
+ send,
}: {
task: ActionTask;
text: string;
@@ -651,6 +715,7 @@ function TaskRow({
/** Resolves true once saved; false when the save failed. */
onEdit: (edit: TaskDetailsEdit & { title: string | null }) => Promise<boolean>;
onDelete: () => void;
+ send: TaskSendOptions;
}) {
// A task sent from the Improve tab opens on its suggestion, as it always
// showed it; the rest open on a click.
@@ -748,6 +813,7 @@ function TaskRow({
details={task.details}
disabled={disabled || skipDraft !== null}
onEdit={() => setEditing(true)}
+ send={send}
/>
))}
diff --git a/web/src/components/action-center/action-export-buttons.tsx b/web/src/components/action-center/action-export-buttons.tsx
index eb932af1e..e08ba091d 100644
--- a/web/src/components/action-center/action-export-buttons.tsx
+++ b/web/src/components/action-center/action-export-buttons.tsx
@@ -237,6 +237,7 @@ export function ActionExportButtons({
event: (event) => actionEventText(event, t, tTasks),
skipped: (reason) => tExport('skipped', { reason }),
taskType: (type) => tTaskTypes(type),
+ taskSent: (to) => tExport(to === 'content' ? 'sentToContent' : 'sentToWebhook'),
answerSource: tExport('answerSource'),
},
{ origin, timeZone: viewerTimeZone() },
diff --git a/web/src/components/action-center/task-detail.test.tsx b/web/src/components/action-center/task-detail.test.tsx
index 6f2a3d44e..4f8a06156 100644
--- a/web/src/components/action-center/task-detail.test.tsx
+++ b/web/src/components/action-center/task-detail.test.tsx
@@ -6,6 +6,14 @@ import messages from '../../../messages/en.json';
import { parseTaskDetails } from '@/lib/action-center/task-details';
import { TaskDetailForm, TaskDetailView, TaskTypeBadge } from './task-detail';
+vi.mock('@/i18n/navigation', () => ({
+ Link: ({ href, children, ...rest }: { href: string; children: React.ReactNode }) => (
+ <a href={href} {...rest}>
+ {children}
+ </a>
+ ),
+}));
+
(
globalThis as typeof globalThis & {
IS_REACT_ACT_ENVIRONMENT: boolean;
@@ -178,3 +186,53 @@ describe('TaskTypeBadge', () => {
expect(container.textContent).toBe('');
});
});
+
+describe('sending a task (AC-004)', () => {
+ const send = (over = {}) => ({ content: true, webhook: true, onSend: vi.fn(), ...over });
+
+ it('offers Content for a content task and the webhook when the brand has one', () => {
+ const options = send();
+ render(<TaskDetailView details={details} disabled={false} onEdit={() => {}} send={options} />);
+ act(() => button('Send to Content').click());
+ act(() => button('Send to webhook').click());
+ expect(options.onSend.mock.calls).toEqual([['content'], ['webhook']]);
+ });
+
+ it('shows where it went, and links to the opportunity instead of sending again', () => {
+ render(
+ <TaskDetailView
+ details={parseTaskDetails({
+ where: '/pricing',
+ type: 'content',
+ sent: {
+ content: { opportunityId: 'o1', at: '2026-10-16T10:00:00Z' },
+ webhook: { at: '2026-10-16T11:00:00Z' },
+ },
+ })}
+ disabled={false}
+ onEdit={() => {}}
+ send={send()}
+ />,
+ );
+ expect(container.querySelector('a')?.getAttribute('href')).toBe(
+ '/dashboard/content?opportunity=o1',
+ );
+ expect(container.textContent).toContain('Sent to the webhook on Oct 16');
+ expect([...container.querySelectorAll('button')].map((b) => b.textContent)).toEqual([
+ 'Edit',
+ 'Send to webhook again',
+ ]);
+ });
+
+ it('offers nothing it cannot do', () => {
+ render(
+ <TaskDetailView
+ details={details}
+ disabled={false}
+ onEdit={() => {}}
+ send={send({ content: false, webhook: false })}
+ />,
+ );
+ expect([...container.querySelectorAll('button')].map((b) => b.textContent)).toEqual(['Edit']);
+ });
+});
diff --git a/web/src/components/action-center/task-detail.tsx b/web/src/components/action-center/task-detail.tsx
index 503dafd25..292c1a4f3 100644
--- a/web/src/components/action-center/task-detail.tsx
+++ b/web/src/components/action-center/task-detail.tsx
@@ -1,7 +1,9 @@
'use client';
import { useId, useState } from 'react';
-import { useTranslations } from 'next-intl';
+import { useFormatter, useTranslations } from 'next-intl';
+import { ArrowUpRight } from 'lucide-react';
+import { Link } from '@/i18n/navigation';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
@@ -34,22 +36,36 @@ export function TaskTypeBadge({ type }: { type: ActionTaskDetails['type'] }) {
);
}
+/** Where a task can be sent from the drawer (AC-004), and the sending. */
+export interface TaskSendOptions {
+ /** A content task, on an action that did not come from Content. */
+ content: boolean;
+ /** The brand has an active webhook. */
+ webhook: boolean;
+ onSend: (to: 'content' | 'webhook') => void;
+}
+
/**
* An opened task (AC-004): where to do it, why, how, when it counts as done
- * and what it takes, and for a task sent from the Improve tab its body,
- * platform and evidence (PROMPT-004).
+ * and what it takes, where it was sent, and for a task sent from the Improve
+ * tab its body, platform and evidence (PROMPT-004).
*/
export function TaskDetailView({
details,
disabled,
onEdit,
+ send,
}: {
details: ActionTaskDetails | null;
disabled: boolean;
onEdit: () => void;
+ send?: TaskSendOptions;
}) {
const t = useTranslations('actionCenter.actionsPage.drawer.task');
+ const format = useFormatter();
const effort = [details?.effort, details?.role].filter(Boolean).join(' · ');
+ const sentContent = details?.sent.content ?? null;
+ const sentWebhook = details?.sent.webhook ?? null;
return (
<div className="space-y-2 border-t px-4 py-3">
@@ -96,16 +112,70 @@ export function TaskDetailView({
) : (
!details && <p className="text-xs text-muted-foreground">{t('empty')}</p>
)}
- <Button
- type="button"
- variant="outline"
- size="sm"
- disabled={disabled}
- onClick={onEdit}
- className="h-7 text-xs"
- >
- {t('edit')}
- </Button>
+ {(sentContent || sentWebhook) && (
+ <div className="space-y-0.5 text-xs text-muted-foreground">
+ {sentContent && (
+ <p className="flex items-center gap-1">
+ {t('sentToContent')}
+ <Link
+ href={`/dashboard/content?opportunity=${sentContent.opportunityId}`}
+ className="inline-flex items-center gap-0.5 font-medium text-foreground underline-offset-2 hover:underline"
+ >
+ {t('openInContent')}
+ <ArrowUpRight className="h-3 w-3" />
+ </Link>
+ </p>
+ )}
+ {sentWebhook && (
+ <p>
+ {t('sentToWebhook', {
+ date: format.dateTime(new Date(sentWebhook.at), {
+ month: 'short',
+ day: 'numeric',
+ hour: 'numeric',
+ minute: '2-digit',
+ }),
+ })}
+ </p>
+ )}
+ </div>
+ )}
+ <div className="flex flex-wrap gap-2">
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={disabled}
+ onClick={onEdit}
+ className="h-7 text-xs"
+ >
+ {t('edit')}
+ </Button>
+ {send?.content && !sentContent && (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={disabled}
+ onClick={() => send.onSend('content')}
+ className="h-7 text-xs"
+ >
+ {t('sendToContent')}
+ </Button>
+ )}
+ {send?.webhook && (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={disabled}
+ onClick={() => send.onSend('webhook')}
+ className="h-7 text-xs"
+ >
+ {sentWebhook ? t('sendToWebhookAgain') : t('sendToWebhook')}
+ </Button>
+ )}
+ </div>
</div>
);
}
diff --git a/web/src/components/content/opportunity-detail.tsx b/web/src/components/content/opportunity-detail.tsx
index 2d20797a9..bf05bbd8f 100644
--- a/web/src/components/content/opportunity-detail.tsx
+++ b/web/src/components/content/opportunity-detail.tsx
@@ -410,25 +410,32 @@ export function OpportunityDetail({
<Badge variant="outline" className="text-xs tabular-nums">
Score: {Math.round(opportunity.opportunityScore)}
</Badge>
- <Button
- type="button"
- variant="ghost"
- size="xs"
- className="ml-auto gap-1 text-xs text-muted-foreground"
- onClick={() => setAlternativeOpen(true)}
- disabled={alternativeRunning}
- title={t('alternative.hint')}
- >
- {alternativeRunning ? (
- <Loader2 className="h-3 w-3 animate-spin" />
- ) : (
- <RefreshCw className="h-3 w-3" />
- )}
- {alternativeRunning ? t('alternative.running') : t('alternative.button')}
- </Button>
+ {/* Another angle is written from a cluster or a prompt; a task sent
+ from the Action Center (AC-004) has neither. */}
+ {opportunity.source !== 'action' && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="xs"
+ className="ml-auto gap-1 text-xs text-muted-foreground"
+ onClick={() => setAlternativeOpen(true)}
+ disabled={alternativeRunning}
+ title={t('alternative.hint')}
+ >
+ {alternativeRunning ? (
+ <Loader2 className="h-3 w-3 animate-spin" />
+ ) : (
+ <RefreshCw className="h-3 w-3" />
+ )}
+ {alternativeRunning ? t('alternative.running') : t('alternative.button')}
+ </Button>
+ )}
{/* The UI's language, not the browser's: an English page showed "25 Eyl". */}
<span
- className="text-xs text-muted-foreground flex items-center gap-1.5"
+ className={cn(
+ 'text-xs text-muted-foreground flex items-center gap-1.5',
+ opportunity.source === 'action' && 'ml-auto',
+ )}
title={suggestedDate(opportunity.createdAt, locale).full}
>
<Clock className="h-3.5 w-3.5" />
@@ -592,106 +599,112 @@ export function OpportunityDetail({
)}
<div className="grid grid-cols-1 gap-4 @3xl:grid-cols-2">
- <Card>
- <CardHeader className="pb-2">
- <CardTitle className="text-sm font-medium">{t('detail.sourceData')}</CardTitle>
- </CardHeader>
- <CardContent className="space-y-3">
- {sd.promptText && !opportunity.clusterId && (
- <StatCard icon={Search} label={t('detail.relatedPrompt')} value={sd.promptText} />
- )}
-
- <div className="grid grid-cols-2 gap-3">
- {sd.estAiVolume !== undefined && (
- <StatCard
- icon={TrendingUp}
- label={t('detail.estAiVolume')}
- value={`~${sd.estAiVolume.toLocaleString()}/mo`}
- />
- )}
- {sd.visibilityScore !== undefined && (
- <StatCard
- icon={Eye}
- label={t('detail.visibility')}
- value={`${Math.round(sd.visibilityScore)}%`}
- />
- )}
- {sd.competitorGap !== undefined && (
- <StatCard
- icon={Users}
- label={t('detail.competitorGap')}
- value={`${sd.competitorGap > 0 ? '+' : ''}${Math.round(sd.competitorGap)}%`}
- />
- )}
- {sd.topCompetitorVisibility !== undefined && (
- <StatCard
- icon={Users}
- label={t('detail.topCompetitor')}
- value={`${Math.round(sd.topCompetitorVisibility)}%`}
- />
- )}
- {sd.intent && (
- <StatCard
- icon={Tag}
- label={t('detail.intent')}
- value={INTENT_LABELS[sd.intent] || sd.intent}
- />
+ {/* Sent from an Action Center task (AC-004): what the task says to do,
+ where a generated one shows the data it was built from. */}
+ {sd.fromAction?.task ? (
+ <FromTaskCard from={sd.fromAction} />
+ ) : (
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm font-medium">{t('detail.sourceData')}</CardTitle>
+ </CardHeader>
+ <CardContent className="space-y-3">
+ {sd.promptText && !opportunity.clusterId && (
+ <StatCard icon={Search} label={t('detail.relatedPrompt')} value={sd.promptText} />
)}
- </div>
- {sd.keywords && sd.keywords.length > 0 && (
- <div>
- <p className="text-xs text-muted-foreground mb-1.5">{t('detail.keywords')}</p>
- <div className="flex flex-wrap gap-1">
- {sd.keywords.map((kw) => (
- <Badge key={kw} variant="outline" className="text-xs">
- {kw}
- </Badge>
- ))}
- </div>
+ <div className="grid grid-cols-2 gap-3">
+ {sd.estAiVolume !== undefined && (
+ <StatCard
+ icon={TrendingUp}
+ label={t('detail.estAiVolume')}
+ value={`~${sd.estAiVolume.toLocaleString()}/mo`}
+ />
+ )}
+ {sd.visibilityScore !== undefined && (
+ <StatCard
+ icon={Eye}
+ label={t('detail.visibility')}
+ value={`${Math.round(sd.visibilityScore)}%`}
+ />
+ )}
+ {sd.competitorGap !== undefined && (
+ <StatCard
+ icon={Users}
+ label={t('detail.competitorGap')}
+ value={`${sd.competitorGap > 0 ? '+' : ''}${Math.round(sd.competitorGap)}%`}
+ />
+ )}
+ {sd.topCompetitorVisibility !== undefined && (
+ <StatCard
+ icon={Users}
+ label={t('detail.topCompetitor')}
+ value={`${Math.round(sd.topCompetitorVisibility)}%`}
+ />
+ )}
+ {sd.intent && (
+ <StatCard
+ icon={Tag}
+ label={t('detail.intent')}
+ value={INTENT_LABELS[sd.intent] || sd.intent}
+ />
+ )}
</div>
- )}
- {fanoutQueries.length > 0 && (
- <div>
- <p className="text-xs text-muted-foreground mb-1.5">Observed fan-out queries</p>
- <div className="flex flex-wrap gap-1">
- {fanoutQueries.map((sq) => (
- <Badge
- key={sq.query}
- variant="outline"
- className="text-xs border-violet-500/30 bg-violet-500/10 text-violet-600 dark:text-violet-400 gap-1"
- title={`Searched ${sq.timesSearched}× by answer engines`}
- >
- <Search className="h-2.5 w-2.5 shrink-0" />
- {sq.query}
- <span className="opacity-60 tabular-nums">×{sq.timesSearched}</span>
- </Badge>
- ))}
+ {sd.keywords && sd.keywords.length > 0 && (
+ <div>
+ <p className="text-xs text-muted-foreground mb-1.5">{t('detail.keywords')}</p>
+ <div className="flex flex-wrap gap-1">
+ {sd.keywords.map((kw) => (
+ <Badge key={kw} variant="outline" className="text-xs">
+ {kw}
+ </Badge>
+ ))}
+ </div>
</div>
- </div>
- )}
+ )}
- {sd.competitorsCited && sd.competitorsCited.length > 0 && (
- <div>
- <p className="text-xs text-muted-foreground mb-1.5">
- {t('detail.competitorsCited')}
- </p>
- <div className="flex flex-wrap gap-1">
- {sd.competitorsCited.map((comp) => (
- <Badge
- key={comp}
- variant="outline"
- className="text-xs border-amber-500/30 bg-amber-500/10 text-amber-600 dark:text-amber-400"
- >
- {comp}
- </Badge>
- ))}
+ {fanoutQueries.length > 0 && (
+ <div>
+ <p className="text-xs text-muted-foreground mb-1.5">Observed fan-out queries</p>
+ <div className="flex flex-wrap gap-1">
+ {fanoutQueries.map((sq) => (
+ <Badge
+ key={sq.query}
+ variant="outline"
+ className="text-xs border-violet-500/30 bg-violet-500/10 text-violet-600 dark:text-violet-400 gap-1"
+ title={`Searched ${sq.timesSearched}× by answer engines`}
+ >
+ <Search className="h-2.5 w-2.5 shrink-0" />
+ {sq.query}
+ <span className="opacity-60 tabular-nums">×{sq.timesSearched}</span>
+ </Badge>
+ ))}
+ </div>
</div>
- </div>
- )}
- </CardContent>
- </Card>
+ )}
+
+ {sd.competitorsCited && sd.competitorsCited.length > 0 && (
+ <div>
+ <p className="text-xs text-muted-foreground mb-1.5">
+ {t('detail.competitorsCited')}
+ </p>
+ <div className="flex flex-wrap gap-1">
+ {sd.competitorsCited.map((comp) => (
+ <Badge
+ key={comp}
+ variant="outline"
+ className="text-xs border-amber-500/30 bg-amber-500/10 text-amber-600 dark:text-amber-400"
+ >
+ {comp}
+ </Badge>
+ ))}
+ </div>
+ </div>
+ )}
+ </CardContent>
+ </Card>
+ )}
{brief ? (
<Card>
@@ -841,3 +854,63 @@ export function OpportunityDetail({
</div>
);
}
+
+/** The Action Center task an opportunity was sent from (AC-004): where, why, how, done when. */
+function FromTaskCard({
+ from,
+}: {
+ from: NonNullable<ContentOpportunity['sourceData']['fromAction']>;
+}) {
+ const t = useTranslations('content.detail.fromTask');
+ const task = from.task ?? {};
+ const effort = [task.effort, task.role].filter(Boolean).join(' · ');
+ return (
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm font-medium">
+ {from.actionNo !== null ? t('title', { ref: `AC-${from.actionNo}` }) : t('titleNoRef')}
+ </CardTitle>
+ </CardHeader>
+ <CardContent>
+ <dl className="grid grid-cols-[6rem_1fr] gap-x-3 gap-y-1.5 text-sm">
+ {task.where && (
+ <>
+ <dt className="text-muted-foreground">{t('where')}</dt>
+ <dd className="min-w-0 break-words">{task.where}</dd>
+ </>
+ )}
+ {task.why && (
+ <>
+ <dt className="text-muted-foreground">{t('why')}</dt>
+ <dd className="min-w-0 break-words">{task.why}</dd>
+ </>
+ )}
+ {task.how && task.how.length > 0 && (
+ <>
+ <dt className="text-muted-foreground">{t('how')}</dt>
+ <dd>
+ <ol className="list-decimal space-y-0.5 pl-4">
+ {task.how.map((step, i) => (
+ <li key={i}>{step}</li>
+ ))}
+ </ol>
+ </dd>
+ </>
+ )}
+ {task.doneWhen && (
+ <>
+ <dt className="text-muted-foreground">{t('doneWhen')}</dt>
+ <dd className="min-w-0 break-words">{task.doneWhen}</dd>
+ </>
+ )}
+ {effort && (
+ <>
+ <dt className="text-muted-foreground">{t('effort')}</dt>
+ <dd>{effort}</dd>
+ </>
+ )}
+ </dl>
+ </CardContent>
+ </Card>
+ );
+}
diff --git a/web/src/lib/action-center/display.test.ts b/web/src/lib/action-center/display.test.ts
index 3124344d6..651e5ecf4 100644
--- a/web/src/lib/action-center/display.test.ts
+++ b/web/src/lib/action-center/display.test.ts
@@ -239,6 +239,19 @@ describe('actionEventText', () => {
createdAt: '2026-10-16T00:00:00Z',
});
+ it('names a task sent onward and where it went', () => {
+ expect(
+ actionEventText(
+ event('task_sent', { to: 'content', title: 'Add a table to /pricing' }),
+ tPage,
+ t,
+ ),
+ ).toBe('Sent to Content: Add a table to /pricing');
+ expect(actionEventText(event('task_sent', { to: 'webhook', title: 'x' }), tPage, t)).toBe(
+ 'Sent to the webhook: x',
+ );
+ });
+
it('reads the 30-day position result with its counts', () => {
expect(
actionEventText(event('position_outcome_recorded', { improved: 2, measurable: 3 }), tPage, t),
diff --git a/web/src/lib/action-center/display.ts b/web/src/lib/action-center/display.ts
index 8f20da4f2..384483116 100644
--- a/web/src/lib/action-center/display.ts
+++ b/web/src/lib/action-center/display.ts
@@ -151,8 +151,8 @@ export function actionEventText(
tool: String(event.data.tool ?? ''),
improved: Number(event.data.improved ?? 0),
measurable: Number(event.data.measurable ?? 0),
- // A task someone added or renamed is named in their own words, as they
- // typed it.
+ // A task someone added, renamed or sent is named in its own words, as it
+ // was typed (AC-004).
title: String(event.data.title ?? ''),
// The validation sweep's verdict once the action closed: improved,
// declined, and so on.
diff --git a/web/src/lib/action-center/export.test.ts b/web/src/lib/action-center/export.test.ts
index 9a3fd273c..f37dec44c 100644
--- a/web/src/lib/action-center/export.test.ts
+++ b/web/src/lib/action-center/export.test.ts
@@ -132,6 +132,7 @@ const texts: ExportTexts = {
event: () => 'Action created',
skipped: (reason) => `Skipped: ${reason}`,
taskType: (type) => ({ content: 'Content', outreach: 'Outreach' })[type] ?? type,
+ taskSent: (to) => (to === 'content' ? 'Sent to Content' : 'Sent to the webhook'),
answerSource: 'AI answer',
};
@@ -344,6 +345,7 @@ describe('a task with AC-004 fields', () => {
type: 'content',
effort: '~2h',
role: 'Content writer',
+ sent: { content: null, webhook: null },
},
},
],
diff --git a/web/src/lib/action-center/export.ts b/web/src/lib/action-center/export.ts
index b3466e076..3e333c8a4 100644
--- a/web/src/lib/action-center/export.ts
+++ b/web/src/lib/action-center/export.ts
@@ -137,6 +137,8 @@ export interface ExportTexts {
skipped: (reason: string) => string;
/** "Content", "On-page"…, for a task's type (AC-004). */
taskType: (type: string) => string;
+ /** "Sent to Content", "Sent to the webhook" (AC-004). */
+ taskSent: (to: 'content' | 'webhook') => string;
/** What an AI answer a task rests on is called; its id means nothing outside. */
answerSource: string;
}
@@ -193,6 +195,8 @@ export function buildActionExport(
),
]
: [];
+ if (d?.sent?.content) details.push(texts.taskSent('content'));
+ if (d?.sent?.webhook) details.push(texts.taskSent('webhook'));
if (task.skipReason) details.push(texts.skipped(task.skipReason));
return {
number: i + 1,
diff --git a/web/src/lib/action-center/task-details.test.ts b/web/src/lib/action-center/task-details.test.ts
index ff243ee74..c395a16a4 100644
--- a/web/src/lib/action-center/task-details.test.ts
+++ b/web/src/lib/action-center/task-details.test.ts
@@ -18,6 +18,7 @@ const empty = {
type: null,
effort: null,
role: null,
+ sent: { content: null, webhook: null },
};
describe('parseTaskDetails', () => {
@@ -147,3 +148,26 @@ describe('isTaskDetailsEdit', () => {
expect(isTaskDetailsEdit({ ...edit, type: 'marketing' })).toBe(false);
});
});
+
+describe('where a task was sent', () => {
+ it('reads the opportunity it became and when it went to the webhook', () => {
+ expect(
+ parseTaskDetails({
+ where: '/pricing',
+ sent: {
+ content: { opportunityId: 'o1', at: '2026-10-16T10:00:00Z' },
+ webhook: { at: '2026-10-16T11:00:00Z', delivered: 1, failed: 0 },
+ },
+ })?.sent,
+ ).toEqual({
+ content: { opportunityId: 'o1', at: '2026-10-16T10:00:00Z' },
+ webhook: { at: '2026-10-16T11:00:00Z' },
+ });
+ });
+
+ it('ignores a malformed record', () => {
+ expect(
+ parseTaskDetails({ where: '/pricing', sent: { content: {}, webhook: 'x' } })?.sent,
+ ).toEqual({ content: null, webhook: null });
+ });
+});
diff --git a/web/src/lib/action-center/task-details.ts b/web/src/lib/action-center/task-details.ts
index 2f3c02a34..0d4ff759a 100644
--- a/web/src/lib/action-center/task-details.ts
+++ b/web/src/lib/action-center/task-details.ts
@@ -31,6 +31,13 @@ export interface ActionTaskDetails {
effort: string | null;
/** Who would do it, e.g. "Content writer". */
role: string | null;
+ /** Where the task was sent (AC-004): the Content opportunity it became, the webhook. */
+ sent: TaskSent;
+}
+
+export interface TaskSent {
+ content: { opportunityId: string; at: string | null } | null;
+ webhook: { at: string } | null;
}
/** The fields a person edits in the drawer. */
@@ -69,6 +76,9 @@ export function isTaskType(value: unknown): value is TaskType {
export function parseTaskDetails(raw: unknown): ActionTaskDetails | null {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
const r = raw as Record<string, unknown>;
+ const sent = (r.sent && typeof r.sent === 'object' ? r.sent : {}) as Record<string, unknown>;
+ const content = (sent.content ?? {}) as Record<string, unknown>;
+ const webhook = (sent.webhook ?? {}) as Record<string, unknown>;
const details: ActionTaskDetails = {
body: text(r.body),
platform: text(r.platform),
@@ -88,6 +98,12 @@ export function parseTaskDetails(raw: unknown): ActionTaskDetails | null {
type: isTaskType(r.type) ? r.type : null,
effort: text(r.effort),
role: text(r.role),
+ sent: {
+ content: text(content.opportunityId)
+ ? { opportunityId: text(content.opportunityId)!, at: text(content.at) }
+ : null,
+ webhook: text(webhook.at) ? { at: text(webhook.at)! } : null,
+ },
};
return hasTaskDetails(details) ? details : null;
}
@@ -98,6 +114,8 @@ export function hasTaskDetails(details: ActionTaskDetails): boolean {
details.body !== null ||
details.platformLabel !== null ||
details.sources.length > 0 ||
+ details.sent.content !== null ||
+ details.sent.webhook !== null ||
hasTaskSpec(details)
);
}
diff --git a/web/src/lib/actions/action-task-send.test.ts b/web/src/lib/actions/action-task-send.test.ts
new file mode 100644
index 000000000..efa637bd0
--- /dev/null
+++ b/web/src/lib/actions/action-task-send.test.ts
@@ -0,0 +1,78 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+let configs: { id: string }[] = [];
+let filters: [string, unknown][] = [];
+let selected = '';
+vi.mock('@/lib/supabase/server', () => ({
+ createClient: async () => ({
+ auth: { getSession: async () => ({ data: { session: { access_token: 'token' } } }) },
+ from: () => {
+ const chain = {
+ select: (columns: string) => ((selected = columns), chain),
+ eq: (column: string, value: unknown) => (filters.push([column, value]), chain),
+ limit: async () => ({ data: configs, error: null }),
+ };
+ return chain;
+ },
+ }),
+}));
+vi.mock('@/config/api', () => ({ API_BASE_URL: 'https://api.example' }));
+
+const { hasActiveWebhook, sendActionTask } = await import('./action-task-send');
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ configs = [];
+ filters = [];
+});
+
+describe('hasActiveWebhook', () => {
+ it('asks only whether an active one exists, never for its secret', async () => {
+ configs = [{ id: 'w1' }];
+ expect(await hasActiveWebhook('b1')).toBe(true);
+ expect(selected).toBe('id');
+ expect(filters).toEqual([
+ ['brand_id', 'b1'],
+ ['is_active', true],
+ ]);
+ configs = [];
+ expect(await hasActiveWebhook('b1')).toBe(false);
+ });
+});
+
+describe('sendActionTask', () => {
+ it('posts where to send it and the text the drawer shows', async () => {
+ const fetch = vi.fn(
+ async () => new Response(JSON.stringify({ opportunityId: 'o1', created: true })),
+ );
+ vi.stubGlobal('fetch', fetch);
+ expect(await sendActionTask('t1', 'content', 'Add a table to /pricing')).toEqual({
+ to: 'content',
+ opportunityId: 'o1',
+ created: true,
+ });
+ const [url, init] = fetch.mock.calls[0] as unknown as [string, RequestInit];
+ expect(url).toBe('https://api.example/api/action-center/tasks/t1/send');
+ expect(JSON.parse(String(init.body))).toEqual({
+ to: 'content',
+ title: 'Add a table to /pricing',
+ });
+ });
+
+ it("returns the server's reason as a code", async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(
+ async () =>
+ new Response(JSON.stringify({ error: 'No webhook', code: 'no_webhook' }), {
+ status: 409,
+ }),
+ ),
+ );
+ expect(await sendActionTask('t1', 'webhook', 'x')).toEqual({
+ error: 'server',
+ code: 'no_webhook',
+ message: 'No webhook',
+ });
+ });
+});
diff --git a/web/src/lib/actions/action-task-send.ts b/web/src/lib/actions/action-task-send.ts
new file mode 100644
index 000000000..6430d438a
--- /dev/null
+++ b/web/src/lib/actions/action-task-send.ts
@@ -0,0 +1,76 @@
+'use server';
+
+import { createClient } from '@/lib/supabase/server';
+import { API_BASE_URL } from '@/config/api';
+
+/**
+ * Whether the brand has an active webhook to send a task to (AC-004). Reads
+ * only that: the drawer has no business with the URL or the secret.
+ */
+export async function hasActiveWebhook(brandId: string): Promise<boolean> {
+ const supabase = await createClient();
+ const { data, error } = await supabase
+ .from('webhook_configs')
+ .select('id')
+ .eq('brand_id', brandId)
+ .eq('is_active', true)
+ .limit(1);
+ if (error) return false;
+ return (data ?? []).length > 0;
+}
+
+/**
+ * What sending a task came to. A failure comes back as a value, so the drawer
+ * can word the server's reason (`code`) — not a content task, no webhook, the
+ * webhook refused it — instead of the masked production digest.
+ */
+export type SendTaskResult =
+ | { to: 'content'; opportunityId: string; created: boolean }
+ | { to: 'webhook'; delivered: number; failed: number }
+ | { error: 'server'; code: string | null; message: string }
+ | { error: 'timeout' | 'unreachable' | 'unauthenticated' };
+
+/**
+ * Send a task to Content as an opportunity, or to the brand's webhook.
+ * `title` is the task's text as the drawer shows it, for a library task.
+ */
+export async function sendActionTask(
+ taskId: string,
+ to: 'content' | 'webhook',
+ title: string,
+): Promise<SendTaskResult> {
+ const supabase = await createClient();
+ const {
+ data: { session },
+ } = await supabase.auth.getSession();
+ if (!session) return { error: 'unauthenticated' };
+
+ try {
+ const res = await fetch(`${API_BASE_URL}/api/action-center/tasks/${taskId}/send`, {
+ method: 'POST',
+ headers: {
+ Authorization: `Bearer ${session.access_token}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({ to, title }),
+ cache: 'no-store',
+ // The server gives each active webhook 15 s, one after another.
+ signal: AbortSignal.timeout(75_000),
+ });
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ return {
+ error: 'server',
+ code: typeof data.code === 'string' ? data.code : null,
+ message: data.error || `Server error: ${res.status}`,
+ };
+ }
+ return to === 'content'
+ ? { to, opportunityId: String(data.opportunityId), created: Boolean(data.created) }
+ : { to, delivered: Number(data.delivered ?? 0), failed: Number(data.failed ?? 0) };
+ } catch (err) {
+ return {
+ error: err instanceof Error && err.name === 'TimeoutError' ? 'timeout' : 'unreachable',
+ };
+ }
+}
diff --git a/web/src/lib/content/opportunity-list.test.ts b/web/src/lib/content/opportunity-list.test.ts
index 2e8fd3cc6..539c4d07a 100644
--- a/web/src/lib/content/opportunity-list.test.ts
+++ b/web/src/lib/content/opportunity-list.test.ts
@@ -34,3 +34,14 @@ describe('Content Opportunities list', () => {
});
});
});
+
+describe('an opportunity sent from an action task (AC-004)', () => {
+ it('reads as from that action, not as a single prompt', () => {
+ expect(
+ opportunityScope({
+ clusterId: null,
+ sourceData: { fromAction: { actionId: 'a1', actionNo: 12, taskId: 't1' } },
+ }),
+ ).toEqual({ kind: 'action', actionNo: 12 });
+ });
+});
diff --git a/web/src/lib/content/opportunity-list.ts b/web/src/lib/content/opportunity-list.ts
index 02d8ecef6..c9d00c0af 100644
--- a/web/src/lib/content/opportunity-list.ts
+++ b/web/src/lib/content/opportunity-list.ts
@@ -11,15 +11,19 @@ export const DEFAULT_OPPORTUNITY_SORT: OpportunitySort = OPPORTUNITY_SORTS[0];
/**
* What an opportunity was built for: a group of related prompts in a topic
- * (cluster opportunities, #857), or a single prompt (the older generator).
+ * (cluster opportunities, #857), a single prompt (the older generator), or
+ * an Action Center task sent to Content (AC-004).
*/
export type OpportunityScope =
| { kind: 'group'; count: number; topic: string | null }
- | { kind: 'single' };
+ | { kind: 'single' }
+ | { kind: 'action'; actionNo: number | null };
export function opportunityScope(
opp: Pick<ContentOpportunity, 'clusterId' | 'sourceData'>,
): OpportunityScope {
+ const from = opp.sourceData?.fromAction;
+ if (from) return { kind: 'action', actionNo: from.actionNo ?? null };
if (!opp.clusterId) return { kind: 'single' };
return {
kind: 'group',
diff --git a/web/src/lib/content/opportunity-markdown.test.ts b/web/src/lib/content/opportunity-markdown.test.ts
index 489a14792..bd9033a1f 100644
--- a/web/src/lib/content/opportunity-markdown.test.ts
+++ b/web/src/lib/content/opportunity-markdown.test.ts
@@ -100,3 +100,41 @@ describe('opportunityToMarkdown', () => {
expect(md).not.toContain('Decision:');
});
});
+
+describe('an opportunity sent from an action task (AC-004)', () => {
+ it("copies the task's where, why, steps and check", () => {
+ const md = opportunityToMarkdown(
+ {
+ ...base,
+ sourceData: {
+ fromAction: {
+ actionId: 'a1',
+ actionNo: 29,
+ taskId: 't1',
+ task: {
+ where: 'acme.example/pricing',
+ why: 'Cited #2 until Oct 12.',
+ how: ['Add a table.', 'Update the title.'],
+ doneWhen: 'Cited again within 14 days.',
+ effort: '~2h',
+ role: 'Content writer',
+ },
+ },
+ },
+ },
+ null,
+ );
+ expect(md).toContain(
+ [
+ '## From a task in AC-29',
+ '',
+ '- Where: acme.example/pricing',
+ '- Why: Cited #2 until Oct 12.',
+ '1. Add a table.',
+ '2. Update the title.',
+ '- Done when: Cited again within 14 days.',
+ '- Effort: ~2h · Content writer',
+ ].join('\n'),
+ );
+ });
+});
diff --git a/web/src/lib/content/opportunity-markdown.ts b/web/src/lib/content/opportunity-markdown.ts
index 4f5602291..a4fca7512 100644
--- a/web/src/lib/content/opportunity-markdown.ts
+++ b/web/src/lib/content/opportunity-markdown.ts
@@ -40,6 +40,24 @@ export function opportunityToMarkdown(
.join('\n'),
);
+ // Sent from an Action Center task (AC-004): what the task says to do.
+ const task = sd.fromAction?.task;
+ parts.push(
+ section(
+ sd.fromAction?.actionNo != null
+ ? `From a task in AC-${sd.fromAction.actionNo}`
+ : 'From an Action Center task',
+ [
+ task?.where && `- Where: ${task.where}`,
+ task?.why && `- Why: ${task.why}`,
+ ...(task?.how ?? []).map((step, i) => `${i + 1}. ${step}`),
+ task?.doneWhen && `- Done when: ${task.doneWhen}`,
+ (task?.effort || task?.role) &&
+ `- Effort: ${[task?.effort, task?.role].filter(Boolean).join(' · ')}`,
+ ],
+ ),
+ );
+
parts.push(
section(
'Target pages',
diff --git a/web/src/lib/mcp/data.ts b/web/src/lib/mcp/data.ts
index d90d27b45..87aaf53ae 100644
--- a/web/src/lib/mcp/data.ts
+++ b/web/src/lib/mcp/data.ts
@@ -2684,6 +2684,11 @@ function mcpTaskDetails(raw: unknown) {
platform: d.platform,
platform_label: d.platformLabel,
sources: d.sources,
+ // Where it was sent (AC-004).
+ sent_to_content: d.sent.content
+ ? { opportunity_id: d.sent.content.opportunityId, at: d.sent.content.at }
+ : null,
+ sent_to_webhook: d.sent.webhook ? { at: d.sent.webhook.at } : null,
};
}
diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.ts
index 225e3e003..d08f69acb 100644
--- a/web/src/lib/mcp/server.ts
+++ b/web/src/lib/mcp/server.ts
@@ -938,7 +938,7 @@ export function createMcpServer(auth: McpAuthContext): McpServer {
'get_action',
{
description:
- 'Get one Action Center action in full: its priority (score, level and the facts it rests on), its payload (the prompts, pages, competitors or numbers it is about), the signals that triggered it, its task list and its event trail. Each task carries `mode` (who carries it out: system, agent, human or human_or_agent) and `permission` (read, write or execute). Read both before proposing to act on a task — anything beyond read needs a human to approve it in the dashboard. A task is described by `title` when someone wrote one, otherwise by `task_key` with `title_params`. `details` says what the task carries beyond that, or null: `where` (the page, prompt, platform, domain or competitor), `why` (the evidence), `how` (the steps), `done_when` (the check that closes it), `type` (content, on_page, technical, outreach, pr or product), `effort` and `role`; a task sent from the Improve tab also carries `body`, `platform`, `platform_label` and `sources`.',
+ 'Get one Action Center action in full: its priority (score, level and the facts it rests on), its payload (the prompts, pages, competitors or numbers it is about), the signals that triggered it, its task list and its event trail. Each task carries `mode` (who carries it out: system, agent, human or human_or_agent) and `permission` (read, write or execute). Read both before proposing to act on a task — anything beyond read needs a human to approve it in the dashboard. A task is described by `title` when someone wrote one, otherwise by `task_key` with `title_params`. `details` says what the task carries beyond that, or null: `where` (the page, prompt, platform, domain or competitor), `why` (the evidence), `how` (the steps), `done_when` (the check that closes it), `type` (content, on_page, technical, outreach, pr or product), `effort` and `role`; a task sent from the Improve tab also carries `body`, `platform`, `platform_label` and `sources`; `sent_to_content` (the opportunity it became) and `sent_to_webhook` say where it was sent.',
inputSchema: {
action_id: relaxedUuid.describe('Action UUID, from list_actions or list_action_history.'),
},
diff --git a/web/src/types/index.ts b/web/src/types/index.ts
index bf0e15e0e..59a3e8958 100644
--- a/web/src/types/index.ts
+++ b/web/src/types/index.ts
@@ -240,6 +240,20 @@ export interface ContentOpportunitySourceData {
duplicatesMerged?: number;
/** The opportunity this one is another angle on (CONTENT-006). */
alternativeOf?: { id: string; title: string };
+ /** Sent from an Action Center task (AC-004): the action, and what the task says. */
+ fromAction?: {
+ actionId: string;
+ actionNo: number | null;
+ taskId: string;
+ task?: {
+ where?: string;
+ why?: string;
+ how?: string[];
+ doneWhen?: string;
+ effort?: string;
+ role?: string;
+ };
+ };
/** Why it was dismissed, when the user said (CONTENT-006). */
dismissReason?: 'not_relevant' | 'wrong_angle';
/** Why a finished opportunity went back to New (#857, Phase 4). */
@@ -303,7 +317,7 @@ export interface ContentBrief {
callToAction: string;
}
-export type ContentOpportunitySource = 'system' | 'manual' | 'prompt';
+export type ContentOpportunitySource = 'system' | 'manual' | 'prompt' | 'action';
export interface ContentOpportunity {
id: string;