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): don't say the Content Agent couldn't run while it is still at work (#1350)
Cihan73bea15e9d72
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 e81788fe3..e19e3a1b8 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@@ -36,6 +36,7 @@ import {} from '@/lib/actions/content-drafts';import { agentWriteRequest, useRuleDescriber } from '@/lib/content/agent-write';import {+ AGENT_POLL_MS,CONTENT_LIBRARY_PATH,isPageType,type ContentDraft,@@ -114,6 +115,27 @@ const DOCUMENT_CLASS = cn('[&_.is-editor-empty:first-child]:before:pointer-events-none [&_.is-editor-empty:first-child]:before:float-left [&_.is-editor-empty:first-child]:before:h-0 [&_.is-editor-empty:first-child]:before:text-muted-foreground [&_.is-editor-empty:first-child]:before:content-[attr(data-placeholder)]',);+/**+ * How long Fix open rules waits for the agent's batch when its answer didn't+ * come back: past the API's model call (content-agent.js, 60 s) and the+ * batch's save.+ */+const FIX_WAIT_MS = 90_000;++/**+ * 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.+ */+async function agentBatch(draftId: string, until: number): Promise<DraftSuggestion[] | null> {+ 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;+ }+ return null;+}+/*** The content editor (Content Editor, CE-004, spec §6): a header with the* draft's title, page type and method, whether it's saved, and Mark ready;@@ -571,10 +593,30 @@ export function DraftEditor({})(),};setFixing(true);+ const asked = Date.now();try {// The agent reads the page as saved.await autosave.settle();- const result = await fixDraftRules(draft.id, draft.brandId, request);+ const result = await fixDraftRules(draft.id, draft.brandId, request).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);+ return { error: 'unconfirmed' as const };+ });+ 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) {+ toast.error(t('suggestions.fixErrors.failed'));+ return;+ }+ setSuggestions(landed);+ setBarClosed(false);+ agentBeforeKept.current = false;+ toast.success(+ t('suggestions.fixed', { count: landed.filter((s) => s.status === 'open').length }),+ );+ return;+ }if ('error' in result) {toast.error(t(`suggestions.fixErrors.${result.error}`));// Another tab (or the API) left them: show them here to decide.diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/layout.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/layout.tsxnew file mode 100644index 000000000..08b42b93e--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/layout.tsx@@ -0,0 +1,10 @@+/**+ * The editor's server actions wait on the Content Agent: Fix open rules+ * answers once the model has (content-agent.js, up to 60 s), past a page's+ * default time on the platform. As the API proxy's long routes do.+ */+export const maxDuration = 300;++export default function ContentEditorLayout({ children }: { children: React.ReactNode }) {+ return children;+}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 27d2507e8..96d2ae54b 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@@ -1724,6 +1724,56 @@ describe('the side panel', () => {);});+ // A timeout on the way back is not the agent failing: it may still finish.+ it('shows the agent’s batch when it lands after the answer didn’t come back', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] });+ try {+ getContentDraft.mockResolvedValue(traced);+ getDraftSuggestions+ .mockResolvedValueOnce([])+ .mockResolvedValueOnce([])+ .mockResolvedValueOnce([agentSuggestion]);+ fixDraftRules.mockRejectedValue(new Error('An unexpected response was received'));+ await openRules();++ await act(async () => panelButton('Fix open rules with agent').click());+ await act(async () => void (await vi.advanceTimersByTimeAsync(5_000)));+ expect(toast.error).not.toHaveBeenCalled();+ await act(async () => void (await vi.advanceTimersByTimeAsync(5_000)));+ await act(async () => {});++ expect(getDraftSuggestions).toHaveBeenCalledTimes(3);+ expect(+ container.querySelector('[role="region"][aria-label="Agent suggestions"]')!.textContent,+ ).toContain('Content Agent suggested 1 change');+ expect(toast.success).toHaveBeenCalledWith(+ 'Content Agent suggested 1 change · review them in the page',+ );+ expect(toast.error).not.toHaveBeenCalled();+ } finally {+ vi.useRealTimers();+ }+ });++ it('says the agent couldn’t run when no batch lands in time', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] });+ try {+ getContentDraft.mockResolvedValue(traced);+ getDraftSuggestions.mockResolvedValue([]);+ fixDraftRules.mockResolvedValue({ error: 'unconfirmed' });+ await openRules();++ await act(async () => panelButton('Fix open rules with agent').click());+ await act(async () => void (await vi.advanceTimersByTimeAsync(85_000)));+ expect(toast.error).not.toHaveBeenCalled();+ await act(async () => void (await vi.advanceTimersByTimeAsync(10_000)));+ await act(async () => {});+ expect(toast.error).toHaveBeenCalledWith("Content Agent couldn't run. Try again.");+ } finally {+ vi.useRealTimers();+ }+ });+it('fixes only the AI traces from their rule', async () => {getContentDraft.mockResolvedValue(traced);await openRules();diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.tsindex 157862974..bb3b70e91 100644--- a/web/src/lib/actions/content-drafts.ts+++ b/web/src/lib/actions/content-drafts.ts@@ -1528,6 +1528,8 @@ const AGENT_FIX_ERRORS = ['open_suggestions','published','failed',+ /** No answer from the API (a timeout on the way): the agent may still finish. */+ 'unconfirmed',] as const;export type AgentFixError = (typeof AGENT_FIX_ERRORS)[number];@@ -1579,13 +1581,15 @@ export async function fixDraftRules(});const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;if (!res.ok) {+ // The API says why; a gateway's page (a timeout) says nothing of the run.+ if (typeof body.code !== 'string') return { error: 'unconfirmed' };const code = body.code as AgentFixError;return { error: (AGENT_FIX_ERRORS as readonly string[]).includes(code) ? code : 'failed' };}return { count: Number(body.count) || 0 };} catch (err) {console.error('Failed to run the Content Agent:', err);- return { error: 'failed' };+ return { error: 'unconfirmed' };}}