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.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(prompts): send selected Improve suggestions to Action Center (#1012)
Cihan8123342ddb05
diff --git a/server/src/lib/action-center/from-prompt-improve.js b/server/src/lib/action-center/from-prompt-improve.jsnew file mode 100644index 000000000..b736e9270--- /dev/null+++ b/server/src/lib/action-center/from-prompt-improve.js@@ -0,0 +1,267 @@+/**+ * Turning selected Improve suggestions into an Action Center action+ * (PROMPT-004).+ *+ * Like an opportunity sent from Content (from-opportunity.js), this action is+ * created by a person, so it skips the definitions and the candidate queue.+ * Unlike it, the tasks are not library tasks: each is one suggestion exactly+ * as the user edited it, with the platform and the evidence behind it in+ * `details`. The action is measured on its own prompt (validate.js), and the+ * positions at send time are kept as its baseline for PROMPT-008.+ */++import supabaseAdmin from '../../config/supabase.js';+import { IMPROVE_PLATFORM_LABELS } from '../prompt-improve.js';++export const IMPROVE_ACTION_KIND = 'prompt_improve';++/**+ * What a completed Improve action is measured on (basket scope: its prompt).+ * Citations are counted on the basket's pages, so they're measured only when+ * the action names brand pages; otherwise the metric could only ever be null.+ */+export function improveKpiKeys(pages) {+ return pages.length ? ['ai_visibility', 'citations', 'mentions'] : ['ai_visibility', 'mentions'];+}++/** The brand pages the selected suggestions work on: their brand_page sources. */+export function improvePages(suggestions) {+ const pages = suggestions.flatMap((s) =>+ (s.sources ?? []).filter((src) => src?.type === 'brand_page').map((src) => src.ref),+ );+ return [...new Set(pages.filter((ref) => typeof ref === 'string' && ref.trim()))];+}++const GAP_POINTS = { not_mentioned: 3, mentioned_late: 2, not_cited: 1 };++/** 0 unknown or small, 1 medium, 2 high — monthly estimated AI searches. */+export function volumeTier(estAiVolume) {+ const v = Number(estAiVolume);+ if (!Number.isFinite(v) || v < 100) return 0;+ return v >= 1000 ? 2 : 1;+}++/**+ * Impact from the size of the position gap on the platforms the action+ * covers and the prompt's demand. A prompt missing from several answers is+ * worth more than one cited a little late; demand scales either way.+ */+export function improveImpact(platforms, estAiVolume) {+ const gap = platforms.reduce((sum, p) => sum + (GAP_POINTS[p.state] ?? 0), 0);+ const tier = volumeTier(estAiVolume);+ const missing = platforms.some((p) => p.state === 'not_mentioned');+ if ((tier === 2 && gap >= 3) || (missing && tier >= 1 && gap >= 4)) return 'high';+ if (gap <= 1 && tier < 2) return 'low';+ return 'medium';+}++const label = (id) => IMPROVE_PLATFORM_LABELS[id] ?? id;++function joinLabels(ids) {+ const names = ids.map(label);+ if (names.length <= 1) return names.join('');+ return `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`;+}++/**+ * "Why", written from the platform states at send time:+ * "Not mentioned on Perplexity; mentioned late (avg #3.4) on ChatGPT; …".+ */+export function improveWhy(platforms) {+ const parts = [];+ const byState = (state) => platforms.filter((p) => p.state === state);+ const missing = byState('not_mentioned');+ if (missing.length) parts.push(`Not mentioned on ${joinLabels(missing.map((p) => p.id))}`);+ for (const p of byState('mentioned_late')) {+ parts.push(+ p.mentionPosition+ ? `mentioned late (avg #${p.mentionPosition}) on ${label(p.id)}`+ : `mentioned late on ${label(p.id)}`,+ );+ }+ const uncited = byState('not_cited');+ if (uncited.length) {+ parts.push(`mentioned early but not cited on ${joinLabels(uncited.map((p) => p.id))}`);+ }+ if (!parts.length) return 'Suggestions sent from the Improve tab.';+ const text = parts.join('; ');+ return `${text.charAt(0).toUpperCase()}${text.slice(1)}.`;+}++export function improveGoal(promptText, platforms) {+ return `Get the brand mentioned early and cited for "${promptText}" on ${joinLabels(+ platforms.map((p) => p.id),+ )}.`;+}++/** The positions at send time, per platform the action covers (PROMPT-008). */+export function improveBaseline(platforms, capturedAt) {+ return {+ capturedAt,+ platforms: platforms.map((p) => ({+ platform: p.id,+ state: p.state,+ runs: p.runs ?? null,+ mentionedRuns: p.mentionedRuns ?? null,+ citedRuns: p.citedRuns ?? null,+ mentionPosition: p.mentionPosition ?? null,+ citationRank: p.citationRank ?? null,+ })),+ };+}++/** One task row per selected suggestion, in the order they were shown. */+export function improveTaskRows(actionId, suggestions) {+ return suggestions.map((s, i) => ({+ action_id: actionId,+ position: i + 1,+ task_key: null,+ title: s.title,+ status: 'todo',+ mode: 'human',+ permission: 'read',+ details: {+ body: s.body ?? '',+ platform: s.platform,+ platformLabel: label(s.platform),+ sources: s.sources ?? [],+ },+ }));+}++/**+ * Creates the action, or returns the one this send already created: the+ * idempotency key makes a double click (or a retried request) a no-op.+ *+ * @param {object} p+ * @param {object} p.prompt - { id, text }+ * @param {string} p.brandId+ * @param {object} p.set - the prompt_improve_suggestions row the suggestions came from+ * @param {Array} p.suggestions - selected, as edited: { id, platform, title, body, sources }+ * @param {string} p.idempotencyKey+ * @param {string} p.panelLink - the Positions panel deep link, for the action's source line+ * @param {string} p.userId+ * @returns {Promise<{ actionId: string, actionNo: number, created: boolean }>}+ */+export async function sendImproveToActionCenter({+ prompt,+ brandId,+ set,+ suggestions,+ idempotencyKey,+ panelLink,+ userId,+}) {+ const dedupKey = `prompt_improve:${prompt.id}:${idempotencyKey}`;+ const { data: existing } = await supabaseAdmin+ .from('actions')+ .select('id, action_no')+ .eq('brand_id', brandId)+ .eq('dedup_key', dedupKey)+ .maybeSingle();+ if (existing) return { actionId: existing.id, actionNo: existing.action_no, created: false };++ const covered = new Set(suggestions.map((s) => s.platform));+ const platforms = (set.platform_states ?? []).filter((p) => covered.has(p.id));++ const { data: volumeRow } = await supabaseAdmin+ .from('prompt_volumes')+ .select('est_ai_volume')+ .eq('prompt_id', prompt.id)+ .order('fetched_at', { ascending: false })+ .limit(1)+ .maybeSingle();++ const now = new Date().toISOString();+ const pages = improvePages(suggestions);+ const payload = {+ source: IMPROVE_ACTION_KIND,+ title: `Improve position: "${prompt.text}"`,+ promptId: prompt.id,+ promptText: prompt.text,+ // Measured on this prompt alone, and on the brand pages the suggestions+ // name for citations (validate.js basket scope).+ promptIds: [prompt.id],+ pages,+ rangeKey: set.range_key,+ region: set.region || null,+ platforms: platforms.map((p) => ({ id: p.id, label: label(p.id), state: p.state })),+ why: improveWhy(platforms),+ goal: improveGoal(prompt.text, platforms),+ panelLink,+ targetEntity: 'platforms',+ targetCount: platforms.length,+ };++ const { data: action, error } = await supabaseAdmin+ .from('actions')+ .insert({+ brand_id: brandId,+ category: 'compete',+ kind: IMPROVE_ACTION_KIND,+ definition_version: 1,+ impact: improveImpact(platforms, volumeRow?.est_ai_volume),+ payload,+ kpi_keys: improveKpiKeys(pages),+ baseline: improveBaseline(platforms, now),+ dedup_key: dedupKey,+ })+ .select('id, action_no')+ .single();+ if (error) {+ // Two requests for the same send can race past the lookup; the partial+ // unique index on (brand_id, dedup_key) lets only one insert win.+ if (error.code === '23505') {+ const { data: winner } = await supabaseAdmin+ .from('actions')+ .select('id, action_no')+ .eq('brand_id', brandId)+ .eq('dedup_key', dedupKey)+ .maybeSingle();+ if (winner) return { actionId: winner.id, actionNo: winner.action_no, created: false };+ }+ throw new Error(error.message);+ }++ const { error: tasksErr } = await supabaseAdmin+ .from('action_tasks')+ .insert(improveTaskRows(action.id, suggestions));+ if (tasksErr) throw new Error(tasksErr.message);++ await supabaseAdmin.from('action_events').insert({+ action_id: action.id,+ event: 'created',+ actor_id: userId,+ data: {+ source: IMPROVE_ACTION_KIND,+ promptId: prompt.id,+ taskCount: suggestions.length,+ platforms: platforms.map((p) => p.id),+ },+ });++ return { actionId: action.id, actionNo: action.action_no, created: true };+}++/**+ * The newest send of the current set whose action is still there and not+ * dismissed — what decides "Open in Actions" over "Send Actions" — plus the+ * ids of the suggestions any live send of this set carried ("Already sent").+ */+export async function liveImproveSends(set) {+ const sends = (set.sent_actions ?? []).filter((s) => s.setGeneratedAt === set.generated_at);+ if (!sends.length) return { latest: null, sentSuggestionIds: [] };+ const { data: actions } = await supabaseAdmin+ .from('actions')+ .select('id, status')+ .in(+ 'id',+ sends.map((s) => s.actionId),+ );+ const live = new Set((actions ?? []).filter((a) => a.status !== 'dismissed').map((a) => a.id));+ const liveSends = sends.filter((s) => live.has(s.actionId));+ return {+ latest: liveSends.length ? liveSends[liveSends.length - 1] : null,+ sentSuggestionIds: [...new Set(liveSends.flatMap((s) => s.suggestionIds ?? []))],+ };+}diff --git a/server/src/lib/action-center/from-prompt-improve.test.js b/server/src/lib/action-center/from-prompt-improve.test.jsnew file mode 100644index 000000000..ee2613b7c--- /dev/null+++ b/server/src/lib/action-center/from-prompt-improve.test.js@@ -0,0 +1,160 @@+import { describe, expect, it, vi } from 'vitest';++// The module imports the supabase admin client, whose config hard-exits when+// SUPABASE_* env is absent (as in CI) — stub it before the import chain.+vi.mock('../../config/supabase.js', () => ({ default: {} }));++const {+ improveBaseline,+ improveGoal,+ improveImpact,+ improveKpiKeys,+ improvePages,+ improveTaskRows,+ improveWhy,+ volumeTier,+} = await import('./from-prompt-improve.js');++const P = (id, state, extra = {}) => ({ id, state, ...extra });++describe('volumeTier', () => {+ it('splits estimated monthly AI searches at 100 and 1,000', () => {+ expect(volumeTier(null)).toBe(0);+ expect(volumeTier(99)).toBe(0);+ expect(volumeTier(100)).toBe(1);+ expect(volumeTier(999)).toBe(1);+ expect(volumeTier(1000)).toBe(2);+ });+});++describe('improveImpact', () => {+ it('is high with demand and a real gap', () => {+ expect(improveImpact([P('chatgpt-web', 'not_mentioned')], 5000)).toBe('high');+ expect(+ improveImpact([P('perplexity-web', 'not_mentioned'), P('google-aio', 'not_cited')], 300),+ ).toBe('high');+ });++ it('is low for a small gap without high demand', () => {+ expect(improveImpact([P('google-aio', 'not_cited')], 50)).toBe('low');+ expect(improveImpact([P('google-aio', 'not_cited')], null)).toBe('low');+ });++ it('is medium otherwise', () => {+ expect(improveImpact([P('chatgpt-web', 'mentioned_late')], 300)).toBe('medium');+ expect(improveImpact([P('chatgpt-web', 'not_mentioned')], null)).toBe('medium');+ expect(improveImpact([P('google-aio', 'not_cited')], 2000)).toBe('medium');+ });+});++describe('improveWhy / improveGoal', () => {+ const platforms = [+ P('perplexity-web', 'not_mentioned'),+ P('gemini-web', 'not_mentioned'),+ P('chatgpt-web', 'mentioned_late', { mentionPosition: 3.4 }),+ P('google-aio', 'not_cited'),+ ];++ it('describes each platform state in one sentence', () => {+ expect(improveWhy(platforms)).toBe(+ 'Not mentioned on Perplexity and Gemini; mentioned late (avg #3.4) on ChatGPT; mentioned early but not cited on Google AI Overviews.',+ );+ });++ it('starts with a capital when the brand is mentioned everywhere', () => {+ expect(improveWhy([P('google-aio', 'not_cited')])).toBe(+ 'Mentioned early but not cited on Google AI Overviews.',+ );+ });++ it('names the prompt and the platforms in the goal', () => {+ expect(improveGoal('best coffee', platforms.slice(0, 2))).toBe(+ 'Get the brand mentioned early and cited for "best coffee" on Perplexity and Gemini.',+ );+ });+});++describe('improveBaseline', () => {+ it('keeps the positions per platform at send time', () => {+ expect(+ improveBaseline(+ [P('chatgpt-web', 'mentioned_late', { runs: 8, mentionedRuns: 8, mentionPosition: 3.4 })],+ '2026-10-13T10:00:00.000Z',+ ),+ ).toEqual({+ capturedAt: '2026-10-13T10:00:00.000Z',+ platforms: [+ {+ platform: 'chatgpt-web',+ state: 'mentioned_late',+ runs: 8,+ mentionedRuns: 8,+ citedRuns: null,+ mentionPosition: 3.4,+ citationRank: null,+ },+ ],+ });+ });+});++describe('improveTaskRows', () => {+ it('makes one human task per suggestion with its text exactly as edited', () => {+ const rows = improveTaskRows('a1', [+ {+ id: 'perplexity-web:0',+ platform: 'perplexity-web',+ title: 'Edited title',+ body: 'Edited body',+ sources: [{ type: 'fanout', ref: 'q' }],+ },+ { id: 'own:1', platform: 'chatgpt-web', title: 'My own idea', body: '', sources: [] },+ ]);+ expect(rows).toEqual([+ {+ action_id: 'a1',+ position: 1,+ task_key: null,+ title: 'Edited title',+ status: 'todo',+ mode: 'human',+ permission: 'read',+ details: {+ body: 'Edited body',+ platform: 'perplexity-web',+ platformLabel: 'Perplexity',+ sources: [{ type: 'fanout', ref: 'q' }],+ },+ },+ expect.objectContaining({+ position: 2,+ title: 'My own idea',+ details: { body: '', platform: 'chatgpt-web', platformLabel: 'ChatGPT', sources: [] },+ }),+ ]);+ });+});++describe('improvePages', () => {+ it('collects the brand pages the suggestions name, once each', () => {+ const suggestions = [+ {+ sources: [+ { type: 'brand_page', ref: 'https://acme.com/plans' },+ { type: 'fanout', ref: 'best coffee subscription' },+ ],+ },+ { sources: [{ type: 'brand_page', ref: 'https://acme.com/plans' }] },+ { sources: [{ type: 'competitor_url', ref: 'https://rival.com/x' }] },+ {},+ ];+ expect(improvePages(suggestions)).toEqual(['https://acme.com/plans']);+ });+});++describe('improveKpiKeys', () => {+ it('measures citations only when the action names brand pages', () => {+ expect(improveKpiKeys(['https://acme.com/plans'])).toContain('citations');+ expect(improveKpiKeys([])).toEqual(['ai_visibility', 'mentions']);+ });+});diff --git a/server/src/lib/action-center/validate.js b/server/src/lib/action-center/validate.jsindex 59567c6f6..9072f45c7 100644--- a/server/src/lib/action-center/validate.js+++ b/server/src/lib/action-center/validate.js@@ -236,7 +236,8 @@ export async function validateAction(action, { now = new Date() } = {}) {// An action sent from a content opportunity is measured on its own prompts// and pages; the brand-wide numbers would bury a single piece of content.- if (action.kind === 'content_opportunity') {+ // An Improve action (PROMPT-004) likewise, on its one prompt.+ if (action.kind === 'content_opportunity' || action.kind === 'prompt_improve') {const scope = await basketScope(action);const [before, after] = await Promise.all([measureBasket(action.brand_id, scope, beforeWindow.from, beforeWindow.to),diff --git a/server/src/routes/prompts.js b/server/src/routes/prompts.jsindex 8cd98ffdc..ec43224c8 100644--- a/server/src/routes/prompts.js+++ b/server/src/routes/prompts.js@@ -17,6 +17,7 @@ import { getGaSuggestionCandidates } from '../lib/ga-suggestions.js';import {ACTIONABLE_STATES,IMPROVE_PLATFORM_LABELS,+ SOURCE_TYPES,buildImprovePrompt,classifyPlatform,collectEvidence,@@ -25,6 +26,10 @@ import {sanitizeSuggestions,} from '../lib/prompt-improve.js';import { generationCostUsd } from '../lib/improve-cost.js';+import {+ liveImproveSends,+ sendImproveToActionCenter,+} from '../lib/action-center/from-prompt-improve.js';const router = Router();@@ -867,9 +872,10 @@ function improveResultsQuery(columns, { promptId, brandId, range }) {return q.order('created_at', { ascending: false });}-function improveResponse(row, newestAt) {+function improveResponse(row, newestAt, sent = { latest: null, sentSuggestionIds: [] }) {if (!row) return null;return {+ sent,rangeKey: row.range_key,region: row.region,platforms: row.platform_states,@@ -919,7 +925,11 @@ router.get('/:promptId/improve', requireFeature('prompt_improve'), async (req, rgetImproveQuotaStatus(brand.organization_id, improveModelId()),]);return res.json({- improve: improveResponse(cached, newest?.[0]?.created_at ?? null),+ improve: improveResponse(+ cached,+ newest?.[0]?.created_at ?? null,+ cached ? await liveImproveSends(cached) : undefined,+ ),quota: publicQuota(quota),});} catch (error) {@@ -1089,4 +1099,111 @@ router.post('/:promptId/improve', requireFeature('prompt_improve'), async (req,}});+// Send the selected suggestions, as edited, to Action Center (PROMPT-004).+const sendImproveSchema = z.object({+ idempotencyKey: z.string().min(8).max(64),+ suggestions: z+ .array(+ z.object({+ id: z.string().min(1).max(120),+ platform: z.enum(Object.keys(IMPROVE_PLATFORM_LABELS)),+ title: z.string().trim().min(1).max(200),+ body: z.string().max(1000).optional().default(''),+ sources: z+ .array(z.object({ type: z.enum(SOURCE_TYPES), ref: z.string().min(1).max(300) }))+ .max(6)+ .optional()+ .default([]),+ }),+ )+ .min(1)+ .max(50),+});++function positionsPanelLink(promptId, range) {+ const params = new URLSearchParams({+ tab: 'all',+ positions: promptId,+ positionsRange: range.preset,+ });+ if (range.preset === 'custom') {+ const [, from, to] = range.key.split(':');+ if (from) params.set('positionsFrom', from);+ if (to) params.set('positionsTo', to);+ }+ return `/dashboard/prompts?${params.toString()}`;+}++router.post('/:promptId/improve/action', requireFeature('prompt_improve'), async (req, res) => {+ try {+ const range = parseImproveRange(req.body);+ const parsed = sendImproveSchema.safeParse(req.body);+ if (!parsed.success) {+ return res.status(400).json({ error: 'Invalid suggestions', details: parsed.error.issues });+ }+ const promptId = req.params.promptId;+ const { prompt, brandId } = await loadImprovePrompt(promptId, req.user.id);++ const { data: set } = await supabaseAdmin+ .from('prompt_improve_suggestions')+ .select('*')+ .eq('prompt_id', promptId)+ .eq('range_key', range.key)+ .eq('region', range.region)+ .maybeSingle();+ if (!set) {+ return res.status(404).json({ error: 'Generate suggestions for this range first' });+ }++ const { suggestions, idempotencyKey } = parsed.data;+ const result = await sendImproveToActionCenter({+ prompt,+ brandId,+ set,+ suggestions,+ idempotencyKey,+ panelLink: positionsPanelLink(promptId, range),+ userId: req.user.id,+ });++ // Record the send on the set, once, so the panel can show it after a reload.+ const sends = set.sent_actions ?? [];+ let updated = set;+ if (!sends.some((s) => s.actionId === result.actionId)) {+ const { data, error } = await supabaseAdmin+ .from('prompt_improve_suggestions')+ .update({+ sent_actions: [+ ...sends,+ {+ actionId: result.actionId,+ actionNo: result.actionNo,+ sentAt: new Date().toISOString(),+ setGeneratedAt: set.generated_at,+ suggestionIds: suggestions.map((s) => s.id),+ },+ ],+ })+ .eq('id', set.id)+ .select('*')+ .single();+ if (error) throw error;+ updated = data;+ }++ return res.json({+ actionId: result.actionId,+ actionNo: result.actionNo,+ created: result.created,+ taskCount: suggestions.length,+ sent: await liveImproveSends(updated),+ });+ } catch (error) {+ req.log.error({ err: error }, 'prompt improve send error');+ return res+ .status(error.status || 500)+ .json({ error: error.message || 'Failed to send to Action Center' });+ }+});+export default router;diff --git a/supabase/migrations/00121_prompt_improve_actions.sql b/supabase/migrations/00121_prompt_improve_actions.sqlnew file mode 100644index 000000000..3e5eb4864--- /dev/null+++ b/supabase/migrations/00121_prompt_improve_actions.sql@@ -0,0 +1,18 @@+-- Positions panel → Improve → Send Actions (PROMPT-004): the selected+-- suggestions become one Action Center action with a task each.+--+-- action_tasks.details: what a task sent from a suggestion carries beyond its+-- title — the body the user wrote or kept, the platform it is for, and the+-- evidence it was based on: { body, platform, platformLabel, sources: [{ type,+-- ref }] }. Null for library and hand-added tasks, which render as before.+alter table public.action_tasks add column if not exists details jsonb;++comment on column public.action_tasks.details is+ 'Extra content for a task sent from the Improve tab (PROMPT-004): { body, platform, platformLabel, sources: [{ type, ref }] }. Null otherwise.';++-- prompt_improve_suggestions.sent_actions: every send of this set, newest+-- last — [{ actionId, actionNo, sentAt, setGeneratedAt, suggestionIds }]. The+-- panel shows "Open in Actions" for the newest send of the current set while+-- its action is still open, and marks the suggestions it carried.+alter table public.prompt_improve_suggestions+ add column if not exists sent_actions jsonb not null default '[]'::jsonb;diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 9b01f7563..e730dfc58 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -14308,3 +14308,25 @@ create index if not exists prompt_improve_usage_org_used_idx-- Service-role only, no policy (as brief_usage).alter table public.prompt_improve_usage enable row level security;+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00121_prompt_improve_actions.sql+-- ─────────────────────────────────────────────────────────────────────────+-- Positions panel → Improve → Send Actions (PROMPT-004): the selected+-- suggestions become one Action Center action with a task each.+--+-- action_tasks.details: what a task sent from a suggestion carries beyond its+-- title — the body the user wrote or kept, the platform it is for, and the+-- evidence it was based on: { body, platform, platformLabel, sources: [{ type,+-- ref }] }. Null for library and hand-added tasks, which render as before.+alter table public.action_tasks add column if not exists details jsonb;++comment on column public.action_tasks.details is+ 'Extra content for a task sent from the Improve tab (PROMPT-004): { body, platform, platformLabel, sources: [{ type, ref }] }. Null otherwise.';++-- prompt_improve_suggestions.sent_actions: every send of this set, newest+-- last — [{ actionId, actionNo, sentAt, setGeneratedAt, suggestionIds }]. The+-- panel shows "Open in Actions" for the newest send of the current set while+-- its action is still open, and marks the suggestions it carried.+alter table public.prompt_improve_suggestions+ add column if not exists sent_actions jsonb not null default '[]'::jsonb;+diff --git a/web/messages/en.json b/web/messages/en.jsonindex 4edc0c2ff..65c6a2f2f 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -732,6 +732,21 @@"allQueries": "Show all {count}","fewerQueries": "Show fewer","unavailable": "The opportunity this action was sent from is no longer available."+ },+ "noSignalsImprove": "This action was sent from the Prompts Improve tab, so it has no detection signals. Its evidence is the prompt and platforms below.",+ "improve": {+ "source": "Source",+ "sourceValue": "Prompts › Improve",+ "openPanel": "Open in Prompts",+ "prompt": "Prompt",+ "platforms": "Platforms at send time",+ "states": {+ "not_mentioned": "Not mentioned",+ "mentioned_late": "Mentioned · Late",+ "not_cited": "Mentioned early · not cited",+ "doing_well": "Doing well",+ "no_runs": "No runs"+ }}}},@@ -1127,6 +1142,12 @@"titleGeneric": "Act on a content opportunity","description": "Sent from Content Optimization: a piece of content, or work on an existing page, that answers a group of related prompts.","goal": "Get the brand into AI answers for these prompts with the content this opportunity calls for."+ },+ "prompt_improve": {+ "title": "Improve position for {targets}",+ "titleGeneric": "Improve a prompt's position",+ "description": "Sent from the Prompts Improve tab: platform-specific changes to get the brand mentioned earlier and cited for one prompt.",+ "goal": "Get the brand mentioned early and cited for this prompt on the platforms it covers."}},"actionTasks": {diff --git a/web/src/components/action-center/action-drawer.tsx b/web/src/components/action-center/action-drawer.tsxindex d5e8e0b57..7b49c6da2 100644--- a/web/src/components/action-center/action-drawer.tsx+++ b/web/src/components/action-center/action-drawer.tsx@@ -59,6 +59,7 @@ import { isKpiKey } from '@/lib/kpis/registry';import { ImpactDots, isSuperseded, SignalStatusBadge } from './signal-table';import { ActionIcon } from './action-table';import { OpportunityContext } from './opportunity-context';+import { ImproveContext } from './improve-context';import { cn } from '@/lib/utils';type DrawerTab = 'overview' | 'tasks' | 'signals' | 'history';@@ -224,7 +225,7 @@ export function ActionDrawer({<Separator /><section><p className="text-xs font-medium text-muted-foreground">{t('drawer.goal')}</p>- <p className="mt-1">{actionGoal(action.kind, tTexts)}</p>+ <p className="mt-1">{actionGoal(action.kind, tTexts, action.payload)}</p></section><Separator /><section>@@ -247,7 +248,9 @@ export function ActionDrawer({)}</section><Separator />- {opportunityId ? (+ {action.kind === 'prompt_improve' ? (+ <ImproveContext payload={action.payload ?? {}} />+ ) : opportunityId ? (<OpportunityContextopportunityId={opportunityId}pageUrls={action.payload?.assetKey ? opportunityPages : undefined}@@ -322,7 +325,11 @@ export function ActionDrawer({<section className="space-y-2">{detail.signals.length === 0 && (<p className="text-xs text-muted-foreground">- {opportunityId ? t('drawer.noSignalsOpportunity') : t('drawer.noSignals')}+ {action.kind === 'prompt_improve'+ ? t('drawer.noSignalsImprove')+ : opportunityId+ ? t('drawer.noSignalsOpportunity')+ : t('drawer.noSignals')}</p>)}{detail.signals.map((signal) => {@@ -570,6 +577,8 @@ function TaskRow({</Button></div>+ {task.details && <TaskDetails details={task.details} />}+{skipDraft !== null && (<div className="flex items-center gap-2 border-t bg-muted/30 px-3 py-2"><Input@@ -703,3 +712,29 @@ function AddTaskForm({</div>);}++/** A task sent from the Improve tab: its platform, body and evidence (PROMPT-004). */+function TaskDetails({ details }: { details: NonNullable<ActionTask['details']> }) {+ return (+ <div className="space-y-1.5 px-4 pb-3">+ {details.body && (+ <p className="text-xs leading-relaxed text-muted-foreground">{details.body}</p>+ )}+ <div className="flex flex-wrap gap-1">+ <Badge variant="secondary" className="text-[10px]">+ {details.platformLabel}+ </Badge>+ {details.sources.map((source) => (+ <Badge+ key={`${source.type}:${source.ref}`}+ variant="outline"+ title={source.ref}+ className="max-w-full truncate text-[10px] font-normal text-muted-foreground"+ >+ {source.type === 'answer' ? 'AI answer' : source.ref}+ </Badge>+ ))}+ </div>+ </div>+ );+}diff --git a/web/src/components/action-center/history-drawer.tsx b/web/src/components/action-center/history-drawer.tsxindex cc489e2ff..f094e629f 100644--- a/web/src/components/action-center/history-drawer.tsx+++ b/web/src/components/action-center/history-drawer.tsx@@ -142,7 +142,7 @@ export function HistoryDrawer({<div className="flex-1 space-y-5 overflow-y-auto px-6 py-4 text-sm"><section><p className="text-xs font-medium text-muted-foreground">{t('drawer.goal')}</p>- <p className="mt-1">{actionGoal(item.kind, tTexts)}</p>+ <p className="mt-1">{actionGoal(item.kind, tTexts, item.payload)}</p></section><Separator />diff --git a/web/src/components/action-center/improve-context.tsx b/web/src/components/action-center/improve-context.tsxnew file mode 100644index 000000000..fc311bd30--- /dev/null+++ b/web/src/components/action-center/improve-context.tsx@@ -0,0 +1,74 @@+'use client';++import { useTranslations } from 'next-intl';+import { ExternalLink } from 'lucide-react';+import { Badge } from '@/components/ui/badge';+import { Link } from '@/i18n/navigation';++type ImproveState = 'not_mentioned' | 'mentioned_late' | 'not_cited' | 'doing_well' | 'no_runs';++const STATES: ImproveState[] = [+ 'not_mentioned',+ 'mentioned_late',+ 'not_cited',+ 'doing_well',+ 'no_runs',+];++/**+ * What an action sent from the Prompts Improve tab is about (PROMPT-004): its+ * source, the prompt with a link back to its Positions panel, and each+ * platform's state when it was sent. Copied onto the action at send time, so+ * it still reads after the prompt's positions move.+ */+export function ImproveContext({ payload }: { payload: Record<string, unknown> }) {+ const t = useTranslations('actionCenter.actionsPage.drawer.improve');+ const promptText = typeof payload.promptText === 'string' ? payload.promptText : null;+ const panelLink = typeof payload.panelLink === 'string' ? payload.panelLink : null;+ const platforms = Array.isArray(payload.platforms)+ ? (payload.platforms as { id?: unknown; label?: unknown; state?: unknown }[]).filter(+ (p): p is { id: string; label: string; state: ImproveState } =>+ typeof p.id === 'string' &&+ typeof p.label === 'string' &&+ STATES.includes(p.state as ImproveState),+ )+ : [];++ return (+ <section className="space-y-3">+ <div>+ <p className="text-xs font-medium text-muted-foreground">{t('source')}</p>+ <div className="mt-1 flex flex-wrap items-center gap-2">+ <span>{t('sourceValue')}</span>+ {panelLink && (+ <Link+ href={panelLink}+ className="inline-flex items-center gap-1 text-xs font-medium text-primary hover:underline"+ >+ {t('openPanel')}+ <ExternalLink className="h-3 w-3" />+ </Link>+ )}+ </div>+ </div>+ {promptText && (+ <div>+ <p className="text-xs font-medium text-muted-foreground">{t('prompt')}</p>+ <p className="mt-1">{promptText}</p>+ </div>+ )}+ {platforms.length > 0 && (+ <div>+ <p className="text-xs font-medium text-muted-foreground">{t('platforms')}</p>+ <div className="mt-2 flex flex-wrap gap-1.5">+ {platforms.map((p) => (+ <Badge key={p.id} variant="outline" className="text-[11px] font-normal">+ {p.label} · {t(`states.${p.state}`)}+ </Badge>+ ))}+ </div>+ </div>+ )}+ </section>+ );+}diff --git a/web/src/components/prompts/prompt-improve-tab.tsx b/web/src/components/prompts/prompt-improve-tab.tsxindex 01d0402fd..3dc1f1e64 100644--- a/web/src/components/prompts/prompt-improve-tab.tsx+++ b/web/src/components/prompts/prompt-improve-tab.tsx@@ -12,7 +12,20 @@*/import { useCallback, useEffect, useMemo, useRef, useState } from 'react';-import { Check, Loader2, Lock, Pencil, Plus, RefreshCw, Sparkles, X } from 'lucide-react';+import {+ ArrowUpRight,+ Check,+ CircleCheck,+ Loader2,+ Lock,+ Pencil,+ Plus,+ RefreshCw,+ Send,+ Sparkles,+ X,+} from 'lucide-react';+import { toast } from 'sonner';import { Link } from '@/i18n/navigation';import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';@@ -24,10 +37,15 @@ import { Textarea } from '@/components/ui/textarea';import { AIProviderAvatar, resolveAIProvider } from '@/components/ai-provider-avatar';import { cn } from '@/lib/utils';import { PLANS, hasFeature, type PlanId } from '@/config/plans';-import { generateImproveSuggestions, getImproveSuggestions } from '@/lib/actions/prompt-improve';+import {+ generateImproveSuggestions,+ getImproveSuggestions,+ sendImproveToActionCenter,+} from '@/lib/actions/prompt-improve';import {STATE_LABEL,STATE_ORDER,+ actionCenterLink,hasUnsentEdits,mentionRateLabel,selectionSummary,@@ -58,6 +76,9 @@ export interface ImproveController {generate: () => void;/** Reads the cached set again; never generates. */reload: () => void;+ /** Sends the checked drafts to Action Center as one action (PROMPT-004). */+ send: () => void;+ sending: boolean;}/**@@ -85,6 +106,10 @@ export function useImprove({error: string | null;}>({ key: '', status: 'idle', set: null, error: null });const [quota, setQuota] = useState<ImproveQuota | null>(null);+ const [sending, setSending] = useState(false);+ // One key per send: kept across a retry of the same send, so a double click+ // or a repeated request creates one action; cleared once a send lands.+ const sendKeyRef = useRef<string | null>(null);const [drafts, setDrafts] = useState<DraftSuggestion[]>([]);// The latest key, so a response for a range the user already left is dropped.const keyRef = useRef(key);@@ -152,6 +177,45 @@ export function useImprove({const status: Status = locked ? 'locked' : (current?.status ?? 'idle');const set = current?.set ?? null;+ const send = useCallback(() => {+ if (!promptId || !state.set || sending) return;+ const selected = drafts.filter((d) => d.checked && !d.removed && d.title.trim());+ if (selected.length === 0) return;+ const forKey = keyRef.current;+ sendKeyRef.current ??= crypto.randomUUID();+ setSending(true);+ sendImproveToActionCenter(promptId, range, {+ idempotencyKey: sendKeyRef.current,+ suggestions: selected.map((d) => ({+ id: d.id,+ platform: d.platform,+ title: d.title.trim(),+ body: d.body.trim(),+ sources: d.sources,+ })),+ })+ .then((result) => {+ if ('error' in result) {+ toast.error(result.error);+ return;+ }+ sendKeyRef.current = null;+ if (keyRef.current === forKey) {+ setState((s) => (s.set ? { ...s, set: { ...s.set, sent: result.sent } } : s));+ }+ toast.success(+ `Action created with ${result.taskCount} task${result.taskCount === 1 ? '' : 's'}`,+ {+ action: {+ label: 'Open',+ onClick: () => window.open(actionCenterLink(result.actionId), '_self'),+ },+ },+ );+ })+ .finally(() => setSending(false));+ }, [promptId, range, drafts, sending, state.set]);+const dirty = useMemo(() => !!set && hasUnsentEdits(drafts, set.suggestions), [drafts, set]);return {@@ -166,13 +230,16 @@ export function useImprove({count: set && !locked ? drafts.filter((d) => !d.removed).length : null,generate,reload,+ send,+ sending,};}// ─── Tab ──────────────────────────────────────────────────────────────────────export function ImproveTab({ improve }: { improve: ImproveController }) {- const { status, set, quota, drafts, setDrafts, error, dirty, generate, reload } = improve;+ const { status, set, quota, drafts, setDrafts, error, dirty, generate, reload, send, sending } =+ improve;const [confirmRegenerate, setConfirmRegenerate] = useState(false);const outOfQuota = !!quota?.exhausted;@@ -222,6 +289,7 @@ export function ImproveTab({ improve }: { improve: ImproveController }) {const tracked = set.platforms.filter((p) => p.state !== 'no_runs');const actionable = tracked.filter((p) => p.state !== 'doing_well');const summary = selectionSummary(drafts);+ const sentLatest = set.sent?.latest ?? null;const update = (id: string, patch: Partial<DraftSuggestion>) =>setDrafts((ds) => ds.map((d) => (d.id === id ? { ...d, ...patch } : d)));@@ -275,6 +343,7 @@ export function ImproveTab({ improve }: { improve: ImproveController }) {<PlatformGroupkey={p.id}platform={p}+ sentIds={set.sent.sentSuggestionIds}drafts={drafts.filter((d) => d.platform === p.id)}onUpdate={update}onAddOwn={() => addOwn(p)}@@ -290,34 +359,56 @@ export function ImproveTab({ improve }: { improve: ImproveController }) {Generated {new Date(set.generatedAt).toLocaleString()}</span><QuotaNote quota={quota} className="ml-2" />+ {sentLatest && (+ <span className="mt-1 flex items-center gap-1 text-emerald-700 dark:text-emerald-400">+ <CircleCheck className="h-3.5 w-3.5" />+ Sent {new Date(sentLatest.sentAt).toLocaleDateString()} · AC-{sentLatest.actionNo}+ </span>+ )}</span>- {confirmRegenerate ? (- <span className="flex items-center gap-2 text-xs">- Discard your edits?- <Button size="xs" variant="outline" onClick={() => setConfirmRegenerate(false)}>- Keep editing- </Button>+ <span className="flex flex-wrap items-center gap-2">+ {confirmRegenerate ? (+ <span className="flex items-center gap-2 text-xs">+ Discard your edits?+ <Button size="xs" variant="outline" onClick={() => setConfirmRegenerate(false)}>+ Keep editing+ </Button>+ <Button+ size="xs"+ onClick={() => {+ setConfirmRegenerate(false);+ generate();+ }}+ >+ Discard & regenerate+ </Button>+ </span>+ ) : (<Button- size="xs"- onClick={() => {- setConfirmRegenerate(false);- generate();- }}+ size="sm"+ variant="outline"+ disabled={outOfQuota}+ onClick={() => (dirty ? setConfirmRegenerate(true) : generate())}>- Discard & regenerate+ <RefreshCw />+ Regenerate</Button>- </span>- ) : (- <Button- size="sm"- variant="outline"- disabled={outOfQuota}- onClick={() => (dirty ? setConfirmRegenerate(true) : generate())}- >- <RefreshCw />- Regenerate- </Button>- )}+ )}+ {sentLatest ? (+ <Link+ href={actionCenterLink(sentLatest.actionId)}+ className={buttonVariants({ size: 'sm' })}+ >+ Open in Actions+ <ArrowUpRight />+ </Link>+ ) : (+ <Button size="sm" onClick={send} disabled={sending || summary.selected === 0}>+ {sending ? <Loader2 className="animate-spin" /> : <Send />}+ Send Actions+ </Button>+ )}+ </span></div></div>);@@ -406,11 +497,14 @@ function inputsNote(p: ImprovePlatform): string | null {function PlatformGroup({platform: p,+ sentIds,drafts,onUpdate,onAddOwn,}: {platform: ImprovePlatform;+ /** Suggestions a live send of this set carried. */+ sentIds: string[];drafts: DraftSuggestion[];onUpdate: (id: string, patch: Partial<DraftSuggestion>) => void;onAddOwn: () => void;@@ -444,7 +538,12 @@ function PlatformGroup({)}{drafts.map((d) => (- <SuggestionCard key={d.id} draft={d} onUpdate={(patch) => onUpdate(d.id, patch)} />+ <SuggestionCard+ key={d.id}+ draft={d}+ sent={sentIds.includes(d.id)}+ onUpdate={(patch) => onUpdate(d.id, patch)}+ />))}{canSuggest && (@@ -463,9 +562,11 @@ function PlatformGroup({function SuggestionCard({draft: d,+ sent,onUpdate,}: {draft: DraftSuggestion;+ sent: boolean;onUpdate: (patch: Partial<DraftSuggestion>) => void;}) {// A new own suggestion opens straight into editing.@@ -564,8 +665,16 @@ function SuggestionCard({</span></div>{d.body && <p className="text-xs leading-relaxed text-muted-foreground">{d.body}</p>}- {(d.sources.length > 0 || d.own) && (+ {(d.sources.length > 0 || d.own || sent) && (<div className="flex flex-wrap gap-1">+ {sent && (+ <Badge+ variant="outline"+ className="border-emerald-500/30 bg-emerald-500/10 text-[10px] text-emerald-700 dark:text-emerald-300"+ >+ Already sent+ </Badge>+ )}{d.own && (<Badge variant="secondary" className="text-[10px]">Your suggestiondiff --git a/web/src/lib/action-center/display.test.ts b/web/src/lib/action-center/display.test.tsindex b3f8ca282..ba74e48d9 100644--- a/web/src/lib/action-center/display.test.ts+++ b/web/src/lib/action-center/display.test.ts@@ -40,8 +40,22 @@ describe('actionTexts', () => {expect(() => actionGoal(kind, t)).not.toThrow();});- it('holds copy for all sixty-two definitions and opportunity actions', () => {- expect(ACTION_KINDS).toHaveLength(63);+ it('holds copy for all sixty-two definitions, opportunity and Improve actions', () => {+ expect(ACTION_KINDS).toHaveLength(64);+ });++ it('names an Improve action after its prompt, with its own why and goal', () => {+ const payload = {+ title: 'Improve position: "best coffee"',+ why: 'Not mentioned on Perplexity.',+ goal: 'Get the brand mentioned early and cited for "best coffee" on Perplexity.',+ };+ const texts = actionTexts(action({ kind: 'prompt_improve', payload }), t);+ expect(texts).toEqual({ title: payload.title, description: payload.why });+ expect(actionGoal('prompt_improve', t, payload)).toBe(payload.goal);+ expect(actionGoal('prompt_improve', t)).toBe(+ messages.actionCenter.actionTexts.prompt_improve.goal,+ );});it('names an opportunity action after the work it was sent for', () => {diff --git a/web/src/lib/action-center/display.ts b/web/src/lib/action-center/display.tsindex 249b53c2c..547e9864b 100644--- a/web/src/lib/action-center/display.ts+++ b/web/src/lib/action-center/display.ts@@ -70,6 +70,14 @@ export function actionTexts(if (action.kind === 'content_opportunity' && typeof p.title === 'string' && p.title) {return { title: p.title, description: t(`${action.kind}.description`) };}+ // An Improve action carries its own title and "why", written from the+ // prompt's platform states when it was sent (PROMPT-004).+ if (action.kind === 'prompt_improve' && typeof p.title === 'string' && p.title) {+ return {+ title: p.title,+ description: typeof p.why === 'string' && p.why ? p.why : t(`${action.kind}.description`),+ };+ }const targets = targetLabel(p, t);return {title: targets ? t(`${action.kind}.title`, { targets }) : t(`${action.kind}.titleGeneric`),@@ -101,17 +109,27 @@ export function eventTaskText(* because an unknown kind has no goal key and next-intl would render the key* itself into the drawer.*/-export function actionGoal(kind: string, t: Translator): string {+export function actionGoal(+ kind: string,+ t: Translator,+ payload?: Record<string, unknown> | null,+): string {+ // An Improve action names its own prompt and platforms (PROMPT-004).+ if (kind === 'prompt_improve' && typeof payload?.goal === 'string' && payload.goal) {+ return payload.goal;+ }return isActionKind(kind) ? t(`${kind}.goal`) : t('unknown.goal');}/** Compact evidence chips under the title: signal count plus the kind's own* count (pages, prompts, competitors). */export function actionContextTags(action: ActionItem, t: Translator): string[] {- // An action sent from a content opportunity has no detection signals by- // design; "0 signals" would read as missing evidence.+ // Actions a person sent (a content opportunity, an Improve set) have no+ // detection signals by design; "0 signals" would read as missing evidence.const tags =- action.kind === 'content_opportunity' ? [] : [t('tags.signals', { count: action.signalCount })];+ action.kind === 'content_opportunity' || action.kind === 'prompt_improve'+ ? []+ : [t('tags.signals', { count: action.signalCount })];const count = num(action.payload ?? {}, 'targetCount');const entity = str(action.payload ?? {}, 'targetEntity');if (count > 0 && entity) tags.push(t(`tags.${entity}`, { count }));diff --git a/web/src/lib/action-center/registry.ts b/web/src/lib/action-center/registry.tsindex f326dd5ab..53e5c9b8e 100644--- a/web/src/lib/action-center/registry.ts+++ b/web/src/lib/action-center/registry.ts@@ -102,7 +102,9 @@ export type ActionKind =| 'earn_competitor_source_presence'| 'create_content_for_competitor_gaps'// Sent by a person from a content opportunity, not raised by a definition.- | 'content_opportunity';+ | 'content_opportunity'+ // Sent by a person from the Prompts Positions panel's Improve tab (PROMPT-004).+ | 'prompt_improve';export type TaskStatus =| 'todo'@@ -217,6 +219,7 @@ export const ACTION_KINDS: readonly ActionKind[] = ['earn_competitor_source_presence','create_content_for_competitor_gaps','content_opportunity',+ 'prompt_improve',];/**diff --git a/web/src/lib/actions/action-center.ts b/web/src/lib/actions/action-center.tsindex 6b1871a2e..d5104633a 100644--- a/web/src/lib/actions/action-center.ts+++ b/web/src/lib/actions/action-center.ts@@ -160,6 +160,18 @@ export interface ActionTask {dependsOn: string[];/** Why the task was skipped; null for every other status. */skipReason: string | null;+ /**+ * What a task sent from the Improve tab carries beyond its title (PROMPT-004):+ * its body, platform and evidence. Null for library and hand-added tasks.+ */+ details: ActionTaskDetails | null;+}++export interface ActionTaskDetails {+ body: string;+ platform: string;+ platformLabel: string;+ sources: { type: string; ref: string }[];}export interface ActionEvent {@@ -191,7 +203,9 @@ export async function getActionDetail(brandId: string, actionId: string): Promisconst [tasksRes, signalsRes, eventsRes, kpisRes] = await Promise.all([supabase.from('action_tasks')- .select('id, position, task_key, title, status, skip_reason, title_params, depends_on')+ .select(+ 'id, position, task_key, title, status, skip_reason, title_params, depends_on, details',+ ).eq('action_id', actionId).order('position'),supabase@@ -226,6 +240,7 @@ export async function getActionDetail(brandId: string, actionId: string): PromistitleParams: (task.title_params ?? {}) as Record<string, string | number>,dependsOn: (task.depends_on ?? []) as string[],skipReason: task.skip_reason,+ details: (task.details ?? null) as ActionTaskDetails | null,})),signals: mapSignalRows((signalsRes.data ?? []) as SignalRow[]),events: (eventsRes.data ?? []).map((event) => ({diff --git a/web/src/lib/actions/prompt-improve.ts b/web/src/lib/actions/prompt-improve.tsindex b742a5f8c..825e9fbe1 100644--- a/web/src/lib/actions/prompt-improve.ts+++ b/web/src/lib/actions/prompt-improve.ts@@ -3,7 +3,13 @@import { createClient } from '@/lib/supabase/server';import { API_BASE_URL } from '@/config/api';// Types only — the helpers that go with them live in a plain module.-import type { ImproveQuota, ImproveRangeInput, ImproveSet } from '@/lib/prompt-improve';+import type {+ ImproveQuota,+ ImproveRangeInput,+ ImproveSent,+ ImproveSet,+ ImproveSource,+} from '@/lib/prompt-improve';/*** Failures come back as a value, not a throw, so the panel can show the real@@ -79,3 +85,51 @@ export async function generateImproveSuggestions(): Promise<ImproveResult> {return call(promptId, range, 'POST');}++export interface SendImproveInput {+ /** One per send, so a double click or a retry creates one action. */+ idempotencyKey: string;+ suggestions: {+ id: string;+ platform: string;+ title: string;+ body: string;+ sources: ImproveSource[];+ }[];+}++type SendResult =+ | { actionId: string; actionNo: number; created: boolean; taskCount: number; sent: ImproveSent }+ | { error: string };++/** Send the selected suggestions, as edited, to Action Center as one action (PROMPT-004). */+export async function sendImproveToActionCenter(+ promptId: string,+ range: ImproveRangeInput,+ input: SendImproveInput,+): Promise<SendResult> {+ const supabase = await createClient();+ const {+ data: { session },+ } = await supabase.auth.getSession();+ if (!session) return { error: 'Not authenticated' };+ const range_: Record<string, string> = {};+ for (const [k, v] of Object.entries(range)) if (typeof v === 'string' && v) range_[k] = v;+ try {+ const res = await fetch(`${API_BASE_URL}/api/prompts/${promptId}/improve/action`, {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${session.access_token}`,+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify({ ...range_, ...input }),+ cache: 'no-store',+ signal: AbortSignal.timeout(30_000),+ });+ const data = await res.json().catch(() => ({}));+ if (!res.ok) return { error: data.message || data.error || `Server error: ${res.status}` };+ return data as SendResult;+ } catch {+ return { error: 'Could not reach the server. Please try again.' };+ }+}diff --git a/web/src/lib/prompt-improve.ts b/web/src/lib/prompt-improve.tsindex 989ed0b9f..e733ebfe6 100644--- a/web/src/lib/prompt-improve.ts+++ b/web/src/lib/prompt-improve.ts@@ -43,7 +43,23 @@ export interface ImprovePlatform {inputs: { fanouts: number; citedDomains: number; competitorUrls: number; answer: boolean } | null;}+/** A send of this set to Action Center that is still live (PROMPT-004). */+export interface ImproveSend {+ actionId: string;+ actionNo: number;+ sentAt: string;+ suggestionIds: string[];+}++export interface ImproveSent {+ /** The newest live send of the current set; decides "Open in Actions". */+ latest: ImproveSend | null;+ /** Suggestions any live send of this set carried ("Already sent"). */+ sentSuggestionIds: string[];+}+export interface ImproveSet {+ sent: ImproveSent;rangeKey: string;region: string;platforms: ImprovePlatform[];@@ -160,3 +176,8 @@ function shortUrl(url: string): string {return url;}}++/** Where "Open in Actions" goes: the Actions tab with this action's panel open. */+export function actionCenterLink(actionId: string): string {+ return `/dashboard/action-center/actions?action=${actionId}`;+}diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex 243585f44..8e4f1346c 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -61,6 +61,7 @@ export type Database = {action_id: stringcreated_at: stringdepends_on: string[]+ details: Json | nullid: stringmode: stringoutput: Json | null@@ -78,6 +79,7 @@ export type Database = {action_id: stringcreated_at?: stringdepends_on?: string[]+ details?: Json | nullid?: stringmode?: stringoutput?: Json | null@@ -95,6 +97,7 @@ export type Database = {action_id?: stringcreated_at?: stringdepends_on?: string[]+ details?: Json | nullid?: stringmode?: stringoutput?: Json | null