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
Feat/913 agent active brand (#970)
Sanjeev Kumare6022dbc72db
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/agent/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/agent/page.tsxindex 045f0facf..dc8cd70bb 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/agent/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/agent/page.tsx@@ -21,6 +21,7 @@ import { Link } from '@/i18n/navigation';import { Button, buttonVariants } from '@/components/ui/button';import { Markdown } from '@/components/ui/markdown';import { cn } from '@/lib/utils';+import { useBrandStore } from '@/stores/use-brand-store';import { toast } from 'sonner';import {Check,@@ -146,6 +147,7 @@ function AgentChat(props: {} = props;const t = useTranslations('agent');const tc = useTranslations('common');+ const activeBrandId = useBrandStore((s) => s.activeBrandId);const [pendingConfirm, setPendingConfirm] = useState<string | null>(null);// Ref mirrors activeId for prepareSendMessagesRequest. Reading the@@ -249,7 +251,7 @@ function AgentChat(props: {const res = await fetch('/api/agent/conversations', {method: 'POST',headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({}),+ body: JSON.stringify({ brandId: activeBrandId }),});if (!res.ok) {const body = await res.json().catch(() => null);@@ -294,7 +296,7 @@ function AgentChat(props: {const res = await fetch('/api/agent/conversations', {method: 'POST',headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({}),+ body: JSON.stringify({ brandId: activeBrandId }),});if (!res.ok) {const body = await res.json().catch(() => null);diff --git a/web/src/app/api/agent/chat/route.ts b/web/src/app/api/agent/chat/route.tsindex 005b581c0..21348d375 100644--- a/web/src/app/api/agent/chat/route.ts+++ b/web/src/app/api/agent/chat/route.ts@@ -57,13 +57,27 @@ export async function POST(req: Request) {// Ownership: the conversation must belong to the calling user.const { data: conv } = await supabaseAdmin.from('agent_conversations')- .select('id, user_id, organization_id')+ .select('id, user_id, organization_id, brand_id').eq('id', conversationId).maybeSingle();if (!conv || conv.user_id !== auth.userId || conv.organization_id !== organizationId) {return NextResponse.json({ error: 'Conversation not found' }, { status: 404 });}+ let defaultBrand: { id: string; name: string } | undefined;+ if (conv.brand_id) {+ const { data: brand } = await supabaseAdmin+ .from('brands')+ .select('id, name')+ .eq('id', conv.brand_id)+ .eq('organization_id', organizationId)+ .maybeSingle();++ if (brand) {+ defaultBrand = brand;+ }+ }+// Plan gate. On cloud the gate is intentionally loose — `ai_agent` is in// every paid plan's feature list; the *real* gate is whether the org has// pasted an Anthropic key in Settings → Agent (BYOK). Self-host bypasses@@ -96,7 +110,7 @@ export async function POST(req: Request) {const result = streamText({model: buildAgentModel(anthropicKey),maxOutputTokens: 16000,- system: buildAgentSystemPrompt(new Date()),+ system: buildAgentSystemPrompt(new Date(), defaultBrand),messages: await convertToModelMessages(messages),tools: buildAgentTools(auth),// streamText is single-step by default in v6 — without an explicitdiff --git a/web/src/app/api/agent/conversations/route.ts b/web/src/app/api/agent/conversations/route.tsindex ac8092781..f7555596b 100644--- a/web/src/app/api/agent/conversations/route.ts+++ b/web/src/app/api/agent/conversations/route.ts@@ -76,12 +76,31 @@ export async function POST(req: Request) {// Empty body is fine — the form may not send one.}+ let brandId: string | null = null;+ if (body.brandId) {+ const { data: brand, error: brandError } = await supabaseAdmin+ .from('brands')+ .select('id')+ .eq('id', body.brandId)+ .eq('organization_id', organizationId)+ .maybeSingle();++ if (brandError) {+ return NextResponse.json({ error: brandError.message }, { status: 500 });+ }+ if (!brand) {+ return NextResponse.json({ error: 'Brand not found' }, { status: 400 });+ }++ brandId = brand.id;+ }+const { data, error } = await supabaseAdmin.from('agent_conversations').insert({user_id: auth.userId,organization_id: auth.organizationId,- brand_id: body.brandId ?? null,+ brand_id: brandId,title: body.title ?? 'New conversation',}).select('id, title, brand_id, created_at, updated_at')diff --git a/web/src/lib/agent/system-prompt.test.ts b/web/src/lib/agent/system-prompt.test.tsnew file mode 100644index 000000000..4f9232766--- /dev/null+++ b/web/src/lib/agent/system-prompt.test.ts@@ -0,0 +1,31 @@+import { describe, expect, it } from 'vitest';+import { buildAgentSystemPrompt } from './system-prompt';++describe('buildAgentSystemPrompt', () => {+ const now = new Date('2026-10-08T00:00:00.000Z');++ it('uses the conversation brand for unqualified questions', () => {+ const prompt = buildAgentSystemPrompt(now, {+ id: '11111111-1111-1111-1111-111111111111',+ name: 'Acme',+ });++ expect(prompt).toContain("The conversation's default brand is **Acme**");+ expect(prompt).toContain('id: `11111111-1111-1111-1111-111111111111`');+ expect(prompt).toContain('Use this brand for questions that do not name a brand explicitly.');+ expect(prompt).toContain(+ 'If the user explicitly asks about another brand, use that brand instead.',+ );+ expect(prompt).toContain('Do not call list_brands just to resolve the default brand.');+ });++ it('falls back to brand selection when there is no conversation brand', () => {+ const prompt = buildAgentSystemPrompt(now);++ expect(prompt).toContain('This conversation has no default brand.');+ expect(prompt).toContain('resolve the available brands with `list_brands`');+ expect(prompt).toContain(+ "If there is no default brand and the user doesn't name one, call list_brands.",+ );+ });+});diff --git a/web/src/lib/agent/system-prompt.ts b/web/src/lib/agent/system-prompt.tsindex c49c2f927..516d1af92 100644--- a/web/src/lib/agent/system-prompt.ts+++ b/web/src/lib/agent/system-prompt.ts@@ -9,7 +9,7 @@* - never invent numbers; always go through a tool first* - respond in plain language, not JSON dumps; act like a 30-second* marketing standup- * - if the user doesn't name a brand, ask (single-line clarification)+ * - if there is no default brand and the user doesn't name one, ask (single-line clarification)* - acknowledge tool gaps explicitly rather than faking the answer** The system prompt is built per-request so today's date can be@@ -18,7 +18,12 @@* model snapshot — and passes the wrong date_from to the time-aware* tools whenever the user says "today" / "this week" / "last 30 days".*/-export function buildAgentSystemPrompt(now: Date): string {+export interface AgentBrandContext {+ id: string;+ name: string;+}++export function buildAgentSystemPrompt(now: Date, defaultBrand?: AgentBrandContext): string {const today = now.toISOString().slice(0, 10);return `You are an Answer Engine Optimization (AEO) analyst working on the user's brand visibility inside AI search products (ChatGPT, Gemini, Perplexity, Claude, Copilot, Google AI Overview, Google AI Mode). You are running inside the Ansvisor dashboard as the in-product assistant.@@ -28,11 +33,13 @@ Your job is to turn raw visibility numbers into something the user can act on. AToday's date is **${today}** (UTC). When the user says "today" / "yesterday" / "this week" / "last 30 days" / "last month", compute the date range from this anchor and pass it as \`date_from\` (and \`date_to\` when relevant) to the time-aware tools. Never invent a different "now".+${defaultBrand ? `The conversation's default brand is **${defaultBrand.name}** (id: \`${defaultBrand.id}\`). Use this brand for questions that do not name a brand explicitly. If the user explicitly asks about another brand, use that brand instead.` : `This conversation has no default brand. If the user does not name a brand, resolve the available brands with \`list_brands\` and ask which one to use when there is more than one.`}+## Tools availableYou have these tools, all scoped to the authenticated user's organization:-- **list_brands** — lists brands the user can access. Always call this first if the user doesn't specify a brand.+- **list_brands** — lists brands the user can access. Use it when there is no conversation default brand and the user has not named one, or when you need to resolve a different brand the user explicitly names.- **get_visibility_summary** — point-in-time snapshot of avg visibility, mentions, citations for a brand over an optional window.- **get_visibility_trend** — time-series of visibility / mentions / citations over a date range, bucketed by day or week. Also includes avg competitor score per bucket. Use this for "how has it changed?" questions and to suggest charts.- **get_competitor_comparison** — competitor benchmark + share of voice for a brand. Returns the brand and every tracked competitor with avg visibility, mentions, citations, appearance count, plus overall SoV and per-platform SoV.@@ -75,7 +82,7 @@ Hard rules:## Rules1. **Never invent numbers.** Always call a tool to get the data before answering with numbers. If you don't have a tool for what's being asked, say so plainly.-2. **If the user doesn't name a brand**, call list_brands. If there's only one, use it silently. If there are several, ask which one with a one-line clarification listing the names — do not pick for them.+2. **Use the conversation's default brand for unqualified questions when one is provided.** Do not call list_brands just to resolve the default brand. If the user explicitly names another brand, use that brand instead and resolve it with list_brands when necessary. If there is no default brand and the user doesn't name one, call list_brands. If there's only one, use it silently. If there are several, ask which one with a one-line clarification listing the names — do not pick for them.3. **Reply in plain language**, not JSON or tables of raw numbers. Numbers belong inline in sentences. A trend over 30 days is one sentence about the slope plus a number, not 30 rows.4. **Lead with the headline.** Open with the single most important thing (visibility up/down, biggest competitor move, biggest content gap). Details follow.5. **Be concrete about what to do next.** End with one or two specific actions the user could take, not generic advice.