Open source alternative to Semrush and Ahrefs
TypeScript backlink-analysisgoogle-search-console-mcpkeyword-researchmcpseoseo-agentseo-auditseo-automationseo-skillsseo-toolssite-audit
Weekly prompt tracking by default, row action menus, and a faster export (EVE-398) (#863)
Carter Smithde442a118704
diff --git a/.agents/skills/ai-visibility-audit/SKILL.md b/.agents/skills/ai-visibility-audit/SKILL.mdindex 5a346d82..99a5c1ae 100644--- a/.agents/skills/ai-visibility-audit/SKILL.md+++ b/.agents/skills/ai-visibility-audit/SKILL.md@@ -27,7 +27,7 @@ The project-context tools are free and shared with the app and other agents.- `get_ai_visibility_trend`: whether visibility is moving, when the tracker has comparable history. Never compute a trend yourself from separate result calls.- `research_ai_visibility_prompts`: the questions around a prompt group and the sources ChatGPT cites for them (US English only).- `explore_prompt`: asks ChatGPT one prompt through its API and returns the answer, citations and `fanOutQueries`, the web searches the model ran before answering. Charged at actual usage per uncached answer; cached answers are free for seven days. Requires a paid plan in hosted mode.-- `estimate_ai_visibility_cost`, `save_ai_visibility_tracker`, `run_ai_visibility_check`, `get_ai_visibility_run`: only for the first-run path below.+- `estimate_ai_visibility_cost`, `save_ai_visibility_tracker`, `set_ai_visibility_schedule`, `run_ai_visibility_check`, `get_ai_visibility_run`: only for the first-run path below.- `get_ranked_keywords`, `get_serp_results`, `get_backlinks_overview`: optional context when an owned page's search performance or authority could change a recommendation.- Web reading (fetch, scrape or search): `robots.txt`, the owned pages that should be cited, and the pages AI answers cite instead.@@ -39,7 +39,7 @@ The project-context tools are free and shared with the app and other agents.- **Run in progress**: when `recentRuns` shows a pending or partially finished run, follow it with `get_ai_visibility_run`, respecting `pollAfterSeconds`. Do not start another. A failed or partial run still supplies whatever answers it completed; report its coverage.- **Tracker with active prompts but no runs**: saved prompts that were never collected, for example because the schedule was never enabled. Estimate one check of the saved active prompts with `estimate_ai_visibility_cost`, get approval once, then call `run_ai_visibility_check` with the approved cost as `maxCostUsd`. Follow the returned run. Do not change the schedule.- **Tracker with no active prompts** (every topic or prompt paused or archived): ask whether to resume the existing prompts or add new ones, then take the matching path. Do not unpause anything without the user's direction.-- **No tracker**: propose 10–15 neutral prompts across two or three topics the business sells into, preferring real prompts from `research_ai_visibility_prompts`. Show one plan with the cost from `estimate_ai_visibility_cost`, get approval once, save through `save_ai_visibility_tracker` with each prompt's `topic`, and run one check with the approved cost as `maxCostUsd`. Do not enable a schedule. If the user declines the spend, run the audit on prompt research alone and say the report has no observed answers.+- **No tracker**: propose 10–15 neutral prompts across two or three topics the business sells into, preferring real prompts from `research_ai_visibility_prompts`. Show one plan with the check cost and the monthly cost from `estimate_ai_visibility_cost`, and say that a new tracker runs weekly, with its first scheduled check a week later. Get approval once, save through `save_ai_visibility_tracker` with each prompt's `topic`, and run one check with the approved cost as `maxCostUsd`. If the user wants this audit only, pause the schedule with `set_ai_visibility_schedule` and `enabled: false`. If the user declines the spend, run the audit on prompt research alone and say the report has no observed answers.### 2. Read where the brand standsdiff --git a/plugins/openseo/.claude-plugin/plugin.json b/plugins/openseo/.claude-plugin/plugin.jsonindex bfb1b558..4fa98dcc 100644--- a/plugins/openseo/.claude-plugin/plugin.json+++ b/plugins/openseo/.claude-plugin/plugin.json@@ -1,7 +1,7 @@{"name": "openseo","displayName": "OpenSEO",- "version": "1.0.18",+ "version": "1.0.19","description": "Research keywords and competitors, audit sites, track rankings and AI visibility, and use connected Search Console data from your AI assistant.","author": {"name": "OpenSEO",diff --git a/plugins/openseo/.codex-plugin/plugin.json b/plugins/openseo/.codex-plugin/plugin.jsonindex 7b02a7c9..9ba1d8fa 100644--- a/plugins/openseo/.codex-plugin/plugin.json+++ b/plugins/openseo/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "openseo",- "version": "1.0.18",+ "version": "1.0.19","description": "Research keywords and competitors, audit sites, track rankings and AI visibility, and use connected Search Console data from your AI assistant.","author": {"name": "OpenSEO",diff --git a/plugins/openseo/.cursor-plugin/plugin.json b/plugins/openseo/.cursor-plugin/plugin.jsonindex 735772e0..e3ff1e32 100644--- a/plugins/openseo/.cursor-plugin/plugin.json+++ b/plugins/openseo/.cursor-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "openseo",- "version": "1.0.18",+ "version": "1.0.19","description": "Research keywords and competitors, audit sites, track rankings and AI visibility, and use connected Search Console data from your AI assistant.","author": {"name": "Every App, Inc",diff --git a/plugins/openseo/skills/ai-visibility-audit/SKILL.md b/plugins/openseo/skills/ai-visibility-audit/SKILL.mdindex 5a346d82..99a5c1ae 100644--- a/plugins/openseo/skills/ai-visibility-audit/SKILL.md+++ b/plugins/openseo/skills/ai-visibility-audit/SKILL.md@@ -27,7 +27,7 @@ The project-context tools are free and shared with the app and other agents.- `get_ai_visibility_trend`: whether visibility is moving, when the tracker has comparable history. Never compute a trend yourself from separate result calls.- `research_ai_visibility_prompts`: the questions around a prompt group and the sources ChatGPT cites for them (US English only).- `explore_prompt`: asks ChatGPT one prompt through its API and returns the answer, citations and `fanOutQueries`, the web searches the model ran before answering. Charged at actual usage per uncached answer; cached answers are free for seven days. Requires a paid plan in hosted mode.-- `estimate_ai_visibility_cost`, `save_ai_visibility_tracker`, `run_ai_visibility_check`, `get_ai_visibility_run`: only for the first-run path below.+- `estimate_ai_visibility_cost`, `save_ai_visibility_tracker`, `set_ai_visibility_schedule`, `run_ai_visibility_check`, `get_ai_visibility_run`: only for the first-run path below.- `get_ranked_keywords`, `get_serp_results`, `get_backlinks_overview`: optional context when an owned page's search performance or authority could change a recommendation.- Web reading (fetch, scrape or search): `robots.txt`, the owned pages that should be cited, and the pages AI answers cite instead.@@ -39,7 +39,7 @@ The project-context tools are free and shared with the app and other agents.- **Run in progress**: when `recentRuns` shows a pending or partially finished run, follow it with `get_ai_visibility_run`, respecting `pollAfterSeconds`. Do not start another. A failed or partial run still supplies whatever answers it completed; report its coverage.- **Tracker with active prompts but no runs**: saved prompts that were never collected, for example because the schedule was never enabled. Estimate one check of the saved active prompts with `estimate_ai_visibility_cost`, get approval once, then call `run_ai_visibility_check` with the approved cost as `maxCostUsd`. Follow the returned run. Do not change the schedule.- **Tracker with no active prompts** (every topic or prompt paused or archived): ask whether to resume the existing prompts or add new ones, then take the matching path. Do not unpause anything without the user's direction.-- **No tracker**: propose 10–15 neutral prompts across two or three topics the business sells into, preferring real prompts from `research_ai_visibility_prompts`. Show one plan with the cost from `estimate_ai_visibility_cost`, get approval once, save through `save_ai_visibility_tracker` with each prompt's `topic`, and run one check with the approved cost as `maxCostUsd`. Do not enable a schedule. If the user declines the spend, run the audit on prompt research alone and say the report has no observed answers.+- **No tracker**: propose 10–15 neutral prompts across two or three topics the business sells into, preferring real prompts from `research_ai_visibility_prompts`. Show one plan with the check cost and the monthly cost from `estimate_ai_visibility_cost`, and say that a new tracker runs weekly, with its first scheduled check a week later. Get approval once, save through `save_ai_visibility_tracker` with each prompt's `topic`, and run one check with the approved cost as `maxCostUsd`. If the user wants this audit only, pause the schedule with `set_ai_visibility_schedule` and `enabled: false`. If the user declines the spend, run the audit on prompt research alone and say the report has no observed answers.### 2. Read where the brand standsdiff --git a/src/client/features/ai-visibility/PromptActions.tsx b/src/client/features/ai-visibility/PromptActions.tsxnew file mode 100644index 00000000..b645e397--- /dev/null+++ b/src/client/features/ai-visibility/PromptActions.tsx@@ -0,0 +1,51 @@+import { Archive, Pause, Pencil, Play } from "lucide-react";+import { RowActionsMenu } from "@/client/components/RowActionsMenu";+import { DropdownMenuItem } from "@/client/components/ui/dropdown-menu";++/** The dots menu of a prompt or topic row in the tracked prompts table. */+export function PromptActionsMenu({+ label,+ kind,+ paused,+ scheduled,+ pending,+ onEdit,+ onTogglePause,+ onArchive,+}: {+ label: string;+ kind: "prompt" | "topic";+ paused: boolean;+ /** Pausing only skips scheduled runs, so it needs a schedule. */+ scheduled: boolean;+ pending: boolean;+ onEdit?: () => void;+ onTogglePause: () => void;+ onArchive: () => void;+}) {+ return (+ <RowActionsMenu label={label}>+ {onEdit && (+ <DropdownMenuItem onClick={onEdit}>+ <Pencil />+ Edit {kind}+ </DropdownMenuItem>+ )}+ <DropdownMenuItem+ disabled={pending || (!paused && !scheduled)}+ onClick={onTogglePause}+ >+ {paused ? <Play /> : <Pause />}+ {paused ? `Resume ${kind}` : `Pause ${kind}`}+ </DropdownMenuItem>+ <DropdownMenuItem+ variant="destructive"+ disabled={pending}+ onClick={onArchive}+ >+ <Archive />+ Archive {kind}+ </DropdownMenuItem>+ </RowActionsMenu>+ );+}diff --git a/src/client/features/ai-visibility/PromptInventory.tsx b/src/client/features/ai-visibility/PromptInventory.tsxindex 255eff04..5628a5cc 100644--- a/src/client/features/ai-visibility/PromptInventory.tsx+++ b/src/client/features/ai-visibility/PromptInventory.tsx@@ -1,13 +1,6 @@import { useState } from "react";import { Link } from "@tanstack/react-router";-import {- Archive,- ChevronDown,- ChevronRight,- Pause,- Pencil,- Play,-} from "lucide-react";+import { ChevronDown, ChevronRight } from "lucide-react";import {AI_ENGINE_LABELS,aiNoAnswerLabel,@@ -15,6 +8,7 @@ import {type AiObservationRow,type AiPrompt,} from "@/shared/ai-visibility";+import { ConfirmDialog } from "@/client/components/ConfirmDialog";import { Button } from "@/client/components/ui/button";import { Skeleton } from "@/client/components/ui/skeleton";import {@@ -26,6 +20,7 @@ import {TableRow,} from "@/client/components/ui/table";import { EngineLabel } from "./EngineLabel";+import { PromptActionsMenu } from "./PromptActions";import { aiRate } from "./shared";import type { AiTrackerPatch } from "@/types/schemas/ai-visibility";@@ -37,6 +32,7 @@ export function PromptInventory({engines,rows,loading,+ scheduled,pending,onEdit,onReduce,@@ -51,12 +47,19 @@ export function PromptInventory({rows: AiObservationRow[] | undefined;/** The run's answers are still loading; prompts show before their rates. */loading: boolean;+ /** Whether the tracker has a schedule; pausing only skips scheduled runs. */+ scheduled: boolean;pending: boolean;onEdit: (prompt: AiPrompt) => void;onReduce: (patch: AiTrackerPatch) => void;onReview: (patch: AiTrackerPatch, description: string) => void;}) {const [collapsed, setCollapsed] = useState<string[]>([]);+ const [archiving, setArchiving] = useState<{+ kind: "prompt" | "topic";+ name: string;+ promptIds: string[];+ } | null>(null);const matches = (prompt: AiPrompt) =>!search ||prompt.text.toLocaleLowerCase().includes(search.toLocaleLowerCase());@@ -67,223 +70,209 @@ export function PromptInventory({</p>);return (- <Table className="min-w-[900px]">- <TableHeader>- <TableRow>- <TableHead className="w-full">Prompts by topic</TableHead>- <TableHead>Engines</TableHead>- <TableHead>Brand mentions</TableHead>- <TableHead>Owned citations</TableHead>- <TableHead>- <span className="sr-only">Manage tracking</span>- </TableHead>- </TableRow>- </TableHeader>- {topics.map((topic) => {- const topicPrompts = prompts.filter((prompt) => prompt.topic === topic);- const shownPrompts = topicPrompts.filter(matches);- if (!shownPrompts.length) return null;- const paused = topicPrompts.every((prompt) => prompt.paused);- const topicRows = rows?.filter((row) =>- shownPrompts.some((prompt) => prompt.id === row.promptId),- );- const open = !collapsed.includes(topic);- return (- <TableBody key={topic}>- <TableRow className="bg-muted/40 hover:bg-muted/40">- <TableCell colSpan={2} className="py-3">- <Button- variant="ghost"- size="sm"- className="flex h-auto items-center justify-start gap-2 px-0 text-left hover:bg-transparent aria-expanded:bg-transparent"- aria-expanded={open}- onClick={() =>- setCollapsed((names) =>- open- ? [...names, topic]- : names.filter((name) => name !== topic),- )- }- >- {open ? <ChevronDown /> : <ChevronRight />}- <span className="inline-flex items-center gap-2">- {topic}- <span className="text-xs font-normal text-muted-foreground">- {shownPrompts.length}{" "}- {shownPrompts.length === 1 ? "prompt" : "prompts"}- {paused ? " · Paused" : ""}- </span>- </span>- </Button>- </TableCell>- <TableCell>- <PromptRate- rows={topicRows}- kind="mentioned"- loading={loading}- />- </TableCell>- <TableCell>- <PromptRate rows={topicRows} kind="cited" loading={loading} />- </TableCell>- <TableCell>- <div className="flex items-center justify-end gap-1">- <Button- variant="ghost"- size="icon-xs"- disabled={pending}- title={paused ? "Resume topic" : "Pause topic"}- aria-label={`${paused ? "Resume" : "Pause"} topic ${topic}`}- onClick={() => {- const patch = {- prompts: topicPrompts.map((prompt) => ({- id: prompt.id,- text: prompt.text,- paused: !paused,- })),- };- if (paused)- onReview(patch, `Resume prompts in ${topic}.`);- else onReduce(patch);- }}- >- {paused ? (- <Play className="size-3.5" />- ) : (- <Pause className="size-3.5" />- )}- </Button>+ <>+ <Table className="min-w-[900px]">+ <TableHeader>+ <TableRow>+ <TableHead className="w-full">Prompts by topic</TableHead>+ <TableHead>Engines</TableHead>+ <TableHead>Brand mentions</TableHead>+ <TableHead>Owned citations</TableHead>+ <TableHead>+ <span className="sr-only">Manage tracking</span>+ </TableHead>+ </TableRow>+ </TableHeader>+ {topics.map((topic) => {+ const topicPrompts = prompts.filter(+ (prompt) => prompt.topic === topic,+ );+ const shownPrompts = topicPrompts.filter(matches);+ if (!shownPrompts.length) return null;+ const paused = topicPrompts.every((prompt) => prompt.paused);+ const topicRows = rows?.filter((row) =>+ shownPrompts.some((prompt) => prompt.id === row.promptId),+ );+ const open = !collapsed.includes(topic);+ return (+ <TableBody key={topic}>+ <TableRow className="bg-muted/40 hover:bg-muted/40">+ <TableCell colSpan={2} className="py-3"><Buttonvariant="ghost"- size="icon-xs"- disabled={pending}- title="Archive topic; keep prompt history"- aria-label={`Archive topic ${topic}`}+ size="sm"+ className="flex h-auto items-center justify-start gap-2 px-0 text-left hover:bg-transparent aria-expanded:bg-transparent"+ aria-expanded={open}onClick={() =>- onReduce({- archivePromptIds: topicPrompts.map(- (prompt) => prompt.id,- ),- })+ setCollapsed((names) =>+ open+ ? [...names, topic]+ : names.filter((name) => name !== topic),+ )}>- <Archive className="size-3.5" />+ {open ? <ChevronDown /> : <ChevronRight />}+ <span className="inline-flex items-center gap-2">+ {topic}+ <span className="text-xs font-normal text-muted-foreground">+ {shownPrompts.length}{" "}+ {shownPrompts.length === 1 ? "prompt" : "prompts"}+ {paused ? " · Paused" : ""}+ </span>+ </span></Button>- </div>- </TableCell>- </TableRow>- {open &&- shownPrompts.map((prompt) => {- const promptRows = rows?.filter(- (row) => row.promptId === prompt.id,- );- return (- <TableRow key={prompt.id}>- <TableCell className="min-w-72 py-4 pl-10 first:pl-10">- <Link- to="/p/$projectId/ai-visibility/prompts/$promptId"- params={{ projectId, promptId: prompt.id }}- className="whitespace-pre-wrap text-sm font-medium underline-offset-4 hover:text-primary hover:underline"- data-ph-mask- >- {prompt.text}- </Link>- <p className="mt-1 text-xs text-muted-foreground">- {prompt.paused ? "Paused" : "Active"} ·{" "}- {prompt.branded ? "Branded" : "Non-branded"}- </p>- </TableCell>- <TableCell>- <div className="flex min-w-64 items-center gap-3">- {engines.map((engine) => (- <EngineResult- key={engine}- engine={engine}- row={promptRows?.find(- (row) => row.engine === engine,- )}- />- ))}- </div>- </TableCell>- <TableCell>- <PromptRate- rows={promptRows}- kind="mentioned"- loading={loading}- />- </TableCell>- <TableCell>- <PromptRate- rows={promptRows}- kind="cited"- loading={loading}- />- </TableCell>- <TableCell>- <div className="flex items-center justify-end gap-1">- <Button- variant="ghost"- size="icon-xs"- title="Edit prompt"- aria-label={`Edit ${prompt.text}`}- onClick={() => onEdit(prompt)}- >- <Pencil className="size-3.5" />- </Button>- <Button- variant="ghost"- size="icon-xs"- disabled={pending}- title={- prompt.paused ? "Resume prompt" : "Pause prompt"- }- aria-label={`${prompt.paused ? "Resume" : "Pause"} ${prompt.text}`}- onClick={() => {- const patch = {- prompts: [- {- id: prompt.id,- text: prompt.text,- paused: !prompt.paused,- },- ],- };- if (prompt.paused)- onReview(- patch,- "Resume this prompt in your tracker.",- );- else onReduce(patch);- }}+ </TableCell>+ <TableCell>+ <PromptRate+ rows={topicRows}+ kind="mentioned"+ loading={loading}+ />+ </TableCell>+ <TableCell>+ <PromptRate rows={topicRows} kind="cited" loading={loading} />+ </TableCell>+ <TableCell>+ <div className="flex justify-end">+ <PromptActionsMenu+ label={`Actions for topic ${topic}`}+ kind="topic"+ paused={paused}+ scheduled={scheduled}+ pending={pending}+ onTogglePause={() => {+ const patch = {+ prompts: topicPrompts.map((prompt) => ({+ id: prompt.id,+ text: prompt.text,+ paused: !paused,+ })),+ };+ if (paused)+ onReview(patch, `Resume prompts in ${topic}.`);+ else onReduce(patch);+ }}+ onArchive={() =>+ setArchiving({+ kind: "topic",+ name: topic,+ promptIds: topicPrompts.map((prompt) => prompt.id),+ })+ }+ />+ </div>+ </TableCell>+ </TableRow>+ {open &&+ shownPrompts.map((prompt) => {+ const promptRows = rows?.filter(+ (row) => row.promptId === prompt.id,+ );+ return (+ <TableRow key={prompt.id}>+ <TableCell className="min-w-72 py-4 pl-10 first:pl-10">+ <Link+ to="/p/$projectId/ai-visibility/prompts/$promptId"+ params={{ projectId, promptId: prompt.id }}+ className="whitespace-pre-wrap text-sm font-medium underline-offset-4 hover:text-primary hover:underline"+ data-ph-mask>- {prompt.paused ? (- <Play className="size-3.5" />- ) : (- <Pause className="size-3.5" />- )}- </Button>- <Button- variant="ghost"- size="icon-xs"- disabled={pending}- title="Archive prompt; keep history"- aria-label={`Archive ${prompt.text}`}- onClick={() =>- onReduce({ archivePromptIds: [prompt.id] })- }- >- <Archive className="size-3.5" />- </Button>- </div>- </TableCell>- </TableRow>- );- })}- </TableBody>- );- })}- </Table>+ {prompt.text}+ </Link>+ <p className="mt-1 text-xs text-muted-foreground">+ {prompt.paused ? "Paused" : "Active"} ·{" "}+ {prompt.branded ? "Branded" : "Non-branded"}+ </p>+ </TableCell>+ <TableCell>+ <div className="flex min-w-64 items-center gap-3">+ {engines.map((engine) => (+ <EngineResult+ key={engine}+ engine={engine}+ row={promptRows?.find(+ (row) => row.engine === engine,+ )}+ />+ ))}+ </div>+ </TableCell>+ <TableCell>+ <PromptRate+ rows={promptRows}+ kind="mentioned"+ loading={loading}+ />+ </TableCell>+ <TableCell>+ <PromptRate+ rows={promptRows}+ kind="cited"+ loading={loading}+ />+ </TableCell>+ <TableCell>+ <div className="flex justify-end">+ <PromptActionsMenu+ label={`Actions for ${prompt.text}`}+ kind="prompt"+ paused={prompt.paused}+ scheduled={scheduled}+ pending={pending}+ onEdit={() => onEdit(prompt)}+ onTogglePause={() => {+ const patch = {+ prompts: [+ {+ id: prompt.id,+ text: prompt.text,+ paused: !prompt.paused,+ },+ ],+ };+ if (prompt.paused)+ onReview(+ patch,+ "Resume this prompt in your tracker.",+ );+ else onReduce(patch);+ }}+ onArchive={() =>+ setArchiving({+ kind: "prompt",+ name: prompt.text,+ promptIds: [prompt.id],+ })+ }+ />+ </div>+ </TableCell>+ </TableRow>+ );+ })}+ </TableBody>+ );+ })}+ </Table>+ {archiving && (+ <ConfirmDialog+ title={`Archive ${archiving.kind}?`}+ confirmLabel="Archive"+ destructive+ onConfirm={() => {+ onReduce({ archivePromptIds: archiving.promptIds });+ setArchiving(null);+ }}+ onClose={() => setArchiving(null)}+ >+ {archiving.kind === "topic"+ ? `This stops tracking every prompt in "${archiving.name}".`+ : `This stops tracking "${archiving.name}".`}{" "}+ You can't view archived prompts yet. Their answer history is kept and+ returns if you add the same prompt again.+ </ConfirmDialog>+ )}+ </>);}diff --git a/src/client/features/ai-visibility/PromptList.tsx b/src/client/features/ai-visibility/PromptList.tsxindex 459ab8dd..1130aed2 100644--- a/src/client/features/ai-visibility/PromptList.tsx+++ b/src/client/features/ai-visibility/PromptList.tsx@@ -105,6 +105,7 @@ export function PromptList({engines={state.engines}rows={results.data}loading={results.isLoading}+ scheduled={Boolean(state.tracker?.enabled)}pending={reducePending}onEdit={onEdit}onReduce={onReduce}diff --git a/src/client/features/ai-visibility/TrackerEditor.tsx b/src/client/features/ai-visibility/TrackerEditor.tsxindex 424bdb30..60d286a4 100644--- a/src/client/features/ai-visibility/TrackerEditor.tsx+++ b/src/client/features/ai-visibility/TrackerEditor.tsx@@ -86,7 +86,14 @@ export function TrackerEditor({const prepare = useMutation({mutationFn: async (patch: AiTrackerPatch) => ({patch,- estimate: await estimateAiVisibilityCost({ data: { projectId, patch } }),+ estimate: await estimateAiVisibilityCost({+ // An unscheduled tracker is offered weekly tracking.+ data: {+ projectId,+ patch,+ scheduleInterval: state.tracker?.enabled ? undefined : "weekly",+ },+ }),}),onSuccess: setReview,});@@ -172,21 +179,21 @@ export function TrackerEditor({<TrackerSetupReviewreview={review}enabled={Boolean(state.tracker?.enabled)}+ creating={!state.tracker}pending={save.isPending}error={save.error}- canRun={- state.providerConfigured &&- !state.recentRuns.some(- (run) => run.status === "queued" || run.status === "running",- )- }- running={save.variables?.runNow ?? false}+ canSchedule={state.providerConfigured}+ scheduling={save.variables?.scheduleWeekly ?? false}onBack={() => {setReview(null);save.reset();}}- onSave={() => save.mutate({ accepted: review, runNow: false })}- onSaveAndRun={() => save.mutate({ accepted: review, runNow: true })}+ onSave={() =>+ save.mutate({ accepted: review, scheduleWeekly: false })+ }+ onSaveAndSchedule={() =>+ save.mutate({ accepted: review, scheduleWeekly: true })+ }/>) : (<formdiff --git a/src/client/features/ai-visibility/TrackerSetupReview.tsx b/src/client/features/ai-visibility/TrackerSetupReview.tsxindex 8319ebd9..6a5db329 100644--- a/src/client/features/ai-visibility/TrackerSetupReview.tsx+++ b/src/client/features/ai-visibility/TrackerSetupReview.tsx@@ -14,29 +14,37 @@ export type TrackerSetupReviewData = {export function TrackerSetupReview({review,enabled,+ creating,pending,error,- canRun,- running,+ canSchedule,+ scheduling,onBack,onSave,- onSaveAndRun,+ onSaveAndSchedule,}: {review: TrackerSetupReviewData;enabled: boolean;+ /** No tracker yet; saving creates one on the weekly schedule. */+ creating: boolean;pending: boolean;error: unknown;- canRun: boolean;- running: boolean;+ canSchedule: boolean;+ scheduling: boolean;onBack: () => void;onSave: () => void;- onSaveAndRun: () => void;+ onSaveAndSchedule: () => void;}) {+ const paused = !enabled && !creating;return (<div className="space-y-4"><p className="text-sm text-muted-foreground">Review your changes before saving.{" "}- {enabled ? "These settings apply to your enabled schedule." : ""}+ {enabled+ ? "These settings apply to your enabled schedule."+ : creating+ ? "Tracking runs weekly. The first check is a week from now; use Run now for results sooner."+ : "Track weekly to collect fresh answers once a week. A tracker that has never run on a schedule also runs its first check now."}</p><dl className="grid grid-cols-2 gap-4 rounded-lg border p-4 text-sm border-border">{review.patch.engines && (@@ -112,21 +120,31 @@ export function TrackerSetupReview({</Button><Buttontype="button"- variant={enabled ? "default" : "secondary"}+ variant={paused ? "secondary" : "default"}disabled={pending}onClick={onSave}>- {pending && !running && <Loader2 className="size-4 animate-spin" />}- {enabled ? "Save reviewed changes" : "Save as paused"}+ {pending && !scheduling && (+ <Loader2 className="size-4 animate-spin" />+ )}+ {enabled+ ? "Save reviewed changes"+ : creating+ ? "Save and track weekly"+ : "Save as paused"}</Button>- {!enabled && (+ {paused && (<Buttontype="button"- disabled={pending || !canRun || review.estimate.observations === 0}- onClick={onSaveAndRun}+ disabled={+ pending || !canSchedule || review.estimate.observations === 0+ }+ onClick={onSaveAndSchedule}>- {pending && running && <Loader2 className="size-4 animate-spin" />}- Save and run now+ {pending && scheduling && (+ <Loader2 className="size-4 animate-spin" />+ )}+ Save and track weekly</Button>)}</DialogFooter>diff --git a/src/client/features/ai-visibility/useTrackerSetupSave.ts b/src/client/features/ai-visibility/useTrackerSetupSave.tsindex 91ea286b..8fb07786 100644--- a/src/client/features/ai-visibility/useTrackerSetupSave.ts+++ b/src/client/features/ai-visibility/useTrackerSetupSave.ts@@ -1,8 +1,9 @@import { useMutation } from "@tanstack/react-query";import { toast } from "sonner";import {- runAiVisibilityCheck,+ getAiVisibilityTracker,saveAiVisibilityTracker,+ setAiVisibilitySchedule,} from "@/serverFunctions/ai-visibility";import { getStandardErrorMessage } from "@/client/lib/error-messages";import type { AiRun, AiTrackerState } from "@/shared/ai-visibility";@@ -18,31 +19,35 @@ export function useTrackerSetupSave({return useMutation({mutationFn: async ({accepted,- runNow,+ scheduleWeekly,}: {accepted: TrackerSetupReviewData;- runNow: boolean;+ scheduleWeekly: boolean;}) => {const result = await saveAiVisibilityTracker({data: { projectId, ...accepted.patch },});- if (!runNow) return { state: result.state };+ if (!scheduleWeekly) return { state: result.state };try {- // The server refuses the run if its cost rose above the reviewed estimate.- const run = await runAiVisibilityCheck({- data: { projectId, maxCostUsd: accepted.estimate.costUsd },+ // A first schedule also collects a baseline now.+ const scheduled = await setAiVisibilitySchedule({+ data: { projectId, enabled: true, scheduleInterval: "weekly" },});- return { state: result.state, run };- } catch (runError) {- // Keep the successful save visible even if collection could not start.- return { state: result.state, runError };+ return { state: scheduled.state, run: scheduled.run ?? undefined };+ } catch (scheduleError) {+ // The schedule is saved before its first check starts, so a failed+ // check can leave tracking on. Show what the server kept.+ const state = await getAiVisibilityTracker({+ data: { projectId },+ }).catch(() => result.state);+ return { state, scheduleError };}},onSuccess: (result) => {onSaved(result.state, result.run);- if (result.runError)+ if (result.scheduleError)toast.error(- `Tracking saved. We couldn't confirm the run started. Check its status before trying again. ${getStandardErrorMessage(result.runError)}`,+ `${result.state.tracker?.enabled ? "Weekly tracking is on, but the first check couldn't start." : "Prompts saved. We couldn't start weekly tracking."} ${getStandardErrorMessage(result.scheduleError)}`,);},});diff --git a/src/server/features/ai-visibility/services/aiVisibilityConfiguration.test.ts b/src/server/features/ai-visibility/services/aiVisibilityConfiguration.test.tsindex 28aff18d..ace66153 100644--- a/src/server/features/ai-visibility/services/aiVisibilityConfiguration.test.ts+++ b/src/server/features/ai-visibility/services/aiVisibilityConfiguration.test.ts@@ -1,4 +1,4 @@-import { describe, expect, it } from "vitest";+import { describe, expect, it, vi } from "vitest";import type { AiTrackerPatch } from "@/types/schemas/ai-visibility";import type { ConfigurationRows } from "../repositories/AiVisibilityRepository";import { aiScope, projectAiConfiguration } from "./aiVisibilityConfiguration";@@ -24,10 +24,15 @@ const saved = () =>}).rows;describe("AI configuration projection", () => {- it("creates a paused tracker in the project market with two consumer engines and General prompts", () => {+ it("creates a weekly tracker, first check at least a week out, in the project market with two consumer engines and General prompts", () => {+ // Late in the UTC day, past the scheduler's 04:00–10:00 UTC slots.+ vi.useFakeTimers({ now: new Date("2026-09-05T23:00:00.000Z") });const rows = saved();+ vi.useRealTimers();+ expect(rows.tracker.nextCheckAt).toMatch(/^2026-09-13T0/);expect(rows.tracker).toMatchObject({- enabled: false,+ enabled: true,+ scheduleInterval: "weekly",locationCode: 2100,languageCode: "bg",chatgpt: true,diff --git a/src/server/features/ai-visibility/services/aiVisibilityConfiguration.ts b/src/server/features/ai-visibility/services/aiVisibilityConfiguration.tsindex f22e93a0..c1aa0488 100644--- a/src/server/features/ai-visibility/services/aiVisibilityConfiguration.ts+++ b/src/server/features/ai-visibility/services/aiVisibilityConfiguration.ts@@ -5,6 +5,7 @@ import {type AiBrand,type AiEngine,} from "@/shared/ai-visibility";+import { computeNextCheckAt } from "@/shared/rank-tracking";import { applyMarket } from "./aiVisibilityMarket";import type {ConfigurationRows,@@ -79,6 +80,18 @@ export function aiBrands(return [...brands.values()];}+/**+ * A new tracker's first check, at least a full week out. The shared weekly+ * slot is seven calendar days ahead at 04:00–10:00 UTC, which lands short of+ * a week for trackers created later in the UTC day.+ */+function firstWeeklyCheckAt() {+ const next = new Date(computeNextCheckAt("weekly"));+ if (next.getTime() < Date.now() + 7 * 86_400_000)+ next.setUTCDate(next.getUTCDate() + 1);+ return next.toISOString();+}+export function projectAiConfiguration(input: {previous: ConfigurationRows | null;projectId: string;@@ -98,11 +111,13 @@ export function projectAiConfiguration(input: {tracker: {id: crypto.randomUUID(),projectId: input.projectId,- enabled: false,+ // New tracking runs weekly. The first check is a week out, so+ // creating a tracker never charges on its own.+ enabled: true,...engineColumns(["chatgpt", "gemini"]),...input.projectMarket,scheduleInterval: "weekly",- nextCheckAt: null,+ nextCheckAt: firstWeeklyCheckAt(),lastSkipReason: null,createdAt: now,},diff --git a/src/server/features/ai-visibility/services/aiVisibilityExport.ts b/src/server/features/ai-visibility/services/aiVisibilityExport.tsindex 9b9fa806..623dfca2 100644--- a/src/server/features/ai-visibility/services/aiVisibilityExport.ts+++ b/src/server/features/ai-visibility/services/aiVisibilityExport.ts@@ -3,7 +3,7 @@ import { z } from "zod";import { resolveUserContextFromHeaders } from "@/middleware/ensure-user/resolve";import { ProjectRepository } from "@/server/features/projects/repositories/ProjectRepository";import type { AiExportInput } from "@/types/schemas/ai-visibility";-import { loadAiAnswer, loadAiResultSet } from "./aiVisibilityResults";+import { loadAiFullAnswers } from "./aiVisibilityResults";import { AiVisibilityError } from "./aiVisibilityErrors";function csvCell(value: string | number | boolean | null | undefined) {@@ -19,20 +19,12 @@ export async function exportAiData(input: AiExportInput, baseUrl: string) {"EXPORT_SCOPE","Choose one run to export. Prompt history can be inspected separately.",);- const { result } = await loadAiResultSet(input);+ const { result, answers } = await loadAiFullAnswers(input);if (!result.runId)throw new AiVisibilityError("NO_RESULTS","There is no baseline or scheduled run to export. Select a manual run explicitly if that is the evidence you want.",);- const answers = [];- for (const row of result.rows)- answers.push(- await loadAiAnswer(- { projectId: input.projectId, observationId: row.id },- { full: true },- ),- );const body =input.format === "json"? JSON.stringify(diff --git a/src/server/features/ai-visibility/services/aiVisibilityResults.test.ts b/src/server/features/ai-visibility/services/aiVisibilityResults.test.tsindex d883c7e6..bd31a6be 100644--- a/src/server/features/ai-visibility/services/aiVisibilityResults.test.ts+++ b/src/server/features/ai-visibility/services/aiVisibilityResults.test.ts@@ -14,8 +14,9 @@ const { testDb } = await vi.hoisted(async () => {const { createAiVisibilityTestDb } = await import("../aiVisibilityTestDb");return { testDb: await createAiVisibilityTestDb() };});+const r2Put = vi.hoisted(() => vi.fn<(key: string, body: string) => void>());vi.mock("cloudflare:workers", () => ({- env: { DATABASE_PROVIDER: "d1", R2: { put: vi.fn() } },+ env: { DATABASE_PROVIDER: "d1", R2: { put: r2Put } },}));vi.mock("@/db", () => ({ db: testDb.db }));vi.mock("@/db/runBatch", () => ({ runBatch: testDb.runBatch }));@@ -238,4 +239,32 @@ describe("AI visibility export", () => {/^https:\/\/app\.openseo\.so\/api\/ai-visibility\/download\?projectId=project&exportId=/,);});++ it("writes each answer with its own mentions and citations", async () => {+ await seedRun("baseline", [+ {+ markdown: "OpenSEO",+ mentioned: ["OpenSEO"],+ sources: ["https://openseo.so/pricing"],+ },+ {+ markdown: "Ahrefs",+ mentioned: ["Ahrefs"],+ sources: ["https://ahrefs.com/blog"],+ },+ ]);+ await exportAiData(+ { ...query, includeHistory: false, competitorGap: false, format: "csv" },+ "https://app.openseo.so",+ );+ const csv = r2Put.mock.calls[0]?.[1];+ expect(csv?.split("\r\n").slice(1)).toEqual([+ expect.stringContaining(+ '"Question 0?","chatgpt","completed","","OpenSEO","https://openseo.so/pricing","OpenSEO"',+ ),+ expect.stringContaining(+ '"Question 1?","chatgpt","completed","","Ahrefs","https://ahrefs.com/blog","Ahrefs"',+ ),+ ]);+ });});diff --git a/src/server/features/ai-visibility/services/aiVisibilityResults.ts b/src/server/features/ai-visibility/services/aiVisibilityResults.tsindex fdac03a3..bbb6403c 100644--- a/src/server/features/ai-visibility/services/aiVisibilityResults.ts+++ b/src/server/features/ai-visibility/services/aiVisibilityResults.ts@@ -82,7 +82,7 @@ function rowsFor(}));}-export async function loadAiResultSet(rawInput: AiResultsInput) {+async function loadAiResultSet(rawInput: AiResultsInput) {const input = {...rawInput,runId: rawInput.runId ?? undefined,@@ -156,7 +156,7 @@ export async function loadAiResultSet(rawInput: AiResultsInput) {},truncated: input.includeHistory && runs.length === 50,};- return { result, runs, evidence };+ return { result, runs, run, observations: scoped, evidence };}function resultPage(@@ -206,7 +206,45 @@ export async function loadAiAnswer("ANSWER_NOT_FOUND","This answer is not available in the selected project.",);- const evidence = await repo.getEvidence([observation.id]);+ return answerView(+ observation,+ run,+ await repo.getEvidence([observation.id]),+ full,+ );+}++/** Every answer of one run in full, from a single result-set read. */+export async function loadAiFullAnswers(input: AiResultsInput) {+ const { result, run, observations, evidence } = await loadAiResultSet(input);+ const sources = groupByProp(evidence.sources, "observationId");+ const matches = groupByProp(evidence.matches, "observationId");+ // Rows carry the competitor-gap filter; observations do not.+ const rowIds = new Set(result.rows.map((row) => row.id));+ const answers = run+ ? observations+ .filter((observation) => rowIds.has(observation.id))+ .map((observation) =>+ answerView(+ observation,+ run,+ {+ sources: sources[observation.id] ?? [],+ matches: matches[observation.id] ?? [],+ },+ true,+ ),+ )+ : [];+ return { result, answers };+}++function answerView(+ observation: ObservationWithPrompt,+ run: RunRow,+ evidence: Evidence,+ full: boolean,+): AiAnswer {const row = rowsFor([observation], evidence)[0];const markdown = observation.answerMarkdown;const answerText = markdown ? markdownToText(markdown) : null;diff --git a/src/server/features/ai-visibility/services/aiVisibilitySetup.ts b/src/server/features/ai-visibility/services/aiVisibilitySetup.tsindex ca0a4a10..acd00ee1 100644--- a/src/server/features/ai-visibility/services/aiVisibilitySetup.ts+++ b/src/server/features/ai-visibility/services/aiVisibilitySetup.ts@@ -3,7 +3,7 @@ import type { SaveAiTrackerInput } from "@/types/schemas/ai-visibility";import { projectPatch } from "./aiVisibilityMutation";import { getTracker } from "./aiVisibilityState";-/** Creates or edits tracking. A new tracker starts paused. */+/** Creates or edits tracking. A new tracker starts weekly, first check a week out. */export async function saveTracker(input: SaveAiTrackerInput) {const { projectId, ...patch } = input;const current = await repo.getConfiguration(projectId);diff --git a/src/server/features/ai-visibility/services/websiteTrackingSetup.ts b/src/server/features/ai-visibility/services/websiteTrackingSetup.tsindex 8fd6cc54..1440739f 100644--- a/src/server/features/ai-visibility/services/websiteTrackingSetup.ts+++ b/src/server/features/ai-visibility/services/websiteTrackingSetup.ts@@ -6,7 +6,7 @@ import { DEFAULT_LOCATION_CODE } from "@/shared/keyword-locations";import type { SaveProjectWebsiteSetup } from "@/types/schemas/projectWebsite";import { AppError } from "@/server/lib/errors";-/** Seeds paused tracking from website setup's first three suggested topics. */+/** Seeds weekly tracking from website setup's first three suggested topics. */export async function prepareWebsiteTracking(input: Pick<SaveProjectWebsiteSetup, "projectId" | "suggestedTopics">,market: { locationCode: number; languageCode: string },diff --git a/src/server/mcp/tools/ai-visibility-tools.ts b/src/server/mcp/tools/ai-visibility-tools.tsindex eb842280..f1b92335 100644--- a/src/server/mcp/tools/ai-visibility-tools.ts+++ b/src/server/mcp/tools/ai-visibility-tools.ts@@ -167,7 +167,7 @@ export const completeAiResearchSetupTool = defineAiTool({readOnly: false,path: "research",description:- "Give a project with a saved website its Prompt Research keywords. Get the user's approval first: unless keywords exist, this starts paid research with usage credits. Starting is idempotent: a running or reviewable setup is returned, not restarted. With a business overview and competitors in shared context, one model call writes the keywords and, when the project has no tracking yet, seeds three paused tracker topics with five prompts each. Missing overview and competitors are researched independently; saved values are reused. Status becomes review when basics or competitors were researched: review new competitors, or preserve the saved list when preserveCompetitors=true, then save with save_project_website_setup. While status is running, call again after about 20 seconds. Never starts answer collection.",+ "Give a project with a saved website its Prompt Research keywords. Get the user's approval first: unless keywords exist, this starts paid research with usage credits. Starting is idempotent: a running or reviewable setup is returned, not restarted. With a business overview and competitors in shared context, one model call writes the keywords and, when the project has no tracking yet, seeds three tracker topics with five prompts each, scheduled weekly with the first check about a week later. Missing overview and competitors are researched independently; saved values are reused. Status becomes review when basics or competitors were researched: review new competitors, or preserve the saved list when preserveCompetitors=true, then save with save_project_website_setup. While status is running, call again after about 20 seconds. Never starts answer collection.",execute: (s, a, b) => s.startResearchSetup(a, b),summarize: (d) =>d.status === "ready"@@ -218,7 +218,7 @@ export const saveAiVisibilityTrackerTool = defineAiTool({}),readOnly: false,description:- "Bulk create or patch AI tracking prompts, their topics, engines, country, and language. Pause or archive a topic by pausing or archiving each of its prompts. Brand name/domain and competitors come from shared Project context; manage them there. Read the tracker first and edit prompts by ID. New trackers start paused and saving uses no collection credits. When tracking is enabled, show the user the new estimate before adding prompts or engines. Do not rewrite customer prompts without direction.",+ "Bulk create or patch AI tracking prompts, their topics, engines, country, and language. Pause or archive a topic by pausing or archiving each of its prompts. Brand name/domain and competitors come from shared Project context; manage them there. Read the tracker first and edit prompts by ID. New trackers start on a weekly schedule; saving uses no credits, and the first paid check runs about a week later. Show the user the estimate before creating a tracker or adding prompts or engines, and pause with set_ai_visibility_schedule if they do not want scheduled checks. Do not rewrite customer prompts without direction.",execute: (s, a) => s.saveTracker(a),summarize: (d) =>`Saved AI tracking: ${d.created} created, ${d.updated} updated, ${d.skipped} skipped.`,diff --git a/src/server/mcp/tools/project-website.ts b/src/server/mcp/tools/project-website.tsindex da549712..70cf8871 100644--- a/src/server/mcp/tools/project-website.ts+++ b/src/server/mcp/tools/project-website.ts@@ -59,7 +59,7 @@ export const saveProjectWebsiteSetupTool = {config: {title: "Save reviewed website setup",description:- "Fill missing website domain, business overview, and competitors after the user confirms setup. Existing project values and competitor lists are authoritative and never overwritten, including values saved while research was running. Pass suggestedTopics and suggestedKeywords from research: when research keywords are missing, the topic names and keywords fill them, and the first three topics seed initial paused AI tracking. Existing keywords and tracking stay intact. New competitor lists can include reviewed manual additions without research evidence. Use update_project_context for explicit edits to saved context. Uses no credits and never starts answer collection.",+ "Fill missing website domain, business overview, and competitors after the user confirms setup. Existing project values and competitor lists are authoritative and never overwritten, including values saved while research was running. Pass suggestedTopics and suggestedKeywords from research: when research keywords are missing, the topic names and keywords fill them, and the first three topics seed initial AI tracking on a weekly schedule, with its first paid check about a week later. Existing keywords and tracking stay intact. New competitor lists can include reviewed manual additions without research evidence. Use update_project_context for explicit edits to saved context. Uses no credits now and never starts answer collection immediately.",inputSchema: saveProjectWebsiteSetupSchema.shape,outputSchema: z.looseObject({project: looseObjectOutputSchema,