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
fix(content): open again the Action Center task Ready completed when the page goes back from Ready (#1447)
Cihana0edfa82ee96
diff --git a/docs/guides/action-center.mdx b/docs/guides/action-center.mdxindex a6d3fb70c..2919aac26 100644--- a/docs/guides/action-center.mdx+++ b/docs/guides/action-center.mdx@@ -87,7 +87,7 @@ A task's status is **To Do**, **In Progress**, **Completed** or **Skipped** (witFrom a task you can also:-- **Create content** or **Optimize page** — open a draft in the [Content Editor](/guides/content-editor) for this task. **Open draft** returns to it, and marking the draft ready completes the task.+- **Create content** or **Optimize page** — open a draft in the [Content Editor](/guides/content-editor) for this task. **Open draft** returns to it, and marking the draft ready completes the task. Moving the draft back from Ready opens the task again, unless someone changed the task since or the action is closed.- **Send to Content** — send a content task to Content as an opportunity, where a brief can be written for it.- **Send to webhook** — post the task to the brand's webhook, for a workflow outside Ansvisor. The webhook is set up under **Content → Webhook Settings**, with the **Action Center task sent** event selected.diff --git a/docs/guides/content-editor.mdx b/docs/guides/content-editor.mdxindex 347adf5d9..9717e04a0 100644--- a/docs/guides/content-editor.mdx+++ b/docs/guides/content-editor.mdx@@ -148,6 +148,7 @@ The Content Agent never changes these passages. If you edit one, the editor asks- **Export** downloads the page as **Word**, **HTML** or **Markdown**. Only the HTML file carries the schema (JSON-LD).- **Add HTML** in the toolbar adds an HTML block: an embed, a widget or a form, kept exactly as written. Ansvisor never runs it. **Edit as HTML** shows the page's source; scripts, iframes and inline styles are removed when you switch back.- **Mark ready** saves the page, sets it to **Ready** and keeps a version in History. If the draft was sent to the Action Center, it also completes its task there. Ansvisor doesn't publish the page: copy or export it to your site.+- Click **Ready** in the header to move the page back to **In review**. A task that Mark ready completed is open again (**In Progress**), unless someone changed it in the Action Center since or the action is closed.## Library@@ -166,7 +167,7 @@ The columns are Content, Type, Method (Create or Optimize), By (you, the Content### Row menu-- **Status**: set the draft to In progress, In review, Ready or Published. Ready works like the editor's Mark ready.+- **Status**: set the draft to In progress, In review, Ready or Published. Ready works like the editor's Mark ready, and moving a ready or published draft back to In progress or In review opens its task again, as the editor's **Ready** does.- **Export Word**, **Export HTML** or **Export Markdown** for that draft.- **Send to Archive** or **Restore** (admins and managers).- **Delete** (admins and managers): the draft leaves the Library for good, with its versions and suggestions. An Action Center task it was sent as stays.diff --git a/web/messages/en.json b/web/messages/en.jsonindex 27746689d..1493e0c29 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -3604,6 +3604,7 @@"readyHint": "Marked ready. Click to move it back to review.","publishedHint": "Published. Change its status in the Library.","backInReview": "Back in review.",+ "backInReviewAction": "Back in review, and {count, plural, one {its task} other {its # tasks}} in Action AC-{no} {count, plural, one {is} other {are}} open again.","backInReviewFailed": "Couldn't move it back to review.","notReady": "Its status is now {status}, so it stays.","renameInHtml": "Rename it in the HTML view's text, or close the view to rename it in the page."diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsxindex 926203dc5..9d3cd30a4 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx@@ -1780,17 +1780,19 @@ export function DraftEditor({/*** Ready, clicked (Next step spec §3b): the page goes back to review, while* it is still ready (published meanwhile from the Library, it says so). The- * task Mark ready completed stays done.+ * task Mark ready completed is open again, unless someone changed it since.*/const [unmarking, setUnmarking] = useState(false);const unmarkReady = async () => {if (unmarking) return;setUnmarking(true);try {- const now = await unmarkContentDraftReady(draft.id);+ const { status: now, tasksReopened } = await unmarkContentDraftReady(draft.id);setStatus(now);- if (now === 'in_review') toast(t('header.backInReview'));- else toast(t('header.notReady', { status: tDraftStatus(now) }));+ if (now !== 'in_review') toast(t('header.notReady', { status: tDraftStatus(now) }));+ else if (tasksReopened > 0 && draft.action) {+ toast(t('header.backInReviewAction', { no: draft.action.number, count: tasksReopened }));+ } else toast(t('header.backInReview'));} catch (err) {console.error('Failed to move the draft back to review:', err);toast.error(t('header.backInReviewFailed'));diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsxindex 76c408b05..4ea69476f 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx@@ -260,7 +260,7 @@ beforeEach(() => {readDraftAiUsage.mockReset().mockResolvedValue(3.7);getContentDraft.mockReset();markContentDraftReady.mockReset();- unmarkContentDraftReady.mockReset().mockResolvedValue('in_review');+ unmarkContentDraftReady.mockReset().mockResolvedValue({ status: 'in_review', tasksReopened: 0 });saveBlob.mockReset();setContentDraftPageType.mockReset().mockResolvedValue(undefined);setContentDraftAuthor.mockReset().mockResolvedValue(undefined);@@ -789,7 +789,7 @@ describe('the content editor', () => {expect(toast.error).toHaveBeenCalledWith("Couldn't move it back to review.");expect(button('Ready: click to move it back to review')).toBeDefined();- unmarkContentDraftReady.mockResolvedValueOnce('published');+ unmarkContentDraftReady.mockResolvedValueOnce({ status: 'published', tasksReopened: 0 });await act(async () => button('Ready: click to move it back to review')!.click());expect(toast).toHaveBeenCalledWith('Its status is now Published, so it stays.');expect(button('Published')!.getAttribute('aria-disabled')).toBe('true');@@ -859,6 +859,13 @@ describe('the content editor', () => {"Marked ready, and its task in Action AC-214 is done. Publish it on your site when you're ready.",);expect(note.textContent).toBe('This draft is the work of Action AC-214.');++ // Taken back, the task Ready completed is open again.+ unmarkContentDraftReady.mockResolvedValueOnce({ status: 'in_review', tasksReopened: 1 });+ await act(async () => button('Ready: click to move it back to review')!.click());+ expect(toast).toHaveBeenCalledWith(+ 'Back in review, and its task in Action AC-214 is open again.',+ );});describe('history', () => {diff --git a/web/src/lib/actions/content-drafts-library.test.ts b/web/src/lib/actions/content-drafts-library.test.tsindex f58aed753..c9173a5f0 100644--- a/web/src/lib/actions/content-drafts-library.test.ts+++ b/web/src/lib/actions/content-drafts-library.test.ts@@ -16,6 +16,11 @@ let writeResult: { data: unknown; error: { code?: string; message: string } | nuvi.mock('@/lib/action-center/assignees', () => ({ readAssignees: vi.fn(async () => new Map()) }));vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin: {} }));+const reopenDraftTasks = vi.hoisted(() => vi.fn());+vi.mock('@/lib/content/action-drafts', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/lib/content/action-drafts')>()),+ reopenDraftTasks,+}));vi.mock('@/lib/supabase/server', () => ({createClient: vi.fn(async () => ({auth: { getUser: async () => ({ data: { user: { id: 'u1' } } }) },@@ -124,6 +129,29 @@ describe('the Library row menu (00233)', () => {it('sets a status any member may set', async () => {await setContentDraftStatus(DRAFT, 'in_review');expect(writes).toEqual([{ op: 'update', value: { status: 'in_review' }, id: DRAFT }]);+ expect(reopenDraftTasks).not.toHaveBeenCalled();+ });++ it('opens again the task Ready completed when a ready page goes back, as the editor does', async () => {+ reopenDraftTasks.mockReset().mockResolvedValue(1);+ const ready = {+ id: DRAFT,+ status: 'ready',+ brand_id: 'b1',+ method: 'optimize',+ action_id: 'a1',+ };+ writeResult = { data: ready, error: null };+ await setContentDraftStatus(DRAFT, 'draft');+ expect(reopenDraftTasks).toHaveBeenCalledWith(+ expect.anything(),+ { id: DRAFT, brandId: 'b1', actionId: 'a1', method: 'optimize' },+ 'u1',+ );+ // Published from Ready, the work stays done.+ reopenDraftTasks.mockClear();+ await setContentDraftStatus(DRAFT, 'published');+ expect(reopenDraftTasks).not.toHaveBeenCalled();});it('refuses Ready (it goes through Mark ready) and a malformed id, writing nothing', async () => {diff --git a/web/src/lib/actions/content-drafts.test.ts b/web/src/lib/actions/content-drafts.test.tsindex 788b1c8c5..846eaa59c 100644--- a/web/src/lib/actions/content-drafts.test.ts+++ b/web/src/lib/actions/content-drafts.test.ts@@ -28,9 +28,11 @@ let rpcResult: { data: unknown; error: { message: string } | null };vi.mock('@/lib/action-center/assignees', () => ({ readAssignees: vi.fn(async () => new Map()) }));vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin: {} }));const completeDraftTasks = vi.hoisted(() => vi.fn());+const reopenDraftTasks = vi.hoisted(() => vi.fn());vi.mock('@/lib/content/action-drafts', async (importOriginal) => ({...(await importOriginal<typeof import('@/lib/content/action-drafts')>()),completeDraftTasks,+ reopenDraftTasks,}));vi.mock('@/lib/supabase/server', () => ({createClient: vi.fn(async () => ({@@ -103,6 +105,7 @@ beforeEach(() => {rpcCalls = [];rpcResult = { data: 'v-new', error: null };completeDraftTasks.mockReset().mockResolvedValue(0);+ reopenDraftTasks.mockReset().mockResolvedValue(0);});describe('saveContentDraft', () => {@@ -347,7 +350,11 @@ describe('setContentDraftAuthor', () => {describe('unmarkContentDraftReady', () => {it('moves a ready draft back to review, and only a ready one', async () => {updated = { status: 'in_review' };- await expect(unmarkContentDraftReady(DRAFT)).resolves.toBe('in_review');+ await expect(unmarkContentDraftReady(DRAFT)).resolves.toEqual({+ status: 'in_review',+ tasksReopened: 0,+ });+ expect(reopenDraftTasks).not.toHaveBeenCalled();expect(calls[0]).toMatchObject({op: 'update',value: { status: 'in_review' },@@ -358,6 +365,28 @@ describe('unmarkContentDraftReady', () => {});});+ it('opens again the task Ready completed in the action the draft is the work of', async () => {+ updated = { status: 'in_review', brand_id: 'b1', method: 'create', action_id: 'act-1' };+ reopenDraftTasks.mockResolvedValue(1);+ await expect(unmarkContentDraftReady(DRAFT)).resolves.toEqual({+ status: 'in_review',+ tasksReopened: 1,+ });+ expect(reopenDraftTasks).toHaveBeenCalledWith(+ expect.anything(),+ { id: DRAFT, brandId: 'b1', actionId: 'act-1', method: 'create' },+ 'u1',+ );++ // The draft is back in review even when the task couldn't be opened.+ reopenDraftTasks.mockRejectedValue(new Error('rls'));+ vi.spyOn(console, 'error').mockImplementation(() => undefined);+ await expect(unmarkContentDraftReady(DRAFT)).resolves.toEqual({+ status: 'in_review',+ tasksReopened: 0,+ });+ });+it('leaves a draft published meanwhile published, and says so', async () => {updated = null;row = {@@ -371,7 +400,11 @@ describe('unmarkContentDraftReady', () => {author: 'user',updated_at: '2026-10-20T15:00:00Z',};- await expect(unmarkContentDraftReady(DRAFT)).resolves.toBe('published');+ await expect(unmarkContentDraftReady(DRAFT)).resolves.toEqual({+ status: 'published',+ tasksReopened: 0,+ });+ expect(reopenDraftTasks).not.toHaveBeenCalled();await expect(unmarkContentDraftReady('d1')).rejects.toThrow('invalid');});});diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.tsindex b338d725b..273ddd08d 100644--- a/web/src/lib/actions/content-drafts.ts+++ b/web/src/lib/actions/content-drafts.ts@@ -84,6 +84,7 @@ import {completeDraftTasks,draftMethodForTask,findActionDraft,+ reopenDraftTasks,setDraftTasksStatus,type ActionDraft,} from '@/lib/content/action-drafts';@@ -1228,7 +1229,9 @@ const ROW_STATUSES = ['draft', 'in_review', 'published'] as const;/*** Set a draft's status from the Library's row menu (any member, as the* editor's own status changes). Ready keeps a History version and completes- * the draft's task, so it goes through markContentDraftReady instead.+ * the draft's task, so it goes through markContentDraftReady instead. A+ * ready or published draft moved back to Draft or In review opens again the+ * task Ready completed, as the editor's Ready does when clicked.*/export async function setContentDraftStatus(id: string,@@ -1238,6 +1241,13 @@ export async function setContentDraftStatus(throw new Error('invalid');}const supabase = await createClient();+ const { data: before, error: readError } = await supabase+ .from('content_drafts')+ .select('status, brand_id, method, action_id')+ .eq('id', id)+ .maybeSingle();+ if (readError) throw new Error(readError.message);+ if (!before) throw new Error('not_found');const { data, error } = await supabase.from('content_drafts').update({ status })@@ -1246,6 +1256,8 @@ export async function setContentDraftStatus(.maybeSingle();if (error) throw new Error(error.message);if (!data) throw new Error('not_found');+ const wasDone = before.status === 'ready' || before.status === 'published';+ if (wasDone && status !== 'published') await reopenTasksOf(supabase, id, before);}/**@@ -1361,10 +1373,13 @@ export async function markContentDraftReady(/*** Ready, clicked in the editor's header (Next step spec §3b): the page goes* back to review, only while it is still ready. One published from the- * Library meanwhile keeps its status. Returns the status the draft has after.- * The task Mark ready completed stays done.+ * Library meanwhile keeps its status. Returns the status the draft has after,+ * and how many of its action's tasks, completed by Ready, it opened again+ * (reopenDraftTasks).*/-export async function unmarkContentDraftReady(id: string): Promise<DraftStatus> {+export async function unmarkContentDraftReady(+ id: string,+): Promise<{ status: DraftStatus; tasksReopened: number }> {if (!draftId.safeParse(id).success) throw new Error('invalid');const supabase = await createClient();const { data, error } = await supabase@@ -1372,13 +1387,50 @@ export async function unmarkContentDraftReady(id: string): Promise<DraftStatus>.update({ status: 'in_review' }).eq('id', id).eq('status', 'ready')- .select('status')+ .select('status, brand_id, method, action_id').maybeSingle();if (error) throw new Error(error.message);- if (data) return draftStatus(data.status);+ if (data) {+ return {+ status: draftStatus(data.status),+ tasksReopened: await reopenTasksOf(supabase, id, data),+ };+ }const current = await getContentDraft(id);if (!current) throw new Error('not_found');- return current.status;+ return { status: current.status, tasksReopened: 0 };+}++/**+ * The tasks a draft's Ready completed in its action, open again once the+ * draft isn't ready or published any more (reopenDraftTasks). The draft's+ * status has changed either way: a failure is logged, and a task left done+ * can be changed in the drawer.+ */+async function reopenTasksOf(+ supabase: Awaited<ReturnType<typeof createClient>>,+ id: string,+ draft: { brand_id: string; method: string; action_id: string | null },+): Promise<number> {+ if (!draft.action_id) return 0;+ try {+ const {+ data: { user },+ } = await supabase.auth.getUser();+ return await reopenDraftTasks(+ supabase,+ {+ id,+ brandId: draft.brand_id,+ actionId: draft.action_id,+ method: draft.method === 'create' ? 'create' : 'optimize',+ },+ user?.id ?? null,+ );+ } catch (err) {+ console.error("Failed to reopen the action's task:", err);+ return 0;+ }}/**diff --git a/web/src/lib/content/action-drafts.test.ts b/web/src/lib/content/action-drafts.test.tsindex 52651868b..92f1b3f41 100644--- a/web/src/lib/content/action-drafts.test.ts+++ b/web/src/lib/content/action-drafts.test.ts@@ -5,12 +5,14 @@ import {completeDraftTasks,draftMethodForTask,findActionDraft,+ reopenDraftTasks,type ActionDraft,} from './action-drafts';/*** An action's writing tasks and their drafts (CE-022): which draft a task is- * written in, and Ready completing the task once the work's drafts are done.+ * written in, Ready completing the task once the work's drafts are done, and+ * Ready taken back opening it again.*/interface Op {@@ -32,6 +34,7 @@ const db = {in: (col: string, v: unknown) => (op.filters.push(['in', col, v]), chain),is: (col: string, v: unknown) => (op.filters.push(['is', col, v]), chain),limit: () => chain,+ order: () => chain,update: (value: unknown) => ((op.op = 'update'), (op.value = value), chain),insert: (value: unknown) => ((op.op = 'insert'), (op.value = value), chain),maybeSingle: async () => ({ data: rows[table]?.[0] ?? null, error: null }),@@ -176,3 +179,73 @@ describe('completeDraftTasks', () => {expect(ops.map((op) => op.table)).toEqual(['actions']);});});++describe('reopenDraftTasks', () => {+ it('opens again the work’s tasks a draft’s Ready completed, each in the action’s History', async () => {+ rows.actions = [{ status: 'in_progress' }];+ rows.action_tasks = [+ { id: 't-optimize', status: 'completed' },+ { id: 't-refresh', status: 'completed' },+ { id: 't-other', status: 'skipped' },+ ];+ // Newest first: t-refresh was completed by a person after Ready.+ rows.action_events = [+ { data: { taskId: 't-refresh', to: 'completed' } },+ { data: { taskId: 't-optimize', to: 'completed', draftId: 'd2' } },+ { data: { taskId: 't-refresh', to: 'completed', draftId: 'd2' } },+ ];+ await expect(reopenDraftTasks(db, draft, 'u1')).resolves.toBe(1);+ expect(ops[1].filters).toContainEqual([+ 'in',+ 'task_key',+ ['optimize_content', 'refresh_content'],+ ]);+ expect(ops[2]).toMatchObject({+ table: 'action_events',+ filters: [+ ['eq', 'action_id', 'act-1'],+ ['eq', 'event', 'task_status'],+ ],+ });+ expect(ops.slice(3, 5)).toEqual([+ {+ table: 'action_tasks',+ op: 'update',+ value: expect.objectContaining({ status: 'in_progress', skip_reason: null }),+ filters: [+ ['eq', 'action_id', 'act-1'],+ ['eq', 'id', 't-optimize'],+ ],+ },+ {+ table: 'action_events',+ op: 'insert',+ value: {+ action_id: 'act-1',+ event: 'task_status',+ data: { taskId: 't-optimize', to: 'in_progress', draftId: 'd1' },+ actor_id: 'u1',+ },+ filters: [],+ },+ ]);+ });++ it('leaves a closed action’s tasks as they are', async () => {+ rows.actions = [{ status: 'completed' }];+ rows.action_tasks = [{ id: 't-optimize', status: 'completed' }];+ await expect(reopenDraftTasks(db, draft, 'u1')).resolves.toBe(0);+ expect(ops).toHaveLength(1);+ });++ it('leaves a deleted action’s tasks, and reads no History when none is done', async () => {+ await expect(reopenDraftTasks(db, draft, 'u1')).resolves.toBe(0);+ expect(ops).toHaveLength(1);++ ops = [];+ rows.actions = [{ status: 'in_progress' }];+ rows.action_tasks = [{ id: 't-optimize', status: 'in_progress' }];+ await expect(reopenDraftTasks(db, draft, 'u1')).resolves.toBe(0);+ expect(ops.some((op) => op.table === 'action_events')).toBe(false);+ });+});diff --git a/web/src/lib/content/action-drafts.ts b/web/src/lib/content/action-drafts.tsindex aa18555c4..662517374 100644--- a/web/src/lib/content/action-drafts.ts+++ b/web/src/lib/content/action-drafts.ts@@ -1,7 +1,7 @@/*** The Content Editor and the Action Center, both ways (CE-022, spec §15): an- * action's writing task opens a draft linked to the action, and marking that- * draft Ready completes the task.+ * action's writing task opens a draft linked to the action, marking that+ * draft Ready completes the task, and taking Ready back opens it again.** A draft is linked through content_drafts.action_id (00208). An action can* hold a new page's task and an existing page's, and name several pages: it@@ -9,6 +9,7 @@*/import type { SupabaseClient } from '@supabase/supabase-js';+import { CLOSED_ACTION_STATUSES, type ActionStatus } from '@/lib/action-center/registry';import type { DraftMethod, DraftStatus } from './drafts';/** The library tasks a draft is the work of, by the draft's method. */@@ -150,3 +151,61 @@ export async function completeDraftTasks();return todo.length;}++/**+ * Ready taken back (the editor's header, Next step spec §3b): the tasks for+ * the draft's work that a draft's Ready completed go back to in progress,+ * each in the action's History. A task whose latest change was a person's+ * (in the drawer, or through the API) stays as it is, as do a deleted+ * action's (00168) and a closed one's (completed or dismissed). Returns how+ * many tasks it reopened.+ */+export async function reopenDraftTasks(+ db: SupabaseClient,+ draft: { id: string; brandId: string; actionId: string; method: DraftMethod },+ actorId: string | null,+): Promise<number> {+ const { data: action, error: actionError } = await db+ .from('actions')+ .select('status')+ .eq('id', draft.actionId)+ .is('deleted_at', null)+ .maybeSingle();+ if (actionError) throw new Error(actionError.message);+ if (!action || CLOSED_ACTION_STATUSES.includes(action.status as ActionStatus)) return 0;++ const { data: tasks, error: tasksError } = await db+ .from('action_tasks')+ .select('id, status')+ .eq('action_id', draft.actionId)+ .in('task_key', [...DRAFT_TASK_KEYS[draft.method]]);+ if (tasksError) throw new Error(tasksError.message);+ const completed = (tasks ?? []).filter((task) => task.status === 'completed');+ if (!completed.length) return 0;++ const { data: events, error: eventsError } = await db+ .from('action_events')+ .select('data')+ .eq('action_id', draft.actionId)+ .eq('event', 'task_status')+ .order('created_at', { ascending: false });+ if (eventsError) throw new Error(eventsError.message);+ // Each task's latest change, newest first: a draft's Ready names its draft.+ const latest = new Map<string, { to?: unknown; draftId?: unknown }>();+ for (const event of events ?? []) {+ const data = event.data as { taskId?: unknown; to?: unknown; draftId?: unknown } | null;+ if (typeof data?.taskId === 'string' && !latest.has(data.taskId)) latest.set(data.taskId, data);+ }+ const byReady = completed.filter((task) => {+ const change = latest.get(task.id);+ return change?.to === 'completed' && typeof change.draftId === 'string';+ });+ await setDraftTasksStatus(+ db,+ draft,+ byReady.map((task) => task.id),+ 'in_progress',+ actorId,+ );+ return byReady.length;+}