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.

fix(content): refuse a Start or a page rewrite while a Fix open rules runs on the draft (#1525)

Cihana622228c6c43
diff --git a/server/src/lib/content-runs.js b/server/src/lib/content-runs.js
index badeb33b9..59e81e799 100644
--- a/server/src/lib/content-runs.js
+++ b/server/src/lib/content-runs.js
@@ -46,9 +46,10 @@ async function shown(what, runId, write) {
/**
* Whether one of the agent's fixes (Fix open rules, Quality's hand-off) is
- * under way on the draft, and not one a stopped server left: a second would
- * make a model call of its own, charged, and its batch would hide the
- * first's (another tab, or a person's beside the editor's own hand-off).
+ * under way on the draft, and not one a stopped server left nor one Stop
+ * ended (its batch is dropped, stopIfStopped): a second would make a model
+ * call of its own, charged, and its batch would hide the first's (another
+ * tab, or a person's beside the editor's own hand-off).
*/
export async function fixUnderWay(draftId) {
const { data, error } = await supabaseAdmin
@@ -57,6 +58,7 @@ export async function fixUnderWay(draftId) {
.eq('draft_id', draftId)
.in('kind', ['fix', 'handoff'])
.is('finished_at', null)
+ .is('stopped_at', null)
.gt('started_at', new Date(Date.now() - RUN_STALE_MS).toISOString())
.limit(1);
if (error) throw error;
@@ -262,8 +264,10 @@ export async function finishRun(run, outcome, counts = {}) {
/**
* Stops a draft's run under way (with `runId`, that run only): marks it
* stopped and aborts its model call when it runs here. Answers the runs it
- * stopped, each with the claim it holds on the draft (claimed_at; null for
- * Fix and the brief, which hold none): none when none was under way.
+ * stopped, each with the claim it holds on the draft (claimed_at: a Start's
+ * or a rewrite's, a live page's Start among them though it runs as a Fix;
+ * null for Fix open rules, Quality's hand-off and the brief, which hold
+ * none): none when none was under way.
*/
export async function stopDraftRun(draftId, runId = null) {
let query = supabaseAdmin
diff --git a/server/src/lib/content-runs.test.js b/server/src/lib/content-runs.test.js
index c463d9087..329edda7b 100644
--- a/server/src/lib/content-runs.test.js
+++ b/server/src/lib/content-runs.test.js
@@ -88,7 +88,7 @@ beforeEach(() => {
});
describe('fixUnderWay', () => {
- it('finds a fix or a hand-off still going on the draft, not one a stopped server left', async () => {
+ it('finds a fix or a hand-off still going on the draft, not one a stopped server left nor one Stop ended', async () => {
rows.updated = [{ id: 'run-1' }];
await expect(fixUnderWay('d1')).resolves.toBe(true);
const [read] = reads;
@@ -97,10 +97,12 @@ describe('fixUnderWay', () => {
['eq', 'draft_id', 'd1'],
['in', 'kind', ['fix', 'handoff']],
['is', 'finished_at', null],
+ // Stopped: its batch is dropped, so a Start or another Fix may go.
+ ['is', 'stopped_at', null],
['gt', 'started_at', expect.any(String)],
]);
// Within RUN_STALE_MS: an older one is a stopped server's.
- expect(Date.now() - Date.parse(read.filters[3][2])).toBeGreaterThanOrEqual(10 * 60_000);
+ expect(Date.now() - Date.parse(read.filters[4][2])).toBeGreaterThanOrEqual(10 * 60_000);
rows.updated = [];
await expect(fixUnderWay('d1')).resolves.toBe(false);
});
diff --git a/server/src/lib/content-writer.js b/server/src/lib/content-writer.js
index 65a059376..b0d417a6a 100644
--- a/server/src/lib/content-writer.js
+++ b/server/src/lib/content-writer.js
@@ -48,7 +48,15 @@ import {
rewriteSchema,
textLength,
} from './content-rewrite.js';
-import { advanceRun, finishRun, isStop, runCall, startRun, stopIfStopped } from './content-runs.js';
+import {
+ advanceRun,
+ finishRun,
+ fixUnderWay,
+ isStop,
+ runCall,
+ startRun,
+ stopIfStopped,
+} from './content-runs.js';
import { getLanguageName } from './languages.js';
import { logger } from './logger.js';
import { reserveAiBudget } from './plan-guard.js';
@@ -338,7 +346,8 @@ async function organizationWriting(organizationId, draftId, staleBefore) {
* that the agent isn't already on it or on another of the organization's
* drafts, the AI usage budget and the model; marks it 'writing' and runs the
* model in the background. Throws with `.status` 404 for a draft outside the
- * brand, 409 (code 'not_draft', 'writing' or 'org_writing'), PlanLimitError
+ * brand, 409 (code 'not_draft', 'writing', 'open_suggestions', 'running'
+ * or 'org_writing'), PlanLimitError
* once the budget is spent, and the provider's error when the model isn't
* set up — all before anything runs.
*/
@@ -379,6 +388,17 @@ export async function startDraftWriting({ draftId, brandId, input, rewrite = fal
code: 'open_suggestions',
});
}
+ // A Fix open rules (or Quality's hand-off) still under way on the draft,
+ // maybe from another tab: a run beside it would make a model call of its
+ // own, charged, and its batch would land on a page this one changes. One at
+ // a time, as Fix open rules refuses beside a Start (content-agent.js). A
+ // live page's Start, which runs as a Fix too, is 'writing' above.
+ if (await fixUnderWay(draftId)) {
+ throw Object.assign(new Error('The agent is already fixing it'), {
+ status: 409,
+ code: 'running',
+ });
+ }
if (rewrite) {
// A page to rewrite, small enough to send whole.
if (!draftPassages(draft.body_html).length) {
diff --git a/server/src/lib/content-writer.test.js b/server/src/lib/content-writer.test.js
index 2e3620eae..c9cb546dd 100644
--- a/server/src/lib/content-writer.test.js
+++ b/server/src/lib/content-writer.test.js
@@ -74,9 +74,11 @@ vi.mock('./plan-guard.js', async (importOriginal) => ({
vi.mock('./logger.js', () => ({ logger: { error: vi.fn(), info: vi.fn(), warn: vi.fn() } }));
const readLinkTargets = vi.hoisted(() => vi.fn());
const stopIfStopped = vi.fn();
+const fixUnderWay = vi.hoisted(() => vi.fn());
vi.mock('./content-runs.js', async (importOriginal) => ({
...(await importOriginal()),
stopIfStopped: (...args) => stopIfStopped(...args),
+ fixUnderWay: (...args) => fixUnderWay(...args),
}));
vi.mock('./content-links.js', async (importOriginal) => ({
...(await importOriginal()),
@@ -161,6 +163,7 @@ beforeEach(() => {
});
reserveAiBudget.mockReset().mockImplementation(realGuard.reserveAiBudget);
hasOpenSuggestions.mockReset().mockResolvedValue(false);
+ fixUnderWay.mockReset().mockResolvedValue(false);
stopIfStopped.mockReset().mockResolvedValue(undefined);
});
@@ -354,6 +357,32 @@ describe('startDraftWriting', () => {
expect(hasOpenSuggestions).not.toHaveBeenCalled();
});
+ it('waits while a Fix open rules runs on the draft, before charging, for a Start or a rewrite', async () => {
+ fixUnderWay.mockResolvedValue(true);
+ for (const [row, rewrite] of [
+ [draftRow(), false],
+ [draftRow({ method: 'optimize', source_url: 'https://acme.example/x' }), false],
+ [draftRow({ method: 'optimize', source_url: 'https://acme.example/x' }), true],
+ ]) {
+ rows.content_drafts = row;
+ await expect(
+ startDraftWriting({ draftId: DRAFT, brandId: BRAND, input: input(), rewrite }),
+ ).rejects.toMatchObject({ status: 409, code: 'running' });
+ }
+ expect(fixUnderWay).toHaveBeenCalledWith(DRAFT);
+ // Nothing held on the budget, no claim on the draft, no model call.
+ expect(reserveAiBudget).not.toHaveBeenCalled();
+ expect(writes).toEqual([]);
+ expect(generateObject).not.toHaveBeenCalled();
+
+ // Once it has finished, the Start goes.
+ fixUnderWay.mockResolvedValue(false);
+ rows.content_drafts = draftRow();
+ await expect(
+ startDraftWriting({ draftId: DRAFT, brandId: BRAND, input: input() }),
+ ).resolves.toEqual({ started: true });
+ });
+
it('writes one of the organization’s drafts at a time', async () => {
rows.writingInOrg = [{ id: 'other-draft' }];
const held = { charge: vi.fn(), release: vi.fn() };
diff --git a/server/src/routes/content-drafts.js b/server/src/routes/content-drafts.js
index 167bb7801..6c3d0cfcb 100644
--- a/server/src/routes/content-drafts.js
+++ b/server/src/routes/content-drafts.js
@@ -286,8 +286,9 @@ const writeBody = writeDraftInput.extend({ brandId: z.guid() });
* Answers 202 { started: true } at once: the agent runs in the background
* and the draft shows where it is (agent_state). 409 when the draft is marked
* ready or published (code not_draft), the agent is on it (code writing) or on
- * another of the organization's drafts (code org_writing), or an existing
- * page's suggestions are still open (code open_suggestions).
+ * another of the organization's drafts (code org_writing), an existing
+ * page's suggestions are still open (code open_suggestions), or a Fix open
+ * rules still runs on it (code running).
*/
router.post('/:draftId/write', async (req, res) => {
const draftId = z.guid().safeParse(req.params.draftId);
@@ -322,7 +323,7 @@ router.post('/:draftId/write', async (req, res) => {
* Rewrite the page to these rules: the agent rewrites the whole page in the
* background and leaves it as ONE suggestion to compare and accept or
* reject. Answers 202 { started: true } at once; 409 as /write (not_draft,
- * writing, org_writing, open_suggestions); 422 when the page has no text
+ * writing, org_writing, open_suggestions, running); 422 when the page has no text
* (empty) or is too long to send whole (too_long).
*/
router.post('/:draftId/rewrite', async (req, res) => {
@@ -387,8 +388,9 @@ router.post('/:draftId/stop', async (req, res) => {
const stopped = await stopDraftRun(draftId.data, runId ?? null);
// A run in the background lets go of the draft once it sees the stop;
// one no server holds any more never would. The editor opens at once.
- // Only the claim a stopped run holds: a Stop on a Fix or the brief (which
- // hold none) leaves a Start or Rewrite on the same draft its claim.
+ // Only the claim a stopped run holds: a Stop on Fix open rules or the
+ // brief (which hold none) leaves a Start or Rewrite on the same draft its
+ // claim. A live page's Start runs as a Fix, and holds its own.
for (const { claimed_at: claimedAt } of stopped) {
if (!claimedAt) continue;
const { error: letGoError } = await supabaseAdmin
diff --git a/web/messages/en.json b/web/messages/en.json
index 0201a3dfd..664c68155 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -3590,6 +3590,7 @@
"writing": "The agent is already working on this draft.",
"org_writing": "The agent is writing another of your team's drafts, so it didn't start. The draft is in the Library for you to write.",
"open_suggestions": "This page has suggestions waiting for review, so the agent didn't start. Accept or reject them in the editor first.",
+ "running": "The agent is already working on this page, so it didn't start. The draft is in the Library for you to write.",
"not_draft": "This draft is no longer a draft, so the agent didn't start.",
"failed": "The agent couldn't start. The draft is in the Library for you to write."
}
@@ -3782,6 +3783,7 @@
"writing": "The agent is already working on this draft.",
"org_writing": "The agent is writing another of your team's drafts. Try again in a minute or two.",
"open_suggestions": "Accept or reject the open suggestions first, then try again.",
+ "running": "Content Agent is fixing this page, maybe from another tab. Try again once it has finished.",
"not_draft": "This draft is no longer a draft, so the agent didn't start.",
"empty": "The page has no text to rewrite yet.",
"too_long": "The page is too long to rewrite whole. Use Fix open rules, or shorten it first.",
diff --git a/web/src/lib/actions/content-drafts-start.test.ts b/web/src/lib/actions/content-drafts-start.test.ts
index fa0a34cbb..cb52410cf 100644
--- a/web/src/lib/actions/content-drafts-start.test.ts
+++ b/web/src/lib/actions/content-drafts-start.test.ts
@@ -932,6 +932,14 @@ describe('startAgentWriting', () => {
await expect(startAgentWriting(OPPORTUNITY, BRAND, request)).resolves.toEqual({
error: 'ai_budget',
});
+ // A Fix open rules still under way on the draft.
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => new Response('{"code":"running"}', { status: 409 })),
+ );
+ await expect(startAgentWriting(OPPORTUNITY, BRAND, request)).resolves.toEqual({
+ error: 'running',
+ });
vi.stubGlobal(
'fetch',
vi.fn(async () => new Response('{"code":"something_new"}', { status: 500 })),
diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.ts
index cf48f41e4..6e82e3e38 100644
--- a/web/src/lib/actions/content-drafts.ts
+++ b/web/src/lib/actions/content-drafts.ts
@@ -2365,6 +2365,8 @@ const AGENT_WRITE_ERRORS = [
'writing',
'org_writing',
'open_suggestions',
+ // A Fix open rules or Quality's hand-off still under way on the draft (content-writer.js).
+ 'running',
'not_draft',
// Rewrite the page to these rules: a page with no text, or one too long to send whole.
'empty',