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): read how an agent run ended when its answer is lost, and say why a run left nothing (#1518)

Cihanf59ab4009fa3
diff --git a/server/src/lib/content-agent.js b/server/src/lib/content-agent.js
index f604bb668..873993bbb 100644
--- a/server/src/lib/content-agent.js
+++ b/server/src/lib/content-agent.js
@@ -476,6 +476,21 @@ export function keepSuggestions(raw, passages, lockedKeys, ruleKeys, links = nul
return kept;
}
+/**
+ * Why a run left nothing to review (editor test 2026-10-25), so the editor
+ * says what to do: the model proposed nothing ('none'); every change it
+ * proposed was in a passage AI answers quote, which the page keeps word for
+ * word ('locked'); or the checks dropped the rest ('dropped': an invented
+ * number, a heading grown too long…).
+ */
+export function emptyWhy(raw, passages, lockedKeys) {
+ if (!raw?.length) return 'none';
+ const onLocked = raw.filter(
+ (s) => s.kind === 'replace' && lockedKeys.has(passageKey(passages[s.passage - 1]?.text ?? '')),
+ );
+ return onLocked.length === raw.length ? 'locked' : 'dropped';
+}
+
/**
* A change row with the sources its suggestion names and the marks on its
* words (a replace's after_text, an insert's HTML read as text); null when
@@ -754,6 +769,9 @@ export async function fixDraftRules({ draftId, brandId, input, handoff = null })
run,
handoff: !!handoff,
});
+ // Why it left nothing, on its writing step: an editor whose answer was
+ // lost reads it there (jsonb, so no column).
+ if (result.why && run?.steps?.[2]) run.steps[2] = { ...run.steps[2], why: result.why };
await finishRun(run, 'done', { 2: result.count });
return result;
} catch (err) {
@@ -908,7 +926,9 @@ async function fixWithRun({
);
// Stopped meanwhile: nothing it wrote is kept.
await stopIfStopped(run);
- if (!rows.length) return { count: 0, batchId: null };
+ if (!rows.length) {
+ return { count: 0, batchId: null, why: emptyWhy(object.suggestions, passages, lockedKeys) };
+ }
const batchId = randomUUID();
const { error: insertError } = await supabaseAdmin.from('content_draft_suggestions').insert(
diff --git a/server/src/lib/content-agent.test.js b/server/src/lib/content-agent.test.js
index 38b667525..51de00a41 100644
--- a/server/src/lib/content-agent.test.js
+++ b/server/src/lib/content-agent.test.js
@@ -75,6 +75,7 @@ const {
cleanInsertHtml,
draftPassages,
dropsPlaceholder,
+ emptyWhy,
fixDraftRules,
keepSuggestions,
growsPastLimit,
@@ -1015,11 +1016,32 @@ describe('fixDraftRules', () => {
expect(writes.find((w) => w.table === 'prompt_improve_usage')).toBeDefined();
});
+ it('says why a run left nothing: none proposed, all in quoted passages, or dropped', () => {
+ const passages = [
+ { tag: 'p', text: 'A quoted passage.' },
+ { tag: 'p', text: 'A free one.' },
+ ];
+ const locked = new Set([passageKey('A quoted passage.')]);
+ expect(emptyWhy([], passages, locked)).toBe('none');
+ expect(emptyWhy([{ kind: 'replace', passage: 1 }], passages, locked)).toBe('locked');
+ expect(
+ emptyWhy(
+ [
+ { kind: 'replace', passage: 1 },
+ { kind: 'replace', passage: 2 },
+ ],
+ passages,
+ locked,
+ ),
+ ).toBe('dropped');
+ expect(emptyWhy([{ kind: 'insert', passage: 1 }], passages, locked)).toBe('dropped');
+ });
+
it('keeps nothing when the agent found nothing it could change', async () => {
generateObject.mockResolvedValue({ object: { suggestions: [] }, usage: {} });
await expect(
fixDraftRules({ draftId: DRAFT, brandId: BRAND, input: input() }),
- ).resolves.toEqual({ count: 0, batchId: null });
+ ).resolves.toEqual({ count: 0, batchId: null, why: 'none' });
expect(writes.some((w) => w.table === 'content_draft_suggestions')).toBe(false);
});
@@ -1065,7 +1087,7 @@ describe('fixDraftRules', () => {
});
await expect(
fixDraftRules({ draftId: DRAFT, brandId: BRAND, input: input() }),
- ).resolves.toEqual({ count: 0, batchId: null });
+ ).resolves.toEqual({ count: 0, batchId: null, why: 'none' });
});
it('refuses a published draft, or one whose latest batch is still open, before charging', async () => {
@@ -1095,7 +1117,7 @@ describe('fixDraftRules', () => {
generateObject.mockResolvedValue({ object: { suggestions: [] }, usage: {} });
await expect(
fixDraftRules({ draftId: DRAFT, brandId: BRAND, input: input() }),
- ).resolves.toEqual({ count: 0, batchId: null });
+ ).resolves.toEqual({ count: 0, batchId: null, why: 'none' });
});
it('stops at the budget', async () => {
diff --git a/server/src/routes/content-drafts.js b/server/src/routes/content-drafts.js
index 6c3d0cfcb..5b995d614 100644
--- a/server/src/routes/content-drafts.js
+++ b/server/src/routes/content-drafts.js
@@ -208,8 +208,9 @@ const fixBody = fixRulesInput.extend({ brandId: z.guid() });
/**
* POST /api/content-drafts/:draftId/suggestions
* Body: { brandId, rules: [{ key, name, detail }], textRules, locked }
- * Answers { count, batchId }: the suggestions left for review (none when the
- * agent found nothing it could change); 409 `open_suggestions` while the
+ * Answers { count, batchId, why? }: the suggestions left for review (none when
+ * the agent found nothing it could change, with `why`: 'none', 'locked' or
+ * 'dropped', content-agent.js emptyWhy); 409 `open_suggestions` while the
* latest batch is undecided, 409 `published` for a published draft, 409
* `running` while a fix or a hand-off on it is under way.
*/
@@ -245,7 +246,7 @@ const handOffBody = handOffInput.extend({ brandId: z.guid() });
/**
* POST /api/content-drafts/:draftId/handoff
* Body: { brandId, items: [{ key, detail }], textRules, locked, sources?, origin }
- * Quality's hand-off (CE-051): answers { count, batchId } as /suggestions
+ * Quality's hand-off (CE-051): answers { count, batchId, why? } as /suggestions
* does, with its errors; 404 `off` before Quality's phase 2, 409 `not_due`
* for an automatic one the brand doesn't hand off, 409 `already` when the
* draft had its automatic one.
diff --git a/web/messages/en.json b/web/messages/en.json
index 947179c51..551ea0804 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -3803,6 +3803,8 @@
}
},
"agentCard": {
+ "runFailed": "Content Agent couldn't finish",
+ "runFailedLine": "Nothing it wrote was kept. Try again; if it fails again, fix what's left yourself.",
"placeholders": "{count, plural, one {# placeholder} other {# placeholders}} to fill",
"waiting": "{count, plural, one {Content Agent has # suggestion for you} other {Content Agent has # suggestions for you}}",
"gain": "Rules {met, number} → {after, number} of {total, number}",
@@ -3911,6 +3913,7 @@
"fixed": "{count, plural, one {Content Agent suggested # change} other {Content Agent suggested # changes}} · review them in the page",
"fixedMax": "Content Agent suggested {count} changes, the most one run makes · review them, then run it again for the rules still open",
"nothingToFix": "Content Agent found nothing it could change without new facts.",
+ "nothingToFixLocked": "Content Agent's changes were all in passages AI answers quote, which it keeps. Unlock the ones you're fine to change (Edit anyway), or change them yourself.",
"notForAgent": "Content Agent doesn't change heading levels: make the extra H1s H2s in the toolbar.",
"notForAgentFeed": "Content Agent doesn't change a price, GTIN or stock: check which is right, the page or your product feed, and fix that one.",
"decideFirst": "{count, plural, one {Review the open suggestion first, then run the agent.} other {Review the open suggestions first, then run the agent.}}",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-card.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-card.test.tsx
index 023570e0b..a175043e3 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-card.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-card.test.tsx
@@ -309,6 +309,13 @@ describe('AgentCard', () => {
expect(container.textContent).not.toContain('longer than the page before');
});
+ it('says the last run failed in place of an earlier batch’s review', async () => {
+ await render([suggestion({ status: 'accepted' })], false, { lastRunFailed: true });
+ expect(container.textContent).toContain("Content Agent couldn't finish");
+ expect(container.textContent).toContain('Nothing it wrote was kept.');
+ expect(container.textContent).not.toContain('All suggestions reviewed');
+ });
+
it('says it is working, with nothing to press', async () => {
await render([], true);
const card = container.querySelector('[role="region"]')!;
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-card.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-card.tsx
index cdb81ddef..7546fe275 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-card.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-card.tsx
@@ -214,6 +214,7 @@ export function AgentCard({
next = null,
onAllSteps,
length = null,
+ lastRunFailed = false,
}: {
suggestions: DraftSuggestion[];
rules: CardRules;
@@ -260,6 +261,8 @@ export function AgentCard({
} | null;
/** Opens the basket with every step. */
onAllSteps?: () => void;
+ /** The agent's last run failed: said in place of an earlier batch's review. */
+ lastRunFailed?: boolean;
/**
* The page's Length rule (its target and band) and what a rewrite keeps
* as it is: a rewrite's result is read against it, never the agent's say.
@@ -454,6 +457,9 @@ export function AgentCard({
)}
</>
);
+ } else if (lastRunFailed) {
+ title = t('runFailed');
+ line = t('runFailedLine');
} else {
title = t('reviewed');
line = (
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.tsx
index 7dd815723..121641f05 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
@@ -41,6 +41,7 @@ import {
getCitedPassages,
getDraftSuggestions,
getLastPageRewrite,
+ type AgentEmptyWhy,
keepAgentBeforeVersion,
markContentDraftReady,
unmarkContentDraftReady,
@@ -60,7 +61,7 @@ import {
} from '@/lib/actions/content-drafts';
import { getSiteTrust } from '@/lib/actions/audits';
import { getContentAuthors } from '@/lib/actions/content-authors';
-import { stopAgentRun } from '@/lib/content/agent-runs-client';
+import { readAgentRun, stopAgentRun } from '@/lib/content/agent-runs-client';
import { agentWriteRequest, useRuleDescriber } from '@/lib/content/agent-write';
import { authorInitials, canEditAuthor, type AuthorsRead } from '@/lib/content/authors';
import type { SiteTrust } from '@/lib/content/site-trust';
@@ -298,16 +299,41 @@ const FIX_WAIT_MS = 90_000;
const FIX_RUNS = ['fix', 'handoff'] as const;
const BRIEF_RUNS = ['brief'] as const;
+/** How a run whose answer was lost on the way ended, as the page and the run's row say. */
+type AgentOutcome =
+ | { batch: DraftSuggestion[] }
+ | { nothing: true; why?: AgentEmptyWhy }
+ | { stopped: true }
+ | { failed: true }
+ | null;
+
/**
- * The draft's suggestions once a new open batch lands, read every few
- * seconds until the deadline; null if none did. Fix open rules only runs
- * with none open, so any open one is the agent's.
+ * How Fix open rules' run ended when its answer didn't come back (a timeout
+ * on the way), read every few seconds until the deadline: its batch once it
+ * lands, or its row once it's finished (content_agent_runs) — done with
+ * nothing left, and why (editor test 2026-10-25: read as "couldn't run"
+ * after 90 s), stopped, or failed. Fix open rules only runs with none open,
+ * so any open suggestion is the agent's. Its row is Fix's kinds' latest that
+ * isn't the one there was before it was asked (`before`). Null when neither
+ * came in time.
*/
-async function agentBatch(draftId: string, until: number): Promise<DraftSuggestion[] | null> {
+async function agentOutcome(
+ draftId: string,
+ before: string | null,
+ until: number,
+): Promise<AgentOutcome> {
while (Date.now() < until) {
await new Promise((resolve) => setTimeout(resolve, AGENT_POLL_MS));
const read = await getDraftSuggestions(draftId).catch(() => null);
- if (read?.some((s) => s.status === 'open')) return read;
+ if (read?.some((s) => s.status === 'open')) return { batch: read };
+ const run = await readAgentRun(draftId, FIX_RUNS).catch(() => null);
+ if (!run || run.id === before || !run.finishedAt) continue;
+ if (run.outcome === 'stopped') return { stopped: true };
+ if (run.outcome === 'failed') return { failed: true };
+ // Done: with what it left (its writing step's count), the batch reads next time round.
+ if (run.outcome === 'done' && !run.steps[2]?.count) {
+ return { nothing: true, why: run.steps[2]?.why };
+ }
}
return null;
}
@@ -397,6 +423,8 @@ export function DraftEditor({
const [citedRead, setCitedRead] = useState(!draft.sourceUrl);
// An agent's suggestions (CE-018): its latest batch, with what was decided.
const [suggestions, setSuggestions] = useState<DraftSuggestion[]>([]);
+ // The agent's last run failed (Fix or hand-off): the card says so over an earlier batch.
+ const [lastRunFailed, setLastRunFailed] = useState(false);
const suggestionsNow = useRef(suggestions);
const [deciding, setDeciding] = useState(false);
const [barClosed, setBarClosed] = useState(false);
@@ -2203,14 +2231,22 @@ export function DraftEditor({
* and Stop or a lost answer is said as such.
*/
const runAgentFix = async (
- send: () => Promise<{ count: number } | { error: HandOffError }>,
+ send: () => Promise<{ count: number; why?: AgentEmptyWhy } | { error: HandOffError }>,
told: (count: number) => string = fixedMessage,
// The editor's own run (the automatic hand-off): what the person didn't
// start isn't said when it doesn't run or finds nothing, only logged.
quiet = false,
) => {
- const failed = (key: string, error: string) =>
- quiet ? console.warn('The automatic hand-off did not run:', error) : toast.error(t(key));
+ const failed = (key: string, error: string) => {
+ if (quiet) {
+ console.warn('The automatic hand-off did not run:', error);
+ return;
+ }
+ toast.error(t(key));
+ // The card's last run says so, not an earlier batch's review.
+ if (error === 'failed') setLastRunFailed(true);
+ };
+ setLastRunFailed(false);
setStoppingRun(null);
stopSent.current = null;
setFixing(true);
@@ -2218,6 +2254,8 @@ export function DraftEditor({
try {
// The agent reads the page as saved.
await autosave.settle();
+ // The run there was before this one: one whose answer is lost is the next.
+ const before = (await readAgentRun(draft.id, FIX_RUNS).catch(() => null))?.id ?? null;
const result = await send().catch((err) => {
// The call itself gave up (a timeout on the way): the agent may still finish.
console.error('Failed to hear back from the Content Agent:', err);
@@ -2230,12 +2268,29 @@ export function DraftEditor({
return;
}
if ('error' in result && result.error === 'unconfirmed') {
- // No answer is not a failure: its batch shows if it lands in time.
- const landed = await agentBatch(draft.id, asked + FIX_WAIT_MS);
- if (!landed) {
+ // No answer is not a failure: how its run ended says (its batch, or its row).
+ const outcome = await agentOutcome(draft.id, before, asked + FIX_WAIT_MS);
+ if (outcome && 'stopped' in outcome) {
+ toast(t('agentCard.stopped'));
+ return;
+ }
+ if (outcome && 'nothing' in outcome) {
+ if (!quiet) {
+ toast(
+ t(
+ outcome.why === 'locked'
+ ? 'suggestions.nothingToFixLocked'
+ : 'suggestions.nothingToFix',
+ ),
+ );
+ }
+ return;
+ }
+ if (!outcome || 'failed' in outcome) {
failed('suggestions.fixErrors.failed', 'failed');
return;
}
+ const landed = outcome.batch;
setSuggestions(landed);
setBarClosed(false);
agentBeforeKept.current = false;
@@ -2258,7 +2313,16 @@ export function DraftEditor({
return;
}
if (result.count === 0) {
- if (!quiet) toast(t('suggestions.nothingToFix'));
+ // Why, so the person knows what to do: every change it had was in a quoted passage.
+ if (!quiet) {
+ toast(
+ t(
+ result.why === 'locked'
+ ? 'suggestions.nothingToFixLocked'
+ : 'suggestions.nothingToFix',
+ ),
+ );
+ }
return;
}
setSuggestions(await getDraftSuggestions(draft.id));
@@ -2336,6 +2400,10 @@ export function DraftEditor({
// The agent at work from this page: Fix open rules, or the brief. Its run,
// step by step, and Stop (CE-027/035).
const agentWorking = fixing || briefRebuilding;
+ // Any run the card follows (Fix, a hand-off, the brief): a failed one before it is behind it.
+ useEffect(() => {
+ if (agentWorking) setLastRunFailed(false);
+ }, [agentWorking]);
const agentRun = useAgentRun(draft.id, agentWorking, fixing ? FIX_RUNS : BRIEF_RUNS);
const stopAgent = async () => {
if (!agentRun) return;
@@ -3546,6 +3614,7 @@ export function DraftEditor({
busy={deciding || htmlSource !== null}
working={agentWorking}
run={agentRun}
+ lastRunFailed={lastRunFailed}
onStop={() => void stopAgent()}
stopping={stoppingRun !== null && stoppingRun === agentRun?.id}
onAcceptAll={() =>
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.tsx
index 3721d670d..15304379b 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
@@ -6518,6 +6518,96 @@ describe('the side panel', () => {
}
});
+ describe('when its answer is lost on the way', () => {
+ const ended = (over: Record<string, unknown>) => ({
+ id: 'r9',
+ kind: 'fix',
+ steps: [
+ { key: 'read_rules', count: 3 },
+ { key: 'gather_sources', count: 0 },
+ { key: 'write_changes', count: 0 },
+ ],
+ step: 3,
+ startedAt: new Date().toISOString(),
+ finishedAt: new Date().toISOString(),
+ stoppedAt: null,
+ outcome: 'done',
+ ...over,
+ });
+ /** Fix's runs as read: `earlier` before it was asked, `then` after. */
+ const runs = (earlier: unknown, then: unknown) => {
+ let read = 0;
+ readAgentRun.mockImplementation(async (_id: string, kinds?: string[]) =>
+ kinds ? (read++ === 0 ? earlier : then) : null,
+ );
+ };
+ async function run() {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] });
+ getContentDraft.mockResolvedValue(traced);
+ getDraftSuggestions.mockResolvedValue([]);
+ fixDraftRules.mockResolvedValue({ error: 'unconfirmed' });
+ await openRules();
+ await act(async () => panelButton('Run Agent').click());
+ await act(async () => void (await vi.advanceTimersByTimeAsync(10_000)));
+ await act(async () => {});
+ }
+ afterEach(() => vi.useRealTimers());
+
+ it('says it found nothing when its run ended with none, and why, not that it couldn’t run', async () => {
+ // Done with nothing left, every change in a quoted passage (editor test 2026-10-25).
+ runs(
+ null,
+ ended({
+ steps: [
+ { key: 'read_rules', count: 3 },
+ { key: 'gather_sources', count: 0 },
+ { key: 'write_changes', count: 0, why: 'locked' },
+ ],
+ }),
+ );
+ await run();
+ expect(toast).toHaveBeenCalledWith(
+ "Content Agent's changes were all in passages AI answers quote, which it keeps. Unlock the ones you're fine to change (Edit anyway), or change them yourself.",
+ );
+ expect(toast.error).not.toHaveBeenCalled();
+ });
+
+ it('says it stopped, or failed, as its row says, without waiting out the minute and a half', async () => {
+ runs(null, ended({ outcome: 'stopped' }));
+ await run();
+ expect(toast).toHaveBeenCalledWith('Stopped · nothing was changed');
+ expect(toast.error).not.toHaveBeenCalled();
+ vi.useRealTimers();
+ act(() => root.unmount());
+ root = createRoot(container);
+ toast.mockClear();
+ runs(null, ended({ outcome: 'failed' }));
+ await run();
+ expect(toast.error).toHaveBeenCalledWith("Content Agent couldn't run. Try again.");
+ });
+
+ it('never reads the run there was before it was asked as this one', async () => {
+ const earlier = ended({ id: 'r8', outcome: 'stopped' });
+ runs(earlier, earlier);
+ await run();
+ expect(toast).not.toHaveBeenCalledWith('Stopped · nothing was changed');
+ await act(async () => void (await vi.advanceTimersByTimeAsync(85_000)));
+ await act(async () => {});
+ expect(toast.error).toHaveBeenCalledWith("Content Agent couldn't run. Try again.");
+ });
+ });
+
+ it('says what to do when every change it had was in a quoted passage', async () => {
+ getContentDraft.mockResolvedValue(traced);
+ fixDraftRules.mockResolvedValue({ count: 0, why: 'locked' });
+ await openRules();
+ await act(async () => panelButton('Run Agent').click());
+ await act(async () => {});
+ expect(toast).toHaveBeenCalledWith(
+ "Content Agent's changes were all in passages AI answers quote, which it keeps. Unlock the ones you're fine to change (Edit anyway), or change them yourself.",
+ );
+ });
+
it('says the agent couldn’t run when no batch lands in time', async () => {
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] });
try {
diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.ts
index 4e469a597..905b9ed99 100644
--- a/web/src/lib/actions/content-drafts.ts
+++ b/web/src/lib/actions/content-drafts.ts
@@ -2259,6 +2259,12 @@ export interface AgentFixRequest {
sources?: RebuildSources;
}
+/** Why a run left nothing to review (content-agent.js emptyWhy). */
+export type AgentEmptyWhy = 'none' | 'locked' | 'dropped';
+
+const fixEmptyWhy = (why: unknown): { why?: AgentEmptyWhy } =>
+ why === 'none' || why === 'locked' || why === 'dropped' ? { why } : {};
+
/**
* Fix open rules with agent (CE-018): the Content Agent reads the draft as
* saved and leaves suggestions on the rules sent, for review in the page,
@@ -2269,7 +2275,7 @@ export async function fixDraftRules(
id: string,
brandId: string,
request: AgentFixRequest,
-): Promise<{ count: number } | { error: AgentFixError }> {
+): Promise<{ count: number; why?: AgentEmptyWhy } | { error: AgentFixError }> {
if (!draftId.safeParse(id).success || !draftId.safeParse(brandId).success) {
return { error: 'failed' };
}
@@ -2305,7 +2311,7 @@ export async function fixDraftRules(
const code = body.code as AgentFixError;
return { error: (AGENT_FIX_ERRORS as readonly string[]).includes(code) ? code : 'failed' };
}
- return { count: Number(body.count) || 0 };
+ return { count: Number(body.count) || 0, ...fixEmptyWhy(body.why) };
} catch (err) {
console.error('Failed to run the Content Agent:', err);
return { error: 'unconfirmed' };
@@ -2342,7 +2348,7 @@ export async function handOffDraft(
id: string,
brandId: string,
request: HandOffRequest,
-): Promise<{ count: number } | { error: HandOffError }> {
+): Promise<{ count: number; why?: AgentEmptyWhy } | { error: HandOffError }> {
if (!draftId.safeParse(id).success || !draftId.safeParse(brandId).success) {
return { error: 'failed' };
}
@@ -2376,7 +2382,7 @@ export async function handOffDraft(
const code = body.code as HandOffError;
return { error: (HANDOFF_ERRORS as readonly string[]).includes(code) ? code : 'failed' };
}
- return { count: Number(body.count) || 0 };
+ return { count: Number(body.count) || 0, ...fixEmptyWhy(body.why) };
} catch (err) {
console.error('Failed to hand the draft off:', err);
return { error: 'unconfirmed' };
diff --git a/web/src/lib/content/agent-runs-client.ts b/web/src/lib/content/agent-runs-client.ts
index 118400228..1a7887bab 100644
--- a/web/src/lib/content/agent-runs-client.ts
+++ b/web/src/lib/content/agent-runs-client.ts
@@ -1,6 +1,6 @@
import { BROWSER_API_BASE_URL } from '@/config/api';
import { createClient } from '@/lib/supabase/client';
-import { agentRunFrom, type AgentRun } from './agent-runs';
+import { agentRunFrom, type AgentRun, type AgentRunKind } from './agent-runs';
/**
* The Content Agent's run, read and stopped from the browser (v1.1
@@ -10,11 +10,17 @@ import { agentRunFrom, type AgentRun } from './agent-runs';
*/
/** The draft's latest run (00249, its members may read it), or null. */
-export async function readAgentRun(draftId: string): Promise<AgentRun | null> {
- const { data, error } = await createClient()
+export async function readAgentRun(
+ draftId: string,
+ kinds?: readonly AgentRunKind[],
+): Promise<AgentRun | null> {
+ let query = createClient()
.from('content_agent_runs')
.select('id, kind, steps, step, started_at, finished_at, stopped_at, outcome')
- .eq('draft_id', draftId)
+ .eq('draft_id', draftId);
+ // Of these kinds only: another kind's later run doesn't hide it.
+ if (kinds?.length) query = query.in('kind', [...kinds]);
+ const { data, error } = await query
.order('started_at', { ascending: false })
.limit(1)
.maybeSingle();
diff --git a/web/src/lib/content/agent-runs.ts b/web/src/lib/content/agent-runs.ts
index f9667a03e..5de541f95 100644
--- a/web/src/lib/content/agent-runs.ts
+++ b/web/src/lib/content/agent-runs.ts
@@ -23,6 +23,8 @@ export interface RunStep {
key: RunStepKey;
/** How many of what it reads ("20 cited pages"), or null. */
count: number | null;
+ /** Why its writing step left nothing (content-agent.js emptyWhy), once done. */
+ why?: 'none' | 'locked' | 'dropped';
}
export type AgentRunKind = 'fix' | 'rewrite' | 'write' | 'brief' | 'handoff';
@@ -56,6 +58,9 @@ export function agentRunFrom(row: Record<string, unknown> | null): AgentRun | nu
{
key: s.key as RunStepKey,
count: Number.isInteger(s.count) ? (s.count as number) : null,
+ ...(s.why === 'none' || s.why === 'locked' || s.why === 'dropped'
+ ? { why: s.why }
+ : {}),
},
]
: [],